SSN CODING CLUBAR, VR & Game Dev Wing
THE SSN CHRONICLE
AR, VR & Game Dev Wing

Master Guide: 3D Environments and XR

A comprehensive AI-ready guide for building immersive 3D environments, AR, VR and MR experiences using Three.js, React Three Fiber, WebXR and IWSDK. Empowers students and AI coding agents to create, optimize, test and deploy visually engaging, cross-platform XR applications.

Master Guide: 3D Environments and XR

A reusable guide for building browser-based 3D worlds, VR/MR experiences and phone AR. It covers two implementation styles: IWSDK with Three.js, and React Three Fiber with WebXR. They are alternatives, not one combined stack. First inspect the target repository and follow the framework it already uses.

Examples are patterns, not assumptions about a repository's installed versions, folder names, APIs or scripts. Confirm those from its manifests, lockfile, source and installed framework documentation before changing code.

Contents


1. Essential terms

  • XR: an immersive session where a headset or supported device presents a virtual or augmented view.
  • VR: the environment is virtual.
  • AR: virtual content is overlaid on a view of the real world.
  • MR: virtual content is integrated with the real environment, often using headset passthrough, detected surfaces or depth.
  • ECS: an entity-component system. Entities are IDs/objects, components hold data, and systems process entities with matching components.
  • IWER: IWSDK's browser-based XR emulator. It is useful for iteration, but cannot prove real passthrough, tracking quality or room alignment.
  • Target-ray pose: the direction a controller points for aiming or selection.
  • Grip pose: the controller's held position and orientation. It is different from the target ray.

2. Choose the existing runtime

If the repository uses... · Use its established pattern

  • IWSDK iwsdk.config.json, World.create(), IWSDK ECS systems, its asset/component manifests and managed dev tools.

  • React Three Fiber (R3F) One persistent <Canvas>, React Three Fiber hooks, and an XR store from the installed XR package.

  • Native WebXR + Three.js navigator.xr, XRSession, reference spaces and frame callbacks with the repository's renderer.

Do not install or combine another renderer/XR framework just because an example uses it. Avoid running raw Three.js objects through duplicate copies of Three.js; mismatched class identities can break type checks and UI systems.


3. Package map

Check package.json and the lockfile first. The list below explains common choices; a project only needs the packages required by its chosen stack.

Rendering and framework

Package · Role

  • three Core WebGL scene graph, cameras, geometry, materials, textures, transforms, raycasting and shader APIs.

  • @iwsdk/core IWSDK runtime: world/XR lifecycle, ECS APIs, asset management, UI integration and Three.js exports. In IWSDK applications, use its Three.js exports for runtime objects so the app has one Three instance.

  • react, react-dom Application UI and DOM mounting for a React/R3F app. Match React's major version with the chosen R3F version.

  • @react-three/fiber Connects Three.js rendering and lifecycle to React. Provides <Canvas>, useFrame and useThree.

  • @react-three/drei Optional R3F helpers for models, textures, environments, controls, text, shadows and performance.

  • @react-three/xr XR store/session integration for R3F, including headset origins, hands, controllers, ray pointers and overlays.

  • three-stdlib Optional Three.js utilities such as water, RGBE loading and post-processing. Prefer the utility already used by the repository.

Import rule: for IWSDK, import Three.js classes from @iwsdk/core. For a plain Three.js/R3F app, import from the one configured three package. Do not mix package instances. Use type-only add-on imports only when the framework's own guidance permits them.

Spatial UI

Package · Role

  • @pmndrs/uikit Three.js spatial UI primitives; often part of IWSDK's UIKit stack.

  • @pmndrs/uikit-horizon Horizon/Reality Labs components for the PMNDRS UIKit stack.

  • @pmndrs/uikit-lucide Lucide icons for PMNDRS UIKit.

  • @react-three/uikit, @react-three/uikit-lucide R3F-oriented spatial panels, controls, text and icons.

These are different UI integrations. Use the one supported by the app. A 2D map or web panel is not a substitute for in-world controls when a spatial interface is required.

Physics, state and procedural content

