# three.js

> a scene, a camera and a renderer, then meshes, lights, textures, models, picking and effects.

source: https://learning.anthnydas.com/graphics/three-js/

## tl;dr

a renderer draws a scene through a camera. the scene is a tree of objects, and a mesh in it is a geometry with a material.

- **version:** r186 (three@0.186.1, what this page runs)
- **axes:** y up (a camera looks down its own -z)
- **cleanup:** by hand (dispose() what you made, or the gpu keeps it)
- **draw calls:** 1 (for thousands of copies of a mesh, instanced)
- **reach for it:** 3d on a web page, model and product viewers, data in 3d, small games and effects

three.js is a javascript library for 3d in the browser. you build a scene out of objects, point a camera at it, and a renderer draws it into a canvas, with webgl or webgpu.[^readme] this sheet runs r186, which is three\@0.186.1 on npm. every figure is a live scene: it starts when you scroll to it, draws only when you change something, and frees its gpu memory when you scroll past.

the code blocks build on each other: `canvas`, `renderer`, `scene` and `camera` come from the first one.

## scene, camera, renderer

it takes three things to draw anything: a `Scene` that holds what you draw, a camera that decides what part of it you see, and a renderer that draws the scene, as the camera sees it, into a canvas.[^creating] `WebGLRenderer` draws with webgl 2: three dropped webgl 1 in r163.[^webgl2]

a `PerspectiveCamera` sees the way an eye does: far things look smaller. it takes four numbers. `fov` is the vertical angle it takes in, in degrees. `aspect` is the canvas's width over its height. anything closer than `near` or past `far` isn't drawn. leave them out and you get 50, 1, 0.1 and 2000.[^camera] a camera looks down its own -z axis, and +y is up.[^axes]

```js
import * as THREE from 'three';

const canvas = document.querySelector('canvas');
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
const scene = new THREE.Scene();
// fov, aspect, near, far
const camera = new THREE.PerspectiveCamera(50, 1, 0.1, 100);
camera.position.set(0, 1.5, 5); // up a little, and back along +z
camera.lookAt(0, 0.6, 0);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshNormalMaterial(),
);
cube.position.y = 0.6;
scene.add(cube);

// the canvas's css size sets the picture's size. keep the two in step
new ResizeObserver(() => {
  const { clientWidth: width, clientHeight: height } = canvas;
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  renderer.setSize(width, height, false); // false: leave the css size alone
  camera.aspect = width / height;
  camera.updateProjectionMatrix(); // fov, aspect, near, far apply after this
}).observe(canvas);

renderer.setAnimationLoop((time) => {
  cube.rotation.y = time / 1000; // radians
  renderer.render(scene, camera);
});
```

`setAnimationLoop` calls you once per screen refresh, and pauses while the tab is hidden.[^creating]

> **interactive figure:** a live three.js scene: a cyan box in front, an amber box behind it on the left and a grey box far back on the right, on a grid. two sliders set the camera's field of view, from 10 to 120 degrees, and its distance from the cyan box, from 2 to 12. a readout gives the height and width of the view at the cyan box, 4.66 by 7.46 at the start (a 50 degree fov from 5 away), and the camera's near and far planes, 0.1 and 100.

what trips people up:

- a change to `fov`, `aspect`, `near` or `far` shows only after `camera.updateProjectionMatrix()`.[^camera]
- flicker where two surfaces nearly touch, called z-fighting: the depth buffer's precision is spread from `near` to `far`, finest close to the camera. set `near` as far out, and `far` as close in, as the scene allows.[^cameras]
- a soft picture on a phone: the drawing buffer is in css pixels unless you scale it by `devicePixelRatio`. that costs: a 3× screen draws 9 times the pixels. the figures here cap the ratio at 2.[^responsive]

## geometry, material, mesh

a `Mesh` is a geometry and a material. the geometry is the shape: vertex positions, normals and uvs, kept in typed arrays on a `BufferGeometry`. the built-in ones, like `BoxGeometry` and `SphereGeometry`, fill those in for you. the material is how the surface looks, and how it takes light.[^creating][^update]

the mesh materials, fastest first: `MeshBasicMaterial` ignores lights. `MeshLambertMaterial` takes light, with no shine. `MeshPhongMaterial` adds a highlight. `MeshStandardMaterial` is physically based, set by `roughness` and `metalness`, which start at 1 and 0: fully rough, not metal. `MeshPhysicalMaterial` adds clearcoat, sheen, glass-like transmission and more, at more cost per pixel. `MeshNormalMaterial` colors each point by the way its surface faces.[^materials][^material-docs]

