All files / adapters/three sceneView.ts

97.61% Statements 164/168
100% Branches 0/0
100% Functions 0/0
97.61% Lines 164/168

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324                                                                                                                          29x     29x 29x 29x         29x 29x 29x 29x 29x 29x   29x     29x       29x 29x 29x 29x 29x 29x   29x 19x 19x 19x     29x 1x     1x           1x 1x 1x     29x 2x 2x 2x 2x 2x 2x 2x 2x 2x     29x           29x 26x 3x 3x 3x 3x 3x 3x     29x 54x 19x 4x 4x 4x 4x 4x 15x 14x   19x     29x 254x   29x 5x 5x 5x 5x     29x 7x 7x 7x     29x 1x 1x 1x 1x     29x 1x 1x 1x 1x 1x     29x 12x 12x 12x 12x 12x 12x 12x 12x 12x     29x 57x 45x 45x 45x 39x 12x 12x 12x     12x 12x 12x     29x 61x 57x 57x 57x 57x 51x   24x     24x 24x 24x     24x 24x     24x       51x 51x       29x 142x 63x 63x 61x 61x 61x       29x 2x 1x 1x         1x 1x     29x 29x 29x   29x   67x 67x     30x 30x 30x     1x 1x 1x     9x             9x 9x 9x 9x 9x     10x 10x   4x 4x       42x 42x 42x     4x 4x 4x 1x 4x 4x 4x 4x        
import type { TwistyPlayer } from 'cubing/twisty';
import * as THREE from 'three';
import {
  createOrientationIndicator,
  setOrientationIndicatorColors,
  type OrientationIndicatorColors,
} from './orientationIndicator';
import { HOME_FRAME_COLORS } from './faceColors';
 
type Vantage = {
  scene: { scene(): Promise<THREE.Scene> } | null;
  canvasInfo(): Promise<{ canvas: HTMLCanvasElement }>;
  render(): Promise<void> | void;
};
 
type ScenePlayer = Pick<TwistyPlayer, 'experimentalCurrentVantages'>;
 
export type SceneRenderer = {
  /** Queue a single frame. Repeated calls before it runs are coalesced. */
  requestRender(): void;
  /** Apply an absolute physical-cube orientation from a transport quaternion. */
  setCubeOrientation(orientation: QuaternionComponents): void;
  /** Restore the cube's presentation-only resting pose. */
  resetCubeOrientation(): void;
  /** Apply the solver-frame basis and axis colors used by the orientation gizmo. */
  setVirtualFrameOrientation(orientation: VirtualFrameOrientation): void;
  /** Stop or resume rendering while the smart-cube session is inactive. */
  setActive(active: boolean): void;
  /** Let mouse/touch drag rotate the scene when a cube has no gyro. */
  setManualOrientationEnabled(enabled: boolean): void;
  /** Remove browser listeners and discard the attached orientation gizmo. */
  dispose(): void;
};
 
export type SceneRenderOptions = {
  onContextLost?: () => void;
  onContextRestored?: () => void;
};
 
export type QuaternionComponents = Readonly<{ x: number; y: number; z: number; w: number }>;
 
type SceneVector = readonly [number, number, number];
 
export type VirtualFrameOrientation = Readonly<{
  right: SceneVector;
  up: SceneVector;
  front: SceneVector;
  colors: OrientationIndicatorColors;
}>;
 
/**
 * Attach the regrip gizmo to cubing.js' existing WebGL scene.
 *
 * This intentionally renders on demand rather than running a permanent 60fps
 * loop: gyro, virtual-frame, and player updates call `requestRender`. That
 * keeps mobile GPUs idle between cube events and makes context loss recoverable.
 */