Package · Role

  • @react-three/rapier Rapier/WASM physics integration for R3F. Use fixed bodies for static structures and avoid a physics body for every decorative mesh.

  • react-joystick-component Optional touch joystick for flat-screen movement.

  • zustand Small shared state store; keep high-frequency transforms in refs or mutable data rather than triggering React renders every frame.

  • leva Development-only runtime tuning controls. Do not make shipped controls depend on it.

  • seedrandom Seeded random values for reproducible procedural layouts.

  • simplex-noise Smooth noise for terrain, waves, clouds and variation.

For modest environments, pure collision boundaries and a ground-height function can be simpler and cheaper than full physics.

Build, tests and development tools

Package · Role

  • vite Development server and production bundler.

  • @vitejs/plugin-react React refresh and JSX transformation in an R3F app.

  • @iwsdk/vite-plugin-dev Connects Vite to IWSDK development and emulation tooling.

  • @iwsdk/cli Managed IWSDK dev server and runtime, scene and XR commands.

  • @iwsdk/reference Local IWSDK API/reference search.

  • @meta-quest/metavr Host-side Quest device and performance CLI; not a browser runtime dependency.

  • typescript, @types/three Type checking and Three.js type declarations.

  • vitest Unit tests, commonly for pure geometry, state and gesture code.

  • eslint Static checks and style rules; use the repository's configured plugins.

  • puppeteer-core Browser automation; requires a separately available compatible browser executable.

  • vite-plugin-pwa Optional app manifest, service worker and offline caching.

  • vite-plugin-compression Optional gzip/Brotli output; the host must serve compressed files correctly.

Version compatibility matters. Pin compatible versions through the lockfile and consult the installed package's docs/types rather than guessing APIs.

For example, current R3F documentation pairs R3F v9 with React 19 and R3F v8 with React 18. Verify the current compatibility table when creating or upgrading an app.


4. Start and inspect a repository

Before coding:

  1. Read the project instructions, package.json, lockfile, runtime config, entry point and the relevant scene/asset/system files.
  2. Identify the renderer, XR library, module boundaries, existing tests and the actual start/build commands.
  3. Search for established examples of the API or component you need; prefer existing helpers over duplicating them.
  4. Confirm the intended device, interaction mode, coordinate scale and failure fallback.

Use the scripts that exist in the repository. A typical project may provide:

npm ci
npm run dev
npm run typecheck
npm test
npm run build

For IWSDK, use the managed dev command and runtime bridge. Starting Vite directly may omit the managed browser and editor integration. For any WebXR app, use HTTPS or localhost; a valid secure origin and browser/device support are required.

Starting from an empty directory

Choose one stack first. Do not install all three runtimes.

IWSDK — use the official scaffolder, then follow the prompts:

npm create @iwsdk@latest

React Three Fiber — scaffold TypeScript React, then install compatible versions. Keep the React major version aligned with R3F:

npm create vite@latest xr-world -- --template react-ts
cd xr-world
npm install
npm install three @react-three/fiber @react-three/xr

Add @react-three/drei only when a feature needs its helpers. If the generated starter already includes a dependency, do not add a duplicate version.

Native Three.js + WebXR — scaffold a small TypeScript or vanilla app and install Three.js:

npm create vite@latest xr-world -- --template vanilla-ts
cd xr-world
npm install
npm install three

First prove the scaffold by rendering one mesh and checking one supported XR session on the target device. Then add assets, input, interactions and world systems incrementally. Re-check the installed package documentation after scaffolding; commands and templates can change.

Device support and fallbacks

Never infer XR support only from the device name. Support depends on browser, operating system, permissions, secure origin, requested mode and optional session features. Detect capabilities at runtime and keep a usable non-immersive path.

Target · Practical default

  • Desktop browser 3D preview with mouse/keyboard; use an emulator for XR iteration.

  • Android phone Touch-first 3D; offer immersive AR only when the browser reports support.

  • iPhone/iPad Touch-first 3D or a native app path; do not assume Safari provides immersive WebXR AR.

  • Standalone headset Test supported VR/AR modes, hand tracking, controllers, passthrough and optional features on the actual device/browser.

  • Other spatial headsets Feature-detect each required session mode and input capability; do not assume Quest-specific APIs exist.

