ugly-game 0.15.21 → 0.15.23
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.
- package/dist/assets/gpuProps.d.ts +71 -3
- package/dist/assets/gpuProps.js +306 -20
- package/dist/gpuShadow.d.ts +69 -1
- package/dist/gpuShadow.js +225 -16
- package/package.json +15 -16
|
@@ -160,14 +160,39 @@ export declare class GpuPropsRenderer {
|
|
|
160
160
|
private drawBGL;
|
|
161
161
|
private occPipe;
|
|
162
162
|
private uBuf;
|
|
163
|
-
|
|
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
|
-
/**
|
|
216
|
-
|
|
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
|
}
|
package/dist/assets/gpuProps.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
486
|
-
|
|
487
|
-
|
|
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(() =>
|
|
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] =
|
|
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.
|
|
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
|
-
/**
|
|
705
|
-
|
|
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.
|
|
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
|
|
718
|
-
|
|
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
|
-
|
|
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,
|
package/dist/gpuShadow.d.ts
CHANGED
|
@@ -129,6 +129,34 @@ export interface AtlasLayout {
|
|
|
129
129
|
* wrapping to an unrelated texture.
|
|
130
130
|
*/
|
|
131
131
|
export declare function packFaceMats(m: readonly number[]): [number, number];
|
|
132
|
+
/**
|
|
133
|
+
* One rigid transform over a contiguous run of instances — see `GpuShadowRenderer.setBodyTransforms`.
|
|
134
|
+
* `first`/`count` are INSTANCE SLOTS in the buffer, matching what `updateInstanceRange` wrote.
|
|
135
|
+
*/
|
|
136
|
+
export interface BodyTransform {
|
|
137
|
+
/** First instance slot the body owns. */
|
|
138
|
+
first: number;
|
|
139
|
+
/** How many consecutive slots. */
|
|
140
|
+
count: number;
|
|
141
|
+
/** World position of the body origin. Default (0,0,0). */
|
|
142
|
+
pos?: [number, number, number];
|
|
143
|
+
/** Body orientation as a quaternion (x, y, z, w). Default identity. */
|
|
144
|
+
rot?: [number, number, number, number];
|
|
145
|
+
}
|
|
146
|
+
/** Rigid-body table: `bodies[0]` is the header, so this is bodies + 1. See `struct Body` in the WGSL. */
|
|
147
|
+
export declare const MAX_BODIES = 32;
|
|
148
|
+
/**
|
|
149
|
+
* Pack the body table into two views over ONE ArrayBuffer, and return how many bodies are live.
|
|
150
|
+
*
|
|
151
|
+
* ⚠️ EXPORTED SO IT CAN BE TESTED WITHOUT A GPU. `Body.range` is `vec4<u32>` while the rest of the
|
|
152
|
+
* struct is f32, so this writes the same 48-byte slot through two typed-array views — the one thing
|
|
153
|
+
* here that can be wrong in a way nothing catches. Write `first` through the f32 view and the shader
|
|
154
|
+
* reads the IEEE bit pattern of 48000.0 as an integer index, which lands somewhere past the end of
|
|
155
|
+
* the buffer and clamps: the body simply never matches and quietly renders at the origin.
|
|
156
|
+
*
|
|
157
|
+
* Slot 0 is the header — see `struct Body` in the WGSL for the field meanings.
|
|
158
|
+
*/
|
|
159
|
+
export declare function packBodyTable(bodies: BodyTransform[], f: Float32Array, u: Uint32Array): number;
|
|
132
160
|
/** The 36-vertex cube as WGSL array-literal bodies (pos + per-face normal). Shared by shadow modules. */
|
|
133
161
|
export declare const CUBE: {
|
|
134
162
|
pos: string;
|
|
@@ -463,6 +491,12 @@ export declare const ALPHA_WGSL: string;
|
|
|
463
491
|
export declare class GpuShadowRenderer {
|
|
464
492
|
private device;
|
|
465
493
|
private instBuf;
|
|
494
|
+
private bodyBuf;
|
|
495
|
+
/** Staging for the body table: f32 and u32 views over ONE buffer, because `Body.range` is u32 and the rest is f32. */
|
|
496
|
+
private bodyScratch;
|
|
497
|
+
private bodyF32;
|
|
498
|
+
private bodyU32;
|
|
499
|
+
private bodyCount;
|
|
466
500
|
private sceneReady;
|
|
467
501
|
private camBuf;
|
|
468
502
|
private shadowTex;
|
|
@@ -689,6 +723,31 @@ export declare class GpuShadowRenderer {
|
|
|
689
723
|
/** How many instances the cull + draw passes consider, whatever is in the buffer past that. Pairs with
|
|
690
724
|
* `updateInstanceRange`: shrinking the dynamic tail is a count change, not an upload. */
|
|
691
725
|
setInstanceCount(n: number): void;
|
|
726
|
+
/**
|
|
727
|
+
* Give contiguous instance RANGES a rigid transform applied on the GPU, so a body that only moves
|
|
728
|
+
* costs a ~48-byte table write instead of a re-upload of every cube it owns.
|
|
729
|
+
*
|
|
730
|
+
* This is the answer to the orbiting-sky-body cost: a planet is thousands of instances whose
|
|
731
|
+
* positions relative to each other never change, and re-packing them in world space each frame was
|
|
732
|
+
* ~283 KB/frame — which also dirtied the shared instance buffer, dragging the untouched terrain
|
|
733
|
+
* segment's upload along with it. Upload the body ONCE in body-local space (`updateInstanceRange`),
|
|
734
|
+
* then call this every frame with its orbit.
|
|
735
|
+
*
|
|
736
|
+
* r.updateInstanceRange(moonCubesInLocalSpace, 48000) // once
|
|
737
|
+
* r.setBodyTransforms([{ first: 48000, count: moon.length, pos: orbitPos, rot: spinQuat }]) // per frame
|
|
738
|
+
*
|
|
739
|
+
* Ranges must not overlap; the first match wins. Positions are body-local, the transform is
|
|
740
|
+
* rotate-then-translate, and a body has no scale (use `CubeInstance.sx/sy/sz` for that).
|
|
741
|
+
*
|
|
742
|
+
* ⚠️ THE RANGES ARE INSTANCE SLOTS, NOT IDENTITIES. They are matched against the instance's slot in
|
|
743
|
+
* the buffer, so re-laying-out your segments silently re-parents whatever now occupies those slots.
|
|
744
|
+
* Reserve fixed capacity per segment — the same discipline `updateInstanceRange` already asks for.
|
|
745
|
+
*
|
|
746
|
+
* Pass `[]` to clear. Bodies past the table's capacity (32) are ignored.
|
|
747
|
+
*/
|
|
748
|
+
setBodyTransforms(bodies: BodyTransform[]): void;
|
|
749
|
+
/** How many rigid bodies the last `setBodyTransforms` installed. */
|
|
750
|
+
bodyTransformCount(): number;
|
|
692
751
|
/** Translucent overlay cubes drawn over the opaque scene; `emissive` carries per-cube alpha (0..1). The buffer
|
|
693
752
|
* GROWS to fit (no hard cap). Pass `eye` to SORT the cubes back-to-front (farthest first) so overlapping
|
|
694
753
|
* translucent cubes blend in the correct order — required for anything denser than the place ghost. By default
|
|
@@ -734,7 +793,16 @@ export declare class GpuShadowRenderer {
|
|
|
734
793
|
depth: GPUTextureView;
|
|
735
794
|
w: number;
|
|
736
795
|
h: number;
|
|
737
|
-
}, tint?: [number, number, number, number], extraShadow?: (sp: GPURenderPassEncoder, lightVP: Float32Array
|
|
796
|
+
}, tint?: [number, number, number, number], extraShadow?: (sp: GPURenderPassEncoder, lightVP: Float32Array, cascade: number) => void,
|
|
797
|
+
/**
|
|
798
|
+
* Dispatch extra CULL work for the cascades, in the same compute pass this frame already opens
|
|
799
|
+
* for its own cube cull.
|
|
800
|
+
*
|
|
801
|
+
* ⚠️ THERE IS NO OTHER PLACE TO PUT IT. `extraShadow` runs inside a RENDER pass, where a compute
|
|
802
|
+
* dispatch cannot be inserted, and by then the cascade passes are already being encoded — so an
|
|
803
|
+
* occluder that wants to cull per cascade has to be handed every cascade matrix up front, here.
|
|
804
|
+
*/
|
|
805
|
+
extraShadowCull?: (cp: GPUComputePassEncoder, lightVPs: Float32Array[]) => void, up?: [number, number, number], linearOut?: boolean): void;
|
|
738
806
|
/** Read back the last frame's GPU cull result (camera-visible, light-visible). Does its OWN copy+submit so it's
|
|
739
807
|
* safe to call from a live render loop (no per-frame readback cost, no race with the ongoing frames). IR/tests. */
|
|
740
808
|
readCullStats(): Promise<{
|
package/dist/gpuShadow.js
CHANGED
|
@@ -54,6 +54,64 @@ export function packFaceMats(m) {
|
|
|
54
54
|
// for the contact decal, which had to widen it for exactly the same reason.
|
|
55
55
|
const INST_F = 20;
|
|
56
56
|
const OVERLAY_CAP = 512; // max translucent overlay cubes per frame (the place ghost + headroom)
|
|
57
|
+
/** Rigid-body table: `bodies[0]` is the header, so this is bodies + 1. See `struct Body` in the WGSL. */
|
|
58
|
+
export const MAX_BODIES = 32;
|
|
59
|
+
const BODY_F = 12; // 3 × vec4 = 48 bytes, the WGSL struct stride
|
|
60
|
+
/**
|
|
61
|
+
* Pack the body table into two views over ONE ArrayBuffer, and return how many bodies are live.
|
|
62
|
+
*
|
|
63
|
+
* ⚠️ EXPORTED SO IT CAN BE TESTED WITHOUT A GPU. `Body.range` is `vec4<u32>` while the rest of the
|
|
64
|
+
* struct is f32, so this writes the same 48-byte slot through two typed-array views — the one thing
|
|
65
|
+
* here that can be wrong in a way nothing catches. Write `first` through the f32 view and the shader
|
|
66
|
+
* reads the IEEE bit pattern of 48000.0 as an integer index, which lands somewhere past the end of
|
|
67
|
+
* the buffer and clamps: the body simply never matches and quietly renders at the origin.
|
|
68
|
+
*
|
|
69
|
+
* Slot 0 is the header — see `struct Body` in the WGSL for the field meanings.
|
|
70
|
+
*/
|
|
71
|
+
export function packBodyTable(bodies, f, u) {
|
|
72
|
+
const n = Math.min(bodies.length, MAX_BODIES);
|
|
73
|
+
let lo = 0xffffffff, hi = 0, live = 0;
|
|
74
|
+
for (let i = 0; i < n; i++) {
|
|
75
|
+
const b = bodies[i];
|
|
76
|
+
if (b.count <= 0 || b.first < 0)
|
|
77
|
+
continue; // empty/invalid ranges are skipped, not errors
|
|
78
|
+
const o = (live + 1) * BODY_F, // +1: slot 0 is the header
|
|
79
|
+
r = b.rot, p = b.pos;
|
|
80
|
+
f[o] = r ? r[0] : 0;
|
|
81
|
+
f[o + 1] = r ? r[1] : 0;
|
|
82
|
+
f[o + 2] = r ? r[2] : 0;
|
|
83
|
+
f[o + 3] = r ? r[3] : 1; // identity quaternion by default
|
|
84
|
+
f[o + 4] = p ? p[0] : 0;
|
|
85
|
+
f[o + 5] = p ? p[1] : 0;
|
|
86
|
+
f[o + 6] = p ? p[2] : 0;
|
|
87
|
+
f[o + 7] = 0;
|
|
88
|
+
u[o + 8] = b.first;
|
|
89
|
+
u[o + 9] = b.count;
|
|
90
|
+
u[o + 10] = 0;
|
|
91
|
+
u[o + 11] = 0;
|
|
92
|
+
if (b.first < lo)
|
|
93
|
+
lo = b.first;
|
|
94
|
+
if (b.first + b.count > hi)
|
|
95
|
+
hi = b.first + b.count;
|
|
96
|
+
live++;
|
|
97
|
+
}
|
|
98
|
+
// The header. range.y = 0 is the "no bodies" sentinel every pass early-outs on, and lo/hi bound
|
|
99
|
+
// the loop away from terrain (below lo) and dynamics (at or above hi) for two compares apiece.
|
|
100
|
+
u[8] = live === 0 ? 0 : lo;
|
|
101
|
+
u[9] = live;
|
|
102
|
+
u[10] = live === 0 ? 0 : hi;
|
|
103
|
+
u[11] = 0;
|
|
104
|
+
return live;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* ⚠️ ONE NUMBER SHARED BY THREE LAYOUTS. `bodies` is declared in `commonHeadWgsl`, which the shadow,
|
|
108
|
+
* main AND alpha shaders all splice in, so the slot has to be free in every one of them and every
|
|
109
|
+
* one of their bind-group layouts has to declare it — even the alpha layout, which otherwise stops
|
|
110
|
+
* at binding 1. Main already occupies 0–10 (GI and patchwork included), hence 11.
|
|
111
|
+
*/
|
|
112
|
+
const BODY_BINDING = 11;
|
|
113
|
+
/** The cull pass has its own layout and its own `Inst`/`Body` declarations; nothing is shared with the draw passes. */
|
|
114
|
+
const CULL_BODY_BINDING = 5;
|
|
57
115
|
// Build the 36-vertex cube (6 faces × 2 tris) in JS and inject as WGSL const arrays —
|
|
58
116
|
// bulletproof + readable vs. bit-twiddling from vertex_index. cullMode is 'none', so winding
|
|
59
117
|
// doesn't matter. Positions in [-0.5, 0.5]; flat per-face normals.
|
|
@@ -1351,8 +1409,25 @@ struct Cam {
|
|
|
1351
1409
|
eye: vec4<f32>, // xyz = camera position in world space (material relief + specular); w = CONVEX (chamfer) radius (0 = sharp cube)
|
|
1352
1410
|
};
|
|
1353
1411
|
struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> }; // pos.w = hue (<0 ⇒ ground) · scl.w = emissive/alpha · rot = quaternion · aux.x = atlas tile (<0 ⇒ hue) · aux.y = up-face code · aux.z/aux.w = CONTACT DECAL (0,0 = none) · aux2.xy = 27-bit NEIGHBOUR OCCUPANCY split 14/13 (0,0 = unknown ⇒ no corner AO) · aux2.z = per-block albedo jitter · aux2.w = texFit (≠0 ⇒ one atlas tile per face, texture coords NOT scaled by inst.scl)
|
|
1412
|
+
// ── RIGID BODIES ────────────────────────────────────────────────────────────────────────────────
|
|
1413
|
+
//
|
|
1414
|
+
// A CONTIGUOUS RANGE OF INSTANCES THAT MOVES AS ONE. Orbiting sky bodies used to be re-uploaded in
|
|
1415
|
+
// world space every frame — 3,535 instances × 80 B = 282,800 B/frame just to rotate a moon — and
|
|
1416
|
+
// the write invalidated the shared instance buffer's memo, so the whole terrain segment went with
|
|
1417
|
+
// it. A body is instead uploaded ONCE in body-local space and given a rotation + translation here.
|
|
1418
|
+
//
|
|
1419
|
+
// ⚠️ RANGE-BASED, NOT PER-INSTANCE. Inst is exactly five vec4s / 80 bytes with no spare slot, so
|
|
1420
|
+
// a per-instance body id would cost a SIXTH vec4 — +20% on every instance in the world, ~1 MB at
|
|
1421
|
+
// N=128 and 6.4 MB at N=256, to serve a few thousand sky cubes. Bodies already occupy contiguous
|
|
1422
|
+
// ranges (that is precisely what updateInstanceRange produces), so a range table costs ~9 × 48 B.
|
|
1423
|
+
//
|
|
1424
|
+
// bodies[0] is a HEADER, not a body: range.x = lowest instance index owned by any body, range.y =
|
|
1425
|
+
// body count, range.z = one past the highest. Terrain sits below range.x and dynamics above
|
|
1426
|
+
// range.z, so everything that is not a body pays two compares and never enters the loop.
|
|
1427
|
+
struct Body { rot: vec4<f32>, pos: vec4<f32>, range: vec4<u32> };
|
|
1354
1428
|
@group(0) @binding(0) var<uniform> cam: Cam;
|
|
1355
1429
|
@group(0) @binding(1) var<storage, read> insts: array<Inst>;
|
|
1430
|
+
@group(0) @binding(${BODY_BINDING}) var<storage, read> bodies: array<Body>;
|
|
1356
1431
|
|
|
1357
1432
|
const CUBE_POS = array<vec3<f32>, 36>(${CUBE.pos});
|
|
1358
1433
|
const CUBE_NRM = array<vec3<f32>, 36>(${CUBE.nrm});
|
|
@@ -1364,6 +1439,27 @@ const BEV_AXIS = array<vec3<f32>, ${V}>(${B.axisWgsl});
|
|
|
1364
1439
|
fn qrot(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> { let t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); }
|
|
1365
1440
|
fn worldOf(inst: Inst, vi: u32) -> vec3<f32> { return inst.pos.xyz + qrot(inst.rot, CUBE_POS[vi] * inst.scl.xyz); }
|
|
1366
1441
|
|
|
1442
|
+
fn bodyNone() -> Body {
|
|
1443
|
+
return Body(vec4<f32>(0.0, 0.0, 0.0, 1.0), vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<u32>(0u, 0u, 0u, 0u));
|
|
1444
|
+
}
|
|
1445
|
+
// ⚠️ TAKES THE GLOBAL INSTANCE INDEX. The draw passes iterate a CULLED VISIBLE LIST, so
|
|
1446
|
+
// @builtin(instance_index) is a position within that list and means nothing to a range — the
|
|
1447
|
+
// caller must pass vis[ii], the same index it used to fetch the Inst.
|
|
1448
|
+
fn bodyOf(gi: u32) -> Body {
|
|
1449
|
+
let hdr = bodies[0];
|
|
1450
|
+
if (hdr.range.y == 0u || gi < hdr.range.x || gi >= hdr.range.z) { return bodyNone(); }
|
|
1451
|
+
for (var b = 1u; b <= hdr.range.y; b = b + 1u) {
|
|
1452
|
+
let bd = bodies[b];
|
|
1453
|
+
if (gi >= bd.range.x && gi < bd.range.x + bd.range.y) { return bd; }
|
|
1454
|
+
}
|
|
1455
|
+
return bodyNone();
|
|
1456
|
+
}
|
|
1457
|
+
// Rotation + translation only — a body has no scale, so a normal just rotates and needs no
|
|
1458
|
+
// inverse-transpose. (bodyDir on an already-inverse-scaled normal stays correct.)
|
|
1459
|
+
fn bodyPos(b: Body, w: vec3<f32>) -> vec3<f32> { return b.pos.xyz + qrot(b.rot, w); }
|
|
1460
|
+
fn bodyDir(b: Body, v: vec3<f32>) -> vec3<f32> { return qrot(b.rot, v); }
|
|
1461
|
+
fn worldOfB(inst: Inst, vi: u32, gi: u32) -> vec3<f32> { return bodyPos(bodyOf(gi), worldOf(inst, vi)); }
|
|
1462
|
+
|
|
1367
1463
|
// ── PER-CORNER AMBIENT OCCLUSION ────────────────────────────────────────────────────────────────
|
|
1368
1464
|
//
|
|
1369
1465
|
// The dark that collects where two surfaces meet: the inside of a step, the base of a wall, the
|
|
@@ -1883,6 +1979,12 @@ ${maskWgsl(seg, B, V, S)}
|
|
|
1883
1979
|
// the wrong offset, and the symptom is cubes winking out of existence at the edge of view rather
|
|
1884
1980
|
// than anything that looks like a struct mismatch.
|
|
1885
1981
|
struct Inst { pos: vec4<f32>, scl: vec4<f32>, rot: vec4<f32>, aux: vec4<f32>, aux2: vec4<f32> };
|
|
1982
|
+
// ⚠️ A SECOND HAND-MAINTAINED COPY, exactly like Inst above — and this one is load-bearing in a way
|
|
1983
|
+
// that fails silently. If the cull pass skips a body's transform, it culls the sky bodies against
|
|
1984
|
+
// the frustum at their AUTHORED positions while the draw passes put them somewhere else: a moon
|
|
1985
|
+
// vanishes when the place it used to be leaves the screen. Keep in step with struct Body / bodyOf
|
|
1986
|
+
// in commonHeadWgsl.
|
|
1987
|
+
struct Body { rot: vec4<f32>, pos: vec4<f32>, range: vec4<u32> };
|
|
1886
1988
|
struct Args { vc: u32, ic: atomic<u32>, fv: u32, fi: u32 };
|
|
1887
1989
|
struct CullCam {
|
|
1888
1990
|
planes: array<vec4<f32>, 6>, cnt: vec4<f32>, // cnt.x = instance count
|
|
@@ -1894,17 +1996,32 @@ struct CullCam {
|
|
|
1894
1996
|
@group(0) @binding(2) var<storage, read_write> visible: array<u32>;
|
|
1895
1997
|
@group(0) @binding(3) var<uniform> cc: CullCam;
|
|
1896
1998
|
@group(0) @binding(4) var hiz: texture_2d<f32>;
|
|
1999
|
+
@group(0) @binding(${CULL_BODY_BINDING}) var<storage, read> bodies: array<Body>;
|
|
1897
2000
|
fn qr(q: vec4<f32>, v: vec3<f32>) -> vec3<f32> { let t = 2.0 * cross(q.xyz, v); return v + q.w * t + cross(q.xyz, t); }
|
|
2001
|
+
fn bodyNone() -> Body {
|
|
2002
|
+
return Body(vec4<f32>(0.0, 0.0, 0.0, 1.0), vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<u32>(0u, 0u, 0u, 0u));
|
|
2003
|
+
}
|
|
2004
|
+
fn bodyOf(gi: u32) -> Body {
|
|
2005
|
+
let hdr = bodies[0];
|
|
2006
|
+
if (hdr.range.y == 0u || gi < hdr.range.x || gi >= hdr.range.z) { return bodyNone(); }
|
|
2007
|
+
for (var b = 1u; b <= hdr.range.y; b = b + 1u) {
|
|
2008
|
+
let bd = bodies[b];
|
|
2009
|
+
if (gi >= bd.range.x && gi < bd.range.x + bd.range.y) { return bd; }
|
|
2010
|
+
}
|
|
2011
|
+
return bodyNone();
|
|
2012
|
+
}
|
|
1898
2013
|
@compute @workgroup_size(${CULL_WG})
|
|
1899
2014
|
fn cull(@builtin(global_invocation_id) gid: vec3<u32>) {
|
|
1900
2015
|
let i = gid.x;
|
|
1901
2016
|
if (i >= u32(cc.cnt.x)) { return; }
|
|
1902
2017
|
let inst = insts[i];
|
|
1903
|
-
|
|
2018
|
+
// The cull pass indexes the instance buffer DIRECTLY, so its instance index is already global.
|
|
2019
|
+
let bd = bodyOf(i);
|
|
2020
|
+
let c = bd.pos.xyz + qr(bd.rot, inst.pos.xyz);
|
|
1904
2021
|
let h = 0.5 * inst.scl.xyz;
|
|
1905
|
-
let bx = qr(inst.rot, vec3<f32>(h.x, 0.0, 0.0)); // rotated box semi-axes
|
|
1906
|
-
let by = qr(inst.rot, vec3<f32>(0.0, h.y, 0.0));
|
|
1907
|
-
let bz = qr(inst.rot, vec3<f32>(0.0, 0.0, h.z));
|
|
2022
|
+
let bx = qr(bd.rot, qr(inst.rot, vec3<f32>(h.x, 0.0, 0.0))); // rotated box semi-axes
|
|
2023
|
+
let by = qr(bd.rot, qr(inst.rot, vec3<f32>(0.0, h.y, 0.0)));
|
|
2024
|
+
let bz = qr(bd.rot, qr(inst.rot, vec3<f32>(0.0, 0.0, h.z)));
|
|
1908
2025
|
for (var p = 0u; p < 6u; p++) {
|
|
1909
2026
|
let pl = cc.planes[p];
|
|
1910
2027
|
let e = abs(dot(pl.xyz, bx)) + abs(dot(pl.xyz, by)) + abs(dot(pl.xyz, bz)); // box half-width along the normal
|
|
@@ -1999,7 +2116,8 @@ export const shadowWgsl = (seg, B, V, S) => commonWgsl(seg, B, V, S) +
|
|
|
1999
2116
|
// Always index [0]: each cascade's shadow pass binds its OWN Cam buffer whose lightVP[0] holds that
|
|
2000
2117
|
// cascade's matrix. One uniform per cascade costs a few hundred bytes and avoids dynamic offsets.
|
|
2001
2118
|
@vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> @builtin(position) vec4<f32> {
|
|
2002
|
-
|
|
2119
|
+
let gi = vis[ii];
|
|
2120
|
+
return cam.lightVP[0] * vec4(worldOfB(insts[gi], vi, gi), 1.0);
|
|
2003
2121
|
}
|
|
2004
2122
|
`;
|
|
2005
2123
|
export const mainWgsl = (seg, B, V, S) => commonWgsl(seg, B, V, S) +
|
|
@@ -2053,7 +2171,9 @@ fn faceVec(code: f32) -> vec3<f32> {
|
|
|
2053
2171
|
}
|
|
2054
2172
|
|
|
2055
2173
|
@vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut {
|
|
2056
|
-
let
|
|
2174
|
+
let gi = vis[ii];
|
|
2175
|
+
let inst = insts[gi];
|
|
2176
|
+
let bd = bodyOf(gi); // rigid-body transform for the range this instance belongs to (identity for terrain)
|
|
2057
2177
|
// ⚠️ PATCHWORK REUSES THE OCCUPANCY FLOATS, so the mask must be suppressed when it is on. tile == -2
|
|
2058
2178
|
// says aux2.xy carry six FACE MATERIALS rather than a neighbour mask; reading them as one would bevel and
|
|
2059
2179
|
// shade the cube off a "neighbourhood" made of material ids. There is nothing lost: a patchwork instance
|
|
@@ -2094,7 +2214,7 @@ fn faceVec(code: f32) -> vec3<f32> {
|
|
|
2094
2214
|
}
|
|
2095
2215
|
|
|
2096
2216
|
let local = bevelPos(mask, sharp, home, cam.eye.w, BEV_ROLE[vi], BEV_AXIS[vi], cam.csm.z);
|
|
2097
|
-
let world = inst.pos.xyz + qrot(inst.rot, local * inst.scl.xyz);
|
|
2217
|
+
let world = bodyPos(bd, inst.pos.xyz + qrot(inst.rot, local * inst.scl.xyz));
|
|
2098
2218
|
var o: VOut;
|
|
2099
2219
|
o.clip = cam.camVP * vec4(world, 1.0);
|
|
2100
2220
|
o.world = world;
|
|
@@ -2204,7 +2324,10 @@ fn faceVec(code: f32) -> vec3<f32> {
|
|
|
2204
2324
|
}
|
|
2205
2325
|
}
|
|
2206
2326
|
}
|
|
2207
|
-
|
|
2327
|
+
// ⚠️ THE BODY ROTATION BELONGS HERE TOO. Transforming the position without the normal lights a
|
|
2328
|
+
// rotating moon as if it were still at its authored orientation — the terminator stops moving
|
|
2329
|
+
// with the geometry, which reads as flat shading rather than as a transform bug.
|
|
2330
|
+
o.nrm = normalize(bodyDir(bd, qrot(inst.rot, shade / inst.scl.xyz)));
|
|
2208
2331
|
o.hue = inst.pos.w;
|
|
2209
2332
|
o.emis = inst.scl.w;
|
|
2210
2333
|
// OBJECT-space block coord (per-sub-block units, anchored to the model, NOT world) so per-block AO moves +
|
|
@@ -2549,6 +2672,10 @@ struct AOut { @builtin(position) clip: vec4<f32>, @location(0) hue: f32, @locati
|
|
|
2549
2672
|
@vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> AOut {
|
|
2550
2673
|
let inst = insts[ii];
|
|
2551
2674
|
var o: AOut;
|
|
2675
|
+
// ⚠️ NO BODY TRANSFORM HERE, AND THAT IS NOT AN OVERSIGHT. This pass binds the OVERLAY buffer to
|
|
2676
|
+
// insts, not the scene instance buffer, so ii lives in a different index space entirely — the
|
|
2677
|
+
// body ranges mean nothing against it. Resolving a body here would transform whichever overlay cube
|
|
2678
|
+
// happened to land in a body's range, i.e. the place ghost would teleport into orbit near a moon.
|
|
2552
2679
|
o.clip = cam.camVP * vec4(worldOf(inst, vi), 1.0);
|
|
2553
2680
|
o.hue = inst.pos.w; o.a = inst.scl.w;
|
|
2554
2681
|
return o;
|
|
@@ -2572,6 +2699,12 @@ export const ALPHA_WGSL = alphaWgsl(B1.seg, B1.cube, B1.verts, B1.sec);
|
|
|
2572
2699
|
export class GpuShadowRenderer {
|
|
2573
2700
|
device;
|
|
2574
2701
|
instBuf;
|
|
2702
|
+
bodyBuf;
|
|
2703
|
+
/** Staging for the body table: f32 and u32 views over ONE buffer, because `Body.range` is u32 and the rest is f32. */
|
|
2704
|
+
bodyScratch = new ArrayBuffer((MAX_BODIES + 1) * BODY_F * 4);
|
|
2705
|
+
bodyF32 = new Float32Array(this.bodyScratch);
|
|
2706
|
+
bodyU32 = new Uint32Array(this.bodyScratch);
|
|
2707
|
+
bodyCount = 0;
|
|
2575
2708
|
sceneReady = false; // instBuf exists — setScene/setCapacity has run at least once
|
|
2576
2709
|
camBuf;
|
|
2577
2710
|
shadowTex = null; // null until the first frame picks a cascade count
|
|
@@ -2688,6 +2821,19 @@ export class GpuShadowRenderer {
|
|
|
2688
2821
|
const mainMod = device.createShaderModule({
|
|
2689
2822
|
code: mainWgsl(this.bev.seg, this.bev.cube, this.bev.verts, this.bev.sec),
|
|
2690
2823
|
});
|
|
2824
|
+
// The rigid-body table. Allocated once at full capacity and zero-filled, so `bodies[0].range.y`
|
|
2825
|
+
// is 0 — the "no bodies" sentinel — and every pass runs the identity path until a caller sets one.
|
|
2826
|
+
this.bodyBuf = device.createBuffer({
|
|
2827
|
+
size: (MAX_BODIES + 1) * BODY_F * 4,
|
|
2828
|
+
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST,
|
|
2829
|
+
});
|
|
2830
|
+
device.queue.writeBuffer(this.bodyBuf, 0, new Float32Array((MAX_BODIES + 1) * BODY_F));
|
|
2831
|
+
/** The `bodies` entry, identical in all three draw layouts. See `BODY_BINDING`. */
|
|
2832
|
+
const bodyEntry = {
|
|
2833
|
+
binding: BODY_BINDING,
|
|
2834
|
+
visibility: GPUShaderStage.VERTEX,
|
|
2835
|
+
buffer: { type: 'read-only-storage' },
|
|
2836
|
+
};
|
|
2691
2837
|
const shadowBGL = device.createBindGroupLayout({
|
|
2692
2838
|
entries: [
|
|
2693
2839
|
{
|
|
@@ -2705,6 +2851,7 @@ export class GpuShadowRenderer {
|
|
|
2705
2851
|
visibility: GPUShaderStage.VERTEX,
|
|
2706
2852
|
buffer: { type: 'read-only-storage' },
|
|
2707
2853
|
}, // light-visible list
|
|
2854
|
+
bodyEntry,
|
|
2708
2855
|
],
|
|
2709
2856
|
});
|
|
2710
2857
|
this.shadowPipe = device.createRenderPipeline({
|
|
@@ -2770,6 +2917,7 @@ export class GpuShadowRenderer {
|
|
|
2770
2917
|
visibility: GPUShaderStage.FRAGMENT,
|
|
2771
2918
|
buffer: { type: 'read-only-storage' },
|
|
2772
2919
|
}, // GI probe irradiance
|
|
2920
|
+
bodyEntry,
|
|
2773
2921
|
],
|
|
2774
2922
|
});
|
|
2775
2923
|
this.mainPipe = device.createRenderPipeline({
|
|
@@ -2818,6 +2966,10 @@ export class GpuShadowRenderer {
|
|
|
2818
2966
|
visibility: GPUShaderStage.VERTEX,
|
|
2819
2967
|
buffer: { type: 'read-only-storage' },
|
|
2820
2968
|
},
|
|
2969
|
+
// The overlay pass deliberately does NOT resolve bodies (its `insts` is the overlay buffer, a
|
|
2970
|
+
// different index space — see alphaWgsl), but commonHeadWgsl still DECLARES the binding, so the
|
|
2971
|
+
// layout has to carry it or pipeline creation fails on a layout/module mismatch.
|
|
2972
|
+
bodyEntry,
|
|
2821
2973
|
],
|
|
2822
2974
|
}));
|
|
2823
2975
|
this.alphaPipe = device.createRenderPipeline({
|
|
@@ -2860,6 +3012,7 @@ export class GpuShadowRenderer {
|
|
|
2860
3012
|
entries: [
|
|
2861
3013
|
{ binding: 0, resource: { buffer: this.camBuf } },
|
|
2862
3014
|
{ binding: 1, resource: { buffer: this.overlayBuf } },
|
|
3015
|
+
{ binding: BODY_BINDING, resource: { buffer: this.bodyBuf } },
|
|
2863
3016
|
],
|
|
2864
3017
|
});
|
|
2865
3018
|
// GPU-driven cull: compute pipeline shared by the camera + light dispatches (each with its own args/vis/uniform).
|
|
@@ -2893,6 +3046,11 @@ export class GpuShadowRenderer {
|
|
|
2893
3046
|
visibility: GPUShaderStage.COMPUTE,
|
|
2894
3047
|
texture: { sampleType: 'unfilterable-float' },
|
|
2895
3048
|
}, // Hi-Z (dummy until occlusion is used)
|
|
3049
|
+
{
|
|
3050
|
+
binding: CULL_BODY_BINDING,
|
|
3051
|
+
visibility: GPUShaderStage.COMPUTE,
|
|
3052
|
+
buffer: { type: 'read-only-storage' },
|
|
3053
|
+
}, // rigid-body table — MUST match the draw passes or bodies cull at the wrong place
|
|
2896
3054
|
],
|
|
2897
3055
|
});
|
|
2898
3056
|
this.cullPipe = device.createComputePipeline({
|
|
@@ -3019,6 +3177,7 @@ export class GpuShadowRenderer {
|
|
|
3019
3177
|
{ binding: 2, resource: { buffer: vis } },
|
|
3020
3178
|
{ binding: 3, resource: { buffer: cull } },
|
|
3021
3179
|
{ binding: 4, resource: this.occView },
|
|
3180
|
+
{ binding: CULL_BODY_BINDING, resource: { buffer: this.bodyBuf } },
|
|
3022
3181
|
],
|
|
3023
3182
|
});
|
|
3024
3183
|
}
|
|
@@ -3152,6 +3311,7 @@ export class GpuShadowRenderer {
|
|
|
3152
3311
|
{ binding: 0, resource: { buffer: this.shadowCamBufs[i] } },
|
|
3153
3312
|
{ binding: 1, resource: { buffer: this.instBuf } },
|
|
3154
3313
|
{ binding: 2, resource: { buffer: vis } },
|
|
3314
|
+
{ binding: BODY_BINDING, resource: { buffer: this.bodyBuf } },
|
|
3155
3315
|
],
|
|
3156
3316
|
}));
|
|
3157
3317
|
// One per vertex-count bucket: identical except for the slice of the visible list at binding 4.
|
|
@@ -3175,6 +3335,7 @@ export class GpuShadowRenderer {
|
|
|
3175
3335
|
{ binding: 8, resource: { buffer: this.giGridBuf } },
|
|
3176
3336
|
{ binding: 9, resource: { buffer: this.giProbeBuf } },
|
|
3177
3337
|
{ binding: 10, resource: { buffer: this.facePatchBuf } },
|
|
3338
|
+
{ binding: BODY_BINDING, resource: { buffer: this.bodyBuf } },
|
|
3178
3339
|
],
|
|
3179
3340
|
}));
|
|
3180
3341
|
}
|
|
@@ -3347,6 +3508,38 @@ export class GpuShadowRenderer {
|
|
|
3347
3508
|
setInstanceCount(n) {
|
|
3348
3509
|
this.count = Math.max(0, Math.min(n, (this.scratch.length / INST_F) | 0));
|
|
3349
3510
|
}
|
|
3511
|
+
/**
|
|
3512
|
+
* Give contiguous instance RANGES a rigid transform applied on the GPU, so a body that only moves
|
|
3513
|
+
* costs a ~48-byte table write instead of a re-upload of every cube it owns.
|
|
3514
|
+
*
|
|
3515
|
+
* This is the answer to the orbiting-sky-body cost: a planet is thousands of instances whose
|
|
3516
|
+
* positions relative to each other never change, and re-packing them in world space each frame was
|
|
3517
|
+
* ~283 KB/frame — which also dirtied the shared instance buffer, dragging the untouched terrain
|
|
3518
|
+
* segment's upload along with it. Upload the body ONCE in body-local space (`updateInstanceRange`),
|
|
3519
|
+
* then call this every frame with its orbit.
|
|
3520
|
+
*
|
|
3521
|
+
* r.updateInstanceRange(moonCubesInLocalSpace, 48000) // once
|
|
3522
|
+
* r.setBodyTransforms([{ first: 48000, count: moon.length, pos: orbitPos, rot: spinQuat }]) // per frame
|
|
3523
|
+
*
|
|
3524
|
+
* Ranges must not overlap; the first match wins. Positions are body-local, the transform is
|
|
3525
|
+
* rotate-then-translate, and a body has no scale (use `CubeInstance.sx/sy/sz` for that).
|
|
3526
|
+
*
|
|
3527
|
+
* ⚠️ THE RANGES ARE INSTANCE SLOTS, NOT IDENTITIES. They are matched against the instance's slot in
|
|
3528
|
+
* the buffer, so re-laying-out your segments silently re-parents whatever now occupies those slots.
|
|
3529
|
+
* Reserve fixed capacity per segment — the same discipline `updateInstanceRange` already asks for.
|
|
3530
|
+
*
|
|
3531
|
+
* Pass `[]` to clear. Bodies past the table's capacity (32) are ignored.
|
|
3532
|
+
*/
|
|
3533
|
+
setBodyTransforms(bodies) {
|
|
3534
|
+
const live = packBodyTable(bodies, this.bodyF32, this.bodyU32);
|
|
3535
|
+
// Only the header and the live entries — a stale tail is unreachable past range.y.
|
|
3536
|
+
this.device.queue.writeBuffer(this.bodyBuf, 0, this.bodyF32, 0, (live + 1) * BODY_F);
|
|
3537
|
+
this.bodyCount = live;
|
|
3538
|
+
}
|
|
3539
|
+
/** How many rigid bodies the last `setBodyTransforms` installed. */
|
|
3540
|
+
bodyTransformCount() {
|
|
3541
|
+
return this.bodyCount;
|
|
3542
|
+
}
|
|
3350
3543
|
/** Translucent overlay cubes drawn over the opaque scene; `emissive` carries per-cube alpha (0..1). The buffer
|
|
3351
3544
|
* GROWS to fit (no hard cap). Pass `eye` to SORT the cubes back-to-front (farthest first) so overlapping
|
|
3352
3545
|
* translucent cubes blend in the correct order — required for anything denser than the place ghost. By default
|
|
@@ -3496,7 +3689,16 @@ export class GpuShadowRenderer {
|
|
|
3496
3689
|
/** camVP/lightVP: column-major Float32Array(16). sunDir: travel direction. Pass `occlusion` (the depth target +
|
|
3497
3690
|
* its size) to enable Hi-Z occlusion culling on the camera pass — the renderer rebuilds a coarse Hi-Z from that
|
|
3498
3691
|
* depth each frame and the NEXT frame's cull uses it (hole-free: the first frame + any resize skip occlusion). */
|
|
3499
|
-
frame(enc, colorView, sceneDepth, camVP, lightVP, sunDir, sunCol, ambient, load = false, occlusion, tint = [1, 1, 1, 0], extraShadow,
|
|
3692
|
+
frame(enc, colorView, sceneDepth, camVP, lightVP, sunDir, sunCol, ambient, load = false, occlusion, tint = [1, 1, 1, 0], extraShadow,
|
|
3693
|
+
/**
|
|
3694
|
+
* Dispatch extra CULL work for the cascades, in the same compute pass this frame already opens
|
|
3695
|
+
* for its own cube cull.
|
|
3696
|
+
*
|
|
3697
|
+
* ⚠️ THERE IS NO OTHER PLACE TO PUT IT. `extraShadow` runs inside a RENDER pass, where a compute
|
|
3698
|
+
* dispatch cannot be inserted, and by then the cascade passes are already being encoded — so an
|
|
3699
|
+
* occluder that wants to cull per cascade has to be handed every cascade matrix up front, here.
|
|
3700
|
+
*/
|
|
3701
|
+
extraShadowCull, up = [0, 1, 0], linearOut = false) {
|
|
3500
3702
|
// One matrix or many — a single Float32Array is the 1-cascade case and stays byte-identical.
|
|
3501
3703
|
const mats = Array.isArray(lightVP) ? lightVP : [lightVP];
|
|
3502
3704
|
const nc = Math.max(1, Math.min(MAX_CASCADES, mats.length));
|
|
@@ -3566,15 +3768,22 @@ export class GpuShadowRenderer {
|
|
|
3566
3768
|
this.writeCull(this.camCull, camVP, occludeNow, camBevel);
|
|
3567
3769
|
for (let i = 0; i < nc; i++)
|
|
3568
3770
|
this.writeCull(this.lightCull[i], mats[i], false);
|
|
3569
|
-
|
|
3771
|
+
// ⚠️ THE PASS OPENS FOR EITHER REASON. It used to be gated on `this.count > 0` alone, which is
|
|
3772
|
+
// right for the cube cull and wrong for a caller's: a scene with no cubes but a forest of props
|
|
3773
|
+
// still needs somewhere to dispatch. Gating on both keeps the empty-scene case free.
|
|
3774
|
+
if (this.count > 0 || extraShadowCull) {
|
|
3570
3775
|
const cp = enc.beginComputePass();
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
for (let i = 0; i < nc; i++) {
|
|
3575
|
-
cp.setBindGroup(0, this.lightCullBG[i]);
|
|
3776
|
+
if (this.count > 0) {
|
|
3777
|
+
cp.setPipeline(this.cullPipe);
|
|
3778
|
+
cp.setBindGroup(0, this.camCullBG);
|
|
3576
3779
|
cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
|
|
3780
|
+
for (let i = 0; i < nc; i++) {
|
|
3781
|
+
cp.setBindGroup(0, this.lightCullBG[i]);
|
|
3782
|
+
cp.dispatchWorkgroups(Math.ceil(this.count / CULL_WG));
|
|
3783
|
+
}
|
|
3577
3784
|
}
|
|
3785
|
+
if (extraShadowCull)
|
|
3786
|
+
extraShadowCull(cp, mats.slice(0, nc));
|
|
3578
3787
|
cp.end();
|
|
3579
3788
|
}
|
|
3580
3789
|
// Pass 1: occluder depth from the sun — one pass per cascade, into its own array layer.
|
|
@@ -3594,7 +3803,7 @@ export class GpuShadowRenderer {
|
|
|
3594
3803
|
// The app casts its own occluders (mesh props/trees) into EVERY cascade — an occluder missing
|
|
3595
3804
|
// from a far cascade would leave a tree lit at distance while its neighbours are shadowed.
|
|
3596
3805
|
if (extraShadow)
|
|
3597
|
-
extraShadow(sp, mats[i]);
|
|
3806
|
+
extraShadow(sp, mats[i], i);
|
|
3598
3807
|
sp.end();
|
|
3599
3808
|
}
|
|
3600
3809
|
// 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.
|
|
3
|
+
"version": "0.15.23",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -15,20 +15,6 @@
|
|
|
15
15
|
"files": [
|
|
16
16
|
"dist"
|
|
17
17
|
],
|
|
18
|
-
"scripts": {
|
|
19
|
-
"preinstall": "npx only-allow pnpm",
|
|
20
|
-
"build": "tsc -p tsconfig.json && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/",
|
|
21
|
-
"lint": "ugly-app lint",
|
|
22
|
-
"lint:fix": "ugly-app lint --fix",
|
|
23
|
-
"lint:wgsl": "node --experimental-strip-types tools/wgslGuard.mts && node --experimental-strip-types tools/wgslLint.mts",
|
|
24
|
-
"test": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/*.test.mts",
|
|
25
|
-
"test:flight": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/flight*.test.mts",
|
|
26
|
-
"test:flight-browser": "playwright test -c playwright.flight.config.ts",
|
|
27
|
-
"test:flight-perf": "playwright test -c playwright.flight.config.ts --grep 'CPU and retained-memory'",
|
|
28
|
-
"test:types": "tsc -p tsconfig.test.json",
|
|
29
|
-
"pretty": "prettier --write .",
|
|
30
|
-
"prepublishOnly": "pnpm run pretty && ugly-app lint && tsc -p tsconfig.json && pnpm run lint:wgsl && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/"
|
|
31
|
-
},
|
|
32
18
|
"dependencies": {
|
|
33
19
|
"meshoptimizer": "^1.2.0"
|
|
34
20
|
},
|
|
@@ -44,5 +30,18 @@
|
|
|
44
30
|
"typescript": "^5.6.0",
|
|
45
31
|
"ugly-app": "^0.1.841",
|
|
46
32
|
"wesl": "0.7.28"
|
|
33
|
+
},
|
|
34
|
+
"scripts": {
|
|
35
|
+
"preinstall": "npx only-allow pnpm",
|
|
36
|
+
"build": "tsc -p tsconfig.json && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/",
|
|
37
|
+
"lint": "ugly-app lint",
|
|
38
|
+
"lint:fix": "ugly-app lint --fix",
|
|
39
|
+
"lint:wgsl": "node --experimental-strip-types tools/wgslGuard.mts && node --experimental-strip-types tools/wgslLint.mts",
|
|
40
|
+
"test": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/*.test.mts",
|
|
41
|
+
"test:flight": "node --experimental-strip-types --import ./tools/tsResolve.mjs --test src/flight*.test.mts",
|
|
42
|
+
"test:flight-browser": "playwright test -c playwright.flight.config.ts",
|
|
43
|
+
"test:flight-perf": "playwright test -c playwright.flight.config.ts --grep 'CPU and retained-memory'",
|
|
44
|
+
"test:types": "tsc -p tsconfig.test.json",
|
|
45
|
+
"pretty": "prettier --write ."
|
|
47
46
|
}
|
|
48
|
-
}
|
|
47
|
+
}
|