@margoengine/vfx 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +2240 -2
  4. package/dist/base-LGs65K7K.js +709 -0
  5. package/dist/base.d.ts +869 -0
  6. package/dist/base.js +1 -0
  7. package/dist/blown-sand.d.ts +218 -0
  8. package/dist/blown-sand.js +700 -0
  9. package/dist/clouds.d.ts +237 -0
  10. package/dist/clouds.js +583 -0
  11. package/dist/compat-BFjXAQuu.js +14 -0
  12. package/dist/compat-CVSEj1Bp.js +217 -0
  13. package/dist/compat.d.ts +59 -0
  14. package/dist/curves.d.ts +11 -0
  15. package/dist/curves.js +59 -0
  16. package/dist/debris.d.ts +154 -0
  17. package/dist/debris.js +290 -0
  18. package/dist/depth-collide.d.ts +7 -0
  19. package/dist/depth-collide.js +96 -0
  20. package/dist/dust-current.d.ts +66 -0
  21. package/dist/dust-current.js +92 -0
  22. package/dist/emitter.d.ts +10 -0
  23. package/dist/emitter.js +125 -0
  24. package/dist/events.d.ts +9 -0
  25. package/dist/events.js +131 -0
  26. package/dist/extra-CgGjbojB.js +4 -0
  27. package/dist/extra.d.ts +2 -0
  28. package/dist/fields.d.ts +11 -0
  29. package/dist/fields.js +95 -0
  30. package/dist/fire-front.d.ts +610 -0
  31. package/dist/fire-front.js +1080 -0
  32. package/dist/fire.d.ts +140 -0
  33. package/dist/fire.js +194 -0
  34. package/dist/flame-ramp-VoBKpYnM.js +75 -0
  35. package/dist/flame-ramp.d.ts +61 -0
  36. package/dist/flame.d.ts +428 -0
  37. package/dist/flame.js +817 -0
  38. package/dist/flipbook.d.ts +7 -0
  39. package/dist/flipbook.js +23 -0
  40. package/dist/flocking-shaders.d.ts +48 -0
  41. package/dist/flocking-sim.d.ts +623 -0
  42. package/dist/flocking.d.ts +145 -0
  43. package/dist/flocking.js +1846 -0
  44. package/dist/fog-B-kBv7g0.js +32 -0
  45. package/dist/frame-BuvMFBPp.js +4 -0
  46. package/dist/frame.d.ts +7 -0
  47. package/dist/gunfire.d.ts +742 -0
  48. package/dist/gunfire.js +1214 -0
  49. package/dist/hash-Btsp6fGK.js +7 -0
  50. package/dist/hash.d.ts +2 -0
  51. package/dist/index.d.ts +17 -0
  52. package/dist/index.js +60 -0
  53. package/dist/json.d.ts +53 -0
  54. package/dist/json.js +239 -0
  55. package/dist/lit-Dx2tNwP-.js +152 -0
  56. package/dist/lit.d.ts +18 -0
  57. package/dist/lit.js +1 -0
  58. package/dist/mesh.d.ts +16 -0
  59. package/dist/mesh.js +248 -0
  60. package/dist/node-system.d.ts +315 -0
  61. package/dist/node-system.js +384 -0
  62. package/dist/nodes.d.ts +14 -0
  63. package/dist/nodes.js +293 -0
  64. package/dist/obstacles.d.ts +3 -0
  65. package/dist/obstacles.js +25 -0
  66. package/dist/over-life.d.ts +14 -0
  67. package/dist/over-life.js +94 -0
  68. package/dist/reactive-mask-B8xbyzlk.js +69 -0
  69. package/dist/require-webgpu--tUXPsmA.js +7 -0
  70. package/dist/ribbons.d.ts +22 -0
  71. package/dist/ribbons.js +165 -0
  72. package/dist/schedule.d.ts +29 -0
  73. package/dist/schedule.js +47 -0
  74. package/dist/settings.d.ts +362 -0
  75. package/dist/settings.js +707 -0
  76. package/dist/shader.d.ts +49 -0
  77. package/dist/shadows.d.ts +26 -0
  78. package/dist/shadows.js +182 -0
  79. package/dist/shapes.d.ts +34 -0
  80. package/dist/shapes.js +81 -0
  81. package/dist/shared/fog.d.ts +33 -0
  82. package/dist/shared/pass.d.ts +53 -0
  83. package/dist/shared/settings.d.ts +89 -0
  84. package/dist/skinned.d.ts +11 -0
  85. package/dist/skinned.js +104 -0
  86. package/dist/smoke.d.ts +283 -0
  87. package/dist/smoke.js +504 -0
  88. package/dist/soft.d.ts +17 -0
  89. package/dist/soft.js +55 -0
  90. package/dist/solid.d.ts +168 -0
  91. package/dist/solid.js +403 -0
  92. package/dist/sort.d.ts +3 -0
  93. package/dist/sort.js +58 -0
  94. package/dist/space.d.ts +14 -0
  95. package/dist/space.js +88 -0
  96. package/dist/stretch.d.ts +7 -0
  97. package/dist/stretch.js +40 -0
  98. package/dist/texture.d.ts +8 -0
  99. package/dist/texture.js +45 -0
  100. package/dist/view-RKprOPAy.js +30 -0
  101. package/dist/view-rect-DkeiiUtw.js +13 -0
  102. package/dist/wrap.d.ts +3 -0
  103. package/dist/wrap.js +5 -0
  104. package/package.json +198 -4
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Particle i's position/life and velocity/size are vec4s 2i and 2i+1 of the buffer; its colour and rotation (birth angle,
3
+ * angular velocity, initial life) are 2n+2i and 2n+2i+1 (n = capacity), written once at birth. The per-frame update so
4
+ * reads and writes only the first half; the drawn angle is the birth angle plus angular velocity times age.
5
+ * indirect counts every live particle; the draw lists in alive those whose triangle can reach the screen. That test
6
+ * bounds the triangle by a sphere of radius size (its circumradius) and checks it
7
+ * against the four side planes in clip space, with row-norm margins that bound any offset of that length (1% and a
8
+ * w-relative slack cover rounding); the side planes together also reject everything behind the eye. (The test uses the
9
+ * true size, so a far particle the billboard grows to its 1.5 px minimum can be culled up to a pixel early at an edge.)
10
+ * A birth's seed is its step number (control.z) and its birth number in that step (its ticket: the dying slots before
11
+ * it), never its slot, so the same steps birth the same particles whatever history left which slots free: a seek and
12
+ * a warm-up give the particles of a continuous run (GAP-FILM-VFXSEED). Random numbers keyed by a counter instead of
13
+ * carried state, as in Salmon, Moraes, Dror and Shaw 2011 ("Parallel random numbers: as easy as 1, 2, 3", SC11), with
14
+ * each key put through the integer hash first (GPU integer hashes compared by Jarzynski and Olano 2020, JCGT 9(3)).
15
+ *
16
+ * Slot order, never atomic tickets, so the same frames give the same particles and the same blend order whatever order
17
+ * the GPU runs the threads in (visual checks were load-dependent before). One dispatch each, per frame:
18
+ * - deaths: each workgroup's dying slots (dies, the update's own test) counted into groups (the births buffer);
19
+ * - scan (one workgroup): groups become exclusive offsets, their sum goes to total[1];
20
+ * - main: a slot's ticket is the dying slots before it (births = those offsets, plus prefix in the workgroup), so births
21
+ * take the lowest dead slots; update returns 1 when the slot is alive and on screen, and each workgroup lists those
22
+ * in slot order in its own 256 entries of listed, its count in groups (the drawn buffer);
23
+ * - scan of the drawn counts (total = the draw's arguments, instanceCount);
24
+ * - compact: each workgroup's run of listed copied to alive at its offset.
25
+ * deaths and the births scan are skipped in a frame without births: every ticket is then at or above the budget, 0.
26
+ * prefix(l, v) sums v over invocations 0..l of the workgroup and must be called from uniform control flow.
27
+ */
28
+ export declare const simulationShader: string;
29
+ /** One triangle around the unit disc (inradius 1) per particle: half the primitives and 3/4 of the vertices of a quad. */
30
+ export declare const billboardShader: string;
31
+ /**
32
+ * With 4x MSAA the fragment shader runs once per pixel but writes every sample the triangle covers, and the triangle
33
+ * covers more samples than the quad it replaced. Keep exactly the quad's samples: those whose uv (from the pixel centre's
34
+ * uv, its screen derivatives and WebGPU's standard 4x sample offsets) lies in the unit square.
35
+ */
36
+ export declare const multisampled: (billboard: string) => string;
37
+ /**
38
+ * A finished billboard shader with a `reactive` entry beside its fragment: the particle's coverage (its alpha) in red,
39
+ * for the frame's reactive mask that TAA reads (KB-TAA-PARTICLEMASK1).
40
+ */
41
+ export declare const reactiveBillboard: (billboard: string) => string;
42
+ /** A finished billboard shader (fog, softness and texture in place) with its fragment feeding a transparency hook. */
43
+ export declare const transparentBillboard: (billboard: string, declarations: string) => string;
44
+ /**
45
+ * Scene fog (`setFog`) on a billboard shader, plain or textured, before `multisampled`: each fragment fades toward the
46
+ * fog colour by the fog at its world position. Particles blend alpha over the scene and write their colour as it is, so
47
+ * the fog colour in the uniform is in the target's terms (sRGB-encoded for an 8-bit canvas). Fog uniform at binding 5.
48
+ */
49
+ export declare const foggedBillboard: (billboard: string) => string;
@@ -0,0 +1,26 @@
1
+ import type { VFXExtension, VFXShadows } from './base.js';
2
+ /**
3
+ * Particles cast sun shadows and the first live ones emit light.
4
+ *
5
+ * Shadows: each live particle is a sphere impostor in the directional shadow map (Akenine-Moller, Haines and
6
+ * Hoffman, Real-Time Rendering, 4th ed., 2018, billboard impostors). Under the cascade's orthographic matrix the
7
+ * front of a sphere is centerZ - sqrt(r^2 - x^2 - y^2) (elementary geometry). Reeves, "Particle Systems", SIGGRAPH
8
+ * 1983, draws particles as their own primitives. The map's receiver bias stays in the shadow pass; this writes
9
+ * geometric depth. WebGPU clips a primitive whose clip z is outside [0, w] (WebGPU spec, primitive clipping). The
10
+ * quad therefore sits inside that interval whenever the sphere's depth interval meets [0, 1], so a centre past the
11
+ * far plane does not drop a front that is still in range. The fragment still writes the geometric depth.
12
+ *
13
+ * Lights: the first `count` live slots, in slot order, become point lights. The order is an inclusive workgroup
14
+ * scan (Blelloch, "Prefix Sums and Their Applications", CMU-CS-90-190, 1990; Harris, Sengupta and Owens, "Parallel
15
+ * Prefix Sum (Scan) with CUDA", GPU Gems 3, ch. 39, 2007). `decay` is 2 so a clustered list uses the windowed
16
+ * inverse-square term (Karis, "Real Shading in Unreal Engine 4", 2013). No other engine's source was read.
17
+ */
18
+ export declare const MAX_PARTICLE_LIGHTS = 64;
19
+ /**
20
+ * The `shadows` feature: particles cast sphere shadows into `cast` (`Shadows` from `@margoengine/shadows`) and the
21
+ * first live slots emit point lights into `into` (`Clustered` from `@margoengine/clustered`). Pass it as `{shadows}`
22
+ * to `VFX` from `@margoengine/vfx/base`; the root `VFX` has it. `count`, `range` and `intensity` are read every frame.
23
+ * `cast` and `into` are fixed at attach. The feature sets `buffer` to the light list (header, then up to 64 lights).
24
+ * `into` sees that list about two frames later, because the read-back waits for the frame to finish.
25
+ */
26
+ export declare const shadows: VFXExtension<VFXShadows>;
@@ -0,0 +1,182 @@
1
+ //#region src/shadows.ts
2
+ var e = 64, t = 2064;
3
+ function n(e) {
4
+ return typeof e == "number" && Number.isFinite(e);
5
+ }
6
+ var r = {
7
+ validate(e) {
8
+ if (!e || typeof e != "object") throw TypeError("VFX shadows must be an object; pass {cast, into} or {}");
9
+ let t = e.count ?? 8;
10
+ if (!Number.isInteger(t) || t < 0 || t > 64) throw RangeError("VFX shadows count must be a whole number from 0 to 64; pass e.g. 8");
11
+ let r = e.range ?? 4;
12
+ if (n(r) && !Number.isFinite(Math.fround(r))) throw RangeError("VFX shadows range is not a finite f32; see https://margoengine.com/errors#vfx-float");
13
+ if (!n(r) || r <= 0) throw RangeError("VFX shadows range must be a finite distance above 0; pass e.g. 4");
14
+ let i = e.intensity ?? 1;
15
+ if (n(i) && !Number.isFinite(Math.fround(i))) throw RangeError("VFX shadows intensity is not a finite f32; see https://margoengine.com/errors#vfx-float");
16
+ if (!n(i) || i < 0) throw RangeError("VFX shadows intensity must be a finite number of 0 or more; pass e.g. 1");
17
+ if (e.cast !== void 0 && (typeof e.cast != "object" || typeof e.cast.add != "function")) throw TypeError("VFX shadows cast must have add(); pass Shadows from @margoengine/shadows");
18
+ if (e.into !== void 0 && (typeof e.into != "object" || typeof e.into.setLights != "function")) throw TypeError("VFX shadows into must have setLights(); pass Clustered from @margoengine/clustered");
19
+ },
20
+ create(e, n, r) {
21
+ let { device: i, capacity: a } = e, o = i.createBuffer({
22
+ size: 16,
23
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
24
+ }), s = i.createBuffer({
25
+ size: Math.ceil(a / 256) * 4,
26
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST
27
+ }), c = i.createBuffer({
28
+ size: t,
29
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
30
+ });
31
+ r.push(o, s, c), n.buffer = c;
32
+ let l = /* @__PURE__ */ new ArrayBuffer(16), u = new Uint32Array(l), d = new Float32Array(l), f = i.createShaderModule({ code: "\nstruct ParticleShadows {capacity:u32,limit:u32,range:f32,intensity:f32}\n@group(0) @binding(0) var<uniform> particleShadows:ParticleShadows;\n@group(0) @binding(1) var<storage,read> particles:array<vec4f>;\n@group(0) @binding(2) var<storage,read_write> groups:array<u32>;\n@group(0) @binding(3) var<storage,read_write> lights:array<vec4f>;\nvar<workgroup> scratch:array<u32,256>;\nfn prefix(l:u32,v:u32)->u32 {\n scratch[l]=v;workgroupBarrier();\n for(var o=1u;o<256u;o=o<<1u){var a=0u;if(l>=o){a=scratch[l-o];}workgroupBarrier();scratch[l]+=a;workgroupBarrier();}\n return scratch[l];\n}\nfn live(i:u32)->u32 {\n if(i>=particleShadows.capacity){return 0u;}\n return select(0u,1u,particles[i*2u].w>0.0);\n}\n@compute @workgroup_size(256) fn count(@builtin(global_invocation_id) id:vec3u,@builtin(local_invocation_index) l:u32,@builtin(workgroup_id) w:vec3u){\n let n=prefix(l,live(id.x));\n if(l==255u){groups[w.x]=n;}\n}\n@compute @workgroup_size(1) fn offsets(){\n let n=(particleShadows.capacity+255u)/256u;\n var sum=0u;\n for(var g=0u;g<n;g++){let c=groups[g];groups[g]=sum;sum+=c;}\n lights[0]=vec4f(f32(min(sum,particleShadows.limit)),particleShadows.range,particleShadows.intensity,0.0);\n}\n@compute @workgroup_size(256) fn pack(@builtin(global_invocation_id) id:vec3u,@builtin(local_invocation_index) l:u32,@builtin(workgroup_id) w:vec3u){\n let on=live(id.x);\n let incl=prefix(l,on);\n if(on==1u){\n let rank=groups[w.x]+incl-1u;\n if(rank<particleShadows.limit){\n let at=id.x*2u;\n let p=particles[at];\n let color=particles[particleShadows.capacity*2u+at];\n let base=1u+rank*2u;\n lights[base]=vec4f(p.xyz,particleShadows.range);\n lights[base+1u]=vec4f(color.rgb,particleShadows.intensity);\n }\n }\n}\n" }), p = [
33
+ {
34
+ binding: 0,
35
+ resource: { buffer: o }
36
+ },
37
+ {
38
+ binding: 1,
39
+ resource: { buffer: e.particles }
40
+ },
41
+ {
42
+ binding: 2,
43
+ resource: { buffer: s }
44
+ },
45
+ {
46
+ binding: 3,
47
+ resource: { buffer: c }
48
+ }
49
+ ], m = (e, t) => {
50
+ let n = i.createComputePipeline({
51
+ layout: "auto",
52
+ compute: {
53
+ module: f,
54
+ entryPoint: e
55
+ }
56
+ });
57
+ return {
58
+ made: n,
59
+ group: i.createBindGroup({
60
+ layout: n.getBindGroupLayout(0),
61
+ entries: p.filter((e) => t.includes(e.binding))
62
+ })
63
+ };
64
+ }, h = m("count", [
65
+ 0,
66
+ 1,
67
+ 2
68
+ ]), g = m("offsets", [
69
+ 0,
70
+ 2,
71
+ 3
72
+ ]), _ = m("pack", [
73
+ 0,
74
+ 1,
75
+ 2,
76
+ 3
77
+ ]), v = n.cast, y = n.into, b = Math.ceil(a / 256), x, S = !1, C = !1, w = null, T = !1, E = !1, D, O = [], k = [], A;
78
+ if (v) {
79
+ let t = i.createShaderModule({ code: "\n@group(0) @binding(0) var<uniform> shadowMatrix:mat4x4f;\n@group(0) @binding(1) var<storage,read> particles:array<vec4f>;\nconst corners=array<vec2f,6>(vec2f(-1.0,-1.0),vec2f(1.0,-1.0),vec2f(1.0,1.0),vec2f(-1.0,-1.0),vec2f(1.0,1.0),vec2f(-1.0,1.0));\nstruct ShadowVary {@builtin(position) @invariant clip:vec4f,@location(0) local:vec2f,@location(1) centerZ:f32,@location(2) depthRadius:f32}\n@vertex fn vertex(@builtin(vertex_index) v:u32,@builtin(instance_index) slot:u32)->ShadowVary {\n var o:ShadowVary;\n let pos=particles[slot*2u];\n let radius=particles[slot*2u+1u].w*0.5;\n let dead=pos.w<=0.0||!(radius>0.0);\n let clip=shadowMatrix*vec4f(pos.xyz,1.0);\n let sx=length(vec3f(shadowMatrix[0].x,shadowMatrix[1].x,shadowMatrix[2].x));\n let sy=length(vec3f(shadowMatrix[0].y,shadowMatrix[1].y,shadowMatrix[2].y));\n let sz=length(vec3f(shadowMatrix[0].z,shadowMatrix[1].z,shadowMatrix[2].z));\n let depthRadius=radius*sz;\n let centerZ=clip.z/max(abs(clip.w),1e-20);\n let front=centerZ-depthRadius;\n let back=centerZ+depthRadius;\n let overlaps=clip.w>0.0&&back>=0.0&&front<=1.0;\n let outside=centerZ<0.0||centerZ>1.0;\n let kept=clamp(centerZ,1e-4,1.0-1e-4);\n let z=select(clip.z,kept*clip.w,overlaps&&outside);\n let local=corners[v];\n o.clip=select(vec4f(clip.xy+local*vec2f(radius*sx,radius*sy)*clip.w,z,clip.w),vec4f(0.0,0.0,0.0,1.0),dead);\n o.local=local;\n o.centerZ=select(centerZ,0.0,dead);\n o.depthRadius=depthRadius;\n return o;\n}\n@fragment fn fragment(i:ShadowVary)->@builtin(frag_depth) f32 {\n let d=dot(i.local,i.local);\n if(d>1.0){discard;}\n return clamp(i.centerZ-sqrt(max(0.0,1.0-d))*i.depthRadius,0.0,1.0);\n}\n" });
80
+ A = i.createRenderPipeline({
81
+ layout: "auto",
82
+ vertex: {
83
+ module: t,
84
+ entryPoint: "vertex"
85
+ },
86
+ fragment: {
87
+ module: t,
88
+ entryPoint: "fragment",
89
+ targets: []
90
+ },
91
+ depthStencil: {
92
+ format: "depth32float",
93
+ depthWriteEnabled: !0,
94
+ depthCompare: "less-equal"
95
+ }
96
+ });
97
+ for (let t = 0; t < 4; t++) {
98
+ let t = i.createBuffer({
99
+ size: 64,
100
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
101
+ });
102
+ r.push(t), O.push(t), k.push(i.createBindGroup({
103
+ layout: A.getBindGroupLayout(0),
104
+ entries: [{
105
+ binding: 0,
106
+ resource: { buffer: t }
107
+ }, {
108
+ binding: 1,
109
+ resource: { buffer: e.particles }
110
+ }]
111
+ }));
112
+ }
113
+ }
114
+ let j = A, M = {
115
+ disposed: !1,
116
+ drawShadow(t) {
117
+ let n = t.cascade;
118
+ if (!j || !Number.isInteger(n) || n < 0 || n > 3) throw RangeError("VFX shadows cascade must be 0 to 3");
119
+ i.queue.writeBuffer(O[n], 0, t.matrix), t.pass.setPipeline(j), t.pass.setBindGroup(0, k[n]), t.pass.draw(6, a), e.stats.drawCalls++;
120
+ }
121
+ };
122
+ v && (D = v.add(M, { static: !1 }));
123
+ let N = () => {
124
+ T || (T = !0, M.disposed = !0, D?.(), E && y.setLights([]));
125
+ }, P = (e) => {
126
+ if (T) return;
127
+ let t = Math.min(64, Math.max(0, Math.round(e[0] ?? 0))), n = [];
128
+ for (let r = 0; r < t; r++) {
129
+ let t = 4 + r * 8;
130
+ n.push({
131
+ position: [
132
+ e[t],
133
+ e[t + 1],
134
+ e[t + 2]
135
+ ],
136
+ range: e[t + 3],
137
+ color: [
138
+ e[t + 4],
139
+ e[t + 5],
140
+ e[t + 6]
141
+ ],
142
+ intensity: e[t + 7],
143
+ decay: 2
144
+ });
145
+ }
146
+ y.setLights(n), E = !0;
147
+ };
148
+ return {
149
+ write(t) {
150
+ if (e.options.shadows !== n) throw TypeError("VFX shadows is fixed at attach; change count, range and intensity in place or attach a new VFX");
151
+ if (n.cast !== v || n.into !== y) throw TypeError("VFX shadows cast and into are fixed at attach; change count, range and intensity in place");
152
+ if (n.buffer = c, u[0] = a, u[1] = n.count ?? 8, d[2] = n.range ?? 4, d[3] = n.intensity ?? 1, t.device.queue.writeBuffer(o, 0, d), y && x && S && !C) {
153
+ C = !0;
154
+ let e = x;
155
+ e.mapAsync(GPUMapMode.READ).then(() => {
156
+ if (C = !1, S = !1, T) return;
157
+ let t = new Float32Array(e.getMappedRange().slice(0));
158
+ e.unmap(), w = t;
159
+ }, (e) => {
160
+ if (C = !1, S = !1, !(T && e instanceof Error && e.name === "AbortError")) throw e;
161
+ });
162
+ }
163
+ if (w && y && !T) {
164
+ let e = w;
165
+ w = null, P(e);
166
+ }
167
+ },
168
+ run(e) {
169
+ e.setPipeline(h.made), e.setBindGroup(0, h.group), e.dispatchWorkgroups(b), e.setPipeline(g.made), e.setBindGroup(0, g.group), e.dispatchWorkgroups(1), e.setPipeline(_.made), e.setBindGroup(0, _.group), e.dispatchWorkgroups(b);
170
+ },
171
+ draw(e) {
172
+ y && (C || S || (x ??= e.device.createBuffer({
173
+ size: t,
174
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
175
+ }), r.includes(x) || r.push(x), e.encoder.copyBufferToBuffer(c, 0, x, 0, t), S = !0));
176
+ },
177
+ dispose: N
178
+ };
179
+ }
180
+ };
181
+ //#endregion
182
+ export { e as MAX_PARTICLE_LIGHTS, r as shadows };
@@ -0,0 +1,34 @@
1
+ import type { VFXFeatures } from './base.js';
2
+ /** Additional birth distributions; all shapes are centered at the effect position, with Y up. */
3
+ export type VFXShape = {
4
+ shape: 'hemisphere';
5
+ radius?: number;
6
+ shell?: boolean;
7
+ speed?: number;
8
+ } | {
9
+ shape: 'cylinder';
10
+ radius?: number;
11
+ height?: number;
12
+ shell?: boolean;
13
+ speed?: number;
14
+ } | {
15
+ shape: 'torus';
16
+ radius?: number;
17
+ tube?: number;
18
+ shell?: boolean;
19
+ speed?: number;
20
+ } | {
21
+ shape: 'rectangle-edge';
22
+ width?: number;
23
+ height?: number;
24
+ speed?: number;
25
+ } | {
26
+ shape: 'grid';
27
+ columns?: number;
28
+ rows?: number;
29
+ layers?: number;
30
+ spacing?: readonly [number, number, number];
31
+ speed?: number;
32
+ };
33
+ /** Superset of `emitter`: hemisphere, cylinder, torus, rectangle perimeter and grid, plus the original shapes. */
34
+ export declare const shapes: NonNullable<VFXFeatures['emitter']>;
package/dist/shapes.js ADDED
@@ -0,0 +1,81 @@
1
+ import { emitter as e } from "./emitter.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ //#region src/shapes.ts
4
+ var n = (e) => [
5
+ "hemisphere",
6
+ "cylinder",
7
+ "torus",
8
+ "rectangle-edge",
9
+ "grid"
10
+ ].includes(e.shape), r = (e, t, n, r) => {
11
+ if (typeof e != "number" || !Number.isFinite(e) || e < n || e > r) throw RangeError(`VFX shapes ${t} must be ${n}..${r}; pass a finite value in range`);
12
+ }, i = (e, n, r) => {
13
+ if (e.split(n).length !== 2) throw new t("unsupported", "VFX shapes need their birth shader; update the shapes edits");
14
+ return e.replace(n, r);
15
+ }, a = "struct Shape {a:vec4f,b:vec4f}\n@group(0) @binding(7) var<uniform> birthShape:Shape;\n", o = {
16
+ hemisphere: "let y=random(seed+8u);let a=6.2831853*random(seed+9u);let r=sqrt(max(0.0,1-y*y));shapeDir=vec3f(r*cos(a),y,r*sin(a));origin+=shapeDir*birthShape.a.x*select(pow(random(seed+10u),0.333333333),1.0,birthShape.a.z>0);",
17
+ cylinder: "let a=6.2831853*random(seed+8u);shapeDir=vec3f(cos(a),0,sin(a));let r=birthShape.a.x*select(sqrt(random(seed+9u)),1.0,birthShape.a.z>0);origin+=shapeDir*r+vec3f(0,(random(seed+10u)-0.5)*birthShape.a.y,0);",
18
+ torus: "let a=6.2831853*random(seed+8u);let r=birthShape.a.y*select(sqrt(random(seed+9u)),1.0,birthShape.a.z>0);let quantile=6.2831853*random(seed+10u);var lo=0.0;var hi=6.2831853;\n for(var k=0u;k<24u;k++){let mid=(lo+hi)*0.5;if(mid+(r/birthShape.a.x)*sin(mid)<quantile){lo=mid;}else{hi=mid;}}\n let b=(lo+hi)*0.5;let ring=vec3f(cos(a),0,sin(a));shapeDir=ring*cos(b)+vec3f(0,sin(b),0);origin+=ring*birthShape.a.x+shapeDir*r;",
19
+ "rectangle-edge": "let w=birthShape.a.x;let h=birthShape.a.y;let t=random(seed+8u)*2*(w+h);var offset=vec3f(0);\n if(t<w){offset=vec3f(t-w*0.5,0,-h*0.5);shapeDir=vec3f(0,0,-1);}else if(t<w+h){offset=vec3f(w*0.5,0,t-w-h*0.5);shapeDir=vec3f(1,0,0);}else if(t<2*w+h){offset=vec3f(w*0.5-(t-w-h),0,h*0.5);shapeDir=vec3f(0,0,1);}else{offset=vec3f(-w*0.5,0,h*0.5-(t-2*w-h));shapeDir=vec3f(-1,0,0);}origin+=offset;",
20
+ grid: "let counts=vec3u(birthShape.b.xyz);let at=min(u32(random(seed+8u)*f32(counts.x*counts.y*counts.z)),counts.x*counts.y*counts.z-1u);let cell=vec3u(at%counts.x,(at/counts.x)%counts.y,at/(counts.x*counts.y));origin+=(vec3f(cell)-(vec3f(counts)-1)*0.5)*birthShape.a.xyz;shapeDir=vec3f(0,1,0);"
21
+ }, s = {
22
+ validate(t, i) {
23
+ if (!t || typeof t != "object" || !n(t)) e.validate(t, i);
24
+ else {
25
+ if (r(t.speed ?? 0, "speed", -1e3, 1e3), "shell" in t && t.shell !== void 0 && typeof t.shell != "boolean") throw TypeError("VFX shapes shell must be boolean; pass true or false");
26
+ if ((t.shape === "hemisphere" || t.shape === "cylinder" || t.shape === "torus") && r(t.radius ?? 1, "radius", 1e-6, 1e6), t.shape === "cylinder" && r(t.height ?? 1, "height", 1e-6, 1e6), t.shape === "torus" && (r(t.tube ?? .25, "tube", 1e-6, 1e6), (t.tube ?? .25) >= (t.radius ?? 1))) throw RangeError("VFX torus tube must be smaller than its radius; use a regular ring");
27
+ if (t.shape === "rectangle-edge" && (r(t.width ?? 1, "width", 1e-6, 1e6), r(t.height ?? 1, "height", 1e-6, 1e6)), t.shape === "grid") {
28
+ let e = 1;
29
+ for (let n of [
30
+ "columns",
31
+ "rows",
32
+ "layers"
33
+ ]) {
34
+ let i = t[n] ?? 1;
35
+ if (r(i, n, 1, 1e6), !Number.isInteger(i)) throw RangeError(`VFX grid ${n} must be whole; pass an integer`);
36
+ e *= i;
37
+ }
38
+ if (e > 1e6) throw RangeError("VFX grid needs at most 1000000 cells; reduce its dimensions");
39
+ let n = t.spacing ?? [
40
+ 1,
41
+ 1,
42
+ 1
43
+ ];
44
+ if (!Array.isArray(n) || n.length !== 3) throw TypeError("VFX grid spacing needs [x,y,z]; pass three distances");
45
+ n.forEach((e) => r(e, "spacing", 0, 1e6));
46
+ }
47
+ }
48
+ },
49
+ patch(t, r) {
50
+ return n(r) ? (t = t.replace("fn update(", a + "fn update("), t = i(t, "let origin=f.emitterTime.xyz+(vec3f(random(seed+5u),random(seed+6u),random(seed+7u))*2-1)*f.emissionExtent.xyz;", `var origin=f.emitterTime.xyz+(vec3f(random(seed+5u),random(seed+6u),random(seed+7u))*2-1)*f.emissionExtent.xyz;var shapeDir=vec3f(0);${o[r.shape]}`), i(t, "f.velocitySpread.xyz+(", "f.velocitySpread.xyz+shapeDir*birthShape.b.w+(")) : e.patch(t, r);
51
+ },
52
+ create(t, r, i) {
53
+ if (!n(r)) return e.create(t, r, i);
54
+ let a = t.createBuffer({
55
+ size: 32,
56
+ usage: 72
57
+ });
58
+ i.push(a);
59
+ let o = /* @__PURE__ */ new Float32Array(8);
60
+ return {
61
+ entries: [{
62
+ binding: 7,
63
+ resource: { buffer: a }
64
+ }],
65
+ write(e, t) {
66
+ if (!n(t) || t.shape !== r.shape) throw TypeError("VFX shape is fixed at attach; create a new effect to change it");
67
+ o.fill(0), o[7] = t.speed ?? 0, (t.shape === "hemisphere" || t.shape === "cylinder" || t.shape === "torus") && (o[0] = t.radius ?? 1, o[2] = +!!t.shell), t.shape === "cylinder" && (o[1] = t.height ?? 1), t.shape === "torus" && (o[1] = t.tube ?? .25), t.shape === "rectangle-edge" && (o[0] = t.width ?? 1, o[1] = t.height ?? 1), t.shape === "grid" && (o.set(t.spacing ?? [
68
+ 1,
69
+ 1,
70
+ 1
71
+ ]), o.set([
72
+ t.columns ?? 1,
73
+ t.rows ?? 1,
74
+ t.layers ?? 1
75
+ ], 4)), e.writeBuffer(a, 0, o);
76
+ }
77
+ };
78
+ }
79
+ };
80
+ //#endregion
81
+ export { s as shapes };
@@ -0,0 +1,33 @@
1
+ import type { ColorInput } from '@margoengine/math/color';
2
+
3
+ /**
4
+ * Fog as `@margoengine/environment`'s `Fog` exposes it: pass that Fog, or any object with these fields. Read every
5
+ * frame, so changing the Fog changes the fog at once. Missing fields take Fog's defaults. A negative or non-finite
6
+ * distance, density or falloff (or a non-finite height) throws a RangeError, a malformed colour a TypeError or
7
+ * RangeError, a non-boolean `enabled` a TypeError.
8
+ */
9
+ export interface FogLike {
10
+ /** Fog colour: hex is sRGB, `[r, g, b]` linear. Default '#ffffff'. */
11
+ readonly color?: ColorInput;
12
+ /** Linear fog start distance from the camera. Default 1. */
13
+ readonly near?: number;
14
+ /** Linear fog end distance, where fog is full. Default 1000. */
15
+ readonly far?: number;
16
+ /** Above 0 selects exponential-squared fog `1 - exp(-(density * distance)^2)`. Default 0. */
17
+ readonly density?: number;
18
+ /** Height fog: fog thins by `exp(-heightFalloff * (y - height))` above world height `height`. Default 0 (off). */
19
+ readonly heightFalloff?: number;
20
+ /** World height below which fog is at full strength. Default 0. */
21
+ readonly height?: number;
22
+ /** False mixes in no fog; switching never recompiles. Default true. */
23
+ readonly enabled?: boolean;
24
+ }
25
+
26
+ /** Bytes of the fog uniform: colour and height, near/far/density/falloff, camera position. */
27
+ export const FOG_BYTES: 48;
28
+ /** WGSL: the fog uniform at `@group(group) @binding(binding)` and `fogAmount(world position)`, 0 (clear) to 1. */
29
+ export function fogWgsl(group: number, binding: number): string;
30
+ /** Throws when `fog` is neither null nor an object; `setFog` calls it so a wrong argument fails where it is passed. */
31
+ export function checkFog(fog: FogLike | null): FogLike | null;
32
+ /** Validates `fog` and writes the 12-float fog uniform into `out` (colour sRGB-encoded with `encode`). */
33
+ export function writeFog(fog: FogLike, eye: ArrayLike<number>, out: Float32Array, encode?: boolean): void;
@@ -0,0 +1,53 @@
1
+ /** A reusable pass descriptor drawing over the frame: colour load/store, depth and stencil read only. */
2
+ export function overlayPass(): GPURenderPassDescriptor & {
3
+ colorAttachments: [GPURenderPassColorAttachment];
4
+ depthStencilAttachment: GPURenderPassDepthStencilAttachment;
5
+ };
6
+ /** {@link overlayPass} that also loads and stores depth. */
7
+ export function overlayDepthPass(): GPURenderPassDescriptor & {
8
+ colorAttachments: [GPURenderPassColorAttachment];
9
+ depthStencilAttachment: GPURenderPassDepthStencilAttachment;
10
+ };
11
+ /** Straight (non-premultiplied) alpha blending. */
12
+ export const alphaBlend: GPUBlendState;
13
+ /** Straight alpha blending that leaves the target's alpha channel unchanged: precipitation and other overlays drawn into a frame. */
14
+ export const overlayBlend: GPUBlendState;
15
+
16
+ /** `mesh` when it is null or a core mesh handle (checked live); else a TypeError. */
17
+ export function attachableMesh<M extends { check(): void } | null>(mesh: M): M;
18
+ /**
19
+ * What an order-independent pass offers an effect that is no PBR surface (particles, splats, points), in place of
20
+ * gltf/pbr's transparency hook. Same contract, but `surface` declares `fn margoTransparentAt(color:vec4f,clip:vec4f,
21
+ * depth:f32)->MargoTransparent`: `clip` is the fragment's position builtin, `depth` its view depth.
22
+ */
23
+ export interface SurfaceTransparency {
24
+ /** Module-scope WGSL: `struct MargoTransparent` (one output per target), `margoTransparentAt` and its bindings in `group`. */
25
+ surface(group: number): string;
26
+ /** Layout of those bindings, for an effect with explicit pipeline layouts. */
27
+ readonly layout: readonly GPUBindGroupLayoutEntry[];
28
+ /** Entries for those bindings. */
29
+ bindings(): GPUBindGroupEntry[];
30
+ /** True: declarations hold `override margoKind:u32`, 0 normal, 1 additive; additive surfaces may draw here. */
31
+ readonly blends?: boolean;
32
+ /** Colour targets of the transparent pass, in `MargoTransparent` location order. */
33
+ readonly targets: readonly GPUColorTargetState[];
34
+ /** This frame's transparent pass, begun on the first draw and ended by the owner. */
35
+ begin(): GPURenderPassEncoder;
36
+ }
37
+ /** The fragment entry `transparent` of an effect under a transparency hook: `inputs` are its parameters, the rest WGSL expressions. */
38
+ export function surfaceEntry(declarations: string, inputs: string, color: string, clip: string, depth: string): string;
39
+ /** Holds an effect's transparency hook: `set` takes it and `released`, and returns the remover. */
40
+ export function transparencySlot(): {
41
+ hook?: SurfaceTransparency;
42
+ released?: () => void;
43
+ set(hook: SurfaceTransparency, released?: () => void): () => void;
44
+ };
45
+ /** `hook`'s pass with `pipeline` set, `group` at group 0 and the hook's bindings at group 1, for an effect with an auto layout. */
46
+ export function surfacePass(
47
+ device: GPUDevice,
48
+ hook: SurfaceTransparency,
49
+ pipeline: GPURenderPipeline,
50
+ group: GPUBindGroup,
51
+ ): GPURenderPassEncoder;
52
+ /** The WGSL `make(group)` builds for bind group `group`, made once per group and kept in `cache`. */
53
+ export function groupCode(cache: Map<number, string>, group: number, make: (group: number) => string): string;
@@ -0,0 +1,89 @@
1
+ /** A colour value: linear RGB. */
2
+ export type SettingColor = readonly [number, number, number];
3
+ /** One gradient stop: a colour at a position (`elevation` unless the row's `stopKey` says otherwise). */
4
+ export type SettingStop = { readonly color: SettingColor };
5
+ /** One value of a setting: a number, a colour, a choice, gradient stops, or null where `nullable`. */
6
+ export type SettingValue = number | SettingColor | string | readonly SettingStop[] | null;
7
+ /** Values by setting name; a name left out takes its default. */
8
+ export type SettingValues = Readonly<Record<string, SettingValue>>;
9
+ /** One slider row, the shape every package's `/settings` entry shares. */
10
+ export interface SettingRow {
11
+ readonly name: string;
12
+ readonly group: string;
13
+ /** `number` is a slider, `color` three sliders or a picker, `choice` a list, `gradient` a stop editor. */
14
+ readonly kind: 'number' | 'color' | 'choice' | 'gradient';
15
+ /** The value with which the target draws exactly as it does without the option (null: follow the weather). */
16
+ readonly default: SettingValue;
17
+ readonly min?: number;
18
+ readonly max?: number;
19
+ readonly step?: number;
20
+ readonly choices?: readonly string[];
21
+ /** May be null: the target uses its own value, or follows the weather when `weather` is set. */
22
+ readonly nullable?: boolean;
23
+ /** The weather master slider that drives this row while it is null. */
24
+ readonly weather?: string;
25
+ /** The key a gradient stop is placed by (default `elevation`). */
26
+ readonly stopKey?: string;
27
+ readonly unit: string;
28
+ readonly about: string;
29
+ /** True: cheap to write every frame (no pipeline, buffer or texture is created), so it can be keyed over a shot. False: writing it rebuilds something. */
30
+ readonly live: boolean;
31
+ }
32
+ export declare const numberSetting: (
33
+ name: string,
34
+ group: string,
35
+ value: number,
36
+ min: number,
37
+ max: number,
38
+ step: number,
39
+ unit: string,
40
+ about: string,
41
+ live?: boolean,
42
+ ) => SettingRow;
43
+ export declare const colorSetting: (
44
+ name: string,
45
+ group: string,
46
+ value: SettingColor,
47
+ min: number,
48
+ max: number,
49
+ about: string,
50
+ live?: boolean,
51
+ ) => SettingRow;
52
+ export declare const choiceSetting: (
53
+ name: string,
54
+ group: string,
55
+ choices: readonly string[],
56
+ about: string,
57
+ live?: boolean,
58
+ ) => SettingRow;
59
+ /** The row with a null default that follows the weather master slider `weather` until a value is given. */
60
+ export declare const followsWeather: (row: SettingRow, weather: string) => SettingRow;
61
+ /** Marks `key` of `target` as set by hand (`held` true) or hands it back to the weather (false). */
62
+ export declare function holdFromWeather(target: object, key: string, held?: boolean): void;
63
+ /** True while `key` of `target` holds a value set by hand, which the weather drive leaves alone. */
64
+ export declare const heldFromWeather: (target: object, key: string) => boolean;
65
+ export declare const sameSettingValue: (a: unknown, b: unknown) => boolean;
66
+ export declare function copySettingValue(v: SettingValue): SettingValue;
67
+ /** A fresh object holding every row at its default (a slider panel's state). */
68
+ export declare function settingDefaults(rows: readonly SettingRow[]): Record<string, SettingValue>;
69
+ /** The rows that may change every frame without a rebuild. */
70
+ export declare const liveSettings: (rows: readonly SettingRow[]) => SettingRow[];
71
+ /** A name to row map. */
72
+ export declare const settingIndex: (rows: readonly SettingRow[]) => Map<string, SettingRow>;
73
+ /** @throws RangeError when `v` is not a value of `row`. */
74
+ export declare function checkSettingValue(row: SettingRow, v: unknown, label: string): void;
75
+ /** @throws TypeError for an unknown name; RangeError for a bad value or a null on a row that is not nullable. */
76
+ export declare function checkSettings(
77
+ rows: readonly SettingRow[] | ReadonlyMap<string, SettingRow>,
78
+ values: SettingValues,
79
+ label: string,
80
+ entry?: string,
81
+ ): void;
82
+ /** Checks `values`, then calls `write` once per row (or per row `only` accepts) with the given value or the default. */
83
+ export declare function applySettings(
84
+ rows: readonly SettingRow[],
85
+ values: SettingValues,
86
+ label: string,
87
+ write: (row: SettingRow, value: SettingValue) => void,
88
+ only?: (row: SettingRow) => boolean,
89
+ ): void;
@@ -0,0 +1,11 @@
1
+ import type { VFXExtension, VFXSkinned } from './base.js';
2
+ /** Most triangles of a skinned emitter (16 bytes each on the GPU, beside the 80-byte vertices). */
3
+ export declare const MAX_SKINNED_TRIANGLES = 262144;
4
+ /** The triangle words: indices and running area share of the bind pose; zero-area triangles left out. */
5
+ export declare function skinnedTriangles(vertices: Float32Array, indices: ArrayLike<number>): Uint32Array;
6
+ /**
7
+ * The `skinned` feature: births on the surface of an animated (skinned or morphed) primitive, following its pose.
8
+ * Pass it as `{skinned}` to `VFX` from `@margoengine/vfx/base`; the root `VFX` has it. The primitive's triangles and
9
+ * bind pose are read at attach; its `deformed` buffer and offset, `transform` and `speed` every frame.
10
+ */
11
+ export declare const skinned: VFXExtension<VFXSkinned>;