@margoengine/vfx 0.1.0 → 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 (46) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +2241 -1642
  4. package/dist/{base-C9upJytz.js → base-LGs65K7K.js} +174 -123
  5. package/dist/base.d.ts +104 -2
  6. package/dist/base.js +1 -1
  7. package/dist/blown-sand.js +3 -3
  8. package/dist/clouds.d.ts +12 -4
  9. package/dist/clouds.js +35 -18
  10. package/dist/compat-BFjXAQuu.js +14 -0
  11. package/dist/debris.d.ts +43 -0
  12. package/dist/debris.js +33 -1
  13. package/dist/dust-current.d.ts +66 -0
  14. package/dist/dust-current.js +92 -0
  15. package/dist/fire-front.d.ts +72 -1
  16. package/dist/fire-front.js +309 -69
  17. package/dist/fire.d.ts +24 -3
  18. package/dist/fire.js +114 -93
  19. package/dist/flame.d.ts +171 -3
  20. package/dist/flame.js +343 -131
  21. package/dist/flocking-shaders.d.ts +48 -0
  22. package/dist/flocking-sim.d.ts +623 -0
  23. package/dist/flocking.d.ts +145 -0
  24. package/dist/flocking.js +1846 -0
  25. package/dist/gunfire.d.ts +52 -6
  26. package/dist/gunfire.js +108 -98
  27. package/dist/index.d.ts +1 -1
  28. package/dist/index.js +5 -5
  29. package/dist/json.js +2 -0
  30. package/dist/lit-Dx2tNwP-.js +152 -0
  31. package/dist/lit.d.ts +8 -1
  32. package/dist/lit.js +1 -105
  33. package/dist/mesh.d.ts +2 -0
  34. package/dist/mesh.js +92 -69
  35. package/dist/over-life.js +16 -15
  36. package/dist/reactive-mask-B8xbyzlk.js +69 -0
  37. package/dist/ribbons.d.ts +4 -2
  38. package/dist/ribbons.js +87 -73
  39. package/dist/settings.js +1 -1
  40. package/dist/shader.d.ts +5 -0
  41. package/dist/shared/fog.d.ts +33 -33
  42. package/dist/shared/pass.d.ts +53 -53
  43. package/dist/shared/settings.d.ts +89 -89
  44. package/dist/smoke.d.ts +72 -4
  45. package/dist/smoke.js +280 -56
  46. package/package.json +200 -192
