TExcelTAD
Home › 3D Web Games with Three.js › Field Notes

Field Notes

These are the lessons Three.js game developers usually learn from a bug report: a phone that gets hot and drops to 20 FPS, a level that leaks memory every time it restarts, textures that look washed out on every machine but the artist's. Each note says what goes wrong, why, and what to do instead.

1. Dispose what you create, or the GPU leaks

JavaScript's garbage collector frees JavaScript objects, but geometries, materials, textures and render targets also own GPU resources that only dispose() releases. scene.remove(mesh) alone leaves the GPU buffers alive. Restart a level ten times without disposing and you have ten levels in GPU memory. renderer.info.memory shows the counts; this playground creates and removes 50 meshes, ten times, with and without disposing (output under the frame):

html · try it yourself
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer();
renderer.setSize(64, 64);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera();

function level(dispose) {
  const meshes = [];
  for (let i = 0; i < 50; i++) {
    const tex = new THREE.DataTexture(new Uint8Array([255, 128, 0, 255]), 1, 1);
    tex.needsUpdate = true;
    const m = new THREE.Mesh(new THREE.BoxGeometry(), new THREE.MeshStandardMaterial({ map: tex }));
    scene.add(m);
    meshes.push(m);
  }
  renderer.render(scene, camera);                 // GPU resources are created on first render
  for (const m of meshes) {
    scene.remove(m);
    if (dispose) { m.geometry.dispose(); m.material.map.dispose(); m.material.dispose(); }
  }
}

for (const dispose of [false, true]) {
  const before = { ...renderer.info.memory };
  for (let i = 0; i < 10; i++) level(dispose);
  const { geometries, textures } = renderer.info.memory;
  console.log(`10 levels ${dispose ? 'with dispose   ' : 'without dispose'}: +${geometries - before.geometries} geometries, +${textures - before.textures} textures left on the GPU`);
}
</script>

Expected output:

text
10 levels without dispose: +500 geometries, +501 textures left on the GPU
10 levels with dispose   : +0 geometries, +0 textures left on the GPU

(The extra texture in the first line is not a leak: the first time a physically based material is drawn, the renderer uploads a small lookup table it keeps for every PBR shader.) Habits:

  • Write a disposeObject(root) helper that traverses and disposes geometries, materials and every texture property of each material (map, normalMap, roughnessMap, … envMap only if you own it).
  • Shared resources (a material used by many meshes, a texture cache) need ownership rules: dispose them when the level, not the mesh, goes away.
  • Also dispose: render targets, PMREMGenerator results, controls (controls.dispose() removes event listeners), loaders with workers (dracoLoader.dispose()), and in Rapier call world.free().
  • Check renderer.info.memory after each level restart in development. If the numbers grow, something leaks.

2. Color spaces: tag color textures, nothing else

The single most common "it looks wrong" bug. Color textures you create or load yourself (TextureLoader, CanvasTexture, video, sprites) need texture.colorSpace = THREE.SRGBColorSpace; data textures (normal, roughness, metalness, AO, height) must stay linear; vertex colors must be linear; GLTFLoader handles its own textures. Leave renderer.outputColorSpace at sRGB. Debug panels and UI that read THREE.Color components directly show linear values. Details in Color Spaces & Tone Mapping.

3. Cap the pixel ratio, and know your pixel count

renderer.setPixelRatio(devicePixelRatio) on a phone with ratio 3 shades 9× the pixels of ratio 1. Use Math.min(devicePixelRatio, 2) as the default, offer a quality setting (1, 1.5, 2), and consider dynamic resolution: if frames take too long, lower the ratio a step; if there's headroom, raise it. Pixel count is usually the first thing that limits phones. See The Render Loop & Resizing.

4. Mobile GPUs hate overdraw

Overdraw is shading the same screen pixel more than once: transparent particles stacked on each other, big semi-transparent planes (fog cards, glass, UI panels in 3D), full-screen post-processing passes. Desktop GPUs shrug it off; mobile GPUs, which are designed around bandwidth limits, slow down dramatically.

  • Prefer alphaTest (cut-out) over transparent where it looks acceptable (foliage, fences).
  • Keep particles small and few; use additive blending with depthWrite: false, and fade them out before they fill the screen.
  • Avoid big transparent quads close to the camera (a smoke effect right in front of the lens can halve the frame rate).
  • Each post-processing pass reads and writes the whole screen. On mobile, use one or two passes, at reduced resolution if possible, or none.
  • Real-time shadows cost an extra render; on mobile use one shadow-casting light with a small map, or baked/blob shadows (Shadows).

5. Don't allocate in the loop

new THREE.Vector3() inside update() creates garbage every frame; the garbage collector eventually pauses the game to clean it up, which shows up as periodic stutter. Create temporary vectors, quaternions and matrices once, at module level, and reuse them:

