ugly-game 0.8.1 → 0.10.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.
@@ -30,18 +30,26 @@ export declare const CUBE: {
30
30
  export declare class GpuShadowRenderer {
31
31
  private device;
32
32
  private instBuf;
33
+ private sceneReady;
33
34
  private camBuf;
34
35
  private shadowTex;
35
36
  private shadowView;
37
+ private shadowArrayView;
38
+ private shadowLayerViews;
39
+ private shadowCamBufs;
36
40
  private shadowPipe;
37
41
  private mainPipe;
38
- private shadowBG;
42
+ private shadowBGs;
39
43
  private mainBG;
40
44
  private shadowBGL;
41
45
  private mainBGL;
42
46
  private shadowSampler;
43
47
  private count;
44
48
  private cam;
49
+ private shadowCam;
50
+ private cascades;
51
+ /** Width of the blend into the next cascade, in uv (0 = hard switch). Small: it costs a 2nd PCF. */
52
+ cascadeBand: number;
45
53
  private atlasView;
46
54
  private atlasSampler;
47
55
  private tileRectBuf;
@@ -85,6 +93,11 @@ export declare class GpuShadowRenderer {
85
93
  private makeCullBuf;
86
94
  private cullBG;
87
95
  private makeCullResources;
96
+ /** (Re)allocate the shadow array + per-cascade uniforms for `n` cascades. Idempotent per count. */
97
+ private ensureCascades;
98
+ /** Allocate the shadow array + per-cascade uniforms. Split from ensureCascades so makeBindGroups
99
+ * can guarantee resources exist without recursing back into it. */
100
+ private allocCascades;
88
101
  /** (Re)create the coarse Hi-Z for a `w×h` depth target and rebind the cull groups to it. Idempotent per size. */
89
102
  private ensureHiZ;
90
103
  private scratch;
@@ -116,14 +129,26 @@ export declare class GpuShadowRenderer {
116
129
  private writeCull;
117
130
  /** The sun shadow-map depth view + its comparison sampler + texel size. Feed these into GpuPropsRenderer/
118
131
  * GpuSkinRenderer.frame(lightVP, …) so mesh props & creatures RECEIVE the same sun shadow the cubes sample.
119
- * Stable for the renderer's lifetime (recreated only on construction). */
132
+ *
133
+ * CASCADES: this is a plain 2d view of layer 0 — the TIGHTEST cascade. Props and skinned meshes
134
+ * sample a `texture_depth_2d`, so handing them the array would be a breaking change to two more
135
+ * shaders; layer 0 is what they already effectively received when there was one map, so they are
136
+ * unaffected. The consequence is that a distant prop receives no shadow even when the terrain
137
+ * around it does. Making those two cascade-aware is the follow-up.
138
+ *
139
+ * NOTE: recreated when the cascade COUNT changes, so re-read it after a frame that changes it
140
+ * rather than caching the view across such a change. */
120
141
  get shadowMapView(): GPUTextureView;
142
+ /** The full cascade array view, for a consumer that samples `texture_depth_2d_array`. */
143
+ get shadowMapArrayView(): GPUTextureView;
144
+ /** How many cascade layers are currently allocated. */
145
+ get cascadeCount(): number;
121
146
  get shadowMapSampler(): GPUSampler;
122
147
  get shadowMapSize(): number;
123
148
  /** camVP/lightVP: column-major Float32Array(16). sunDir: travel direction. Pass `occlusion` (the depth target +
124
149
  * its size) to enable Hi-Z occlusion culling on the camera pass — the renderer rebuilds a coarse Hi-Z from that
125
150
  * depth each frame and the NEXT frame's cull uses it (hole-free: the first frame + any resize skip occlusion). */
126
- frame(enc: GPUCommandEncoder, colorView: GPUTextureView, sceneDepth: GPUTextureView, camVP: Float32Array, lightVP: Float32Array, sunDir: [number, number, number], sunCol: [number, number, number], ambient: number, load?: boolean, occlusion?: {
151
+ frame(enc: GPUCommandEncoder, colorView: GPUTextureView, sceneDepth: GPUTextureView, camVP: Float32Array, lightVP: Float32Array | Float32Array[], sunDir: [number, number, number], sunCol: [number, number, number], ambient: number, load?: boolean, occlusion?: {
127
152
  depth: GPUTextureView;
128
153
  w: number;
129
154
  h: number;
package/dist/gpuShadow.js CHANGED
@@ -13,6 +13,15 @@
13
13
  * place ghost, destroy marker, projectiles, and sparkles so effect cubes read as distinct from terrain). */
14
14
  import { frustumPlanes } from './mat4';
15
15
  const SHADOW_SIZE = 2048;
16
+ // CASCADED SHADOW MAPS. One ortho map has to choose between resolution and reach: AMS ran a single
17
+ // 90-block box against a 280-block draw distance, so everything past it was simply unshadowed and
18
+ // the far terrain read flat. Cascades split the range into nested boxes — tight and crisp near the
19
+ // camera, loose and far behind it — each rendered into its own layer of a depth-2d-array.
20
+ //
21
+ // A caller passing ONE matrix gets exactly the old behaviour, byte for byte: one layer, one cull,
22
+ // one sample, and the selection loop terminates immediately. That keeps the five demo pages and
23
+ // AMS's existing props/doors/skin path unmoved until each opts in.
24
+ const MAX_CASCADES = 4;
16
25
  const CULL_WG = 64; // compute-cull workgroup size
17
26
  const INST_F = 16; // floats per instance: pos.xyz+hue, scl.xyz+emissive, rot quat, aux (tile,up,_,_)
18
27
  const OVERLAY_CAP = 512; // max translucent overlay cubes per frame (the place ghost + headroom)
@@ -53,12 +62,13 @@ export const CUBE = buildCube();
53
62
  const COMMON_WGSL = /* wgsl */ `
54
63
  struct Cam {
55
64
  camVP: mat4x4<f32>,
56
- lightVP: mat4x4<f32>,
65
+ lightVP: array<mat4x4<f32>, ${MAX_CASCADES}>, // CASCADES, tightest first. A 1-cascade caller uses only [0].
57
66
  sun: vec4<f32>, // xyz = direction light travels, w = ambient
58
67
  sunCol: vec4<f32>, // xyz = sun colour, w = shadow map size (texels)
59
68
  tint: vec4<f32>, // rgb = per-planet tint · w = tint strength (0 = none)
60
69
  atlas: vec4<f32>, // x = useAtlas (1/0)
61
- up: vec4<f32>, // xyz = local gravity up (for hemisphere face-shading readability); w unused
70
+ up: vec4<f32>, // xyz = local gravity up (for hemisphere face-shading readability); w = linear-HDR flag
71
+ csm: vec4<f32>, // x = active cascade count · y = crossfade band in uv units
62
72
  };
63
73
  struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32> }; // pos.w = hue (<0 ⇒ ground) · scl.w = emissive/alpha · rot = quaternion · aux.x = atlas tile (<0 ⇒ hue) · aux.y = up-face code
64
74
  @group(0) @binding(0) var<uniform> cam: Cam;
@@ -196,13 +206,15 @@ const HIZ_DOWN = 8; // source pixels per Hi-Z texel (coarse ⇒ conservative, ch
196
206
  const SHADOW_WGSL = COMMON_WGSL +
197
207
  /* wgsl */ `
198
208
  @group(0) @binding(2) var<storage, read> vis: array<u32>;
209
+ // Always index [0]: each cascade's shadow pass binds its OWN Cam buffer whose lightVP[0] holds that
210
+ // cascade's matrix. One uniform per cascade costs a few hundred bytes and avoids dynamic offsets.
199
211
  @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> @builtin(position) vec4<f32> {
200
- return cam.lightVP * vec4(worldOf(insts[vis[ii]], vi), 1.0);
212
+ return cam.lightVP[0] * vec4(worldOf(insts[vis[ii]], vi), 1.0);
201
213
  }
202
214
  `;
203
215
  const MAIN_WGSL = COMMON_WGSL +
204
216
  /* wgsl */ `
205
- @group(0) @binding(2) var shadowMap: texture_depth_2d;
217
+ @group(0) @binding(2) var shadowMap: texture_depth_2d_array;
206
218
  @group(0) @binding(3) var shadowSamp: sampler_comparison;
207
219
  @group(0) @binding(4) var<storage, read> vis: array<u32>;
208
220
  @group(0) @binding(5) var atlasTex: texture_2d<f32>;
@@ -236,23 +248,56 @@ fn faceVec(code: f32) -> vec3<f32> {
236
248
  return o;
237
249
  }
238
250
 
239
- // PCF 3×3 sun shadow. Returns 1 = fully lit, 0 = fully shadowed.
240
- fn shadowFactor(world: vec3<f32>, ndl: f32) -> f32 {
241
- let lp = cam.lightVP * vec4(world, 1.0);
251
+ // PCF 3x3 against ONE cascade layer. Returns 1 = fully lit, 0 = fully shadowed; the 'inside' out-param
252
+ // reports whether the point actually fell in this cascade's box, so the caller can try the next one.
253
+ fn pcfLayer(world: vec3<f32>, ndl: f32, layer: i32, inside: ptr<function, bool>, edge: ptr<function, f32>) -> f32 {
254
+ let lp = cam.lightVP[layer] * vec4(world, 1.0);
242
255
  let proj = lp.xyz / lp.w;
243
256
  let uv = proj.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);
244
- if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z > 1.0 || proj.z < 0.0) { return 1.0; }
245
- let bias = max(0.0006 * (1.0 - ndl), 0.0004); // slope-scaled, kills acne on grazing faces
257
+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z > 1.0 || proj.z < 0.0) {
258
+ *inside = false; *edge = 0.0; return 1.0;
259
+ }
260
+ *inside = true;
261
+ // How close to this cascade's border we are, 0 at the middle and 1 at the rim — drives the blend
262
+ // into the next cascade so the resolution change is a gradient rather than a visible seam.
263
+ let m = max(max(abs(uv.x - 0.5), abs(uv.y - 0.5)) * 2.0, abs(proj.z * 2.0 - 1.0));
264
+ *edge = clamp((m - (1.0 - cam.csm.y)) / max(cam.csm.y, 1e-5), 0.0, 1.0);
265
+ // Bias scales with the cascade's world extent: a far cascade covers far more world per texel, so
266
+ // the depth slope across one texel is larger and a near-cascade bias would let acne back in.
267
+ let scale = 1.0 + f32(layer) * 1.5;
268
+ let bias = max(0.0006 * (1.0 - ndl), 0.0004) * scale;
246
269
  let texel = 1.0 / cam.sunCol.w;
247
270
  var s = 0.0;
248
271
  for (var dy = -1; dy <= 1; dy = dy + 1) {
249
272
  for (var dx = -1; dx <= 1; dx = dx + 1) {
250
- s = s + textureSampleCompareLevel(shadowMap, shadowSamp, uv + vec2(f32(dx), f32(dy)) * texel, proj.z - bias);
273
+ s = s + textureSampleCompareLevel(shadowMap, shadowSamp, uv + vec2(f32(dx), f32(dy)) * texel, layer, proj.z - bias);
251
274
  }
252
275
  }
253
276
  return s / 9.0;
254
277
  }
255
278
 
279
+ // Walk the cascades tightest-first and use the first that contains the point. Selection by
280
+ // CONTAINMENT rather than by view depth means no split distances have to be shipped to the shader
281
+ // and kept in sync with the matrices — the boxes themselves are the authority.
282
+ fn shadowFactor(world: vec3<f32>, ndl: f32) -> f32 {
283
+ let n = i32(cam.csm.x);
284
+ var inside = false; var edge = 0.0;
285
+ for (var c = 0; c < n; c = c + 1) {
286
+ let f = pcfLayer(world, ndl, c, &inside, &edge);
287
+ if (inside) {
288
+ // Near this cascade's rim, cross-fade into the next one (if there is a next one) so the
289
+ // resolution step never draws a hard line across the ground.
290
+ if (edge > 0.0 && c + 1 < n) {
291
+ var i2 = false; var e2 = 0.0;
292
+ let g = pcfLayer(world, ndl, c + 1, &i2, &e2);
293
+ if (i2) { return mix(f, g, edge); }
294
+ }
295
+ return f;
296
+ }
297
+ }
298
+ return 1.0; // beyond every cascade → unshadowed, same as the old single-map out-of-range case
299
+ }
300
+
256
301
  // Per-block edge darkening (baked AO) — mirrors shared/voxelShade.ts blockShade so a flat face shows its
257
302
  // individual voxels instead of reading as one uniform slab. fx,fz ∈ [0,1) within the block face.
258
303
  fn blockShade(fx: f32, fz: f32) -> f32 {
@@ -335,18 +380,27 @@ struct AOut { @builtin(position) clip: vec4<f32>, @location(0) hue: f32, @locati
335
380
  export class GpuShadowRenderer {
336
381
  device;
337
382
  instBuf;
383
+ sceneReady = false; // instBuf exists — setScene/setCapacity has run at least once
338
384
  camBuf;
339
- shadowTex;
340
- shadowView;
385
+ shadowTex = null; // null until the first frame picks a cascade count
386
+ shadowView; // layer-0 2d view — the back-compat getter for props/skin
387
+ shadowArrayView; // the 2d-array view the main pass samples
388
+ shadowLayerViews = []; // one render-attachment view per cascade
389
+ shadowCamBufs = [];
341
390
  shadowPipe;
342
391
  mainPipe;
343
- shadowBG;
392
+ shadowBGs = [];
344
393
  mainBG;
345
394
  shadowBGL;
346
395
  mainBGL;
347
396
  shadowSampler;
348
397
  count = 0;
349
- cam = new Float32Array(52); // 2×mat4 + sun + sunCol + tint + atlas + up
398
+ // camVP(16) + lightVP[MAX_CASCADES](16 each) + sun + sunCol + tint + atlas + up + csm
399
+ cam = new Float32Array(16 + MAX_CASCADES * 16 + 6 * 4);
400
+ shadowCam = new Float32Array(16 + MAX_CASCADES * 16 + 6 * 4); // scratch for a per-cascade copy
401
+ cascades = 0; // layers currently allocated; 0 until the first frame sizes it
402
+ /** Width of the blend into the next cascade, in uv (0 = hard switch). Small: it costs a 2nd PCF. */
403
+ cascadeBand = 0.12;
350
404
  atlasView;
351
405
  atlasSampler;
352
406
  tileRectBuf;
@@ -367,10 +421,10 @@ export class GpuShadowRenderer {
367
421
  camVis;
368
422
  camCull;
369
423
  camCullBG;
370
- lightArgs;
371
- lightVis;
372
- lightCull;
373
- lightCullBG;
424
+ lightArgs = [];
425
+ lightVis = [];
426
+ lightCull = [];
427
+ lightCullBG = [];
374
428
  statsBuf; // readback: [camVisible, lightVisible] for the IR/tests
375
429
  /** Last frame's visible counts (main-pass camera cull, shadow-pass light cull) + total — for IR/telemetry. */
376
430
  lastCull = { total: 0, camVisible: 0, lightVisible: 0 };
@@ -390,12 +444,6 @@ export class GpuShadowRenderer {
390
444
  size: this.cam.byteLength,
391
445
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
392
446
  });
393
- this.shadowTex = device.createTexture({
394
- size: [SHADOW_SIZE, SHADOW_SIZE],
395
- format: 'depth32float',
396
- usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
397
- });
398
- this.shadowView = this.shadowTex.createView();
399
447
  const shadowMod = device.createShaderModule({ code: SHADOW_WGSL });
400
448
  const mainMod = device.createShaderModule({ code: MAIN_WGSL });
401
449
  const shadowBGL = device.createBindGroupLayout({
@@ -442,7 +490,7 @@ export class GpuShadowRenderer {
442
490
  {
443
491
  binding: 2,
444
492
  visibility: GPUShaderStage.FRAGMENT,
445
- texture: { sampleType: 'depth' },
493
+ texture: { sampleType: 'depth', viewDimension: '2d-array' }, // cascades live in array layers
446
494
  },
447
495
  {
448
496
  binding: 3,
@@ -669,17 +717,65 @@ export class GpuShadowRenderer {
669
717
  this.camArgs = cam.args;
670
718
  this.camVis = cam.vis;
671
719
  this.camCull = cam.cull;
672
- const lit = this.makeCullBuf();
673
- this.lightArgs = lit.args;
674
- this.lightVis = lit.vis;
675
- this.lightCull = lit.cull;
720
+ // One light frustum per cascade: each box culls independently, so a far cascade still draws the
721
+ // distant occluders a tight near box would have thrown away.
722
+ const n = Math.max(1, this.cascades);
723
+ this.lightArgs = [];
724
+ this.lightVis = [];
725
+ this.lightCull = [];
726
+ for (let i = 0; i < n; i++) {
727
+ const lit = this.makeCullBuf();
728
+ this.lightArgs.push(lit.args);
729
+ this.lightVis.push(lit.vis);
730
+ this.lightCull.push(lit.cull);
731
+ }
676
732
  this.camCullBG = this.cullBG(this.camArgs, this.camVis, this.camCull);
677
- this.lightCullBG = this.cullBG(this.lightArgs, this.lightVis, this.lightCull);
733
+ this.lightCullBG = this.lightArgs.map((a, i) => this.cullBG(a, this.lightVis[i], this.lightCull[i]));
678
734
  this.statsBuf = this.device.createBuffer({
679
735
  size: 4 * 4 * 2,
680
736
  usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
681
737
  });
682
738
  }
739
+ /** (Re)allocate the shadow array + per-cascade uniforms for `n` cascades. Idempotent per count. */
740
+ ensureCascades(n) {
741
+ if (this.cascades === n && this.shadowTex)
742
+ return;
743
+ this.allocCascades(n);
744
+ // setScene may not have run yet (no instance buffer to bind), in which case makeBindGroups will
745
+ // pick these up when it does.
746
+ if (this.sceneReady)
747
+ this.makeBindGroups();
748
+ }
749
+ /** Allocate the shadow array + per-cascade uniforms. Split from ensureCascades so makeBindGroups
750
+ * can guarantee resources exist without recursing back into it. */
751
+ allocCascades(n) {
752
+ this.shadowTex?.destroy();
753
+ for (const b of this.shadowCamBufs)
754
+ b.destroy();
755
+ this.cascades = n;
756
+ this.shadowTex = this.device.createTexture({
757
+ size: [SHADOW_SIZE, SHADOW_SIZE, n],
758
+ format: 'depth32float',
759
+ dimension: '2d',
760
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
761
+ });
762
+ this.shadowArrayView = this.shadowTex.createView({ dimension: '2d-array' });
763
+ this.shadowLayerViews = [];
764
+ for (let i = 0; i < n; i++)
765
+ this.shadowLayerViews.push(this.shadowTex.createView({
766
+ dimension: '2d',
767
+ baseArrayLayer: i,
768
+ arrayLayerCount: 1,
769
+ }));
770
+ // Layer 0 is the tightest cascade — the one a caller that only understands a single map wants.
771
+ this.shadowView = this.shadowLayerViews[0];
772
+ this.shadowCamBufs = [];
773
+ for (let i = 0; i < n; i++)
774
+ this.shadowCamBufs.push(this.device.createBuffer({
775
+ size: this.cam.byteLength,
776
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
777
+ }));
778
+ }
683
779
  /** (Re)create the coarse Hi-Z for a `w×h` depth target and rebind the cull groups to it. Idempotent per size. */
684
780
  ensureHiZ(w, h) {
685
781
  const hw = Math.max(1, Math.ceil(w / HIZ_DOWN)), hh = Math.max(1, Math.ceil(h / HIZ_DOWN));
@@ -696,7 +792,7 @@ export class GpuShadowRenderer {
696
792
  this.hizView = this.hizTex.createView();
697
793
  this.occView = this.hizView; // the cull now samples the real Hi-Z
698
794
  this.camCullBG = this.cullBG(this.camArgs, this.camVis, this.camCull);
699
- this.lightCullBG = this.cullBG(this.lightArgs, this.lightVis, this.lightCull);
795
+ this.lightCullBG = this.lightArgs.map((a, i) => this.cullBG(a, this.lightVis[i], this.lightCull[i]));
700
796
  }
701
797
  scratch = new Float32Array(0);
702
798
  fill(scratch, instances, n) {
@@ -721,21 +817,25 @@ export class GpuShadowRenderer {
721
817
  }
722
818
  }
723
819
  makeBindGroups() {
820
+ // A caller can setScene before the first frame has said how many cascades it wants; default to
821
+ // one, which is the old single-map behaviour, and frame() will re-allocate if it asks for more.
822
+ if (!this.shadowTex)
823
+ this.allocCascades(1);
724
824
  this.makeCullResources(); // (re)create the cull buffers against the fresh instBuf/cap first — the draw passes bind their visible lists
725
- this.shadowBG = this.device.createBindGroup({
825
+ this.shadowBGs = this.lightVis.map((vis, i) => this.device.createBindGroup({
726
826
  layout: this.shadowBGL,
727
827
  entries: [
728
- { binding: 0, resource: { buffer: this.camBuf } },
828
+ { binding: 0, resource: { buffer: this.shadowCamBufs[i] } },
729
829
  { binding: 1, resource: { buffer: this.instBuf } },
730
- { binding: 2, resource: { buffer: this.lightVis } },
830
+ { binding: 2, resource: { buffer: vis } },
731
831
  ],
732
- });
832
+ }));
733
833
  this.mainBG = this.device.createBindGroup({
734
834
  layout: this.mainBGL,
735
835
  entries: [
736
836
  { binding: 0, resource: { buffer: this.camBuf } },
737
837
  { binding: 1, resource: { buffer: this.instBuf } },
738
- { binding: 2, resource: this.shadowView },
838
+ { binding: 2, resource: this.shadowArrayView },
739
839
  { binding: 3, resource: this.shadowSampler },
740
840
  { binding: 4, resource: { buffer: this.camVis } },
741
841
  { binding: 5, resource: this.atlasView },
@@ -781,6 +881,7 @@ export class GpuShadowRenderer {
781
881
  this.cap = this.count;
782
882
  this.scratch = new Float32Array(this.count * INST_F);
783
883
  this.fill(this.scratch, instances, this.count);
884
+ this.sceneReady = true;
784
885
  this.instBuf = this.device.createBuffer({
785
886
  size: this.scratch.byteLength,
786
887
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
@@ -792,6 +893,7 @@ export class GpuShadowRenderer {
792
893
  setCapacity(cap) {
793
894
  this.cap = cap;
794
895
  this.scratch = new Float32Array(cap * INST_F);
896
+ this.sceneReady = true;
795
897
  this.instBuf = this.device.createBuffer({
796
898
  size: this.scratch.byteLength,
797
899
  usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
@@ -886,10 +988,26 @@ export class GpuShadowRenderer {
886
988
  }
887
989
  /** The sun shadow-map depth view + its comparison sampler + texel size. Feed these into GpuPropsRenderer/
888
990
  * GpuSkinRenderer.frame(lightVP, …) so mesh props & creatures RECEIVE the same sun shadow the cubes sample.
889
- * Stable for the renderer's lifetime (recreated only on construction). */
991
+ *
992
+ * CASCADES: this is a plain 2d view of layer 0 — the TIGHTEST cascade. Props and skinned meshes
993
+ * sample a `texture_depth_2d`, so handing them the array would be a breaking change to two more
994
+ * shaders; layer 0 is what they already effectively received when there was one map, so they are
995
+ * unaffected. The consequence is that a distant prop receives no shadow even when the terrain
996
+ * around it does. Making those two cascade-aware is the follow-up.
997
+ *
998
+ * NOTE: recreated when the cascade COUNT changes, so re-read it after a frame that changes it
999
+ * rather than caching the view across such a change. */
890
1000
  get shadowMapView() {
891
1001
  return this.shadowView;
892
1002
  }
1003
+ /** The full cascade array view, for a consumer that samples `texture_depth_2d_array`. */
1004
+ get shadowMapArrayView() {
1005
+ return this.shadowArrayView;
1006
+ }
1007
+ /** How many cascade layers are currently allocated. */
1008
+ get cascadeCount() {
1009
+ return this.cascades;
1010
+ }
893
1011
  get shadowMapSampler() {
894
1012
  return this.shadowSampler;
895
1013
  }
@@ -900,26 +1018,41 @@ export class GpuShadowRenderer {
900
1018
  * its size) to enable Hi-Z occlusion culling on the camera pass — the renderer rebuilds a coarse Hi-Z from that
901
1019
  * depth each frame and the NEXT frame's cull uses it (hole-free: the first frame + any resize skip occlusion). */
902
1020
  frame(enc, colorView, sceneDepth, camVP, lightVP, sunDir, sunCol, ambient, load = false, occlusion, tint = [1, 1, 1, 0], extraShadow, up = [0, 1, 0], linearOut = false) {
1021
+ // One matrix or many — a single Float32Array is the 1-cascade case and stays byte-identical.
1022
+ const mats = Array.isArray(lightVP) ? lightVP : [lightVP];
1023
+ const nc = Math.max(1, Math.min(MAX_CASCADES, mats.length));
1024
+ this.ensureCascades(nc);
1025
+ const L = 16; // lightVP[0] starts here
1026
+ const S = 16 + MAX_CASCADES * 16; // ...and the scalars start after the whole array
903
1027
  this.cam.set(camVP, 0);
904
- this.cam.set(lightVP, 16);
905
- this.cam[32] = sunDir[0];
906
- this.cam[33] = sunDir[1];
907
- this.cam[34] = sunDir[2];
908
- this.cam[35] = ambient;
909
- this.cam[36] = sunCol[0];
910
- this.cam[37] = sunCol[1];
911
- this.cam[38] = sunCol[2];
912
- this.cam[39] = SHADOW_SIZE;
913
- this.cam[40] = tint[0];
914
- this.cam[41] = tint[1];
915
- this.cam[42] = tint[2];
916
- this.cam[43] = tint[3];
917
- this.cam[44] = this.useAtlas;
918
- this.cam[48] = up[0];
919
- this.cam[49] = up[1];
920
- this.cam[50] = up[2];
921
- this.cam[51] = linearOut ? 1 : 0; // up.w = linear-HDR output flag
1028
+ for (let i = 0; i < nc; i++)
1029
+ this.cam.set(mats[i], L + i * 16);
1030
+ this.cam[S + 0] = sunDir[0];
1031
+ this.cam[S + 1] = sunDir[1];
1032
+ this.cam[S + 2] = sunDir[2];
1033
+ this.cam[S + 3] = ambient;
1034
+ this.cam[S + 4] = sunCol[0];
1035
+ this.cam[S + 5] = sunCol[1];
1036
+ this.cam[S + 6] = sunCol[2];
1037
+ this.cam[S + 7] = SHADOW_SIZE;
1038
+ this.cam[S + 8] = tint[0];
1039
+ this.cam[S + 9] = tint[1];
1040
+ this.cam[S + 10] = tint[2];
1041
+ this.cam[S + 11] = tint[3];
1042
+ this.cam[S + 12] = this.useAtlas;
1043
+ this.cam[S + 16] = up[0];
1044
+ this.cam[S + 17] = up[1];
1045
+ this.cam[S + 18] = up[2];
1046
+ this.cam[S + 19] = linearOut ? 1 : 0; // up.w = linear-HDR output flag
1047
+ this.cam[S + 20] = nc; // csm.x = active cascade count
1048
+ this.cam[S + 21] = nc > 1 ? this.cascadeBand : 0; // csm.y = crossfade band (pointless with one box)
922
1049
  this.device.queue.writeBuffer(this.camBuf, 0, this.cam);
1050
+ // Each cascade's shadow pass reads its OWN copy with that cascade's matrix parked at lightVP[0].
1051
+ for (let i = 0; i < nc; i++) {
1052
+ this.shadowCam.set(this.cam);
1053
+ this.shadowCam.set(mats[i], L);
1054
+ this.device.queue.writeBuffer(this.shadowCamBufs[i], 0, this.shadowCam);
1055
+ }
923
1056
  if (occlusion)
924
1057
  this.ensureHiZ(occlusion.w, occlusion.h);
925
1058
  const occludeNow = !!occlusion && this.hizReady; // only once a Hi-Z from a prior frame exists (never on frame 1/resize)
@@ -928,34 +1061,42 @@ export class GpuShadowRenderer {
928
1061
  // compacts its survivors into a visible list + counts them in instanceCount, which the matching drawIndirect consumes.
929
1062
  const resetArgs = new Uint32Array([36, 0, 0, 0]);
930
1063
  this.device.queue.writeBuffer(this.camArgs, 0, resetArgs);
931
- this.device.queue.writeBuffer(this.lightArgs, 0, resetArgs);
1064
+ for (const a of this.lightArgs)
1065
+ this.device.queue.writeBuffer(a, 0, resetArgs);
932
1066
  this.writeCull(this.camCull, camVP, occludeNow);
933
- this.writeCull(this.lightCull, lightVP, false);
1067
+ for (let i = 0; i < nc; i++)
1068
+ this.writeCull(this.lightCull[i], mats[i], false);
934
1069
  if (this.count > 0) {
935
1070
  const cp = enc.beginComputePass();
936
1071
  cp.setPipeline(this.cullPipe);
937
1072
  cp.setBindGroup(0, this.camCullBG);
938
1073
  cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
939
- cp.setBindGroup(0, this.lightCullBG);
940
- cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
1074
+ for (let i = 0; i < nc; i++) {
1075
+ cp.setBindGroup(0, this.lightCullBG[i]);
1076
+ cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
1077
+ }
941
1078
  cp.end();
942
1079
  }
943
- // Pass 1: occluder depth from the sun (light-frustum-culled).
944
- const sp = enc.beginRenderPass({
945
- colorAttachments: [],
946
- depthStencilAttachment: {
947
- view: this.shadowView,
948
- depthClearValue: 1.0,
949
- depthLoadOp: 'clear',
950
- depthStoreOp: 'store',
951
- },
952
- });
953
- sp.setPipeline(this.shadowPipe);
954
- sp.setBindGroup(0, this.shadowBG);
955
- sp.drawIndirect(this.lightArgs, 0);
956
- if (extraShadow)
957
- extraShadow(sp, lightVP); // let the app cast extra occluders (mesh props/trees) into the same sun shadow map
958
- sp.end();
1080
+ // Pass 1: occluder depth from the sun — one pass per cascade, into its own array layer.
1081
+ for (let i = 0; i < nc; i++) {
1082
+ const sp = enc.beginRenderPass({
1083
+ colorAttachments: [],
1084
+ depthStencilAttachment: {
1085
+ view: this.shadowLayerViews[i],
1086
+ depthClearValue: 1.0,
1087
+ depthLoadOp: 'clear',
1088
+ depthStoreOp: 'store',
1089
+ },
1090
+ });
1091
+ sp.setPipeline(this.shadowPipe);
1092
+ sp.setBindGroup(0, this.shadowBGs[i]);
1093
+ sp.drawIndirect(this.lightArgs[i], 0);
1094
+ // The app casts its own occluders (mesh props/trees) into EVERY cascade — an occluder missing
1095
+ // from a far cascade would leave a tree lit at distance while its neighbours are shadowed.
1096
+ if (extraShadow)
1097
+ extraShadow(sp, mats[i]);
1098
+ sp.end();
1099
+ }
959
1100
  // Pass 2: camera, shadow-sampled (camera-frustum + Hi-Z-occlusion-culled).
960
1101
  const mp = enc.beginRenderPass({
961
1102
  colorAttachments: [
@@ -1012,7 +1153,7 @@ export class GpuShadowRenderer {
1012
1153
  async readCullStats() {
1013
1154
  const enc = this.device.createCommandEncoder();
1014
1155
  enc.copyBufferToBuffer(this.camArgs, 0, this.statsBuf, 0, 16); // args[1] = instanceCount (the visible count)
1015
- enc.copyBufferToBuffer(this.lightArgs, 0, this.statsBuf, 16, 16);
1156
+ enc.copyBufferToBuffer(this.lightArgs[0], 0, this.statsBuf, 16, 16);
1016
1157
  this.device.queue.submit([enc.finish()]);
1017
1158
  await this.statsBuf.mapAsync(GPUMapMode.READ);
1018
1159
  const a = new Uint32Array(this.statsBuf.getMappedRange().slice(0));
@@ -0,0 +1,33 @@
1
+ /** Halton(2,3) sub-pixel jitter for frame `i`, in CLIP space. Multiply into the projection. */
2
+ export declare function haltonJitter(i: number, w: number, h: number, samples?: number): [number, number];
3
+ export declare class GpuTaaResolve {
4
+ private device;
5
+ private format;
6
+ private pipe;
7
+ private uBuf;
8
+ private u;
9
+ private samp;
10
+ private hist;
11
+ private histView;
12
+ private bg;
13
+ private ping;
14
+ private w;
15
+ private h;
16
+ private primed;
17
+ constructor(device: GPUDevice, format: GPUTextureFormat);
18
+ /** (Re)allocate history at the render size. Also invalidates history — a resize is a cut. */
19
+ resize(w: number, h: number, colorView: GPUTextureView, depthView: GPUTextureView): void;
20
+ /** Bind group i READS history[i]; the same frame WRITES history[1-i]. */
21
+ private rebind;
22
+ /** Call when the colour/depth VIEWS change identity without a size change. */
23
+ setInputs(colorView: GPUTextureView, depthView: GPUTextureView): void;
24
+ /** Throw the history away — camera cuts, teleports, origin rebases, pause→resume. */
25
+ invalidate(): void;
26
+ /**
27
+ * Resolve one frame. `invCurrVP` inverts the UNJITTERED current view-projection; `prevVP` is the
28
+ * previous frame's UNJITTERED view-projection. Jitter belongs in the geometry pass's projection
29
+ * only — reprojection done with a jittered matrix would chase its own offset.
30
+ */
31
+ frame(enc: GPUCommandEncoder, out: GPUTextureView, invCurrVP: Float32Array, prevVP: Float32Array, blend?: number, enabled?: boolean): void;
32
+ destroy(): void;
33
+ }
@@ -0,0 +1,231 @@
1
+ // PLATFORM PASS. Temporal anti-aliasing as a POST PASS over an existing colour+depth pair, so any
2
+ // renderer in this package can get TAA without becoming a TAA renderer.
3
+ //
4
+ // `GpuTaaRenderer` (gpuTaa.ts) already does TAA, but it is a closed demo renderer: it owns its own
5
+ // cube pipeline, its own scene, and its own MRT colour+motion targets. There is no seam to feed it
6
+ // someone else's frame. This module lifts the part that was general -- the reprojection, the 3x3
7
+ // neighbourhood clamp and the history ping-pong -- and gives it the shape GpuSSAO already has:
8
+ //
9
+ // frame(enc, out, colorView, depthView, invCurrVP, prevVP, blend, reset)
10
+ //
11
+ // MOTION COMES FROM DEPTH, not a motion buffer. GpuSSAO reconstructs normals from depth rather than
12
+ // demanding a normal target; the same trick applies here: unproject each pixel with the current
13
+ // inverse view-projection, reproject it with the previous frame's view-projection, and the
14
+ // difference is the screen-space velocity. That covers the case that dominates a voxel world -- a
15
+ // static world under a moving camera -- and costs the caller nothing but a matrix it already has.
16
+ //
17
+ // The limit, stated plainly: a pixel whose GEOMETRY moved between frames (a walking creature, a
18
+ // flying ship) reprojects as though it were static, so its history is wrong and it ghosts. The 3x3
19
+ // colour-box clamp suppresses most of that -- history is clamped to the range of the current
20
+ // frame's neighbourhood, so it can only ever be a plausible colour for that pixel -- but fast,
21
+ // high-contrast movers will still smear. When that shows up, the fix is per-object motion vectors
22
+ // (an MRT motion target on the geometry pass), and this pass gains a `motionView` input rather than
23
+ // being replaced.
24
+ //
25
+ // Sky pixels sit at depth 1.0. Unprojecting them yields a point on the far plane, which reprojects
26
+ // correctly under camera ROTATION and slightly wrongly under camera TRANSLATION -- the parallax of
27
+ // something infinitely far away is zero, and the far plane is not infinite. At normal draw
28
+ // distances the error is far below a pixel.
29
+ /** Halton(2,3) sub-pixel jitter for frame `i`, in CLIP space. Multiply into the projection. */
30
+ export function haltonJitter(i, w, h, samples = 8) {
31
+ const radical = (n, base) => {
32
+ let f = 1, r = 0;
33
+ while (n > 0) {
34
+ f /= base;
35
+ r += f * (n % base);
36
+ n = Math.floor(n / base);
37
+ }
38
+ return r;
39
+ };
40
+ const k = (i % samples) + 1;
41
+ // Halton is in [0,1); centre it on the pixel, then convert pixels -> clip (clip spans 2 units).
42
+ return [((radical(k, 2) - 0.5) * 2) / w, ((radical(k, 3) - 0.5) * 2) / h];
43
+ }
44
+ const RESOLVE_WGSL = /* wgsl */ `
45
+ struct RU {
46
+ invCurrVP: mat4x4<f32>,
47
+ prevVP: mat4x4<f32>,
48
+ texel: vec4<f32>, // xy = 1/size, zw = size
49
+ ctrl: vec4<f32>, // x = history blend, y = enabled, z = reset
50
+ };
51
+ @group(0) @binding(0) var<uniform> ru: RU;
52
+ @group(0) @binding(1) var histSamp: sampler;
53
+ @group(0) @binding(2) var colorTex: texture_2d<f32>;
54
+ @group(0) @binding(3) var depthTex: texture_depth_2d;
55
+ @group(0) @binding(4) var histTex: texture_2d<f32>;
56
+
57
+ @vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
58
+ var p = array<vec2<f32>, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));
59
+ return vec4(p[vi], 0.0, 1.0);
60
+ }
61
+
62
+ struct ROut { @location(0) screen: vec4<f32>, @location(1) hist: vec4<f32> };
63
+
64
+ @fragment fn fs(@builtin(position) fc: vec4<f32>) -> ROut {
65
+ let dim = vec2<i32>(i32(ru.texel.z), i32(ru.texel.w));
66
+ let px = clamp(vec2<i32>(floor(fc.xy)), vec2<i32>(0, 0), dim - vec2<i32>(1, 1));
67
+ let cur = textureLoad(colorTex, px, 0).rgb;
68
+ var o: ROut;
69
+ // Disabled, or the first frame after a cut: the current frame IS the answer and the history.
70
+ if (ru.ctrl.y < 0.5 || ru.ctrl.z > 0.5) { o.screen = vec4(cur, 1.0); o.hist = vec4(cur, 1.0); return o; }
71
+
72
+ // 3x3 neighbourhood colour box of the current frame -- the anti-ghosting clamp. Coordinates are
73
+ // clamped to the texture: an out-of-range textureLoad returns zero in WGSL, which would drag the
74
+ // box's minimum to black along every screen edge and put a dark rim on the frame.
75
+ var mn = cur; var mx = cur;
76
+ for (var dy = -1; dy <= 1; dy = dy + 1) {
77
+ for (var dx = -1; dx <= 1; dx = dx + 1) {
78
+ let q = clamp(px + vec2<i32>(dx, dy), vec2<i32>(0, 0), dim - vec2<i32>(1, 1));
79
+ let c = textureLoad(colorTex, q, 0).rgb;
80
+ mn = min(mn, c); mx = max(mx, c);
81
+ }
82
+ }
83
+
84
+ // Depth -> world -> previous clip. WebGPU depth is [0,1] and clip-space Y is up while the
85
+ // framebuffer's Y is down, hence the flip in both directions.
86
+ let d = textureLoad(depthTex, px, 0);
87
+ let uv = fc.xy * ru.texel.xy;
88
+ let ndc = vec3<f32>(uv.x * 2.0 - 1.0, 1.0 - uv.y * 2.0, d);
89
+ let wp4 = ru.invCurrVP * vec4(ndc, 1.0);
90
+ let world = wp4.xyz / wp4.w;
91
+ let pc = ru.prevVP * vec4(world, 1.0);
92
+
93
+ var outc = cur;
94
+ if (pc.w > 0.0) { // behind the previous camera -> no usable history
95
+ let pndc = pc.xyz / pc.w;
96
+ let prevUV = vec2<f32>(pndc.x * 0.5 + 0.5, 0.5 - pndc.y * 0.5);
97
+ if (prevUV.x >= 0.0 && prevUV.x <= 1.0 && prevUV.y >= 0.0 && prevUV.y <= 1.0) {
98
+ let hist = clamp(textureSampleLevel(histTex, histSamp, prevUV, 0.0).rgb, mn, mx);
99
+ outc = mix(cur, hist, ru.ctrl.x); // ctrl.x ~ 0.9 => 10% current, 90% reprojected history
100
+ }
101
+ }
102
+ o.screen = vec4(outc, 1.0); o.hist = vec4(outc, 1.0);
103
+ return o;
104
+ }
105
+ `;
106
+ export class GpuTaaResolve {
107
+ device;
108
+ format;
109
+ pipe;
110
+ uBuf;
111
+ u = new Float32Array(40); // 2 x mat4 + 2 x vec4
112
+ samp;
113
+ hist = [];
114
+ histView = [];
115
+ bg = [];
116
+ ping = 0;
117
+ w = 0;
118
+ h = 0;
119
+ primed = false;
120
+ constructor(device, format) {
121
+ this.device = device;
122
+ this.format = format;
123
+ const mod = device.createShaderModule({ code: RESOLVE_WGSL });
124
+ this.pipe = device.createRenderPipeline({
125
+ layout: 'auto',
126
+ vertex: { module: mod, entryPoint: 'vs' },
127
+ fragment: {
128
+ module: mod,
129
+ entryPoint: 'fs',
130
+ targets: [{ format }, { format }],
131
+ },
132
+ primitive: { topology: 'triangle-list' },
133
+ });
134
+ this.uBuf = device.createBuffer({
135
+ size: this.u.byteLength,
136
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
137
+ });
138
+ this.samp = device.createSampler({
139
+ magFilter: 'linear',
140
+ minFilter: 'linear',
141
+ });
142
+ }
143
+ /** (Re)allocate history at the render size. Also invalidates history — a resize is a cut. */
144
+ resize(w, h, colorView, depthView) {
145
+ if (w === this.w && h === this.h && this.bg.length === 2)
146
+ return;
147
+ for (const t of this.hist)
148
+ t.destroy();
149
+ this.w = w;
150
+ this.h = h;
151
+ const mk = () => this.device.createTexture({
152
+ size: [w, h],
153
+ format: this.format,
154
+ usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
155
+ });
156
+ this.hist = [mk(), mk()];
157
+ this.histView = this.hist.map((t) => t.createView());
158
+ this.rebind(colorView, depthView);
159
+ this.primed = false;
160
+ }
161
+ /** Bind group i READS history[i]; the same frame WRITES history[1-i]. */
162
+ rebind(colorView, depthView) {
163
+ this.bg = [0, 1].map((i) => this.device.createBindGroup({
164
+ layout: this.pipe.getBindGroupLayout(0),
165
+ entries: [
166
+ { binding: 0, resource: { buffer: this.uBuf } },
167
+ { binding: 1, resource: this.samp },
168
+ { binding: 2, resource: colorView },
169
+ { binding: 3, resource: depthView },
170
+ { binding: 4, resource: this.histView[i] },
171
+ ],
172
+ }));
173
+ }
174
+ /** Call when the colour/depth VIEWS change identity without a size change. */
175
+ setInputs(colorView, depthView) {
176
+ if (this.histView.length === 2)
177
+ this.rebind(colorView, depthView);
178
+ }
179
+ /** Throw the history away — camera cuts, teleports, origin rebases, pause→resume. */
180
+ invalidate() {
181
+ this.primed = false;
182
+ }
183
+ /**
184
+ * Resolve one frame. `invCurrVP` inverts the UNJITTERED current view-projection; `prevVP` is the
185
+ * previous frame's UNJITTERED view-projection. Jitter belongs in the geometry pass's projection
186
+ * only — reprojection done with a jittered matrix would chase its own offset.
187
+ */
188
+ frame(enc, out, invCurrVP, prevVP, blend = 0.9, enabled = true) {
189
+ if (this.histView.length !== 2)
190
+ return;
191
+ this.u.set(invCurrVP, 0);
192
+ this.u.set(prevVP, 16);
193
+ this.u[32] = 1 / this.w;
194
+ this.u[33] = 1 / this.h;
195
+ this.u[34] = this.w;
196
+ this.u[35] = this.h;
197
+ this.u[36] = blend;
198
+ this.u[37] = enabled ? 1 : 0;
199
+ this.u[38] = this.primed ? 0 : 1; // first frame after a cut has no history to blend
200
+ this.device.queue.writeBuffer(this.uBuf, 0, this.u);
201
+ const pass = enc.beginRenderPass({
202
+ colorAttachments: [
203
+ {
204
+ view: out,
205
+ loadOp: 'clear',
206
+ storeOp: 'store',
207
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
208
+ },
209
+ {
210
+ view: this.histView[1 - this.ping],
211
+ loadOp: 'clear',
212
+ storeOp: 'store',
213
+ clearValue: { r: 0, g: 0, b: 0, a: 1 },
214
+ },
215
+ ],
216
+ });
217
+ pass.setPipeline(this.pipe);
218
+ pass.setBindGroup(0, this.bg[this.ping]);
219
+ pass.draw(3);
220
+ pass.end();
221
+ this.ping = 1 - this.ping;
222
+ this.primed = true;
223
+ }
224
+ destroy() {
225
+ for (const t of this.hist)
226
+ t.destroy();
227
+ this.hist = [];
228
+ this.histView = [];
229
+ this.bg = [];
230
+ }
231
+ }
@@ -0,0 +1,31 @@
1
+ /** Milliseconds per labelled span, plus the whole bracketed region as `total`. */
2
+ export type GpuSpans = Record<string, number>;
3
+ export declare class GpuTimer {
4
+ private smoothing;
5
+ readonly supported: boolean;
6
+ private device;
7
+ private qs;
8
+ private resolve;
9
+ private ring;
10
+ private labels;
11
+ private active;
12
+ private last;
13
+ private ewma;
14
+ constructor(device: GPUDevice, smoothing?: number);
15
+ /** A device advertising the feature is not proof the encoder exposes the call — check both. */
16
+ static isSupported(device: GPUDevice): boolean;
17
+ private write;
18
+ /** Open a timed frame. No-op (and no slot consumed) when every readback buffer is still in flight. */
19
+ begin(enc: GPUCommandEncoder): void;
20
+ /** Close the span that started at the previous mark (or at `begin`) and name it. */
21
+ mark(enc: GPUCommandEncoder, label: string): void;
22
+ /** Resolve the frame's queries into the claimed readback slot. Call before `submit`. */
23
+ end(enc: GPUCommandEncoder): void;
24
+ /** Map any finished slot and fold it into the running averages. Never blocks; call once a frame. */
25
+ poll(): void;
26
+ /** Most recent complete frame, ms per label. Empty until the first readback lands. */
27
+ spans(): GpuSpans;
28
+ /** Smoothed ms per label — what a HUD or an IR scalar should report. */
29
+ average(): GpuSpans;
30
+ destroy(): void;
31
+ }
@@ -0,0 +1,165 @@
1
+ // PLATFORM PASS-TIMER. Real GPU time per render pass, via `timestamp-query`.
2
+ //
3
+ // Why marks between passes rather than `timestampWrites` on the pass descriptor: every renderer in
4
+ // this package (GpuShadowRenderer, GpuSSAO, GpuPropsRenderer, …) opens its own `beginRenderPass`
5
+ // inside `frame()`. Timing via the pass descriptor would mean threading a query set through every
6
+ // one of those private call sites. `encoder.writeTimestamp` brackets spans on the ENCODER instead,
7
+ // so a caller can time existing renderers without any of them changing:
8
+ //
9
+ // timer.begin(enc);
10
+ // skyR.frame(enc, …); timer.mark(enc, 'sky');
11
+ // renderer.frame(enc, …); timer.mark(enc, 'cubes');
12
+ // ssaoR.frame(enc, …); timer.mark(enc, 'ssao');
13
+ // timer.end(enc);
14
+ // device.queue.submit([enc.finish()]);
15
+ // timer.poll(); // non-blocking; results land a few frames later
16
+ //
17
+ // MEASURED on the Electron WebGPU host, timing two 512² passes whose fragment loops differ 5000×:
18
+ // `timestampWrites` reported 0.072 / 79.19 ms and `encoder.writeTimestamp` 0.137 / 70.32 ms. Both
19
+ // attribute correctly, so the encoder path was chosen purely because it needs no renderer changes.
20
+ //
21
+ // THE TRAP, worth knowing before trusting any number this produces: a render pass whose result is
22
+ // never consumed can be dropped by the driver, and then its time lands in a NEIGHBOURING span. An
23
+ // early version of the oracle drew two passes into one texture with `loadOp: 'clear'` and never
24
+ // read it; the first pass was dead work, got elided, and the timer duly reported the heavy pass at
25
+ // 0.01 ms. The timer was right and the scene was a lie. If a span looks impossibly cheap, check
26
+ // that something downstream actually reads what the pass wrote.
27
+ //
28
+ // Unsupported devices degrade quietly: `supported` is false, marks are no-ops, and `spans()` stays
29
+ // empty so callers fall back to wall-clock frame time.
30
+ const MAX_MARKS = 32; // query-set slots: 1 begin + up to 31 marks
31
+ const RING = 3; // readback buffers in flight — enough to never stall a 60fps loop
32
+ export class GpuTimer {
33
+ smoothing;
34
+ supported;
35
+ device;
36
+ qs = null;
37
+ resolve = null;
38
+ ring = [];
39
+ labels = []; // labels for the frame currently being encoded
40
+ active = null; // slot claimed by the frame being encoded
41
+ last = {};
42
+ // A Map, not a Record: `Record<string, number>` claims every key is present, so the "have I seen
43
+ // this label before" check reads as dead code to the type checker even though it decides whether
44
+ // a sample seeds the average or blends into it. A Map says what is actually true.
45
+ ewma = new Map();
46
+ constructor(device, smoothing = 0.1) {
47
+ this.smoothing = smoothing;
48
+ this.device = device;
49
+ this.supported = GpuTimer.isSupported(device);
50
+ if (!this.supported)
51
+ return;
52
+ this.qs = device.createQuerySet({ type: 'timestamp', count: MAX_MARKS });
53
+ this.resolve = device.createBuffer({
54
+ size: MAX_MARKS * 8,
55
+ usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
56
+ });
57
+ for (let i = 0; i < RING; i++)
58
+ this.ring.push({
59
+ read: device.createBuffer({
60
+ size: MAX_MARKS * 8,
61
+ usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
62
+ }),
63
+ busy: false,
64
+ labels: [],
65
+ });
66
+ }
67
+ /** A device advertising the feature is not proof the encoder exposes the call — check both. */
68
+ static isSupported(device) {
69
+ if (!device.features.has('timestamp-query'))
70
+ return false;
71
+ const enc = device.createCommandEncoder();
72
+ return (typeof enc.writeTimestamp ===
73
+ 'function');
74
+ }
75
+ write(enc, index) {
76
+ enc.writeTimestamp(this.qs, index);
77
+ }
78
+ /** Open a timed frame. No-op (and no slot consumed) when every readback buffer is still in flight. */
79
+ begin(enc) {
80
+ if (!this.supported)
81
+ return;
82
+ const slot = this.ring.find((s) => !s.busy);
83
+ if (!slot) {
84
+ this.active = null; // all buffers mapped — skip timing this frame rather than stall
85
+ return;
86
+ }
87
+ this.active = slot;
88
+ this.labels = [];
89
+ this.write(enc, 0);
90
+ }
91
+ /** Close the span that started at the previous mark (or at `begin`) and name it. */
92
+ mark(enc, label) {
93
+ if (!this.supported || !this.active)
94
+ return;
95
+ if (this.labels.length + 1 >= MAX_MARKS)
96
+ return;
97
+ this.labels.push(label);
98
+ this.write(enc, this.labels.length);
99
+ }
100
+ /** Resolve the frame's queries into the claimed readback slot. Call before `submit`. */
101
+ end(enc) {
102
+ if (!this.supported || !this.active || this.labels.length === 0) {
103
+ this.active = null;
104
+ return;
105
+ }
106
+ const n = this.labels.length + 1;
107
+ enc.resolveQuerySet(this.qs, 0, n, this.resolve, 0);
108
+ enc.copyBufferToBuffer(this.resolve, 0, this.active.read, 0, n * 8);
109
+ this.active.busy = true;
110
+ this.active.labels = this.labels.slice();
111
+ this.active = null;
112
+ }
113
+ /** Map any finished slot and fold it into the running averages. Never blocks; call once a frame. */
114
+ poll() {
115
+ if (!this.supported)
116
+ return;
117
+ for (const slot of this.ring) {
118
+ if (!slot.busy || slot.read.mapState !== 'unmapped')
119
+ continue;
120
+ const labels = slot.labels;
121
+ void slot.read
122
+ .mapAsync(GPUMapMode.READ)
123
+ .then(() => {
124
+ const t = new BigUint64Array(slot.read.getMappedRange().slice(0));
125
+ slot.read.unmap();
126
+ slot.busy = false;
127
+ // A GPU that reorders or drops a write leaves a zero — a zero timestamp is missing data,
128
+ // not a 0ms pass, so discard the whole frame rather than report a fabricated span. The
129
+ // range is guaranteed: `end` resolved exactly labels.length + 1 queries into this slot.
130
+ for (let i = 0; i <= labels.length; i++)
131
+ if (t[i] === 0n)
132
+ return;
133
+ const out = {};
134
+ for (let i = 0; i < labels.length; i++)
135
+ out[labels[i]] =
136
+ (out[labels[i]] ?? 0) + Number(t[i + 1] - t[i]) / 1e6;
137
+ out.total = Number(t[labels.length] - t[0]) / 1e6;
138
+ this.last = out;
139
+ const a = this.smoothing;
140
+ for (const k of Object.keys(out)) {
141
+ const prev = this.ewma.get(k);
142
+ this.ewma.set(k, prev === undefined ? out[k] : prev * (1 - a) + out[k] * a);
143
+ }
144
+ })
145
+ .catch(() => {
146
+ slot.busy = false;
147
+ });
148
+ }
149
+ }
150
+ /** Most recent complete frame, ms per label. Empty until the first readback lands. */
151
+ spans() {
152
+ return this.last;
153
+ }
154
+ /** Smoothed ms per label — what a HUD or an IR scalar should report. */
155
+ average() {
156
+ return Object.fromEntries(this.ewma);
157
+ }
158
+ destroy() {
159
+ this.qs?.destroy();
160
+ this.resolve?.destroy();
161
+ for (const s of this.ring)
162
+ s.read.destroy();
163
+ this.ring = [];
164
+ }
165
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Which LOD ring a distance falls in, biased to keep whatever was already chosen.
3
+ *
4
+ * `radii` are the OUTER edges of each ring, ascending — `[64, 128, 256]` means LOD0 out to 64,
5
+ * LOD1 to 128, LOD2 to 256, LOD3 beyond. `current` is last frame's answer for this item (pass -1
6
+ * the first time, when there is nothing to be sticky about). `hysteresis` is in the same units as
7
+ * `dist`, and is the distance you must overshoot a boundary before it lets go.
8
+ */
9
+ export declare function selectLod(dist: number, radii: readonly number[], current?: number, hysteresis?: number): number;
10
+ /**
11
+ * How much of `lod` to show while it hands over to its neighbour, in [0,1].
12
+ *
13
+ * 1 means fully this LOD, 0 means fully the next one. Within `band` of the boundary the two are
14
+ * meant to be drawn TOGETHER with alphas that sum to 1 — `crossfadeAlpha(d, radii, lod)` and
15
+ * `1 - crossfadeAlpha(...)` — so nothing ever blinks between representations.
16
+ */
17
+ export declare function crossfadeAlpha(dist: number, radii: readonly number[], lod: number, band?: number): number;
18
+ /** Per-item LOD state, so a caller can keep hysteresis without inventing its own bookkeeping. */
19
+ export declare class LodTracker {
20
+ private radii;
21
+ private hysteresis;
22
+ private band;
23
+ private state;
24
+ constructor(radii: readonly number[], hysteresis?: number, band?: number);
25
+ /** Resolve one item by stable id. Returns the ring and how much of it to draw. */
26
+ select(id: number, dist: number): {
27
+ lod: number;
28
+ alpha: number;
29
+ next: number;
30
+ };
31
+ /** Drop items that are no longer streamed in, so the map can't grow without bound. */
32
+ forget(id: number): void;
33
+ clear(): void;
34
+ get size(): number;
35
+ }
@@ -0,0 +1,95 @@
1
+ // PLATFORM. LOD ring selection with HYSTERESIS and a CROSSFADE band — the two things that turn a
2
+ // set of detail rings into something that doesn't flicker.
3
+ //
4
+ // The naive rule is `lod = count of radii below dist`, and it has one specific failure: a camera
5
+ // sitting near a boundary. Walk back and forth across r=64 and the ring flips every frame, so a
6
+ // whole band of the world rebuilds its mesh, re-uploads, and pops — at exactly the moment the
7
+ // player is standing still enough to notice. `selectLod` fixes it by making the boundary depend on
8
+ // which side you are already on: you must travel `hysteresis` PAST the radius to promote, and
9
+ // `hysteresis` back INSIDE it to demote. The two thresholds never coincide, so no amount of jitter
10
+ // at a single distance can oscillate.
11
+ //
12
+ // `crossfadeAlpha` covers the other half: even a correct, stable switch is a visible pop if the two
13
+ // LODs differ. Fading one out as the other comes in across a band around the boundary turns the pop
14
+ // into a dissolve. It is deliberately a plain number rather than a shader: GpuShadowRenderer already
15
+ // carries per-instance alpha for its translucent overlay, so a caller feeds this straight into the
16
+ // instance it was already going to submit.
17
+ //
18
+ // Pure functions, no GPU, no game knowledge — so the oracle is headless and the same logic serves
19
+ // voxel rings, mesh LOD ladders and impostor handoff alike.
20
+ /**
21
+ * Which LOD ring a distance falls in, biased to keep whatever was already chosen.
22
+ *
23
+ * `radii` are the OUTER edges of each ring, ascending — `[64, 128, 256]` means LOD0 out to 64,
24
+ * LOD1 to 128, LOD2 to 256, LOD3 beyond. `current` is last frame's answer for this item (pass -1
25
+ * the first time, when there is nothing to be sticky about). `hysteresis` is in the same units as
26
+ * `dist`, and is the distance you must overshoot a boundary before it lets go.
27
+ */
28
+ export function selectLod(dist, radii, current = -1, hysteresis = 0) {
29
+ // No prior state: the plain rule is the honest answer, since there is nothing to stick to.
30
+ if (current < 0 || hysteresis <= 0) {
31
+ let l = 0;
32
+ while (l < radii.length && dist > radii[l])
33
+ l++;
34
+ return l;
35
+ }
36
+ const clamped = Math.max(0, Math.min(radii.length, current));
37
+ // Promote (coarser) only once past the outer edge PLUS the margin; demote (finer) only once back
38
+ // inside the inner edge MINUS it. Between the two the previous choice simply stands.
39
+ let l = clamped;
40
+ while (l < radii.length && dist > radii[l] + hysteresis)
41
+ l++;
42
+ while (l > 0 && dist < radii[l - 1] - hysteresis)
43
+ l--;
44
+ return l;
45
+ }
46
+ /**
47
+ * How much of `lod` to show while it hands over to its neighbour, in [0,1].
48
+ *
49
+ * 1 means fully this LOD, 0 means fully the next one. Within `band` of the boundary the two are
50
+ * meant to be drawn TOGETHER with alphas that sum to 1 — `crossfadeAlpha(d, radii, lod)` and
51
+ * `1 - crossfadeAlpha(...)` — so nothing ever blinks between representations.
52
+ */
53
+ export function crossfadeAlpha(dist, radii, lod, band = 0) {
54
+ if (band <= 0 || lod < 0 || lod >= radii.length)
55
+ return 1;
56
+ const edge = radii[lod];
57
+ if (dist <= edge - band)
58
+ return 1;
59
+ if (dist >= edge + band)
60
+ return 0;
61
+ const t = (dist - (edge - band)) / (2 * band);
62
+ return 1 - t * t * (3 - 2 * t); // smoothstep — a linear ramp shows its corners as a brightness kink
63
+ }
64
+ /** Per-item LOD state, so a caller can keep hysteresis without inventing its own bookkeeping. */
65
+ export class LodTracker {
66
+ radii;
67
+ hysteresis;
68
+ band;
69
+ state = new Map();
70
+ constructor(radii, hysteresis = 0, band = 0) {
71
+ this.radii = radii;
72
+ this.hysteresis = hysteresis;
73
+ this.band = band;
74
+ }
75
+ /** Resolve one item by stable id. Returns the ring and how much of it to draw. */
76
+ select(id, dist) {
77
+ const lod = selectLod(dist, this.radii, this.state.get(id) ?? -1, this.hysteresis);
78
+ this.state.set(id, lod);
79
+ return {
80
+ lod,
81
+ alpha: crossfadeAlpha(dist, this.radii, lod, this.band),
82
+ next: Math.min(lod + 1, this.radii.length),
83
+ };
84
+ }
85
+ /** Drop items that are no longer streamed in, so the map can't grow without bound. */
86
+ forget(id) {
87
+ this.state.delete(id);
88
+ }
89
+ clear() {
90
+ this.state.clear();
91
+ }
92
+ get size() {
93
+ return this.state.size;
94
+ }
95
+ }
package/dist/mat4.d.ts CHANGED
@@ -3,6 +3,15 @@ export type Vec3 = readonly [number, number, number];
3
3
  export declare function perspective(fovY: number, aspect: number, near: number, far: number): Mat4;
4
4
  export declare function lookAt(eye: Vec3, target: Vec3, up: Vec3): Mat4;
5
5
  export declare function mul(a: Mat4, b: Mat4): Mat4;
6
+ /**
7
+ * General 4×4 inverse (cofactor / Laplace expansion), or `null` when `m` is singular.
8
+ *
9
+ * Needed to go the other way through a projection: TAA's depth reprojection unprojects a pixel with
10
+ * `invert(camVP)` to recover its world position. A view-projection is not affine — the perspective
11
+ * divide puts values in the bottom row — so the cheap "transpose the rotation, negate the
12
+ * translation" shortcut does not apply here and the full inverse is the honest one.
13
+ */
14
+ export declare function invert(m: Mat4): Mat4 | null;
6
15
  /** camera view-projection = perspective · lookAt (world → clip). */
7
16
  export declare function viewProjection(eye: Vec3, target: Vec3, fovY: number, aspect: number, near?: number, far?: number): Mat4;
8
17
  /** Orthographic projection, WebGPU clip z ∈ [0,1] (for shadow-map light views). */
package/dist/mat4.js CHANGED
@@ -51,6 +51,40 @@ export function mul(a, b) {
51
51
  }
52
52
  return o;
53
53
  }
54
+ /**
55
+ * General 4×4 inverse (cofactor / Laplace expansion), or `null` when `m` is singular.
56
+ *
57
+ * Needed to go the other way through a projection: TAA's depth reprojection unprojects a pixel with
58
+ * `invert(camVP)` to recover its world position. A view-projection is not affine — the perspective
59
+ * divide puts values in the bottom row — so the cheap "transpose the rotation, negate the
60
+ * translation" shortcut does not apply here and the full inverse is the honest one.
61
+ */
62
+ export function invert(m) {
63
+ const a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3], a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7], a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11], a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15];
64
+ const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
65
+ const det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
66
+ if (det === 0 || !Number.isFinite(det))
67
+ return null;
68
+ const d = 1 / det;
69
+ const o = new Float64Array(16);
70
+ o[0] = (a11 * b11 - a12 * b10 + a13 * b09) * d;
71
+ o[1] = (a02 * b10 - a01 * b11 - a03 * b09) * d;
72
+ o[2] = (a31 * b05 - a32 * b04 + a33 * b03) * d;
73
+ o[3] = (a22 * b04 - a21 * b05 - a23 * b03) * d;
74
+ o[4] = (a12 * b08 - a10 * b11 - a13 * b07) * d;
75
+ o[5] = (a00 * b11 - a02 * b08 + a03 * b07) * d;
76
+ o[6] = (a32 * b02 - a30 * b05 - a33 * b01) * d;
77
+ o[7] = (a20 * b05 - a22 * b02 + a23 * b01) * d;
78
+ o[8] = (a10 * b10 - a11 * b08 + a13 * b06) * d;
79
+ o[9] = (a01 * b08 - a00 * b10 - a03 * b06) * d;
80
+ o[10] = (a30 * b04 - a31 * b02 + a33 * b00) * d;
81
+ o[11] = (a21 * b02 - a20 * b04 - a23 * b00) * d;
82
+ o[12] = (a11 * b07 - a10 * b09 - a12 * b06) * d;
83
+ o[13] = (a00 * b09 - a01 * b07 + a02 * b06) * d;
84
+ o[14] = (a31 * b01 - a30 * b03 - a32 * b00) * d;
85
+ o[15] = (a20 * b03 - a21 * b01 + a22 * b00) * d;
86
+ return o;
87
+ }
54
88
  /** camera view-projection = perspective · lookAt (world → clip). */
55
89
  export function viewProjection(eye, target, fovY, aspect, near = 0.1, far = 1000) {
56
90
  return mul(perspective(fovY, aspect, near, far), lookAt(eye, target, [0, 1, 0]));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.8.1",
3
+ "version": "0.10.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {