@playcanvas/supersplat-viewer 1.35.2 → 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const TRACEID_GPU_TIMINGS = "GpuTimings";
2
2
 
3
- const version$1 = "2.22.4";
4
- const revision = "b5b9839";
3
+ const version$1 = "2.22.5";
4
+ const revision = "1069984";
5
5
  function extend(target, ex) {
6
6
  for (const prop in ex) {
7
7
  const copy = ex[prop];
@@ -27150,7 +27150,7 @@ class LayerComposition extends EventHandler {
27150
27150
  }
27151
27151
  }
27152
27152
 
27153
- const tmpVec = new Vec3();
27153
+ const tmpVec$1 = new Vec3();
27154
27154
  const tmpBiases = {
27155
27155
  bias: 0,
27156
27156
  normalBias: 0
@@ -27826,15 +27826,15 @@ class Light {
27826
27826
  const angle = this._outerConeAngle;
27827
27827
  const cosAngle = this._outerConeAngleCos;
27828
27828
  const node = this._node;
27829
- tmpVec.copy(node.up);
27829
+ tmpVec$1.copy(node.up);
27830
27830
  if (angle > 45) {
27831
27831
  sphere.radius = size * this._outerConeAngleSin;
27832
- tmpVec.mulScalar(-size * cosAngle);
27832
+ tmpVec$1.mulScalar(-size * cosAngle);
27833
27833
  } else {
27834
27834
  sphere.radius = size / (2 * cosAngle);
27835
- tmpVec.mulScalar(-sphere.radius);
27835
+ tmpVec$1.mulScalar(-sphere.radius);
27836
27836
  }
27837
- sphere.center.add2(node.getPosition(), tmpVec);
27837
+ sphere.center.add2(node.getPosition(), tmpVec$1);
27838
27838
  } else if (this._type === LIGHTTYPE_OMNI) {
27839
27839
  sphere.center.copy(this._node.getPosition());
27840
27840
  sphere.radius = this.attenuationEnd;
@@ -61349,7 +61349,7 @@ fn gsplatGetSizeFromScale(scale: vec3f) -> f32 {
61349
61349
  `;
61350
61350
 
61351
61351
  const INDEX_COUNT$2 = 6 * GSplatResourceBase.instanceSize;
61352
- const PROJECTOR_WORKGROUP_SIZE = 256;
61352
+ const PROJECTOR_WORKGROUP_SIZE$1 = 256;
61353
61353
  const PROJECTOR_INTERNAL_DEFINES = /* @__PURE__ */ new Set([
61354
61354
  "{CACHE_STRIDE}",
61355
61355
  "RADIAL_SORT",
@@ -61730,7 +61730,7 @@ class GSplatProjector {
61730
61730
  compute.setParameter("fisheye_projMat00", fisheyeProj.projMat00);
61731
61731
  compute.setParameter("fisheye_projMat11", fisheyeProj.projMat11);
61732
61732
  }
61733
- const workgroupCount = Math.ceil(totalCapacity / PROJECTOR_WORKGROUP_SIZE);
61733
+ const workgroupCount = Math.ceil(totalCapacity / PROJECTOR_WORKGROUP_SIZE$1);
61734
61734
  Compute.calcDispatchSize(
61735
61735
  workgroupCount,
61736
61736
  _dispatchSize,
@@ -62355,7 +62355,6 @@ class GSplatHybridRenderer extends GSplatRenderer {
62355
62355
  return true;
62356
62356
  }
62357
62357
  preparePickingView(world, worldState, pickParams) {
62358
- const pickMode = !!world.workBuffer.format.getStream("pcId");
62359
62358
  const sortedIndices = this.sortAndProjectForCamera(
62360
62359
  world,
62361
62360
  worldState,
@@ -62363,7 +62362,7 @@ class GSplatHybridRenderer extends GSplatRenderer {
62363
62362
  pickParams.width,
62364
62363
  pickParams.height,
62365
62364
  Math.max(ALPHA_VISIBILITY_THRESHOLD, pickParams.alphaClip),
62366
- pickMode,
62365
+ true,
62367
62366
  false,
62368
62367
  pickParams
62369
62368
  );
@@ -62378,9 +62377,10 @@ class GSplatHybridRenderer extends GSplatRenderer {
62378
62377
  pickParams.cameraNode
62379
62378
  );
62380
62379
  }
62381
- sortAndProjectForCamera(world, worldState, cameraNode, viewportWidth, viewportHeight, alphaClip, pickMode, isStereo, params) {
62380
+ sortAndProjectForCamera(world, worldState, cameraNode, viewportWidth, viewportHeight, alphaClip, isPicking, isStereo, params) {
62382
62381
  const elementCount = worldState.totalActiveSplats;
62383
62382
  if (elementCount === 0) return null;
62383
+ const pickMode = isPicking && !!world.workBuffer.format.getStream("pcId");
62384
62384
  this._ensureGpuPipeline();
62385
62385
  const gpuSorter = this.gpuSorter;
62386
62386
  const projector = this.projector;
@@ -62434,7 +62434,7 @@ class GSplatHybridRenderer extends GSplatRenderer {
62434
62434
  ic.sortElementCountBuffer,
62435
62435
  sortIndirectInfo
62436
62436
  );
62437
- if (pickMode) {
62437
+ if (isPicking) {
62438
62438
  this.device.submit();
62439
62439
  }
62440
62440
  return gpuSorter.sortIndirect(
@@ -83843,7 +83843,7 @@ const importSettings = (settings) => {
83843
83843
  return result;
83844
83844
  };
83845
83845
 
83846
- var version = "1.35.2";
83846
+ var version = "1.36.0";
83847
83847
 
83848
83848
  class Tooltip {
83849
83849
  register;
@@ -88505,6 +88505,132 @@ const fitPlaneNormal = (points, toCamera, outNormal) => {
88505
88505
  outNormal.set(vx, vy, vz);
88506
88506
  return true;
88507
88507
  };
88508
+ // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a small
88509
+ // disc, which is the depth where the opacity in front reaches that. Null where it never does.
88510
+ const surfaceDepth = (depthAt, x, y) => {
88511
+ const samples = [];
88512
+ for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
88513
+ for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
88514
+ if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
88515
+ continue;
88516
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
88517
+ const depth = depthAt(x + dx, y + dy, trial);
88518
+ if (depth !== null)
88519
+ samples.push(depth);
88520
+ }
88521
+ }
88522
+ }
88523
+ if (samples.length === 0) {
88524
+ return null;
88525
+ }
88526
+ samples.sort((a, b) => a - b);
88527
+ const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
88528
+ return Number.isFinite(depth) && depth < 1 ? depth : null;
88529
+ };
88530
+ // The surface under a pixel and its normal, fitted through surface points on rings around it.
88531
+ // `depthAt` must cover NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX around the pixel.
88532
+ const estimateSurface = (depthAt, pickCamera, width, height, screenX, screenY) => {
88533
+ const surfacePoint = (px, py) => {
88534
+ const depth = surfaceDepth(depthAt, px, py);
88535
+ return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
88536
+ };
88537
+ const position = surfacePoint(screenX, screenY);
88538
+ if (!position) {
88539
+ return null;
88540
+ }
88541
+ const samplePixel = (px, py) => {
88542
+ if (px < 0 || px >= width || py < 0 || py >= height) {
88543
+ return null;
88544
+ }
88545
+ return surfacePoint(px, py);
88546
+ };
88547
+ // Pixel radius corresponding to a fixed world radius at the
88548
+ // picked-point's depth. Clamped so distant picks still sample
88549
+ // enough pixels and very-close picks stay inside the block read.
88550
+ const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
88551
+ const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
88552
+ const sampleRings = ringPixelRadii.map((radius) => {
88553
+ return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
88554
+ return samplePixel(screenX + dx * radius, screenY + dy * radius);
88555
+ });
88556
+ });
88557
+ const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
88558
+ // Collect every valid 3D sample: the picked position plus all ring
88559
+ // samples that didn't fall off-screen or find no surface.
88560
+ const fitPoints = [position];
88561
+ for (let i = 0; i < sampleRings.length; i++) {
88562
+ const ring = sampleRings[i];
88563
+ for (let j = 0; j < ring.length; j++) {
88564
+ const pt = ring[j];
88565
+ if (pt)
88566
+ fitPoints.push(pt);
88567
+ }
88568
+ }
88569
+ const normal = new Vec3();
88570
+ if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
88571
+ normal.copy(toCamera);
88572
+ }
88573
+ return {
88574
+ position,
88575
+ normal
88576
+ };
88577
+ };
88578
+ // The share of samples over a disc of `r` pixels whose nearest survivor is nearer than the view
88579
+ // depth `depth`; null where the disc has no samples. `depthAt` must cover the disc.
88580
+ const opacityInFront = (depthAt, pickCamera, screenX, screenY, r, depth) => {
88581
+ const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
88582
+ let total = 0;
88583
+ let inFront = 0;
88584
+ for (let dy = -r; dy <= r; dy++) {
88585
+ for (let dx = -r; dx <= r; dx++) {
88586
+ if (dx * dx + dy * dy > r * r)
88587
+ continue;
88588
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
88589
+ const nearest = depthAt(screenX + dx, screenY + dy, trial);
88590
+ if (nearest === null)
88591
+ continue;
88592
+ total++;
88593
+ if (nearest < threshold)
88594
+ inFront++;
88595
+ }
88596
+ }
88597
+ }
88598
+ return total > 0 ? inFront / total : null;
88599
+ };
88600
+ // One pick pixel per css pixel, never more than the backbuffer has: picking then behaves the
88601
+ // same in performance mode and at any device pixel ratio, since the pixel sizes above are css
88602
+ // pixels, and a high-density display does not multiply the pass's cost. Null before the device
88603
+ // or the canvas has been sized.
88604
+ const pickTargetSize = (graphicsDevice) => {
88605
+ const canvas = graphicsDevice.canvas;
88606
+ const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
88607
+ const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
88608
+ return width > 0 && height > 0 ? { width, height } : null;
88609
+ };
88610
+ const clampPixel = (v, size) => Math.min(size - 1, Math.max(0, Math.floor(v * size)));
88611
+ // Picks run one at a time, since they share one render. `fallback` is the result for a pick
88612
+ // that release overtakes: one queued behind another pick, or one whose read-back is cut short
88613
+ // as the device goes.
88614
+ class PickQueue {
88615
+ released = false;
88616
+ queue = Promise.resolve();
88617
+ run(operation, fallback) {
88618
+ const guarded = () => {
88619
+ if (this.released) {
88620
+ return Promise.resolve(fallback);
88621
+ }
88622
+ return operation().catch((error) => {
88623
+ if (this.released) {
88624
+ return fallback;
88625
+ }
88626
+ throw error;
88627
+ });
88628
+ };
88629
+ const result = this.queue.then(guarded, guarded);
88630
+ this.queue = result.then(() => undefined, () => undefined);
88631
+ return result;
88632
+ }
88633
+ }
88508
88634
  class Picker {
88509
88635
  pick;
88510
88636
  pickSurface;
@@ -88533,10 +88659,7 @@ class Picker {
88533
88659
  let pickTarget;
88534
88660
  let pickPass;
88535
88661
  let chunksPatched = false;
88536
- // set by release: queued and in-flight picks then resolve to nothing, rather than render
88537
- // with released resources or reach an app that is being destroyed
88538
- let released = false;
88539
- let pickQueue = Promise.resolve();
88662
+ const queue = new PickQueue();
88540
88663
  let cacheValid = false;
88541
88664
  let renders = 0;
88542
88665
  let cacheWidth = 0;
@@ -88589,8 +88712,6 @@ class Picker {
88589
88712
  return snapshot;
88590
88713
  };
88591
88714
  // Read the pick render around a pixel, `margin` pixels each way, clamped to the render.
88592
- // The accessor returns a pixel's nearest surviving normalised depth in one of its
88593
- // PICK_TRIALS trials, 1 where no fragment survived, or null outside the block.
88594
88715
  const readAround = async (screenX, screenY, margin, width, height) => {
88595
88716
  const blockX = Math.max(0, screenX - margin);
88596
88717
  const blockY = Math.max(0, screenY - margin);
@@ -88611,29 +88732,6 @@ class Picker {
88611
88732
  return half2Float(pixels[(row * blockWidth + localX) * 4 + trial]);
88612
88733
  };
88613
88734
  };
88614
- // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a
88615
- // small disc, which is the depth where the opacity in front reaches that. Null where it
88616
- // never does.
88617
- const surfaceDepth = (depthAt, x, y) => {
88618
- const samples = [];
88619
- for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
88620
- for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
88621
- if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
88622
- continue;
88623
- for (let trial = 0; trial < PICK_TRIALS; trial++) {
88624
- const depth = depthAt(x + dx, y + dy, trial);
88625
- if (depth !== null)
88626
- samples.push(depth);
88627
- }
88628
- }
88629
- }
88630
- if (samples.length === 0) {
88631
- return null;
88632
- }
88633
- samples.sort((a, b) => a - b);
88634
- const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
88635
- return Number.isFinite(depth) && depth < 1 ? depth : null;
88636
- };
88637
88735
  const ensureRendered = (width, height, worldLayer) => {
88638
88736
  if (cameraMatches(width, height)) {
88639
88737
  return;
@@ -88660,49 +88758,24 @@ class Picker {
88660
88758
  renders++;
88661
88759
  };
88662
88760
  const prepareSample = (x, y) => {
88663
- if (released) {
88761
+ if (queue.released) {
88664
88762
  return null;
88665
88763
  }
88666
- // One pick pixel per css pixel, never more than the backbuffer has: picking then
88667
- // behaves the same in performance mode and at any device pixel ratio, since the
88668
- // pixel sizes above are css pixels, and a high-density display does not multiply
88669
- // the pass's cost
88670
- const canvas = graphicsDevice.canvas;
88671
- const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
88672
- const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
88673
- // bail out if the device or the canvas hasn't been sized yet
88674
- if (width <= 0 || height <= 0) {
88764
+ const size = pickTargetSize(graphicsDevice);
88765
+ if (!size) {
88675
88766
  return null;
88676
88767
  }
88768
+ const { width, height } = size;
88677
88769
  const worldLayer = app.scene.layers.getLayerByName('World');
88678
88770
  if (!worldLayer) {
88679
88771
  return null;
88680
88772
  }
88681
- const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
88682
- const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
88773
+ const screenX = clampPixel(x, width);
88774
+ const screenY = clampPixel(y, height);
88683
88775
  ensureRendered(width, height, worldLayer);
88684
88776
  const pickCamera = getCacheCameraSnapshot();
88685
88777
  return { width, height, screenX, screenY, pickCamera };
88686
88778
  };
88687
- // `fallback` is the result for a pick that release overtakes: one queued behind another
88688
- // pick, or one whose read-back is cut short as the device goes
88689
- const serializePick = (operation, fallback) => {
88690
- const guarded = () => {
88691
- if (released) {
88692
- return Promise.resolve(fallback);
88693
- }
88694
- return operation().catch((error) => {
88695
- if (released) {
88696
- return fallback;
88697
- }
88698
- throw error;
88699
- });
88700
- };
88701
- // The render target is shared by all picks on this instance.
88702
- const result = pickQueue.then(guarded, guarded);
88703
- pickQueue = result.then(() => undefined, () => undefined);
88704
- return result;
88705
- };
88706
88779
  const pick = async (x, y) => {
88707
88780
  const sample = prepareSample(x, y);
88708
88781
  if (!sample) {
@@ -88723,50 +88796,7 @@ class Picker {
88723
88796
  // Sized to the maximum possible ring pixel-radius, plus the surface disc around each
88724
88797
  // sample, so the dynamic ring offsets always lie inside the buffer we read.
88725
88798
  const depthAt = await readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
88726
- const surfacePoint = (px, py) => {
88727
- const depth = surfaceDepth(depthAt, px, py);
88728
- return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
88729
- };
88730
- const position = surfacePoint(screenX, screenY);
88731
- if (!position) {
88732
- return null;
88733
- }
88734
- const samplePixel = (px, py) => {
88735
- if (px < 0 || px >= width || py < 0 || py >= height) {
88736
- return null;
88737
- }
88738
- return surfacePoint(px, py);
88739
- };
88740
- // Pixel radius corresponding to a fixed world radius at the
88741
- // picked-point's depth. Clamped so distant picks still sample
88742
- // enough pixels and very-close picks stay inside the block read.
88743
- const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
88744
- const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
88745
- const sampleRings = ringPixelRadii.map((radius) => {
88746
- return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
88747
- return samplePixel(screenX + dx * radius, screenY + dy * radius);
88748
- });
88749
- });
88750
- const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
88751
- // Collect every valid 3D sample: the picked position plus all ring
88752
- // samples that didn't fall off-screen or find no surface.
88753
- const fitPoints = [position];
88754
- for (let i = 0; i < sampleRings.length; i++) {
88755
- const ring = sampleRings[i];
88756
- for (let j = 0; j < ring.length; j++) {
88757
- const pt = ring[j];
88758
- if (pt)
88759
- fitPoints.push(pt);
88760
- }
88761
- }
88762
- const normal = new Vec3();
88763
- if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
88764
- normal.copy(toCamera);
88765
- }
88766
- return {
88767
- position,
88768
- normal
88769
- };
88799
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
88770
88800
  };
88771
88801
  const pickVisibility = async (points, radius) => {
88772
88802
  if (points.length === 0) {
@@ -88782,29 +88812,12 @@ class Picker {
88782
88812
  const { width, height, screenX, screenY, pickCamera } = sample;
88783
88813
  const r = Math.max(1, Math.round(radius * height));
88784
88814
  const depthAt = await readAround(screenX, screenY, r, width, height);
88785
- const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
88786
- let total = 0;
88787
- let inFront = 0;
88788
- for (let dy = -r; dy <= r; dy++) {
88789
- for (let dx = -r; dx <= r; dx++) {
88790
- if (dx * dx + dy * dy > r * r)
88791
- continue;
88792
- for (let trial = 0; trial < PICK_TRIALS; trial++) {
88793
- const nearest = depthAt(screenX + dx, screenY + dy, trial);
88794
- if (nearest === null)
88795
- continue;
88796
- total++;
88797
- if (nearest < threshold)
88798
- inFront++;
88799
- }
88800
- }
88801
- }
88802
- return total > 0 ? inFront / total : null;
88815
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
88803
88816
  }));
88804
88817
  };
88805
- this.pick = (x, y) => serializePick(() => pick(x, y), null);
88806
- this.pickSurface = (x, y) => serializePick(() => pickSurface(x, y), null);
88807
- this.pickVisibility = (points, radius) => serializePick(() => pickVisibility(points, radius), points.map(() => null));
88818
+ this.pick = (x, y) => queue.run(() => pick(x, y), null);
88819
+ this.pickSurface = (x, y) => queue.run(() => pickSurface(x, y), null);
88820
+ this.pickVisibility = (points, radius) => queue.run(() => pickVisibility(points, radius), points.map(() => null));
88808
88821
  this.renderView = () => (prepareSample(0, 0) ? { texture: pickBuffer, renders } : null);
88809
88822
  // The scene can change under a still camera, which the camera-based cache cannot see:
88810
88823
  // finer detail streams in after the reveal and after every move. The engine reports each
@@ -88823,7 +88836,7 @@ class Picker {
88823
88836
  };
88824
88837
  gsplatSystem.on('frame:ready', onFrameReady);
88825
88838
  this.release = () => {
88826
- released = true;
88839
+ queue.released = true;
88827
88840
  gsplatSystem.off('frame:ready', onFrameReady);
88828
88841
  if (chunksPatched) {
88829
88842
  unregisterPickerShaderPatches(app);
@@ -89194,6 +89207,20 @@ const STYLES = `
89194
89207
  .${PANEL_CLASS} button.sse-flash {
89195
89208
  background: rgba(120, 220, 140, 0.35);
89196
89209
  }
89210
+ .${PANEL_CLASS} button.sse-flash-bad {
89211
+ background: rgba(220, 100, 100, 0.45);
89212
+ }
89213
+ .${PANEL_CLASS} input.sse-debug-paste {
89214
+ width: 100%;
89215
+ box-sizing: border-box;
89216
+ margin-top: 6px;
89217
+ background: rgba(255, 255, 255, 0.08);
89218
+ color: #eee;
89219
+ border: 1px solid rgba(120, 180, 255, 0.6);
89220
+ border-radius: 3px;
89221
+ padding: 4px 8px;
89222
+ font: inherit;
89223
+ }
89197
89224
  .${PANEL_CLASS} button.sse-debug-on {
89198
89225
  background: rgba(120, 180, 255, 0.35);
89199
89226
  }
@@ -89216,6 +89243,14 @@ class DebugPanel {
89216
89243
  _global;
89217
89244
  _cameraManager;
89218
89245
  _picker;
89246
+ // the stochastic renderer when this viewer opted in, for its depth cull toggle and counts
89247
+ _splatRenderer;
89248
+ _cullButton = null;
89249
+ _taaButton = null;
89250
+ _poplessButton = null;
89251
+ _culledValue = null;
89252
+ _cullStatsFrames = 0;
89253
+ _cullStatsPending = false;
89219
89254
  _pickDepthOverlay = null;
89220
89255
  _focusTmp = new Vec3();
89221
89256
  _root = null;
@@ -89224,12 +89259,20 @@ class DebugPanel {
89224
89259
  _focusValue = null;
89225
89260
  _copyButton = null;
89226
89261
  _pasteButton = null;
89262
+ // shown when the clipboard cannot be read (a cross-origin iframe without clipboard-read):
89263
+ // the paste event of a focused field carries the text without that permission
89264
+ _pasteField = null;
89265
+ _miniStatsButton = null;
89266
+ // the viewer's MiniStats switch
89267
+ _miniStats;
89227
89268
  _screenshotButton = null;
89228
89269
  _pickDepthButton = null;
89229
89270
  _editing = null;
89230
89271
  _editCanceled = false;
89231
89272
  _visible = false;
89232
89273
  _onPrerender = () => this._render();
89274
+ // the cull state is decided inside the frame, so its row refreshes after it
89275
+ _onFrameEnd = () => this._renderCull();
89233
89276
  _onKeyDown = (event) => {
89234
89277
  // Ctrl+Shift+D — also accept Meta+Shift+D on macOS for parity
89235
89278
  if (!this._global.state.inputEnabled)
@@ -89239,10 +89282,12 @@ class DebugPanel {
89239
89282
  this.toggle();
89240
89283
  }
89241
89284
  };
89242
- constructor(global, cameraManager, picker) {
89285
+ constructor(global, cameraManager, picker, splatRenderer = null, miniStats = null) {
89243
89286
  this._global = global;
89244
89287
  this._cameraManager = cameraManager;
89245
89288
  this._picker = picker;
89289
+ this._splatRenderer = splatRenderer;
89290
+ this._miniStats = miniStats;
89246
89291
  window.addEventListener('keydown', this._onKeyDown);
89247
89292
  if (global.config.debug) {
89248
89293
  this.show();
@@ -89257,6 +89302,7 @@ class DebugPanel {
89257
89302
  }
89258
89303
  this._root.style.display = '';
89259
89304
  this._global.app.on('prerender', this._onPrerender);
89305
+ this._global.app.on('frameend', this._onFrameEnd);
89260
89306
  if (this._global.config.exposeGlobals) {
89261
89307
  window.getCameraState = () => captureCameraState(this._cameraManager, this._global.state);
89262
89308
  window.setCameraState = (snapshot) => restoreCameraState(this._cameraManager, this._global.state, snapshot);
@@ -89273,6 +89319,7 @@ class DebugPanel {
89273
89319
  // the view is only reachable from the panel, so it goes with it
89274
89320
  this._setPickDepth(false);
89275
89321
  this._global.app.off('prerender', this._onPrerender);
89322
+ this._global.app.off('frameend', this._onFrameEnd);
89276
89323
  if (this._global.config.exposeGlobals) {
89277
89324
  delete window.getCameraState;
89278
89325
  delete window.setCameraState;
@@ -89317,8 +89364,19 @@ class DebugPanel {
89317
89364
  </div>
89318
89365
  <div class="sse-debug-buttons">
89319
89366
  <button data-id="screenshot">Screenshot</button>
89320
- <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Pick depth</button>
89367
+ <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Show depth</button>
89368
+ <button data-id="ministats" title="Show the engine's MiniStats graphs (the viewer then renders every frame)">MiniStats</button>
89369
+ </div>
89370
+ <input class="sse-debug-paste" data-id="paste-field" placeholder="Clipboard blocked here: paste with Ctrl/Cmd+V" spellcheck="false" style="display: none">
89371
+ ${this._splatRenderer
89372
+ ? `
89373
+ <div class="sse-debug-buttons">
89374
+ <button data-id="depth-cull" title="Stochastic renderer: cull splats hidden in the previous frame's depth (auto suspends the test when it removes too little)">Depth cull</button>
89375
+ <button data-id="taa" title="Stochastic renderer: accumulate the samples over frames (reprojected while the camera moves)">TAA</button>
89376
+ <button data-id="popless" title="Stochastic renderer: give each fragment the depth of the Gaussian's peak along its ray, rather than the splat centre's">Popless</button>
89321
89377
  </div>
89378
+ <div class="sse-debug-row"><span class="sse-debug-label">culled</span><span class="sse-debug-value" data-id="culled">—</span></div>`
89379
+ : ''}
89322
89380
  `;
89323
89381
  host.appendChild(root);
89324
89382
  this._root = root;
@@ -89328,12 +89386,52 @@ class DebugPanel {
89328
89386
  this._pasteButton = root.querySelector('[data-id="paste"]');
89329
89387
  this._screenshotButton = root.querySelector('[data-id="screenshot"]');
89330
89388
  this._pickDepthButton = root.querySelector('[data-id="pick-depth"]');
89389
+ this._miniStatsButton = root.querySelector('[data-id="ministats"]');
89390
+ this._pasteField = root.querySelector('[data-id="paste-field"]');
89391
+ this._wirePasteField(this._pasteField);
89392
+ if (this._miniStats) {
89393
+ this._miniStatsButton.addEventListener('click', () => {
89394
+ this._miniStats.show(!this._miniStats.shown());
89395
+ this._renderMiniStats();
89396
+ });
89397
+ this._renderMiniStats();
89398
+ }
89399
+ else {
89400
+ this._miniStatsButton.remove();
89401
+ }
89331
89402
  this._copyButton.addEventListener('click', () => this._copy());
89332
89403
  this._pasteButton.addEventListener('click', () => this._paste());
89333
89404
  this._screenshotButton.addEventListener('click', () => this._screenshot());
89334
89405
  this._pickDepthButton.addEventListener('click', () => {
89335
89406
  this._setPickDepth(!this._pickDepthOverlay?.enabled);
89336
89407
  });
89408
+ if (this._splatRenderer) {
89409
+ this._cullButton = root.querySelector('[data-id="depth-cull"]');
89410
+ this._taaButton = root.querySelector('[data-id="taa"]');
89411
+ this._poplessButton = root.querySelector('[data-id="popless"]');
89412
+ this._poplessButton.addEventListener('click', () => {
89413
+ const renderer = this._splatRenderer;
89414
+ renderer.variant.popless = renderer.variant.popless === 'on' ? 'off' : 'on';
89415
+ renderer.applyVariant();
89416
+ this._renderCull();
89417
+ });
89418
+ this._culledValue = root.querySelector('[data-id="culled"]');
89419
+ this._taaButton.addEventListener('click', () => {
89420
+ const renderer = this._splatRenderer;
89421
+ renderer.variant.taa = renderer.variant.taa === 'on' ? 'off' : 'on';
89422
+ renderer.applyVariant();
89423
+ this._renderCull();
89424
+ });
89425
+ // cycles the cull mode: auto (the default) -> on (both grid levels) -> off
89426
+ this._cullButton.addEventListener('click', () => {
89427
+ const renderer = this._splatRenderer;
89428
+ const next = { auto: 'l2', l2: 'off', l1: 'off', off: 'auto' };
89429
+ renderer.variant.cull = next[renderer.variant.cull];
89430
+ renderer.applyVariant();
89431
+ this._renderCull();
89432
+ });
89433
+ this._renderCull();
89434
+ }
89337
89435
  this._wireEditable(this._positionValue, 'position');
89338
89436
  this._wireEditable(this._focusValue, 'focus');
89339
89437
  }
@@ -89429,27 +89527,153 @@ class DebugPanel {
89429
89527
  this._focusValue.textContent = fmt(this._focusTmp);
89430
89528
  }
89431
89529
  }
89530
+ // the cull button shows the mode; the counts come back from the gpu every few frames
89531
+ _renderCull() {
89532
+ const renderer = this._splatRenderer;
89533
+ if (!renderer || !this._cullButton || !this._culledValue)
89534
+ return;
89535
+ const mode = renderer.variant.cull;
89536
+ this._cullButton.textContent = `Depth cull: ${mode === 'off' ? 'off' : mode === 'auto' ? 'auto' : 'on'}`;
89537
+ this._cullButton.classList.toggle('sse-debug-on', mode !== 'off');
89538
+ if (this._taaButton) {
89539
+ this._taaButton.textContent = `TAA: ${renderer.variant.taa}`;
89540
+ this._taaButton.classList.toggle('sse-debug-on', renderer.variant.taa === 'on');
89541
+ }
89542
+ if (this._poplessButton) {
89543
+ this._poplessButton.textContent = `Popless: ${renderer.variant.popless}`;
89544
+ this._poplessButton.classList.toggle('sse-debug-on', renderer.variant.popless === 'on');
89545
+ }
89546
+ if (mode === 'off') {
89547
+ this._culledValue.textContent = 'off';
89548
+ return;
89549
+ }
89550
+ if (!renderer.culling) {
89551
+ this._culledValue.textContent = renderer.cullSuspended ? 'suspended' : 'no previous frame';
89552
+ return;
89553
+ }
89554
+ if (this._cullStatsPending || this._cullStatsFrames++ % 15 !== 0)
89555
+ return;
89556
+ this._cullStatsPending = true;
89557
+ renderer
89558
+ .readStats()
89559
+ .then(({ survivors, occluded }) => {
89560
+ const total = survivors + occluded;
89561
+ const pct = total > 0 ? ((100 * occluded) / total).toFixed(0) : '0';
89562
+ if (this._culledValue && renderer.culling) {
89563
+ this._culledValue.textContent = `${pct}% (${occluded.toLocaleString()} of ${total.toLocaleString()})`;
89564
+ }
89565
+ })
89566
+ .catch(() => {
89567
+ // a destroyed buffer or lost device; the next refresh tries again
89568
+ })
89569
+ .finally(() => {
89570
+ this._cullStatsPending = false;
89571
+ });
89572
+ }
89573
+ // The clipboard api, else a selection copied with execCommand: the api is refused in a
89574
+ // cross-origin iframe without clipboard-write (superspl.at's local-frontend frame), while
89575
+ // the command still works there inside the click
89432
89576
  async _copy() {
89433
- const snapshot = captureCameraState(this._cameraManager, this._global.state);
89577
+ const text = JSON.stringify(captureCameraState(this._cameraManager, this._global.state));
89578
+ let copied = false;
89434
89579
  try {
89435
- await navigator.clipboard.writeText(JSON.stringify(snapshot));
89580
+ await navigator.clipboard.writeText(text);
89581
+ copied = true;
89582
+ }
89583
+ catch {
89584
+ // destroyed while the clipboard was refusing
89585
+ if (!this._root)
89586
+ return;
89587
+ const area = document.createElement('textarea');
89588
+ area.value = text;
89589
+ area.style.cssText = 'position: fixed; opacity: 0; pointer-events: none';
89590
+ this._root.appendChild(area);
89591
+ area.select();
89592
+ try {
89593
+ copied = document.execCommand('copy');
89594
+ }
89595
+ catch {
89596
+ copied = false;
89597
+ }
89598
+ area.remove();
89599
+ }
89600
+ if (copied) {
89436
89601
  this._flash(this._copyButton);
89437
89602
  }
89438
- catch (err) {
89439
- console.warn('[debug-panel] copy failed', err);
89603
+ else {
89604
+ console.warn('[debug-panel] copy failed');
89605
+ this._flashBad(this._copyButton);
89440
89606
  }
89441
89607
  }
89608
+ // The clipboard api, else the paste field: reading needs clipboard-read, which a
89609
+ // cross-origin iframe only has when its embedder grants it
89442
89610
  async _paste() {
89611
+ let text;
89612
+ try {
89613
+ text = await navigator.clipboard.readText();
89614
+ }
89615
+ catch {
89616
+ this._showPasteField(true);
89617
+ return;
89618
+ }
89619
+ // destroyed while the clipboard was being read
89620
+ if (!this._root)
89621
+ return;
89622
+ this._applyPasted(text);
89623
+ }
89624
+ _applyPasted(text) {
89443
89625
  try {
89444
- const text = await navigator.clipboard.readText();
89445
89626
  const snapshot = JSON.parse(text);
89446
89627
  restoreCameraState(this._cameraManager, this._global.state, snapshot);
89447
89628
  this._flash(this._pasteButton);
89448
89629
  }
89449
89630
  catch (err) {
89450
89631
  console.warn('[debug-panel] paste failed', err);
89632
+ this._flashBad(this._pasteButton);
89451
89633
  }
89452
89634
  }
89635
+ _showPasteField(value) {
89636
+ const field = this._pasteField;
89637
+ if (!field)
89638
+ return;
89639
+ field.value = '';
89640
+ field.style.display = value ? '' : 'none';
89641
+ if (value)
89642
+ field.focus();
89643
+ }
89644
+ _wirePasteField(field) {
89645
+ // keys typed here are text, not camera controls (see _wireEditable)
89646
+ const stopKey = (e) => e.stopPropagation();
89647
+ field.addEventListener('keydown', (e) => {
89648
+ stopKey(e);
89649
+ if (e.key === 'Enter') {
89650
+ e.preventDefault();
89651
+ const text = field.value;
89652
+ this._showPasteField(false);
89653
+ this._applyPasted(text);
89654
+ }
89655
+ else if (e.key === 'Escape') {
89656
+ e.preventDefault();
89657
+ this._showPasteField(false);
89658
+ }
89659
+ });
89660
+ field.addEventListener('keyup', stopKey);
89661
+ field.addEventListener('keypress', stopKey);
89662
+ field.addEventListener('paste', (e) => {
89663
+ e.preventDefault();
89664
+ const text = e.clipboardData?.getData('text/plain') ?? '';
89665
+ this._showPasteField(false);
89666
+ this._applyPasted(text);
89667
+ });
89668
+ field.addEventListener('blur', () => this._showPasteField(false));
89669
+ }
89670
+ _renderMiniStats() {
89671
+ if (!this._miniStats || !this._miniStatsButton)
89672
+ return;
89673
+ const shown = this._miniStats.shown();
89674
+ this._miniStatsButton.textContent = `MiniStats: ${shown ? 'on' : 'off'}`;
89675
+ this._miniStatsButton.classList.toggle('sse-debug-on', shown);
89676
+ }
89453
89677
  _screenshot() {
89454
89678
  const app = this._global.app;
89455
89679
  const canvas = app.graphicsDevice.canvas;
@@ -91424,6 +91648,3294 @@ class NavCursor {
91424
91648
  }
91425
91649
  }
91426
91650
 
91651
+ /**
91652
+ * World picking from the stochastic renderer's own frame.
91653
+ *
91654
+ * Every pixel of that renderer's depth texture holds the nearest surviving sample, which is
91655
+ * exactly what the pass picker in `picker.ts` renders on purpose: a stochastic depth whose
91656
+ * distribution over a disc is the scene's opacity along the ray. So no pick pass: the frame's
91657
+ * depth is snapshotted into the same encoding (normalised linear depth in four half-float
91658
+ * channels, 1 where nothing survived) at css resolution, and the shared estimators, the
91659
+ * annotation test and the debug overlay read it unchanged. A css pixel's four channels are four
91660
+ * of the device pixels it covers, so a high-density display supplies four trials as before.
91661
+ */
91662
+ // The frame's hardware depth as normalised linear view depth, in the pass picker's encoding.
91663
+ // Each snapshot pixel covers a block of device pixels; four of them, at the block's quarter
91664
+ // points, fill the four channels.
91665
+ const snapshotWgsl = /* wgsl */ `
91666
+ var splatDepth: texture_depth_2d;
91667
+ // clip z = a * viewDepth + b over w = viewDepth (x, y), near and far (z, w)
91668
+ uniform depthViewParams: vec4f;
91669
+ // device pixels per snapshot pixel (x, y), 1 for an orthographic camera (z)
91670
+ uniform snapshotParams: vec4f;
91671
+
91672
+ @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
91673
+ var output: FragmentOutput;
91674
+ let dims = vec2i(textureDimensions(splatDepth));
91675
+ let p = uniform.depthViewParams;
91676
+ let ortho = uniform.snapshotParams.z > 0.5;
91677
+ let origin = floor(pcPosition.xy);
91678
+ var trials = vec4f(1.0);
91679
+ for (var i = 0; i < 4; i++) {
91680
+ let corner = vec2f(0.25 + 0.5 * f32(i & 1), 0.25 + 0.5 * f32(i >> 1));
91681
+ let q = clamp(vec2i(floor((origin + corner) * uniform.snapshotParams.xy)), vec2i(0), dims - vec2i(1));
91682
+ let depth = textureLoad(splatDepth, q, 0);
91683
+ if (depth < 1.0) {
91684
+ let dz = depth - p.x;
91685
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
91686
+ let viewDepth = select(p.y / safeDz, (depth - p.y) / p.x, ortho);
91687
+ trials[i] = clamp((viewDepth - p.z) / (p.w - p.z), 0.0, 0.99951171875);
91688
+ }
91689
+ }
91690
+ output.color = trials;
91691
+ return output;
91692
+ }
91693
+ `;
91694
+ const cameraMatches = (frame, camera) => {
91695
+ const cam = camera.camera;
91696
+ return (frame.viewMatrix.equals(cam.viewMatrix) &&
91697
+ frame.projectionMatrix.equals(cam.projectionMatrix) &&
91698
+ frame.nearClip === cam.nearClip &&
91699
+ frame.farClip === cam.farClip &&
91700
+ frame.projection === cam.projection);
91701
+ };
91702
+ const sameCamera = (a, b) => a.viewMatrix.equals(b.viewMatrix) &&
91703
+ a.projectionMatrix.equals(b.projectionMatrix) &&
91704
+ a.nearClip === b.nearClip &&
91705
+ a.farClip === b.farClip &&
91706
+ a.projection === b.projection;
91707
+ const copyCameraSnapshot = (from, to) => {
91708
+ to.position.copy(from.position);
91709
+ to.viewMatrix.copy(from.viewMatrix);
91710
+ to.projectionMatrix.copy(from.projectionMatrix);
91711
+ to.nearClip = from.nearClip;
91712
+ to.farClip = from.farClip;
91713
+ to.projection = from.projection;
91714
+ };
91715
+ class FrameDepthPicker {
91716
+ app;
91717
+ camera;
91718
+ renderer;
91719
+ shader;
91720
+ texture = null;
91721
+ target = null;
91722
+ // the renderer frame the snapshot was taken from, and the camera it was drawn with
91723
+ snapshotFrame = -1;
91724
+ snapshotCamera = createPickCameraSnapshot();
91725
+ renders = 0;
91726
+ queue = new PickQueue();
91727
+ // picks waiting for a frame to render; settled by release as well
91728
+ waiters = new Set();
91729
+ constructor(app, camera, renderer) {
91730
+ this.app = app;
91731
+ this.camera = camera;
91732
+ this.renderer = renderer;
91733
+ this.shader = ShaderUtils.createShader(app.graphicsDevice, {
91734
+ uniqueName: 'sse-splat-depth-snapshot',
91735
+ attributes: { vertex_position: SEMANTIC_POSITION },
91736
+ vertexChunk: 'fullscreenQuadVS',
91737
+ fragmentWGSL: snapshotWgsl
91738
+ });
91739
+ }
91740
+ // Wait for the next frame to finish, or for release.
91741
+ nextFrame() {
91742
+ return new Promise((resolve) => {
91743
+ const done = () => {
91744
+ handle.off();
91745
+ this.waiters.delete(done);
91746
+ resolve();
91747
+ };
91748
+ const handle = this.app.once('frameend', done);
91749
+ this.waiters.add(done);
91750
+ });
91751
+ }
91752
+ // Snapshot the renderer's frame at css resolution, unless the snapshot already is of it. With
91753
+ // `latest` false a snapshot of an earlier frame from the same camera serves: every stochastic
91754
+ // frame is a new sample, so the debug overlay would otherwise ask for frames without end.
91755
+ snapshot(frame, latest) {
91756
+ const device = this.app.graphicsDevice;
91757
+ const size = pickTargetSize(device);
91758
+ if (!size)
91759
+ return null;
91760
+ const { width, height } = size;
91761
+ if (!this.texture) {
91762
+ this.texture = new Texture(device, {
91763
+ name: 'sse-splat-depth-snapshot',
91764
+ format: PIXELFORMAT_RGBA16F,
91765
+ width,
91766
+ height,
91767
+ mipmaps: false,
91768
+ minFilter: FILTER_NEAREST,
91769
+ magFilter: FILTER_NEAREST,
91770
+ addressU: ADDRESS_CLAMP_TO_EDGE,
91771
+ addressV: ADDRESS_CLAMP_TO_EDGE
91772
+ });
91773
+ this.target = new RenderTarget({
91774
+ name: 'sse-splat-depth-snapshot',
91775
+ colorBuffer: this.texture,
91776
+ depth: false
91777
+ });
91778
+ this.snapshotFrame = -1;
91779
+ }
91780
+ else if (this.texture.width !== width || this.texture.height !== height) {
91781
+ this.target.resize(width, height);
91782
+ this.snapshotFrame = -1;
91783
+ }
91784
+ const current = this.snapshotFrame === frame.id ||
91785
+ (!latest && this.snapshotFrame >= 0 && sameCamera(this.snapshotCamera, frame.camera));
91786
+ if (!current) {
91787
+ const { scope } = device;
91788
+ const { camera } = frame;
91789
+ scope.resolve('splatDepth').setValue(this.renderer.frameDepthTexture);
91790
+ scope
91791
+ .resolve('depthViewParams')
91792
+ .setValue([frame.clipZ[0], frame.clipZ[1], camera.nearClip, camera.farClip]);
91793
+ scope
91794
+ .resolve('snapshotParams')
91795
+ .setValue([
91796
+ frame.width / width,
91797
+ frame.height / height,
91798
+ camera.projection === PROJECTION_ORTHOGRAPHIC ? 1 : 0,
91799
+ 0
91800
+ ]);
91801
+ device.setBlendState(BlendState.NOBLEND);
91802
+ drawQuadWithShader(device, this.target, this.shader);
91803
+ this.snapshotFrame = frame.id;
91804
+ copyCameraSnapshot(frame.camera, this.snapshotCamera);
91805
+ this.renders++;
91806
+ }
91807
+ // the renderer rewrites its snapshot every frame, and frames render while a pick awaits
91808
+ // its readback: the pick unprojects with a copy of the camera its depth was drawn with
91809
+ const pickCamera = createPickCameraSnapshot();
91810
+ copyCameraSnapshot(frame.camera, pickCamera);
91811
+ return { width, height, pickCamera };
91812
+ }
91813
+ // The frame to pick from: the last one rendered if the camera has not moved since, else
91814
+ // one requested now. Its own camera unprojects it, whatever the live camera does meanwhile.
91815
+ async prepare() {
91816
+ if (this.queue.released)
91817
+ return null;
91818
+ let frame = this.renderer.depthFrame;
91819
+ if (!frame || !cameraMatches(frame.camera, this.camera)) {
91820
+ this.app.renderNextFrame = true;
91821
+ await this.nextFrame();
91822
+ frame = this.renderer.depthFrame;
91823
+ if (!frame || this.queue.released)
91824
+ return null;
91825
+ }
91826
+ return this.snapshot(frame, true);
91827
+ }
91828
+ // Read the snapshot around a pixel, `margin` pixels each way, clamped to it.
91829
+ async readAround(screenX, screenY, margin, width, height) {
91830
+ const blockX = Math.max(0, screenX - margin);
91831
+ const blockY = Math.max(0, screenY - margin);
91832
+ const blockWidth = Math.min(width - 1, screenX + margin) - blockX + 1;
91833
+ const blockHeight = Math.min(height - 1, screenY + margin) - blockY + 1;
91834
+ const pixels = (await this.texture.read(blockX, blockY, blockWidth, blockHeight, {
91835
+ renderTarget: this.target,
91836
+ immediate: true
91837
+ }));
91838
+ return (x, y, trial) => {
91839
+ const localX = x - blockX;
91840
+ const localY = y - blockY;
91841
+ if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
91842
+ return null;
91843
+ }
91844
+ return half2Float(pixels[(localY * blockWidth + localX) * 4 + trial]);
91845
+ };
91846
+ }
91847
+ pick(x, y) {
91848
+ return this.queue.run(async () => {
91849
+ const sample = await this.prepare();
91850
+ if (!sample)
91851
+ return null;
91852
+ const { width, height, pickCamera } = sample;
91853
+ const screenX = clampPixel(x, width);
91854
+ const screenY = clampPixel(y, height);
91855
+ const depthAt = await this.readAround(screenX, screenY, SURFACE_RADIUS_PX, width, height);
91856
+ const depth = surfaceDepth(depthAt, screenX, screenY);
91857
+ return depth === null ? null : getWorldPoint(pickCamera, screenX, screenY, width, height, depth);
91858
+ }, null);
91859
+ }
91860
+ pickSurface(x, y) {
91861
+ return this.queue.run(async () => {
91862
+ const sample = await this.prepare();
91863
+ if (!sample)
91864
+ return null;
91865
+ const { width, height, pickCamera } = sample;
91866
+ const screenX = clampPixel(x, width);
91867
+ const screenY = clampPixel(y, height);
91868
+ const depthAt = await this.readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
91869
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
91870
+ }, null);
91871
+ }
91872
+ pickVisibility(points, radius) {
91873
+ if (points.length === 0) {
91874
+ return Promise.resolve([]);
91875
+ }
91876
+ return this.queue.run(async () => {
91877
+ const sample = await this.prepare();
91878
+ if (!sample)
91879
+ return points.map(() => null);
91880
+ const { width, height, pickCamera } = sample;
91881
+ const r = Math.max(1, Math.round(radius * height));
91882
+ return Promise.all(points.map(async ({ x, y, depth }) => {
91883
+ const screenX = clampPixel(x, width);
91884
+ const screenY = clampPixel(y, height);
91885
+ const depthAt = await this.readAround(screenX, screenY, r, width, height);
91886
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
91887
+ }));
91888
+ }, points.map(() => null));
91889
+ }
91890
+ // The last frame's snapshot, for the debug overlay; it asks after each frame, so the frame
91891
+ // is the current camera's.
91892
+ renderView() {
91893
+ if (this.queue.released)
91894
+ return null;
91895
+ const frame = this.renderer.depthFrame;
91896
+ if (!frame || !this.snapshot(frame, false))
91897
+ return null;
91898
+ return { texture: this.texture, renders: this.renders };
91899
+ }
91900
+ release() {
91901
+ this.queue.released = true;
91902
+ for (const done of [...this.waiters])
91903
+ done();
91904
+ this.target?.destroy();
91905
+ this.texture?.destroy();
91906
+ this.target = null;
91907
+ this.texture = null;
91908
+ this.shader.destroy();
91909
+ }
91910
+ }
91911
+
91912
+ // The resident set: which splats the engine's LOD and streaming have made resident this
91913
+ // frame, and where each node's data sits. The engine keeps octree LOD, the budget, file
91914
+ // streaming and the block allocator (one slot range per node); the stochastic renderer
91915
+ // consumes its decisions and owns everything after them.
91916
+ //
91917
+ // Read through the engine's internal (@ignore) gsplat-unified classes until the public
91918
+ // `world:update` api lands (engine change E3 in the plan). Every internal shape used is
91919
+ // narrowed here to the members this file reads, so a change in the engine fails in one place.
91920
+ const tmpVec = new Vec3();
91921
+ const tmpVec2$1 = new Vec3();
91922
+ /**
91923
+ * Hooks the engine's per-frame gsplat update for one camera and layer and exposes the resident
91924
+ * set. `frame:ready` fires inside `GSplatManager.update()` after `world.bake()` and after the
91925
+ * engine's own render prep (both in 2.22.4 and on main), so a listener sees the baked state of
91926
+ * the current frame and can replace that prep.
91927
+ */
91928
+ class EngineResidentSetProvider {
91929
+ app;
91930
+ camera;
91931
+ layer;
91932
+ handles = [];
91933
+ callbacks = new Set();
91934
+ set = null;
91935
+ // the engine renderers this provider has switched off, with their original prep function
91936
+ takenOver = new Map();
91937
+ // while false the engine keeps rendering the splats itself (XR), and the hook stays quiet
91938
+ active = true;
91939
+ constructor(app, camera, layer) {
91940
+ this.app = app;
91941
+ this.camera = camera;
91942
+ this.layer = layer;
91943
+ const system = app.systems.gsplat;
91944
+ // fires when a manager is created for a camera and layer, before its first update:
91945
+ // the earliest point to switch the engine's own renderer off, so it never allocates
91946
+ // its projector, sort and draw resources
91947
+ this.handles.push(system.on('material:created', (material, cam, lyr) => {
91948
+ if (cam === this.camera && lyr === this.layer && this.active) {
91949
+ const manager = this.manager();
91950
+ if (manager)
91951
+ this.takeOver(manager);
91952
+ }
91953
+ }));
91954
+ this.handles.push(system.on('frame:ready', (cam, lyr) => {
91955
+ if (cam !== this.camera || lyr !== this.layer || !this.active)
91956
+ return;
91957
+ const manager = this.manager();
91958
+ if (!manager)
91959
+ return;
91960
+ this.takeOver(manager);
91961
+ const state = manager.world.currentState;
91962
+ if (!state)
91963
+ return;
91964
+ const changed = !this.set || this.set.version !== state.version;
91965
+ if (changed) {
91966
+ this.set = buildResidentSet(state);
91967
+ }
91968
+ for (const cb of this.callbacks) {
91969
+ cb(this.set, changed, manager);
91970
+ }
91971
+ }));
91972
+ }
91973
+ /** The engine manager for this camera and layer, once the engine has created it. */
91974
+ manager() {
91975
+ const director = this.app.renderer.gsplatDirector;
91976
+ // the director keys its cameras by the scene camera, not the component
91977
+ const cameraData = director?.camerasMap.get(this.camera.camera);
91978
+ return cameraData?.layersMap.get(this.layer)?.gsplatManager ?? null;
91979
+ }
91980
+ /** Hand the splats back to the engine's renderer (false), or take them over again (true). */
91981
+ setActive(value) {
91982
+ if (this.active === value)
91983
+ return;
91984
+ this.active = value;
91985
+ if (value) {
91986
+ const manager = this.manager();
91987
+ if (manager)
91988
+ this.takeOver(manager);
91989
+ }
91990
+ else {
91991
+ this.restore();
91992
+ }
91993
+ }
91994
+ onFrame(cb) {
91995
+ this.callbacks.add(cb);
91996
+ return () => this.callbacks.delete(cb);
91997
+ }
91998
+ /**
91999
+ * Switch the engine's own splat rendering off for this manager: its render prep returns
92000
+ * false (so the hybrid renderer never builds its projector, sorter or cache) and its mesh
92001
+ * instance is hidden. The world (LOD, streaming, allocation, the work-buffer copy) keeps
92002
+ * running. Reversed by {@link restore}.
92003
+ */
92004
+ takeOver(manager) {
92005
+ const renderer = manager.renderer;
92006
+ if (!this.takenOver.has(renderer)) {
92007
+ this.takenOver.set(renderer, renderer.prepareRenderView);
92008
+ renderer.prepareRenderView = () => false;
92009
+ }
92010
+ if (renderer.meshInstance)
92011
+ renderer.meshInstance.visible = false;
92012
+ // The manager's first update runs its render prep before frame:ready fires, and
92013
+ // material:created fires before the layer data holds the manager, so the engine's
92014
+ // projector, sorter and compaction get allocated once (32 bytes a splat and more).
92015
+ // Release them; the engine recreates them lazily if it renders again (XR, restore)
92016
+ // or picks through its sorted path.
92017
+ for (const key of ['gpuSorter', 'projector', 'intervalCompaction']) {
92018
+ const resource = renderer[key];
92019
+ if (resource) {
92020
+ resource.destroy();
92021
+ renderer[key] = null;
92022
+ }
92023
+ }
92024
+ }
92025
+ restore() {
92026
+ for (const [renderer, original] of this.takenOver) {
92027
+ renderer.prepareRenderView = original;
92028
+ if (renderer.meshInstance)
92029
+ renderer.meshInstance.visible = true;
92030
+ }
92031
+ this.takenOver.clear();
92032
+ }
92033
+ destroy() {
92034
+ this.restore();
92035
+ for (const handle of this.handles)
92036
+ handle.off();
92037
+ this.handles.length = 0;
92038
+ this.callbacks.clear();
92039
+ this.set = null;
92040
+ }
92041
+ }
92042
+ // Flatten the engine world state into files and nodes with world-space bounds.
92043
+ const buildResidentSet = (state) => {
92044
+ const files = [];
92045
+ const nodes = [];
92046
+ const spheres = [];
92047
+ const pushNode = (node, cx, cy, cz, radius) => {
92048
+ nodes.push(node);
92049
+ spheres.push(cx, cy, cz, radius);
92050
+ };
92051
+ state.splats.forEach((info, fileIndex) => {
92052
+ const modelMatrix = info.node.getWorldTransform().clone();
92053
+ const scale = modelMatrix.getScale(tmpVec2$1);
92054
+ const maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
92055
+ const file = {
92056
+ fileIndex,
92057
+ lodIndex: info.lodIndex,
92058
+ nodes: [],
92059
+ modelMatrix,
92060
+ resource: info.resource
92061
+ };
92062
+ const numIntervals = info.intervals.length / 2;
92063
+ if (numIntervals === 0) {
92064
+ // a single-file resource: one range covering it whole, bounded by its aabb
92065
+ const node = {
92066
+ fileIndex,
92067
+ nodeIndex: nodes.length,
92068
+ lodIndex: info.lodIndex,
92069
+ sourceBase: 0,
92070
+ count: info.activeSplats,
92071
+ slotBase: info.intervalOffsets[0] ?? 0,
92072
+ allocId: info.allocId
92073
+ };
92074
+ modelMatrix.transformPoint(info.aabb.center, tmpVec);
92075
+ const he = info.aabb.halfExtents;
92076
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, he.length() * maxScale);
92077
+ file.nodes.push(node);
92078
+ }
92079
+ else {
92080
+ for (let j = 0; j < numIntervals; j++) {
92081
+ const start = info.intervals[j * 2];
92082
+ const end = info.intervals[j * 2 + 1];
92083
+ const nodeIndex = info.intervalNodeIndices[j];
92084
+ const node = {
92085
+ fileIndex,
92086
+ nodeIndex: nodes.length,
92087
+ lodIndex: info.lodIndex,
92088
+ sourceBase: start,
92089
+ count: end - start,
92090
+ slotBase: info.intervalOffsets[j] ?? 0,
92091
+ allocId: info.intervalAllocIds[j]
92092
+ };
92093
+ const sphere = info.octreeNodes?.[nodeIndex]?.boundingSphere;
92094
+ if (sphere) {
92095
+ tmpVec.set(sphere.x, sphere.y, sphere.z);
92096
+ modelMatrix.transformPoint(tmpVec, tmpVec);
92097
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, sphere.w * maxScale);
92098
+ }
92099
+ else {
92100
+ // no bounds: never culled
92101
+ pushNode(node, 0, 0, 0, Infinity);
92102
+ }
92103
+ file.nodes.push(node);
92104
+ }
92105
+ }
92106
+ files.push(file);
92107
+ });
92108
+ return {
92109
+ version: state.version,
92110
+ activeSplats: state.totalActiveSplats,
92111
+ slotCapacity: state.textureSize * state.textureSize,
92112
+ fullRebuild: state.fullRebuild,
92113
+ changedAllocIds: state.needsUploadIds,
92114
+ files,
92115
+ nodes,
92116
+ nodeSpheres: new Float32Array(spheres)
92117
+ };
92118
+ };
92119
+
92120
+ // Single-thread pass turning the projector's survivor count into the indexed indirect draw
92121
+ // arguments for the raster pass and the indirect dispatch size of the order scatter. Nothing
92122
+ // comes back to the cpu, so a frame never stalls on the count. Entry layouts match the engine's
92123
+ // indirect draw buffer (5 u32 per slot) and indirect dispatch buffer (3 u32 per slot).
92124
+ const argsWGSL = /* wgsl */ `
92125
+ struct DrawIndexedIndirectArgs {
92126
+ indexCount: u32,
92127
+ instanceCount: u32,
92128
+ firstIndex: u32,
92129
+ baseVertex: i32,
92130
+ firstInstance: u32
92131
+ }
92132
+
92133
+ struct ArgsUniforms {
92134
+ drawSlot: u32,
92135
+ indexCount: u32,
92136
+ quadsPerInstance: u32,
92137
+ dispatchSlot: u32,
92138
+ scatterWorkgroupSize: u32
92139
+ }
92140
+
92141
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
92142
+ @group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>;
92143
+ @group(0) @binding(2) var<storage, read_write> indirectDispatchArgs: array<u32>;
92144
+ @group(0) @binding(3) var<uniform> uniforms: ArgsUniforms;
92145
+
92146
+ @compute @workgroup_size(1)
92147
+ fn main() {
92148
+ let count = counter[0];
92149
+ indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs(
92150
+ uniforms.indexCount,
92151
+ (count + uniforms.quadsPerInstance - 1u) / uniforms.quadsPerInstance,
92152
+ 0u,
92153
+ 0,
92154
+ 0u
92155
+ );
92156
+ // the scatter: one workgroup per scatterWorkgroupSize survivors, 2D past the 65535 limit
92157
+ let groups = (count + uniforms.scatterWorkgroupSize - 1u) / uniforms.scatterWorkgroupSize;
92158
+ let x = max(min(groups, 65535u), 1u);
92159
+ let base = uniforms.dispatchSlot * 3u;
92160
+ indirectDispatchArgs[base] = x;
92161
+ indirectDispatchArgs[base + 1u] = (groups + x - 1u) / x;
92162
+ indirectDispatchArgs[base + 2u] = 1u;
92163
+ }
92164
+ `;
92165
+
92166
+ // Temporal accumulation for the stochastic frame. Each frame the raster leaves one sample per
92167
+ // pixel (a colour where a splat's fragment survived its coverage test, nothing otherwise) and
92168
+ // the nearest surviving depth; this pass folds it into a per-pixel history of premultiplied
92169
+ // colour and coverage, so a still camera converges to the expected image over a few hundred
92170
+ // frames and a moving one keeps most of that history by reprojecting it.
92171
+ //
92172
+ // Reprojection uses the sample's own depth: the pixel's world point is carried into the
92173
+ // previous view and the history is fetched there, clamped to the colours this frame's
92174
+ // neighbourhood holds so a stale colour cannot survive a disocclusion. A pixel with no sample
92175
+ // this frame reprojects through the mean depth its own history remembers, so coverage fades out
92176
+ // where a surface has moved away rather than smearing into the background.
92177
+ //
92178
+ // The history is 12 bytes a pixel (24 with the ping-pong). The colour is the running mean as
92179
+ // 16-bit fixed point: a half float cannot hold it, since its steps in [0.5, 1) are 1 / 2048 and
92180
+ // the 1 / N step of a 256-sample mean rounds away once a sample lies within 1 / 16 of the mean
92181
+ // (an error floor of about 5 rms in 8-bit units), while fixed point steps by 1 / 65535
92182
+ // everywhere, so the same step only rounds away within half an 8-bit level of the mean. The
92183
+ // depth record is the mean view depth of the pixel's samples and their count in one 32-bit word.
92184
+ // the most samples the history's count field holds
92185
+ const TAA_MAX_COUNT = 511;
92186
+ const taaVertexWGSL = /* wgsl */ `
92187
+ attribute vertex_position: vec2f;
92188
+
92189
+ @vertex
92190
+ fn vertexMain(input: VertexInput) -> VertexOutput {
92191
+ var output: VertexOutput;
92192
+ output.position = vec4f(vertex_position, 0.0, 1.0);
92193
+ return output;
92194
+ }
92195
+ `;
92196
+ // The history's encoding, shared with the compose that reads it
92197
+ const taaHistoryWGSL = /* wgsl */ `
92198
+ const TAA_COLOR_SCALE = 65535.0;
92199
+
92200
+ fn decodeColor(v: vec4u) -> vec4f {
92201
+ return vec4f(v) / TAA_COLOR_SCALE;
92202
+ }
92203
+
92204
+ // premultiplied colour and coverage: coverage in [0, 1] and colour within it (the Catmull-Rom
92205
+ // fetch over- and undershoots both), rounded to the nearest step
92206
+ fn encodeColor(c: vec4f) -> vec4u {
92207
+ let a = clamp(c.a, 0.0, 1.0);
92208
+ return vec4u(round(vec4f(clamp(c.rgb, vec3f(0.0), vec3f(a)), a) * TAA_COLOR_SCALE));
92209
+ }
92210
+
92211
+ struct HistoryInfo {
92212
+ depth: f32,
92213
+ count: f32
92214
+ }
92215
+
92216
+ // The mean view depth keeps the float's exponent and top 15 mantissa bits, rounded: a relative
92217
+ // step of 2^-15, which stalls a 256-sample mean only within 0.4 % of the depth (the depth steers
92218
+ // the reprojection, where that is far below a pixel). The count takes the low 9 bits
92219
+ fn decodeInfo(v: u32) -> HistoryInfo {
92220
+ var info: HistoryInfo;
92221
+ info.depth = bitcast<f32>((v >> 9u) << 8u);
92222
+ info.count = f32(v & ${TAA_MAX_COUNT}u);
92223
+ return info;
92224
+ }
92225
+
92226
+ fn encodeInfo(depth: f32, count: f32) -> u32 {
92227
+ let bits = bitcast<u32>(max(depth, 0.0));
92228
+ return (((bits + 0x80u) >> 8u) << 9u) | min(u32(count), ${TAA_MAX_COUNT}u);
92229
+ }
92230
+ `;
92231
+ const taaFragmentWGSL = /* wgsl */ `
92232
+ var curColor: texture_2d<f32>;
92233
+ var curColorSampler: sampler;
92234
+ var curDepth: texture_depth_2d;
92235
+ // premultiplied colour and coverage, unorm16 (decodeColor)
92236
+ var histColor: texture_2d<u32>;
92237
+ // the mean view depth of the pixel's samples and their count, in the previous frame's view
92238
+ // depths (decodeInfo)
92239
+ var histInfo: texture_2d<u32>;
92240
+
92241
+ // the camera's world transform (the inverse view), and its projection's x and y terms: x, y the
92242
+ // scales, z, w the offsets (the column that multiplies view z for a perspective camera, the
92243
+ // translation for an orthographic one)
92244
+ uniform cameraWorld: mat4x4f;
92245
+ uniform unproject: vec4f;
92246
+ uniform prevViewProj: mat4x4f;
92247
+ uniform prevView: mat4x4f;
92248
+ // clip z = a * viewDepth + b over w = viewDepth (x, y); z: 1 for an orthographic camera
92249
+ uniform clipZParams: vec4f;
92250
+ // x: sample cap, y: 1 when the history holds the previous frame, z: 1 when the camera moved
92251
+ // since that frame, w: the frames the camera has rested, this one included (0 on a frame whose
92252
+ // resident set changed)
92253
+ uniform taaParams: vec4f;
92254
+ // width, height, 1 / width, 1 / height
92255
+ uniform taaViewport: vec4f;
92256
+ // x: -1 when the target's rows run bottom-up (an offscreen target), else 1; y: the colour
92257
+ // clamp width in neighbourhood standard deviations (0: no clamp); z: 1 when the raster's
92258
+ // thresholds are quad-stratified
92259
+ uniform taaControl: vec4f;
92260
+ // x: 1 for a Catmull-Rom history fetch while moving (0: bilinear); y: 1 to reproject through
92261
+ // the pixel's accumulated mean depth rather than this frame's sample depth; z: image motion in
92262
+ // pixels a frame that halves the moving sample cap (0: fixed cap)
92263
+ uniform taaFilter: vec4f;
92264
+ // 1: write the accumulation state instead of colour (r: count / cap, g: history accepted,
92265
+ // b: the camera moved since the previous frame)
92266
+ uniform taaDebug: f32;
92267
+
92268
+ ${taaHistoryWGSL}
92269
+
92270
+ fn viewDepthOf(z: f32) -> f32 {
92271
+ let p = uniform.clipZParams;
92272
+ let dz = z - p.x;
92273
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
92274
+ return select(p.y / safeDz, (z - p.y) / p.x, p.z != 0.0);
92275
+ }
92276
+
92277
+ struct Reprojected {
92278
+ valid: bool,
92279
+ uv: vec2f,
92280
+ prevDepth: f32
92281
+ }
92282
+
92283
+ // The previous frame's view depth and texture coordinate of this pixel's point at a view
92284
+ // depth. The point is built in view space from the depth and the projection's x and y terms,
92285
+ // then moved by the camera's rigid transform: through the inverse view-projection instead, a
92286
+ // near plane at 1e-4 of the depth (the viewer's floor once the camera is inside the scene
92287
+ // bound) leaves a 32-bit float about three digits of the point, a pixel of error that changes
92288
+ // with every frame's sample depths and shakes the history.
92289
+ fn reproject(pix: vec2i, viewDepth: f32) -> Reprojected {
92290
+ var r: Reprojected;
92291
+ let flip = uniform.taaControl.x;
92292
+ let uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
92293
+ let ndc = vec2f(uv.x * 2.0 - 1.0, flip * (1.0 - 2.0 * uv.y));
92294
+ let u = uniform.unproject;
92295
+ let viewXY = select((ndc + u.zw) * viewDepth, ndc - u.zw, uniform.clipZParams.z != 0.0) / u.xy;
92296
+ let world = (uniform.cameraWorld * vec4f(viewXY, -viewDepth, 1.0)).xyz;
92297
+ let prevClip = uniform.prevViewProj * vec4f(world, 1.0);
92298
+ r.prevDepth = -(uniform.prevView * vec4f(world, 1.0)).z;
92299
+ r.valid = prevClip.w > 0.0;
92300
+ let prevNdc = prevClip.xy / max(prevClip.w, 1e-9);
92301
+ r.uv = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * flip * 0.5);
92302
+ r.valid = r.valid && all(r.uv >= vec2f(0.0)) && all(r.uv <= vec2f(1.0));
92303
+ return r;
92304
+ }
92305
+
92306
+ // the premultiplied sample at a texel: its colour where a fragment landed, nothing otherwise
92307
+ fn sampleAt(pix: vec2i, dims: vec2i) -> vec4f {
92308
+ let p = clamp(pix, vec2i(0), dims - vec2i(1));
92309
+ let c = textureLoad(curColor, p, 0);
92310
+ let z = textureLoad(curDepth, p, 0);
92311
+ return select(vec4f(0.0), vec4f(c.rgb, 1.0), c.a > 0.0 && z < 1.0);
92312
+ }
92313
+
92314
+ // The mean of the 2x2 quad's samples, bilinear between quad centres (the compose's resolve of
92315
+ // the raster's quad-stratified thresholds): four samples a pixel, at a little sharpness, for
92316
+ // the frames where the history is too short to carry the noise on its own
92317
+ fn quadSample(pix: vec2i, dims: vec2i) -> vec4f {
92318
+ let size = vec2f(dims);
92319
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
92320
+ let q0 = floor(u);
92321
+ let f = u - q0;
92322
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
92323
+ let step = vec2f(2.0) / size;
92324
+ let a = textureSampleLevel(curColor, curColorSampler, uv, 0.0);
92325
+ let b = textureSampleLevel(curColor, curColorSampler, uv + vec2f(step.x, 0.0), 0.0);
92326
+ let c = textureSampleLevel(curColor, curColorSampler, uv + vec2f(0.0, step.y), 0.0);
92327
+ let d = textureSampleLevel(curColor, curColorSampler, uv + step, 0.0);
92328
+ let m = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
92329
+ // the raster leaves empty texels transparent black, so the mean is premultiplied coverage
92330
+ return vec4f(m.rgb, m.a);
92331
+ }
92332
+
92333
+ fn historyTexel(p: vec2i, dims: vec2i) -> vec4f {
92334
+ return decodeColor(textureLoad(histColor, clamp(p, vec2i(0), dims - vec2i(1)), 0));
92335
+ }
92336
+
92337
+ // Catmull-Rom fetch of the history: sharper than bilinear, whose blur compounds over the
92338
+ // frames a moving history lives. Its lobes over- and undershoot; the encoding clamps both
92339
+ fn historyCubicAt(uv: vec2f, dims: vec2i) -> vec4f {
92340
+ let p = uv * vec2f(dims) - vec2f(0.5);
92341
+ let i0 = vec2i(floor(p));
92342
+ let f = p - floor(p);
92343
+ let f2 = f * f;
92344
+ let f3 = f2 * f;
92345
+ // Catmull-Rom weights for taps at -1, 0, 1, 2
92346
+ let w0 = -0.5 * f3 + f2 - 0.5 * f;
92347
+ let w1 = 1.5 * f3 - 2.5 * f2 + vec2f(1.0);
92348
+ let w2 = -1.5 * f3 + 2.0 * f2 + 0.5 * f;
92349
+ let w3 = 0.5 * f3 - 0.5 * f2;
92350
+ let wx = array<f32, 4>(w0.x, w1.x, w2.x, w3.x);
92351
+ let wy = array<f32, 4>(w0.y, w1.y, w2.y, w3.y);
92352
+ var sum = vec4f(0.0);
92353
+ for (var y = 0; y < 4; y++) {
92354
+ for (var x = 0; x < 4; x++) {
92355
+ sum += historyTexel(i0 + vec2i(x - 1, y - 1), dims) * (wx[x] * wy[y]);
92356
+ }
92357
+ }
92358
+ return sum;
92359
+ }
92360
+
92361
+ // bilinear fetch of the history
92362
+ fn historyAt(uv: vec2f, dims: vec2i) -> vec4f {
92363
+ let p = uv * vec2f(dims) - vec2f(0.5);
92364
+ let i0 = vec2i(floor(p));
92365
+ let f = p - floor(p);
92366
+ let a = historyTexel(i0, dims);
92367
+ let b = historyTexel(i0 + vec2i(1, 0), dims);
92368
+ let c = historyTexel(i0 + vec2i(0, 1), dims);
92369
+ let d = historyTexel(i0 + vec2i(1, 1), dims);
92370
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
92371
+ }
92372
+
92373
+ @fragment
92374
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
92375
+ var output: FragmentOutput;
92376
+ let pix = vec2i(pcPosition.xy);
92377
+ let dims = vec2i(textureDimensions(curColor));
92378
+ let cur = textureLoad(curColor, pix, 0);
92379
+ let z = textureLoad(curDepth, pix, 0);
92380
+ let hit = cur.a > 0.0 && z < 1.0;
92381
+ let d = viewDepthOf(z);
92382
+
92383
+ let own = decodeInfo(textureLoad(histInfo, pix, 0).x);
92384
+ let maxCount = uniform.taaParams.x;
92385
+ let historyValid = uniform.taaParams.y > 0.5;
92386
+ let moving = uniform.taaParams.z > 0.5;
92387
+ // still: this pixel's own sample, so the history converges to full resolution; moving:
92388
+ // the quad's four
92389
+ var sample = select(vec4f(0.0), vec4f(cur.rgb, 1.0), hit);
92390
+ if (moving && uniform.taaControl.z > 0.5) {
92391
+ sample = quadSample(pix, dims);
92392
+ }
92393
+
92394
+ // Where to look in the history: through this frame's sample, or, with no sample, through
92395
+ // the depth this pixel's own history remembers, so an emptied pixel fades rather than
92396
+ // holding a stale colour
92397
+ var r: Reprojected;
92398
+ r.valid = false;
92399
+ var carryDepth = 0.0;
92400
+ if (!moving) {
92401
+ // a resting camera maps every pixel onto itself: the exact texel, not the round trip
92402
+ // through the matrices, whose rounding would blur the history a little every frame
92403
+ r.valid = true;
92404
+ r.uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
92405
+ r.prevDepth = select(own.depth, d, hit);
92406
+ carryDepth = r.prevDepth;
92407
+ } else if (uniform.taaFilter.y > 0.5 && own.count > 0.5) {
92408
+ // through the depth the pixel's history has settled on: one stochastic sample's depth
92409
+ // is one layer of the mixture the history holds, and reprojecting the mixture through
92410
+ // a different layer every frame smears it by their parallax
92411
+ r = reproject(pix, own.depth);
92412
+ carryDepth = own.depth;
92413
+ } else if (hit) {
92414
+ r = reproject(pix, d);
92415
+ carryDepth = d;
92416
+ } else if (own.count > 0.5) {
92417
+ r = reproject(pix, own.depth);
92418
+ carryDepth = own.depth;
92419
+ }
92420
+ r.valid = r.valid && historyValid;
92421
+
92422
+ var hist = vec4f(0.0);
92423
+ var info: HistoryInfo;
92424
+ var accepted = false;
92425
+ if (r.valid) {
92426
+ // at rest the exact texel; moving, a filtered fetch of the reprojected position
92427
+ if (!moving) {
92428
+ hist = decodeColor(textureLoad(histColor, pix, 0));
92429
+ info = own;
92430
+ } else {
92431
+ if (uniform.taaFilter.x > 0.5) {
92432
+ hist = historyCubicAt(r.uv, dims);
92433
+ } else {
92434
+ hist = historyAt(r.uv, dims);
92435
+ }
92436
+ info = decodeInfo(textureLoad(histInfo, clamp(vec2i(r.uv * vec2f(dims)), vec2i(0), dims - vec2i(1)), 0).x);
92437
+ }
92438
+ // a resting camera cannot disocclude anything, so every sample is accepted and the
92439
+ // pixel converges; moving, the colour clamp below keeps a disoccluded history out
92440
+ accepted = info.count > 0.5;
92441
+ }
92442
+
92443
+ var color: vec4f;
92444
+ var mean: f32;
92445
+ var count: f32;
92446
+ if (!accepted) {
92447
+ color = sample;
92448
+ mean = d;
92449
+ count = select(0.0, 1.0, hit);
92450
+ // at rest a pixel with no hit yet has still been sampled on every rest frame, so its
92451
+ // first hit is one of that many samples: at full weight a rare hit would flash to full
92452
+ // coverage, and freeze there once the viewer stops rendering. Its depth is the hit's
92453
+ if (hit && !moving && historyValid) {
92454
+ count = clamp(uniform.taaParams.w, 1.0, maxCount);
92455
+ color = sample / count;
92456
+ }
92457
+ } else {
92458
+ // moving, the history is clamped to the colours this frame's neighbourhood holds, so a
92459
+ // stale colour cannot survive where nothing like it is drawn any more
92460
+ if (moving && uniform.taaControl.y > 0.0) {
92461
+ var m1 = vec4f(0.0);
92462
+ var m2 = vec4f(0.0);
92463
+ for (var dy = -1; dy <= 1; dy++) {
92464
+ for (var dx = -1; dx <= 1; dx++) {
92465
+ let n = sampleAt(pix + vec2i(dx, dy), dims);
92466
+ m1 += n;
92467
+ m2 += n * n;
92468
+ }
92469
+ }
92470
+ let mu = m1 / 9.0;
92471
+ let sd = sqrt(max(m2 / 9.0 - mu * mu, vec4f(0.0)));
92472
+ let halfWidth = sd * uniform.taaControl.y;
92473
+ hist = clamp(hist, mu - halfWidth, mu + halfWidth);
92474
+ }
92475
+ // the faster the image moves, the shorter the history: a stochastic pixel's layers
92476
+ // reproject through one layer's depth, so their parallax smears the history by an
92477
+ // amount that grows with the motion, and a raw frame is the better estimate past it
92478
+ var cap = maxCount;
92479
+ if (moving && uniform.taaFilter.z > 0.0) {
92480
+ let speed = length(r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5));
92481
+ cap = max(2.0, maxCount / (1.0 + speed / uniform.taaFilter.z));
92482
+ }
92483
+ count = min(info.count + 1.0, cap);
92484
+ let w = 1.0 / count;
92485
+ color = mix(hist, sample, w);
92486
+ // an empty sample takes at least a step off the coverage: rounded to the nearest, a
92487
+ // decay of less than half a step holds (below cap / 2 steps, about 0.002 at the default
92488
+ // cap), so a faint pixel would keep its coverage, and the depth the compose writes for
92489
+ // it, forever. The colour follows, since the encoding keeps it within the coverage
92490
+ if (sample.a == 0.0) {
92491
+ color.a = min(color.a, max(hist.a - 1.0 / TAA_COLOR_SCALE, 0.0));
92492
+ }
92493
+ // carry the mean depth into this view: the point moved along the ray by the change in
92494
+ // its depth, then the sample joins it
92495
+ let shifted = info.depth + (carryDepth - r.prevDepth);
92496
+ mean = select(shifted, shifted + w * (d - shifted), hit);
92497
+ }
92498
+
92499
+ if (uniform.taaDebug > 1.5) {
92500
+ // the reprojection offset in pixels, 8 px full scale, centred on 0.5
92501
+ let mv = select(vec2f(0.0), r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5), r.valid);
92502
+ color = vec4f(mv / 16.0 + vec2f(0.5), select(0.0, 1.0, r.valid), 1.0);
92503
+ } else if (uniform.taaDebug > 0.5) {
92504
+ color = vec4f(count / maxCount, select(0.0, 1.0, accepted), select(0.0, 1.0, moving), 1.0);
92505
+ }
92506
+ output.color = encodeColor(color);
92507
+ output.color1 = encodeInfo(mean, count);
92508
+ return output;
92509
+ }
92510
+ `;
92511
+
92512
+ // The compose: a fullscreen quad in the World layer's transparent sublayer that blends the
92513
+ // stochastic target over the camera's target (after the skybox and opaque meshes) and writes
92514
+ // its depth, so everything drawn later depth-tests against the splats. The colour transform
92515
+ // the engine's own splat shader applies (gsplatOutputVS: tonemap and gamma, or the viewer's
92516
+ // pass-through patch under CameraFrame) runs here, once per pixel instead of once per splat.
92517
+ const composeVertexWGSL = /* wgsl */ `
92518
+ attribute vertex_position: vec2f;
92519
+
92520
+ @vertex
92521
+ fn vertexMain(input: VertexInput) -> VertexOutput {
92522
+ var output: VertexOutput;
92523
+ output.position = vec4f(vertex_position, 0.0, 1.0);
92524
+ return output;
92525
+ }
92526
+ `;
92527
+ const composeFragmentWGSL = /* wgsl */ `
92528
+ #include "gsplatOutputVS"
92529
+
92530
+ var splatColor: texture_2d<f32>;
92531
+ var splatColorSampler: sampler;
92532
+ var splatDepth: texture_depth_2d;
92533
+ // the temporally accumulated frame (premultiplied colour, coverage), when taa ran this frame
92534
+ var taaColor: texture_2d<u32>;
92535
+ // its depth record: the mean view depth of the pixel's samples and their count
92536
+ var taaInfo: texture_2d<u32>;
92537
+ // x: 1 when the splat target's rows run the other way to the camera target's; y: 1 for an
92538
+ // orthographic camera; z: 1 to read the taa history instead of the raw frame
92539
+ uniform composeParams: vec4f;
92540
+ // the splat target's depth: clip z = a * viewDepth + b over w = viewDepth (x, y), and the
92541
+ // camera's near and far (z, w) for the depth view
92542
+ uniform depthViewParams: vec4f;
92543
+ // the camera's own depth, the one written for the rest of the scene: clip z = a * viewDepth + b
92544
+ // (x, y). The splat target's far plane is at infinity where the camera's is fitted to the scene
92545
+ uniform cameraClipZ: vec4f;
92546
+
92547
+ ${taaHistoryWGSL}
92548
+
92549
+ const FAR_DEPTH = 0.999999;
92550
+
92551
+ // the splat target's depth texel of a view depth, just inside its far plane at most: the
92552
+ // raster clamps there too, since a depth of 1 reads as no sample
92553
+ fn clipZOf(viewDepth: f32) -> f32 {
92554
+ let p = uniform.depthViewParams;
92555
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
92556
+ return min(clamp(p.x * viewDepth + p.y, 0.0, w) / w, FAR_DEPTH);
92557
+ }
92558
+
92559
+ // the view depth of a splat target depth texel
92560
+ fn viewDepthOf(z: f32) -> f32 {
92561
+ let p = uniform.depthViewParams;
92562
+ let dz = z - p.x;
92563
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
92564
+ return select(p.y / safeDz, (z - p.y) / p.x, uniform.composeParams.y > 0.5);
92565
+ }
92566
+
92567
+ // A splat target depth in the camera's depth, clamped just inside the camera's far plane as the
92568
+ // engine clamps its splats: splats beyond it stay behind everything the scene draws
92569
+ fn cameraDepthOf(z: f32) -> f32 {
92570
+ let viewDepth = viewDepthOf(z);
92571
+ let c = uniform.cameraClipZ;
92572
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
92573
+ return min(clamp(c.x * viewDepth + c.y, 0.0, w) / w, FAR_DEPTH);
92574
+ }
92575
+
92576
+ @fragment
92577
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
92578
+ var output: FragmentOutput;
92579
+ let dims = vec2i(textureDimensions(splatColor));
92580
+ var pix = vec2i(pcPosition.xy);
92581
+ if (uniform.composeParams.x > 0.5) {
92582
+ pix.y = dims.y - 1 - pix.y;
92583
+ }
92584
+ pix = clamp(pix, vec2i(0), dims - vec2i(1));
92585
+
92586
+ var depth = textureLoad(splatDepth, pix, 0);
92587
+ var color: vec4f;
92588
+ if (uniform.composeParams.z > 0.5) {
92589
+ // the accumulated history: coverage in alpha, colour premultiplied by it
92590
+ color = decodeColor(textureLoad(taaColor, pix, 0));
92591
+ if (depth >= 1.0 && color.a > 0.001) {
92592
+ // covered by the history but no sample this frame, which a faint pixel sees on
92593
+ // most frames: the mean depth of the pixel's own samples, or, for a history this
92594
+ // frame started (moving, from the quad's samples), the nearest sampled neighbour's,
92595
+ // so the pixel still occludes what is behind the splats
92596
+ let info = decodeInfo(textureLoad(taaInfo, pix, 0).x);
92597
+ if (info.count > 0.5) {
92598
+ depth = clipZOf(info.depth);
92599
+ } else {
92600
+ for (var dy = -1; dy <= 1; dy++) {
92601
+ for (var dx = -1; dx <= 1; dx++) {
92602
+ depth = min(depth, textureLoad(splatDepth, clamp(pix + vec2i(dx, dy), vec2i(0), dims - vec2i(1)), 0));
92603
+ }
92604
+ }
92605
+ }
92606
+ }
92607
+ } else {
92608
+ #ifdef SSE_SPP_QUAD
92609
+ // the mean of each 2x2 quad, bilinearly interpolated between quad centres: the four
92610
+ // strata of the raster's thresholds average out to the splat's coverage. Empty texels
92611
+ // are transparent black, so the result is premultiplied coverage
92612
+ let size = vec2f(dims);
92613
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
92614
+ let q0 = floor(u);
92615
+ let f = u - q0;
92616
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
92617
+ let step = vec2f(2.0) / size;
92618
+ let a = textureSampleLevel(splatColor, splatColorSampler, uv, 0.0);
92619
+ let b = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(step.x, 0.0), 0.0);
92620
+ let c = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(0.0, step.y), 0.0);
92621
+ let d = textureSampleLevel(splatColor, splatColorSampler, uv + step, 0.0);
92622
+ color = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
92623
+ if (depth >= 1.0) {
92624
+ // no sample at this pixel but coverage from its quad: the quad's nearest depth
92625
+ let quad = (pix >> vec2u(1u)) << vec2u(1u);
92626
+ depth = min(
92627
+ min(textureLoad(splatDepth, quad, 0), textureLoad(splatDepth, min(quad + vec2i(1, 0), dims - 1), 0)),
92628
+ min(textureLoad(splatDepth, min(quad + vec2i(0, 1), dims - 1), 0), textureLoad(splatDepth, min(quad + vec2i(1, 1), dims - 1), 0))
92629
+ );
92630
+ }
92631
+ #else
92632
+ color = textureLoad(splatColor, pix, 0);
92633
+ #endif
92634
+ }
92635
+ if (color.a <= 0.001) {
92636
+ discard;
92637
+ }
92638
+ // coverage with no depth anywhere near: shown, behind everything the scene drew
92639
+ depth = min(depth, FAR_DEPTH);
92640
+
92641
+ #ifdef SSE_SHOW_DEPTH
92642
+ // the nearest sample's view depth, log-spaced between near and far, as grey
92643
+ let p = uniform.depthViewParams;
92644
+ let viewDepth = viewDepthOf(depth);
92645
+ let t = clamp(log(max(viewDepth, p.z) / p.z) / log(p.w / p.z), 0.0, 1.0);
92646
+ // 24-bit fixed point across rgb (high byte in red), so a capture can read it precisely
92647
+ let fixed = floor(t * 16777215.0);
92648
+ let hi = floor(fixed / 65536.0);
92649
+ let mid = floor((fixed - hi * 65536.0) / 256.0);
92650
+ let lo = fixed - hi * 65536.0 - mid * 256.0;
92651
+ output.color = vec4f(vec3f(hi, mid, lo) / 255.0, 1.0);
92652
+ output.fragDepth = cameraDepthOf(depth);
92653
+ return output;
92654
+ #endif
92655
+
92656
+ // un-premultiply for the output transform, then premultiply for the blend
92657
+ let gamma = color.rgb / color.a;
92658
+ let rgb = prepareOutputFromGamma(gamma, 0.0);
92659
+ output.color = vec4f(rgb * color.a, color.a);
92660
+ output.fragDepth = cameraDepthOf(depth);
92661
+ return output;
92662
+ }
92663
+ `;
92664
+
92665
+ // The projector: one 256-thread workgroup per chunk of the resident set. Each thread reads one
92666
+ // splat through the source's read code, projects it, applies the culls, and survivors append
92667
+ // themselves to a dense cache with one global atomic per workgroup. The chunk table and node
92668
+ // visibility come from the cpu (resident-set rebuild on version change, frustum cull per frame).
92669
+ /** Words per cache entry. See the layout in the plan: ndc, depth, axis1, len2|alpha|flags, rgb, popless, id. */
92670
+ const CACHE_WORDS = 7;
92671
+ const PROJECTOR_WORKGROUP_SIZE = 256;
92672
+ /** Buckets of the counting order (order:bucket); the workgroup size, so each thread owns one. */
92673
+ const ORDER_BUCKETS = PROJECTOR_WORKGROUP_SIZE;
92674
+ /** Splats per chunk-table entry; a chunk is one workgroup. */
92675
+ const CHUNK_SIZE = PROJECTOR_WORKGROUP_SIZE;
92676
+ const projectorWGSL = (readChunk, occlusion, order) => /* wgsl */ `
92677
+ struct ProjectorUniforms {
92678
+ view: mat4x4f,
92679
+ viewProj: mat4x4f,
92680
+ // the previous frame, for the occlusion cull: its view and view-projection, its clip-z
92681
+ // mapping (a, b, isOrtho, 0), viewport and focal length
92682
+ prevViewProj: mat4x4f,
92683
+ prevView: mat4x4f,
92684
+ prevClipZ: vec4f,
92685
+ viewport: vec2f,
92686
+ focal: vec2f,
92687
+ prevViewport: vec2f,
92688
+ prevFocal: vec2f,
92689
+ numChunks: u32,
92690
+ splatTextureSize: u32,
92691
+ isOrtho: u32,
92692
+ minPixelSize: f32,
92693
+ alphaClip: f32,
92694
+ minContribution: f32,
92695
+ // the occlusion grid: level 1 (8 px) and level 2 (32 px) block counts
92696
+ occBlocksX1: u32,
92697
+ occBlocksY1: u32,
92698
+ occBlocksX2: u32,
92699
+ occBlocksY2: u32,
92700
+ // 0 off, 1 level 1 only, 2 both levels
92701
+ occlusionMode: u32,
92702
+ // -1 when the previous depth texture's rows run bottom-up (an offscreen target), else 1
92703
+ prevFlip: f32,
92704
+ // the order key: bucket = (log(depth) - keyLogNear) * keyInvLogRange, over [0, 1)
92705
+ keyLogNear: f32,
92706
+ keyInvLogRange: f32,
92707
+ // first chunk-table entry of this dispatch (per-file sources dispatch one run each)
92708
+ chunkBase: u32,
92709
+ // the file's model transform, for sources that read splats in the file's own space
92710
+ model: mat4x4f,
92711
+ modelRotation: vec4f,
92712
+ modelScale: vec4f,
92713
+ cameraPosition: vec4f,
92714
+ // colour ceiling per channel: 8 keeps the cache's range, 1 clamps like the engine's 8-bit cache
92715
+ colorMax: f32,
92716
+ // 1: covariance in true pixels. 2: the engine's convention (its focal is viewport * proj[0][0],
92717
+ // twice the pixel focal), which makes its 0.3 dilation 0.075 px^2 and scales its culls
92718
+ unitScale: f32,
92719
+ // the view depths of the near plane and of the raster's far clamp
92720
+ depthNear: f32,
92721
+ depthFar: f32
92722
+ }
92723
+
92724
+ // chunk table entry: slotBase, count, node, lod | file << 16
92725
+ @group(0) @binding(0) var<storage, read> chunks: array<vec4u>;
92726
+ // one bit per node: 1 = inside the frustum this frame
92727
+ @group(0) @binding(1) var<storage, read> nodeVisible: array<u32>;
92728
+ @group(0) @binding(2) var<storage, read_write> cache: array<u32>;
92729
+ // [0] survivors this frame, [1] splats the occlusion cull removed
92730
+ @group(0) @binding(3) var<storage, read_write> counter: array<atomic<u32>>;
92731
+ @group(0) @binding(4) var<uniform> uniforms: ProjectorUniforms;
92732
+ // the previous frame's farthest depth per block, as f32 bits (see shaders/reduce.ts)
92733
+ @group(0) @binding(5) var<storage, read> occL1: array<u32>;
92734
+ @group(0) @binding(6) var<storage, read> occL2: array<u32>;
92735
+ // order:bucket: survivors per depth bucket (see shaders/order.ts)
92736
+ @group(0) @binding(7) var<storage, read_write> buckets: array<atomic<u32>>;
92737
+
92738
+ struct Splat {
92739
+ index: u32,
92740
+ uv: vec2i
92741
+ }
92742
+ var<private> splat: Splat;
92743
+ fn setSplat(idx: u32) {
92744
+ splat.index = idx;
92745
+ splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize));
92746
+ }
92747
+
92748
+ ${readChunk}
92749
+
92750
+ // quaternion (x, y, z, w) to a rotation matrix (columns)
92751
+ fn rotationMatrix(qIn: vec4f) -> mat3x3f {
92752
+ let q = normalize(qIn);
92753
+ let x = q.x;
92754
+ let y = q.y;
92755
+ let z = q.z;
92756
+ let w = q.w;
92757
+ return mat3x3f(
92758
+ vec3f(1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + w * z), 2.0 * (x * z - w * y)),
92759
+ vec3f(2.0 * (x * y - w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z + w * x)),
92760
+ vec3f(2.0 * (x * z + w * y), 2.0 * (y * z - w * x), 1.0 - 2.0 * (x * x + y * y))
92761
+ );
92762
+ }
92763
+
92764
+ struct Projected {
92765
+ valid: bool,
92766
+ occluded: bool,
92767
+ words: array<u32, ${CACHE_WORDS}>
92768
+ }
92769
+
92770
+ // The farthest depth over the (2g+1)^2 blocks around a block, on one grid level.
92771
+ fn farthestL1(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
92772
+ var farthest = 0u;
92773
+ for (var dy = -gather; dy <= gather; dy++) {
92774
+ for (var dx = -gather; dx <= gather; dx++) {
92775
+ farthest = max(farthest, occL1[u32((block.y + dy) * blocks.x + block.x + dx)]);
92776
+ }
92777
+ }
92778
+ return farthest;
92779
+ }
92780
+
92781
+ fn farthestL2(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
92782
+ var farthest = 0u;
92783
+ for (var dy = -gather; dy <= gather; dy++) {
92784
+ for (var dx = -gather; dx <= gather; dx++) {
92785
+ farthest = max(farthest, occL2[u32((block.y + dy) * blocks.x + block.x + dx)]);
92786
+ }
92787
+ }
92788
+ return farthest;
92789
+ }
92790
+
92791
+ fn project(slot: u32, file: u32) -> Projected {
92792
+ var result: Projected;
92793
+ result.valid = false;
92794
+ result.occluded = false;
92795
+
92796
+ setSplat(slot);
92797
+ let center = srcCenter();
92798
+ let opacity = srcOpacity();
92799
+ if (opacity < uniforms.alphaClip) {
92800
+ return result;
92801
+ }
92802
+
92803
+ let viewCenter = uniforms.view * vec4f(center, 1.0);
92804
+ let depth = -viewCenter.z;
92805
+ if (uniforms.isOrtho == 0u && depth <= 0.0) {
92806
+ return result;
92807
+ }
92808
+ let clip = uniforms.viewProj * vec4f(center, 1.0);
92809
+ if (clip.w == 0.0) {
92810
+ return result;
92811
+ }
92812
+
92813
+ let viewport = uniforms.viewport;
92814
+ let focal = uniforms.focal;
92815
+
92816
+ // the work buffer holds world-space splats, so the view matrix is the model-view
92817
+ let rot = srcRotation();
92818
+ let scale = srcScale();
92819
+ let linear = mat3x3f(uniforms.view[0].xyz, uniforms.view[1].xyz, uniforms.view[2].xyz);
92820
+ let gaussian = linear * rotationMatrix(vec4f(rot.yzw, rot.x)) * mat3x3f(
92821
+ vec3f(scale.x, 0.0, 0.0),
92822
+ vec3f(0.0, scale.y, 0.0),
92823
+ vec3f(0.0, 0.0, scale.z)
92824
+ );
92825
+ let row0 = vec3f(gaussian[0].x, gaussian[1].x, gaussian[2].x);
92826
+ let row1 = vec3f(gaussian[0].y, gaussian[1].y, gaussian[2].y);
92827
+ let row2 = vec3f(gaussian[0].z, gaussian[1].z, gaussian[2].z);
92828
+ let c00 = dot(row0, row0);
92829
+ let c01 = dot(row0, row1);
92830
+ let c02 = dot(row0, row2);
92831
+ let c11 = dot(row1, row1);
92832
+ let c12 = dot(row1, row2);
92833
+ let c22 = dot(row2, row2);
92834
+
92835
+ var cov00: f32;
92836
+ var cov01: f32;
92837
+ var cov11: f32;
92838
+ if (uniforms.isOrtho != 0u) {
92839
+ cov00 = focal.x * focal.x * c00;
92840
+ cov01 = focal.x * focal.y * c01;
92841
+ cov11 = focal.y * focal.y * c11;
92842
+ } else {
92843
+ let safeDepth = max(depth, 0.001);
92844
+ let invDepth = 1.0 / safeDepth;
92845
+ let jx0 = focal.x * invDepth;
92846
+ let jx2 = focal.x * viewCenter.x * invDepth * invDepth;
92847
+ let jy1 = focal.y * invDepth;
92848
+ let jy2 = focal.y * viewCenter.y * invDepth * invDepth;
92849
+ let u00 = jx0 * c00 + jx2 * c02;
92850
+ let u01 = jx0 * c01 + jx2 * c12;
92851
+ let u02 = jx0 * c02 + jx2 * c22;
92852
+ let u11 = jy1 * c11 + jy2 * c12;
92853
+ let u12 = jy1 * c12 + jy2 * c22;
92854
+ cov00 = u00 * jx0 + u02 * jx2;
92855
+ cov01 = u01 * jy1 + u02 * jy2;
92856
+ cov11 = u11 * jy1 + u12 * jy2;
92857
+ }
92858
+
92859
+ // the low-pass dilation every splat renderer applies, 0.3 in the chosen units
92860
+ let us2 = uniforms.unitScale * uniforms.unitScale;
92861
+ cov00 += 0.3 / us2;
92862
+ cov11 += 0.3 / us2;
92863
+ let determinant = cov00 * cov11 - cov01 * cov01;
92864
+ if (determinant <= 0.0) {
92865
+ return result;
92866
+ }
92867
+
92868
+ let mid = 0.5 * (cov00 + cov11);
92869
+ let radius = length(vec2f(0.5 * (cov00 - cov11), cov01));
92870
+ let lambda1 = mid + radius;
92871
+ let lambda2 = max(mid - radius, 0.1 / us2);
92872
+
92873
+ // size cull on the footprint's radius in pixels. minPixelSize is a diameter: the engine's
92874
+ // projector is dispatched with half of it, and its quad path tests the full extent
92875
+ // (2 sqrt(2 lambda)) against the whole value, so both cut at the same place
92876
+ if (uniforms.unitScale * sqrt(2.0 * lambda1) < 0.5 * uniforms.minPixelSize) {
92877
+ return result;
92878
+ }
92879
+
92880
+ // contribution cull: the splat's alpha mass in pixels (the engine's minContribution rule)
92881
+ if (opacity * 6.283185 * sqrt(determinant) * us2 < uniforms.minContribution) {
92882
+ return result;
92883
+ }
92884
+
92885
+ // principal axis; a circular footprint has no defined eigenvector, any axis is right
92886
+ let eigenVec = vec2f(cov01, lambda1 - cov00);
92887
+ let eigenLen = length(eigenVec);
92888
+ let direction = select(vec2f(1.0, 0.0), eigenVec / eigenLen, eigenLen > 1e-9);
92889
+ let maxRadius = min(1024.0, min(viewport.x, viewport.y));
92890
+ let len1 = 2.0 * sqrt(2.0 * lambda1);
92891
+ let radiusScale = min(1.0, maxRadius / len1);
92892
+ let axis1 = len1 * radiusScale * direction;
92893
+ let len2 = 2.0 * sqrt(2.0 * lambda2) * radiusScale;
92894
+ let axis2 = len2 * vec2f(direction.y, -direction.x);
92895
+
92896
+ let ndc = clip.xy / clip.w;
92897
+ let extent = abs(axis1) + abs(axis2);
92898
+ let centerPixels = (ndc * 0.5 + 0.5) * viewport;
92899
+ if (centerPixels.x + extent.x < 0.0 || centerPixels.x - extent.x > viewport.x
92900
+ || centerPixels.y + extent.y < 0.0 || centerPixels.y - extent.y > viewport.y) {
92901
+ return result;
92902
+ }
92903
+
92904
+ ${occlusion
92905
+ ? `
92906
+ // Occlusion cull against the previous frame. Each stored depth is the nearest sample that
92907
+ // survived there, so the farthest depth over the blocks a splat covered bounds what could
92908
+ // still have shown behind it; a splat whose front (its centre less 2 sqrt(2) sigma along the
92909
+ // view, the same cut-off as the quad's edge) lies beyond that bound was invisible last
92910
+ // frame, up to sampling. Static splats reproject exactly through the previous view, so only
92911
+ // true disocclusions arrive a frame late. The footprint the splat had last frame bounds the
92912
+ // gather; footprints up to 16 px use the 8 px grid, up to 64 px the 32 px grid, larger ones
92913
+ // skip the test.
92914
+ if (uniforms.occlusionMode != 0u) {
92915
+ let prevClip = uniforms.prevViewProj * vec4f(center, 1.0);
92916
+ let prevDepth = -(uniforms.prevView * vec4f(center, 1.0)).z;
92917
+ let prevOrtho = uniforms.prevClipZ.z != 0.0;
92918
+ if (prevClip.w > 0.0 && (prevOrtho || prevDepth > 0.0)) {
92919
+ let prevNdc = prevClip.xy / prevClip.w;
92920
+ let halfExtent = len1 * radiusScale;
92921
+ let prevHalfExtent = halfExtent * (uniforms.prevFocal.x / focal.x)
92922
+ * select(depth / max(prevDepth, 0.001), 1.0, prevOrtho);
92923
+ let footprint = max(halfExtent, prevHalfExtent);
92924
+ var level = 1u;
92925
+ var blockSize = 8.0;
92926
+ var blocks = vec2i(i32(uniforms.occBlocksX1), i32(uniforms.occBlocksY1));
92927
+ if (footprint > 16.0) {
92928
+ level = 2u;
92929
+ blockSize = 32.0;
92930
+ blocks = vec2i(i32(uniforms.occBlocksX2), i32(uniforms.occBlocksY2));
92931
+ }
92932
+ if (footprint <= 64.0 && level <= uniforms.occlusionMode) {
92933
+ let gather = max(i32(ceil(footprint / blockSize)), 1);
92934
+ let prevPixel = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * uniforms.prevFlip * 0.5) * uniforms.prevViewport;
92935
+ let block = vec2i(floor(prevPixel / blockSize));
92936
+ if (block.x >= gather && block.y >= gather && block.x < blocks.x - gather && block.y < blocks.y - gather) {
92937
+ let front = prevDepth - 2.8284 * sqrt(c22);
92938
+ let w = select(front, 1.0, prevOrtho);
92939
+ if (w > 0.0) {
92940
+ let frontZ = clamp(uniforms.prevClipZ.x * front + uniforms.prevClipZ.y, 0.0, w) / w;
92941
+ // the block under the centre first: the neighbourhood's maximum is at
92942
+ // least its maximum, so a splat that block alone cannot cull is visible,
92943
+ // and most splats leave here after one load
92944
+ let centreIndex = u32(block.y * blocks.x + block.x);
92945
+ var farthest = select(occL1[centreIndex], occL2[centreIndex], level == 2u);
92946
+ if (frontZ > bitcast<f32>(farthest)) {
92947
+ if (level == 1u) {
92948
+ farthest = farthestL1(block, gather, blocks);
92949
+ } else {
92950
+ farthest = farthestL2(block, gather, blocks);
92951
+ }
92952
+ if (frontZ > bitcast<f32>(farthest)) {
92953
+ result.occluded = true;
92954
+ return result;
92955
+ }
92956
+ }
92957
+ }
92958
+ }
92959
+ }
92960
+ }
92961
+ }
92962
+
92963
+ `
92964
+ : ''}
92965
+ let color = clamp(srcColor(), vec3f(0.0), vec3f(uniforms.colorMax));
92966
+
92967
+ // rgb: 10/10/10 unorm with a 2-bit shared exponent (scale 1/2/4/8, range [0, 8])
92968
+ let maxChannel = max(color.r, max(color.g, color.b));
92969
+ var exponent = 0u;
92970
+ if (maxChannel > 4.0) {
92971
+ exponent = 3u;
92972
+ } else if (maxChannel > 2.0) {
92973
+ exponent = 2u;
92974
+ } else if (maxChannel > 1.0) {
92975
+ exponent = 1u;
92976
+ }
92977
+ let rgb = vec3u(clamp(color / f32(1u << exponent), vec3f(0.0), vec3f(1.0)) * 1023.0 + 0.5);
92978
+
92979
+ // centre as snorm16 over the range the offscreen cull bounds visible centres to; the
92980
+ // raster shader derives the same range from its viewport
92981
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / viewport;
92982
+
92983
+ result.valid = true;
92984
+ result.words[0] = pack2x16snorm(ndc / ndcRange);
92985
+ result.words[1] = bitcast<u32>(depth);
92986
+ result.words[2] = pack2x16float(axis1);
92987
+ result.words[3] = pack2x16float(vec2f(len2, 0.0)) | (u32(clamp(opacity, 0.0, 1.0) * 255.0 + 0.5) << 16u);
92988
+ ${order
92989
+ ? `
92990
+ // the depth bucket, log-spaced from the near plane, in the flags byte
92991
+ let key = clamp((log(max(depth, 1e-6)) - uniforms.keyLogNear) * uniforms.keyInvLogRange, 0.0, 0.999) * ${ORDER_BUCKETS}.0;
92992
+ result.words[3] |= u32(key) << 24u;
92993
+ `
92994
+ : ''}
92995
+ result.words[4] = rgb.r | (rgb.g << 10u) | (rgb.b << 20u) | (exponent << 30u);
92996
+ // Popless depth (StochasticSplats 3.4): the quad is tilted onto the plane through the
92997
+ // centre with normal adj(Sigma) mu (view space; adj rather than the inverse, so a flat
92998
+ // splat needs no division by its tiny determinant), and the raster gives each corner the
92999
+ // depth where its own view ray meets that plane, so hardware interpolation hands every
93000
+ // fragment the depth of the Gaussian's peak along its ray instead of the centre's. Stored
93001
+ // as g = n.xy / (n . mu): a corner at view offset d (in the plane z = -depth) lands at
93002
+ // depth / (1 + g . d). Orthographic rays are parallel, so there n = adj(Sigma) e_z and
93003
+ // the corner depth is depth + g . d with g = n.xy / n.z. Bounded so every corner stays
93004
+ // within 2 sqrt(2) sigma_z of the centre (the occlusion cull's front margin) and the
93005
+ // perspective scale stays positive, and so no corner crosses the near plane or the
93006
+ // raster's far clamp: a corner clamped there while the others are not bends the quad, whose
93007
+ // two triangles then take different depths and show as polygons (large far splats, the
93008
+ // sky, sit right at a far plane fitted to the scene). A centre beyond the clamp stays flat.
93009
+ let ortho = uniforms.isOrtho != 0u;
93010
+ let a00 = c11 * c22 - c12 * c12;
93011
+ let a01 = c02 * c12 - c01 * c22;
93012
+ let a02 = c01 * c12 - c02 * c11;
93013
+ let a11 = c00 * c22 - c02 * c02;
93014
+ let a12 = c01 * c02 - c00 * c12;
93015
+ let a22 = c00 * c11 - c01 * c01;
93016
+ let toward = select(viewCenter.xyz, vec3f(0.0, 0.0, -1.0), ortho);
93017
+ let n = vec3f(
93018
+ a00 * toward.x + a01 * toward.y + a02 * toward.z,
93019
+ a01 * toward.x + a11 * toward.y + a12 * toward.z,
93020
+ a02 * toward.x + a12 * toward.y + a22 * toward.z
93021
+ );
93022
+ let denom = select(dot(n, viewCenter.xyz), n.z, ortho);
93023
+ var g = vec2f(0.0);
93024
+ if (abs(denom) > 1e-20) {
93025
+ g = n.xy / denom;
93026
+ // view units per pixel at the centre's depth, and the quad's half extents in them
93027
+ let viewScale = select(depth, 1.0, ortho) / focal;
93028
+ let ext = (abs(axis1) + abs(axis2)) * viewScale;
93029
+ let bound = abs(g.x) * ext.x + abs(g.y) * ext.y;
93030
+ let margin = 2.8284 * sqrt(max(c22, 0.0));
93031
+ let inRange = select(
93032
+ min(1.0 - depth / uniforms.depthFar, depth / max(uniforms.depthNear, 1e-6) - 1.0),
93033
+ min(uniforms.depthFar - depth, depth - uniforms.depthNear),
93034
+ ortho
93035
+ );
93036
+ let limit = max(0.0, min(select(min(0.25, margin / max(depth, 1e-6)), margin, ortho), 0.999 * inRange));
93037
+ if (bound > limit) {
93038
+ g *= limit / max(bound, 1e-20);
93039
+ }
93040
+ }
93041
+ result.words[5] = pack2x16float(g);
93042
+ // the stable id the coverage hash seeds from: the slot, salted by the file for sources
93043
+ // whose indices restart per file
93044
+ result.words[6] = slot ^ (file * 2654435761u);
93045
+ return result;
93046
+ }
93047
+
93048
+ var<workgroup> wgCount: atomic<u32>;
93049
+ var<workgroup> wgOccluded: atomic<u32>;
93050
+ var<workgroup> wgBase: u32;
93051
+ ${order ? `var<workgroup> wgBuckets: array<atomic<u32>, ${ORDER_BUCKETS}>;` : ''}
93052
+
93053
+ @compute @workgroup_size(${PROJECTOR_WORKGROUP_SIZE})
93054
+ fn main(
93055
+ @builtin(workgroup_id) wg: vec3u,
93056
+ @builtin(num_workgroups) numWorkgroups: vec3u,
93057
+ @builtin(local_invocation_index) local: u32
93058
+ ) {
93059
+ // no early returns: the barriers below need every thread of the workgroup
93060
+ let chunkIndex = wg.x + wg.y * numWorkgroups.x;
93061
+ ${order ? ` atomicStore(&wgBuckets[local], 0u);` : ''}
93062
+ var projected: Projected;
93063
+ projected.valid = false;
93064
+ projected.occluded = false;
93065
+ if (chunkIndex < uniforms.numChunks) {
93066
+ let chunk = chunks[uniforms.chunkBase + chunkIndex];
93067
+ let visible = (nodeVisible[chunk.z >> 5u] >> (chunk.z & 31u)) & 1u;
93068
+ if (visible != 0u && local < chunk.y) {
93069
+ projected = project(chunk.x + local, chunk.w >> 16u);
93070
+ }
93071
+ }
93072
+
93073
+ // survivors claim consecutive slots: one workgroup-local count, one global atomic
93074
+ var localSlot = 0u;
93075
+ if (projected.valid) {
93076
+ localSlot = atomicAdd(&wgCount, 1u);
93077
+ }
93078
+ if (projected.occluded) {
93079
+ atomicAdd(&wgOccluded, 1u);
93080
+ }
93081
+ workgroupBarrier();
93082
+ if (local == 0u) {
93083
+ let n = atomicLoad(&wgCount);
93084
+ wgBase = select(0u, atomicAdd(&counter[0], n), n > 0u);
93085
+ let o = atomicLoad(&wgOccluded);
93086
+ if (o > 0u) {
93087
+ atomicAdd(&counter[1], o);
93088
+ }
93089
+ }
93090
+ workgroupBarrier();
93091
+ if (projected.valid) {
93092
+ let base = (wgBase + localSlot) * ${CACHE_WORDS}u;
93093
+ for (var i = 0u; i < ${CACHE_WORDS}u; i++) {
93094
+ cache[base + i] = projected.words[i];
93095
+ }
93096
+ ${order ? ` atomicAdd(&wgBuckets[projected.words[3] >> 24u], 1u);` : ''}
93097
+ }
93098
+ ${order
93099
+ ? `
93100
+ // a chunk's splats are spatially coherent, so few of its buckets are non-empty: one
93101
+ // workgroup count each, then one global atomic per non-empty bucket
93102
+ workgroupBarrier();
93103
+ let bucketCount = atomicLoad(&wgBuckets[local]);
93104
+ if (bucketCount > 0u) {
93105
+ atomicAdd(&buckets[local], bucketCount);
93106
+ }
93107
+ `
93108
+ : ''}
93109
+ }
93110
+ `;
93111
+
93112
+ // The ordering passes (variant order:bucket): the projector counts its survivors into 256
93113
+ // depth buckets, front to back; a one-workgroup scan turns the counts into bucket offsets, and
93114
+ // the scatter writes each survivor's cache slot into the ordered list the raster then follows.
93115
+ // Splats inside a bucket land in append order, so a bucket keeps its chunks' locality.
93116
+ // exclusive prefix sum of the bucket counts into the bucket offsets, in one workgroup
93117
+ const orderScanWGSL = /* wgsl */ `
93118
+ // [0, ${ORDER_BUCKETS}) counts, [${ORDER_BUCKETS}, ${2 * ORDER_BUCKETS}) offsets
93119
+ @group(0) @binding(0) var<storage, read_write> buckets: array<u32>;
93120
+
93121
+ var<workgroup> partial: array<u32, ${ORDER_BUCKETS}>;
93122
+
93123
+ @compute @workgroup_size(${ORDER_BUCKETS})
93124
+ fn main(@builtin(local_invocation_index) local: u32) {
93125
+ partial[local] = buckets[local];
93126
+ for (var stride = 1u; stride < ${ORDER_BUCKETS}u; stride <<= 1u) {
93127
+ workgroupBarrier();
93128
+ let value = select(0u, partial[local - stride], local >= stride);
93129
+ workgroupBarrier();
93130
+ partial[local] += value;
93131
+ }
93132
+ // inclusive to exclusive
93133
+ buckets[${ORDER_BUCKETS}u + local] = partial[local] - buckets[local];
93134
+ }
93135
+ `;
93136
+ // One thread per cache slot, one workgroup per 256 consecutive slots. Consecutive slots come
93137
+ // from one chunk, so a workgroup touches few buckets: it counts them locally, claims each
93138
+ // bucket's range with one global atomic, and places its splats in append order inside it.
93139
+ const orderScatterWGSL = /* wgsl */ `
93140
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
93141
+ @group(0) @binding(1) var<storage, read> cache: array<u32>;
93142
+ @group(0) @binding(2) var<storage, read_write> buckets: array<atomic<u32>>;
93143
+ @group(0) @binding(3) var<storage, read_write> ordered: array<u32>;
93144
+
93145
+ var<workgroup> wgCounts: array<atomic<u32>, ${ORDER_BUCKETS}>;
93146
+ var<workgroup> wgBase: array<u32, ${ORDER_BUCKETS}>;
93147
+
93148
+ @compute @workgroup_size(${ORDER_BUCKETS})
93149
+ fn main(
93150
+ @builtin(workgroup_id) wg: vec3u,
93151
+ @builtin(num_workgroups) numWorkgroups: vec3u,
93152
+ @builtin(local_invocation_index) local: u32
93153
+ ) {
93154
+ // no early returns: the barriers need every thread
93155
+ atomicStore(&wgCounts[local], 0u);
93156
+ let slot = (wg.x + wg.y * numWorkgroups.x) * ${ORDER_BUCKETS}u + local;
93157
+ let live = slot < counter[0];
93158
+ var key = 0u;
93159
+ var rank = 0u;
93160
+ workgroupBarrier();
93161
+ if (live) {
93162
+ key = cache[slot * ${CACHE_WORDS}u + 3u] >> 24u;
93163
+ rank = atomicAdd(&wgCounts[key], 1u);
93164
+ }
93165
+ workgroupBarrier();
93166
+ let count = atomicLoad(&wgCounts[local]);
93167
+ if (count > 0u) {
93168
+ wgBase[local] = atomicAdd(&buckets[${ORDER_BUCKETS}u + local], count);
93169
+ }
93170
+ workgroupBarrier();
93171
+ if (live) {
93172
+ ordered[wgBase[key] + rank] = slot;
93173
+ }
93174
+ }
93175
+ `;
93176
+
93177
+ // The raster pass: an indirect instanced draw of 128-quad meshes over the projector's
93178
+ // survivors, into the renderer's own colour + depth target. Fragments keep themselves with
93179
+ // probability alpha (StochasticSplats, Listing 1) and write opaque colour with hardware depth,
93180
+ // so no sort is needed and the depth buffer holds the nearest surviving sample per pixel.
93181
+ /** Quads per draw instance; the mesh holds this many quads. */
93182
+ const QUADS_PER_INSTANCE = 128;
93183
+ /** The raster's far clamp in normalised depth: just inside 1, which the compose reads as empty. */
93184
+ const FAR_CLIP_Z = 0.999999;
93185
+ const rasterVertexWGSL = /* wgsl */ `
93186
+ attribute vertex_position: vec3f;
93187
+
93188
+ // width, height, 2 / width, 2 / height
93189
+ uniform viewportSize: vec4f;
93190
+ // clip z = a * viewDepth + b (x, y); z = 1 for an orthographic camera
93191
+ uniform clipZParams: vec4f;
93192
+ // set by the engine's forward renderer for the target being rendered
93193
+ uniform projectionFlipY: f32;
93194
+ // focal length in pixels (x, y), for the popless corner depths
93195
+ uniform focalParams: vec4f;
93196
+
93197
+ var<storage, read> splatCache: array<u32>;
93198
+ var<storage, read> splatCount: array<u32>;
93199
+ #ifdef SSE_ORDERED
93200
+ // cache slots in draw order (variant order:bucket)
93201
+ var<storage, read> orderedSlots: array<u32>;
93202
+ #endif
93203
+
93204
+ // screen-linear: the corners share one screen footprint whatever depth they carry
93205
+ varying @interpolate(linear) gaussianUV: vec2f;
93206
+ varying @interpolate(flat, either) packedColor: u32;
93207
+ varying @interpolate(flat, either) packedAlpha: u32;
93208
+ varying @interpolate(flat, either) splatId: u32;
93209
+
93210
+ const discardPosition = vec4f(0.0, 0.0, 2.0, 1.0);
93211
+
93212
+ @vertex
93213
+ fn vertexMain(input: VertexInput) -> VertexOutput {
93214
+ var output: VertexOutput;
93215
+ let order = pcInstanceIndex * ${QUADS_PER_INSTANCE}u + u32(vertex_position.z);
93216
+ // the indirect instance count rounds up to whole instances; the tail is discarded here
93217
+ if (order >= splatCount[0]) {
93218
+ output.position = discardPosition;
93219
+ return output;
93220
+ }
93221
+
93222
+ #ifdef SSE_ORDERED
93223
+ let base = orderedSlots[order] * ${CACHE_WORDS}u;
93224
+ #else
93225
+ let base = order * ${CACHE_WORDS}u;
93226
+ #endif
93227
+ let maxRadius = min(1024.0, min(uniform.viewportSize.x, uniform.viewportSize.y));
93228
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / uniform.viewportSize.xy;
93229
+ let ndc = unpack2x16snorm(splatCache[base]) * ndcRange;
93230
+ let depth = bitcast<f32>(splatCache[base + 1u]);
93231
+ let ortho = uniform.clipZParams.z != 0.0;
93232
+
93233
+ let axis1 = unpack2x16float(splatCache[base + 2u]);
93234
+ let word3 = splatCache[base + 3u];
93235
+ let len2 = unpack2x16float(word3).x;
93236
+ let axis2 = len2 * normalize(vec2f(axis1.y, -axis1.x));
93237
+
93238
+ let corner = vertex_position.xy;
93239
+ let pixelOffset = corner.x * axis1 + corner.y * axis2;
93240
+ #ifdef SSE_POPLESS
93241
+ // the corner's depth on the splat's plane (see the projector): its view-space offset
93242
+ // at the centre's depth, times the stored gradient
93243
+ let g = unpack2x16float(splatCache[base + 5u]);
93244
+ let shift = dot(g, pixelOffset * select(depth, 1.0, ortho) / uniform.focalParams.xy);
93245
+ let cornerDepth = select(depth / (1.0 + shift), depth + shift, ortho);
93246
+ #else
93247
+ let cornerDepth = depth;
93248
+ #endif
93249
+ let w = select(cornerDepth, 1.0, ortho);
93250
+ let ndcCorner = ndc + pixelOffset * uniform.viewportSize.zw;
93251
+ // clip z clamped into range like the engine's splat shader, so splats beyond the far plane
93252
+ // still draw; just inside it, since the compose and the accumulation read depth 1 as empty
93253
+ let pos = vec4f(ndcCorner * w, clamp(uniform.clipZParams.x * cornerDepth + uniform.clipZParams.y, 0.0, w * ${FAR_CLIP_Z}), w);
93254
+ output.position = vec4f(pos.x, pos.y * uniform.projectionFlipY, pos.z, pos.w);
93255
+ output.gaussianUV = corner;
93256
+ output.packedColor = splatCache[base + 4u];
93257
+ output.packedAlpha = word3 >> 16u;
93258
+ output.splatId = splatCache[base + 6u];
93259
+ return output;
93260
+ }
93261
+ `;
93262
+ const rasterFragmentWGSL = /* wgsl */ `
93263
+ varying @interpolate(linear) gaussianUV: vec2f;
93264
+ varying @interpolate(flat, either) packedColor: u32;
93265
+ varying @interpolate(flat, either) packedAlpha: u32;
93266
+ varying @interpolate(flat, either) splatId: u32;
93267
+
93268
+ uniform sseAlphaClip: f32;
93269
+ // 0 while the camera rests, so a still frame reproduces itself; the frame index once TAA
93270
+ // accumulates
93271
+ uniform frameSeed: u32;
93272
+
93273
+ const EXP4 = exp(-4.0);
93274
+ const INV_EXP4 = 1.0 / (1.0 - EXP4);
93275
+
93276
+ // the engine's falloff: zero at the quad edge, which sits at 2 sqrt(2) sigma
93277
+ fn normExp(x: f32) -> f32 {
93278
+ return (exp(x * -4.0) - EXP4) * INV_EXP4;
93279
+ }
93280
+
93281
+ // integer hash (Wellons' prospector mix)
93282
+ fn hashU32(x: u32) -> u32 {
93283
+ var v = x;
93284
+ v ^= v >> 16u;
93285
+ v *= 0x7feb352du;
93286
+ v ^= v >> 15u;
93287
+ v *= 0x846ca68bu;
93288
+ v ^= v >> 16u;
93289
+ return v;
93290
+ }
93291
+
93292
+ @fragment
93293
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
93294
+ var output: FragmentOutput;
93295
+ let radius = dot(gaussianUV, gaussianUV);
93296
+ if (radius > 1.0) {
93297
+ discard;
93298
+ }
93299
+ let opacity = f32(packedAlpha & 0xffu) / 255.0;
93300
+ let alpha = normExp(radius) * opacity;
93301
+ if (alpha < uniform.sseAlphaClip) {
93302
+ discard;
93303
+ }
93304
+
93305
+ let pix = vec2u(pcPosition.xy);
93306
+ #ifdef SSE_SPP_QUAD
93307
+ // one sample per pixel, thresholds stratified over each 2x2 pixel quad: the quad's four
93308
+ // pixels take the four strata of [0, 1) in a per-(quad, splat) scrambled order, so a
93309
+ // splat with alpha a covers 4a +- 1 of its quad and the compose's quad mean is nearly
93310
+ // exact. Hashing quad and splat keeps overlapping splats decorrelated
93311
+ let quad = pix >> vec2u(1u);
93312
+ let h = hashU32((quad.x * 1973u) ^ (quad.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
93313
+ let stratum = ((pix.y & 1u) * 2u + (pix.x & 1u)) ^ (h & 3u);
93314
+ let rnd = (f32(stratum) + f32(h >> 8u) * (1.0 / 16777216.0)) * 0.25;
93315
+ #else
93316
+ let h = hashU32((pix.x * 1973u) ^ (pix.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
93317
+ let rnd = f32(h >> 8u) * (1.0 / 16777216.0);
93318
+ #endif
93319
+ if (rnd >= alpha) {
93320
+ discard;
93321
+ }
93322
+
93323
+ let bits = packedColor;
93324
+ let color = vec3f(vec3u(bits, bits >> 10u, bits >> 20u) & vec3u(1023u)) * (f32(1u << (bits >> 30u)) / 1023.0);
93325
+ // opaque coverage: the compose reads alpha 1 as "a sample landed here"
93326
+ output.color = vec4f(color, 1.0);
93327
+ return output;
93328
+ }
93329
+ `;
93330
+
93331
+ // The occlusion grid: the previous frame's depth texture reduced to the farthest depth per 8x8
93332
+ // pixel block (level 1), and the farthest of each 4x4 group of those (level 2, 32 px). Each
93333
+ // pixel's depth is the nearest surviving sample there, so a block's maximum bounds what could
93334
+ // still have shown behind it; a splat whose front lies beyond that bound over every block it
93335
+ // covers was invisible last frame. Depths are hardware z in [0, 1], stored as their f32 bits
93336
+ // (non-negative floats order the same as their bits, so atomicMax works on them).
93337
+ const reduceL1WGSL = /* wgsl */ `
93338
+ struct ReduceUniforms {
93339
+ width: u32,
93340
+ height: u32,
93341
+ blocksX: u32,
93342
+ blocksY: u32
93343
+ }
93344
+
93345
+ @group(0) @binding(0) var prevDepth: texture_depth_2d;
93346
+ @group(0) @binding(1) var<storage, read_write> blockMax: array<u32>;
93347
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
93348
+
93349
+ var<workgroup> wgMax: atomic<u32>;
93350
+
93351
+ @compute @workgroup_size(8, 8)
93352
+ fn main(
93353
+ @builtin(workgroup_id) wg: vec3u,
93354
+ @builtin(local_invocation_id) lid: vec3u,
93355
+ @builtin(local_invocation_index) li: u32
93356
+ ) {
93357
+ let pixel = wg.xy * 8u + lid.xy;
93358
+ // pixels off the texture count as far, so an edge block never culls
93359
+ var depth = 1.0;
93360
+ if (pixel.x < uniforms.width && pixel.y < uniforms.height) {
93361
+ depth = textureLoad(prevDepth, vec2i(pixel), 0);
93362
+ }
93363
+ atomicMax(&wgMax, bitcast<u32>(depth));
93364
+ workgroupBarrier();
93365
+ if (li == 0u) {
93366
+ blockMax[wg.y * uniforms.blocksX + wg.x] = atomicLoad(&wgMax);
93367
+ }
93368
+ }
93369
+ `;
93370
+ const reduceL2WGSL = /* wgsl */ `
93371
+ struct ReduceUniforms {
93372
+ blocksX1: u32,
93373
+ blocksY1: u32,
93374
+ blocksX2: u32,
93375
+ blocksY2: u32
93376
+ }
93377
+
93378
+ @group(0) @binding(0) var<storage, read> level1: array<u32>;
93379
+ @group(0) @binding(1) var<storage, read_write> level2: array<u32>;
93380
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
93381
+
93382
+ @compute @workgroup_size(64)
93383
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
93384
+ let index = gid.x;
93385
+ if (index >= uniforms.blocksX2 * uniforms.blocksY2) {
93386
+ return;
93387
+ }
93388
+ let bx = index % uniforms.blocksX2;
93389
+ let by = index / uniforms.blocksX2;
93390
+ var farthest = 0u;
93391
+ for (var dy = 0u; dy < 4u; dy++) {
93392
+ for (var dx = 0u; dx < 4u; dx++) {
93393
+ let x = bx * 4u + dx;
93394
+ let y = by * 4u + dy;
93395
+ if (x < uniforms.blocksX1 && y < uniforms.blocksY1) {
93396
+ farthest = max(farthest, level1[y * uniforms.blocksX1 + x]);
93397
+ } else {
93398
+ farthest = max(farthest, bitcast<u32>(1.0));
93399
+ }
93400
+ }
93401
+ }
93402
+ level2[index] = farthest;
93403
+ }
93404
+ `;
93405
+
93406
+ // Data path (ii): the projector reads each resident file's own textures (sog, ply or
93407
+ // compressed ply) through the engine's format read chunks, so nothing is copied into a work
93408
+ // buffer: no decoded 24-byte copy per splat, no re-copy when a node's lod changes, no
93409
+ // colour refresh when the camera turns. The price is one dispatch per resident file, the
93410
+ // model transform and the sh evaluation per splat per frame.
93411
+ //
93412
+ // Interim: the engine still allocates its work buffer and would keep copying into it, so the
93413
+ // copy passes are switched off on the work buffer this source sees; the textures themselves
93414
+ // stay until engine change E2 (no work buffer in external mode) lands.
93415
+ const tmpScale = new Vec3();
93416
+ const tmpRotation = new Quat();
93417
+ class DirectSplatSource {
93418
+ kind = 'direct';
93419
+ device;
93420
+ resource = null;
93421
+ set = null;
93422
+ constants = new Map();
93423
+ patched = null;
93424
+ constructor(device) {
93425
+ this.device = device;
93426
+ }
93427
+ update(set, manager) {
93428
+ // one format per scene: a sog lod set shares its format across files. The first file's
93429
+ // format compiles the projector; a file of another format is skipped by dispatchPlan
93430
+ this.resource = set.files[0]?.resource ?? this.resource;
93431
+ this.set = set;
93432
+ this.constants.clear();
93433
+ for (const file of set.files) {
93434
+ const m = file.modelMatrix;
93435
+ m.getScale(tmpScale);
93436
+ tmpRotation.setFromMat4(m);
93437
+ if (tmpRotation.w < 0)
93438
+ tmpRotation.mulScalar(-1);
93439
+ this.constants.set(file.fileIndex, {
93440
+ rotation: [tmpRotation.x, tmpRotation.y, tmpRotation.z, tmpRotation.w],
93441
+ scale: [tmpScale.x, tmpScale.y, tmpScale.z, 0]
93442
+ });
93443
+ }
93444
+ this.patchWorkBuffer(manager.world.workBuffer);
93445
+ }
93446
+ // the engine's copy into the work buffer is wasted work for this path
93447
+ patchWorkBuffer(workBuffer) {
93448
+ if (this.patched?.workBuffer === workBuffer)
93449
+ return;
93450
+ this.restoreWorkBuffer();
93451
+ this.patched = { workBuffer, render: workBuffer.render, renderColor: workBuffer.renderColor };
93452
+ const skip = () => undefined;
93453
+ workBuffer.render = skip;
93454
+ workBuffer.renderColor = skip;
93455
+ }
93456
+ restoreWorkBuffer() {
93457
+ if (!this.patched)
93458
+ return;
93459
+ const { workBuffer, render, renderColor } = this.patched;
93460
+ workBuffer.render = render;
93461
+ workBuffer.renderColor = renderColor;
93462
+ this.patched = null;
93463
+ }
93464
+ readChunk(bindingBase) {
93465
+ const format = this.require().format;
93466
+ // The format's read chunk reads the file's own space and returns sh0 colour + alpha;
93467
+ // the adapter below applies the file's model transform and evaluates its sh for this
93468
+ // camera. Its loose `uniform` and texture declarations (dequantisation constants, the
93469
+ // compressed format's chunk texture) are reflected by the engine into a second bind
93470
+ // group and set by name like any other parameter.
93471
+ // The engine writes its 32-bit float streams (the sog v2 codebook) as `texture_2d<uff>`,
93472
+ // an alias only its reflection of loose declarations resolves; explicit bindings need
93473
+ // the wgsl type, and the matching unfilterable sample type in bindFormats()
93474
+ const declarations = format
93475
+ .getComputeInputDeclarations(bindingBase)
93476
+ .replace(/texture_2d<uff>/g, 'texture_2d<f32>');
93477
+ return /* wgsl */ `
93478
+ #include "halfTypesCS"
93479
+ #include "gsplatEvalSHVS"
93480
+ ${declarations}
93481
+ ${format.getReadCode()}
93482
+
93483
+ var<private> srcWorldCenter: vec3f;
93484
+ var<private> srcColorCache: vec4f;
93485
+
93486
+ fn quatMulF(a: vec4f, b: vec4f) -> vec4f {
93487
+ return vec4f(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
93488
+ }
93489
+
93490
+ // v rotated by the inverse of q (x, y, z, w)
93491
+ fn quatRotateInvF(q: vec4f, v: vec3f) -> vec3f {
93492
+ let u = -q.xyz;
93493
+ return v + 2.0 * cross(u, cross(u, v) + q.w * v);
93494
+ }
93495
+
93496
+ fn srcCenter() -> vec3f {
93497
+ srcWorldCenter = (uniforms.model * vec4f(getCenter(), 1.0)).xyz;
93498
+ return srcWorldCenter;
93499
+ }
93500
+
93501
+ fn srcOpacity() -> f32 {
93502
+ srcColorCache = getColor();
93503
+ return srcColorCache.a;
93504
+ }
93505
+
93506
+ // the format returns (w, x, y, z); world = model * source
93507
+ fn srcRotation() -> vec4f {
93508
+ let q = quatMulF(uniforms.modelRotation, getRotation().yzwx);
93509
+ return q.wxyz;
93510
+ }
93511
+
93512
+ fn srcScale() -> vec3f {
93513
+ return uniforms.modelScale.xyz * getScale();
93514
+ }
93515
+
93516
+ fn srcColor() -> vec3f {
93517
+ var color = srcColorCache.rgb;
93518
+ #if SH_BANDS > 0
93519
+ // the view direction in the file's space; orthographic rays all run along the camera forward
93520
+ let view = uniforms.view;
93521
+ let orthoDir = vec3f(0.0, 0.0, -1.0) * mat3x3f(view[0].xyz, view[1].xyz, view[2].xyz);
93522
+ let viewDir = select(srcWorldCenter - uniforms.cameraPosition.xyz, orthoDir, uniforms.isOrtho != 0u);
93523
+ let dir = normalize(quatRotateInvF(uniforms.modelRotation, viewDir));
93524
+ var sh: array<half3, SH_COEFFS>;
93525
+ var shScale: f32;
93526
+ readSHData(&sh, &shScale);
93527
+ color += vec3f(evalSH(&sh, dir) * half(shScale));
93528
+ #endif
93529
+ return color;
93530
+ }
93531
+ `;
93532
+ }
93533
+ bindFormats() {
93534
+ const format = this.require().format;
93535
+ const entries = format.getComputeBindFormats();
93536
+ for (const entry of entries) {
93537
+ const stream = format.streams.find((s) => s.name === entry.name);
93538
+ if (stream?.format === PIXELFORMAT_RGBA32F)
93539
+ entry.sampleType = SAMPLETYPE_UNFILTERABLE_FLOAT;
93540
+ }
93541
+ return entries;
93542
+ }
93543
+ shaderIncludes() {
93544
+ // the read chunks include the engine's own gsplat chunks by name
93545
+ return new Map(ShaderChunks.get(this.device, SHADERLANGUAGE_WGSL));
93546
+ }
93547
+ shaderDefines() {
93548
+ const defines = new Map();
93549
+ this.require().configureMaterialDefines(defines);
93550
+ return defines;
93551
+ }
93552
+ chunkBase(node) {
93553
+ return node.sourceBase;
93554
+ }
93555
+ dispatchPlan(set) {
93556
+ // one run of the chunk table per file (the table is built file by file)
93557
+ const groups = [];
93558
+ let chunkBase = 0;
93559
+ const hash = this.resource?.format.hash;
93560
+ for (const file of set.files) {
93561
+ let chunkCount = 0;
93562
+ for (const node of file.nodes)
93563
+ chunkCount += Math.ceil(node.count / 256);
93564
+ if (chunkCount > 0 && file.resource.format.hash === hash) {
93565
+ groups.push({ fileIndex: file.fileIndex, chunkBase, chunkCount });
93566
+ }
93567
+ chunkBase += chunkCount;
93568
+ }
93569
+ return groups;
93570
+ }
93571
+ bind(compute, group, set) {
93572
+ const file = set.files[group.fileIndex];
93573
+ const { resource } = file;
93574
+ for (const [name, texture] of resource.streams.textures) {
93575
+ compute.setParameter(name, texture);
93576
+ }
93577
+ for (const [name, value] of resource.parameters) {
93578
+ compute.setParameter(name, value);
93579
+ }
93580
+ const constants = this.constants.get(file.fileIndex);
93581
+ compute.setParameter('model', file.modelMatrix.data);
93582
+ compute.setParameter('modelRotation', constants.rotation);
93583
+ compute.setParameter('modelScale', constants.scale);
93584
+ }
93585
+ textureSize(group) {
93586
+ return this.set?.files[group.fileIndex].resource.textureDimensions.x ?? 0;
93587
+ }
93588
+ gpuBytes() {
93589
+ // the file textures belong to the engine and are counted by app.stats.vram
93590
+ return 0;
93591
+ }
93592
+ shaderKey() {
93593
+ const resource = this.resource;
93594
+ if (!resource)
93595
+ return 'direct:';
93596
+ const defines = this.shaderDefines();
93597
+ return `direct:${resource.format.hash}:${[...defines].map(([k, v]) => `${k}=${v}`).join(',')}`;
93598
+ }
93599
+ destroy() {
93600
+ this.restoreWorkBuffer();
93601
+ this.resource = null;
93602
+ this.set = null;
93603
+ this.constants.clear();
93604
+ }
93605
+ require() {
93606
+ if (!this.resource)
93607
+ throw new Error('DirectSplatSource: update() has not run');
93608
+ return this.resource;
93609
+ }
93610
+ }
93611
+
93612
+ class WorkBufferSplatSource {
93613
+ kind = 'workbuffer';
93614
+ workBuffer = null;
93615
+ update(set, manager) {
93616
+ this.workBuffer = manager.world.workBuffer;
93617
+ }
93618
+ readChunk(bindingBase) {
93619
+ const format = this.require().format;
93620
+ // the engine's declarations bind one texture per stream from bindingBase and define
93621
+ // loadDataX(); its read code decodes them into getCenter() and friends, already in
93622
+ // world space with the sh colour baked for this camera
93623
+ return /* wgsl */ `
93624
+ ${format.getComputeInputDeclarations(bindingBase)}
93625
+ ${format.getReadCode()}
93626
+ fn srcCenter() -> vec3f { return getCenter(); }
93627
+ fn srcOpacity() -> f32 { return getOpacity(); }
93628
+ fn srcRotation() -> vec4f { return getRotation(); }
93629
+ fn srcScale() -> vec3f { return getScale(); }
93630
+ fn srcColor() -> vec3f { return getColor(); }
93631
+ `;
93632
+ }
93633
+ bindFormats() {
93634
+ return this.require().format.getComputeBindFormats();
93635
+ }
93636
+ shaderIncludes() {
93637
+ return undefined;
93638
+ }
93639
+ shaderDefines() {
93640
+ return undefined;
93641
+ }
93642
+ chunkBase(node) {
93643
+ return node.slotBase;
93644
+ }
93645
+ dispatchPlan(set, numChunks) {
93646
+ return [{ fileIndex: -1, chunkBase: 0, chunkCount: numChunks }];
93647
+ }
93648
+ bind(compute) {
93649
+ const workBuffer = this.require();
93650
+ for (const stream of workBuffer.format.streams) {
93651
+ compute.setParameter(stream.name, workBuffer.getTexture(stream.name));
93652
+ }
93653
+ }
93654
+ textureSize() {
93655
+ return this.require().textureSize;
93656
+ }
93657
+ gpuBytes() {
93658
+ // the work buffer belongs to the engine and is counted by app.stats.vram
93659
+ return 0;
93660
+ }
93661
+ shaderKey() {
93662
+ const workBuffer = this.workBuffer;
93663
+ return workBuffer ? `wb:${workBuffer.format.streams.map((s) => s.name).join(',')}` : 'wb:';
93664
+ }
93665
+ destroy() {
93666
+ this.workBuffer = null;
93667
+ }
93668
+ require() {
93669
+ if (!this.workBuffer)
93670
+ throw new Error('WorkBufferSplatSource: update() has not run');
93671
+ return this.workBuffer;
93672
+ }
93673
+ }
93674
+
93675
+ // The stochastic splat renderer (WebGPU, opt-in). The engine keeps LOD, streaming and the
93676
+ // work-buffer copy; this owns everything after: per frame it culls nodes on the cpu, projects
93677
+ // the resident splats in a compute pass into a dense cache, writes the indirect draw arguments,
93678
+ // rasterises the survivors as opaque depth-tested quads into its own colour + depth target
93679
+ // (StochasticSplats: keep a fragment with probability alpha, no sort), and composes that target
93680
+ // over the camera's target from a fullscreen quad in the World layer that also writes depth.
93681
+ //
93682
+ // Frame flow: the compute runs inside the engine's gsplat update (the `frame:ready` hook, before
93683
+ // the frame graph), the raster pass runs from `camera.beforePasses`, and the compose is an
93684
+ // ordinary mesh instance in the camera's forward pass. See docs/stochastic-renderer.md.
93685
+ const defaultVariant = () => ({
93686
+ spp: 'quad',
93687
+ compose: 'blend',
93688
+ cull: 'auto',
93689
+ order: 'bucket',
93690
+ contribution: 0,
93691
+ popless: 'on',
93692
+ taa: 'on',
93693
+ taaMax: 256,
93694
+ taaMoveMax: 16,
93695
+ taaClip: 1.25,
93696
+ taaFilter: 'cubic',
93697
+ taaReproj: 'sample',
93698
+ taaMotion: 4,
93699
+ taaDebug: 0,
93700
+ taaFlip: 0,
93701
+ colorMax: 8,
93702
+ units: 'engine'
93703
+ });
93704
+ const taaCount = (value) => Math.min(TAA_MAX_COUNT, Math.max(1, Math.round(value)));
93705
+ const parseVariant = (text) => {
93706
+ const variant = defaultVariant();
93707
+ for (const part of (text ?? '').split(',')) {
93708
+ const [key, value] = part.split(':').map((s) => s.trim());
93709
+ if (!key || value === undefined)
93710
+ continue;
93711
+ if (key === 'spp' && (value === '1' || value === 'quad'))
93712
+ variant.spp = value;
93713
+ if (key === 'compose' && (value === 'blend' || value === 'none' || value === 'depth'))
93714
+ variant.compose = value;
93715
+ if (key === 'popless' && (value === 'on' || value === 'off'))
93716
+ variant.popless = value;
93717
+ if (key === 'taa' && (value === 'on' || value === 'off'))
93718
+ variant.taa = value;
93719
+ if (key === 'taaMax' && Number.isFinite(Number(value)))
93720
+ variant.taaMax = taaCount(Number(value));
93721
+ if (key === 'taaMoveMax' && Number.isFinite(Number(value)))
93722
+ variant.taaMoveMax = taaCount(Number(value));
93723
+ if (key === 'taaDebug' && Number.isFinite(Number(value)))
93724
+ variant.taaDebug = Number(value);
93725
+ if (key === 'taaClip' && Number.isFinite(Number(value)))
93726
+ variant.taaClip = Math.max(0, Number(value));
93727
+ if (key === 'taaFilter' && (value === 'linear' || value === 'cubic'))
93728
+ variant.taaFilter = value;
93729
+ if (key === 'taaReproj' && (value === 'sample' || value === 'history'))
93730
+ variant.taaReproj = value;
93731
+ if (key === 'taaMotion' && Number.isFinite(Number(value)))
93732
+ variant.taaMotion = Math.max(0, Number(value));
93733
+ if (key === 'taaFlip' && Number.isFinite(Number(value)))
93734
+ variant.taaFlip = Number(value);
93735
+ if (key === 'colorMax' && Number.isFinite(Number(value)))
93736
+ variant.colorMax = Math.max(0, Number(value));
93737
+ if (key === 'units' && (value === 'px' || value === 'engine'))
93738
+ variant.units = value;
93739
+ if (key === 'cull' && (value === 'off' || value === 'l1' || value === 'l2' || value === 'auto')) {
93740
+ variant.cull = value;
93741
+ }
93742
+ if (key === 'order' && (value === 'append' || value === 'bucket'))
93743
+ variant.order = value;
93744
+ if (key === 'contribution' && Number.isFinite(Number(value)))
93745
+ variant.contribution = Math.max(0, Number(value));
93746
+ }
93747
+ return variant;
93748
+ };
93749
+ // Renders an explicit mesh-instance list into the renderer's own target (the raster and the
93750
+ // taa resolve). Not a layer: a layer in camera.layers is culled once and drawn by every pass
93751
+ // for the camera, so the scene pass would draw the splats into the camera target as well.
93752
+ class SplatRasterPass extends RenderPass {
93753
+ forward;
93754
+ camera;
93755
+ instances;
93756
+ constructor(device, forward, camera, instances, name = 'sse-splat-raster') {
93757
+ super(device);
93758
+ this.forward = forward;
93759
+ this.camera = camera;
93760
+ this.instances = instances;
93761
+ this.name = name;
93762
+ }
93763
+ execute() {
93764
+ this.forward.renderForwardLayer(this.camera.camera, this.renderTarget, null, undefined, SHADER_FORWARD, {
93765
+ meshInstances: this.instances
93766
+ });
93767
+ }
93768
+ }
93769
+ const createQuadMesh = (device, quads) => {
93770
+ const positions = new Float32Array(quads * 4 * 3);
93771
+ const indices = new Uint32Array(quads * 6);
93772
+ for (let i = 0; i < quads; ++i) {
93773
+ // z carries the quad's index within the instance
93774
+ positions.set([-1, -1, i, 1, -1, i, 1, 1, i, -1, 1, i], i * 12);
93775
+ const v = i * 4;
93776
+ indices.set([v, v + 1, v + 2, v, v + 2, v + 3], i * 6);
93777
+ }
93778
+ const mesh = new Mesh(device);
93779
+ mesh.setPositions(positions, 3);
93780
+ mesh.setIndices(indices);
93781
+ mesh.update(PRIMITIVE_TRIANGLES);
93782
+ return mesh;
93783
+ };
93784
+ const createFullscreenMesh = (device) => {
93785
+ const mesh = new Mesh(device);
93786
+ mesh.setPositions(new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), 2);
93787
+ mesh.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3]));
93788
+ mesh.update(PRIMITIVE_TRIANGLES);
93789
+ return mesh;
93790
+ };
93791
+ const tmpVec2 = new Vec2();
93792
+ class StochasticSplatRenderer {
93793
+ variant;
93794
+ source;
93795
+ app;
93796
+ device;
93797
+ camera;
93798
+ worldLayer;
93799
+ provider;
93800
+ unsubscribe;
93801
+ enabled = true;
93802
+ // the resident set and its chunk table
93803
+ set = null;
93804
+ numChunks = 0;
93805
+ chunkData = new Uint32Array(0);
93806
+ chunkBuffer = null;
93807
+ nodeVisibleData = new Uint32Array(0);
93808
+ nodeVisibleBuffer = null;
93809
+ cacheBuffer = null;
93810
+ cacheSlots = 0;
93811
+ counter;
93812
+ // compute
93813
+ // one projector shader per source and occlusion / order specialisation: the test's code
93814
+ // costs a little even when a uniform disables it, so a disabled or suspended cull runs
93815
+ // without it. One compute per shader and dispatch group, since a compute owns the uniform
93816
+ // buffer its dispatch reads and per-file sources dispatch once per file
93817
+ projectorShaders = new Map();
93818
+ projectorComputes = new Map();
93819
+ projectorBindGroupFormat = null;
93820
+ projectorSourceKey = '';
93821
+ args;
93822
+ argsBindGroupFormat;
93823
+ // order:bucket: bucket counts then offsets, the ordered slot list, and its two passes
93824
+ orderBuckets;
93825
+ orderedBuffer = null;
93826
+ orderScan;
93827
+ orderScatter;
93828
+ orderFormats = [];
93829
+ // the occlusion grid: farthest depth per 8 px block (level 1) and per 32 px block (level 2)
93830
+ occL1;
93831
+ occL2;
93832
+ occBlocks = { x1: 0, y1: 0, x2: 0, y2: 0 };
93833
+ reduceL1;
93834
+ reduceL2;
93835
+ reduceFormats = [];
93836
+ // the previous frame the grid and the reprojection describe; valid only when that frame
93837
+ // rendered to the same target at the same size from the same world state
93838
+ prevValid = false;
93839
+ prevViewProjection = new Mat4();
93840
+ prevView = new Mat4();
93841
+ prevProjection = new Mat4();
93842
+ prevClipZ = [0, 0, 0, 0];
93843
+ prevViewport = [0, 0];
93844
+ prevFocal = [0, 0];
93845
+ prevFlip = 1;
93846
+ prevWidth = 0;
93847
+ prevHeight = 0;
93848
+ prevVersion = -1;
93849
+ // the allocations resident when the previous frame drew, and whether any of them has gone
93850
+ // since: only a removed splat can make the previous depth wrong (it may have hidden what is
93851
+ // now behind it), so arrivals leave the cull on while a scene streams in
93852
+ residentAllocIds = new Set();
93853
+ nodesRemoved = false;
93854
+ prevOrtho = false;
93855
+ /** Whether the last frame ran the occlusion cull, for the debug panel and the harness. */
93856
+ culling = false;
93857
+ /** Whether cull:auto currently has the test switched off for culling too little. */
93858
+ get cullSuspended() {
93859
+ return this.variant.cull === 'auto' && (!this.cullActive || this.cullSuspendedFrames > 0);
93860
+ }
93861
+ // cull:auto bookkeeping. The last decision holds while a readback is in flight: while the
93862
+ // test is active every culled frame's counts are read back and a poor one suspends it;
93863
+ // while suspended the frames count down, then one probe frame runs the test and the rest
93864
+ // wait for its counts
93865
+ cullActive = true;
93866
+ cullSuspendedFrames = 0;
93867
+ cullStatsPending = false;
93868
+ /** Frames the test stays off after culling too little (cull:auto). */
93869
+ /**
93870
+ * Whether the projected cache for `splats` resident splats fits one storage binding on this
93871
+ * device. The cache reserves 25% over the resident count; adapters differ in the limit
93872
+ * (128 MiB is the WebGPU default), so a viewer checks before opting in.
93873
+ */
93874
+ static cacheFits(device, splats) {
93875
+ const limit = device.wgpu?.limits
93876
+ ?.maxStorageBufferBindingSize;
93877
+ return !limit || Math.ceil(splats * 1.25) * CACHE_WORDS * 4 <= limit;
93878
+ }
93879
+ static CULL_SUSPEND_FRAMES = 60;
93880
+ /** The culled fraction below which cull:auto suspends the test. */
93881
+ static CULL_MIN_FRACTION = 0.08;
93882
+ /**
93883
+ * Let a capture (query) frame cull against the previous on-screen frame when it renders at
93884
+ * the same size. Off by default: a query frame is not culled, since its cull thins what a
93885
+ * pick or a thumbnail should see. The harness turns it on to photograph culled frames.
93886
+ */
93887
+ allowQueryCull = false;
93888
+ // raster
93889
+ colorTexture;
93890
+ depthTexture;
93891
+ target;
93892
+ rasterMesh;
93893
+ rasterMaterial;
93894
+ rasterInstance;
93895
+ rasterPass;
93896
+ // taa: ping-pong history (premultiplied colour + coverage as unorm16, and the depth mean and
93897
+ // sample count packed in 32 bits; shaders/taa.ts), resolved by a fullscreen pass after the
93898
+ // raster. Sized with the target on the first accumulating frame, and shrunk back while taa is off
93899
+ taaColor = [];
93900
+ taaInfo = [];
93901
+ taaTargets = [];
93902
+ taaWrite = 0;
93903
+ taaMesh;
93904
+ taaMaterial;
93905
+ taaInstance;
93906
+ taaPass;
93907
+ // whether the history holds the previous on-screen frame at the current size
93908
+ taaHistoryValid = false;
93909
+ // the previous taa frame's matrices as the pass reads them, and this frame's, copied over
93910
+ // at the start of the next frame: the material holds the data arrays by reference and
93911
+ // uploads them when it draws, after this hook has run
93912
+ taaPrevViewProjection = new Mat4();
93913
+ taaPrevView = new Mat4();
93914
+ taaLastViewProjection = new Mat4();
93915
+ taaLastView = new Mat4();
93916
+ taaWidth = 0;
93917
+ taaHeight = 0;
93918
+ // the camera's world transform, for the accumulation's reprojection
93919
+ cameraWorld = new Mat4();
93920
+ // frames since the camera or the scene last changed, for converging at rest
93921
+ restFrames = 0;
93922
+ /** The frame the depth texture holds, null while it holds a capture's or nothing. */
93923
+ depthFrame = null;
93924
+ depthFrameCount = 0;
93925
+ depthFrameCamera = createPickCameraSnapshot();
93926
+ // a frame requested from inside the render: the engine clears app.renderNextFrame right
93927
+ // after render(), so the request is applied on frameend instead
93928
+ frameWanted = false;
93929
+ onFrameEnd = () => {
93930
+ if (this.frameWanted) {
93931
+ this.frameWanted = false;
93932
+ this.app.renderNextFrame = true;
93933
+ }
93934
+ };
93935
+ frameIndex = 0;
93936
+ // the seed the harness sets; the frame index replaces it while taa accumulates
93937
+ userSeed = 0;
93938
+ /** Whether the last frame ran the temporal accumulation, for the debug panel. */
93939
+ taaActive = false;
93940
+ /**
93941
+ * Let a capture (query) frame at the on-screen size run the accumulation over the on-screen
93942
+ * history, so the harness can photograph converged and moving frames. Off by default.
93943
+ */
93944
+ allowQueryTaa = false;
93945
+ // compose
93946
+ composeMesh;
93947
+ composeMaterial;
93948
+ composeInstance;
93949
+ frustum = new Frustum();
93950
+ sphere = new BoundingSphere();
93951
+ shaderProjection = new Mat4();
93952
+ viewProjection = new Mat4();
93953
+ frameSeed = 0;
93954
+ ready = false;
93955
+ /** Byte sizes of the buffers this renderer owns, for the bench harness and the debug panel. */
93956
+ /** The renderer's depth texture: the nearest surviving sample per pixel of `depthFrame`. */
93957
+ get frameDepthTexture() {
93958
+ return this.depthTexture;
93959
+ }
93960
+ get gpuBytes() {
93961
+ const buffers = [
93962
+ this.chunkBuffer,
93963
+ this.nodeVisibleBuffer,
93964
+ this.cacheBuffer,
93965
+ this.orderedBuffer,
93966
+ this.counter,
93967
+ this.orderBuckets,
93968
+ this.occL1,
93969
+ this.occL2
93970
+ ];
93971
+ let bytes = 0;
93972
+ for (const buffer of buffers)
93973
+ bytes += buffer?.byteSize ?? 0;
93974
+ bytes += this.colorTexture.gpuSize + this.depthTexture.gpuSize;
93975
+ for (const texture of [...this.taaColor, ...this.taaInfo])
93976
+ bytes += texture.gpuSize;
93977
+ return bytes + this.source.gpuBytes();
93978
+ }
93979
+ /**
93980
+ * The seed mixed into every coverage hash. 0 makes a still camera reproduce its frame;
93981
+ * the harness varies it to measure the sampling noise floor, and TAA will animate it.
93982
+ */
93983
+ get seed() {
93984
+ return this.frameSeed;
93985
+ }
93986
+ set seed(value) {
93987
+ this.userSeed = value >>> 0;
93988
+ this.frameSeed = this.userSeed;
93989
+ this.app.renderNextFrame = true;
93990
+ }
93991
+ /** The last projected frame's survivor count and occlusion-culled count, read back from the gpu. */
93992
+ async readStats() {
93993
+ // without a typed array the engine hands back bytes
93994
+ const data = new Uint32Array(2);
93995
+ await this.counter.read(0, 8, data, true);
93996
+ return { survivors: data[0], occluded: data[1] };
93997
+ }
93998
+ // reduce the previous frame's depth into the two grid levels
93999
+ reduceDepth(width, height) {
94000
+ const { device } = this;
94001
+ const x1 = Math.ceil(width / 8);
94002
+ const y1 = Math.ceil(height / 8);
94003
+ const x2 = Math.ceil(x1 / 4);
94004
+ const y2 = Math.ceil(y1 / 4);
94005
+ if (this.occBlocks.x1 !== x1 || this.occBlocks.y1 !== y1) {
94006
+ this.occL1.destroy();
94007
+ this.occL2.destroy();
94008
+ this.occL1 = new StorageBuffer(device, x1 * y1 * 4, BUFFERUSAGE_COPY_DST);
94009
+ this.occL2 = new StorageBuffer(device, x2 * y2 * 4, BUFFERUSAGE_COPY_DST);
94010
+ this.occBlocks = { x1, y1, x2, y2 };
94011
+ }
94012
+ const l1 = this.reduceL1;
94013
+ l1.setParameter('prevDepth', this.depthTexture);
94014
+ l1.setParameter('blockMax', this.occL1);
94015
+ l1.setParameter('width', width);
94016
+ l1.setParameter('height', height);
94017
+ l1.setParameter('blocksX', x1);
94018
+ l1.setParameter('blocksY', y1);
94019
+ l1.setupDispatch(x1, y1, 1);
94020
+ const l2 = this.reduceL2;
94021
+ l2.setParameter('level1', this.occL1);
94022
+ l2.setParameter('level2', this.occL2);
94023
+ l2.setParameter('blocksX1', x1);
94024
+ l2.setParameter('blocksY1', y1);
94025
+ l2.setParameter('blocksX2', x2);
94026
+ l2.setParameter('blocksY2', y2);
94027
+ Compute.calcDispatchSize(Math.ceil((x2 * y2) / 64), tmpVec2);
94028
+ l2.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
94029
+ device.computeDispatch([l1], 'sse-splat-reduce1');
94030
+ device.computeDispatch([l2], 'sse-splat-reduce2');
94031
+ }
94032
+ /** Survivors of the last frame's projection are only known to the gpu; this is the resident count. */
94033
+ activeSplats = 0;
94034
+ constructor(app, camera, worldLayer, options = {}) {
94035
+ this.app = app;
94036
+ this.device = app.graphicsDevice;
94037
+ this.camera = camera;
94038
+ this.worldLayer = worldLayer;
94039
+ this.variant = parseVariant(options.variant);
94040
+ const { device } = this;
94041
+ if (options.source === 'direct') {
94042
+ this.source = new DirectSplatSource(device);
94043
+ }
94044
+ else {
94045
+ if (options.source && options.source !== 'workbuffer') {
94046
+ console.warn(`StochasticSplatRenderer: splat source '${options.source}' is not implemented yet, using the work buffer`);
94047
+ }
94048
+ this.source = new WorkBufferSplatSource();
94049
+ }
94050
+ this.counter = new StorageBuffer(device, 16, BUFFERUSAGE_COPY_DST | BUFFERUSAGE_COPY_SRC);
94051
+ // indirect draw arguments
94052
+ this.argsBindGroupFormat = new BindGroupFormat(device, [
94053
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
94054
+ new BindStorageBufferFormat('indirectDrawArgs', SHADERSTAGE_COMPUTE),
94055
+ new BindStorageBufferFormat('indirectDispatchArgs', SHADERSTAGE_COMPUTE),
94056
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
94057
+ ]);
94058
+ this.args = new Compute(device, new Shader(device, {
94059
+ name: 'sse-splat-args',
94060
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94061
+ cshader: argsWGSL,
94062
+ computeUniformBufferFormats: {
94063
+ uniforms: new UniformBufferFormat(device, [
94064
+ new UniformFormat('drawSlot', UNIFORMTYPE_UINT),
94065
+ new UniformFormat('indexCount', UNIFORMTYPE_UINT),
94066
+ new UniformFormat('quadsPerInstance', UNIFORMTYPE_UINT),
94067
+ new UniformFormat('dispatchSlot', UNIFORMTYPE_UINT),
94068
+ new UniformFormat('scatterWorkgroupSize', UNIFORMTYPE_UINT)
94069
+ ])
94070
+ },
94071
+ computeBindGroupFormat: this.argsBindGroupFormat
94072
+ }), 'sse-splat-args');
94073
+ // the ordering passes
94074
+ this.orderBuckets = new StorageBuffer(device, 2 * ORDER_BUCKETS * 4, BUFFERUSAGE_COPY_DST);
94075
+ const scanFormat = new BindGroupFormat(device, [new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)]);
94076
+ const scatterFormat = new BindGroupFormat(device, [
94077
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
94078
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE, true),
94079
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE),
94080
+ new BindStorageBufferFormat('ordered', SHADERSTAGE_COMPUTE)
94081
+ ]);
94082
+ this.orderFormats = [scanFormat, scatterFormat];
94083
+ this.orderScan = new Compute(device, new Shader(device, {
94084
+ name: 'sse-splat-order-scan',
94085
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94086
+ cshader: orderScanWGSL,
94087
+ computeBindGroupFormat: scanFormat
94088
+ }), 'sse-splat-order-scan');
94089
+ this.orderScatter = new Compute(device, new Shader(device, {
94090
+ name: 'sse-splat-order-scatter',
94091
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94092
+ cshader: orderScatterWGSL,
94093
+ computeBindGroupFormat: scatterFormat
94094
+ }), 'sse-splat-order-scatter');
94095
+ // the occlusion grid and its two reduce passes
94096
+ this.occL1 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
94097
+ this.occL2 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
94098
+ const reduceL1Format = new BindGroupFormat(device, [
94099
+ new BindTextureFormat('prevDepth', SHADERSTAGE_COMPUTE, TEXTUREDIMENSION_2D, SAMPLETYPE_DEPTH, false),
94100
+ new BindStorageBufferFormat('blockMax', SHADERSTAGE_COMPUTE),
94101
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
94102
+ ]);
94103
+ const reduceL2Format = new BindGroupFormat(device, [
94104
+ new BindStorageBufferFormat('level1', SHADERSTAGE_COMPUTE, true),
94105
+ new BindStorageBufferFormat('level2', SHADERSTAGE_COMPUTE),
94106
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
94107
+ ]);
94108
+ this.reduceFormats = [reduceL1Format, reduceL2Format];
94109
+ this.reduceL1 = new Compute(device, new Shader(device, {
94110
+ name: 'sse-splat-reduce1',
94111
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94112
+ cshader: reduceL1WGSL,
94113
+ computeUniformBufferFormats: {
94114
+ uniforms: new UniformBufferFormat(device, [
94115
+ new UniformFormat('width', UNIFORMTYPE_UINT),
94116
+ new UniformFormat('height', UNIFORMTYPE_UINT),
94117
+ new UniformFormat('blocksX', UNIFORMTYPE_UINT),
94118
+ new UniformFormat('blocksY', UNIFORMTYPE_UINT)
94119
+ ])
94120
+ },
94121
+ computeBindGroupFormat: reduceL1Format
94122
+ }), 'sse-splat-reduce1');
94123
+ this.reduceL2 = new Compute(device, new Shader(device, {
94124
+ name: 'sse-splat-reduce2',
94125
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94126
+ cshader: reduceL2WGSL,
94127
+ computeUniformBufferFormats: {
94128
+ uniforms: new UniformBufferFormat(device, [
94129
+ new UniformFormat('blocksX1', UNIFORMTYPE_UINT),
94130
+ new UniformFormat('blocksY1', UNIFORMTYPE_UINT),
94131
+ new UniformFormat('blocksX2', UNIFORMTYPE_UINT),
94132
+ new UniformFormat('blocksY2', UNIFORMTYPE_UINT)
94133
+ ])
94134
+ },
94135
+ computeBindGroupFormat: reduceL2Format
94136
+ }), 'sse-splat-reduce2');
94137
+ // the raster target: colour, and a depth texture the compose, the occlusion cull and
94138
+ // (later) the picker read
94139
+ this.colorTexture = new Texture(device, {
94140
+ name: 'sse-splat-color',
94141
+ width: 4,
94142
+ height: 4,
94143
+ format: PIXELFORMAT_RGBA8,
94144
+ mipmaps: false,
94145
+ minFilter: FILTER_LINEAR,
94146
+ magFilter: FILTER_LINEAR,
94147
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94148
+ addressV: ADDRESS_CLAMP_TO_EDGE
94149
+ });
94150
+ this.depthTexture = new Texture(device, {
94151
+ name: 'sse-splat-depth',
94152
+ width: 4,
94153
+ height: 4,
94154
+ format: PIXELFORMAT_DEPTH,
94155
+ mipmaps: false,
94156
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94157
+ addressV: ADDRESS_CLAMP_TO_EDGE
94158
+ });
94159
+ this.target = new RenderTarget({
94160
+ name: 'sse-splat-target',
94161
+ colorBuffer: this.colorTexture,
94162
+ depthBuffer: this.depthTexture,
94163
+ samples: 1
94164
+ });
94165
+ this.rasterMesh = createQuadMesh(device, QUADS_PER_INSTANCE);
94166
+ this.rasterMaterial = new ShaderMaterial({
94167
+ uniqueName: 'sse-splat-raster',
94168
+ vertexWGSL: rasterVertexWGSL,
94169
+ fragmentWGSL: rasterFragmentWGSL,
94170
+ attributes: { vertex_position: SEMANTIC_POSITION }
94171
+ });
94172
+ this.rasterMaterial.blendType = BLEND_NONE;
94173
+ this.rasterMaterial.depthWrite = true;
94174
+ this.rasterMaterial.depthTest = true;
94175
+ this.rasterMaterial.cull = CULLFACE_NONE;
94176
+ // the forward renderer reads the instance's node for its cull setup and world transform
94177
+ this.rasterInstance = new MeshInstance(this.rasterMesh, this.rasterMaterial, new GraphNode('sse-splat-raster'));
94178
+ this.rasterInstance.cull = false;
94179
+ this.rasterInstance.castShadow = false;
94180
+ this.rasterInstance.receiveShadow = false;
94181
+ this.rasterPass = new SplatRasterPass(device, app.renderer, camera, [
94182
+ this.rasterInstance
94183
+ ]);
94184
+ this.rasterPass.init(this.target);
94185
+ this.rasterPass.setClearColor(new Color(0, 0, 0, 0));
94186
+ this.rasterPass.setClearDepth(1);
94187
+ // nothing to draw, and no buffers bound, until the first populated frame
94188
+ this.rasterPass.enabled = false;
94189
+ // the taa resolve: a fullscreen pass from the raster target and the previous history
94190
+ // into the other history, sized with the target on its first frame
94191
+ for (let i = 0; i < 2; i++) {
94192
+ this.taaColor.push(new Texture(device, {
94193
+ name: `sse-splat-taa-color-${i}`,
94194
+ width: 4,
94195
+ height: 4,
94196
+ format: PIXELFORMAT_RGBA16U,
94197
+ mipmaps: false,
94198
+ minFilter: FILTER_NEAREST,
94199
+ magFilter: FILTER_NEAREST,
94200
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94201
+ addressV: ADDRESS_CLAMP_TO_EDGE
94202
+ }));
94203
+ this.taaInfo.push(new Texture(device, {
94204
+ name: `sse-splat-taa-info-${i}`,
94205
+ width: 4,
94206
+ height: 4,
94207
+ format: PIXELFORMAT_R32U,
94208
+ mipmaps: false,
94209
+ minFilter: FILTER_NEAREST,
94210
+ magFilter: FILTER_NEAREST,
94211
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94212
+ addressV: ADDRESS_CLAMP_TO_EDGE
94213
+ }));
94214
+ this.taaTargets.push(new RenderTarget({
94215
+ name: `sse-splat-taa-${i}`,
94216
+ colorBuffers: [this.taaColor[i], this.taaInfo[i]],
94217
+ depth: false,
94218
+ samples: 1
94219
+ }));
94220
+ }
94221
+ this.taaMesh = createFullscreenMesh(device);
94222
+ this.taaMaterial = new ShaderMaterial({
94223
+ uniqueName: 'sse-splat-taa',
94224
+ vertexWGSL: taaVertexWGSL,
94225
+ fragmentWGSL: taaFragmentWGSL,
94226
+ attributes: { vertex_position: SEMANTIC_POSITION },
94227
+ fragmentOutputTypes: ['uvec4', 'uint']
94228
+ });
94229
+ this.taaMaterial.blendType = BLEND_NONE;
94230
+ this.taaMaterial.depthWrite = false;
94231
+ this.taaMaterial.depthTest = false;
94232
+ this.taaMaterial.cull = CULLFACE_NONE;
94233
+ this.taaInstance = new MeshInstance(this.taaMesh, this.taaMaterial, new GraphNode('sse-splat-taa'));
94234
+ this.taaInstance.cull = false;
94235
+ this.taaInstance.castShadow = false;
94236
+ this.taaInstance.receiveShadow = false;
94237
+ this.taaPass = new SplatRasterPass(device, app.renderer, camera, [this.taaInstance], 'sse-splat-taa');
94238
+ this.taaPass.init(this.taaTargets[0]);
94239
+ this.taaPass.enabled = false;
94240
+ // the compose quad, blended over the skybox and opaque meshes with the splat depth
94241
+ this.composeMesh = createFullscreenMesh(device);
94242
+ this.composeMaterial = new ShaderMaterial({
94243
+ uniqueName: 'sse-splat-compose',
94244
+ vertexWGSL: composeVertexWGSL,
94245
+ fragmentWGSL: composeFragmentWGSL,
94246
+ attributes: { vertex_position: SEMANTIC_POSITION }
94247
+ });
94248
+ this.composeMaterial.blendType = BLEND_PREMULTIPLIED;
94249
+ this.composeMaterial.depthWrite = true;
94250
+ this.composeMaterial.depthTest = true;
94251
+ this.composeMaterial.cull = CULLFACE_NONE;
94252
+ this.composeMaterial.setParameter('splatColor', this.colorTexture);
94253
+ this.composeMaterial.setParameter('splatDepth', this.depthTexture);
94254
+ // always bound, even while taa is off: a declared texture without a value makes the
94255
+ // engine create and upload a placeholder inside the forward pass, which submits the
94256
+ // command buffer mid-pass on WebGPU
94257
+ this.composeMaterial.setParameter('taaColor', this.taaColor[0]);
94258
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[0]);
94259
+ this.composeInstance = new MeshInstance(this.composeMesh, this.composeMaterial, new GraphNode('sse-splat-compose'));
94260
+ this.composeInstance.cull = false;
94261
+ this.composeInstance.castShadow = false;
94262
+ this.composeInstance.receiveShadow = false;
94263
+ // the picker pass draws every pickable instance of the layer into a target without a
94264
+ // depth attachment; this shader writes frag_depth, which makes that pipeline invalid
94265
+ // and drops the whole submit, the frame's command buffer included
94266
+ this.composeInstance.pick = false;
94267
+ // first among the transparents, whichever way the layer sorts them
94268
+ this.composeInstance.drawOrder = -1e3;
94269
+ this.composeInstance.calculateSortDistance = () => Number.MAX_VALUE;
94270
+ this.applyVariant();
94271
+ this.provider = new EngineResidentSetProvider(app, camera, worldLayer);
94272
+ this.unsubscribe = this.provider.onFrame((set, changed, manager) => this.frame(set, changed, manager));
94273
+ app.on('frameend', this.onFrameEnd);
94274
+ this.attach();
94275
+ }
94276
+ /** Switch the renderer off and hand the splats back to the engine's renderer (XR), or on again. */
94277
+ setEnabled(value) {
94278
+ if (this.enabled === value)
94279
+ return;
94280
+ this.enabled = value;
94281
+ if (value) {
94282
+ this.attach();
94283
+ }
94284
+ else {
94285
+ this.detach();
94286
+ }
94287
+ this.app.renderNextFrame = true;
94288
+ }
94289
+ /** Replace the experiment switches from a `key:value,key:value` string (unset keys reset). */
94290
+ setVariant(text) {
94291
+ Object.assign(this.variant, parseVariant(text));
94292
+ // the cull decides afresh under new switches
94293
+ this.cullActive = true;
94294
+ this.cullSuspendedFrames = 0;
94295
+ this.applyVariant();
94296
+ }
94297
+ /**
94298
+ * Drop the temporal history; the next frame starts accumulating from its own sample. The
94299
+ * coverage seeds restart too, so a variant accumulates the same samples every time (the
94300
+ * harness compares builds image for image).
94301
+ */
94302
+ resetHistory() {
94303
+ this.taaHistoryValid = false;
94304
+ this.restFrames = 0;
94305
+ this.frameIndex = 0;
94306
+ }
94307
+ /** Re-read {@link variant} after a field changed. */
94308
+ applyVariant() {
94309
+ // a switch changes what the frames hold; an old history would leak into the new ones
94310
+ this.resetHistory();
94311
+ const quad = this.variant.spp === 'quad';
94312
+ this.rasterMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
94313
+ this.rasterMaterial.setDefine('SSE_ORDERED', this.variant.order === 'bucket' ? '' : undefined);
94314
+ this.rasterMaterial.setDefine('SSE_POPLESS', this.variant.popless === 'on' ? '' : undefined);
94315
+ this.composeMaterial.setDefine('SSE_SHOW_DEPTH', this.variant.compose === 'depth' ? '' : undefined);
94316
+ this.composeMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
94317
+ this.rasterMaterial.update();
94318
+ this.composeMaterial.update();
94319
+ this.setReady(this.ready);
94320
+ this.app.renderNextFrame = true;
94321
+ }
94322
+ // the raster pass and the compose only run once a frame has bound the buffers they read
94323
+ setReady(value) {
94324
+ this.ready = value;
94325
+ this.rasterPass.enabled = value;
94326
+ this.composeInstance.visible = value && this.variant.compose !== 'none';
94327
+ }
94328
+ attach() {
94329
+ const passes = this.camera.camera.beforePasses;
94330
+ if (!passes.includes(this.rasterPass))
94331
+ passes.push(this.rasterPass);
94332
+ if (!passes.includes(this.taaPass))
94333
+ passes.push(this.taaPass);
94334
+ this.worldLayer.addMeshInstances([this.composeInstance]);
94335
+ this.provider.setActive(true);
94336
+ }
94337
+ detach() {
94338
+ const passes = this.camera.camera.beforePasses;
94339
+ for (const pass of [this.rasterPass, this.taaPass]) {
94340
+ const index = passes.indexOf(pass);
94341
+ if (index >= 0)
94342
+ passes.splice(index, 1);
94343
+ }
94344
+ this.resetHistory();
94345
+ this.depthFrame = null;
94346
+ this.worldLayer.removeMeshInstances([this.composeInstance]);
94347
+ this.provider.setActive(false);
94348
+ }
94349
+ frame(set, changed, manager) {
94350
+ if (!this.enabled)
94351
+ return;
94352
+ const { device, camera } = this;
94353
+ const cam = camera.camera;
94354
+ this.nodesRemoved = false;
94355
+ if (changed || this.set !== set) {
94356
+ const ids = new Set(set.nodes.map((node) => node.allocId));
94357
+ for (const id of this.residentAllocIds) {
94358
+ if (!ids.has(id)) {
94359
+ this.nodesRemoved = true;
94360
+ break;
94361
+ }
94362
+ }
94363
+ this.residentAllocIds = ids;
94364
+ this.source.update(set, manager);
94365
+ this.rebuildChunkTable(set);
94366
+ this.ensureCache(set.activeSplats);
94367
+ this.activeSplats = set.activeSplats;
94368
+ this.pruneProjectorComputes(set);
94369
+ // recorded last, so a rebuild that throws is retried next frame
94370
+ this.set = set;
94371
+ }
94372
+ if (this.numChunks === 0) {
94373
+ // nothing resident: draw nothing
94374
+ this.setReady(false);
94375
+ return;
94376
+ }
94377
+ // the target follows whatever the camera renders into this frame: the backbuffer, or a
94378
+ // capture's render target at another size
94379
+ const rt = camera.renderTarget;
94380
+ const width = rt ? rt.width : device.width;
94381
+ const height = rt ? rt.height : device.height;
94382
+ if (this.target.width !== width || this.target.height !== height) {
94383
+ this.target.resize(width, height);
94384
+ }
94385
+ const view = cam.viewMatrix;
94386
+ const projection = cam.projectionMatrix;
94387
+ const isOrtho = cam.projection === PROJECTION_ORTHOGRAPHIC;
94388
+ // the clip z the raster shader reconstructs must match the engine's WebGPU depth range
94389
+ const shaderProjection = Camera$1.applyShaderProjectionTransform(projection, this.shaderProjection, false, true);
94390
+ this.viewProjection.mul2(shaderProjection, view);
94391
+ // The splats' own depth: clip z = a * depth + b (over w = depth for a perspective
94392
+ // camera). The camera's far plane is fitted to the scene bound, which can leave a sky
94393
+ // outside it, and splats clamped there share one depth and lose their order; so a
94394
+ // perspective raster puts its far plane at infinity (z = 1 - near / depth), with the same
94395
+ // near plane and, near where precision matters, the same resolution. The compose converts
94396
+ // back to the camera's depth where the splats meet the rest of the scene. An orthographic
94397
+ // camera keeps its own mapping: a linear depth has no far plane at infinity.
94398
+ const cameraClipZ = [-shaderProjection.data[10], shaderProjection.data[14]];
94399
+ const clipZ = isOrtho ? cameraClipZ : [1, cameraClipZ[1] / cameraClipZ[0]];
94400
+ const clipZParams = [clipZ[0], clipZ[1], isOrtho ? 1 : 0, 0];
94401
+ this.cullNodes(set, this.viewProjection);
94402
+ const focal = [Math.abs(projection.data[0]) * width * 0.5, Math.abs(projection.data[5]) * height * 0.5];
94403
+ const gsplat = this.app.scene.gsplat;
94404
+ // the moving-camera contribution cull: a raised threshold while the view changes, then
94405
+ // one more frame at the scene's threshold once it has stopped
94406
+ const moved = this.viewMoved(view, projection);
94407
+ const raised = moved && this.variant.contribution > 0;
94408
+ const minContribution = raised
94409
+ ? Math.max(gsplat.minContribution, this.variant.contribution)
94410
+ : gsplat.minContribution;
94411
+ if (raised)
94412
+ this.frameWanted = true;
94413
+ // Temporal accumulation runs on on-screen frames (and, for the harness, on a capture at
94414
+ // the same size); the history is only trusted when it holds the previous such frame at
94415
+ // this size. While it runs the coverage seed changes every frame, and a resting camera
94416
+ // keeps requesting frames until the history has filled its cap
94417
+ const isQuery = !!rt;
94418
+ const taaOn = this.variant.taa === 'on' &&
94419
+ (!isQuery || (this.allowQueryTaa && width === this.taaWidth && height === this.taaHeight));
94420
+ if (taaOn) {
94421
+ if (this.taaWidth !== width || this.taaHeight !== height) {
94422
+ this.resizeHistory(width, height);
94423
+ this.taaWidth = width;
94424
+ this.taaHeight = height;
94425
+ this.taaHistoryValid = false;
94426
+ this.restFrames = 0;
94427
+ }
94428
+ this.frameSeed = this.frameIndex++ >>> 0;
94429
+ if (moved || changed)
94430
+ this.restFrames = 0;
94431
+ else
94432
+ this.restFrames++;
94433
+ if (this.restFrames < this.variant.taaMax + 2)
94434
+ this.frameWanted = true;
94435
+ }
94436
+ else {
94437
+ this.frameSeed = this.userSeed;
94438
+ // a capture at another size does not accumulate; the next on-screen frame starts over
94439
+ this.taaHistoryValid = false;
94440
+ this.restFrames = 0;
94441
+ // switched off: the history goes back to its placeholder size until it is wanted
94442
+ if (this.variant.taa === 'off' && this.taaWidth !== 0) {
94443
+ this.resizeHistory(4, 4);
94444
+ this.taaWidth = 0;
94445
+ this.taaHeight = 0;
94446
+ }
94447
+ }
94448
+ this.taaActive = taaOn;
94449
+ // The occlusion cull reads the depth texture as the previous frame left it, so it needs
94450
+ // that frame to have drawn to this target at this size (a resize loses the texture, a
94451
+ // capture draws elsewhere), with no splat removed since (its depth would hide what is
94452
+ // now behind it; arrivals are safe) and the same projection type. A capture frame is
94453
+ // never culled and never becomes the previous frame.
94454
+ // a new world state can change what is occluded: try the test again
94455
+ if (this.prevVersion !== set.version) {
94456
+ this.cullSuspendedFrames = 0;
94457
+ this.cullActive = true;
94458
+ }
94459
+ const cullMode = this.variant.cull;
94460
+ let wanted = cullMode !== 'off';
94461
+ let probe = false;
94462
+ if (cullMode === 'auto' && !isQuery) {
94463
+ if (this.cullSuspendedFrames > 0) {
94464
+ // a moving camera changes what is occluded, so the probe comes sooner
94465
+ const moved = this.viewMoved(view, projection);
94466
+ this.cullSuspendedFrames = Math.max(0, this.cullSuspendedFrames - (moved ? 4 : 1));
94467
+ wanted = false;
94468
+ }
94469
+ else if (!this.cullActive) {
94470
+ // suspended and due: one probe frame, then wait for its counts
94471
+ probe = !this.cullStatsPending;
94472
+ wanted = probe;
94473
+ }
94474
+ }
94475
+ const culling = wanted &&
94476
+ (!isQuery || this.allowQueryCull) &&
94477
+ this.prevValid &&
94478
+ this.prevWidth === width &&
94479
+ this.prevHeight === height &&
94480
+ !this.nodesRemoved &&
94481
+ this.prevOrtho === isOrtho;
94482
+ this.culling = culling;
94483
+ if (culling) {
94484
+ this.reduceDepth(width, height);
94485
+ }
94486
+ this.counter.clear();
94487
+ const ordered = this.variant.order === 'bucket';
94488
+ if (ordered)
94489
+ this.orderBuckets.clear();
94490
+ // the order key spans the fitted clip range, log-spaced
94491
+ const logNear = Math.log(Math.max(cam.nearClip, 1e-6));
94492
+ const invLogRange = 1 / Math.max(Math.log(Math.max(cam.farClip, 1e-6)) - logNear, 1e-6);
94493
+ // the view depths where the raster's clip z reaches 0 and its far clamp (FAR_CLIP_Z), from
94494
+ // clip z = a * depth + b (over w = depth for a perspective camera)
94495
+ const [clipA, clipB] = clipZ;
94496
+ const depthNear = -clipB / clipA;
94497
+ const depthFar = isOrtho ? (FAR_CLIP_Z - clipB) / clipA : clipB / (FAR_CLIP_Z - clipA);
94498
+ const cameraPosition = camera.entity.getPosition();
94499
+ const groups = this.source.dispatchPlan(set, this.numChunks);
94500
+ for (const group of groups) {
94501
+ // a file with no node in the frustum has nothing to dispatch
94502
+ if (group.fileIndex >= 0 && !this.anyNodeVisible(set.files[group.fileIndex].nodes))
94503
+ continue;
94504
+ const projector = this.ensureProjector(culling, ordered, group);
94505
+ this.source.bind(projector, group, set);
94506
+ projector.setParameter('chunks', this.chunkBuffer);
94507
+ projector.setParameter('nodeVisible', this.nodeVisibleBuffer);
94508
+ projector.setParameter('cache', this.cacheBuffer);
94509
+ projector.setParameter('counter', this.counter);
94510
+ projector.setParameter('occL1', this.occL1);
94511
+ projector.setParameter('occL2', this.occL2);
94512
+ projector.setParameter('buckets', this.orderBuckets);
94513
+ projector.setParameter('view', view.data);
94514
+ projector.setParameter('viewProj', this.viewProjection.data);
94515
+ projector.setParameter('prevViewProj', this.prevViewProjection.data);
94516
+ projector.setParameter('prevView', this.prevView.data);
94517
+ projector.setParameter('prevClipZ', this.prevClipZ);
94518
+ projector.setParameter('viewport', [width, height]);
94519
+ projector.setParameter('focal', focal);
94520
+ projector.setParameter('prevViewport', this.prevViewport);
94521
+ projector.setParameter('prevFocal', this.prevFocal);
94522
+ projector.setParameter('numChunks', group.chunkCount);
94523
+ projector.setParameter('chunkBase', group.chunkBase);
94524
+ projector.setParameter('cameraPosition', [cameraPosition.x, cameraPosition.y, cameraPosition.z, 0]);
94525
+ projector.setParameter('splatTextureSize', this.source.textureSize(group));
94526
+ projector.setParameter('isOrtho', isOrtho ? 1 : 0);
94527
+ projector.setParameter('minPixelSize', gsplat.minPixelSize);
94528
+ projector.setParameter('alphaClip', gsplat.alphaClipForward);
94529
+ projector.setParameter('minContribution', minContribution);
94530
+ projector.setParameter('colorMax', this.variant.colorMax);
94531
+ projector.setParameter('unitScale', this.variant.units === 'engine' ? 2 : 1);
94532
+ projector.setParameter('occBlocksX1', this.occBlocks.x1);
94533
+ projector.setParameter('occBlocksY1', this.occBlocks.y1);
94534
+ projector.setParameter('occBlocksX2', this.occBlocks.x2);
94535
+ projector.setParameter('occBlocksY2', this.occBlocks.y2);
94536
+ projector.setParameter('occlusionMode', culling ? (cullMode === 'l1' ? 1 : 2) : 0);
94537
+ projector.setParameter('prevFlip', this.prevFlip);
94538
+ projector.setParameter('keyLogNear', logNear);
94539
+ projector.setParameter('keyInvLogRange', invLogRange);
94540
+ projector.setParameter('depthNear', depthNear);
94541
+ projector.setParameter('depthFar', depthFar);
94542
+ Compute.calcDispatchSize(group.chunkCount, tmpVec2);
94543
+ projector.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
94544
+ device.computeDispatch([projector], 'sse-splat-project');
94545
+ }
94546
+ // indirect draw arguments for the raster and dispatch size for the scatter; slots are
94547
+ // per frame
94548
+ const drawSlot = device.getIndirectDrawSlot(1);
94549
+ const dispatchSlot = device.getIndirectDispatchSlot(1);
94550
+ this.args.setParameter('counter', this.counter);
94551
+ this.args.setParameter('indirectDrawArgs', device.indirectDrawBuffer);
94552
+ this.args.setParameter('indirectDispatchArgs', device.indirectDispatchBuffer);
94553
+ this.args.setParameter('drawSlot', drawSlot);
94554
+ this.args.setParameter('indexCount', QUADS_PER_INSTANCE * 6);
94555
+ this.args.setParameter('quadsPerInstance', QUADS_PER_INSTANCE);
94556
+ this.args.setParameter('dispatchSlot', dispatchSlot);
94557
+ this.args.setParameter('scatterWorkgroupSize', ORDER_BUCKETS);
94558
+ this.args.setupDispatch(1, 1, 1);
94559
+ device.computeDispatch([this.args], 'sse-splat-args');
94560
+ this.rasterInstance.setIndirect(null, drawSlot, 1);
94561
+ if (ordered) {
94562
+ // bucket offsets, then every survivor claims its place in its bucket
94563
+ this.orderScan.setParameter('buckets', this.orderBuckets);
94564
+ this.orderScan.setupDispatch(1, 1, 1);
94565
+ device.computeDispatch([this.orderScan], 'sse-splat-order-scan');
94566
+ const scatter = this.orderScatter;
94567
+ scatter.setParameter('counter', this.counter);
94568
+ scatter.setParameter('cache', this.cacheBuffer);
94569
+ scatter.setParameter('buckets', this.orderBuckets);
94570
+ scatter.setParameter('ordered', this.orderedBuffer);
94571
+ scatter.setupIndirectDispatch(dispatchSlot);
94572
+ device.computeDispatch([scatter], 'sse-splat-order-scatter');
94573
+ }
94574
+ const material = this.rasterMaterial;
94575
+ material.setParameter('splatCache', this.cacheBuffer);
94576
+ material.setParameter('splatCount', this.counter);
94577
+ if (ordered)
94578
+ material.setParameter('orderedSlots', this.orderedBuffer);
94579
+ material.setParameter('viewportSize', [width, height, 2 / width, 2 / height]);
94580
+ material.setParameter('clipZParams', clipZParams);
94581
+ material.setParameter('focalParams', [focal[0], focal[1], 0, 0]);
94582
+ material.setParameter('sseAlphaClip', gsplat.alphaClipForward);
94583
+ material.setParameter('frameSeed', this.frameSeed);
94584
+ this.taaPass.enabled = taaOn;
94585
+ if (taaOn) {
94586
+ const read = this.taaWrite ^ 1;
94587
+ const taa = this.taaMaterial;
94588
+ this.taaPrevViewProjection.copy(this.taaLastViewProjection);
94589
+ this.taaPrevView.copy(this.taaLastView);
94590
+ this.cameraWorld.copy(view).invert();
94591
+ taa.setParameter('curColor', this.colorTexture);
94592
+ taa.setParameter('curDepth', this.depthTexture);
94593
+ taa.setParameter('histColor', this.taaColor[read]);
94594
+ taa.setParameter('histInfo', this.taaInfo[read]);
94595
+ taa.setParameter('cameraWorld', this.cameraWorld.data);
94596
+ // x_ndc = (m00 x + m02 z) / -z for a perspective camera, m00 x + m03 for an orthographic one
94597
+ const sp = shaderProjection.data;
94598
+ taa.setParameter('unproject', isOrtho ? [sp[0], sp[5], sp[12], sp[13]] : [sp[0], sp[5], sp[8], sp[9]]);
94599
+ taa.setParameter('prevViewProj', this.taaPrevViewProjection.data);
94600
+ taa.setParameter('prevView', this.taaPrevView.data);
94601
+ taa.setParameter('clipZParams', clipZParams);
94602
+ // a changed resident set (detail streamed in) keeps the history but caps its weight,
94603
+ // so the new content shows within taaMoveMax frames rather than 1 / taaMax a frame
94604
+ taa.setParameter('taaParams', [
94605
+ moved || changed ? this.variant.taaMoveMax : this.variant.taaMax,
94606
+ this.taaHistoryValid ? 1 : 0,
94607
+ moved ? 1 : 0,
94608
+ this.restFrames
94609
+ ]);
94610
+ taa.setParameter('taaViewport', [width, height, 1 / width, 1 / height]);
94611
+ taa.setParameter('taaControl', [
94612
+ this.variant.taaFlip || (this.target.flipY ? -1 : 1),
94613
+ this.variant.taaClip,
94614
+ this.variant.spp === 'quad' ? 1 : 0,
94615
+ 0
94616
+ ]);
94617
+ taa.setParameter('taaDebug', this.variant.taaDebug);
94618
+ taa.setParameter('taaFilter', [
94619
+ this.variant.taaFilter === 'cubic' ? 1 : 0,
94620
+ this.variant.taaReproj === 'history' ? 1 : 0,
94621
+ this.variant.taaMotion,
94622
+ 0
94623
+ ]);
94624
+ this.taaPass.renderTarget = this.taaTargets[this.taaWrite];
94625
+ this.composeMaterial.setParameter('taaColor', this.taaColor[this.taaWrite]);
94626
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[this.taaWrite]);
94627
+ this.taaLastViewProjection.copy(this.viewProjection);
94628
+ this.taaLastView.copy(view);
94629
+ this.taaHistoryValid = true;
94630
+ this.taaWrite ^= 1;
94631
+ }
94632
+ // an offscreen target's rows run the other way to the backbuffer's on WebGPU
94633
+ const targetFlipY = rt ? rt.flipY : device.backBuffer.flipY;
94634
+ this.composeMaterial.setParameter('composeParams', [
94635
+ this.target.flipY !== targetFlipY ? 1 : 0,
94636
+ isOrtho ? 1 : 0,
94637
+ taaOn ? 1 : 0,
94638
+ 0
94639
+ ]);
94640
+ this.composeMaterial.setParameter('depthViewParams', [
94641
+ clipZ[0],
94642
+ clipZ[1],
94643
+ Math.max(cam.nearClip, 1e-4),
94644
+ Math.max(cam.farClip, cam.nearClip * 2)
94645
+ ]);
94646
+ this.composeMaterial.setParameter('cameraClipZ', [cameraClipZ[0], cameraClipZ[1], isOrtho ? 1 : 0, 0]);
94647
+ // cull:auto: read this culled frame's counts back (asynchronously, off the frame) and
94648
+ // keep the test only while it removes enough to pay for itself
94649
+ if (culling && cullMode === 'auto' && !isQuery && !this.cullStatsPending) {
94650
+ this.cullStatsPending = true;
94651
+ const data = new Uint32Array(2);
94652
+ this.counter
94653
+ .read(0, 8, data, false)
94654
+ .then(() => {
94655
+ const total = data[0] + data[1];
94656
+ const worthwhile = total > 0 && data[1] / total >= StochasticSplatRenderer.CULL_MIN_FRACTION;
94657
+ this.cullActive = worthwhile;
94658
+ if (!worthwhile)
94659
+ this.cullSuspendedFrames = StochasticSplatRenderer.CULL_SUSPEND_FRAMES;
94660
+ })
94661
+ .catch(() => {
94662
+ // a lost device or a destroyed buffer; the next frame tries again
94663
+ })
94664
+ .finally(() => {
94665
+ this.cullStatsPending = false;
94666
+ });
94667
+ }
94668
+ // this frame becomes the previous one, unless it is a capture
94669
+ if (isQuery) {
94670
+ // the capture drew elsewhere; the on-screen depth texture is no longer this frame's
94671
+ this.prevValid = false;
94672
+ this.depthFrame = null;
94673
+ this.setReady(true);
94674
+ return;
94675
+ }
94676
+ captureCameraSnapshot(camera.entity, this.depthFrameCamera);
94677
+ this.depthFrame = {
94678
+ id: ++this.depthFrameCount,
94679
+ camera: this.depthFrameCamera,
94680
+ width,
94681
+ height,
94682
+ clipZ: [clipZ[0], clipZ[1]]
94683
+ };
94684
+ this.prevViewProjection.copy(this.viewProjection);
94685
+ this.prevView.copy(view);
94686
+ this.prevProjection.copy(projection);
94687
+ this.prevClipZ = clipZParams;
94688
+ this.prevViewport = [width, height];
94689
+ this.prevFocal = focal;
94690
+ this.prevFlip = this.target.flipY ? -1 : 1;
94691
+ this.prevWidth = width;
94692
+ this.prevHeight = height;
94693
+ this.prevVersion = set.version;
94694
+ this.prevOrtho = isOrtho;
94695
+ this.prevValid = !isQuery;
94696
+ this.setReady(true);
94697
+ }
94698
+ resizeHistory(width, height) {
94699
+ for (const texture of [...this.taaColor, ...this.taaInfo])
94700
+ texture.resize(width, height);
94701
+ for (const target of this.taaTargets)
94702
+ target.resize(width, height);
94703
+ }
94704
+ // whether the view or the projection differs from the previous on-screen frame's beyond
94705
+ // float noise (the camera controllers settle over many frames; a fov animation moves the
94706
+ // image without moving the camera)
94707
+ viewMoved(view, projection) {
94708
+ for (let i = 0; i < 16; i++) {
94709
+ if (Math.abs(view.data[i] - this.prevView.data[i]) > 1e-6)
94710
+ return true;
94711
+ if (Math.abs(projection.data[i] - this.prevProjection.data[i]) > 1e-6)
94712
+ return true;
94713
+ }
94714
+ return false;
94715
+ }
94716
+ // one chunk-table entry per CHUNK_SIZE splats of every resident node
94717
+ rebuildChunkTable(set) {
94718
+ let count = 0;
94719
+ for (const node of set.nodes)
94720
+ count += Math.ceil(node.count / CHUNK_SIZE);
94721
+ if (this.chunkData.length < count * 4) {
94722
+ this.chunkData = new Uint32Array(Math.ceil(count * 1.25) * 4);
94723
+ this.chunkBuffer?.destroy();
94724
+ this.chunkBuffer = new StorageBuffer(this.device, this.chunkData.byteLength, BUFFERUSAGE_COPY_DST);
94725
+ }
94726
+ const data = this.chunkData;
94727
+ let k = 0;
94728
+ set.nodes.forEach((node, nodeIndex) => {
94729
+ const base = this.source.chunkBase(node);
94730
+ for (let offset = 0; offset < node.count; offset += CHUNK_SIZE) {
94731
+ data[k++] = base + offset;
94732
+ data[k++] = Math.min(CHUNK_SIZE, node.count - offset);
94733
+ data[k++] = nodeIndex;
94734
+ data[k++] = (node.lodIndex & 0xffff) | (node.fileIndex << 16);
94735
+ }
94736
+ });
94737
+ this.numChunks = count;
94738
+ // writeBuffer counts typed-array elements, not bytes
94739
+ if (count > 0)
94740
+ this.chunkBuffer.write(0, data, 0, count * 4);
94741
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
94742
+ if (this.nodeVisibleData.length < words) {
94743
+ this.nodeVisibleData = new Uint32Array(words);
94744
+ this.nodeVisibleBuffer?.destroy();
94745
+ this.nodeVisibleBuffer = new StorageBuffer(this.device, words * 4, BUFFERUSAGE_COPY_DST);
94746
+ }
94747
+ }
94748
+ // the cache is dense (indexed by compact slot), so it only needs room for the resident
94749
+ // splats, not the allocator's address space; grown geometrically, never shrunk
94750
+ ensureCache(splats) {
94751
+ if (splats <= this.cacheSlots)
94752
+ return;
94753
+ this.cacheBuffer?.destroy();
94754
+ this.orderedBuffer?.destroy();
94755
+ this.cacheSlots = Math.max(1, Math.ceil(splats * 1.25));
94756
+ this.cacheBuffer = new StorageBuffer(this.device, this.cacheSlots * CACHE_WORDS * 4, BUFFERUSAGE_COPY_SRC);
94757
+ this.orderedBuffer = new StorageBuffer(this.device, this.cacheSlots * 4);
94758
+ }
94759
+ // sphere-frustum test per node on the cpu: thousands of nodes, one bit each
94760
+ cullNodes(set, viewProjection) {
94761
+ const bits = this.nodeVisibleData;
94762
+ bits.fill(0);
94763
+ this.frustum.setFromMat4(viewProjection);
94764
+ const spheres = set.nodeSpheres;
94765
+ const { sphere } = this;
94766
+ for (let i = 0; i < set.nodes.length; i++) {
94767
+ sphere.center.set(spheres[i * 4], spheres[i * 4 + 1], spheres[i * 4 + 2]);
94768
+ sphere.radius = spheres[i * 4 + 3];
94769
+ if (this.frustum.containsSphere(sphere) !== 0) {
94770
+ bits[i >> 5] |= 1 << (i & 31);
94771
+ }
94772
+ }
94773
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
94774
+ this.nodeVisibleBuffer.write(0, bits, 0, words);
94775
+ }
94776
+ anyNodeVisible(nodes) {
94777
+ const bits = this.nodeVisibleData;
94778
+ return nodes.some((node) => (bits[node.nodeIndex >> 5] >>> (node.nodeIndex & 31)) & 1);
94779
+ }
94780
+ ensureProjector(occlusion, ordered, group) {
94781
+ const sourceKey = this.source.shaderKey();
94782
+ if (this.projectorSourceKey !== sourceKey) {
94783
+ // a different source: every specialisation and the bind group format go
94784
+ this.destroyProjector();
94785
+ this.projectorSourceKey = sourceKey;
94786
+ }
94787
+ const key = `${occlusion ? 'occlusion' : 'plain'}-${ordered ? 'bucket' : 'append'}`;
94788
+ const computeKey = `${key}:${group.fileIndex}`;
94789
+ const existing = this.projectorComputes.get(computeKey);
94790
+ if (existing)
94791
+ return existing;
94792
+ const shader = this.ensureProjectorShader(key, occlusion, ordered);
94793
+ const compute = new Compute(this.device, shader, 'sse-splat-project');
94794
+ this.projectorComputes.set(computeKey, compute);
94795
+ return compute;
94796
+ }
94797
+ // drop the computes of files that left the resident set
94798
+ pruneProjectorComputes(set) {
94799
+ for (const [key, compute] of this.projectorComputes) {
94800
+ const fileIndex = Number(key.slice(key.lastIndexOf(':') + 1));
94801
+ if (fileIndex >= 0 && !set.files[fileIndex]) {
94802
+ compute.destroy();
94803
+ this.projectorComputes.delete(key);
94804
+ }
94805
+ }
94806
+ }
94807
+ ensureProjectorShader(key, occlusion, ordered) {
94808
+ const existing = this.projectorShaders.get(key);
94809
+ if (existing)
94810
+ return existing;
94811
+ const { device } = this;
94812
+ const fixed = [
94813
+ new BindStorageBufferFormat('chunks', SHADERSTAGE_COMPUTE, true),
94814
+ new BindStorageBufferFormat('nodeVisible', SHADERSTAGE_COMPUTE, true),
94815
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE),
94816
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE),
94817
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE),
94818
+ new BindStorageBufferFormat('occL1', SHADERSTAGE_COMPUTE, true),
94819
+ new BindStorageBufferFormat('occL2', SHADERSTAGE_COMPUTE, true),
94820
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)
94821
+ ];
94822
+ const formats = [...fixed, ...this.source.bindFormats()];
94823
+ this.projectorBindGroupFormat ??= new BindGroupFormat(device, formats);
94824
+ const shader = new Shader(device, {
94825
+ name: `sse-splat-project-${key}`,
94826
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94827
+ cshader: projectorWGSL(this.source.readChunk(fixed.length), occlusion, ordered),
94828
+ cincludes: this.source.shaderIncludes(),
94829
+ cdefines: this.source.shaderDefines(),
94830
+ computeUniformBufferFormats: {
94831
+ // the same order as the wgsl struct; both follow the same alignment rules
94832
+ uniforms: new UniformBufferFormat(device, [
94833
+ new UniformFormat('view', UNIFORMTYPE_MAT4),
94834
+ new UniformFormat('viewProj', UNIFORMTYPE_MAT4),
94835
+ new UniformFormat('prevViewProj', UNIFORMTYPE_MAT4),
94836
+ new UniformFormat('prevView', UNIFORMTYPE_MAT4),
94837
+ new UniformFormat('prevClipZ', UNIFORMTYPE_VEC4),
94838
+ new UniformFormat('viewport', UNIFORMTYPE_VEC2),
94839
+ new UniformFormat('focal', UNIFORMTYPE_VEC2),
94840
+ new UniformFormat('prevViewport', UNIFORMTYPE_VEC2),
94841
+ new UniformFormat('prevFocal', UNIFORMTYPE_VEC2),
94842
+ new UniformFormat('numChunks', UNIFORMTYPE_UINT),
94843
+ new UniformFormat('splatTextureSize', UNIFORMTYPE_UINT),
94844
+ new UniformFormat('isOrtho', UNIFORMTYPE_UINT),
94845
+ new UniformFormat('minPixelSize', UNIFORMTYPE_FLOAT),
94846
+ new UniformFormat('alphaClip', UNIFORMTYPE_FLOAT),
94847
+ new UniformFormat('minContribution', UNIFORMTYPE_FLOAT),
94848
+ new UniformFormat('occBlocksX1', UNIFORMTYPE_UINT),
94849
+ new UniformFormat('occBlocksY1', UNIFORMTYPE_UINT),
94850
+ new UniformFormat('occBlocksX2', UNIFORMTYPE_UINT),
94851
+ new UniformFormat('occBlocksY2', UNIFORMTYPE_UINT),
94852
+ new UniformFormat('occlusionMode', UNIFORMTYPE_UINT),
94853
+ new UniformFormat('prevFlip', UNIFORMTYPE_FLOAT),
94854
+ new UniformFormat('keyLogNear', UNIFORMTYPE_FLOAT),
94855
+ new UniformFormat('keyInvLogRange', UNIFORMTYPE_FLOAT),
94856
+ new UniformFormat('chunkBase', UNIFORMTYPE_UINT),
94857
+ new UniformFormat('model', UNIFORMTYPE_MAT4),
94858
+ new UniformFormat('modelRotation', UNIFORMTYPE_VEC4),
94859
+ new UniformFormat('modelScale', UNIFORMTYPE_VEC4),
94860
+ new UniformFormat('cameraPosition', UNIFORMTYPE_VEC4),
94861
+ new UniformFormat('colorMax', UNIFORMTYPE_FLOAT),
94862
+ new UniformFormat('unitScale', UNIFORMTYPE_FLOAT),
94863
+ new UniformFormat('depthNear', UNIFORMTYPE_FLOAT),
94864
+ new UniformFormat('depthFar', UNIFORMTYPE_FLOAT)
94865
+ ])
94866
+ },
94867
+ computeBindGroupFormat: this.projectorBindGroupFormat
94868
+ });
94869
+ this.projectorShaders.set(key, shader);
94870
+ return shader;
94871
+ }
94872
+ destroyProjector() {
94873
+ for (const compute of this.projectorComputes.values())
94874
+ compute.destroy();
94875
+ this.projectorComputes.clear();
94876
+ for (const shader of this.projectorShaders.values())
94877
+ shader.destroy();
94878
+ this.projectorShaders.clear();
94879
+ this.projectorBindGroupFormat?.destroy();
94880
+ this.projectorBindGroupFormat = null;
94881
+ this.projectorSourceKey = '';
94882
+ }
94883
+ destroy() {
94884
+ this.unsubscribe();
94885
+ this.app.off('frameend', this.onFrameEnd);
94886
+ this.detach();
94887
+ this.provider.destroy();
94888
+ this.source.destroy();
94889
+ this.destroyProjector();
94890
+ this.args.shader.destroy();
94891
+ this.args.destroy();
94892
+ this.argsBindGroupFormat.destroy();
94893
+ for (const compute of [this.reduceL1, this.reduceL2]) {
94894
+ compute.shader.destroy();
94895
+ compute.destroy();
94896
+ }
94897
+ for (const format of this.reduceFormats)
94898
+ format.destroy();
94899
+ this.occL1.destroy();
94900
+ this.occL2.destroy();
94901
+ for (const compute of [this.orderScan, this.orderScatter]) {
94902
+ compute.shader.destroy();
94903
+ compute.destroy();
94904
+ }
94905
+ for (const format of this.orderFormats)
94906
+ format.destroy();
94907
+ this.orderBuckets.destroy();
94908
+ this.orderedBuffer?.destroy();
94909
+ this.orderedBuffer = null;
94910
+ this.chunkBuffer?.destroy();
94911
+ this.nodeVisibleBuffer?.destroy();
94912
+ this.cacheBuffer?.destroy();
94913
+ this.counter.destroy();
94914
+ this.chunkBuffer = this.nodeVisibleBuffer = this.cacheBuffer = null;
94915
+ this.rasterPass.destroy();
94916
+ this.rasterInstance.destroy();
94917
+ this.rasterMaterial.destroy();
94918
+ this.rasterMesh.destroy();
94919
+ this.taaPass.destroy();
94920
+ this.taaInstance.destroy();
94921
+ this.taaMaterial.destroy();
94922
+ this.taaMesh.destroy();
94923
+ for (const target of this.taaTargets)
94924
+ target.destroy();
94925
+ for (const texture of [...this.taaColor, ...this.taaInfo])
94926
+ texture.destroy();
94927
+ this.taaTargets.length = 0;
94928
+ this.taaColor.length = 0;
94929
+ this.taaInfo.length = 0;
94930
+ this.target.destroy();
94931
+ this.colorTexture.destroy();
94932
+ this.depthTexture.destroy();
94933
+ this.composeInstance.destroy();
94934
+ this.composeMaterial.destroy();
94935
+ this.composeMesh.destroy();
94936
+ }
94937
+ }
94938
+
91427
94939
  // ---------------------------------------------------------------------------
91428
94940
  // WGSL compute shader: ray-march through the sparse voxel octree per pixel
91429
94941
  // ---------------------------------------------------------------------------
@@ -93631,6 +97143,17 @@ const rendererTable = {
93631
97143
  webgl: GSPLAT_RENDERER_RASTER_CPU_SORT,
93632
97144
  webgpu: GSPLAT_RENDERER_RASTER_GPU_SORT
93633
97145
  };
97146
+ // quality budget, millions of splats
97147
+ const budgets = {
97148
+ mobile: {
97149
+ low: 1,
97150
+ high: 2
97151
+ },
97152
+ desktop: {
97153
+ low: 2,
97154
+ high: 4
97155
+ }
97156
+ };
93634
97157
  const tonemapTable = {
93635
97158
  none: TONEMAP_NONE,
93636
97159
  linear: TONEMAP_LINEAR,
@@ -93725,6 +97248,13 @@ class Viewer {
93725
97248
  meshOverlay = null;
93726
97249
  navCursor = null;
93727
97250
  debugPanel = null;
97251
+ /** The opt-in stochastic renderer (WebGPU only); null when the engine's sorted renderer draws. */
97252
+ splatRenderer = null;
97253
+ /**
97254
+ * The engine's MiniStats panel once first shown (`?ministats` or the debug panel), else null.
97255
+ * Hiding disables it rather than destroying it.
97256
+ */
97257
+ miniStats = null;
93728
97258
  /** Set once {@link destroy} has run. Load continuations check it and bail. */
93729
97259
  destroyed = false;
93730
97260
  disposers = [];
@@ -93784,10 +97314,35 @@ class Viewer {
93784
97314
  app.autoRender = true;
93785
97315
  // configure the camera
93786
97316
  this.configureCamera(settings);
93787
- // reconfigure camera when entering/exiting XR
97317
+ // The stochastic renderer, when opted in. Created before the first frame so it can
97318
+ // switch the engine's own splat renderer off as soon as the engine creates it. An
97319
+ // instance without the flag never constructs it, and the sorted path is untouched.
97320
+ if (config.stochastic && renderer === 'webgpu') {
97321
+ const worldLayer = app.scene.layers.getLayerByName('World');
97322
+ // the largest budget this instance can ask for must fit the device's storage binding
97323
+ const budget = (config.budget && config.budget > 0
97324
+ ? config.budget
97325
+ : (platform.mobile ? budgets.mobile : budgets.desktop).high) * 1000000;
97326
+ if (!StochasticSplatRenderer.cacheFits(app.graphicsDevice, budget)) {
97327
+ console.warn(`stochastic renderer: a ${budget / 1000000}M splat budget exceeds this device's storage binding limit; the sorted renderer draws`);
97328
+ }
97329
+ else if (worldLayer) {
97330
+ this.splatRenderer = new StochasticSplatRenderer(app, camera.camera, worldLayer, {
97331
+ source: config.splatSource,
97332
+ variant: config.variant
97333
+ });
97334
+ // announced on the first frame rather than here: createViewer resolves after this
97335
+ // constructor, so a page can only subscribe once loading is under way
97336
+ events.once('firstFrame', () => events.fire('splatRenderer:ready', this.splatRenderer));
97337
+ }
97338
+ }
97339
+ // reconfigure camera when entering/exiting XR. The stochastic renderer has no stereo
97340
+ // path yet, so the engine's renderer draws the splats for the session
93788
97341
  const configureXrCamera = () => {
93789
- if (!this.destroyed)
93790
- this.configureCamera(settings);
97342
+ if (this.destroyed)
97343
+ return;
97344
+ this.configureCamera(settings);
97345
+ this.splatRenderer?.setEnabled(!app.xr.active);
93791
97346
  };
93792
97347
  const xrStart = app.xr.on('start', configureXrCamera);
93793
97348
  const xrEnd = app.xr.on('end', configureXrCamera);
@@ -93795,28 +97350,12 @@ class Viewer {
93795
97350
  xrStart.off();
93796
97351
  xrEnd.off();
93797
97352
  });
93798
- // construct debug ministats
93799
- if (config.ministats) {
93800
- const options = MiniStats.getDefaultOptions();
93801
- options.cpu.enabled = false;
93802
- options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
93803
- options.stats.push({
93804
- name: 'VRAM',
93805
- stats: ['vram.tex'],
93806
- decimalPlaces: 1,
93807
- multiplier: 1 / (1024 * 1024),
93808
- unitsName: 'MB',
93809
- watermark: 1024
93810
- }, {
93811
- name: 'Splats',
93812
- stats: ['frame.gsplats'],
93813
- decimalPlaces: 3,
93814
- multiplier: 1 / 1000000,
93815
- unitsName: 'M',
93816
- watermark: 5
93817
- });
93818
- new MiniStats(app, options);
93819
- }
97353
+ // debug ministats, from the flag at start and the debug panel's toggle after
97354
+ this.setMiniStats(config.ministats);
97355
+ this.onDestroy(() => {
97356
+ this.miniStats?.destroy();
97357
+ this.miniStats = null;
97358
+ });
93820
97359
  const prevProj = new Mat4();
93821
97360
  const prevWorld = new Mat4();
93822
97361
  const sceneBound = new BoundingBox();
@@ -93825,7 +97364,7 @@ class Viewer {
93825
97364
  const world = camera.getWorldTransform();
93826
97365
  const proj = camera.camera.projectionMatrix;
93827
97366
  if (!app.renderNextFrame) {
93828
- if (config.ministats ||
97367
+ if (this.miniStats?.enabled ||
93829
97368
  !nearlyEquals(world.data, prevWorld.data) ||
93830
97369
  !nearlyEquals(proj.data, prevProj.data)) {
93831
97370
  app.renderNextFrame = true;
@@ -94006,7 +97545,12 @@ class Viewer {
94006
97545
  if (gsplatBbox) {
94007
97546
  sceneBound.setFromTransformedAabb(gsplatBbox, results[0].getWorldTransform());
94008
97547
  }
94009
- this.picker = new Picker(app, camera);
97548
+ // the stochastic renderer leaves its frame's depth behind, so no pick pass is needed
97549
+ this.picker = this.splatRenderer
97550
+ ? new FrameDepthPicker(app, camera, this.splatRenderer)
97551
+ : new Picker(app, camera);
97552
+ // for development pages (the bench measures pick noise), as splatRenderer:ready
97553
+ events.fire('picker:ready', this.picker);
94010
97554
  this.inputController = new InputController(global, this.picker);
94011
97555
  this.cameraManager = new CameraManager(global, sceneBound);
94012
97556
  applyCamera(this.cameraManager.camera);
@@ -94056,18 +97600,10 @@ class Viewer {
94056
97600
  // collision may already have landed while the splats were still streaming
94057
97601
  if (collisionReady)
94058
97602
  attachCollision(collisionReady);
94059
- this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker);
94060
- // quality budget
94061
- const budgets = {
94062
- mobile: {
94063
- low: 1,
94064
- high: 2
94065
- },
94066
- desktop: {
94067
- low: 2,
94068
- high: 4
94069
- }
94070
- };
97603
+ this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker, this.splatRenderer, {
97604
+ shown: () => !!this.miniStats?.enabled,
97605
+ show: (value) => this.setMiniStats(value)
97606
+ });
94071
97607
  const applyPerfSettings = () => {
94072
97608
  const budget = () => {
94073
97609
  if (config.budget !== undefined && Number.isFinite(config.budget) && config.budget > 0) {
@@ -94122,7 +97658,12 @@ class Viewer {
94122
97658
  // handle quality mode changes
94123
97659
  events.on('performanceMode:changed', applyPerfSettings);
94124
97660
  applyPerfSettings();
94125
- gsplat.renderer = rendererTable[renderer];
97661
+ // the stochastic renderer consumes the engine's world under whatever
97662
+ // renderer mode the engine resolved; switching modes here would rebuild
97663
+ // the work buffer for nothing
97664
+ if (!this.splatRenderer) {
97665
+ gsplat.renderer = rendererTable[renderer];
97666
+ }
94126
97667
  // wait for the first valid frame to complete rendering
94127
97668
  app.once('frameend', () => {
94128
97669
  events.fire('firstFrame');
@@ -94272,6 +97813,49 @@ class Viewer {
94272
97813
  }
94273
97814
  this.disposers.push(fn);
94274
97815
  }
97816
+ /**
97817
+ * Show or hide the engine's MiniStats panel. While shown the viewer renders every frame, so
97818
+ * the graphs keep moving.
97819
+ */
97820
+ setMiniStats(value) {
97821
+ if (value === !!this.miniStats?.enabled)
97822
+ return;
97823
+ // hidden by disabling rather than destroying: the engine's destroy() leaves its stats
97824
+ // timers reading every frame and its buffers allocated, so a panel per toggle would pile
97825
+ // them up until teardown
97826
+ if (this.miniStats) {
97827
+ this.miniStats.enabled = value;
97828
+ // the panel's transparent div would keep catching clicks over the canvas
97829
+ this.miniStats.div.style.display = value ? '' : 'none';
97830
+ if (value) {
97831
+ // enabling turns every graph on, the text-only size's too: its size puts them back
97832
+ const size = this.miniStats.activeSizeIndex;
97833
+ this.miniStats.activeSizeIndex = size;
97834
+ this.global.app.renderNextFrame = true;
97835
+ }
97836
+ return;
97837
+ }
97838
+ const options = MiniStats.getDefaultOptions();
97839
+ options.cpu.enabled = false;
97840
+ options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
97841
+ options.stats.push({
97842
+ name: 'VRAM',
97843
+ stats: ['vram.tex'],
97844
+ decimalPlaces: 1,
97845
+ multiplier: 1 / (1024 * 1024),
97846
+ unitsName: 'MB',
97847
+ watermark: 1024
97848
+ }, {
97849
+ name: 'Splats',
97850
+ stats: ['frame.gsplats'],
97851
+ decimalPlaces: 3,
97852
+ multiplier: 1 / 1000000,
97853
+ unitsName: 'M',
97854
+ watermark: 5
97855
+ });
97856
+ this.miniStats = new MiniStats(this.global.app, options);
97857
+ this.global.app.renderNextFrame = true;
97858
+ }
94275
97859
  /**
94276
97860
  * Tear the viewer down: stop rendering, remove every listener it added to the window,
94277
97861
  * document and canvas, restore the globals it patched, and release the graphics device.
@@ -94302,6 +97886,8 @@ class Viewer {
94302
97886
  this.voxelOverlay?.destroy();
94303
97887
  this.meshOverlay?.destroy();
94304
97888
  this.picker?.release();
97889
+ this.splatRenderer?.destroy();
97890
+ this.splatRenderer = null;
94305
97891
  this.capture?.destroy();
94306
97892
  this.capture = null;
94307
97893
  if (this.cameraFrame) {
@@ -94497,6 +98083,12 @@ const createApp = async (canvas, config) => {
94497
98083
  touch: new TouchDevice$1(canvas),
94498
98084
  keyboard: new Keyboard(window)
94499
98085
  });
98086
+ // The stochastic renderer never sorts on the cpu, so the per-splat centres the engine
98087
+ // reads back for its cpu sort (12 bytes each, plus a gpu readback per file) are dead
98088
+ // weight. Read once per file at load, so it has to be set before any asset loads.
98089
+ if (config.stochastic && renderer === 'webgpu') {
98090
+ app.scene.gsplatCentersEnabled = false;
98091
+ }
94500
98092
  // enable anonymous CORS for image loading in safari (must be set before any
94501
98093
  // texture asset starts loading, otherwise the <img> is fetched without the
94502
98094
  // crossorigin attribute and WebGL rejects it with SecurityError)
@@ -94600,6 +98192,9 @@ const resolveConfig = (options) => ({
94600
98192
  colorize: options.colorize ?? false,
94601
98193
  fullload: options.fullload ?? false,
94602
98194
  aa: options.aa ?? false,
98195
+ stochastic: options.stochastic ?? false,
98196
+ splatSource: options.splatSource ?? 'workbuffer',
98197
+ variant: options.variant ?? '',
94603
98198
  budget: options.budget,
94604
98199
  heatmap: options.heatmap ?? false,
94605
98200
  debug: options.debug ?? false,