Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Compare runtime cost with three.js on matching scenes

Nguyen Xuan Andbdd7604b723
diff --git a/bench/runtime/README.md b/bench/runtime/README.md
new file mode 100644
index 00000000..e43990e4
--- /dev/null
+++ b/bench/runtime/README.md
@@ -0,0 +1,102 @@
+# Runtime against three.js
+
+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.**
+
+## Run it
+
+Run `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.
+
+CI does not run this suite. It needs Chrome and a GPU, and `tests/runtime-report.test.js` checks only that the committed report is complete.
+
+## Result
+
+Measured on 2026-10-31 at 960 by 540 with 4 MSAA samples, against three.js 0.186.1. A ratio above 1 means that 67.js costs more.
+
+**Full frame on SwiftShader, in milliseconds.** This is the path that a headless agent uses.
+
+| Scene | 67.js | three.js | Ratio |
+| --- | --- | --- | --- |
+| `instanced-objects` | 631 | 48 (instanced 44) | 13.3 |
+| `many-materials` | 2,207 | 237 | 9.3 |
+| `many-lights` | 1,506 | 261 | 5.8 |
+| `transparency` | 1,699 | 131 | 12.9 |
+| `moving-shadows` | 411 | 43 | 9.5 |
+| `large-mesh` | 2,216 | 221 | 10.0 |
+| `skinned-characters` | 730 | 68 | 10.8 |
+
+**Full frame on an RTX 3060, in milliseconds.** Other jobs were using the GPU during this run, so these numbers are noisy.
+
+| Scene | 67.js | three.js | Ratio |
+| --- | --- | --- | --- |
+| `instanced-objects` | 1.25 | 4.34 (instanced 0.36) | 0.3 |
+| `many-materials` | 4.75 | 2.97 | 1.6 |
+| `many-lights` | 4.54 | 2.46 | 1.8 |
+| `transparency` | 2.70 | 1.35 | 2.0 |
+| `moving-shadows` | 2.34 | 1.85 | 1.3 |
+| `large-mesh` | 4.24 | 0.59 | 7.2 |
+| `skinned-characters` | 9.02 | 3.13 | 2.9 |
+
+**First frame on an RTX 3060, in milliseconds.** Each run has an empty browser profile, so no shader cache helps either engine.
+
+| Scene | 67.js | three.js | Ratio |
+| --- | --- | --- | --- |
+| `instanced-objects` | 2,608 | 204 | 12.8 |
+| `many-materials` | 2,564 | 269 | 9.5 |
+| `many-lights` | 2,655 | 276 | 9.6 |
+| `transparency` | 2,853 | 231 | 12.4 |
+| `moving-shadows` | 2,606 | 245 | 10.6 |
+| `large-mesh` | 3,113 | 459 | 6.8 |
+| `skinned-characters` | 3,266 | 551 | 5.9 |
+
+## Where each engine wins
+
+**three.js wins:**
+
+- Full frames on SwiftShader, in every scene.
+- Full frames on the RTX 3060, in 6 of 7 scenes. In the seventh, an `InstancedMesh` beats 67.js by 3.5 times.
+- The first frame, in every scene.
+- GPU memory that WebGL calls show, in every scene. 67.js allocates about 46 MB for its render targets.
+- Fewer triangles when objects are off camera, because it culls them. 67.js draws all of them (issue 37).
+- Heap memory in `skinned-characters`, because three.js clones one parsed file.
+
+**67.js wins:**
+
+- CPU time to submit a frame, in 6 of 7 scenes. It takes 0.07 ms against 3.91 ms for 5,000 individual meshes. It groups objects into a few draw calls by itself. An `InstancedMesh` needs the same grouping by hand in three.js.
+- Heap memory in 6 of 7 scenes.
+
+Issue 74 tracks the frame and first-frame costs. The cause is not measured yet.
+
+## Do the pictures match?
+
+FLIP between the two engines, where 0 means identical.
+
+| Scene | FLIP |
+| --- | --- |
+| `large-mesh` | 0.027 |
+| `instanced-objects` | 0.047 |
+| `moving-shadows` | 0.090 |
+| `skinned-characters` | 0.102 |
+| `transparency` | 0.129 |
+| `many-lights` | 0.132 |
+| `many-materials` | 0.241 |
+
+Both engines use the same geometry, lights and tone curve, so these are small differences. `many-materials` is the largest, because half of its spheres are metal and three.js has only an ambient light, with nothing for metal to reflect. 67.js reflects a constant environment map, so it is the one that has reflections.
+
+The comparison is not exact. 67.js pays for an environment map and an HDR post-processing pass, and three.js does not. A scene with an environment map in three.js costs more than this.
+
+## How it measures
+
+- **Full frame:** from the start of the render call until `readPixels` returns one pixel, which waits for the GPU. `context.finish()` returns at once in Chrome, so it can not do this.
+- **CPU submit:** the render call only.
+- **First frame:** from building the scene to the first finished frame, with a new browser and profile for each run.
+- **GPU memory:** watched through WebGL buffer, texture and renderbuffer calls. It leaves out the canvas's own buffers, for both engines.
+- **Heap:** after a forced garbage collection, minus the heap before the scene was built.
+
+`report.json` also holds GPU timer query results. Do not rely on them: they gave 0.15 ms for 1 million triangles in three.js, which is not plausible.
+
+## Limits
+
+- One machine and one resolution. Other jobs used the GPU during the RTX 3060 runs, and `report.json` records how busy it was.
+- `skinned-characters` draws its robots at one spot, so that the same pixels overdraw in both engines.
+- The scenes do not use textures.
+- These numbers replace no claim in `docs/benchmark.json`. That file compares one scene with the same raw shader in both engines, so it measures submission cost only.
diff --git a/bench/runtime/adapters.js b/bench/runtime/adapters.js
new file mode 100644
index 00000000..c7627b76
--- /dev/null
+++ b/bench/runtime/adapters.js
@@ -0,0 +1,195 @@
+// One adapter per engine. Each uses the engine's normal path for the job, and draws the same data with the same lights.
+import {
+ AmbientLight, AnimationMixer, BufferAttribute, BufferGeometry, Color, CustomToneMapping,
+ DirectionalLight, InstancedMesh, Matrix4, Mesh, MeshStandardMaterial, PerspectiveCamera, PointLight, Scene,
+ ShaderChunk, SRGBColorSpace, Vector3, WebGLRenderer,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+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';
+
+const AMBIENT_RADIANCE = 0.3;
+const SECONDS_PER_CHARACTER_OFFSET = 0.4;
+
+function acesLikeEngine(value) {
+ return (value * (2.51 * value + 0.03)) / (value * (2.43 * value + 0.59) + 0.14);
+}
+
+// three.js has its own ACES curve. This gives it the curve in src/post.js, so the pictures can be compared.
+function installSharedToneCurve() {
+ const pattern = /vec3 CustomToneMapping\( vec3 color \) \{ return color; \}/;
+ if (!pattern.test(ShaderChunk.tonemapping_pars_fragment)) return;
+ ShaderChunk.tonemapping_pars_fragment = ShaderChunk.tonemapping_pars_fragment.replace(
+ pattern,
+ 'vec3 CustomToneMapping( vec3 color ) { return saturate( ( color * ( 2.51 * color + 0.03 ) ) / ( color * ( 2.43 * color + 0.59 ) + 0.14 ) ); }',
+ );
+}
+
+function engineMaterial(material) {
+ const { opacity, ...rest } = material;
+ return { tag: 'surface', emission: 0, ...rest, ...(opacity === undefined ? {} : { alphaMode: 'blend', opacity }) };
+}
+
+export async function create67Adapter(canvas, scene, characters) {
+ const environment = {
+ world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0,
+ lightDirection: scene.sun.direction, keyColor: scene.sun.color,
+ pointLights: scene.pointLights.map(light => ({ ...light, radius: 0.05 })),
+ map: createEnvironmentMap({
+ width: 8, height: 4, data: new Float32Array(8 * 4 * 3).fill(AMBIENT_RADIANCE), showBackground: true,
+ }),
+ };
+ const parts = scene.objects.map((object, index) => ({
+ name: `object-${index}`, geometry: scene.geometries[object.geometry], matrix: object.matrix, material: engineMaterial(object.material),
+ }));
+ const assets = [];
+ if (characters) {
+ const bytes = await (await fetch(characters.url)).arrayBuffer();
+ for (let index = 0; index < characters.count; index++) {
+ const asset = await parseGltf(bytes.slice(0));
+ assets.push(asset);
+ parts.push(...asset.parts);
+ }
+ }
+ const shadowBounds = scene.shadowExtent
+ ? { 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,
+ });
+ 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: {} };
+ return {
+ context: renderer.context,
+ update(time) {
+ if (scene.update) {
+ scene.update(time);
+ renderer.updateParts(parts);
+ }
+ if (assets.length) {
+ assets.forEach((asset, index) => asset.applyAnimation(time + index * SECONDS_PER_CHARACTER_OFFSET, 0));
+ renderer.updateParts(parts);
+ }
+ },
+ render() {
+ renderer.render(frame);
+ },
+ dispose() {
+ renderer.dispose();
+ },
+ };
+}
+
+function threeGeometry(source) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute('position', new BufferAttribute(source.positions, 3));
+ geometry.setAttribute('normal', new BufferAttribute(source.normals, 3));
+ geometry.setIndex(new BufferAttribute(source.indices, 1));
+ return geometry;
+}
+
+function threeMaterial(material) {
+ const transparent = material.opacity !== undefined;
+ const color = new Color().setRGB(...material.color);
+ return new MeshStandardMaterial({
+ color, metalness: material.metallic, roughness: material.roughness, transparent, opacity: material.opacity ?? 1, depthWrite: !transparent,
+ });
+}
+
+function addThreeLights(threeScene, scene) {
+ threeScene.add(new AmbientLight(0xffffff, Math.PI * AMBIENT_RADIANCE));
+ const strength = Math.max(...scene.sun.color);
+ if (strength > 0) {
+ const sun = new DirectionalLight(new Color().setRGB(...scene.sun.color.map(value => value / strength)), strength);
+ sun.position.set(...scene.sun.direction);
+ if (scene.shadowExtent) {
+ sun.position.set(...scene.sun.direction.map(value => value * 5));
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ Object.assign(sun.shadow.camera, { left: -scene.shadowExtent, right: scene.shadowExtent, top: scene.shadowExtent, bottom: -scene.shadowExtent, near: 0.1, far: 150 });
+ }
+ threeScene.add(sun);
+ }
+ for (const light of scene.pointLights) {
+ const point = new PointLight(new Color().setRGB(...light.color), light.intensity, 0, 2);
+ point.position.set(...light.position);
+ threeScene.add(point);
+ }
+}
+
+function addIndividualMeshes(threeScene, scene) {
+ const geometries = Object.fromEntries(Object.entries(scene.geometries).map(([name, source]) => [name, threeGeometry(source)]));
+ const materials = new Map();
+ const meshes = new Map();
+ for (const object of scene.objects) {
+ if (!materials.has(object.material)) materials.set(object.material, threeMaterial(object.material));
+ const mesh = new Mesh(geometries[object.geometry], materials.get(object.material));
+ mesh.matrixAutoUpdate = false;
+ mesh.matrix.fromArray(object.matrix);
+ mesh.castShadow = Boolean(scene.shadowExtent);
+ mesh.receiveShadow = Boolean(scene.shadowExtent);
+ threeScene.add(mesh);
+ meshes.set(object, mesh);
+ }
+ return meshes;
+}
+
+function addInstancedMesh(threeScene, scene) {
+ const [first] = scene.objects;
+ const mesh = new InstancedMesh(threeGeometry(scene.geometries[first.geometry]), threeMaterial(first.material), scene.objects.length);
+ const matrix = new Matrix4();
+ scene.objects.forEach((object, index) => mesh.setMatrixAt(index, matrix.fromArray(object.matrix)));
+ threeScene.add(mesh);
+}
+
+export async function createThreeAdapter(canvas, scene, characters, { instanced = false } = {}) {
+ installSharedToneCurve();
+ const renderer = new WebGLRenderer({ canvas, antialias: true });
+ renderer.setPixelRatio(1);
+ renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
+ renderer.toneMapping = CustomToneMapping;
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.shadowMap.enabled = Boolean(scene.shadowExtent);
+ const tonedBackground = acesLikeEngine(AMBIENT_RADIANCE) ** (1 / 2.2);
+ renderer.setClearColor(new Color().setRGB(tonedBackground, tonedBackground, tonedBackground, SRGBColorSpace));
+ const threeScene = new Scene();
+ addThreeLights(threeScene, scene);
+ const meshes = instanced ? new Map() : addIndividualMeshes(threeScene, scene);
+ if (instanced) addInstancedMesh(threeScene, scene);
+ const mixers = [];
+ if (characters) {
+ const gltf = await new GLTFLoader().loadAsync(characters.url);
+ for (let index = 0; index < characters.count; index++) {
+ const copy = cloneSkeleton(gltf.scene);
+ copy.traverse(node => {
+ node.castShadow = node.isMesh === true;
+ });
+ threeScene.add(copy);
+ const mixer = new AnimationMixer(copy);
+ mixer.clipAction(gltf.animations[0]).play();
+ mixers.push(mixer);
+ }
+ }
+ const camera = new PerspectiveCamera(scene.camera.fov, canvas.clientWidth / canvas.clientHeight, scene.camera.near, scene.camera.far);
+ camera.position.set(...scene.camera.eye);
+ camera.lookAt(new Vector3(...scene.camera.target));
+ return {
+ context: renderer.getContext(),
+ update(time) {
+ if (scene.update) {
+ scene.update(time);
+ for (const [object, mesh] of meshes) mesh.matrix.fromArray(object.matrix);
+ }
+ mixers.forEach((mixer, index) => mixer.setTime(time + index * SECONDS_PER_CHARACTER_OFFSET));
+ },
+ render() {
+ renderer.render(threeScene, camera);
+ },
+ dispose() {
+ renderer.dispose();
+ },
+ };
+}
+
diff --git a/bench/runtime/harness.html b/bench/runtime/harness.html
new file mode 100644
index 00000000..4cb9a49a
--- /dev/null
+++ b/bench/runtime/harness.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+<head>
+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>
+</head>
+<body>
+<canvas></canvas>
+<script type="module" src="./harness.js"></script>
+</body>
+</html>
diff --git a/bench/runtime/harness.js b/bench/runtime/harness.js
new file mode 100644
index 00000000..1b7feaa2
--- /dev/null
+++ b/bench/runtime/harness.js
@@ -0,0 +1,186 @@
+// Runs in the page. It measures one engine on one scene, in a page of its own, so runs do not share a heap.
+import { create67Adapter, createThreeAdapter } from './adapters.js';
+import { BENCHMARK_SCENES } from './scenes.js';
+
+const WARMUP_FRAMES = 20;
+const FRAME_TIME_STEP = 1 / 60;
+const BYTES_PER_PIXEL_BY_FORMAT = new Map([
+ [WebGL2RenderingContext.R8, 1], [WebGL2RenderingContext.RG8, 2], [WebGL2RenderingContext.RGBA16F, 8],
+ [WebGL2RenderingContext.RGBA32F, 16], [WebGL2RenderingContext.R32F, 4], [WebGL2RenderingContext.RG16F, 4],
+ [WebGL2RenderingContext.R11F_G11F_B10F, 4], [WebGL2RenderingContext.DEPTH_COMPONENT16, 2],
+]);
+const DEFAULT_BYTES_PER_PIXEL = 4;
+const BYTES_FOR_MIP_CHAINS = 4 / 3;
+const ONE_PIXEL = new Uint8Array(4);
+
+// Counts draw calls and GPU memory by watching WebGL, so one method applies to both engines.
+function watchWebGl() {
+ const prototype = WebGL2RenderingContext.prototype;
+ const counters = { drawCalls: 0, triangles: 0 };
+ const sizes = new Map();
+ const bound = new Map();
+ const wrap = (name, after) => {
+ const original = prototype[name];
+ prototype[name] = function wrapped(...parameters) {
+ const result = original.apply(this, parameters);
+ after(this, parameters, result);
+ return result;
+ };
+ };
+ const addTriangles = (mode, count, instances = 1) => {
+ counters.drawCalls += 1;
+ if (mode === WebGL2RenderingContext.TRIANGLES) counters.triangles += (count / 3) * instances;
+ };
+ wrap('drawElements', (_, [mode, count]) => addTriangles(mode, count));
+ wrap('drawArrays', (_, [mode, , count]) => addTriangles(mode, count));
+ wrap('drawElementsInstanced', (_, [mode, count, , , instances]) => addTriangles(mode, count, instances));
+ wrap('drawArraysInstanced', (_, [mode, , count, instances]) => addTriangles(mode, count, instances));
+ wrap('bindBuffer', (_, [target, buffer]) => bound.set(target, buffer));
+ wrap('bufferData', (_, [target, data]) => {
+ const handle = bound.get(target);
+ if (handle) sizes.set(handle, typeof data === 'number' ? data : data?.byteLength ?? 0);
+ });
+ wrap('deleteBuffer', (_, [buffer]) => sizes.delete(buffer));
+ wrap('bindTexture', (_, [target, texture]) => bound.set(target, texture));
+ wrap('texImage2D', (_, [target, level, format, width, height]) => {
+ const handle = bound.get(target) ?? bound.get(WebGL2RenderingContext.TEXTURE_CUBE_MAP);
+ if (handle && level === 0 && typeof width === 'number' && typeof height === 'number') {
+ sizes.set(handle, width * height * (BYTES_PER_PIXEL_BY_FORMAT.get(format) ?? DEFAULT_BYTES_PER_PIXEL));
+ }
+ });
+ wrap('texStorage2D', (_, [target, levels, format, width, height]) => {
+ const handle = bound.get(target);
+ if (!handle) return;
+ const mipFactor = levels > 1 ? BYTES_FOR_MIP_CHAINS : 1;
+ sizes.set(handle, width * height * (BYTES_PER_PIXEL_BY_FORMAT.get(format) ?? DEFAULT_BYTES_PER_PIXEL) * mipFactor);
+ });
+ wrap('deleteTexture', (_, [texture]) => sizes.delete(texture));
+ wrap('bindRenderbuffer', (_, [target, renderbuffer]) => bound.set(target, renderbuffer));
+ wrap('renderbufferStorage', (_, [target, format, width, height]) => {
+ const handle = bound.get(target);
+ if (handle) sizes.set(handle, width * height * (BYTES_PER_PIXEL_BY_FORMAT.get(format) ?? DEFAULT_BYTES_PER_PIXEL));
+ });
+ wrap('renderbufferStorageMultisample', (_, [target, samples, format, width, height]) => {
+ const handle = bound.get(target);
+ if (handle) sizes.set(handle, width * height * samples * (BYTES_PER_PIXEL_BY_FORMAT.get(format) ?? DEFAULT_BYTES_PER_PIXEL));
+ });
+ wrap('deleteRenderbuffer', (_, [renderbuffer]) => sizes.delete(renderbuffer));
+ return {
+ counters,
+ gpuBytes: () => [...sizes.values()].reduce((total, size) => total + size, 0),
+ resetDrawCounters() {
+ counters.drawCalls = 0;
+ counters.triangles = 0;
+ },
+ };
+}
+
+// context.finish() returns at once in Chrome. Reading one pixel waits until the GPU has finished the frame, so frames
+// can not pile up in its queue, and the wait stays outside the measured time.
+function waitForGpu(context) {
+ context.readPixels(0, 0, 1, 1, context.RGBA, context.UNSIGNED_BYTE, ONE_PIXEL);
+}
+
+function median(values) {
+ if (!values.length) return null;
+ const sorted = [...values].sort((first, second) => first - second);
+ return sorted[Math.floor(sorted.length / 2)];
+}
+
+function heapBytes() {
+ globalThis.gc?.();
+ return performance.memory?.usedJSHeapSize ?? null;
+}
+
+async function readTimerQueries(context, queries, timer) {
+ const results = [];
+ for (const query of queries) {
+ const started = performance.now();
+ while (!context.getQueryParameter(query, context.QUERY_RESULT_AVAILABLE)) {
+ if (performance.now() - started > 5000) throw new Error('A GPU timer query timed out.');
+ await new Promise(resolve => setTimeout(resolve, 1));
+ }
+ if (!context.getParameter(timer.GPU_DISJOINT_EXT)) results.push(context.getQueryParameter(query, context.QUERY_RESULT) / 1e6);
+ context.deleteQuery(query);
+ }
+ return results;
+}
+
+async function createAdapter(engine, canvas, scene, characters) {
+ if (engine === '67js') return create67Adapter(canvas, scene, characters);
+ if (engine === 'three-instanced') return createThreeAdapter(canvas, scene, characters, { instanced: true });
+ return createThreeAdapter(canvas, scene, characters);
+}
+
+const watcher = watchWebGl();
+
+async function runBenchmark(sceneId, engine, frames) {
+ const definition = BENCHMARK_SCENES[sceneId];
+ const canvas = document.querySelector('canvas');
+ const heapBefore = heapBytes();
+ const started = performance.now();
+ const scene = definition.build();
+ const adapter = await createAdapter(engine, canvas, scene, definition.characters);
+ adapter.update(0);
+ adapter.render();
+ waitForGpu(adapter.context);
+ const firstFrameMilliseconds = performance.now() - started;
+ const timer = adapter.context.getExtension('EXT_disjoint_timer_query_webgl2');
+ let time = 0;
+ for (let frame = 0; frame < WARMUP_FRAMES; frame++) {
+ time += FRAME_TIME_STEP;
+ adapter.update(time);
+ adapter.render();
+ waitForGpu(adapter.context);
+ }
+ const updateTimes = [];
+ const renderTimes = [];
+ const fullFrameTimes = [];
+ const queries = [];
+ watcher.resetDrawCounters();
+ for (let frame = 0; frame < frames; frame++) {
+ time += FRAME_TIME_STEP;
+ const beforeUpdate = performance.now();
+ adapter.update(time);
+ const beforeRender = performance.now();
+ let query = null;
+ if (timer) {
+ query = adapter.context.createQuery();
+ adapter.context.beginQuery(timer.TIME_ELAPSED_EXT, query);
+ }
+ adapter.render();
+ if (timer) {
+ adapter.context.endQuery(timer.TIME_ELAPSED_EXT);
+ queries.push(query);
+ }
+ const afterRender = performance.now();
+ waitForGpu(adapter.context);
+ fullFrameTimes.push(performance.now() - beforeRender);
+ updateTimes.push(beforeRender - beforeUpdate);
+ renderTimes.push(afterRender - beforeRender);
+ }
+ const gpuTimes = timer ? await readTimerQueries(adapter.context, queries, timer) : [];
+ const drawCalls = watcher.counters.drawCalls / frames;
+ const triangles = watcher.counters.triangles / frames;
+ adapter.update(0);
+ adapter.render();
+ const image = canvas.toDataURL('image/png').split(',')[1];
+ const result = {
+ scene: sceneId, engine,
+ firstFrameMilliseconds,
+ updateMilliseconds: median(updateTimes),
+ renderCpuMilliseconds: median(renderTimes),
+ gpuMilliseconds: median(gpuTimes),
+ fullFrameMilliseconds: median(fullFrameTimes),
+ drawCalls, triangles,
+ gpuBytes: watcher.gpuBytes(),
+ heapBytes: heapBefore === null ? null : heapBytes() - heapBefore,
+ glError: adapter.context.getError(),
+ image,
+ };
+ adapter.dispose();
+ return result;
+}
+
+window.runBenchmark = runBenchmark;
+window.benchmarkScenes = Object.fromEntries(Object.entries(BENCHMARK_SCENES).map(([id, scene]) => [id, scene.description]));
diff --git a/bench/runtime/report.json b/bench/runtime/report.json
new file mode 100644
index 00000000..f25ab3d2
--- /dev/null
+++ b/bench/runtime/report.json
@@ -0,0 +1,431 @@
+{
+ "resolution": [
+ 960,
+ 540
+ ],
+ "msaaSamples": 4,
+ "graphics": {
+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",
+ "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"
+ },
+ "results": {
+ "gpu": {
+ "instanced-objects": {
+ "67js": {
+ "firstFrameMilliseconds": 2608,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.07,
+ "gpuMilliseconds": 0.66,
+ "fullFrameMilliseconds": 1.25,
+ "drawCalls": 3,
+ "triangles": 60002,
+ "gpuMegabytes": 46.51,
+ "heapMegabytes": 5,
+ "gpuBusyBefore": 95
+ },
+ "three": {
+ "firstFrameMilliseconds": 204,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 3.91,
+ "gpuMilliseconds": 0.3,
+ "fullFrameMilliseconds": 4.34,
+ "drawCalls": 4154,
+ "triangles": 49848,
+ "gpuMegabytes": 0,
+ "heapMegabytes": 8.5,
+ "gpuBusyBefore": 41
+ },
+ "three-instanced": {
+ "firstFrameMilliseconds": 190,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.05,
+ "gpuMilliseconds": 0.05,
+ "fullFrameMilliseconds": 0.36,
+ "drawCalls": 1,
+ "triangles": 60000,
+ "gpuMegabytes": 0.31,
+ "heapMegabytes": 2.4,
+ "gpuBusyBefore": 10
+ }
+ },
+ "many-materials": {
+ "67js": {
+ "firstFrameMilliseconds": 2564,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.11,
+ "gpuMilliseconds": 4.24,
+ "fullFrameMilliseconds": 4.75,
+ "drawCalls": 4,
+ "triangles": 960014,
+ "gpuMegabytes": 45.91,
+ "heapMegabytes": 2.4,
+ "gpuBusyBefore": 19
+ },
+ "three": {
+ "firstFrameMilliseconds": 269,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 2.34,
+ "gpuMilliseconds": 0.19,
+ "fullFrameMilliseconds": 2.97,
+ "drawCalls": 965,
+ "triangles": 925452,
+ "gpuMegabytes": 0.03,
+ "heapMegabytes": 12.9,
+ "gpuBusyBefore": 84
+ }
+ },
+ "many-lights": {
+ "67js": {
+ "firstFrameMilliseconds": 2655,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.11,
+ "gpuMilliseconds": 3.78,
+ "fullFrameMilliseconds": 4.54,
+ "drawCalls": 4,
+ "triangles": 384014,
+ "gpuMegabytes": 45.82,
+ "heapMegabytes": 1.6,
+ "gpuBusyBefore": 13
+ },
+ "three": {
+ "firstFrameMilliseconds": 276,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.82,
+ "gpuMilliseconds": 0.33,
+ "fullFrameMilliseconds": 2.46,
+ "drawCalls": 385,
+ "triangles": 368652,
+ "gpuMegabytes": 0.03,
+ "heapMegabytes": 2.3,
+ "gpuBusyBefore": 92
+ }
+ },
+ "transparency": {
+ "67js": {
+ "firstFrameMilliseconds": 2853,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.16,
+ "gpuMilliseconds": 2.02,
+ "fullFrameMilliseconds": 2.7,
+ "drawCalls": 4,
+ "triangles": 288014,
+ "gpuMegabytes": 45.8,
+ "heapMegabytes": 1.4,
+ "gpuBusyBefore": 88
+ },
+ "three": {
+ "firstFrameMilliseconds": 231,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.55,
+ "gpuMilliseconds": 0.16,
+ "fullFrameMilliseconds": 1.35,
+ "drawCalls": 301,
+ "triangles": 288012,
+ "gpuMegabytes": 0.03,
+ "heapMegabytes": 5,
+ "gpuBusyBefore": 83
+ }
+ },
+ "moving-shadows": {
+ "67js": {
+ "firstFrameMilliseconds": 2606,
+ "updateMilliseconds": 0.54,
+ "renderCpuMilliseconds": 0.21,
+ "gpuMilliseconds": 1.34,
+ "fullFrameMilliseconds": 2.34,
+ "drawCalls": 4,
+ "triangles": 12026,
+ "gpuMegabytes": 45.8,
+ "heapMegabytes": 1.4,
+ "gpuBusyBefore": 8
+ },
+ "three": {
+ "firstFrameMilliseconds": 245,
+ "updateMilliseconds": 0.05,
+ "renderCpuMilliseconds": 1.31,
+ "gpuMilliseconds": 0.16,
+ "fullFrameMilliseconds": 1.85,
+ "drawCalls": 1002,
+ "triangles": 12024,
+ "gpuMegabytes": 32,
+ "heapMegabytes": 2.2,
+ "gpuBusyBefore": 98
+ }
+ },
+ "large-mesh": {
+ "67js": {
+ "firstFrameMilliseconds": 3113,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.11,
+ "gpuMilliseconds": 3.57,
+ "fullFrameMilliseconds": 4.24,
+ "drawCalls": 3,
+ "triangles": 1046530,
+ "gpuMegabytes": 73.75,
+ "heapMegabytes": 28.6,
+ "gpuBusyBefore": 10
+ },
+ "three": {
+ "firstFrameMilliseconds": 459,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.05,
+ "gpuMilliseconds": 0.15,
+ "fullFrameMilliseconds": 0.59,
+ "drawCalls": 1,
+ "triangles": 1046528,
+ "gpuMegabytes": 24.01,
+ "heapMegabytes": 29,
+ "gpuBusyBefore": 85
+ }
+ },
+ "skinned-characters": {
+ "67js": {
+ "firstFrameMilliseconds": 3266,
+ "updateMilliseconds": 7.57,
+ "renderCpuMilliseconds": 1.27,
+ "gpuMilliseconds": 5.17,
+ "fullFrameMilliseconds": 9.02,
+ "drawCalls": 308,
+ "triangles": 51818,
+ "gpuMegabytes": 49.02,
+ "heapMegabytes": 17.8,
+ "gpuBusyBefore": 73
+ },
+ "three": {
+ "firstFrameMilliseconds": 551,
+ "updateMilliseconds": 0.05,
+ "renderCpuMilliseconds": 1.84,
+ "gpuMilliseconds": 0.37,
+ "fullFrameMilliseconds": 3.13,
+ "drawCalls": 306,
+ "triangles": 51816,
+ "gpuMegabytes": 32.34,
+ "heapMegabytes": 5.6,
+ "gpuBusyBefore": 79
+ }
+ }
+ },
+ "cpu": {
+ "instanced-objects": {
+ "67js": {
+ "firstFrameMilliseconds": 2109,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.2,
+ "gpuMilliseconds": 629.74,
+ "fullFrameMilliseconds": 631.01,
+ "drawCalls": 3,
+ "triangles": 60002,
+ "gpuMegabytes": 46.51,
+ "heapMegabytes": 4.9,
+ "gpuBusyBefore": 78
+ },
+ "three": {
+ "firstFrameMilliseconds": 290,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 7.87,
+ "gpuMilliseconds": 36.89,
+ "fullFrameMilliseconds": 47.58,
+ "drawCalls": 4154,
+ "triangles": 49848,
+ "gpuMegabytes": 0,
+ "heapMegabytes": 8.5,
+ "gpuBusyBefore": 35
+ },
+ "three-instanced": {
+ "firstFrameMilliseconds": 347,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.18,
+ "gpuMilliseconds": 42.69,
+ "fullFrameMilliseconds": 43.66,
+ "drawCalls": 1,
+ "triangles": 60000,
+ "gpuMegabytes": 0.31,
+ "heapMegabytes": 2.4,
+ "gpuBusyBefore": 78
+ }
+ },
+ "many-materials": {
+ "67js": {
+ "firstFrameMilliseconds": 3681,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.2,
+ "gpuMilliseconds": 2206.27,
+ "fullFrameMilliseconds": 2207.49,
+ "drawCalls": 4,
+ "triangles": 960014,
+ "gpuMegabytes": 45.91,
+ "heapMegabytes": 2.4,
+ "gpuBusyBefore": 90
+ },
+ "three": {
+ "firstFrameMilliseconds": 542,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 4.51,
+ "gpuMilliseconds": 231.55,
+ "fullFrameMilliseconds": 236.68,
+ "drawCalls": 965,
+ "triangles": 925452,
+ "gpuMegabytes": 0.03,
+ "heapMegabytes": 12.9,
+ "gpuBusyBefore": 5
+ }
+ },
+ "many-lights": {
+ "67js": {
+ "firstFrameMilliseconds": 3080,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.26,
+ "gpuMilliseconds": 1504.6,
+ "fullFrameMilliseconds": 1506.23,
+ "drawCalls": 4,
+ "triangles": 384014,
+ "gpuMegabytes": 45.82,
+ "heapMegabytes": 1.6,
+ "gpuBusyBefore": 5
+ },
+ "three": {
+ "firstFrameMilliseconds": 444,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 1.12,
+ "gpuMilliseconds": 258.75,
+ "fullFrameMilliseconds": 261.08,
+ "drawCalls": 385,
+ "triangles": 368652,
+ "gpuMegabytes": 0.03,
+ "heapMegabytes": 2.3,
+ "gpuBusyBefore": 5
+ }
+ },
+ "transparency": {
+ "67js": {
+ "firstFrameMilliseconds": 3834,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.39,
+ "gpuMilliseconds": 1697.26,
+ "fullFrameMilliseconds": 1698.63,
+ "drawCalls": 4,
+ "triangles": 288014,
+ "gpuMegabytes": 45.8,
+ "heapMegabytes": 1.3,
+ "gpuBusyBefore": 30
+ },
+ "three": {
+ "firstFrameMilliseconds": 461,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 1.78,
+ "gpuMilliseconds": 128.53,
+ "fullFrameMilliseconds": 131.2,
+ "drawCalls": 301,
+ "triangles": 288012,
+ "gpuMegabytes": 0.03,
+ "heapMegabytes": 4.9,
+ "gpuBusyBefore": 5
+ }
+ },
+ "moving-shadows": {
+ "67js": {
+ "firstFrameMilliseconds": 1756,
+ "updateMilliseconds": 1.44,
+ "renderCpuMilliseconds": 0.45,
+ "gpuMilliseconds": 409.61,
+ "fullFrameMilliseconds": 411.28,
+ "drawCalls": 4,
+ "triangles": 12026,
+ "gpuMegabytes": 45.8,
+ "heapMegabytes": 1.4,
+ "gpuBusyBefore": 5
+ },
+ "three": {
+ "firstFrameMilliseconds": 336,
+ "updateMilliseconds": 0.15,
+ "renderCpuMilliseconds": 2.59,
+ "gpuMilliseconds": 39.22,
+ "fullFrameMilliseconds": 43.1,
+ "drawCalls": 1002,
+ "triangles": 12024,
+ "gpuMegabytes": 32,
+ "heapMegabytes": 2.1,
+ "gpuBusyBefore": 6
+ }
+ },
+ "large-mesh": {
+ "67js": {
+ "firstFrameMilliseconds": 4154,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.21,
+ "gpuMilliseconds": 2214.27,
+ "fullFrameMilliseconds": 2215.82,
+ "drawCalls": 3,
+ "triangles": 1046530,
+ "gpuMegabytes": 73.75,
+ "heapMegabytes": 28.6,
+ "gpuBusyBefore": 31
+ },
+ "three": {
+ "firstFrameMilliseconds": 797,
+ "updateMilliseconds": 0,
+ "renderCpuMilliseconds": 0.18,
+ "gpuMilliseconds": 219.34,
+ "fullFrameMilliseconds": 220.5,
+ "drawCalls": 1,
+ "triangles": 1046528,
+ "gpuMegabytes": 24.01,
+ "heapMegabytes": 29,
+ "gpuBusyBefore": 12
+ }
+ },
+ "skinned-characters": {
+ "67js": {
+ "firstFrameMilliseconds": 2295,
+ "updateMilliseconds": 11.43,
+ "renderCpuMilliseconds": 1.43,
+ "gpuMilliseconds": 721.09,
+ "fullFrameMilliseconds": 730.07,
+ "drawCalls": 308,
+ "triangles": 51818,
+ "gpuMegabytes": 49.02,
+ "heapMegabytes": 17.7,
+ "gpuBusyBefore": 7
+ },
+ "three": {
+ "firstFrameMilliseconds": 640,
+ "updateMilliseconds": 0.09,
+ "renderCpuMilliseconds": 2.96,
+ "gpuMilliseconds": 63.23,
+ "fullFrameMilliseconds": 67.76,
+ "drawCalls": 306,
+ "triangles": 51816,
+ "gpuMegabytes": 32.34,
+ "heapMegabytes": 5.5,
+ "gpuBusyBefore": 6
+ }
+ }
+ }
+ },
+ "scenes": {
+ "instanced-objects": "5,000 boxes that share a geometry and a material",
+ "many-materials": "1,000 spheres with 1,000 different materials",
+ "many-lights": "400 spheres lit by 8 point lights",
+ "transparency": "300 overlapping translucent spheres that need sorting",
+ "moving-shadows": "500 moving boxes that cast a directional shadow",
+ "large-mesh": "One sphere with about 1 million triangles",
+ "skinned-characters": "8 animated copies of a CC0 robot, at one spot with different clip times"
+ },
+ "pictureDifference": {
+ "cpu-instanced-objects": 0.0456,
+ "cpu-large-mesh": 0.027,
+ "cpu-many-lights": 0.131,
+ "cpu-many-materials": 0.2411,
+ "cpu-moving-shadows": 0.091,
+ "cpu-skinned-characters": 0.1037,
+ "cpu-transparency": 0.1293,
+ "gpu-instanced-objects": 0.0465,
+ "gpu-large-mesh": 0.027,
+ "gpu-many-lights": 0.1315,
+ "gpu-many-materials": 0.2411,
+ "gpu-moving-shadows": 0.0903,
+ "gpu-skinned-characters": 0.1038,
+ "gpu-transparency": 0.1293
+ },
+ "threeVersion": "0.186.1"
+}
diff --git a/bench/runtime/run.mjs b/bench/runtime/run.mjs
new file mode 100644
index 00000000..5e482aa0
--- /dev/null
+++ b/bench/runtime/run.mjs
@@ -0,0 +1,148 @@
+// Compares 67.js and three.js on matching scenes: npm run benchmark:runtime
+// Use --gpu-only to skip SwiftShader. --scene <id>, --engine <name> and --frames <count> run a part, and do not rewrite
+// the report.
+import { spawnSync } from 'node:child_process';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { resolve } from 'node:path';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const WORK_DIRECTORY = resolve('artifacts/runtime');
+const REPORT_PATH = resolve('bench/runtime/report.json');
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const SHARED_ARGUMENTS = ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding', '--enable-precise-memory-info', '--js-flags=--expose-gc'];
+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 INSTANCED_SCENES = new Set(['instanced-objects']);
+
+const flags = process.argv.slice(2);
+const gpuOnly = flags.includes('--gpu-only');
+const sceneFlag = flags.indexOf('--scene');
+const onlyScene = sceneFlag >= 0 ? flags[sceneFlag + 1] : null;
+const engineFlag = flags.indexOf('--engine');
+const onlyEngine = engineFlag >= 0 ? flags[engineFlag + 1] : null;
+const framesFlag = flags.indexOf('--frames');
+const framesOverride = framesFlag >= 0 ? Number(flags[framesFlag + 1]) : null;
+const isPartialRun = Boolean(onlyScene || onlyEngine || framesOverride);
+
+function enginesFor(sceneId) {
+ return ENGINES.filter(engine => {
+ if (onlyEngine) return engine === onlyEngine;
+ return engine !== 'three-instanced' || INSTANCED_SCENES.has(sceneId);
+ });
+}
+
+// Each run gets a new browser with an empty profile, so a shader cache from an earlier run can not hide compile time.
+async function runOne(backend, serverUrl, sceneId, engine, frames) {
+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: backend.arguments });
+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ try {
+ await page.goto(`${serverUrl}/bench/runtime/harness.html`);
+ 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'));
+ if (result.glError !== 0) throw new Error(`${sceneId} on ${engine} gave WebGL error ${result.glError}.`);
+ return result;
+ } finally {
+ await browser.close();
+ }
+}
+
+async function sceneDescriptions(browser, serverUrl) {
+ const page = await browser.newPage();
+ await page.goto(`${serverUrl}/bench/runtime/harness.html`);
+ await page.waitForFunction(() => window.benchmarkScenes);
+ const scenes = await page.evaluate(() => window.benchmarkScenes);
+ await page.close();
+ return scenes;
+}
+
+// Another job on the GPU distorts its timings, so each result records how busy the GPU was just before it ran.
+function gpuBusyPercent() {
+ const result = spawnSync('nvidia-smi', ['--query-gpu=utilization.gpu', '--format=csv,noheader,nounits'], { encoding: 'utf8' });
+ return result.status === 0 ? Number(result.stdout.trim()) : null;
+}
+
+function rounded(value, digits = 2) {
+ return value === null ? null : Number(value.toFixed(digits));
+}
+
+function summarize({ image: _image, glError: _glError, scene: _scene, engine: _engine, ...result }) {
+ return {
+ firstFrameMilliseconds: rounded(result.firstFrameMilliseconds, 0),
+ updateMilliseconds: rounded(result.updateMilliseconds),
+ renderCpuMilliseconds: rounded(result.renderCpuMilliseconds),
+ gpuMilliseconds: rounded(result.gpuMilliseconds),
+ fullFrameMilliseconds: rounded(result.fullFrameMilliseconds),
+ drawCalls: rounded(result.drawCalls, 0),
+ triangles: rounded(result.triangles, 0),
+ gpuMegabytes: rounded(result.gpuBytes / 1048576, 2),
+ heapMegabytes: result.heapBytes === null ? null : rounded(result.heapBytes / 1048576, 1),
+ };
+}
+
+async function runBackend(backendName, serverUrl, report) {
+ const backend = BACKENDS[backendName];
+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: backend.arguments });
+ try {
+ const scenes = await sceneDescriptions(browser, serverUrl);
+ report.scenes = scenes;
+ const graphicsPage = await browser.newPage();
+ report.graphics[backendName] = await graphicsPage.evaluate(() => {
+ const context = document.createElement('canvas').getContext('webgl2');
+ const debug = context.getExtension('WEBGL_debug_renderer_info');
+ return context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : context.RENDERER);
+ });
+ await graphicsPage.close();
+ for (const sceneId of Object.keys(scenes)) {
+ if (onlyScene && sceneId !== onlyScene) continue;
+ for (const engine of enginesFor(sceneId)) {
+ const gpuBusyBefore = gpuBusyPercent();
+ const result = await runOne(backend, serverUrl, sceneId, engine, framesOverride ?? backend.frames);
+ await writeFile(`${WORK_DIRECTORY}/${backendName}-${sceneId}-${engine}.png`, Buffer.from(result.image, 'base64'));
+ report.results[backendName][sceneId] ??= {};
+ report.results[backendName][sceneId][engine] = { ...summarize(result), gpuBusyBefore };
+ const summary = report.results[backendName][sceneId][engine];
+ console.log(`${backendName} ${sceneId.padEnd(20)} ${engine.padEnd(16)} first ${summary.firstFrameMilliseconds} ms, render ${summary.renderCpuMilliseconds} ms, frame ${summary.fullFrameMilliseconds} ms, ${summary.drawCalls} draws, ${summary.triangles} tris, gpu mem ${summary.gpuMegabytes} MB, heap ${summary.heapMegabytes} MB, busy ${gpuBusyBefore}%`);
+ }
+ }
+ } finally {
+ await browser.close();
+ }
+}
+
+function scorePictures() {
+ const result = spawnSync('uv', [
+ 'run', '--no-project', '--python', '3.12', '--with', 'flip-evaluator', '--with', 'pillow', '--with', 'numpy',
+ 'python', '-I', 'bench/runtime/score-pictures.py', WORK_DIRECTORY,
+ ], { stdio: 'inherit' });
+ if (result.status !== 0) throw new Error(`uv exited with ${result.status}.`);
+}
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir(WORK_DIRECTORY, { recursive: true });
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const report = { resolution: [960, 540], msaaSamples: 4, graphics: {}, results: { gpu: {}, cpu: {} }, scenes: {} };
+try {
+ const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+ await runBackend('gpu', serverUrl, report);
+ if (!gpuOnly) await runBackend('cpu', serverUrl, report);
+} finally {
+ await server.close();
+}
+if (!isPartialRun) scorePictures();
+if (!isPartialRun) {
+ report.pictureDifference = JSON.parse(await readFile(`${WORK_DIRECTORY}/pictures.json`, 'utf8'));
+ const manifest = JSON.parse(await readFile('package.json', 'utf8'));
+ report.threeVersion = manifest.devDependencies.three;
+ await writeFile(REPORT_PATH, `${JSON.stringify(report, null, 1)}\n`);
+ console.log(JSON.stringify(report.pictureDifference, null, 1));
+}
+process.exit(0);
diff --git a/bench/runtime/scenes.js b/bench/runtime/scenes.js
new file mode 100644
index 00000000..6e3de2a4
--- /dev/null
+++ b/bench/runtime/scenes.js
@@ -0,0 +1,122 @@
+// The benchmark scenes as plain data, so both engine adapters draw the same triangles, materials and lights.
+import { box, sphere } from '/src/geometry.js';
+
+const FLOOR_SIZE = 200;
+const CHARACTER_COUNT = 8;
+
+function translation(x, y, z, scale = 1) {
+ return new Float32Array([scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1]);
+}
+
+function gridObjects(count, spacing, geometry, scale, materialFor) {
+ const side = Math.ceil(Math.sqrt(count));
+ const objects = [];
+ for (let index = 0; index < count; index++) {
+ const x = (index % side - (side - 1) / 2) * spacing;
+ const z = (Math.floor(index / side) - (side - 1) / 2) * spacing;
+ objects.push({ geometry, matrix: translation(x, scale, z, scale), material: materialFor(index) });
+ }
+ return objects;
+}
+
+function hueColor(index, count) {
+ const angle = (index / count) * Math.PI * 2;
+ return [0.5 + 0.45 * Math.cos(angle), 0.5 + 0.45 * Math.cos(angle + 2.09), 0.5 + 0.45 * Math.cos(angle + 4.19)];
+}
+
+function floorObject() {
+ return {
+ geometry: 'box',
+ matrix: new Float32Array([FLOOR_SIZE, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, FLOOR_SIZE, 0, 0, -0.05, 0, 1]),
+ material: { color: [0.4, 0.4, 0.4], metallic: 0, roughness: 0.9 },
+ };
+}
+
+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 };
+
+export const BENCHMARK_SCENES = {
+ 'instanced-objects': {
+ description: '5,000 boxes that share a geometry and a material',
+ build: () => ({
+ geometries: { box: box(0, 1) },
+ objects: gridObjects(5000, 1.5, 'box', 0.5, () => SHARED_MATERIAL),
+ sun: SUN, pointLights: [], shadowExtent: 0,
+ camera: { eye: [0, 40, 70], target: [0, 0, 0], fov: 45, near: 0.5, far: 400 },
+ }),
+ },
+ 'many-materials': {
+ description: '1,000 spheres with 1,000 different materials',
+ build: () => ({
+ geometries: { box: box(0, 1), sphere: sphere(32, 16) },
+ objects: [floorObject(), ...gridObjects(1000, 2.2, 'sphere', 0.9, index => ({
+ color: hueColor(index, 1000), metallic: index % 2, roughness: 0.2 + (index % 7) * 0.1,
+ }))],
+ sun: SUN, pointLights: [], shadowExtent: 0,
+ camera: { eye: [0, 30, 55], target: [0, 0, 0], fov: 45, near: 0.5, far: 400 },
+ }),
+ },
+ 'many-lights': {
+ description: '400 spheres lit by 8 point lights',
+ build: () => {
+ const pointLights = [];
+ for (let index = 0; index < 8; index++) {
+ const angle = (index / 8) * Math.PI * 2;
+ pointLights.push({ position: [Math.cos(angle) * 14, 4, Math.sin(angle) * 14], color: hueColor(index, 8), intensity: 60 });
+ }
+ return {
+ geometries: { box: box(0, 1), sphere: sphere(32, 16) },
+ objects: [floorObject(), ...gridObjects(400, 2.2, 'sphere', 0.9, () => SHARED_MATERIAL)],
+ sun: { direction: SUN.direction, color: [0, 0, 0] }, pointLights, shadowExtent: 0,
+ camera: { eye: [0, 18, 34], target: [0, 0, 0], fov: 45, near: 0.5, far: 400 },
+ };
+ },
+ },
+ transparency: {
+ description: '300 overlapping translucent spheres that need sorting',
+ build: () => ({
+ geometries: { box: box(0, 1), sphere: sphere(32, 16) },
+ objects: [floorObject(), ...gridObjects(300, 0.9, 'sphere', 0.8, index => ({
+ color: hueColor(index, 300), metallic: 0, roughness: 0.3, opacity: 0.4,
+ }))],
+ sun: SUN, pointLights: [], shadowExtent: 0,
+ camera: { eye: [0, 7, 16], target: [0, 0.5, 0], fov: 45, near: 0.5, far: 400 },
+ }),
+ },
+ 'moving-shadows': {
+ description: '500 moving boxes that cast a directional shadow',
+ build: () => {
+ const objects = [floorObject(), ...gridObjects(500, 2, 'box', 1, () => SHARED_MATERIAL)];
+ return {
+ geometries: { box: box(0, 1) },
+ objects, sun: SUN, pointLights: [], shadowExtent: 30,
+ camera: { eye: [0, 25, 45], target: [0, 0, 0], fov: 45, near: 0.5, far: 400 },
+ moving: objects.slice(1),
+ update(time) {
+ objects.slice(1).forEach((object, index) => {
+ object.matrix[13] = 1.5 + Math.sin(time * 2 + index * 0.37);
+ });
+ },
+ };
+ },
+ },
+ 'large-mesh': {
+ description: 'One sphere with about 1 million triangles',
+ build: () => ({
+ geometries: { sphere: sphere(1024, 512) },
+ objects: [{ geometry: 'sphere', matrix: translation(0, 0, 0, 3), material: SHARED_MATERIAL }],
+ sun: SUN, pointLights: [], shadowExtent: 0,
+ camera: { eye: [0, 3, 9], target: [0, 0, 0], fov: 45, near: 0.5, far: 100 },
+ }),
+ },
+ 'skinned-characters': {
+ description: `${CHARACTER_COUNT} animated copies of a CC0 robot, at one spot with different clip times`,
+ characters: { count: CHARACTER_COUNT, url: '/tests/fixtures/RobotExpressive.glb' },
+ build: () => ({
+ geometries: { box: box(0, 1) },
+ objects: [floorObject()],
+ sun: SUN, pointLights: [], shadowExtent: 12,
+ camera: { eye: [2, 3.5, 9], target: [0, 2.4, 0], fov: 35, near: 0.1, far: 200 },
+ }),
+ },
+};
diff --git a/bench/runtime/score-pictures.py b/bench/runtime/score-pictures.py
new file mode 100644
index 00000000..2fefe57c
--- /dev/null
+++ b/bench/runtime/score-pictures.py
@@ -0,0 +1,27 @@
+# Scores how close the two engines' pictures are with FLIP, and writes one number for each scene and backend.
+# uv run --no-project --python 3.12 --with flip-evaluator --with pillow --with numpy python -I bench/runtime/score-pictures.py <work directory>
+import json
+import sys
+from pathlib import Path
+
+import flip_evaluator
+import numpy as np
+from PIL import Image
+
+
+def load(path):
+ return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) / 255
+
+
+def main():
+ work_directory = Path(sys.argv[1])
+ scores = {}
+ for reference in sorted(work_directory.glob("*-three.png")):
+ name = reference.name.removesuffix("-three.png")
+ test = work_directory / f"{name}-67js.png"
+ _, mean_error, _ = flip_evaluator.evaluate(load(reference), load(test), "LDR", inputsRGB=True)
+ scores[name] = round(float(mean_error), 4)
+ (work_directory / "pictures.json").write_text(json.dumps(scores, indent=1), encoding="utf-8")
+
+
+main()
diff --git a/docs/parity.md b/docs/parity.md
index c7fbb40e..9b706797 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 still in the glTF and modeling paths. | #27, #33, #34, #35, #36 |
-| Runtime speed | partial | One benchmark scene. There is no culling, LOD selection or adaptive quality, and bakes run on the main thread. | #28, #37, #38 |
+| 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 |
| 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/package.json b/package.json
index 13020750..459bf7c2 100644
--- a/package.json
+++ b/package.json
@@ -132,7 +132,8 @@
"smoke:agent-review": "node scripts/smoke-agent-review.mjs",
"parity": "node scripts/parity-report.mjs",
"reference": "node bench/reference/run.mjs",
- "size": "node scripts/measure-size.mjs"
+ "size": "node scripts/measure-size.mjs",
+ "benchmark:runtime": "node bench/runtime/run.mjs"
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0",
diff --git a/tests/runtime-report.test.js b/tests/runtime-report.test.js
new file mode 100644
index 00000000..3ae28099
--- /dev/null
+++ b/tests/runtime-report.test.js
@@ -0,0 +1,32 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+
+const report = JSON.parse(readFileSync(new URL('../bench/runtime/report.json', import.meta.url), 'utf8'));
+const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
+const EXPECTED_SCENES = ['instanced-objects', 'large-mesh', 'many-lights', 'many-materials', 'moving-shadows', 'skinned-characters', 'transparency'];
+const REQUIRED_MEASURES = ['firstFrameMilliseconds', 'fullFrameMilliseconds', 'renderCpuMilliseconds', 'gpuMegabytes', 'drawCalls', 'triangles'];
+
+test('the runtime report covers every scene in both engines on both backends', () => {
+ for (const backend of ['gpu', 'cpu']) {
+ assert.deepEqual(Object.keys(report.results[backend]).sort(), EXPECTED_SCENES);
+ for (const [scene, engines] of Object.entries(report.results[backend])) {
+ for (const engine of ['67js', 'three']) {
+ for (const measure of REQUIRED_MEASURES) {
+ assert.ok(Number.isFinite(engines[engine][measure]), `${backend} ${scene} ${engine} ${measure}`);
+ }
+ }
+ }
+ }
+});
+
+test('each picture difference is recorded, and the three.js version matches the package', () => {
+ assert.equal(report.threeVersion, manifest.devDependencies.three);
+ for (const scene of EXPECTED_SCENES) assert.ok(report.pictureDifference[`gpu-${scene}`] >= 0, scene);
+});
+
+test('the report names real hardware and a software renderer, and no local paths', () => {
+ assert.doesNotMatch(report.graphics.gpu, /swiftshader/i);
+ assert.match(report.graphics.cpu, /swiftshader/i);
+ assert.doesNotMatch(JSON.stringify(report), /[A-Z]:[\\/]Users/);
+});