Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Cut the water mirror cost to +25% with a larger small-part floor (part of #316)

Nguyen Xuan An18f847764db9
diff --git a/changes/316-mirror-cost.md b/changes/316-mirror-cost.md
new file mode 100644
index 00000000..ca8012f1
--- /dev/null
+++ b/changes/316-mirror-cost.md
@@ -0,0 +1,3 @@
+- The water mirror draw now skips a part whose bounding sphere covers under 5 pixels of radius on screen (it was 1.5), since the ripples and blur hide it (part of #316). On the 960 by 540 water benchmark (20k pebbles, dense terrain with `mirrorLevels: 2`) the mirror pass draws 97 instances and 184 K triangles where it drew 1,241 and 527 K; against the uncut mirror the lit frame differs by at most 3 of 255 per channel (mean 0.0017).
+- `scripts/benchmark-water-reflection.mjs` builds its terrain with `mirrorLevels: 2` by default (`--mirror-levels 0` gives the old numbers) and runs its variants in turn for several rounds (`--rounds`, default 3) and pools the timings, so a machine under load drifts the same way for every variant (part of #316).
+- Median GPU ms per frame on the RTX 3060 through the GPU lock, 960 by 540, 240 samples per variant: reflection off 6.08, old unculled mirror 10.79 (+77%), new mirror 7.60 (+25%), `updateEvery: 2` 6.54 (+7%), still camera 6.08 (0 mirror draws). With `mirrorLevels` left at 0 the new mirror costs about +70% in the same scene, because the mirror then draws every terrain triangle: a terrain used with water should set `mirrorLevels: 2`. With the mirror draw stripped to two instances the pass costs 0.1 ms, so the rest is the geometry it draws, not fill: a mirror at scale 0.5 is no faster than at 0.75.
diff --git a/changes/316-mirror-cost.size.md b/changes/316-mirror-cost.size.md
new file mode 100644
index 00000000..f320ccf8
--- /dev/null
+++ b/changes/316-mirror-cost.size.md
@@ -0,0 +1 @@
+- No bundle grows. Gzip bytes after the change against origin/main: entry:core 80032 (0), entry:water-reflection 13036 (-2), scene:lit-box 50137 (0), scene:gltf-box 77581 (0), scene:agent-scene 103052 (-3), scene:agent-scene+lazy 359884 (-16). The only source change in a shipped file is a constant in the water addon.
diff --git a/scripts/benchmark-water-reflection.mjs b/scripts/benchmark-water-reflection.mjs
index 86fd2411..ec6116db 100644
--- a/scripts/benchmark-water-reflection.mjs
+++ b/scripts/benchmark-water-reflection.mjs
@@ -1,6 +1,6 @@
// Times a lit frame of a large sea with dense terrain and many small parts, with the water reflection off and on, and counts
// what the mirror pass draws. GPU time comes from a native timer query, so run it through the GPU lock:
-// bash ~/.agents/tools/gpu-lock.sh node scripts/benchmark-water-reflection.mjs [--width 1920] [--height 1080] [--parts 20000] [--stills folder]
+// bash ~/.agents/tools/gpu-lock.sh node scripts/benchmark-water-reflection.mjs [--width 1920] [--height 1080] [--parts 20000] [--mirror-levels 2] [--rounds 3] [--stills folder]
// --counts-only skips the timer and runs on SwiftShader, so it needs no GPU lock and prints draw counts only.
// --stills writes a PNG of the lit frame for the off, on and half-scale variants, for a side-by-side check.
// The draw counts (calls, instances, triangles in the mirror pass) do not need the GPU and stay valid when the lock is busy.
@@ -18,7 +18,8 @@ const width = argument('width', 1920);
const height = argument('height', 1080);
const smallPartCount = argument('parts', 20000);
const SAMPLES = argument('samples', 20);
-const mirrorLevels = argument('mirror-levels', 0);
+const ROUNDS = argument('rounds', 3);
+const mirrorLevels = argument('mirror-levels', 2);
const countsOnly = process.argv.includes('--counts-only');
const stillsFolder =process.argv.includes('--stills') ? process.argv[process.argv.indexOf('--stills') + 1] : null;
@@ -30,7 +31,7 @@ try {
const page = await browser.newPage({ viewport: { width, height } });
await page.route('**/water-benchmark.html', route => route.fulfill({ contentType: 'text/html', body: `<canvas style="width:${width}px;height:${height}px;display:block"></canvas>` }));
await page.goto(`${serverUrl}/water-benchmark.html`);
- const results = await page.evaluate(async ({ smallPartCount, samples, wantStills, countsOnly, mirrorLevels }) => {
+ const results = await page.evaluate(async ({ smallPartCount, samples, rounds, wantStills, countsOnly, mirrorLevels }) => {
const { Renderer67 } = await import('/src/renderer.js');
const { box } = await import('/src/geometry.js');
const { createTerrain } = await import('/src/terrain.js');
@@ -117,7 +118,7 @@ try {
context.deleteQuery(query);
}
timings.sort((first, second) => first - second);
- const output = { label, medianMilliseconds: timings[Math.floor(timings.length / 2)], minimumMilliseconds: timings[0], maximumMilliseconds: timings[timings.length - 1], mirrorDraw: { ...phases.mirror }, mainDraw: { ...phases.main }, glError: context.getError() };
+ const output = { label, rawTimings: timings, medianMilliseconds: timings[Math.floor(timings.length / 2)], minimumMilliseconds: timings[0], maximumMilliseconds: timings[timings.length - 1], mirrorDraw: { ...phases.mirror }, mainDraw: { ...phases.main }, glError: context.getError() };
if (wantStills) {
renderer.render(frame);
output.image = canvas.toDataURL('image/png');
@@ -126,14 +127,28 @@ try {
return output;
}
const report = { canvas: [canvas.width, canvas.height], terrainVertices: terrain.parts.reduce((sum, part) => sum + part.geometry.positions.length / 3, 0), smallParts: smallPartCount };
- report.reflectionOff = await measure('off', false);
- report.reflectionOld = await withoutMirrorCulling(() => measure('old (no mirror culling), scale 0.75', true, { scale: 0.75 }));
- report.reflectionOn = await measure('on', true);
- report.updateEvery2 = await measure('updateEvery 2', true, { updateEvery: 2 });
- if (wantStills) report.halfScale = await measure('scale 0.5', true, { scale: 0.5 });
- report.stillCamera = await measure('still camera', true, {}, true);
+ // The variants run in rounds, in turn, and each variant pools its timings from every round, so a loaded machine drifts
+ // the same way for all of them instead of favouring whichever ran in a quiet moment.
+ const variants = {
+ reflectionOff: () => measure('off', false),
+ reflectionOld: () => withoutMirrorCulling(() => measure('old (no mirror culling), scale 0.75', true, { scale: 0.75 })),
+ reflectionOn: () => measure('on', true),
+ updateEvery2: () => measure('updateEvery 2', true, { updateEvery: 2 }),
+ ...(wantStills ? { halfScale: () => measure('scale 0.5', true, { scale: 0.5 }) } : {}),
+ stillCamera: () => measure('still camera', true, {}, true),
+ };
+ for (let round = 0; round < (countsOnly ? 1 : rounds); round++) {
+ for (const [name, run] of Object.entries(variants)) {
+ const result = await run();
+ const pooled = [...(report[name]?.rawTimings ?? []), ...result.rawTimings].sort((first, second) => first - second);
+ report[name] = { ...result, rawTimings: pooled, medianMilliseconds: pooled[Math.floor(pooled.length / 2)], minimumMilliseconds: pooled[0], maximumMilliseconds: pooled[pooled.length - 1] };
+ }
+ }
+ for (const entry of Object.values(report)) {
+ if (entry?.rawTimings) delete entry.rawTimings;
+ }
return report;
- }, { smallPartCount, samples: SAMPLES, wantStills: stillsFolder !== null, countsOnly, mirrorLevels });
+ }, { smallPartCount, samples: SAMPLES, rounds: ROUNDS, wantStills: stillsFolder !== null, countsOnly, mirrorLevels });
if (stillsFolder) {
await mkdir(stillsFolder, { recursive: true });
for (const [name, entry] of Object.entries(results)) {
diff --git a/src/water-reflection.js b/src/water-reflection.js
index d9f3644b..1473acc6 100644
--- a/src/water-reflection.js
+++ b/src/water-reflection.js
@@ -36,7 +36,7 @@ export const WATER_REFLECTION_SCALE = 0.75;
/** The mirror draw accepts this many times the level error that the lit frame accepts (`lodPixelError`). */
export const WATER_MIRROR_LOD_SCALE = 3;
/** The mirror draw skips a part whose bounding sphere covers a smaller radius than this on screen, in pixels. */
-export const WATER_MIRROR_MINIMUM_PIXEL_RADIUS = 1.5;
+export const WATER_MIRROR_MINIMUM_PIXEL_RADIUS = 5;
// How the picture is treated before it reaches the surface (see afterEmission). Fresnel starts at the reflectance of water.
const FRESNEL_BASE = '0.02';
const REFLECTION_GAIN = '1.0';
diff --git a/tests/water-reflection.test.js b/tests/water-reflection.test.js
index 250922d2..ee720004 100644
--- a/tests/water-reflection.test.js
+++ b/tests/water-reflection.test.js
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { box, sphere } from '../src/geometry.js';
-import { applyWaterReflection, attachWaterReflection, findWaterSurface, waterMirrorLevel, waterMirrorWeight, WATER_BLUR_LIMIT_ROUGHNESS, WATER_MAXIMUM_BLUR_LEVEL } from '../src/water-reflection.js';
+import { applyWaterReflection, attachWaterReflection, canReuseMirrorImage, findWaterSurface, waterMirrorLevel, waterMirrorWeight, WATER_BLUR_LIMIT_ROUGHNESS, WATER_MAXIMUM_BLUR_LEVEL, WATER_MIRROR_LOD_SCALE, WATER_MIRROR_MINIMUM_PIXEL_RADIUS } from '../src/water-reflection.js';
import { createFragmentShader } from '../src/shaders.js';
import { Renderer67 } from '../src/renderer.js';
@@ -249,6 +249,35 @@ test('the shader samples a mip level taken from roughness', () => {
assert.match(source, /textureLod\(waterReflection,/);
});
+test('canReuseMirrorImage needs a drawn picture, the same frame and parts, or an updateEvery window that is still open', () => {
+ const drawnFrame = { eye: [0, 20, 100], target: [0, 0, 0], time: 1 };
+ const base = { ready: true, drawnFrame, partsRevision: 3, drawnRevision: 3, framesSinceDraw: 0, updateEvery: 1 };
+ assert.equal(canReuseMirrorImage({ ...base, ready: false }, drawnFrame), false);
+ assert.equal(canReuseMirrorImage({ ...base, drawnFrame: null }, drawnFrame), false);
+ assert.equal(canReuseMirrorImage(base, { ...drawnFrame, eye: [0, 20, 100] }), true);
+ assert.equal(canReuseMirrorImage(base, { ...drawnFrame, time: 2 }), false);
+ assert.equal(canReuseMirrorImage({ ...base, partsRevision: 4 }, drawnFrame), false);
+ assert.equal(canReuseMirrorImage({ ...base, updateEvery: 2 }, { ...drawnFrame, time: 2 }), true);
+ assert.equal(canReuseMirrorImage({ ...base, updateEvery: 2, framesSinceDraw: 1 }, { ...drawnFrame, time: 2 }), false);
+});
+
+test('only the mirror draw carries the mirror culling: parts under the plane, coarser levels and small far parts', () => {
+ const context = new Proxy({}, { get: (_, name) => (name === 'checkFramebufferStatus' ? () => 1 : name === 'FRAMEBUFFER_COMPLETE' ? 1 : typeof name === 'string' && name === name.toUpperCase() ? 0 : () => ({})) });
+ const cullingSeen = [];
+ const renderer = { context, canvas: { width: 960, height: 540 }, hdr: false, viewProjection: new Float32Array(16), mirrorCulling: null, render: frame => cullingSeen.push({ mirror: Boolean(frame.reflectionTarget), culling: renderer.mirrorCulling }), dispose() {} };
+ const surface = findWaterSurface(lakeScene());
+ const detach = attachWaterReflection(renderer, surface);
+ renderer.render({ eye: [0, 20, 100], target: [0, 0, 0] });
+ assert.equal(cullingSeen.length, 2);
+ assert.equal(cullingSeen[0].mirror, true);
+ assert.ok(cullingSeen[0].culling.belowHeight > surface.height);
+ assert.equal(cullingSeen[0].culling.lodScale, WATER_MIRROR_LOD_SCALE);
+ assert.equal(cullingSeen[0].culling.minimumPixelRadius, WATER_MIRROR_MINIMUM_PIXEL_RADIUS);
+ assert.equal(cullingSeen[1].mirror, false);
+ assert.equal(cullingSeen[1].culling, null);
+ detach();
+});
+
test('worldBounds equals the per-axis formula it replaced, under a rotated and moved matrix', async () => {
const { worldBounds } = await import('../src/probe-trace.js');
const positions = new Float32Array(3 * 500);