@playcanvas/supersplat-viewer 1.35.2 → 1.36.1

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.1";
83847
83847
 
83848
83848
  class Tooltip {
83849
83849
  register;
@@ -84008,6 +84008,58 @@ const initAnnotationControls = (viewer, root) => {
84008
84008
  };
84009
84009
  };
84010
84010
 
84011
+ /**
84012
+ * Displacement-based inputs (mouse, touch, wheel, pinch) return accumulated
84013
+ * pixel offsets that already scale with frame time. This factor converts
84014
+ * rate-based speed constants (tuned for degrees-per-second) to work with
84015
+ * per-frame displacements, making them frame-rate-independent.
84016
+ */
84017
+ const DISPLACEMENT_SCALE = 1 / 60;
84018
+ /** Maximum accumulated touch movement (px) to still count as a tap. */
84019
+ const TAP_EPSILON = 15;
84020
+ const tmpHalfSize = new Vec3();
84021
+ /**
84022
+ * Converts screen-space pixel deltas to a world-space pan vector at the
84023
+ * given depth.
84024
+ *
84025
+ * @param camera - The camera component.
84026
+ * @param dx - Horizontal pixel delta.
84027
+ * @param dy - Vertical pixel delta.
84028
+ * @param dz - Depth (world-space) at which to project the delta.
84029
+ * @param out - Optional output vector.
84030
+ * @returns The pan vector in world space.
84031
+ */
84032
+ const screenToWorld = (camera, dx, dy, dz, out = new Vec3()) => {
84033
+ const { system, fov, aspectRatio, horizontalFov, projection, orthoHeight } = camera;
84034
+ const { width, height } = system.app.graphicsDevice.clientRect;
84035
+ out.set(-(dx / width) * 2, (dy / height) * 2, 0);
84036
+ const halfSize = tmpHalfSize.set(0, 0, 0);
84037
+ if (projection === PROJECTION_PERSPECTIVE) {
84038
+ const halfSlice = dz * Math.tan(0.5 * fov * math.DEG_TO_RAD);
84039
+ if (horizontalFov) {
84040
+ halfSize.set(halfSlice, halfSlice / aspectRatio, 0);
84041
+ }
84042
+ else {
84043
+ halfSize.set(halfSlice * aspectRatio, halfSlice, 0);
84044
+ }
84045
+ }
84046
+ else {
84047
+ halfSize.set(orthoHeight * aspectRatio, orthoHeight, 0);
84048
+ }
84049
+ out.mul(halfSize);
84050
+ return out;
84051
+ };
84052
+ /**
84053
+ * The orbit camera and the fly camera disagree on the sign of the z-axis
84054
+ * for forward motion. Apply this when emitting a forward/back z-component
84055
+ * so the same wheel-style delta drives both cameras correctly.
84056
+ *
84057
+ * @param mode - The current camera mode.
84058
+ * @param z - The raw forward/back z-component.
84059
+ * @returns The z-component flipped for orbit mode, unchanged otherwise.
84060
+ */
84061
+ const flipZForOrbit = (mode, z) => (mode === 'orbit' ? -z : z);
84062
+
84011
84063
  const vec$1 = new Vec3();
84012
84064
  /**
84013
84065
  * A script for creating interactive 3D annotations in a scene. Each annotation consists of:
@@ -84083,8 +84135,9 @@ class Annotation extends Script {
84083
84135
  }
84084
84136
  /**
84085
84137
  * Update the screen-space elements for this annotation. Called each frame from the
84086
- * prerender callback, and also directly from showTooltip to ensure the tooltip is positioned
84087
- * correctly even when the camera hasn't moved (e.g. annotations sharing the same camera pose).
84138
+ * prerender callback, and also directly from revealTooltip to ensure the tooltip is
84139
+ * positioned correctly even when the camera hasn't moved (e.g. annotations sharing the same
84140
+ * camera pose).
84088
84141
  * @private
84089
84142
  */