navigator.xr.isSessionSupported(mode) checks the mode, not every optional feature. Request optional features when the experience can degrade gracefully, and handle a rejected session request with a visible explanation and fallback.

When embedding an XR app, check the iframe's allow attribute and the server's Permissions Policy. For example, an embedding page may need allow="xr-spatial-tracking"; only grant permissions to trusted origins.


5. IWSDK architecture

Configuration and world creation

iwsdk.config.json is the project authority for the active scene, asset/component modules, XR mode/features, rendering and world features. vite.config.ts wires Vite and its plugin; it is not a substitute for the IWSDK world config.

virtual:iwsdk-project is generated by IWSDK. Import and pass it whole to World.create(); do not hand-build a parallel options object:

import { World } from '@iwsdk/core';
import projectOptions from 'virtual:iwsdk-project';

World.create(
  document.getElementById('scene-container') as HTMLDivElement,
  projectOptions,
).then((world) => {
  world.registerSystem(GameSystem);
});

The actual entry point may register multiple systems and additional app setup. Preserve that pattern.

Assets, components and scene composition

A typical IWSDK layout is:

iwsdk.config.json
src/
  index.ts
  assets.ts
  components.ts
  systems/
  scene-assets/
public/
  scenes/
  ui/
  models/
  textures/
  env/

Use the repository's actual names if they differ.

  • Geometry/model prototypes: create reusable parentless Group/Object3D assets in TypeScript.
  • Asset manifest: register stable asset IDs with defineAssets(). Use AssetType for GLTF, textures and UIKitML. Load through AssetManager or the established manifest path, not an unrelated loader.
  • Public files: build URLs from import.meta.env.BASE_URL if the app can be deployed below a subpath. Lazy-load large assets that are not immediately needed.
  • Scene JSON: use it for composition, transforms, lights and environment settings according to the installed schema. Keep procedural geometry and materials in TypeScript; do not put raw geometry or arbitrary URLs in a schema that expects manifest IDs.
  • Components: declare them in the system-free component module exported through defineComponents(), so both runtime and editor can discover them.
  • Asset module purity: IWSDK may evaluate the asset module in separate runtime/editor realms. Keep it deterministic and free of world, DOM, timers or shared-object-identity assumptions.

Simple procedural asset:

import { Group, Mesh, MeshStandardMaterial, SphereGeometry } from '@iwsdk/core';

export function createMarker(): Group {
  const root = new Group();
  root.name = 'Marker';
  root.add(
    new Mesh(
      new SphereGeometry(0.15, 16, 12),
      new MeshStandardMaterial({ color: '#3DF5FF', roughness: 0.4 }),
    ),
  );
  return root;
}

Register the returned prototype in the manifest and create runtime entities through world.createTransformEntity(...). Do not bypass the ECS with scene.add() for gameplay objects.

ECS system structure

Systems own engine-facing behavior. Put one-time setup and reusable objects in init(), update state in update(delta, time), query components rather than maintaining parallel entity arrays, and clean up subscriptions.

import { createSystem, Group, XRPlane } from '@iwsdk/core';

export class RoomSystem extends createSystem({
  planes: { required: [XRPlane] },
}) {
  init(): void {
    const root = new Group();
    root.name = 'RoomContent';
    this.world.createTransformEntity(root, { persistent: true });
  }

  update(delta: number, time: number): void {
    for (const entity of this.queries.planes.entities) {
      // Read the detected plane and update reusable room state.
    }
  }
}

Use queries.x.subscribe('qualify', ...) when reacting to entities entering a query, and add every teardown to cleanupFuncs. Reuse vectors, matrices, geometries and materials; per-frame allocation is a performance bug in standalone XR.


6. React Three Fiber architecture

Use one persistent Canvas and XR store while changing worlds or routes. Unmounting the Canvas can end an active XR session.

import { useState } from 'react';
import { Canvas } from '@react-three/fiber';
import { XR, createXRStore } from '@react-three/xr';