js
const _tmp = new THREE.Vector3();               // module-level scratch objects
const _q = new THREE.Quaternion();
function update(dt) {
  _tmp.copy(target.position).sub(enemy.position).normalize();   // no allocation
  enemy.position.addScaledVector(_tmp, speed * dt);
}

The same applies to arrays ([...set], .map(), .filter() in hot loops), closures created per frame, and string building for HUDs every frame (update the HUD only when the value changes).

6. Far from the origin, floats run out of precision

GPUs and Three.js matrices use 32-bit floats, which have about 7 significant digits. Near the origin that's sub-micrometre precision; 10 km away, positions snap to about a millimetre, and 100 km away to almost a centimetre, which shows up as jittering characters and cameras:

js · try it yourself
// Spacing between neighbouring 32-bit floats at different distances from the origin.
for (const d of [1, 100, 1000, 10000, 100000, 1000000]) {
  const f = Math.fround(d);
  let next = f;
  for (let step = 1e-9; next === f; step *= 2) next = Math.fround(d + step);   // smallest representable step up
  const gap = next - f;
  console.log(`${String(d).padStart(7)} m from origin: step ${gap < 0.001 ? (gap * 1e6).toFixed(2) + ' µm' : (gap * 1000).toFixed(2) + ' mm'}`);
}
      1 m from origin: step 0.12 µm
    100 m from origin: step 7.63 µm
   1000 m from origin: step 61.04 µm
  10000 m from origin: step 976.56 µm
 100000 m from origin: step 7.81 mm
1000000 m from origin: step 62.50 mm

Keep game worlds within a few kilometres of the origin. Large open worlds use origin shifting: when the player gets far from (0, 0, 0), move the whole world back so the player is near the origin again.

7. Watch the console, pin the version

Three.js warns before it removes things (Clock: This module has been deprecated. Please use THREE.Timer instead., WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead.). Treat every warning as a bug: today's warning is next year's crash. Pin an exact three version, upgrade a few releases at a time, read the migration notes, and keep @types/three in step.

8. The first-frame hitch is shader compilation

A new material type, a new light, or turning shadows on compiles shader programs, freezing the game for tens to hundreds of milliseconds (much longer on some phones). Compile behind the loading screen with renderer.compileAsync(scene, camera), keep the number of lights constant (switch with intensity, not by adding/removing; see Lights), and reuse a small set of materials. renderer.info.programs.length should stop growing after the level has loaded.

9. Clamp dt on both sides

Math.min(dt, 0.1) protects against huge steps after a pause. But THREE.Timer's first update can report a small negative delta (the animation-frame timestamp can be earlier than the moment the timer was created), and a negative dt makes accumulators, tweens and physics misbehave in subtle ways. Use Math.min(Math.max(dt, 0), 0.1), or a fixed-step loop that simply runs no update for a negative frame.

10. Handle a lost WebGL context

On phones and laptops with switchable GPUs, the browser can take the GPU away (app switch, driver reset, too many contexts). The canvas fires webglcontextlost; Three.js restores what it can after webglcontextrestored, but your loop and resources need to survive:

js
renderer.domElement.addEventListener('webglcontextlost', (e) => { e.preventDefault(); pause(); });   // preventDefault allows a restore
renderer.domElement.addEventListener('webglcontextrestored', () => { resume(); });

Browsers also limit the number of live WebGL contexts per page (often 16). Creating a renderer per menu screen or per preview thumbnail eventually kills the oldest one: reuse one renderer.

11. Scale and units decide physics stability

Use 1 unit = 1 metre everywhere: physics engines tune their tolerances for human-sized objects, and glTF uses metres. A character 170 units tall falls in slow motion (gravity is 9.81 units/s²); a 1 cm coin at that scale vibrates through the floor. Fix scale in the asset (Blender export settings), not with mesh.scale in code, because scaled meshes don't scale their colliders.

12. Z-fighting has three fixes

Two surfaces at almost the same depth flicker (decals on walls, roads on terrain, coplanar faces from a modelling mistake). In order of preference: move them apart a little (a few millimetres up for decals), raise the camera's near plane (precision depends on the near/far ratio far more than on far alone), or use material.polygonOffset = true with polygonOffsetFactor: -1 on the decal.

Test yourself

You restart a level ten times and renderer.info.memory.textures grows each time. What is missing?

  1. scene.clear()
  2. Calling dispose() on the removed textures (and geometries and materials)
  3. A smaller pixel ratio
  4. renderer.compileAsync()

Why do large semi-transparent particles slow down phones much more than desktops?

  1. Phones can't blend
  2. Overdraw: every layer re-shades the same pixels, and mobile GPUs are especially bandwidth-limited
  3. Particles disable instancing
  4. Transparency needs WebGPU

A character 50 km from the world origin jitters when standing still. What is the cause and fix?

  1. Physics timestep; use 120 Hz
  2. 32-bit float precision is a few millimetres there; keep the action near the origin (origin shifting)
  3. Z-fighting; raise near
  4. Damping; use exponential smoothing