3D engine that AI agents drive
Docs: live examples call the real addons
Nguyen Xuan An24ca03ce7c2d
diff --git a/changes/docs-live-real-addons.md b/changes/docs-live-real-addons.mdnew file mode 100644index 00000000..fa602668--- /dev/null+++ b/changes/docs-live-real-addons.md@@ -0,0 +1 @@+- The live examples on the terrain, trees and grass, grass fields, wheeled vehicles, baked liquid, humanoid crowds and recorded physics learn pages now call the real addons (`createTerrain`, `scatterVegetation` with `selectLevels`, `createGrass`, `createVehicleRig` with `driveAlongPath`, `loadSpumeCache` with `createSpumePlayer`, `createCrowd` with `mapHumanoidBones`, `createPhysicsScene`) instead of core-only stand-ins, and print real counts, heights and timings to the console panel. Only the calls that need CC0 texture files or a rigged character stay as plain code blocks. The `window.parent` typed array line is gone from every live example, since the frame supplies those constructors.diff --git a/docs/learn/animation-curves-and-mixing.md b/docs/learn/animation-curves-and-mixing.mdindex 0d5957a1..f8fae346 100644--- a/docs/learn/animation-curves-and-mixing.md+++ b/docs/learn/animation-curves-and-mixing.md@@ -9,8 +9,6 @@ Four balls travel the same distance in two seconds. From the back: `LINEAR`, `ST```js live poster=animation-curvesimport { Renderer67, sphere, createAnimationClip, createAnimationPlayer, sampleAnimationClip } from '67js';-// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.-const { Float32Array, Uint16Array, Uint32Array } = window.parent;const modes = [{ name: 'LINEAR', interpolation: 'LINEAR' },@@ -103,8 +101,6 @@ A keyframe on a `LINEAR` or `SMOOTH` track can carry `easing`. The value is `lin```js live poster=animation-mixerimport { Renderer67, box, createAnimationClip, createAnimationMixer } from '67js';-// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.-const { Float32Array, Uint16Array, Uint32Array } = window.parent;const rotation = angle => [0, Math.sin(angle / 2), 0, Math.cos(angle / 2)];const part = { name: 'Blade', geometry: box(0.05, 4), matrix: new Float32Array([1.6, 0, 0, 0, 0, 0.25, 0, 0, 0, 0, 0.4, 0, 0, 0.6, 0, 1]), material: { color: [0.9, 0.5, 0.25], metallic: 0, roughness: 0.5 } };diff --git a/docs/learn/baked-liquid.md b/docs/learn/baked-liquid.mdindex d2268fa7..1a9628b4 100644--- a/docs/learn/baked-liquid.md+++ b/docs/learn/baked-liquid.md@@ -4,111 +4,118 @@## Cache, frame, time-The docs run with the core module only and cannot load a Spume cache, so this example bakes a tiny cache itself, packs every frame into int16 (the way Spume stores frames), and plays it back with a `partsAt(seconds)` function shaped like the addon's. Drag the slider to scrub. Tick Loop to wrap time instead of holding the last frame. The console prints the cache size, the frame index for a time and how long each `replaceParts` took.+The docs host has no baked cache to serve, so the example writes a small one in memory in Spume's own file format: a `meta.json` and one `frame_NNNN.glb` per frame, with positions packed as int16 over each frame's own bounding box and normals as int8. It then loads that cache with `loadSpumeCache` through a reader function, which is the same call that loads a folder from a server, and plays it with `createSpumePlayer`. The cache is a rippling water surface over a stone slab. Drag the slider to scrub. Tick Loop to wrap time instead of holding the last frame. The console prints the cache size, the frame index for a time and how long each `replaceParts` took.```js live poster=spume-playback-import { Renderer67, sphere, box } from '67js';+import { Renderer67, box } from '67js';+import { loadSpumeCache, createSpumePlayer } from '67js/addons/spume';-function random(seed) {- let value = seed >>> 0;- return () => {- value = (value * 1664525 + 1013904223) >>> 0;- return value / 4294967296;- };+// Bake: a ripple that spreads from the middle. In the real workflow the Spume solver does this offline.+const fps = 20;+const frameCount = 40;+const gridSide = 25;+const halfWidth = 3;+function surfaceHeight(x, z, seconds) {+ const distance = Math.hypot(x, z);+ return 0.22 * Math.sin(2.4 * distance - 5 * seconds) / (1 + 0.6 * distance) + 0.05 * Math.sin(3 * x + 2 * seconds);}--// Bake: droplets leave a spout and bounce on the floor. Done once, offline in the real workflow.-const fps = 30;-const frameCount = 75;-const dropletCount = 180;-const next = random(5);-const droplets = Array.from({ length: dropletCount }, () => ({- start: next() * 1.2,- velocity: [1.5 + next() * 2.2, 2.2 + next() * 2, (next() - 0.5) * 1.6],- position: null,- speed: null,-}));-const baked = [];-for (let frame = 0; frame < frameCount; frame++) {- const time = frame / fps;- const positions = new Float32Array(dropletCount * 3);- droplets.forEach((droplet, index) => {- const age = Math.max(0, time - droplet.start);- let y = 1.4 + droplet.velocity[1] * age - 4.9 * age * age;- let bounces = 0;- let vy = droplet.velocity[1] - 9.8 * age;- while (y < 0.05 && bounces < 3) { y = 0.05 - (y - 0.05) * 0.45; vy = -vy * 0.45; bounces++; }- const x = -3 + droplet.velocity[0] * age;- const z = droplet.velocity[2] * age;- positions.set(age === 0 ? [-3, 1.4, 0] : [x, Math.max(0.05, y), z], index * 3);- });- baked.push(positions);-}--// Pack each frame over its own min..max box into int16, like Spume's frame files.-function pack(positions) {- const low = [Infinity, Infinity, Infinity];- const high = [-Infinity, -Infinity, -Infinity];- for (let index = 0; index < positions.length; index++) {- low[index % 3] = Math.min(low[index % 3], positions[index]);- high[index % 3] = Math.max(high[index % 3], positions[index]);+function bakeFrame(seconds) {+ const positions = [];+ const normals = [];+ const step = 0.01;+ for (let row = 0; row < gridSide; row++) {+ for (let column = 0; column < gridSide; column++) {+ const x = -halfWidth + column / (gridSide - 1) * halfWidth * 2;+ const z = -halfWidth + row / (gridSide - 1) * halfWidth * 2;+ positions.push(x, 0.5 + surfaceHeight(x, z, seconds), z);+ const slopeX = (surfaceHeight(x + step, z, seconds) - surfaceHeight(x - step, z, seconds)) / (2 * step);+ const slopeZ = (surfaceHeight(x, z + step, seconds) - surfaceHeight(x, z - step, seconds)) / (2 * step);+ const length = Math.hypot(slopeX, 1, slopeZ);+ normals.push(-slopeX / length, 1 / length, -slopeZ / length);+ }}- const packed = new Int16Array(positions.length);- for (let index = 0; index < positions.length; index++) {- const span = high[index % 3] - low[index % 3] || 1;- packed[index] = Math.round(((positions[index] - low[index % 3]) / span - 0.5) * 65534);+ const indices = [];+ for (let row = 0; row < gridSide - 1; row++) {+ for (let column = 0; column < gridSide - 1; column++) {+ const corner = row * gridSide + column;+ indices.push(corner, corner + gridSide, corner + 1, corner + 1, corner + gridSide, corner + gridSide + 1);+ }}- return { packed, low, high };+ return { positions, normals, indices };}-function unpack({ packed, low, high }) {- const positions = new Float32Array(packed.length);- for (let index = 0; index < packed.length; index++) positions[index] = low[index % 3] + (packed[index] / 65534 + 0.5) * (high[index % 3] - low[index % 3]);- return positions;++// Pack one frame like Spume's export: int16 positions over the frame's own min..max box, int8 normals, a binary glTF.+function padToFour(bytes, fill = 0) {+ const padded = new Uint8Array(Math.ceil(bytes.byteLength / 4) * 4).fill(fill);+ padded.set(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength));+ return padded;}-const cache = baked.map(pack);-const packedBytes = cache.reduce((sum, frame) => sum + frame.packed.byteLength, 0);-const floatBytes = baked.reduce((sum, frame) => sum + frame.byteLength, 0);-console.log(`cache: ${frameCount} frames at ${fps} fps, ${dropletCount} droplets, ${(packedBytes / 1024).toFixed(1)} KiB packed vs ${(floatBytes / 1024).toFixed(1)} KiB as floats`);--const state = { loop: false };-const duration = frameCount / fps;-function frameIndexAt(seconds) {- const frame = Math.floor(seconds * fps);- return state.loop ? ((frame % frameCount) + frameCount) % frameCount : Math.min(frameCount - 1, Math.max(0, frame));+function encodeFrame({ positions, normals, indices }) {+ const minimum = [0, 1, 2].map(axis => Math.min(...positions.filter((unused, index) => index % 3 === axis)));+ const maximum = [0, 1, 2].map(axis => Math.max(...positions.filter((unused, index) => index % 3 === axis)));+ const span = maximum.map((value, axis) => Math.max(value - minimum[axis], 1e-6));+ const packedPositions = Int16Array.from(positions, (value, index) => Math.round((value - minimum[index % 3]) / span[index % 3] * 65535 - 32768));+ const packedNormals = Int8Array.from(normals, value => Math.round(value * 127));+ const indexBytes = padToFour(Uint16Array.from(indices));+ const positionBytes = padToFour(packedPositions);+ const normalBytes = padToFour(packedNormals);+ const description = {+ asset: { version: '2.0', generator: 'docs example' },+ buffers: [{ byteLength: indexBytes.length + positionBytes.length + normalBytes.length }],+ bufferViews: [+ { buffer: 0, byteOffset: 0, byteLength: indexBytes.length },+ { buffer: 0, byteOffset: indexBytes.length, byteLength: positionBytes.length },+ { buffer: 0, byteOffset: indexBytes.length + positionBytes.length, byteLength: normalBytes.length },+ ],+ accessors: [+ { bufferView: 0, componentType: 5123, count: indices.length, type: 'SCALAR' },+ { bufferView: 1, componentType: 5122, count: positions.length / 3, type: 'VEC3', min: minimum, max: maximum },+ { bufferView: 2, componentType: 5120, normalized: true, count: normals.length / 3, type: 'VEC3' },+ ],+ meshes: [{ primitives: [{ attributes: { POSITION: 1, NORMAL: 2 }, indices: 0 }] }],+ nodes: [{ mesh: 0 }],+ scenes: [{ nodes: [0] }],+ scene: 0,+ };+ const json = padToFour(new TextEncoder().encode(JSON.stringify(description)), 32);+ const binary = new Uint8Array([...indexBytes, ...positionBytes, ...normalBytes]);+ const total = 12 + 8 + json.length + 8 + binary.length;+ const glb = new Uint8Array(total);+ const view = new DataView(glb.buffer);+ view.setUint32(0, 0x46546c67, true);+ view.setUint32(4, 2, true);+ view.setUint32(8, total, true);+ view.setUint32(12, json.length, true);+ view.setUint32(16, 0x4e4f534a, true);+ glb.set(json, 20);+ view.setUint32(20 + json.length, binary.length, true);+ view.setUint32(24 + json.length, 0x004e4942, true);+ glb.set(binary, 28 + json.length);+ return glb.buffer;}-const decoded = new Map();-function partsAt(seconds) {- const index = frameIndexAt(seconds);- if (!decoded.has(index)) {- decoded.set(index, unpack(cache[index]));- if (decoded.size > 4) decoded.delete(decoded.keys().next().value);- }- const positions = decoded.get(index);- return Array.from({ length: dropletCount }, (unused, droplet) => ({- name: `Droplet ${droplet}`,- geometry: dropletShape,- matrix: new Float32Array([0.07, 0, 0, 0, 0, 0.07, 0, 0, 0, 0, 0.07, 0, positions[droplet * 3], positions[droplet * 3 + 1], positions[droplet * 3 + 2], 1]),- material: dropletMaterial,- }));+const files = { 'meta.json': new TextEncoder().encode(JSON.stringify({ name: 'ripple', fps, frameCount, frameFile: 'frame_%04d.glb' })).buffer };+for (let frame = 0; frame < frameCount; frame++) {+ files[`frame_${String(frame).padStart(4, '0')}.glb`] = encodeFrame(bakeFrame(frame / fps));}+const totalBytes = Object.values(files).reduce((sum, bytes) => sum + bytes.byteLength, 0);-const dropletShape = sphere(10, 8);-const dropletMaterial = { color: [0.45, 0.78, 0.9], metallic: 0, roughness: 0.15 };-const scenery = [{ name: 'Spout', geometry: box(0.08, 3), matrix: new Float32Array([0.5, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0.5, 0, -3.3, 1.4, 0, 1]), material: { color: [0.5, 0.5, 0.55], metallic: 0.6, roughness: 0.4 } }];+const cache = await loadSpumeCache(async fileName => files[fileName] ?? null);+const player = createSpumePlayer(cache, { loop: false });+console.log(`cache: ${player.frameCount} frames at ${player.fps} fps, ${player.duration.toFixed(2)} s, ${(totalBytes / 1024).toFixed(1)} KiB in ${Object.keys(files).length} files`);+const scenery = [{ name: 'Slab', geometry: box(0.1, 3), matrix: new Float32Array([6.4, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 6.4, 0, 0, -0.1, 0, 1]), material: { color: [0.45, 0.43, 0.4], metallic: 0, roughness: 0.8 } }];const canvas = document.querySelector('#scene');-const renderer = new Renderer67(canvas, [...scenery, ...partsAt(0)]);+const renderer = new Renderer67(canvas, [...scenery, ...player.partsAt(0)]);const timings = [];-let seconds = 1;-let playing = true;+const state = { seconds: 0.5, playing: true, loop: false };let last = performance.now();function draw() {const start = performance.now();- renderer.replaceParts([...scenery, ...partsAt(seconds)]);+ renderer.replaceParts([...scenery, ...player.partsAt(state.seconds)]);timings.push(performance.now() - start);- renderer.render({ eye: [0, 3, 8], target: [0, 0.8, 0], fov: 40 });+ renderer.render({ eye: [0, 4, 8], target: [0, 0.5, 0], fov: 40 });}const bar = document.createElement('div');@@ -118,35 +125,34 @@ toggle.textContent = 'Pause';const slider = document.createElement('input');slider.type = 'range';slider.min = 0;-slider.max = duration;+slider.max = player.duration;slider.step = 0.01;-slider.value = seconds;+slider.value = state.seconds;const loopLabel = document.createElement('label');const loopBox = document.createElement('input');loopBox.type = 'checkbox';loopLabel.append(loopBox, 'loop');bar.append(toggle, slider, loopLabel);document.body.append(bar);-toggle.addEventListener('click', () => { playing = !playing; toggle.textContent = playing ? 'Pause' : 'Play'; last = performance.now(); });+toggle.addEventListener('click', () => { state.playing = !state.playing; toggle.textContent = state.playing ? 'Pause' : 'Play'; last = performance.now(); });loopBox.addEventListener('change', () => { state.loop = loopBox.checked; console.log('loop', state.loop); });-slider.addEventListener('input', () => { playing = false; toggle.textContent = 'Play'; seconds = Number(slider.value); draw(); });-slider.addEventListener('change', () => console.log(`t=${seconds.toFixed(2)} s -> frameIndexAt ${frameIndexAt(seconds)}`));+slider.addEventListener('input', () => { state.playing = false; toggle.textContent = 'Play'; state.seconds = Number(slider.value); draw(); });+slider.addEventListener('change', () => console.log(`t=${state.seconds.toFixed(2)} s -> frameIndexAt ${player.frameIndexAt(state.seconds)}`));let nextReport = 1;function frame(now) {- if (playing) {- seconds += (now - last) / 1000;- if (!state.loop) seconds = Math.min(seconds, duration);- else seconds %= duration;- slider.value = seconds % duration;+ if (state.playing) {+ state.seconds += (now - last) / 1000;+ state.seconds = state.loop ? state.seconds % player.duration : Math.min(state.seconds, player.duration);+ slider.value = state.seconds;draw();}last = now;- if (playing && seconds >= nextReport) {+ if (state.playing && timings.length && performance.now() / 1000 > nextReport) {const average = timings.reduce((sum, value) => sum + value, 0) / timings.length;console.log(`replaceParts averaged ${average.toFixed(2)} ms over ${timings.length} frames`);timings.length = 0;- nextReport = seconds + 1;+ nextReport = performance.now() / 1000 + 2;}requestAnimationFrame(frame);}@@ -155,9 +161,9 @@ requestAnimationFrame(frame);addEventListener('pagehide', () => renderer.dispose());```-The droplets are plain parts, replaced each frame. The real cache holds a liquid mesh per frame and whitewater points, and draws them with the `liquid` and `foam` materials that refract opaque parts.+The player is made with `loop: false`, so time past the last frame holds it, and the example wraps time itself when you tick Loop. A real cache also holds whitewater points per frame, which the player draws with the `foam` material next to the `liquid` mesh that refracts the slab.-## Play a real cache+## Play a real cache from a folder1. Bake a cache folder with Spume's `run.py` or its Blender add-on.2. Load it with `loadSpumeCache(folderUrl)`.@@ -171,17 +177,8 @@ uv run python run.py --out out/geyser --name geyser --pressure cg --iterations 2A low-resolution check takes seconds after the first kernel compile: `uv run python run.py --out out/test --cell 0.2 --width 6 --height 12 --frames 40 --mesh-cell 0.25`. Units are metres with +Y up and the floor at y = 0, which matches 67js. Serve the output folder next to the page. It holds `meta.json`, one `frame_NNNN.glb` per frame and the whitewater files `spray.bin`, `spray_ids.bin` and `spray_kinds.bin`.```js-import { Renderer67 } from '67js';-import { loadSpumeCache, createSpumePlayer } from '67js/addons/spume';-const cache = await loadSpumeCache('/caches/geyser/');const player = createSpumePlayer(cache, { matrix: placeAt(0, 0, 0), loop: true });-console.log(player.frameCount, player.fps, player.duration);-const renderer = new Renderer67(canvas, [...sceneParts, ...player.partsAt(0)]);-function draw(seconds) {- renderer.replaceParts([...sceneParts, ...player.partsAt(seconds)]);- renderer.render({ eye, target });-}````loadSpumeCache(source)` accepts a folder URL or an `async (fileName) => ArrayBuffer | null` reader, so the same cache loads from a server, from disk in Node or from a dropped folder. It validates `meta.json`, reads every frame file and keeps frames int16-packed until they are played, which is about a fifth of the decoded size. The frame files are not general glTF: positions are int16 spread over each frame's own min..max box, so standard loaders, including `67js/addons/gltf`, read them at the wrong scale. Use `decodeSpumeFrame(bytes)` for one frame.diff --git a/docs/learn/deterministic-animation.md b/docs/learn/deterministic-animation.mdindex 83cc09dc..3ae43e5b 100644--- a/docs/learn/deterministic-animation.md+++ b/docs/learn/deterministic-animation.md@@ -9,8 +9,6 @@ The cube moves along a smooth path and turns, and the sphere pulses and glows. P```js live poster=deterministic-animationimport { Renderer67, box, sphere, createAnimationClip, sampleAnimationClip, createAnimationPlayer } from '67js';-// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.-const { Float32Array, Uint16Array, Uint32Array } = window.parent;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]);diff --git a/docs/learn/grass-fields.md b/docs/learn/grass-fields.mdindex 16001f36..d7c6658c 100644--- a/docs/learn/grass-fields.md+++ b/docs/learn/grass-fields.md@@ -4,129 +4,69 @@## Tiles and levels of detail-The docs run with the core module only, so this example draws flat blade strips by hand with the same tile rule as the addon: three levels that keep all, 35 percent and 12 percent of the blades, at up to 10 m, 26 m and 60 m, with wider blades farther out. Move the slider to walk the eye across the field and watch tiles change level. The console prints what `grass.stats()` would: tiles per level, triangles and an estimate of geometry bytes.+The example calls `createGrass` for a 40 by 40 m meadow with a path cleared by `mask`. The slider walks the eye along the field: tiles near it keep every blade and tiles farther out keep 35 percent and then 12 percent, as the default levels say. A coarser level keeps a fixed subset of the same blades, so a tile that changes level does not reshuffle. The buttons rebuild the field with another preset. The console prints `grass.stats()` and the build time, and says when `update(eye)` returned true.```js live poster=grass-tilesimport { Renderer67 } from '67js';+import { createGrass } from '67js/addons/grass';-function random(seed) {- let value = seed >>> 0;- return () => {- value = (value * 1664525 + 1013904223) >>> 0;- return value / 4294967296;- };-}+const area = { minX: -20, maxX: 20, minZ: -20, maxZ: 20 };+const mask = (x, z) => (Math.abs(z) < 0.8 ? 0 : 1);+const state = { eyeX: -14, preset: 'meadow' };-const fieldSize = 48;-const tileSize = 4;-const levels = [- { distance: 10, keep: 1, widthScale: 1 },- { distance: 26, keep: 0.35, widthScale: 2 },- { distance: 60, keep: 0.12, widthScale: 4.5 },-];-const density = 4;-const bladesPerTile = Math.round(density * tileSize * tileSize);--// One blade is a two-sided strip: a quad of two triangles, front and back.-const blade = {- positions: new Float32Array([-0.5, 0, 0, 0.5, 0, 0, 0, 1, 0, -0.5, 0, 0, 0, 1, 0, 0.5, 0, 0]),- normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1]),- indices: new Uint32Array([0, 1, 2, 3, 4, 5]),-};-const triangles = 2;-const material = { color: [0.3, 0.55, 0.16], metallic: 0, roughness: 0.8 };--// Blades of a tile come from the tile's own seed, in a fixed order, so keeping the first N keeps the same blades.-const tiles = [];-for (let row = 0; row < fieldSize / tileSize; row++) {- for (let column = 0; column < fieldSize / tileSize; column++) {- const next = random(row * 1000 + column + 7);- const blades = Array.from({ length: bladesPerTile }, () => ({- x: -fieldSize / 2 + (column + next()) * tileSize,- z: -fieldSize / 2 + (row + next()) * tileSize,- yaw: next() * Math.PI,- height: 0.25 + next() * 0.3,- }));- tiles.push({ centerX: -fieldSize / 2 + (column + 0.5) * tileSize, centerZ: -fieldSize / 2 + (row + 0.5) * tileSize, blades, level: -1 });- }+function eye() {+ return [state.eyeX, 1.3, 0];}--function levelFor(tile, eyeX) {- const distance = Math.hypot(tile.centerX - eyeX, tile.centerZ);- const boundary = levels.findIndex(entry => distance < entry.distance);- const target = boundary === -1 ? levels.length : boundary;- // Hysteresis: a tile moves to a coarser level only when it is 10 percent past the boundary.- if (tile.level >= 0 && target > tile.level && distance < levels[tile.level].distance * 1.1) return tile.level;- return target;-}--function update(eyeX) {- let changed = false;- const stats = { tiles: [0, 0, 0], culled: 0, triangles: 0 };- for (const tile of tiles) {- const level = levelFor(tile, eyeX);- if (level !== tile.level) changed = true;- tile.level = level;- if (level >= levels.length) stats.culled++;- else {- stats.tiles[level]++;- stats.triangles += Math.ceil(bladesPerTile * levels[level].keep) * triangles;- }- }- stats.geometryBytes = stats.triangles * 3 * 24;- return { changed, stats };-}--function partsFor() {- const parts = [];- for (const [tileIndex, tile] of tiles.entries()) {- if (tile.level >= levels.length) continue;- const { keep, widthScale } = levels[tile.level];- for (const [bladeIndex, entry] of tile.blades.slice(0, Math.ceil(bladesPerTile * keep)).entries()) {- const c = Math.cos(entry.yaw);- const s = Math.sin(entry.yaw);- const width = 0.03 * widthScale;- parts.push({ name: `Blade ${tileIndex}-${bladeIndex}`, geometry: blade, material, matrix: new Float32Array([c * width, 0, -s * width, 0, 0, entry.height, 0, 0, s, 0, c, 0, entry.x, 0, entry.z, 1]) });- }- }- return parts;+function build(preset) {+ const started = performance.now();+ const built = createGrass({ preset, area, mask, density: 120, eye: eye() });+ console.log(`${preset}: built in ${Math.round(performance.now() - started)} ms`, built.stats());+ return built;}+let grass = build(state.preset);const canvas = document.querySelector('#scene');-let eyeX = -12;-let { stats } = update(eyeX);-console.log('tiles', tiles.length, 'blades per tile at full detail', bladesPerTile);-console.log('stats()', stats);-const renderer = new Renderer67(canvas, partsFor(), { world: true });+const renderer = new Renderer67(canvas, grass.parts, { world: true });function draw() {- renderer.render({ eye: [eyeX, 1.3, 0], target: [eyeX + 12, 0.3, 4], fov: 60, wind: 0.3 });+ renderer.render({ eye: eye(), target: [state.eyeX + 12, 0.3, 4], fov: 60, wind: 0.3 });}+const bar = document.createElement('div');+bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:8px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';const slider = document.createElement('input');slider.type = 'range';slider.min = -16;slider.max = 16;slider.step = 0.5;-slider.value = eyeX;+slider.value = state.eyeX;slider.setAttribute('aria-label', 'Eye position along the field');-slider.style.cssText = 'position:fixed;left:8px;bottom:8px;width:40%';slider.addEventListener('input', () => {- eyeX = Number(slider.value);- const result = update(eyeX);- if (result.changed) {- renderer.replaceParts(partsFor());- console.log('update(eye) = true', result.stats);+ state.eyeX = Number(slider.value);+ if (grass.update(eye())) {+ renderer.replaceParts(grass.parts);+ console.log('update(eye) = true', grass.stats());}draw();});-document.body.append(slider);+bar.append(slider);+for (const preset of ['meadow', 'lawn', 'savanna', 'wild']) {+ const button = document.createElement('button');+ button.textContent = preset;+ button.addEventListener('click', () => {+ grass = build(preset);+ renderer.replaceParts(grass.parts);+ draw();+ });+ bar.append(button);+}+document.body.append(bar);new ResizeObserver(() => { renderer.resize(); draw(); }).observe(canvas);draw();addEventListener('pagehide', () => renderer.dispose());```-The `update` function returns `changed` the way `grass.update(eye)` returns `true`: rebuild the part list only then, not every frame.+`update(eye)` returns true only when a tile changed level, so rebuild the part list then and not every frame.## Grow a real field@@ -134,23 +74,11 @@ The `update` function returns `changed` the way `grass.update(eye)` returns `tru2. Add `grass.parts` to the renderer and pass `wind` in each frame.3. When `grass.update(eye)` returns true, call `renderer.replaceParts` with the new part list.-```js-import { Renderer67 } from '67js';-import { createGrass } from '67js/addons/grass';+With a terrain from `createTerrain`, pass its `heightAt` as `terrainHeight` and put its parts next to the grass:-const grass = createGrass({- preset: 'meadow',- area: { minX: -40, maxX: 40, minZ: -50, maxZ: 50 },- terrainHeight: terrain.heightAt,- mask: (x, z) => (Math.abs(x) < 1.5 ? 0 : 1),- eye,-});+```js+const grass = createGrass({ preset: 'meadow', area, terrainHeight: terrain.heightAt, mask, eye });const renderer = new Renderer67(canvas, [...terrain.parts, ...grass.parts], { world: true, memoryBudgetMiB: 512 });-function draw(eye, seconds) {- if (grass.update(eye)) renderer.replaceParts([...terrain.parts, ...grass.parts]);- renderer.render({ eye, target, wind: 0.5, time: seconds });-}-console.log(grass.stats());```Tint the ground under the grass with `grass.groundColor`. On a splat terrain, darken every layer the grass covers, not only the grass layer, because soil under a sward sits in the blades' shade and a bright floor between blades is what makes a field look fake.diff --git a/docs/learn/humanoid-retargeting-and-crowds.md b/docs/learn/humanoid-retargeting-and-crowds.mdindex 83e2234f..c37b7f3e 100644--- a/docs/learn/humanoid-retargeting-and-crowds.md+++ b/docs/learn/humanoid-retargeting-and-crowds.md@@ -4,18 +4,12 @@## One clip, many walkers-The docs run with the core module only and cannot load a rigged character, so this example shows the part of the pipeline that matters for a crowd: one shared clip, and for every instance a seeded placement, a time offset and a playback rate. The clip only has rotations, so it plays on figures of any size, which is the same reason a retargeted clip works on another skeleton. Drag the slider to change the count. The console prints the first instances the way `createCrowd` reports them.+The example calls the real `createCrowd` for a seeded placement, a time offset and a playback rate per walker, and `crowd.sample(seconds)` for each walker's pose tracks. The docs host cannot load a rigged character, so the walkers are blocks posed from those tracks, and the clip only has rotations, so it plays on figures of any size, which is the same reason a retargeted clip works on another skeleton. Drag the slider to change the count and press the button to switch between a grid and a scatter layout. The console prints the first instances, how `mapHumanoidBones` reads the joint names of two rig families, and the cost of each batch of frames.```js live poster=crowd-walk-import { Renderer67, box, sphere, createAnimationClip, sampleAnimationClip } from '67js';--function random(seed) {- let value = seed >>> 0;- return () => {- value = (value * 1664525 + 1013904223) >>> 0;- return value / 4294967296;- };-}+import { Renderer67, box, sphere, createAnimationClip } from '67js';+import { createCrowd, mapHumanoidBones } from '67js/addons/retarget';+const multiply = (a, b) => {const out = new Float32Array(16);for (let column = 0; column < 4; column++) {@@ -29,7 +23,6 @@ const multiply = (a, b) => {};const move = (x, y, z) => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);const scale = (x, y, z) => new Float32Array([x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]);-const turnY = a => new Float32Array([Math.cos(a), 0, -Math.sin(a), 0, 0, 1, 0, 0, Math.sin(a), 0, Math.cos(a), 0, 0, 0, 0, 1]);function fromQuaternion([x, y, z, w]) {return new Float32Array([1 - 2 * (y * y + z * z), 2 * (x * y + z * w), 2 * (x * z - y * w), 0,@@ -46,18 +39,13 @@ const track = (target, phase) => ({});const clip = createAnimationClip({ duration: 1, loop: true, tracks: [track('LegL', 1), track('LegR', -1), track('ArmL', -1), track('ArmR', 1)] });-// createCrowd in the addon returns position, yawRadians, timeOffset, playbackRate and matrix per instance, deterministic for a seed.-function createCrowd({ count, seed, columns, spacing, rateJitter = 0.15 }) {- const next = random(seed);- const instances = Array.from({ length: count }, (unused, index) => ({- position: [(index % columns - (columns - 1) / 2) * spacing, 0, (Math.floor(index / columns) - 1.5) * spacing],- yawRadians: (next() - 0.5) * 0.8,- timeOffset: next() * clip.duration,- playbackRate: 1 + (next() * 2 - 1) * rateJitter,- height: 0.9 + next() * 0.25,- shirt: Math.floor(next() * 4),- }));- return { instances, clipTime: (index, seconds) => (instances[index].timeOffset + seconds * instances[index].playbackRate) % clip.duration };+// Which canonical bones does the addon find in a rig? Real joint names of two families.+for (const [family, jointNames] of [+ ['Mixamo', ['mixamorig:Hips', 'mixamorig:Spine', 'mixamorig:Head', 'mixamorig:LeftArm', 'mixamorig:LeftHand', 'mixamorig:RightArm', 'mixamorig:RightHand', 'mixamorig:LeftUpLeg', 'mixamorig:LeftFoot', 'mixamorig:RightUpLeg', 'mixamorig:RightFoot']],+ ['Unreal', ['pelvis', 'spine_01', 'head', 'upperarm_l', 'hand_l', 'upperarm_r', 'hand_r', 'thigh_l', 'foot_l', 'thigh_r', 'foot_r']],+]) {+ const { mapping, unmapped, missing } = mapHumanoidBones(jointNames);+ console.log(`${family}: ${Object.keys(mapping).length} bones mapped, ${unmapped.length} unmapped, missing`, missing);}const shirts = [[0.8, 0.25, 0.2], [0.2, 0.5, 0.8], [0.9, 0.75, 0.2], [0.3, 0.65, 0.35]].map(color => ({ color, metallic: 0, roughness: 0.7 }));@@ -73,33 +61,34 @@ const limbs = [];function buildParts(crowd) {- return crowd.instances.flatMap((instance, index) => [- { name: `P${index} torso`, geometry: block, matrix: scale(1, 1, 1), material: shirts[instance.shirt] },- { name: `P${index} head`, geometry: headShape, matrix: scale(1, 1, 1), material: skin },- ...limbs.map(limb => ({ name: `P${index} ${limb.name}`, geometry: block, matrix: scale(1, 1, 1), material: limb.name.startsWith('Leg') ? trousers : skin })),+ return crowd.instances.flatMap(instance => [+ { name: `P${instance.index} torso`, geometry: block, matrix: scale(1, 1, 1), material: shirts[instance.index % 4] },+ { name: `P${instance.index} head`, geometry: headShape, matrix: scale(1, 1, 1), material: skin },+ ...limbs.map(limb => ({ name: `P${instance.index} ${limb.name}`, geometry: block, matrix: scale(1, 1, 1), material: limb.name.startsWith('Leg') ? trousers : skin })),]);}function pose(parts, crowd, seconds) {- crowd.instances.forEach((instance, index) => {- const samples = sampleAnimationClip(clip, crowd.clipTime(index, seconds));- const frame = multiply(multiply(move(...instance.position), turnY(instance.yawRadians)), scale(instance.height, instance.height, instance.height));- const base = index * 6;+ crowd.sample(seconds).forEach(({ instance, tracks }) => {+ const height = 0.9 + (instance.index * 7 % 5) * 0.06;+ const frame = multiply(instance.matrix, scale(height, height, height));+ const base = instance.index * 6;parts[base].matrix = multiply(frame, multiply(move(0, 1.0, 0), scale(0.5, 0.7, 0.28)));parts[base + 1].matrix = multiply(frame, multiply(move(0, 1.55, 0), scale(0.18, 0.18, 0.18)));limbs.forEach((limb, limbIndex) => {- const rotation = samples.find(sample => sample.target === limb.name).value;+ const rotation = tracks.find(sample => sample.target === limb.name).output;parts[base + 2 + limbIndex].matrix = multiply(frame, multiply(move(...limb.pivot), multiply(fromQuaternion(rotation), multiply(move(0, -limb.size[1] / 2, 0), scale(...limb.size)))));});});}const canvas = document.querySelector('#scene');-let crowd = createCrowd({ count: 24, seed: 7, columns: 6, spacing: 1.4 });+const state = { count: 24, layout: 'grid' };+const makeCrowd = () => createCrowd({ count: state.count, clip, seed: 7, layout: state.layout, spacing: 1.4, columns: 6, size: 8, randomYaw: state.layout === 'scatter' });+let crowd = makeCrowd();let parts = buildParts(crowd);const renderer = new Renderer67(canvas, parts);console.log('first instances:', crowd.instances.slice(0, 3).map(instance => ({ timeOffset: instance.timeOffset, playbackRate: instance.playbackRate })));-console.log('parts', parts.length, 'draws are batched by shared geometry and material');const bar = document.createElement('div');bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:10px;align-items:center;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';@@ -108,15 +97,22 @@ slider.type = 'range';slider.min = 6;slider.max = 60;slider.step = 6;-slider.value = 24;-slider.addEventListener('change', () => {- const count = Number(slider.value);- crowd = createCrowd({ count, seed: 7, columns: 6, spacing: 1.4 });+slider.value = state.count;+const layoutButton = document.createElement('button');+layoutButton.textContent = 'layout: grid';+function rebuild() {+ crowd = makeCrowd();parts = buildParts(crowd);renderer.replaceParts(parts);- console.log(`crowd of ${count}: ${parts.length} parts`);+ console.log(`crowd of ${state.count} in a ${state.layout}: ${parts.length} parts`);+}+slider.addEventListener('change', () => { state.count = Number(slider.value); rebuild(); });+layoutButton.addEventListener('click', () => {+ state.layout = state.layout === 'grid' ? 'scatter' : 'grid';+ layoutButton.textContent = `layout: ${state.layout}`;+ rebuild();});-bar.append('count', slider);+bar.append('count', slider, layoutButton);document.body.append(bar);const started = performance.now();@@ -126,9 +122,9 @@ function frame(now) {const before = performance.now();pose(parts, crowd, elapsed / 1000);renderer.updateParts(parts);- renderer.render({ eye: [0, 5, 9], target: [0, 0.9, 0], fov: 42 });+ renderer.render({ eye: [0, 6, 10], target: [0, 0.9, 0], fov: 42 });if (elapsed > nextReport) {- console.log(`pose + upload + render: ${(performance.now() - before).toFixed(2)} ms for ${crowd.instances.length} walkers`);+ console.log(`sample + pose + upload + render: ${(performance.now() - before).toFixed(2)} ms for ${crowd.instances.length} walkers`);nextReport = elapsed + 3000;}requestAnimationFrame(frame);@@ -138,7 +134,7 @@ requestAnimationFrame(frame);addEventListener('pagehide', () => renderer.dispose());```-Every walker plays the same clip at its own time, so the legs are never in step. The pose code touches every instance each frame, which is the cost the GPU crowd path removes.+Every walker plays the same clip at its own time and rate, so the legs are never in step. The pose code touches every instance each frame, which is the cost the GPU crowd path removes. A real character is retargeted with `retargetClip` and baked with `crowd-skinning`, as in the next section.## Retarget a real clipdiff --git a/docs/learn/recorded-physics.md b/docs/learn/recorded-physics.mdindex ccbc0f09..1a11a0d2 100644--- a/docs/learn/recorded-physics.md+++ b/docs/learn/recorded-physics.md@@ -4,96 +4,58 @@## Bake once, seek anywhere-Rapier is an optional peer dependency and is not loaded in the docs, so this example bakes a ball and a crate with a tiny hand-written integrator and then plays the recording the same way: one pose per body per frame, seven floats each, sampled at an absolute time. Drag the slider back and forth, and tick a time in the middle of a bounce to see the interpolation. The console prints the plan, the bake time, the contact ticks, and the lowest height of the ball between frames.+The example bakes a real Rapier recording in the page: a floor, a bouncing ball that gets a kick at tick 120, and a crate that slides across the floor. `planPhysicsScene` sizes the timeline first, `createPhysicsScene` bakes it, and `physics.bindParts` ties the two parts to their bodies. After that playback never runs the solver again. Drag the slider back and forth, or let it play, and a seek backward gives the same pose. The console prints the plan, the bake time, the contact events, the tick where each body came to rest and the lowest height of the ball between frames.```js live poster=physics-recordingimport { Renderer67, sphere, box } from '67js';+import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';-// A plan before the bake: frames x bodies x 7 floats x 4 bytes, like planPhysicsScene's timelineBytes.-const frameCount = 361;-const timestep = 1 / 60;-const bodyNames = ['ball', 'crate'];-const duration = (frameCount - 1) * timestep;-console.log('plan:', { frameCount, timestep, duration, timelineBytes: frameCount * bodyNames.length * 7 * 4 });--// Bake: gravity, a bounce on the floor (y = 0) and a kick at tick 120, like { tick: 120, body: 'ball', impulse }.const radius = 0.4;-const events = [{ tick: 120, body: 'ball', impulse: [3, 3, 0] }];-const contacts = [];-const timeline = new Float32Array(frameCount * bodyNames.length * 7);-const bakeStart = performance.now();-const ball = { position: [-3, 4, 0], velocity: [0, 0, 0] };-const crate = { position: [1.5, 0.35, 0], velocity: [-1.2, 0, 0] };-for (let frame = 0; frame < frameCount; frame++) {- const ballAngle = -(ball.position[0] + 3) / radius;- const crateYaw = (crate.position[0] - 1.5) * 0.1;- timeline.set([...ball.position, 0, 0, Math.sin(ballAngle / 2), Math.cos(ballAngle / 2)], (frame * 2) * 7);- timeline.set([...crate.position, 0, Math.sin(crateYaw / 2), 0, Math.cos(crateYaw / 2)], (frame * 2 + 1) * 7);- for (const event of events) {- if (event.tick === frame) ball.velocity = ball.velocity.map((value, axis) => value + event.impulse[axis]);- }- ball.velocity[1] -= 9.81 * timestep;- ball.position = ball.position.map((value, axis) => value + ball.velocity[axis] * timestep);- if (ball.position[1] < radius && ball.velocity[1] < 0) {- ball.position[1] = radius;- ball.velocity[1] *= -0.62;- ball.velocity[0] *= 0.99;- contacts.push(frame);- }- crate.velocity[0] *= 0.985;- crate.position[0] += crate.velocity[0] * timestep;-}-console.log(`baked ${frameCount} frames in ${(performance.now() - bakeStart).toFixed(1)} ms; contact ticks:`, contacts.slice(0, 8));--// Sampling: clamp time, linear translation, normalized shortest-arc quaternion, into a retained output.-function sample(time, out) {- const clamped = Math.min(duration, Math.max(0, time));- const exact = clamped / timestep;- const first = Math.min(frameCount - 2, Math.floor(exact));- const blend = exact - first;- for (let body = 0; body < bodyNames.length; body++) {- const a = (first * bodyNames.length + body) * 7;- const b = ((first + 1) * bodyNames.length + body) * 7;- for (let index = 0; index < 3; index++) out[body * 7 + index] = timeline[a + index] + (timeline[b + index] - timeline[a + index]) * blend;- let dot = 0;- for (let index = 3; index < 7; index++) dot += timeline[a + index] * timeline[b + index];- const direction = dot < 0 ? -1 : 1;- let length = 0;- for (let index = 3; index < 7; index++) {- out[body * 7 + index] = timeline[a + index] + (direction * timeline[b + index] - timeline[a + index]) * blend;- length += out[body * 7 + index] ** 2;- }- for (let index = 3; index < 7; index++) out[body * 7 + index] /= Math.sqrt(length);- }- return out;-}--function matrixFrom(pose, offset, sx, sy, sz) {- const [x, y, z, qx, qy, qz, qw] = pose.slice(offset, offset + 7);- return new Float32Array([- (1 - 2 * (qy * qy + qz * qz)) * sx, 2 * (qx * qy + qz * qw) * sx, 2 * (qx * qz - qy * qw) * sx, 0,- 2 * (qx * qy - qz * qw) * sy, (1 - 2 * (qx * qx + qz * qz)) * sy, 2 * (qy * qz + qx * qw) * sy, 0,- 2 * (qx * qz + qy * qw) * sz, 2 * (qy * qz - qx * qw) * sz, (1 - 2 * (qx * qx + qy * qy)) * sz, 0,- x, y, z, 1,- ]);-}+const definition = {+ gravity: [0, -9.81, 0],+ bodies: [+ { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },+ { name: 'ball', type: 'dynamic', translation: [-3, 4, 0] },+ { name: 'crate', type: 'dynamic', translation: [1.5, 0.35, 0], linearVelocity: [-1.2, 0, 0] },+ ],+ colliders: [+ { name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [8, 0.5, 4], friction: 0.6 },+ { name: 'ball', body: 'ball', shape: 'ball', radius, restitution: 0.62, mass: 1 },+ { name: 'crate', body: 'crate', shape: 'cuboid', halfExtents: [0.35, 0.35, 0.35], friction: 0.6, mass: 1 },+ ],+ events: [{ tick: 120, body: 'ball', impulse: [3, 3, 0] }],+};+const options = { frameCount: 361, timestep: 1 / 60, maxMemoryBytes: 32 * 1024 * 1024 };+const plan = planPhysicsScene(definition, options);+console.log('plan:', { timelineBytes: plan.timelineBytes, estimatedPeakBytes: plan.estimatedPeakBytes });-const pose = new Float32Array(bodyNames.length * 7);-const ballPart = { name: 'Ball', geometry: sphere(32, 20), matrix: matrixFrom(sample(0, pose), 0, radius, radius, radius), material: { color: [0.9, 0.45, 0.2], metallic: 0, roughness: 0.4 } };-const cratePart = { name: 'Crate', geometry: box(0.05, 3), matrix: matrixFrom(pose, 7, 0.7, 0.7, 0.7), material: { color: [0.55, 0.4, 0.25], metallic: 0, roughness: 0.7 } };-const parts = [ballPart, cratePart];+const bakeStart = performance.now();+const physics = await createPhysicsScene(definition, options);+const duration = (options.frameCount - 1) * options.timestep;+console.log(`baked ${options.frameCount} frames in ${(performance.now() - bakeStart).toFixed(1)} ms; contact events: ${physics.contactEvents.length}, bodies at rest from tick`, Object.fromEntries(physics.bodyNames.map((name, index) => [name, physics.restFrames[index]])));++// The matrix keeps its scale; the binding writes the recorded translation and rotation into it.+const ballPart = { name: 'Ball', geometry: sphere(32, 20), matrix: new Float32Array([radius, 0, 0, 0, 0, radius, 0, 0, 0, 0, radius, 0, 0, 0, 0, 1]), material: { color: [0.9, 0.45, 0.2], metallic: 0, roughness: 0.4 } };+const cratePart = { name: 'Crate', geometry: box(0.05, 3), matrix: new Float32Array([0.7, 0, 0, 0, 0, 0.7, 0, 0, 0, 0, 0.7, 0, 0, 0, 0, 1]), material: { color: [0.55, 0.4, 0.25], metallic: 0, roughness: 0.7 } };+const floorPart = { name: 'Floor', geometry: box(0.05, 3), matrix: new Float32Array([16, 0, 0, 0, 0, 1, 0, 0, 0, 0, 8, 0, 0, 0, 0, 1]), material: { color: [0.4, 0.42, 0.45], metallic: 0, roughness: 0.9 } };+const parts = [floorPart, ballPart, cratePart];+const bindings = physics.bindParts([+ { body: 'floor', part: floorPart },+ { body: 'ball', part: ballPart },+ { body: 'crate', part: cratePart },+]);// The lowest the ball gets between frames. An interpolated pose runs no collision test, so a rotated shape can dip below the floor; a ball stays above it.+const pose = new Float32Array(physics.bodyNames.length * 7);+const ballIndex = physics.bodyIndex('ball');let lowest = Infinity;-for (let time = 0; time <= duration; time += timestep / 10) lowest = Math.min(lowest, sample(time, pose)[1] - radius);+for (let time = 0; time <= duration; time += options.timestep / 10) lowest = Math.min(lowest, physics.sample(time, pose)[ballIndex * 7 + 1] - radius);console.log(`lowest ball underside while sampling at 10x the step: ${lowest.toFixed(4)} m`);const canvas = document.querySelector('#scene');const renderer = new Renderer67(canvas, parts);function applyAnimation(time) {- sample(time, pose);- ballPart.matrix = matrixFrom(pose, 0, radius, radius, radius);- cratePart.matrix = matrixFrom(pose, 7, 0.7, 0.7, 0.7);+ bindings.apply(time);renderer.updateParts(parts);renderer.render({ eye: [0, 3.5, 9], target: [0, 1, 0], fov: 42 });}@@ -116,8 +78,8 @@ let last = performance.now();toggle.addEventListener('click', () => { playing = !playing; toggle.textContent = playing ? 'Pause' : 'Play'; last = performance.now(); });slider.addEventListener('input', () => { playing = false; toggle.textContent = 'Play'; seconds = Number(slider.value); applyAnimation(seconds); });slider.addEventListener('change', () => {- sample(seconds, pose);- console.log(`t=${seconds.toFixed(2)} s ball y=${pose[1].toFixed(3)} crate x=${pose[7].toFixed(3)}`);+ physics.sample(seconds, pose);+ console.log(`t=${seconds.toFixed(2)} s ball y=${pose[ballIndex * 7 + 1].toFixed(3)} crate x=${pose[physics.bodyIndex('crate') * 7].toFixed(3)}`);});function frame(now) {if (playing) {@@ -131,17 +93,20 @@ function frame(now) {new ResizeObserver(() => renderer.resize()).observe(canvas);requestAnimationFrame(frame);// Seeking back reproduces an earlier pose exactly: sampling is a pure function of the time.-sample(1.25, pose);+physics.sample(1.25, pose);const firstPose = Array.from(pose);-sample(5, pose);-sample(1.25, pose);+physics.sample(5, pose);+physics.sample(1.25, pose);console.log('backward seek reproduces the pose:', firstPose.every((value, index) => value === pose[index]));-addEventListener('pagehide', () => renderer.dispose());+addEventListener('pagehide', () => {+ renderer.dispose();+ physics.dispose();+});```-## Bake with Rapier+The timeline holds one pose per body per frame, seven floats each, and `sample` blends the two nearest frames at an absolute time, so scrubbing costs the same as playing.-The addon requires the optional peer dependency `@dimforge/[email protected]` (`npm install @dimforge/[email protected]`), and a package-aware dev server such as Vite to resolve it. It bakes body contacts, joints, limits and bounded motors into a timeline.+## Bake your own scene1. Define named bodies, colliders, joints and tick events.2. Call `planPhysicsScene` to validate the definition and allocation estimate.@@ -150,35 +115,7 @@ The addon requires the optional peer dependency `@dimforge/[email protected].5. Apply bindings at absolute time before uploading changed parts.6. Call `physics.dispose()` when the recording is no longer needed.-```js-import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';--const definition = {- gravity: [0, -9.81, 0],- bodies: [- { name: 'floor', type: 'fixed', translation: [0, -0.5, 0] },- { name: 'box', type: 'dynamic', translation: [0, 3, 0] },- ],- colliders: [- { name: 'floor', body: 'floor', shape: 'cuboid', halfExtents: [5, 0.5, 5] },- { name: 'box', body: 'box', shape: 'cuboid', halfExtents: [0.5, 0.5, 0.5], mass: 1 },- ],- events: [{ tick: 120, body: 'box', impulse: [2, 4, 0] }],-};-const options = { frameCount: 601, timestep: 1 / 60, maxMemoryBytes: 64 * 1024 * 1024 };-const plan = planPhysicsScene(definition, options);-console.log(plan.timelineBytes, plan.estimatedPeakBytes);-const physics = await createPhysicsScene(definition, options);-const bindings = physics.bindParts([{ body: 'box', part: boxPart }]);--function applyAnimation(time) {- bindings.apply(time);- renderer.updateParts([boxPart]);-}-applyAnimation(5);-applyAnimation(1); // A backward seek produces the same recorded pose.-physics.dispose();-```+The addon requires the optional peer dependency `@dimforge/[email protected]` (`npm install @dimforge/[email protected]`), and a package-aware dev server such as Vite to resolve it. It bakes body contacts, joints, limits and bounded motors into a timeline.`physics.sample(time, out)` returns packed poses in `physics.bodyNames` order, seven Float32 values per body `[x, y, z, qx, qy, qz, qw]`, and `physics.bodyIndex(name)` gives a body's index. Supply a retained `out` of `bodyNames.length * 7` values to avoid allocation. The binding replaces a part's world translation and rotation while keeping its scale and matrix identity, so the physics body origin must match the visual part origin. Several parts can bind to one body when they share that origin.diff --git a/docs/learn/skeletal-and-morph-animation.md b/docs/learn/skeletal-and-morph-animation.mdindex ff24f7d2..74a4e4f6 100644--- a/docs/learn/skeletal-and-morph-animation.md+++ b/docs/learn/skeletal-and-morph-animation.md@@ -9,8 +9,6 @@ The column has two joints. The upper joint bends it at the middle. A morph targe```js live poster=skeletal-morphimport { Renderer67, box, createSkinPose, updateSkinPose, createMorphPose } from '67js';-// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.-const { Float32Array, Uint16Array, Uint32Array } = window.parent;function translation(x, y, z) {return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);diff --git a/docs/learn/terrain-and-ground-textures.md b/docs/learn/terrain-and-ground-textures.mdindex 4ab49015..cbce8453 100644--- a/docs/learn/terrain-and-ground-textures.md+++ b/docs/learn/terrain-and-ground-textures.md@@ -2,100 +2,62 @@`67js/addons/terrain` builds a chunked, seeded heightfield with distance level of detail. `67js/addons/texture-set` loads CC0 scans and a four-layer ground material draws them with slope, height and mask rules, height-based edge blending, triplanar cliffs and anti-tiling. Both are available from version `0.10.0`.-## The idea: a height function and rules+## Try the real terrain-The docs run in the browser with the core module only, so the example builds a small heightfield by hand and sorts its triangles with the same kind of rules that the splat material uses: a slope range and a height range per layer. Drag the sliders. Grass takes what the other layers leave, rock takes the steep triangles and snow takes the high, flat ones. The console prints how many triangles each layer got and what `heightAt` returns for the ball.+`createTerrain` builds the ground in chunks and swaps each chunk between detail levels as the eye moves. The example below calls it with a noise height, one circular hole and three levels. Drag to orbit, change the distance, and move the red ball with the slider. The console prints `heightAt` for the ball, whether it is over the hole, and after each `update(eye)` how many chunks changed level and how many triangles the ground holds.```js live poster=terrain-rulesimport { Renderer67, sphere } from '67js';+import { createTerrain } from '67js/addons/terrain';-// The docs frame shares the engine of the page, so take the typed arrays that the engine checks for. In your own project this line changes nothing.-const { Float32Array, Uint16Array, Uint32Array } = window.parent;--const size = 40;-const cells = 64;-const heightAt = (x, z) => 2.2 * Math.sin(x * 0.22 + 0.5) * Math.cos(z * 0.19) + 1.1 * Math.sin(x * 0.5 + z * 0.4)- + 0.5 * Math.sin(z * 0.9 - x * 0.3) + 4.5 * Math.exp(-((x - 7) ** 2 + (z + 5) ** 2) / 70);--function build(slopeLimit, snowLine) {- const layers = { grass: [], rock: [], snow: [] };- const step = size / cells;- for (let row = 0; row < cells; row++) {- for (let column = 0; column < cells; column++) {- const x0 = -size / 2 + column * step;- const z0 = -size / 2 + row * step;- const corner = (dx, dz) => [x0 + dx * step, heightAt(x0 + dx * step, z0 + dz * step), z0 + dz * step];- for (const triangle of [[corner(0, 0), corner(0, 1), corner(1, 0)], [corner(1, 0), corner(0, 1), corner(1, 1)]]) {- const [a, b, c] = triangle;- const edgeA = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];- const edgeB = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];- const normal = [edgeA[1] * edgeB[2] - edgeA[2] * edgeB[1], edgeA[2] * edgeB[0] - edgeA[0] * edgeB[2], edgeA[0] * edgeB[1] - edgeA[1] * edgeB[0]];- const length = Math.hypot(...normal);- const unit = normal.map(value => value / length);- const slope = Math.acos(unit[1]) * 180 / Math.PI;- const height = (a[1] + b[1] + c[1]) / 3;- const layer = slope > slopeLimit ? 'rock' : height > snowLine ? 'snow' : 'grass';- layers[layer].push({ triangle, unit });- }- }- }- return layers;-}--function geometryOf(entries) {- const positions = new Float32Array(entries.length * 9);- const normals = new Float32Array(entries.length * 9);- entries.forEach(({ triangle, unit }, index) => {- triangle.forEach((point, corner) => {- positions.set(point, index * 9 + corner * 3);- normals.set(unit, index * 9 + corner * 3);- });- });- return { positions, normals, indices: Uint32Array.from({ length: entries.length * 3 }, (unused, index) => index) };-}--const materials = {- grass: { color: [0.25, 0.5, 0.18], metallic: 0, roughness: 0.9 },- rock: { color: [0.42, 0.4, 0.38], metallic: 0, roughness: 0.85 },- snow: { color: [0.92, 0.94, 0.97], metallic: 0, roughness: 0.6 },+const material = { color: [0.3, 0.5, 0.22], metallic: 0, roughness: 0.9 };+const terrain = createTerrain({+ size: 240, chunks: 8, resolution: 16, levels: 3, seed: 7, material,+ height: { amplitude: 9, mountainAmplitude: 22, featureSize: 70 },+ holes: [{ center: [20, 12], radius: 7 }],+});+const marker = {+ name: 'Marker', geometry: sphere(24, 16), material: { color: [0.9, 0.2, 0.2], metallic: 0, roughness: 0.4 },+ matrix: new Float32Array(16),};-const marker = { name: 'Marker', geometry: sphere(24, 16), matrix: new Float32Array([0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, heightAt(0, 0) + 0.5, 0, 1]), material: { color: [0.9, 0.2, 0.2], metallic: 0, roughness: 0.4 } };--function partsFor(slopeLimit, snowLine) {- const layers = build(slopeLimit, snowLine);- const parts = Object.entries(layers).filter(([unused, entries]) => entries.length).map(([name, entries]) => ({- name: `Terrain ${name}`, geometry: geometryOf(entries), matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: materials[name],- }));- console.log(`slope limit ${slopeLimit}°, snow line ${snowLine} m:`, Object.fromEntries(Object.entries(layers).map(([name, entries]) => [name, entries.length])));- return [...parts, marker];+function placeMarker(x) {+ const z = 12;+ const y = terrain.heightAt(x, z);+ marker.matrix.set([0.6, 0, 0, 0, 0, 0.6, 0, 0, 0, 0, 0.6, 0, x, y + 0.6, z, 1]);+ console.log(`heightAt(${x}, ${z}) = ${y.toFixed(2)} m, over a hole: ${terrain.isHole(x, z)}`);}+placeMarker(0);const canvas = document.querySelector('#scene');canvas.style.touchAction = 'none';-const state = { slope: 32, snow: 3.2, yaw: 0.6, pitch: 0.55, distance: 54 };-const renderer = new Renderer67(canvas, partsFor(state.slope, state.snow), { world: true });-console.log(`heightAt(0, 0) = ${heightAt(0, 0).toFixed(3)} m, ${cells * cells * 2} triangles`);+const renderer = new Renderer67(canvas, [...terrain.parts, marker], { world: true });+const state = { yaw: 0.5, pitch: 0.5, distance: 40 };+console.log(`${terrain.triangleCount} triangles, chunk size ${terrain.chunkSize} m, bounds`, terrain.bounds);function draw() {const flat = Math.cos(state.pitch) * state.distance;- renderer.render({ eye: [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance, Math.cos(state.yaw) * flat], target: [0, 1, 0], fov: 40 });-}-function rebuild() {- renderer.replaceParts(partsFor(state.slope, state.snow));- draw();+ const eye = [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance + 2, Math.cos(state.yaw) * flat];+ const changed = terrain.update(eye);+ if (changed.length) {+ renderer.replaceParts([...terrain.parts, marker]);+ console.log(`${changed.length} chunks changed level, ${terrain.triangleCount} triangles, levels`, terrain.chunkLevels().join(''));+ }+ renderer.render({ eye, target: [0, 2, 0], fov: 45 });}const bar = document.createElement('div');bar.style.cssText = 'position:fixed;left:8px;bottom:8px;display:flex;gap:12px;color:#dde;font:12px system-ui;background:#000a;padding:6px 8px;border-radius:6px';-for (const [label, key, min, max] of [['slope limit', 'slope', 10, 70], ['snow line', 'snow', 0, 6]]) {+for (const [label, min, max, start, apply] of [+ ['distance', 8, 200, state.distance, value => { state.distance = value; }],+ ['ball x', -40, 40, 0, value => { placeMarker(value); renderer.updateParts([marker]); }],+]) {const wrap = document.createElement('label');const input = document.createElement('input');input.type = 'range';input.min = min;input.max = max;- input.step = 0.5;- input.value = state[key];- input.addEventListener('change', () => { state[key] = Number(input.value); rebuild(); });+ input.value = start;+ input.addEventListener('input', () => { apply(Number(input.value)); draw(); });wrap.append(label + ' ', input);bar.append(wrap);}@@ -104,24 +66,24 @@ canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pcanvas.addEventListener('pointermove', event => {if (!canvas.hasPointerCapture(event.pointerId)) return;state.yaw -= event.movementX * 0.01;- state.pitch = Math.min(1.3, Math.max(0.15, state.pitch + event.movementY * 0.01));+ state.pitch = Math.min(1.3, Math.max(0.1, state.pitch + event.movementY * 0.01));draw();});new ResizeObserver(() => { renderer.resize(); draw(); }).observe(canvas);addEventListener('pagehide', () => renderer.dispose());```-The sliders apply on release (the `change` event), because each change rebuilds the triangle lists. The real addon does this per vertex in the shader, so the rules cost nothing on the CPU and blend smoothly instead of switching per triangle.+Slide the ball to x = 20: it sits over the hole, and `heightAt` still returns a number, because it ignores holes. That is why the common mistakes below say to check `isHole` first.++## Ground textures and splat rules-## Build the real terrain+The docs host has no CC0 scans to load, so the splat part of the call stays a plain block. The rules work per vertex in the shader. A layer with a `slope` range takes the steep parts, a `height` range takes a band of altitude, and a layer with no rule takes what the others leave. Put grass first with no rule, rock second with a slope rule and snow last with a height rule.1. Load a texture set per layer, then give the layers to one material: `const set = await loadTextureSet('/textures/leafy_grass')`, `material.layers = [{ ...set, scale: 3 }, ...]` and `material.splat = { rules }`.-2. Create the heightfield: `const terrain = createTerrain({ size, chunks, resolution, levels, seed })`. Give every entry of `terrain.parts` the one shared material.+2. Create the heightfield with that material, as in the example above. Every entry of `terrain.parts` shares it.3. Pass `terrain.heightAt` to `scatterVegetation` and to vehicles, and call `renderer.replaceParts` when `terrain.update(eye)` returns parts.```js-import { Renderer67 } from '67js';-import { createTerrain } from '67js/addons/terrain';import { loadTextureSet } from '67js/addons/texture-set';const material = { color: [1, 1, 1], metallic: 0, roughness: 1, tag: 'standard' };@@ -130,14 +92,6 @@ material.layers = [{ ...await loadTextureSet('/textures/rock'), scale: 4, triplanar: true },];material.splat = { rules: [undefined, { slope: [32, 90], slopeSoftness: 6 }] };--const terrain = createTerrain({ size: 600, chunks: 10, resolution: 32, levels: 4, seed: 7, material });-const renderer = new Renderer67(canvas, terrain.parts, { world: true });-function draw(eye) {- const changed = terrain.update(eye);- if (changed.length) renderer.replaceParts(terrain.parts);- renderer.render({ eye, target: [0, 0, 0] });-}```## Optionsdiff --git a/docs/learn/trees-and-grass.md b/docs/learn/trees-and-grass.mdindex 96f01c19..04f4f034 100644--- a/docs/learn/trees-and-grass.md+++ b/docs/learn/trees-and-grass.md@@ -4,87 +4,46 @@## Scatter, then pick detail by distance-The docs run with the core module only, so this example scatters trees by hand and mirrors what the addon returns: a seeded scatter with a slope limit and an exclusion zone, and a per-camera level choice. Drag to orbit and the near trees get the detailed crown while the far ones get a coarse one. The slider changes the density. The console prints what `selectLevels` reports: level counts and triangles.+The example calls `scatterVegetation` for a seeded scatter with a slope limit and an exclusion zone, then `selectLevels` for the detail of each tree from the camera. Drag to orbit and scroll to move closer: the near trees get the detailed crown, the far ones a coarse one. The slider changes the density. The console prints what the two calls return: counts per species, level counts, culled instances and triangles. Leaf cards use the built-in 128 px sprites here, because the docs host has no scanned leaf textures.```js live poster=trees-scatter-import { Renderer67, cylinder, sphere } from '67js';--function random(seed) {- let value = seed >>> 0;- return () => {- value = (value * 1664525 + 1013904223) >>> 0;- return value / 4294967296;- };-}+import { Renderer67 } from '67js';+import { scatterVegetation, selectLevels } from '67js/addons/vegetation';+const terrainHeight = (x, z) => 1.5 * Math.sin(x * 0.18) * Math.cos(z * 0.15);-const slopeAt = (x, z) => Math.atan(Math.hypot(terrainHeight(x + 0.6, z) - terrainHeight(x - 0.6, z), terrainHeight(x, z + 0.6) - terrainHeight(x, z - 0.6)) / 1.2) * 180 / Math.PI;const exclusion = (x, z) => Math.hypot(x, z) < 3.5;+const area = { minX: -25, maxX: 25, minZ: -25, maxZ: 25 };-// Jittered grid: each cell holds at most one tree, so spacing is at least about half a cell.-function scatter({ area, density, slopeLimit, seed }) {- const next = random(seed);- const cell = Math.sqrt(1 / density);- const instances = [];- for (let x = -area / 2; x < area / 2; x += cell) {- for (let z = -area / 2; z < area / 2; z += cell) {- const px = x + next() * cell;- const pz = z + next() * cell;- if (exclusion(px, pz) || slopeAt(px, pz) > slopeLimit) continue;- instances.push({ x: px, z: pz, y: terrainHeight(px, pz), scale: 0.8 + next() * 0.6, variant: Math.floor(next() * 3) });- }- }- return instances;+function scatter(density) {+ const started = performance.now();+ const forest = scatterVegetation({+ area, density, terrainHeight, slopeLimit: 14, exclusion, seed: 11,+ mix: { broadleaf: 3, birch: 1, bush: 2 }, variants: 2,+ });+ console.log(`density ${density} per m²:`, forest.counts, `${Math.round(performance.now() - started)} ms`);+ return forest;}-const trunk = cylinder(12, 0.02, 2);-const crownLevels = [sphere(20, 14), sphere(8, 6)];-const crownMaterials = [0, 1, 2].map(variant => ({ color: [0.12 + variant * 0.04, 0.38 + variant * 0.05, 0.14], metallic: 0, roughness: 0.8 }));-const trunkMaterial = { color: [0.3, 0.2, 0.12], metallic: 0, roughness: 0.9 };-const triangles = geometry => geometry.indices.length / 3;--const state = { density: 0.35, yaw: 0.7, distance: 24, pitch: 0.5 };-let instances = scatter({ area: 40, density: state.density, slopeLimit: 14, seed: 11 });-let levels = [];+const state = { density: 0.02, yaw: 0.7, distance: 30, pitch: 0.5 };+let forest = scatter(state.density);function eye() {const flat = Math.cos(state.pitch) * state.distance;return [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance + 2, Math.cos(state.yaw) * flat];}-// Level 0 within 14 m of the camera, level 1 beyond it. Part objects are cached, so unchanged instances keep their identity.-function selectLevels(position) {- let changed = false;- const counts = [0, 0];- let totalTriangles = 0;- instances.forEach((tree, index) => {- const level = Math.hypot(tree.x - position[0], tree.z - position[2]) < 14 ? 0 : 1;- if (levels[index] !== level) changed = true;- levels[index] = level;- counts[level]++;- totalTriangles += triangles(trunk) + triangles(crownLevels[level]);- });- return { changed, counts, totalTriangles };-}--function partsFor() {- return instances.flatMap((tree, index) => [- { name: `Trunk ${index}`, geometry: trunk, matrix: new Float32Array([0.18 * tree.scale, 0, 0, 0, 0, 1.2 * tree.scale, 0, 0, 0, 0, 0.18 * tree.scale, 0, tree.x, tree.y + 0.6 * tree.scale, tree.z, 1]), material: trunkMaterial },- { name: `Crown ${index}`, geometry: crownLevels[levels[index]], matrix: new Float32Array([0.9 * tree.scale, 0, 0, 0, 0, 1.1 * tree.scale, 0, 0, 0, 0, 0.9 * tree.scale, 0, tree.x, tree.y + 1.7 * tree.scale, tree.z, 1]), material: crownMaterials[tree.variant] },- ]);-}-const canvas = document.querySelector('#scene');canvas.style.touchAction = 'none';-const first = selectLevels(eye());-console.log(`scattered ${instances.length} trees, 3 variants, slope limit 14°`, first);-const renderer = new Renderer67(canvas, partsFor(), { world: true });+let view = selectLevels(forest.instances, eye());+const renderer = new Renderer67(canvas, view.parts, { world: true });+console.log('first view:', { levelCounts: view.levelCounts, culled: view.culled, triangles: view.triangles });function draw() {const position = eye();- const result = selectLevels(position);- if (result.changed) {- renderer.replaceParts(partsFor());- console.log('levels changed:', { levelCounts: result.counts, triangles: result.totalTriangles });+ view = selectLevels(forest.instances, position);+ if (view.changed) {+ renderer.replaceParts(view.parts);+ console.log('levels changed:', { levelCounts: view.levelCounts, culled: view.culled, triangles: view.triangles });}renderer.render({ eye: position, target: [0, 1, 0], fov: 45 });}@@ -98,25 +57,24 @@ canvas.addEventListener('pointermove', event => {});canvas.addEventListener('wheel', event => {event.preventDefault();- state.distance = Math.min(40, Math.max(6, state.distance * Math.exp(event.deltaY * 0.001)));+ state.distance = Math.min(45, Math.max(5, state.distance * Math.exp(event.deltaY * 0.001)));draw();}, { passive: false });const slider = document.createElement('input');slider.type = 'range';-slider.min = 0.1;-slider.max = 0.8;-slider.step = 0.05;+slider.min = 0.01;+slider.max = 0.06;+slider.step = 0.005;slider.value = state.density;slider.setAttribute('aria-label', 'Trees per square metre');slider.style.cssText = 'position:fixed;left:8px;bottom:8px;width:40%';slider.addEventListener('change', () => {state.density = Number(slider.value);- instances = scatter({ area: 40, density: state.density, slopeLimit: 14, seed: 11 });- levels = [];- selectLevels(eye());- renderer.replaceParts(partsFor());- console.log(`density ${state.density} per m²: ${instances.length} trees`);+ forest = scatter(state.density);+ view = selectLevels(forest.instances, eye());+ renderer.replaceParts(view.parts);+ console.log('after scatter:', { levelCounts: view.levelCounts, triangles: view.triangles });draw();});document.body.append(slider);@@ -125,11 +83,13 @@ draw();addEventListener('pagehide', () => renderer.dispose());```-## Grow the real forest+Levels change only after a distance passes a threshold by `hysteresis`, so a tree on the boundary does not flicker between two crowns while you orbit.++## Grow the real forest with scanned leaves++The scanned leaf cards need the CC0 files, which the docs host does not serve, so this call stays a plain block. It is the example above with `leafTextures` added:```js-import { Renderer67 } from '67js';-import { scatterVegetation, selectLevels } from '67js/addons/vegetation';import { loadLeafTextures } from '67js/addons/texture-set';const forest = scatterVegetation({@@ -141,9 +101,6 @@ const forest = scatterVegetation({mix: { broadleaf: 3, birch: 1, bush: 2 },leafTextures: await loadLeafTextures('/textures/leaves'),});-let view = selectLevels(forest.instances, eye);-const renderer = new Renderer67(canvas, view.parts, { world: true });-console.log(forest.counts, view.levelCounts, view.triangles);```1. Scatter with `scatterVegetation({ area, density, terrainHeight, slopeLimit, exclusion, mix, leaves })`.diff --git a/docs/learn/wheeled-vehicles.md b/docs/learn/wheeled-vehicles.mdindex 9d7cfc2c..05d3eb23 100644--- a/docs/learn/wheeled-vehicles.md+++ b/docs/learn/wheeled-vehicles.md@@ -2,97 +2,109 @@`67js/addons/vehicle` drives a car or truck along a path with deterministic, physics-free animation. It is available from version `0.10.0`. Wheel spin, front-wheel steering, roll, pitch and ground following all come from the path, and `sample(seconds)` gives the same pose for the same time.-## The maths behind a drive+## Drive a real vehicle-The docs run with the core module only, so this example builds a car from boxes and cylinders and applies the same rules by hand on a circular path: wheel spin is `distance / radius`, the steer angle is `atan(wheelbase * curvature)` with Ackermann angles per front wheel, and roll follows lateral acceleration. Drag the speed slider. Faster driving leans the body more. The console prints the pose once a second.+The example builds a car from a box body and four wheel parts named `Wheel FL`, `Wheel FR`, `Wheel RL` and `Wheel RR`, each a cylinder whose axle runs along x. It passes them to `createVehicleRig`, which finds the wheels by name and geometry, then drives them around an oval with `driveAlongPath`. Drag to orbit and change the speed with the slider. The console prints the rig (wheel count, wheelbase, track width), the length and duration of each drive, and once a second the pose: distance, steer angle, roll and the spin of the front-left wheel.```js live poster=vehicle-drive-import { Renderer67, box, cylinder } from '67js';--const multiply = (a, b) => {- const out = new Float32Array(16);- for (let column = 0; column < 4; column++) {- for (let row = 0; row < 4; row++) {- let sum = 0;- for (let k = 0; k < 4; k++) sum += a[k * 4 + row] * b[column * 4 + k];- out[column * 4 + row] = sum;+import { Renderer67 } from '67js';+import { createVehicleRig, driveAlongPath, applyVehiclePoseToParts } from '67js/addons/vehicle';++// Geometry at rest in the model's own coordinates: forward is +z, left is +x, the ground is y = 0.+function boxGeometry(center, size) {+ const positions = [];+ const normals = [];+ const indices = [];+ for (const [axis, sign] of [[0, 1], [0, -1], [1, 1], [1, -1], [2, 1], [2, -1]]) {+ const first = (axis + 1) % 3;+ const second = (axis + 2) % 3;+ const base = positions.length / 3;+ for (const [a, b] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {+ const point = [0, 0, 0];+ point[axis] = center[axis] + sign * size[axis] / 2;+ point[first] = center[first] + a * size[first] / 2;+ point[second] = center[second] + b * size[second] / 2;+ positions.push(...point);+ const normal = [0, 0, 0];+ normal[axis] = sign;+ normals.push(...normal);}+ indices.push(...(sign > 0 ? [0, 1, 2, 0, 2, 3] : [0, 2, 1, 0, 3, 2]).map(index => base + index));}- return out;-};-const move = (x, y, z) => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]);-const scale = (x, y, z) => new Float32Array([x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]);-const turnY = a => new Float32Array([Math.cos(a), 0, -Math.sin(a), 0, 0, 1, 0, 0, Math.sin(a), 0, Math.cos(a), 0, 0, 0, 0, 1]);-const turnX = a => new Float32Array([1, 0, 0, 0, 0, Math.cos(a), Math.sin(a), 0, 0, -Math.sin(a), Math.cos(a), 0, 0, 0, 0, 1]);-const turnZ = a => new Float32Array([Math.cos(a), Math.sin(a), 0, 0, -Math.sin(a), Math.cos(a), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);--const wheelRadius = 0.35;-const wheelbase = 2.6;-const trackWidth = 1.5;-const pathRadius = 6;-const rollGain = 0.012;-const wheelSpecs = [- { id: 'front left', x: trackWidth / 2, z: wheelbase / 2, front: true },- { id: 'front right', x: -trackWidth / 2, z: wheelbase / 2, front: true },- { id: 'rear left', x: trackWidth / 2, z: -wheelbase / 2, front: false },- { id: 'rear right', x: -trackWidth / 2, z: -wheelbase / 2, front: false },-];+ return { positions: new Float32Array(positions), normals: new Float32Array(normals), indices: new Uint32Array(indices) };+}-const bodyPart = { name: 'Body', geometry: box(0.1, 3), matrix: scale(1.8, 0.55, 4), material: { color: [0.8, 0.2, 0.18], metallic: 0.3, roughness: 0.35 } };-const cabinPart = { name: 'Cabin', geometry: box(0.15, 3), matrix: scale(1.5, 0.5, 2), material: { color: [0.15, 0.2, 0.28], metallic: 0, roughness: 0.2 } };-const tire = cylinder(24, 0.05, 2);-const wheelParts = wheelSpecs.map(spec => ({ name: `Wheel ${spec.id}`, geometry: tire, matrix: scale(1, 1, 1), material: { color: [0.06, 0.06, 0.07], metallic: 0, roughness: 0.8 } }));-const parts = [bodyPart, cabinPart, ...wheelParts];--// The pose for a time, from the path alone: nothing depends on the previous frame.-function sample(seconds, speed) {- const distance = speed * seconds;- const angle = distance / pathRadius;- const curvature = 1 / pathRadius;- const steer = Math.atan(wheelbase * curvature);- const lateral = speed * speed * curvature;- return {- time: seconds,- distance,- speed,- position: [pathRadius * Math.sin(angle), 0, pathRadius * Math.cos(angle) - pathRadius],- heading: Math.PI / 2 + angle,- roll: rollGain * lateral,- steerAngle: steer,- wheels: wheelSpecs.map(spec => {- const side = spec.x > 0 ? 1 : -1;- const turnRadius = pathRadius - side * spec.x;- const ackermann = spec.front ? Math.atan2(spec.z + wheelbase / 2, turnRadius) : 0;- return { id: spec.id, spinAngle: distance * (turnRadius / pathRadius) / wheelRadius, steerAngle: ackermann };- }),- };+function wheelGeometry(center, radius, width) {+ const positions = [];+ const normals = [];+ const indices = [];+ const steps = 24;+ for (let step = 0; step < steps; step++) {+ const angle = step / steps * Math.PI * 2;+ const up = Math.sin(angle);+ const ahead = Math.cos(angle);+ for (const side of [-1, 1]) {+ positions.push(center[0] + side * width / 2, center[1] + up * radius, center[2] + ahead * radius);+ normals.push(0, up, ahead);+ }+ const next = (step + 1) % steps;+ indices.push(step * 2, step * 2 + 1, next * 2, step * 2 + 1, next * 2 + 1, next * 2);+ }+ for (const side of [-1, 1]) {+ const hub = positions.length / 3;+ positions.push(center[0] + side * width / 2, center[1], center[2]);+ normals.push(side, 0, 0);+ const ring = positions.length / 3;+ for (let step = 0; step < steps; step++) {+ const angle = step / steps * Math.PI * 2;+ positions.push(center[0] + side * width / 2, center[1] + Math.sin(angle) * radius, center[2] + Math.cos(angle) * radius);+ normals.push(side, 0, 0);+ }+ for (let step = 0; step < steps; step++) {+ const next = (step + 1) % steps;+ indices.push(...(side > 0 ? [hub, ring + next, ring + step] : [hub, ring + step, ring + next]));+ }+ }+ return { positions: new Float32Array(positions), normals: new Float32Array(normals), indices: new Uint32Array(indices) };}-function apply(pose) {- const frame = multiply(multiply(move(...pose.position), turnY(pose.heading)), turnZ(pose.roll));- parts[0].matrix = multiply(frame, multiply(move(0, 0.65, 0), scale(1.8, 0.55, 4)));- parts[1].matrix = multiply(frame, multiply(move(0, 1.15, -0.2), scale(1.5, 0.5, 2)));- pose.wheels.forEach((wheel, index) => {- const spec = wheelSpecs[index];- const local = multiply(move(spec.x, wheelRadius, spec.z), multiply(turnY(wheel.steerAngle), multiply(turnX(-wheel.spinAngle), multiply(turnZ(Math.PI / 2), scale(wheelRadius, 0.28, wheelRadius)))));- parts[2 + index].matrix = multiply(frame, local);- });+const identity = () => new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);+const tireMaterial = { color: [0.06, 0.06, 0.07], metallic: 0, roughness: 0.8 };+const corners = [['FL', 0.8, 1.3], ['FR', -0.8, 1.3], ['RL', 0.8, -1.3], ['RR', -0.8, -1.3]];+const parts = [+ { name: 'Body', geometry: boxGeometry([0, 0.75, 0], [1.6, 0.5, 3.6]), matrix: identity(), material: { color: [0.8, 0.2, 0.18], metallic: 0.3, roughness: 0.35 } },+ { name: 'Cabin', geometry: boxGeometry([0, 1.2, -0.2], [1.4, 0.45, 1.8]), matrix: identity(), material: { color: [0.15, 0.2, 0.28], metallic: 0, roughness: 0.2 } },+ ...corners.map(([id, x, z]) => ({ name: `Wheel ${id}`, geometry: wheelGeometry([x, 0.35, z], 0.35, 0.25), matrix: identity(), material: tireMaterial })),+];++const rig = createVehicleRig({ parts, body: [parts[0], parts[1]] });+console.log(`rig: ${rig.wheels.length} wheels, wheelbase ${rig.wheelbase.toFixed(2)} m, track ${rig.trackWidth.toFixed(2)} m`);++const oval = Array.from({ length: 16 }, (unused, index) => {+ const angle = index / 16 * Math.PI * 2;+ return [10 * Math.sin(angle), 0, 6 * Math.cos(angle)];+});+function makeDrive(speed) {+ const drive = driveAlongPath(rig, oval, { speed });+ console.log(`speed ${speed} m/s: path ${drive.length.toFixed(1)} m, one pass takes ${drive.duration.toFixed(1)} s`);+ return drive;}const canvas = document.querySelector('#scene');canvas.style.touchAction = 'none';-const renderer = new Renderer67(canvas, parts);-const state = { speed: 6, yaw: 0.5, pitch: 0.7, distance: 17, playing: true };+const renderer = new Renderer67(canvas, parts, { world: true });+const state = { speed: 6, yaw: 0.5, pitch: 0.6, distance: 24, playing: true };+let drive = makeDrive(state.speed);let seconds = 0;let last = performance.now();let nextLog = 0;function draw() {- const pose = sample(seconds, state.speed);- apply(pose);+ const pose = drive.sample(seconds % drive.duration);+ applyVehiclePoseToParts(rig, pose);renderer.updateParts(parts);const flat = Math.cos(state.pitch) * state.distance;- renderer.render({ eye: [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance, Math.cos(state.yaw) * flat - pathRadius], target: [0, 0.5, -pathRadius], fov: 42 });+ renderer.render({ eye: [Math.sin(state.yaw) * flat, Math.sin(state.pitch) * state.distance, Math.cos(state.yaw) * flat], target: [0, 0.5, 0], fov: 42 });return pose;}@@ -114,12 +126,16 @@ toggle.textContent = 'Pause';toggle.addEventListener('click', () => { state.playing = !state.playing; toggle.textContent = state.playing ? 'Pause' : 'Play'; });const speed = document.createElement('input');speed.type = 'range';-speed.min = 1;+speed.min = 2;speed.max = 14;speed.step = 0.5;speed.value = state.speed;-speed.addEventListener('input', () => { state.speed = Number(speed.value); });-speed.addEventListener('change', () => console.log(`speed ${state.speed} m/s, lateral acceleration ${(state.speed ** 2 / pathRadius).toFixed(2)} m/s²`));+speed.addEventListener('change', () => {+ state.speed = Number(speed.value);+ drive = makeDrive(state.speed);+ seconds = 0;+ nextLog = 0;+});bar.append(toggle, 'speed', speed);document.body.append(bar);canvas.addEventListener('pointerdown', event => canvas.setPointerCapture(event.pointerId));@@ -133,30 +149,12 @@ requestAnimationFrame(frame);addEventListener('pagehide', () => renderer.dispose());```-In this model the inside wheels spin slower in the corner because their path is shorter, as in the addon, where they turn slower by their lateral offset times the heading change.+The lean you see at speed is `rollGain` times the lateral acceleration. A wheel spins by the distance it covers divided by its radius, and the inside wheels of a corner spin slower because their path is shorter. The drive holds the end of the path, so the example samples at `seconds % drive.duration` to go round again.-## Drive a real vehicle--1. Describe the vehicle with `createVehicleRig({ parts })`. Wheels are found by name and geometry. Check `rig.wheels` or `findWheelCandidates(names)`.-2. Build a drive with `driveAlongPath(rig, points, { cruiseSpeed, groundHeight })`.+1. Describe the vehicle with `createVehicleRig({ parts })`. Check `rig.wheels` or `findWheelCandidates(names)` when a wheel is missed.+2. Build a drive with `driveAlongPath(rig, points, { cruiseSpeed, groundHeight })`. Pass `groundHeight: terrain.heightAt` to follow a terrain, and `cruiseSpeed` for a natural start and stop.3. Each frame, call `applyVehiclePoseToParts(rig, drive.sample(seconds))` and then `renderer.updateParts(parts)`.-```js-import { Renderer67 } from '67js';-import { createVehicleRig, driveAlongPath, applyVehiclePoseToParts } from '67js/addons/vehicle';--const rig = createVehicleRig({ parts: carParts });-console.log(rig.wheels.length, rig.wheelbase, rig.trackWidth);-const drive = driveAlongPath(rig, [[0, 0, 0], [10, 0, 4], [20, 0, 4], [30, 0, 0]], { cruiseSpeed: 8, groundHeight: terrain.heightAt });-const renderer = new Renderer67(canvas, [...sceneParts, ...carParts]);-function draw(seconds) {- const pose = drive.sample(Math.min(seconds, drive.duration));- applyVehiclePoseToParts(rig, pose);- renderer.updateParts(carParts);- renderer.render({ eye, target: pose.position });-}-```-Scene-graph nodes and imported GLBs use `applyVehiclePoseToSceneGraph` and `applyVehiclePoseToAsset`.## Conventions and optionsdiff --git a/public/docs-media/crowd-walk.webp b/public/docs-media/crowd-walk.webpindex 722a3493..62261b60 100644Binary files a/public/docs-media/crowd-walk.webp and b/public/docs-media/crowd-walk.webp differdiff --git a/public/docs-media/grass-tiles.webp b/public/docs-media/grass-tiles.webpindex 7ac19c55..3552162e 100644Binary files a/public/docs-media/grass-tiles.webp and b/public/docs-media/grass-tiles.webp differdiff --git a/public/docs-media/physics-recording.webp b/public/docs-media/physics-recording.webpindex ca4c1032..cf4c090a 100644Binary files a/public/docs-media/physics-recording.webp and b/public/docs-media/physics-recording.webp differdiff --git a/public/docs-media/spume-playback.webp b/public/docs-media/spume-playback.webpindex 26a1832b..1fd17127 100644Binary files a/public/docs-media/spume-playback.webp and b/public/docs-media/spume-playback.webp differdiff --git a/public/docs-media/terrain-rules.webp b/public/docs-media/terrain-rules.webpindex fa2401d3..92671c55 100644Binary files a/public/docs-media/terrain-rules.webp and b/public/docs-media/terrain-rules.webp differdiff --git a/public/docs-media/trees-scatter.webp b/public/docs-media/trees-scatter.webpindex cf972f6b..b37b5e99 100644Binary files a/public/docs-media/trees-scatter.webp and b/public/docs-media/trees-scatter.webp differdiff --git a/public/docs-media/vehicle-drive.webp b/public/docs-media/vehicle-drive.webpindex 68af9379..5ae2e6db 100644Binary files a/public/docs-media/vehicle-drive.webp and b/public/docs-media/vehicle-drive.webp differ