ugly-game 0.15.22 → 0.15.24

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.
@@ -160,14 +160,39 @@ export declare class GpuPropsRenderer {
160
160
  private drawBGL;
161
161
  private occPipe;
162
162
  private uBuf;
163
- private lightBuf;
163
+ /**
164
+ * The occluder's per-cascade uniform — lightVP + wind. ONE PER CASCADE, and that is a bug fix, not
165
+ * an optimization.
166
+ *
167
+ * ⚠️ `queue.writeBuffer` runs on the QUEUE TIMELINE, before the next submitted command buffer. All
168
+ * of a frame's cascade passes are encoded into ONE command buffer, so writing a single shared
169
+ * uniform once per cascade during encoding does not give each pass its own matrix — all three
170
+ * writes land first and every pass reads the LAST one. Props were therefore cast into cascades 0
171
+ * and 1 using cascade 2's light matrix. The bug is invisible in code review and obvious on screen
172
+ * once you know to look: near tree shadows sitting where the far cascade would have put them.
173
+ */
174
+ private lightBufs;
164
175
  private models;
165
176
  private instBufs;
166
177
  /** Allocated capacity in instances, so a per-frame LOD re-bucket reuses the buffer. */
167
178
  private caps;
168
179
  private bgs;
180
+ /** Indexed [model][cascade] — each cascade binds its own light uniform and survivor slice. */
169
181
  private occBGs;
170
182
  private counts;
183
+ private cullPipe;
184
+ private cullU;
185
+ private cullArgs;
186
+ private cullVis;
187
+ private cullBGs;
188
+ /** Survivor lists are per (model, cascade) but packed into one buffer per model at this stride. */
189
+ private visStride;
190
+ /** Scratch for one cascade's plane set, reused across models and frames. */
191
+ private cullScratch;
192
+ private cullOn;
193
+ private cullReady;
194
+ /** IR: instances submitted to the occluder last frame, before and after the cull. */
195
+ private cullStats;
171
196
  /** Shared across every model — one sampler is all a prop atlas needs. */
172
197
  private sampler;
173
198
  /** 1x1 white, so an untextured model binds the same resources and multiplies by 1. */
@@ -212,7 +237,50 @@ export declare class GpuPropsRenderer {
212
237
  * re-allocating a megabyte of storage buffers per frame would cost more than the LOD saves.
213
238
  */
214
239
  setInstances(instances: PropInstance[]): void;
215
- /** Occluder pass: draw all instanced props' depth into the shared shadow map from the sun's ortho view. */
216
- shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array): void;
240
+ /**
241
+ * Allocate this model's per-cascade cull resources at `cap` instances.
242
+ *
243
+ * One survivor list per model, split into MAX_CASCADES slices at `visStride`. The stride is padded
244
+ * to `STORAGE_ALIGN` because a bound sub-range of a storage buffer must start on that boundary —
245
+ * an unpadded stride validates fine at cap = 64 and fails the moment a model grows past it, which
246
+ * is the sort of thing that only shows up on a dense world.
247
+ */
248
+ private allocCull;
249
+ /** Does this model cast a sun shadow at all? Translucent and cut-out models do not — see shadowPass. */
250
+ private casts;
251
+ /** Turn the per-cascade occluder cull on or off. Off restores the pre-cull behaviour exactly. */
252
+ setShadowCull(on: boolean): void;
253
+ /** IR: occluder instances before and after the cull, summed over the cascades drawn last frame. */
254
+ shadowCullStats(): {
255
+ submitted: number;
256
+ drawn: number;
257
+ cascades: number;
258
+ };
259
+ /**
260
+ * Compact each model's instances against every cascade's light frustum.
261
+ *
262
+ * ⚠️ MUST BE DISPATCHED BEFORE THE CASCADE RENDER PASSES, in the same command encoder — that is why
263
+ * it takes a compute pass rather than opening its own. `GpuShadowRenderer.frame` already opens one
264
+ * for its own cube cull and hands it over through `extraShadowCull`.
265
+ *
266
+ * ⚠️ AND IT TAKES EVERY CASCADE AT ONCE, because `shadowPass` cannot: by the time the cascade passes
267
+ * are being encoded, a compute dispatch can no longer be inserted ahead of them.
268
+ */
269
+ cullPass(cp: GPUComputePassEncoder, lightVPs: Float32Array[]): void;
270
+ /**
271
+ * With the cull off, every survivor list is the identity — so the occluder shader keeps its single
272
+ * `models[vis[ii]]` code path and the toggle cannot introduce a second one that drifts.
273
+ *
274
+ * Written once per capacity change rather than per frame: the identity does not depend on anything
275
+ * that moves.
276
+ */
277
+ private fillIdentityVis;
278
+ /**
279
+ * Occluder pass: draw the props' depth into cascade `cascade` of the shared shadow map.
280
+ *
281
+ * ⚠️ `cascade` SELECTS THE LIGHT UNIFORM AS WELL AS THE SURVIVOR LIST. Both are per-cascade because
282
+ * a single shared uniform written once per cascade during encoding does not work — see `lightBufs`.
283
+ */
284
+ shadowPass(pass: GPURenderPassEncoder, lightVP: Float32Array, cascade?: number): void;
217
285
  frame(enc: GPUCommandEncoder, colorView: GPUTextureView, depthView: GPUTextureView, camVP: Float32Array, sunDir: [number, number, number], sunCol: [number, number, number], amb: [number, number, number], camPos: [number, number, number], fog: [number, number, number], fogDensity: number, up?: [number, number, number], lightVP?: Float32Array | Float32Array[], shadowView?: GPUTextureView, shadowSamp?: GPUSampler): void;
218
286
  }
