@playcanvas/supersplat-viewer 1.22.4 → 1.23.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
@@ -77723,7 +77723,7 @@ const importSettings = (settings) => {
77723
77723
  return result;
77724
77724
  };
77725
77725
 
77726
- var version = "1.22.4";
77726
+ var version = "1.23.1";
77727
77727
 
77728
77728
  class Tooltip {
77729
77729
  register;
@@ -78013,7 +78013,7 @@ const initUI = (global) => {
78013
78013
  'reset', 'frame',
78014
78014
  'loadingText', 'loadingBar',
78015
78015
  'joystickBase', 'joystick',
78016
- 'showCollision',
78016
+ 'showCollision', 'desktopShowCollisionHelp',
78017
78017
  'tooltip',
78018
78018
  'annotationNav', 'annotationPrev', 'annotationNext', 'annotationInfo', 'annotationNavTitle',
78019
78019
  'viewerBranding', 'viewerTitle', 'appVersionLabel'
@@ -78359,16 +78359,18 @@ const initUI = (global) => {
78359
78359
  if (type === 'interrupt')
78360
78360
  dismissWalkHint();
78361
78361
  });
78362
- // show/hide the FPS button based on voxel data availability
78363
- events.on('hasCollision:changed', (value) => {
78362
+ // show/hide the FPS button based on whether walk mode is offered
78363
+ // (collision data exists AND scene is large enough to walk around in)
78364
+ events.on('walkAllowed:changed', (value) => {
78364
78365
  dom.fpsCamera.classList.toggle('hidden', !value);
78365
78366
  // adjust fly button shape: middle when FPS is visible, right when hidden
78366
78367
  dom.flyCamera.classList.toggle('middle', value);
78367
78368
  dom.flyCamera.classList.toggle('right', !value);
78368
78369
  });
78369
- // Collision overlay toggle (only visible when overlay is available)
78370
+ // Collision overlay toggle + matching help-panel row (only visible when overlay is available)
78370
78371
  events.on('hasCollisionOverlay:changed', (value) => {
78371
78372
  dom.showCollision.classList.toggle('hidden', !value);
78373
+ dom.desktopShowCollisionHelp.classList.toggle('hidden', !value);
78372
78374
  });
78373
78375
  dom.showCollision.addEventListener('click', () => {
78374
78376
  state.collisionOverlayEnabled = !state.collisionOverlayEnabled;
@@ -80565,6 +80567,16 @@ class WalkSource {
80565
80567
 
80566
80568
  const tmpCamera = new Camera();
80567
80569
  const tmpv = new Vec3();
80570
+ // Walk mode is only enabled when the scene's horizontal footprint is large
80571
+ // enough to walk around in. Vertical extent (Y) is irrelevant — a tall but
80572
+ // narrow scene isn't walkable. Both X and Z ranges must exceed this
80573
+ // minimum (in metres); below it walk mode is hidden and the viewer falls
80574
+ // back to fly as the default first-person mode.
80575
+ const WALK_MIN_HORIZONTAL_RANGE = 5;
80576
+ const isWalkAllowed = (bbox, collision) => {
80577
+ const { x, z } = bbox.halfExtents;
80578
+ return !!collision && x * 2 >= WALK_MIN_HORIZONTAL_RANGE && z * 2 >= WALK_MIN_HORIZONTAL_RANGE;
80579
+ };
80568
80580
  const createCamera = (position, target, fov) => {
80569
80581
  const result = new Camera();
80570
80582
  result.look(position, target);
@@ -80582,6 +80594,7 @@ class CameraManager {
80582
80594
  camera = new Camera();
80583
80595
  constructor(global, bbox, collision = null) {
80584
80596
  const { events, settings, state } = global;
80597
+ const walkAllowed = isWalkAllowed(bbox, collision);
80585
80598
  const camera0 = settings.cameras[0]?.initial;
80586
80599
  const defaultFov = camera0?.fov ?? 75;
80587
80600
  const frameCamera = createFrameCamera(bbox, defaultFov);
@@ -80633,11 +80646,11 @@ class CameraManager {
80633
80646
  state.hasAnimation = !!controllers.anim;
80634
80647
  state.animationDuration = controllers.anim ? controllers.anim.animState.cursor.duration : 0;
80635
80648
  // initialize camera mode and initial camera position
80636
- state.cameraMode = state.hasAnimation ? 'anim' : (isObjectExperience ? 'orbit' : (collision ? 'walk' : 'fly'));
80649
+ state.cameraMode = state.hasAnimation ? 'anim' : (isObjectExperience ? 'orbit' : (walkAllowed ? 'walk' : 'fly'));
80637
80650
  this.camera.copy(resetCamera);
80638
80651
  const target = new Camera(this.camera); // the active controller updates this
80639
80652
  const from = new Camera(this.camera); // stores the previous camera state during transition
80640
- const defaultMode = isObjectExperience ? 'orbit' : (collision ? 'walk' : 'fly');
80653
+ const defaultMode = isObjectExperience ? 'orbit' : (walkAllowed ? 'walk' : 'fly');
80641
80654
  let fromMode = defaultMode;
80642
80655
  // tracks the mode to restore when exiting walk
80643
80656
  let preWalkMode = isObjectExperience ? 'orbit' : 'fly';
@@ -80721,7 +80734,7 @@ class CameraManager {
80721
80734
  state.cameraMode = 'fly';
80722
80735
  break;
80723
80736
  case 'toggleWalk':
80724
- if (collision) {
80737
+ if (walkAllowed) {
80725
80738
  if (state.cameraMode === 'walk') {
80726
80739
  state.cameraMode = preWalkMode;
80727
80740
  }
@@ -81578,7 +81591,6 @@ class KeyboardMouseDevice {
81578
81591
  const tmpV$2 = new Vec3();
81579
81592
  const orbitMove = new Vec3();
81580
81593
  const flyMoveTmp = new Vec3();
81581
- const flyTouchPan = new Vec3();
81582
81594
  const pinchMoveTmp = new Vec3();
81583
81595
  const orbitRotate = new Vec3();
81584
81596
  const flyRotate = new Vec3();
@@ -81587,19 +81599,12 @@ class TouchDevice {
81587
81599
  moveSpeed = 4;
81588
81600
  pinchSpeed = 0.4;
81589
81601
  touchRotateSensitivity = 1.5;
81590
- touchPinchMoveSensitivity = 1.5;
81591
- pinchVelocitySensitivity = 0.006;
81592
- panVelocitySensitivity = 0.005;
81593
81602
  _source = new MultiTouchSource();
81594
81603
  _global = null;
81595
81604
  /** Touches currently active (running count from .read() deltas). */
81596
81605
  _touchCount = 0;
81597
81606
  /** UI joystick value [x, y], -1..1. */
81598
81607
  _joystick = [0, 0];
81599
- /** Smoothed forward/back velocity from pinch gesture (-1..1). */
81600
- _pinchVelocity = 0;
81601
- /** Smoothed strafe/vertical velocity from two-finger pan, -1..1 each. */
81602
- _panVelocity = [0, 0];
81603
81608
  /** Tap-detection state — touch count, max touches, and accumulated movement. */
81604
81609
  _tapTouches = 0;
81605
81610
  _tapMaxTouches = 0;
@@ -81680,49 +81685,38 @@ class TouchDevice {
81680
81685
  this._tapTouches = 0;
81681
81686
  this._tapMaxTouches = 0;
81682
81687
  }
81683
- // smoothed velocities for fly/walk first-person motion (non-gaming)
81684
- if (isFirstPerson && !gamingControls && this._touchCount > 1) {
81685
- // pinch[0] = oldDist - newDist: negative when spreading,
81686
- // positive when closing. Spreading = forward → subtract.
81687
- this._pinchVelocity -= pinch[0] * this.pinchVelocitySensitivity;
81688
- this._pinchVelocity = math.clamp(this._pinchVelocity, -1, 1.0);
81689
- this._panVelocity[0] += touch[0] * this.panVelocitySensitivity;
81690
- this._panVelocity[0] = math.clamp(this._panVelocity[0], -1, 1.0);
81691
- this._panVelocity[1] += touch[1] * this.panVelocitySensitivity;
81692
- this._panVelocity[1] = math.clamp(this._panVelocity[1], -1, 1.0);
81693
- }
81694
- else if (isFirstPerson && this._touchCount <= 1) {
81695
- this._pinchVelocity = 0;
81696
- this._panVelocity[0] = 0;
81697
- this._panVelocity[1] = 0;
81698
- }
81699
81688
  const orbit = isOrbit ? 1 : 0;
81700
81689
  const fly = isFirstPerson ? 1 : 0;
81701
81690
  const double = this._touchCount > 1 ? 1 : 0;
81702
81691
  const orbitFactor = isFirstPerson ? cameraComponent.fov / 120 : 1;
81703
81692
  const dragInvert = (isFirstPerson && !gamingControls) ? -1 : 1;
81693
+ // First-person modes (fly and walk) opt into the direct two-finger
81694
+ // model only outside gaming controls (gaming uses the joystick).
81695
+ const directFirstPerson = fly * (gamingControls ? 0 : 1);
81704
81696
  const { deltas } = frame;
81705
81697
  // move
81706
81698
  const v = tmpV$2.set(0, 0, 0);
81707
- // two-finger orbit-pan when in orbit mode (single touch is rotate, double is pan)
81699
+ // Two-finger pan: orbit pans the target; fly strafes/rises in the
81700
+ // camera basis; walk strafes along the ground plane. Identical 1:1
81701
+ // screen-space mapping in every mode so dragging feels the same —
81702
+ // what your fingers move, the camera moves. Walk zeros y because
81703
+ // WalkController treats any nonzero move[1] as a jump trigger.
81708
81704
  screenToWorld(cameraComponent, touch[0], touch[1], distance, orbitMove);
81709
- v.add(orbitMove.mulScalar(orbit * double));
81705
+ if (isWalk) {
81706
+ orbitMove.y = 0;
81707
+ }
81708
+ v.add(orbitMove.mulScalar((orbit + directFirstPerson) * double));
81710
81709
  if (gamingControls) {
81711
81710
  // joystick UI drives strafe + forward/back in fly/walk
81712
81711
  flyMoveTmp.set(this._joystick[0], 0, -this._joystick[1]);
81713
81712
  v.add(flyMoveTmp.mulScalar(fly * this.moveSpeed * dt));
81714
81713
  }
81715
- else {
81716
- // smoothed pan velocity → strafe (X) and vertical (Y, fly only)
81717
- flyTouchPan.set(this._panVelocity[0], isWalk ? 0 : -this._panVelocity[1], 0);
81718
- v.add(flyTouchPan.mulScalar(fly * this.touchPinchMoveSensitivity * this.moveSpeed * dt));
81719
- // smoothed pinch velocity → forward/back
81720
- flyMoveTmp.set(0, 0, this._pinchVelocity);
81721
- v.add(flyMoveTmp.mulScalar(fly * this.touchPinchMoveSensitivity * this.moveSpeed * dt));
81722
- }
81723
- // raw pinch for orbit-mode zoom
81724
- pinchMoveTmp.set(0, 0, pinch[0]);
81725
- v.add(pinchMoveTmp.mulScalar(orbit * double * this.pinchSpeed * DISPLACEMENT_SCALE));
81714
+ // Two-finger pinch z: orbit interprets +z as "farther from target"
81715
+ // (close-pinch = +pinch[0] = zoom out). First-person modes interpret
81716
+ // +z as "forward", so spreading (pinch[0] < 0) should move forward —
81717
+ // flip the sign there.
81718
+ pinchMoveTmp.set(0, 0, (orbit - directFirstPerson) * pinch[0]);
81719
+ v.add(pinchMoveTmp.mulScalar(double * this.pinchSpeed * DISPLACEMENT_SCALE));
81726
81720
  // tap-to-jump in walk + gaming controls
81727
81721
  if (isWalk && this._tapJump) {
81728
81722
  v.y = 1;
@@ -81741,62 +81735,6 @@ class TouchDevice {
81741
81735
  }
81742
81736
  }
81743
81737
 
81744
- /**
81745
- * Distinguishes a physical mouse wheel from a trackpad two-finger scroll.
81746
- *
81747
- * A single wheel event is unreliable (Magic Mouse, hi-res mice, and macOS
81748
- * Shift-remapping all confuse per-event heuristics), so classify on the
81749
- * first event of a burst and let the rest of the burst inherit that label.
81750
- * A burst is a run of wheel events separated by less than BURST_GAP_MS;
81751
- * trackpads stream at ~60Hz (~16ms), wheels emit one event per notch
81752
- * (typically >>50ms apart).
81753
- */
81754
- const BURST_GAP_MS = 80;
81755
- const isMouseWheelEvent = (event) => {
81756
- // Firefox: physical wheels report line/page mode; trackpads report
81757
- // pixel mode. Firefox doesn't expose wheelDelta* so this is the only
81758
- // reliable signal there.
81759
- if (event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL) {
81760
- return true;
81761
- }
81762
- // Chrome / Safari: the non-standard wheelDelta{X,Y} properties preserve
81763
- // the raw wheel-tick value (always multiples of ±120 per notch)
81764
- // regardless of macOS scroll smoothing. Trackpads and Magic Mouse emit
81765
- // arbitrary values that are essentially never aligned to 120.
81766
- const e = event;
81767
- if (typeof e.wheelDeltaY === 'number' && e.wheelDeltaY !== 0) {
81768
- return e.wheelDeltaY % 120 === 0;
81769
- }
81770
- if (typeof e.wheelDeltaX === 'number' && e.wheelDeltaX !== 0) {
81771
- return e.wheelDeltaX % 120 === 0;
81772
- }
81773
- // Last-resort fallback for browsers without wheelDelta*.
81774
- const { deltaX, deltaY } = event;
81775
- if (deltaX !== 0 && deltaY !== 0) {
81776
- return false;
81777
- }
81778
- return Number.isInteger(deltaX) && Number.isInteger(deltaY);
81779
- };
81780
- class WheelClassifier {
81781
- _lastTime = -Infinity;
81782
- _burstIsMouseWheel = false;
81783
- /**
81784
- * Classify the given event. The first event of a burst sets the label
81785
- * for the burst; subsequent events within BURST_GAP_MS inherit it.
81786
- *
81787
- * @param event - The wheel event to classify.
81788
- * @returns True if the event came from a physical mouse wheel.
81789
- */
81790
- classify(event) {
81791
- const now = performance.now();
81792
- if (now - this._lastTime > BURST_GAP_MS) {
81793
- this._burstIsMouseWheel = isMouseWheelEvent(event);
81794
- }
81795
- this._lastTime = now;
81796
- return this._burstIsMouseWheel;
81797
- }
81798
- }
81799
-
81800
81738
  const tmpV$1 = new Vec3();
81801
81739
  class TrackpadDevice {
81802
81740
  orbitSpeed = 18;
@@ -81804,22 +81742,59 @@ class TrackpadDevice {
81804
81742
  trackpadOrbitSensitivity = 0.75;
81805
81743
  trackpadPanSensitivity = 1.0;
81806
81744
  trackpadZoomSensitivity = 2.0;
81807
- _classifier = new WheelClassifier();
81808
81745
  _global = null;
81809
81746
  _orbit = [0, 0];
81810
81747
  _pan = [0, 0];
81811
81748
  _zoom = 0;
81812
- _onWheel = (event) => {
81813
- if (this._classifier.classify(event)) {
81814
- // physical mouse wheel — KeyboardMouseSource handles it
81815
- return;
81749
+ // Tracks physical Ctrl key state so we can distinguish macOS-synthesized
81750
+ // pinch events (wheel + ctrlKey, no physical Ctrl) from a user holding
81751
+ // Ctrl while spinning a mouse wheel. The synthetic-Ctrl signal is the
81752
+ // one reliable trackpad indicator the platform gives us — every other
81753
+ // per-event heuristic has been tried (wheelDelta % 120, deltaMode,
81754
+ // fractional/diagonal deltas) and misfires on hi-res mice or in
81755
+ // momentum tails. Modifier-key state we can trust 100%.
81756
+ _ctrlDown = false;
81757
+ _onKeyDown = (event) => {
81758
+ if (event.key === 'Control') {
81759
+ this._ctrlDown = true;
81760
+ }
81761
+ };
81762
+ _onKeyUp = (event) => {
81763
+ if (event.key === 'Control') {
81764
+ this._ctrlDown = false;
81816
81765
  }
81766
+ };
81767
+ // Window blur (alt-tab, focus another app) drops keyup events, so
81768
+ // clear Ctrl state defensively to avoid getting stuck.
81769
+ _onBlur = () => {
81770
+ this._ctrlDown = false;
81771
+ };
81772
+ _onWheel = (event) => {
81817
81773
  const mode = this._global.state.cameraMode;
81818
- const isFirstPersonMode = mode === 'fly' || mode === 'walk';
81819
- const hasZoomModifier = event.ctrlKey || event.metaKey;
81820
- if (mode === 'orbit') ;
81821
- else if (isFirstPersonMode && !hasZoomModifier) ;
81822
- else {
81774
+ // Synthetic Ctrl (macOS pinch-to-zoom, Magic Mouse pinch): ctrlKey
81775
+ // is true on the event but the user isn't physically holding Ctrl.
81776
+ // Routes to trackpad-tuned zoom.
81777
+ const isPinch = event.ctrlKey && !this._ctrlDown;
81778
+ // Physical Ctrl + wheel/swipe: rotate. In orbit mode rotates around
81779
+ // the target; in fly/walk mode looks around. Applies to both mouse
81780
+ // wheel and trackpad swipe — we can't distinguish them, and the
81781
+ // modifier signals intent either way.
81782
+ // Corner case: user physically holds Ctrl AND pinches at the same
81783
+ // time — both flags are true, the gesture lands here as rotate
81784
+ // rather than pinch. Intentional: physical Ctrl is the explicit
81785
+ // signal, so it wins over the synthetic-Ctrl pinch heuristic.
81786
+ const isCtrlRotate = event.ctrlKey && this._ctrlDown;
81787
+ // Shift + wheel/swipe: pan (= strafe + vertical) in all modes. The
81788
+ // downstream camera controllers translate the screen-space pan
81789
+ // vector appropriately (orbit pans around the target plane; fly
81790
+ // strafes sideways and translates vertically; walk strafes).
81791
+ const isShiftPan = event.shiftKey;
81792
+ if (!isPinch && !isCtrlRotate && !isShiftPan) {
81793
+ // Bare wheel (mouse or trackpad swipe), unmodified fly/walk
81794
+ // wheels — all fall through to KeyboardMouseDevice for
81795
+ // standard forward/back motion (which dollys toward the orbit
81796
+ // target in orbit mode via flipZForOrbit, giving the universal
81797
+ // bare-scroll-zooms behavior).
81823
81798
  return;
81824
81799
  }
81825
81800
  event.preventDefault();
@@ -81830,29 +81805,21 @@ class TrackpadDevice {
81830
81805
  // so fire interrupt explicitly to keep parity with mouse-wheel.
81831
81806
  event.stopImmediatePropagation();
81832
81807
  this._global.events.fire('inputEvent', 'interrupt', event);
81808
+ if (mode === 'fly') {
81809
+ this._global.events.fire('navigateCancel');
81810
+ }
81833
81811
  const { deltaX, deltaY } = event;
81834
- if (mode === 'orbit') {
81835
- if (event.ctrlKey || event.metaKey) {
81836
- // pinch on macOS arrives as ctrl+wheel; ctrl/meta+scroll routes here too
81837
- this._zoom += deltaY;
81838
- }
81839
- else if (event.shiftKey) {
81840
- this._pan[0] += deltaX;
81841
- this._pan[1] += deltaY;
81842
- }
81843
- else {
81844
- this._orbit[0] += deltaX;
81845
- this._orbit[1] += deltaY;
81846
- }
81812
+ if (isPinch) {
81813
+ this._zoom += deltaY;
81847
81814
  }
81848
- else {
81849
- // fly / walk: always rotate (shift is a speed modifier, not a gesture)
81850
- if (mode === 'fly') {
81851
- this._global.events.fire('navigateCancel');
81852
- }
81815
+ else if (isCtrlRotate) {
81853
81816
  this._orbit[0] += deltaX;
81854
81817
  this._orbit[1] += deltaY;
81855
81818
  }
81819
+ else {
81820
+ this._pan[0] += deltaX;
81821
+ this._pan[1] += deltaY;
81822
+ }
81856
81823
  };
81857
81824
  _canvas = null;
81858
81825
  /**
@@ -81861,6 +81828,9 @@ class TrackpadDevice {
81861
81828
  * for trackpad bursts. The coordinator enforces this by attaching
81862
81829
  * trackpad before keyboard-mouse.
81863
81830
  *
81831
+ * Keyboard listeners attach on `window` (not the canvas) so we still
81832
+ * see Ctrl keydown/keyup when focus is on a UI overlay.
81833
+ *
81864
81834
  * @param canvas - The canvas element to listen to.
81865
81835
  * @param global - The global app context (state, events, etc.).
81866
81836
  */
@@ -81868,13 +81838,20 @@ class TrackpadDevice {
81868
81838
  this._canvas = canvas;
81869
81839
  this._global = global;
81870
81840
  canvas.addEventListener('wheel', this._onWheel, { passive: false });
81841
+ window.addEventListener('keydown', this._onKeyDown);
81842
+ window.addEventListener('keyup', this._onKeyUp);
81843
+ window.addEventListener('blur', this._onBlur);
81871
81844
  }
81872
81845
  detach() {
81873
81846
  if (this._canvas) {
81874
81847
  this._canvas.removeEventListener('wheel', this._onWheel);
81875
81848
  this._canvas = null;
81876
81849
  }
81850
+ window.removeEventListener('keydown', this._onKeyDown);
81851
+ window.removeEventListener('keyup', this._onKeyUp);
81852
+ window.removeEventListener('blur', this._onBlur);
81877
81853
  this._global = null;
81854
+ this._ctrlDown = false;
81878
81855
  this._orbit[0] = this._orbit[1] = 0;
81879
81856
  this._pan[0] = this._pan[1] = 0;
81880
81857
  this._zoom = 0;
@@ -81884,24 +81861,34 @@ class TrackpadDevice {
81884
81861
  const orbitFactor = isFirstPerson ? cameraComponent.fov / 120 : 1;
81885
81862
  const { deltas } = frame;
81886
81863
  if (isOrbit) {
81887
- // orbit rotate
81864
+ // Ctrl + scroll → orbit rotate
81888
81865
  const v = tmpV$1.set(this._orbit[0], this._orbit[1], 0);
81889
81866
  v.mulScalar(this.orbitSpeed * this.trackpadOrbitSensitivity * DISPLACEMENT_SCALE);
81890
81867
  deltas.rotate.append([v.x, v.y, 0]);
81891
- // pan in world space (matches desktop pan path); reuse tmpV after rotate append
81868
+ // shift + scroll → pan in world space (matches desktop pan path); reuse tmpV after rotate append
81892
81869
  screenToWorld(cameraComponent, this._pan[0], this._pan[1], distance, tmpV$1);
81893
81870
  tmpV$1.mulScalar(this.trackpadPanSensitivity);
81894
81871
  deltas.move.append([tmpV$1.x, tmpV$1.y, 0]);
81895
- // zoom along z; positive deltaY (scroll-down / pinch-in) → zoom out → +z for orbit
81872
+ // synthetic-Ctrl pinch → zoom along z; positive deltaY (scroll-down / pinch-in) → zoom out → +z for orbit
81896
81873
  const zoomZ = this._zoom * this.wheelSpeed * this.trackpadZoomSensitivity * DISPLACEMENT_SCALE;
81897
81874
  deltas.move.append([0, 0, zoomZ]);
81898
81875
  }
81899
81876
  else if (isFirstPerson) {
81900
- // fly / walk look-around (only the no-modifier swipe is captured;
81901
- // pinch / Ctrl-swipe fall through to the wheel→forward path)
81877
+ // Ctrl + scroll → look around in fly/walk
81902
81878
  const v = tmpV$1.set(this._orbit[0], this._orbit[1], 0);
81903
81879
  v.mulScalar(this.orbitSpeed * orbitFactor * this.trackpadOrbitSensitivity * DISPLACEMENT_SCALE);
81904
81880
  deltas.rotate.append([v.x, v.y, 0]);
81881
+ // shift + scroll → strafe (X) + vertical (Y) via the same
81882
+ // screen-space pan pipeline as orbit mode; the fly/walk
81883
+ // controllers translate this into sideways/vertical motion
81884
+ screenToWorld(cameraComponent, this._pan[0], this._pan[1], distance, tmpV$1);
81885
+ tmpV$1.mulScalar(this.trackpadPanSensitivity);
81886
+ deltas.move.append([tmpV$1.x, tmpV$1.y, 0]);
81887
+ // synthetic-Ctrl pinch → forward/back along z (same sign as the
81888
+ // bare-wheel path in KeyboardMouseDevice, so pinch and scroll
81889
+ // produce identical motion in fly/walk modes)
81890
+ const moveZ = -this._zoom * this.wheelSpeed * this.trackpadZoomSensitivity * DISPLACEMENT_SCALE;
81891
+ deltas.move.append([0, 0, moveZ]);
81905
81892
  }
81906
81893
  this._orbit[0] = this._orbit[1] = 0;
81907
81894
  this._pan[0] = this._pan[1] = 0;
@@ -82263,1171 +82250,1019 @@ class MeshDebugOverlay {
82263
82250
  }
82264
82251
  }
82265
82252
 
82266
- /**
82267
- * World picking for splat scenes.
82268
- *
82269
- * Uses a custom `pickPS` / `gsplatPS` patch plus `RGBA16F` alpha-weighted depth accumulation,
82270
- * because the stock pick pass encodes splat IDs / last-fragment depth rather than expected depth.
82271
- */
82272
- // Override global picking to pack alpha-weighted splat depth instead of meshInstance id.
82273
- const pickDepthGlsl = /* glsl */ `
82274
- vec4 encodePickOutput(uint id) {
82275
- const vec4 inv = vec4(1.0 / 255.0);
82276
- const uvec4 shifts = uvec4(16, 8, 0, 24);
82277
- uvec4 col = (uvec4(id) >> shifts) & uvec4(0xff);
82278
- return vec4(col) * inv;
82279
- }
82280
-
82281
- #ifdef GSPLAT_PICK_DEPTH
82282
- #ifndef CAMERAPLANES
82283
- #define CAMERAPLANES
82284
- uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
82285
- #endif
82286
-
82287
- vec4 getPickOutput() {
82288
- float normalizedDepth;
82289
- if (camera_params.w > 0.5) {
82290
- normalizedDepth = gl_FragCoord.z;
82291
- } else {
82292
- float linearDepth = 1.0 / gl_FragCoord.w;
82293
- normalizedDepth = (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);
82294
- }
82295
-
82296
- return vec4(gaussianColor.a * normalizedDepth, 0.0, 0.0, gaussianColor.a);
82297
- }
82298
- #else
82299
- #ifndef PICK_CUSTOM_ID
82300
- uniform uint meshInstanceId;
82301
-
82302
- vec4 getPickOutput() {
82303
- return encodePickOutput(meshInstanceId);
82253
+ const SVGNS = 'http://www.w3.org/2000/svg';
82254
+ const NUM_SAMPLES = 12;
82255
+ const BASE_OUTER_RADIUS = 0.2;
82256
+ const INNER_OUTER_RATIO = 0.17 / 0.2;
82257
+ // Screen-space diameter (in CSS pixels) used for both hover and target
82258
+ // rings when the scene has no collision data. With collision present the
82259
+ // rings render world-space (BASE_OUTER_RADIUS) so they orient to the
82260
+ // surface; without collision the picks fall back to splat depth and a
82261
+ // fixed pixel size is more legible. Selection happens in
82262
+ // screenPixelsForRing(), keyed on state.hasCollision.
82263
+ const SCREEN_OUTER_PIXELS = 48;
82264
+ const BEZIER_K = 1 / 6;
82265
+ const NORMAL_SMOOTH_FACTOR = 0.25;
82266
+ const NORMAL_SNAP_ANGLE = Math.PI / 4;
82267
+ const NORMAL_EPSILON$1 = 1e-6;
82268
+ const createNormalSnapDirections = () => {
82269
+ const result = [];
82270
+ for (let pitchStep = -2; pitchStep <= 2; pitchStep++) {
82271
+ const pitch = pitchStep * NORMAL_SNAP_ANGLE;
82272
+ const cp = Math.cos(pitch);
82273
+ const sy = Math.sin(pitch);
82274
+ if (Math.abs(cp) <= NORMAL_EPSILON$1) {
82275
+ result.push(new Vec3(0, sy > 0 ? 1 : -1, 0));
82276
+ continue;
82304
82277
  }
82305
- #endif
82306
- #endif
82307
-
82308
- #ifdef DEPTH_PICK_PASS
82309
- #include "floatAsUintPS"
82310
- #ifndef CAMERAPLANES
82311
- #define CAMERAPLANES
82312
- uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
82313
- #endif
82314
-
82315
- vec4 getPickDepth() {
82316
- float linearDepth;
82317
- if (camera_params.w > 0.5) {
82318
- linearDepth = gl_FragCoord.z;
82319
- } else {
82320
- float viewDist = 1.0 / gl_FragCoord.w;
82321
- linearDepth = (viewDist - camera_params.z) / (camera_params.y - camera_params.z);
82278
+ for (let yawStep = 0; yawStep < 8; yawStep++) {
82279
+ const yaw = yawStep * NORMAL_SNAP_ANGLE;
82280
+ result.push(new Vec3(Math.cos(yaw) * cp, sy, Math.sin(yaw) * cp));
82322
82281
  }
82323
- return float2uint(linearDepth);
82324
82282
  }
82325
- #endif
82326
- `;
82327
- const pickDepthWgsl = /* wgsl */ `
82328
- fn encodePickOutput(id: u32) -> vec4f {
82329
- let inv: vec4f = vec4f(1.0 / 255.0);
82330
- let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);
82331
- let col: vec4u = (vec4u(id) >> shifts) & vec4u(0xffu);
82332
- return vec4f(col) * inv;
82333
- }
82334
-
82335
- #ifdef GSPLAT_PICK_DEPTH
82336
- #ifndef CAMERAPLANES
82337
- #define CAMERAPLANES
82338
- uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
82339
- #endif
82340
-
82341
- fn getPickOutput() -> vec4f {
82342
- var normalizedDepth: f32;
82343
- if (uniform.camera_params.w > 0.5) {
82344
- normalizedDepth = pcPosition.z;
82345
- } else {
82346
- let linearDepth = 1.0 / pcPosition.w;
82347
- normalizedDepth = (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
82348
- }
82349
-
82350
- let a = f32(gaussianColor.a);
82351
- return vec4f(a * normalizedDepth, 0.0, 0.0, a);
82283
+ return result;
82284
+ };
82285
+ const NORMAL_SNAP_DIRECTIONS = createNormalSnapDirections();
82286
+ const snapNormal = (nx, ny, nz, out) => {
82287
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
82288
+ if (len <= NORMAL_EPSILON$1) {
82289
+ return out.set(0, 1, 0);
82352
82290
  }
82353
- #else
82354
- #ifndef PICK_CUSTOM_ID
82355
- uniform meshInstanceId: u32;
82356
-
82357
- fn getPickOutput() -> vec4f {
82358
- return encodePickOutput(uniform.meshInstanceId);
82359
- }
82360
- #endif
82361
- #endif
82362
-
82363
- #ifdef DEPTH_PICK_PASS
82364
- #include "floatAsUintPS"
82365
- #ifndef CAMERAPLANES
82366
- #define CAMERAPLANES
82367
- uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
82368
- #endif
82369
-
82370
- fn getPickDepth() -> vec4f {
82371
- var linearDepth: f32;
82372
- if (uniform.camera_params.w > 0.5) {
82373
- linearDepth = pcPosition.z;
82374
- } else {
82375
- let viewDist = 1.0 / pcPosition.w;
82376
- linearDepth = (viewDist - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
82291
+ const invLen = 1 / len;
82292
+ const x = nx * invLen;
82293
+ const y = ny * invLen;
82294
+ const z = nz * invLen;
82295
+ let best = NORMAL_SNAP_DIRECTIONS[0];
82296
+ let bestDot = -Infinity;
82297
+ for (let i = 0; i < NORMAL_SNAP_DIRECTIONS.length; i++) {
82298
+ const candidate = NORMAL_SNAP_DIRECTIONS[i];
82299
+ const dot = candidate.x * x + candidate.y * y + candidate.z * z;
82300
+ if (dot > bestDot) {
82301
+ bestDot = dot;
82302
+ best = candidate;
82377
82303
  }
82378
- return float2uint(linearDepth);
82379
- }
82380
- #endif
82381
- `;
82382
- const pickPassChunkInjected = [
82383
- '#ifdef PICK_PASS',
82384
- ' #define GSPLAT_PICK_DEPTH',
82385
- ' #include "pickPS"',
82386
- '#endif'
82387
- ].join('\n');
82388
- const safeChunkReplace = (s, find, repl) => {
82389
- const out = s.replace(find, repl);
82390
- if (out === s) {
82391
- throw new Error('picker: engine gsplat/pick chunk patch failed (engine version mismatch?)');
82392
82304
  }
82393
- return out;
82305
+ return out.copy(best);
82394
82306
  };
82395
- const patchGsplatPickGlsl = (chunk) => {
82396
- return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'pcFragColor0 = encodePickOutput(vPickId);', 'pcFragColor0 = getPickOutput();');
82307
+ const tmpV = new Vec3();
82308
+ const tmpScreen = new Vec3();
82309
+ const tangent = new Vec3();
82310
+ const bitangent = new Vec3();
82311
+ const worldPt = new Vec3();
82312
+ const up = new Vec3(0, 1, 0);
82313
+ const right = new Vec3(1, 0, 0);
82314
+ // Compute the world-space radius such that a circle at `pos` projects to a
82315
+ // ring of `pixelDiameter` on screen. Used by the no-collision sizing path
82316
+ // (see screenPixelsForRing) to keep a constant on-screen diameter
82317
+ // regardless of camera distance.
82318
+ const worldRadiusForPixels = (camera, canvasHeight, pos, pixelDiameter) => {
82319
+ const cam = camera.camera;
82320
+ if (cam.projection === PROJECTION_ORTHOGRAPHIC) {
82321
+ return pixelDiameter * cam.orthoHeight / canvasHeight;
82322
+ }
82323
+ const camPos = camera.getPosition();
82324
+ const dx = pos.x - camPos.x;
82325
+ const dy = pos.y - camPos.y;
82326
+ const dz = pos.z - camPos.z;
82327
+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
82328
+ const halfFovTan = Math.tan(cam.fov * Math.PI / 360);
82329
+ return pixelDiameter * distance * halfFovTan / canvasHeight;
82397
82330
  };
82398
- const patchGsplatPickWgsl = (chunk) => {
82399
- return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'output.color = encodePickOutput(vPickId);', 'output.color = getPickOutput();');
82331
+ const buildBezierRing = (sx, sy) => {
82332
+ const n = sx.length;
82333
+ let p = `M${sx[0].toFixed(1)},${sy[0].toFixed(1)}`;
82334
+ for (let i = 0; i < n; i++) {
82335
+ const i0 = (i - 1 + n) % n;
82336
+ const i1 = i;
82337
+ const i2 = (i + 1) % n;
82338
+ const i3 = (i + 2) % n;
82339
+ const cp1x = sx[i1] + (sx[i2] - sx[i0]) * BEZIER_K;
82340
+ const cp1y = sy[i1] + (sy[i2] - sy[i0]) * BEZIER_K;
82341
+ const cp2x = sx[i2] - (sx[i3] - sx[i1]) * BEZIER_K;
82342
+ const cp2y = sy[i2] - (sy[i3] - sy[i1]) * BEZIER_K;
82343
+ p += ` C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${sx[i2].toFixed(1)},${sy[i2].toFixed(1)}`;
82344
+ }
82345
+ return `${p} Z`;
82400
82346
  };
82401
- /** Per-device original chunk strings + refcount so we can restore after the last Picker releases. */
82402
- const pickerShaderPatchState = new WeakMap();
82403
- const vec4 = new Vec4();
82404
- const viewProjMat = new Mat4();
82405
- const clearColor = new Color(0, 0, 0, 1);
82406
- const NORMAL_EPSILON$1 = 1e-12;
82407
- const NORMAL_DEGENERATE_EPSILON = 1e-20;
82408
- // Sampling for the surface-normal estimator runs on a circular footprint of
82409
- // fixed *world* radius, projected to pixels at the picked-point's depth.
82410
- // Keeping the world area constant means adjacent cursor positions sample
82411
- // almost the same world cluster, which stabilises the plane fit. The pixel
82412
- // radius is clamped so distant picks still get enough samples and very-close
82413
- // picks don't blow the block read.
82414
- const NORMAL_SAMPLE_WORLD_RADIUS = 0.2;
82415
- const NORMAL_SAMPLE_MIN_PX = 6;
82416
- const NORMAL_SAMPLE_MAX_PX = 48;
82417
- const NORMAL_RING_FRACTIONS = [0.3, 0.55, 0.8, 1.0];
82418
- const NORMAL_OUTLIER_THRESHOLD = 2.5;
82419
- const NORMAL_SAMPLE_DIRECTIONS = [
82420
- [1, 0],
82421
- [1, 1],
82422
- [0, 1],
82423
- [-1, 1],
82424
- [-1, 0],
82425
- [-1, -1],
82426
- [0, -1],
82427
- [1, -1]
82428
- ];
82429
- // Shared buffer for half-to-float conversion
82430
- const float32 = new Float32Array(1);
82431
- const uint32 = new Uint32Array(float32.buffer);
82432
- // Convert 16-bit half-float to 32-bit float using bit manipulation.
82433
- const half2Float = (h) => {
82434
- const sign = (h & 0x8000) << 16;
82435
- const exponent = (h & 0x7C00) >> 10;
82436
- const mantissa = h & 0x03FF;
82437
- if (exponent === 0) {
82438
- if (mantissa === 0) {
82439
- uint32[0] = sign;
82347
+ class CursorRing {
82348
+ path;
82349
+ svg;
82350
+ canvas;
82351
+ camera;
82352
+ smoothing;
82353
+ smoothNx = 0;
82354
+ smoothNy = 1;
82355
+ smoothNz = 0;
82356
+ hasSmoothedNormal = false;
82357
+ outerX = new Float64Array(NUM_SAMPLES);
82358
+ outerY = new Float64Array(NUM_SAMPLES);
82359
+ innerX = new Float64Array(NUM_SAMPLES);
82360
+ innerY = new Float64Array(NUM_SAMPLES);
82361
+ constructor(svg, canvas, camera, smoothing) {
82362
+ this.svg = svg;
82363
+ this.canvas = canvas;
82364
+ this.camera = camera;
82365
+ this.smoothing = smoothing;
82366
+ this.path = document.createElementNS(SVGNS, 'path');
82367
+ this.path.setAttribute('fill', 'white');
82368
+ this.path.setAttribute('fill-opacity', '0.6');
82369
+ this.path.setAttribute('fill-rule', 'evenodd');
82370
+ this.path.setAttribute('stroke', 'none');
82371
+ this.path.style.display = 'none';
82372
+ svg.appendChild(this.path);
82373
+ }
82374
+ projectCircle(px, py, pz, nx, ny, nz, radius, outX, outY) {
82375
+ const normal = tmpV.set(nx, ny, nz);
82376
+ if (Math.abs(normal.y) < 0.99) {
82377
+ tangent.cross(normal, up).normalize();
82440
82378
  }
82441
82379
  else {
82442
- let e = -1;
82443
- let m = mantissa;
82444
- do {
82445
- e++;
82446
- m <<= 1;
82447
- } while ((m & 0x0400) === 0);
82448
- uint32[0] = sign | ((127 - 15 - e) << 23) | ((m & 0x03FF) << 13);
82380
+ tangent.cross(normal, right).normalize();
82381
+ }
82382
+ bitangent.cross(normal, tangent);
82383
+ const cam = this.camera.camera;
82384
+ const angleStep = (2 * Math.PI) / NUM_SAMPLES;
82385
+ for (let i = 0; i < NUM_SAMPLES; i++) {
82386
+ const theta = i * angleStep;
82387
+ const ct = Math.cos(theta);
82388
+ const st = Math.sin(theta);
82389
+ const tx = ct * tangent.x + st * bitangent.x;
82390
+ const ty = ct * tangent.y + st * bitangent.y;
82391
+ const tz = ct * tangent.z + st * bitangent.z;
82392
+ worldPt.set(px + tx * radius, py + ty * radius, pz + tz * radius);
82393
+ cam.worldToScreen(worldPt, tmpScreen);
82394
+ outX[i] = tmpScreen.x;
82395
+ outY[i] = tmpScreen.y;
82449
82396
  }
82450
82397
  }
82451
- else if (exponent === 31) {
82452
- uint32[0] = sign | 0x7F800000 | (mantissa << 13);
82453
- }
82454
- else {
82455
- uint32[0] = sign | ((exponent + 127 - 15) << 23) | (mantissa << 13);
82398
+ // screenPixels: null → world-space ring (fixed world radius, shrinks
82399
+ // with distance); number → constant on-screen diameter in CSS pixels.
82400
+ render(pos, normal, screenPixels) {
82401
+ snapNormal(normal.x, normal.y, normal.z, tmpV);
82402
+ let nx = tmpV.x;
82403
+ let ny = tmpV.y;
82404
+ let nz = tmpV.z;
82405
+ if (this.smoothing) {
82406
+ if (this.hasSmoothedNormal) {
82407
+ const t = NORMAL_SMOOTH_FACTOR;
82408
+ nx = this.smoothNx + (nx - this.smoothNx) * t;
82409
+ ny = this.smoothNy + (ny - this.smoothNy) * t;
82410
+ nz = this.smoothNz + (nz - this.smoothNz) * t;
82411
+ const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
82412
+ if (len > 1e-6) {
82413
+ const invLen = 1.0 / len;
82414
+ nx *= invLen;
82415
+ ny *= invLen;
82416
+ nz *= invLen;
82417
+ }
82418
+ }
82419
+ this.smoothNx = nx;
82420
+ this.smoothNy = ny;
82421
+ this.smoothNz = nz;
82422
+ this.hasSmoothedNormal = true;
82423
+ }
82424
+ const outerRadius = screenPixels !== null ?
82425
+ worldRadiusForPixels(this.camera, this.canvas.clientHeight || 1, pos, screenPixels) :
82426
+ BASE_OUTER_RADIUS;
82427
+ const innerRadius = outerRadius * INNER_OUTER_RATIO;
82428
+ this.projectCircle(pos.x, pos.y, pos.z, nx, ny, nz, outerRadius, this.outerX, this.outerY);
82429
+ this.projectCircle(pos.x, pos.y, pos.z, nx, ny, nz, innerRadius, this.innerX, this.innerY);
82430
+ this.path.setAttribute('d', `${buildBezierRing(this.outerX, this.outerY)} ${buildBezierRing(this.innerX, this.innerY)}`);
82431
+ this.path.style.display = '';
82432
+ this.svg.style.display = '';
82456
82433
  }
82457
- return float32[0];
82458
- };
82459
- const registerPickerShaderPatches = (app) => {
82460
- const device = app.graphicsDevice;
82461
- const existing = pickerShaderPatchState.get(device);
82462
- if (existing) {
82463
- existing.refCount++;
82464
- return;
82434
+ hide() {
82435
+ this.path.style.display = 'none';
82436
+ this.hasSmoothedNormal = false;
82465
82437
  }
82466
- const glslChunks = ShaderChunks.get(device, 'glsl');
82467
- const wgslChunks = ShaderChunks.get(device, 'wgsl');
82468
- const glslPickPS = glslChunks.get('pickPS');
82469
- const glslGsplatPS = glslChunks.get('gsplatPS');
82470
- const wgslPickPS = wgslChunks.get('pickPS');
82471
- const wgslGsplatPS = wgslChunks.get('gsplatPS');
82472
- // Patch strings before mutating ShaderChunks so engine mismatches leave globals untouched.
82473
- const patchedGlslGsplatPS = patchGsplatPickGlsl(glslGsplatPS);
82474
- const patchedWgslGsplatPS = patchGsplatPickWgsl(wgslGsplatPS);
82475
- const state = {
82476
- glslPickPS,
82477
- glslGsplatPS,
82478
- wgslPickPS,
82479
- wgslGsplatPS,
82480
- refCount: 1
82438
+ }
82439
+ class NavCursor {
82440
+ svg;
82441
+ hoverRing;
82442
+ targetRing;
82443
+ camera;
82444
+ collision;
82445
+ canvas;
82446
+ state;
82447
+ app;
82448
+ onPrerender;
82449
+ // True when the hover ring should track the pointer. Only walk mode
82450
+ // (with mouse navigation, not gaming controls) shows the hover ring;
82451
+ // fly/orbit only show the target ring on click.
82452
+ hoverActive = false;
82453
+ navigating = false;
82454
+ targetPos = null;
82455
+ targetNormal = null;
82456
+ targetMode = null;
82457
+ onPointerMove;
82458
+ onPointerLeave;
82459
+ collisionTarget = {
82460
+ position: new Vec3(),
82461
+ normal: new Vec3()
82481
82462
  };
82482
- pickerShaderPatchState.set(device, state);
82483
- glslChunks.set('pickPS', pickDepthGlsl);
82484
- wgslChunks.set('pickPS', pickDepthWgsl);
82485
- glslChunks.set('gsplatPS', patchedGlslGsplatPS);
82486
- wgslChunks.set('gsplatPS', patchedWgslGsplatPS);
82487
- };
82488
- const unregisterPickerShaderPatches = (app) => {
82489
- const device = app.graphicsDevice;
82490
- const state = pickerShaderPatchState.get(device);
82491
- if (!state) {
82492
- return;
82463
+ constructor(app, camera, collision, events, state) {
82464
+ this.camera = camera;
82465
+ this.collision = collision;
82466
+ this.canvas = app.graphicsDevice.canvas;
82467
+ this.state = state;
82468
+ this.app = app;
82469
+ this.svg = document.createElementNS(SVGNS, 'svg');
82470
+ this.svg.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:1';
82471
+ this.canvas.parentElement.appendChild(this.svg);
82472
+ this.hoverRing = new CursorRing(this.svg, this.canvas, camera, true);
82473
+ this.targetRing = new CursorRing(this.svg, this.canvas, camera, false);
82474
+ this.svg.style.display = 'none';
82475
+ this.onPointerMove = (e) => {
82476
+ if (e.pointerType === 'touch' || e.buttons) {
82477
+ this.hoverRing.hide();
82478
+ return;
82479
+ }
82480
+ this.updateCursor(e.offsetX, e.offsetY);
82481
+ };
82482
+ this.onPointerLeave = () => {
82483
+ this.hoverRing.hide();
82484
+ };
82485
+ this.canvas.addEventListener('pointermove', this.onPointerMove);
82486
+ this.canvas.addEventListener('pointerleave', this.onPointerLeave);
82487
+ const updateActive = () => {
82488
+ // Hover ring only in walk mode with mouse navigation. Gaming
82489
+ // controls use pointer-lock and don't need a hover preview.
82490
+ this.hoverActive = state.cameraMode === 'walk' && !state.gamingControls;
82491
+ this.hoverRing.hide();
82492
+ if (this.targetMode && this.targetMode !== state.cameraMode) {
82493
+ this.navigating = false;
82494
+ this.clearTarget();
82495
+ }
82496
+ };
82497
+ events.on('cameraMode:changed', updateActive);
82498
+ events.on('inputMode:changed', updateActive);
82499
+ events.on('gamingControls:changed', updateActive);
82500
+ events.on('navigateTo', () => {
82501
+ this.navigating = true;
82502
+ this.hoverRing.hide();
82503
+ });
82504
+ events.on('navigateCancel', () => {
82505
+ this.navigating = false;
82506
+ this.clearTarget();
82507
+ });
82508
+ events.on('navigateComplete', () => {
82509
+ this.navigating = false;
82510
+ this.clearTarget();
82511
+ });
82512
+ events.on('navTarget:set', (pos, normal) => {
82513
+ const mode = state.cameraMode === 'walk' || state.cameraMode === 'fly' ?
82514
+ state.cameraMode : 'walk';
82515
+ this.setTarget(pos, normal, mode);
82516
+ });
82517
+ events.on('navTarget:clear', () => {
82518
+ this.clearTarget();
82519
+ });
82520
+ events.on('orbitTarget:set', (pos, normal) => {
82521
+ this.navigating = false;
82522
+ this.setTarget(pos, normal, 'orbit');
82523
+ });
82524
+ events.on('orbitTarget:clear', () => {
82525
+ if (this.targetMode === 'orbit') {
82526
+ this.clearTarget();
82527
+ }
82528
+ });
82529
+ this.onPrerender = () => {
82530
+ this.updateTarget();
82531
+ };
82532
+ app.on('prerender', this.onPrerender);
82533
+ updateActive();
82493
82534
  }
82494
- state.refCount--;
82495
- if (state.refCount > 0) {
82496
- return;
82535
+ // Ring sizing is per-scene: when the scene has collision data we get
82536
+ // accurate surface picks with real normals, so world-space rings read
82537
+ // as physical footprints on the surface with visible orientation.
82538
+ // Without collision the pick falls back to splat depth which can be
82539
+ // noisy at distance, so a fixed screen-size ring is more legible.
82540
+ screenPixelsForRing() {
82541
+ return this.state.hasCollision ? null : SCREEN_OUTER_PIXELS;
82497
82542
  }
82498
- const glslChunks = ShaderChunks.get(device, 'glsl');
82499
- const wgslChunks = ShaderChunks.get(device, 'wgsl');
82500
- glslChunks.set('pickPS', state.glslPickPS);
82501
- glslChunks.set('gsplatPS', state.glslGsplatPS);
82502
- wgslChunks.set('pickPS', state.wgslPickPS);
82503
- wgslChunks.set('gsplatPS', state.wgslGsplatPS);
82504
- pickerShaderPatchState.delete(device);
82505
- };
82506
- const createPickCameraSnapshot = () => ({
82507
- position: new Vec3(),
82508
- viewMatrix: new Mat4(),
82509
- projectionMatrix: new Mat4(),
82510
- nearClip: 0,
82511
- farClip: 0,
82512
- projection: 0
82513
- });
82514
- const captureCameraSnapshot = (camera, out) => {
82515
- const cam = camera.camera;
82516
- out.position.copy(camera.getPosition());
82517
- out.viewMatrix.copy(cam.viewMatrix);
82518
- out.projectionMatrix.copy(cam.projectionMatrix);
82519
- out.nearClip = cam.nearClip;
82520
- out.farClip = cam.farClip;
82521
- out.projection = cam.projection;
82522
- };
82523
- const getWorldPoint = (camera, x, y, width, height, normalizedDepth, out) => {
82524
- if (!Number.isFinite(normalizedDepth) || normalizedDepth < 0 || normalizedDepth > 1) {
82525
- return null;
82526
- }
82527
- const { farClip: far, nearClip: near } = camera;
82528
- const ndcDepth = camera.projection === PROJECTION_ORTHOGRAPHIC ?
82529
- normalizedDepth :
82530
- far * normalizedDepth / (normalizedDepth * (far - near) + near);
82531
- viewProjMat.mul2(camera.projectionMatrix, camera.viewMatrix).invert();
82532
- vec4.set(x / width * 2 - 1, (1 - y / height) * 2 - 1, ndcDepth * 2 - 1, 1);
82533
- viewProjMat.transformVec4(vec4, vec4);
82534
- if (!Number.isFinite(vec4.w) || Math.abs(vec4.w) < 1e-8) {
82535
- return null;
82543
+ setTarget(pos, normal, mode) {
82544
+ this.targetPos = pos.clone();
82545
+ this.targetNormal = normal.clone();
82546
+ this.targetMode = mode;
82547
+ this.hoverRing.hide();
82548
+ this.targetRing.hide();
82536
82549
  }
82537
- vec4.mulScalar(1 / vec4.w);
82538
- if (!Number.isFinite(vec4.x) || !Number.isFinite(vec4.y) || !Number.isFinite(vec4.z)) {
82539
- return null;
82550
+ clearTarget() {
82551
+ this.targetPos = null;
82552
+ this.targetNormal = null;
82553
+ this.targetMode = null;
82554
+ this.targetRing.hide();
82540
82555
  }
82541
- return (out ?? new Vec3()).set(vec4.x, vec4.y, vec4.z);
82542
- };
82543
- const setCameraFacingNormal = (cameraPosition, position, normal) => {
82544
- normal.sub2(cameraPosition, position);
82545
- const len = normal.length();
82546
- if (len > 1e-6) {
82547
- normal.mulScalar(1 / len);
82556
+ pickCollision(offsetX, offsetY) {
82557
+ if (!this.collision) {
82558
+ return null;
82559
+ }
82560
+ const { camera, collision } = this;
82561
+ const cameraPos = camera.getPosition();
82562
+ camera.camera.screenToWorld(offsetX, offsetY, 1.0, tmpV);
82563
+ tmpV.sub(cameraPos).normalize();
82564
+ const hit = collision.queryRay(cameraPos.x, cameraPos.y, cameraPos.z, tmpV.x, tmpV.y, tmpV.z, camera.camera.farClip);
82565
+ if (!hit) {
82566
+ return null;
82567
+ }
82568
+ const sn = collision.querySurfaceNormal(hit.x, hit.y, hit.z, tmpV.x, tmpV.y, tmpV.z);
82569
+ this.collisionTarget.position.set(hit.x, hit.y, hit.z);
82570
+ this.collisionTarget.normal.set(sn.nx, sn.ny, sn.nz);
82571
+ return this.collisionTarget;
82548
82572
  }
82549
- else {
82550
- normal.set(0, 1, 0);
82573
+ updateCursor(offsetX, offsetY) {
82574
+ if (!this.hoverActive || this.navigating) {
82575
+ this.hoverRing.hide();
82576
+ return;
82577
+ }
82578
+ const target = this.pickCollision(offsetX, offsetY);
82579
+ if (!target) {
82580
+ this.hoverRing.hide();
82581
+ return;
82582
+ }
82583
+ this.hoverRing.render(target.position, target.normal, this.screenPixelsForRing());
82551
82584
  }
82552
- return normal;
82553
- };
82554
- // Project a world-space radius around `pos` to its on-screen pixel radius for
82555
- // the given camera. Uses the projection matrix's [1][1] entry (= 1/tan(fov/2)
82556
- // for perspective, = 1/orthoHeight for orthographic) so we don't need fov or
82557
- // orthoHeight on the snapshot.
82558
- const worldRadiusToPixelRadius = (cam, pos, canvasHeight, worldRadius) => {
82559
- const projY = cam.projectionMatrix.data[5];
82560
- if (cam.projection === PROJECTION_ORTHOGRAPHIC) {
82561
- return worldRadius * projY * canvasHeight / 2;
82585
+ updateTarget() {
82586
+ if (!this.targetPos || !this.targetNormal || !this.targetMode) {
82587
+ return;
82588
+ }
82589
+ const camPos = this.camera.getPosition();
82590
+ const dist = camPos.distance(this.targetPos);
82591
+ if (this.targetMode !== 'orbit' && dist < 2.0) {
82592
+ this.targetRing.hide();
82593
+ return;
82594
+ }
82595
+ this.targetRing.render(this.targetPos, this.targetNormal, this.screenPixelsForRing());
82562
82596
  }
82563
- const dx = pos.x - cam.position.x;
82564
- const dy = pos.y - cam.position.y;
82565
- const dz = pos.z - cam.position.z;
82566
- const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
82567
- if (distance < 1e-6)
82568
- return Infinity;
82569
- return worldRadius * projY * canvasHeight / (2 * distance);
82570
- };
82571
- // Single least-squares plane fit through a cluster of 3D points. The normal
82572
- // is the eigenvector of the smallest eigenvalue of the points' 3x3 covariance
82573
- // matrix, computed in closed form (analytic eigendecomposition for 3x3
82574
- // symmetric, Smith 1961). Returns null on degenerate input.
82575
- const fitPlaneOnce = (points) => {
82576
- const n = points.length;
82577
- if (n < 3)
82578
- return null;
82579
- let cx = 0, cy = 0, cz = 0;
82580
- for (let i = 0; i < n; i++) {
82581
- cx += points[i].x;
82582
- cy += points[i].y;
82583
- cz += points[i].z;
82597
+ destroy() {
82598
+ this.app.off('prerender', this.onPrerender);
82599
+ this.canvas.removeEventListener('pointermove', this.onPointerMove);
82600
+ this.canvas.removeEventListener('pointerleave', this.onPointerLeave);
82601
+ this.svg.remove();
82584
82602
  }
82585
- cx /= n;
82586
- cy /= n;
82587
- cz /= n;
82588
- let cxx = 0, cxy = 0, cxz = 0, cyy = 0, cyz = 0, czz = 0;
82589
- for (let i = 0; i < n; i++) {
82590
- const dx = points[i].x - cx;
82591
- const dy = points[i].y - cy;
82592
- const dz = points[i].z - cz;
82593
- cxx += dx * dx;
82594
- cxy += dx * dy;
82595
- cxz += dx * dz;
82596
- cyy += dy * dy;
82597
- cyz += dy * dz;
82598
- czz += dz * dz;
82603
+ }
82604
+
82605
+ /**
82606
+ * World picking for splat scenes.
82607
+ *
82608
+ * Uses a custom `pickPS` / `gsplatPS` patch plus `RGBA16F` alpha-weighted depth accumulation,
82609
+ * because the stock pick pass encodes splat IDs / last-fragment depth rather than expected depth.
82610
+ */
82611
+ // Override global picking to pack alpha-weighted splat depth instead of meshInstance id.
82612
+ const pickDepthGlsl = /* glsl */ `
82613
+ vec4 encodePickOutput(uint id) {
82614
+ const vec4 inv = vec4(1.0 / 255.0);
82615
+ const uvec4 shifts = uvec4(16, 8, 0, 24);
82616
+ uvec4 col = (uvec4(id) >> shifts) & uvec4(0xff);
82617
+ return vec4(col) * inv;
82618
+ }
82619
+
82620
+ #ifdef GSPLAT_PICK_DEPTH
82621
+ #ifndef CAMERAPLANES
82622
+ #define CAMERAPLANES
82623
+ uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
82624
+ #endif
82625
+
82626
+ vec4 getPickOutput() {
82627
+ float normalizedDepth;
82628
+ if (camera_params.w > 0.5) {
82629
+ normalizedDepth = gl_FragCoord.z;
82630
+ } else {
82631
+ float linearDepth = 1.0 / gl_FragCoord.w;
82632
+ normalizedDepth = (linearDepth - camera_params.z) / (camera_params.y - camera_params.z);
82633
+ }
82634
+
82635
+ return vec4(gaussianColor.a * normalizedDepth, 0.0, 0.0, gaussianColor.a);
82599
82636
  }
82600
- const q = (cxx + cyy + czz) / 3;
82601
- const a = cxx - q, b = cyy - q, c = czz - q;
82602
- const p2 = a * a + b * b + c * c + 2 * (cxy * cxy + cxz * cxz + cyz * cyz);
82603
- if (p2 < NORMAL_DEGENERATE_EPSILON)
82604
- return null;
82605
- const p = Math.sqrt(p2 / 6);
82606
- const inv = 1 / p;
82607
- const Bxx = a * inv, Bxy = cxy * inv, Bxz = cxz * inv;
82608
- const Byy = b * inv, Byz = cyz * inv, Bzz = c * inv;
82609
- const detB = Bxx * (Byy * Bzz - Byz * Byz) -
82610
- Bxy * (Bxy * Bzz - Byz * Bxz) +
82611
- Bxz * (Bxy * Byz - Byy * Bxz);
82612
- const r = Math.max(-1, Math.min(1, detB / 2));
82613
- const phi = Math.acos(r) / 3;
82614
- const lambdaMin = q + 2 * p * Math.cos(phi + 2 * Math.PI / 3);
82615
- const Mxx = cxx - lambdaMin, Myy = cyy - lambdaMin, Mzz = czz - lambdaMin;
82616
- const v1x = cxy * cyz - cxz * Myy;
82617
- const v1y = cxz * cxy - Mxx * cyz;
82618
- const v1z = Mxx * Myy - cxy * cxy;
82619
- const v2x = cxy * Mzz - cxz * cyz;
82620
- const v2y = cxz * cxz - Mxx * Mzz;
82621
- const v2z = Mxx * cyz - cxy * cxz;
82622
- const v3x = Myy * Mzz - cyz * cyz;
82623
- const v3y = cyz * cxz - cxy * Mzz;
82624
- const v3z = cxy * cyz - Myy * cxz;
82625
- const l1 = v1x * v1x + v1y * v1y + v1z * v1z;
82626
- const l2 = v2x * v2x + v2y * v2y + v2z * v2z;
82627
- const l3 = v3x * v3x + v3y * v3y + v3z * v3z;
82628
- let vx, vy, vz, lSq;
82629
- if (l1 >= l2 && l1 >= l3) {
82630
- vx = v1x;
82631
- vy = v1y;
82632
- vz = v1z;
82633
- lSq = l1;
82637
+ #else
82638
+ #ifndef PICK_CUSTOM_ID
82639
+ uniform uint meshInstanceId;
82640
+
82641
+ vec4 getPickOutput() {
82642
+ return encodePickOutput(meshInstanceId);
82643
+ }
82644
+ #endif
82645
+ #endif
82646
+
82647
+ #ifdef DEPTH_PICK_PASS
82648
+ #include "floatAsUintPS"
82649
+ #ifndef CAMERAPLANES
82650
+ #define CAMERAPLANES
82651
+ uniform vec4 camera_params; // x: 1/far, y: far, z: near, w: isOrtho
82652
+ #endif
82653
+
82654
+ vec4 getPickDepth() {
82655
+ float linearDepth;
82656
+ if (camera_params.w > 0.5) {
82657
+ linearDepth = gl_FragCoord.z;
82658
+ } else {
82659
+ float viewDist = 1.0 / gl_FragCoord.w;
82660
+ linearDepth = (viewDist - camera_params.z) / (camera_params.y - camera_params.z);
82661
+ }
82662
+ return float2uint(linearDepth);
82634
82663
  }
82635
- else if (l2 >= l3) {
82636
- vx = v2x;
82637
- vy = v2y;
82638
- vz = v2z;
82639
- lSq = l2;
82664
+ #endif
82665
+ `;
82666
+ const pickDepthWgsl = /* wgsl */ `
82667
+ fn encodePickOutput(id: u32) -> vec4f {
82668
+ let inv: vec4f = vec4f(1.0 / 255.0);
82669
+ let shifts: vec4u = vec4u(16u, 8u, 0u, 24u);
82670
+ let col: vec4u = (vec4u(id) >> shifts) & vec4u(0xffu);
82671
+ return vec4f(col) * inv;
82672
+ }
82673
+
82674
+ #ifdef GSPLAT_PICK_DEPTH
82675
+ #ifndef CAMERAPLANES
82676
+ #define CAMERAPLANES
82677
+ uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
82678
+ #endif
82679
+
82680
+ fn getPickOutput() -> vec4f {
82681
+ var normalizedDepth: f32;
82682
+ if (uniform.camera_params.w > 0.5) {
82683
+ normalizedDepth = pcPosition.z;
82684
+ } else {
82685
+ let linearDepth = 1.0 / pcPosition.w;
82686
+ normalizedDepth = (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
82687
+ }
82688
+
82689
+ let a = f32(gaussianColor.a);
82690
+ return vec4f(a * normalizedDepth, 0.0, 0.0, a);
82640
82691
  }
82641
- else {
82642
- vx = v3x;
82643
- vy = v3y;
82644
- vz = v3z;
82645
- lSq = l3;
82646
- }
82647
- if (lSq < NORMAL_EPSILON$1)
82648
- return null;
82649
- const invLen = 1 / Math.sqrt(lSq);
82650
- return { cx, cy, cz, vx: vx * invLen, vy: vy * invLen, vz: vz * invLen };
82651
- };
82652
- // Two-pass plane fit: first pass on all points, then drop points whose
82653
- // distance from the fitted plane exceeds NORMAL_OUTLIER_THRESHOLD * the mean
82654
- // residual, refit on the inliers. Sign-flips the result toward toCamera so
82655
- // the cursor's tangent basis stays consistent. Returns false on degenerate
82656
- // input (fewer than 3 points, collinear/coincident samples).
82657
- const fitPlaneNormal = (points, toCamera, outNormal) => {
82658
- const first = fitPlaneOnce(points);
82659
- if (!first)
82660
- return false;
82661
- let residualSum = 0;
82662
- for (let i = 0; i < points.length; i++) {
82663
- const dx = points[i].x - first.cx;
82664
- const dy = points[i].y - first.cy;
82665
- const dz = points[i].z - first.cz;
82666
- residualSum += Math.abs(dx * first.vx + dy * first.vy + dz * first.vz);
82667
- }
82668
- const threshold = (residualSum / points.length) * NORMAL_OUTLIER_THRESHOLD;
82669
- const inliers = [];
82670
- for (let i = 0; i < points.length; i++) {
82671
- const dx = points[i].x - first.cx;
82672
- const dy = points[i].y - first.cy;
82673
- const dz = points[i].z - first.cz;
82674
- if (Math.abs(dx * first.vx + dy * first.vy + dz * first.vz) <= threshold) {
82675
- inliers.push(points[i]);
82692
+ #else
82693
+ #ifndef PICK_CUSTOM_ID
82694
+ uniform meshInstanceId: u32;
82695
+
82696
+ fn getPickOutput() -> vec4f {
82697
+ return encodePickOutput(uniform.meshInstanceId);
82676
82698
  }
82699
+ #endif
82700
+ #endif
82701
+
82702
+ #ifdef DEPTH_PICK_PASS
82703
+ #include "floatAsUintPS"
82704
+ #ifndef CAMERAPLANES
82705
+ #define CAMERAPLANES
82706
+ uniform camera_params: vec4f; // x: 1/far, y: far, z: near, w: isOrtho
82707
+ #endif
82708
+
82709
+ fn getPickDepth() -> vec4f {
82710
+ var linearDepth: f32;
82711
+ if (uniform.camera_params.w > 0.5) {
82712
+ linearDepth = pcPosition.z;
82713
+ } else {
82714
+ let viewDist = 1.0 / pcPosition.w;
82715
+ linearDepth = (viewDist - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z);
82716
+ }
82717
+ return float2uint(linearDepth);
82677
82718
  }
82678
- let result = first;
82679
- if (inliers.length >= 3 && inliers.length < points.length) {
82680
- const refined = fitPlaneOnce(inliers);
82681
- if (refined)
82682
- result = refined;
82683
- }
82684
- let { vx, vy, vz } = result;
82685
- if (vx * toCamera.x + vy * toCamera.y + vz * toCamera.z < 0) {
82686
- vx = -vx;
82687
- vy = -vy;
82688
- vz = -vz;
82719
+ #endif
82720
+ `;
82721
+ const pickPassChunkInjected = [
82722
+ '#ifdef PICK_PASS',
82723
+ ' #define GSPLAT_PICK_DEPTH',
82724
+ ' #include "pickPS"',
82725
+ '#endif'
82726
+ ].join('\n');
82727
+ const safeChunkReplace = (s, find, repl) => {
82728
+ const out = s.replace(find, repl);
82729
+ if (out === s) {
82730
+ throw new Error('picker: engine gsplat/pick chunk patch failed (engine version mismatch?)');
82689
82731
  }
82690
- outNormal.set(vx, vy, vz);
82691
- return true;
82732
+ return out;
82692
82733
  };
82693
- class Picker {
82694
- pick;
82695
- pickSurface;
82696
- release;
82697
- constructor(app, camera) {
82698
- const { graphicsDevice } = app;
82699
- let accumBuffer;
82700
- let accumTarget;
82701
- let accumPass;
82702
- let chunksPatched = false;
82703
- let pickQueue = Promise.resolve();
82704
- let cacheValid = false;
82705
- let cacheWidth = 0;
82706
- let cacheHeight = 0;
82707
- const cacheCamera = createPickCameraSnapshot();
82708
- const initRasterAccum = (width, height) => {
82709
- accumBuffer = new Texture(graphicsDevice, {
82710
- format: PIXELFORMAT_RGBA16F,
82711
- width,
82712
- height,
82713
- mipmaps: false,
82714
- minFilter: FILTER_NEAREST,
82715
- magFilter: FILTER_NEAREST,
82716
- addressU: ADDRESS_CLAMP_TO_EDGE,
82717
- addressV: ADDRESS_CLAMP_TO_EDGE,
82718
- name: 'picker-accum'
82719
- });
82720
- accumTarget = new RenderTarget({
82721
- colorBuffer: accumBuffer,
82722
- depth: false // not needed — gaussians are rendered back to front
82723
- });
82724
- accumPass = new RenderPassPicker(graphicsDevice, app.renderer);
82725
- // RGB: additive depth accumulation. Alpha: multiplicative transmittance.
82726
- accumPass.blendState = new BlendState(true, BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ONE_MINUS_SRC_ALPHA, BLENDEQUATION_ADD, BLENDMODE_ZERO, BLENDMODE_ONE_MINUS_SRC_ALPHA);
82727
- };
82728
- const readTexture = (texture, x, y, target) => {
82729
- const texY = graphicsDevice.isWebGL2 ? target.height - y - 1 : y;
82730
- return texture.read(x, texY, 1, 1, {
82731
- renderTarget: target,
82732
- immediate: true
82733
- });
82734
- };
82735
- const updateCache = (width, height) => {
82736
- captureCameraSnapshot(camera, cacheCamera);
82737
- cacheWidth = width;
82738
- cacheHeight = height;
82739
- };
82740
- const cameraMatches = (width, height) => {
82741
- const cam = camera.camera;
82742
- return cacheValid &&
82743
- cacheWidth === width &&
82744
- cacheHeight === height &&
82745
- cacheCamera.viewMatrix.equals(cam.viewMatrix) &&
82746
- cacheCamera.projectionMatrix.equals(cam.projectionMatrix) &&
82747
- cacheCamera.nearClip === cam.nearClip &&
82748
- cacheCamera.farClip === cam.farClip &&
82749
- cacheCamera.projection === cam.projection;
82750
- };
82751
- const getCacheCameraSnapshot = () => {
82752
- const snapshot = createPickCameraSnapshot();
82753
- snapshot.position.copy(cacheCamera.position);
82754
- snapshot.viewMatrix.copy(cacheCamera.viewMatrix);
82755
- snapshot.projectionMatrix.copy(cacheCamera.projectionMatrix);
82756
- snapshot.nearClip = cacheCamera.nearClip;
82757
- snapshot.farClip = cacheCamera.farClip;
82758
- snapshot.projection = cacheCamera.projection;
82759
- return snapshot;
82760
- };
82761
- const readRasterBlock = async (blockX, blockY, blockWidth, blockHeight, viewportWidth, viewportHeight, pickCamera) => {
82762
- const texY = graphicsDevice.isWebGL2 ? accumTarget.height - blockY - blockHeight : blockY;
82763
- const pixels = await accumBuffer.read(blockX, texY, blockWidth, blockHeight, {
82764
- renderTarget: accumTarget,
82765
- immediate: true
82766
- });
82767
- return (x, y) => {
82768
- const localX = x - blockX;
82769
- const localY = y - blockY;
82770
- if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
82771
- return null;
82772
- }
82773
- const row = graphicsDevice.isWebGL2 ? blockHeight - localY - 1 : localY;
82774
- const index = (row * blockWidth + localX) * 4;
82775
- const r = half2Float(pixels[index]);
82776
- const transmittance = half2Float(pixels[index + 3]);
82777
- const alpha = 1 - transmittance;
82778
- if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
82779
- return null;
82780
- }
82781
- const normalizedDepth = r / alpha;
82782
- return getWorldPoint(pickCamera, x, y, viewportWidth, viewportHeight, normalizedDepth);
82783
- };
82784
- };
82785
- const ensureRendered = (width, height, worldLayer) => {
82786
- if (cameraMatches(width, height)) {
82787
- return;
82788
- }
82789
- // Enable gsplat IDs only while rendering the pick target so we
82790
- // don't pay the memory/perf cost between pick passes.
82791
- const prevEnableIds = app.scene.gsplat.enableIds;
82792
- app.scene.gsplat.enableIds = true;
82793
- try {
82794
- if (!chunksPatched) {
82795
- registerPickerShaderPatches(app);
82796
- chunksPatched = true;
82797
- }
82798
- if (!accumPass) {
82799
- initRasterAccum(width, height);
82800
- }
82801
- else if (cacheWidth !== width || cacheHeight !== height) {
82802
- cacheValid = false;
82803
- accumTarget.resize(width, height);
82804
- }
82805
- accumPass.init(accumTarget);
82806
- accumPass.setClearColor(clearColor);
82807
- accumPass.update(camera.camera, app.scene, [worldLayer], new Map(), false);
82808
- accumPass.render();
82809
- updateCache(width, height);
82810
- cacheValid = true;
82811
- }
82812
- finally {
82813
- app.scene.gsplat.enableIds = prevEnableIds;
82814
- }
82815
- };
82816
- const prepareSample = (x, y) => {
82817
- const width = Math.floor(graphicsDevice.width);
82818
- const height = Math.floor(graphicsDevice.height);
82819
- // bail out if the device hasn't been sized yet
82820
- if (width <= 0 || height <= 0) {
82821
- return null;
82822
- }
82823
- const worldLayer = app.scene.layers.getLayerByName('World');
82824
- if (!worldLayer) {
82825
- return null;
82826
- }
82827
- const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
82828
- const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
82829
- ensureRendered(width, height, worldLayer);
82830
- const pickCamera = getCacheCameraSnapshot();
82831
- return { width, height, screenX, screenY, pickCamera };
82832
- };
82833
- const pickPosition = async (x, y) => {
82834
- const sample = prepareSample(x, y);
82835
- if (!sample) {
82836
- return null;
82837
- }
82838
- const { width, height, screenX, screenY, pickCamera } = sample;
82839
- const pixels = await readTexture(accumBuffer, screenX, screenY, accumTarget);
82840
- const r = half2Float(pixels[0]);
82841
- const transmittance = half2Float(pixels[3]);
82842
- const alpha = 1 - transmittance;
82843
- if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
82844
- return null;
82845
- }
82846
- const normalizedDepth = r / alpha;
82847
- const position = getWorldPoint(pickCamera, screenX, screenY, width, height, normalizedDepth);
82848
- return position ? { position, camera: pickCamera, screenX, screenY, width, height } : null;
82849
- };
82850
- const serializePick = (operation) => {
82851
- // The render targets are shared by all picks on this instance.
82852
- const result = pickQueue.then(operation, operation);
82853
- pickQueue = result.then(() => undefined, () => undefined);
82854
- return result;
82855
- };
82856
- const pick = async (x, y) => {
82857
- const result = await pickPosition(x, y);
82858
- return result?.position ?? null;
82859
- };
82860
- const pickSurface = async (x, y) => {
82861
- const sample = prepareSample(x, y);
82862
- if (!sample) {
82863
- return null;
82864
- }
82865
- const { width, height, screenX, screenY, pickCamera } = sample;
82866
- // Single block read serves both depth (center pixel) and normal
82867
- // samples. Sized to the maximum possible ring pixel-radius so the
82868
- // dynamic ring offsets always lie inside the buffer we read.
82869
- const blockX = Math.max(0, screenX - NORMAL_SAMPLE_MAX_PX);
82870
- const blockY = Math.max(0, screenY - NORMAL_SAMPLE_MAX_PX);
82871
- const blockWidth = Math.min(width - 1, screenX + NORMAL_SAMPLE_MAX_PX) - blockX + 1;
82872
- const blockHeight = Math.min(height - 1, screenY + NORMAL_SAMPLE_MAX_PX) - blockY + 1;
82873
- const rasterBlock = await readRasterBlock(blockX, blockY, blockWidth, blockHeight, width, height, pickCamera);
82874
- const position = rasterBlock(screenX, screenY);
82875
- if (!position) {
82876
- return null;
82877
- }
82878
- const samplePixel = (px, py) => {
82879
- if (px < 0 || px >= width || py < 0 || py >= height) {
82880
- return null;
82881
- }
82882
- return rasterBlock(px, py);
82883
- };
82884
- // Pixel radius corresponding to a fixed world radius at the
82885
- // picked-point's depth. Clamped so distant picks still sample
82886
- // enough pixels and very-close picks stay inside the block read.
82887
- const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
82888
- const ringPixelRadii = NORMAL_RING_FRACTIONS.map(f => Math.max(1, Math.round(f * pixelRadius)));
82889
- const sampleRings = ringPixelRadii.map((radius) => {
82890
- return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
82891
- return samplePixel(screenX + dx * radius, screenY + dy * radius);
82892
- });
82893
- });
82894
- const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
82895
- // Collect every valid 3D sample: the picked position plus all ring
82896
- // samples that didn't fall off-screen or fail the depth read.
82897
- const fitPoints = [position];
82898
- for (let i = 0; i < sampleRings.length; i++) {
82899
- const ring = sampleRings[i];
82900
- for (let j = 0; j < ring.length; j++) {
82901
- const pt = ring[j];
82902
- if (pt)
82903
- fitPoints.push(pt);
82904
- }
82905
- }
82906
- const normal = new Vec3();
82907
- if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
82908
- normal.copy(toCamera);
82909
- }
82910
- return {
82911
- position,
82912
- normal
82913
- };
82914
- };
82915
- this.pick = (x, y) => serializePick(() => pick(x, y));
82916
- this.pickSurface = (x, y) => serializePick(() => pickSurface(x, y));
82917
- this.release = () => {
82918
- if (chunksPatched) {
82919
- unregisterPickerShaderPatches(app);
82920
- chunksPatched = false;
82921
- }
82922
- accumPass?.destroy();
82923
- accumTarget?.destroy();
82924
- accumBuffer?.destroy();
82925
- cacheValid = false;
82926
- };
82927
- }
82928
- }
82929
-
82930
- const SVGNS = 'http://www.w3.org/2000/svg';
82931
- const NUM_SAMPLES = 12;
82932
- const BASE_OUTER_RADIUS = 0.2;
82933
- const INNER_OUTER_RATIO = 0.17 / 0.2;
82934
- // Scenes with halfExtents.length() below this are smaller than the walk
82935
- // capsule (~1.5 m) — not navigable in walk mode and the world-space ring
82936
- // engulfs the whole scene. Switch the cursor to a fixed screen size instead.
82937
- const SMALL_SCENE_THRESHOLD = 2;
82938
- const SCREEN_OUTER_PIXELS = 60;
82939
- const BEZIER_K = 1 / 6;
82940
- const NORMAL_SMOOTH_FACTOR = 0.25;
82941
- const NORMAL_SNAP_ANGLE = Math.PI / 4;
82942
- const NORMAL_EPSILON = 1e-6;
82943
- const createNormalSnapDirections = () => {
82944
- const result = [];
82945
- for (let pitchStep = -2; pitchStep <= 2; pitchStep++) {
82946
- const pitch = pitchStep * NORMAL_SNAP_ANGLE;
82947
- const cp = Math.cos(pitch);
82948
- const sy = Math.sin(pitch);
82949
- if (Math.abs(cp) <= NORMAL_EPSILON) {
82950
- result.push(new Vec3(0, sy > 0 ? 1 : -1, 0));
82951
- continue;
82734
+ const patchGsplatPickGlsl = (chunk) => {
82735
+ return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'pcFragColor0 = encodePickOutput(vPickId);', 'pcFragColor0 = getPickOutput();');
82736
+ };
82737
+ const patchGsplatPickWgsl = (chunk) => {
82738
+ return safeChunkReplace(safeChunkReplace(chunk, /#ifdef PICK_PASS\s*#include "pickPS"\s*#endif/, pickPassChunkInjected), 'output.color = encodePickOutput(vPickId);', 'output.color = getPickOutput();');
82739
+ };
82740
+ /** Per-device original chunk strings + refcount so we can restore after the last Picker releases. */
82741
+ const pickerShaderPatchState = new WeakMap();
82742
+ const vec4 = new Vec4();
82743
+ const viewProjMat = new Mat4();
82744
+ const clearColor = new Color(0, 0, 0, 1);
82745
+ const NORMAL_EPSILON = 1e-12;
82746
+ const NORMAL_DEGENERATE_EPSILON = 1e-20;
82747
+ // Sampling for the surface-normal estimator runs on a circular footprint of
82748
+ // fixed *world* radius, projected to pixels at the picked-point's depth.
82749
+ // Keeping the world area constant means adjacent cursor positions sample
82750
+ // almost the same world cluster, which stabilises the plane fit. The pixel
82751
+ // radius is clamped so distant picks still get enough samples and very-close
82752
+ // picks don't blow the block read.
82753
+ const NORMAL_SAMPLE_WORLD_RADIUS = 0.2;
82754
+ const NORMAL_SAMPLE_MIN_PX = 6;
82755
+ const NORMAL_SAMPLE_MAX_PX = 48;
82756
+ const NORMAL_RING_FRACTIONS = [0.3, 0.55, 0.8, 1.0];
82757
+ const NORMAL_OUTLIER_THRESHOLD = 2.5;
82758
+ const NORMAL_SAMPLE_DIRECTIONS = [
82759
+ [1, 0],
82760
+ [1, 1],
82761
+ [0, 1],
82762
+ [-1, 1],
82763
+ [-1, 0],
82764
+ [-1, -1],
82765
+ [0, -1],
82766
+ [1, -1]
82767
+ ];
82768
+ // Shared buffer for half-to-float conversion
82769
+ const float32 = new Float32Array(1);
82770
+ const uint32 = new Uint32Array(float32.buffer);
82771
+ // Convert 16-bit half-float to 32-bit float using bit manipulation.
82772
+ const half2Float = (h) => {
82773
+ const sign = (h & 0x8000) << 16;
82774
+ const exponent = (h & 0x7C00) >> 10;
82775
+ const mantissa = h & 0x03FF;
82776
+ if (exponent === 0) {
82777
+ if (mantissa === 0) {
82778
+ uint32[0] = sign;
82952
82779
  }
82953
- for (let yawStep = 0; yawStep < 8; yawStep++) {
82954
- const yaw = yawStep * NORMAL_SNAP_ANGLE;
82955
- result.push(new Vec3(Math.cos(yaw) * cp, sy, Math.sin(yaw) * cp));
82780
+ else {
82781
+ let e = -1;
82782
+ let m = mantissa;
82783
+ do {
82784
+ e++;
82785
+ m <<= 1;
82786
+ } while ((m & 0x0400) === 0);
82787
+ uint32[0] = sign | ((127 - 15 - e) << 23) | ((m & 0x03FF) << 13);
82956
82788
  }
82957
82789
  }
82958
- return result;
82790
+ else if (exponent === 31) {
82791
+ uint32[0] = sign | 0x7F800000 | (mantissa << 13);
82792
+ }
82793
+ else {
82794
+ uint32[0] = sign | ((exponent + 127 - 15) << 23) | (mantissa << 13);
82795
+ }
82796
+ return float32[0];
82959
82797
  };
82960
- const NORMAL_SNAP_DIRECTIONS = createNormalSnapDirections();
82961
- const snapNormal = (nx, ny, nz, out) => {
82962
- const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
82963
- if (len <= NORMAL_EPSILON) {
82964
- return out.set(0, 1, 0);
82798
+ const registerPickerShaderPatches = (app) => {
82799
+ const device = app.graphicsDevice;
82800
+ const existing = pickerShaderPatchState.get(device);
82801
+ if (existing) {
82802
+ existing.refCount++;
82803
+ return;
82965
82804
  }
82966
- const invLen = 1 / len;
82967
- const x = nx * invLen;
82968
- const y = ny * invLen;
82969
- const z = nz * invLen;
82970
- let best = NORMAL_SNAP_DIRECTIONS[0];
82971
- let bestDot = -Infinity;
82972
- for (let i = 0; i < NORMAL_SNAP_DIRECTIONS.length; i++) {
82973
- const candidate = NORMAL_SNAP_DIRECTIONS[i];
82974
- const dot = candidate.x * x + candidate.y * y + candidate.z * z;
82975
- if (dot > bestDot) {
82976
- bestDot = dot;
82977
- best = candidate;
82978
- }
82805
+ const glslChunks = ShaderChunks.get(device, 'glsl');
82806
+ const wgslChunks = ShaderChunks.get(device, 'wgsl');
82807
+ const glslPickPS = glslChunks.get('pickPS');
82808
+ const glslGsplatPS = glslChunks.get('gsplatPS');
82809
+ const wgslPickPS = wgslChunks.get('pickPS');
82810
+ const wgslGsplatPS = wgslChunks.get('gsplatPS');
82811
+ // Patch strings before mutating ShaderChunks so engine mismatches leave globals untouched.
82812
+ const patchedGlslGsplatPS = patchGsplatPickGlsl(glslGsplatPS);
82813
+ const patchedWgslGsplatPS = patchGsplatPickWgsl(wgslGsplatPS);
82814
+ const state = {
82815
+ glslPickPS,
82816
+ glslGsplatPS,
82817
+ wgslPickPS,
82818
+ wgslGsplatPS,
82819
+ refCount: 1
82820
+ };
82821
+ pickerShaderPatchState.set(device, state);
82822
+ glslChunks.set('pickPS', pickDepthGlsl);
82823
+ wgslChunks.set('pickPS', pickDepthWgsl);
82824
+ glslChunks.set('gsplatPS', patchedGlslGsplatPS);
82825
+ wgslChunks.set('gsplatPS', patchedWgslGsplatPS);
82826
+ };
82827
+ const unregisterPickerShaderPatches = (app) => {
82828
+ const device = app.graphicsDevice;
82829
+ const state = pickerShaderPatchState.get(device);
82830
+ if (!state) {
82831
+ return;
82979
82832
  }
82980
- return out.copy(best);
82833
+ state.refCount--;
82834
+ if (state.refCount > 0) {
82835
+ return;
82836
+ }
82837
+ const glslChunks = ShaderChunks.get(device, 'glsl');
82838
+ const wgslChunks = ShaderChunks.get(device, 'wgsl');
82839
+ glslChunks.set('pickPS', state.glslPickPS);
82840
+ glslChunks.set('gsplatPS', state.glslGsplatPS);
82841
+ wgslChunks.set('pickPS', state.wgslPickPS);
82842
+ wgslChunks.set('gsplatPS', state.wgslGsplatPS);
82843
+ pickerShaderPatchState.delete(device);
82981
82844
  };
82982
- const tmpV = new Vec3();
82983
- const tmpScreen = new Vec3();
82984
- const tangent = new Vec3();
82985
- const bitangent = new Vec3();
82986
- const worldPt = new Vec3();
82987
- const up = new Vec3(0, 1, 0);
82988
- const right = new Vec3(1, 0, 0);
82989
- const tmpViewPos = new Vec3();
82990
- const tmpClipVec = new Vec4();
82991
- const tmpViewProj = new Mat4();
82992
- // Compute the world-space radius such that a circle at `pos` projects to a
82993
- // ring of `pixelDiameter` on screen. Used for the small-scene cursor mode
82994
- // where we want a constant screen size regardless of zoom.
82995
- const worldRadiusForPixels = (camera, canvasHeight, pos, pixelDiameter) => {
82845
+ const createPickCameraSnapshot = () => ({
82846
+ position: new Vec3(),
82847
+ viewMatrix: new Mat4(),
82848
+ projectionMatrix: new Mat4(),
82849
+ nearClip: 0,
82850
+ farClip: 0,
82851
+ projection: 0
82852
+ });
82853
+ const captureCameraSnapshot = (camera, out) => {
82996
82854
  const cam = camera.camera;
82997
- if (cam.projection === PROJECTION_ORTHOGRAPHIC) {
82998
- return pixelDiameter * cam.orthoHeight / canvasHeight;
82855
+ out.position.copy(camera.getPosition());
82856
+ out.viewMatrix.copy(cam.viewMatrix);
82857
+ out.projectionMatrix.copy(cam.projectionMatrix);
82858
+ out.nearClip = cam.nearClip;
82859
+ out.farClip = cam.farClip;
82860
+ out.projection = cam.projection;
82861
+ };
82862
+ const getWorldPoint = (camera, x, y, width, height, normalizedDepth, out) => {
82863
+ if (!Number.isFinite(normalizedDepth) || normalizedDepth < 0 || normalizedDepth > 1) {
82864
+ return null;
82999
82865
  }
83000
- const camPos = camera.getPosition();
83001
- const dx = pos.x - camPos.x;
83002
- const dy = pos.y - camPos.y;
83003
- const dz = pos.z - camPos.z;
83004
- const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
83005
- const halfFovTan = Math.tan(cam.fov * Math.PI / 360);
83006
- return pixelDiameter * distance * halfFovTan / canvasHeight;
82866
+ const { farClip: far, nearClip: near } = camera;
82867
+ const ndcDepth = camera.projection === PROJECTION_ORTHOGRAPHIC ?
82868
+ normalizedDepth :
82869
+ far * normalizedDepth / (normalizedDepth * (far - near) + near);
82870
+ viewProjMat.mul2(camera.projectionMatrix, camera.viewMatrix).invert();
82871
+ vec4.set(x / width * 2 - 1, (1 - y / height) * 2 - 1, ndcDepth * 2 - 1, 1);
82872
+ viewProjMat.transformVec4(vec4, vec4);
82873
+ if (!Number.isFinite(vec4.w) || Math.abs(vec4.w) < 1e-8) {
82874
+ return null;
82875
+ }
82876
+ vec4.mulScalar(1 / vec4.w);
82877
+ if (!Number.isFinite(vec4.x) || !Number.isFinite(vec4.y) || !Number.isFinite(vec4.z)) {
82878
+ return null;
82879
+ }
82880
+ return (out ?? new Vec3()).set(vec4.x, vec4.y, vec4.z);
83007
82881
  };
83008
- const worldPointToDepth = (camera, worldPos) => {
83009
- if (camera.projection === PROJECTION_ORTHOGRAPHIC) {
83010
- tmpViewProj.mul2(camera.projectionMatrix, camera.viewMatrix);
83011
- tmpClipVec.set(worldPos.x, worldPos.y, worldPos.z, 1);
83012
- tmpViewProj.transformVec4(tmpClipVec, tmpClipVec);
83013
- if (Math.abs(tmpClipVec.w) < 1e-8) {
83014
- return -1;
83015
- }
83016
- return (tmpClipVec.z / tmpClipVec.w + 1) * 0.5;
82882
+ const setCameraFacingNormal = (cameraPosition, position, normal) => {
82883
+ normal.sub2(cameraPosition, position);
82884
+ const len = normal.length();
82885
+ if (len > 1e-6) {
82886
+ normal.mulScalar(1 / len);
83017
82887
  }
83018
- camera.viewMatrix.transformPoint(worldPos, tmpViewPos);
83019
- const linearDepth = -tmpViewPos.z;
83020
- const range = camera.farClip - camera.nearClip;
83021
- if (range <= 0) {
83022
- return -1;
82888
+ else {
82889
+ normal.set(0, 1, 0);
83023
82890
  }
83024
- return (linearDepth - camera.nearClip) / range;
82891
+ return normal;
83025
82892
  };
83026
- const createSurfaceSample = () => ({
83027
- normalizedDepth: 0,
83028
- normal: new Vec3(),
83029
- camera: {
83030
- position: new Vec3(),
83031
- viewMatrix: new Mat4(),
83032
- projectionMatrix: new Mat4(),
83033
- nearClip: 0,
83034
- farClip: 0,
83035
- projection: 0
83036
- },
83037
- width: 0,
83038
- height: 0
83039
- });
83040
- const buildBezierRing = (sx, sy) => {
83041
- const n = sx.length;
83042
- let p = `M${sx[0].toFixed(1)},${sy[0].toFixed(1)}`;
82893
+ // Project a world-space radius around `pos` to its on-screen pixel radius for
82894
+ // the given camera. Uses the projection matrix's [1][1] entry (= 1/tan(fov/2)
82895
+ // for perspective, = 1/orthoHeight for orthographic) so we don't need fov or
82896
+ // orthoHeight on the snapshot.
82897
+ const worldRadiusToPixelRadius = (cam, pos, canvasHeight, worldRadius) => {
82898
+ const projY = cam.projectionMatrix.data[5];
82899
+ if (cam.projection === PROJECTION_ORTHOGRAPHIC) {
82900
+ return worldRadius * projY * canvasHeight / 2;
82901
+ }
82902
+ const dx = pos.x - cam.position.x;
82903
+ const dy = pos.y - cam.position.y;
82904
+ const dz = pos.z - cam.position.z;
82905
+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
82906
+ if (distance < 1e-6)
82907
+ return Infinity;
82908
+ return worldRadius * projY * canvasHeight / (2 * distance);
82909
+ };
82910
+ // Single least-squares plane fit through a cluster of 3D points. The normal
82911
+ // is the eigenvector of the smallest eigenvalue of the points' 3x3 covariance
82912
+ // matrix, computed in closed form (analytic eigendecomposition for 3x3
82913
+ // symmetric, Smith 1961). Returns null on degenerate input.
82914
+ const fitPlaneOnce = (points) => {
82915
+ const n = points.length;
82916
+ if (n < 3)
82917
+ return null;
82918
+ let cx = 0, cy = 0, cz = 0;
83043
82919
  for (let i = 0; i < n; i++) {
83044
- const i0 = (i - 1 + n) % n;
83045
- const i1 = i;
83046
- const i2 = (i + 1) % n;
83047
- const i3 = (i + 2) % n;
83048
- const cp1x = sx[i1] + (sx[i2] - sx[i0]) * BEZIER_K;
83049
- const cp1y = sy[i1] + (sy[i2] - sy[i0]) * BEZIER_K;
83050
- const cp2x = sx[i2] - (sx[i3] - sx[i1]) * BEZIER_K;
83051
- const cp2y = sy[i2] - (sy[i3] - sy[i1]) * BEZIER_K;
83052
- p += ` C${cp1x.toFixed(1)},${cp1y.toFixed(1)} ${cp2x.toFixed(1)},${cp2y.toFixed(1)} ${sx[i2].toFixed(1)},${sy[i2].toFixed(1)}`;
82920
+ cx += points[i].x;
82921
+ cy += points[i].y;
82922
+ cz += points[i].z;
82923
+ }
82924
+ cx /= n;
82925
+ cy /= n;
82926
+ cz /= n;
82927
+ let cxx = 0, cxy = 0, cxz = 0, cyy = 0, cyz = 0, czz = 0;
82928
+ for (let i = 0; i < n; i++) {
82929
+ const dx = points[i].x - cx;
82930
+ const dy = points[i].y - cy;
82931
+ const dz = points[i].z - cz;
82932
+ cxx += dx * dx;
82933
+ cxy += dx * dy;
82934
+ cxz += dx * dz;
82935
+ cyy += dy * dy;
82936
+ cyz += dy * dz;
82937
+ czz += dz * dz;
82938
+ }
82939
+ const q = (cxx + cyy + czz) / 3;
82940
+ const a = cxx - q, b = cyy - q, c = czz - q;
82941
+ const p2 = a * a + b * b + c * c + 2 * (cxy * cxy + cxz * cxz + cyz * cyz);
82942
+ if (p2 < NORMAL_DEGENERATE_EPSILON)
82943
+ return null;
82944
+ const p = Math.sqrt(p2 / 6);
82945
+ const inv = 1 / p;
82946
+ const Bxx = a * inv, Bxy = cxy * inv, Bxz = cxz * inv;
82947
+ const Byy = b * inv, Byz = cyz * inv, Bzz = c * inv;
82948
+ const detB = Bxx * (Byy * Bzz - Byz * Byz) -
82949
+ Bxy * (Bxy * Bzz - Byz * Bxz) +
82950
+ Bxz * (Bxy * Byz - Byy * Bxz);
82951
+ const r = Math.max(-1, Math.min(1, detB / 2));
82952
+ const phi = Math.acos(r) / 3;
82953
+ const lambdaMin = q + 2 * p * Math.cos(phi + 2 * Math.PI / 3);
82954
+ const Mxx = cxx - lambdaMin, Myy = cyy - lambdaMin, Mzz = czz - lambdaMin;
82955
+ const v1x = cxy * cyz - cxz * Myy;
82956
+ const v1y = cxz * cxy - Mxx * cyz;
82957
+ const v1z = Mxx * Myy - cxy * cxy;
82958
+ const v2x = cxy * Mzz - cxz * cyz;
82959
+ const v2y = cxz * cxz - Mxx * Mzz;
82960
+ const v2z = Mxx * cyz - cxy * cxz;
82961
+ const v3x = Myy * Mzz - cyz * cyz;
82962
+ const v3y = cyz * cxz - cxy * Mzz;
82963
+ const v3z = cxy * cyz - Myy * cxz;
82964
+ const l1 = v1x * v1x + v1y * v1y + v1z * v1z;
82965
+ const l2 = v2x * v2x + v2y * v2y + v2z * v2z;
82966
+ const l3 = v3x * v3x + v3y * v3y + v3z * v3z;
82967
+ let vx, vy, vz, lSq;
82968
+ if (l1 >= l2 && l1 >= l3) {
82969
+ vx = v1x;
82970
+ vy = v1y;
82971
+ vz = v1z;
82972
+ lSq = l1;
82973
+ }
82974
+ else if (l2 >= l3) {
82975
+ vx = v2x;
82976
+ vy = v2y;
82977
+ vz = v2z;
82978
+ lSq = l2;
82979
+ }
82980
+ else {
82981
+ vx = v3x;
82982
+ vy = v3y;
82983
+ vz = v3z;
82984
+ lSq = l3;
83053
82985
  }
83054
- return `${p} Z`;
82986
+ if (lSq < NORMAL_EPSILON)
82987
+ return null;
82988
+ const invLen = 1 / Math.sqrt(lSq);
82989
+ return { cx, cy, cz, vx: vx * invLen, vy: vy * invLen, vz: vz * invLen };
83055
82990
  };
83056
- class CursorRing {
83057
- path;
83058
- svg;
83059
- canvas;
83060
- camera;
83061
- smoothing;
83062
- // null = world-space ring (fixed world radius, shrinks with distance);
83063
- // number = constant on-screen diameter in pixels.
83064
- screenPixels;
83065
- smoothNx = 0;
83066
- smoothNy = 1;
83067
- smoothNz = 0;
83068
- hasSmoothedNormal = false;
83069
- outerX = new Float64Array(NUM_SAMPLES);
83070
- outerY = new Float64Array(NUM_SAMPLES);
83071
- innerX = new Float64Array(NUM_SAMPLES);
83072
- innerY = new Float64Array(NUM_SAMPLES);
83073
- constructor(svg, canvas, camera, smoothing, screenPixels) {
83074
- this.svg = svg;
83075
- this.canvas = canvas;
83076
- this.camera = camera;
83077
- this.smoothing = smoothing;
83078
- this.screenPixels = screenPixels;
83079
- this.path = document.createElementNS(SVGNS, 'path');
83080
- this.path.setAttribute('fill', 'white');
83081
- this.path.setAttribute('fill-opacity', '0.6');
83082
- this.path.setAttribute('fill-rule', 'evenodd');
83083
- this.path.setAttribute('stroke', 'none');
83084
- this.path.style.display = 'none';
83085
- svg.appendChild(this.path);
82991
+ // Two-pass plane fit: first pass on all points, then drop points whose
82992
+ // distance from the fitted plane exceeds NORMAL_OUTLIER_THRESHOLD * the mean
82993
+ // residual, refit on the inliers. Sign-flips the result toward toCamera so
82994
+ // the cursor's tangent basis stays consistent. Returns false on degenerate
82995
+ // input (fewer than 3 points, collinear/coincident samples).
82996
+ const fitPlaneNormal = (points, toCamera, outNormal) => {
82997
+ const first = fitPlaneOnce(points);
82998
+ if (!first)
82999
+ return false;
83000
+ let residualSum = 0;
83001
+ for (let i = 0; i < points.length; i++) {
83002
+ const dx = points[i].x - first.cx;
83003
+ const dy = points[i].y - first.cy;
83004
+ const dz = points[i].z - first.cz;
83005
+ residualSum += Math.abs(dx * first.vx + dy * first.vy + dz * first.vz);
83086
83006
  }
83087
- projectCircle(px, py, pz, nx, ny, nz, radius, outX, outY) {
83088
- const normal = tmpV.set(nx, ny, nz);
83089
- if (Math.abs(normal.y) < 0.99) {
83090
- tangent.cross(normal, up).normalize();
83091
- }
83092
- else {
83093
- tangent.cross(normal, right).normalize();
83094
- }
83095
- bitangent.cross(normal, tangent);
83096
- const cam = this.camera.camera;
83097
- const angleStep = (2 * Math.PI) / NUM_SAMPLES;
83098
- for (let i = 0; i < NUM_SAMPLES; i++) {
83099
- const theta = i * angleStep;
83100
- const ct = Math.cos(theta);
83101
- const st = Math.sin(theta);
83102
- const tx = ct * tangent.x + st * bitangent.x;
83103
- const ty = ct * tangent.y + st * bitangent.y;
83104
- const tz = ct * tangent.z + st * bitangent.z;
83105
- worldPt.set(px + tx * radius, py + ty * radius, pz + tz * radius);
83106
- cam.worldToScreen(worldPt, tmpScreen);
83107
- outX[i] = tmpScreen.x;
83108
- outY[i] = tmpScreen.y;
83007
+ const threshold = (residualSum / points.length) * NORMAL_OUTLIER_THRESHOLD;
83008
+ const inliers = [];
83009
+ for (let i = 0; i < points.length; i++) {
83010
+ const dx = points[i].x - first.cx;
83011
+ const dy = points[i].y - first.cy;
83012
+ const dz = points[i].z - first.cz;
83013
+ if (Math.abs(dx * first.vx + dy * first.vy + dz * first.vz) <= threshold) {
83014
+ inliers.push(points[i]);
83109
83015
  }
83110
83016
  }
83111
- render(pos, normal) {
83112
- snapNormal(normal.x, normal.y, normal.z, tmpV);
83113
- let nx = tmpV.x;
83114
- let ny = tmpV.y;
83115
- let nz = tmpV.z;
83116
- if (this.smoothing) {
83117
- if (this.hasSmoothedNormal) {
83118
- const t = NORMAL_SMOOTH_FACTOR;
83119
- nx = this.smoothNx + (nx - this.smoothNx) * t;
83120
- ny = this.smoothNy + (ny - this.smoothNy) * t;
83121
- nz = this.smoothNz + (nz - this.smoothNz) * t;
83122
- const len = Math.sqrt(nx * nx + ny * ny + nz * nz);
83123
- if (len > 1e-6) {
83124
- const invLen = 1.0 / len;
83125
- nx *= invLen;
83126
- ny *= invLen;
83127
- nz *= invLen;
83128
- }
83129
- }
83130
- this.smoothNx = nx;
83131
- this.smoothNy = ny;
83132
- this.smoothNz = nz;
83133
- this.hasSmoothedNormal = true;
83134
- }
83135
- const outerRadius = this.screenPixels !== null ?
83136
- worldRadiusForPixels(this.camera, this.canvas.clientHeight || 1, pos, this.screenPixels) :
83137
- BASE_OUTER_RADIUS;
83138
- const innerRadius = outerRadius * INNER_OUTER_RATIO;
83139
- this.projectCircle(pos.x, pos.y, pos.z, nx, ny, nz, outerRadius, this.outerX, this.outerY);
83140
- this.projectCircle(pos.x, pos.y, pos.z, nx, ny, nz, innerRadius, this.innerX, this.innerY);
83141
- this.path.setAttribute('d', `${buildBezierRing(this.outerX, this.outerY)} ${buildBezierRing(this.innerX, this.innerY)}`);
83142
- this.path.style.display = '';
83143
- this.svg.style.display = '';
83017
+ let result = first;
83018
+ if (inliers.length >= 3 && inliers.length < points.length) {
83019
+ const refined = fitPlaneOnce(inliers);
83020
+ if (refined)
83021
+ result = refined;
83144
83022
  }
83145
- hide() {
83146
- this.path.style.display = 'none';
83147
- this.hasSmoothedNormal = false;
83023
+ let { vx, vy, vz } = result;
83024
+ if (vx * toCamera.x + vy * toCamera.y + vz * toCamera.z < 0) {
83025
+ vx = -vx;
83026
+ vy = -vy;
83027
+ vz = -vz;
83148
83028
  }
83149
- }
83150
- class NavCursor {
83151
- svg;
83152
- hoverRing;
83153
- targetRing;
83154
- camera;
83155
- collision;
83156
- canvas;
83157
- state;
83158
- picker;
83159
- app;
83160
- onPrerender;
83161
- active = false;
83162
- navigating = false;
83163
- targetPos = null;
83164
- targetNormal = null;
83165
- targetMode = null;
83166
- surfaceCursorX = 0;
83167
- surfaceCursorY = 0;
83168
- hasSurfaceCursorPosition = false;
83169
- surfaceCursorVersion = 0;
83170
- surfaceCursorPickPending = false;
83171
- surfaceSample = createSurfaceSample();
83172
- hasSurfaceSample = false;
83173
- scratchHoverPos = new Vec3();
83174
- onPointerMove;
83175
- onPointerLeave;
83176
- collisionTarget = {
83177
- position: new Vec3(),
83178
- normal: new Vec3()
83179
- };
83180
- constructor(app, camera, collision, events, state, picker, sceneSize) {
83181
- this.camera = camera;
83182
- this.collision = collision;
83183
- this.canvas = app.graphicsDevice.canvas;
83184
- this.state = state;
83185
- this.picker = picker;
83186
- this.app = app;
83187
- this.svg = document.createElementNS(SVGNS, 'svg');
83188
- this.svg.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;overflow:visible;z-index:1';
83189
- this.canvas.parentElement.appendChild(this.svg);
83190
- const screenPixels = sceneSize < SMALL_SCENE_THRESHOLD ? SCREEN_OUTER_PIXELS : null;
83191
- this.hoverRing = new CursorRing(this.svg, this.canvas, camera, true, screenPixels);
83192
- this.targetRing = new CursorRing(this.svg, this.canvas, camera, false, screenPixels);
83193
- this.svg.style.display = 'none';
83194
- this.onPointerMove = (e) => {
83195
- if (e.pointerType === 'touch') {
83196
- this.hasSurfaceCursorPosition = false;
83197
- this.surfaceCursorVersion++;
83198
- this.hoverRing.hide();
83029
+ outNormal.set(vx, vy, vz);
83030
+ return true;
83031
+ };
83032
+ class Picker {
83033
+ pick;
83034
+ pickSurface;
83035
+ release;
83036
+ constructor(app, camera) {
83037
+ const { graphicsDevice } = app;
83038
+ let accumBuffer;
83039
+ let accumTarget;
83040
+ let accumPass;
83041
+ let chunksPatched = false;
83042
+ let pickQueue = Promise.resolve();
83043
+ let cacheValid = false;
83044
+ let cacheWidth = 0;
83045
+ let cacheHeight = 0;
83046
+ const cacheCamera = createPickCameraSnapshot();
83047
+ const initRasterAccum = (width, height) => {
83048
+ accumBuffer = new Texture(graphicsDevice, {
83049
+ format: PIXELFORMAT_RGBA16F,
83050
+ width,
83051
+ height,
83052
+ mipmaps: false,
83053
+ minFilter: FILTER_NEAREST,
83054
+ magFilter: FILTER_NEAREST,
83055
+ addressU: ADDRESS_CLAMP_TO_EDGE,
83056
+ addressV: ADDRESS_CLAMP_TO_EDGE,
83057
+ name: 'picker-accum'
83058
+ });
83059
+ accumTarget = new RenderTarget({
83060
+ colorBuffer: accumBuffer,
83061
+ depth: false // not needed — gaussians are rendered back to front
83062
+ });
83063
+ accumPass = new RenderPassPicker(graphicsDevice, app.renderer);
83064
+ // RGB: additive depth accumulation. Alpha: multiplicative transmittance.
83065
+ accumPass.blendState = new BlendState(true, BLENDEQUATION_ADD, BLENDMODE_ONE, BLENDMODE_ONE_MINUS_SRC_ALPHA, BLENDEQUATION_ADD, BLENDMODE_ZERO, BLENDMODE_ONE_MINUS_SRC_ALPHA);
83066
+ };
83067
+ const readTexture = (texture, x, y, target) => {
83068
+ const texY = graphicsDevice.isWebGL2 ? target.height - y - 1 : y;
83069
+ return texture.read(x, texY, 1, 1, {
83070
+ renderTarget: target,
83071
+ immediate: true
83072
+ });
83073
+ };
83074
+ const updateCache = (width, height) => {
83075
+ captureCameraSnapshot(camera, cacheCamera);
83076
+ cacheWidth = width;
83077
+ cacheHeight = height;
83078
+ };
83079
+ const cameraMatches = (width, height) => {
83080
+ const cam = camera.camera;
83081
+ return cacheValid &&
83082
+ cacheWidth === width &&
83083
+ cacheHeight === height &&
83084
+ cacheCamera.viewMatrix.equals(cam.viewMatrix) &&
83085
+ cacheCamera.projectionMatrix.equals(cam.projectionMatrix) &&
83086
+ cacheCamera.nearClip === cam.nearClip &&
83087
+ cacheCamera.farClip === cam.farClip &&
83088
+ cacheCamera.projection === cam.projection;
83089
+ };
83090
+ const getCacheCameraSnapshot = () => {
83091
+ const snapshot = createPickCameraSnapshot();
83092
+ snapshot.position.copy(cacheCamera.position);
83093
+ snapshot.viewMatrix.copy(cacheCamera.viewMatrix);
83094
+ snapshot.projectionMatrix.copy(cacheCamera.projectionMatrix);
83095
+ snapshot.nearClip = cacheCamera.nearClip;
83096
+ snapshot.farClip = cacheCamera.farClip;
83097
+ snapshot.projection = cacheCamera.projection;
83098
+ return snapshot;
83099
+ };
83100
+ const readRasterBlock = async (blockX, blockY, blockWidth, blockHeight, viewportWidth, viewportHeight, pickCamera) => {
83101
+ const texY = graphicsDevice.isWebGL2 ? accumTarget.height - blockY - blockHeight : blockY;
83102
+ const pixels = await accumBuffer.read(blockX, texY, blockWidth, blockHeight, {
83103
+ renderTarget: accumTarget,
83104
+ immediate: true
83105
+ });
83106
+ return (x, y) => {
83107
+ const localX = x - blockX;
83108
+ const localY = y - blockY;
83109
+ if (localX < 0 || localX >= blockWidth || localY < 0 || localY >= blockHeight) {
83110
+ return null;
83111
+ }
83112
+ const row = graphicsDevice.isWebGL2 ? blockHeight - localY - 1 : localY;
83113
+ const index = (row * blockWidth + localX) * 4;
83114
+ const r = half2Float(pixels[index]);
83115
+ const transmittance = half2Float(pixels[index + 3]);
83116
+ const alpha = 1 - transmittance;
83117
+ if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
83118
+ return null;
83119
+ }
83120
+ const normalizedDepth = r / alpha;
83121
+ return getWorldPoint(pickCamera, x, y, viewportWidth, viewportHeight, normalizedDepth);
83122
+ };
83123
+ };
83124
+ const ensureRendered = (width, height, worldLayer) => {
83125
+ if (cameraMatches(width, height)) {
83199
83126
  return;
83200
83127
  }
83201
- if (e.buttons) {
83202
- this.hasSurfaceCursorPosition = false;
83203
- this.surfaceCursorVersion++;
83204
- this.hoverRing.hide();
83205
- return;
83128
+ // Enable gsplat IDs only while rendering the pick target so we
83129
+ // don't pay the memory/perf cost between pick passes.
83130
+ const prevEnableIds = app.scene.gsplat.enableIds;
83131
+ app.scene.gsplat.enableIds = true;
83132
+ try {
83133
+ if (!chunksPatched) {
83134
+ registerPickerShaderPatches(app);
83135
+ chunksPatched = true;
83136
+ }
83137
+ if (!accumPass) {
83138
+ initRasterAccum(width, height);
83139
+ }
83140
+ else if (cacheWidth !== width || cacheHeight !== height) {
83141
+ cacheValid = false;
83142
+ accumTarget.resize(width, height);
83143
+ }
83144
+ accumPass.init(accumTarget);
83145
+ accumPass.setClearColor(clearColor);
83146
+ accumPass.update(camera.camera, app.scene, [worldLayer], new Map(), false);
83147
+ accumPass.render();
83148
+ updateCache(width, height);
83149
+ cacheValid = true;
83150
+ }
83151
+ finally {
83152
+ app.scene.gsplat.enableIds = prevEnableIds;
83206
83153
  }
83207
- this.updateCursor(e.offsetX, e.offsetY);
83208
83154
  };
83209
- this.onPointerLeave = () => {
83210
- this.hasSurfaceCursorPosition = false;
83211
- this.surfaceCursorVersion++;
83212
- this.hoverRing.hide();
83213
- };
83214
- this.canvas.addEventListener('pointermove', this.onPointerMove);
83215
- this.canvas.addEventListener('pointerleave', this.onPointerLeave);
83216
- const updateActive = () => {
83217
- const flyMouseCaptured = (state.cameraMode === 'fly' &&
83218
- state.inputMode === 'desktop' &&
83219
- state.gamingControls);
83220
- this.active = (state.cameraMode === 'walk' && !state.gamingControls) ||
83221
- (state.cameraMode === 'fly' && !flyMouseCaptured) ||
83222
- state.cameraMode === 'orbit';
83223
- this.surfaceCursorVersion++;
83224
- this.hoverRing.hide();
83225
- if (state.inputMode !== 'desktop') {
83226
- this.hasSurfaceCursorPosition = false;
83227
- }
83228
- if (this.targetMode && this.targetMode !== state.cameraMode) {
83229
- this.navigating = false;
83230
- this.clearTarget();
83155
+ const prepareSample = (x, y) => {
83156
+ const width = Math.floor(graphicsDevice.width);
83157
+ const height = Math.floor(graphicsDevice.height);
83158
+ // bail out if the device hasn't been sized yet
83159
+ if (width <= 0 || height <= 0) {
83160
+ return null;
83231
83161
  }
83232
- if (!this.active) {
83233
- this.svg.style.display = 'none';
83162
+ const worldLayer = app.scene.layers.getLayerByName('World');
83163
+ if (!worldLayer) {
83164
+ return null;
83234
83165
  }
83166
+ const screenX = Math.min(width - 1, Math.max(0, Math.floor(x * width)));
83167
+ const screenY = Math.min(height - 1, Math.max(0, Math.floor(y * height)));
83168
+ ensureRendered(width, height, worldLayer);
83169
+ const pickCamera = getCacheCameraSnapshot();
83170
+ return { width, height, screenX, screenY, pickCamera };
83235
83171
  };
83236
- events.on('cameraMode:changed', updateActive);
83237
- events.on('inputMode:changed', updateActive);
83238
- events.on('gamingControls:changed', updateActive);
83239
- events.on('navigateTo', () => {
83240
- this.navigating = true;
83241
- this.hoverRing.hide();
83242
- });
83243
- events.on('navigateCancel', () => {
83244
- this.navigating = false;
83245
- this.clearTarget();
83246
- });
83247
- events.on('navigateComplete', () => {
83248
- this.navigating = false;
83249
- this.clearTarget();
83250
- });
83251
- events.on('navTarget:set', (pos, normal) => {
83252
- const mode = state.cameraMode === 'walk' || state.cameraMode === 'fly' ?
83253
- state.cameraMode : 'walk';
83254
- this.setTarget(pos, normal, mode);
83255
- });
83256
- events.on('navTarget:clear', () => {
83257
- this.clearTarget();
83258
- });
83259
- events.on('orbitTarget:set', (pos, normal) => {
83260
- this.navigating = false;
83261
- this.setTarget(pos, normal, 'orbit');
83262
- });
83263
- events.on('orbitTarget:clear', () => {
83264
- if (this.targetMode === 'orbit') {
83265
- this.clearTarget();
83172
+ const pickPosition = async (x, y) => {
83173
+ const sample = prepareSample(x, y);
83174
+ if (!sample) {
83175
+ return null;
83266
83176
  }
83267
- });
83268
- this.onPrerender = () => {
83269
- this.updateTarget();
83177
+ const { width, height, screenX, screenY, pickCamera } = sample;
83178
+ const pixels = await readTexture(accumBuffer, screenX, screenY, accumTarget);
83179
+ const r = half2Float(pixels[0]);
83180
+ const transmittance = half2Float(pixels[3]);
83181
+ const alpha = 1 - transmittance;
83182
+ if (!Number.isFinite(r) || !Number.isFinite(alpha) || alpha < 1e-6) {
83183
+ return null;
83184
+ }
83185
+ const normalizedDepth = r / alpha;
83186
+ const position = getWorldPoint(pickCamera, screenX, screenY, width, height, normalizedDepth);
83187
+ return position ? { position, camera: pickCamera, screenX, screenY, width, height } : null;
83270
83188
  };
83271
- app.on('prerender', this.onPrerender);
83272
- updateActive();
83273
- }
83274
- setTarget(pos, normal, mode) {
83275
- this.surfaceCursorVersion++;
83276
- this.targetPos = pos.clone();
83277
- this.targetNormal = normal.clone();
83278
- this.targetMode = mode;
83279
- this.hoverRing.hide();
83280
- this.targetRing.hide();
83281
- }
83282
- clearTarget() {
83283
- const mode = this.targetMode;
83284
- this.targetPos = null;
83285
- this.targetNormal = null;
83286
- this.targetMode = null;
83287
- if (mode === 'orbit') {
83288
- this.hoverRing.hide();
83289
- }
83290
- this.targetRing.hide();
83291
- this.refreshSurfaceCursor();
83292
- }
83293
- pickCollision(offsetX, offsetY) {
83294
- if (!this.collision) {
83295
- return null;
83296
- }
83297
- const { camera, collision } = this;
83298
- const cameraPos = camera.getPosition();
83299
- camera.camera.screenToWorld(offsetX, offsetY, 1.0, tmpV);
83300
- tmpV.sub(cameraPos).normalize();
83301
- const hit = collision.queryRay(cameraPos.x, cameraPos.y, cameraPos.z, tmpV.x, tmpV.y, tmpV.z, camera.camera.farClip);
83302
- if (!hit) {
83303
- return null;
83304
- }
83305
- const sn = collision.querySurfaceNormal(hit.x, hit.y, hit.z, tmpV.x, tmpV.y, tmpV.z);
83306
- this.collisionTarget.position.set(hit.x, hit.y, hit.z);
83307
- this.collisionTarget.normal.set(sn.nx, sn.ny, sn.nz);
83308
- return this.collisionTarget;
83309
- }
83310
- async pickSceneTarget(offsetX, offsetY) {
83311
- const collisionTarget = this.pickCollision(offsetX, offsetY);
83312
- if (collisionTarget) {
83313
- return collisionTarget;
83314
- }
83315
- const result = await this.picker.pickSurface(offsetX / this.canvas.clientWidth, offsetY / this.canvas.clientHeight);
83316
- return result ?? null;
83317
- }
83318
- shouldShowSurfaceCursor() {
83319
- const flyMouseCaptured = this.state.cameraMode === 'fly' &&
83320
- this.state.inputMode === 'desktop' &&
83321
- this.state.gamingControls;
83322
- return this.active &&
83323
- this.state.inputMode === 'desktop' &&
83324
- this.hasSurfaceCursorPosition &&
83325
- !this.navigating && ((this.state.cameraMode === 'fly' && !flyMouseCaptured) ||
83326
- (this.state.cameraMode === 'orbit' && this.targetMode !== 'orbit'));
83327
- }
83328
- updateSurfaceCursor(offsetX, offsetY) {
83329
- this.surfaceCursorX = offsetX;
83330
- this.surfaceCursorY = offsetY;
83331
- this.hasSurfaceCursorPosition = true;
83332
- this.surfaceCursorVersion++;
83333
- // Render immediately using the most recent depth sample, re-projecting
83334
- // at the new pointer position. The async pick below will refresh the
83335
- // sample.
83336
- this.renderSurfaceCursor();
83337
- if (!this.surfaceCursorPickPending) {
83338
- this.processSurfaceCursor();
83339
- }
83340
- }
83341
- renderSurfaceCursor() {
83342
- if (!this.hasSurfaceSample || !this.shouldShowSurfaceCursor()) {
83343
- this.hoverRing.hide();
83344
- return;
83345
- }
83346
- const sample = this.surfaceSample;
83347
- const position = getWorldPoint(sample.camera, this.surfaceCursorX, this.surfaceCursorY, sample.width, sample.height, sample.normalizedDepth, this.scratchHoverPos);
83348
- if (!position) {
83349
- this.hoverRing.hide();
83350
- return;
83351
- }
83352
- this.hoverRing.render(position, sample.normal);
83353
- }
83354
- refreshSurfaceCursor() {
83355
- if (this.hasSurfaceCursorPosition && this.shouldShowSurfaceCursor() && !this.surfaceCursorPickPending) {
83356
- this.surfaceCursorVersion++;
83357
- this.processSurfaceCursor();
83358
- }
83359
- }
83360
- processSurfaceCursor() {
83361
- this.surfaceCursorPickPending = true;
83362
- const version = this.surfaceCursorVersion;
83363
- // Capture the camera at pick fire time so the depth we extract from
83364
- // the result is interpretable through the same view/projection. The
83365
- // surface cursor only animates while the camera is static, so this
83366
- // snapshot matches the camera the picker actually rendered with.
83367
- captureCameraSnapshot(this.camera, this.surfaceSample.camera);
83368
- const snapshotWidth = this.canvas.clientWidth;
83369
- const snapshotHeight = this.canvas.clientHeight;
83370
- this.pickSceneTarget(this.surfaceCursorX, this.surfaceCursorY).then((target) => {
83371
- if (target) {
83372
- this.surfaceSample.normalizedDepth = worldPointToDepth(this.surfaceSample.camera, target.position);
83373
- this.surfaceSample.normal.copy(target.normal);
83374
- this.surfaceSample.width = snapshotWidth;
83375
- this.surfaceSample.height = snapshotHeight;
83376
- this.hasSurfaceSample = this.surfaceSample.normalizedDepth >= 0;
83189
+ const serializePick = (operation) => {
83190
+ // The render targets are shared by all picks on this instance.
83191
+ const result = pickQueue.then(operation, operation);
83192
+ pickQueue = result.then(() => undefined, () => undefined);
83193
+ return result;
83194
+ };
83195
+ const pick = async (x, y) => {
83196
+ const result = await pickPosition(x, y);
83197
+ return result?.position ?? null;
83198
+ };
83199
+ const pickSurface = async (x, y) => {
83200
+ const sample = prepareSample(x, y);
83201
+ if (!sample) {
83202
+ return null;
83377
83203
  }
83378
- else {
83379
- this.hasSurfaceSample = false;
83204
+ const { width, height, screenX, screenY, pickCamera } = sample;
83205
+ // Single block read serves both depth (center pixel) and normal
83206
+ // samples. Sized to the maximum possible ring pixel-radius so the
83207
+ // dynamic ring offsets always lie inside the buffer we read.
83208
+ const blockX = Math.max(0, screenX - NORMAL_SAMPLE_MAX_PX);
83209
+ const blockY = Math.max(0, screenY - NORMAL_SAMPLE_MAX_PX);
83210
+ const blockWidth = Math.min(width - 1, screenX + NORMAL_SAMPLE_MAX_PX) - blockX + 1;
83211
+ const blockHeight = Math.min(height - 1, screenY + NORMAL_SAMPLE_MAX_PX) - blockY + 1;
83212
+ const rasterBlock = await readRasterBlock(blockX, blockY, blockWidth, blockHeight, width, height, pickCamera);
83213
+ const position = rasterBlock(screenX, screenY);
83214
+ if (!position) {
83215
+ return null;
83380
83216
  }
83381
- this.renderSurfaceCursor();
83382
- }).catch(() => {
83383
- if (version === this.surfaceCursorVersion) {
83384
- this.hasSurfaceSample = false;
83385
- this.hoverRing.hide();
83217
+ const samplePixel = (px, py) => {
83218
+ if (px < 0 || px >= width || py < 0 || py >= height) {
83219
+ return null;
83220
+ }
83221
+ return rasterBlock(px, py);
83222
+ };
83223
+ // Pixel radius corresponding to a fixed world radius at the
83224
+ // picked-point's depth. Clamped so distant picks still sample
83225
+ // enough pixels and very-close picks stay inside the block read.
83226
+ const pixelRadius = Math.max(NORMAL_SAMPLE_MIN_PX, Math.min(NORMAL_SAMPLE_MAX_PX, worldRadiusToPixelRadius(pickCamera, position, height, NORMAL_SAMPLE_WORLD_RADIUS)));
83227
+ const ringPixelRadii = NORMAL_RING_FRACTIONS.map(f => Math.max(1, Math.round(f * pixelRadius)));
83228
+ const sampleRings = ringPixelRadii.map((radius) => {
83229
+ return NORMAL_SAMPLE_DIRECTIONS.map(([dx, dy]) => {
83230
+ return samplePixel(screenX + dx * radius, screenY + dy * radius);
83231
+ });
83232
+ });
83233
+ const toCamera = setCameraFacingNormal(pickCamera.position, position, new Vec3());
83234
+ // Collect every valid 3D sample: the picked position plus all ring
83235
+ // samples that didn't fall off-screen or fail the depth read.
83236
+ const fitPoints = [position];
83237
+ for (let i = 0; i < sampleRings.length; i++) {
83238
+ const ring = sampleRings[i];
83239
+ for (let j = 0; j < ring.length; j++) {
83240
+ const pt = ring[j];
83241
+ if (pt)
83242
+ fitPoints.push(pt);
83243
+ }
83386
83244
  }
83387
- }).finally(() => {
83388
- this.surfaceCursorPickPending = false;
83389
- if (version !== this.surfaceCursorVersion && this.shouldShowSurfaceCursor()) {
83390
- this.processSurfaceCursor();
83245
+ const normal = new Vec3();
83246
+ if (!fitPlaneNormal(fitPoints, toCamera, normal)) {
83247
+ normal.copy(toCamera);
83391
83248
  }
83392
- });
83393
- }
83394
- updateCursor(offsetX, offsetY) {
83395
- if (!this.active || this.navigating) {
83396
- this.hoverRing.hide();
83397
- return;
83398
- }
83399
- if (this.state.cameraMode === 'orbit' && this.targetMode === 'orbit') {
83400
- this.hoverRing.hide();
83401
- return;
83402
- }
83403
- if (this.state.cameraMode === 'fly' || this.state.cameraMode === 'orbit') {
83404
- this.updateSurfaceCursor(offsetX, offsetY);
83405
- return;
83406
- }
83407
- const target = this.pickCollision(offsetX, offsetY);
83408
- if (!target) {
83409
- this.hoverRing.hide();
83410
- return;
83411
- }
83412
- this.hoverRing.render(target.position, target.normal);
83413
- }
83414
- updateTarget() {
83415
- if (!this.active || !this.targetPos || !this.targetNormal) {
83416
- return;
83417
- }
83418
- const camPos = this.camera.getPosition();
83419
- const dist = camPos.distance(this.targetPos);
83420
- if (this.targetMode !== 'orbit' && dist < 2.0) {
83421
- this.targetRing.hide();
83422
- return;
83423
- }
83424
- this.targetRing.render(this.targetPos, this.targetNormal);
83425
- }
83426
- destroy() {
83427
- this.app.off('prerender', this.onPrerender);
83428
- this.canvas.removeEventListener('pointermove', this.onPointerMove);
83429
- this.canvas.removeEventListener('pointerleave', this.onPointerLeave);
83430
- this.svg.remove();
83249
+ return {
83250
+ position,
83251
+ normal
83252
+ };
83253
+ };
83254
+ this.pick = (x, y) => serializePick(() => pick(x, y));
83255
+ this.pickSurface = (x, y) => serializePick(() => pickSurface(x, y));
83256
+ this.release = () => {
83257
+ if (chunksPatched) {
83258
+ unregisterPickerShaderPatches(app);
83259
+ chunksPatched = false;
83260
+ }
83261
+ accumPass?.destroy();
83262
+ accumTarget?.destroy();
83263
+ accumBuffer?.destroy();
83264
+ cacheValid = false;
83265
+ };
83431
83266
  }
83432
83267
  }
83433
83268
 
@@ -84303,7 +84138,12 @@ class Viewer {
84303
84138
  this.picker = new Picker(app, camera);
84304
84139
  this.inputController = new InputController(global, this.picker);
84305
84140
  this.inputController.collision = collision ?? null;
84141
+ // hasCollision = collision data exists (drives fly-mode collision
84142
+ // detection and the voxel/mesh debug overlay availability).
84143
+ // walkAllowed = walk mode is offered to the user; requires both
84144
+ // collision data and a scene large enough to walk around in.
84306
84145
  state.hasCollision = !!collision;
84146
+ state.walkAllowed = isWalkAllowed(sceneBound, collision ?? null);
84307
84147
  // Create collision debug overlay (voxel uses a compute shader, mesh
84308
84148
  // uses standard line rendering). The voxel path requires WebGPU.
84309
84149
  if (collision instanceof VoxelCollision && config.renderer !== 'webgl') {
@@ -84326,7 +84166,7 @@ class Viewer {
84326
84166
  this.cameraManager = new CameraManager(global, sceneBound, collision);
84327
84167
  applyCamera(this.cameraManager.camera);
84328
84168
  if (!config.noui) {
84329
- this.navCursor = new NavCursor(app, camera, collision ?? null, events, state, this.picker, sceneBound.halfExtents.length());
84169
+ this.navCursor = new NavCursor(app, camera, collision ?? null, events, state);
84330
84170
  }
84331
84171
  const { instance } = gsplat;
84332
84172
  if (instance) {
@@ -85574,6 +85414,7 @@ const main = async (canvas, settingsJson, config) => {
85574
85414
  hasVR: false,
85575
85415
  hasCollision: false,
85576
85416
  hasCollisionOverlay: false,
85417
+ walkAllowed: false,
85577
85418
  collisionOverlayEnabled: false,
85578
85419
  isFullscreen: false,
85579
85420
  controlsHidden: false,