export function startSceneRenderLoop(
  player: ScenePlayer,
  { onContextLost, onContextRestored }: SceneRenderOptions = {},
): SceneRenderer {
  const restingCubeQuaternion = new THREE.Quaternion().setFromEuler(
    new THREE.Euler((30 * Math.PI) / 180, (-30 * Math.PI) / 180, 0),
  );
  const cubeQuaternion = restingCubeQuaternion.clone();
  const virtualFrameQuaternion = new THREE.Quaternion();
  const virtualFrameColors = { ...HOME_FRAME_COLORS };
  let scene: THREE.Scene | undefined;
  let vantage: Vantage | undefined;
  let canvas: HTMLCanvasElement | undefined;
  let orientationIndicator: THREE.Group | undefined;
  let active = true;
  let contextLost = false;
  let disposed = false;
  let scheduled = false;
  let rendering = false;
  let dirty = true;
  let animationFrame: number | undefined;
  let manualOrientationEnabled = false;
  let manualPointer:
    { id: number; x: number; y: number; orientation: THREE.Quaternion } | undefined;
  let manualListenersAttached = false;
  // This is a stable world-space corner; the R/U/F axes still inherit the
  // scene rotation that renders the physical cube. Virtual regrips transform
  // move notation, but the gyro-driven scene already represents their pose.
  const indicatorPosition = new THREE.Vector3(-0.82, -0.8, 0);
  const inverseSceneQuaternion = new THREE.Quaternion();
  const yawAxis = new THREE.Vector3(0, 1, 0);
  const pitchAxis = new THREE.Vector3(1, 0, 0);
  const manualYaw = new THREE.Quaternion();
  const manualPitch = new THREE.Quaternion();
 
  const updateCanvasCursor = (): void => {
    if (!canvas?.style) return;
    canvas.style.cursor = manualOrientationEnabled ? 'grab' : '';
    canvas.style.touchAction = manualOrientationEnabled ? 'none' : '';
  };
 
  const handlePointerDown = (event: PointerEvent): void => {
    if (!manualOrientationEnabled || !canvas) return;
    // Snapshot the current pose. Each drag is measured from this familiar
    // starting angle instead of compounding a new rotation for every pixel.
    manualPointer = {
      id: event.pointerId,
      x: event.clientX,
      y: event.clientY,
      orientation: cubeQuaternion.clone(),
    };
    canvas.setPointerCapture?.(event.pointerId);
    if (canvas.style) canvas.style.cursor = 'grabbing';
    event.preventDefault();
  };
 
  const handlePointerMove = (event: PointerEvent): void => {
    if (!manualOrientationEnabled || !manualPointer || event.pointerId !== manualPointer.id) return;
    const dx = event.clientX - manualPointer.x;
    const dy = event.clientY - manualPointer.y;
    manualYaw.setFromAxisAngle(yawAxis, dx * 0.008);
    manualPitch.setFromAxisAngle(pitchAxis, dy * 0.008);
    cubeQuaternion.copy(manualPointer.orientation).premultiply(manualYaw).premultiply(manualPitch);
    event.preventDefault();
    dirty = true;
    schedule();
  };
 
  const handlePointerUp = (event: PointerEvent): void => {
    if (event.pointerId !== manualPointer?.id) return;
    manualPointer = undefined;
    if (canvas?.style) canvas.style.cursor = 'grab';
  };
 
  const detachManualOrientation = (): void => {
    if (!canvas || !manualListenersAttached) return;
    canvas.removeEventListener('pointerdown', handlePointerDown);
    canvas.removeEventListener('pointermove', handlePointerMove);
    canvas.removeEventListener('pointerup', handlePointerUp);
    canvas.removeEventListener('pointercancel', handlePointerUp);
    manualListenersAttached = false;
    manualPointer = undefined;
  };
 
  const syncManualOrientation = (): void => {
    if (!canvas) return;
    if (manualOrientationEnabled && !manualListenersAttached) {
      canvas.addEventListener('pointerdown', handlePointerDown);
      canvas.addEventListener('pointermove', handlePointerMove);
      canvas.addEventListener('pointerup', handlePointerUp);
      canvas.addEventListener('pointercancel', handlePointerUp);
      manualListenersAttached = true;
    } else if (!manualOrientationEnabled) {
      detachManualOrientation();
    }
    updateCanvasCursor();
  };
 
  const canRender = (): boolean =>
    active && !contextLost && !disposed && (typeof document === 'undefined' || !document.hidden);
 
  const detachScene = (): void => {
    if (scene && orientationIndicator) scene.remove(orientationIndicator);
    scene = undefined;
    vantage = undefined;
    orientationIndicator = undefined;
  };
 
  const cancelFrame = (): void => {
    if (animationFrame !== undefined) cancelAnimationFrame(animationFrame);
    animationFrame = undefined;
    scheduled = false;
  };
 
  const handleContextLost = (event: Event): void => {
    event.preventDefault();
    contextLost = true;
    cancelFrame();
    onContextLost?.();
  };
 
  const handleContextRestored = (): void => {
    contextLost = false;
    detachScene();
    dirty = true;
    onContextRestored?.();
    schedule();
  };
 
  const attachCanvas = async (nextVantage: Vantage): Promise<void> => {
    const nextCanvas = (await nextVantage.canvasInfo()).canvas;
    if (canvas === nextCanvas) return;
    detachManualOrientation();
    canvas?.removeEventListener('webglcontextlost', handleContextLost);
    canvas?.removeEventListener('webglcontextrestored', handleContextRestored);
    canvas = nextCanvas;
    canvas.addEventListener('webglcontextlost', handleContextLost);
    canvas.addEventListener('webglcontextrestored', handleContextRestored);
    syncManualOrientation();
  };
 
  const ensureScene = async (): Promise<void> => {
    if (scene && vantage) return;
    const vantages = await player.experimentalCurrentVantages();
    const nextVantage = [...vantages][0] as Vantage | undefined;
    const nextScene = nextVantage?.scene && (await nextVantage.scene.scene());
    if (!nextVantage || !nextScene) return;
    vantage = nextVantage;
    scene = nextScene;
    orientationIndicator = createOrientationIndicator();
    // cubing.js scene units project much larger than the rendered cube; keep
    // the compass compact and comfortably inside the viewport.
    orientationIndicator.scale.setScalar(0.38);
    scene.add(orientationIndicator);
    await attachCanvas(nextVantage);
  };
 
  const render = async (): Promise<void> => {
    if (!canRender() || !dirty || rendering) return;
    rendering = true;
    dirty = false;
    try {
      await ensureScene();
      if (!canRender() || !scene || !vantage) return;
      // OrientationStabilizer provides the smoothing and detent behaviour.
      scene.quaternion.copy(cubeQuaternion);
      // Only the indicator is reframed: virtual x/y/z turns rename the
      // user's R/U/F frame without changing the physical gyro pose.
      orientationIndicator?.quaternion.copy(virtualFrameQuaternion);
      if (orientationIndicator)
        setOrientationIndicatorColors(orientationIndicator, virtualFrameColors);
      // Compensate the parent transform for position only: this pins the
      // gizmo in view while preserving the inherited axis rotation.
      inverseSceneQuaternion.copy(scene.quaternion).invert();
      orientationIndicator?.position
        .copy(indicatorPosition)
        .applyQuaternion(inverseSceneQuaternion);
      await vantage.render();
    } catch (error) {
      console.warn('cube scene render', error);
    } finally {
      rendering = false;
      if (dirty) schedule();
    }
  };
 
  const schedule = (): void => {
    if (!canRender() || !dirty || scheduled) return;
    scheduled = true;
    animationFrame = requestAnimationFrame(() => {
      animationFrame = undefined;
      scheduled = false;
      void render();
    });
  };
 
  const handleVisibilityChange = (): void => {
    if (typeof document === 'undefined' || document.hidden) {
      cancelFrame();
      return;
    }
    // A long-backgrounded tab can have its GPU context reclaimed without any
    // pending cube event to mark the scene dirty again. Always repaint on
    // return rather than relying on dirty already being true.
    dirty = true;
    schedule();
  };
 
  if (typeof document !== 'undefined')
    document.addEventListener('visibilitychange', handleVisibilityChange);
  schedule();
 
  return {
    requestRender: () => {
      dirty = true;
      schedule();
    },
    setCubeOrientation: ({ x, y, z, w }) => {
      cubeQuaternion.set(x, y, z, w);
      dirty = true;
      schedule();
    },
    resetCubeOrientation: () => {
      cubeQuaternion.copy(restingCubeQuaternion);
      dirty = true;
      schedule();
    },
    setVirtualFrameOrientation: ({ right, up, front, colors }) => {
      virtualFrameQuaternion.setFromRotationMatrix(
        new THREE.Matrix4().makeBasis(
          new THREE.Vector3(...right),
          new THREE.Vector3(...up),
          new THREE.Vector3(...front),
        ),
      );
      virtualFrameColors.x = colors.x;
      virtualFrameColors.y = colors.y;
      virtualFrameColors.z = colors.z;
      dirty = true;
      schedule();
    },
    setActive: (nextActive) => {
      active = nextActive;
      if (!active) cancelFrame();
      else {
        dirty = true;
        schedule();
      }
    },
    setManualOrientationEnabled: (enabled) => {
      manualOrientationEnabled = enabled;
      if (!enabled) manualPointer = undefined;
      syncManualOrientation();
    },
    dispose: () => {
      disposed = true;
      cancelFrame();
      if (typeof document !== 'undefined')
        document.removeEventListener('visibilitychange', handleVisibilityChange);
      canvas?.removeEventListener('webglcontextlost', handleContextLost);
      canvas?.removeEventListener('webglcontextrestored', handleContextRestored);
      detachManualOrientation();
      detachScene();
    },
  };
}