@@ -3,6 +3,9 @@
3
3
  // model (tree/rock/bush/…) many times at per-instance world transforms, lit + fogged to match the
4
4
  // terrain. Runs in a load pass after the terrain so props depth-test against the surface.
5
5
  // ─────────────────────────────────────────────────────────────────────────────
6
+ // The cull reuses the SAME plane extraction the rest of the engine uses. A second, local copy of
7
+ // Gribb-Hartmann is exactly how a cull ends up disagreeing with the projection it is culling for.
8
+ import { frustumPlanes } from '../mat4';
6
9
  export const MAX_CASCADES = 4; // must match gpuShadow's
7
10
  const SHADER = /* wgsl */ `
8
11
  // wind = (dirX, dirZ, amplitude, phase) — sway, amplitude scaled by the world's air density
@@ -246,8 +249,14 @@ fn deformLocal(p: vec3<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>) -> vec
246
249
  let cy = cos(d2.x); let sy = sin(d2.x);
247
250
  return vec3(x * cy - z * sy, y, x * sy + z * cy);
248
251
  }
252
+ // ⚠️ THE VISIBLE LIST, NOT THE INSTANCE INDEX. When the per-cascade cull is on, this pass is issued as
253
+ // drawIndexedIndirect over a COMPACTED list of survivors, so @builtin(instance_index) counts positions
254
+ // within that list and says nothing about which prop is being drawn. With the cull off the list is
255
+ // filled with the identity (vis[i] = i) rather than the shader being swapped, so there is one code path
256
+ // and the toggle cannot introduce a second, differently-buggy one.
257
+ @group(0) @binding(2) var<storage,read> vis: array<u32>;
249
258
  @vertex fn vs(@location(0) p: vec3<f32>, @builtin(instance_index) ii: u32) -> @builtin(position) vec4<f32> {
250
- let inst = models[ii];
259
+ let inst = models[vis[ii]];
251
260
  let m = inst.m;
252
261
  let dp = deformLocal(p, inst.d0, inst.d1, inst.d2);
253
262
  var world = (m * vec4(dp, 1.0)).xyz;
@@ -272,6 +281,76 @@ fn deformLocal(p: vec3<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>) -> vec
272
281
  * instance; it reads into the next one.
273
282
  */
274
283
  const INST_FLOATS = 32;
284
+ /**
285
+ * PER-CASCADE OCCLUDER CULL — why this exists, measured rather than assumed.
286
+ *
287
+ * `shadowPass` used to draw `counts[m]` instances of every model into EVERY cascade at full mesh
288
+ * resolution. In all-mine-sky at N=128 that was 10.9 ms of a 22.9 ms frame, and the per-cascade cost
289
+ * was FLAT: 3.63, 3.70, 3.63 ms. Cascade 0 is a tight box around the camera and cascade 2 is the far
290
+ * box, so costs that equal mean the pass is not bound by what each cascade contains — every tree in
291
+ * the world was vertex-shaded three times per frame whether or not it lay in the box being rendered.
292
+ *
293
+ * A survivor list per (model, cascade) fixes that without changing the draw count: still one draw per
294
+ * model per cascade, now `drawIndexedIndirect` over however many instances actually landed in the box.
295
+ *
296
+ * ⚠️ QUALITY-NEUTRAL ONLY IF THE BOUND IS CONSERVATIVE. An instance culled from a cascade it really
297
+ * touches leaves a lit tree among shadowed neighbours, and nothing reports it. The sphere below is
298
+ * therefore inflated (see `CULL_FATTEN`) to cover the deform and the wind sway, both of which move
299
+ * vertices AFTER the matrix that the cull sees.
300
+ */
301
+ const CULL_WG = 64;
302
+ /**
303
+ * How much the cull's bounding sphere is inflated over the mesh's own extent.
304
+ *
305
+ * The occluder shader applies `deformLocal` and a wind sway on top of the instance matrix, so a prop's
306
+ * drawn silhouette is strictly larger than its matrix implies: the deform scales radius by up to
307
+ * `d0.y·(1+d0.z)` and height by `d0.x`, and the sway adds `windAmp` at the tip. Rather than reproduce
308
+ * that algebra in the cull — where getting it slightly wrong costs a shadow and says nothing — the
309
+ * sphere is simply fattened past any of it. The cost of being generous is a few instances surviving a
310
+ * cascade they barely touch; the cost of being tight is a missing shadow.
311
+ */
312
+ const CULL_FATTEN = 1.75;
313
+ /** `drawIndexedIndirect` args: indexCount, instanceCount, firstIndex, baseVertex, firstInstance. */
314
+ const INDIRECT_U32 = 5;
315
+ /** `minStorageBufferOffsetAlignment` — the boundary a bound storage sub-range must start on. */
316
+ const STORAGE_ALIGN = 256;
317
+ const PROP_CULL = /* wgsl */ `
318
+ struct Inst { m: mat4x4<f32>, d0: vec4<f32>, d1: vec4<f32>, d2: vec4<f32>, d3: vec4<f32> };
319
+ struct Args { indexCount: u32, instanceCount: atomic<u32>, firstIndex: u32, baseVertex: u32, firstInstance: u32 };
320
+ // info.x = instance count · info.y = local sphere radius · info.z = extra world margin (wind)
321
+ struct CullU { planes: array<vec4<f32>, 6>, info: vec4<f32>, centre: vec4<f32> };
322
+ @group(0) @binding(0) var<uniform> c: CullU;
323
+ @group(0) @binding(1) var<storage,read> insts: array<Inst>;
324
+ @group(0) @binding(2) var<storage,read_write> args: Args;
325
+ @group(0) @binding(3) var<storage,read_write> vis: array<u32>;
326
+ @compute @workgroup_size(${CULL_WG})
327
+ fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
328
+ let i = gid.x;
329
+ if (i >= u32(c.info.x)) { return; }
330
+ let m = insts[i].m;
331
+ let world = (m * vec4<f32>(c.centre.xyz, 1.0)).xyz;
332
+ // Largest column length of the upper 3x3 — the most any direction can be scaled by this matrix.
333
+ let sx = length(m[0].xyz);
334
+ let sy = length(m[1].xyz);
335
+ let sz = length(m[2].xyz);
336
+ let r = c.info.y * max(sx, max(sy, sz)) + c.info.z;
337
+ // ⚠️ ALL SIX PLANES, INCLUDING NEAR — and that is safe here for a specific reason, not by convention.
338
+ // The usual warning is that a caster behind the light's near plane still casts INTO the box, so
339
+ // shadow culls drop the near test. That warning applies when the cull is tighter than the
340
+ // projection. It is not, here: this pass already rasterizes through the SAME ortho matrix these
341
+ // planes are extracted from, so anything outside them was being clipped by the rasterizer anyway.
342
+ // Culling on all six removes exactly what was already being discarded, which is what makes this
343
+ // quality-neutral rather than a judgement call. If the cascade projection ever stops containing its
344
+ // casters, the bug is in the projection and must be fixed there — do not compensate by loosening
345
+ // this, because then the two disagree and only one of them is visible in a screenshot.
346
+ for (var p = 0u; p < 6u; p++) {
347
+ let pl = c.planes[p];
348
+ if (dot(pl.xyz, world) + pl.w < -r) { return; }
349
+ }
350
+ let slot = atomicAdd(&args.instanceCount, 1u);
351
+ vis[slot] = i;
352
+ }
353
+ `;
275
354
  export class GpuPropsRenderer {
276
355
  device;
277
356
  pipe;
@@ -288,14 +367,43 @@ export class GpuPropsRenderer {
288
367
  drawBGL;
289
368
  occPipe;
290
369
  uBuf;
291
- lightBuf;
370
+ /**
371
+ * The occluder's per-cascade uniform — lightVP + wind. ONE PER CASCADE, and that is a bug fix, not
372
+ * an optimization.
373
+ *
374
+ * ⚠️ `queue.writeBuffer` runs on the QUEUE TIMELINE, before the next submitted command buffer. All
375
+ * of a frame's cascade passes are encoded into ONE command buffer, so writing a single shared
376
+ * uniform once per cascade during encoding does not give each pass its own matrix — all three
377
+ * writes land first and every pass reads the LAST one. Props were therefore cast into cascades 0
378
+ * and 1 using cascade 2's light matrix. The bug is invisible in code review and obvious on screen
379
+ * once you know to look: near tree shadows sitting where the far cascade would have put them.
380
+ */
381
+ lightBufs = [];
292
382
  models = [];
293
383
  instBufs = [];
294
384
  /** Allocated capacity in instances, so a per-frame LOD re-bucket reuses the buffer. */
295
385
  caps = [];
296
386
  bgs = [];
387
+ /** Indexed [model][cascade] — each cascade binds its own light uniform and survivor slice. */
297
388
  occBGs = [];
298
389
  counts = [];
390
+ // ── PER-CASCADE OCCLUDER CULL STATE ─────────────────────────────────────────────────────────────
391
+ // Indexed [model][cascade]. Every one of these is sized to the model's instance CAPACITY, not its
392
+ // current count, so a re-bucket that grows a model does not have to reallocate on the frame it
393
+ // happens — the same reason `caps` exists.
394
+ cullPipe = null;
395
+ cullU = []; // planes + info, one per (model, cascade)
396
+ cullArgs = []; // drawIndexedIndirect args
397
+ cullVis = []; // survivor list — per MODEL, see cullPass
398
+ cullBGs = [];
399
+ /** Survivor lists are per (model, cascade) but packed into one buffer per model at this stride. */
400
+ visStride = [];
401
+ /** Scratch for one cascade's plane set, reused across models and frames. */
402
+ cullScratch = new Float32Array(6 * 4 + 4 + 4);
403
+ cullOn = true;
404
+ cullReady = false;
405
+ /** IR: instances submitted to the occluder last frame, before and after the cull. */
406
+ cullStats = { submitted: 0, drawn: 0, cascades: 0 };
299
407
  /** Shared across every model — one sampler is all a prop atlas needs. */
300
408
  sampler = null;
301
409
  /** 1x1 white, so an untextured model binds the same resources and multiplies by 1. */
@@ -482,9 +590,17 @@ export class GpuPropsRenderer {
482
590
  size: 128 + 16 * 9 + 16 + 64 * MAX_CASCADES, // + csm vec4 + the cascade matrices
483
591
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
484
592
  });
485
- this.lightBuf = device.createBuffer({
486
- size: 64 + 16, // lightVP + wind (the occluder sways identically or shadows detach)
487
- usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
593
+ for (let c = 0; c < MAX_CASCADES; c++)
594
+ this.lightBufs.push(device.createBuffer({
595
+ size: 64 + 16, // lightVP + wind (the occluder sways identically or shadows detach)
596
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
597
+ }));
598
+ this.cullPipe = device.createComputePipeline({
599
+ layout: 'auto',
600
+ compute: {
601
+ module: device.createShaderModule({ code: PROP_CULL }),
602
+ entryPoint: 'cull',
603
+ },
488
604
  });
489
605
  const dummy = device.createTexture({
490
606
  size: [1, 1],
@@ -634,8 +750,14 @@ export class GpuPropsRenderer {
634
750
  this.caps = meshes.map(() => 0);
635
751
  this.instBufs = meshes.map(() => null);
636
752
  this.bgs = meshes.map(() => null);
637
- this.occBGs = meshes.map(() => null);
753
+ this.occBGs = meshes.map(() => []);
638
754
  this.counts = meshes.map(() => 0);
755
+ this.cullU = meshes.map(() => []);
756
+ this.cullArgs = meshes.map(() => []);
757
+ this.cullBGs = meshes.map(() => []);
758
+ this.cullVis = meshes.map(() => null);
759
+ this.visStride = meshes.map(() => 0);
760
+ this.cullReady = false;
639
761
  }
640
762
  /**
641
763
  * Group instances by model and upload the per-model instance buffers.
@@ -671,7 +793,7 @@ export class GpuPropsRenderer {
671
793
  // keep the buffer allocated — an empty LOD bucket this frame is usually full the next one
672
794
  if (!this.instBufs[m]) {
673
795
  this.bgs[m] = null;
674
- this.occBGs[m] = null;
796
+ this.occBGs[m] = [];
675
797
  }
676
798
  continue;
677
799
  }
@@ -690,19 +812,173 @@ export class GpuPropsRenderer {
690
812
  { binding: 1, resource: { buffer: this.instBufs[m] } },
691
813
  ],
692
814
  });
693
- this.occBGs[m] = dev.createBindGroup({
694
- layout: this.occPipe.getBindGroupLayout(0),
695
- entries: [
696
- { binding: 0, resource: { buffer: this.lightBuf } },
697
- { binding: 1, resource: { buffer: this.instBufs[m] } },
698
- ],
699
- });
815
+ this.allocCull(m, cap);
700
816
  }
701
817
  dev.queue.writeBuffer(this.instBufs[m], 0, arr);
702
818
  }
703
819
  }
704
- /** Occluder pass: draw all instanced props' depth into the shared shadow map from the sun's ortho view. */
705
- shadowPass(pass, lightVP) {
820
+ /**
821
+ * Allocate this model's per-cascade cull resources at `cap` instances.
822
+ *
823
+ * One survivor list per model, split into MAX_CASCADES slices at `visStride`. The stride is padded
824
+ * to `STORAGE_ALIGN` because a bound sub-range of a storage buffer must start on that boundary —
825
+ * an unpadded stride validates fine at cap = 64 and fails the moment a model grows past it, which
826
+ * is the sort of thing that only shows up on a dense world.
827
+ */
828
+ allocCull(m, cap) {
829
+ const dev = this.device;
830
+ const stride = Math.ceil((cap * 4) / STORAGE_ALIGN) * STORAGE_ALIGN || STORAGE_ALIGN;
831
+ this.visStride[m] = stride;
832
+ this.cullVis[m] = dev.createBuffer({
833
+ size: stride * MAX_CASCADES,
834
+ usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
835
+ });
836
+ this.cullU[m] = [];
837
+ this.cullArgs[m] = [];
838
+ this.cullBGs[m] = [];
839
+ this.occBGs[m] = [];
840
+ for (let c = 0; c < MAX_CASCADES; c++) {
841
+ const u = dev.createBuffer({
842
+ size: this.cullScratch.byteLength,
843
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
844
+ });
845
+ const args = dev.createBuffer({
846
+ size: INDIRECT_U32 * 4,
847
+ usage: GPUBufferUsage.INDIRECT |
848
+ GPUBufferUsage.STORAGE |
849
+ GPUBufferUsage.COPY_DST,
850
+ });
851
+ this.cullU[m].push(u);
852
+ this.cullArgs[m].push(args);
853
+ const vis = {
854
+ buffer: this.cullVis[m],
855
+ offset: c * stride,
856
+ size: stride,
857
+ };
858
+ this.cullBGs[m].push(dev.createBindGroup({
859
+ layout: this.cullPipe.getBindGroupLayout(0),
860
+ entries: [
861
+ { binding: 0, resource: { buffer: u } },
862
+ { binding: 1, resource: { buffer: this.instBufs[m] } },
863
+ { binding: 2, resource: { buffer: args } },
864
+ { binding: 3, resource: vis },
865
+ ],
866
+ }));
867
+ this.occBGs[m].push(dev.createBindGroup({
868
+ layout: this.occPipe.getBindGroupLayout(0),
869
+ entries: [
870
+ { binding: 0, resource: { buffer: this.lightBufs[c] } },
871
+ { binding: 1, resource: { buffer: this.instBufs[m] } },
872
+ { binding: 2, resource: vis },
873
+ ],
874
+ }));
875
+ }
876
+ this.cullReady = false; // the identity fallback list has to be rewritten at the new capacity
877
+ }
878
+ /** Does this model cast a sun shadow at all? Translucent and cut-out models do not — see shadowPass. */
879
+ casts(m) {
880
+ const mdl = this.models[m];
881
+ return mdl.alpha >= 1 && mdl.cutout === 0 && this.counts[m] > 0;
882
+ }
883
+ /** Turn the per-cascade occluder cull on or off. Off restores the pre-cull behaviour exactly. */
884
+ setShadowCull(on) {
885
+ if (this.cullOn === on)
886
+ return;
887
+ this.cullOn = on;
888
+ this.cullReady = false;
889
+ }
890
+ /** IR: occluder instances before and after the cull, summed over the cascades drawn last frame. */
891
+ shadowCullStats() {
892
+ return { ...this.cullStats };
893
+ }
894
+ /**
895
+ * Compact each model's instances against every cascade's light frustum.
896
+ *
897
+ * ⚠️ MUST BE DISPATCHED BEFORE THE CASCADE RENDER PASSES, in the same command encoder — that is why
898
+ * it takes a compute pass rather than opening its own. `GpuShadowRenderer.frame` already opens one
899
+ * for its own cube cull and hands it over through `extraShadowCull`.
900
+ *
901
+ * ⚠️ AND IT TAKES EVERY CASCADE AT ONCE, because `shadowPass` cannot: by the time the cascade passes
902
+ * are being encoded, a compute dispatch can no longer be inserted ahead of them.
903
+ */
904
+ cullPass(cp, lightVPs) {
905
+ const nc = Math.min(lightVPs.length, MAX_CASCADES);
906
+ this.cullStats = { submitted: 0, drawn: 0, cascades: nc };
907
+ if (!this.cullPipe)
908
+ return;
909
+ // Reset every model's indirect args first. `writeBuffer` lands on the queue ahead of this command
910
+ // buffer, so these are all in place before a single workgroup runs, whatever order they were
911
+ // issued in — the same ordering rule that made ONE shared light uniform wrong (see lightBufs).
912
+ const reset = new Uint32Array(INDIRECT_U32);
913
+ for (let m = 0; m < this.models.length; m++) {
914
+ if (!this.casts(m) || !this.cullVis[m])
915
+ continue;
916
+ this.cullStats.submitted += this.counts[m] * nc;
917
+ reset[0] = this.models[m].idxCount;
918
+ reset[1] = this.cullOn ? 0 : this.counts[m]; // cull off ⇒ draw them all, no dispatch
919
+ for (let c = 0; c < nc; c++)
920
+ this.device.queue.writeBuffer(this.cullArgs[m][c], 0, reset);
921
+ }
922
+ if (!this.cullOn) {
923
+ this.fillIdentityVis();
924
+ return;
925
+ }
926
+ cp.setPipeline(this.cullPipe);
927
+ for (let c = 0; c < nc; c++) {
928
+ const planes = frustumPlanes(lightVPs[c]);
929
+ for (let p = 0; p < 6; p++) {
930
+ const pl = planes[p];
931
+ this.cullScratch.set([pl[0], pl[1], pl[2], pl[3]], p * 4);
932
+ }
933
+ for (let m = 0; m < this.models.length; m++) {
934
+ if (!this.casts(m) || !this.cullBGs[m]?.[c])
935
+ continue;
936
+ const mdl = this.models[m];
937
+ // Local bounding sphere of the SOURCE mesh: the cook normalises props to base-at-y=0, so the
938
+ // centre is half its height up and the radius reaches the far top corner. Fattened past the
939
+ // deform and the sway — see CULL_FATTEN.
940
+ const h = 1 / Math.max(mdl.extent.invH, 1e-9);
941
+ const halfW = 1 / Math.max(mdl.extent.invHalfW, 1e-9);
942
+ const r = Math.hypot(halfW, h * 0.5) * CULL_FATTEN;
943
+ this.cullScratch.set([this.counts[m], r, this.world.windAmp, 0], 24);
944
+ this.cullScratch.set([0, h * 0.5, 0, 0], 28);
945
+ this.device.queue.writeBuffer(this.cullU[m][c], 0, this.cullScratch);
946
+ cp.setBindGroup(0, this.cullBGs[m][c]);
947
+ cp.dispatchWorkgroups(Math.ceil(this.counts[m] / CULL_WG));
948
+ }
949
+ }
950
+ }
951
+ /**
952
+ * With the cull off, every survivor list is the identity — so the occluder shader keeps its single
953
+ * `models[vis[ii]]` code path and the toggle cannot introduce a second one that drifts.
954
+ *
955
+ * Written once per capacity change rather than per frame: the identity does not depend on anything
956
+ * that moves.
957
+ */
958
+ fillIdentityVis() {
959
+ if (this.cullReady)
960
+ return;
961
+ for (let m = 0; m < this.models.length; m++) {
962
+ const buf = this.cullVis[m];
963
+ if (!buf)
964
+ continue;
965
+ const n = Math.max(1, this.caps[m] ?? 0);
966
+ const ident = new Uint32Array(n);
967
+ for (let i = 0; i < n; i++)
968
+ ident[i] = i;
969
+ for (let c = 0; c < MAX_CASCADES; c++)
970
+ this.device.queue.writeBuffer(buf, c * this.visStride[m], ident);
971
+ }
972
+ this.cullReady = true;
973
+ }
974
+ /**
975
+ * Occluder pass: draw the props' depth into cascade `cascade` of the shared shadow map.
976
+ *
977
+ * ⚠️ `cascade` SELECTS THE LIGHT UNIFORM AS WELL AS THE SURVIVOR LIST. Both are per-cascade because
978
+ * a single shared uniform written once per cascade during encoding does not work — see `lightBufs`.
979
+ */
980
+ shadowPass(pass, lightVP, cascade = 0) {
981
+ const c = Math.max(0, Math.min(MAX_CASCADES - 1, cascade));
706
982
  const ob = new Float32Array(20);
707
983
  ob.set(lightVP, 0);
708
984
  ob.set([
@@ -711,12 +987,16 @@ export class GpuPropsRenderer {
711
987
  this.world.windAmp,
712
988
  this.phase,
713
989
  ], 16);
714
- this.device.queue.writeBuffer(this.lightBuf, 0, ob);
990
+ this.device.queue.writeBuffer(this.lightBufs[c], 0, ob);
715
991
  pass.setPipeline(this.occPipe);
716
992
  for (let m = 0; m < this.models.length; m++) {
717
- const bg = this.occBGs[m], mdl = this.models[m];
718
- if (!bg || this.counts[m] === 0)
993
+ const mdl = this.models[m];
994
+ // A model whose cull resources have not been allocated yet (its bucket was empty when the
995
+ // instances last changed) has no bind group for this cascade — length, not a null check,
996
+ // because the array is typed dense.
997
+ if (this.occBGs[m].length <= c || this.counts[m] === 0)
719
998
  continue;
999
+ const bg = this.occBGs[m][c];
720
1000
  // A translucent model casts no shadow. The shadow map is one depth buffer and has nowhere to
721
1001
  // record a partial occluder, so the choice is an OPAQUE silhouette cast by a pane of glass or
722
1002
  // none at all — and the opaque one is the more obviously wrong picture.
@@ -730,10 +1010,16 @@ export class GpuPropsRenderer {
730
1010
  // pipeline for the tested case.
731
1011
  if (mdl.cutout > 0)
732
1012
  continue;
1013
+ const args = this.cullArgs[m]?.[c];
1014
+ if (!args)
1015
+ continue;
733
1016
  pass.setBindGroup(0, bg);
734
1017
  pass.setVertexBuffer(0, mdl.posB);
735
1018
  pass.setIndexBuffer(mdl.idxB, 'uint32');
736
- pass.drawIndexed(mdl.idxCount, this.counts[m]);
1019
+ // ⚠️ INDIRECT, so the count comes from the GPU. Reading it back to skip empty models would cost
1020
+ // a stall per model per cascade to save a draw whose instanceCount is already 0 — and the draw
1021
+ // count is the number this whole exercise is not allowed to raise.
1022
+ pass.drawIndexedIndirect(args, 0);
737
1023
  }
738
1024
  }
739
1025
  frame(enc, colorView, depthView, camVP, sunDir, sunCol, amb, camPos, fog, fogDensity, up,
@@ -571,6 +571,8 @@ export declare class GpuShadowRenderer {
571
571
  private lightCull;
572
572
  private lightCullBG;
573
573
  private statsBuf;
574
+ /** Current shadow-map edge length; see setShadowMapSize. */
575
+ private shadowSize;
574
576
  /** Last frame's visible counts (main-pass camera cull, shadow-pass light cull) + total — for IR/telemetry. */
575
577
  lastCull: {
576
578
  total: number;
@@ -786,6 +788,20 @@ export declare class GpuShadowRenderer {
786
788
  get cascadeCount(): number;
787
789
  get shadowMapSampler(): GPUSampler;
788
790
  get shadowMapSize(): number;
791
+ /**
792
+ * Resize the cascaded shadow map. Powers of two 512..4096; anything else is clamped to the nearest.
793
+ *
794
+ * ⚠️ THE FILL, NOT THE INSTANCES, IS WHAT THIS BUYS. Measured in all-mine-sky at N=256: dropping
795
+ * from three cascades to one made the light see 2.9x MORE instances and ran 14.2 ms FASTER, while
796
+ * cutting light-visible instances 56x at three cascades bought only 11.4 ms. The pass is dominated
797
+ * by clearing, rasterizing and storing its depth targets, so edge length is the lever with the
798
+ * squared term in it — and unlike dropping cascades it keeps the cascade STRUCTURE, which is what
799
+ * carries near-field shadow quality.
800
+ *
801
+ * ⚠️ REALLOCATES THE TEXTURE AND EVERY BIND GROUP THAT SAMPLES IT. Cheap once, ruinous per frame —
802
+ * this is a settings-change call, not something to drive from a slider's every tick.
803
+ */
804
+ setShadowMapSize(px: number): void;
789
805
  /** camVP/lightVP: column-major Float32Array(16). sunDir: travel direction. Pass `occlusion` (the depth target +
790
806
  * its size) to enable Hi-Z occlusion culling on the camera pass — the renderer rebuilds a coarse Hi-Z from that
791
807
  * depth each frame and the NEXT frame's cull uses it (hole-free: the first frame + any resize skip occlusion). */
@@ -793,7 +809,16 @@ export declare class GpuShadowRenderer {
793
809
  depth: GPUTextureView;
794
810
  w: number;
795
811
  h: number;
796
- }, tint?: [number, number, number, number], extraShadow?: (sp: GPURenderPassEncoder, lightVP: Float32Array) => void, up?: [number, number, number], linearOut?: boolean): void;
812
+ }, tint?: [number, number, number, number], extraShadow?: (sp: GPURenderPassEncoder, lightVP: Float32Array, cascade: number) => void,
813
+ /**
814
+ * Dispatch extra CULL work for the cascades, in the same compute pass this frame already opens
815
+ * for its own cube cull.
816
+ *
817
+ * ⚠️ THERE IS NO OTHER PLACE TO PUT IT. `extraShadow` runs inside a RENDER pass, where a compute
818
+ * dispatch cannot be inserted, and by then the cascade passes are already being encoded — so an
819
+ * occluder that wants to cull per cascade has to be handed every cascade matrix up front, here.
820
+ */
821
+ extraShadowCull?: (cp: GPUComputePassEncoder, lightVPs: Float32Array[]) => void, up?: [number, number, number], linearOut?: boolean): void;
797
822
  /** Read back the last frame's GPU cull result (camera-visible, light-visible). Does its OWN copy+submit so it's
798
823
  * safe to call from a live render loop (no per-frame readback cost, no race with the ongoing frames). IR/tests. */
799
824
  readCullStats(): Promise<{
package/dist/gpuShadow.js CHANGED
@@ -14,6 +14,12 @@
14
14
  import { frustumPlanes } from './mat4';
15
15
  import { GI_WGSL, PROBE_STRIDE } from './giProbes';
16
16
  const SHADOW_SIZE = 2048;
17
+ /**
18
+ * Shadow-map edge lengths a caller may ask for. Powers of two only, and bounded at both ends: below
19
+ * 512 a cascade cannot resolve a block at any useful range, and above 4096 the allocation is larger
20
+ * than most of the frame's other targets combined.
21
+ */
22
+ const SHADOW_SIZES = [512, 1024, 1536, 2048, 3072, 4096];
17
23
  // CASCADED SHADOW MAPS. One ortho map has to choose between resolution and reach: AMS ran a single
18
24
  // 90-block box against a 280-block draw distance, so everything past it was simply unshadowed and
19
25
  // the far terrain read flat. Cascades split the range into nested boxes — tight and crisp near the
@@ -2781,6 +2787,8 @@ export class GpuShadowRenderer {
2781
2787
  lightCull = [];
2782
2788
  lightCullBG = [];
2783
2789
  statsBuf; // readback: [camVisible, lightVisible] for the IR/tests
2790
+ /** Current shadow-map edge length; see setShadowMapSize. */
2791
+ shadowSize = SHADOW_SIZE;
2784
2792
  /** Last frame's visible counts (main-pass camera cull, shadow-pass light cull) + total — for IR/telemetry. */
2785
2793
  lastCull = { total: 0, camVisible: 0, lightVisible: 0 };
2786
2794
  // Hi-Z OCCLUSION: a coarse max-depth buffer rebuilt from each frame's depth, sampled by next frame's camera cull.
@@ -3223,7 +3231,7 @@ export class GpuShadowRenderer {
3223
3231
  b.destroy();
3224
3232
  this.cascades = n;
3225
3233
  this.shadowTex = this.device.createTexture({
3226
- size: [SHADOW_SIZE, SHADOW_SIZE, n],
3234
+ size: [this.shadowSize, this.shadowSize, n],
3227
3235
  format: 'depth32float',
3228
3236
  dimension: '2d',
3229
3237
  usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
@@ -3684,12 +3692,46 @@ export class GpuShadowRenderer {
3684
3692
  return this.shadowSampler;
3685
3693
  }
3686
3694
  get shadowMapSize() {
3687
- return SHADOW_SIZE;
3695
+ return this.shadowSize;
3696
+ }
3697
+ /**
3698
+ * Resize the cascaded shadow map. Powers of two 512..4096; anything else is clamped to the nearest.
3699
+ *
3700
+ * ⚠️ THE FILL, NOT THE INSTANCES, IS WHAT THIS BUYS. Measured in all-mine-sky at N=256: dropping
3701
+ * from three cascades to one made the light see 2.9x MORE instances and ran 14.2 ms FASTER, while
3702
+ * cutting light-visible instances 56x at three cascades bought only 11.4 ms. The pass is dominated
3703
+ * by clearing, rasterizing and storing its depth targets, so edge length is the lever with the
3704
+ * squared term in it — and unlike dropping cascades it keeps the cascade STRUCTURE, which is what
3705
+ * carries near-field shadow quality.
3706
+ *
3707
+ * ⚠️ REALLOCATES THE TEXTURE AND EVERY BIND GROUP THAT SAMPLES IT. Cheap once, ruinous per frame —
3708
+ * this is a settings-change call, not something to drive from a slider's every tick.
3709
+ */
3710
+ setShadowMapSize(px) {
3711
+ const want = SHADOW_SIZES.reduce((best, s) => Math.abs(s - px) < Math.abs(best - px) ? s : best);
3712
+ if (want === this.shadowSize)
3713
+ return;
3714
+ this.shadowSize = want;
3715
+ // Force the reallocation: allocCascades is the only thing that sizes the texture, and
3716
+ // ensureCascades short-circuits when the COUNT is unchanged, which it is here.
3717
+ const n = Math.max(1, this.cascades);
3718
+ this.allocCascades(n);
3719
+ if (this.sceneReady)
3720
+ this.makeBindGroups();
3688
3721
  }
3689
3722
  /** camVP/lightVP: column-major Float32Array(16). sunDir: travel direction. Pass `occlusion` (the depth target +
3690
3723
  * its size) to enable Hi-Z occlusion culling on the camera pass — the renderer rebuilds a coarse Hi-Z from that
3691
3724
  * depth each frame and the NEXT frame's cull uses it (hole-free: the first frame + any resize skip occlusion). */
3692
- frame(enc, colorView, sceneDepth, camVP, lightVP, sunDir, sunCol, ambient, load = false, occlusion, tint = [1, 1, 1, 0], extraShadow, up = [0, 1, 0], linearOut = false) {
3725
+ frame(enc, colorView, sceneDepth, camVP, lightVP, sunDir, sunCol, ambient, load = false, occlusion, tint = [1, 1, 1, 0], extraShadow,
3726
+ /**
3727
+ * Dispatch extra CULL work for the cascades, in the same compute pass this frame already opens
3728
+ * for its own cube cull.
3729
+ *
3730
+ * ⚠️ THERE IS NO OTHER PLACE TO PUT IT. `extraShadow` runs inside a RENDER pass, where a compute
3731
+ * dispatch cannot be inserted, and by then the cascade passes are already being encoded — so an
3732
+ * occluder that wants to cull per cascade has to be handed every cascade matrix up front, here.
3733
+ */
3734
+ extraShadowCull, up = [0, 1, 0], linearOut = false) {
3693
3735
  // One matrix or many — a single Float32Array is the 1-cascade case and stays byte-identical.
3694
3736
  const mats = Array.isArray(lightVP) ? lightVP : [lightVP];
3695
3737
  const nc = Math.max(1, Math.min(MAX_CASCADES, mats.length));
@@ -3706,7 +3748,7 @@ export class GpuShadowRenderer {
3706
3748
  this.cam[S + 4] = sunCol[0];
3707
3749
  this.cam[S + 5] = sunCol[1];
3708
3750
  this.cam[S + 6] = sunCol[2];
3709
- this.cam[S + 7] = SHADOW_SIZE;
3751
+ this.cam[S + 7] = this.shadowSize; // sunCol.w — the PCF texel step reads this, so it MUST follow a resize
3710
3752
  this.cam[S + 8] = tint[0];
3711
3753
  this.cam[S + 9] = tint[1];
3712
3754
  this.cam[S + 10] = tint[2];
@@ -3759,15 +3801,22 @@ export class GpuShadowRenderer {
3759
3801
  this.writeCull(this.camCull, camVP, occludeNow, camBevel);
3760
3802
  for (let i = 0; i < nc; i++)
3761
3803
  this.writeCull(this.lightCull[i], mats[i], false);
3762
- if (this.count > 0) {
3804
+ // ⚠️ THE PASS OPENS FOR EITHER REASON. It used to be gated on `this.count > 0` alone, which is
3805
+ // right for the cube cull and wrong for a caller's: a scene with no cubes but a forest of props
3806
+ // still needs somewhere to dispatch. Gating on both keeps the empty-scene case free.
3807
+ if (this.count > 0 || extraShadowCull) {
3763
3808
  const cp = enc.beginComputePass();
3764
- cp.setPipeline(this.cullPipe);
3765
- cp.setBindGroup(0, this.camCullBG);
3766
- cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
3767
- for (let i = 0; i < nc; i++) {
3768
- cp.setBindGroup(0, this.lightCullBG[i]);
3809
+ if (this.count > 0) {
3810
+ cp.setPipeline(this.cullPipe);
3811
+ cp.setBindGroup(0, this.camCullBG);
3769
3812
  cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
3813
+ for (let i = 0; i < nc; i++) {
3814
+ cp.setBindGroup(0, this.lightCullBG[i]);
3815
+ cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
3816
+ }
3770
3817
  }
3818
+ if (extraShadowCull)
3819
+ extraShadowCull(cp, mats.slice(0, nc));
3771
3820
  cp.end();
3772
3821
  }
3773
3822
  // Pass 1: occluder depth from the sun — one pass per cascade, into its own array layer.
@@ -3787,7 +3836,7 @@ export class GpuShadowRenderer {
3787
3836
  // The app casts its own occluders (mesh props/trees) into EVERY cascade — an occluder missing
3788
3837
  // from a far cascade would leave a tree lit at distance while its neighbours are shadowed.
3789
3838
  if (extraShadow)
3790
- extraShadow(sp, mats[i]);
3839
+ extraShadow(sp, mats[i], i);
3791
3840
  sp.end();
3792
3841
  }
3793
3842
  // Pass 2: camera, shadow-sampled (camera-frustum + Hi-Z-occlusion-culled).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.22",
3
+ "version": "0.15.24",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {