Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Make nine docs pages interactive learn pages (part of #508)

Nguyen Xuan An9085607f6b07
diff --git a/changes/docs-interactive-build-model.md b/changes/docs-interactive-build-model.md
new file mode 100644
index 00000000..e1f817be
--- /dev/null
+++ b/changes/docs-interactive-build-model.md
@@ -0,0 +1 @@
+- Rewrite nine documentation pages as interactive learn pages (part of #508): parts and geometry, procedural modeling, sculpt brushes, contact detection, shrinkwrap and surface patches, retained surface attachments, local lights and volume fog, HDR environment lighting, and the renderer reference. Each page has live examples with a drag or slider control, logged output (counts, timings, query results), an options table taken from the code, and a list of common mistakes. Every fact of the old guide sections moved into the page with the same id.
diff --git a/docs/learn/contact-detection.md b/docs/learn/contact-detection.md
new file mode 100644
index 00000000..98a7130d
--- /dev/null
+++ b/docs/learn/contact-detection.md
@@ -0,0 +1,228 @@
+# Contact detection
+
+Version `0.4.0` provides static BVH queries through `67js/addons/mesh-query`. `createMeshQueryIndex` copies positions and indices. `createMeshPairQuery` tests two indices under explicit affine matrices. The `surfaces` mode finds triangle contact. The `closed-solids` mode also tests containment between two validated solid indices.
+
+The workflow has five steps:
+
+1. Build one index per static geometry with explicit count and memory budgets.
+2. For containment, create both indices with `solid: true`.
+3. Create a pair query with the required mode.
+4. Evaluate the query with both current world matrices.
+5. Dispose the indices when their geometry is no longer needed.
+
+Rebuild indices after geometry edits. Queries reject skin and morph channels. Contact results do not measure penetration depth or resolve collisions.
+
+## Two solids: apart, touching, inside
+
+The small sphere moves along X through the big one. Every move evaluates the pair query with both current matrices, and the sphere turns red while the surfaces touch. The log prints one line each time the answer changes.
+
+```js live poster=contact-solids
+import { Renderer67, sphere } from '67js';
+import { createMeshQueryIndex, createMeshPairQuery } from '67js/addons/mesh-query';
+
+function placeAt(x, size) {
+ return new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, 0, 0, 1]);
+}
+
+const geometry = sphere(32, 20);
+const big = { name: 'Big', geometry, matrix: placeAt(0, 1), material: { color: [0.3, 0.5, 0.8], metallic: 0, roughness: 0.5 } };
+const small = { name: 'Small', geometry, matrix: placeAt(-3, 0.45), material: { color: [0.95, 0.75, 0.2], metallic: 0, roughness: 0.4 } };
+
+// Both indices are solids, so the pair query can tell "inside" from "apart".
+const started = performance.now();
+const bigIndex = createMeshQueryIndex(geometry, { solid: true });
+const smallIndex = createMeshQueryIndex(geometry, { solid: true });
+console.log(`two solid indices: ${(performance.now() - started).toFixed(0)} ms, ${bigIndex.info.vertexCount} vertices and ${bigIndex.info.triangleCount} triangles each, ${(bigIndex.info.estimatedBytes / 1024).toFixed(0)} KiB`);
+const query = createMeshPairQuery(bigIndex, smallIndex, { mode: 'closed-solids' });
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, [big, small], { ground: false, samples: 4, pixelRatio: 1.25 });
+let lastKind = '';
+
+function update(x) {
+ small.matrix.set(placeAt(x, 0.45));
+ const result = query.evaluate(big.matrix, small.matrix);
+ small.material.color = result.kind === 'surface-intersection' ? [0.9, 0.2, 0.2] : result.kind === 'contained' ? [0.2, 0.75, 0.4] : [0.95, 0.75, 0.2];
+ renderer.updateParts([big, small]);
+ renderer.render({ eye: [0, 1.5, 6], target: [0, 0, 0], fov: 40 });
+ if (result.kind !== lastKind) {
+ lastKind = result.kind;
+ console.log(`x ${x.toFixed(2)}: ${result.kind} / ${result.solidRelation}, triangles ${JSON.stringify(result.triangles)}, ${result.triangleTests} triangle tests, ${result.rayAttempts} rays`);
+ }
+}
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: -3, max: 3, step: 0.02, value: -3 });
+slider.addEventListener('input', () => update(Number(slider.value)));
+row.append('Move the small sphere', slider);
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ update(Number(slider.value));
+}).observe(canvas);
+update(-3);
+addEventListener('pagehide', () => {
+ bigIndex.dispose();
+ smallIndex.dispose();
+});
+```
+
+The slider sweeps the small sphere through four states: `separate` / `outside` while the two are apart, `surface-intersection` / `boundaries-intersect` while the shells cross, `contained` / `b-in-a` when the small one sits fully inside the big one, and back again. Notice that while the small sphere is inside, the surfaces are disjoint. A `surfaces` query would report `surface-disjoint` there, because it does not test containment.
+
+`triangles` holds the first contacting pair of original triangle numbers, or `null`. The order of traversal decides which pair comes first, so the result never lists every contact. `triangleTests` counts the triangle callbacks, including containment rays, and `rayAttempts` counts the ray directions that containment tried.
+
+## Rays against a static mesh
+
+An index also supports `raycast(matrix, ray)` for a triangle number, hit point and barycentric coordinates. The two sliders move the origin of a ray that points down the -Z axis at a torus. The gold marker sits on the hit point, and the log prints the hit or `null` for a miss.
+
+```js live poster=contact-raycast
+import { Renderer67, torus, sphere } from '67js';
+import { createMeshQueryIndex } from '67js/addons/mesh-query';
+
+const ringMatrix = new Float32Array([1.2, 0, 0, 0, 0, 1.2, 0, 0, 0, 0, 1.2, 0, 0, 0, 0, 1]);
+const ring = { name: 'Ring', geometry: torus(0.3, 64, 24), matrix: ringMatrix, material: { color: [0.3, 0.5, 0.8], metallic: 0.1, roughness: 0.4 } };
+const marker = {
+ name: 'Hit',
+ geometry: sphere(16, 10),
+ matrix: new Float32Array([0.08, 0, 0, 0, 0, 0.08, 0, 0, 0, 0, 0.08, 0, 0, -50, 0, 1]),
+ material: { color: [1, 0.75, 0.2], metallic: 0, roughness: 0.3, emission: 2 },
+};
+
+const index = createMeshQueryIndex(ring.geometry);
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, [ring, marker], { ground: false, samples: 4, pixelRatio: 1.25 });
+const origin = { x: 1.2, y: 0 };
+
+function update() {
+ const hit = index.raycast(ringMatrix, { origin: [origin.x, origin.y, 6], direction: [0, 0, -1], maxDistance: 20 });
+ const position = hit ? hit.point : [0, -50, 0];
+ marker.matrix[12] = position[0];
+ marker.matrix[13] = position[1];
+ marker.matrix[14] = position[2];
+ renderer.updateParts([ring, marker]);
+ renderer.render({ eye: [0, 0.5, 6], target: [0, 0, 0], fov: 40 });
+ if (hit) {
+ console.log(`origin (${origin.x.toFixed(2)}, ${origin.y.toFixed(2)}): triangle ${hit.triangle}, distance ${hit.distance.toFixed(3)}, point ${hit.point.map(value => value.toFixed(2)).join(', ')}, barycentric ${hit.barycentric.map(value => value.toFixed(2)).join(', ')}`);
+ } else {
+ console.log(`origin (${origin.x.toFixed(2)}, ${origin.y.toFixed(2)}): null (miss)`);
+ }
+}
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+for (const axis of ['x', 'y']) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: -2, max: 2, step: 0.02, value: origin[axis] });
+ input.addEventListener('input', () => {
+ origin[axis] = Number(input.value);
+ update();
+ });
+ row.append(`Ray ${axis}`, input);
+ panel.append(row);
+}
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ update();
+}).observe(canvas);
+update();
+```
+
+A ray at `y = 0` and `x = 1.2` passes through the middle of the ring's tube, so it hits. Move `x` to 0 and it passes through the hole: the result is `null`. The hit's `triangle` is an original index-buffer triangle number, which is exactly what [attachments](#retained-surface-attachments) take as a binding. The `barycentric` coordinates follow the triangle's three index entries.
+
+A ray uses world-space `origin` and `direction`. `maxDistance` defaults to infinity and must be nonnegative.
+
+## Z-fighting is a different problem
+
+Contact queries find triangle contact. They do not explain why two parts flicker. Z-fighting has its own check: `renderer.diagnostics` and `scene_inspect` report `coplanar-overlap` for two parts that draw the same plane (within 1 mm, same facing, at least 1 cm2 shared). The example below puts a slab and a patch on the same top plane. Tick the box to mark the patch as a decal and watch the warning leave.
+
+```js live poster=contact-coplanar
+import { Renderer67, box } from '67js';
+import { installCoplanarDiagnostics } from '67js/addons/coplanar-overlap';
+
+function slab(x, y, z, width, height, depth) {
+ return new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, depth, 0, x, y, z, 1]);
+}
+
+const canvas = document.querySelector('#scene');
+const geometry = box(0, 1);
+let renderer = null;
+
+function build(useDecal) {
+ const parts = [
+ { name: 'Slab', geometry, matrix: slab(0, 0, 0, 4, 0.2, 4), material: { color: [0.3, 0.45, 0.7], metallic: 0, roughness: 0.5 } },
+ { name: 'Patch', geometry, matrix: slab(0.6, 0.05, 0.4, 1.8, 0.1, 1.6), material: { color: [0.9, 0.55, 0.2], metallic: 0, roughness: 0.5 }, decal: useDecal },
+ ];
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, parts, { ground: false, samples: 4, pixelRatio: 1.25 });
+ installCoplanarDiagnostics(renderer);
+ renderer.resize();
+ renderer.render({ eye: [3, 5.5, 5.5], target: [0, 0, 0], fov: 40 });
+ console.log(`decal: ${useDecal}, diagnostics: ${renderer.diagnostics.length ? renderer.diagnostics.map(problem => problem.message).join(' | ') : 'none'}`);
+}
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const checkbox = document.createElement('input');
+checkbox.type = 'checkbox';
+checkbox.addEventListener('change', () => build(checkbox.checked));
+row.append(checkbox, 'decal: true on the patch');
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ renderer.render({ eye: [3, 5.5, 5.5], target: [0, 0, 0], fov: 40 });
+}).observe(canvas);
+build(false);
+```
+
+Both parts draw the plane `y = 0.1`, so the patch flickers against the slab. The diagnostic names the smaller part and suggests the fix. `decal: true` puts the part on layer 1 (`depthLayer` 0 to 4 orders stacked decals) and draws it with a scoped polygon offset in the colour pass and the render passes, so it never moves geometry. In an agent scene recipe, `environment.resolveCoplanar: 'offset'` biases the smaller part of every flagged pair in the same way.
+
+Use a real offset along the normal when the gap should be visible in exports or the path tracer.
+
+The coplanar code is not in the core bundle. Call `installCoplanarDiagnostics(renderer)` from `67js/addons/coplanar-overlap` to add the warning to `renderer.diagnostics` (checked once per layout). `scene_inspect` shows it once `loadAllAgentSceneModules()` (or a recipe with `resolveCoplanar`) has loaded the code.
+
+### Depth precision far from the camera
+
+Far from the camera, depth precision is the other cause. `installReversedDepth(renderer, 'auto')` from `67js/addons/reversed-depth` switches on reversed-Z with a 32-bit float depth buffer and camera-relative drawing when a frame's far / near passes 10,000, or when `installDepthPrecision` finds a flush pair more than 40 units from the eye. It still has a float32 limit, because vertex positions are float32.
+
+On the RTX 3060 a 0.1 mm gap at 500 m still draws the far surface on 6.9% of pixels, and a 1 mm gap at 500 m on 1.4%. At 50 m both stay under 1%. Keep surfaces that must not flicker at least 1 mm apart when they sit hundreds of metres from the camera, or mark the top one `decal: true`.
+
+## Options
+
+| Index option | Default | Accepted range |
+| --- | --- | --- |
+| `maxVertices` | 250000 | Integer from 1 through 1000000 |
+| `maxTriangles` | 250000 | Integer from 1 through 1000000 |
+| `memoryBudgetMiB` | 64 | Number greater than 0 through 1024 |
+| `solid` | false | Boolean |
+| `maxValidationPairs` | 2000000 | Integer from 1 through 100000000 |
+
+`createMeshPairQuery(indexA, indexB, options)` takes `mode` (`'surfaces'` by default, or `'closed-solids'`) and `maxTriangleTests` (default 2000000, integers from 1 through 100000000). Exhausting a budget throws instead of returning a disjoint result, and the index stays usable.
+
+| `kind` | `solidRelation` | Meaning |
+| --- | --- | --- |
+| `surface-intersection` | `not-tested` | Surface mode found touching, crossing or coplanar triangles |
+| `surface-disjoint` | `not-tested` | Surface mode found no boundary contact |
+| `surface-intersection` | `boundaries-intersect` | Closed-solid mode found boundary contact |
+| `contained` | `a-in-b` | Solid A lies inside solid B without boundary contact |
+| `contained` | `b-in-a` | Solid B lies inside solid A without boundary contact |
+| `separate` | `outside` | Closed-solid mode found neither contact nor containment |
+
+`index.info` has frozen `vertexCount`, `triangleCount` and `estimatedBytes`. `index.memoryPlan` adds `reservedBytes`, `memoryBudgetMiB` and `validationPairs`. `dispose()` can be called twice, but later queries throw.
+
+A solid index needs closed geometry: every welded edge has two oppositely directed faces, the boundary is connected, and the surface does not cross itself. Separate shells and cavities are rejected. Query matrices are column-major, finite, affine and nonsingular, and reflections, nonuniform scales and shear are supported. The [mesh query contract](https://github.com/codepawl/67.js/blob/main/docs/mesh-query.md) describes results, solid validation, numerical limits and budget errors.
+
+## Common mistakes
+
+- **Using `surfaces` mode to find "inside".** Two surfaces can stay disjoint while one solid contains the other. Use `closed-solids` with `solid: true` on both indices.
+- **Reading contact as penetration.** Contact results do not measure penetration depth or resolve collisions, and two closed solids can touch at a face without overlapping interiors.
+- **A stale index.** The index holds a copy of the geometry. Build another one after any geometry edit. A shader that displaces the surface also changes what is visible without changing the triangles.
+- **Querying skinned or morphed geometry.** Indices reject skin and morph channels, and they cannot raycast a visibly skinned or morphed surface.
+- **Fixing flicker with a bigger index budget.** Z-fighting depends on the camera, projection and depth precision, not on mesh contact. Use `decal: true`, a real offset, or reversed depth.
diff --git a/docs/learn/hdr-environment-lighting.md b/docs/learn/hdr-environment-lighting.md
new file mode 100644
index 00000000..fda5c94b
--- /dev/null
+++ b/docs/learn/hdr-environment-lighting.md
@@ -0,0 +1,220 @@
+# HDR environment lighting
+
+Pass `environment: { map }` to light and reflect from an equirectangular HDR image. `loadHdri(url)` from `67js/addons/hdri` parses a Poly Haven `.hdr` file, and `createEnvironmentMap` accepts your own float data. Without a map, rendering is unchanged. The [lighting contract](/lighting.md#environment-maps-ibl) covers rotation, background display, memory and limits.
+
+```js
+import { Renderer67 } from '67js';
+import { loadHdri } from '67js/addons/hdri';
+
+const map = await loadHdri('/studio_small_09_1k.hdr', { intensity: 1, rotation: 0.6 });
+const renderer = new Renderer67(canvas, parts, { hdr: true, environment: { map } });
+```
+
+`loadHdri(url, options)` fetches and parses a Radiance `.hdr` (RGBE, `-Y height +X width`, flat or run-length scanlines) and returns the descriptor. Poly Haven CC0 HDRIs at 1k or 2k work well, and larger files only cost load time. The examples below build the map from data so that they need no download.
+
+## Build a map and turn it
+
+`createEnvironmentMap({ width, height, data, intensity, rotation, showBackground, backgroundBlur })` takes a `Float32Array` of linear RGB or RGBA, top row first. The image centre looks toward -Z. The example paints a small sky with a bright sun, and the sphere row reflects it. Drag to orbit, and use the slider to turn the map with `{ ...map, rotation }`: maps spread from one created map reuse their GPU textures, so rotation animates for free.
+
+```js live poster=hdr-rotate
+import { Renderer67, sphere, createEnvironmentMap } from '67js';
+
+// A 128 x 64 sky: blue zenith, pale horizon, dark ground and one very bright sun.
+function paintSky(width, height) {
+ const data = new Float32Array(width * height * 3);
+ const sun = [0.55, 0.5, -0.67];
+ const sunLength = Math.hypot(...sun);
+ for (let row = 0; row < height; row++) {
+ const elevation = (0.5 - (row + 0.5) / height) * Math.PI;
+ for (let column = 0; column < width; column++) {
+ const azimuth = ((column + 0.5) / width - 0.5) * Math.PI * 2;
+ const direction = [Math.sin(azimuth) * Math.cos(elevation), Math.sin(elevation), -Math.cos(azimuth) * Math.cos(elevation)];
+ const up = Math.max(direction[1], 0);
+ let color = direction[1] >= 0
+ ? [0.75 - 0.6 * Math.sqrt(up), 0.82 - 0.5 * Math.sqrt(up), 0.9 - 0.2 * Math.sqrt(up)]
+ : [0.1, 0.09, 0.08];
+ const alignment = Math.max(0, (direction[0] * sun[0] + direction[1] * sun[1] + direction[2] * sun[2]) / sunLength);
+ const glare = 60 * Math.pow(alignment, 300);
+ color = [color[0] + glare, color[1] + glare * 0.9, color[2] + glare * 0.7];
+ data.set(color, (row * width + column) * 3);
+ }
+ }
+ return data;
+}
+
+const width = 128;
+const height = 64;
+const map = createEnvironmentMap({ width, height, data: paintSky(width, height), intensity: 1, showBackground: true, backgroundBlur: 0.2 });
+
+const geometry = sphere(48, 30);
+const parts = [0, 1, 2, 3].map(index => ({
+ name: `Ball ${index}`,
+ geometry,
+ matrix: new Float32Array([0.7, 0, 0, 0, 0, 0.7, 0, 0, 0, 0, 0.7, 0, (index - 1.5) * 1.7, 0.7, 0, 1]),
+ material: { color: [0.9, 0.82, 0.7], metallic: index < 3 ? 1 : 0, roughness: [0.05, 0.3, 0.6, 0.5][index] },
+}));
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts, {
+ ground: false,
+ hdr: true,
+ pixelRatio: 1.25,
+ environment: { map, keyIntensity: 0, fillIntensity: 0 },
+});
+const orbit = { yaw: 0.2, pitch: 0.15, distance: 7 };
+let rotation = 0;
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 0.7, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0.7, 0], fov: 40, environment: { map: { ...map, rotation } } });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.008;
+ orbit.pitch = Math.min(1.2, Math.max(-0.2, orbit.pitch + event.movementY * 0.008));
+ draw();
+});
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 0, max: 6.28, step: 0.02, value: 0 });
+slider.addEventListener('input', () => {
+ rotation = Number(slider.value);
+ draw();
+});
+slider.addEventListener('change', () => console.log(`rotation ${rotation.toFixed(2)} rad, cpu ${renderer.cpuMilliseconds.toFixed(2)} ms`));
+row.append('Rotation', slider);
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+draw();
+console.log(`map ${map.width} x ${map.height}, ${map.channels} channels, ${(map.data.byteLength / 1024).toFixed(0)} KiB of float data`);
+console.log(`render memory estimate ${(renderer.memoryPlan.estimatedBytes / 1048576).toFixed(1)} MiB, HDR ${renderer.capabilities.hdr}`);
+```
+
+Turn the slider and the sun glints slide around the three polished metal spheres, the sharpest on the one with roughness 0.05. The fourth sphere is a dielectric: it takes its soft light from the map's diffuse term. The log shows the size of the float data and the render memory estimate, which includes the prefiltered chain.
+
+## Compare studio lighting and the map
+
+Set `map: null` in a frame to return to studio lighting, and set the map again to switch back. The row below goes from a mirror to a rough metal. The checkbox toggles the map, and the slider scales its `intensity`.
+
+```js live poster=hdr-compare
+import { Renderer67, sphere, createEnvironmentMap } from '67js';
+
+const width = 64;
+const height = 32;
+const data = new Float32Array(width * height * 3);
+for (let row = 0; row < height; row++) {
+ const elevation = (0.5 - (row + 0.5) / height) * Math.PI;
+ for (let column = 0; column < width; column++) {
+ const azimuth = ((column + 0.5) / width - 0.5) * Math.PI * 2;
+ // A warm band of light low on one side, a cool sky above, and a bright strip lamp.
+ const sky = Math.max(Math.sin(elevation), 0);
+ const lamp = Math.abs(azimuth - 0.9) < 0.25 && Math.abs(elevation - 0.5) < 0.12 ? 25 : 0;
+ data.set([0.2 + 0.3 * sky + lamp, 0.3 + 0.3 * sky + lamp, 0.45 + 0.4 * sky + lamp * 0.8], (row * width + column) * 3);
+ }
+}
+const map = createEnvironmentMap({ width, height, data });
+
+const geometry = sphere(48, 30);
+const parts = [0, 1, 2, 3, 4].map(index => ({
+ name: `Roughness ${index}`,
+ geometry,
+ matrix: new Float32Array([0.8, 0, 0, 0, 0, 0.8, 0, 0, 0, 0, 0.8, 0, (index - 2) * 1.8, 0.8, 0, 1]),
+ material: { color: [0.95, 0.9, 0.85], metallic: 1, roughness: index / 4 },
+}));
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, parts, { ground: false, hdr: true, pixelRatio: 1.25 });
+const state = { useMap: true, intensity: 1 };
+
+function draw() {
+ renderer.render({
+ eye: [0, 1.6, 8],
+ target: [0, 0.8, 0],
+ fov: 36,
+ environment: { map: state.useMap ? { ...map, intensity: state.intensity } : null },
+ });
+}
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const checkRow = document.createElement('label');
+checkRow.style.cssText = 'display:flex;gap:8px;align-items:center';
+const check = document.createElement('input');
+check.type = 'checkbox';
+check.checked = true;
+check.addEventListener('change', () => {
+ state.useMap = check.checked;
+ draw();
+ console.log(state.useMap ? 'environment map on' : 'map: null, studio lighting');
+});
+checkRow.append(check, 'Environment map');
+const intensityRow = document.createElement('label');
+intensityRow.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 0, max: 3, step: 0.05, value: 1 });
+slider.addEventListener('input', () => {
+ state.intensity = Number(slider.value);
+ draw();
+});
+slider.addEventListener('change', () => console.log(`map intensity ${state.intensity}`));
+intensityRow.append('Intensity', slider);
+panel.append(checkRow, intensityRow);
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+draw();
+console.log(`${parts.length} spheres, roughness 0 to 1, one prefiltered map of ${width} x ${height}`);
+```
+
+The mirror sphere shows the strip lamp as a sharp stripe. As roughness grows, the reflection blurs into a soft glow, because the renderer samples a GGX-prefiltered chain, by roughness. Without a map the same spheres show the procedural studio reflection, and the result is pixel-identical to a renderer that never had a map.
+
+## What a map changes
+
+When a map is set:
+
+- Standard PBR surfaces take specular reflection by roughness from a GGX-prefiltered chain and diffuse ambient from L2 spherical harmonics, with a split-sum BRDF lookup. `ambientIntensity` and occlusion maps still scale it.
+- Liquid reflections sample the same chain.
+- `showBackground: true` draws the map behind the scene in studio and world mode, blurred by `backgroundBlur`. It is skipped on transparent canvases.
+- Key, fill and point lights still add direct light. Set `keyIntensity` and `fillIntensity` to zero to light a scene from the map alone, as the first example does.
+- The procedural floor, water tag, fire and smoke keep their own shading.
+
+Set `environment.map` in the constructor or in `frame.environment`. Passing a different map prefilters it on first use, and `map: null` returns to studio lighting.
+
+### Options
+
+| Field of `createEnvironmentMap` | Default | Meaning |
+| --- | --- | --- |
+| `width`, `height` | required | Integers: width 4 to 16384, height 2 to 16384. |
+| `data` | required | `Float32Array` of linear RGB or RGBA, top row first, finite values only. Its length is `width * height * 3` or `* 4`. |
+| `intensity` | `1` | Number from 0 to 1000. |
+| `rotation` | `0` | Radians, turns the map about the vertical axis. |
+| `showBackground` | `false` | Boolean. Draw the map behind the scene. |
+| `backgroundBlur` | `0` | Number from 0 to 1. |
+
+`loadHdri(url, options)` accepts `intensity`, `rotation`, `showBackground`, `backgroundBlur`, `signal` and `fetchImplementation`.
+
+Prefiltering runs once when a map is first used, not per frame: about 30 ms for a 512x256 map on an RTX 3060 after shader compilation, plus about 0.6 s of first-use shader compile. The renderer keeps a half-float chain of at most 1024 wide (about 8 MB for 1024x512, 1.4 MB for 512x256) and a 128x128 BRDF lookup, and counts both in the memory budget. The source upload is freed after prefiltering. A 2048x1024 source briefly needs about 11 MB of GPU memory and 32 MB of CPU memory while loading. Maps need `EXT_color_buffer_float`, and without it the constructor throws.
+
+Limits: the diffuse term uses L2 spherical harmonics, so a very small intense sun gives soft, slightly ringing diffuse light and no shadow. Use the key light for sun shadows. Reflections have no parallax or occlusion, and the procedural water tag does not use the map.
+
+## Common mistakes
+
+- **Forgetting `hdr: true`.** The examples all create the renderer with `hdr: true`, because a bright sun needs floating-point targets. Maps also need `EXT_color_buffer_float`.
+- **Leaving the key and fill lights on and expecting a map-only look.** Set `keyIntensity` and `fillIntensity` to zero.
+- **Expecting a sun shadow from the map.** A map gives soft diffuse light and reflections, and no shadow. Use the key light for that.
+- **A data array of the wrong length.** The length must match `width * height * 3` or `* 4`, with no NaN or Infinity.
+- **Creating a new map for every rotation step.** Spread the one created map, `{ ...map, rotation }`, and the GPU textures are reused. A different map costs a new prefilter.
+- **Expecting parallax in reflections.** A map reflects an infinitely distant room, so the reflection never shifts when an object moves.
diff --git a/docs/learn/local-lights-and-volume-fog.md b/docs/learn/local-lights-and-volume-fog.md
new file mode 100644
index 00000000..ffe5fd20
--- /dev/null
+++ b/docs/learn/local-lights-and-volume-fog.md
@@ -0,0 +1,255 @@
+# Local lights and volume fog
+
+Version `0.4.0` supports local lighting through the renderer's `environment` option and per-frame environment overrides. `pointLights` accepts at most 16 world-space lights with linear RGB colors. `keyIntensity`, `fillIntensity` and `ambientIntensity` control the existing studio lighting.
+
+The workflow has three steps:
+
+1. Set the environment's lighting controls when creating the renderer.
+2. Supply the complete `frame.environment.pointLights` list to animate local lights.
+3. Inspect exposure and material response at a fixed sample time.
+
+## Move a point light
+
+In the scene below, the studio lights are turned down, so the point light does most of the work. Drag in the picture to move the light across the floor. The slider sets the intensity, and the box turns on a shadow for the light. Every frame passes the whole `pointLights` list in `frame.environment`.
+
+```js live poster=lights-point
+import { Renderer67, box, sphere } from '67js';
+
+function placeAt(x, y, z, width, height, depth) {
+ return new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, depth, 0, x, y, z, 1]);
+}
+
+const cube = box(0.04, 3);
+const white = { color: [0.8, 0.8, 0.8], metallic: 0, roughness: 0.6 };
+const parts = [
+ { name: 'Floor', geometry: box(0, 1), matrix: placeAt(0, -0.1, 0, 9, 0.2, 9), material: white },
+ { name: 'Wall', geometry: box(0, 1), matrix: placeAt(0, 0.8, 0, 0.2, 1.6, 3.5), material: { color: [0.7, 0.55, 0.45], metallic: 0, roughness: 0.6 } },
+ { name: 'Cube left', geometry: cube, matrix: placeAt(-1.8, 0.4, 0.9, 0.8, 0.8, 0.8), material: { color: [0.3, 0.5, 0.8], metallic: 0, roughness: 0.4 } },
+ { name: 'Cube right', geometry: cube, matrix: placeAt(1.8, 0.4, -0.6, 0.8, 0.8, 0.8), material: { color: [0.8, 0.35, 0.3], metallic: 0, roughness: 0.4 } },
+ { name: 'Bulb', geometry: sphere(16, 10), matrix: placeAt(-1.4, 1.2, 0, 0.12, 0.12, 0.12), material: { color: [1, 0.8, 0.5], metallic: 0, roughness: 0.3, emission: 3 } },
+];
+const bulb = parts[4];
+const light = { x: -1.4, z: 0, intensity: 8, castShadow: false };
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts, {
+ ground: false,
+ hdr: true,
+ pixelRatio: 1.25,
+ environment: { keyIntensity: 0.05, fillIntensity: 0.05, ambientIntensity: 0.1 },
+});
+
+function draw() {
+ bulb.matrix.set(placeAt(light.x, 1.2, light.z, 0.12, 0.12, 0.12));
+ renderer.updateParts(parts);
+ renderer.render({
+ eye: [0, 5.5, 6.5],
+ target: [0, 0.2, 0],
+ fov: 38,
+ environment: {
+ pointLights: [{
+ position: [light.x, 1.2, light.z],
+ color: [1, 0.75, 0.45],
+ intensity: light.intensity,
+ radius: 0.08,
+ range: 9,
+ castShadow: light.castShadow,
+ }],
+ },
+ });
+}
+
+function moveLight(event) {
+ const bounds = canvas.getBoundingClientRect();
+ light.x = (((event.clientX - bounds.left) / bounds.width) * 2 - 1) * 4;
+ light.z = (((event.clientY - bounds.top) / bounds.height) * 2 - 1) * 3.5;
+ draw();
+}
+canvas.addEventListener('pointerdown', event => {
+ canvas.setPointerCapture(event.pointerId);
+ moveLight(event);
+});
+canvas.addEventListener('pointermove', event => {
+ if (canvas.hasPointerCapture(event.pointerId)) moveLight(event);
+});
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const intensityRow = document.createElement('label');
+intensityRow.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+const intensity = document.createElement('input');
+Object.assign(intensity, { type: 'range', min: 0, max: 30, step: 0.5, value: light.intensity });
+intensity.addEventListener('input', () => {
+ light.intensity = Number(intensity.value);
+ draw();
+});
+intensity.addEventListener('change', () => console.log(`intensity ${light.intensity}`));
+intensityRow.append('Intensity', intensity);
+const shadowRow = document.createElement('label');
+shadowRow.style.cssText = 'display:flex;gap:8px;align-items:center';
+const shadow = document.createElement('input');
+shadow.type = 'checkbox';
+shadow.addEventListener('change', () => {
+ light.castShadow = shadow.checked;
+ draw();
+ console.log(`castShadow ${light.castShadow}, cpu ${renderer.cpuMilliseconds.toFixed(2)} ms`);
+});
+shadowRow.append(shadow, 'castShadow');
+panel.append(intensityRow, shadowRow);
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+draw();
+console.log(`lights: 1 of 16, triangles ${renderer.triangles}, cpu ${renderer.cpuMilliseconds.toFixed(2)} ms`);
+```
+
+The light falls off with the inverse square of the distance, so doubling the distance gives a quarter of the light. With the wall between the bulb and the right cube, the cube still catches light when `castShadow` is off. Tick the box and the wall shadows it. Move the light with the mouse to see the pool of light slide over the floor and the wall.
+
+Light updates add no geometry, texture, framebuffer or draw pass. Each renderer retains one set of light uniform arrays, which hold 75 floats, and shading cost grows with the active lights and the covered pixels.
+
+Absolute-time animation keeps light movement independent of seek order. Excessive brightness clips at the finite half-float HDR target limit of 65,504 before bloom and tone mapping.
+
+### Point light fields
+
+Each light supplies `position`. Optional fields default to white `color`, `intensity: 1`, `radius: 0.05` and unlimited `range: 0`.
+
+| Field | Range | Meaning |
+| --- | --- | --- |
+| `position` | within ±1,000,000 scene units | World-space position. |
+| `color` | components from 0 to 1 | Linear RGB. |
+| `intensity` | 0 to 100,000 | Candela for a point source. The pipeline is not calibrated to photographic exposure. |
+| `radius` | 0.001 to 1,000,000 | Limits the near-source attenuation. It does not create an area emitter or soften shadows. |
+| `range` | 0, or 0.001 to 1,000,000 | Zero keeps unlimited falloff. A positive range fades the light to zero with `(max(1 - (distance / range)^4, 0))^2`. |
+| `castShadow` | boolean | Draws the light's depth into a shared shadow atlas. |
+
+Studio controls: `keyIntensity`, `fillIntensity` and `ambientIntensity` each go from 0 to 100 and default to 1. `keyColor` replaces the key light's linear RGB color, with components from 0 to 1,000. Set all three intensities to zero to isolate local lights on standard PBR surfaces. These controls do not disable the sky, emission, fog or the special floor, fire and smoke shading.
+
+Pass the entire list in `frame.environment.pointLights` to replace the constructor list. An empty list removes all local lights, and omitted fields keep the constructor defaults. Validation runs before the light arrays change, so an invalid later light leaves the previous lighting state intact. The [lighting contract](/lighting.md) defines intensity, radius, range and validation limits, and covers spot and area lights.
+
+A point light with `castShadow: true` takes six tiles of a shadow atlas of 24 tiles (a 24 MiB depth texture, allocated on first use), so at most four point lights can cast shadows. Without `castShadow` a point light can illuminate through walls. The original directional shadow map stays in use for the key light.
+
+## Volume fog
+
+`environment.volumeFog` defines one axis-aligned world-space volume of fog that scatters the sun's light. Active fog requires `hdr: true`, `depth: true` and supported floating-point targets: WebGL 2 `EXT_color_buffer_float`, and an opaque, non-benchmark renderer. The depth texture contributes to the render memory estimate.
+
+The scene has pillars and a low sun. The slider sets the density, and `frame.environment.volumeFog` replaces the whole fog object for each frame. Drag to turn the camera. The log prints the memory the depth texture adds.
+
+```js live poster=fog-volume
+import { Renderer67, box, cylinder } from '67js';
+
+function placeAt(x, y, z, width, height, depth) {
+ return new Float32Array([width, 0, 0, 0, 0, height, 0, 0, 0, 0, depth, 0, x, y, z, 1]);
+}
+
+const pillar = cylinder(24, 0, 1);
+const stone = { color: [0.75, 0.72, 0.68], metallic: 0, roughness: 0.7 };
+const parts = [{ name: 'Floor', geometry: box(0, 1), matrix: placeAt(0, -0.1, 0, 12, 0.2, 10), material: { color: [0.4, 0.4, 0.42], metallic: 0, roughness: 0.8 } }];
+for (let column = 0; column < 4; column++) {
+ parts.push({ name: `Pillar ${column}`, geometry: pillar, matrix: placeAt(-3.6 + column * 2.4, 1.5, -1, 0.7, 3, 0.7), material: stone });
+}
+
+const fog = {
+ density: 0.05,
+ minimum: [-5.7, 0.03, -4.7],
+ maximum: [5.7, 4.5, 4.7],
+ color: [0.9, 0.83, 0.7],
+ steps: 24,
+ maxDistance: 20,
+};
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts, {
+ hdr: true,
+ depth: true,
+ ground: false,
+ pixelRatio: 1,
+ environment: {
+ lightDirection: [-0.35, 0.55, -0.85],
+ volumeFog: fog,
+ },
+});
+const orbit = { yaw: 0.25, pitch: 0.18, distance: 9 };
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 1, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 1.3, 0], fov: 42, time: 0, environment: { volumeFog: { ...fog } } });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.008;
+ orbit.pitch = Math.min(0.9, Math.max(0.02, orbit.pitch + event.movementY * 0.008));
+ draw();
+});
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 0, max: 0.3, step: 0.01, value: fog.density });
+slider.addEventListener('input', () => {
+ fog.density = Number(slider.value);
+ draw();
+});
+slider.addEventListener('change', () => console.log(`density ${fog.density}, cpu ${renderer.cpuMilliseconds.toFixed(2)} ms`));
+row.append('Density', slider);
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+draw();
+const plan = renderer.memoryPlan;
+console.log(`render size ${plan.width} x ${plan.height}, estimated ${(plan.estimatedBytes / 1048576).toFixed(1)} MiB, depth texture ${plan.width * plan.height * 4} bytes, HDR ${renderer.capabilities.hdr}`);
+```
+
+The fog marches from the camera through the volume for every pixel, clips against the resolved opaque depth, and stops at the boundary of the box or at `maxDistance`. It integrates Beer-Lambert extinction and directional single scattering with a Henyey-Greenstein phase function, using the key light's color and the existing directional shadow map. The shadows of the pillars cut dark wedges out of the lit haze. Keep authored shadow bounds aligned with the light direction and covering the medium.
+
+Set `density: 0` to turn the fog off. Noise samples absolute time, so a backward seek reproduces earlier density.
+
+### Volume fog fields
+
+`frame.environment.volumeFog` replaces the whole constructor fog object for that frame, and omitted fields use these defaults.
+
+| Field | Default | Accepted range |
+| --- | --- | --- |
+| `density` | `0` | `0…10`, extinction per scene unit |
+| `minimum` | `[-100, 0, -100]` | Three components within ±100,000 |
+| `maximum` | `[100, 20, 100]` | Three components within ±100,000; greater than minimum after Float32 rounding |
+| `color` | `[0.8, 0.85, 0.9]` | Linear RGB, `0…1` |
+| `ambient` | `[0.03, 0.035, 0.04]` | Linear RGB, `0…10` |
+| `steps` | `16` | Integer `8…48` |
+| `anisotropy` | `0.3` | `-0.9…0.9`; positive favors forward scattering |
+| `noiseAmount` | `0.5` | `0…1`; zero gives uniform density |
+| `noiseScale` | `0.3` | `0.001…100`, inverse scene units |
+| `drift` | `[0.03, 0, 0]` | Three components within ±100, scene units per second |
+| `maxDistance` | `100` | `0.01…10,000`, ray distance in scene units |
+| `shadowAmbient` | derived | `0…1`; the share of `ambient` the fog keeps where the sun's shadow covers it. Left unset, 32 upward rays from the middle of the fog box decide: a closed room keeps 0.15, open ground under a sky keeps 1, and a partly covered scene lands between. Set it to override |
+
+Values must be finite numbers. Active volume fog accepts finite frame time within ±1,000,000 seconds and a nonzero light direction with components within ±1,000,000.
+
+Resolved depth adds four estimated bytes per rendered pixel, or 2,073,600 bytes at 960 × 540. The planner reduces render dimensions when needed. The target is allocated at construction and resize, reused across frames and released by `dispose()`. Shading cost grows with covered pixels and step count.
+
+`part.castShadow: false` excludes a mesh from shadow rendering while keeping it visible and opaque, for example a luminous window that should not block the sun. The flag must be boolean, and changing a part's casting regime needs a new renderer, because `updateParts()` rejects it.
+
+The ambient of the fog can follow a per-point sky visibility and a bounce from the surfaces, instead of one share for the whole box. Pass `fogSkyVisibility` from `src/fog-sky-visibility.js` to `Renderer67` (the agent preview and the reference harness do). In a scene with an irradiance grid (`bake.irradianceGrid`) the bounce term is the grid's mean light at the cell, and the fog's ambient stands for the sky only. The [volume fog contract](https://github.com/codepawl/67.js/blob/main/docs/volumetric.md) covers these terms, the cost and the limits.
+
+This is one bounded medium with one directional scattering source. Point-light scattering, multiple scattering, attenuation toward the source, transparent depth, volume grids, particles, temporal accumulation and half-resolution rendering are not built. Fog runs after bloom extraction, so scattering itself does not feed bloom.
+
+With `world: true` the default `environment.fogDensity` is 0.006 per unit, which hazes a model 100 to 600 units wide into milky haze. Set a lower `fogDensity` for a large scene.
+
+## Common mistakes
+
+- **Sending only the lights that changed.** `frame.environment.pointLights` replaces the whole list, so send every light each frame, or all other lights go dark.
+- **More than 16 point lights.** The limit is 16 per frame. Spot lights (8) and area lights (7) have their own counts, and shadow-casting point lights are limited to four.
+- **Expecting walls to block a light.** A point light shines through walls unless it has `castShadow: true`.
+- **Setting `radius` for a soft shadow or an area light.** Radius only limits near-source attenuation.
+- **Fog without `hdr: true` and `depth: true`.** Active fog needs both, and floating-point targets.
+- **Passing a partial fog object in a frame and expecting merged values.** It replaces the constructor's fog object, and omitted fields return to the defaults, so spread your fog object into it.
+- **A fog box that is too big for `maxDistance`.** The march stops at `maxDistance`, so a long volume fades out early. Raise it, and raise `steps` if the haze bands.
diff --git a/docs/learn/parts-and-geometry.md b/docs/learn/parts-and-geometry.md
new file mode 100644
index 00000000..0459f474
--- /dev/null
+++ b/docs/learn/parts-and-geometry.md
@@ -0,0 +1,200 @@
+# Parts and geometry
+
+A scene is an array of parts. Each part has a unique `name`, a shared `geometry`, a column-major 16-value `Float32Array` `matrix`, and a `material`. The renderer reads that array once when it is created, so the shape of the array is the shape of your scene.
+
+Geometry uses `Float32Array` positions and normals, and `Uint32Array` triangle indices. Normals must have unit length and triangles face outward. Optional `uvs` have two values per vertex. Optional `colors` are opaque linear RGB.
+
+## Parts that share one geometry
+
+Transforms must be finite and invertible. Use one geometry object for repeated parts, rather than creating identical meshes for every instance. Each geometry and texture descriptor identity pair becomes an instanced batch.
+
+Drag the picture to orbit. The slider turns one part: the code changes its matrix in place and calls `updateParts`, which uploads the new matrix without building anything again.
+
+```js live poster=parts-shared-geometry
+import { Renderer67, box } from '67js';
+
+// A column-major matrix: turn about Y by `angle`, scale by `size`, move to (x, y, z).
+function placeAt(x, y, z, size, angle = 0) {
+ const cosine = Math.cos(angle) * size;
+ const sine = Math.sin(angle) * size;
+ return new Float32Array([cosine, 0, -sine, 0, 0, size, 0, 0, sine, 0, cosine, 0, x, y, z, 1]);
+}
+
+function addSlider(label, minimum, maximum, value, onInput) {
+ let panel = document.querySelector('#controls');
+ if (!panel) {
+ panel = document.createElement('div');
+ panel.id = 'controls';
+ panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+ document.body.append(panel);
+ }
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center';
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: minimum, max: maximum, step: 'any', value });
+ input.addEventListener('input', () => onInput(Number(input.value)));
+ row.append(label, input);
+ panel.append(row);
+}
+
+// One geometry object, nine parts: the renderer draws them in a single batch.
+const geometry = box(0.08, 4);
+const parts = [];
+for (let row = 0; row < 3; row++) {
+ for (let column = 0; column < 3; column++) {
+ parts.push({
+ name: `Cube ${row}-${column}`,
+ geometry,
+ matrix: placeAt((column - 1) * 1.3, 0.5, (row - 1) * 1.3, 0.9),
+ material: { color: [0.3, 0.35 + row * 0.1, 0.55 + column * 0.1], metallic: 0.2, roughness: 0.45 },
+ });
+ }
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const renderer = new Renderer67(canvas, parts, { samples: 4, pixelRatio: 1.25 });
+const orbit = { yaw: 0.6, pitch: 0.5, distance: 7 };
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0.4, 0], fov: 40 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(0.05, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+addSlider('Turn the middle cube', 0, 6.283, 0, angle => {
+ parts[4].matrix.set(placeAt(0, 0.5, 0, 0.9, angle));
+ renderer.updateParts(parts);
+ draw();
+});
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+
+console.log('parts:', parts.length);
+console.log('triangles:', renderer.triangles);
+console.log('instance batches:', renderer.batches.length);
+console.log('estimated render memory (MiB):', (renderer.memoryPlan.estimatedBytes / 1048576).toFixed(1));
+```
+
+The log shows the effect of sharing: nine parts and one batch. If each part had its own `box()` call, there would be nine batches and nine copies of the geometry on the GPU.
+
+`parts[4].matrix.set(...)` writes into the same `Float32Array`, and `updateParts(parts)` uploads the changed matrices and materials from retained buffers. It cannot add a new part, geometry or texture identity: for that, create a new renderer.
+
+> **Tip:** Keep each geometry near its own origin and move it with the matrix. Float32 positions lose detail far from zero, and a shared geometry that sits at the origin can serve every instance.
+
+## Primitives and their detail
+
+`box(fillet, samples)`, `cylinder(segments)`, `sphere(segments, rings)` and `torus(tubeRadius, segments, sides)` are the core primitives. Every call returns `{ positions, normals, indices, uvs }` at unit size, and the part matrix sets the size. The slider below rebuilds the scene with more or fewer segments, so you can see what the numbers buy.
+
+```js live poster=parts-primitive-detail
+import { Renderer67, box, cylinder, sphere, torus } from '67js';
+
+function placeAt(x, y, z, size) {
+ return new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+}
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const orbit = { yaw: 0.3, pitch: 0.35, distance: 7 };
+let renderer = null;
+
+function build(segments) {
+ const shapes = [
+ ['Box', box(0.08, Math.max(1, Math.round(segments / 8))), [-2.7, 0.5, 0], 1],
+ ['Cylinder', cylinder(segments, 0.025, 2), [-1, 0.4, 0], 0.8],
+ ['Sphere', sphere(segments, Math.max(2, Math.round(segments * 0.6))), [0.7, 0.5, 0], 0.5],
+ ['Torus', torus(0.18, segments, Math.max(3, Math.round(segments / 3))), [2.3, 0.5, 0], 0.45],
+ ];
+ const parts = shapes.map(([name, geometry, [x, y, z], size], index) => ({
+ name,
+ geometry,
+ matrix: placeAt(x, y, z, size),
+ material: { color: [0.3 + index * 0.15, 0.5, 0.75 - index * 0.15], metallic: 0.1, roughness: 0.4 },
+ }));
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, parts, { samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+ const counts = shapes.map(([name, geometry]) => `${name} ${geometry.indices.length / 3}`);
+ console.log(`segments ${segments}, triangles: ${counts.join(', ')}`);
+}
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0.5, 0], fov: 38 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(0.05, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+const panel = document.createElement('label');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 3, max: 64, step: 1, value: 12 });
+slider.addEventListener('change', () => build(Number(slider.value)));
+panel.append('Segments', slider);
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build(12);
+```
+
+At 12 segments the sphere is visibly faceted, and at 48 it looks round. The cost is the triangle count, which grows with the product of segments and rings. Every constructor checks its vertex count before it samples, with a fixed limit of one million vertices.
+
+| Constructor | Shape | Input bounds |
+| --- | --- | --- |
+| `box(bevel = 0.08, subdivisions = 6)` | Cube with each axis from -0.5 to 0.5. | Bevel from 0 to 0.5. Subdivisions from 1 to 128. |
+| `sphere(segments = 64, rings = 40)` | Unit-radius sphere. | Segments from 3 to 2048. Rings from 2 to 2048. |
+| `cylinder(segments = 80, bevel = 0.025, bevelSegments = 6)` | Y-axis cylinder with radius 1 and height 1. | Segments from 3 to 2048. Bevel from 0 to 0.5. Bevel segments from 1 to 128. |
+| `torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = 2π, start = 0)` | XY torus with major radius 1. Partial arcs have end caps. | Positive tube radius. Segments from 3 to 2048. Sides from 3 to 128. Arc within (0, 2π]. Start uses radians. |
+
+Counts must be integers and numbers must stay finite in Float32. The [primitive contract](https://github.com/codepawl/67.js/blob/main/docs/primitives.md) covers closed seams and the geometry limits. Primitives do not perform Boolean operations, sculpting or collision resolution.
+
+## Constructor options that matter for parts
+
+Supply a real HTML canvas with nonzero CSS width and height.
+
+```js
+const renderer = new Renderer67(canvas, parts, {
+ ground: false, hdr: true, samples: 4, pixelRatio: 1.25, memoryBudgetMiB: 256,
+});
+renderer.render({ eye: [3, 2, 4], target: [0, 0, 0] });
+```
+
+| Part field | Meaning |
+| --- | --- |
+| `name` | Unique text label. Error messages name the part with it. |
+| `geometry` | Shared object with `positions`, `normals`, `indices` and optional `uvs` and `colors`. |
+| `matrix` | Column-major `Float32Array(16)`, finite and invertible. The translation is the last four values. |
+| `material` | `color`, `metallic` and `roughness` are required. `emission` and `tag` are optional, and `tag: 'surface'` is the standard material. |
+
+The [renderer reference](#renderer-reference) lists every constructor option.
+
+## Common mistakes
+
+- **A row-major matrix.** The translation belongs in positions 12, 13 and 14. In row-major order it lands in the wrong place, and the part moves or shears.
+- **One geometry per instance.** Identical meshes created in a loop produce one batch each. Create the geometry once and reuse the object.
+- **Normals that are not unit length, or triangles that face inward.** Lighting looks wrong and the surface can vanish from one side.
+- **A singular matrix.** A scale of 0 on any axis makes the transform non-invertible, and the renderer throws `Singular transform` with the part name.
+- **Adding parts after construction.** `updateParts` only changes matrices and materials of parts that exist. A new geometry or texture needs a new renderer, and `dispose()` frees the old one.
+- **A zero-size canvas.** Give the canvas a CSS width and height before you create the renderer.
diff --git a/docs/learn/procedural-modeling.md b/docs/learn/procedural-modeling.md
new file mode 100644
index 00000000..568e1c06
--- /dev/null
+++ b/docs/learn/procedural-modeling.md
@@ -0,0 +1,182 @@
+# Procedural modeling
+
+Version `0.4.0` provides `lathe`, `extrude` and `tube` through `67js/addons/modeling`, and the addon also has `curve`. They generate static geometry from radius and height profiles, polygon contours and XYZ paths. Extrusion supports holes and bevels. Open tube ends remain uncapped.
+
+The workflow has four steps:
+
+1. Choose a profile, contour or path in local coordinates.
+2. Generate the geometry once with the matching addon function.
+3. Assign the result to a part before creating `Renderer67`.
+4. Share the geometry among repeated parts.
+
+Each result has Float32 positions, normalized normals and UV channel zero, plus Uint32 triangle indices. Inputs are copied. The generators run when you build the scene, not every frame.
+
+## Lathe: spin a profile into a vessel
+
+`lathe(profile, options)` revolves `[radius, height]` pairs around the Y axis. The first slider changes the belly radius of the profile and the second changes the number of segments around the axis. Both rebuild the vase, and the log shows what each build costs. Drag to orbit.
+
+```js live poster=modeling-lathe
+import { Renderer67 } from '67js';
+import { lathe } from '67js/addons/modeling';
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const orbit = { yaw: 0.5, pitch: 0.3, distance: 6 };
+const state = { belly: 0.85, segments: 24 };
+let renderer = null;
+
+function build() {
+ const profile = [[0, 0], [0.5, 0], [state.belly, 0.7], [0.55, 1.5], [0.4, 2], [0.5, 2.15], [0, 2.15]];
+ const started = performance.now();
+ const geometry = lathe(profile, { segments: state.segments });
+ const milliseconds = performance.now() - started;
+ const part = {
+ name: 'Vase',
+ geometry,
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ material: { color: [0.75, 0.35, 0.22], metallic: 0, roughness: 0.4 },
+ };
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, [part], { samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+ console.log(`belly ${state.belly.toFixed(2)}, segments ${state.segments}: ${geometry.positions.length / 3} vertices, ${geometry.indices.length / 3} triangles, ${milliseconds.toFixed(2)} ms`);
+}
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 1, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 1, 0], fov: 38 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(0.05, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+function addSlider(label, key, minimum, maximum, step) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: minimum, max: maximum, step, value: state[key] });
+ input.addEventListener('change', () => {
+ state[key] = Number(input.value);
+ build();
+ });
+ row.append(label, input);
+ panel.append(row);
+}
+addSlider('Belly radius', 'belly', 0.5, 1.3, 0.05);
+addSlider('Segments', 'segments', 3, 96, 1);
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build();
+```
+
+The profile lists points from the bottom to the top: a radius of zero closes the base on the axis, the belly radius is the widest point, and the last two points make the lip and close the top. A profile whose ends meet the axis gives a closed shape. A partial `sweep` or an open profile end stays open.
+
+With 3 segments the vase becomes a triangular prism, which shows what the number controls. At 96 segments the vertex count is thirty times higher for a shape that looks the same as 48.
+
+## Extrude, tube and curve
+
+`extrude` pushes a flat outline along +Z. `tube` sweeps a circle along a path through XYZ points. `curve` does the same along cubic Bezier spans and can thin toward its end. The slider changes the bevel of the panel, so the geometry is rebuilt and the log prints the sizes.
+
+```js live poster=modeling-shapes
+import { Renderer67 } from '67js';
+import { extrude, tube, curve } from '67js/addons/modeling';
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const orbit = { yaw: 0.35, pitch: 0.3, distance: 8 };
+let renderer = null;
+
+function placeAt(x, y, z, size) {
+ return new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+}
+
+function build(bevel) {
+ const panel = extrude([[-1, -1], [1, -1], [1, 1], [-1, 1]], {
+ holes: [[[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5]]],
+ depth: 0.3,
+ bevel,
+ });
+ const cable = tube([[0, 0, 0], [0.8, 1.2, 0.5], [1.6, 0.2, -0.4], [2.2, 1.4, 0]], { radius: 0.07 });
+ const horn = curve([[0, 0, 0], [0.5, 0.9, 0], [1.2, 1.2, 0.3]], { radius: 0.3, taper: [1, 0.05] });
+ const parts = [
+ { name: 'Panel', geometry: panel, matrix: placeAt(-2.6, 1, 0, 1), material: { color: [0.3, 0.45, 0.7], metallic: 0.1, roughness: 0.4 } },
+ { name: 'Cable', geometry: cable, matrix: placeAt(-0.5, 0, 0, 1), material: { color: [0.85, 0.7, 0.2], metallic: 0, roughness: 0.4 } },
+ { name: 'Horn', geometry: horn, matrix: placeAt(2.2, 0, 0, 1), material: { color: [0.8, 0.3, 0.3], metallic: 0, roughness: 0.45 } },
+ ];
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, parts, { samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+ const counts = parts.map(part => `${part.name} ${part.geometry.indices.length / 3}`);
+ console.log(`bevel ${bevel.toFixed(2)}, triangles: ${counts.join(', ')}`);
+}
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance + 0.8, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0.2, 0.8, 0], fov: 38 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(0.05, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 0, max: 0.2, step: 0.01, value: 0.05 });
+slider.addEventListener('change', () => build(Number(slider.value)));
+row.append('Panel bevel', slider);
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build(0.05);
+```
+
+The panel has a square hole, and its bevel adds rounded edges on both caps, from `-bevelThickness` to `depth + bevelThickness` along Z. Push the slider to its end and see how the corners round. A bevel that is large compared with the hole can make surfaces cross, so reduce it to fit the local clearance.
+
+The horn uses `taper: [1, 0.05]`, which spreads two radius factors along the length of the curve: full radius at the start and a twentieth at the tip. Open curves get flat caps, so the surface is closed and works with Boolean tools.
+
+## Options
+
+| Function | Options and defaults | Limits |
+| --- | --- | --- |
+| `lathe(profile, options)` | `segments = 64`, `startAngle = 0`, `sweep = 2π`, `maxVertices = 250000` | Radii are nonnegative, with at least one positive. Segments from 3 to 2048. Angles in radians. |
+| `extrude(contour, options)` | `holes = []`, `depth = 1`, `steps = 1`, `bevel = 0`, `bevelThickness = bevel`, `bevelSegments = 3`, `maxVertices` | Steps from 1 to 256. Bevel segments from 1 to 32. At most 128 holes. Holes stay strictly inside the contour and cannot overlap, touch or nest. |
+| `tube(path, options)` | `radius = 0.1`, `segments = 64`, `radialSegments = 12`, `closed = false`, `maxVertices` | Open paths need two points, closed paths three. Segments from 3 to 2048. Radial segments from 3 to 128. |
+| `curve(points, options)` | `closed = false`, `radius = 0.05`, `taper`, `profile`, `resolution = 12`, `radialSegments = 8`, `maxVertices` | 2 to 1024 points (3 when closed). `resolution` 1 to 64. `taper` has 2 to 64 non-negative factors. `profile` has 3 to 256 `[x, y]` points. |
+
+Every generator accepts at most 4096 input points, and `maxVertices` ranges from 3 to 1000000. It bounds geometry size, not total browser memory. The [modeling contract](/modeling.md) defines input bounds, winding, bevel limits and resource estimates, and also covers the `text` generator and `registerFont`.
+
+A `curve` point is `[x, y, z]` with automatic smooth handles, or `{ position, handleIn, handleOut }` with absolute handle positions. A lone handle is mirrored.
+
+## Common mistakes
+
+- **Expecting a solid Boolean.** These generators do not perform solid Boolean operations or provide a mesh editor. Build the pieces and place them with part matrices.
+- **A hole that touches the contour.** `extrude` throws `Every hole must lie strictly inside the contour.` Move the hole inward or make it smaller.
+- **Consecutive duplicate points.** A path or profile with two identical neighbors throws. Remove the repeat.
+- **Looking for caps on an open tube.** `tube` leaves its ends open. Use `curve`, which adds flat caps, when the shape must be closed.
+- **A folded lathe profile.** A profile that doubles back can intersect itself.
+- **Generating inside the render loop.** Build once, then share the geometry. The renderer does not take new geometry after construction.
+
+See also the [scene graph](https://github.com/codepawl/67.js/blob/main/docs/scene-graph.md), which supports hierarchy and pivots without changing mesh topology, and the [modeling demo](https://67js.codepawl.com/modeling.html), which combines these tools in a lantern scene.
diff --git a/docs/learn/renderer-reference.md b/docs/learn/renderer-reference.md
new file mode 100644
index 00000000..f69b7c09
--- /dev/null
+++ b/docs/learn/renderer-reference.md
@@ -0,0 +1,174 @@
+# Renderer reference
+
+`new Renderer67(canvas, parts, options)` owns GPU geometry, texture and target allocations. Construct a new renderer for a new graph, and call `dispose()` to release the resources it owns.
+
+## Constructor options
+
+| Option | Default | Purpose |
+| --- | --- | --- |
+| `batching` | true | Share instance batches by geometry and map identity |
+| `pixelRatio` | 1.5 | Render scale relative to CSS size. Not automatically devicePixelRatio |
+| `ground` | true | Add the studio floor at y 0.019, or 2% up from the lowest point of a scene it would bury more than a tenth of (small objects, scenes below y 0). Disable for worlds, 2D and assets |
+| `world` | false | Enable outdoor rendering and world clipping defaults |
+| `samples` | 4 | Requested MSAA count. Negotiated against hardware |
+| `hdr` | false | Request floating-point color targets |
+| `depth` | false | Keep a resolved depth texture across frames. [Volume fog](#local-lights-and-volume-fog) needs it |
+| (compact colour) | off | `useCompactColor(renderer)` from `@codepawlhq/67js/addons/compact-color` stores the HDR frame and its multisample colour as R11F_G11F_B10F instead of RGBA16F: 39.55 MB less at 1920 x 1080 with 4 samples (110.92 to 71.37 MB). The format has no alpha, so it needs `hdr: true` and an opaque canvas and throws otherwise; it also throws when the device does not support the renderer's sample count in that format. Mean FLIP against the default is 0.002 to 0.030 (median 0.021) over the 26 reference scenes. Without the call nothing changes. `renderer.memoryReport()` lists the formats |
+| `memoryBudgetMiB` | sized to the scene | Estimated render allocation budget. Without it the renderer takes room for the scene and one full frame: at least 256 MiB, at most 1024 MiB on a device reporting 8 GiB of memory or more (512 MiB otherwise). A scene over the budget fails with an error that names the bytes and the `memoryBudgetMiB` that fits. |
+| `environment` | {} | Sky, light and fog settings |
+| `shadowBounds` | {} | Custom extent, eye and target for shadow framing |
+| `benchmark` | false | Diagnostic flat shader. Not the appearance renderer |
+| `shading` | 'full' | `'light'` is a cheaper picture for weak machines and software rendering: at most 2 MSAA samples, one shadow fetch, a fitted BRDF, the sky reflected by its blurred irradiance, no second order irradiance. `'full'` is unchanged |
+
+## Try the options
+
+Change an option and the example builds a new renderer with it, then prints what the renderer reports: the render size it planned, the estimated memory, the negotiated MSAA count and whether HDR was granted. This is the information to read before you trust a frame.
+
+```js live poster=renderer-options
+import { Renderer67, box, sphere, torus } from '67js';
+
+function placeAt(x, y, z, size) {
+ return new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, size, 0, x, y, z, 1]);
+}
+
+const parts = [
+ { name: 'Block', geometry: box(0.08, 4), matrix: placeAt(-1.6, 0.5, 0, 1), material: { color: [0.3, 0.45, 0.7], metallic: 0, roughness: 0.5 } },
+ { name: 'Ball', geometry: sphere(48, 30), matrix: placeAt(0, 0.5, 0, 0.5), material: { color: [0.9, 0.62, 0.2], metallic: 0.8, roughness: 0.25 } },
+ { name: 'Ring', geometry: torus(0.14, 64, 20), matrix: placeAt(1.6, 0.6, 0, 0.5), material: { color: [0.8, 0.3, 0.3], metallic: 0, roughness: 0.4 } },
+];
+
+const canvas = document.querySelector('#scene');
+const settings = { ground: true, hdr: false, samples: 4, pixelRatio: 1.5, shading: 'full' };
+let renderer = null;
+
+function build() {
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, parts, { ...settings });
+ renderer.resize();
+ renderer.render({ eye: [0, 2.6, 6], target: [0, 0.4, 0], fov: 38 });
+ const plan = renderer.memoryPlan;
+ console.log(`options ${JSON.stringify(settings)}`);
+ console.log(` planned ${plan.width} x ${plan.height}, estimated ${(plan.estimatedBytes / 1048576).toFixed(1)} MiB of ${plan.memoryBudgetMiB} MiB, reduced ${plan.reduced}`);
+ console.log(` capabilities ${JSON.stringify(renderer.capabilities)}`);
+ console.log(` triangles ${renderer.triangles}, batches ${renderer.batches.length}, cpu ${renderer.cpuMilliseconds.toFixed(2)} ms`);
+}
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+function addRow(label, control) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ row.append(label, control);
+ panel.append(row);
+}
+function checkbox(key) {
+ const input = document.createElement('input');
+ input.type = 'checkbox';
+ input.checked = settings[key];
+ input.addEventListener('change', () => {
+ settings[key] = input.checked;
+ build();
+ });
+ return input;
+}
+function choice(key, values) {
+ const select = document.createElement('select');
+ for (const value of values) select.add(new Option(String(value), String(value)));
+ select.value = String(settings[key]);
+ select.addEventListener('change', () => {
+ settings[key] = typeof settings[key] === 'number' ? Number(select.value) : select.value;
+ build();
+ });
+ return select;
+}
+addRow('ground', checkbox('ground'));
+addRow('hdr', checkbox('hdr'));
+addRow('samples', choice('samples', [1, 2, 4]));
+addRow('pixelRatio', choice('pixelRatio', [0.5, 1, 1.5, 2]));
+addRow('shading', choice('shading', ['full', 'light']));
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ renderer.render({ eye: [0, 2.6, 6], target: [0, 0.4, 0], fov: 38 });
+}).observe(canvas);
+build();
+```
+
+Turn `ground` off and the studio floor and its shadows disappear. Lower `pixelRatio` and the planned width and height shrink with it, and so does the estimate. `hdr` asks for floating-point targets: read `capabilities.hdr`, because the request can be refused (`hdrFallbackReason` says why). `samples` is a request, and `capabilities.samples` is what the hardware gave. `shading: 'light'` caps MSAA at 2 samples.
+
+## Memory budget
+
+`memoryBudgetMiB` caps the estimate of the render allocation. When the frame at the requested size would pass the budget, the planner reduces the render width and height instead, and the plan says `reduced: true`. Drag the slider to see it happen.
+
+```js live poster=renderer-budget
+import { Renderer67, sphere } from '67js';
+
+const parts = [{
+ name: 'Ball',
+ geometry: sphere(48, 30),
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ material: { color: [0.3, 0.55, 0.8], metallic: 0.2, roughness: 0.35 },
+}];
+
+const canvas = document.querySelector('#scene');
+let renderer = null;
+const draw = () => renderer.render({ eye: [0, 1, 3.5], target: [0, 0, 0], fov: 38 });
+
+function build(budget) {
+ renderer?.dispose();
+ try {
+ renderer = new Renderer67(canvas, parts, { ground: false, hdr: true, pixelRatio: 2, samples: 4, memoryBudgetMiB: budget });
+ } catch (error) {
+ console.log(`budget ${budget} MiB: ${error.message}`);
+ return;
+ }
+ renderer.resize();
+ draw();
+ const plan = renderer.memoryPlan;
+ console.log(`budget ${budget} MiB: planned ${plan.width} x ${plan.height}, estimated ${(plan.estimatedBytes / 1048576).toFixed(1)} MiB, reduced ${plan.reduced}`);
+}
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 16, max: 512, step: 16, value: 256 });
+slider.addEventListener('change', () => build(Number(slider.value)));
+row.append('memoryBudgetMiB', slider);
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer?.resize();
+ if (renderer) draw();
+}).observe(canvas);
+build(256);
+```
+
+With a small budget the picture gets softer because the render targets are smaller than the canvas needs. A budget too small for even the scene's geometry throws an error that names the bytes and the `memoryBudgetMiB` that fits. Read `memoryPlan` for the actual `width`, `height`, `estimatedBytes` and `reduced` status.
+
+## Methods and fields
+
+`render(frame)` draws synchronously. `resize()` replans targets after CSS size or `pixelRatio` changes. `updateParts(parts, { shadows: true })` uploads changed matrices and materials using retained buffers. It does not add new part, geometry or texture identities.
+
+`updateTexture(descriptor, { image?, region? })` pushes new pixels into a texture the renderer already uploaded, such as a live canvas or a simulation. Import `@codepawlhq/67js/addons/texture-update` first. `docs/material-maps.md` has the options.
+
+Read these fields for diagnostics:
+
+| Field | Meaning |
+| --- | --- |
+| `memoryPlan` | Actual `width`, `height`, `estimatedBytes` and `reduced` status. |
+| `capabilities` | HDR and MSAA negotiation: `hdr`, `hdrRequested`, `hdrFallbackReason` and `samples`. |
+| `triangles` | Triangles of the part list. |
+| `batches.length` | Instance batches. Shared geometry keeps it small. |
+| `cpuMilliseconds` | CPU submission time of the last `render`. It is not GPU frame time. |
+| `diagnostics` | Warnings about the last frame, such as `coplanar-overlap` when [that check is installed](#contact-detection). |
+
+## Common mistakes
+
+- **Treating `pixelRatio` as `devicePixelRatio`.** The default is 1.5 and it is not copied from the device. Set it yourself.
+- **Reading `cpuMilliseconds` as frame time.** It measures CPU submission only.
+- **Asking for `hdr: true` and assuming it was granted.** Check `capabilities.hdr`. Features that need float targets, such as volume fog and environment maps, depend on it.
+- **Reusing a renderer for a new graph.** Construct a new renderer, and `dispose()` the old one so its GPU allocations are released.
+- **Expecting `updateParts` to add a part.** It uploads changed matrices and materials only.
+- **Leaving the studio floor on in a world or an asset view.** Pass `ground: false` for worlds, 2D and assets.
+- **Using `benchmark: true` to judge appearance.** It is a diagnostic flat shader, not the appearance renderer.
diff --git a/docs/learn/retained-surface-attachments.md b/docs/learn/retained-surface-attachments.md
new file mode 100644
index 00000000..19ce1587
--- /dev/null
+++ b/docs/learn/retained-surface-attachments.md
@@ -0,0 +1,133 @@
+# Retained surface attachments
+
+`createSurfaceAttachment` is introduced in `0.4.1`. Published npm `0.4.0` does not include this addon. It binds a rigid accessory to one triangle through world transforms, relative morphs and four-influence skinning. The accessory uses the attachment's retained world matrix. Its positive Z axis follows the posed triangle's geometric winding.
+
+The workflow has five steps:
+
+1. Choose an original triangle number and barycentric coordinates for the contact point.
+2. Bind the target with `createSurfaceAttachment` from `67js/addons/surface-attachment` using `0.4.1` or a current source build.
+3. Assign `attachment.matrix` to the accessory part before creating the renderer.
+4. Update the target matrix, morph weights and skin palette for the frame.
+5. Call `attachment.update()` before `renderer.updateParts()`.
+
+## A spike that follows a squashing, turning sphere
+
+A ray from the camera side picks the triangle: `createMeshQueryIndex(...).raycast` returns the `triangle` and `barycentric` that the binding takes. The target sphere has one relative morph target that flattens it. The first slider turns the target, and the second one squashes it. The spike follows both, because each frame calls `attachment.update()` and then `renderer.updateParts()`.
+
+```js live poster=attachment-spike
+import { Renderer67, sphere, box, createMorphPose } from '67js';
+import { createMeshQueryIndex } from '67js/addons/mesh-query';
+import { createSurfaceAttachment } from '67js/addons/surface-attachment';
+
+// A morph target that flattens the sphere to half its height. Deltas are relative to the base mesh.
+const base = sphere(48, 30);
+const flatten = 0.5;
+const positionDeltas = new Float32Array(base.positions.length);
+const normalDeltas = new Float32Array(base.normals.length);
+for (let offset = 0; offset < base.positions.length; offset += 3) {
+ positionDeltas[offset + 1] = base.positions[offset + 1] * (flatten - 1);
+ const x = base.positions[offset];
+ const y = base.positions[offset + 1] / flatten;
+ const z = base.positions[offset + 2];
+ const length = Math.hypot(x, y, z);
+ normalDeltas[offset] = x / length - base.normals[offset];
+ normalDeltas[offset + 1] = y / length - base.normals[offset + 1];
+ normalDeltas[offset + 2] = z / length - base.normals[offset + 2];
+}
+const targetGeometry = { ...base, morphTargets: [{ positions: positionDeltas, normals: normalDeltas }] };
+const morph = createMorphPose(1);
+const target = {
+ name: 'Ball',
+ geometry: targetGeometry,
+ morph,
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ material: { color: [0.25, 0.4, 0.6], metallic: 0, roughness: 0.5 },
+};
+
+// Pick the triangle with a static ray against the undeformed mesh.
+const index = createMeshQueryIndex(base);
+const hit = index.raycast(target.matrix, { origin: [0.45, 0.4, 4], direction: [0, 0, -1] });
+console.log(`ray hit: triangle ${hit.triangle}, barycentric ${hit.barycentric.map(value => value.toFixed(2)).join(', ')}`);
+const attachment = createSurfaceAttachment(target, { triangle: hit.triangle, barycentric: hit.barycentric, clearance: 0.003 });
+
+// The accessory's +Z axis points out of the surface, so the spike is long along Z and starts at the origin.
+const spikeGeometry = box(0, 1);
+const spikePositions = Float32Array.from(spikeGeometry.positions, (value, position) => [value * 0.12, value * 0.12, value * 0.4 + 0.2][position % 3]);
+const spike = {
+ name: 'Spike',
+ geometry: { ...spikeGeometry, positions: spikePositions },
+ matrix: attachment.matrix,
+ material: { color: [1, 0.55, 0.15], metallic: 0, roughness: 0.4 },
+};
+
+const canvas = document.querySelector('#scene');
+const renderer = new Renderer67(canvas, [target, spike], { ground: false, samples: 4, pixelRatio: 1.25 });
+const state = { turn: 0.4, squash: 0 };
+
+function update(logIt) {
+ const cosine = Math.cos(state.turn);
+ const sine = Math.sin(state.turn);
+ target.matrix.set([cosine, 0, -sine, 0, 0, 1, 0, 0, sine, 0, cosine, 0, 0, 0, 0, 1]);
+ morph.weights[0] = state.squash;
+ attachment.update();
+ renderer.updateParts([target, spike]);
+ renderer.render({ eye: [1.5, 1.6, 4.2], target: [0, 0.2, 0], fov: 40 });
+ if (logIt) {
+ const matrix = attachment.matrix;
+ console.log(`turn ${state.turn.toFixed(2)}, squash ${state.squash.toFixed(2)}: attachment at (${matrix[12].toFixed(3)}, ${matrix[13].toFixed(3)}, ${matrix[14].toFixed(3)}), Z axis (${matrix[8].toFixed(2)}, ${matrix[9].toFixed(2)}, ${matrix[10].toFixed(2)})`);
+ }
+}
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+function addSlider(label, key, minimum, maximum) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: minimum, max: maximum, step: 0.01, value: state[key] });
+ input.addEventListener('input', () => {
+ state[key] = Number(input.value);
+ update(false);
+ });
+ input.addEventListener('change', () => update(true));
+ row.append(label, input);
+ panel.append(row);
+}
+addSlider('Turn the ball', 'turn', -3.1, 3.1);
+addSlider('Squash', 'squash', 0, 1);
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ update(false);
+}).observe(canvas);
+update(true);
+```
+
+The spike stays on the same triangle at the same barycentric point through the turn and the squash. Its Z axis stays perpendicular to the posed triangle, so when the squash flattens the top of the sphere, the spike leans with the surface. Nothing rebuilds a BVH: `update()` samples the one selected triangle and returns the same `Float32Array(16)` every time.
+
+## Binding options
+
+| Option | Default | Contract |
+| --- | --- | --- |
+| `triangle` | Required | Integer from zero through the target triangle count minus one. It is an original index-buffer triangle number, as in a `createMeshQueryIndex` hit. |
+| `barycentric` | Required | Three nonnegative finite Float32-representable components that sum to one within `1e-6`. |
+| `clearance` | 0 | Nonnegative finite distance in world units along the geometric Z axis. |
+| `rotation` | 0 | Finite twist in radians about local positive Z. |
+| `maxVertices` | 250000 | Integer from 1 through 1000000. |
+| `maxTriangles` | 250000 | Integer from 1 through 1000000. |
+
+Unknown option fields throw. The target needs Float32 positions and matching unit normals, a `Uint32Array` triangle index buffer and a retained `Float32Array(16)` matrix that stays finite, affine and nonsingular. Morph targets need the matching retained morph pose, and skin channels need the matching retained joint palette.
+
+The frame follows the posed world triangle: local X runs along edge zero-to-one, local Z is the normalized cross product of edges zero-to-one and zero-to-two, and local Y completes the right-handed frame. The output matrix has unit scale and does not inherit shear or nonuniform scale of the target.
+
+Updates sample the selected triangle without rebuilding a BVH. Static raycast hits can supply binding coordinates, but query indices cannot raycast a visibly skinned or morphed surface, so pick the triangle on the static mesh first. The [attachment contract](https://github.com/codepawl/67.js/blob/main/docs/surface-attachment.md) defines retained identities, world-unit clearance and unsupported shader deformation.
+
+## Common mistakes
+
+- **Using the 0.4.0 npm package.** `createSurfaceAttachment` is introduced in `0.4.1`. Use that version or a current source build.
+- **Skipping `attachment.update()`.** The matrix only changes when you call it, and it must come after you change the target matrix, morph weights or skin palette and before `renderer.updateParts()`.
+- **Copying the matrix.** Assign `attachment.matrix` itself to the part. It is a retained buffer that the attachment owns, so a copy never moves.
+- **Replacing a retained identity.** The binding retains the target part, geometry, matrix, channel buffers and pose objects. Replace any of them and you must bind again, and after rebuilding or uploading edited geometry as well.
+- **Expecting more than one rigid frame.** An attachment positions one rigid frame. It does not conform the accessory footprint or prevent every intersection, and it does not follow shader displacement beyond morph and skin deformation.
+- **Raycasting the deformed mesh.** Raycast the static mesh and keep the `triangle` and `barycentric` it returns.
diff --git a/docs/learn/sculpt-brushes.md b/docs/learn/sculpt-brushes.md
new file mode 100644
index 00000000..63a9889e
--- /dev/null
+++ b/docs/learn/sculpt-brushes.md
@@ -0,0 +1,227 @@
+# Sculpt brushes
+
+Version `0.4.0` provides `sculptGeometry` through `67js/addons/sculpt`. It applies `inflate`, directional `displace` and `smooth` strokes to a copy of static indexed geometry. Stroke centers, radii and strengths use geometry-local units. The result preserves topology, UVs and colors, and rebuilds normals. The source geometry stays unchanged, and replaying the same strokes gives the same geometry.
+
+The workflow has four steps:
+
+1. Define bounded strokes on the undeformed mesh.
+2. Call `sculptGeometry` before creating the renderer.
+3. Inspect the resulting surface for folds or intersections.
+4. Rebuild surface patches and query indices after changing geometry.
+
+## One brush on a sphere
+
+The scene below sculpts a unit sphere with one stroke centered on the front. Choose the brush, and change its strength and radius. Each change builds the geometry again, and the log reports the vertex count, the time and how far the farthest vertex moved. Drag the picture to turn the sphere and look at the bump from the side.
+
+```js live poster=sculpt-one-brush
+import { Renderer67, sphere } from '67js';
+import { sculptGeometry } from '67js/addons/sculpt';
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const orbit = { yaw: 0.9, pitch: 0.25, distance: 4.2 };
+const brush = { type: 'inflate', strength: 0.3, radius: 0.7 };
+const original = sphere(64, 40);
+let renderer = null;
+
+function strokeFor() {
+ // A smooth stroke takes a blend from 0 to 1, so a negative strength would throw.
+ const strength = brush.type === 'smooth' ? Math.min(1, Math.max(0, brush.strength)) : brush.strength;
+ const stroke = { type: brush.type, center: [0, 0, 1], radius: brush.radius, strength };
+ if (brush.type === 'displace') stroke.direction = [0, 0, 1];
+ return stroke;
+}
+
+function farthestMove(result) {
+ let farthest = 0;
+ for (let offset = 0; offset < result.positions.length; offset += 3) {
+ const moved = Math.hypot(
+ result.positions[offset] - original.positions[offset],
+ result.positions[offset + 1] - original.positions[offset + 1],
+ result.positions[offset + 2] - original.positions[offset + 2],
+ );
+ farthest = Math.max(farthest, moved);
+ }
+ return farthest;
+}
+
+function build() {
+ const started = performance.now();
+ const geometry = sculptGeometry(original, [strokeFor()]);
+ const milliseconds = performance.now() - started;
+ const part = {
+ name: 'Clay',
+ geometry,
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ material: { color: [0.8, 0.55, 0.4], metallic: 0, roughness: 0.55 },
+ };
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, [part], { ground: false, samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+ console.log(`${brush.type}, strength ${brush.strength}, radius ${brush.radius}: ${geometry.positions.length / 3} vertices, ${milliseconds.toFixed(1)} ms, farthest move ${farthestMove(geometry).toFixed(3)}`);
+}
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0, 0.2], fov: 38 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(-1.4, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+function addRow(label, control) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ row.append(label, control);
+ panel.append(row);
+}
+const typeSelect = document.createElement('select');
+for (const type of ['inflate', 'displace', 'smooth']) typeSelect.add(new Option(type, type));
+typeSelect.addEventListener('change', () => {
+ brush.type = typeSelect.value;
+ build();
+});
+function slider(key, minimum, maximum, step) {
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: minimum, max: maximum, step, value: brush[key] });
+ input.addEventListener('change', () => {
+ brush[key] = Number(input.value);
+ build();
+ });
+ return input;
+}
+addRow('Brush', typeSelect);
+addRow('Strength', slider('strength', -0.6, 0.6, 0.05));
+addRow('Radius', slider('radius', 0.2, 1.5, 0.05));
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build();
+```
+
+`inflate` with a positive strength pushes the surface out along the original normals, and a negative strength dents it. `displace` moves the same vertices along one fixed direction, here `[0, 0, 1]`, so the bump has a flat push where `inflate` follows the sphere. `smooth` has little to even out on a sphere, so it changes this mesh only a little: it pays off on a surface that was already sculpted.
+
+The brush falls off smoothly. For a normalized distance `t = distance / radius`, the influence is `1 - 10t³ + 15t⁴ - 6t⁵` inside the brush and zero outside. Its first and second derivatives vanish at the center and at the boundary, so no ridge forms where the brush ends.
+
+## Strokes build on each other, and smoothing shrinks
+
+Each stroke reads the positions that the previous strokes produced. This example raises a bump, then applies a `smooth` stroke over it. The slider sets the smooth strength, from 0 to 1. The log shows that smoothing also pulls the whole patch inward, because Laplacian smoothing does not preserve volume.
+
+```js live poster=sculpt-smooth-shrink
+import { Renderer67, sphere } from '67js';
+import { sculptGeometry } from '67js/addons/sculpt';
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const orbit = { yaw: 0.9, pitch: 0.2, distance: 4.2 };
+const original = sphere(64, 40);
+let renderer = null;
+
+function meanRadius(geometry) {
+ let total = 0;
+ const count = geometry.positions.length / 3;
+ for (let vertex = 0; vertex < count; vertex++) {
+ total += Math.hypot(geometry.positions[vertex * 3], geometry.positions[vertex * 3 + 1], geometry.positions[vertex * 3 + 2]);
+ }
+ return total / count;
+}
+
+function build(smoothStrength) {
+ const strokes = [
+ { type: 'inflate', center: [0.3, 0.2, 0.95], radius: 0.5, strength: 0.25 },
+ { type: 'displace', center: [-0.4, 0.3, 0.9], radius: 0.4, strength: -0.15, direction: [0, 0, 1] },
+ { type: 'smooth', center: [0, 0.2, 0.95], radius: 0.9, strength: smoothStrength },
+ ];
+ const geometry = sculptGeometry(original, strokes);
+ const beforeSmoothing = sculptGeometry(original, strokes.slice(0, 2));
+ const part = {
+ name: 'Clay',
+ geometry,
+ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
+ material: { color: [0.8, 0.55, 0.4], metallic: 0, roughness: 0.55 },
+ };
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, [part], { ground: false, samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+ console.log(`smooth strength ${smoothStrength.toFixed(2)}: mean radius ${meanRadius(beforeSmoothing).toFixed(4)} before the smooth stroke, ${meanRadius(geometry).toFixed(4)} after`);
+}
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0, 0.2], fov: 38 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(-1.4, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+const row = document.createElement('label');
+row.style.cssText = 'position:fixed;left:12px;bottom:12px;display:flex;gap:8px;align-items:center;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+const slider = document.createElement('input');
+Object.assign(slider, { type: 'range', min: 0, max: 1, step: 0.05, value: 0.5 });
+slider.addEventListener('change', () => build(Number(slider.value)));
+row.append('Smooth strength', slider);
+document.body.append(row);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build(0.5);
+```
+
+At strength 0 the bump and the dent stay as sculpted. At 1 each vertex moves all the way to the mean of its connected neighbors, which rounds the features off and lowers the mean radius. The smooth stroke is one Jacobi step: it reads a fixed snapshot of positions, so the order of vertices does not matter.
+
+## Seams and normals
+
+Vertices with exactly equal input Float32 positions move together, which keeps duplicated UV seams closed. Nearly coincident positions are not welded, and separate shells at the same position are treated as one group. Cancelling normals at coincident positions throw rather than choosing a direction.
+
+Normals are rebuilt from area-weighted triangle cross products. UV coordinates, colors and topology are preserved, so stretching the surface also stretches an existing texture.
+
+## Options
+
+| Stroke field | Meaning |
+| --- | --- |
+| `type` | `'inflate'`, `'displace'` or `'smooth'`. |
+| `center` | Three components in geometry-local units. |
+| `radius` | Brush radius, positive at Float32 precision. |
+| `strength` | Signed distance for `inflate` and `displace`. For `smooth`, a blend from 0 to 1. |
+| `direction` | `displace` only: a nonzero vector, normalized by the addon. |
+
+| Limit | Default | Ceiling |
+| --- | --- | --- |
+| `maxVertices` | 250000 | 1000000 |
+| `maxTriangles` | 500000 | 2000000 |
+| `maxStrokes` | 256 | 4096 |
+| `maxVertexVisits` | 20000000 | 100000000 |
+
+`maxVertexVisits` bounds the vertex count multiplied by the stroke count. Each limit is checked before the geometry is copied. These limits bound inputs and work, not total browser memory. An empty or zero-strength stroke list returns an independent copy.
+
+The [sculpt contract](https://github.com/codepawl/67.js/blob/main/docs/sculpt.md) defines brush strength, seam handling and work limits.
+
+## Common mistakes
+
+- **Sculpting every frame.** Renderer geometry buffers are static, so rebuilding the mesh each frame costs CPU time and new GPU uploads. Build once, or turn compatible deformations into [relative morph targets](https://github.com/codepawl/67.js/blob/main/docs/morph-targets.md) and animate their weights.
+- **A negative or large `smooth` strength.** The blend must be within 0 and 1, otherwise the call throws.
+- **A stroke too strong for the mesh.** Strong strokes can fold or intersect surfaces, and sculpting does not detect that. A triangle that collapses throws `Sculpt stroke collapsed a triangle at Float32 precision. Reduce strength.`
+- **Expecting a volume-preserving smooth.** Smoothing can shrink volume and soften boundaries, as the second example shows.
+- **Sculpting a skinned or morphed mesh.** Sculpting rejects skin and morph channels, and it does not remesh, update rig weights or provide a brush editor.
+- **Forgetting dependent data.** Rebuild surface patches and query indices after the geometry changes.
diff --git a/docs/learn/shrinkwrap-and-surface-patches.md b/docs/learn/shrinkwrap-and-surface-patches.md
new file mode 100644
index 00000000..19ffcb84
--- /dev/null
+++ b/docs/learn/shrinkwrap-and-surface-patches.md
@@ -0,0 +1,275 @@
+# Shrinkwrap and surface patches
+
+Two static tools fit one mesh to another. `shrinkwrapGeometry` from `67js/addons/shrinkwrap` moves the vertices of a source mesh onto a target surface and keeps the source topology, UVs and colors. `createSurfacePatch` from `67js/addons/surface` clips the target's own triangles into a small overlay with its own UVs and material. Both are construction-time operations: they do not follow skin or morph deformation.
+
+## Shrinkwrap a grid onto a sphere
+
+`shrinkwrapGeometry(source, target, options)` returns new static geometry in target-local coordinates. `nearest` mode chooses the closest surface point. `project` mode casts along a target-local direction. The workflow has five steps:
+
+1. Define `sourceToTarget` to map source-local positions into target-local coordinates.
+2. Choose `nearest` or `project` mode and a bounded `maxDistance`.
+3. Set `clearance` and an explicit `onMiss` policy.
+4. Use the returned geometry with the target part's retained matrix.
+5. Inspect `stats` and the resulting mesh before rendering.
+
+The example wraps a flat grid onto a sphere. Pick the mode, change the clearance, and make the grid bigger than the sphere to see misses. The log prints `stats` for every build, and the error text if a build throws.
+
+```js live poster=shrinkwrap-grid
+import { Renderer67, sphere } from '67js';
+import { shrinkwrapGeometry } from '67js/addons/shrinkwrap';
+
+// A flat grid in the XY plane at height z, facing +Z.
+function grid(halfSize, divisions, z) {
+ const side = divisions + 1;
+ const positions = new Float32Array(side * side * 3);
+ const normals = new Float32Array(side * side * 3);
+ const uvs = new Float32Array(side * side * 2);
+ const indices = [];
+ for (let row = 0; row < side; row++) {
+ for (let column = 0; column < side; column++) {
+ const vertex = row * side + column;
+ positions.set([(column / divisions * 2 - 1) * halfSize, (row / divisions * 2 - 1) * halfSize, z], vertex * 3);
+ normals.set([0, 0, 1], vertex * 3);
+ uvs.set([column / divisions, row / divisions], vertex * 2);
+ if (row < divisions && column < divisions) {
+ indices.push(vertex, vertex + 1, vertex + side, vertex + 1, vertex + side + 1, vertex + side);
+ }
+ }
+ }
+ return { positions, normals, uvs, indices: new Uint32Array(indices) };
+}
+
+const identity = () => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+const target = { name: 'Ball', geometry: sphere(64, 40), matrix: identity(), material: { color: [0.25, 0.4, 0.6], metallic: 0, roughness: 0.5 } };
+const settings = { mode: 'project', clearance: 0.02, halfSize: 0.6, height: 1.1 };
+
+const canvas = document.querySelector('#scene');
+canvas.style.touchAction = 'none';
+const orbit = { yaw: 0.6, pitch: 0.35, distance: 4.5 };
+let renderer = null;
+
+function build() {
+ const source = grid(settings.halfSize, 32, settings.height);
+ const parts = [target];
+ try {
+ const started = performance.now();
+ const { geometry, stats } = shrinkwrapGeometry(source, target.geometry, {
+ mode: settings.mode,
+ direction: settings.mode === 'project' ? [0, 0, -1] : undefined,
+ clearance: settings.clearance,
+ onMiss: 'keep',
+ });
+ parts.push({ name: 'Wrap', geometry, matrix: target.matrix, material: { color: [0.95, 0.7, 0.2], metallic: 0, roughness: 0.45 } });
+ console.log(`${settings.mode}, clearance ${settings.clearance}, grid ${(settings.halfSize * 2).toFixed(1)} wide at height ${settings.height}: ${JSON.stringify(stats)}, ${(performance.now() - started).toFixed(0)} ms`);
+ } catch (error) {
+ console.log(`${settings.mode}: ${error.message}`);
+ }
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, parts, { ground: false, samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+}
+
+function draw() {
+ const flat = Math.cos(orbit.pitch) * orbit.distance;
+ const eye = [Math.sin(orbit.yaw) * flat, Math.sin(orbit.pitch) * orbit.distance, Math.cos(orbit.yaw) * flat];
+ renderer.render({ eye, target: [0, 0, 0.4], fov: 38 });
+}
+
+canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));
+canvas.addEventListener('pointermove', event => {
+ if (!canvas.hasPointerCapture(event.pointerId)) return;
+ orbit.yaw -= event.movementX * 0.01;
+ orbit.pitch = Math.min(1.4, Math.max(-1.4, orbit.pitch + event.movementY * 0.01));
+ draw();
+});
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+function addRow(label, control) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ row.append(label, control);
+ panel.append(row);
+}
+const modeSelect = document.createElement('select');
+for (const mode of ['project', 'nearest']) modeSelect.add(new Option(mode, mode));
+modeSelect.addEventListener('change', () => {
+ settings.mode = modeSelect.value;
+ build();
+});
+function slider(key, minimum, maximum, step) {
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: minimum, max: maximum, step, value: settings[key] });
+ input.addEventListener('change', () => {
+ settings[key] = Number(input.value);
+ build();
+ });
+ return input;
+}
+addRow('Mode', modeSelect);
+addRow('Clearance', slider('clearance', 0, 0.2, 0.01));
+addRow('Grid half size', slider('halfSize', 0.4, 1.4, 0.05));
+addRow('Grid height', slider('height', 1.05, 2.5, 0.05));
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build();
+```
+
+In `project` mode every grid vertex slides straight down the -Z axis until it hits the sphere, so the grid keeps its footprint like a cloth dropped from above. In `nearest` mode each vertex goes to the closest point on the surface, so the grid draws toward the center and its corners crowd together. Grow the grid until its corners pass the sphere's silhouette (half size above about 0.7) in project mode and the vertices outside it miss: `onMiss: 'keep'` leaves them at their transformed source position, and `stats.missedVertices` counts them. With the default `onMiss: 'error'` the same call would throw.
+
+`clearance` offsets each matched vertex along the geometric normal of its target triangle, so the wrap floats just above the sphere instead of sharing its surface.
+
+Raise the grid in `nearest` mode and the build fails: the log prints `Shrinkwrap collapses a triangle within Float32 precision`. From far away, all the nearest points crowd onto a small part of the sphere, and neighbouring vertices land on the same spot. `project` has no such problem, because it keeps the footprint. Bring the grid close to the sphere or use `project`.
+
+The return value is `{ geometry, stats }`. `stats` has `queriedVertices`, `matchedVertices`, `missedVertices` and `triangleTests`. The first three count unique exact-position groups, so duplicate seam vertices count once.
+
+### Shrinkwrap options
+
+| Option | Default | Contract |
+| --- | --- | --- |
+| `mode` | `'nearest'` | `'nearest'` or `'project'` |
+| `sourceToTarget` | Identity | Nonsingular affine matrix, 16 column-major components |
+| `direction` | None | Required only for project mode, in target-local coordinates |
+| `maxDistance` | Infinity | Nonnegative Float32-representable number or Infinity |
+| `clearance` | 0 | Nonnegative finite Float32-representable number |
+| `onMiss` | `'error'` | `'error'` or `'keep'` |
+| `maxVertices` | 250000 | Integer from 1 through 1000000, applied to both meshes |
+| `maxTriangles` | 250000 | Integer from 1 through 1000000, applied to both meshes |
+| `maxQueries` | 250000 | Integer from 1 through 1000000 |
+| `maxTriangleTests` | 20000000 | Total callback budget from 1 through 100000000 |
+| `memoryBudgetMiB` | 64 | Target index allocation estimate, greater than 0 through 1024 |
+
+Use the output with the target part's retained matrix. The [shrinkwrap contract](https://github.com/codepawl/67.js/blob/main/docs/shrinkwrap.md) defines local distances, work budgets and miss handling. Moving the shared matrix moves the wrapped geometry rigidly without rebuilding it, but changing the target's vertices needs another shrinkwrap. The mode distinction follows Blender's [Nearest Surface Point and Project methods](https://docs.blender.org/manual/en/latest/modeling/modifiers/deform/shrinkwrap.html).
+
+`createMeshQueryIndex` also gives target-local `nearest(point, options)` and `project(ray)` helpers. Both return `{ hit, triangleTests }`, where `hit` is `null` or `{ point, distance, triangle, barycentric, normal }`.
+
+### Animate the result once it is built
+
+The wrapping runs before the renderer exists. When the source and the output share a coordinate frame and topology, their difference becomes a relative GPU morph target, so no BVH is rebuilt and no vertex is wrapped on each frame.
+
+```js
+import { createMorphPose } from '67js';
+import { shrinkwrapGeometry } from '67js/addons/shrinkwrap';
+
+const wrapped = shrinkwrapGeometry(source, target, { mode: 'project', direction: [0, 0, -1] }).geometry;
+const animatedGeometry = {
+ ...source,
+ morphTargets: [{
+ positions: Float32Array.from(source.positions, (value, index) => wrapped.positions[index] - value),
+ normals: Float32Array.from(source.normals, (value, index) => wrapped.normals[index] - value),
+ }],
+};
+const morph = createMorphPose(1);
+// Assign animatedGeometry and morph to the part before constructing Renderer67.
+// Update morph.weights[0] between zero and one before renderer.updateParts(parts).
+```
+
+Intermediate shapes need their own collision checks. Safe endpoints do not prove that an interpolated mesh avoids every obstacle.
+
+## Surface patches
+
+`createSurfacePatch(targetPart, options)` clips target triangles into a standalone patch that follows their curved shape. It generates new projector UVs and normalized interpolated normals, and it copies no colors, original UVs, maps or material. The patch uses its own material. Every option is in target-local coordinates.
+
+The slider walks a badge around the equator of a sphere. For each position the projector is rotated so that its +Z axis faces outward from the sphere, and the patch is built again. The log prints its size.
+
+```js live poster=surface-badge
+import { Renderer67, sphere } from '67js';
+import { createSurfacePatch } from '67js/addons/surface';
+
+const matrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+const target = { name: 'Shell', geometry: sphere(64, 40), matrix, material: { color: [0.03, 0.2, 0.3], metallic: 0.2, roughness: 0.4 } };
+const canvas = document.querySelector('#scene');
+const settings = { angle: 0.6, width: 0.6 };
+let renderer = null;
+
+function build() {
+ // The surface point at this angle around Y, and the projector rotation that makes +Z face away from the sphere.
+ const position = [Math.sin(settings.angle), 0, Math.cos(settings.angle)];
+ const started = performance.now();
+ const geometry = createSurfacePatch(target, {
+ position,
+ rotation: [0, settings.angle, 0],
+ size: [settings.width, settings.width * 0.66, 0.4],
+ clearance: 0.001,
+ });
+ const badge = { name: 'Badge', geometry, matrix: target.matrix, material: { color: [1, 0.2, 0.02], metallic: 0, roughness: 0.5 } };
+ renderer?.dispose();
+ renderer = new Renderer67(canvas, [target, badge], { ground: false, samples: 4, pixelRatio: 1.25 });
+ renderer.resize();
+ draw();
+ console.log(`angle ${settings.angle.toFixed(2)}, width ${settings.width.toFixed(2)}: ${geometry.positions.length / 3} vertices, ${geometry.indices.length / 3} triangles, ${(performance.now() - started).toFixed(1)} ms`);
+}
+
+function draw() {
+ renderer.render({ eye: [0, 1.2, 4.2], target: [0, 0, 0.3], fov: 38 });
+}
+
+const panel = document.createElement('div');
+panel.style.cssText = 'position:fixed;left:12px;bottom:12px;display:grid;gap:6px;padding:8px 12px;border-radius:8px;background:#000b;color:#eee;font:12px system-ui';
+function addSlider(label, key, minimum, maximum, step) {
+ const row = document.createElement('label');
+ row.style.cssText = 'display:flex;gap:8px;align-items:center;justify-content:space-between';
+ const input = document.createElement('input');
+ Object.assign(input, { type: 'range', min: minimum, max: maximum, step, value: settings[key] });
+ input.addEventListener('change', () => {
+ settings[key] = Number(input.value);
+ build();
+ });
+ row.append(label, input);
+ panel.append(row);
+}
+addSlider('Angle around the sphere', 'angle', -1.2, 1.2, 0.05);
+addSlider('Badge width', 'width', 0.2, 1.2, 0.05);
+document.body.append(panel);
+
+new ResizeObserver(() => {
+ renderer.resize();
+ draw();
+}).observe(canvas);
+build();
+```
+
+The patch sits `clearance` above the sphere along the interpolated surface normals, so it does not fight the sphere's own surface for depth. Sharing the retained `target.matrix` on the patch part keeps both objects together through rigid translation, rotation, affine scale and shear. Replacing only the target matrix breaks that relationship.
+
+Back-facing triangles are excluded, but a deep projector can still catch several outward-facing layers. Keep the box depth (the third value of `size`) and `maxAngle` narrow enough to select the surface you mean. A projector that crosses a sharp corner can distort the UVs.
+
+### Surface patch options
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `position` | `[0, 0, 0]` | Center of the clipping box. |
+| `rotation` | `[0, 0, 0]` | XYZ Euler radians. Projector +Z faces outward from the target. |
+| `size` | `[1, 1, 1]` | Positive width, height and depth of the clipping box. |
+| `clearance` | `0.001` | Nonnegative local offset along interpolated surface normals. |
+| `maxAngle` | `Math.PI / 2` | Maximum angle between geometric face normal and projector +Z. Must exceed zero. |
+| `maxVertices` | `250000` | Conservative clipping reservation and output vertex cap. |
+| `maxTriangles` | `250000` | Input triangle cap. |
+
+Zero clearance deliberately creates a coplanar patch and can produce z-fighting. Constant local clearance does not give a constant world gap under nonuniform scale. The addon checks the rounded displacement against each clipped Float32 triangle, so vanishing gaps, reversed winding and a fully collapsed output throw. This checks local patch construction, not collision against other scene objects.
+
+Clipping runs while you build the scene, and the patch is reused every frame without clipping again. Skin, morph, assembly and procedural target materials are rejected, because their visible surfaces differ from the static target geometry. Rebuild the patch after static sculpting. The [surface patch contract](https://github.com/codepawl/67.js/blob/main/docs/surface.md) defines projector orientation, depth and local clearance.
+
+### Three different overlap problems
+
+| Problem | Required response |
+| --- | --- |
+| Nearly coplanar surfaces flicker | Geometric clearance or scoped render depth bias. A patch supplies geometric clearance. |
+| A rigid accessory intersects a curved shell | Adjust the contact transform or deform its footprint. A flat rigid panel cannot fit an arbitrary curved surface completely. |
+| Two closed meshes penetrate or one contains the other | Mesh collision queries and resolution, see [contact detection](#contact-detection). |
+
+Antialiasing, material colors and shadow bias do not repair mesh penetration. A patch is a surface overlay, not a whole-object shrinkwrap.
+
+## Common mistakes
+
+- **Nearest mode on a coarse convex target.** Several source vertices can land on the same edge or vertex and collapse triangles, and the call throws. Refine the target, or use `project` with a suitable footprint.
+- **Passing `direction` in nearest mode.** `direction` applies only to project mode, and the call throws otherwise.
+- **Leaving `onMiss` at its default.** One missing vertex throws with `'error'`. Pass `'keep'` and read `stats.missedVertices` when misses are expected.
+- **Long source edges.** Clearance at matched vertices does not prove clearance across the connecting triangle, and a long edge can bridge a concave target or a sharp crease. Increase the source resolution and inspect the result.
+- **Using the wrapped geometry with another matrix.** The output is in target-local coordinates. Give the part the target part's matrix.
+- **Patch materials copied from the target.** The patch has no colors, maps or material of the target. Give it its own.
+- **Expecting a patch to follow a deformed surface.** Patches and shrinkwrap are static. They do not follow skin or morph deformation, and a projection does not guarantee clearance across the complete accessory surface.
diff --git a/public/docs-media/attachment-spike.webp b/public/docs-media/attachment-spike.webp
new file mode 100644
index 00000000..15ff537d
Binary files /dev/null and b/public/docs-media/attachment-spike.webp differ
diff --git a/public/docs-media/contact-coplanar.webp b/public/docs-media/contact-coplanar.webp
new file mode 100644
index 00000000..4c2cef8f
Binary files /dev/null and b/public/docs-media/contact-coplanar.webp differ
diff --git a/public/docs-media/contact-raycast.webp b/public/docs-media/contact-raycast.webp
new file mode 100644
index 00000000..a54da86c
Binary files /dev/null and b/public/docs-media/contact-raycast.webp differ
diff --git a/public/docs-media/contact-solids.webp b/public/docs-media/contact-solids.webp
new file mode 100644
index 00000000..c5be3c1e
Binary files /dev/null and b/public/docs-media/contact-solids.webp differ
diff --git a/public/docs-media/fog-volume.webp b/public/docs-media/fog-volume.webp
new file mode 100644
index 00000000..bab05e33
Binary files /dev/null and b/public/docs-media/fog-volume.webp differ
diff --git a/public/docs-media/hdr-compare.webp b/public/docs-media/hdr-compare.webp
new file mode 100644
index 00000000..78ca607a
Binary files /dev/null and b/public/docs-media/hdr-compare.webp differ
diff --git a/public/docs-media/hdr-rotate.webp b/public/docs-media/hdr-rotate.webp
new file mode 100644
index 00000000..be1007df
Binary files /dev/null and b/public/docs-media/hdr-rotate.webp differ
diff --git a/public/docs-media/lights-point.webp b/public/docs-media/lights-point.webp
new file mode 100644
index 00000000..16ba184d
Binary files /dev/null and b/public/docs-media/lights-point.webp differ
diff --git a/public/docs-media/modeling-lathe.webp b/public/docs-media/modeling-lathe.webp
new file mode 100644
index 00000000..62bf054d
Binary files /dev/null and b/public/docs-media/modeling-lathe.webp differ
diff --git a/public/docs-media/modeling-shapes.webp b/public/docs-media/modeling-shapes.webp
new file mode 100644
index 00000000..bf7d6175
Binary files /dev/null and b/public/docs-media/modeling-shapes.webp differ
diff --git a/public/docs-media/parts-primitive-detail.webp b/public/docs-media/parts-primitive-detail.webp
new file mode 100644
index 00000000..103997ba
Binary files /dev/null and b/public/docs-media/parts-primitive-detail.webp differ
diff --git a/public/docs-media/parts-shared-geometry.webp b/public/docs-media/parts-shared-geometry.webp
new file mode 100644
index 00000000..5a38638e
Binary files /dev/null and b/public/docs-media/parts-shared-geometry.webp differ
diff --git a/public/docs-media/renderer-budget.webp b/public/docs-media/renderer-budget.webp
new file mode 100644
index 00000000..bce7b7cb
Binary files /dev/null and b/public/docs-media/renderer-budget.webp differ
diff --git a/public/docs-media/renderer-options.webp b/public/docs-media/renderer-options.webp
new file mode 100644
index 00000000..3738cf3d
Binary files /dev/null and b/public/docs-media/renderer-options.webp differ
diff --git a/public/docs-media/sculpt-one-brush.webp b/public/docs-media/sculpt-one-brush.webp
new file mode 100644
index 00000000..a51f6bb2
Binary files /dev/null and b/public/docs-media/sculpt-one-brush.webp differ
diff --git a/public/docs-media/sculpt-smooth-shrink.webp b/public/docs-media/sculpt-smooth-shrink.webp
new file mode 100644
index 00000000..d9057853
Binary files /dev/null and b/public/docs-media/sculpt-smooth-shrink.webp differ
diff --git a/public/docs-media/shrinkwrap-grid.webp b/public/docs-media/shrinkwrap-grid.webp
new file mode 100644
index 00000000..06eab638
Binary files /dev/null and b/public/docs-media/shrinkwrap-grid.webp differ
diff --git a/public/docs-media/surface-badge.webp b/public/docs-media/surface-badge.webp
new file mode 100644
index 00000000..968ccc91
Binary files /dev/null and b/public/docs-media/surface-badge.webp differ