package/dist/base.d.ts CHANGED
@@ -70,6 +70,13 @@ export interface VFXOptions {
70
70
  * and `onPreUpdate` then move nothing. Read every frame. Default none: one step of the frame's delta, as before.
71
71
  */
72
72
  clock?: Pick<FilmClock, 'ticks'>;
73
+ /**
74
+ * With a `clock`: called once a tick, with the tick's time in seconds, before its births are counted. It may set
75
+ * `rate`, `position`, `velocity`, `spread` and `emissionExtent` here and call `burst(count)`, and that tick is born
76
+ * with them, so an emitter that moves (a ship's bow) births at each tick where it was then, whatever the frame rate.
77
+ * Default none: every tick of a frame births at the options as the frame left them.
78
+ */
79
+ tick?: (time: number) => void;
73
80
  /** Up to 64 spheres/boxes that the flow bends around and particles bounce off. Contents are read each frame; pass an array (even `[]`) before attaching. */
74
81
  obstacles?: readonly VFXObstacle[];
75
82
  /** Keep particles inside the emission box, re-entering on the opposite face (every extent must be > 0). Read at attach. */
@@ -82,6 +89,13 @@ export interface VFXOptions {
82
89
  * feature and `depth`; changeable between frames. Default 0 (off: no extra shader code, bindings or per-frame work).
83
90
  */
84
91
  softness?: number;
92
+ /**
93
+ * Draw the billboards' coverage (their alpha, depth tested like the particles) into the frame's shared reactive mask,
94
+ * which TAA reads with no option, so moving particles stay crisp instead of smearing into a history they have no
95
+ * motion vectors for. Default: on while TAA (or another reader of reactive masks) runs, off otherwise; `true` draws
96
+ * it every frame, `false` never. Changeable between frames.
97
+ */
98
+ reactive?: boolean;
85
99
  /**
86
100
  * Scene depth for `softness`: a function returning a sampleable depth texture (reversed Z: 1 at the near plane, 0 where
87
101
  * nothing is drawn; 1 sample or the scene's sample count) the size of the drawing buffer, or undefined before it
@@ -278,6 +292,13 @@ export interface VFXLightSource {
278
292
  };
279
293
  bindings(): GPUBindGroupEntry[];
280
294
  }
295
+ /** What `VFXLit.lamps` takes: `Clustered.lamps` of `@margoengine/clustered`. */
296
+ export interface VFXLamps {
297
+ lamps(group: number): {
298
+ readonly declarations: string;
299
+ bindings(): GPUBindGroupEntry[];
300
+ };
301
+ }
281
302
  /**
282
303
  * Lighting for the billboards: each one is shaded as a ball (its normal from where the pixel lies on the disc) in its
283
304
  * own colour, by the engine's sun with wrap lighting, the ambient light, and optionally clustered lights and sun
@@ -287,6 +308,26 @@ export interface VFXLightSource {
287
308
  export interface VFXLit {
288
309
  /** Point and spot lights: `Clustered` from `@margoengine/clustered`. Fixed at attach. */
289
310
  lights?: VFXLightSource;
311
+ /**
312
+ * Point and spot lamps the particles scatter instead of shading as balls: pass the `Clustered` the scene is lit by.
313
+ * Each pixel adds `colour * lampAlbedo * lamp irradiance * phase`, the lamps' own falloff and cones with a
314
+ * forward-peaked two-lobe Henyey-Greenstein phase (`lampPhase`), the same light Weather's `lamps` give snow
315
+ * (`shared/lamp-scatter.js`), so spray and spindrift glow round a ship's lamps at night and brightest looking toward
316
+ * them. A function of each particle's position alone, so it seeks and replays. Lamp shadows are not read. Takes the
317
+ * place of `lights` (give one or the other). Fixed at attach. Default none.
318
+ */
319
+ lamps?: VFXLamps;
320
+ /** Albedo of a particle to the lamps' light, 0 to 1, read every frame. Default 1 (water drops absorb almost nothing in the visible). */
321
+ lampAlbedo?: number;
322
+ /**
323
+ * The phase: forward and back Henyey-Greenstein g (-0.99 to 0.99) and the back lobe's share (0 to 1), read every
324
+ * frame. Default `SPRAY_PHASE`, {forward: 0.9, back: -0.3, backWeight: 0.1}.
325
+ */
326
+ lampPhase?: {
327
+ forward?: number;
328
+ back?: number;
329
+ backWeight?: number;
330
+ };
290
331
  /** Sun shadows on the particles: `Shadows` from `@margoengine/shadows`. Fixed at attach. */
291
332
  shadows?: VFXLightSource;
292
333
  /** How far the sun wraps round the dark side, 0 (a hard ball) to 1 (dark only at the far pole). Default 0.5. */
@@ -296,8 +337,8 @@ export interface VFXLit {
296
337
  /**
297
338
  * A fire's glow on the particles, read every frame: a point source radiating `power` watts at `position`, softened
298
339
  * over `radius` metres (default 1), of `color` (default `GLOW_COLOR`, a flame's orange). Its irradiance
299
- * P / (4 pi (d^2 + r^2)) lights a particle as the sun at intensity pi lights it with 1,000 W/m^2, so smoke over a fire
300
- * is lit orange from below, by night with no other light. Default none.
340
+ * P / (4 pi (d^2 + r^2)) lights a particle as the scene's noon sun (`noon`) lights it with 1,000 W/m^2, so smoke over
341
+ * a fire is lit orange from below, by night with no other light. Default none.
301
342
  */
302
343
  glow?: {
303
344
  position: readonly [number, number, number];
@@ -305,6 +346,34 @@ export interface VFXLit {
305
346
  radius?: number;
306
347
  color?: readonly [number, number, number];
307
348
  };
349
+ /**
350
+ * The engine sun intensity of the scene's noon sun, the light of 1,000 W/m^2 the glow is referred to: the sky's
351
+ * `lighting.intensity` (1 by default, `SUN_ILLUMINANCE` in a scene lit in lux, 5 in timber valley). A glow of E W/m^2
352
+ * lights a particle as a sun of intensity `noon * E / 1,000` would, so a fire is the same share of the noon light in
353
+ * any scene units. Read every frame; `WeatherDrive` writes it on its fire fronts' smoke from its sky. Default pi.
354
+ */
355
+ noon?: number;
356
+ /**
357
+ * Light of the air round the particles, beside the ambient: red, green and blue shares of the noon sun's light
358
+ * (`noon`, 1,000 W/m^2) that the haze they sit in receives, as a fire lights its smoke pall from below. Light of that
359
+ * share from every side adds `air * noon / pi` to the ambient, so smoke inside a firelit pall takes the pall's light.
360
+ * Read every frame; `WeatherDrive` writes it on its fire fronts' smoke. Each 0 to 1,000. Default none.
361
+ */
362
+ air?: readonly [number, number, number];
363
+ /**
364
+ * The ground's albedo under the particles, 0 to 1: the ambient comes down from the sky and the ground sends back this
365
+ * share of it, so a particle is lit on top by the sky and less underneath, with the same mean (Liu and Jordan's
366
+ * isotropic view factors, KB-VFX-SMOKEFLAT1). 1 lights every side alike. Read every frame. Default 0.2, as Sky
367
+ * `lighting.ground`.
368
+ */
369
+ ground?: number;
370
+ /**
371
+ * The reflectance of the layer over the particles, red, green and blue, each 0 to 1: the `air`'s light comes up from
372
+ * below (a fire under its pall) and the layer sends back this share of it from above, so smoke over a fire glows
373
+ * underneath, with the same mean. 1 lights every side alike. Read every frame; `WeatherDrive` writes its haze's
374
+ * reflectance on its fire fronts' smoke. Default `PALL_REFLECTANCE`, a thick smoke pall's.
375
+ */
376
+ airReflectance?: readonly [number, number, number];
308
377
  }
309
378
  /**
310
379
  * Sub-emitters: a particle that is born from the emitter (`on: 'birth'`, a trail or a flash at the muzzle), dies (`on: 'death'`), or meets the ground faster than `speed` (`on: 'collision'`),
@@ -610,6 +679,12 @@ export declare class VFX implements EnginePlugin {
610
679
  private readonly attachment;
611
680
  private readonly depthAttachment;
612
681
  private readonly presentation;
682
+ private readonly reactiveAttachments;
683
+ /** The last billboard pass, whose coverage an ambient replay of the same frame, view and depth veils. */
684
+ private readonly veiled;
685
+ private readonly ambientVeil;
686
+ private leaveVeils?;
687
+ private readonly reactivePass;
613
688
  private renderFormat;
614
689
  private renderDepth;
615
690
  private renderKey;
@@ -670,6 +745,7 @@ export declare class VFX implements EnginePlugin {
670
745
  /** Steps taken while the WebGL2 route is still loading, run in order when it resolves (KB-VFX-EMBERCPU1). */
671
746
  private held;
672
747
  private routeLoading;
748
+ private routeReady;
673
749
  private disposed;
674
750
  constructor(options?: VFXOptions, features?: VFXFeatures);
675
751
  static attach(instance: EngineKernel, options?: VFXOptions, features?: VFXFeatures): VFX;
@@ -710,6 +786,20 @@ export declare class VFX implements EnginePlugin {
710
786
  */
711
787
  setWind(wind: VFXWind | undefined): this;
712
788
  setup(engine: Engine): void;
789
+ /**
790
+ * Settles once every frame simulates and draws the effect as it will from then on. On the WebGL2 compatibility layer
791
+ * a VFX loads its route (a dynamic import) when it attaches; until it has loaded an effect with a prewarm holds its
792
+ * steps, and one without runs its WebGPU kernels on the layer's CPU tier. Resolved at once on WebGPU. Read it after
793
+ * attaching, and await it before a frame that must be exact: a film frame, a pixel comparison (KB-COMPAT-READY1).
794
+ *
795
+ * @example
796
+ * ```ts
797
+ * const sparks = VFX.attach(engine, { capacity: 1000 });
798
+ * await sparks.ready;
799
+ * engine.render();
800
+ * ```
801
+ */
802
+ get ready(): Promise<void>;
713
803
  registerPasses(graph: FrameGraph): void;
714
804
  /**
715
805
  * Seconds on the effect's clock: the sum of its frame deltas since it started or since `reset()`; with a film clock,
@@ -745,6 +835,18 @@ export declare class VFX implements EnginePlugin {
745
835
  private prepare;
746
836
  private draw;
747
837
  private billboards;
838
+ /**
839
+ * Draws this frame's billboards over an ambient replay's target (`c.color`, of `format`) as a veil: where a particle
840
+ * covers alpha of a pixel, that share of the light of the surface behind it leaves the target, so occlusion takes no
841
+ * more than the pixel holds (KB-SSAO-BLENDVEIL1). Only after this view's own billboard pass of the same frame; returns
842
+ * whether it drew.
843
+ */
844
+ private veil;
845
+ /**
846
+ * The billboards' coverage into the frame's shared reactive mask, which TAA reads by itself (KB-TAA-PARTICLEMASK1):
847
+ * while TAA reads masks, or always with `reactive: true`.
848
+ */
849
+ private drawReactive;
748
850
  /**
749
851
  * Leaves the frame's draw (order 6) to an order-independent pass, which calls `drawTransparent`. Use `addEffect` from
750
852
  * `@margoengine/oit/vfx`. Returns a remover; `released` runs if this effect is disposed first.
package/dist/base.js CHANGED
@@ -1 +1 @@
1
- export { t as VFX, n as VFX_TICK_RATE } from "./base-C9upJytz.js";
1
+ export { t as VFX, n as VFX_TICK_RATE } from "./base-LGs65K7K.js";
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
4
  import { t as e } from "./view-RKprOPAy.js";
@@ -338,7 +338,7 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
338
338
  ${t ? "rgb=encodeSrgb(max(rgb,vec3f(0.0)));" : ""}
339
339
  return vec4f(rgb*a,a);
340
340
  }
341
- `, F = 56, I = 0, L = class i {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
341
+ `, F = 56, I = 0, L = class i {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
342
342
  constructor(e) {
343
343
  this.name = "blown-sand:" + I++, this.stats = {
344
344
  tiles: 0,
@@ -353,7 +353,7 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
353
353
  depthReadOnly: !0
354
354
  }, this.options = e, this.validate();
355
355
  }
356
- static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
356
+ static attach(e, t) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
357
357
  let n = new i(t);
358
358
  return e.use(n), n;
359
359
  }
package/dist/clouds.d.ts CHANGED
@@ -78,10 +78,12 @@ export interface CloudsOptions {
78
78
  /** Optical depth through the centre of a full-size puff, for the light reaching the puffs behind it, 0 or more. Default 1. */
79
79
  density?: number;
80
80
  /**
81
- * 0..1: shades each puff of 'scatter' as a lit sphere instead of a flat disc, so a heap of puffs reads as rounded
82
- * lobes with lit tops and dark undersides: the direct light by the half-Lambert of the sphere's normal, and the
83
- * ambient by the sky the normal faces times the sky light left after the puffs above it; above 0 the light through
84
- * the cloud also counts multiple scattering (three octaves, Wrenninge et al. 2013). 0 keeps flat puffs. Default 0.
81
+ * 0..1: shades each puff of 'scatter' as a lit surface instead of a flat disc, so a heap of puffs reads as rounded
82
+ * lobes with lit tops and dark undersides: the direct light by the half-Lambert of the normal, and the ambient by the
83
+ * sky the normal faces times the sky light left after the puffs above it. The normal is the heap's own (the gradient
84
+ * of its puffs' density, {@link CloudPuff.normal}) with the puff's sphere as a lobe on it, so a column of many puffs
85
+ * shades as one rounded body, not a stack of balls; a puff alone is its sphere. Above 0 the light through the cloud
86
+ * also counts multiple scattering (three octaves, Wrenninge et al. 2013). 0 keeps flat puffs. Default 0.
85
87
  */
86
88
  relief?: number;
87
89
  /** World units over which a puff fades out in front of the surface behind it (needs `depth`); 0 is off. Default 0. */
@@ -104,6 +106,12 @@ export interface CloudPuff {
104
106
  light: number;
105
107
  /** Share of the sky light from straight above that reaches the puff, 0..1 (1 unless `relief` is above 0). */
106
108
  sky: number;
109
+ /**
110
+ * With `relief`, the heap's outward normal at the puff, unnormalised: minus the gradient of the other puffs' Gaussian
111
+ * density there (Levoy 1988's gradient normal), in units of the puff's radius, so it is about 1 at a heap's surface
112
+ * and near 0 for a puff alone or deep inside. The puff's own sphere adds to it as a lobe. [0, 0, 0] without relief.
113
+ */
114
+ normal: [number, number, number];
107
115
  /** Light the puff gives off, linear RGB. */
108
116
  emission: [number, number, number];
109
117
  /** Linear RGB and opacity (before the near fade). */
package/dist/clouds.js CHANGED
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
4
  import { t as e } from "./view-RKprOPAy.js";
@@ -10,7 +10,7 @@ import { MargoError as c } from "@margoengine/math/errors";
10
10
  import { parseColor as l } from "@margoengine/math/color";
11
11
  import { createRandom as u } from "@margoengine/math/mathutils";
12
12
  //#region src/clouds.ts
13
- var d = 16, f = 36, p = 0, m = (e) => {
13
+ var d = 20, f = 36, p = 0, m = (e) => {
14
14
  throw RangeError(e);
15
15
  }, h = (e, t, n, r, i = Infinity) => {
16
16
  let a = e === void 0 ? t : e;
@@ -180,8 +180,8 @@ struct Frame {camera:mat4x4f,right:vec4f,up:vec4f,eye:vec4f,light:vec4f,lightCol
180
180
  @group(0) @binding(1) var puffTexture:texture_2d<f32>;
181
181
  @group(0) @binding(2) var puffSampler:sampler;
182
182
  ${e ? o(e) : ""}${n ? t(0, 5) : ""}
183
- struct Out {@builtin(position) clip:vec4f,@location(0) uv:vec2f,@location(1) color:vec4f,@location(2) world:vec3f,@location(3) viewDepth:f32,@location(4) offset:vec2f,@location(5) back:vec3f,@location(6) shade:vec2f,@location(7) glow:vec3f}
184
- @vertex fn vertex(@builtin(vertex_index) v:u32,@location(0) centre:vec4f,@location(1) tint:vec4f,@location(2) extra:vec4f,@location(3) glow:vec4f)->Out {
183
+ struct Out {@builtin(position) clip:vec4f,@location(0) uv:vec2f,@location(1) color:vec4f,@location(2) world:vec3f,@location(3) viewDepth:f32,@location(4) offset:vec2f,@location(5) back:vec3f,@location(6) shade:vec2f,@location(7) glow:vec3f,@location(8) heap:vec3f}
184
+ @vertex fn vertex(@builtin(vertex_index) v:u32,@location(0) centre:vec4f,@location(1) tint:vec4f,@location(2) extra:vec4f,@location(3) glow:vec4f,@location(4) heap:vec4f)->Out {
185
185
  let corner=vec2f(f32(v&1u),f32(v>>1u))*2.0-1.0;
186
186
  let c=cos(extra.x);let s=sin(extra.x);
187
187
  let offset=vec2f(c*corner.x-s*corner.y,s*corner.x+c*corner.y);
@@ -201,6 +201,7 @@ struct Out {@builtin(position) clip:vec4f,@location(0) uv:vec2f,@location(1) col
201
201
  o.back=-toPuff/max(distance,1e-6);
202
202
  o.shade=vec2f(extra.y*0.75*(1.0+cosine*cosine),extra.w);
203
203
  o.glow=glow.rgb;
204
+ o.heap=heap.xyz;
204
205
  o.color=vec4f(tint.rgb,tint.a*near);
205
206
  return o;
206
207
  }
@@ -214,8 +215,11 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
214
215
  if (frame.lightColor.w>0.5) {
215
216
 
216
217
 
218
+
217
219
  let relief=frame.right.w;
218
- let n=normalize(frame.right.xyz*i.offset.x+frame.up.xyz*i.offset.y+i.back*sqrt(max(1.0-dot(i.offset,i.offset),0.0)));
220
+ let lobe=frame.right.xyz*i.offset.x+frame.up.xyz*i.offset.y+i.back*sqrt(max(1.0-dot(i.offset,i.offset),0.0));
221
+ let m=lobe+i.heap;
222
+ let n=m*inverseSqrt(max(dot(m,m),1e-8));
219
223
  let h=dot(n,frame.light.xyz)*0.5+0.5;
220
224
  let direct=mix(1.0,2.0*h*h,relief)*i.shade.x;
221
225
 
@@ -227,7 +231,7 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
227
231
  ${r ? "rgb=encodeSrgb(max(rgb,vec3f(0.0)));" : ""}
228
232
  return vec4f(rgb*a,a);
229
233
  }
230
- `, D = class t {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
234
+ `, D = class t {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
231
235
  constructor(e = {}) {
232
236
  this.name = "clouds:" + p++, this.stats = {
233
237
  puffs: 0,
@@ -243,7 +247,7 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
243
247
  depthReadOnly: !0
244
248
  }, this.options = e, this.validate();
245
249
  }
246
- static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
250
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
247
251
  let r = new t(n);
248
252
  return e.use(r), r;
249
253
  }
@@ -321,6 +325,11 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
321
325
  angle: g[t + 4] + l * u * s,
322
326
  light: 1,
323
327
  sky: 1,
328
+ normal: [
329
+ 0,
330
+ 0,
331
+ 0
332
+ ],
324
333
  color: _.length && !Number.isNaN(_[t]) ? [
325
334
  _[t],
326
335
  _[t + 1],
@@ -346,15 +355,22 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
346
355
  }
347
356
  let b = h(r.volume, 6, "Cloud volume", 0) * m / 2;
348
357
  for (let e = v; e < o.length; e++) {
349
- let r = o[e].centre, i = 0, s = 0;
350
- for (let c = v; c < o.length; c++) {
351
- if (c === e) continue;
352
- let l = o[c].centre, u = l[0] - r[0], d = l[1] - r[1], f = l[2] - r[2], p = u * a[0] + d * a[1] + f * a[2], m = o[c].size / 2;
353
- if (!(m > 0)) continue;
354
- let h = u * u + d * d + f * f, g = t * (b > 0 ? m / b : 1);
355
- p > 0 && (i += g * Math.exp(-(h - p * p) / (m * m))), n > 0 && d > 0 && (s += g * Math.exp(-(h - d * d) / (m * m)));
358
+ let r = o[e].centre, i = 0, s = 0, c = 0, l = 0, u = 0, d = o[e].size / 2;
359
+ for (let f = v; f < o.length; f++) {
360
+ if (f === e) continue;
361
+ let p = o[f].centre, m = p[0] - r[0], h = p[1] - r[1], g = p[2] - r[2], _ = m * a[0] + h * a[1] + g * a[2], v = o[f].size / 2;
362
+ if (!(v > 0)) continue;
363
+ let y = m * m + h * h + g * g, x = t * (b > 0 ? v / b : 1);
364
+ if (_ > 0 && (i += x * Math.exp(-(y - _ * _) / (v * v))), n > 0 && h > 0 && (s += x * Math.exp(-(y - h * h) / (v * v))), n > 0) {
365
+ let e = 2 * x * Math.exp(-y / (v * v)) * d / (v * v);
366
+ c -= e * m, l -= e * h, u -= e * g;
367
+ }
356
368
  }
357
- o[e].light = n > 0 ? y(i) : Math.exp(-i), o[e].sky = n > 0 ? y(s) : 1;
369
+ o[e].light = n > 0 ? y(i) : Math.exp(-i), o[e].sky = n > 0 ? y(s) : 1, n > 0 && (o[e].normal = [
370
+ c,
371
+ l,
372
+ u
373
+ ]);
358
374
  }
359
375
  }
360
376
  return o;
@@ -402,7 +418,7 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
402
418
  a.culled = m - h.length, h.sort((e, t) => t.depth - e.depth || e.index - t.index), this.data.length < h.length * d && (this.data = new Float32Array(Math.max(n, h.length) * d));
403
419
  let g = this.data;
404
420
  return h.forEach(({ puff: e }, t) => {
405
- g.set(e.centre, t * d), g[t * d + 3] = e.size, g.set(e.color, t * d + 4), g[t * d + 8] = e.angle, g[t * d + 9] = e.light, g[t * d + 10] = e.fade, g[t * d + 11] = e.sky, g.set(e.emission, t * d + 12), g[t * d + 15] = 0;
421
+ g.set(e.centre, t * d), g[t * d + 3] = e.size, g.set(e.color, t * d + 4), g[t * d + 8] = e.angle, g[t * d + 9] = e.light, g[t * d + 10] = e.fade, g[t * d + 11] = e.sky, g.set(e.emission, t * d + 12), g[t * d + 15] = 0, g.set(e.normal, t * d + 16), g[t * d + 19] = 0;
406
422
  }), a.drawn = h.length, h.length;
407
423
  }
408
424
  textureFor(e) {
@@ -465,13 +481,14 @@ fn encodeSrgb(c:vec3f)->vec3f {return select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c
465
481
  module: t,
466
482
  entryPoint: "vertex",
467
483
  buffers: [{
468
- arrayStride: 64,
484
+ arrayStride: 80,
469
485
  stepMode: "instance",
470
486
  attributes: [
471
487
  0,
472
488
  1,
473
489
  2,
474
- 3
490
+ 3,
491
+ 4
475
492
  ].map((e) => ({
476
493
  shaderLocation: e,
477
494
  offset: e * 16,
@@ -0,0 +1,14 @@
1
+ function e(e) {
2
+ return e?.adapterInfo?.vendor === "margo-webgl2" ? "webgl2" : "native";
3
+ }
4
+ function t(t, n) {
5
+ return t.backend = e(n) === "webgl2" ? "webgl2-compat" : "webgpu", t.backend === "webgl2-compat";
6
+ }
7
+ function n(t, n) {
8
+ return e(t) === "webgl2" ? n() : void 0;
9
+ }
10
+ function r(e) {
11
+ return e ? e.then(() => void 0, () => void 0) : Promise.resolve();
12
+ }
13
+ //#endregion
14
+ export { t as n, r, n as t };
package/dist/debris.d.ts CHANGED
@@ -109,3 +109,46 @@ export declare class Debris {
109
109
  /** Takes the puff cloud {@link drawPuffs} added out of its `Clouds`. */
110
110
  clearPuffs(): void;
111
111
  }
112
+ /** A crater's spoil as `ejectaSpoil` of @margoengine/physics/crater gives it: per cell, fragments per size bin. */
113
+ export interface SpoilScatterSource {
114
+ readonly columns: number;
115
+ readonly rows: number;
116
+ /** The cell's size, m, and the grid's minimum corner, [x, z] m. */
117
+ readonly cell: number;
118
+ readonly origin: readonly [number, number];
119
+ /** The size bins' edges, m (bins + 1). */
120
+ readonly sizes: readonly number[];
121
+ /** Expected fragments landing in each cell in each bin, at (c + r * columns) * bins + bin. */
122
+ readonly counts: ArrayLike<number>;
123
+ }
124
+ /** Options of {@link drawSpoil}. */
125
+ export interface SpoilScatterOptions {
126
+ /** The ground's height at (x, z), m. Default flat at 0. */
127
+ readonly height?: (x: number, z: number) => number;
128
+ /**
129
+ * The size of the clods a fragment breaks into on landing, over its own, 0.1 to 1 (default 0.5: eight clods of half
130
+ * its size, its volume kept). A look choice: no measurement of how ejecta clods break was found.
131
+ */
132
+ readonly breakup?: number;
133
+ /** How far each clod sits in the ground, as a share of its size, 0 to 1 (default 0.35, half buried as at Fauld). */
134
+ readonly bury?: number;
135
+ /** The drawn mesh's own size at a scale of 1, m (default 1). */
136
+ readonly meshSize?: number;
137
+ /** The clods' colours, linear RGBA, each clod one of them in turn (default the red-brown mudstone of Fauld's spoil). */
138
+ readonly colors?: readonly (readonly [number, number, number, number])[];
139
+ /** The layout seed, a whole number (default 1). */
140
+ readonly seed?: number;
141
+ }
142
+ /** What {@link drawSpoil} drew: clods, the smallest size it reached, m, and the share of the spoil's clods drawn. */
143
+ export interface SpoilScatterResult {
144
+ readonly drawn: number;
145
+ readonly smallest: number;
146
+ readonly share: number;
147
+ }
148
+ /**
149
+ * Draws a crater's spoil into `target` as clods: each fragment breaks on landing into 1 / breakup^3 clods of `breakup`
150
+ * its size, scattered over its cell, turned and half buried. The largest are drawn first; when the target cannot hold
151
+ * them all, the size class that fills it is thinned evenly and smaller ones are left out. Deterministic in its seed.
152
+ * @throws RangeError for an option out of range or a source of the wrong shape.
153
+ */
154
+ export declare function drawSpoil(target: DebrisInstanceTarget, source: SpoilScatterSource, options?: SpoilScatterOptions): SpoilScatterResult;
package/dist/debris.js CHANGED
@@ -254,5 +254,37 @@ var n = 1 / 60, r = 120, i = (e) => {
254
254
  this.puff && this.puffTarget?.remove(this.puff), this.puff = null;
255
255
  }
256
256
  };
257
+ function l(e, t, n = {}) {
258
+ let r = n.height ?? (() => 0), i = n.breakup ?? .5, a = n.bury ?? .35, s = n.meshSize ?? 1, c = n.colors ?? [[
259
+ .36,
260
+ .2,
261
+ .14,
262
+ 1
263
+ ]], l = n.seed ?? 1, u = t.sizes.length - 1, d = t.columns * t.rows;
264
+ if (!(i >= .1 && i <= 1) || !(a >= 0 && a <= 1) || !(s > 0) || !c.length) throw RangeError("drawSpoil: breakup 0.1 to 1, bury 0 to 1, meshSize above 0 and one colour or more; pass them so.");
265
+ if (!(u >= 1 && t.counts.length === d * u && t.cell > 0)) throw RangeError("drawSpoil: pass a spoil field of counts per cell and bin (ejectaSpoil of @margoengine/physics/crater).");
266
+ let f = 1 / (i * i * i), p = new Float64Array(u);
267
+ for (let e = 0; e < d; e++) for (let n = 0; n < u; n++) p[n] += t.counts[e * u + n] * f;
268
+ let m = new Float64Array(u), h = Math.floor(.97 * e.capacity), g = Infinity, _ = 0, v = 0;
269
+ for (let e = u - 1; e >= 0; e--) _ += p[e], m[e] = h <= 0 ? 0 : Math.min(1, h / Math.max(p[e], 1e-12)), h -= p[e] * m[e], v += p[e] * m[e], m[e] > 0 && (g = Math.min(g, i * t.sizes[e]));
270
+ let y = /* @__PURE__ */ new Float32Array(16), b = 0;
271
+ for (let n = 0; n < d && b < e.capacity; n++) {
272
+ let d = n % t.columns, p = (n - d) / t.columns;
273
+ for (let h = u - 1; h >= 0 && b < e.capacity; h--) {
274
+ let g = t.counts[n * u + h] * f * m[h];
275
+ if (!(g > 0)) continue;
276
+ let _ = Math.imul(n, 64) + h ^ Math.imul(l, 2654435769), v = Math.min(e.capacity - b, Math.floor(g + o(_)));
277
+ for (let n = 0; n < v; n++) {
278
+ let l = Math.imul(_, 2246822507) + n, u = t.origin[0] + (d + o(l * 5 + 1)) * t.cell, f = t.origin[1] + (p + o(l * 5 + 2)) * t.cell, m = t.sizes[h], g = i * m * (t.sizes[h + 1] / m) ** o(l * 5 + 3), v = 2 * Math.PI * o(l * 5 + 4), x = g / s, S = Math.cos(v), C = Math.sin(v);
279
+ y.fill(0), y[0] = x * S, y[2] = -x * C, y[5] = x, y[8] = x * C, y[10] = x * S, y[12] = u, y[13] = r(u, f) - a * g, y[14] = f, y[15] = 1, e.setMatrixAt(b, y), e.setColorAt?.(b, c[b % c.length]), b++;
280
+ }
281
+ }
282
+ }
283
+ return e.count = b, {
284
+ drawn: b,
285
+ smallest: Number.isFinite(g) ? g : 0,
286
+ share: _ > 0 ? v / _ : 1
287
+ };
288
+ }
257
289
  //#endregion
258
- export { c as Debris };
290
+ export { c as Debris, l as drawSpoil };
@@ -0,0 +1,66 @@
1
+ /** The current to draw: its grid and, at a point, its depth (m) and its dust's optical depth; and the ground's height. */
2
+ export interface DustCurrentSource {
3
+ /** The grid: cells across X and Z, its size, m, and its centre [x, z]. */
4
+ readonly shape: {
5
+ readonly columns: number;
6
+ readonly rows: number;
7
+ readonly width: number;
8
+ readonly depth: number;
9
+ readonly centre: readonly [number, number];
10
+ };
11
+ /** The current at (x, z), m: its depth, m, and its dust's optical depth (1.5 a h / r for grains of radius r). */
12
+ sample(x: number, z: number, out: {
13
+ depth: number;
14
+ opacity: number;
15
+ }): {
16
+ depth: number;
17
+ opacity: number;
18
+ };
19
+ /** The ground's height at (x, z), m. */
20
+ ground(x: number, z: number): number;
21
+ }
22
+ /** What `DustCurrent.draw` draws into: a `Clouds` of `@margoengine/vfx/clouds` fits. */
23
+ export interface DustCurrentTarget {
24
+ add(options: object): {
25
+ readonly options: object;
26
+ readonly matrix: Float32Array;
27
+ };
28
+ remove(cloud: object): boolean;
29
+ }
30
+ /** Options of {@link DustCurrent}. Every field has a documented default; the constructor checks the ranges. */
31
+ export interface DustCurrentOptions {
32
+ /** Cells a puff covers along each axis (default 2): fewer puffs for a fine grid. A whole number from 1 to 64. */
33
+ readonly stride?: number;
34
+ /** The least optical depth a patch needs to be drawn, as the share of light it stops (default 0.1: about a tenth). From 0 to 10. */
35
+ readonly least?: number;
36
+ /** At most this many puffs (default 1024); a patch past it widens the stride. A whole number from 1 to 65,536. */
37
+ readonly most?: number;
38
+ /** The dust's colour, linear RGB (default [0.36, 0.3, 0.23], dry earth, as `Debris`'s dust). */
39
+ readonly color?: readonly [number, number, number];
40
+ /** The puffs' layout seed (default 1). */
41
+ readonly seed?: number;
42
+ }
43
+ /** One puff as `DustCurrent` lays it: its centre, m, its width, m, and the share of light its patch stops. */
44
+ export interface DustCurrentPuff {
45
+ readonly centre: readonly [number, number, number];
46
+ readonly size: number;
47
+ readonly visibility: number;
48
+ }
49
+ /** Draws a dusty current on the ground into a `Clouds` as puffs, one a visible patch, with its visibility as its size. */
50
+ export declare class DustCurrent {
51
+ readonly source: DustCurrentSource;
52
+ private readonly stride;
53
+ private readonly least;
54
+ private readonly most;
55
+ private readonly color;
56
+ private readonly seed;
57
+ private cloud;
58
+ private target;
59
+ constructor(source: DustCurrentSource, options?: DustCurrentOptions);
60
+ /** The puffs the current makes now: one for each visible patch of `stride` by `stride` cells, at most `most`. */
61
+ puffs(): DustCurrentPuff[];
62
+ /** Puts the current's puffs into `clouds` (one cloud, replaced each draw); none when nothing is visible. */
63
+ draw(clouds: DustCurrentTarget): void;
64
+ /** Takes the cloud {@link draw} added out of its `Clouds`. */
65
+ clear(): void;
66
+ }
@@ -0,0 +1,92 @@
1
+ //#region src/dust-current.ts
2
+ function e(e, t, n, r, i = !1) {
3
+ if (!(e >= n && e <= r) || i && !Number.isInteger(e)) throw RangeError(`DustCurrent ${t} is ${e}; pass ${i ? "a whole number" : "a number"} from ${n} to ${r}.`);
4
+ return e;
5
+ }
6
+ var t = class {
7
+ constructor(t, n = {}) {
8
+ if (this.source = t, this.cloud = null, this.target = null, !t?.shape || typeof t.sample != "function" || typeof t.ground != "function") throw TypeError("DustCurrent needs a source with its grid `shape`, `sample(x, z, out)` and `ground(x, z)`.");
9
+ this.stride = e(n.stride ?? 2, "stride", 1, 64, !0), this.least = e(n.least ?? .1, "least optical depth", 0, 10), this.most = e(n.most ?? 1024, "most puffs", 1, 65536, !0);
10
+ let r = n.color ?? [
11
+ .36,
12
+ .3,
13
+ .23
14
+ ];
15
+ if (!(r.length === 3 && r.every((e) => e >= 0 && Number.isFinite(e)))) throw RangeError("DustCurrent color is three linear values of 0 or more; pass [r, g, b].");
16
+ this.color = [
17
+ r[0],
18
+ r[1],
19
+ r[2]
20
+ ], this.seed = e(n.seed ?? 1, "seed", 0, 2 ** 31, !0);
21
+ }
22
+ puffs() {
23
+ let { columns: e, rows: t, width: n, depth: r, centre: i } = this.source.shape, a = n / e, o = r / t, s = {
24
+ depth: 0,
25
+ opacity: 0
26
+ };
27
+ for (let c = this.stride;; c *= 2) {
28
+ let l = [];
29
+ for (let u = 0; u < e; u += c) for (let d = 0; d < t; d += c) {
30
+ let f = 0, p = 0, m = 0;
31
+ for (let l = u; l < Math.min(e, u + c); l++) for (let e = d; e < Math.min(t, d + c); e++) {
32
+ let t = i[0] - n / 2 + (l + .5) * a, c = i[1] - r / 2 + (e + .5) * o;
33
+ this.source.sample(t, c, s), f = Math.max(f, s.depth), p += Math.exp(-Math.max(s.opacity, 0)), m++;
34
+ }
35
+ let h = 1 - p / m;
36
+ if (!(h >= 1 - Math.exp(-this.least)) || !(f > 0)) continue;
37
+ let g = Math.min(c, e - u) * a, _ = i[0] - n / 2 + (u + Math.min(c, e - u) / 2) * a, v = i[1] - r / 2 + (d + Math.min(c, t - d) / 2) * o;
38
+ l.push({
39
+ centre: [
40
+ _,
41
+ this.source.ground(_, v) + f / 2,
42
+ v
43
+ ],
44
+ size: Math.max(g, f),
45
+ visibility: h
46
+ });
47
+ }
48
+ if (l.length <= this.most || c >= Math.max(e, t)) return l.slice(0, this.most);
49
+ }
50
+ }
51
+ draw(e) {
52
+ this.target && this.target !== e && this.clear(), this.target = e;
53
+ let t = this.puffs();
54
+ if (!t.length) {
55
+ this.clear();
56
+ return;
57
+ }
58
+ let n = Infinity, r = Infinity, i = Infinity, a = -Infinity, o = -Infinity, s = -Infinity, c = 0, l = 0;
59
+ for (let e of t) n = Math.min(n, e.centre[0]), a = Math.max(a, e.centre[0]), r = Math.min(r, e.centre[1]), o = Math.max(o, e.centre[1]), i = Math.min(i, e.centre[2]), s = Math.max(s, e.centre[2]), c = Math.max(c, e.size), l += e.visibility;
60
+ let u = .5 * (n + a), d = .5 * (r + o), f = .5 * (i + s), p = [
61
+ Math.max(a - n, .001),
62
+ Math.max(o - r, .001),
63
+ Math.max(s - i, .001)
64
+ ], m = {
65
+ seed: this.seed,
66
+ segments: t.length,
67
+ bounds: p,
68
+ volume: c,
69
+ color: [...this.color],
70
+ opacity: Math.min(1, l / t.length),
71
+ distribute: (e) => {
72
+ let n = t[e];
73
+ return {
74
+ point: [
75
+ (n.centre[0] - u) * 2 / p[0],
76
+ (n.centre[1] - d) * 2 / p[1],
77
+ (n.centre[2] - f) * 2 / p[2]
78
+ ],
79
+ volume: n.size / c * (.4 + .6 * n.visibility)
80
+ };
81
+ }
82
+ };
83
+ this.cloud ? Object.assign(this.cloud.options, m) : this.cloud = e.add(m);
84
+ let h = this.cloud.matrix;
85
+ h.fill(0), h[0] = h[5] = h[10] = h[15] = 1, h[12] = u, h[13] = d, h[14] = f;
86
+ }
87
+ clear() {
88
+ this.cloud && this.target?.remove(this.cloud), this.cloud = null;
89
+ }
90
+ };
91
+ //#endregion
92
+ export { t as DustCurrent };