const xrStore = createXRStore();

export function App() {
  const [error, setError] = useState('');

  async function enter(mode) {
    setError('');
    try {
      if (!navigator.xr || !(await navigator.xr.isSessionSupported(mode))) {
        throw new Error(`${mode} is not supported on this device/browser.`);
      }
      if (mode === 'immersive-vr') await xrStore.enterVR();
      else await xrStore.enterAR();
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : String(reason));
    }
  }

  return (
    <>
      <button onClick={() => void enter('immersive-vr')}>Enter VR</button>
      <button onClick={() => void enter('immersive-ar')}>Enter AR</button>
      {error && <p role="alert">{error}</p>}
      <Canvas>
        <XR store={xrStore}>
          <ambientLight intensity={0.8} />
          <directionalLight position={[5, 5, 5]} intensity={2} />
          <mesh position={[0, 1.5, -3]}>
            <boxGeometry />
            <meshStandardMaterial color="orange" />
          </mesh>
        </XR>
      </Canvas>
    </>
  );
}

This is a minimal starting point, not a finished production shell. navigator.xr may need WebXR TypeScript definitions or a typed feature guard. Keep the buttons in a normal DOM overlay unless spatial controls are required; add loading/disabled states and clear recovery for real applications. Each enter*() call must remain inside a user-activation handler.

The scene should remain mounted through route changes:

<Canvas camera={{ fov: 62, near: 0.05, far: 700 }}>
  <XR store={xrStore}>
    {activeWorld}
  </XR>
</Canvas>

Initialize the XR store once. Replace activeWorld rather than the Canvas/XR provider when navigating.

  • Use useFrame for high-frequency animation and mutate refs/Three objects directly.
  • Avoid React state updates for every hand pose or frame.
  • Keep shared player/session state in a small store; keep frame-local transforms in refs.
  • Start enterVR()/enterAR() only in response to a user gesture.
  • Check navigator.xr?.isSessionSupported() before showing an entry option.
  • Restore or synchronize desktop player state on XR exit if continuity matters.

7. Build a 3D environment

Plan the scene before modelling

  1. Define the experience scale in metres, player height/origin and comfortable viewing distance.
  2. Block out the ground, walkable area, major silhouettes, landmarks and safe boundaries.
  3. Decide what is static, interactive, repeated, animated or visible only at a particular distance.
  4. Establish a readable visual hierarchy: primary subject first, supporting geometry second, detail last.
  5. Add collision only where gameplay needs it; visual meshes and physics colliders do not need one-to-one correspondence.

Geometry, materials and lighting

  • Use primitives for blockout, then replace only important forms with authored or optimized models.
  • Keep object origins/pivots meaningful; apply scale and transforms deliberately.
  • Name important child meshes when runtime code needs to animate or recolor them.
  • Use physically based materials for ordinary surfaces; use custom shaders only for effects that justify their cost.
  • Use environment maps for broad ambient reflections and a small set of purposeful lights for form and focus.
  • Use a sky dome/gradient when needed, but hide or adapt it when real-world passthrough is the background.
  • Use a stable palette and lighting direction so silhouettes remain legible on a headset.
  • Reuse materials and textures; avoid creating a unique material for each repeated object.

Procedural worlds

Use a seeded random generator when layouts must reproduce across reloads or devices. Use smooth noise for terrain or organic variation: lower frequencies form broad hills and higher frequencies add detail. Clamp slopes and heights to keep paths traversable, and keep gameplay placement separate from cosmetic noise.

For repeated props, use InstancedMesh or an engine equivalent. For a complex static model, normalize world transforms, merge compatible geometry/material groups, remove unused attributes and instance the result where possible. Measure the result; merging can hurt culling or material flexibility if applied indiscriminately.


8. Mixed reality, AR and room-scale

Room-scale MR