84090
84143
  _update() {
@@ -84112,16 +84165,33 @@ class Annotation extends Script {
84112
84165
  this.hotspotDom.classList.toggle('sse-occluded', occluded);
84113
84166
  }
84114
84167
  /**
84168
+ * Make this the annotation whose tooltip shows. The tooltip itself waits for the camera to
84169
+ * near the end of its move here, when `Annotations` calls `revealTooltip`, rather than
84170
+ * chasing the hotspot across the screen during the flight.
84115
84171
  * @private
84116
84172
  */
84117
84173
  showTooltip() {
84118
84174
  const ctx = this.context;
84119
84175
  ctx.activeAnnotation = this;
84120
- ctx.titleDom.textContent = this.title;
84121
- ctx.textDom.textContent = this.text;
84122
- ctx.tooltipDom.classList.add('sse-visible');
84176
+ ctx.revealed = false;
84123
84177
  this.hotspotDom.classList.add('sse-active');
84124
- // Immediately update incase the camera doesn't move
84178
+ }
84179
+ /**
84180
+ * Show the tooltip beside this annotation, the camera being at or nearly at rest.
84181
+ * @private
84182
+ */
84183
+ revealTooltip() {
84184
+ const ctx = this.context;
84185
+ ctx.revealed = true;
84186
+ if (ctx.tooltipOwner !== this) {
84187
+ // taken over only now, so the tooltip fades out with the previous annotation's text,
84188
+ // beside its hotspot; and with no side yet, rather than the one it left it on
84189
+ ctx.tooltipOwner = this;
84190
+ ctx.titleDom.textContent = this.title;
84191
+ ctx.textDom.textContent = this.text;
84192
+ ctx.tooltipDom.classList.remove('sse-arrow-left', 'sse-arrow-right');
84193
+ }
84194
+ // the camera may be still, so no prerender may follow
84125
84195
  this._update();
84126
84196
  }
84127
84197
  /**
@@ -84139,7 +84209,7 @@ class Annotation extends Script {
84139
84209
  */
84140
84210
  _hideElements() {
84141
84211
  this.hotspotDom.style.display = 'none';
84142
- if (this.context.activeAnnotation === this) {
84212
+ if (this.context.tooltipOwner === this) {
84143
84213
  this.context.tooltipDom.classList.remove('sse-visible');
84144
84214
  }
84145
84215
  }
@@ -84158,28 +84228,43 @@ class Annotation extends Script {
84158
84228
  // nearer hotspots draw over farther ones
84159
84229
  hotspot.style.zIndex = String(Math.round(100000 / (1 + distance)));
84160
84230
  const ctx = this.context;
84161
- if (ctx.activeAnnotation !== this) {
84231
+ if (ctx.tooltipOwner !== this) {
84162
84232
  return;
84163
84233
  }
84164
- // Re-show tooltip if it was hidden while behind camera
84234
+ // Shown while this annotation is selected and revealed, clamped to the canvas when the
84235
+ // hotspot is beyond it, so moving the camera yourself does not lose it. Hidden, it fades
84236
+ // out, moving with the hotspot at the offset it last had rather than standing still while
84237
+ // the camera moves on
84165
84238
  const tooltip = ctx.tooltipDom;
84166
- tooltip.classList.add('sse-visible');
84167
- // Position tooltip, clamped to the canvas (screenPos is in canvas pixels)
84239
+ const vw = ctx.canvas.clientWidth;
84240
+ const vh = ctx.canvas.clientHeight;
84241
+ const onCanvas = screenPos.x >= 0 && screenPos.x <= vw && screenPos.y >= 0 && screenPos.y <= vh;
84242
+ if (ctx.activeAnnotation !== this || !ctx.revealed) {
84243
+ tooltip.classList.remove('sse-visible');
84244
+ const offset = ctx.tooltipOffset;
84245
+ if (offset) {
84246
+ tooltip.style.transform = `translate(${screenPos.x + offset.x}px, ${screenPos.y + offset.y}px)`;
84247
+ }
84248
+ return;
84249
+ }
84250
+ // Position tooltip, clamped to the canvas (screenPos is in canvas pixels). Measured
84251
+ // before it is shown, which also lets a tooltip that was empty, and so not displayed,
84252
+ // fade in rather than appear at once
84168
84253
  const margin = 8;
84169
84254
  const arrowOffset = 24;
84170
84255
  const tw = tooltip.offsetWidth;
84171
84256
  const th = tooltip.offsetHeight;
84172
- const vw = ctx.canvas.clientWidth;
84173
- const vh = ctx.canvas.clientHeight;
84174
- // Default position: to the right of hotspot, vertically centered
84175
- let left = screenPos.x + arrowOffset;
84176
- let top = screenPos.y - th / 2;
84177
- let flipped = false;
84178
- // If tooltip overflows right edge, flip to left side of hotspot
84179
- if (left + tw > vw - margin) {
84180
- left = screenPos.x - arrowOffset - tw;
84181
- flipped = true;
84257
+ // Beside the hotspot, vertically centered, on the side it is already on: changing sides
84258
+ // jumps it across the hotspot, so it does only when it no longer fits there and does on
84259
+ // the other side. With no side yet, the right unless that overflows
84260
+ const onRight = screenPos.x + arrowOffset;
84261
+ const onLeft = screenPos.x - arrowOffset - tw;
84262
+ let flipped = tooltip.classList.contains('sse-arrow-left');
84263
+ if (flipped ? onLeft < margin && onRight + tw <= vw - margin : onRight + tw > vw - margin) {
84264
+ flipped = !flipped;
84182
84265
  }
84266
+ let left = flipped ? onLeft : onRight;
84267
+ let top = screenPos.y - th / 2;
84183
84268
  // Clamp horizontal
84184
84269
  left = Math.max(margin, Math.min(left, vw - tw - margin));
84185
84270
  // Clamp vertical
@@ -84190,6 +84275,8 @@ class Annotation extends Script {
84190
84275
  tooltip.classList.toggle('sse-arrow-right', !flipped);
84191
84276
  tooltip.classList.toggle('sse-arrow-left', flipped);
84192
84277
  tooltip.style.transform = `translate(${left}px, ${top}px)`;
84278
+ tooltip.classList.add('sse-visible');
84279
+ ctx.tooltipOffset = onCanvas ? { x: left - screenPos.x, y: top - screenPos.y } : null;
84193
84280
  }
84194
84281
  }
84195
84282
  /**
@@ -84208,6 +84295,15 @@ class AnnotationContext {
84208
84295
  titleDom;
84209
84296
  textDom;
84210
84297
  activeAnnotation = null;
84298
+ // whether the active annotation's tooltip has been revealed: it hides for each camera
84299
+ // transition, the move to the annotation among them, until the transition nearly ends
84300
+ revealed = false;
84301
+ // the annotation the tooltip belongs to: the active one once revealed, until then the one
84302
+ // before it, beside whose hotspot it fades out. And its offset from that hotspot when it
84303
+ // last showed, which it keeps while fading; null when it last showed clamped to the canvas
84304
+ // with the hotspot beyond it, since it is not beside the hotspot, and then it fades in place
84305
+ tooltipOwner = null;
84306
+ tooltipOffset = null;
84211
84307
  constructor(canvas, camera, parentDom) {
84212
84308
  this.parentDom = parentDom;
84213
84309
  this.canvas = canvas;
@@ -84238,6 +84334,10 @@ const OCCLUDING_OPACITY = 0.5;
84238
84334
  const OCCLUSION_TOLERANCE = 0.1;
84239
84335
  // the hotspot's radius in css pixels: the opacity in front is averaged over its whole disc
84240
84336
  const HOTSPOT_RADIUS = 13;
84337
+ // the selected annotation's tooltip starts fading in once the camera has eased this far along
84338
+ // a transition, its move there among them: the move settles slowly, so waiting for it to stop
84339
+ // shows the tooltip well after the camera looks to have arrived
84340
+ const REVEAL_PROGRESS = 0.9;
84241
84341
  // Built-in hotspot and panel presentation. Selection and camera navigation belong to the viewer.
84242
84342
  class Annotations {
84243
84343
  parentDom;
@@ -84245,7 +84345,7 @@ class Annotations {
84245
84345
  subscriptions;
84246
84346
  removeClick;
84247
84347
  removeOcclusion;
84248
- constructor(viewer, root, camera, getPicker) {
84348
+ constructor(viewer, root, camera, getPicker, getCameraProgress) {
84249
84349
  const { app, state, events, annotations } = viewer;
84250
84350
  const parentDom = document.createElement('div');
84251
84351
  parentDom.className = 'sse-annotations';
@@ -84282,7 +84382,7 @@ class Annotations {
84282
84382
  // bumped on every camera move, so a test that resolves after the camera moved again is
84283
84383
  // discarded rather than applied to a pose it was not taken from
84284
84384
  let pose = 0;
84285
- const lastView = new Mat4();
84385
+ const lastWorld = new Mat4();
84286
84386
  const lastProjection = new Mat4();
84287
84387
  const testOcclusion = async () => {
84288
84388
  settleTimer = null;
@@ -84321,12 +84421,43 @@ class Annotations {
84321
84421
  clearTimeout(settleTimer);
84322
84422
  settleTimer = setTimeout(testOcclusion, SETTLE_MS);
84323
84423
  };
84324
- // after each frame, since the hotspots' screen positions are updated in prerender
84424
+ // A new camera transition (a reset, say): the tooltip hides until it nearly ends, as on
84425
+ // the move to an annotation. Checked after the camera update but before the frame
84426
+ // renders, so the tooltip is not laid out for the transition's first frame
84427
+ let lastProgress = 1;
84428
+ const onFrameRender = () => {
84429
+ const progress = getCameraProgress();
84430
+ if (progress < lastProgress)
84431
+ context.revealed = false;
84432
+ lastProgress = progress;
84433
+ };
84434
+ app.on('framerender', onFrameRender);
84435
+ // after each frame, since the hotspots' screen positions are updated in prerender. The
84436
+ // camera entity's transform rather than its view matrix, which the engine refreshes only
84437
+ // for frames that render: the viewer skips a frame whose camera moved too little to see,
84438
+ // and a stale view matrix would pass for a camera at rest
84325
84439
  const onFrameEnd = () => {
84326
- const { viewMatrix, projectionMatrix } = camera.camera;
84327
- if (lastView.equals(viewMatrix) && lastProjection.equals(projectionMatrix))
84440
+ const world = camera.getWorldTransform();
84441
+ const { projectionMatrix } = camera.camera;
84442
+ const still = lastWorld.equals(world) && lastProjection.equals(projectionMatrix);
84443
+ const progress = getCameraProgress();
84444
+ // Show the selected annotation's tooltip once the camera is nearly there with the
84445
+ // hotspot on the canvas, fading in as the camera lands, or once the camera is at rest.
84446
+ // A hotspot that ends beyond the canvas gets its tooltip at rest, clamped to the edge,
84447
+ // rather than one that shows and then hides again as the hotspot slides off
84448
+ const { activeAnnotation } = context;
84449
+ const screen = activeAnnotation?.screen;
84450
+ const onCanvas = screen &&
84451
+ screen.x >= 0 &&
84452
+ screen.x <= canvas.clientWidth &&
84453
+ screen.y >= 0 &&
84454
+ screen.y <= canvas.clientHeight;
84455
+ if (activeAnnotation && !context.revealed && (still || (progress >= REVEAL_PROGRESS && onCanvas))) {
84456
+ activeAnnotation.revealTooltip();
84457
+ }
84458
+ if (still)
84328
84459
  return;
84329
- lastView.copy(viewMatrix);
84460
+ lastWorld.copy(world);
84330
84461
  lastProjection.copy(projectionMatrix);
84331
84462
  pose++;
84332
84463
  scheduleOcclusion();
@@ -84352,6 +84483,7 @@ class Annotations {
84352
84483
  destroyed = true;
84353
84484
  if (settleTimer)
84354
84485
  clearTimeout(settleTimer);
84486
+ app.off('framerender', onFrameRender);
84355
84487
  app.off('frameend', onFrameEnd);
84356
84488
  gsplatSystem.off('frame:ready', onFrameReady);
84357
84489
  };
@@ -84379,12 +84511,32 @@ class Annotations {
84379
84511
  events.on('gamingControls:changed', update)
84380
84512
  ];
84381
84513
  update();
84514
+ // A click deselects, but a drag ends in a click too, so releasing an orbit would close
84515
+ // the tooltip. A press that moved farther than a tap may is a drag, as the navigation
84516
+ // clicks count it
84517
+ let pressMovement = 0;
84518
+ const onPointerDown = () => {
84519
+ pressMovement = 0;
84520
+ };
84521
+ const onPointerMove = (event) => {
84522
+ if (event.buttons)
84523
+ pressMovement += Math.abs(event.movementX) + Math.abs(event.movementY);
84524
+ };
84382
84525
  const onClick = () => {
84383
- if (state.loaded && state.selectedAnnotation !== null)
84526
+ // consumed, so a later click from the keyboard is not taken for the drag
84527
+ const dragged = pressMovement >= TAP_EPSILON;
84528
+ pressMovement = 0;
84529
+ if (!dragged && state.loaded && state.selectedAnnotation !== null)
84384
84530
  viewer.selectAnnotation(null);
84385
84531
  };
84532
+ root.addEventListener('pointerdown', onPointerDown);
84533
+ root.addEventListener('pointermove', onPointerMove);
84386
84534
  root.addEventListener('click', onClick);
84387
- this.removeClick = () => root.removeEventListener('click', onClick);
84535
+ this.removeClick = () => {
84536
+ root.removeEventListener('pointerdown', onPointerDown);
84537
+ root.removeEventListener('pointermove', onPointerMove);
84538
+ root.removeEventListener('click', onClick);
84539
+ };
84388
84540
  }
84389
84541
  destroy() {
84390
84542
  for (const subscription of this.subscriptions)
@@ -85069,8 +85221,9 @@ const getGpuName = (device) => {
85069
85221
  // document, screen) and cancels pending timers. Listeners on the subtree's own elements are
85070
85222
  // released with the elements.
85071
85223
  // `getPicker` returns the viewer's picker once the scene has loaded, for the annotation
85072
- // occlusion test
85073
- const initUI = (global, viewer, getPicker) => {
85224
+ // occlusion test; `getCameraProgress` how far the camera's current move has eased, 1 when there
85225
+ // is none, for the annotation tooltip's timing
85226
+ const initUI = (global, viewer, getPicker, getCameraProgress) => {
85074
85227
  const { root, localize } = global;
85075
85228
  const { events, state } = viewer;
85076
85229
  const disposers = [];
@@ -85434,7 +85587,7 @@ const initUI = (global, viewer, getPicker) => {
85434
85587
  disposers.push(initJoystick(viewer, root));
85435
85588
  disposers.push(initAnnotationControls(viewer, root));
85436
85589
  if (viewer.annotations.length > 0) {
85437
- const annotations = new Annotations(viewer, root, global.camera, getPicker);
85590
+ const annotations = new Annotations(viewer, root, global.camera, getPicker, getCameraProgress);
85438
85591
  disposers.push(() => annotations.destroy());
85439
85592
  }
85440
85593
  // tooltips
@@ -87434,6 +87587,9 @@ class CameraManager {
87434
87587
  // mutating `camera` and/or `state.cameraMode` to make the change
87435
87588
  // visible instantly.
87436
87589
  snap;
87590
+ // How far the current transition has eased toward its destination, from 0 to 1; 1 when
87591
+ // there is none. The annotations time their tooltip to the camera's arrival with it.
87592
+ transitionProgress;
87437
87593
  // Attach (or clear) collision after construction. The viewer reveals the scene without
87438
87594
  // waiting for collision data, which can be larger than the splats themselves, so this
87439
87595
  // arrives late. It re-tests whether walk mode is allowed, which gates the walk toggle
@@ -87527,6 +87683,7 @@ class CameraManager {
87527
87683
  transitionEase = ease;
87528
87684
  transitionTurnEase = turnEase;
87529
87685
  };
87686
+ this.transitionProgress = () => (transitionTimer < 1 ? transitionEase(transitionTimer) : 1);
87530
87687
  this.setCollision = (value) => {
87531
87688
  controllers.fly.collision = value;
87532
87689
  controllers.walk.collision = value;
@@ -88505,6 +88662,132 @@ const fitPlaneNormal = (points, toCamera, outNormal) => {
88505
88662
  outNormal.set(vx, vy, vz);
88506
88663
  return true;
88507
88664
  };
88665
+ // The surface at a pixel: the SURFACE_OPACITY quantile of the nearest survivors over a small
88666
+ // disc, which is the depth where the opacity in front reaches that. Null where it never does.
88667
+ const surfaceDepth = (depthAt, x, y) => {
88668
+ const samples = [];
88669
+ for (let dy = -SURFACE_RADIUS_PX; dy <= SURFACE_RADIUS_PX; dy++) {
88670
+ for (let dx = -SURFACE_RADIUS_PX; dx <= SURFACE_RADIUS_PX; dx++) {
88671
+ if (dx * dx + dy * dy > SURFACE_RADIUS_PX * SURFACE_RADIUS_PX)
88672
+ continue;
88673
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
88674
+ const depth = depthAt(x + dx, y + dy, trial);
88675
+ if (depth !== null)
88676
+ samples.push(depth);
88677
+ }
88678
+ }
88679
+ }
88680
+ if (samples.length === 0) {
88681
+ return null;
88682
+ }
88683
+ samples.sort((a, b) => a - b);
88684
+ const depth = samples[Math.max(0, Math.ceil(samples.length * SURFACE_OPACITY) - 1)];
88685
+ return Number.isFinite(depth) && depth < 1 ? depth : null;
88686
+ };
88687
+ // The surface under a pixel and its normal, fitted through surface points on rings around it.
88688
+ // `depthAt` must cover NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX around the pixel.
88689
+ const estimateSurface = (depthAt, pickCamera, width, height, screenX, screenY) => {
88690
+ const surfacePoint = (px, py) => {
88691
+ const depth = surfaceDepth(depthAt, px, py);
88692
+ return depth === null ? null : getWorldPoint(pickCamera, px, py, width, height, depth);
88693
+ };
88694
+ const position = surfacePoint(screenX, screenY);
88695
+ if (!position) {
88696
+ return null;
88697
+ }
88698
+ const samplePixel = (px, py) => {
88699
+ if (px < 0 || px >= width || py < 0 || py >= height) {
88700
+ return null;
88701
+ }
88702
+ return surfacePoint(px, py);
88703
+ };
88704
+ // Pixel radius corresponding to a fixed world radius at the
88705
+ // picked-point's depth. Clamped so distant picks still sample
88706
+ // enough pixels and very-close picks stay inside the block read.
88707
+ const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
88708
+ const ringPixelRadii = NORMAL_RING_FRACTIONS.map((f) => Math.max(1, Math.round(f * pixelRadius)));
88709
+ const sampleRings = ringPixelRadii.map((radius) => {
88710
+ return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
88711
+ return samplePixel(screenX + dx * radius, screenY + dy * radius);
88712
+ });
88713
+ });
88714
+ const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
88715
+ // Collect every valid 3D sample: the picked position plus all ring
88716
+ // samples that didn't fall off-screen or find no surface.
88717
+ const fitPoints = [position];
88718
+ for (let i = 0; i < sampleRings.length; i++) {
88719
+ const ring = sampleRings[i];
88720
+ for (let j = 0; j < ring.length; j++) {
88721
+ const pt = ring[j];
88722
+ if (pt)
88723
+ fitPoints.push(pt);
88724
+ }
88725
+ }
88726
+ const normal = new Vec3();
88727
+ if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
88728
+ normal.copy(toCamera);
88729
+ }
88730
+ return {
88731
+ position,
88732
+ normal
88733
+ };
88734
+ };
88735
+ // The share of samples over a disc of `r` pixels whose nearest survivor is nearer than the view
88736
+ // depth `depth`; null where the disc has no samples. `depthAt` must cover the disc.
88737
+ const opacityInFront = (depthAt, pickCamera, screenX, screenY, r, depth) => {
88738
+ const threshold = (depth - pickCamera.nearClip) / (pickCamera.farClip - pickCamera.nearClip);
88739
+ let total = 0;
88740
+ let inFront = 0;
88741
+ for (let dy = -r; dy <= r; dy++) {
88742
+ for (let dx = -r; dx <= r; dx++) {
88743
+ if (dx * dx + dy * dy > r * r)
88744
+ continue;
88745
+ for (let trial = 0; trial < PICK_TRIALS; trial++) {
88746
+ const nearest = depthAt(screenX + dx, screenY + dy, trial);
88747
+ if (nearest === null)
88748
+ continue;
88749
+ total++;
88750
+ if (nearest < threshold)
88751
+ inFront++;
88752
+ }
88753
+ }
88754
+ }
88755
+ return total > 0 ? inFront / total : null;
88756
+ };
88757
+ // One pick pixel per css pixel, never more than the backbuffer has: picking then behaves the
88758
+ // same in performance mode and at any device pixel ratio, since the pixel sizes above are css
88759
+ // pixels, and a high-density display does not multiply the pass's cost. Null before the device
88760
+ // or the canvas has been sized.
88761
+ const pickTargetSize = (graphicsDevice) => {
88762
+ const canvas = graphicsDevice.canvas;
88763
+ const width = Math.min(Math.floor(graphicsDevice.width), Math.round(canvas.clientWidth));
88764
+ const height = Math.min(Math.floor(graphicsDevice.height), Math.round(canvas.clientHeight));
88765
+ return width > 0 && height > 0 ? { width, height } : null;
88766
+ };
88767
+ const clampPixel = (v, size) => Math.min(size - 1, Math.max(0, Math.floor(v * size)));
88768
+ // Picks run one at a time, since they share one render. `fallback` is the result for a pick
88769
+ // that release overtakes: one queued behind another pick, or one whose read-back is cut short
88770
+ // as the device goes.
88771
+ class PickQueue {
88772
+ released = false;
88773
+ queue = Promise.resolve();
88774
+ run(operation, fallback) {
88775
+ const guarded = () => {
88776
+ if (this.released) {
88777
+ return Promise.resolve(fallback);
88778
+ }
88779
+ return operation().catch((error) => {
88780
+ if (this.released) {
88781
+ return fallback;
88782
+ }
88783
+ throw error;
88784
+ });
88785
+ };
88786
+ const result = this.queue.then(guarded, guarded);
88787
+ this.queue = result.then(() => undefined, () => undefined);
88788
+ return result;
88789
+ }
88790
+ }
88508
88791
  class Picker {
88509
88792
  pick;
88510
88793
  pickSurface;
@@ -88533,10 +88816,7 @@ class Picker {
88533
88816
  let pickTarget;
88534
88817
  let pickPass;
88535
88818
  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();
88819
+ const queue = new PickQueue();
88540
88820
  let cacheValid = false;
88541
88821
  let renders = 0;
88542
88822
  let cacheWidth = 0;
@@ -88589,8 +88869,6 @@ class Picker {
88589
88869
  return snapshot;
88590
88870
  };
88591
88871
  // 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
88872
  const readAround = async (screenX, screenY, margin, width, height) => {
88595
88873
  const blockX = Math.max(0, screenX - margin);
88596
88874
  const blockY = Math.max(0, screenY - margin);
@@ -88611,29 +88889,6 @@ class Picker {
88611
88889
  return half2Float(pixels[(row * blockWidth + localX) * 4 + trial]);
88612
88890
  };
88613
88891
  };
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
88892
  const ensureRendered = (width, height, worldLayer) => {
88638
88893
  if (cameraMatches(width, height)) {
88639
88894
  return;
@@ -88660,49 +88915,24 @@ class Picker {
88660
88915
  renders++;
88661
88916
  };
88662
88917
  const prepareSample = (x, y) => {
88663
- if (released) {
88918
+ if (queue.released) {
88664
88919
  return null;
88665
88920
  }
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) {
88921
+ const size = pickTargetSize(graphicsDevice);
88922
+ if (!size) {
88675
88923
  return null;
88676
88924
  }
88925
+ const { width, height } = size;
88677
88926
  const worldLayer = app.scene.layers.getLayerByName('World');
88678
88927
  if (!worldLayer) {
88679
88928
  return null;
88680
88929
  }
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)));
88930
+ const screenX = clampPixel(x, width);
88931
+ const screenY = clampPixel(y, height);
88683
88932
  ensureRendered(width, height, worldLayer);
88684
88933
  const pickCamera = getCacheCameraSnapshot();
88685
88934
  return { width, height, screenX, screenY, pickCamera };
88686
88935
  };
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
88936
  const pick = async (x, y) => {
88707
88937
  const sample = prepareSample(x, y);
88708
88938
  if (!sample) {
@@ -88723,50 +88953,7 @@ class Picker {
88723
88953
  // Sized to the maximum possible ring pixel-radius, plus the surface disc around each
88724
88954
  // sample, so the dynamic ring offsets always lie inside the buffer we read.
88725
88955
  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
- };
88956
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
88770
88957
  };
88771
88958
  const pickVisibility = async (points, radius) => {
88772
88959
  if (points.length === 0) {
@@ -88782,29 +88969,12 @@ class Picker {
88782
88969
  const { width, height, screenX, screenY, pickCamera } = sample;
88783
88970
  const r = Math.max(1, Math.round(radius * height));
88784
88971
  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;
88972
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
88803
88973
  }));
88804
88974
  };
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));
88975
+ this.pick = (x, y) => queue.run(() => pick(x, y), null);
88976
+ this.pickSurface = (x, y) => queue.run(() => pickSurface(x, y), null);
88977
+ this.pickVisibility = (points, radius) => queue.run(() => pickVisibility(points, radius), points.map(() => null));
88808
88978
  this.renderView = () => (prepareSample(0, 0) ? { texture: pickBuffer, renders } : null);
88809
88979
  // The scene can change under a still camera, which the camera-based cache cannot see:
88810
88980
  // finer detail streams in after the reveal and after every move. The engine reports each
@@ -88823,7 +88993,7 @@ class Picker {
88823
88993
  };
88824
88994
  gsplatSystem.on('frame:ready', onFrameReady);
88825
88995
  this.release = () => {
88826
- released = true;
88996
+ queue.released = true;
88827
88997
  gsplatSystem.off('frame:ready', onFrameReady);
88828
88998
  if (chunksPatched) {
88829
88999
  unregisterPickerShaderPatches(app);
@@ -89194,6 +89364,20 @@ const STYLES = `
89194
89364
  .${PANEL_CLASS} button.sse-flash {
89195
89365
  background: rgba(120, 220, 140, 0.35);
89196
89366
  }
89367
+ .${PANEL_CLASS} button.sse-flash-bad {
89368
+ background: rgba(220, 100, 100, 0.45);
89369
+ }
89370
+ .${PANEL_CLASS} input.sse-debug-paste {
89371
+ width: 100%;
89372
+ box-sizing: border-box;
89373
+ margin-top: 6px;
89374
+ background: rgba(255, 255, 255, 0.08);
89375
+ color: #eee;
89376
+ border: 1px solid rgba(120, 180, 255, 0.6);
89377
+ border-radius: 3px;
89378
+ padding: 4px 8px;
89379
+ font: inherit;
89380
+ }
89197
89381
  .${PANEL_CLASS} button.sse-debug-on {
89198
89382
  background: rgba(120, 180, 255, 0.35);
89199
89383
  }
@@ -89216,6 +89400,14 @@ class DebugPanel {
89216
89400
  _global;
89217
89401
  _cameraManager;
89218
89402
  _picker;
89403
+ // the stochastic renderer when this viewer opted in, for its depth cull toggle and counts
89404
+ _splatRenderer;
89405
+ _cullButton = null;
89406
+ _taaButton = null;
89407
+ _poplessButton = null;
89408
+ _culledValue = null;
89409
+ _cullStatsFrames = 0;
89410
+ _cullStatsPending = false;
89219
89411
  _pickDepthOverlay = null;
89220
89412
  _focusTmp = new Vec3();
89221
89413
  _root = null;
@@ -89224,12 +89416,20 @@ class DebugPanel {
89224
89416
  _focusValue = null;
89225
89417
  _copyButton = null;
89226
89418
  _pasteButton = null;
89419
+ // shown when the clipboard cannot be read (a cross-origin iframe without clipboard-read):
89420
+ // the paste event of a focused field carries the text without that permission
89421
+ _pasteField = null;
89422
+ _miniStatsButton = null;
89423
+ // the viewer's MiniStats switch
89424
+ _miniStats;
89227
89425
  _screenshotButton = null;
89228
89426
  _pickDepthButton = null;
89229
89427
  _editing = null;
89230
89428
  _editCanceled = false;
89231
89429
  _visible = false;
89232
89430
  _onPrerender = () => this._render();
89431
+ // the cull state is decided inside the frame, so its row refreshes after it
89432
+ _onFrameEnd = () => this._renderCull();
89233
89433
  _onKeyDown = (event) => {
89234
89434
  // Ctrl+Shift+D — also accept Meta+Shift+D on macOS for parity
89235
89435
  if (!this._global.state.inputEnabled)
@@ -89239,10 +89439,12 @@ class DebugPanel {
89239
89439
  this.toggle();
89240
89440
  }
89241
89441
  };
89242
- constructor(global, cameraManager, picker) {
89442
+ constructor(global, cameraManager, picker, splatRenderer = null, miniStats = null) {
89243
89443
  this._global = global;
89244
89444
  this._cameraManager = cameraManager;
89245
89445
  this._picker = picker;
89446
+ this._splatRenderer = splatRenderer;
89447
+ this._miniStats = miniStats;
89246
89448
  window.addEventListener('keydown', this._onKeyDown);
89247
89449
  if (global.config.debug) {
89248
89450
  this.show();
@@ -89257,6 +89459,7 @@ class DebugPanel {
89257
89459
  }
89258
89460
  this._root.style.display = '';
89259
89461
  this._global.app.on('prerender', this._onPrerender);
89462
+ this._global.app.on('frameend', this._onFrameEnd);
89260
89463
  if (this._global.config.exposeGlobals) {
89261
89464
  window.getCameraState = () => captureCameraState(this._cameraManager, this._global.state);
89262
89465
  window.setCameraState = (snapshot) => restoreCameraState(this._cameraManager, this._global.state, snapshot);
@@ -89273,6 +89476,7 @@ class DebugPanel {
89273
89476
  // the view is only reachable from the panel, so it goes with it
89274
89477
  this._setPickDepth(false);
89275
89478
  this._global.app.off('prerender', this._onPrerender);
89479
+ this._global.app.off('frameend', this._onFrameEnd);
89276
89480
  if (this._global.config.exposeGlobals) {
89277
89481
  delete window.getCameraState;
89278
89482
  delete window.setCameraState;
@@ -89317,8 +89521,19 @@ class DebugPanel {
89317
89521
  </div>
89318
89522
  <div class="sse-debug-buttons">
89319
89523
  <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>
89524
+ <button data-id="pick-depth" title="Show the depth a navigation pick finds at every pixel">Show depth</button>
89525
+ <button data-id="ministats" title="Show the engine's MiniStats graphs (the viewer then renders every frame)">MiniStats</button>
89526
+ </div>
89527
+ <input class="sse-debug-paste" data-id="paste-field" placeholder="Clipboard blocked here: paste with Ctrl/Cmd+V" spellcheck="false" style="display: none">
89528
+ ${this._splatRenderer
89529
+ ? `
89530
+ <div class="sse-debug-buttons">
89531
+ <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>
89532
+ <button data-id="taa" title="Stochastic renderer: accumulate the samples over frames (reprojected while the camera moves)">TAA</button>
89533
+ <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
89534
  </div>
89535
+ <div class="sse-debug-row"><span class="sse-debug-label">culled</span><span class="sse-debug-value" data-id="culled">—</span></div>`
89536
+ : ''}
89322
89537
  `;
89323
89538
  host.appendChild(root);
89324
89539
  this._root = root;
@@ -89328,12 +89543,52 @@ class DebugPanel {
89328
89543
  this._pasteButton = root.querySelector('[data-id="paste"]');
89329
89544
  this._screenshotButton = root.querySelector('[data-id="screenshot"]');
89330
89545
  this._pickDepthButton = root.querySelector('[data-id="pick-depth"]');
89546
+ this._miniStatsButton = root.querySelector('[data-id="ministats"]');
89547
+ this._pasteField = root.querySelector('[data-id="paste-field"]');
89548
+ this._wirePasteField(this._pasteField);
89549
+ if (this._miniStats) {
89550
+ this._miniStatsButton.addEventListener('click', () => {
89551
+ this._miniStats.show(!this._miniStats.shown());
89552
+ this._renderMiniStats();
89553
+ });
89554
+ this._renderMiniStats();
89555
+ }
89556
+ else {
89557
+ this._miniStatsButton.remove();
89558
+ }
89331
89559
  this._copyButton.addEventListener('click', () => this._copy());
89332
89560
  this._pasteButton.addEventListener('click', () => this._paste());
89333
89561
  this._screenshotButton.addEventListener('click', () => this._screenshot());
89334
89562
  this._pickDepthButton.addEventListener('click', () => {
89335
89563
  this._setPickDepth(!this._pickDepthOverlay?.enabled);
89336
89564
  });
89565
+ if (this._splatRenderer) {
89566
+ this._cullButton = root.querySelector('[data-id="depth-cull"]');
89567
+ this._taaButton = root.querySelector('[data-id="taa"]');
89568
+ this._poplessButton = root.querySelector('[data-id="popless"]');
89569
+ this._poplessButton.addEventListener('click', () => {
89570
+ const renderer = this._splatRenderer;
89571
+ renderer.variant.popless = renderer.variant.popless === 'on' ? 'off' : 'on';
89572
+ renderer.applyVariant();
89573
+ this._renderCull();
89574
+ });
89575
+ this._culledValue = root.querySelector('[data-id="culled"]');
89576
+ this._taaButton.addEventListener('click', () => {
89577
+ const renderer = this._splatRenderer;
89578
+ renderer.variant.taa = renderer.variant.taa === 'on' ? 'off' : 'on';
89579
+ renderer.applyVariant();
89580
+ this._renderCull();
89581
+ });
89582
+ // cycles the cull mode: auto (the default) -> on (both grid levels) -> off
89583
+ this._cullButton.addEventListener('click', () => {
89584
+ const renderer = this._splatRenderer;
89585
+ const next = { auto: 'l2', l2: 'off', l1: 'off', off: 'auto' };
89586
+ renderer.variant.cull = next[renderer.variant.cull];
89587
+ renderer.applyVariant();
89588
+ this._renderCull();
89589
+ });
89590
+ this._renderCull();
89591
+ }
89337
89592
  this._wireEditable(this._positionValue, 'position');
89338
89593
  this._wireEditable(this._focusValue, 'focus');
89339
89594
  }
@@ -89429,27 +89684,153 @@ class DebugPanel {
89429
89684
  this._focusValue.textContent = fmt(this._focusTmp);
89430
89685
  }
89431
89686
  }
89687
+ // the cull button shows the mode; the counts come back from the gpu every few frames
89688
+ _renderCull() {
89689
+ const renderer = this._splatRenderer;
89690
+ if (!renderer || !this._cullButton || !this._culledValue)
89691
+ return;
89692
+ const mode = renderer.variant.cull;
89693
+ this._cullButton.textContent = `Depth cull: ${mode === 'off' ? 'off' : mode === 'auto' ? 'auto' : 'on'}`;
89694
+ this._cullButton.classList.toggle('sse-debug-on', mode !== 'off');
89695
+ if (this._taaButton) {
89696
+ this._taaButton.textContent = `TAA: ${renderer.variant.taa}`;
89697
+ this._taaButton.classList.toggle('sse-debug-on', renderer.variant.taa === 'on');
89698
+ }
89699
+ if (this._poplessButton) {
89700
+ this._poplessButton.textContent = `Popless: ${renderer.variant.popless}`;
89701
+ this._poplessButton.classList.toggle('sse-debug-on', renderer.variant.popless === 'on');
89702
+ }
89703
+ if (mode === 'off') {
89704
+ this._culledValue.textContent = 'off';
89705
+ return;
89706
+ }
89707
+ if (!renderer.culling) {
89708
+ this._culledValue.textContent = renderer.cullSuspended ? 'suspended' : 'no previous frame';
89709
+ return;
89710
+ }
89711
+ if (this._cullStatsPending || this._cullStatsFrames++ % 15 !== 0)
89712
+ return;
89713
+ this._cullStatsPending = true;
89714
+ renderer
89715
+ .readStats()
89716
+ .then(({ survivors, occluded }) => {
89717
+ const total = survivors + occluded;
89718
+ const pct = total > 0 ? ((100 * occluded) / total).toFixed(0) : '0';
89719
+ if (this._culledValue && renderer.culling) {
89720
+ this._culledValue.textContent = `${pct}% (${occluded.toLocaleString()} of ${total.toLocaleString()})`;
89721
+ }
89722
+ })
89723
+ .catch(() => {
89724
+ // a destroyed buffer or lost device; the next refresh tries again
89725
+ })
89726
+ .finally(() => {
89727
+ this._cullStatsPending = false;
89728
+ });
89729
+ }
89730
+ // The clipboard api, else a selection copied with execCommand: the api is refused in a
89731
+ // cross-origin iframe without clipboard-write (superspl.at's local-frontend frame), while
89732
+ // the command still works there inside the click
89432
89733
  async _copy() {
89433
- const snapshot = captureCameraState(this._cameraManager, this._global.state);
89734
+ const text = JSON.stringify(captureCameraState(this._cameraManager, this._global.state));
89735
+ let copied = false;
89434
89736
  try {
89435
- await navigator.clipboard.writeText(JSON.stringify(snapshot));
89737
+ await navigator.clipboard.writeText(text);
89738
+ copied = true;
89739
+ }
89740
+ catch {
89741
+ // destroyed while the clipboard was refusing
89742
+ if (!this._root)
89743
+ return;
89744
+ const area = document.createElement('textarea');
89745
+ area.value = text;
89746
+ area.style.cssText = 'position: fixed; opacity: 0; pointer-events: none';
89747
+ this._root.appendChild(area);
89748
+ area.select();
89749
+ try {
89750
+ copied = document.execCommand('copy');
89751
+ }
89752
+ catch {
89753
+ copied = false;
89754
+ }
89755
+ area.remove();
89756
+ }
89757
+ if (copied) {
89436
89758
  this._flash(this._copyButton);
89437
89759
  }
89438
- catch (err) {
89439
- console.warn('[debug-panel] copy failed', err);
89760
+ else {
89761
+ console.warn('[debug-panel] copy failed');
89762
+ this._flashBad(this._copyButton);
89440
89763
  }
89441
89764
  }
89765
+ // The clipboard api, else the paste field: reading needs clipboard-read, which a
89766
+ // cross-origin iframe only has when its embedder grants it
89442
89767
  async _paste() {
89768
+ let text;
89769
+ try {
89770
+ text = await navigator.clipboard.readText();
89771
+ }
89772
+ catch {
89773
+ this._showPasteField(true);
89774
+ return;
89775
+ }
89776
+ // destroyed while the clipboard was being read
89777
+ if (!this._root)
89778
+ return;
89779
+ this._applyPasted(text);
89780
+ }
89781
+ _applyPasted(text) {
89443
89782
  try {
89444
- const text = await navigator.clipboard.readText();
89445
89783
  const snapshot = JSON.parse(text);
89446
89784
  restoreCameraState(this._cameraManager, this._global.state, snapshot);
89447
89785
  this._flash(this._pasteButton);
89448
89786
  }
89449
89787
  catch (err) {
89450
89788
  console.warn('[debug-panel] paste failed', err);
89789
+ this._flashBad(this._pasteButton);
89451
89790
  }
89452
89791
  }
89792
+ _showPasteField(value) {
89793
+ const field = this._pasteField;
89794
+ if (!field)
89795
+ return;
89796
+ field.value = '';
89797
+ field.style.display = value ? '' : 'none';
89798
+ if (value)
89799
+ field.focus();
89800
+ }
89801
+ _wirePasteField(field) {
89802
+ // keys typed here are text, not camera controls (see _wireEditable)
89803
+ const stopKey = (e) => e.stopPropagation();
89804
+ field.addEventListener('keydown', (e) => {
89805
+ stopKey(e);
89806
+ if (e.key === 'Enter') {
89807
+ e.preventDefault();
89808
+ const text = field.value;
89809
+ this._showPasteField(false);
89810
+ this._applyPasted(text);
89811
+ }
89812
+ else if (e.key === 'Escape') {
89813
+ e.preventDefault();
89814
+ this._showPasteField(false);
89815
+ }
89816
+ });
89817
+ field.addEventListener('keyup', stopKey);
89818
+ field.addEventListener('keypress', stopKey);
89819
+ field.addEventListener('paste', (e) => {
89820
+ e.preventDefault();
89821
+ const text = e.clipboardData?.getData('text/plain') ?? '';
89822
+ this._showPasteField(false);
89823
+ this._applyPasted(text);
89824
+ });
89825
+ field.addEventListener('blur', () => this._showPasteField(false));
89826
+ }
89827
+ _renderMiniStats() {
89828
+ if (!this._miniStats || !this._miniStatsButton)
89829
+ return;
89830
+ const shown = this._miniStats.shown();
89831
+ this._miniStatsButton.textContent = `MiniStats: ${shown ? 'on' : 'off'}`;
89832
+ this._miniStatsButton.classList.toggle('sse-debug-on', shown);
89833
+ }
89453
89834
  _screenshot() {
89454
89835
  const app = this._global.app;
89455
89836
  const canvas = app.graphicsDevice.canvas;
@@ -89687,58 +90068,6 @@ class ModeShortcuts {
89687
90068
  }
89688
90069
  }
89689
90070
 
89690
- /**
89691
- * Displacement-based inputs (mouse, touch, wheel, pinch) return accumulated
89692
- * pixel offsets that already scale with frame time. This factor converts
89693
- * rate-based speed constants (tuned for degrees-per-second) to work with
89694
- * per-frame displacements, making them frame-rate-independent.
89695
- */
89696
- const DISPLACEMENT_SCALE = 1 / 60;
89697
- /** Maximum accumulated touch movement (px) to still count as a tap. */
89698
- const TAP_EPSILON = 15;
89699
- const tmpHalfSize = new Vec3();
89700
- /**
89701
- * Converts screen-space pixel deltas to a world-space pan vector at the
89702
- * given depth.
89703
- *
89704
- * @param camera - The camera component.
89705
- * @param dx - Horizontal pixel delta.
89706
- * @param dy - Vertical pixel delta.
89707
- * @param dz - Depth (world-space) at which to project the delta.
89708
- * @param out - Optional output vector.
89709
- * @returns The pan vector in world space.
89710
- */
89711
- const screenToWorld = (camera, dx, dy, dz, out = new Vec3()) => {
89712
- const { system, fov, aspectRatio, horizontalFov, projection, orthoHeight } = camera;
89713
- const { width, height } = system.app.graphicsDevice.clientRect;
89714
- out.set(-(dx / width) * 2, (dy / height) * 2, 0);
89715
- const halfSize = tmpHalfSize.set(0, 0, 0);
89716
- if (projection === PROJECTION_PERSPECTIVE) {
89717
- const halfSlice = dz * Math.tan(0.5 * fov * math.DEG_TO_RAD);
89718
- if (horizontalFov) {
89719
- halfSize.set(halfSlice, halfSlice / aspectRatio, 0);
89720
- }
89721
- else {
89722
- halfSize.set(halfSlice * aspectRatio, halfSlice, 0);
89723
- }
89724
- }
89725
- else {
89726
- halfSize.set(orthoHeight * aspectRatio, orthoHeight, 0);
89727
- }
89728
- out.mul(halfSize);
89729
- return out;
89730
- };
89731
- /**
89732
- * The orbit camera and the fly camera disagree on the sign of the z-axis
89733
- * for forward motion. Apply this when emitting a forward/back z-component
89734
- * so the same wheel-style delta drives both cameras correctly.
89735
- *
89736
- * @param mode - The current camera mode.
89737
- * @param z - The raw forward/back z-component.
89738
- * @returns The z-component flipped for orbit mode, unchanged otherwise.
89739
- */
89740
- const flipZForOrbit = (mode, z) => (mode === 'orbit' ? -z : z);
89741
-
89742
90071
  const tmpV$4 = new Vec3();
89743
90072
  const canTargetFly = (global) => global.state.cameraMode === 'fly' && !(global.state.inputMode === 'desktop' && global.state.gamingControls);
89744
90073
  // Mirror gaming-controls speed modifiers: shift = run/boost, ctrl = crawl/slow.
@@ -91424,6 +91753,3294 @@ class NavCursor {
91424
91753
  }
91425
91754
  }
91426
91755
 
91756
+ /**
91757
+ * World picking from the stochastic renderer's own frame.
91758
+ *
91759
+ * Every pixel of that renderer's depth texture holds the nearest surviving sample, which is
91760
+ * exactly what the pass picker in `picker.ts` renders on purpose: a stochastic depth whose
91761
+ * distribution over a disc is the scene's opacity along the ray. So no pick pass: the frame's
91762
+ * depth is snapshotted into the same encoding (normalised linear depth in four half-float
91763
+ * channels, 1 where nothing survived) at css resolution, and the shared estimators, the
91764
+ * annotation test and the debug overlay read it unchanged. A css pixel's four channels are four
91765
+ * of the device pixels it covers, so a high-density display supplies four trials as before.
91766
+ */
91767
+ // The frame's hardware depth as normalised linear view depth, in the pass picker's encoding.
91768
+ // Each snapshot pixel covers a block of device pixels; four of them, at the block's quarter
91769
+ // points, fill the four channels.
91770
+ const snapshotWgsl = /* wgsl */ `
91771
+ var splatDepth: texture_depth_2d;
91772
+ // clip z = a * viewDepth + b over w = viewDepth (x, y), near and far (z, w)
91773
+ uniform depthViewParams: vec4f;
91774
+ // device pixels per snapshot pixel (x, y), 1 for an orthographic camera (z)
91775
+ uniform snapshotParams: vec4f;
91776
+
91777
+ @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput {
91778
+ var output: FragmentOutput;
91779
+ let dims = vec2i(textureDimensions(splatDepth));
91780
+ let p = uniform.depthViewParams;
91781
+ let ortho = uniform.snapshotParams.z > 0.5;
91782
+ let origin = floor(pcPosition.xy);
91783
+ var trials = vec4f(1.0);
91784
+ for (var i = 0; i < 4; i++) {
91785
+ let corner = vec2f(0.25 + 0.5 * f32(i & 1), 0.25 + 0.5 * f32(i >> 1));
91786
+ let q = clamp(vec2i(floor((origin + corner) * uniform.snapshotParams.xy)), vec2i(0), dims - vec2i(1));
91787
+ let depth = textureLoad(splatDepth, q, 0);
91788
+ if (depth < 1.0) {
91789
+ let dz = depth - p.x;
91790
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
91791
+ let viewDepth = select(p.y / safeDz, (depth - p.y) / p.x, ortho);
91792
+ trials[i] = clamp((viewDepth - p.z) / (p.w - p.z), 0.0, 0.99951171875);
91793
+ }
91794
+ }
91795
+ output.color = trials;
91796
+ return output;
91797
+ }
91798
+ `;
91799
+ const cameraMatches = (frame, camera) => {
91800
+ const cam = camera.camera;
91801
+ return (frame.viewMatrix.equals(cam.viewMatrix) &&
91802
+ frame.projectionMatrix.equals(cam.projectionMatrix) &&
91803
+ frame.nearClip === cam.nearClip &&
91804
+ frame.farClip === cam.farClip &&
91805
+ frame.projection === cam.projection);
91806
+ };
91807
+ const sameCamera = (a, b) => a.viewMatrix.equals(b.viewMatrix) &&
91808
+ a.projectionMatrix.equals(b.projectionMatrix) &&
91809
+ a.nearClip === b.nearClip &&
91810
+ a.farClip === b.farClip &&
91811
+ a.projection === b.projection;
91812
+ const copyCameraSnapshot = (from, to) => {
91813
+ to.position.copy(from.position);
91814
+ to.viewMatrix.copy(from.viewMatrix);
91815
+ to.projectionMatrix.copy(from.projectionMatrix);
91816
+ to.nearClip = from.nearClip;
91817
+ to.farClip = from.farClip;
91818
+ to.projection = from.projection;
91819
+ };
91820
+ class FrameDepthPicker {
91821
+ app;
91822
+ camera;
91823
+ renderer;
91824
+ shader;
91825
+ texture = null;
91826
+ target = null;
91827
+ // the renderer frame the snapshot was taken from, and the camera it was drawn with
91828
+ snapshotFrame = -1;
91829
+ snapshotCamera = createPickCameraSnapshot();
91830
+ renders = 0;
91831
+ queue = new PickQueue();
91832
+ // picks waiting for a frame to render; settled by release as well
91833
+ waiters = new Set();
91834
+ constructor(app, camera, renderer) {
91835
+ this.app = app;
91836
+ this.camera = camera;
91837
+ this.renderer = renderer;
91838
+ this.shader = ShaderUtils.createShader(app.graphicsDevice, {
91839
+ uniqueName: 'sse-splat-depth-snapshot',
91840
+ attributes: { vertex_position: SEMANTIC_POSITION },
91841
+ vertexChunk: 'fullscreenQuadVS',
91842
+ fragmentWGSL: snapshotWgsl
91843
+ });
91844
+ }
91845
+ // Wait for the next frame to finish, or for release.
91846
+ nextFrame() {
91847
+ return new Promise((resolve) => {
91848
+ const done = () => {
91849
+ handle.off();
91850
+ this.waiters.delete(done);
91851
+ resolve();
91852
+ };
91853
+ const handle = this.app.once('frameend', done);
91854
+ this.waiters.add(done);
91855
+ });
91856
+ }
91857
+ // Snapshot the renderer's frame at css resolution, unless the snapshot already is of it. With
91858
+ // `latest` false a snapshot of an earlier frame from the same camera serves: every stochastic
91859
+ // frame is a new sample, so the debug overlay would otherwise ask for frames without end.
91860
+ snapshot(frame, latest) {
91861
+ const device = this.app.graphicsDevice;
91862
+ const size = pickTargetSize(device);
91863
+ if (!size)
91864
+ return null;
91865
+ const { width, height } = size;
91866
+ if (!this.texture) {
91867
+ this.texture = new Texture(device, {
91868
+ name: 'sse-splat-depth-snapshot',
91869
+ format: PIXELFORMAT_RGBA16F,
91870
+ width,
91871
+ height,
91872
+ mipmaps: false,
91873
+ minFilter: FILTER_NEAREST,
91874
+ magFilter: FILTER_NEAREST,
91875
+ addressU: ADDRESS_CLAMP_TO_EDGE,
91876
+ addressV: ADDRESS_CLAMP_TO_EDGE
91877
+ });
91878
+ this.target = new RenderTarget({
91879
+ name: 'sse-splat-depth-snapshot',
91880
+ colorBuffer: this.texture,
91881
+ depth: false
91882
+ });
91883
+ this.snapshotFrame = -1;
91884
+ }
91885
+ else if (this.texture.width !== width || this.texture.height !== height) {
91886
+ this.target.resize(width, height);
91887
+ this.snapshotFrame = -1;
91888
+ }
91889
+ const current = this.snapshotFrame === frame.id ||
91890
+ (!latest && this.snapshotFrame >= 0 && sameCamera(this.snapshotCamera, frame.camera));
91891
+ if (!current) {
91892
+ const { scope } = device;
91893
+ const { camera } = frame;
91894
+ scope.resolve('splatDepth').setValue(this.renderer.frameDepthTexture);
91895
+ scope
91896
+ .resolve('depthViewParams')
91897
+ .setValue([frame.clipZ[0], frame.clipZ[1], camera.nearClip, camera.farClip]);
91898
+ scope
91899
+ .resolve('snapshotParams')
91900
+ .setValue([
91901
+ frame.width / width,
91902
+ frame.height / height,
91903
+ camera.projection === PROJECTION_ORTHOGRAPHIC ? 1 : 0,
91904
+ 0
91905
+ ]);
91906
+ device.setBlendState(BlendState.NOBLEND);
91907
+ drawQuadWithShader(device, this.target, this.shader);
91908
+ this.snapshotFrame = frame.id;
91909
+ copyCameraSnapshot(frame.camera, this.snapshotCamera);
91910
+ this.renders++;
91911
+ }
91912
+ // the renderer rewrites its snapshot every frame, and frames render while a pick awaits
91913
+ // its readback: the pick unprojects with a copy of the camera its depth was drawn with
91914
+ const pickCamera = createPickCameraSnapshot();
91915
+ copyCameraSnapshot(frame.camera, pickCamera);
91916
+ return { width, height, pickCamera };
91917
+ }
91918
+ // The frame to pick from: the last one rendered if the camera has not moved since, else
91919
+ // one requested now. Its own camera unprojects it, whatever the live camera does meanwhile.
91920
+ async prepare() {
91921
+ if (this.queue.released)
91922
+ return null;
91923
+ let frame = this.renderer.depthFrame;
91924
+ if (!frame || !cameraMatches(frame.camera, this.camera)) {
91925
+ this.app.renderNextFrame = true;
91926
+ await this.nextFrame();
91927
+ frame = this.renderer.depthFrame;
91928
+ if (!frame || this.queue.released)
91929
+ return null;
91930
+ }
91931
+ return this.snapshot(frame, true);
91932
+ }
91933
+ // Read the snapshot around a pixel, `margin` pixels each way, clamped to it.
91934
+ async readAround(screenX, screenY, margin, width, height) {
91935
+ const blockX = Math.max(0, screenX - margin);
91936
+ const blockY = Math.max(0, screenY - margin);
91937
+ const blockWidth = Math.min(width - 1, screenX + margin) - blockX + 1;
91938
+ const blockHeight = Math.min(height - 1, screenY + margin) - blockY + 1;
91939
+ const pixels = (await this.texture.read(blockX, blockY, blockWidth, blockHeight, {
91940
+ renderTarget: this.target,
91941
+ immediate: true
91942
+ }));
91943
+ return (x, y, trial) => {
91944
+ const localX = x - blockX;
91945
+ const localY = y - blockY;
91946
+ if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
91947
+ return null;
91948
+ }
91949
+ return half2Float(pixels[(localY * blockWidth + localX) * 4 + trial]);
91950
+ };
91951
+ }
91952
+ pick(x, y) {
91953
+ return this.queue.run(async () => {
91954
+ const sample = await this.prepare();
91955
+ if (!sample)
91956
+ return null;
91957
+ const { width, height, pickCamera } = sample;
91958
+ const screenX = clampPixel(x, width);
91959
+ const screenY = clampPixel(y, height);
91960
+ const depthAt = await this.readAround(screenX, screenY, SURFACE_RADIUS_PX, width, height);
91961
+ const depth = surfaceDepth(depthAt, screenX, screenY);
91962
+ return depth === null ? null : getWorldPoint(pickCamera, screenX, screenY, width, height, depth);
91963
+ }, null);
91964
+ }
91965
+ pickSurface(x, y) {
91966
+ return this.queue.run(async () => {
91967
+ const sample = await this.prepare();
91968
+ if (!sample)
91969
+ return null;
91970
+ const { width, height, pickCamera } = sample;
91971
+ const screenX = clampPixel(x, width);
91972
+ const screenY = clampPixel(y, height);
91973
+ const depthAt = await this.readAround(screenX, screenY, NORMAL_SAMPLE_MAX_PX + SURFACE_RADIUS_PX, width, height);
91974
+ return estimateSurface(depthAt, pickCamera, width, height, screenX, screenY);
91975
+ }, null);
91976
+ }
91977
+ pickVisibility(points, radius) {
91978
+ if (points.length === 0) {
91979
+ return Promise.resolve([]);
91980
+ }
91981
+ return this.queue.run(async () => {
91982
+ const sample = await this.prepare();
91983
+ if (!sample)
91984
+ return points.map(() => null);
91985
+ const { width, height, pickCamera } = sample;
91986
+ const r = Math.max(1, Math.round(radius * height));
91987
+ return Promise.all(points.map(async ({ x, y, depth }) => {
91988
+ const screenX = clampPixel(x, width);
91989
+ const screenY = clampPixel(y, height);
91990
+ const depthAt = await this.readAround(screenX, screenY, r, width, height);
91991
+ return opacityInFront(depthAt, pickCamera, screenX, screenY, r, depth);
91992
+ }));
91993
+ }, points.map(() => null));
91994
+ }
91995
+ // The last frame's snapshot, for the debug overlay; it asks after each frame, so the frame
91996
+ // is the current camera's.
91997
+ renderView() {
91998
+ if (this.queue.released)
91999
+ return null;
92000
+ const frame = this.renderer.depthFrame;
92001
+ if (!frame || !this.snapshot(frame, false))
92002
+ return null;
92003
+ return { texture: this.texture, renders: this.renders };
92004
+ }
92005
+ release() {
92006
+ this.queue.released = true;
92007
+ for (const done of [...this.waiters])
92008
+ done();
92009
+ this.target?.destroy();
92010
+ this.texture?.destroy();
92011
+ this.target = null;
92012
+ this.texture = null;
92013
+ this.shader.destroy();
92014
+ }
92015
+ }
92016
+
92017
+ // The resident set: which splats the engine's LOD and streaming have made resident this
92018
+ // frame, and where each node's data sits. The engine keeps octree LOD, the budget, file
92019
+ // streaming and the block allocator (one slot range per node); the stochastic renderer
92020
+ // consumes its decisions and owns everything after them.
92021
+ //
92022
+ // Read through the engine's internal (@ignore) gsplat-unified classes until the public
92023
+ // `world:update` api lands (engine change E3 in the plan). Every internal shape used is
92024
+ // narrowed here to the members this file reads, so a change in the engine fails in one place.
92025
+ const tmpVec = new Vec3();
92026
+ const tmpVec2$1 = new Vec3();
92027
+ /**
92028
+ * Hooks the engine's per-frame gsplat update for one camera and layer and exposes the resident
92029
+ * set. `frame:ready` fires inside `GSplatManager.update()` after `world.bake()` and after the
92030
+ * engine's own render prep (both in 2.22.4 and on main), so a listener sees the baked state of
92031
+ * the current frame and can replace that prep.
92032
+ */
92033
+ class EngineResidentSetProvider {
92034
+ app;
92035
+ camera;
92036
+ layer;
92037
+ handles = [];
92038
+ callbacks = new Set();
92039
+ set = null;
92040
+ // the engine renderers this provider has switched off, with their original prep function
92041
+ takenOver = new Map();
92042
+ // while false the engine keeps rendering the splats itself (XR), and the hook stays quiet
92043
+ active = true;
92044
+ constructor(app, camera, layer) {
92045
+ this.app = app;
92046
+ this.camera = camera;
92047
+ this.layer = layer;
92048
+ const system = app.systems.gsplat;
92049
+ // fires when a manager is created for a camera and layer, before its first update:
92050
+ // the earliest point to switch the engine's own renderer off, so it never allocates
92051
+ // its projector, sort and draw resources
92052
+ this.handles.push(system.on('material:created', (material, cam, lyr) => {
92053
+ if (cam === this.camera && lyr === this.layer && this.active) {
92054
+ const manager = this.manager();
92055
+ if (manager)
92056
+ this.takeOver(manager);
92057
+ }
92058
+ }));
92059
+ this.handles.push(system.on('frame:ready', (cam, lyr) => {
92060
+ if (cam !== this.camera || lyr !== this.layer || !this.active)
92061
+ return;
92062
+ const manager = this.manager();
92063
+ if (!manager)
92064
+ return;
92065
+ this.takeOver(manager);
92066
+ const state = manager.world.currentState;
92067
+ if (!state)
92068
+ return;
92069
+ const changed = !this.set || this.set.version !== state.version;
92070
+ if (changed) {
92071
+ this.set = buildResidentSet(state);
92072
+ }
92073
+ for (const cb of this.callbacks) {
92074
+ cb(this.set, changed, manager);
92075
+ }
92076
+ }));
92077
+ }
92078
+ /** The engine manager for this camera and layer, once the engine has created it. */
92079
+ manager() {
92080
+ const director = this.app.renderer.gsplatDirector;
92081
+ // the director keys its cameras by the scene camera, not the component
92082
+ const cameraData = director?.camerasMap.get(this.camera.camera);
92083
+ return cameraData?.layersMap.get(this.layer)?.gsplatManager ?? null;
92084
+ }
92085
+ /** Hand the splats back to the engine's renderer (false), or take them over again (true). */
92086
+ setActive(value) {
92087
+ if (this.active === value)
92088
+ return;
92089
+ this.active = value;
92090
+ if (value) {
92091
+ const manager = this.manager();
92092
+ if (manager)
92093
+ this.takeOver(manager);
92094
+ }
92095
+ else {
92096
+ this.restore();
92097
+ }
92098
+ }
92099
+ onFrame(cb) {
92100
+ this.callbacks.add(cb);
92101
+ return () => this.callbacks.delete(cb);
92102
+ }
92103
+ /**
92104
+ * Switch the engine's own splat rendering off for this manager: its render prep returns
92105
+ * false (so the hybrid renderer never builds its projector, sorter or cache) and its mesh
92106
+ * instance is hidden. The world (LOD, streaming, allocation, the work-buffer copy) keeps
92107
+ * running. Reversed by {@link restore}.
92108
+ */
92109
+ takeOver(manager) {
92110
+ const renderer = manager.renderer;
92111
+ if (!this.takenOver.has(renderer)) {
92112
+ this.takenOver.set(renderer, renderer.prepareRenderView);
92113
+ renderer.prepareRenderView = () => false;
92114
+ }
92115
+ if (renderer.meshInstance)
92116
+ renderer.meshInstance.visible = false;
92117
+ // The manager's first update runs its render prep before frame:ready fires, and
92118
+ // material:created fires before the layer data holds the manager, so the engine's
92119
+ // projector, sorter and compaction get allocated once (32 bytes a splat and more).
92120
+ // Release them; the engine recreates them lazily if it renders again (XR, restore)
92121
+ // or picks through its sorted path.
92122
+ for (const key of ['gpuSorter', 'projector', 'intervalCompaction']) {
92123
+ const resource = renderer[key];
92124
+ if (resource) {
92125
+ resource.destroy();
92126
+ renderer[key] = null;
92127
+ }
92128
+ }
92129
+ }
92130
+ restore() {
92131
+ for (const [renderer, original] of this.takenOver) {
92132
+ renderer.prepareRenderView = original;
92133
+ if (renderer.meshInstance)
92134
+ renderer.meshInstance.visible = true;
92135
+ }
92136
+ this.takenOver.clear();
92137
+ }
92138
+ destroy() {
92139
+ this.restore();
92140
+ for (const handle of this.handles)
92141
+ handle.off();
92142
+ this.handles.length = 0;
92143
+ this.callbacks.clear();
92144
+ this.set = null;
92145
+ }
92146
+ }
92147
+ // Flatten the engine world state into files and nodes with world-space bounds.
92148
+ const buildResidentSet = (state) => {
92149
+ const files = [];
92150
+ const nodes = [];
92151
+ const spheres = [];
92152
+ const pushNode = (node, cx, cy, cz, radius) => {
92153
+ nodes.push(node);
92154
+ spheres.push(cx, cy, cz, radius);
92155
+ };
92156
+ state.splats.forEach((info, fileIndex) => {
92157
+ const modelMatrix = info.node.getWorldTransform().clone();
92158
+ const scale = modelMatrix.getScale(tmpVec2$1);
92159
+ const maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
92160
+ const file = {
92161
+ fileIndex,
92162
+ lodIndex: info.lodIndex,
92163
+ nodes: [],
92164
+ modelMatrix,
92165
+ resource: info.resource
92166
+ };
92167
+ const numIntervals = info.intervals.length / 2;
92168
+ if (numIntervals === 0) {
92169
+ // a single-file resource: one range covering it whole, bounded by its aabb
92170
+ const node = {
92171
+ fileIndex,
92172
+ nodeIndex: nodes.length,
92173
+ lodIndex: info.lodIndex,
92174
+ sourceBase: 0,
92175
+ count: info.activeSplats,
92176
+ slotBase: info.intervalOffsets[0] ?? 0,
92177
+ allocId: info.allocId
92178
+ };
92179
+ modelMatrix.transformPoint(info.aabb.center, tmpVec);
92180
+ const he = info.aabb.halfExtents;
92181
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, he.length() * maxScale);
92182
+ file.nodes.push(node);
92183
+ }
92184
+ else {
92185
+ for (let j = 0; j < numIntervals; j++) {
92186
+ const start = info.intervals[j * 2];
92187
+ const end = info.intervals[j * 2 + 1];
92188
+ const nodeIndex = info.intervalNodeIndices[j];
92189
+ const node = {
92190
+ fileIndex,
92191
+ nodeIndex: nodes.length,
92192
+ lodIndex: info.lodIndex,
92193
+ sourceBase: start,
92194
+ count: end - start,
92195
+ slotBase: info.intervalOffsets[j] ?? 0,
92196
+ allocId: info.intervalAllocIds[j]
92197
+ };
92198
+ const sphere = info.octreeNodes?.[nodeIndex]?.boundingSphere;
92199
+ if (sphere) {
92200
+ tmpVec.set(sphere.x, sphere.y, sphere.z);
92201
+ modelMatrix.transformPoint(tmpVec, tmpVec);
92202
+ pushNode(node, tmpVec.x, tmpVec.y, tmpVec.z, sphere.w * maxScale);
92203
+ }
92204
+ else {
92205
+ // no bounds: never culled
92206
+ pushNode(node, 0, 0, 0, Infinity);
92207
+ }
92208
+ file.nodes.push(node);
92209
+ }
92210
+ }
92211
+ files.push(file);
92212
+ });
92213
+ return {
92214
+ version: state.version,
92215
+ activeSplats: state.totalActiveSplats,
92216
+ slotCapacity: state.textureSize * state.textureSize,
92217
+ fullRebuild: state.fullRebuild,
92218
+ changedAllocIds: state.needsUploadIds,
92219
+ files,
92220
+ nodes,
92221
+ nodeSpheres: new Float32Array(spheres)
92222
+ };
92223
+ };
92224
+
92225
+ // Single-thread pass turning the projector's survivor count into the indexed indirect draw
92226
+ // arguments for the raster pass and the indirect dispatch size of the order scatter. Nothing
92227
+ // comes back to the cpu, so a frame never stalls on the count. Entry layouts match the engine's
92228
+ // indirect draw buffer (5 u32 per slot) and indirect dispatch buffer (3 u32 per slot).
92229
+ const argsWGSL = /* wgsl */ `
92230
+ struct DrawIndexedIndirectArgs {
92231
+ indexCount: u32,
92232
+ instanceCount: u32,
92233
+ firstIndex: u32,
92234
+ baseVertex: i32,
92235
+ firstInstance: u32
92236
+ }
92237
+
92238
+ struct ArgsUniforms {
92239
+ drawSlot: u32,
92240
+ indexCount: u32,
92241
+ quadsPerInstance: u32,
92242
+ dispatchSlot: u32,
92243
+ scatterWorkgroupSize: u32
92244
+ }
92245
+
92246
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
92247
+ @group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>;
92248
+ @group(0) @binding(2) var<storage, read_write> indirectDispatchArgs: array<u32>;
92249
+ @group(0) @binding(3) var<uniform> uniforms: ArgsUniforms;
92250
+
92251
+ @compute @workgroup_size(1)
92252
+ fn main() {
92253
+ let count = counter[0];
92254
+ indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs(
92255
+ uniforms.indexCount,
92256
+ (count + uniforms.quadsPerInstance - 1u) / uniforms.quadsPerInstance,
92257
+ 0u,
92258
+ 0,
92259
+ 0u
92260
+ );
92261
+ // the scatter: one workgroup per scatterWorkgroupSize survivors, 2D past the 65535 limit
92262
+ let groups = (count + uniforms.scatterWorkgroupSize - 1u) / uniforms.scatterWorkgroupSize;
92263
+ let x = max(min(groups, 65535u), 1u);
92264
+ let base = uniforms.dispatchSlot * 3u;
92265
+ indirectDispatchArgs[base] = x;
92266
+ indirectDispatchArgs[base + 1u] = (groups + x - 1u) / x;
92267
+ indirectDispatchArgs[base + 2u] = 1u;
92268
+ }
92269
+ `;
92270
+
92271
+ // Temporal accumulation for the stochastic frame. Each frame the raster leaves one sample per
92272
+ // pixel (a colour where a splat's fragment survived its coverage test, nothing otherwise) and
92273
+ // the nearest surviving depth; this pass folds it into a per-pixel history of premultiplied
92274
+ // colour and coverage, so a still camera converges to the expected image over a few hundred
92275
+ // frames and a moving one keeps most of that history by reprojecting it.
92276
+ //
92277
+ // Reprojection uses the sample's own depth: the pixel's world point is carried into the
92278
+ // previous view and the history is fetched there, clamped to the colours this frame's
92279
+ // neighbourhood holds so a stale colour cannot survive a disocclusion. A pixel with no sample
92280
+ // this frame reprojects through the mean depth its own history remembers, so coverage fades out
92281
+ // where a surface has moved away rather than smearing into the background.
92282
+ //
92283
+ // The history is 12 bytes a pixel (24 with the ping-pong). The colour is the running mean as
92284
+ // 16-bit fixed point: a half float cannot hold it, since its steps in [0.5, 1) are 1 / 2048 and
92285
+ // the 1 / N step of a 256-sample mean rounds away once a sample lies within 1 / 16 of the mean
92286
+ // (an error floor of about 5 rms in 8-bit units), while fixed point steps by 1 / 65535
92287
+ // everywhere, so the same step only rounds away within half an 8-bit level of the mean. The
92288
+ // depth record is the mean view depth of the pixel's samples and their count in one 32-bit word.
92289
+ // the most samples the history's count field holds
92290
+ const TAA_MAX_COUNT = 511;
92291
+ const taaVertexWGSL = /* wgsl */ `
92292
+ attribute vertex_position: vec2f;
92293
+
92294
+ @vertex
92295
+ fn vertexMain(input: VertexInput) -> VertexOutput {
92296
+ var output: VertexOutput;
92297
+ output.position = vec4f(vertex_position, 0.0, 1.0);
92298
+ return output;
92299
+ }
92300
+ `;
92301
+ // The history's encoding, shared with the compose that reads it
92302
+ const taaHistoryWGSL = /* wgsl */ `
92303
+ const TAA_COLOR_SCALE = 65535.0;
92304
+
92305
+ fn decodeColor(v: vec4u) -> vec4f {
92306
+ return vec4f(v) / TAA_COLOR_SCALE;
92307
+ }
92308
+
92309
+ // premultiplied colour and coverage: coverage in [0, 1] and colour within it (the Catmull-Rom
92310
+ // fetch over- and undershoots both), rounded to the nearest step
92311
+ fn encodeColor(c: vec4f) -> vec4u {
92312
+ let a = clamp(c.a, 0.0, 1.0);
92313
+ return vec4u(round(vec4f(clamp(c.rgb, vec3f(0.0), vec3f(a)), a) * TAA_COLOR_SCALE));
92314
+ }
92315
+
92316
+ struct HistoryInfo {
92317
+ depth: f32,
92318
+ count: f32
92319
+ }
92320
+
92321
+ // The mean view depth keeps the float's exponent and top 15 mantissa bits, rounded: a relative
92322
+ // step of 2^-15, which stalls a 256-sample mean only within 0.4 % of the depth (the depth steers
92323
+ // the reprojection, where that is far below a pixel). The count takes the low 9 bits
92324
+ fn decodeInfo(v: u32) -> HistoryInfo {
92325
+ var info: HistoryInfo;
92326
+ info.depth = bitcast<f32>((v >> 9u) << 8u);
92327
+ info.count = f32(v & ${TAA_MAX_COUNT}u);
92328
+ return info;
92329
+ }
92330
+
92331
+ fn encodeInfo(depth: f32, count: f32) -> u32 {
92332
+ let bits = bitcast<u32>(max(depth, 0.0));
92333
+ return (((bits + 0x80u) >> 8u) << 9u) | min(u32(count), ${TAA_MAX_COUNT}u);
92334
+ }
92335
+ `;
92336
+ const taaFragmentWGSL = /* wgsl */ `
92337
+ var curColor: texture_2d<f32>;
92338
+ var curColorSampler: sampler;
92339
+ var curDepth: texture_depth_2d;
92340
+ // premultiplied colour and coverage, unorm16 (decodeColor)
92341
+ var histColor: texture_2d<u32>;
92342
+ // the mean view depth of the pixel's samples and their count, in the previous frame's view
92343
+ // depths (decodeInfo)
92344
+ var histInfo: texture_2d<u32>;
92345
+
92346
+ // the camera's world transform (the inverse view), and its projection's x and y terms: x, y the
92347
+ // scales, z, w the offsets (the column that multiplies view z for a perspective camera, the
92348
+ // translation for an orthographic one)
92349
+ uniform cameraWorld: mat4x4f;
92350
+ uniform unproject: vec4f;
92351
+ uniform prevViewProj: mat4x4f;
92352
+ uniform prevView: mat4x4f;
92353
+ // clip z = a * viewDepth + b over w = viewDepth (x, y); z: 1 for an orthographic camera
92354
+ uniform clipZParams: vec4f;
92355
+ // x: sample cap, y: 1 when the history holds the previous frame, z: 1 when the camera moved
92356
+ // since that frame, w: the frames the camera has rested, this one included (0 on a frame whose
92357
+ // resident set changed)
92358
+ uniform taaParams: vec4f;
92359
+ // width, height, 1 / width, 1 / height
92360
+ uniform taaViewport: vec4f;
92361
+ // x: -1 when the target's rows run bottom-up (an offscreen target), else 1; y: the colour
92362
+ // clamp width in neighbourhood standard deviations (0: no clamp); z: 1 when the raster's
92363
+ // thresholds are quad-stratified
92364
+ uniform taaControl: vec4f;
92365
+ // x: 1 for a Catmull-Rom history fetch while moving (0: bilinear); y: 1 to reproject through
92366
+ // the pixel's accumulated mean depth rather than this frame's sample depth; z: image motion in
92367
+ // pixels a frame that halves the moving sample cap (0: fixed cap)
92368
+ uniform taaFilter: vec4f;
92369
+ // 1: write the accumulation state instead of colour (r: count / cap, g: history accepted,
92370
+ // b: the camera moved since the previous frame)
92371
+ uniform taaDebug: f32;
92372
+
92373
+ ${taaHistoryWGSL}
92374
+
92375
+ fn viewDepthOf(z: f32) -> f32 {
92376
+ let p = uniform.clipZParams;
92377
+ let dz = z - p.x;
92378
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
92379
+ return select(p.y / safeDz, (z - p.y) / p.x, p.z != 0.0);
92380
+ }
92381
+
92382
+ struct Reprojected {
92383
+ valid: bool,
92384
+ uv: vec2f,
92385
+ prevDepth: f32
92386
+ }
92387
+
92388
+ // The previous frame's view depth and texture coordinate of this pixel's point at a view
92389
+ // depth. The point is built in view space from the depth and the projection's x and y terms,
92390
+ // then moved by the camera's rigid transform: through the inverse view-projection instead, a
92391
+ // near plane at 1e-4 of the depth (the viewer's floor once the camera is inside the scene
92392
+ // bound) leaves a 32-bit float about three digits of the point, a pixel of error that changes
92393
+ // with every frame's sample depths and shakes the history.
92394
+ fn reproject(pix: vec2i, viewDepth: f32) -> Reprojected {
92395
+ var r: Reprojected;
92396
+ let flip = uniform.taaControl.x;
92397
+ let uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
92398
+ let ndc = vec2f(uv.x * 2.0 - 1.0, flip * (1.0 - 2.0 * uv.y));
92399
+ let u = uniform.unproject;
92400
+ let viewXY = select((ndc + u.zw) * viewDepth, ndc - u.zw, uniform.clipZParams.z != 0.0) / u.xy;
92401
+ let world = (uniform.cameraWorld * vec4f(viewXY, -viewDepth, 1.0)).xyz;
92402
+ let prevClip = uniform.prevViewProj * vec4f(world, 1.0);
92403
+ r.prevDepth = -(uniform.prevView * vec4f(world, 1.0)).z;
92404
+ r.valid = prevClip.w > 0.0;
92405
+ let prevNdc = prevClip.xy / max(prevClip.w, 1e-9);
92406
+ r.uv = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * flip * 0.5);
92407
+ r.valid = r.valid && all(r.uv >= vec2f(0.0)) && all(r.uv <= vec2f(1.0));
92408
+ return r;
92409
+ }
92410
+
92411
+ // the premultiplied sample at a texel: its colour where a fragment landed, nothing otherwise
92412
+ fn sampleAt(pix: vec2i, dims: vec2i) -> vec4f {
92413
+ let p = clamp(pix, vec2i(0), dims - vec2i(1));
92414
+ let c = textureLoad(curColor, p, 0);
92415
+ let z = textureLoad(curDepth, p, 0);
92416
+ return select(vec4f(0.0), vec4f(c.rgb, 1.0), c.a > 0.0 && z < 1.0);
92417
+ }
92418
+
92419
+ // The mean of the 2x2 quad's samples, bilinear between quad centres (the compose's resolve of
92420
+ // the raster's quad-stratified thresholds): four samples a pixel, at a little sharpness, for
92421
+ // the frames where the history is too short to carry the noise on its own
92422
+ fn quadSample(pix: vec2i, dims: vec2i) -> vec4f {
92423
+ let size = vec2f(dims);
92424
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
92425
+ let q0 = floor(u);
92426
+ let f = u - q0;
92427
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
92428
+ let step = vec2f(2.0) / size;
92429
+ let a = textureSampleLevel(curColor, curColorSampler, uv, 0.0);
92430
+ let b = textureSampleLevel(curColor, curColorSampler, uv + vec2f(step.x, 0.0), 0.0);
92431
+ let c = textureSampleLevel(curColor, curColorSampler, uv + vec2f(0.0, step.y), 0.0);
92432
+ let d = textureSampleLevel(curColor, curColorSampler, uv + step, 0.0);
92433
+ let m = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
92434
+ // the raster leaves empty texels transparent black, so the mean is premultiplied coverage
92435
+ return vec4f(m.rgb, m.a);
92436
+ }
92437
+
92438
+ fn historyTexel(p: vec2i, dims: vec2i) -> vec4f {
92439
+ return decodeColor(textureLoad(histColor, clamp(p, vec2i(0), dims - vec2i(1)), 0));
92440
+ }
92441
+
92442
+ // Catmull-Rom fetch of the history: sharper than bilinear, whose blur compounds over the
92443
+ // frames a moving history lives. Its lobes over- and undershoot; the encoding clamps both
92444
+ fn historyCubicAt(uv: vec2f, dims: vec2i) -> vec4f {
92445
+ let p = uv * vec2f(dims) - vec2f(0.5);
92446
+ let i0 = vec2i(floor(p));
92447
+ let f = p - floor(p);
92448
+ let f2 = f * f;
92449
+ let f3 = f2 * f;
92450
+ // Catmull-Rom weights for taps at -1, 0, 1, 2
92451
+ let w0 = -0.5 * f3 + f2 - 0.5 * f;
92452
+ let w1 = 1.5 * f3 - 2.5 * f2 + vec2f(1.0);
92453
+ let w2 = -1.5 * f3 + 2.0 * f2 + 0.5 * f;
92454
+ let w3 = 0.5 * f3 - 0.5 * f2;
92455
+ let wx = array<f32, 4>(w0.x, w1.x, w2.x, w3.x);
92456
+ let wy = array<f32, 4>(w0.y, w1.y, w2.y, w3.y);
92457
+ var sum = vec4f(0.0);
92458
+ for (var y = 0; y < 4; y++) {
92459
+ for (var x = 0; x < 4; x++) {
92460
+ sum += historyTexel(i0 + vec2i(x - 1, y - 1), dims) * (wx[x] * wy[y]);
92461
+ }
92462
+ }
92463
+ return sum;
92464
+ }
92465
+
92466
+ // bilinear fetch of the history
92467
+ fn historyAt(uv: vec2f, dims: vec2i) -> vec4f {
92468
+ let p = uv * vec2f(dims) - vec2f(0.5);
92469
+ let i0 = vec2i(floor(p));
92470
+ let f = p - floor(p);
92471
+ let a = historyTexel(i0, dims);
92472
+ let b = historyTexel(i0 + vec2i(1, 0), dims);
92473
+ let c = historyTexel(i0 + vec2i(0, 1), dims);
92474
+ let d = historyTexel(i0 + vec2i(1, 1), dims);
92475
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
92476
+ }
92477
+
92478
+ @fragment
92479
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
92480
+ var output: FragmentOutput;
92481
+ let pix = vec2i(pcPosition.xy);
92482
+ let dims = vec2i(textureDimensions(curColor));
92483
+ let cur = textureLoad(curColor, pix, 0);
92484
+ let z = textureLoad(curDepth, pix, 0);
92485
+ let hit = cur.a > 0.0 && z < 1.0;
92486
+ let d = viewDepthOf(z);
92487
+
92488
+ let own = decodeInfo(textureLoad(histInfo, pix, 0).x);
92489
+ let maxCount = uniform.taaParams.x;
92490
+ let historyValid = uniform.taaParams.y > 0.5;
92491
+ let moving = uniform.taaParams.z > 0.5;
92492
+ // still: this pixel's own sample, so the history converges to full resolution; moving:
92493
+ // the quad's four
92494
+ var sample = select(vec4f(0.0), vec4f(cur.rgb, 1.0), hit);
92495
+ if (moving && uniform.taaControl.z > 0.5) {
92496
+ sample = quadSample(pix, dims);
92497
+ }
92498
+
92499
+ // Where to look in the history: through this frame's sample, or, with no sample, through
92500
+ // the depth this pixel's own history remembers, so an emptied pixel fades rather than
92501
+ // holding a stale colour
92502
+ var r: Reprojected;
92503
+ r.valid = false;
92504
+ var carryDepth = 0.0;
92505
+ if (!moving) {
92506
+ // a resting camera maps every pixel onto itself: the exact texel, not the round trip
92507
+ // through the matrices, whose rounding would blur the history a little every frame
92508
+ r.valid = true;
92509
+ r.uv = (vec2f(pix) + vec2f(0.5)) * uniform.taaViewport.zw;
92510
+ r.prevDepth = select(own.depth, d, hit);
92511
+ carryDepth = r.prevDepth;
92512
+ } else if (uniform.taaFilter.y > 0.5 && own.count > 0.5) {
92513
+ // through the depth the pixel's history has settled on: one stochastic sample's depth
92514
+ // is one layer of the mixture the history holds, and reprojecting the mixture through
92515
+ // a different layer every frame smears it by their parallax
92516
+ r = reproject(pix, own.depth);
92517
+ carryDepth = own.depth;
92518
+ } else if (hit) {
92519
+ r = reproject(pix, d);
92520
+ carryDepth = d;
92521
+ } else if (own.count > 0.5) {
92522
+ r = reproject(pix, own.depth);
92523
+ carryDepth = own.depth;
92524
+ }
92525
+ r.valid = r.valid && historyValid;
92526
+
92527
+ var hist = vec4f(0.0);
92528
+ var info: HistoryInfo;
92529
+ var accepted = false;
92530
+ if (r.valid) {
92531
+ // at rest the exact texel; moving, a filtered fetch of the reprojected position
92532
+ if (!moving) {
92533
+ hist = decodeColor(textureLoad(histColor, pix, 0));
92534
+ info = own;
92535
+ } else {
92536
+ if (uniform.taaFilter.x > 0.5) {
92537
+ hist = historyCubicAt(r.uv, dims);
92538
+ } else {
92539
+ hist = historyAt(r.uv, dims);
92540
+ }
92541
+ info = decodeInfo(textureLoad(histInfo, clamp(vec2i(r.uv * vec2f(dims)), vec2i(0), dims - vec2i(1)), 0).x);
92542
+ }
92543
+ // a resting camera cannot disocclude anything, so every sample is accepted and the
92544
+ // pixel converges; moving, the colour clamp below keeps a disoccluded history out
92545
+ accepted = info.count > 0.5;
92546
+ }
92547
+
92548
+ var color: vec4f;
92549
+ var mean: f32;
92550
+ var count: f32;
92551
+ if (!accepted) {
92552
+ color = sample;
92553
+ mean = d;
92554
+ count = select(0.0, 1.0, hit);
92555
+ // at rest a pixel with no hit yet has still been sampled on every rest frame, so its
92556
+ // first hit is one of that many samples: at full weight a rare hit would flash to full
92557
+ // coverage, and freeze there once the viewer stops rendering. Its depth is the hit's
92558
+ if (hit && !moving && historyValid) {
92559
+ count = clamp(uniform.taaParams.w, 1.0, maxCount);
92560
+ color = sample / count;
92561
+ }
92562
+ } else {
92563
+ // moving, the history is clamped to the colours this frame's neighbourhood holds, so a
92564
+ // stale colour cannot survive where nothing like it is drawn any more
92565
+ if (moving && uniform.taaControl.y > 0.0) {
92566
+ var m1 = vec4f(0.0);
92567
+ var m2 = vec4f(0.0);
92568
+ for (var dy = -1; dy <= 1; dy++) {
92569
+ for (var dx = -1; dx <= 1; dx++) {
92570
+ let n = sampleAt(pix + vec2i(dx, dy), dims);
92571
+ m1 += n;
92572
+ m2 += n * n;
92573
+ }
92574
+ }
92575
+ let mu = m1 / 9.0;
92576
+ let sd = sqrt(max(m2 / 9.0 - mu * mu, vec4f(0.0)));
92577
+ let halfWidth = sd * uniform.taaControl.y;
92578
+ hist = clamp(hist, mu - halfWidth, mu + halfWidth);
92579
+ }
92580
+ // the faster the image moves, the shorter the history: a stochastic pixel's layers
92581
+ // reproject through one layer's depth, so their parallax smears the history by an
92582
+ // amount that grows with the motion, and a raw frame is the better estimate past it
92583
+ var cap = maxCount;
92584
+ if (moving && uniform.taaFilter.z > 0.0) {
92585
+ let speed = length(r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5));
92586
+ cap = max(2.0, maxCount / (1.0 + speed / uniform.taaFilter.z));
92587
+ }
92588
+ count = min(info.count + 1.0, cap);
92589
+ let w = 1.0 / count;
92590
+ color = mix(hist, sample, w);
92591
+ // an empty sample takes at least a step off the coverage: rounded to the nearest, a
92592
+ // decay of less than half a step holds (below cap / 2 steps, about 0.002 at the default
92593
+ // cap), so a faint pixel would keep its coverage, and the depth the compose writes for
92594
+ // it, forever. The colour follows, since the encoding keeps it within the coverage
92595
+ if (sample.a == 0.0) {
92596
+ color.a = min(color.a, max(hist.a - 1.0 / TAA_COLOR_SCALE, 0.0));
92597
+ }
92598
+ // carry the mean depth into this view: the point moved along the ray by the change in
92599
+ // its depth, then the sample joins it
92600
+ let shifted = info.depth + (carryDepth - r.prevDepth);
92601
+ mean = select(shifted, shifted + w * (d - shifted), hit);
92602
+ }
92603
+
92604
+ if (uniform.taaDebug > 1.5) {
92605
+ // the reprojection offset in pixels, 8 px full scale, centred on 0.5
92606
+ let mv = select(vec2f(0.0), r.uv * vec2f(dims) - vec2f(pix) - vec2f(0.5), r.valid);
92607
+ color = vec4f(mv / 16.0 + vec2f(0.5), select(0.0, 1.0, r.valid), 1.0);
92608
+ } else if (uniform.taaDebug > 0.5) {
92609
+ color = vec4f(count / maxCount, select(0.0, 1.0, accepted), select(0.0, 1.0, moving), 1.0);
92610
+ }
92611
+ output.color = encodeColor(color);
92612
+ output.color1 = encodeInfo(mean, count);
92613
+ return output;
92614
+ }
92615
+ `;
92616
+
92617
+ // The compose: a fullscreen quad in the World layer's transparent sublayer that blends the
92618
+ // stochastic target over the camera's target (after the skybox and opaque meshes) and writes
92619
+ // its depth, so everything drawn later depth-tests against the splats. The colour transform
92620
+ // the engine's own splat shader applies (gsplatOutputVS: tonemap and gamma, or the viewer's
92621
+ // pass-through patch under CameraFrame) runs here, once per pixel instead of once per splat.
92622
+ const composeVertexWGSL = /* wgsl */ `
92623
+ attribute vertex_position: vec2f;
92624
+
92625
+ @vertex
92626
+ fn vertexMain(input: VertexInput) -> VertexOutput {
92627
+ var output: VertexOutput;
92628
+ output.position = vec4f(vertex_position, 0.0, 1.0);
92629
+ return output;
92630
+ }
92631
+ `;
92632
+ const composeFragmentWGSL = /* wgsl */ `
92633
+ #include "gsplatOutputVS"
92634
+
92635
+ var splatColor: texture_2d<f32>;
92636
+ var splatColorSampler: sampler;
92637
+ var splatDepth: texture_depth_2d;
92638
+ // the temporally accumulated frame (premultiplied colour, coverage), when taa ran this frame
92639
+ var taaColor: texture_2d<u32>;
92640
+ // its depth record: the mean view depth of the pixel's samples and their count
92641
+ var taaInfo: texture_2d<u32>;
92642
+ // x: 1 when the splat target's rows run the other way to the camera target's; y: 1 for an
92643
+ // orthographic camera; z: 1 to read the taa history instead of the raw frame
92644
+ uniform composeParams: vec4f;
92645
+ // the splat target's depth: clip z = a * viewDepth + b over w = viewDepth (x, y), and the
92646
+ // camera's near and far (z, w) for the depth view
92647
+ uniform depthViewParams: vec4f;
92648
+ // the camera's own depth, the one written for the rest of the scene: clip z = a * viewDepth + b
92649
+ // (x, y). The splat target's far plane is at infinity where the camera's is fitted to the scene
92650
+ uniform cameraClipZ: vec4f;
92651
+
92652
+ ${taaHistoryWGSL}
92653
+
92654
+ const FAR_DEPTH = 0.999999;
92655
+
92656
+ // the splat target's depth texel of a view depth, just inside its far plane at most: the
92657
+ // raster clamps there too, since a depth of 1 reads as no sample
92658
+ fn clipZOf(viewDepth: f32) -> f32 {
92659
+ let p = uniform.depthViewParams;
92660
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
92661
+ return min(clamp(p.x * viewDepth + p.y, 0.0, w) / w, FAR_DEPTH);
92662
+ }
92663
+
92664
+ // the view depth of a splat target depth texel
92665
+ fn viewDepthOf(z: f32) -> f32 {
92666
+ let p = uniform.depthViewParams;
92667
+ let dz = z - p.x;
92668
+ let safeDz = select(dz, sign(dz) * 1e-9 + 1e-12, abs(dz) < 1e-9);
92669
+ return select(p.y / safeDz, (z - p.y) / p.x, uniform.composeParams.y > 0.5);
92670
+ }
92671
+
92672
+ // A splat target depth in the camera's depth, clamped just inside the camera's far plane as the
92673
+ // engine clamps its splats: splats beyond it stay behind everything the scene draws
92674
+ fn cameraDepthOf(z: f32) -> f32 {
92675
+ let viewDepth = viewDepthOf(z);
92676
+ let c = uniform.cameraClipZ;
92677
+ let w = select(viewDepth, 1.0, uniform.composeParams.y > 0.5);
92678
+ return min(clamp(c.x * viewDepth + c.y, 0.0, w) / w, FAR_DEPTH);
92679
+ }
92680
+
92681
+ @fragment
92682
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
92683
+ var output: FragmentOutput;
92684
+ let dims = vec2i(textureDimensions(splatColor));
92685
+ var pix = vec2i(pcPosition.xy);
92686
+ if (uniform.composeParams.x > 0.5) {
92687
+ pix.y = dims.y - 1 - pix.y;
92688
+ }
92689
+ pix = clamp(pix, vec2i(0), dims - vec2i(1));
92690
+
92691
+ var depth = textureLoad(splatDepth, pix, 0);
92692
+ var color: vec4f;
92693
+ if (uniform.composeParams.z > 0.5) {
92694
+ // the accumulated history: coverage in alpha, colour premultiplied by it
92695
+ color = decodeColor(textureLoad(taaColor, pix, 0));
92696
+ if (depth >= 1.0 && color.a > 0.001) {
92697
+ // covered by the history but no sample this frame, which a faint pixel sees on
92698
+ // most frames: the mean depth of the pixel's own samples, or, for a history this
92699
+ // frame started (moving, from the quad's samples), the nearest sampled neighbour's,
92700
+ // so the pixel still occludes what is behind the splats
92701
+ let info = decodeInfo(textureLoad(taaInfo, pix, 0).x);
92702
+ if (info.count > 0.5) {
92703
+ depth = clipZOf(info.depth);
92704
+ } else {
92705
+ for (var dy = -1; dy <= 1; dy++) {
92706
+ for (var dx = -1; dx <= 1; dx++) {
92707
+ depth = min(depth, textureLoad(splatDepth, clamp(pix + vec2i(dx, dy), vec2i(0), dims - vec2i(1)), 0));
92708
+ }
92709
+ }
92710
+ }
92711
+ }
92712
+ } else {
92713
+ #ifdef SSE_SPP_QUAD
92714
+ // the mean of each 2x2 quad, bilinearly interpolated between quad centres: the four
92715
+ // strata of the raster's thresholds average out to the splat's coverage. Empty texels
92716
+ // are transparent black, so the result is premultiplied coverage
92717
+ let size = vec2f(dims);
92718
+ let u = (vec2f(pix) - vec2f(0.5)) * 0.5;
92719
+ let q0 = floor(u);
92720
+ let f = u - q0;
92721
+ let uv = (q0 * 2.0 + vec2f(1.0)) / size;
92722
+ let step = vec2f(2.0) / size;
92723
+ let a = textureSampleLevel(splatColor, splatColorSampler, uv, 0.0);
92724
+ let b = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(step.x, 0.0), 0.0);
92725
+ let c = textureSampleLevel(splatColor, splatColorSampler, uv + vec2f(0.0, step.y), 0.0);
92726
+ let d = textureSampleLevel(splatColor, splatColorSampler, uv + step, 0.0);
92727
+ color = mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
92728
+ if (depth >= 1.0) {
92729
+ // no sample at this pixel but coverage from its quad: the quad's nearest depth
92730
+ let quad = (pix >> vec2u(1u)) << vec2u(1u);
92731
+ depth = min(
92732
+ min(textureLoad(splatDepth, quad, 0), textureLoad(splatDepth, min(quad + vec2i(1, 0), dims - 1), 0)),
92733
+ min(textureLoad(splatDepth, min(quad + vec2i(0, 1), dims - 1), 0), textureLoad(splatDepth, min(quad + vec2i(1, 1), dims - 1), 0))
92734
+ );
92735
+ }
92736
+ #else
92737
+ color = textureLoad(splatColor, pix, 0);
92738
+ #endif
92739
+ }
92740
+ if (color.a <= 0.001) {
92741
+ discard;
92742
+ }
92743
+ // coverage with no depth anywhere near: shown, behind everything the scene drew
92744
+ depth = min(depth, FAR_DEPTH);
92745
+
92746
+ #ifdef SSE_SHOW_DEPTH
92747
+ // the nearest sample's view depth, log-spaced between near and far, as grey
92748
+ let p = uniform.depthViewParams;
92749
+ let viewDepth = viewDepthOf(depth);
92750
+ let t = clamp(log(max(viewDepth, p.z) / p.z) / log(p.w / p.z), 0.0, 1.0);
92751
+ // 24-bit fixed point across rgb (high byte in red), so a capture can read it precisely
92752
+ let fixed = floor(t * 16777215.0);
92753
+ let hi = floor(fixed / 65536.0);
92754
+ let mid = floor((fixed - hi * 65536.0) / 256.0);
92755
+ let lo = fixed - hi * 65536.0 - mid * 256.0;
92756
+ output.color = vec4f(vec3f(hi, mid, lo) / 255.0, 1.0);
92757
+ output.fragDepth = cameraDepthOf(depth);
92758
+ return output;
92759
+ #endif
92760
+
92761
+ // un-premultiply for the output transform, then premultiply for the blend
92762
+ let gamma = color.rgb / color.a;
92763
+ let rgb = prepareOutputFromGamma(gamma, 0.0);
92764
+ output.color = vec4f(rgb * color.a, color.a);
92765
+ output.fragDepth = cameraDepthOf(depth);
92766
+ return output;
92767
+ }
92768
+ `;
92769
+
92770
+ // The projector: one 256-thread workgroup per chunk of the resident set. Each thread reads one
92771
+ // splat through the source's read code, projects it, applies the culls, and survivors append
92772
+ // themselves to a dense cache with one global atomic per workgroup. The chunk table and node
92773
+ // visibility come from the cpu (resident-set rebuild on version change, frustum cull per frame).
92774
+ /** Words per cache entry. See the layout in the plan: ndc, depth, axis1, len2|alpha|flags, rgb, popless, id. */
92775
+ const CACHE_WORDS = 7;
92776
+ const PROJECTOR_WORKGROUP_SIZE = 256;
92777
+ /** Buckets of the counting order (order:bucket); the workgroup size, so each thread owns one. */
92778
+ const ORDER_BUCKETS = PROJECTOR_WORKGROUP_SIZE;
92779
+ /** Splats per chunk-table entry; a chunk is one workgroup. */
92780
+ const CHUNK_SIZE = PROJECTOR_WORKGROUP_SIZE;
92781
+ const projectorWGSL = (readChunk, occlusion, order) => /* wgsl */ `
92782
+ struct ProjectorUniforms {
92783
+ view: mat4x4f,
92784
+ viewProj: mat4x4f,
92785
+ // the previous frame, for the occlusion cull: its view and view-projection, its clip-z
92786
+ // mapping (a, b, isOrtho, 0), viewport and focal length
92787
+ prevViewProj: mat4x4f,
92788
+ prevView: mat4x4f,
92789
+ prevClipZ: vec4f,
92790
+ viewport: vec2f,
92791
+ focal: vec2f,
92792
+ prevViewport: vec2f,
92793
+ prevFocal: vec2f,
92794
+ numChunks: u32,
92795
+ splatTextureSize: u32,
92796
+ isOrtho: u32,
92797
+ minPixelSize: f32,
92798
+ alphaClip: f32,
92799
+ minContribution: f32,
92800
+ // the occlusion grid: level 1 (8 px) and level 2 (32 px) block counts
92801
+ occBlocksX1: u32,
92802
+ occBlocksY1: u32,
92803
+ occBlocksX2: u32,
92804
+ occBlocksY2: u32,
92805
+ // 0 off, 1 level 1 only, 2 both levels
92806
+ occlusionMode: u32,
92807
+ // -1 when the previous depth texture's rows run bottom-up (an offscreen target), else 1
92808
+ prevFlip: f32,
92809
+ // the order key: bucket = (log(depth) - keyLogNear) * keyInvLogRange, over [0, 1)
92810
+ keyLogNear: f32,
92811
+ keyInvLogRange: f32,
92812
+ // first chunk-table entry of this dispatch (per-file sources dispatch one run each)
92813
+ chunkBase: u32,
92814
+ // the file's model transform, for sources that read splats in the file's own space
92815
+ model: mat4x4f,
92816
+ modelRotation: vec4f,
92817
+ modelScale: vec4f,
92818
+ cameraPosition: vec4f,
92819
+ // colour ceiling per channel: 8 keeps the cache's range, 1 clamps like the engine's 8-bit cache
92820
+ colorMax: f32,
92821
+ // 1: covariance in true pixels. 2: the engine's convention (its focal is viewport * proj[0][0],
92822
+ // twice the pixel focal), which makes its 0.3 dilation 0.075 px^2 and scales its culls
92823
+ unitScale: f32,
92824
+ // the view depths of the near plane and of the raster's far clamp
92825
+ depthNear: f32,
92826
+ depthFar: f32
92827
+ }
92828
+
92829
+ // chunk table entry: slotBase, count, node, lod | file << 16
92830
+ @group(0) @binding(0) var<storage, read> chunks: array<vec4u>;
92831
+ // one bit per node: 1 = inside the frustum this frame
92832
+ @group(0) @binding(1) var<storage, read> nodeVisible: array<u32>;
92833
+ @group(0) @binding(2) var<storage, read_write> cache: array<u32>;
92834
+ // [0] survivors this frame, [1] splats the occlusion cull removed
92835
+ @group(0) @binding(3) var<storage, read_write> counter: array<atomic<u32>>;
92836
+ @group(0) @binding(4) var<uniform> uniforms: ProjectorUniforms;
92837
+ // the previous frame's farthest depth per block, as f32 bits (see shaders/reduce.ts)
92838
+ @group(0) @binding(5) var<storage, read> occL1: array<u32>;
92839
+ @group(0) @binding(6) var<storage, read> occL2: array<u32>;
92840
+ // order:bucket: survivors per depth bucket (see shaders/order.ts)
92841
+ @group(0) @binding(7) var<storage, read_write> buckets: array<atomic<u32>>;
92842
+
92843
+ struct Splat {
92844
+ index: u32,
92845
+ uv: vec2i
92846
+ }
92847
+ var<private> splat: Splat;
92848
+ fn setSplat(idx: u32) {
92849
+ splat.index = idx;
92850
+ splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize));
92851
+ }
92852
+
92853
+ ${readChunk}
92854
+
92855
+ // quaternion (x, y, z, w) to a rotation matrix (columns)
92856
+ fn rotationMatrix(qIn: vec4f) -> mat3x3f {
92857
+ let q = normalize(qIn);
92858
+ let x = q.x;
92859
+ let y = q.y;
92860
+ let z = q.z;
92861
+ let w = q.w;
92862
+ return mat3x3f(
92863
+ vec3f(1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y + w * z), 2.0 * (x * z - w * y)),
92864
+ vec3f(2.0 * (x * y - w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z + w * x)),
92865
+ vec3f(2.0 * (x * z + w * y), 2.0 * (y * z - w * x), 1.0 - 2.0 * (x * x + y * y))
92866
+ );
92867
+ }
92868
+
92869
+ struct Projected {
92870
+ valid: bool,
92871
+ occluded: bool,
92872
+ words: array<u32, ${CACHE_WORDS}>
92873
+ }
92874
+
92875
+ // The farthest depth over the (2g+1)^2 blocks around a block, on one grid level.
92876
+ fn farthestL1(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
92877
+ var farthest = 0u;
92878
+ for (var dy = -gather; dy <= gather; dy++) {
92879
+ for (var dx = -gather; dx <= gather; dx++) {
92880
+ farthest = max(farthest, occL1[u32((block.y + dy) * blocks.x + block.x + dx)]);
92881
+ }
92882
+ }
92883
+ return farthest;
92884
+ }
92885
+
92886
+ fn farthestL2(block: vec2i, gather: i32, blocks: vec2i) -> u32 {
92887
+ var farthest = 0u;
92888
+ for (var dy = -gather; dy <= gather; dy++) {
92889
+ for (var dx = -gather; dx <= gather; dx++) {
92890
+ farthest = max(farthest, occL2[u32((block.y + dy) * blocks.x + block.x + dx)]);
92891
+ }
92892
+ }
92893
+ return farthest;
92894
+ }
92895
+
92896
+ fn project(slot: u32, file: u32) -> Projected {
92897
+ var result: Projected;
92898
+ result.valid = false;
92899
+ result.occluded = false;
92900
+
92901
+ setSplat(slot);
92902
+ let center = srcCenter();
92903
+ let opacity = srcOpacity();
92904
+ if (opacity < uniforms.alphaClip) {
92905
+ return result;
92906
+ }
92907
+
92908
+ let viewCenter = uniforms.view * vec4f(center, 1.0);
92909
+ let depth = -viewCenter.z;
92910
+ if (uniforms.isOrtho == 0u && depth <= 0.0) {
92911
+ return result;
92912
+ }
92913
+ let clip = uniforms.viewProj * vec4f(center, 1.0);
92914
+ if (clip.w == 0.0) {
92915
+ return result;
92916
+ }
92917
+
92918
+ let viewport = uniforms.viewport;
92919
+ let focal = uniforms.focal;
92920
+
92921
+ // the work buffer holds world-space splats, so the view matrix is the model-view
92922
+ let rot = srcRotation();
92923
+ let scale = srcScale();
92924
+ let linear = mat3x3f(uniforms.view[0].xyz, uniforms.view[1].xyz, uniforms.view[2].xyz);
92925
+ let gaussian = linear * rotationMatrix(vec4f(rot.yzw, rot.x)) * mat3x3f(
92926
+ vec3f(scale.x, 0.0, 0.0),
92927
+ vec3f(0.0, scale.y, 0.0),
92928
+ vec3f(0.0, 0.0, scale.z)
92929
+ );
92930
+ let row0 = vec3f(gaussian[0].x, gaussian[1].x, gaussian[2].x);
92931
+ let row1 = vec3f(gaussian[0].y, gaussian[1].y, gaussian[2].y);
92932
+ let row2 = vec3f(gaussian[0].z, gaussian[1].z, gaussian[2].z);
92933
+ let c00 = dot(row0, row0);
92934
+ let c01 = dot(row0, row1);
92935
+ let c02 = dot(row0, row2);
92936
+ let c11 = dot(row1, row1);
92937
+ let c12 = dot(row1, row2);
92938
+ let c22 = dot(row2, row2);
92939
+
92940
+ var cov00: f32;
92941
+ var cov01: f32;
92942
+ var cov11: f32;
92943
+ if (uniforms.isOrtho != 0u) {
92944
+ cov00 = focal.x * focal.x * c00;
92945
+ cov01 = focal.x * focal.y * c01;
92946
+ cov11 = focal.y * focal.y * c11;
92947
+ } else {
92948
+ let safeDepth = max(depth, 0.001);
92949
+ let invDepth = 1.0 / safeDepth;
92950
+ let jx0 = focal.x * invDepth;
92951
+ let jx2 = focal.x * viewCenter.x * invDepth * invDepth;
92952
+ let jy1 = focal.y * invDepth;
92953
+ let jy2 = focal.y * viewCenter.y * invDepth * invDepth;
92954
+ let u00 = jx0 * c00 + jx2 * c02;
92955
+ let u01 = jx0 * c01 + jx2 * c12;
92956
+ let u02 = jx0 * c02 + jx2 * c22;
92957
+ let u11 = jy1 * c11 + jy2 * c12;
92958
+ let u12 = jy1 * c12 + jy2 * c22;
92959
+ cov00 = u00 * jx0 + u02 * jx2;
92960
+ cov01 = u01 * jy1 + u02 * jy2;
92961
+ cov11 = u11 * jy1 + u12 * jy2;
92962
+ }
92963
+
92964
+ // the low-pass dilation every splat renderer applies, 0.3 in the chosen units
92965
+ let us2 = uniforms.unitScale * uniforms.unitScale;
92966
+ cov00 += 0.3 / us2;
92967
+ cov11 += 0.3 / us2;
92968
+ let determinant = cov00 * cov11 - cov01 * cov01;
92969
+ if (determinant <= 0.0) {
92970
+ return result;
92971
+ }
92972
+
92973
+ let mid = 0.5 * (cov00 + cov11);
92974
+ let radius = length(vec2f(0.5 * (cov00 - cov11), cov01));
92975
+ let lambda1 = mid + radius;
92976
+ let lambda2 = max(mid - radius, 0.1 / us2);
92977
+
92978
+ // size cull on the footprint's radius in pixels. minPixelSize is a diameter: the engine's
92979
+ // projector is dispatched with half of it, and its quad path tests the full extent
92980
+ // (2 sqrt(2 lambda)) against the whole value, so both cut at the same place
92981
+ if (uniforms.unitScale * sqrt(2.0 * lambda1) < 0.5 * uniforms.minPixelSize) {
92982
+ return result;
92983
+ }
92984
+
92985
+ // contribution cull: the splat's alpha mass in pixels (the engine's minContribution rule)
92986
+ if (opacity * 6.283185 * sqrt(determinant) * us2 < uniforms.minContribution) {
92987
+ return result;
92988
+ }
92989
+
92990
+ // principal axis; a circular footprint has no defined eigenvector, any axis is right
92991
+ let eigenVec = vec2f(cov01, lambda1 - cov00);
92992
+ let eigenLen = length(eigenVec);
92993
+ let direction = select(vec2f(1.0, 0.0), eigenVec / eigenLen, eigenLen > 1e-9);
92994
+ let maxRadius = min(1024.0, min(viewport.x, viewport.y));
92995
+ let len1 = 2.0 * sqrt(2.0 * lambda1);
92996
+ let radiusScale = min(1.0, maxRadius / len1);
92997
+ let axis1 = len1 * radiusScale * direction;
92998
+ let len2 = 2.0 * sqrt(2.0 * lambda2) * radiusScale;
92999
+ let axis2 = len2 * vec2f(direction.y, -direction.x);
93000
+
93001
+ let ndc = clip.xy / clip.w;
93002
+ let extent = abs(axis1) + abs(axis2);
93003
+ let centerPixels = (ndc * 0.5 + 0.5) * viewport;
93004
+ if (centerPixels.x + extent.x < 0.0 || centerPixels.x - extent.x > viewport.x
93005
+ || centerPixels.y + extent.y < 0.0 || centerPixels.y - extent.y > viewport.y) {
93006
+ return result;
93007
+ }
93008
+
93009
+ ${occlusion
93010
+ ? `
93011
+ // Occlusion cull against the previous frame. Each stored depth is the nearest sample that
93012
+ // survived there, so the farthest depth over the blocks a splat covered bounds what could
93013
+ // still have shown behind it; a splat whose front (its centre less 2 sqrt(2) sigma along the
93014
+ // view, the same cut-off as the quad's edge) lies beyond that bound was invisible last
93015
+ // frame, up to sampling. Static splats reproject exactly through the previous view, so only
93016
+ // true disocclusions arrive a frame late. The footprint the splat had last frame bounds the
93017
+ // gather; footprints up to 16 px use the 8 px grid, up to 64 px the 32 px grid, larger ones
93018
+ // skip the test.
93019
+ if (uniforms.occlusionMode != 0u) {
93020
+ let prevClip = uniforms.prevViewProj * vec4f(center, 1.0);
93021
+ let prevDepth = -(uniforms.prevView * vec4f(center, 1.0)).z;
93022
+ let prevOrtho = uniforms.prevClipZ.z != 0.0;
93023
+ if (prevClip.w > 0.0 && (prevOrtho || prevDepth > 0.0)) {
93024
+ let prevNdc = prevClip.xy / prevClip.w;
93025
+ let halfExtent = len1 * radiusScale;
93026
+ let prevHalfExtent = halfExtent * (uniforms.prevFocal.x / focal.x)
93027
+ * select(depth / max(prevDepth, 0.001), 1.0, prevOrtho);
93028
+ let footprint = max(halfExtent, prevHalfExtent);
93029
+ var level = 1u;
93030
+ var blockSize = 8.0;
93031
+ var blocks = vec2i(i32(uniforms.occBlocksX1), i32(uniforms.occBlocksY1));
93032
+ if (footprint > 16.0) {
93033
+ level = 2u;
93034
+ blockSize = 32.0;
93035
+ blocks = vec2i(i32(uniforms.occBlocksX2), i32(uniforms.occBlocksY2));
93036
+ }
93037
+ if (footprint <= 64.0 && level <= uniforms.occlusionMode) {
93038
+ let gather = max(i32(ceil(footprint / blockSize)), 1);
93039
+ let prevPixel = vec2f(prevNdc.x * 0.5 + 0.5, 0.5 - prevNdc.y * uniforms.prevFlip * 0.5) * uniforms.prevViewport;
93040
+ let block = vec2i(floor(prevPixel / blockSize));
93041
+ if (block.x >= gather && block.y >= gather && block.x < blocks.x - gather && block.y < blocks.y - gather) {
93042
+ let front = prevDepth - 2.8284 * sqrt(c22);
93043
+ let w = select(front, 1.0, prevOrtho);
93044
+ if (w > 0.0) {
93045
+ let frontZ = clamp(uniforms.prevClipZ.x * front + uniforms.prevClipZ.y, 0.0, w) / w;
93046
+ // the block under the centre first: the neighbourhood's maximum is at
93047
+ // least its maximum, so a splat that block alone cannot cull is visible,
93048
+ // and most splats leave here after one load
93049
+ let centreIndex = u32(block.y * blocks.x + block.x);
93050
+ var farthest = select(occL1[centreIndex], occL2[centreIndex], level == 2u);
93051
+ if (frontZ > bitcast<f32>(farthest)) {
93052
+ if (level == 1u) {
93053
+ farthest = farthestL1(block, gather, blocks);
93054
+ } else {
93055
+ farthest = farthestL2(block, gather, blocks);
93056
+ }
93057
+ if (frontZ > bitcast<f32>(farthest)) {
93058
+ result.occluded = true;
93059
+ return result;
93060
+ }
93061
+ }
93062
+ }
93063
+ }
93064
+ }
93065
+ }
93066
+ }
93067
+
93068
+ `
93069
+ : ''}
93070
+ let color = clamp(srcColor(), vec3f(0.0), vec3f(uniforms.colorMax));
93071
+
93072
+ // rgb: 10/10/10 unorm with a 2-bit shared exponent (scale 1/2/4/8, range [0, 8])
93073
+ let maxChannel = max(color.r, max(color.g, color.b));
93074
+ var exponent = 0u;
93075
+ if (maxChannel > 4.0) {
93076
+ exponent = 3u;
93077
+ } else if (maxChannel > 2.0) {
93078
+ exponent = 2u;
93079
+ } else if (maxChannel > 1.0) {
93080
+ exponent = 1u;
93081
+ }
93082
+ let rgb = vec3u(clamp(color / f32(1u << exponent), vec3f(0.0), vec3f(1.0)) * 1023.0 + 0.5);
93083
+
93084
+ // centre as snorm16 over the range the offscreen cull bounds visible centres to; the
93085
+ // raster shader derives the same range from its viewport
93086
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / viewport;
93087
+
93088
+ result.valid = true;
93089
+ result.words[0] = pack2x16snorm(ndc / ndcRange);
93090
+ result.words[1] = bitcast<u32>(depth);
93091
+ result.words[2] = pack2x16float(axis1);
93092
+ result.words[3] = pack2x16float(vec2f(len2, 0.0)) | (u32(clamp(opacity, 0.0, 1.0) * 255.0 + 0.5) << 16u);
93093
+ ${order
93094
+ ? `
93095
+ // the depth bucket, log-spaced from the near plane, in the flags byte
93096
+ let key = clamp((log(max(depth, 1e-6)) - uniforms.keyLogNear) * uniforms.keyInvLogRange, 0.0, 0.999) * ${ORDER_BUCKETS}.0;
93097
+ result.words[3] |= u32(key) << 24u;
93098
+ `
93099
+ : ''}
93100
+ result.words[4] = rgb.r | (rgb.g << 10u) | (rgb.b << 20u) | (exponent << 30u);
93101
+ // Popless depth (StochasticSplats 3.4): the quad is tilted onto the plane through the
93102
+ // centre with normal adj(Sigma) mu (view space; adj rather than the inverse, so a flat
93103
+ // splat needs no division by its tiny determinant), and the raster gives each corner the
93104
+ // depth where its own view ray meets that plane, so hardware interpolation hands every
93105
+ // fragment the depth of the Gaussian's peak along its ray instead of the centre's. Stored
93106
+ // as g = n.xy / (n . mu): a corner at view offset d (in the plane z = -depth) lands at
93107
+ // depth / (1 + g . d). Orthographic rays are parallel, so there n = adj(Sigma) e_z and
93108
+ // the corner depth is depth + g . d with g = n.xy / n.z. Bounded so every corner stays
93109
+ // within 2 sqrt(2) sigma_z of the centre (the occlusion cull's front margin) and the
93110
+ // perspective scale stays positive, and so no corner crosses the near plane or the
93111
+ // raster's far clamp: a corner clamped there while the others are not bends the quad, whose
93112
+ // two triangles then take different depths and show as polygons (large far splats, the
93113
+ // sky, sit right at a far plane fitted to the scene). A centre beyond the clamp stays flat.
93114
+ let ortho = uniforms.isOrtho != 0u;
93115
+ let a00 = c11 * c22 - c12 * c12;
93116
+ let a01 = c02 * c12 - c01 * c22;
93117
+ let a02 = c01 * c12 - c02 * c11;
93118
+ let a11 = c00 * c22 - c02 * c02;
93119
+ let a12 = c01 * c02 - c00 * c12;
93120
+ let a22 = c00 * c11 - c01 * c01;
93121
+ let toward = select(viewCenter.xyz, vec3f(0.0, 0.0, -1.0), ortho);
93122
+ let n = vec3f(
93123
+ a00 * toward.x + a01 * toward.y + a02 * toward.z,
93124
+ a01 * toward.x + a11 * toward.y + a12 * toward.z,
93125
+ a02 * toward.x + a12 * toward.y + a22 * toward.z
93126
+ );
93127
+ let denom = select(dot(n, viewCenter.xyz), n.z, ortho);
93128
+ var g = vec2f(0.0);
93129
+ if (abs(denom) > 1e-20) {
93130
+ g = n.xy / denom;
93131
+ // view units per pixel at the centre's depth, and the quad's half extents in them
93132
+ let viewScale = select(depth, 1.0, ortho) / focal;
93133
+ let ext = (abs(axis1) + abs(axis2)) * viewScale;
93134
+ let bound = abs(g.x) * ext.x + abs(g.y) * ext.y;
93135
+ let margin = 2.8284 * sqrt(max(c22, 0.0));
93136
+ let inRange = select(
93137
+ min(1.0 - depth / uniforms.depthFar, depth / max(uniforms.depthNear, 1e-6) - 1.0),
93138
+ min(uniforms.depthFar - depth, depth - uniforms.depthNear),
93139
+ ortho
93140
+ );
93141
+ let limit = max(0.0, min(select(min(0.25, margin / max(depth, 1e-6)), margin, ortho), 0.999 * inRange));
93142
+ if (bound > limit) {
93143
+ g *= limit / max(bound, 1e-20);
93144
+ }
93145
+ }
93146
+ result.words[5] = pack2x16float(g);
93147
+ // the stable id the coverage hash seeds from: the slot, salted by the file for sources
93148
+ // whose indices restart per file
93149
+ result.words[6] = slot ^ (file * 2654435761u);
93150
+ return result;
93151
+ }
93152
+
93153
+ var<workgroup> wgCount: atomic<u32>;
93154
+ var<workgroup> wgOccluded: atomic<u32>;
93155
+ var<workgroup> wgBase: u32;
93156
+ ${order ? `var<workgroup> wgBuckets: array<atomic<u32>, ${ORDER_BUCKETS}>;` : ''}
93157
+
93158
+ @compute @workgroup_size(${PROJECTOR_WORKGROUP_SIZE})
93159
+ fn main(
93160
+ @builtin(workgroup_id) wg: vec3u,
93161
+ @builtin(num_workgroups) numWorkgroups: vec3u,
93162
+ @builtin(local_invocation_index) local: u32
93163
+ ) {
93164
+ // no early returns: the barriers below need every thread of the workgroup
93165
+ let chunkIndex = wg.x + wg.y * numWorkgroups.x;
93166
+ ${order ? ` atomicStore(&wgBuckets[local], 0u);` : ''}
93167
+ var projected: Projected;
93168
+ projected.valid = false;
93169
+ projected.occluded = false;
93170
+ if (chunkIndex < uniforms.numChunks) {
93171
+ let chunk = chunks[uniforms.chunkBase + chunkIndex];
93172
+ let visible = (nodeVisible[chunk.z >> 5u] >> (chunk.z & 31u)) & 1u;
93173
+ if (visible != 0u && local < chunk.y) {
93174
+ projected = project(chunk.x + local, chunk.w >> 16u);
93175
+ }
93176
+ }
93177
+
93178
+ // survivors claim consecutive slots: one workgroup-local count, one global atomic
93179
+ var localSlot = 0u;
93180
+ if (projected.valid) {
93181
+ localSlot = atomicAdd(&wgCount, 1u);
93182
+ }
93183
+ if (projected.occluded) {
93184
+ atomicAdd(&wgOccluded, 1u);
93185
+ }
93186
+ workgroupBarrier();
93187
+ if (local == 0u) {
93188
+ let n = atomicLoad(&wgCount);
93189
+ wgBase = select(0u, atomicAdd(&counter[0], n), n > 0u);
93190
+ let o = atomicLoad(&wgOccluded);
93191
+ if (o > 0u) {
93192
+ atomicAdd(&counter[1], o);
93193
+ }
93194
+ }
93195
+ workgroupBarrier();
93196
+ if (projected.valid) {
93197
+ let base = (wgBase + localSlot) * ${CACHE_WORDS}u;
93198
+ for (var i = 0u; i < ${CACHE_WORDS}u; i++) {
93199
+ cache[base + i] = projected.words[i];
93200
+ }
93201
+ ${order ? ` atomicAdd(&wgBuckets[projected.words[3] >> 24u], 1u);` : ''}
93202
+ }
93203
+ ${order
93204
+ ? `
93205
+ // a chunk's splats are spatially coherent, so few of its buckets are non-empty: one
93206
+ // workgroup count each, then one global atomic per non-empty bucket
93207
+ workgroupBarrier();
93208
+ let bucketCount = atomicLoad(&wgBuckets[local]);
93209
+ if (bucketCount > 0u) {
93210
+ atomicAdd(&buckets[local], bucketCount);
93211
+ }
93212
+ `
93213
+ : ''}
93214
+ }
93215
+ `;
93216
+
93217
+ // The ordering passes (variant order:bucket): the projector counts its survivors into 256
93218
+ // depth buckets, front to back; a one-workgroup scan turns the counts into bucket offsets, and
93219
+ // the scatter writes each survivor's cache slot into the ordered list the raster then follows.
93220
+ // Splats inside a bucket land in append order, so a bucket keeps its chunks' locality.
93221
+ // exclusive prefix sum of the bucket counts into the bucket offsets, in one workgroup
93222
+ const orderScanWGSL = /* wgsl */ `
93223
+ // [0, ${ORDER_BUCKETS}) counts, [${ORDER_BUCKETS}, ${2 * ORDER_BUCKETS}) offsets
93224
+ @group(0) @binding(0) var<storage, read_write> buckets: array<u32>;
93225
+
93226
+ var<workgroup> partial: array<u32, ${ORDER_BUCKETS}>;
93227
+
93228
+ @compute @workgroup_size(${ORDER_BUCKETS})
93229
+ fn main(@builtin(local_invocation_index) local: u32) {
93230
+ partial[local] = buckets[local];
93231
+ for (var stride = 1u; stride < ${ORDER_BUCKETS}u; stride <<= 1u) {
93232
+ workgroupBarrier();
93233
+ let value = select(0u, partial[local - stride], local >= stride);
93234
+ workgroupBarrier();
93235
+ partial[local] += value;
93236
+ }
93237
+ // inclusive to exclusive
93238
+ buckets[${ORDER_BUCKETS}u + local] = partial[local] - buckets[local];
93239
+ }
93240
+ `;
93241
+ // One thread per cache slot, one workgroup per 256 consecutive slots. Consecutive slots come
93242
+ // from one chunk, so a workgroup touches few buckets: it counts them locally, claims each
93243
+ // bucket's range with one global atomic, and places its splats in append order inside it.
93244
+ const orderScatterWGSL = /* wgsl */ `
93245
+ @group(0) @binding(0) var<storage, read> counter: array<u32>;
93246
+ @group(0) @binding(1) var<storage, read> cache: array<u32>;
93247
+ @group(0) @binding(2) var<storage, read_write> buckets: array<atomic<u32>>;
93248
+ @group(0) @binding(3) var<storage, read_write> ordered: array<u32>;
93249
+
93250
+ var<workgroup> wgCounts: array<atomic<u32>, ${ORDER_BUCKETS}>;
93251
+ var<workgroup> wgBase: array<u32, ${ORDER_BUCKETS}>;
93252
+
93253
+ @compute @workgroup_size(${ORDER_BUCKETS})
93254
+ fn main(
93255
+ @builtin(workgroup_id) wg: vec3u,
93256
+ @builtin(num_workgroups) numWorkgroups: vec3u,
93257
+ @builtin(local_invocation_index) local: u32
93258
+ ) {
93259
+ // no early returns: the barriers need every thread
93260
+ atomicStore(&wgCounts[local], 0u);
93261
+ let slot = (wg.x + wg.y * numWorkgroups.x) * ${ORDER_BUCKETS}u + local;
93262
+ let live = slot < counter[0];
93263
+ var key = 0u;
93264
+ var rank = 0u;
93265
+ workgroupBarrier();
93266
+ if (live) {
93267
+ key = cache[slot * ${CACHE_WORDS}u + 3u] >> 24u;
93268
+ rank = atomicAdd(&wgCounts[key], 1u);
93269
+ }
93270
+ workgroupBarrier();
93271
+ let count = atomicLoad(&wgCounts[local]);
93272
+ if (count > 0u) {
93273
+ wgBase[local] = atomicAdd(&buckets[${ORDER_BUCKETS}u + local], count);
93274
+ }
93275
+ workgroupBarrier();
93276
+ if (live) {
93277
+ ordered[wgBase[key] + rank] = slot;
93278
+ }
93279
+ }
93280
+ `;
93281
+
93282
+ // The raster pass: an indirect instanced draw of 128-quad meshes over the projector's
93283
+ // survivors, into the renderer's own colour + depth target. Fragments keep themselves with
93284
+ // probability alpha (StochasticSplats, Listing 1) and write opaque colour with hardware depth,
93285
+ // so no sort is needed and the depth buffer holds the nearest surviving sample per pixel.
93286
+ /** Quads per draw instance; the mesh holds this many quads. */
93287
+ const QUADS_PER_INSTANCE = 128;
93288
+ /** The raster's far clamp in normalised depth: just inside 1, which the compose reads as empty. */
93289
+ const FAR_CLIP_Z = 0.999999;
93290
+ const rasterVertexWGSL = /* wgsl */ `
93291
+ attribute vertex_position: vec3f;
93292
+
93293
+ // width, height, 2 / width, 2 / height
93294
+ uniform viewportSize: vec4f;
93295
+ // clip z = a * viewDepth + b (x, y); z = 1 for an orthographic camera
93296
+ uniform clipZParams: vec4f;
93297
+ // set by the engine's forward renderer for the target being rendered
93298
+ uniform projectionFlipY: f32;
93299
+ // focal length in pixels (x, y), for the popless corner depths
93300
+ uniform focalParams: vec4f;
93301
+
93302
+ var<storage, read> splatCache: array<u32>;
93303
+ var<storage, read> splatCount: array<u32>;
93304
+ #ifdef SSE_ORDERED
93305
+ // cache slots in draw order (variant order:bucket)
93306
+ var<storage, read> orderedSlots: array<u32>;
93307
+ #endif
93308
+
93309
+ // screen-linear: the corners share one screen footprint whatever depth they carry
93310
+ varying @interpolate(linear) gaussianUV: vec2f;
93311
+ varying @interpolate(flat, either) packedColor: u32;
93312
+ varying @interpolate(flat, either) packedAlpha: u32;
93313
+ varying @interpolate(flat, either) splatId: u32;
93314
+
93315
+ const discardPosition = vec4f(0.0, 0.0, 2.0, 1.0);
93316
+
93317
+ @vertex
93318
+ fn vertexMain(input: VertexInput) -> VertexOutput {
93319
+ var output: VertexOutput;
93320
+ let order = pcInstanceIndex * ${QUADS_PER_INSTANCE}u + u32(vertex_position.z);
93321
+ // the indirect instance count rounds up to whole instances; the tail is discarded here
93322
+ if (order >= splatCount[0]) {
93323
+ output.position = discardPosition;
93324
+ return output;
93325
+ }
93326
+
93327
+ #ifdef SSE_ORDERED
93328
+ let base = orderedSlots[order] * ${CACHE_WORDS}u;
93329
+ #else
93330
+ let base = order * ${CACHE_WORDS}u;
93331
+ #endif
93332
+ let maxRadius = min(1024.0, min(uniform.viewportSize.x, uniform.viewportSize.y));
93333
+ let ndcRange = vec2f(1.0) + vec2f(4.0 * maxRadius) / uniform.viewportSize.xy;
93334
+ let ndc = unpack2x16snorm(splatCache[base]) * ndcRange;
93335
+ let depth = bitcast<f32>(splatCache[base + 1u]);
93336
+ let ortho = uniform.clipZParams.z != 0.0;
93337
+
93338
+ let axis1 = unpack2x16float(splatCache[base + 2u]);
93339
+ let word3 = splatCache[base + 3u];
93340
+ let len2 = unpack2x16float(word3).x;
93341
+ let axis2 = len2 * normalize(vec2f(axis1.y, -axis1.x));
93342
+
93343
+ let corner = vertex_position.xy;
93344
+ let pixelOffset = corner.x * axis1 + corner.y * axis2;
93345
+ #ifdef SSE_POPLESS
93346
+ // the corner's depth on the splat's plane (see the projector): its view-space offset
93347
+ // at the centre's depth, times the stored gradient
93348
+ let g = unpack2x16float(splatCache[base + 5u]);
93349
+ let shift = dot(g, pixelOffset * select(depth, 1.0, ortho) / uniform.focalParams.xy);
93350
+ let cornerDepth = select(depth / (1.0 + shift), depth + shift, ortho);
93351
+ #else
93352
+ let cornerDepth = depth;
93353
+ #endif
93354
+ let w = select(cornerDepth, 1.0, ortho);
93355
+ let ndcCorner = ndc + pixelOffset * uniform.viewportSize.zw;
93356
+ // clip z clamped into range like the engine's splat shader, so splats beyond the far plane
93357
+ // still draw; just inside it, since the compose and the accumulation read depth 1 as empty
93358
+ let pos = vec4f(ndcCorner * w, clamp(uniform.clipZParams.x * cornerDepth + uniform.clipZParams.y, 0.0, w * ${FAR_CLIP_Z}), w);
93359
+ output.position = vec4f(pos.x, pos.y * uniform.projectionFlipY, pos.z, pos.w);
93360
+ output.gaussianUV = corner;
93361
+ output.packedColor = splatCache[base + 4u];
93362
+ output.packedAlpha = word3 >> 16u;
93363
+ output.splatId = splatCache[base + 6u];
93364
+ return output;
93365
+ }
93366
+ `;
93367
+ const rasterFragmentWGSL = /* wgsl */ `
93368
+ varying @interpolate(linear) gaussianUV: vec2f;
93369
+ varying @interpolate(flat, either) packedColor: u32;
93370
+ varying @interpolate(flat, either) packedAlpha: u32;
93371
+ varying @interpolate(flat, either) splatId: u32;
93372
+
93373
+ uniform sseAlphaClip: f32;
93374
+ // 0 while the camera rests, so a still frame reproduces itself; the frame index once TAA
93375
+ // accumulates
93376
+ uniform frameSeed: u32;
93377
+
93378
+ const EXP4 = exp(-4.0);
93379
+ const INV_EXP4 = 1.0 / (1.0 - EXP4);
93380
+
93381
+ // the engine's falloff: zero at the quad edge, which sits at 2 sqrt(2) sigma
93382
+ fn normExp(x: f32) -> f32 {
93383
+ return (exp(x * -4.0) - EXP4) * INV_EXP4;
93384
+ }
93385
+
93386
+ // integer hash (Wellons' prospector mix)
93387
+ fn hashU32(x: u32) -> u32 {
93388
+ var v = x;
93389
+ v ^= v >> 16u;
93390
+ v *= 0x7feb352du;
93391
+ v ^= v >> 15u;
93392
+ v *= 0x846ca68bu;
93393
+ v ^= v >> 16u;
93394
+ return v;
93395
+ }
93396
+
93397
+ @fragment
93398
+ fn fragmentMain(input: FragmentInput) -> FragmentOutput {
93399
+ var output: FragmentOutput;
93400
+ let radius = dot(gaussianUV, gaussianUV);
93401
+ if (radius > 1.0) {
93402
+ discard;
93403
+ }
93404
+ let opacity = f32(packedAlpha & 0xffu) / 255.0;
93405
+ let alpha = normExp(radius) * opacity;
93406
+ if (alpha < uniform.sseAlphaClip) {
93407
+ discard;
93408
+ }
93409
+
93410
+ let pix = vec2u(pcPosition.xy);
93411
+ #ifdef SSE_SPP_QUAD
93412
+ // one sample per pixel, thresholds stratified over each 2x2 pixel quad: the quad's four
93413
+ // pixels take the four strata of [0, 1) in a per-(quad, splat) scrambled order, so a
93414
+ // splat with alpha a covers 4a +- 1 of its quad and the compose's quad mean is nearly
93415
+ // exact. Hashing quad and splat keeps overlapping splats decorrelated
93416
+ let quad = pix >> vec2u(1u);
93417
+ let h = hashU32((quad.x * 1973u) ^ (quad.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
93418
+ let stratum = ((pix.y & 1u) * 2u + (pix.x & 1u)) ^ (h & 3u);
93419
+ let rnd = (f32(stratum) + f32(h >> 8u) * (1.0 / 16777216.0)) * 0.25;
93420
+ #else
93421
+ let h = hashU32((pix.x * 1973u) ^ (pix.y * 9277u) ^ ((splatId + 1u) * 26699u) ^ uniform.frameSeed);
93422
+ let rnd = f32(h >> 8u) * (1.0 / 16777216.0);
93423
+ #endif
93424
+ if (rnd >= alpha) {
93425
+ discard;
93426
+ }
93427
+
93428
+ let bits = packedColor;
93429
+ let color = vec3f(vec3u(bits, bits >> 10u, bits >> 20u) & vec3u(1023u)) * (f32(1u << (bits >> 30u)) / 1023.0);
93430
+ // opaque coverage: the compose reads alpha 1 as "a sample landed here"
93431
+ output.color = vec4f(color, 1.0);
93432
+ return output;
93433
+ }
93434
+ `;
93435
+
93436
+ // The occlusion grid: the previous frame's depth texture reduced to the farthest depth per 8x8
93437
+ // pixel block (level 1), and the farthest of each 4x4 group of those (level 2, 32 px). Each
93438
+ // pixel's depth is the nearest surviving sample there, so a block's maximum bounds what could
93439
+ // still have shown behind it; a splat whose front lies beyond that bound over every block it
93440
+ // covers was invisible last frame. Depths are hardware z in [0, 1], stored as their f32 bits
93441
+ // (non-negative floats order the same as their bits, so atomicMax works on them).
93442
+ const reduceL1WGSL = /* wgsl */ `
93443
+ struct ReduceUniforms {
93444
+ width: u32,
93445
+ height: u32,
93446
+ blocksX: u32,
93447
+ blocksY: u32
93448
+ }
93449
+
93450
+ @group(0) @binding(0) var prevDepth: texture_depth_2d;
93451
+ @group(0) @binding(1) var<storage, read_write> blockMax: array<u32>;
93452
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
93453
+
93454
+ var<workgroup> wgMax: atomic<u32>;
93455
+
93456
+ @compute @workgroup_size(8, 8)
93457
+ fn main(
93458
+ @builtin(workgroup_id) wg: vec3u,
93459
+ @builtin(local_invocation_id) lid: vec3u,
93460
+ @builtin(local_invocation_index) li: u32
93461
+ ) {
93462
+ let pixel = wg.xy * 8u + lid.xy;
93463
+ // pixels off the texture count as far, so an edge block never culls
93464
+ var depth = 1.0;
93465
+ if (pixel.x < uniforms.width && pixel.y < uniforms.height) {
93466
+ depth = textureLoad(prevDepth, vec2i(pixel), 0);
93467
+ }
93468
+ atomicMax(&wgMax, bitcast<u32>(depth));
93469
+ workgroupBarrier();
93470
+ if (li == 0u) {
93471
+ blockMax[wg.y * uniforms.blocksX + wg.x] = atomicLoad(&wgMax);
93472
+ }
93473
+ }
93474
+ `;
93475
+ const reduceL2WGSL = /* wgsl */ `
93476
+ struct ReduceUniforms {
93477
+ blocksX1: u32,
93478
+ blocksY1: u32,
93479
+ blocksX2: u32,
93480
+ blocksY2: u32
93481
+ }
93482
+
93483
+ @group(0) @binding(0) var<storage, read> level1: array<u32>;
93484
+ @group(0) @binding(1) var<storage, read_write> level2: array<u32>;
93485
+ @group(0) @binding(2) var<uniform> uniforms: ReduceUniforms;
93486
+
93487
+ @compute @workgroup_size(64)
93488
+ fn main(@builtin(global_invocation_id) gid: vec3u) {
93489
+ let index = gid.x;
93490
+ if (index >= uniforms.blocksX2 * uniforms.blocksY2) {
93491
+ return;
93492
+ }
93493
+ let bx = index % uniforms.blocksX2;
93494
+ let by = index / uniforms.blocksX2;
93495
+ var farthest = 0u;
93496
+ for (var dy = 0u; dy < 4u; dy++) {
93497
+ for (var dx = 0u; dx < 4u; dx++) {
93498
+ let x = bx * 4u + dx;
93499
+ let y = by * 4u + dy;
93500
+ if (x < uniforms.blocksX1 && y < uniforms.blocksY1) {
93501
+ farthest = max(farthest, level1[y * uniforms.blocksX1 + x]);
93502
+ } else {
93503
+ farthest = max(farthest, bitcast<u32>(1.0));
93504
+ }
93505
+ }
93506
+ }
93507
+ level2[index] = farthest;
93508
+ }
93509
+ `;
93510
+
93511
+ // Data path (ii): the projector reads each resident file's own textures (sog, ply or
93512
+ // compressed ply) through the engine's format read chunks, so nothing is copied into a work
93513
+ // buffer: no decoded 24-byte copy per splat, no re-copy when a node's lod changes, no
93514
+ // colour refresh when the camera turns. The price is one dispatch per resident file, the
93515
+ // model transform and the sh evaluation per splat per frame.
93516
+ //
93517
+ // Interim: the engine still allocates its work buffer and would keep copying into it, so the
93518
+ // copy passes are switched off on the work buffer this source sees; the textures themselves
93519
+ // stay until engine change E2 (no work buffer in external mode) lands.
93520
+ const tmpScale = new Vec3();
93521
+ const tmpRotation = new Quat();
93522
+ class DirectSplatSource {
93523
+ kind = 'direct';
93524
+ device;
93525
+ resource = null;
93526
+ set = null;
93527
+ constants = new Map();
93528
+ patched = null;
93529
+ constructor(device) {
93530
+ this.device = device;
93531
+ }
93532
+ update(set, manager) {
93533
+ // one format per scene: a sog lod set shares its format across files. The first file's
93534
+ // format compiles the projector; a file of another format is skipped by dispatchPlan
93535
+ this.resource = set.files[0]?.resource ?? this.resource;
93536
+ this.set = set;
93537
+ this.constants.clear();
93538
+ for (const file of set.files) {
93539
+ const m = file.modelMatrix;
93540
+ m.getScale(tmpScale);
93541
+ tmpRotation.setFromMat4(m);
93542
+ if (tmpRotation.w < 0)
93543
+ tmpRotation.mulScalar(-1);
93544
+ this.constants.set(file.fileIndex, {
93545
+ rotation: [tmpRotation.x, tmpRotation.y, tmpRotation.z, tmpRotation.w],
93546
+ scale: [tmpScale.x, tmpScale.y, tmpScale.z, 0]
93547
+ });
93548
+ }
93549
+ this.patchWorkBuffer(manager.world.workBuffer);
93550
+ }
93551
+ // the engine's copy into the work buffer is wasted work for this path
93552
+ patchWorkBuffer(workBuffer) {
93553
+ if (this.patched?.workBuffer === workBuffer)
93554
+ return;
93555
+ this.restoreWorkBuffer();
93556
+ this.patched = { workBuffer, render: workBuffer.render, renderColor: workBuffer.renderColor };
93557
+ const skip = () => undefined;
93558
+ workBuffer.render = skip;
93559
+ workBuffer.renderColor = skip;
93560
+ }
93561
+ restoreWorkBuffer() {
93562
+ if (!this.patched)
93563
+ return;
93564
+ const { workBuffer, render, renderColor } = this.patched;
93565
+ workBuffer.render = render;
93566
+ workBuffer.renderColor = renderColor;
93567
+ this.patched = null;
93568
+ }
93569
+ readChunk(bindingBase) {
93570
+ const format = this.require().format;
93571
+ // The format's read chunk reads the file's own space and returns sh0 colour + alpha;
93572
+ // the adapter below applies the file's model transform and evaluates its sh for this
93573
+ // camera. Its loose `uniform` and texture declarations (dequantisation constants, the
93574
+ // compressed format's chunk texture) are reflected by the engine into a second bind
93575
+ // group and set by name like any other parameter.
93576
+ // The engine writes its 32-bit float streams (the sog v2 codebook) as `texture_2d<uff>`,
93577
+ // an alias only its reflection of loose declarations resolves; explicit bindings need
93578
+ // the wgsl type, and the matching unfilterable sample type in bindFormats()
93579
+ const declarations = format
93580
+ .getComputeInputDeclarations(bindingBase)
93581
+ .replace(/texture_2d<uff>/g, 'texture_2d<f32>');
93582
+ return /* wgsl */ `
93583
+ #include "halfTypesCS"
93584
+ #include "gsplatEvalSHVS"
93585
+ ${declarations}
93586
+ ${format.getReadCode()}
93587
+
93588
+ var<private> srcWorldCenter: vec3f;
93589
+ var<private> srcColorCache: vec4f;
93590
+
93591
+ fn quatMulF(a: vec4f, b: vec4f) -> vec4f {
93592
+ return vec4f(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz));
93593
+ }
93594
+
93595
+ // v rotated by the inverse of q (x, y, z, w)
93596
+ fn quatRotateInvF(q: vec4f, v: vec3f) -> vec3f {
93597
+ let u = -q.xyz;
93598
+ return v + 2.0 * cross(u, cross(u, v) + q.w * v);
93599
+ }
93600
+
93601
+ fn srcCenter() -> vec3f {
93602
+ srcWorldCenter = (uniforms.model * vec4f(getCenter(), 1.0)).xyz;
93603
+ return srcWorldCenter;
93604
+ }
93605
+
93606
+ fn srcOpacity() -> f32 {
93607
+ srcColorCache = getColor();
93608
+ return srcColorCache.a;
93609
+ }
93610
+
93611
+ // the format returns (w, x, y, z); world = model * source
93612
+ fn srcRotation() -> vec4f {
93613
+ let q = quatMulF(uniforms.modelRotation, getRotation().yzwx);
93614
+ return q.wxyz;
93615
+ }
93616
+
93617
+ fn srcScale() -> vec3f {
93618
+ return uniforms.modelScale.xyz * getScale();
93619
+ }
93620
+
93621
+ fn srcColor() -> vec3f {
93622
+ var color = srcColorCache.rgb;
93623
+ #if SH_BANDS > 0
93624
+ // the view direction in the file's space; orthographic rays all run along the camera forward
93625
+ let view = uniforms.view;
93626
+ let orthoDir = vec3f(0.0, 0.0, -1.0) * mat3x3f(view[0].xyz, view[1].xyz, view[2].xyz);
93627
+ let viewDir = select(srcWorldCenter - uniforms.cameraPosition.xyz, orthoDir, uniforms.isOrtho != 0u);
93628
+ let dir = normalize(quatRotateInvF(uniforms.modelRotation, viewDir));
93629
+ var sh: array<half3, SH_COEFFS>;
93630
+ var shScale: f32;
93631
+ readSHData(&sh, &shScale);
93632
+ color += vec3f(evalSH(&sh, dir) * half(shScale));
93633
+ #endif
93634
+ return color;
93635
+ }
93636
+ `;
93637
+ }
93638
+ bindFormats() {
93639
+ const format = this.require().format;
93640
+ const entries = format.getComputeBindFormats();
93641
+ for (const entry of entries) {
93642
+ const stream = format.streams.find((s) => s.name === entry.name);
93643
+ if (stream?.format === PIXELFORMAT_RGBA32F)
93644
+ entry.sampleType = SAMPLETYPE_UNFILTERABLE_FLOAT;
93645
+ }
93646
+ return entries;
93647
+ }
93648
+ shaderIncludes() {
93649
+ // the read chunks include the engine's own gsplat chunks by name
93650
+ return new Map(ShaderChunks.get(this.device, SHADERLANGUAGE_WGSL));
93651
+ }
93652
+ shaderDefines() {
93653
+ const defines = new Map();
93654
+ this.require().configureMaterialDefines(defines);
93655
+ return defines;
93656
+ }
93657
+ chunkBase(node) {
93658
+ return node.sourceBase;
93659
+ }
93660
+ dispatchPlan(set) {
93661
+ // one run of the chunk table per file (the table is built file by file)
93662
+ const groups = [];
93663
+ let chunkBase = 0;
93664
+ const hash = this.resource?.format.hash;
93665
+ for (const file of set.files) {
93666
+ let chunkCount = 0;
93667
+ for (const node of file.nodes)
93668
+ chunkCount += Math.ceil(node.count / 256);
93669
+ if (chunkCount > 0 && file.resource.format.hash === hash) {
93670
+ groups.push({ fileIndex: file.fileIndex, chunkBase, chunkCount });
93671
+ }
93672
+ chunkBase += chunkCount;
93673
+ }
93674
+ return groups;
93675
+ }
93676
+ bind(compute, group, set) {
93677
+ const file = set.files[group.fileIndex];
93678
+ const { resource } = file;
93679
+ for (const [name, texture] of resource.streams.textures) {
93680
+ compute.setParameter(name, texture);
93681
+ }
93682
+ for (const [name, value] of resource.parameters) {
93683
+ compute.setParameter(name, value);
93684
+ }
93685
+ const constants = this.constants.get(file.fileIndex);
93686
+ compute.setParameter('model', file.modelMatrix.data);
93687
+ compute.setParameter('modelRotation', constants.rotation);
93688
+ compute.setParameter('modelScale', constants.scale);
93689
+ }
93690
+ textureSize(group) {
93691
+ return this.set?.files[group.fileIndex].resource.textureDimensions.x ?? 0;
93692
+ }
93693
+ gpuBytes() {
93694
+ // the file textures belong to the engine and are counted by app.stats.vram
93695
+ return 0;
93696
+ }
93697
+ shaderKey() {
93698
+ const resource = this.resource;
93699
+ if (!resource)
93700
+ return 'direct:';
93701
+ const defines = this.shaderDefines();
93702
+ return `direct:${resource.format.hash}:${[...defines].map(([k, v]) => `${k}=${v}`).join(',')}`;
93703
+ }
93704
+ destroy() {
93705
+ this.restoreWorkBuffer();
93706
+ this.resource = null;
93707
+ this.set = null;
93708
+ this.constants.clear();
93709
+ }
93710
+ require() {
93711
+ if (!this.resource)
93712
+ throw new Error('DirectSplatSource: update() has not run');
93713
+ return this.resource;
93714
+ }
93715
+ }
93716
+
93717
+ class WorkBufferSplatSource {
93718
+ kind = 'workbuffer';
93719
+ workBuffer = null;
93720
+ update(set, manager) {
93721
+ this.workBuffer = manager.world.workBuffer;
93722
+ }
93723
+ readChunk(bindingBase) {
93724
+ const format = this.require().format;
93725
+ // the engine's declarations bind one texture per stream from bindingBase and define
93726
+ // loadDataX(); its read code decodes them into getCenter() and friends, already in
93727
+ // world space with the sh colour baked for this camera
93728
+ return /* wgsl */ `
93729
+ ${format.getComputeInputDeclarations(bindingBase)}
93730
+ ${format.getReadCode()}
93731
+ fn srcCenter() -> vec3f { return getCenter(); }
93732
+ fn srcOpacity() -> f32 { return getOpacity(); }
93733
+ fn srcRotation() -> vec4f { return getRotation(); }
93734
+ fn srcScale() -> vec3f { return getScale(); }
93735
+ fn srcColor() -> vec3f { return getColor(); }
93736
+ `;
93737
+ }
93738
+ bindFormats() {
93739
+ return this.require().format.getComputeBindFormats();
93740
+ }
93741
+ shaderIncludes() {
93742
+ return undefined;
93743
+ }
93744
+ shaderDefines() {
93745
+ return undefined;
93746
+ }
93747
+ chunkBase(node) {
93748
+ return node.slotBase;
93749
+ }
93750
+ dispatchPlan(set, numChunks) {
93751
+ return [{ fileIndex: -1, chunkBase: 0, chunkCount: numChunks }];
93752
+ }
93753
+ bind(compute) {
93754
+ const workBuffer = this.require();
93755
+ for (const stream of workBuffer.format.streams) {
93756
+ compute.setParameter(stream.name, workBuffer.getTexture(stream.name));
93757
+ }
93758
+ }
93759
+ textureSize() {
93760
+ return this.require().textureSize;
93761
+ }
93762
+ gpuBytes() {
93763
+ // the work buffer belongs to the engine and is counted by app.stats.vram
93764
+ return 0;
93765
+ }
93766
+ shaderKey() {
93767
+ const workBuffer = this.workBuffer;
93768
+ return workBuffer ? `wb:${workBuffer.format.streams.map((s) => s.name).join(',')}` : 'wb:';
93769
+ }
93770
+ destroy() {
93771
+ this.workBuffer = null;
93772
+ }
93773
+ require() {
93774
+ if (!this.workBuffer)
93775
+ throw new Error('WorkBufferSplatSource: update() has not run');
93776
+ return this.workBuffer;
93777
+ }
93778
+ }
93779
+
93780
+ // The stochastic splat renderer (WebGPU, opt-in). The engine keeps LOD, streaming and the
93781
+ // work-buffer copy; this owns everything after: per frame it culls nodes on the cpu, projects
93782
+ // the resident splats in a compute pass into a dense cache, writes the indirect draw arguments,
93783
+ // rasterises the survivors as opaque depth-tested quads into its own colour + depth target
93784
+ // (StochasticSplats: keep a fragment with probability alpha, no sort), and composes that target
93785
+ // over the camera's target from a fullscreen quad in the World layer that also writes depth.
93786
+ //
93787
+ // Frame flow: the compute runs inside the engine's gsplat update (the `frame:ready` hook, before
93788
+ // the frame graph), the raster pass runs from `camera.beforePasses`, and the compose is an
93789
+ // ordinary mesh instance in the camera's forward pass. See docs/stochastic-renderer.md.
93790
+ const defaultVariant = () => ({
93791
+ spp: 'quad',
93792
+ compose: 'blend',
93793
+ cull: 'auto',
93794
+ order: 'bucket',
93795
+ contribution: 0,
93796
+ popless: 'on',
93797
+ taa: 'on',
93798
+ taaMax: 256,
93799
+ taaMoveMax: 16,
93800
+ taaClip: 1.25,
93801
+ taaFilter: 'cubic',
93802
+ taaReproj: 'sample',
93803
+ taaMotion: 4,
93804
+ taaDebug: 0,
93805
+ taaFlip: 0,
93806
+ colorMax: 8,
93807
+ units: 'engine'
93808
+ });
93809
+ const taaCount = (value) => Math.min(TAA_MAX_COUNT, Math.max(1, Math.round(value)));
93810
+ const parseVariant = (text) => {
93811
+ const variant = defaultVariant();
93812
+ for (const part of (text ?? '').split(',')) {
93813
+ const [key, value] = part.split(':').map((s) => s.trim());
93814
+ if (!key || value === undefined)
93815
+ continue;
93816
+ if (key === 'spp' && (value === '1' || value === 'quad'))
93817
+ variant.spp = value;
93818
+ if (key === 'compose' && (value === 'blend' || value === 'none' || value === 'depth'))
93819
+ variant.compose = value;
93820
+ if (key === 'popless' && (value === 'on' || value === 'off'))
93821
+ variant.popless = value;
93822
+ if (key === 'taa' && (value === 'on' || value === 'off'))
93823
+ variant.taa = value;
93824
+ if (key === 'taaMax' && Number.isFinite(Number(value)))
93825
+ variant.taaMax = taaCount(Number(value));
93826
+ if (key === 'taaMoveMax' && Number.isFinite(Number(value)))
93827
+ variant.taaMoveMax = taaCount(Number(value));
93828
+ if (key === 'taaDebug' && Number.isFinite(Number(value)))
93829
+ variant.taaDebug = Number(value);
93830
+ if (key === 'taaClip' && Number.isFinite(Number(value)))
93831
+ variant.taaClip = Math.max(0, Number(value));
93832
+ if (key === 'taaFilter' && (value === 'linear' || value === 'cubic'))
93833
+ variant.taaFilter = value;
93834
+ if (key === 'taaReproj' && (value === 'sample' || value === 'history'))
93835
+ variant.taaReproj = value;
93836
+ if (key === 'taaMotion' && Number.isFinite(Number(value)))
93837
+ variant.taaMotion = Math.max(0, Number(value));
93838
+ if (key === 'taaFlip' && Number.isFinite(Number(value)))
93839
+ variant.taaFlip = Number(value);
93840
+ if (key === 'colorMax' && Number.isFinite(Number(value)))
93841
+ variant.colorMax = Math.max(0, Number(value));
93842
+ if (key === 'units' && (value === 'px' || value === 'engine'))
93843
+ variant.units = value;
93844
+ if (key === 'cull' && (value === 'off' || value === 'l1' || value === 'l2' || value === 'auto')) {
93845
+ variant.cull = value;
93846
+ }
93847
+ if (key === 'order' && (value === 'append' || value === 'bucket'))
93848
+ variant.order = value;
93849
+ if (key === 'contribution' && Number.isFinite(Number(value)))
93850
+ variant.contribution = Math.max(0, Number(value));
93851
+ }
93852
+ return variant;
93853
+ };
93854
+ // Renders an explicit mesh-instance list into the renderer's own target (the raster and the
93855
+ // taa resolve). Not a layer: a layer in camera.layers is culled once and drawn by every pass
93856
+ // for the camera, so the scene pass would draw the splats into the camera target as well.
93857
+ class SplatRasterPass extends RenderPass {
93858
+ forward;
93859
+ camera;
93860
+ instances;
93861
+ constructor(device, forward, camera, instances, name = 'sse-splat-raster') {
93862
+ super(device);
93863
+ this.forward = forward;
93864
+ this.camera = camera;
93865
+ this.instances = instances;
93866
+ this.name = name;
93867
+ }
93868
+ execute() {
93869
+ this.forward.renderForwardLayer(this.camera.camera, this.renderTarget, null, undefined, SHADER_FORWARD, {
93870
+ meshInstances: this.instances
93871
+ });
93872
+ }
93873
+ }
93874
+ const createQuadMesh = (device, quads) => {
93875
+ const positions = new Float32Array(quads * 4 * 3);
93876
+ const indices = new Uint32Array(quads * 6);
93877
+ for (let i = 0; i < quads; ++i) {
93878
+ // z carries the quad's index within the instance
93879
+ positions.set([-1, -1, i, 1, -1, i, 1, 1, i, -1, 1, i], i * 12);
93880
+ const v = i * 4;
93881
+ indices.set([v, v + 1, v + 2, v, v + 2, v + 3], i * 6);
93882
+ }
93883
+ const mesh = new Mesh(device);
93884
+ mesh.setPositions(positions, 3);
93885
+ mesh.setIndices(indices);
93886
+ mesh.update(PRIMITIVE_TRIANGLES);
93887
+ return mesh;
93888
+ };
93889
+ const createFullscreenMesh = (device) => {
93890
+ const mesh = new Mesh(device);
93891
+ mesh.setPositions(new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), 2);
93892
+ mesh.setIndices(new Uint16Array([0, 1, 2, 0, 2, 3]));
93893
+ mesh.update(PRIMITIVE_TRIANGLES);
93894
+ return mesh;
93895
+ };
93896
+ const tmpVec2 = new Vec2();
93897
+ class StochasticSplatRenderer {
93898
+ variant;
93899
+ source;
93900
+ app;
93901
+ device;
93902
+ camera;
93903
+ worldLayer;
93904
+ provider;
93905
+ unsubscribe;
93906
+ enabled = true;
93907
+ // the resident set and its chunk table
93908
+ set = null;
93909
+ numChunks = 0;
93910
+ chunkData = new Uint32Array(0);
93911
+ chunkBuffer = null;
93912
+ nodeVisibleData = new Uint32Array(0);
93913
+ nodeVisibleBuffer = null;
93914
+ cacheBuffer = null;
93915
+ cacheSlots = 0;
93916
+ counter;
93917
+ // compute
93918
+ // one projector shader per source and occlusion / order specialisation: the test's code
93919
+ // costs a little even when a uniform disables it, so a disabled or suspended cull runs
93920
+ // without it. One compute per shader and dispatch group, since a compute owns the uniform
93921
+ // buffer its dispatch reads and per-file sources dispatch once per file
93922
+ projectorShaders = new Map();
93923
+ projectorComputes = new Map();
93924
+ projectorBindGroupFormat = null;
93925
+ projectorSourceKey = '';
93926
+ args;
93927
+ argsBindGroupFormat;
93928
+ // order:bucket: bucket counts then offsets, the ordered slot list, and its two passes
93929
+ orderBuckets;
93930
+ orderedBuffer = null;
93931
+ orderScan;
93932
+ orderScatter;
93933
+ orderFormats = [];
93934
+ // the occlusion grid: farthest depth per 8 px block (level 1) and per 32 px block (level 2)
93935
+ occL1;
93936
+ occL2;
93937
+ occBlocks = { x1: 0, y1: 0, x2: 0, y2: 0 };
93938
+ reduceL1;
93939
+ reduceL2;
93940
+ reduceFormats = [];
93941
+ // the previous frame the grid and the reprojection describe; valid only when that frame
93942
+ // rendered to the same target at the same size from the same world state
93943
+ prevValid = false;
93944
+ prevViewProjection = new Mat4();
93945
+ prevView = new Mat4();
93946
+ prevProjection = new Mat4();
93947
+ prevClipZ = [0, 0, 0, 0];
93948
+ prevViewport = [0, 0];
93949
+ prevFocal = [0, 0];
93950
+ prevFlip = 1;
93951
+ prevWidth = 0;
93952
+ prevHeight = 0;
93953
+ prevVersion = -1;
93954
+ // the allocations resident when the previous frame drew, and whether any of them has gone
93955
+ // since: only a removed splat can make the previous depth wrong (it may have hidden what is
93956
+ // now behind it), so arrivals leave the cull on while a scene streams in
93957
+ residentAllocIds = new Set();
93958
+ nodesRemoved = false;
93959
+ prevOrtho = false;
93960
+ /** Whether the last frame ran the occlusion cull, for the debug panel and the harness. */
93961
+ culling = false;
93962
+ /** Whether cull:auto currently has the test switched off for culling too little. */
93963
+ get cullSuspended() {
93964
+ return this.variant.cull === 'auto' && (!this.cullActive || this.cullSuspendedFrames > 0);
93965
+ }
93966
+ // cull:auto bookkeeping. The last decision holds while a readback is in flight: while the
93967
+ // test is active every culled frame's counts are read back and a poor one suspends it;
93968
+ // while suspended the frames count down, then one probe frame runs the test and the rest
93969
+ // wait for its counts
93970
+ cullActive = true;
93971
+ cullSuspendedFrames = 0;
93972
+ cullStatsPending = false;
93973
+ /** Frames the test stays off after culling too little (cull:auto). */
93974
+ /**
93975
+ * Whether the projected cache for `splats` resident splats fits one storage binding on this
93976
+ * device. The cache reserves 25% over the resident count; adapters differ in the limit
93977
+ * (128 MiB is the WebGPU default), so a viewer checks before opting in.
93978
+ */
93979
+ static cacheFits(device, splats) {
93980
+ const limit = device.wgpu?.limits
93981
+ ?.maxStorageBufferBindingSize;
93982
+ return !limit || Math.ceil(splats * 1.25) * CACHE_WORDS * 4 <= limit;
93983
+ }
93984
+ static CULL_SUSPEND_FRAMES = 60;
93985
+ /** The culled fraction below which cull:auto suspends the test. */
93986
+ static CULL_MIN_FRACTION = 0.08;
93987
+ /**
93988
+ * Let a capture (query) frame cull against the previous on-screen frame when it renders at
93989
+ * the same size. Off by default: a query frame is not culled, since its cull thins what a
93990
+ * pick or a thumbnail should see. The harness turns it on to photograph culled frames.
93991
+ */
93992
+ allowQueryCull = false;
93993
+ // raster
93994
+ colorTexture;
93995
+ depthTexture;
93996
+ target;
93997
+ rasterMesh;
93998
+ rasterMaterial;
93999
+ rasterInstance;
94000
+ rasterPass;
94001
+ // taa: ping-pong history (premultiplied colour + coverage as unorm16, and the depth mean and
94002
+ // sample count packed in 32 bits; shaders/taa.ts), resolved by a fullscreen pass after the
94003
+ // raster. Sized with the target on the first accumulating frame, and shrunk back while taa is off
94004
+ taaColor = [];
94005
+ taaInfo = [];
94006
+ taaTargets = [];
94007
+ taaWrite = 0;
94008
+ taaMesh;
94009
+ taaMaterial;
94010
+ taaInstance;
94011
+ taaPass;
94012
+ // whether the history holds the previous on-screen frame at the current size
94013
+ taaHistoryValid = false;
94014
+ // the previous taa frame's matrices as the pass reads them, and this frame's, copied over
94015
+ // at the start of the next frame: the material holds the data arrays by reference and
94016
+ // uploads them when it draws, after this hook has run
94017
+ taaPrevViewProjection = new Mat4();
94018
+ taaPrevView = new Mat4();
94019
+ taaLastViewProjection = new Mat4();
94020
+ taaLastView = new Mat4();
94021
+ taaWidth = 0;
94022
+ taaHeight = 0;
94023
+ // the camera's world transform, for the accumulation's reprojection
94024
+ cameraWorld = new Mat4();
94025
+ // frames since the camera or the scene last changed, for converging at rest
94026
+ restFrames = 0;
94027
+ /** The frame the depth texture holds, null while it holds a capture's or nothing. */
94028
+ depthFrame = null;
94029
+ depthFrameCount = 0;
94030
+ depthFrameCamera = createPickCameraSnapshot();
94031
+ // a frame requested from inside the render: the engine clears app.renderNextFrame right
94032
+ // after render(), so the request is applied on frameend instead
94033
+ frameWanted = false;
94034
+ onFrameEnd = () => {
94035
+ if (this.frameWanted) {
94036
+ this.frameWanted = false;
94037
+ this.app.renderNextFrame = true;
94038
+ }
94039
+ };
94040
+ frameIndex = 0;
94041
+ // the seed the harness sets; the frame index replaces it while taa accumulates
94042
+ userSeed = 0;
94043
+ /** Whether the last frame ran the temporal accumulation, for the debug panel. */
94044
+ taaActive = false;
94045
+ /**
94046
+ * Let a capture (query) frame at the on-screen size run the accumulation over the on-screen
94047
+ * history, so the harness can photograph converged and moving frames. Off by default.
94048
+ */
94049
+ allowQueryTaa = false;
94050
+ // compose
94051
+ composeMesh;
94052
+ composeMaterial;
94053
+ composeInstance;
94054
+ frustum = new Frustum();
94055
+ sphere = new BoundingSphere();
94056
+ shaderProjection = new Mat4();
94057
+ viewProjection = new Mat4();
94058
+ frameSeed = 0;
94059
+ ready = false;
94060
+ /** Byte sizes of the buffers this renderer owns, for the bench harness and the debug panel. */
94061
+ /** The renderer's depth texture: the nearest surviving sample per pixel of `depthFrame`. */
94062
+ get frameDepthTexture() {
94063
+ return this.depthTexture;
94064
+ }
94065
+ get gpuBytes() {
94066
+ const buffers = [
94067
+ this.chunkBuffer,
94068
+ this.nodeVisibleBuffer,
94069
+ this.cacheBuffer,
94070
+ this.orderedBuffer,
94071
+ this.counter,
94072
+ this.orderBuckets,
94073
+ this.occL1,
94074
+ this.occL2
94075
+ ];
94076
+ let bytes = 0;
94077
+ for (const buffer of buffers)
94078
+ bytes += buffer?.byteSize ?? 0;
94079
+ bytes += this.colorTexture.gpuSize + this.depthTexture.gpuSize;
94080
+ for (const texture of [...this.taaColor, ...this.taaInfo])
94081
+ bytes += texture.gpuSize;
94082
+ return bytes + this.source.gpuBytes();
94083
+ }
94084
+ /**
94085
+ * The seed mixed into every coverage hash. 0 makes a still camera reproduce its frame;
94086
+ * the harness varies it to measure the sampling noise floor, and TAA will animate it.
94087
+ */
94088
+ get seed() {
94089
+ return this.frameSeed;
94090
+ }
94091
+ set seed(value) {
94092
+ this.userSeed = value >>> 0;
94093
+ this.frameSeed = this.userSeed;
94094
+ this.app.renderNextFrame = true;
94095
+ }
94096
+ /** The last projected frame's survivor count and occlusion-culled count, read back from the gpu. */
94097
+ async readStats() {
94098
+ // without a typed array the engine hands back bytes
94099
+ const data = new Uint32Array(2);
94100
+ await this.counter.read(0, 8, data, true);
94101
+ return { survivors: data[0], occluded: data[1] };
94102
+ }
94103
+ // reduce the previous frame's depth into the two grid levels
94104
+ reduceDepth(width, height) {
94105
+ const { device } = this;
94106
+ const x1 = Math.ceil(width / 8);
94107
+ const y1 = Math.ceil(height / 8);
94108
+ const x2 = Math.ceil(x1 / 4);
94109
+ const y2 = Math.ceil(y1 / 4);
94110
+ if (this.occBlocks.x1 !== x1 || this.occBlocks.y1 !== y1) {
94111
+ this.occL1.destroy();
94112
+ this.occL2.destroy();
94113
+ this.occL1 = new StorageBuffer(device, x1 * y1 * 4, BUFFERUSAGE_COPY_DST);
94114
+ this.occL2 = new StorageBuffer(device, x2 * y2 * 4, BUFFERUSAGE_COPY_DST);
94115
+ this.occBlocks = { x1, y1, x2, y2 };
94116
+ }
94117
+ const l1 = this.reduceL1;
94118
+ l1.setParameter('prevDepth', this.depthTexture);
94119
+ l1.setParameter('blockMax', this.occL1);
94120
+ l1.setParameter('width', width);
94121
+ l1.setParameter('height', height);
94122
+ l1.setParameter('blocksX', x1);
94123
+ l1.setParameter('blocksY', y1);
94124
+ l1.setupDispatch(x1, y1, 1);
94125
+ const l2 = this.reduceL2;
94126
+ l2.setParameter('level1', this.occL1);
94127
+ l2.setParameter('level2', this.occL2);
94128
+ l2.setParameter('blocksX1', x1);
94129
+ l2.setParameter('blocksY1', y1);
94130
+ l2.setParameter('blocksX2', x2);
94131
+ l2.setParameter('blocksY2', y2);
94132
+ Compute.calcDispatchSize(Math.ceil((x2 * y2) / 64), tmpVec2);
94133
+ l2.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
94134
+ device.computeDispatch([l1], 'sse-splat-reduce1');
94135
+ device.computeDispatch([l2], 'sse-splat-reduce2');
94136
+ }
94137
+ /** Survivors of the last frame's projection are only known to the gpu; this is the resident count. */
94138
+ activeSplats = 0;
94139
+ constructor(app, camera, worldLayer, options = {}) {
94140
+ this.app = app;
94141
+ this.device = app.graphicsDevice;
94142
+ this.camera = camera;
94143
+ this.worldLayer = worldLayer;
94144
+ this.variant = parseVariant(options.variant);
94145
+ const { device } = this;
94146
+ if (options.source === 'direct') {
94147
+ this.source = new DirectSplatSource(device);
94148
+ }
94149
+ else {
94150
+ if (options.source && options.source !== 'workbuffer') {
94151
+ console.warn(`StochasticSplatRenderer: splat source '${options.source}' is not implemented yet, using the work buffer`);
94152
+ }
94153
+ this.source = new WorkBufferSplatSource();
94154
+ }
94155
+ this.counter = new StorageBuffer(device, 16, BUFFERUSAGE_COPY_DST | BUFFERUSAGE_COPY_SRC);
94156
+ // indirect draw arguments
94157
+ this.argsBindGroupFormat = new BindGroupFormat(device, [
94158
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
94159
+ new BindStorageBufferFormat('indirectDrawArgs', SHADERSTAGE_COMPUTE),
94160
+ new BindStorageBufferFormat('indirectDispatchArgs', SHADERSTAGE_COMPUTE),
94161
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
94162
+ ]);
94163
+ this.args = new Compute(device, new Shader(device, {
94164
+ name: 'sse-splat-args',
94165
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94166
+ cshader: argsWGSL,
94167
+ computeUniformBufferFormats: {
94168
+ uniforms: new UniformBufferFormat(device, [
94169
+ new UniformFormat('drawSlot', UNIFORMTYPE_UINT),
94170
+ new UniformFormat('indexCount', UNIFORMTYPE_UINT),
94171
+ new UniformFormat('quadsPerInstance', UNIFORMTYPE_UINT),
94172
+ new UniformFormat('dispatchSlot', UNIFORMTYPE_UINT),
94173
+ new UniformFormat('scatterWorkgroupSize', UNIFORMTYPE_UINT)
94174
+ ])
94175
+ },
94176
+ computeBindGroupFormat: this.argsBindGroupFormat
94177
+ }), 'sse-splat-args');
94178
+ // the ordering passes
94179
+ this.orderBuckets = new StorageBuffer(device, 2 * ORDER_BUCKETS * 4, BUFFERUSAGE_COPY_DST);
94180
+ const scanFormat = new BindGroupFormat(device, [new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)]);
94181
+ const scatterFormat = new BindGroupFormat(device, [
94182
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE, true),
94183
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE, true),
94184
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE),
94185
+ new BindStorageBufferFormat('ordered', SHADERSTAGE_COMPUTE)
94186
+ ]);
94187
+ this.orderFormats = [scanFormat, scatterFormat];
94188
+ this.orderScan = new Compute(device, new Shader(device, {
94189
+ name: 'sse-splat-order-scan',
94190
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94191
+ cshader: orderScanWGSL,
94192
+ computeBindGroupFormat: scanFormat
94193
+ }), 'sse-splat-order-scan');
94194
+ this.orderScatter = new Compute(device, new Shader(device, {
94195
+ name: 'sse-splat-order-scatter',
94196
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94197
+ cshader: orderScatterWGSL,
94198
+ computeBindGroupFormat: scatterFormat
94199
+ }), 'sse-splat-order-scatter');
94200
+ // the occlusion grid and its two reduce passes
94201
+ this.occL1 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
94202
+ this.occL2 = new StorageBuffer(device, 4, BUFFERUSAGE_COPY_DST);
94203
+ const reduceL1Format = new BindGroupFormat(device, [
94204
+ new BindTextureFormat('prevDepth', SHADERSTAGE_COMPUTE, TEXTUREDIMENSION_2D, SAMPLETYPE_DEPTH, false),
94205
+ new BindStorageBufferFormat('blockMax', SHADERSTAGE_COMPUTE),
94206
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
94207
+ ]);
94208
+ const reduceL2Format = new BindGroupFormat(device, [
94209
+ new BindStorageBufferFormat('level1', SHADERSTAGE_COMPUTE, true),
94210
+ new BindStorageBufferFormat('level2', SHADERSTAGE_COMPUTE),
94211
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE)
94212
+ ]);
94213
+ this.reduceFormats = [reduceL1Format, reduceL2Format];
94214
+ this.reduceL1 = new Compute(device, new Shader(device, {
94215
+ name: 'sse-splat-reduce1',
94216
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94217
+ cshader: reduceL1WGSL,
94218
+ computeUniformBufferFormats: {
94219
+ uniforms: new UniformBufferFormat(device, [
94220
+ new UniformFormat('width', UNIFORMTYPE_UINT),
94221
+ new UniformFormat('height', UNIFORMTYPE_UINT),
94222
+ new UniformFormat('blocksX', UNIFORMTYPE_UINT),
94223
+ new UniformFormat('blocksY', UNIFORMTYPE_UINT)
94224
+ ])
94225
+ },
94226
+ computeBindGroupFormat: reduceL1Format
94227
+ }), 'sse-splat-reduce1');
94228
+ this.reduceL2 = new Compute(device, new Shader(device, {
94229
+ name: 'sse-splat-reduce2',
94230
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94231
+ cshader: reduceL2WGSL,
94232
+ computeUniformBufferFormats: {
94233
+ uniforms: new UniformBufferFormat(device, [
94234
+ new UniformFormat('blocksX1', UNIFORMTYPE_UINT),
94235
+ new UniformFormat('blocksY1', UNIFORMTYPE_UINT),
94236
+ new UniformFormat('blocksX2', UNIFORMTYPE_UINT),
94237
+ new UniformFormat('blocksY2', UNIFORMTYPE_UINT)
94238
+ ])
94239
+ },
94240
+ computeBindGroupFormat: reduceL2Format
94241
+ }), 'sse-splat-reduce2');
94242
+ // the raster target: colour, and a depth texture the compose, the occlusion cull and
94243
+ // (later) the picker read
94244
+ this.colorTexture = new Texture(device, {
94245
+ name: 'sse-splat-color',
94246
+ width: 4,
94247
+ height: 4,
94248
+ format: PIXELFORMAT_RGBA8,
94249
+ mipmaps: false,
94250
+ minFilter: FILTER_LINEAR,
94251
+ magFilter: FILTER_LINEAR,
94252
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94253
+ addressV: ADDRESS_CLAMP_TO_EDGE
94254
+ });
94255
+ this.depthTexture = new Texture(device, {
94256
+ name: 'sse-splat-depth',
94257
+ width: 4,
94258
+ height: 4,
94259
+ format: PIXELFORMAT_DEPTH,
94260
+ mipmaps: false,
94261
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94262
+ addressV: ADDRESS_CLAMP_TO_EDGE
94263
+ });
94264
+ this.target = new RenderTarget({
94265
+ name: 'sse-splat-target',
94266
+ colorBuffer: this.colorTexture,
94267
+ depthBuffer: this.depthTexture,
94268
+ samples: 1
94269
+ });
94270
+ this.rasterMesh = createQuadMesh(device, QUADS_PER_INSTANCE);
94271
+ this.rasterMaterial = new ShaderMaterial({
94272
+ uniqueName: 'sse-splat-raster',
94273
+ vertexWGSL: rasterVertexWGSL,
94274
+ fragmentWGSL: rasterFragmentWGSL,
94275
+ attributes: { vertex_position: SEMANTIC_POSITION }
94276
+ });
94277
+ this.rasterMaterial.blendType = BLEND_NONE;
94278
+ this.rasterMaterial.depthWrite = true;
94279
+ this.rasterMaterial.depthTest = true;
94280
+ this.rasterMaterial.cull = CULLFACE_NONE;
94281
+ // the forward renderer reads the instance's node for its cull setup and world transform
94282
+ this.rasterInstance = new MeshInstance(this.rasterMesh, this.rasterMaterial, new GraphNode('sse-splat-raster'));
94283
+ this.rasterInstance.cull = false;
94284
+ this.rasterInstance.castShadow = false;
94285
+ this.rasterInstance.receiveShadow = false;
94286
+ this.rasterPass = new SplatRasterPass(device, app.renderer, camera, [
94287
+ this.rasterInstance
94288
+ ]);
94289
+ this.rasterPass.init(this.target);
94290
+ this.rasterPass.setClearColor(new Color(0, 0, 0, 0));
94291
+ this.rasterPass.setClearDepth(1);
94292
+ // nothing to draw, and no buffers bound, until the first populated frame
94293
+ this.rasterPass.enabled = false;
94294
+ // the taa resolve: a fullscreen pass from the raster target and the previous history
94295
+ // into the other history, sized with the target on its first frame
94296
+ for (let i = 0; i < 2; i++) {
94297
+ this.taaColor.push(new Texture(device, {
94298
+ name: `sse-splat-taa-color-${i}`,
94299
+ width: 4,
94300
+ height: 4,
94301
+ format: PIXELFORMAT_RGBA16U,
94302
+ mipmaps: false,
94303
+ minFilter: FILTER_NEAREST,
94304
+ magFilter: FILTER_NEAREST,
94305
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94306
+ addressV: ADDRESS_CLAMP_TO_EDGE
94307
+ }));
94308
+ this.taaInfo.push(new Texture(device, {
94309
+ name: `sse-splat-taa-info-${i}`,
94310
+ width: 4,
94311
+ height: 4,
94312
+ format: PIXELFORMAT_R32U,
94313
+ mipmaps: false,
94314
+ minFilter: FILTER_NEAREST,
94315
+ magFilter: FILTER_NEAREST,
94316
+ addressU: ADDRESS_CLAMP_TO_EDGE,
94317
+ addressV: ADDRESS_CLAMP_TO_EDGE
94318
+ }));
94319
+ this.taaTargets.push(new RenderTarget({
94320
+ name: `sse-splat-taa-${i}`,
94321
+ colorBuffers: [this.taaColor[i], this.taaInfo[i]],
94322
+ depth: false,
94323
+ samples: 1
94324
+ }));
94325
+ }
94326
+ this.taaMesh = createFullscreenMesh(device);
94327
+ this.taaMaterial = new ShaderMaterial({
94328
+ uniqueName: 'sse-splat-taa',
94329
+ vertexWGSL: taaVertexWGSL,
94330
+ fragmentWGSL: taaFragmentWGSL,
94331
+ attributes: { vertex_position: SEMANTIC_POSITION },
94332
+ fragmentOutputTypes: ['uvec4', 'uint']
94333
+ });
94334
+ this.taaMaterial.blendType = BLEND_NONE;
94335
+ this.taaMaterial.depthWrite = false;
94336
+ this.taaMaterial.depthTest = false;
94337
+ this.taaMaterial.cull = CULLFACE_NONE;
94338
+ this.taaInstance = new MeshInstance(this.taaMesh, this.taaMaterial, new GraphNode('sse-splat-taa'));
94339
+ this.taaInstance.cull = false;
94340
+ this.taaInstance.castShadow = false;
94341
+ this.taaInstance.receiveShadow = false;
94342
+ this.taaPass = new SplatRasterPass(device, app.renderer, camera, [this.taaInstance], 'sse-splat-taa');
94343
+ this.taaPass.init(this.taaTargets[0]);
94344
+ this.taaPass.enabled = false;
94345
+ // the compose quad, blended over the skybox and opaque meshes with the splat depth
94346
+ this.composeMesh = createFullscreenMesh(device);
94347
+ this.composeMaterial = new ShaderMaterial({
94348
+ uniqueName: 'sse-splat-compose',
94349
+ vertexWGSL: composeVertexWGSL,
94350
+ fragmentWGSL: composeFragmentWGSL,
94351
+ attributes: { vertex_position: SEMANTIC_POSITION }
94352
+ });
94353
+ this.composeMaterial.blendType = BLEND_PREMULTIPLIED;
94354
+ this.composeMaterial.depthWrite = true;
94355
+ this.composeMaterial.depthTest = true;
94356
+ this.composeMaterial.cull = CULLFACE_NONE;
94357
+ this.composeMaterial.setParameter('splatColor', this.colorTexture);
94358
+ this.composeMaterial.setParameter('splatDepth', this.depthTexture);
94359
+ // always bound, even while taa is off: a declared texture without a value makes the
94360
+ // engine create and upload a placeholder inside the forward pass, which submits the
94361
+ // command buffer mid-pass on WebGPU
94362
+ this.composeMaterial.setParameter('taaColor', this.taaColor[0]);
94363
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[0]);
94364
+ this.composeInstance = new MeshInstance(this.composeMesh, this.composeMaterial, new GraphNode('sse-splat-compose'));
94365
+ this.composeInstance.cull = false;
94366
+ this.composeInstance.castShadow = false;
94367
+ this.composeInstance.receiveShadow = false;
94368
+ // the picker pass draws every pickable instance of the layer into a target without a
94369
+ // depth attachment; this shader writes frag_depth, which makes that pipeline invalid
94370
+ // and drops the whole submit, the frame's command buffer included
94371
+ this.composeInstance.pick = false;
94372
+ // first among the transparents, whichever way the layer sorts them
94373
+ this.composeInstance.drawOrder = -1e3;
94374
+ this.composeInstance.calculateSortDistance = () => Number.MAX_VALUE;
94375
+ this.applyVariant();
94376
+ this.provider = new EngineResidentSetProvider(app, camera, worldLayer);
94377
+ this.unsubscribe = this.provider.onFrame((set, changed, manager) => this.frame(set, changed, manager));
94378
+ app.on('frameend', this.onFrameEnd);
94379
+ this.attach();
94380
+ }
94381
+ /** Switch the renderer off and hand the splats back to the engine's renderer (XR), or on again. */
94382
+ setEnabled(value) {
94383
+ if (this.enabled === value)
94384
+ return;
94385
+ this.enabled = value;
94386
+ if (value) {
94387
+ this.attach();
94388
+ }
94389
+ else {
94390
+ this.detach();
94391
+ }
94392
+ this.app.renderNextFrame = true;
94393
+ }
94394
+ /** Replace the experiment switches from a `key:value,key:value` string (unset keys reset). */
94395
+ setVariant(text) {
94396
+ Object.assign(this.variant, parseVariant(text));
94397
+ // the cull decides afresh under new switches
94398
+ this.cullActive = true;
94399
+ this.cullSuspendedFrames = 0;
94400
+ this.applyVariant();
94401
+ }
94402
+ /**
94403
+ * Drop the temporal history; the next frame starts accumulating from its own sample. The
94404
+ * coverage seeds restart too, so a variant accumulates the same samples every time (the
94405
+ * harness compares builds image for image).
94406
+ */
94407
+ resetHistory() {
94408
+ this.taaHistoryValid = false;
94409
+ this.restFrames = 0;
94410
+ this.frameIndex = 0;
94411
+ }
94412
+ /** Re-read {@link variant} after a field changed. */
94413
+ applyVariant() {
94414
+ // a switch changes what the frames hold; an old history would leak into the new ones
94415
+ this.resetHistory();
94416
+ const quad = this.variant.spp === 'quad';
94417
+ this.rasterMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
94418
+ this.rasterMaterial.setDefine('SSE_ORDERED', this.variant.order === 'bucket' ? '' : undefined);
94419
+ this.rasterMaterial.setDefine('SSE_POPLESS', this.variant.popless === 'on' ? '' : undefined);
94420
+ this.composeMaterial.setDefine('SSE_SHOW_DEPTH', this.variant.compose === 'depth' ? '' : undefined);
94421
+ this.composeMaterial.setDefine('SSE_SPP_QUAD', quad ? '' : undefined);
94422
+ this.rasterMaterial.update();
94423
+ this.composeMaterial.update();
94424
+ this.setReady(this.ready);
94425
+ this.app.renderNextFrame = true;
94426
+ }
94427
+ // the raster pass and the compose only run once a frame has bound the buffers they read
94428
+ setReady(value) {
94429
+ this.ready = value;
94430
+ this.rasterPass.enabled = value;
94431
+ this.composeInstance.visible = value && this.variant.compose !== 'none';
94432
+ }
94433
+ attach() {
94434
+ const passes = this.camera.camera.beforePasses;
94435
+ if (!passes.includes(this.rasterPass))
94436
+ passes.push(this.rasterPass);
94437
+ if (!passes.includes(this.taaPass))
94438
+ passes.push(this.taaPass);
94439
+ this.worldLayer.addMeshInstances([this.composeInstance]);
94440
+ this.provider.setActive(true);
94441
+ }
94442
+ detach() {
94443
+ const passes = this.camera.camera.beforePasses;
94444
+ for (const pass of [this.rasterPass, this.taaPass]) {
94445
+ const index = passes.indexOf(pass);
94446
+ if (index >= 0)
94447
+ passes.splice(index, 1);
94448
+ }
94449
+ this.resetHistory();
94450
+ this.depthFrame = null;
94451
+ this.worldLayer.removeMeshInstances([this.composeInstance]);
94452
+ this.provider.setActive(false);
94453
+ }
94454
+ frame(set, changed, manager) {
94455
+ if (!this.enabled)
94456
+ return;
94457
+ const { device, camera } = this;
94458
+ const cam = camera.camera;
94459
+ this.nodesRemoved = false;
94460
+ if (changed || this.set !== set) {
94461
+ const ids = new Set(set.nodes.map((node) => node.allocId));
94462
+ for (const id of this.residentAllocIds) {
94463
+ if (!ids.has(id)) {
94464
+ this.nodesRemoved = true;
94465
+ break;
94466
+ }
94467
+ }
94468
+ this.residentAllocIds = ids;
94469
+ this.source.update(set, manager);
94470
+ this.rebuildChunkTable(set);
94471
+ this.ensureCache(set.activeSplats);
94472
+ this.activeSplats = set.activeSplats;
94473
+ this.pruneProjectorComputes(set);
94474
+ // recorded last, so a rebuild that throws is retried next frame
94475
+ this.set = set;
94476
+ }
94477
+ if (this.numChunks === 0) {
94478
+ // nothing resident: draw nothing
94479
+ this.setReady(false);
94480
+ return;
94481
+ }
94482
+ // the target follows whatever the camera renders into this frame: the backbuffer, or a
94483
+ // capture's render target at another size
94484
+ const rt = camera.renderTarget;
94485
+ const width = rt ? rt.width : device.width;
94486
+ const height = rt ? rt.height : device.height;
94487
+ if (this.target.width !== width || this.target.height !== height) {
94488
+ this.target.resize(width, height);
94489
+ }
94490
+ const view = cam.viewMatrix;
94491
+ const projection = cam.projectionMatrix;
94492
+ const isOrtho = cam.projection === PROJECTION_ORTHOGRAPHIC;
94493
+ // the clip z the raster shader reconstructs must match the engine's WebGPU depth range
94494
+ const shaderProjection = Camera$1.applyShaderProjectionTransform(projection, this.shaderProjection, false, true);
94495
+ this.viewProjection.mul2(shaderProjection, view);
94496
+ // The splats' own depth: clip z = a * depth + b (over w = depth for a perspective
94497
+ // camera). The camera's far plane is fitted to the scene bound, which can leave a sky
94498
+ // outside it, and splats clamped there share one depth and lose their order; so a
94499
+ // perspective raster puts its far plane at infinity (z = 1 - near / depth), with the same
94500
+ // near plane and, near where precision matters, the same resolution. The compose converts
94501
+ // back to the camera's depth where the splats meet the rest of the scene. An orthographic
94502
+ // camera keeps its own mapping: a linear depth has no far plane at infinity.
94503
+ const cameraClipZ = [-shaderProjection.data[10], shaderProjection.data[14]];
94504
+ const clipZ = isOrtho ? cameraClipZ : [1, cameraClipZ[1] / cameraClipZ[0]];
94505
+ const clipZParams = [clipZ[0], clipZ[1], isOrtho ? 1 : 0, 0];
94506
+ this.cullNodes(set, this.viewProjection);
94507
+ const focal = [Math.abs(projection.data[0]) * width * 0.5, Math.abs(projection.data[5]) * height * 0.5];
94508
+ const gsplat = this.app.scene.gsplat;
94509
+ // the moving-camera contribution cull: a raised threshold while the view changes, then
94510
+ // one more frame at the scene's threshold once it has stopped
94511
+ const moved = this.viewMoved(view, projection);
94512
+ const raised = moved && this.variant.contribution > 0;
94513
+ const minContribution = raised
94514
+ ? Math.max(gsplat.minContribution, this.variant.contribution)
94515
+ : gsplat.minContribution;
94516
+ if (raised)
94517
+ this.frameWanted = true;
94518
+ // Temporal accumulation runs on on-screen frames (and, for the harness, on a capture at
94519
+ // the same size); the history is only trusted when it holds the previous such frame at
94520
+ // this size. While it runs the coverage seed changes every frame, and a resting camera
94521
+ // keeps requesting frames until the history has filled its cap
94522
+ const isQuery = !!rt;
94523
+ const taaOn = this.variant.taa === 'on' &&
94524
+ (!isQuery || (this.allowQueryTaa && width === this.taaWidth && height === this.taaHeight));
94525
+ if (taaOn) {
94526
+ if (this.taaWidth !== width || this.taaHeight !== height) {
94527
+ this.resizeHistory(width, height);
94528
+ this.taaWidth = width;
94529
+ this.taaHeight = height;
94530
+ this.taaHistoryValid = false;
94531
+ this.restFrames = 0;
94532
+ }
94533
+ this.frameSeed = this.frameIndex++ >>> 0;
94534
+ if (moved || changed)
94535
+ this.restFrames = 0;
94536
+ else
94537
+ this.restFrames++;
94538
+ if (this.restFrames < this.variant.taaMax + 2)
94539
+ this.frameWanted = true;
94540
+ }
94541
+ else {
94542
+ this.frameSeed = this.userSeed;
94543
+ // a capture at another size does not accumulate; the next on-screen frame starts over
94544
+ this.taaHistoryValid = false;
94545
+ this.restFrames = 0;
94546
+ // switched off: the history goes back to its placeholder size until it is wanted
94547
+ if (this.variant.taa === 'off' && this.taaWidth !== 0) {
94548
+ this.resizeHistory(4, 4);
94549
+ this.taaWidth = 0;
94550
+ this.taaHeight = 0;
94551
+ }
94552
+ }
94553
+ this.taaActive = taaOn;
94554
+ // The occlusion cull reads the depth texture as the previous frame left it, so it needs
94555
+ // that frame to have drawn to this target at this size (a resize loses the texture, a
94556
+ // capture draws elsewhere), with no splat removed since (its depth would hide what is
94557
+ // now behind it; arrivals are safe) and the same projection type. A capture frame is
94558
+ // never culled and never becomes the previous frame.
94559
+ // a new world state can change what is occluded: try the test again
94560
+ if (this.prevVersion !== set.version) {
94561
+ this.cullSuspendedFrames = 0;
94562
+ this.cullActive = true;
94563
+ }
94564
+ const cullMode = this.variant.cull;
94565
+ let wanted = cullMode !== 'off';
94566
+ let probe = false;
94567
+ if (cullMode === 'auto' && !isQuery) {
94568
+ if (this.cullSuspendedFrames > 0) {
94569
+ // a moving camera changes what is occluded, so the probe comes sooner
94570
+ const moved = this.viewMoved(view, projection);
94571
+ this.cullSuspendedFrames = Math.max(0, this.cullSuspendedFrames - (moved ? 4 : 1));
94572
+ wanted = false;
94573
+ }
94574
+ else if (!this.cullActive) {
94575
+ // suspended and due: one probe frame, then wait for its counts
94576
+ probe = !this.cullStatsPending;
94577
+ wanted = probe;
94578
+ }
94579
+ }
94580
+ const culling = wanted &&
94581
+ (!isQuery || this.allowQueryCull) &&
94582
+ this.prevValid &&
94583
+ this.prevWidth === width &&
94584
+ this.prevHeight === height &&
94585
+ !this.nodesRemoved &&
94586
+ this.prevOrtho === isOrtho;
94587
+ this.culling = culling;
94588
+ if (culling) {
94589
+ this.reduceDepth(width, height);
94590
+ }
94591
+ this.counter.clear();
94592
+ const ordered = this.variant.order === 'bucket';
94593
+ if (ordered)
94594
+ this.orderBuckets.clear();
94595
+ // the order key spans the fitted clip range, log-spaced
94596
+ const logNear = Math.log(Math.max(cam.nearClip, 1e-6));
94597
+ const invLogRange = 1 / Math.max(Math.log(Math.max(cam.farClip, 1e-6)) - logNear, 1e-6);
94598
+ // the view depths where the raster's clip z reaches 0 and its far clamp (FAR_CLIP_Z), from
94599
+ // clip z = a * depth + b (over w = depth for a perspective camera)
94600
+ const [clipA, clipB] = clipZ;
94601
+ const depthNear = -clipB / clipA;
94602
+ const depthFar = isOrtho ? (FAR_CLIP_Z - clipB) / clipA : clipB / (FAR_CLIP_Z - clipA);
94603
+ const cameraPosition = camera.entity.getPosition();
94604
+ const groups = this.source.dispatchPlan(set, this.numChunks);
94605
+ for (const group of groups) {
94606
+ // a file with no node in the frustum has nothing to dispatch
94607
+ if (group.fileIndex >= 0 && !this.anyNodeVisible(set.files[group.fileIndex].nodes))
94608
+ continue;
94609
+ const projector = this.ensureProjector(culling, ordered, group);
94610
+ this.source.bind(projector, group, set);
94611
+ projector.setParameter('chunks', this.chunkBuffer);
94612
+ projector.setParameter('nodeVisible', this.nodeVisibleBuffer);
94613
+ projector.setParameter('cache', this.cacheBuffer);
94614
+ projector.setParameter('counter', this.counter);
94615
+ projector.setParameter('occL1', this.occL1);
94616
+ projector.setParameter('occL2', this.occL2);
94617
+ projector.setParameter('buckets', this.orderBuckets);
94618
+ projector.setParameter('view', view.data);
94619
+ projector.setParameter('viewProj', this.viewProjection.data);
94620
+ projector.setParameter('prevViewProj', this.prevViewProjection.data);
94621
+ projector.setParameter('prevView', this.prevView.data);
94622
+ projector.setParameter('prevClipZ', this.prevClipZ);
94623
+ projector.setParameter('viewport', [width, height]);
94624
+ projector.setParameter('focal', focal);
94625
+ projector.setParameter('prevViewport', this.prevViewport);
94626
+ projector.setParameter('prevFocal', this.prevFocal);
94627
+ projector.setParameter('numChunks', group.chunkCount);
94628
+ projector.setParameter('chunkBase', group.chunkBase);
94629
+ projector.setParameter('cameraPosition', [cameraPosition.x, cameraPosition.y, cameraPosition.z, 0]);
94630
+ projector.setParameter('splatTextureSize', this.source.textureSize(group));
94631
+ projector.setParameter('isOrtho', isOrtho ? 1 : 0);
94632
+ projector.setParameter('minPixelSize', gsplat.minPixelSize);
94633
+ projector.setParameter('alphaClip', gsplat.alphaClipForward);
94634
+ projector.setParameter('minContribution', minContribution);
94635
+ projector.setParameter('colorMax', this.variant.colorMax);
94636
+ projector.setParameter('unitScale', this.variant.units === 'engine' ? 2 : 1);
94637
+ projector.setParameter('occBlocksX1', this.occBlocks.x1);
94638
+ projector.setParameter('occBlocksY1', this.occBlocks.y1);
94639
+ projector.setParameter('occBlocksX2', this.occBlocks.x2);
94640
+ projector.setParameter('occBlocksY2', this.occBlocks.y2);
94641
+ projector.setParameter('occlusionMode', culling ? (cullMode === 'l1' ? 1 : 2) : 0);
94642
+ projector.setParameter('prevFlip', this.prevFlip);
94643
+ projector.setParameter('keyLogNear', logNear);
94644
+ projector.setParameter('keyInvLogRange', invLogRange);
94645
+ projector.setParameter('depthNear', depthNear);
94646
+ projector.setParameter('depthFar', depthFar);
94647
+ Compute.calcDispatchSize(group.chunkCount, tmpVec2);
94648
+ projector.setupDispatch(tmpVec2.x, tmpVec2.y, 1);
94649
+ device.computeDispatch([projector], 'sse-splat-project');
94650
+ }
94651
+ // indirect draw arguments for the raster and dispatch size for the scatter; slots are
94652
+ // per frame
94653
+ const drawSlot = device.getIndirectDrawSlot(1);
94654
+ const dispatchSlot = device.getIndirectDispatchSlot(1);
94655
+ this.args.setParameter('counter', this.counter);
94656
+ this.args.setParameter('indirectDrawArgs', device.indirectDrawBuffer);
94657
+ this.args.setParameter('indirectDispatchArgs', device.indirectDispatchBuffer);
94658
+ this.args.setParameter('drawSlot', drawSlot);
94659
+ this.args.setParameter('indexCount', QUADS_PER_INSTANCE * 6);
94660
+ this.args.setParameter('quadsPerInstance', QUADS_PER_INSTANCE);
94661
+ this.args.setParameter('dispatchSlot', dispatchSlot);
94662
+ this.args.setParameter('scatterWorkgroupSize', ORDER_BUCKETS);
94663
+ this.args.setupDispatch(1, 1, 1);
94664
+ device.computeDispatch([this.args], 'sse-splat-args');
94665
+ this.rasterInstance.setIndirect(null, drawSlot, 1);
94666
+ if (ordered) {
94667
+ // bucket offsets, then every survivor claims its place in its bucket
94668
+ this.orderScan.setParameter('buckets', this.orderBuckets);
94669
+ this.orderScan.setupDispatch(1, 1, 1);
94670
+ device.computeDispatch([this.orderScan], 'sse-splat-order-scan');
94671
+ const scatter = this.orderScatter;
94672
+ scatter.setParameter('counter', this.counter);
94673
+ scatter.setParameter('cache', this.cacheBuffer);
94674
+ scatter.setParameter('buckets', this.orderBuckets);
94675
+ scatter.setParameter('ordered', this.orderedBuffer);
94676
+ scatter.setupIndirectDispatch(dispatchSlot);
94677
+ device.computeDispatch([scatter], 'sse-splat-order-scatter');
94678
+ }
94679
+ const material = this.rasterMaterial;
94680
+ material.setParameter('splatCache', this.cacheBuffer);
94681
+ material.setParameter('splatCount', this.counter);
94682
+ if (ordered)
94683
+ material.setParameter('orderedSlots', this.orderedBuffer);
94684
+ material.setParameter('viewportSize', [width, height, 2 / width, 2 / height]);
94685
+ material.setParameter('clipZParams', clipZParams);
94686
+ material.setParameter('focalParams', [focal[0], focal[1], 0, 0]);
94687
+ material.setParameter('sseAlphaClip', gsplat.alphaClipForward);
94688
+ material.setParameter('frameSeed', this.frameSeed);
94689
+ this.taaPass.enabled = taaOn;
94690
+ if (taaOn) {
94691
+ const read = this.taaWrite ^ 1;
94692
+ const taa = this.taaMaterial;
94693
+ this.taaPrevViewProjection.copy(this.taaLastViewProjection);
94694
+ this.taaPrevView.copy(this.taaLastView);
94695
+ this.cameraWorld.copy(view).invert();
94696
+ taa.setParameter('curColor', this.colorTexture);
94697
+ taa.setParameter('curDepth', this.depthTexture);
94698
+ taa.setParameter('histColor', this.taaColor[read]);
94699
+ taa.setParameter('histInfo', this.taaInfo[read]);
94700
+ taa.setParameter('cameraWorld', this.cameraWorld.data);
94701
+ // x_ndc = (m00 x + m02 z) / -z for a perspective camera, m00 x + m03 for an orthographic one
94702
+ const sp = shaderProjection.data;
94703
+ taa.setParameter('unproject', isOrtho ? [sp[0], sp[5], sp[12], sp[13]] : [sp[0], sp[5], sp[8], sp[9]]);
94704
+ taa.setParameter('prevViewProj', this.taaPrevViewProjection.data);
94705
+ taa.setParameter('prevView', this.taaPrevView.data);
94706
+ taa.setParameter('clipZParams', clipZParams);
94707
+ // a changed resident set (detail streamed in) keeps the history but caps its weight,
94708
+ // so the new content shows within taaMoveMax frames rather than 1 / taaMax a frame
94709
+ taa.setParameter('taaParams', [
94710
+ moved || changed ? this.variant.taaMoveMax : this.variant.taaMax,
94711
+ this.taaHistoryValid ? 1 : 0,
94712
+ moved ? 1 : 0,
94713
+ this.restFrames
94714
+ ]);
94715
+ taa.setParameter('taaViewport', [width, height, 1 / width, 1 / height]);
94716
+ taa.setParameter('taaControl', [
94717
+ this.variant.taaFlip || (this.target.flipY ? -1 : 1),
94718
+ this.variant.taaClip,
94719
+ this.variant.spp === 'quad' ? 1 : 0,
94720
+ 0
94721
+ ]);
94722
+ taa.setParameter('taaDebug', this.variant.taaDebug);
94723
+ taa.setParameter('taaFilter', [
94724
+ this.variant.taaFilter === 'cubic' ? 1 : 0,
94725
+ this.variant.taaReproj === 'history' ? 1 : 0,
94726
+ this.variant.taaMotion,
94727
+ 0
94728
+ ]);
94729
+ this.taaPass.renderTarget = this.taaTargets[this.taaWrite];
94730
+ this.composeMaterial.setParameter('taaColor', this.taaColor[this.taaWrite]);
94731
+ this.composeMaterial.setParameter('taaInfo', this.taaInfo[this.taaWrite]);
94732
+ this.taaLastViewProjection.copy(this.viewProjection);
94733
+ this.taaLastView.copy(view);
94734
+ this.taaHistoryValid = true;
94735
+ this.taaWrite ^= 1;
94736
+ }
94737
+ // an offscreen target's rows run the other way to the backbuffer's on WebGPU
94738
+ const targetFlipY = rt ? rt.flipY : device.backBuffer.flipY;
94739
+ this.composeMaterial.setParameter('composeParams', [
94740
+ this.target.flipY !== targetFlipY ? 1 : 0,
94741
+ isOrtho ? 1 : 0,
94742
+ taaOn ? 1 : 0,
94743
+ 0
94744
+ ]);
94745
+ this.composeMaterial.setParameter('depthViewParams', [
94746
+ clipZ[0],
94747
+ clipZ[1],
94748
+ Math.max(cam.nearClip, 1e-4),
94749
+ Math.max(cam.farClip, cam.nearClip * 2)
94750
+ ]);
94751
+ this.composeMaterial.setParameter('cameraClipZ', [cameraClipZ[0], cameraClipZ[1], isOrtho ? 1 : 0, 0]);
94752
+ // cull:auto: read this culled frame's counts back (asynchronously, off the frame) and
94753
+ // keep the test only while it removes enough to pay for itself
94754
+ if (culling && cullMode === 'auto' && !isQuery && !this.cullStatsPending) {
94755
+ this.cullStatsPending = true;
94756
+ const data = new Uint32Array(2);
94757
+ this.counter
94758
+ .read(0, 8, data, false)
94759
+ .then(() => {
94760
+ const total = data[0] + data[1];
94761
+ const worthwhile = total > 0 && data[1] / total >= StochasticSplatRenderer.CULL_MIN_FRACTION;
94762
+ this.cullActive = worthwhile;
94763
+ if (!worthwhile)
94764
+ this.cullSuspendedFrames = StochasticSplatRenderer.CULL_SUSPEND_FRAMES;
94765
+ })
94766
+ .catch(() => {
94767
+ // a lost device or a destroyed buffer; the next frame tries again
94768
+ })
94769
+ .finally(() => {
94770
+ this.cullStatsPending = false;
94771
+ });
94772
+ }
94773
+ // this frame becomes the previous one, unless it is a capture
94774
+ if (isQuery) {
94775
+ // the capture drew elsewhere; the on-screen depth texture is no longer this frame's
94776
+ this.prevValid = false;
94777
+ this.depthFrame = null;
94778
+ this.setReady(true);
94779
+ return;
94780
+ }
94781
+ captureCameraSnapshot(camera.entity, this.depthFrameCamera);
94782
+ this.depthFrame = {
94783
+ id: ++this.depthFrameCount,
94784
+ camera: this.depthFrameCamera,
94785
+ width,
94786
+ height,
94787
+ clipZ: [clipZ[0], clipZ[1]]
94788
+ };
94789
+ this.prevViewProjection.copy(this.viewProjection);
94790
+ this.prevView.copy(view);
94791
+ this.prevProjection.copy(projection);
94792
+ this.prevClipZ = clipZParams;
94793
+ this.prevViewport = [width, height];
94794
+ this.prevFocal = focal;
94795
+ this.prevFlip = this.target.flipY ? -1 : 1;
94796
+ this.prevWidth = width;
94797
+ this.prevHeight = height;
94798
+ this.prevVersion = set.version;
94799
+ this.prevOrtho = isOrtho;
94800
+ this.prevValid = !isQuery;
94801
+ this.setReady(true);
94802
+ }
94803
+ resizeHistory(width, height) {
94804
+ for (const texture of [...this.taaColor, ...this.taaInfo])
94805
+ texture.resize(width, height);
94806
+ for (const target of this.taaTargets)
94807
+ target.resize(width, height);
94808
+ }
94809
+ // whether the view or the projection differs from the previous on-screen frame's beyond
94810
+ // float noise (the camera controllers settle over many frames; a fov animation moves the
94811
+ // image without moving the camera)
94812
+ viewMoved(view, projection) {
94813
+ for (let i = 0; i < 16; i++) {
94814
+ if (Math.abs(view.data[i] - this.prevView.data[i]) > 1e-6)
94815
+ return true;
94816
+ if (Math.abs(projection.data[i] - this.prevProjection.data[i]) > 1e-6)
94817
+ return true;
94818
+ }
94819
+ return false;
94820
+ }
94821
+ // one chunk-table entry per CHUNK_SIZE splats of every resident node
94822
+ rebuildChunkTable(set) {
94823
+ let count = 0;
94824
+ for (const node of set.nodes)
94825
+ count += Math.ceil(node.count / CHUNK_SIZE);
94826
+ if (this.chunkData.length < count * 4) {
94827
+ this.chunkData = new Uint32Array(Math.ceil(count * 1.25) * 4);
94828
+ this.chunkBuffer?.destroy();
94829
+ this.chunkBuffer = new StorageBuffer(this.device, this.chunkData.byteLength, BUFFERUSAGE_COPY_DST);
94830
+ }
94831
+ const data = this.chunkData;
94832
+ let k = 0;
94833
+ set.nodes.forEach((node, nodeIndex) => {
94834
+ const base = this.source.chunkBase(node);
94835
+ for (let offset = 0; offset < node.count; offset += CHUNK_SIZE) {
94836
+ data[k++] = base + offset;
94837
+ data[k++] = Math.min(CHUNK_SIZE, node.count - offset);
94838
+ data[k++] = nodeIndex;
94839
+ data[k++] = (node.lodIndex & 0xffff) | (node.fileIndex << 16);
94840
+ }
94841
+ });
94842
+ this.numChunks = count;
94843
+ // writeBuffer counts typed-array elements, not bytes
94844
+ if (count > 0)
94845
+ this.chunkBuffer.write(0, data, 0, count * 4);
94846
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
94847
+ if (this.nodeVisibleData.length < words) {
94848
+ this.nodeVisibleData = new Uint32Array(words);
94849
+ this.nodeVisibleBuffer?.destroy();
94850
+ this.nodeVisibleBuffer = new StorageBuffer(this.device, words * 4, BUFFERUSAGE_COPY_DST);
94851
+ }
94852
+ }
94853
+ // the cache is dense (indexed by compact slot), so it only needs room for the resident
94854
+ // splats, not the allocator's address space; grown geometrically, never shrunk
94855
+ ensureCache(splats) {
94856
+ if (splats <= this.cacheSlots)
94857
+ return;
94858
+ this.cacheBuffer?.destroy();
94859
+ this.orderedBuffer?.destroy();
94860
+ this.cacheSlots = Math.max(1, Math.ceil(splats * 1.25));
94861
+ this.cacheBuffer = new StorageBuffer(this.device, this.cacheSlots * CACHE_WORDS * 4, BUFFERUSAGE_COPY_SRC);
94862
+ this.orderedBuffer = new StorageBuffer(this.device, this.cacheSlots * 4);
94863
+ }
94864
+ // sphere-frustum test per node on the cpu: thousands of nodes, one bit each
94865
+ cullNodes(set, viewProjection) {
94866
+ const bits = this.nodeVisibleData;
94867
+ bits.fill(0);
94868
+ this.frustum.setFromMat4(viewProjection);
94869
+ const spheres = set.nodeSpheres;
94870
+ const { sphere } = this;
94871
+ for (let i = 0; i < set.nodes.length; i++) {
94872
+ sphere.center.set(spheres[i * 4], spheres[i * 4 + 1], spheres[i * 4 + 2]);
94873
+ sphere.radius = spheres[i * 4 + 3];
94874
+ if (this.frustum.containsSphere(sphere) !== 0) {
94875
+ bits[i >> 5] |= 1 << (i & 31);
94876
+ }
94877
+ }
94878
+ const words = Math.max(1, Math.ceil(set.nodes.length / 32));
94879
+ this.nodeVisibleBuffer.write(0, bits, 0, words);
94880
+ }
94881
+ anyNodeVisible(nodes) {
94882
+ const bits = this.nodeVisibleData;
94883
+ return nodes.some((node) => (bits[node.nodeIndex >> 5] >>> (node.nodeIndex & 31)) & 1);
94884
+ }
94885
+ ensureProjector(occlusion, ordered, group) {
94886
+ const sourceKey = this.source.shaderKey();
94887
+ if (this.projectorSourceKey !== sourceKey) {
94888
+ // a different source: every specialisation and the bind group format go
94889
+ this.destroyProjector();
94890
+ this.projectorSourceKey = sourceKey;
94891
+ }
94892
+ const key = `${occlusion ? 'occlusion' : 'plain'}-${ordered ? 'bucket' : 'append'}`;
94893
+ const computeKey = `${key}:${group.fileIndex}`;
94894
+ const existing = this.projectorComputes.get(computeKey);
94895
+ if (existing)
94896
+ return existing;
94897
+ const shader = this.ensureProjectorShader(key, occlusion, ordered);
94898
+ const compute = new Compute(this.device, shader, 'sse-splat-project');
94899
+ this.projectorComputes.set(computeKey, compute);
94900
+ return compute;
94901
+ }
94902
+ // drop the computes of files that left the resident set
94903
+ pruneProjectorComputes(set) {
94904
+ for (const [key, compute] of this.projectorComputes) {
94905
+ const fileIndex = Number(key.slice(key.lastIndexOf(':') + 1));
94906
+ if (fileIndex >= 0 && !set.files[fileIndex]) {
94907
+ compute.destroy();
94908
+ this.projectorComputes.delete(key);
94909
+ }
94910
+ }
94911
+ }
94912
+ ensureProjectorShader(key, occlusion, ordered) {
94913
+ const existing = this.projectorShaders.get(key);
94914
+ if (existing)
94915
+ return existing;
94916
+ const { device } = this;
94917
+ const fixed = [
94918
+ new BindStorageBufferFormat('chunks', SHADERSTAGE_COMPUTE, true),
94919
+ new BindStorageBufferFormat('nodeVisible', SHADERSTAGE_COMPUTE, true),
94920
+ new BindStorageBufferFormat('cache', SHADERSTAGE_COMPUTE),
94921
+ new BindStorageBufferFormat('counter', SHADERSTAGE_COMPUTE),
94922
+ new BindUniformBufferFormat('uniforms', SHADERSTAGE_COMPUTE),
94923
+ new BindStorageBufferFormat('occL1', SHADERSTAGE_COMPUTE, true),
94924
+ new BindStorageBufferFormat('occL2', SHADERSTAGE_COMPUTE, true),
94925
+ new BindStorageBufferFormat('buckets', SHADERSTAGE_COMPUTE)
94926
+ ];
94927
+ const formats = [...fixed, ...this.source.bindFormats()];
94928
+ this.projectorBindGroupFormat ??= new BindGroupFormat(device, formats);
94929
+ const shader = new Shader(device, {
94930
+ name: `sse-splat-project-${key}`,
94931
+ shaderLanguage: SHADERLANGUAGE_WGSL,
94932
+ cshader: projectorWGSL(this.source.readChunk(fixed.length), occlusion, ordered),
94933
+ cincludes: this.source.shaderIncludes(),
94934
+ cdefines: this.source.shaderDefines(),
94935
+ computeUniformBufferFormats: {
94936
+ // the same order as the wgsl struct; both follow the same alignment rules
94937
+ uniforms: new UniformBufferFormat(device, [
94938
+ new UniformFormat('view', UNIFORMTYPE_MAT4),
94939
+ new UniformFormat('viewProj', UNIFORMTYPE_MAT4),
94940
+ new UniformFormat('prevViewProj', UNIFORMTYPE_MAT4),
94941
+ new UniformFormat('prevView', UNIFORMTYPE_MAT4),
94942
+ new UniformFormat('prevClipZ', UNIFORMTYPE_VEC4),
94943
+ new UniformFormat('viewport', UNIFORMTYPE_VEC2),
94944
+ new UniformFormat('focal', UNIFORMTYPE_VEC2),
94945
+ new UniformFormat('prevViewport', UNIFORMTYPE_VEC2),
94946
+ new UniformFormat('prevFocal', UNIFORMTYPE_VEC2),
94947
+ new UniformFormat('numChunks', UNIFORMTYPE_UINT),
94948
+ new UniformFormat('splatTextureSize', UNIFORMTYPE_UINT),
94949
+ new UniformFormat('isOrtho', UNIFORMTYPE_UINT),
94950
+ new UniformFormat('minPixelSize', UNIFORMTYPE_FLOAT),
94951
+ new UniformFormat('alphaClip', UNIFORMTYPE_FLOAT),
94952
+ new UniformFormat('minContribution', UNIFORMTYPE_FLOAT),
94953
+ new UniformFormat('occBlocksX1', UNIFORMTYPE_UINT),
94954
+ new UniformFormat('occBlocksY1', UNIFORMTYPE_UINT),
94955
+ new UniformFormat('occBlocksX2', UNIFORMTYPE_UINT),
94956
+ new UniformFormat('occBlocksY2', UNIFORMTYPE_UINT),
94957
+ new UniformFormat('occlusionMode', UNIFORMTYPE_UINT),
94958
+ new UniformFormat('prevFlip', UNIFORMTYPE_FLOAT),
94959
+ new UniformFormat('keyLogNear', UNIFORMTYPE_FLOAT),
94960
+ new UniformFormat('keyInvLogRange', UNIFORMTYPE_FLOAT),
94961
+ new UniformFormat('chunkBase', UNIFORMTYPE_UINT),
94962
+ new UniformFormat('model', UNIFORMTYPE_MAT4),
94963
+ new UniformFormat('modelRotation', UNIFORMTYPE_VEC4),
94964
+ new UniformFormat('modelScale', UNIFORMTYPE_VEC4),
94965
+ new UniformFormat('cameraPosition', UNIFORMTYPE_VEC4),
94966
+ new UniformFormat('colorMax', UNIFORMTYPE_FLOAT),
94967
+ new UniformFormat('unitScale', UNIFORMTYPE_FLOAT),
94968
+ new UniformFormat('depthNear', UNIFORMTYPE_FLOAT),
94969
+ new UniformFormat('depthFar', UNIFORMTYPE_FLOAT)
94970
+ ])
94971
+ },
94972
+ computeBindGroupFormat: this.projectorBindGroupFormat
94973
+ });
94974
+ this.projectorShaders.set(key, shader);
94975
+ return shader;
94976
+ }
94977
+ destroyProjector() {
94978
+ for (const compute of this.projectorComputes.values())
94979
+ compute.destroy();
94980
+ this.projectorComputes.clear();
94981
+ for (const shader of this.projectorShaders.values())
94982
+ shader.destroy();
94983
+ this.projectorShaders.clear();
94984
+ this.projectorBindGroupFormat?.destroy();
94985
+ this.projectorBindGroupFormat = null;
94986
+ this.projectorSourceKey = '';
94987
+ }
94988
+ destroy() {
94989
+ this.unsubscribe();
94990
+ this.app.off('frameend', this.onFrameEnd);
94991
+ this.detach();
94992
+ this.provider.destroy();
94993
+ this.source.destroy();
94994
+ this.destroyProjector();
94995
+ this.args.shader.destroy();
94996
+ this.args.destroy();
94997
+ this.argsBindGroupFormat.destroy();
94998
+ for (const compute of [this.reduceL1, this.reduceL2]) {
94999
+ compute.shader.destroy();
95000
+ compute.destroy();
95001
+ }
95002
+ for (const format of this.reduceFormats)
95003
+ format.destroy();
95004
+ this.occL1.destroy();
95005
+ this.occL2.destroy();
95006
+ for (const compute of [this.orderScan, this.orderScatter]) {
95007
+ compute.shader.destroy();
95008
+ compute.destroy();
95009
+ }
95010
+ for (const format of this.orderFormats)
95011
+ format.destroy();
95012
+ this.orderBuckets.destroy();
95013
+ this.orderedBuffer?.destroy();
95014
+ this.orderedBuffer = null;
95015
+ this.chunkBuffer?.destroy();
95016
+ this.nodeVisibleBuffer?.destroy();
95017
+ this.cacheBuffer?.destroy();
95018
+ this.counter.destroy();
95019
+ this.chunkBuffer = this.nodeVisibleBuffer = this.cacheBuffer = null;
95020
+ this.rasterPass.destroy();
95021
+ this.rasterInstance.destroy();
95022
+ this.rasterMaterial.destroy();
95023
+ this.rasterMesh.destroy();
95024
+ this.taaPass.destroy();
95025
+ this.taaInstance.destroy();
95026
+ this.taaMaterial.destroy();
95027
+ this.taaMesh.destroy();
95028
+ for (const target of this.taaTargets)
95029
+ target.destroy();
95030
+ for (const texture of [...this.taaColor, ...this.taaInfo])
95031
+ texture.destroy();
95032
+ this.taaTargets.length = 0;
95033
+ this.taaColor.length = 0;
95034
+ this.taaInfo.length = 0;
95035
+ this.target.destroy();
95036
+ this.colorTexture.destroy();
95037
+ this.depthTexture.destroy();
95038
+ this.composeInstance.destroy();
95039
+ this.composeMaterial.destroy();
95040
+ this.composeMesh.destroy();
95041
+ }
95042
+ }
95043
+
91427
95044
  // ---------------------------------------------------------------------------
