Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Draw the shadow map once on the first frame, and profile mountain-valley

Nguyen Xuan An1dfe62bbb4c5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7ad26c8..73f965f9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- A renderer no longer draws its shadow map a second time on the first frame when the frame has no assembly; the constructor already drew it. On `mountain-valley` that removes 9.72 million shadow triangles from the first frame, with identical pictures (issue #171). `node bench/reference/profile-scene.mjs <scene>` prints where a scene's time goes, and `frame-time.mjs --plain` measures scenes that are too large for the light bake.
- The GitHub repository is `anxuanng/67.js`, public since 2026-11-02. Links and `repository.url` point there, which npm provenance needs to match.
- Follow 3 bounces by default in a light bake, up from 2 (part of issue #159, which stays open). Baked rooms scored worse after the sky visibility change (`lit-interior` 0.1444 to 0.1915, `brick-room` 0.1515 to 0.2048 against Cycles) because the occlusion map removed the world light that had been filling the light a 2 bounce path cuts off. With 3 bounces they score 0.1341 and 0.1412, `dark-shaft` 0.0609 and `temple-hall` 0.0560. A bake takes about 1.3 to 1.9 times as long (`temple-hall` 39 to 75 s); pass `bounces: 2` for the old light and time. Recipe presets are unchanged.
- Remove the streaks in baked dark scenes and the speckle in the fog's glow (part of issue #159, which stays open). A bake unwrapped each shared geometry once at unit size, so a 2 x 32 x 180 m wall got texels 90 times longer than wide (carpet 2,867 times), which drew as streaks fanning from the vanishing point; it now unwraps each part at its world size and smooths the gathered light and sky visibility over neighbouring texels of the same surface. The glow reads the frame's mip chain instead of 24 jittered single pixels. `bench/reference/noise.py` measures what FLIP misses (high frequency energy in dark regions and around the door): `temple-hall` baked 0.448 to 0.182 and its glow ring 1.826 to 0.990 (Cycles 0.158 and 1.053), `dark-shaft` baked 0.318 to 0.150; whole frame scores against Cycles stay within 0.006 and `temple-hall` baked goes from 0.0716 to 0.0578. A baked part's report `skyVisibility` now weighs texels by area, and baked thin parts get more texels (`brick-room` 28,576 to 98,848). Core grows 92 bytes gzip and a frame with fog costs about 0.5 ms more on a shared machine. **Baked scenes with long or thin parts look smoother and lightmaps are larger.**
diff --git a/bench/reference/frame-time.mjs b/bench/reference/frame-time.mjs
index ef913c59..492e3071 100644
--- a/bench/reference/frame-time.mjs
+++ b/bench/reference/frame-time.mjs
@@ -24,7 +24,10 @@ try {
const results = [];
// Alternate the order so a drifting machine load does not favor one side. --cascades measures one map and three
// cascades, each with a still camera and with a camera that moves every frame.
- const variants = process.argv.includes('--cascades')
+ // --plain measures only the plain frame, for scenes with more parts than the light bake takes.
+ const variants = process.argv.includes('--plain')
+ ? [1, 2, 3].map(() => ({ bake: false, probes: false }))
+ : process.argv.includes('--cascades')
? [0, 3, 0, 3].flatMap(cascades => [false, true].map(orbit => ({ bake: false, cascades, orbit })))
: [1, 2, 3].flatMap(round => (round % 2 ? [[false, false], [true, false], [true, true], [false, true]] : [[false, true], [true, true], [true, false], [false, false]]).map(([bake, probes]) => ({ bake, probes })));
for (const variant of variants) {
diff --git a/bench/reference/profile-scene.mjs b/bench/reference/profile-scene.mjs
new file mode 100644
index 00000000..1a237d1c
--- /dev/null
+++ b/bench/reference/profile-scene.mjs
@@ -0,0 +1,86 @@
+// Where the time of one reference scene goes: scene build, renderer construction (geometry upload), first frame, later frames.
+// node bench/reference/profile-scene.mjs [scene-id] [gpu|cpu]
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const PAGE_LOAD_TIMEOUT = 180000;
+const [sceneId = 'mountain-valley', backend = 'gpu'] = process.argv.slice(2);
+const BACKEND_ARGUMENTS = {
+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],
+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+};
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
+
+async function profileOnce(page) {
+ return page.evaluate(async id => {
+ const { REFERENCE_SCENES } = await import('/bench/reference/scenes.js');
+ const { Renderer67 } = await import('/src/renderer.js');
+ const { applyLightLinks } = await import('/src/light-linking.js');
+ const milliseconds = {};
+ let started = performance.now();
+ const lap = name => {
+ milliseconds[name] = Number((performance.now() - started).toFixed(1));
+ started = performance.now();
+ };
+ // Counts what each frame hands to the GPU: draw calls and triangles.
+ const drawn = { calls: 0, triangles: 0 };
+ const originalDraw = WebGL2RenderingContext.prototype.drawElementsInstanced;
+ WebGL2RenderingContext.prototype.drawElementsInstanced = function (mode, count, type, offset, instances) {
+ drawn.calls++;
+ drawn.triangles += (count / 3) * instances;
+ return originalDraw.call(this, mode, count, type, offset, instances);
+ };
+ const scene = await REFERENCE_SCENES[id]();
+ lap('sceneBuild');
+ const linked = applyLightLinks(scene.parts, scene.environment);
+ lap('lightLinks');
+ const canvas = document.querySelector('canvas');
+ const renderer = new Renderer67(canvas, linked, {
+ ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,
+ environment: scene.environment, shadowBounds: scene.shadow, shadowCascades: null,
+ });
+ lap('rendererConstruct');
+ renderer.resize();
+ const gl = renderer.context;
+ const pixel = new Uint8Array(4);
+ const wait = () => gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
+ const frame = { ...scene.camera, environment: scene.environment, time: 0, exposure: 1, effects: { ambientOcclusion: 0, ambientOcclusionRadius: 0.5 } };
+ renderer.render(frame);
+ wait();
+ lap('firstFrame');
+ const firstFrameDrawn = { ...drawn };
+ drawn.calls = 0;
+ drawn.triangles = 0;
+ renderer.render(frame);
+ wait();
+ lap('secondFrame');
+ const secondFrameDrawn = { ...drawn };
+ WebGL2RenderingContext.prototype.drawElementsInstanced = originalDraw;
+ renderer.render(frame);
+ wait();
+ lap('thirdFrame');
+ const image = canvas.toDataURL('image/png');
+ lap('canvasToPng');
+ renderer.dispose();
+ return { parts: scene.parts.length, batches: renderer.batches.length, sceneTriangles: renderer.triangles, firstFrameDrawn, secondFrameDrawn, pngBytes: image.length, milliseconds };
+ }, sceneId);
+}
+
+try {
+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });
+ await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: PAGE_LOAD_TIMEOUT });
+ await page.waitForFunction(() => window.measureReferenceFrameTime, null, { timeout: PAGE_LOAD_TIMEOUT });
+ const runs = [];
+ for (let run = 0; run < 3; run++) runs.push(await profileOnce(page));
+ console.log(JSON.stringify({ sceneId, backend, runs }, null, 1));
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/bench/runtime/PROFILE.md b/bench/runtime/PROFILE.md
index 2e1d59bb..d948990e 100644
--- a/bench/runtime/PROFILE.md
+++ b/bench/runtime/PROFILE.md
@@ -176,3 +176,30 @@ The vertex split on `large-mesh` (1,070 ms; the vertex stage alone is 360 ms the
**3 times is not met.** What is left, by size, on `instanced-objects` (frame about 265): the lit shader about 160 over a constant shader (shadow filter, environment lookups, three lights, runtime-uniform fill and fog), the resolve 35, the background 25, the post pass 30. Items that need a picture or format decision by An: (a) `R11F_G11F_B10F` for the 4 sample target and the frame texture, without alpha, only for an opaque canvas. Measured: `instanced-objects` 338 to 271 (20 percent), but the pictures are not identical: mean absolute difference 0.13 to 0.59 levels per scene, maximum 6 to 53 levels, and the `transparency` scene has 32,689 pixels more than 2 levels away. It was not kept; `npm run reference` was not run on it. (b) Fewer shadow taps, or no MSAA (about 40 percent), or an LDR target (about 20 percent), as before. Cheap exact ones left: `boxPosition` only when a box-mapped material exists (about 25 ms on `large-mesh`), starting the environment background program with the others.
Tests: `npm test` 1,292 tests, 1,283 pass; the 8 failures all need the optional `manifold-3d`, which this checkout does not have (mesh boolean, bracket recipe, blender-golden, other-clients, agent-asset-mesh, two suite reference tests). `npm run size` passes after `--update-baseline` and `--set-budgets`, because the program variants add about 2.4 to 2.8 KB gzip to the entries that include the renderer.
+
+## `mountain-valley`: where the time goes (issue #171)
+
+`node bench/reference/profile-scene.mjs mountain-valley gpu|cpu` runs the phases of one render three times and counts what the frame hands to the GPU. The scene has 7,698 parts in 418 batches and 9,721,668 triangles before culling. Measured on the RTX 3060 and on SwiftShader, 2026-11-02, while other sessions loaded the machine, so each number is a range over 3 runs.
+
+| Phase | RTX 3060 (ms) | SwiftShader (ms) |
+| --- | --- | --- |
+| Scene build (terrain, scatter, level selection) | 1,690 to 2,050 | 1,680 to 1,950 |
+| Renderer construction (upload, shadow commands queued) | 190 to 640 | 180 to 250 |
+| First frame, before the change | 41 to 94 | 9,900 to 10,600 |
+| First frame, after the change | 30 to 70 | 9,100 to 9,250 |
+| Later frame (main pass only) | 19 to 20 | 6,800 to 7,300 |
+| Whole `run.mjs` step for the scene | 10,000 to 15,200 | 19,900 to 22,400 |
+
+Triangles handed to the GPU: the later frame draws 6.46 million in 184 calls after frustum culling. Before the change the first frame drew 25.90 million in 1,020 calls, which is the main pass plus two shadow passes of 9.72 million each. After it draws 16.18 million in 602 calls, one shadow pass.
+
+What this shows:
+
+- The 8.3 s of the issue is not the GPU frame. On the 3060 the whole frame is about 20 ms. Most of the wall time of the step is outside the frame: scene build 1.7 s, and about 7 s for the harness to move the 21 MB scene description out of the page and write it, which is Blender export work and not renderer work. The in-page describe step itself takes 0.6 s (43 ms for the parts, 580 ms for the geometry bytes).
+- On SwiftShader the main pass is 7 s of the 9 s first frame, so triangles drawn matter there. The shadow pass is about 1.5 s per pass and is not culled: `drawShadowCasters` draws every caster batch whole, with no frustum test against the light and no level selection.
+- Level of detail already works on the camera side: with `distanceScale: 3` the trees switch at 114 m and 285 m, and 4,469 of 13,951 instances are beyond `cullDistance`. The last level still has 2,180 triangles per conifer (a trunk of about 2,050 and a crown of 120), so about 4,500 trees at 285 m and beyond make most of the 6.46 million.
+
+Kept: the constructor draws the shadow map, and the first `render` drew it again because `assemblyAmount` started undefined and compared as changed. It now starts at 0. Pictures are byte-identical to the renders before the change (GPU and SwiftShader PNG compared with `cmp`). Effect: first frame 41 to 94 ms became 30 to 70 ms on the 3060, and 9.9 to 10.6 s became 9.1 to 9.25 s on SwiftShader. The main pass is unchanged.
+
+Tried and reverted: a fourth tree level of detail beyond 260 m (trunk only, crown clumps 2.6 times wider, 152 triangles for a conifer). The unculled count fell, but the score against Cycles moved from 0.3473 to 0.3427 (SwiftShader 0.3460 to 0.3413), outside the 0.002 limit, and the other 20 scenes kept their scores. Distant trees are not invisible in this picture: the forest is a wide band across the valley and its coverage changes the mean. A gentler far level (keep the branches, widen the clumps less) was not tried because one rescore takes about 50 minutes on a loaded machine.
+
+Next ideas, by expected size: a far level that keeps the picture (try the clump width at 1.5 times and the trunk with its first branches); shadow level selection from the shadow texel size (2.2 m here, so level 3 geometry is enough for every tree in the map); a light frustum test per instance in the shadow pass; scene build at 1.7 s, of which scatter is 0.55 s and the rest is terrain and painting.
diff --git a/src/renderer.js b/src/renderer.js
index e760e7d2..03a0c456 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -431,6 +431,8 @@ export class Renderer67 {
this.textureBytes = 4;
this.shadowsDirty = true;
this.windState = { time: 0, strength: 0.3 };
+ // The shadow map the constructor draws uses no assembly, so a first frame with none does not draw it again.
+ this.assemblyAmount = 0;
const groups = groupParts(this.groundPart ? [...parts, this.groundPart] : parts, batching);
const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);
this.hasSkins = groups.some(group => group[0].skin);