For passthrough MR, configure only the XR features the experience needs: hand tracking, plane detection, mesh detection, anchors, hit testing or depth sensing. Feature support depends on browser, runtime and hardware; request optional capabilities when the app can still work without them.

  • Use detected horizontal planes for placement and vertical planes for wall-aware placement or boundaries.
  • Convert room planes into simple, tested geometry data (segments, polygons, bounds) before using them in gameplay.
  • Keep a fallback when room data is absent, incomplete or delayed. Core gameplay must not dead-end on a failed scan.
  • Keep real-world movement aligned to the user's tracked origin. Avoid artificial locomotion when the design expects safe room-scale walking.
  • Provide clear placement affordances and prevent virtual objects from appearing inside the user or unsafe real-world geometry.
  • Treat tabletop and life-size modes as different coordinate transforms. Save/restore the world transform when switching.
  • If depth sensing is available, use it for real-object occlusion; otherwise be explicit that virtual objects may render over real furniture.
  • Avoid covering real hazards and keep play areas clear.

Tabletop AR

For a tabletop world, place a bounded miniature at a comfortable distance, keep distant skies/geometry out of view, and let users move/rotate/scale the entire world. For life-size mode, align the player origin and floor to the real floor rather than scaling the miniature in place. Restore the previous transform when changing modes.

Native WebXR hit testing

For a Three.js app not managed by IWSDK, use Three.js's WebXRManager to attach the immersive session and drive rendering. The following example assumes renderer, scene, camera, reticle, a UI status element and an Enter AR button already exist:

renderer.xr.enabled = true;
renderer.xr.setReferenceSpaceType('local');
reticle.matrixAutoUpdate = false;
reticle.visible = false;
scene.add(reticle);

let hitTestSource = null;
let activeSession = null;
let sessionEndHandler = null;

renderer.setAnimationLoop((_time, frame) => {
  let hasHit = false;
  const referenceSpace = renderer.xr.getReferenceSpace();

  if (frame && hitTestSource && referenceSpace) {
    const hit = frame.getHitTestResults(hitTestSource)[0];
    const pose = hit?.getPose(referenceSpace);
    if (pose) {
      reticle.matrix.fromArray(pose.transform.matrix);
      reticle.matrixWorldNeedsUpdate = true;
      hasHit = true;
    }
  }

  reticle.visible = hasHit;
  renderer.render(scene, camera);
});

async function enterAR() {
  let session = null;
  let source = null;
  try {
    if (activeSession) throw new Error('An AR session is already active.');
    if (!navigator.xr || !(await navigator.xr.isSessionSupported('immersive-ar'))) {
      throw new Error('Immersive AR is not supported on this device/browser.');
    }

    session = await navigator.xr.requestSession('immersive-ar', {
      requiredFeatures: ['hit-test'],
    });
    await renderer.xr.setSession(session);

    const viewerSpace = await session.requestReferenceSpace('viewer');
    source = await session.requestHitTestSource({ space: viewerSpace });
    hitTestSource = source;
    activeSession = session;
    sessionEndHandler = () => {
      source.cancel();
      if (hitTestSource === source) hitTestSource = null;
      if (activeSession === session) activeSession = null;
      sessionEndHandler = null;
      reticle.visible = false;
    };
    session.addEventListener('end', sessionEndHandler, { once: true });
    statusElement.textContent = '';
  } catch (error) {
    source?.cancel();
    if (hitTestSource === source) hitTestSource = null;
    if (activeSession === session) activeSession = null;
    if (session && sessionEndHandler) {
      session.removeEventListener('end', sessionEndHandler);
      sessionEndHandler = null;
    }
    reticle.visible = false;
    if (session) {
      try {
        await session.end();
      } catch (endError) {
        console.error('Could not end the partially initialized XR session:', endError);
      }
    }
    statusElement.textContent = `Unable to start AR: ${
      error instanceof Error ? error.message : String(error)
    }`;
  }
}

function cleanupAR() {
  const session = activeSession;
  if (session && sessionEndHandler) {
    session.removeEventListener('end', sessionEndHandler);
  }
  hitTestSource?.cancel();
  hitTestSource = null;
  activeSession = null;
  sessionEndHandler = null;
  reticle.visible = false;
  if (session) {
    void session.end().catch((error) => {
      console.error('Could not end the XR session during cleanup:', error);
    });
  }
}

