3D engine that AI agents drive
Add frustum culling, level selection and adaptive resolution
Nguyen Xuan Anbac4f5296ea9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d7336b46..208264ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add frustum culling, levels of detail and live adaptive resolution (part of issue #37). `Renderer67` tests each instance of a batch against the view frustum with the geometry's bounding sphere and draws only the visible ones (on by default, `culling: false` turns it off; skinned, morphed, swaying, fire, smoke, water, assembly and blended batches and the shadow passes are not culled). A part's `lods`, the array from `generateGeometryLods`, makes each instance pick a level by pixel error (`lodPixelError`, default 1). Selection is a pure function of the camera and the matrices, so a seek draws the same frame. `createGpuTimer` and `AdaptiveResolution` in `src/adaptive-quality.js` give live viewers GPU timing and a resolution scale with a minimum; an export can not build one, and `src/main.js` uses it only outside `export=1`. New `large-outdoor` scene in `bench/runtime` with ablations: 1.55 ms against 8.41 ms without culling and 6.0 ms for three.js on an RTX 3060, 517 ms against 4,428 ms and 944 ms on SwiftShader. Core grows 1,845 bytes gzip (budget 81,500). Recipes cannot declare `lods` yet. See `docs/culling-lod.md`.+- Use one expression language for fields and drivers (issue #98). `src/expression.js` holds the limits, number literals, operator table, syntax and hostile-input checks; `src/mesh-fields.js` (per mesh element: attributes, noise, random, vectors) and `src/motion-expression.js` (per time: `time`, node reads) only add their own inputs, and each rejects the other's with a message that names the context. **This changes driver expressions** (neither language was released): an operator with one operand may be written bare, `{"neg": x}`, in drivers as in fields; `if` takes its second operand when the condition is not 0 (a driver used above 0); `sqrt` of a negative, `pow` overflow and `mod` by 0 give 0 instead of an error; `smoothstep` with equal edges is a step; `div` by 0 is still a non-finite error in a driver, because a hostile-input test pins it, and 0 in a field. Drivers gain `ceil`, `round`, `sign`, `lte`, `gte`, `eq`, `and`, `or`, `not` and booleans; fields gain `atan2` and `saturate`. The unknown-operator hint of fields lists operators in a new order. Error messages for a malformed driver changed in wording and are all TypeErrors. The MCP schema for drivers now points at the field language instead of listing operators (schemas 183,741 to 183,762 bytes), and the `scene_capabilities` budget rises from 3,050 to 3,100 bytes for two operator names.- Add branches and labelled images to the agent tools (part of issue #67, no new tool). `scene_apply` with a `branch` name runs the operations on a scratch copy and stores the result in a snapshot store that holds one copy per distinct recipe (8 branches), leaving the scene, its revision and its checkpoints untouched. `scene_review` shots take a `branch` and render it in a private scene; `scene_restore` with `branch` keeps one. `labels: true` on `scene_look` and `scene_review` draws part names, material tags and mesh lint problems on the image and returns them as JSON with pixel positions. Branch names are bounded (`^[a-z][a-z0-9_-]{0,23}$`). The tool-schema budget rose by 800 bytes in total (150 for `scene_apply`). `npm run smoke:agent-branches` drives it through MCP on SwiftShader.diff --git a/bench/runtime/README.md b/bench/runtime/README.mdindex e43990e4..071b3909 100644--- a/bench/runtime/README.md+++ b/bench/runtime/README.md@@ -2,6 +2,19 @@This suite compares what a frame costs in 67.js and in three.js on 7 matching scenes. **three.js wins most of them today.**+## Culling and levels of detail (issue 37)++Scene `large-outdoor` has 6,000 spheres of about 1,000 triangles over 600 by 600 units, seen from the edge, so about a quarter of them are in view and most are far. `67js` uses the default frustum culling and the levels from `generateGeometryLods` (ratios 0.25 and 0.06, 1 pixel of error). `67js-no-lod` has culling only, and `67js-no-culling` has neither, which is what the renderer did before. three.js draws 6,000 individual meshes, which it culls per mesh, without levels. Measured on 2026-10-31 at 960 by 540, `--frames 30`, other jobs were using the RTX 3060 between 1 and 87 percent (`gpuBusyBefore` in a full report), so the GPU numbers are noisy.++| Engine | RTX 3060 frame (ms) | Triangles | SwiftShader frame (ms) |+| --- | --- | --- | --- |+| `67js-no-culling` | 8.41 | 5,760,014 | 4,428 |+| `67js-no-lod` (culling) | 7.68 | 4,359,374 | 4,061 |+| `67js` (culling and levels) | 1.55 | 270,474 | 517 |+| three.js | 6.00 | 4,359,372 | 944 |++Culling alone gives the same picture pixel for pixel as no culling, on both backends. Levels change 1.9 percent of the pixels by more than 8 levels (mean absolute difference 0.45 of 255). The other 7 scenes draw the same pictures as before pixel for pixel on the RTX 3060 (checked on 4 of them), and their frame times moved within the noise. The run draws the first frame again after the measured frames and fails when the `large-outdoor` picture differs.+## Run itRun `npm run benchmark:runtime`. It takes about 8 minutes, and it rewrites `report.json`. Stop other GPU work first, because `report.json` records how busy the GPU was before each run.diff --git a/bench/runtime/adapters.js b/bench/runtime/adapters.jsindex c7627b76..e1d9806b 100644--- a/bench/runtime/adapters.js+++ b/bench/runtime/adapters.js@@ -9,6 +9,7 @@ import { clone as cloneSkeleton } from 'three/addons/utils/SkeletonUtils.js';import { Renderer67 } from '/src/renderer.js';import { createEnvironmentMap } from '/src/hdri.js';import { parseGltf } from '/src/gltf.js';+import { generateGeometryLods } from '/src/mesh-lod.js';const AMBIENT_RADIANCE = 0.3;const SECONDS_PER_CHARACTER_OFFSET = 0.4;@@ -32,7 +33,14 @@ function engineMaterial(material) {return { tag: 'surface', emission: 0, ...rest, ...(opacity === undefined ? {} : { alphaMode: 'blend', opacity }) };}-export async function create67Adapter(canvas, scene, characters) {+// The options turn culling and level selection off one at a time, so each one's share of a measured gain can be told apart.+function levelsForScene(scene) {+ const levels = new Map();+ for (const [name, ratios] of Object.entries(scene.lods ?? {})) levels.set(name, generateGeometryLods(scene.geometries[name], { ratios }));+ return levels;+}++export async function create67Adapter(canvas, scene, characters, { culling = true, lods = true } = {}) {const environment = {world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0,lightDirection: scene.sun.direction, keyColor: scene.sun.color,@@ -41,8 +49,10 @@ export async function create67Adapter(canvas, scene, characters) {width: 8, height: 4, data: new Float32Array(8 * 4 * 3).fill(AMBIENT_RADIANCE), showBackground: true,}),};+ const lodsByGeometry = lods ? levelsForScene(scene) : new Map();const parts = scene.objects.map((object, index) => ({name: `object-${index}`, geometry: scene.geometries[object.geometry], matrix: object.matrix, material: engineMaterial(object.material),+ ...(lodsByGeometry.has(object.geometry) ? { lods: lodsByGeometry.get(object.geometry) } : {}),}));const assets = [];if (characters) {@@ -57,7 +67,7 @@ export async function create67Adapter(canvas, scene, characters) {? { eye: scene.sun.direction.map(value => value * 5), target: [0, 0, 0], up: [0, 1, 0], extent: scene.shadowExtent, near: 0.1, far: 150 }: {};const renderer = new Renderer67(canvas, parts, {- ground: false, hdr: true, depth: false, samples: 4, pixelRatio: 1, memoryBudgetMiB: 2048, world: true, environment, shadowBounds,+ ground: false, hdr: true, depth: false, samples: 4, pixelRatio: 1, memoryBudgetMiB: 2048, world: true, environment, shadowBounds, culling,});renderer.resize();const frame = { eye: scene.camera.eye, target: scene.camera.target, up: [0, 1, 0], fov: scene.camera.fov, near: scene.camera.near, far: scene.camera.far, environment, time: 0, exposure: 1, effects: {} };diff --git a/bench/runtime/harness.js b/bench/runtime/harness.jsindex 1b7feaa2..4b038827 100644--- a/bench/runtime/harness.js+++ b/bench/runtime/harness.js@@ -108,6 +108,8 @@ async function readTimerQueries(context, queries, timer) {async function createAdapter(engine, canvas, scene, characters) {if (engine === '67js') return create67Adapter(canvas, scene, characters);+ if (engine === '67js-no-lod') return create67Adapter(canvas, scene, characters, { lods: false });+ if (engine === '67js-no-culling') return create67Adapter(canvas, scene, characters, { culling: false, lods: false });if (engine === 'three-instanced') return createThreeAdapter(canvas, scene, characters, { instanced: true });return createThreeAdapter(canvas, scene, characters);}@@ -125,6 +127,7 @@ async function runBenchmark(sceneId, engine, frames) {adapter.render();waitForGpu(adapter.context);const firstFrameMilliseconds = performance.now() - started;+ const firstImage = canvas.toDataURL('image/png');const timer = adapter.context.getExtension('EXT_disjoint_timer_query_webgl2');let time = 0;for (let frame = 0; frame < WARMUP_FRAMES; frame++) {@@ -164,7 +167,8 @@ async function runBenchmark(sceneId, engine, frames) {const triangles = watcher.counters.triangles / frames;adapter.update(0);adapter.render();- const image = canvas.toDataURL('image/png').split(',')[1];+ const finalImage = canvas.toDataURL('image/png');+ const image = finalImage.split(',')[1];const result = {scene: sceneId, engine,firstFrameMilliseconds,@@ -176,6 +180,8 @@ async function runBenchmark(sceneId, engine, frames) {gpuBytes: watcher.gpuBytes(),heapBytes: heapBefore === null ? null : heapBytes() - heapBefore,glError: adapter.context.getError(),+ // The frame at time 0 after many frames must match the first frame drawn: nothing may depend on what came before.+ repeatable: finalImage === firstImage,image,};adapter.dispose();diff --git a/bench/runtime/run.mjs b/bench/runtime/run.mjsindex 5e482aa0..afb7528e 100644--- a/bench/runtime/run.mjs+++ b/bench/runtime/run.mjs@@ -16,8 +16,11 @@ const BACKENDS = {gpu: { arguments: SHARED_ARGUMENTS, frames: 120 },cpu: { arguments: [...SHARED_ARGUMENTS, '--use-angle=swiftshader', '--enable-unsafe-swiftshader'], frames: 15 },};-const ENGINES = ['67js', 'three', 'three-instanced'];+const ENGINES = ['67js', 'three', 'three-instanced', '67js-no-lod', '67js-no-culling'];const INSTANCED_SCENES = new Set(['instanced-objects']);+// Ablations of this renderer's own culling and level selection, which only a scene that has them can show.+const ABLATION_SCENES = new Set(['large-outdoor']);+const ABLATION_ENGINES = new Set(['67js-no-lod', '67js-no-culling']);const flags = process.argv.slice(2);const gpuOnly = flags.includes('--gpu-only');@@ -32,6 +35,7 @@ const isPartialRun = Boolean(onlyScene || onlyEngine || framesOverride);function enginesFor(sceneId) {return ENGINES.filter(engine => {if (onlyEngine) return engine === onlyEngine;+ if (ABLATION_ENGINES.has(engine)) return ABLATION_SCENES.has(sceneId);return engine !== 'three-instanced' || INSTANCED_SCENES.has(sceneId);});}@@ -47,6 +51,8 @@ async function runOne(backend, serverUrl, sceneId, engine, frames) {await page.waitForFunction(() => window.runBenchmark);const result = await page.evaluate(([scene, name, count]) => window.runBenchmark(scene, name, count), [sceneId, engine, frames]);if (errors.length) throw new Error(errors.join('\n'));+ // Blended scenes already differ between their first and later frames before culling existed, so only the scene that tests culling is held to this.+ if (!result.repeatable && ABLATION_SCENES.has(sceneId) && engine.startsWith('67js')) throw new Error(`${sceneId} on ${engine} drew a different picture for the same time.`);if (result.glError !== 0) throw new Error(`${sceneId} on ${engine} gave WebGL error ${result.glError}.`);return result;} finally {@@ -73,7 +79,7 @@ function rounded(value, digits = 2) {return value === null ? null : Number(value.toFixed(digits));}-function summarize({ image: _image, glError: _glError, scene: _scene, engine: _engine, ...result }) {+function summarize({ image: _image, repeatable: _repeatable, glError: _glError, scene: _scene, engine: _engine, ...result }) {return {firstFrameMilliseconds: rounded(result.firstFrameMilliseconds, 0),updateMilliseconds: rounded(result.updateMilliseconds),diff --git a/bench/runtime/scenes.js b/bench/runtime/scenes.jsindex 6e3de2a4..4352d52d 100644--- a/bench/runtime/scenes.js+++ b/bench/runtime/scenes.js@@ -32,6 +32,28 @@ function floorObject() {};}+const OUTDOOR_SIZE = 600;+const OUTDOOR_OBJECT_COUNT = 6000;++// A fixed pseudo-random sequence, so every engine and every run places the same objects.+function seededSequence(seed) {+ let state = seed;+ return () => {+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;+ return state / 4294967296;+ };+}++function scatteredObjects(count, extent, geometry, material) {+ const next = seededSequence(67);+ const objects = [];+ for (let index = 0; index < count; index++) {+ const scale = 0.8 + next() * 1.2;+ objects.push({ geometry, matrix: translation((next() - 0.5) * extent, scale, (next() - 0.5) * extent, scale), material });+ }+ return objects;+}+const SUN = { direction: [-3, 6, 4], color: [3, 2.8, 2.5] };const SHARED_MATERIAL = { color: [0.7, 0.45, 0.25], metallic: 0, roughness: 0.5 };@@ -45,6 +67,19 @@ export const BENCHMARK_SCENES = {camera: { eye: [0, 40, 70], target: [0, 0, 0], fov: 45, near: 0.5, far: 400 },}),},+ 'large-outdoor': {+ description: `${OUTDOOR_OBJECT_COUNT} spheres of about 1,000 triangles over ${OUTDOOR_SIZE} by ${OUTDOOR_SIZE} units, seen from the edge`,+ build: () => ({+ geometries: { box: box(0, 1), sphere: sphere(32, 16) },+ lods: { sphere: [0.25, 0.06] },+ objects: [+ { geometry: 'box', matrix: new Float32Array([OUTDOOR_SIZE, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, OUTDOOR_SIZE, 0, 0, -0.05, 0, 1]), material: { color: [0.3, 0.4, 0.25], metallic: 0, roughness: 0.9 } },+ ...scatteredObjects(OUTDOOR_OBJECT_COUNT, OUTDOOR_SIZE - 20, 'sphere', SHARED_MATERIAL),+ ],+ sun: SUN, pointLights: [], shadowExtent: 0,+ camera: { eye: [0, 4, -290], target: [0, 3, 0], fov: 60, near: 0.5, far: 900 },+ }),+ },'many-materials': {description: '1,000 spheres with 1,000 different materials',build: () => ({diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex 0c615fd5..1de505ad 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 274408,- "gzip": 78007,- "brotli": 66600+ "min": 279820,+ "gzip": 79852,+ "brotli": 68242},"entry:model": {"min": 40093,@@ -40,8 +40,8 @@},"entry:gltf": {"min": 152150,- "gzip": 46704,- "brotli": 39993+ "gzip": 46707,+ "brotli": 40067},"entry:modeling": {"min": 15517,@@ -130,23 +130,23 @@},"entry:agent-scene": {"min": 190657,- "gzip": 57334,- "brotli": 49621+ "gzip": 57330,+ "brotli": 49632},"entry:agent-scene+lazy": {"min": 497784,- "gzip": 164822,- "brotli": 143860+ "gzip": 164818,+ "brotli": 143871},"entry:agent-asset": {"min": 273341,"gzip": 83733,- "brotli": 72966+ "brotli": 72953},"entry:agent-asset+lazy": {"min": 524940,"gzip": 172137,- "brotli": 149822+ "brotli": 149809},"entry:hdri": {"min": 8075,@@ -154,24 +154,24 @@"brotli": 2801},"scene:lit-box": {- "min": 206353,- "gzip": 56023,- "brotli": 47903+ "min": 211766,+ "gzip": 57906,+ "brotli": 49427},"scene:gltf-box": {- "min": 264230,- "gzip": 74991,- "brotli": 64299+ "min": 269645,+ "gzip": 76810,+ "brotli": 66055},"scene:agent-scene": {- "min": 294042,- "gzip": 84365,- "brotli": 72463+ "min": 299465,+ "gzip": 86309,+ "brotli": 74093},"scene:agent-scene+lazy": {- "min": 601169,- "gzip": 191853,- "brotli": 166724+ "min": 606592,+ "gzip": 193797,+ "brotli": 168354}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 88289792..1e91f839 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -5,7 +5,7 @@"agent-scene": 100000},"budgets": {- "entry:core": 79600,+ "entry:core": 81500,"entry:model": 14400,"entry:nature": 13200,"entry:motion": 13600,@@ -33,9 +33,9 @@"entry:agent-asset": 85500,"entry:agent-asset+lazy": 175600,"entry:hdri": 3300,- "scene:lit-box": 57200,- "scene:gltf-box": 76500,- "scene:agent-scene": 86100,+ "scene:lit-box": 59100,+ "scene:gltf-box": 78500,+ "scene:agent-scene": 88100,"scene:agent-scene+lazy": 195700}}diff --git a/docs/culling-lod.md b/docs/culling-lod.mdnew file mode 100644index 00000000..9b4edaca--- /dev/null+++ b/docs/culling-lod.md@@ -0,0 +1,45 @@+# Culling, levels of detail and adaptive resolution++`Renderer67` skips what the camera can not see and can draw far copies of a model with fewer triangles. Both are decided on the CPU from the camera and the instance matrices alone. A scene that has no off-screen parts and no levels draws as before.++## Culling++On by default, with no schema and no option to set. Each frame the renderer tests every instance of a batch (the parts that share a geometry and a material) against the six planes of the view frustum, using the geometry's bounding sphere scaled by the instance matrix. The colour pass then draws only the instances that touch the frustum. A batch with nothing visible costs no draw call, a batch that is entirely visible uses its full instance buffer as before, and a partly visible batch uploads the visible instances once.++What is not culled, because its bounding sphere would not hold or because it draws in another pass:++- Skinned and morphed parts.+- `foliage`, `grass`, `water`, `fire` and `smoke` materials, whose vertex shader moves vertices.+- Parts with an `assembly`.+- Alpha-blended, `liquid` and `foam` batches.+- The shadow passes. A caster outside the view can still shadow the view, so shadow maps draw every caster.++Pass `culling: false` to the `Renderer67` options to turn it off, for example to compare a picture.++## Levels of detail++Give a part `lods`, the array that `generateGeometryLods(geometry, { ratios })` returns (`generateAssetLods` gives one asset per level, so use the geometries of its parts). Level 0 must be the part's own `geometry`. Parts with the same geometry and the same `lods` array share one batch, and each instance picks its own level.++```js+const levels = generateGeometryLods(rock, { ratios: [0.25, 0.06] });+const parts = positions.map((position, index) => ({ name: `rock-${index}`, geometry: rock, lods: levels, matrix: translate(position), material }));+const renderer = new Renderer67(canvas, parts, { lodPixelError: 1 });+```++An instance uses the coarsest level whose `error` (the farthest its vertices lie from level 0, in geometry units, times the instance's largest scale) covers at most `lodPixelError` pixels on screen at its distance. The default is 1 pixel. Level 0 is always allowed, so a close instance is never reduced.++`lods` is refused for the parts that culling skips (the list above), because their levels could not be chosen from a bounding sphere.++## Determinism++The selection is a pure function of the geometry, the instance matrices, the camera and the canvas height. It keeps no state between frames, so a seek to any time draws the same instances at the same levels as playing up to it. `tests/render-culling.test.js` checks this on the selection, and `npm run benchmark:runtime` draws the first frame again after every measured frame and fails when the picture differs.++## GPU timing and adaptive resolution++`createGpuTimer(context)` from `src/adaptive-quality.js` wraps `EXT_disjoint_timer_query_webgl2` (it returns `null` without the extension). Pass the function itself as the `createGpuTimer` option of `Renderer67` and the renderer times each frame. A result arrives a few frames late, so `renderer.gpuMilliseconds` holds the latest finished one, or `null` after a disjoint measurement. Without the option nothing is timed and the timer code is not bundled.++`createAdaptiveResolution({ exporting: false, targetMilliseconds, minimumScale, step, window })` from `src/adaptive-quality.js` returns a controller. Feed it one frame time per frame with `update(milliseconds)` and multiply the pixel ratio by the scale it returns. It lowers the scale by one `step` when the average of `window` frames is over the target, raises it only after a whole window under 0.6 of the target, and never goes below `minimumScale` (default 0.5). `createAdaptiveResolution({ exporting: true })` throws: exports keep full quality, and the live viewer in `src/main.js` builds a controller only when its `export` parameter is not `1`.++## Measured++See `bench/runtime/README.md`, scene `large-outdoor`.diff --git a/docs/mesh.md b/docs/mesh.mdindex ffb23978..4f110169 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -372,7 +372,8 @@ cells). The mesh must be closed, and the result carries no tags or attributes.`generateAssetLods` for a static imported asset) returns level 0, the input, and one level for each ratio, from strictlydecreasing ratios in (0, 1), up to 8. Each level has `triangles`, `error` (the farthest its vertices lie from the input surface, inthe input's units) and `relativeError` (over the bounds diagonal); the asset form returns a whole asset per level.-Skinned and morphed parts are refused. `surfaceDeviation(a, b)` gives the vertex Hausdorff distance both ways.+Skinned and morphed parts are refused. `surfaceDeviation(a, b)` gives the vertex Hausdorff distance both ways. Hand the levels to a+part as `lods` and `Renderer67` picks one per instance by its size on screen: see `docs/culling-lod.md`.Why our own collapse and not meshoptimizer 1.3.0 (npm, MIT, 2026-09-25): on the same sphere, torus and open bowl atratios 0.5, 0.2 and 0.05 our Hausdorff error was 0.25 to 0.85 of its error (0.0088 against 0.0153 at 0.5 and 0.0647 against 0.0773diff --git a/docs/parity.md b/docs/parity.mdindex e133e51a..6bc307ac 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -238,7 +238,7 @@ The goal also needs this work, and no page in the Blender manual covers it.| --- | --- | --- | --- || Parity evidence | partial | This ledger exists. The Blender comparisons do not. | #24, #25, #26 || Bundle size | partial | `npm run size` checks a budget for each entry, and the package has a 1 MiB limit. three.js is gone from the library; only the benchmark page imports it. | #27, #33, #34, #35, #36 |-| Runtime speed | partial | `bench/runtime` compares 7 scenes, and three.js wins most of them. There is no culling, LOD selection or adaptive quality, and bakes run on the main thread. | #28, #37, #38, #74 |+| Runtime speed | partial | `bench/runtime` compares 8 scenes, and three.js wins most of the 7 older ones. Frustum culling per part and per instance group is on by default, `lods` from `generateGeometryLods` pick a level per instance by pixel error (`docs/culling-lod.md`), and `createGpuTimer` plus `createAdaptiveResolution` give live viewers GPU timing and a bounded resolution scale. On `large-outdoor` 67.js is 1.55 ms against 6.0 ms for three.js on an RTX 3060. Part of #37: recipes have no way to declare `lods` yet, shadow passes are not culled, and bakes run on the main thread. | #28, #37, #38, #74 || Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 || Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 || Relations between parts | missing | The agent version of snapping. | #44 |diff --git a/src/adaptive-quality.js b/src/adaptive-quality.jsnew file mode 100644index 00000000..a6e473db--- /dev/null+++ b/src/adaptive-quality.js@@ -0,0 +1,93 @@+// GPU frame timing and adaptive resolution for live viewing (issue 37).+//+// Adaptive resolution trades picture size for speed, so it must never touch an export: a viewer builds one only+// when it is not exporting, and `createAdaptiveResolution` refuses to build one otherwise.++const GPU_TIMER_EXTENSION = 'EXT_disjoint_timer_query_webgl2';+const NANOSECONDS_PER_MILLISECOND = 1e6;++/**+ * Times the GPU work between `begin()` and `end()`. A result arrives a few frames later, so `milliseconds` holds+ * the latest finished measurement (null until the first one). Returns null when the browser has no timer queries.+ */+export function createGpuTimer(context) {+ const extension = context.getExtension(GPU_TIMER_EXTENSION);+ if (!extension) return null;+ const pending = [];+ let active = false;+ const timer = {+ milliseconds: null,+ begin() {+ if (active) return;+ const query = context.createQuery();+ context.beginQuery(extension.TIME_ELAPSED_EXT, query);+ pending.push(query);+ active = true;+ },+ end() {+ if (!active) return;+ context.endQuery(extension.TIME_ELAPSED_EXT);+ active = false;+ },+ collect() {+ const disjoint = context.getParameter(extension.GPU_DISJOINT_EXT);+ // The newest query is still open while a measurement is running, and cannot be read yet.+ while (pending.length > (active ? 1 : 0)) {+ const query = pending[0];+ if (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) break;+ if (!disjoint) timer.milliseconds = context.getQueryParameter(query, context.QUERY_RESULT) / NANOSECONDS_PER_MILLISECOND;+ context.deleteQuery(query);+ pending.shift();+ }+ if (disjoint) timer.milliseconds = null;+ return timer.milliseconds;+ },+ dispose() {+ if (active) context.endQuery(extension.TIME_ELAPSED_EXT);+ pending.forEach(query => context.deleteQuery(query));+ pending.length = 0;+ active = false;+ },+ };+ return timer;+}++/**+ * Chooses a resolution scale between `minimumScale` and 1 from measured frame times. It lowers the scale a step+ * when the average of the last `window` frames is over `targetMilliseconds`, and raises it a step only after the+ * average has stayed under `raiseBelow` of the target for `window` frames, so the size does not flicker. The scale+ * only takes values on the grid of `step`, and never falls under `minimumScale`.+ */+export class AdaptiveResolution {+ constructor({ targetMilliseconds = 1000 / 60, minimumScale = 0.5, step = 0.125, window = 20, raiseBelow = 0.6 } = {}) {+ if (!(targetMilliseconds > 0)) throw new RangeError('targetMilliseconds must be above 0.');+ if (!(minimumScale > 0) || minimumScale > 1) throw new RangeError('minimumScale must be above 0 and at most 1.');+ if (!(step > 0) || step >= 1) throw new RangeError('step must be above 0 and below 1.');+ if (!Number.isInteger(window) || window < 1) throw new RangeError('window must be a whole number of frames.');+ this.targetMilliseconds = targetMilliseconds;+ this.minimumScale = minimumScale;+ this.step = step;+ this.window = window;+ this.raiseBelow = raiseBelow;+ this.scale = 1;+ this.recent = [];+ }++ /** Adds a frame time and returns the scale to use for the next frame. */+ update(frameMilliseconds) {+ if (!Number.isFinite(frameMilliseconds) || frameMilliseconds < 0) return this.scale;+ this.recent.push(frameMilliseconds);+ if (this.recent.length < this.window) return this.scale;+ const average = this.recent.reduce((total, value) => total + value, 0) / this.recent.length;+ this.recent.length = 0;+ if (average > this.targetMilliseconds) this.scale = Math.max(this.minimumScale, this.scale - this.step);+ else if (average < this.targetMilliseconds * this.raiseBelow) this.scale = Math.min(1, this.scale + this.step);+ return this.scale;+ }+}++/** The adaptive resolution for a live viewer; throws when the viewer is exporting, because exports keep full quality. */+export function createAdaptiveResolution({ exporting, ...options }) {+ if (exporting) throw new Error('Adaptive resolution never applies to an export.');+ return new AdaptiveResolution(options);+}diff --git a/src/main.js b/src/main.jsindex 8305417c..4cafe8ef 100644--- a/src/main.js+++ b/src/main.js@@ -1,6 +1,7 @@import './style.css';import './brand.js';import { Renderer67 } from './renderer.js';+import { createAdaptiveResolution, createGpuTimer } from './adaptive-quality.js';import { createModel } from './model.js';import { downloadGlb } from './export.js';import { assemblyOffset } from './assembly.js';@@ -8,6 +9,10 @@ import { approachValue } from './preview-transition.js';const canvas = document.querySelector('#viewport');const renderParameters = new URLSearchParams(location.search);+const isExport = renderParameters.get('export') === '1';+// Live viewing lowers the resolution when frames run long. An export keeps full quality, so it has none.+const adaptiveResolution = isExport ? null : createAdaptiveResolution({ exporting: false });+let selectedPixelRatio = isExport ? 1 : 1.5;const parts = createModel();const finishes = {yellow: { name: 'Factory yellow', color: [0.62, 0.34, 0.035], surface: [0.48, 0.43] },@@ -75,19 +80,27 @@ function draw(time) {lastTime = time;renderer.render(camera());cpuTotal += renderer.cpuMilliseconds;+ adaptResolution();frameCount++;document.querySelector('#cpu').textContent = `${(cpuTotal / frameCount).toFixed(2)} ms CPU`;if (frameCount > 60) { cpuTotal = renderer.cpuMilliseconds; frameCount = 1; }if (state.rotating || state.touring || state.assembly !== state.assemblyTarget) invalidate();}+function adaptResolution() {+ if (!adaptiveResolution) return;+ const previousRatio = renderer.pixelRatio;+ renderer.pixelRatio = selectedPixelRatio * adaptiveResolution.update(renderer.gpuMilliseconds ?? renderer.cpuMilliseconds);+ if (renderer.pixelRatio !== previousRatio) renderer.resize();+}+function invalidate() {if (!scheduledFrame && renderer && !document.hidden) scheduledFrame = requestAnimationFrame(draw);}function initialize() {const visibleParts = state.layer === 'all' ? parts : parts.filter((part) => part.assembly?.layer === state.layer);- renderer = new Renderer67(canvas, visibleParts, { hdr: true, samples: Number(renderParameters.get('samples') ?? 4), memoryBudgetMiB: Number(renderParameters.get('memory') ?? 256), pixelRatio: renderParameters.get('export') === '1' ? 1 : 1.5, shadowBounds: { extent: 6, eye: [-3, 7, 4], target: [0, 1.5, 0] } });+ renderer = new Renderer67(canvas, visibleParts, { hdr: true, samples: Number(renderParameters.get('samples') ?? 4), memoryBudgetMiB: Number(renderParameters.get('memory') ?? 256), pixelRatio: selectedPixelRatio, createGpuTimer: isExport ? null : createGpuTimer, shadowBounds: { extent: 6, eye: [-3, 7, 4], target: [0, 1.5, 0] } });document.querySelector('#parts').textContent = `${visibleParts.length} parts · ${Math.round(renderer.triangles / 1000)}k triangles`;document.querySelector('#calls').textContent = `${renderer.batches.length} geometry draws`;invalidate();@@ -230,7 +243,8 @@ document.querySelector('#inspect').addEventListener('click', (event) => {});document.querySelector('#quality').addEventListener('change', (event) => {if (!renderer) return;- renderer.pixelRatio = Number(event.target.value);+ selectedPixelRatio = Number(event.target.value);+ renderer.pixelRatio = selectedPixelRatio * (adaptiveResolution?.scale ?? 1);renderer.resize();invalidate();});diff --git a/src/render-culling.js b/src/render-culling.jsnew file mode 100644index 00000000..08ba2c65--- /dev/null+++ b/src/render-culling.js@@ -0,0 +1,123 @@+// Frustum culling and level-of-detail selection for instanced batches (issue 37).+//+// Everything here is a pure function of the geometry, the instance matrices, the view-projection matrix and the+// canvas height. It keeps no state between frames, so a frame drawn after a seek to any time picks the same+// instances and the same levels as one drawn in sequence.++const PLANE_COUNT = 6;+const MINIMUM_DEPTH = 1e-6;++/** Pixel error that a level may cause before the next finer level is used. */+export const DEFAULT_LOD_PIXEL_ERROR = 1;++const boundingSpheres = new WeakMap();++/** Smallest sphere around the geometry's vertices that is centred on the middle of their bounding box. */+export function geometryBoundingSphere(geometry) {+ const cached = boundingSpheres.get(geometry);+ if (cached) return cached;+ const positions = geometry.positions;+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < positions.length; index += 3) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], positions[index + axis]);+ maximum[axis] = Math.max(maximum[axis], positions[index + axis]);+ }+ }+ const center = minimum.map((value, axis) => (value + maximum[axis]) / 2);+ let radiusSquared = 0;+ for (let index = 0; index < positions.length; index += 3) {+ const dx = positions[index] - center[0];+ const dy = positions[index + 1] - center[1];+ const dz = positions[index + 2] - center[2];+ radiusSquared = Math.max(radiusSquared, dx * dx + dy * dy + dz * dz);+ }+ const sphere = Object.freeze({ center: Object.freeze(center), radius: Math.sqrt(radiusSquared) });+ boundingSpheres.set(geometry, sphere);+ return sphere;+}++/**+ * Fills `planes` (6 x 4 numbers, normalised, normals pointing inside) from a column-major view-projection matrix,+ * so a point is inside when every plane gives a distance of zero or more.+ */+export function extractFrustumPlanes(viewProjection, planes) {+ for (let plane = 0; plane < PLANE_COUNT; plane++) {+ const axis = plane >> 1;+ const sign = plane % 2 === 0 ? 1 : -1;+ for (let component = 0; component < 4; component++) {+ planes[plane * 4 + component] = viewProjection[component * 4 + 3] + sign * viewProjection[component * 4 + axis];+ }+ const length = Math.hypot(planes[plane * 4], planes[plane * 4 + 1], planes[plane * 4 + 2]);+ for (let component = 0; component < 4; component++) planes[plane * 4 + component] /= length || 1;+ }+ return planes;+}++function largestColumnLength(matrix, offset) {+ const first = matrix[offset] ** 2 + matrix[offset + 1] ** 2 + matrix[offset + 2] ** 2;+ const second = matrix[offset + 4] ** 2 + matrix[offset + 5] ** 2 + matrix[offset + 6] ** 2;+ const third = matrix[offset + 8] ** 2 + matrix[offset + 9] ** 2 + matrix[offset + 10] ** 2;+ return Math.sqrt(Math.max(first, second, third));+}++function isOutsideFrustum(planes, x, y, z, radius) {+ for (let plane = 0; plane < PLANE_COUNT; plane++) {+ const offset = plane * 4;+ if (planes[offset] * x + planes[offset + 1] * y + planes[offset + 2] * z + planes[offset + 3] < -radius) return true;+ }+ return false;+}++/** The coarsest level whose error, at this size on screen, stays within `pixelError`. Level 0 is always allowed. */+export function chooseLevel(levelErrors, worldScale, pixelsPerUnit, pixelError) {+ let chosen = 0;+ for (let level = 1; level < levelErrors.length; level++) {+ if (levelErrors[level] * worldScale * pixelsPerUnit > pixelError) break;+ chosen = level;+ }+ return chosen;+}++/** Instance indices of one batch, split by level, reused between frames. */+export class InstanceSelection {+ constructor(instanceCount, levelCount) {+ this.indices = Array.from({ length: levelCount }, () => new Uint32Array(instanceCount));+ this.counts = new Uint32Array(levelCount);+ this.visibleCount = 0;+ }++ /** True when every instance is drawn at level 0, so the batch can use its full instance buffer as it is. */+ get isEverything() {+ return this.visibleCount === this.indices[0].length && this.counts[0] === this.visibleCount;+ }+}++/**+ * Splits a batch's instances into the ones that touch the frustum, by level. `bounds` is the geometry's bounding+ * sphere, `levelErrors` the error of each level in geometry units (level 0 is 0), and `pixelsPerUnit` the pixels+ * that one world unit covers at depth 1 (half the canvas height times projection[5]).+ */+export function selectInstances(selection, { instanceData, instanceCount, stride, bounds, levelErrors, planes, viewProjection, pixelsPerUnit, pixelError = DEFAULT_LOD_PIXEL_ERROR }) {+ selection.counts.fill(0);+ selection.visibleCount = 0;+ const hasLevels = levelErrors.length > 1;+ const [centerX, centerY, centerZ] = bounds.center;+ for (let index = 0; index < instanceCount; index++) {+ const offset = index * stride;+ const x = instanceData[offset] * centerX + instanceData[offset + 4] * centerY + instanceData[offset + 8] * centerZ + instanceData[offset + 12];+ const y = instanceData[offset + 1] * centerX + instanceData[offset + 5] * centerY + instanceData[offset + 9] * centerZ + instanceData[offset + 13];+ const z = instanceData[offset + 2] * centerX + instanceData[offset + 6] * centerY + instanceData[offset + 10] * centerZ + instanceData[offset + 14];+ const worldScale = largestColumnLength(instanceData, offset);+ if (isOutsideFrustum(planes, x, y, z, bounds.radius * worldScale)) continue;+ let level = 0;+ if (hasLevels) {+ const depth = viewProjection[3] * x + viewProjection[7] * y + viewProjection[11] * z + viewProjection[15];+ level = depth > MINIMUM_DEPTH ? chooseLevel(levelErrors, worldScale, pixelsPerUnit / depth, pixelError) : 0;+ }+ selection.indices[level][selection.counts[level]++] = index;+ selection.visibleCount++;+ }+ return selection;+}diff --git a/src/renderer.js b/src/renderer.jsindex 55f13634..d2bc392b 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -12,6 +12,7 @@ import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundimport { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';import { validateSplatMaterial, splatBatchState, splatTextureBytes, resolveSplatSize, packSplatParameters, buildSplatPixels } from './splat.js';import { materialLayerState } from './material-layers.js';+import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };@@ -31,6 +32,8 @@ const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain'// Tags whose vertices sway in the wind; the shadow pass must be redrawn when time moves.const SWAYING_TAGS = new Set(['foliage', 'grass']);+// Tags whose vertex shader moves vertices away from the instance matrix, so a bounding sphere would not hold.+const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);const MAP_SHADER_FEATURES = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];// Tags whose look the main fragment shader draws with code that other tags never reach.@@ -203,6 +206,25 @@ function packInstance(data, index, part, normalMatrix) {data.set(part.material.emissiveColor ?? part.material.color, offset + 38);}+function isCullable(parts) {+ const first = parts[0];+ if (first.skin || first.morph || DEFORMING_TAGS.has(first.material.tag)) return false;+ if (renderPass(first.material) !== 'opaque' || materialAlphaState(first.material)[0] === 'blend') return false;+ return parts.every(part => !part.assembly);+}++function validateLods(part, levels) {+ if (!Array.isArray(levels) || levels.length < 2 || levels[0].geometry !== part.geometry) {+ throw new TypeError(`lods must list level 0 (the own geometry of the part) and at least one coarser level: ${part.name}`);+ }+ levels.forEach((level, index) => {+ if (!level.geometry?.positions || !level.geometry.indices) throw new TypeError(`Every lods entry needs a geometry: ${part.name}`);+ if (!Number.isFinite(level.error) || level.error < 0 || (index > 0 && level.error < levels[index - 1].error)) {+ throw new RangeError(`lods errors must be finite and not decrease from level to level: ${part.name}`);+ }+ });+}+// Starting a program without asking for its result lets the driver build several programs at once.function startProgram(context, vertexSource, fragmentSource) {const program = context.createProgram();@@ -265,7 +287,7 @@ export function groupParts(parts, batching = true) {const key = batching ? part.geometry : part;if (!groups.has(key)) groups.set(key, new Map());let maps = groups.get(key);- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), ...materialAlphaState(part.material)]) {+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), part.lods ?? null, ...materialAlphaState(part.material)]) {if (!maps.has(value)) maps.set(value, new Map());maps = maps.get(value);}@@ -338,8 +360,16 @@ function allFinite(values) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, culling = true, lodPixelError = 1, createGpuTimer = null } = {}) {this.canvas = canvas;+ // `createGpuTimer` from adaptive-quality.js is passed in, which keeps the timer code out of scenes that do not time frames.+ this.createGpuTimer = createGpuTimer;+ this.gpuTimer = undefined;+ /** Milliseconds the GPU took for a recent frame, when `createGpuTimer` is given. */+ this.gpuMilliseconds = null;+ this.culling = culling;+ this.lodPixelError = lodPixelError;+ this.frustumPlanes = new Float32Array(24);if (!Number.isInteger(samples) || samples < 1) throw new Error('MSAA sample count must be a positive integer.');if (new Set(parts).size !== parts.length) throw new Error('Scene parts must have distinct object identities for animation.');this.lighting = createLightingState();@@ -697,10 +727,9 @@ export class Renderer67 {}}- uploadBatchData(parts, vertexArray) {+ /** Binds the geometry's vertex buffers and attributes into the bound vertex array. */+ bindGeometryAttributes(geometry, material) {const context = this.context;- const geometry = parts[0].geometry;- context.bindVertexArray(vertexArray);let geometryBuffers = this.geometryBuffers.get(geometry);if (!geometryBuffers) {geometryBuffers = new Map();@@ -723,7 +752,7 @@ export class Renderer67 {context.enableVertexAttribArray(13);context.vertexAttribPointer(13, 2, context.FLOAT, false, 0, 0);} else {- if (hasMaterialMap(parts[0].material) && !parts[0].material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');+ if (hasMaterialMap(material) && !material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');context.disableVertexAttribArray(13);// (-1, -1) marks "no UVs": grass wind then bends by local height instead of by blade position.context.vertexAttrib2f(13, -1, -1);@@ -738,14 +767,11 @@ export class Renderer67 {context.vertexAttrib3f(14, 1, 1, 1);}context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, geometryBuffers.get('indices'));+ }++ /** Points the instance attributes of the bound vertex array at the bound array buffer. */+ pointInstanceAttributes() {const stride = INSTANCE_STRIDE;- const instanceData = new Float32Array(parts.length * stride);- const normalMatrix = mat3.create();- parts.forEach((part, index) => {- mat3.normalFromMat4(normalMatrix, part.matrix);- packInstance(instanceData, index, part, normalMatrix);- });- const instanceBuffer = this.uploadBuffer(context.ARRAY_BUFFER, instanceData, context.DYNAMIC_DRAW);for (let column = 0; column < 4; column++) this.attribute(2 + column, 4, stride * 4, column * 16);for (let column = 0; column < 3; column++) this.attribute(6 + column, 3, stride * 4, 64 + column * 12);this.attribute(9, 3, stride * 4, 100);@@ -753,6 +779,92 @@ export class Renderer67 {this.attribute(11, 3, stride * 4, 128);this.attribute(12, 3, stride * 4, 140);this.attribute(15, 3, stride * 4, 152);+ }++ createCullingState(parts) {+ const first = parts[0];+ const cullable = isCullable(parts);+ if (first.lods) {+ validateLods(first, first.lods);+ if (!cullable) throw new RangeError(`lods need rigid, opaque parts without assembly motion: ${first.name}`);+ }+ const levels = first.lods ?? [{ geometry: first.geometry, error: 0 }];+ const levelErrors = levels.map(level => level.error);+ const sphere = geometryBoundingSphere(first.geometry);+ const bounds = { center: sphere.center, radius: sphere.radius + Math.max(...levelErrors) };+ return { cullable, bounds, levelErrors, levelGeometries: levels.map(level => level.geometry), levelDraws: [], selection: new InstanceSelection(parts.length, levels.length) };+ }++ /** The vertex array and instance buffer that draw one level of a batch from the instances selected for it. */+ levelDraw(batch, level) {+ if (batch.levelDraws[level]) return batch.levelDraws[level];+ const context = this.context;+ const geometry = batch.levelGeometries[level];+ const vertexArray = context.createVertexArray();+ context.bindVertexArray(vertexArray);+ this.bindGeometryAttributes(geometry, batch.parts[0].material);+ const instanceBuffer = context.createBuffer();+ this.buffers.push(instanceBuffer);+ context.bindBuffer(context.ARRAY_BUFFER, instanceBuffer);+ context.bufferData(context.ARRAY_BUFFER, batch.instanceData.byteLength, context.DYNAMIC_DRAW);+ this.pointInstanceAttributes();+ context.bindVertexArray(null);+ batch.levelDraws[level] = { vertexArray, instanceBuffer, indexCount: geometry.indices.length };+ return batch.levelDraws[level];+ }++ releaseLevelDraws(batch, releasedBuffers) {+ for (const draw of batch.levelDraws) {+ if (!draw) continue;+ this.context.deleteVertexArray(draw.vertexArray);+ releasedBuffers?.add(draw.instanceBuffer);+ }+ batch.levelDraws = [];+ }++ /** The instances of a batch that the camera can see, split by level; null when the whole batch draws as it is. */+ selectBatchInstances(batch) {+ if (!this.culling || !batch.cullable) return null;+ return selectInstances(batch.selection, {+ instanceData: batch.instanceData, instanceCount: batch.instanceCount, stride: INSTANCE_STRIDE, bounds: batch.bounds,+ levelErrors: batch.levelErrors, planes: this.frustumPlanes, viewProjection: this.viewProjection,+ pixelsPerUnit: this.canvas.height / 2 * this.projection[5], pixelError: this.lodPixelError,+ });+ }++ drawSelectedLevels(batch, selection) {+ const context = this.context;+ const stride = INSTANCE_STRIDE;+ for (let level = 0; level < selection.counts.length; level++) {+ const count = selection.counts[level];+ if (count === 0) continue;+ const draw = this.levelDraw(batch, level);+ if (!(this.selectionScratch?.length >= count * stride)) this.selectionScratch = new Float32Array(count * stride);+ for (let slot = 0; slot < count; slot++) {+ const instance = selection.indices[level][slot];+ this.selectionScratch.set(batch.instanceData.subarray(instance * stride, (instance + 1) * stride), slot * stride);+ }+ context.bindBuffer(context.ARRAY_BUFFER, draw.instanceBuffer);+ context.bufferSubData(context.ARRAY_BUFFER, 0, this.selectionScratch, 0, count * stride);+ context.bindVertexArray(draw.vertexArray);+ context.drawElementsInstanced(context.TRIANGLES, draw.indexCount, context.UNSIGNED_INT, 0, count);+ }+ }++ uploadBatchData(parts, vertexArray) {+ const context = this.context;+ const geometry = parts[0].geometry;+ context.bindVertexArray(vertexArray);+ this.bindGeometryAttributes(geometry, parts[0].material);+ const stride = INSTANCE_STRIDE;+ const instanceData = new Float32Array(parts.length * stride);+ const normalMatrix = mat3.create();+ parts.forEach((part, index) => {+ mat3.normalFromMat4(normalMatrix, part.matrix);+ packInstance(instanceData, index, part, normalMatrix);+ });+ const instanceBuffer = this.uploadBuffer(context.ARRAY_BUFFER, instanceData, context.DYNAMIC_DRAW);+ this.pointInstanceAttributes();context.bindVertexArray(null);const map = parts[0].material.map ?? null;const mapState = materialMapState(parts[0].material);@@ -766,7 +878,9 @@ export class Renderer67 {const morphWeights = morph ? new Float32Array(morph.weights) : null;const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);const layerState = materialLayerState(parts[0].material);- const batch = { alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };+ const culling = this.createCullingState(parts);+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };+ if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));return batch;}@@ -778,7 +892,7 @@ export class Renderer67 {}const renderParts = this.groundPart ? [...parts, this.groundPart] : parts;const groups = groupParts(renderParts, this.batching);- const geometries = new Set(renderParts.map(part => part.geometry));+ const geometries = new Set(renderParts.flatMap(part => part.lods ? part.lods.map(level => level.geometry) : [part.geometry]));// Uploaded geometry was validated when it arrived; rechecking a large static scene every frame dominated streamed playback.for (const geometry of geometries) {if (!this.geometryBuffers.has(geometry)) validateReplacementGeometry(geometry);@@ -845,7 +959,10 @@ export class Renderer67 {}} catch (error) {for (const batch of stagedBatches) {- if (!retained.has(batch)) this.context.deleteVertexArray(batch.vertexArray);+ if (!retained.has(batch)) {+ this.context.deleteVertexArray(batch.vertexArray);+ this.releaseLevelDraws(batch);+ }}for (const buffer of this.buffers.slice(previousBuffers.length)) {this.context.deleteBuffer(buffer);@@ -862,6 +979,7 @@ export class Renderer67 {if (!retained.has(batch)) {this.context.deleteVertexArray(batch.vertexArray);releasedBuffers.add(batch.instanceBuffer);+ this.releaseLevelDraws(batch, releasedBuffers);}}for (const [geometry, buffers] of this.geometryBuffers) {@@ -1609,12 +1727,14 @@ export class Renderer67 {context.bindVertexArray(null);}- drawAlphaBatch(batch, textured) {+ drawAlphaBatch(batch, textured, culled = false) {+ const selection = culled ? this.selectBatchInstances(batch) : null;+ if (selection?.visibleCount === 0) return;this.applyAlphaState(batch, textured);- this.drawBatch(batch, textured);+ this.drawBatch(batch, textured, selection);}- drawBatch(batch, textured = false) {+ drawBatch(batch, textured = false, selection = null) {if (this.hasMorphs) {const uniforms = textured ? this.uniforms : this.depthMorphUniforms;this.context.uniform1f(uniforms.morphEnabled, batch.morph ? 1 : 0);@@ -1656,6 +1776,10 @@ export class Renderer67 {this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);this.bindSplat(batch.splat);}+ if (selection && !selection.isEverything) {+ this.drawSelectedLevels(batch, selection);+ return;+ }this.context.bindVertexArray(batch.vertexArray);this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);}@@ -1675,6 +1799,7 @@ export class Renderer67 {updateLightingState(this.lighting, environment, { world: this.world });const start = performance.now();const context = this.context;+ this.beginGpuTiming();const assemblyAmount = Math.max(0, Math.min(1, frame.assemblyAmount ?? 0));// Swaying foliage moves every frame, so its shadow map is redrawn whenever time or wind changes.const windChanged = this.updateWindState(frame);@@ -1690,6 +1815,7 @@ export class Renderer67 {mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);mat4.multiply(this.viewProjection, this.projection, this.view);mat4.invert(this.inverseViewProjection, this.viewProjection);+ extractFrustumPlanes(this.viewProjection, this.frustumPlanes);context.bindFramebuffer(context.FRAMEBUFFER, this.benchmark ? null : this.multisampleFramebuffer);context.viewport(0, 0, this.canvas.width, this.canvas.height);if (this.transparent) {@@ -1739,7 +1865,7 @@ export class Renderer67 {if (this.benchmark) {this.drawBatch(batch, true);} else if (batchPass(batch) === 'opaque' && batch.alphaMode !== 'blend') {- this.drawAlphaBatch(batch, true);+ this.drawAlphaBatch(batch, true, true);}}context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);@@ -1748,9 +1874,21 @@ export class Renderer67 {if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);if (!this.benchmark) this.drawBlendBatches(frame);if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);+ this.endGpuTiming();this.cpuMilliseconds = performance.now() - start;}+ beginGpuTiming() {+ if (this.gpuTimer === undefined) this.gpuTimer = this.createGpuTimer?.(this.context) ?? null;+ this.gpuTimer?.begin();+ }++ endGpuTiming() {+ if (!this.gpuTimer) return;+ this.gpuTimer.end();+ this.gpuMilliseconds = this.gpuTimer.collect();+ }+applyLocalLightUniforms() {const context = this.context;const lighting = this.lighting;@@ -1779,7 +1917,10 @@ export class Renderer67 {this.releaseFrameTargets();if (this.localShadowTexture) this.context.deleteTexture(this.localShadowTexture);if (this.localShadowFramebuffer) this.context.deleteFramebuffer(this.localShadowFramebuffer);- this.batches.forEach((batch) => this.context.deleteVertexArray(batch.vertexArray));+ this.batches.forEach((batch) => {+ this.context.deleteVertexArray(batch.vertexArray);+ this.releaseLevelDraws(batch);+ });this.buffers.forEach((buffer) => this.context.deleteBuffer(buffer));this.geometryBuffers?.clear();this.context.deleteTexture(this.shadowTexture);diff --git a/tests/adaptive-quality.test.js b/tests/adaptive-quality.test.jsnew file mode 100644index 00000000..a6ec3934--- /dev/null+++ b/tests/adaptive-quality.test.js@@ -0,0 +1,75 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { AdaptiveResolution, createAdaptiveResolution, createGpuTimer } from '../src/adaptive-quality.js';++function feed(adaptive, milliseconds, frames) {+ let scale = adaptive.scale;+ for (let frame = 0; frame < frames; frame++) scale = adaptive.update(milliseconds);+ return scale;+}++test('slow frames lower the scale one step per window and stop at the minimum', () => {+ const adaptive = new AdaptiveResolution({ targetMilliseconds: 16, minimumScale: 0.5, step: 0.25, window: 4 });+ assert.equal(feed(adaptive, 30, 4), 0.75);+ assert.equal(feed(adaptive, 30, 4), 0.5);+ assert.equal(feed(adaptive, 30, 40), 0.5);+});++test('the scale rises again only after a full window well under the target', () => {+ const adaptive = new AdaptiveResolution({ targetMilliseconds: 16, minimumScale: 0.5, step: 0.25, window: 4 });+ feed(adaptive, 30, 8);+ assert.equal(adaptive.scale, 0.5);+ assert.equal(feed(adaptive, 14, 4), 0.5, 'a frame near the target does not raise it');+ assert.equal(feed(adaptive, 4, 3), 0.5, 'a short run of fast frames does not raise it');+ assert.equal(feed(adaptive, 4, 1), 0.75);+ assert.equal(feed(adaptive, 4, 40), 1);+});++test('the same frame times always give the same scales', () => {+ const times = Array.from({ length: 80 }, (unused, index) => 8 + ((index * 7) % 23));+ const run = () => {+ const adaptive = new AdaptiveResolution({ window: 5 });+ return times.map(time => adaptive.update(time));+ };+ assert.deepEqual(run(), run());+});++test('bad frame times are ignored and bad settings are refused', () => {+ const adaptive = new AdaptiveResolution({ window: 1 });+ assert.equal(adaptive.update(Number.NaN), 1);+ assert.equal(adaptive.update(-1), 1);+ assert.throws(() => new AdaptiveResolution({ minimumScale: 0 }), RangeError);+ assert.throws(() => new AdaptiveResolution({ step: 1 }), RangeError);+ assert.throws(() => new AdaptiveResolution({ window: 0 }), RangeError);+});++test('an export can not have adaptive resolution', () => {+ assert.throws(() => createAdaptiveResolution({ exporting: true }), /never applies to an export/);+ assert.ok(createAdaptiveResolution({ exporting: false }) instanceof AdaptiveResolution);+});++test('the GPU timer reads finished queries in order and drops a disjoint result', () => {+ const finished = new Set();+ let disjoint = false;+ let nextQuery = 0;+ const context = {+ QUERY_RESULT: 'result', QUERY_RESULT_AVAILABLE: 'available',+ getExtension: () => ({ TIME_ELAPSED_EXT: 1, GPU_DISJOINT_EXT: 2 }),+ getParameter: () => disjoint,+ createQuery: () => ({ id: nextQuery++ }),+ beginQuery() {}, endQuery() {}, deleteQuery() {},+ getQueryParameter: (query, name) => (name === 'available' ? finished.has(query.id) : (query.id + 1) * 2e6),+ };+ const timer = createGpuTimer(context);+ timer.begin();+ timer.end();+ assert.equal(timer.collect(), null, 'the query is not finished yet');+ finished.add(0);+ assert.equal(timer.collect(), 2);+ timer.begin();+ timer.end();+ finished.add(1);+ disjoint = true;+ assert.equal(timer.collect(), null);+ assert.equal(createGpuTimer({ getExtension: () => null }), null);+});diff --git a/tests/render-culling.test.js b/tests/render-culling.test.jsnew file mode 100644index 00000000..60db5bdf--- /dev/null+++ b/tests/render-culling.test.js@@ -0,0 +1,153 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mat4 } from 'gl-matrix';+import { box, sphere } from '../src/geometry.js';+import { generateGeometryLods } from '../src/mesh-lod.js';+import { Renderer67 } from '../src/renderer.js';+import { InstanceSelection, chooseLevel, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from '../src/render-culling.js';++const STRIDE = 41;+const CANVAS_HEIGHT = 540;++function cameraMatrices(eye = [0, 0, 10], target = [0, 0, 0]) {+ const projection = mat4.perspective(mat4.create(), Math.PI / 4, 16 / 9, 0.5, 100);+ const view = mat4.lookAt(mat4.create(), eye, target, [0, 1, 0]);+ const viewProjection = mat4.multiply(mat4.create(), projection, view);+ return { projection, viewProjection, planes: extractFrustumPlanes(viewProjection, new Float32Array(24)) };+}++function instanceData(positions, scale = 1) {+ const data = new Float32Array(positions.length * STRIDE);+ positions.forEach(([x, y, z], index) => {+ data.set([scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1], index * STRIDE);+ });+ return data;+}++function selectionFor(positions, { levelErrors = [0], bounds = { center: [0, 0, 0], radius: 1 }, eye, scale } = {}) {+ const { projection, viewProjection, planes } = cameraMatrices(eye);+ const selection = new InstanceSelection(positions.length, levelErrors.length);+ return selectInstances(selection, {+ instanceData: instanceData(positions, scale), instanceCount: positions.length, stride: STRIDE, bounds, levelErrors, planes, viewProjection,+ pixelsPerUnit: CANVAS_HEIGHT / 2 * projection[5],+ });+}++test('a bounding sphere is centred on the box of the vertices and reaches the farthest one', () => {+ const unitBox = box(0, 1);+ const bounds = geometryBoundingSphere(unitBox);+ assert.deepEqual([...bounds.center], [0, 0, 0]);+ assert.ok(Math.abs(bounds.radius - Math.hypot(...unitBox.positions.subarray(0, 3))) < 1e-6);+ assert.equal(geometryBoundingSphere(unitBox), bounds);+});++test('instances behind, beside and beyond the camera are culled and the rest stay in order', () => {+ const selection = selectionFor([[0, 0, 0], [500, 0, 0], [0, 0, 50], [0, 0, -200], [2, 1, 0]]);+ assert.deepEqual([...selection.indices[0].subarray(0, selection.counts[0])], [0, 4]);+ assert.equal(selection.visibleCount, 2);+});++test('a sphere that only touches the frustum edge is kept, and scale grows its reach', () => {+ const nearEdge = [[9.5, 0, 0]];+ assert.equal(selectionFor(nearEdge).visibleCount, 0);+ assert.equal(selectionFor(nearEdge, { scale: 4 }).visibleCount, 1);+});++test('an instance that is everywhere in view reports that the full buffer can be used', () => {+ assert.equal(selectionFor([[0, 0, 0], [1, 0, 0]]).isEverything, true);+ assert.equal(selectionFor([[0, 0, 0], [500, 0, 0]]).isEverything, false);+});++test('a level is chosen by the pixels of error it would show, coarsest first allowed', () => {+ const errors = [0, 0.01, 0.1];+ assert.equal(chooseLevel(errors, 1, 100, 1), 1);+ assert.equal(chooseLevel(errors, 1, 5, 1), 2);+ assert.equal(chooseLevel(errors, 1, 1000, 1), 0);+ assert.equal(chooseLevel([0], 1, 1, 1), 0);+});++test('farther copies of one model use coarser levels, and each copy lands in exactly one level', () => {+ const levelErrors = [0, 0.02, 0.1];+ const selection = selectionFor([[0, 0, 4], [0, 0, -30], [0, 0, -90]], { levelErrors, eye: [0, 0, 10] });+ assert.equal(selection.visibleCount, 3);+ assert.equal(selection.counts.reduce((total, count) => total + count, 0), 3);+ assert.deepEqual([...selection.counts], [1, 1, 1]);+});++test('selection depends only on its inputs, so any frame picks the same instances', () => {+ const positions = Array.from({ length: 200 }, (unused, index) => [(index % 20 - 10) * 3, 0, -Math.floor(index / 20) * 9]);+ const levelErrors = [0, 0.02, 0.2];+ const first = selectionFor(positions, { levelErrors });+ selectionFor(positions.slice(0, 7), { levelErrors, eye: [30, 3, 40] });+ const second = selectionFor(positions, { levelErrors });+ assert.deepEqual([...second.counts], [...first.counts]);+ first.indices.forEach((indices, level) => assert.deepEqual([...second.indices[level]], [...indices]));+});++function drawingRenderer(parts) {+ const calls = [];+ const renderer = Object.create(Renderer67.prototype);+ renderer.buffers = [];+ renderer.geometryBuffers = new Map();+ renderer.culling = true;+ renderer.lodPixelError = 1;+ renderer.canvas = { height: CANVAS_HEIGHT };+ const noop = () => {};+ renderer.context = {+ ARRAY_BUFFER: 1, ELEMENT_ARRAY_BUFFER: 2, DYNAMIC_DRAW: 3, STATIC_DRAW: 4, FLOAT: 5, TRIANGLES: 6, UNSIGNED_INT: 7,+ createBuffer: () => ({}), createVertexArray: () => ({}), bindBuffer: noop, bindVertexArray: noop, bufferData: noop,+ enableVertexAttribArray: noop, disableVertexAttribArray: noop, vertexAttribPointer: noop, vertexAttribDivisor: noop,+ vertexAttrib2f: noop, vertexAttrib3f: noop,+ bufferSubData: (target, offset, data, start, length) => calls.push({ upload: length / STRIDE }),+ drawElementsInstanced: (mode, count, type, offset, instances) => calls.push({ indices: count, instances }),+ };+ renderer.createTexture = () => null;+ renderer.partLocations = new Map();+ renderer.uploadBuffer = (target, data) => {+ renderer.buffers.push({});+ return {};+ };+ const batch = renderer.uploadBatchData(parts, {});+ return { renderer, batch, calls };+}++function rigidPart(name, geometry, position, extra = {}) {+ const matrix = mat4.fromTranslation(mat4.create(), position);+ return { name, geometry, matrix, material: { tag: 'surface', color: [0.5, 0.5, 0.5], metallic: 0, roughness: 0.5 }, ...extra };+}++test('the renderer draws only the visible instances, each level from its own geometry', () => {+ const geometry = sphere(24, 12);+ const lods = generateGeometryLods(geometry, { ratios: [0.25] });+ const positions = [[0, 0, 4], [0, 0, -80], [900, 0, 0]];+ const parts = positions.map((position, index) => rigidPart(`p${index}`, geometry, position, { lods }));+ const { renderer, batch, calls } = drawingRenderer(parts);+ const { viewProjection, projection, planes } = cameraMatrices([0, 0, 10]);+ renderer.viewProjection = viewProjection;+ renderer.projection = projection;+ renderer.frustumPlanes = planes;+ const selection = renderer.selectBatchInstances(batch);+ assert.equal(selection.visibleCount, 2);+ renderer.drawSelectedLevels(batch, selection);+ const draws = calls.filter(call => call.instances);+ assert.deepEqual(draws.map(call => call.instances), [1, 1]);+ assert.equal(draws[0].indices, geometry.indices.length);+ assert.equal(draws[1].indices, lods[1].geometry.indices.length);+ assert.ok(lods[1].geometry.indices.length < geometry.indices.length);+});++test('culling is off for deforming, skinned and alpha-blended batches, and lods are refused there', () => {+ const geometry = box(0, 1);+ const lods = [{ geometry, error: 0 }, { geometry: box(0, 1), error: 0.1 }];+ const { renderer, batch } = drawingRenderer([rigidPart('tree', geometry, [0, 0, 0])]);+ assert.equal(batch.cullable, true);+ const swaying = rigidPart('grass', geometry, [0, 0, 0]);+ swaying.material.tag = 'grass';+ assert.equal(renderer.createCullingState([swaying]).cullable, false);+ assert.throws(() => renderer.createCullingState([{ ...swaying, lods }]), /lods need rigid, opaque parts/);+ const glass = rigidPart('glass', geometry, [0, 0, 0]);+ glass.material.alphaMode = 'blend';+ glass.material.opacity = 0.5;+ assert.equal(renderer.createCullingState([glass]).cullable, false);+ assert.throws(() => renderer.createCullingState([rigidPart('bad', geometry, [0, 0, 0], { lods: [lods[1], lods[0]] })]), /lods must list level 0/);+});