91428
95045
  // WGSL compute shader: ray-march through the sparse voxel octree per pixel
91429
95046
  // ---------------------------------------------------------------------------
@@ -93631,6 +97248,17 @@ const rendererTable = {
93631
97248
  webgl: GSPLAT_RENDERER_RASTER_CPU_SORT,
93632
97249
  webgpu: GSPLAT_RENDERER_RASTER_GPU_SORT
93633
97250
  };
97251
+ // quality budget, millions of splats
97252
+ const budgets = {
97253
+ mobile: {
97254
+ low: 1,
97255
+ high: 2
97256
+ },
97257
+ desktop: {
97258
+ low: 2,
97259
+ high: 4
97260
+ }
97261
+ };
93634
97262
  const tonemapTable = {
93635
97263
  none: TONEMAP_NONE,
93636
97264
  linear: TONEMAP_LINEAR,
@@ -93725,6 +97353,13 @@ class Viewer {
93725
97353
  meshOverlay = null;
93726
97354
  navCursor = null;
93727
97355
  debugPanel = null;
97356
+ /** The opt-in stochastic renderer (WebGPU only); null when the engine's sorted renderer draws. */
97357
+ splatRenderer = null;
97358
+ /**
97359
+ * The engine's MiniStats panel once first shown (`?ministats` or the debug panel), else null.
97360
+ * Hiding disables it rather than destroying it.
97361
+ */
97362
+ miniStats = null;
93728
97363
  /** Set once {@link destroy} has run. Load continuations check it and bail. */
93729
97364
  destroyed = false;
93730
97365
  disposers = [];
@@ -93784,10 +97419,35 @@ class Viewer {
93784
97419
  app.autoRender = true;
93785
97420
  // configure the camera
93786
97421
  this.configureCamera(settings);
93787
- // reconfigure camera when entering/exiting XR
97422
+ // The stochastic renderer, when opted in. Created before the first frame so it can
97423
+ // switch the engine's own splat renderer off as soon as the engine creates it. An
97424
+ // instance without the flag never constructs it, and the sorted path is untouched.
97425
+ if (config.stochastic && renderer === 'webgpu') {
97426
+ const worldLayer = app.scene.layers.getLayerByName('World');
97427
+ // the largest budget this instance can ask for must fit the device's storage binding
97428
+ const budget = (config.budget && config.budget > 0
97429
+ ? config.budget
97430
+ : (platform.mobile ? budgets.mobile : budgets.desktop).high) * 1000000;
97431
+ if (!StochasticSplatRenderer.cacheFits(app.graphicsDevice, budget)) {
97432
+ console.warn(`stochastic renderer: a ${budget / 1000000}M splat budget exceeds this device's storage binding limit; the sorted renderer draws`);
97433
+ }
97434
+ else if (worldLayer) {
97435
+ this.splatRenderer = new StochasticSplatRenderer(app, camera.camera, worldLayer, {
97436
+ source: config.splatSource,
97437
+ variant: config.variant
97438
+ });
97439
+ // announced on the first frame rather than here: createViewer resolves after this
97440
+ // constructor, so a page can only subscribe once loading is under way
97441
+ events.once('firstFrame', () => events.fire('splatRenderer:ready', this.splatRenderer));
97442
+ }
97443
+ }
97444
+ // reconfigure camera when entering/exiting XR. The stochastic renderer has no stereo
97445
+ // path yet, so the engine's renderer draws the splats for the session
93788
97446
  const configureXrCamera = () => {
93789
- if (!this.destroyed)
93790
- this.configureCamera(settings);
97447
+ if (this.destroyed)
97448
+ return;
97449
+ this.configureCamera(settings);
97450
+ this.splatRenderer?.setEnabled(!app.xr.active);
93791
97451
  };
93792
97452
  const xrStart = app.xr.on('start', configureXrCamera);
93793
97453
  const xrEnd = app.xr.on('end', configureXrCamera);
@@ -93795,28 +97455,12 @@ class Viewer {
93795
97455
  xrStart.off();
93796
97456
  xrEnd.off();
93797
97457
  });
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
- }
97458
+ // debug ministats, from the flag at start and the debug panel's toggle after
97459
+ this.setMiniStats(config.ministats);
97460
+ this.onDestroy(() => {
97461
+ this.miniStats?.destroy();
97462
+ this.miniStats = null;
97463
+ });
93820
97464
  const prevProj = new Mat4();
93821
97465
  const prevWorld = new Mat4();
93822
97466
  const sceneBound = new BoundingBox();
@@ -93825,7 +97469,7 @@ class Viewer {
93825
97469
  const world = camera.getWorldTransform();
93826
97470
  const proj = camera.camera.projectionMatrix;
93827
97471
  if (!app.renderNextFrame) {
93828
- if (config.ministats ||
97472
+ if (this.miniStats?.enabled ||
93829
97473
  !nearlyEquals(world.data, prevWorld.data) ||
93830
97474
  !nearlyEquals(proj.data, prevProj.data)) {
93831
97475
  app.renderNextFrame = true;
@@ -94006,7 +97650,12 @@ class Viewer {
94006
97650
  if (gsplatBbox) {
94007
97651
  sceneBound.setFromTransformedAabb(gsplatBbox, results[0].getWorldTransform());
94008
97652
  }
94009
- this.picker = new Picker(app, camera);
97653
+ // the stochastic renderer leaves its frame's depth behind, so no pick pass is needed
97654
+ this.picker = this.splatRenderer
97655
+ ? new FrameDepthPicker(app, camera, this.splatRenderer)
97656
+ : new Picker(app, camera);
97657
+ // for development pages (the bench measures pick noise), as splatRenderer:ready
97658
+ events.fire('picker:ready', this.picker);
94010
97659
  this.inputController = new InputController(global, this.picker);
94011
97660
  this.cameraManager = new CameraManager(global, sceneBound);
94012
97661
  applyCamera(this.cameraManager.camera);
@@ -94056,18 +97705,10 @@ class Viewer {
94056
97705
  // collision may already have landed while the splats were still streaming
94057
97706
  if (collisionReady)
94058
97707
  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
- };
97708
+ this.debugPanel = new DebugPanel(global, this.cameraManager, this.picker, this.splatRenderer, {
97709
+ shown: () => !!this.miniStats?.enabled,
97710
+ show: (value) => this.setMiniStats(value)
97711
+ });
94071
97712
  const applyPerfSettings = () => {
94072
97713
  const budget = () => {
94073
97714
  if (config.budget !== undefined && Number.isFinite(config.budget) && config.budget > 0) {
@@ -94122,7 +97763,12 @@ class Viewer {
94122
97763
  // handle quality mode changes
94123
97764
  events.on('performanceMode:changed', applyPerfSettings);
94124
97765
  applyPerfSettings();
94125
- gsplat.renderer = rendererTable[renderer];
97766
+ // the stochastic renderer consumes the engine's world under whatever
97767
+ // renderer mode the engine resolved; switching modes here would rebuild
97768
+ // the work buffer for nothing
97769
+ if (!this.splatRenderer) {
97770
+ gsplat.renderer = rendererTable[renderer];
97771
+ }
94126
97772
  // wait for the first valid frame to complete rendering
94127
97773
  app.once('frameend', () => {
94128
97774
  events.fire('firstFrame');
@@ -94272,6 +97918,49 @@ class Viewer {
94272
97918
  }
94273
97919
  this.disposers.push(fn);
94274
97920
  }
97921
+ /**
97922
+ * Show or hide the engine's MiniStats panel. While shown the viewer renders every frame, so
97923
+ * the graphs keep moving.
97924
+ */
97925
+ setMiniStats(value) {
97926
+ if (value === !!this.miniStats?.enabled)
97927
+ return;
97928
+ // hidden by disabling rather than destroying: the engine's destroy() leaves its stats
97929
+ // timers reading every frame and its buffers allocated, so a panel per toggle would pile
97930
+ // them up until teardown
97931
+ if (this.miniStats) {
97932
+ this.miniStats.enabled = value;
97933
+ // the panel's transparent div would keep catching clicks over the canvas
97934
+ this.miniStats.div.style.display = value ? '' : 'none';
97935
+ if (value) {
97936
+ // enabling turns every graph on, the text-only size's too: its size puts them back
97937
+ const size = this.miniStats.activeSizeIndex;
97938
+ this.miniStats.activeSizeIndex = size;
97939
+ this.global.app.renderNextFrame = true;
97940
+ }
97941
+ return;
97942
+ }
97943
+ const options = MiniStats.getDefaultOptions();
97944
+ options.cpu.enabled = false;
97945
+ options.stats = options.stats.filter((s) => s.name !== 'DrawCalls');
97946
+ options.stats.push({
97947
+ name: 'VRAM',
97948
+ stats: ['vram.tex'],
97949
+ decimalPlaces: 1,
97950
+ multiplier: 1 / (1024 * 1024),
97951
+ unitsName: 'MB',
97952
+ watermark: 1024
97953
+ }, {
97954
+ name: 'Splats',
97955
+ stats: ['frame.gsplats'],
97956
+ decimalPlaces: 3,
97957
+ multiplier: 1 / 1000000,
97958
+ unitsName: 'M',
97959
+ watermark: 5
97960
+ });
97961
+ this.miniStats = new MiniStats(this.global.app, options);
97962
+ this.global.app.renderNextFrame = true;
97963
+ }
94275
97964
  /**
94276
97965
  * Tear the viewer down: stop rendering, remove every listener it added to the window,
94277
97966
  * document and canvas, restore the globals it patched, and release the graphics device.
@@ -94302,6 +97991,8 @@ class Viewer {
94302
97991
  this.voxelOverlay?.destroy();
94303
97992
  this.meshOverlay?.destroy();
94304
97993
  this.picker?.release();
97994
+ this.splatRenderer?.destroy();
97995
+ this.splatRenderer = null;
94305
97996
  this.capture?.destroy();
94306
97997
  this.capture = null;
94307
97998
  if (this.cameraFrame) {
@@ -94497,6 +98188,12 @@ const createApp = async (canvas, config) => {
94497
98188
  touch: new TouchDevice$1(canvas),
94498
98189
  keyboard: new Keyboard(window)
94499
98190
  });
98191
+ // The stochastic renderer never sorts on the cpu, so the per-splat centres the engine
98192
+ // reads back for its cpu sort (12 bytes each, plus a gpu readback per file) are dead
98193
+ // weight. Read once per file at load, so it has to be set before any asset loads.
98194
+ if (config.stochastic && renderer === 'webgpu') {
98195
+ app.scene.gsplatCentersEnabled = false;
98196
+ }
94500
98197
  // enable anonymous CORS for image loading in safari (must be set before any
94501
98198
  // texture asset starts loading, otherwise the <img> is fetched without the
94502
98199
  // crossorigin attribute and WebGL rejects it with SecurityError)
@@ -94600,6 +98297,9 @@ const resolveConfig = (options) => ({
94600
98297
  colorize: options.colorize ?? false,
94601
98298
  fullload: options.fullload ?? false,
94602
98299
  aa: options.aa ?? false,
98300
+ stochastic: options.stochastic ?? false,
98301
+ splatSource: options.splatSource ?? 'workbuffer',
98302
+ variant: options.variant ?? '',
94603
98303
  budget: options.budget,
94604
98304
  heatmap: options.heatmap ?? false,
94605
98305
  debug: options.debug ?? false,
@@ -94754,7 +98454,9 @@ const createViewer = async (options) => {
94754
98454
  destroy: () => viewer.destroy()
94755
98455
  };
94756
98456
  // The built-in controls use the same handle returned to an embedding host.
94757
- const disposeUI = config.ui ? initUI(global, handle, () => viewer.picker) : null;
98457
+ const disposeUI = config.ui
98458
+ ? initUI(global, handle, () => viewer.picker, () => viewer.cameraManager?.transitionProgress() ?? 1)
98459
+ : null;
94758
98460
  viewer.onDestroy(() => {
94759
98461
  destroyed = true;
94760
98462
  });