```js
// radius, then segments around and from top to bottom
const geometry = new THREE.SphereGeometry(1, 32, 16);
const material = new THREE.MeshStandardMaterial({
  color: 0x22d3ee,
  roughness: 0.4,
});
const ball = new THREE.Mesh(geometry, material);
ball.position.set(-1.5, 1, 0);
ball.rotation.y = Math.PI / 4; // rotations are in radians
ball.scale.setScalar(0.5);
scene.add(ball);

// meshes can share a geometry and a material
const twin = new THREE.Mesh(geometry, material);
twin.position.set(1.5, 1, 0);
scene.add(twin);
```

> **interactive figure:** a live three.js scene with one cyan mesh over a grid. one menu picks its geometry: a box, a 32 by 16 sphere, a cone, a torus knot or a plane. another picks its material: standard, lambert, basic, normal or wireframe. a readout counts the geometry's vertices and triangles, 24 and 12 for the box and 561 and 960 for the sphere, and says whether the material uses the scene's lights. a line under it says what the material does.

what trips people up:

- a black mesh: lambert, phong, standard and physical need a light. standard and physical look their best with an environment map too, set on `scene.environment` or the material's `envMap`.[^material-docs]
- a plane that vanishes when you look at it from behind: a material draws front faces only. `side: THREE.DoubleSide` draws both.[^materials]

## lights and shadows

lights reach the lit materials only. `AmbientLight` lights everything evenly, from no direction. `HemisphereLight` fades from a sky color above to a ground color below. `DirectionalLight` is the sun: parallel rays, aimed from its position at its target. `PointLight` is a bulb, `SpotLight` a cone, and `RectAreaLight` a glowing rectangle that works with standard and physical materials only and casts no shadow.[^lights] point and spot lights fade with the square of the distance (`decay` is 2), and their intensity is in candela.[^point]

shadows take four switches: the renderer's shadow map, the light, and each mesh that casts or receives one. for every light that casts shadows, three draws the shadow casters again from the light's point of view, into a depth texture called the shadow map, then checks each pixel of the real frame against it. a point light takes six of those passes, one per direction. only directional, point and spot lights cast shadows.[^shadows]

```js
renderer.shadowMap.enabled = true; // off by default
renderer.shadowMap.type = THREE.PCFShadowMap; // the default: filtered edges

const floor = new THREE.Mesh(
  new THREE.PlaneGeometry(10, 10),
  new THREE.MeshStandardMaterial(),
);
floor.rotation.x = -Math.PI / 2; // a plane starts upright, facing +z
floor.receiveShadow = true;
scene.add(floor);
ball.castShadow = true;

const sun = new THREE.DirectionalLight(0xffffff, 2.5);
sun.position.set(3, 5, 4); // it shines from here toward sun.target, at the origin
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024); // 512 × 512 by default
// the shadow box starts -5 to 5 across, 0.5 to 500 deep. fit it to the scene
const box = sun.shadow.camera;
box.left = box.bottom = -4;
box.right = box.top = 4;
box.far = 20;
sun.shadow.bias = -0.0005; // moves the depth test a little, against shadow acne
scene.add(sun, new THREE.AmbientLight(0xffffff, 0.3));
scene.add(new THREE.CameraHelper(box)); // draws the box, to see what it covers
```

the other types are `BasicShadowMap`, unfiltered, and `VSMShadowMap`. `PCFSoftShadowMap` is deprecated in r186: three warns and uses `PCFShadowMap`.[^shadowmap] `shadow.radius` above 1 softens the edges of pcf and vsm shadows, and does nothing to basic ones.[^lightshadow]

> **interactive figure:** a live three.js scene: a cyan box, an amber ball and a grey ring on a dark floor, lit by one directional light that casts shadows. a helper draws the light as a small amber square with a line to its target, the middle of the floor. a slider sets the sun's height, from 8 to 85 degrees above the floor. a menu sets the renderer's shadow map type: off, basic, pcf (the default) or vsm. a readout lists the shadow map's size, 512 by 512, and the shadow camera's box, 10 by 10 and 0.5 to 500 deep, which are three's defaults, and the figure's own radius, 4, and bias, -0.0005.

what trips people up:

- no shadow: one of the four switches is off. turning shadows on or off after the first frame also needs `material.needsUpdate = true`, since a shadow map changes the shader.[^update]
- a shadow cut off at an edge: it fell outside the shadow camera's box. a bigger box spreads the same map over more ground, and the shadow turns blocky. a `CameraHelper` on `sun.shadow.camera` draws the box.[^shadows]
- stripes or speckles on lit faces, called shadow acne: nudge `shadow.bias` by around 0.0001, or raise `shadow.normalBias`.[^lightshadow]
- a directional light that won't turn: it aims at `sun.target`. move the target, and add it to the scene, or it stays put.[^directional]

## textures and uv

a texture is an image the gpu samples while it draws. each vertex carries a uv coordinate that says where in the image it lands: u runs left to right and v bottom to top, both 0 to 1 across the image. the built-in geometries come with uvs.[^textures]

`TextureLoader` loads an image. a `CanvasTexture` reads a canvas you draw on, and a `DataTexture` takes raw numbers. an image of colors holds srgb values, so mark it: `colorSpace = THREE.SRGBColorSpace`. textures that hold data, like normal and roughness maps, keep the default, `NoColorSpace`.[^color]

```js
// returns at once. the image fills in when it arrives
const bricks = new THREE.TextureLoader().load('/textures/bricks.jpg');
bricks.colorSpace = THREE.SRGBColorSpace; // an image of colors
bricks.wrapS = bricks.wrapT = THREE.RepeatWrapping; // the default clamps
bricks.repeat.set(4, 4); // uv runs 0 to 4: four copies each way
bricks.anisotropy = renderer.capabilities.getMaxAnisotropy(); // sharper at a slant
floor.material.map = bricks;
floor.material.needsUpdate = true; // a new map changes the shader

// any canvas can be a texture
const paper = document.createElement('canvas');
paper.width = paper.height = 256;
const ctx = paper.getContext('2d');
ctx.fillStyle = '#22d3ee';
ctx.fillRect(0, 0, 128, 128);
const drawn = new THREE.CanvasTexture(paper);
drawn.colorSpace = THREE.SRGBColorSpace;
// after drawing on the canvas again:
drawn.needsUpdate = true;
```

> **interactive figure:** a live three.js scene: a texture drawn on a 256 pixel canvas, a dark checkerboard with a cyan u axis along the bottom, an amber v axis up the left and the corners labelled 0,0 to 1,1, mapped onto a tilted square. the canvas itself shows in the corner. a slider sets repeat from 1 to 4 and a menu sets the wrap mode: clamp to edge (the default), repeat or mirrored repeat. at repeat 1 the image shows once, with uv 0,0 at its bottom-left. past 1, clamp smears the edge pixels, repeat starts the image over, and mirrored repeat flips every other copy.

what trips people up:

- washed-out colors: a color texture left at `NoColorSpace` is read as linear, so it comes out too light.[^color]
- `repeat` with no tiling: past 1 it needs `RepeatWrapping` or `MirroredRepeatWrapping`. a wrap mode changed after the first draw also needs `texture.needsUpdate = true`, since it's set on the gpu when the image uploads. `repeat` and `offset` don't: they reach the shader on every draw.[^texture]
- gpu memory is the pixels, not the file: about width × height × 4 bytes, and a third more for the mipmaps. a 2048 × 2048 jpeg takes about 22 mb on the gpu, however small the file is.[^textures]

## orbit controls

`OrbitControls` moves a camera around a target point as you drag. it's an addon, so it comes from `three/addons/`, not `three`.[^install] one finger or the left button orbits, the wheel or a pinch zooms, and the right button, two fingers or the arrow keys pan. the camera's up stays up.[^orbit]

it moves the camera and nothing else: something still has to draw. a loop works, or a render on each `change` event, so nothing runs while the view sits still.[^demand]

```js
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0.6, 0); // the point it circles, the origin by default
controls.minDistance = 2;
controls.maxDistance = 12;
controls.maxPolarAngle = Math.PI / 2; // no lower than level: above the floor
controls.listenToKeyEvents(window); // arrow keys pan
controls.update(); // after any change made in code

// draw on demand: no loop, a frame when the view changes
renderer.setAnimationLoop(null);
controls.addEventListener('change', () => renderer.render(scene, camera));
renderer.render(scene, camera);
```

damping lets the view coast after you let go, so `update()` has to run every frame:

```js
controls.enableDamping = true; // dampingFactor is 0.05
renderer.setAnimationLoop(() => {
  controls.update();
  renderer.render(scene, camera);
});
```

> **interactive figure:** a live three.js scene: the site's own small gltf house, with grey walls, an amber roof and a cyan door, on a grid, loaded with GLTFLoader. drag to orbit it, click it and scroll or pinch to zoom, use the arrow keys to pan, and shift with the arrows to orbit. a damping button lets the view coast after you let go, and is off under reduced motion. reset view goes back to the start. a readout gives where the camera sits around the house: 5.5 away, 32 degrees around and 62 degrees down from straight above, at the start. a line under it gives the file's size and what it loaded as.

what trips people up:

- damping on, but no `update()` every frame: the view lags behind the drag and stops short when you let go. `autoRotate` needs the loop too.[^orbit]
- `camera.lookAt` while the controls are on: the next `update()` points the camera back at `controls.target`. move the target instead.[^orbit]
- on a phone the canvas takes every swipe: OrbitControls sets `touch-action: none` on it, so the page won't scroll over it. leave room around it to scroll by.[^orbit]
- the wheel zooms instead of scrolling the page, since the controls stop its scroll. this figure turns zoom on only after a click.[^orbit]

## gltf loading

