# Quest WebXR Performance & Draw-Call Instancing in Three.js

> Stay under 200 draw calls and 300k stereo triangles per frame in WebXR via InstancedMesh batches, zero-alloc updates, and WorldPanel HUDs.

- **Canonical page:** https://gamecrew.ai/techniques/three/webxr-quest-performance-instancing
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** vr
- **Tags:** `webxr`, `vr`, `instancing`, `performance`, `quest`, `draw-calls`, `world-ui`
- **Verification:** Compile-verified pattern

## When to Use & Field Best Practices

In WebXR, the GPU renders left and right eyes every frame at 72–90 Hz on mobile tile-based GPUs. A scene that coasts along on desktop can stall Quest frame timing if every lantern, balustrade post, crystal shard, or reed draws individually:

1. **Batch Repeats into `THREE.InstancedMesh`**: Group static and rhythmically swaying props of the same material into one `InstancedMesh`, computing transforms through a single pre-allocated `THREE.Object3D` dummy outside `game.onUpdate`.
2. **Hard Stereo Ceiling (`<= 200` Draws, `<= 300k` Triangles)**: Reserve real-time shadows for the main directional light on a compact shadow frustum (`512`–`1024`), use `MeshLambertMaterial` or lightweight `MeshStandardMaterial`, and disable `EffectComposer` / bloom automatically when `game.xr.active` is true.
3. **World-Space UI Only**: DOM overlays never appear inside a headset. Render wave counters, scoreboards, and interactive buttons with `game.xr.panel(...)` (`WorldPanel`) placed 1.2–2.0 m from eye height.

## Mathematical & Algorithmic Core

- **Total Vertex Shading Work**:
  $$C_{\text{draw}} \approx N_{\text{unique\_materials}} \times 2_{\text{eyes}}, \qquad T_{\text{frame}} = 2 \sum_{i} \text{tris}(M_i) \cdot \text{instances}(M_i)$$
- **Phase-Staggered Instance Matrix Update**: Update only active animated instances (`visibleCount`), using deterministic trig phase $\phi_i = i \cdot 1.618$ without allocating per-step matrices or quaternions.

## Engine Implementation

### Batched Prop Instancer & World HUD (`Assets/Game/vr-instanced-stage.ts`)

```ts
import * as THREE from 'three';
import type { Game, WorldPanel } from 'ccgd';

export interface SwayPropBatch {
  readonly mesh: THREE.InstancedMesh;
  readonly count: number;
  readonly baseX: Float32Array;
  readonly baseY: Float32Array;
  readonly baseZ: Float32Array;
  readonly baseYaw: Float32Array;
  readonly phase: Float32Array;
}

const _dummy = new THREE.Object3D();
const _tint = new THREE.Color();

export function createSwayPropBatch(
  scene: THREE.Scene,
  geometry: THREE.BufferGeometry,
  material: THREE.Material,
  positions: ReadonlyArray<readonly [number, number, number, number]>,
): SwayPropBatch {
  const count = positions.length;
  const mesh = new THREE.InstancedMesh(geometry, material, count);
  mesh.castShadow = false;
  mesh.receiveShadow = true;

  const baseX = new Float32Array(count);
  const baseY = new Float32Array(count);
  const baseZ = new Float32Array(count);
  const baseYaw = new Float32Array(count);
  const phase = new Float32Array(count);

  for (let i = 0; i < count; i++) {
    const [x, y, z, yaw] = positions[i];
    baseX[i] = x;
    baseY[i] = y;
    baseZ[i] = z;
    baseYaw[i] = yaw;
    phase[i] = i * 1.6180339;

    _dummy.position.set(x, y, z);
    _dummy.rotation.set(0, yaw, 0);
    _dummy.scale.setScalar(1);
    _dummy.updateMatrix();
    mesh.setMatrixAt(i, _dummy.matrix);

    // Subtle per-instance warmth variation with zero extra materials
    _tint.setHSL(0.08 + (i % 5) * 0.012, 0.28, 0.52 + (i % 3) * 0.06);
    mesh.setColorAt(i, _tint);
  }

  mesh.instanceMatrix.needsUpdate = true;
  if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
  scene.add(mesh);

  return { mesh, count, baseX, baseY, baseZ, baseYaw, phase };
}

export function mountVrStageBudget(
  game: Game,
  batch: SwayPropBatch,
): { readonly scoreboard: WorldPanel; setScore: (value: number) => void } {
  let score = 0;
  const scoreboard = game.xr.panel({ width: 0.72, height: 0.34 });
  scoreboard.object.position.set(0, 1.55, -2.2);
  game.scene.add(scoreboard.object);

  const redrawBoard = () => {
    scoreboard.draw((p) => {
      p.panel(0, 0, p.w, p.h);
      p.label('Sanctuary Resonance', 32, 30);
      p.text(String(score), 32, 92, { size: 112, font: 'display', color: 'accent' });
      p.text(
        game.xr.active ? 'WebXR Stereo Active' : 'Desktop Flat Mode',
        32,
        240,
        { size: 32, color: 'muted' },
      );
    });
  };
  redrawBoard();

  game.xr.onEnter(() => redrawBoard());
  game.xr.onExit(() => redrawBoard());

  let time = 0;
  game.onUpdate((dt) => {
    time += dt;
    for (let i = 0; i < batch.count; i++) {
      const sway = Math.sin(time * 2.1 + batch.phase[i]) * 0.06;
      _dummy.position.set(batch.baseX[i], batch.baseY[i], batch.baseZ[i]);
      _dummy.rotation.set(sway, batch.baseYaw[i], sway * 0.5);
      _dummy.scale.setScalar(1);
      _dummy.updateMatrix();
      batch.mesh.setMatrixAt(i, _dummy.matrix);
    }
    batch.mesh.instanceMatrix.needsUpdate = true;
  });

  return {
    scoreboard,
    setScore: (value: number) => {
      score = value;
      redrawBoard();
    },
  };
}
```

## Headset & Desktop Budgets

- **Redraw World Panels On Change Only**: Calling `scoreboard.redraw()` when scores or states change — never inside `game.onUpdate` — avoids 60 Hz Canvas2D texture uploads over the WebXR bridge.
- **Keep Dynamic Shadows Narrow**: Disable `castShadow` on small instanced foliage/debris so the shadow pass renders only major architecture and gameplay landmarks.

## Verification Checklist

1. Inspect `game.renderer.info.render.calls` during an emulated headset run (`vr-check`) and confirm total draw calls stay well under `200` and triangles under `300,000`.
2. Toggle `xr.sim.enter()` / `xr.sim.exit()` and verify the `WorldPanel` board updates cleanly without overlapping HTML or headset errors.

## Official references

- Meta Quest WebXR Frame Budget Guidelines
- Khronos WebGL 2 Instanced Drawing Specification