function onEnterARClick() {
  void enterAR();
}

enterArButton.addEventListener('click', onEnterARClick);
// Call when this app-owned AR scene is torn down.
function disposeAR() {
  enterArButton.removeEventListener('click', onEnterARClick);
  cleanupAR();
}

The reticle should be a world-space object with a surface-aligned ring geometry; the example assumes it is attached directly to the scene. Keep the session request inside the button's user-activation handler and call disposeAR() when its app-owned scene is torn down. The animation loop renders both the desktop preview and active XR session; the XR-enabled renderer supplies an XRFrame while presenting.

Set reticle.matrixAutoUpdate = false before assigning the hit pose. For a horizontal placement reticle, orient its ring geometry to local +Y (for example, rotate a RingGeometry by -Math.PI / 2 around X); the hit-pose matrix then aligns that normal with the detected surface.

To use a DOM overlay, provide an existing root element when requesting the feature, and verify that it was enabled. Omit both the feature and option if no overlay is needed:

const overlayRoot = document.getElementById('xr-overlay');
if (!overlayRoot) throw new Error('Missing XR overlay root.');

const session = await navigator.xr.requestSession('immersive-ar', {
  requiredFeatures: ['hit-test'],
  optionalFeatures: ['dom-overlay'],
  domOverlay: { root: overlayRoot },
});

const hasDomOverlay = session.domOverlayState !== null;

Check hasDomOverlay before relying on DOM controls in XR; if false, keep controls usable in-world or continue without the overlay.

The hit-test source describes the ray to test; the returned pose is expressed in the requested reference space. XRReferenceSpace defines coordinates, XRViewerPose describes the viewer, XRInputSource represents an input source, and XREstimatedLight can expose estimated real-world lighting when supported.

If WebXR is unavailable, provide a desktop 3D preview and manual placement controls. A camera/gyro fallback can aid navigation but is not true surface-tracked AR.


9. Hand, gaze and controller interaction

  • Read joints/poses in a consistent coordinate space and metres.
  • Keep pose recognition in pure functions so it can be unit tested without a headset.
  • Normalize finger extension against hand dimensions instead of using one absolute distance for every hand.
  • Distinguish open palm, relaxed hand, fist, pinch and hand-tracking loss. Avoid overlapping gesture thresholds.
  • Use hysteresis, edge detection or a short dwell for pinch/selection so a gesture does not rapidly toggle.
  • Require a deliberate user action before starting an immersive session or destructive action.
  • Map recognized poses to game actions in a system/controller layer, not in UI rendering.
  • Provide an accessible fallback for essential actions when tracking is lost or unavailable.
  • A controller target ray is for aiming/selection; a grip pose is the controller's held transform. Use the correct pose for each task.

Unified input and locomotion

Separate device-specific input adapters from gameplay. Convert mouse/keyboard, touch, controller and tracked-hand events into a small shared action set such as move, turn, select, grab, release and interact. World/game logic should consume those actions rather than branch on hardware throughout every feature. Keep device capabilities and unavailable inputs explicit.

Choose movement for the experience and comfort needs:

  • Physical room-scale: let the player walk; respect tracked boundaries and keep hazards clear.
  • Teleport: point to a valid surface, show a preview, then move on confirmation.
  • Snap turn: rotate by a comfortable fixed increment; often the safest default for artificial turning.
  • Smooth turn / thumbstick locomotion: offer as an explicit option and test for motion discomfort.
  • Desktop: WASD/mouse or simple orbit controls for preview.
  • Mobile: touch joystick or drag controls only when useful; distinguish them from tracked movement.

Never directly overwrite a tracked headset camera pose to implement locomotion. Move the supported player rig/XR origin (for R3F, XROrigin) or apply a supported reference-space offset. In IWSDK, use its configured locomotion/input APIs rather than adding a second competing camera controller. Keep camera-relative interactions in the correct reference space and prevent the virtual player from crossing colliders.


10. Spatial UI and regular UI