gltf is the khronos group's format for 3d scenes, made for loading at runtime. a `.gltf` file is json, with the binary data in `.bin` files beside it or inside the json as base64 data uris, which take about a third more bytes. a `.glb` packs the json and the binary data into one file: a 12-byte header, a json chunk and a binary chunk.[^gltf-spec] three's manual recommends gltf over the other formats.[^models]

the json is a tree of indices. a scene lists nodes, a node holds a transform and a mesh, a mesh is a list of primitives, and a primitive points at accessors for its positions, normals and indices. an accessor reads typed numbers out of a buffer view, a slice of a buffer. lengths are in meters, +y is up, and the front of a model faces +z. materials are pbr metallic-roughness.[^gltf-spec] `GLTFLoader` makes them `MeshStandardMaterial`, or `MeshPhysicalMaterial` when an extension adds clearcoat, transmission and the like.[^gltfloader]

```js
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const gltf = await new GLTFLoader().loadAsync('/models/house.glb');
scene.add(gltf.scene); // a Group: the file's nodes, meshes and materials

gltf.scene.traverse((object) => {
  if (object.isMesh) object.castShadow = true; // meshes cast no shadow until asked
});
// gltf.animations holds the clips for an AnimationMixer, gltf.cameras the cameras
```

the house in the orbit figure is the site's own. `site/scripts/make-house.mjs` writes it from a tested module: three primitives (walls, roof and door), 30 vertices and 16 triangles in one 816-byte buffer, no textures. `house.glb` is 2,668 bytes. the same model as readable json, with the buffer as a data uri, is [house.gltf](/models/house.gltf), 4,569 bytes.

what trips people up:

- a model you can't see: it may be far too big (with the camera inside it) or too small, or sitting in the dark. the manual's first checks: an `onError` callback to see the error, a light, and a scale up or down by 1000.[^models]
- a model that loads but looks black: its materials are pbr, so they need light, and look best with an environment map.[^material-docs]
- images packed inside a `.glb` load through `blob:` urls, and a content security policy has to list `blob:` to allow them: `'self'` never matches one.[^gltfloader][^csp] this site's policy doesn't, so the house has no textures.

## raycasting

a `Raycaster` sends a ray from the camera through a point on the screen and lists what it hits, nearest first. the point goes in normalized device coordinates: -1 to 1 across the canvas on both axes, with y up, the other way from the page's y. each hit has the `object`, its `distance` from the camera, the `point` in world space, the `face` and its `uv`, and an `instanceId` for an `InstancedMesh`.[^raycaster]

```js
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();

canvas.addEventListener('pointerdown', (event) => {
  const rect = canvas.getBoundingClientRect(); // the canvas, not the window
  pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
  pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1; // y flips
  raycaster.setFromCamera(pointer, camera);
  const [hit] = raycaster.intersectObjects([ball, twin, floor]); // nearest first
  if (hit) console.log(hit.object, hit.distance, hit.point);
});
```

> **interactive figure:** a live three.js scene: nine grey cubes in a three by three grid, seen from above and in front. tap or click the scene, or focus it, move the crosshair with the arrow keys and press enter, and a ray goes from the camera through that point. the first cube it hits turns amber. a readout gives the point in normalized device coordinates, the cube's name, the distance from the camera to the hit and the point it hit.

what trips people up:

- the cost: past a bounding sphere test, the ray checks every triangle of every mesh you pass, on the cpu. pass only what can be picked, and `false` as the second argument when the children don't matter.[^raycaster][^mesh]
- hidden objects still get hit: the raycaster checks `layers`, not `visible`.[^raycaster]
- a face seen from behind isn't hit. `side: THREE.DoubleSide` on the material catches both sides.[^raycaster]

## instancing

every mesh is at least one draw call, a request from the cpu to the gpu, and each one costs something however small the mesh.[^lots] an `InstancedMesh` draws many copies of one geometry with one material in one call. each copy gets its own matrix, and its own color if you set one.[^instanced] a `BatchedMesh` does the same for different geometries that share a material.[^batched]

```js
const count = 1000;
const boxes = new THREE.InstancedMesh(
  new THREE.BoxGeometry(0.1, 0.1, 0.1),
  new THREE.MeshStandardMaterial(),
  count,
);
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
for (let i = 0; i < count; i++) {
  const [col, row] = [i % 32, Math.floor(i / 32)]; // a 32-wide grid
  matrix.makeTranslation(col * 0.2 - 3.1, 0.05, row * 0.2 - 3.1);
  boxes.setMatrixAt(i, matrix);
  boxes.setColorAt(i, color.setHSL(i / count, 0.7, 0.6));
}
scene.add(boxes); // a thousand boxes, one draw call

// moving one later
boxes.setMatrixAt(7, matrix.makeTranslation(0, 1, 0));
boxes.instanceMatrix.needsUpdate = true;
boxes.computeBoundingSphere(); // culling and raycasting read it
```

> **interactive figure:** a live three.js scene: small boxes in a sunflower spiral on a grid, colored from cyan in the middle to blue at the edge. a slider sets how many, from 100 to 10,000, and the camera backs away as the spiral grows. a menu draws them as one InstancedMesh or as one Mesh each, which stops at 3,000. a readout counts the boxes, the draw calls and the triangles the renderer reports, and times one render() call. instanced, every count is 2 draw calls: the boxes and the grid. as separate meshes it is one call per box, plus the grid.

what trips people up:

- instances that don't move: after `setMatrixAt` or `setColorAt` on a mesh that has been drawn, set `instanceMatrix.needsUpdate` or `instanceColor.needsUpdate` to `true`.[^instanced]
- instances that vanish near the edge of the view: culling uses the mesh's bounding sphere, worked out once, from the matrices it had on its first frame. call `computeBoundingSphere()` after moving them.[^update][^frustum]

## post-processing

post-processing draws the scene into a render target, an image on the gpu, then runs passes over that image, and the last one draws to the screen. `EffectComposer` holds the chain: a `RenderPass` first to draw the scene, then the effects, then `OutputPass`, which applies tone mapping and converts to srgb. passes run in the order you add them.[^post]

```js
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';

renderer.toneMapping = THREE.ACESFilmicToneMapping; // bloom needs tone mapping on
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const size = renderer.getSize(new THREE.Vector2());
// strength, radius, threshold
composer.addPass(new UnrealBloomPass(size, 0.8, 0.2, 0.8));
composer.addPass(new OutputPass()); // tone mapping and srgb, last

// composer.render, not renderer.render
renderer.setAnimationLoop(() => composer.render());
// on resize, after the renderer's own setSize: composer.setSize(width, height)
```

> **interactive figure:** a live three.js scene: a cyan torus knot lit by one light, and two balls that glow, amber and white, on a grid, drawn through an EffectComposer. a menu picks the effect: bloom, pixelate or none. bloom has a strength slider from 0 to 3, and pixelate a pixel size slider from 1 to 16. a line under it lists the passes in order, like RenderPass, UnrealBloomPass, OutputPass. the balls are brighter than the bloom threshold and glow, and the lit knot isn't and doesn't.

what trips people up:

- everything darker or lighter once the composer is in: `OutputPass` is missing, or something converts to srgb twice. the composer's targets hold linear color in half floats, and the canvas wants srgb.[^color][^composer]
- `renderer.render` in the loop: it draws the scene straight to the screen and skips the passes. call `composer.render()`.[^post]
- a blurry or stretched result after a resize: the composer keeps its own targets, so it needs its own `setSize`.[^composer]

## pitfalls

- **nothing frees itself.** removing a mesh from the scene leaves its geometry, material and textures on the gpu. call `dispose()` on each when you're done with it, and on render targets, controls and passes. `renderer.info.memory` counts what's still held.[^dispose]
- **too many canvases.** chrome keeps 16 webgl contexts alive at once, 8 on android, and when a page makes one more, the oldest is lost.[^chromium] a page with many scenes can start each one near the viewport and drop it after, the way this one does: `renderer.dispose()`, then `renderer.forceContextLoss()` to hand the context back right away.[^lose]
- **colors that look off.** three works in linear srgb and converts hex and css colors into it for you. textures and the output are yours to mark: `colorSpace` on color textures, `renderer.outputColorSpace` for the canvas (srgb by default), and `OutputPass` with a composer.[^color][^webgl2]
- **a loop that never stops.** `setAnimationLoop` draws every frame, even when nothing moves. a scene that mostly sits still can draw on change instead, like the orbit controls code above, and spare the battery.[^demand]