Use spatial UI for controls that should remain in the world or follow the user; use regular DOM UI for setup, accessibility, maps or non-immersive screens. Keep critical information readable at headset resolution and avoid placing a panel directly over the main object or real-world hazards.

In IWSDK, authored UIKitML assets can be registered through the manifest and accessed through its UIKitML API. In R3F, use its compatible spatial UI library. Do not mix UI packages across framework stacks without verifying that they share the same Three.js instance.

For HUDs rendered as textures on meshes:

  • Keep text high-contrast and large enough at the intended viewing distance.
  • Redraw only when content changes.
  • Reuse the texture/material and avoid rebuilding the mesh every update.
  • Consider camera-facing billboards for small indicators, but avoid excessive transparency/overdraw.

11. Asset loading and deployment

  • Prefer optimized GLB for browser 3D models; compress large environments and resize textures to the actual need.
  • Reuse immutable models, textures and environment maps.
  • Lazy-load large worlds and models not needed on initial entry.
  • Preload only frequently used assets; offline precaching can consume significant headset storage.
  • Preserve asset licences and attribution with the asset collection.
  • Use a base/public URL helper so deployment below a URL subpath works.
  • Cache stable model/texture/environment assets separately from frequently changing data.
  • Browser-exposed environment variables should use the bundler's public prefix (for Vite, VITE_). Never put private credentials in client code.

Loading and integrating models

  • Never invent asset URLs, model filenames, package APIs or licences. Confirm that each referenced asset exists in the repository or comes from a verified source.
  • Prefer GLB for distribution. Check model scale, orientation, pivot/origin, bounding box, material count and animation clips before placing it in the scene.
  • Use the framework's asset manager/loader path. Draco or Meshopt geometry compression and KTX2/Basis Universal textures can reduce downloads, but require compatible decoders/transcoders and hosting paths. Do not add compression until the loader and build setup are verified.
  • For animated glTF, use an AnimationMixer; advance it with frame delta, stop actions and uncache the root when the model is permanently removed.
  • Use separate simple collision meshes when detailed render geometry is too expensive for physics.
  • Use LOD or distance-based detail only when profiling shows it helps and transitions do not pop distractingly.
  • Prefer procedural geometry for original, small forms when no suitable licensed asset is available. Keep generated geometry deterministic when it must match across runs.
  • Record asset origin, licence and attribution before shipping.

Deployment and secure origins

WebXR is restricted to secure contexts. https:// and loopback origins such as http://localhost are generally trustworthy; a plain LAN address such as http://192.168.x.x is not. For headset testing from another device, use HTTPS with a certificate trusted by that device, a secure development tunnel, or the framework's supported device-testing workflow. Accepting an invalid certificate may not make the origin trustworthy to every browser.

Static hosting (for example, GitHub Pages, Netlify or Vercel) is enough for client-side rendering, physics and interactions. Add a backend only when the product actually needs shared accounts, persistence, multiplayer or server-side services. For deployment, verify:

  • The build's base path and all model/texture/HDR URLs work from the deployed path.
  • Cross-origin assets send suitable CORS headers, especially when fetched by JavaScript/WebGL.
  • HTTPS is active and required WebXR permission policy is not blocked.
  • Embedded deployments grant xr-spatial-tracking only to the intended frame/origin.
  • Large model downloads and offline caching fit the device's network and storage limits.

12. Performance and comfort

Standalone headsets commonly target 72–90 frames per second, roughly 14–11 ms per frame for the whole rendering pipeline. Measure on the target device rather than assuming a desktop result transfers.

  • Avoid full-screen post-processing unless measured performance allows it.
  • Reduce draw calls with instancing, shared materials and carefully merged static geometry.
  • Pool transient particles/effects and reuse frame-loop objects.
  • Limit transparent layers, shadows, lights and costly shader work.
  • Use adaptive pixel ratio/quality tiers when device load requires them.
  • Lazy-load content and avoid shader compilation during active gameplay when feasible.
  • Keep locomotion comfortable; offer seated/standing or reduced-motion alternatives where appropriate.
  • Do not use frequent camera acceleration, forced movement or intense flashes without comfort options.
  • Profile both JS and GPU/rendering cost; optimizing only one may not improve frame rate.