[^readme]: the [three.js readme](https://github.com/mrdoob/three.js/blob/r186/README.md) at r186: a general-purpose 3d library whose builds include a webgl and a webgpu renderer, with svg and css3d renderers as addons. the [package.json](https://github.com/mrdoob/three.js/blob/r186/package.json#L3) at the same tag is version 0.186.1.

[^creating]: [creating a scene](https://threejs.org/manual/#en/creating-a-scene) in the three.js manual: the scene, the camera and the renderer, a mesh as a geometry with a material applied, and an animation loop that draws on every screen refresh and pauses when you switch tabs.

[^webgl2]: [WebGLRenderer.js](https://github.com/mrdoob/three.js/blob/r186/src/renderers/WebGLRenderer.js#L58-L61) at r186: it draws with webgl 2, and webgl 1 isn't supported since r163 (the error at [line 102](https://github.com/mrdoob/three.js/blob/r186/src/renderers/WebGLRenderer.js#L102)). `outputColorSpace` starts as srgb at [line 312](https://github.com/mrdoob/three.js/blob/r186/src/renderers/WebGLRenderer.js#L312).

[^camera]: [PerspectiveCamera.js](https://github.com/mrdoob/three.js/blob/r186/src/cameras/PerspectiveCamera.js#L25-L33) at r186: the defaults, fov 50, aspect 1, near 0.1 and far 2000, the [vertical fov in degrees](https://github.com/mrdoob/three.js/blob/r186/src/cameras/PerspectiveCamera.js#L48-L55), and [`updateProjectionMatrix()`](https://github.com/mrdoob/three.js/blob/r186/src/cameras/PerspectiveCamera.js#L349-L353), which must be called after any change to the camera's settings. the 4.66 and 7.46 in the figure are checked in `site/src/visuals/three/camera.test.ts`.

[^axes]: [Camera.js](https://github.com/mrdoob/three.js/blob/r186/src/cameras/Camera.js#L97-L101) at r186: a camera looks down its local negative z axis. [Object3D.js](https://github.com/mrdoob/three.js/blob/r186/src/core/Object3D.js#L1679-L1687): the default up for objects is (0, 1, 0).

[^cameras]: [cameras](https://threejs.org/manual/#en/cameras) in the three.js manual: the gpu's depth precision is spread between near and far, fine near the camera and coarse far away, z fighting when there isn't enough, and choosing near and far to fit the scene.

[^responsive]: [responsive design](https://threejs.org/manual/#en/responsive) in the three.js manual, on hd-dpi displays: css pixels, a 3× phone drawing 9 times the pixels, and scaling the drawing buffer by `devicePixelRatio`.

[^update]: [how to update things](https://threejs.org/manual/#en/how-to-update-things) in the three.js manual: geometry data lives in typed arrays; after the first render, a material needs `needsUpdate = true` when a texture or a shadow map appears or goes; textures need `needsUpdate` when their image changes; a camera needs `updateProjectionMatrix()` after fov, aspect, near or far change; and an `InstancedMesh` needs its bounding box and sphere computed again after `setMatrixAt()`.

[^materials]: [materials](https://threejs.org/manual/#en/materials) in the three.js manual: the mesh materials from fastest to slowest (basic, lambert, phong, standard, physical), basic not affected by lights, and `side` defaulting to `THREE.FrontSide`.

[^material-docs]: the class notes at r186: [MeshLambertMaterial](https://github.com/mrdoob/three.js/blob/r186/src/materials/MeshLambertMaterial.js#L7-L23) is for non-shiny surfaces, without specular highlights. [MeshPhongMaterial](https://github.com/mrdoob/three.js/blob/r186/src/materials/MeshPhongMaterial.js#L7-L21) adds them. [MeshStandardMaterial](https://github.com/mrdoob/three.js/blob/r186/src/materials/MeshStandardMaterial.js#L7-L40) is physically based and does best with an environment map, and its [roughness and metalness](https://github.com/mrdoob/three.js/blob/r186/src/materials/MeshStandardMaterial.js#L77-L96) start at 1 and 0. [MeshPhysicalMaterial](https://github.com/mrdoob/three.js/blob/r186/src/materials/MeshPhysicalMaterial.js#L6-L33) adds clearcoat, sheen, transmission and more, costs more per pixel, and also wants an environment map. [MeshNormalMaterial](https://github.com/mrdoob/three.js/blob/r186/src/materials/MeshNormalMaterial.js#L5-L10) maps normals to rgb colors.

[^lights]: [lights](https://threejs.org/manual/#en/lights) in the three.js manual, and the class notes at r186: [AmbientLight](https://github.com/mrdoob/three.js/blob/r186/src/lights/AmbientLight.js#L3-L14), [HemisphereLight](https://github.com/mrdoob/three.js/blob/r186/src/lights/HemisphereLight.js#L5-L17), [DirectionalLight](https://github.com/mrdoob/three.js/blob/r186/src/lights/DirectionalLight.js#L5-L31), [SpotLight](https://github.com/mrdoob/three.js/blob/r186/src/lights/SpotLight.js#L5-L26) and [RectAreaLight](https://github.com/mrdoob/three.js/blob/r186/src/lights/RectAreaLight.js#L3-L27): no shadows and pbr materials only.

[^point]: [PointLight.js](https://github.com/mrdoob/three.js/blob/r186/src/lights/PointLight.js#L21-L63) at r186: intensity in candela, a `distance` of 0 for no limit, and a `decay` of 2, inverse-square, which physically correct rendering should leave alone. [SpotLight.js](https://github.com/mrdoob/three.js/blob/r186/src/lights/SpotLight.js#L32-L39) takes the same, plus a cone `angle` of π/3 and a `penumbra` of 0.

[^shadows]: [shadows](https://threejs.org/manual/#en/shadows) in the three.js manual: every light that casts shadows draws the casters from its own point of view, a point light six times; the three lights that can cast shadows; the renderer, light and mesh switches; `CameraHelper` on the shadow camera; and why a larger shadow area makes blockier shadows.

[^shadowmap]: [WebGLShadowMap.js](https://github.com/mrdoob/three.js/blob/r186/src/renderers/webgl/WebGLShadowMap.js#L84-L104) at r186: shadow maps start off, the type starts at `PCFShadowMap`, and `PCFSoftShadowMap` logs a warning and falls back to it. [constants.js](https://github.com/mrdoob/three.js/blob/r186/src/constants.js#L51-L84) marks `PCFSoftShadowMap` deprecated since r186.

[^lightshadow]: [LightShadow.js](https://github.com/mrdoob/three.js/blob/r186/src/lights/LightShadow.js#L43-L104) at r186: `bias` starts at 0 and adjustments around 0.0001 may reduce artifacts; `normalBias` reduces shadow acne, at the cost of some distortion; `radius` above 1 blurs shadow edges and has no effect with `BasicShadowMap`; `mapSize` is 512 by 512. [DirectionalLightShadow.js](https://github.com/mrdoob/three.js/blob/r186/src/lights/DirectionalLightShadow.js#L16) makes its camera an orthographic box from -5 to 5, 0.5 to 500 deep. these defaults are checked in `site/src/visuals/three/lights.test.ts`.

[^directional]: [DirectionalLight.js](https://github.com/mrdoob/three.js/blob/r186/src/lights/DirectionalLight.js#L12-L70) at r186: the light points from its position to its target, rotating it does nothing, and the target has to be in the scene for a new position to count.

[^textures]: [textures](https://threejs.org/manual/#en/textures) in the three.js manual: loading, memory use of about width × height × 4 × 1.33 bytes, mipmaps and filtering, and repeating, offsetting and wrapping. the 22 mb is computed in `site/src/visuals/three/uv-grid.ts` and checked in its test.

[^color]: [color management](https://threejs.org/manual/#en/color-management) in the three.js manual: the linear srgb working color space, `ColorManagement` on by default and converting hex and css colors, color textures marked `SRGBColorSpace`, data textures left at `NoColorSpace`, the output color space and `OutputPass`, and what goes wrong when one is set wrong.

[^texture]: [Texture.js](https://github.com/mrdoob/three.js/blob/r186/src/textures/Texture.js#L120-L136) at r186: `wrapS` and `wrapT`, and [`repeat`](https://github.com/mrdoob/three.js/blob/r186/src/textures/Texture.js#L201-L210), which needs a repeating wrap mode past 1. [WebGLTextures.js](https://github.com/mrdoob/three.js/blob/r186/src/renderers/webgl/WebGLTextures.js#L900-L942) sets the wrap mode only while it uploads the texture, which happens when its version changes, and [WebGLMaterials.js](https://github.com/mrdoob/three.js/blob/r186/src/renderers/webgl/WebGLMaterials.js#L13-L23) copies repeat and offset into the shader on every draw.

[^install]: [installation](https://threejs.org/manual/#en/installation) in the three.js manual: the addons (controls, loaders, post-processing) are imported from `three/addons/`, which the [package.json](https://github.com/mrdoob/three.js/blob/r186/package.json#L15-L16) maps to `examples/jsm/`.

[^orbit]: [OrbitControls.js](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/controls/OrbitControls.js#L58-L87) at r186: the mouse, touch and key gestures, up staying up, `update()` after any change to the camera made in code, and every frame with damping or autorotate on. `dampingFactor` is [0.05](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/controls/OrbitControls.js#L219). `update()` [points the camera at the target](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/controls/OrbitControls.js#L797), connecting the controls [sets `touch-action: none`](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/controls/OrbitControls.js#L508) on the canvas, and the [wheel handler](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/controls/OrbitControls.js#L1776-L1788) calls `preventDefault()` while zoom is on.

[^demand]: [rendering on demand](https://threejs.org/manual/#en/rendering-on-demand) in the three.js manual: why a scene that doesn't animate shouldn't draw continuously, a render on the controls' `change` event, and the extra care damping needs.

[^gltf-spec]: the [gltf 2.0 specification](https://github.com/KhronosGroup/glTF/blob/1c84b58ba3338be4731ea546fa4138dcbb93d42d/specification/2.0/Specification.adoc), at the khronos repo's commit 1c84b58: what a `.gltf`, its `.bin` files and a glb hold (lines 417 to 426); base64 data urls a third longer than the bytes (line 558); the right-handed axes, +y up with the front facing +z, and lengths in meters (lines 755 to 764); scenes and nodes (from line 778), buffers, buffer views and accessors (from 993), meshes and their primitives (from 1590) and metallic-roughness materials (from 2618); and the glb container, a 12-byte header, then a json chunk and a binary chunk, each padded to 4 bytes (lines 3375 to 3480).

[^models]: [loading 3d models](https://threejs.org/manual/#en/loading-3d-models) in the three.js manual: gltf as the recommended format, `GLTFLoader` from the addons, and the troubleshooting list: log errors with `onError`, try a scale 1000 times up or down, and add a light.

[^gltfloader]: [GLTFLoader.js](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/loaders/GLTFLoader.js#L3583-L3587) at r186 makes its materials `MeshStandardMaterial`, and a [material extension](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/loaders/GLTFLoader.js#L898-L904) like clearcoat switches one to `MeshPhysicalMaterial`. it [loads an image stored in a buffer view](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/loaders/GLTFLoader.js#L3360-L3371) through a blob url from `URL.createObjectURL`.

[^csp]: the [content security policy level 3](https://www.w3.org/TR/2026/WD-CSP3-20261027/#match-url-to-source-expression) working draft of 27 october 2026, section 6.7.2.8: a url with the `blob` scheme never matches `'self'`.

[^raycaster]: [Raycaster.js](https://github.com/mrdoob/three.js/blob/r186/src/core/Raycaster.js#L113-L265) at r186: `setFromCamera` takes the point in normalized device coordinates, -1 to 1; the fields of a hit, `instanceId` included; hits sorted nearest first; faces hit only from the front unless the material is `DoubleSide`; children checked unless `recursive` is false; and the walk tests each object's `layers`, with no check of `visible`.

[^mesh]: `raycast()` in [Mesh.js](https://github.com/mrdoob/three.js/blob/r186/src/objects/Mesh.js#L238-L282) at r186: a bounding sphere test, a bounding box test, then the geometry's triangles.

[^lots]: [optimize lots of objects](https://threejs.org/manual/#en/optimize-lots-of-objects) in the three.js manual: every mesh is one or more requests to draw, and drawing two things has more overhead than drawing one.

[^instanced]: [InstancedMesh.js](https://github.com/mrdoob/three.js/blob/r186/src/objects/InstancedMesh.js#L19-L67) at r186: one geometry and material with many transforms, to cut draw calls; and `instanceMatrix` and `instanceColor` need `needsUpdate` after [`setMatrixAt` and `setColorAt`](https://github.com/mrdoob/three.js/blob/r186/src/objects/InstancedMesh.js#L310-L344).

[^batched]: [BatchedMesh.js](https://github.com/mrdoob/three.js/blob/r186/src/objects/BatchedMesh.js#L146-L151) at r186: many objects with one material but different geometries, drawn with multi-draw to cut draw calls.

[^frustum]: `intersectsObject()` in [Frustum.js](https://github.com/mrdoob/three.js/blob/r186/src/math/Frustum.js#L146-L166) at r186 computes an object's bounding sphere only when it has none yet, then tests that sphere.

[^post]: [how to use post processing](https://threejs.org/manual/#en/how-to-use-post-processing) in the three.js manual: render to a render target, passes in the order they're added, `composer.render()` in place of `renderer.render()`, the last enabled pass drawn to the screen, `RenderPass` first and `OutputPass` last for the srgb conversion and tone mapping.

[^composer]: [EffectComposer.js](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/postprocessing/EffectComposer.js#L61-L69) at r186 makes its two targets at the canvas size times the pixel ratio, in half floats, and [`setSize()`](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/postprocessing/EffectComposer.js#L310-L333) resizes them and every pass. [OutputPass.js](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/postprocessing/OutputPass.js#L17-L32) adds tone mapping and the color space conversion, and [UnrealBloomPass.js](https://github.com/mrdoob/three.js/blob/r186/examples/jsm/postprocessing/UnrealBloomPass.js#L16-L46) needs tone mapping on and takes strength, radius and threshold.

[^dispose]: [how to dispose of objects](https://threejs.org/manual/#en/how-to-dispose-of-objects) in the three.js manual: geometries, materials, textures and render targets keep their gpu side until `dispose()`, removing a mesh doesn't dispose of anything, controls and passes have `dispose()` too, and `renderer.info` counts what's held.

[^chromium]: chromium at commit 509a17e: [webgraphicscontext3d_provider_impl.cc](https://chromium.googlesource.com/chromium/src/+/509a17e6fd5cbac2e226e597f1a551f3b8ed2990/content/renderer/webgraphicscontext3d_provider_impl.cc), lines 121 to 127, sets the limit to 16 active webgl contexts, 8 on android, and [webgl_rendering_context_base.cc](https://chromium.googlesource.com/chromium/src/+/509a17e6fd5cbac2e226e597f1a551f3b8ed2990/third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.cc), lines 499 to 513, loses the oldest one with a warning when a new one would pass it.

[^lose]: [webgl best practices](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/WebGL_best_practices#lose_contexts_eagerly) on mdn: lose contexts eagerly with `WEBGL_lose_context` once you're done with them. three's [`forceContextLoss()`](https://github.com/mrdoob/three.js/blob/r186/src/renderers/WebGLRenderer.js#L604-L612) at r186 calls that extension.

## related

- https://learning.anthnydas.com/graphics/cg-fundamentals.md
- https://learning.anthnydas.com/graphics/webgl-glsl.md