GPU and lifecycle cleanup

Dispose GPU-backed resources only when their owning content is permanently removed and they are not shared:

geometry.dispose();
material.dispose();
texture.dispose();

If a material uses shared textures, dispose those textures only when their final owner is done. Traverse removed subtrees to dispose owned geometries/materials, but do not blindly dispose cached/shared assets. Also stop animation mixers/actions, remove DOM and XR event listeners, cancel hit-test sources, unsubscribe ECS/query listeners, stop audio nodes and remove physics bodies. Prefer the framework's asset cache/pool cleanup APIs when it owns those resources.


13. Visual quality

Technical correctness is only the foundation. Before adding detail, establish:

  • A deliberate visual style, limited palette and consistent material response.
  • A clear focal point, readable silhouettes, environmental storytelling and a purposeful horizon.
  • Realistic world scale, comfortable viewing distances and consistent object proportions.
  • Lighting that supports navigation and interaction, not only decoration.
  • A visible response to important actions (sound, animation, haptics, particles or state change) without overwhelming the scene.
  • A polished non-immersive landing/setup screen, clear onboarding, loading/error states and a reliable way to exit or restart.
  • Accessibility options for motion, flashes, seated/standing use and input alternatives where relevant.

Use restraint with bloom-like glow, particles, transparent layers and screen flashes; readability and headset comfort outrank spectacle.


14. Testing and verification

Test in increasing levels:

  1. Pure tests: geometry, deterministic generation, state transitions and gesture classification.
  2. Type check/lint: catch API and lifecycle errors before runtime.
  3. Desktop preview/emulator: validate scene load, basic UI and input flow.
  4. Runtime inspection: query the relevant entity/component or UI state; inspect console errors when a command fails.
  5. Headset: verify actual XR session, hand/controller input, comfort, passthrough, scale, placement and frame rate.

An editor preview does not run every app system. A desktop screenshot cannot prove real-world occlusion, physical hand alignment or immersive interaction. Use a real headset for those claims. If changing framework configuration, wait for the framework-managed runtime to be ready before issuing browser/XR commands.


15. Reliable implementation workflow for an LLM

Give an implementation agent this workflow for each feature or bug:

  1. Discover: read repository instructions, manifests, active runtime config, entry point and the narrow code path. Search for existing patterns and tests.
  2. Classify: identify the renderer/XR stack and the exact device/input target. Do not invent package APIs or migrate stacks as part of a small feature.
  3. Specify: state the expected behavior, preserved behavior, fallback behavior and a measurable check.
  4. Plan small: change the fewest related files. Keep pure rules separate from renderer/XR code.
  5. Implement: reuse assets, systems, helpers, naming, localization and cleanup conventions. Handle unsupported hardware and tracking loss explicitly.
  6. Check: run the smallest relevant test, then typecheck/build as configured. Fix errors caused by the change; avoid unrelated cleanup.
  7. Verify the real path: exercise the actual user input and inspect the resulting state. Use an emulator for iteration and real hardware for hardware-specific claims.
  8. Report honestly: list changed files, commands that passed, unverified device behavior and any assumptions.

Never claim a feature works on a headset based only on typecheck, unit tests or a flat screenshot. Make no silent fallbacks, broad error swallowing, per-frame allocations or risky API guesses.


16. Final build sequence

  1. Identify the stack and device targets from the existing repository.
  2. Confirm runtime configuration and package/API versions.
  3. Define world scale, composition, assets, lighting and collision needs.
  4. Build a small scene blockout and confirm the player view.
  5. Add interaction and room awareness with fallbacks.
  6. Add spatial UI and feedback.
  7. Optimize geometry, materials, draw calls, textures and frame-loop allocations.
  8. Run pure tests, typecheck, build and emulator checks.
  9. Verify on the actual headset/phone class before shipping.

17. Official references

ssn@codingclub:~$ discussion_

// Questions & conversations

Ask a question, share an idea or leave a reply.

THE MARGIN NOTES

Sign in with GitHub to join the conversation.

Opening the discussion…