Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Draw with reversed-Z float depth by default and drop the 16-bit depth buffer (#751)

Nguyen Xuan An29049981f66a
diff --git a/bench/flicker/index.html b/bench/flicker/index.html
new file mode 100644
index 00000000..ecb7e7f0
--- /dev/null
+++ b/bench/flicker/index.html
@@ -0,0 +1,49 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>67js flicker viewer</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #14161a; color: #e6e8eb; font: 13px/1.4 system-ui, sans-serif; overflow: hidden; user-select: none; }
+ canvas { position: fixed; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; }
+ .panel { position: fixed; top: 12px; left: 12px; display: grid; gap: 8px; padding: 10px; border-radius: 10px; background: rgb(20 22 26 / 0.82); backdrop-filter: blur(8px); max-width: 340px; }
+ .row { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; }
+ button { font: inherit; color: #9aa1ab; background: none; border: 0; padding: 4px 9px; border-radius: 6px; cursor: pointer; display: inline-flex; gap: 6px; align-items: center; }
+ button:hover { background: rgb(255 255 255 / 0.06); }
+ button[aria-pressed="true"] { color: #e6e8eb; background: rgb(255 255 255 / 0.12); }
+ button svg { width: 14px; height: 14px; flex: none; }
+ .readout { font: 12px/1.5 ui-monospace, Consolas, monospace; color: #b8bec7; white-space: pre; padding: 0 4px; }
+ .status { display: flex; gap: 6px; align-items: center; padding: 0 4px; min-height: 18px; }
+ .status svg { width: 14px; height: 14px; flex: none; }
+ .ok { color: #5ec27f; } .bad { color: #ff6b8b; } .wait { color: #e0b64a; }
+ label { display: flex; gap: 8px; align-items: center; padding: 0 4px; color: #9aa1ab; }
+ input[type=range] { width: 130px; }
+ #drop[hidden] { display: none; }
+ #drop { position: fixed; inset: 0; display: grid; place-items: center; color: #9aa1ab; pointer-events: none; }
+ #overlay { position: fixed; inset: 0; width: 100%; height: 100%; pointer-events: none; }
+</style>
+</head>
+<body>
+<canvas id="viewport"></canvas>
+<canvas id="overlay"></canvas>
+<div id="drop">Drop a GLB here, or open this page with ?asset=/path</div>
+<div class="panel">
+ <div class="row" id="mode">
+ <button data-mode="orbit" aria-pressed="true">Orbit</button>
+ <button data-mode="fly" aria-pressed="false">Fly</button>
+ </div>
+ <label>Speed <input id="speed" type="range" min="-2" max="3" step="0.05" value="1"><span id="speedValue"></span></label>
+ <div class="row" id="toggles">
+ <button data-toggle="reversed" aria-pressed="true">Reversed-Z</button>
+ <button data-toggle="nearFit" aria-pressed="true">Near fit</button>
+ <button data-toggle="offset" aria-pressed="false">Coplanar offset</button>
+ <button data-toggle="ids" aria-pressed="false">Part colours</button>
+ </div>
+ <div class="row"><button id="probe">Flicker probe</button><button id="clear">Clear</button></div>
+ <div class="status" id="status"></div>
+ <div class="readout" id="readout"></div>
+</div>
+<script type="module" src="./viewer.js"></script>
+</body>
+</html>
diff --git a/bench/flicker/probe.mjs b/bench/flicker/probe.mjs
new file mode 100644
index 00000000..91dbe994
--- /dev/null
+++ b/bench/flicker/probe.mjs
@@ -0,0 +1,65 @@
+// Drives the flicker viewer in headless Chrome on the GPU and prints how many pixels flicker at each camera spot.
+// node bench/flicker/probe.mjs --url http://127.0.0.1:5210 --asset /@fs/D:/path/file.glb --out artifacts/flicker \
+// --spots spots.json --configs "reversed=1,nearFit=1;reversed=0,nearFit=0"
+// spots.json: [{ "name": "roofs", "eye": [x, y, z], "target": [x, y, z] }]. Without --spots it prints the scene bounds and exits.
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { chromium } from 'playwright';
+
+function argument(name, fallback) {
+ const index = process.argv.indexOf(`--${name}`);
+ return index === -1 ? fallback : process.argv[index + 1];
+}
+
+const baseUrl = argument('url', 'http://127.0.0.1:5210');
+const asset = argument('asset');
+const outputFolder = argument('out', 'artifacts/flicker');
+const spotsFile = argument('spots');
+const [width, height] = argument('viewport', '1920x1080').split('x').map(Number);
+const configurations = argument('configs', 'reversed=1,nearFit=1').split(';').map(text => Object.fromEntries(text.split(',').map(pair => pair.split('='))));
+const prefix = argument('prefix', 'view');
+mkdirSync(outputFolder, { recursive: true });
+
+const browser = await chromium.launch({
+ channel: 'chrome', headless: true,
+ args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-webgl', '--disable-renderer-backgrounding'],
+});
+const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 1 });
+page.setDefaultTimeout(240000);
+page.on('pageerror', error => console.error('pageerror', error.message));
+page.on('console', message => { if (message.type() === 'error') console.error('console', message.text()); });
+const results = [];
+
+async function open(configuration) {
+ const query = new URLSearchParams({ asset, ...Object.fromEntries(Object.entries(configuration).map(([key, value]) => [key, value])) });
+ await page.goto(`${baseUrl}/bench/flicker/index.html?${query}`);
+ await page.evaluate(() => window.flicker.ready);
+}
+
+try {
+ if (!spotsFile) {
+ await open(configurations[0]);
+ console.log(JSON.stringify(await page.evaluate(() => window.flicker.info), null, 1));
+ } else {
+ const spots = JSON.parse(readFileSync(spotsFile, 'utf8'));
+ for (const configuration of configurations) {
+ await open(configuration);
+ await page.waitForTimeout(1500);
+ const label = Object.entries(configuration).map(([key, value]) => `${key}${value}`).join('-');
+ for (const spot of spots) {
+ const outcome = await page.evaluate(async ({ eye, target }) => {
+ window.flicker.setCamera({ eye, target });
+ window.flicker.render();
+ const probe = await window.flicker.probe();
+ return { probe, info: window.flicker.info };
+ }, spot);
+ await page.screenshot({ path: path.join(outputFolder, `${prefix}-${spot.name}-${label}.png`) });
+ results.push({ spot: spot.name, moved: outcome.probe.totalChanged, configuration: label, changed: outcome.probe.changed, fraction: outcome.probe.fraction, depth: outcome.info.depthMode, near: outcome.info.near, far: outcome.info.far });
+ console.log(JSON.stringify(results.at(-1)));
+ }
+ }
+ writeFileSync(path.join(outputFolder, `${prefix}-results.json`), JSON.stringify(results, null, 1));
+ }
+} finally {
+ await browser.close();
+}
diff --git a/bench/flicker/viewer.js b/bench/flicker/viewer.js
new file mode 100644
index 00000000..f0431421
--- /dev/null
+++ b/bench/flicker/viewer.js
@@ -0,0 +1,344 @@
+// Flicker viewer (issue #751): fly or orbit through a GLB and see which pixels still change owner between two frames that differ
+// by a sub-pixel camera jitter. Open /bench/flicker/index.html?asset=/path/to/file.glb, or drop a GLB on the page.
+import { vec3 } from 'gl-matrix';
+import { Renderer67 } from '../../src/index.js';
+import { parseGltf } from '../../src/gltf.js';
+import { resolveFlushParts } from '../../src/coplanar-overlap.js';
+
+// One flat colour per part, no textures, so a pixel's colour says which part owns it and a changed colour is a changed owner.
+function paintPartsByOwner(parts) {
+ parts.forEach((part, index) => {
+ const hue = ((index * 0.618034) % 1) * 0.72;
+ const channel = offset => 0.5 + 0.5 * Math.cos(2 * Math.PI * (hue + offset));
+ const { map, ...material } = part.material;
+ part.material = { ...material, color: [channel(0), channel(1 / 3), channel(2 / 3)], metallic: 0, roughness: 1 };
+ });
+}
+
+function measureBounds(parts) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ const point = vec3.create();
+ for (const part of parts) {
+ const positions = part.geometry.positions;
+ for (let index = 0; index < positions.length; index += 3) {
+ vec3.transformMat4(point, positions.subarray(index, index + 3), part.matrix);
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], point[axis]);
+ maximum[axis] = Math.max(maximum[axis], point[axis]);
+ }
+ }
+ }
+ return { minimum, maximum };
+}
+
+const JITTER_PIXELS = 0.125;
+const CHANGE_THRESHOLD = 24;
+const EDGE_THRESHOLD = 48;
+const FIELD_OF_VIEW = 45;
+
+const canvas = document.querySelector('#viewport');
+const overlay = document.querySelector('#overlay');
+const readout = document.querySelector('#readout');
+const status = document.querySelector('#status');
+const parameters = new URLSearchParams(location.search);
+
+const ICONS = {
+ ok: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6.5"/><path d="M5 8.3l2 2 4-4.6"/></svg>',
+ bad: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 1.8l6.5 11.7h-13z"/><path d="M8 6.5v3"/><path d="M8 11.8v.1"/></svg>',
+ wait: '<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="8" cy="8" r="6.5"/><path d="M8 4.5V8l2.5 1.5"/></svg>',
+};
+
+const options = {
+ reversed: parameters.get('reversed') !== '0',
+ nearFit: parameters.get('nearFit') !== '0',
+ offset: parameters.get('offset') === '1',
+ ids: parameters.get('ids') === '1',
+};
+const camera = { pivot: [0, 0, 0], yaw: 0.8, pitch: -0.5, distance: 10 };
+let mode = 'orbit';
+let glbBytes = null;
+let assetName = '';
+let renderer = null;
+let bounds = null;
+let extent = 1;
+let dirty = true;
+let lastProbe = null;
+const keys = new Set();
+
+function setStatus(kind, text) {
+ status.className = `status ${kind}`;
+ status.innerHTML = `${ICONS[kind]}<span></span>`;
+ status.querySelector('span').textContent = text;
+}
+
+function viewDirection() {
+ const cosPitch = Math.cos(camera.pitch);
+ return [Math.sin(camera.yaw) * cosPitch, Math.sin(camera.pitch), -Math.cos(camera.yaw) * cosPitch];
+}
+
+function eyePosition() {
+ const direction = viewDirection();
+ return camera.pivot.map((value, axis) => value - direction[axis] * camera.distance);
+}
+
+function setCamera({ eye, target }) {
+ const delta = vec3.sub(vec3.create(), target, eye);
+ camera.distance = Math.max(vec3.length(delta), 0.01);
+ vec3.normalize(delta, delta);
+ camera.pitch = Math.asin(delta[1]);
+ camera.yaw = Math.atan2(delta[0], -delta[2]);
+ camera.pivot = [...target];
+ markDirty();
+}
+
+function markDirty() {
+ dirty = true;
+ const context = overlay.getContext('2d');
+ context.clearRect(0, 0, overlay.width, overlay.height);
+}
+
+function frameFor(jitterPixels = 0) {
+ const frame = { eye: eyePosition(), target: camera.pivot, up: [0, 1, 0], fov: FIELD_OF_VIEW, far: Math.max(extent * 2.5, 100) };
+ if (!options.nearFit) frame.near = 0.1;
+ if (jitterPixels) frame.shift = [jitterPixels / canvas.width, 0];
+ return frame;
+}
+
+async function build() {
+ if (!glbBytes) return;
+ setStatus('wait', 'Building the scene');
+ renderer?.dispose();
+ renderer = null;
+ const loaded = await parseGltf(glbBytes.slice(0));
+ if (options.ids) paintPartsByOwner(loaded.parts);
+ bounds = measureBounds(loaded.parts);
+ const size = bounds.maximum.map((value, axis) => value - bounds.minimum[axis]);
+ extent = Math.max(...size);
+ renderer = new Renderer67(canvas, loaded.parts, {
+ ground: false, hdr: true, samples: 4, pixelRatio: Math.min(devicePixelRatio, 1.5), memoryBudgetMiB: 1024,
+ reversedDepth: options.reversed ? 'auto' : false,
+ resolveCoplanar: options.offset ? resolveFlushParts : false,
+ });
+ window.flickerRenderer = renderer;
+ window.flickerParts = loaded.parts;
+ document.querySelector('#drop').hidden = true;
+ setStatus('ok', `${assetName} loaded`);
+ markDirty();
+}
+
+function nearAndFar() {
+ const matrix = renderer.projection;
+ const near = matrix[14] / (matrix[10] - 1);
+ const far = matrix[14] / (matrix[10] + 1);
+ return { near, far };
+}
+
+function depthModeLabel() {
+ if (!renderer) return 'none';
+ return renderer.reversedDepth ? 'reversed-Z, 32-bit float' : '24-bit, standard';
+}
+
+function updateReadout() {
+ if (!renderer) return;
+ const { near, far } = nearAndFar();
+ const lines = [
+ `depth ${depthModeLabel()}`,
+ `near ${near.toFixed(3)} m far ${far.toFixed(0)} m`,
+ `ratio ${(far / near).toFixed(0)}:1`,
+ `speed ${speed().toFixed(1)} m/s`,
+ ];
+ if (lastProbe) lines.push(`probe ${lastProbe.changed} px flicker, ${lastProbe.totalChanged} px moved`);
+ readout.textContent = lines.join('\n');
+}
+
+function speed() {
+ return 10 ** Number(document.querySelector('#speed').value) * Math.max(extent / 200, 0.05);
+}
+
+function readFrame(context) {
+ context.drawImage(canvas, 0, 0);
+ return context.getImageData(0, 0, canvas.width, canvas.height).data;
+}
+
+// Two frames with a sub-pixel jitter, drawn with one flat colour per part. A pixel is flicker when its owner changes while the first
+// frame is the same colour on all four sides of it: a silhouette moves by the jitter at its own edge, which that test leaves out.
+// `totalChanged` counts every pixel whose owner changed, edges included.
+async function probe() {
+ if (!renderer) return null;
+ if (!options.ids) {
+ options.ids = true;
+ document.querySelector('[data-toggle="ids"]').setAttribute('aria-pressed', 'true');
+ await build();
+ }
+ const { width, height } = canvas;
+ const scratch = document.createElement('canvas');
+ scratch.width = width;
+ scratch.height = height;
+ const context = scratch.getContext('2d', { willReadFrequently: true });
+ renderer.render(frameFor(0));
+ const first = new Uint8ClampedArray(readFrame(context));
+ renderer.render(frameFor(JITTER_PIXELS));
+ const second = readFrame(context);
+ overlay.width = width;
+ overlay.height = height;
+ const paint = overlay.getContext('2d');
+ const image = paint.createImageData(width, height);
+ let changed = 0;
+ let totalChanged = 0;
+ for (let y = 1; y < height - 1; y++) {
+ for (let x = 1; x < width - 1; x++) {
+ const index = (y * width + x) * 4;
+ if (colourDistance(first, second, index) <= CHANGE_THRESHOLD) continue;
+ totalChanged++;
+ if (hasEdgeAround(first, width, index)) continue;
+ changed++;
+ image.data.set([255, 0, 255, 255], index);
+ }
+ }
+ paint.putImageData(image, 0, 0);
+ renderer.render(frameFor(0));
+ lastProbe = { changed, totalChanged, total: width * height, fraction: changed / (width * height), width, height };
+ setStatus(changed === 0 ? 'ok' : 'bad', changed === 0 ? 'No flicker in this view' : `${changed} pixels flicker`);
+ updateReadout();
+ return lastProbe;
+}
+
+function colourDistance(a, b, index, otherIndex = index) {
+ return Math.max(Math.abs(a[index] - b[otherIndex]), Math.abs(a[index + 1] - b[otherIndex + 1]), Math.abs(a[index + 2] - b[otherIndex + 2]));
+}
+
+function hasEdgeAround(data, width, index) {
+ const neighbours = [index - 4, index + 4, index - width * 4, index + width * 4];
+ return neighbours.some(neighbour => colourDistance(data, data, index, neighbour) > EDGE_THRESHOLD);
+}
+
+function tick(timestamp) {
+ requestAnimationFrame(tick);
+ const seconds = Math.min((timestamp - (tick.last ?? timestamp)) / 1000, 0.1);
+ tick.last = timestamp;
+ if (keys.size && moveWithKeys(seconds)) dirty = true;
+ if (!renderer || !dirty) return;
+ dirty = false;
+ renderer.render(frameFor(0));
+ updateReadout();
+}
+
+function moveWithKeys(seconds) {
+ const direction = viewDirection();
+ const right = vec3.normalize(vec3.create(), vec3.cross(vec3.create(), direction, [0, 1, 0]));
+ const step = speed() * seconds * (keys.has('shift') ? 4 : 1);
+ const move = [0, 0, 0];
+ const add = (vector, scale) => vec3.scaleAndAdd(move, move, vector, scale);
+ if (keys.has('w')) add(direction, 1);
+ if (keys.has('s')) add(direction, -1);
+ if (keys.has('d')) add(right, 1);
+ if (keys.has('a')) add(right, -1);
+ if (keys.has('e')) add([0, 1, 0], 1);
+ if (keys.has('q')) add([0, 1, 0], -1);
+ if (!vec3.length(move)) return false;
+ camera.pivot = camera.pivot.map((value, axis) => value + move[axis] * step);
+ markDirty();
+ return true;
+}
+
+function bindControls() {
+ let drag = null;
+ canvas.addEventListener('pointerdown', (event) => {
+ canvas.setPointerCapture(event.pointerId);
+ drag = { x: event.clientX, y: event.clientY, pan: event.button === 2 || event.shiftKey };
+ });
+ canvas.addEventListener('pointerup', () => { drag = null; });
+ canvas.addEventListener('contextmenu', event => event.preventDefault());
+ canvas.addEventListener('pointermove', (event) => {
+ if (!drag) return;
+ const dx = event.clientX - drag.x;
+ const dy = event.clientY - drag.y;
+ drag.x = event.clientX;
+ drag.y = event.clientY;
+ if (drag.pan) {
+ const direction = viewDirection();
+ const right = vec3.normalize(vec3.create(), vec3.cross(vec3.create(), direction, [0, 1, 0]));
+ const scale = camera.distance * 0.0015;
+ camera.pivot = camera.pivot.map((value, axis) => value - right[axis] * dx * scale + (axis === 1 ? dy * scale : 0));
+ } else {
+ const eye = eyePosition();
+ camera.yaw -= dx * 0.005;
+ camera.pitch = Math.max(-1.5, Math.min(1.5, camera.pitch + dy * 0.005 * (mode === 'fly' ? 1 : -1)));
+ if (mode === 'fly') {
+ const direction = viewDirection();
+ camera.pivot = eye.map((value, axis) => value + direction[axis] * camera.distance);
+ }
+ }
+ markDirty();
+ });
+ canvas.addEventListener('wheel', (event) => {
+ event.preventDefault();
+ camera.distance = Math.max(0.05, camera.distance * Math.exp(event.deltaY * 0.001));
+ markDirty();
+ }, { passive: false });
+ window.addEventListener('keydown', (event) => { keys.add(event.key.toLowerCase()); });
+ window.addEventListener('keyup', (event) => { keys.delete(event.key.toLowerCase()); });
+ window.addEventListener('blur', () => keys.clear());
+ window.addEventListener('resize', () => { renderer?.resize(); markDirty(); });
+ document.querySelector('#speed').addEventListener('input', () => { updateReadout(); });
+ for (const button of document.querySelectorAll('[data-mode]')) {
+ button.addEventListener('click', () => {
+ mode = button.dataset.mode;
+ for (const other of document.querySelectorAll('[data-mode]')) other.setAttribute('aria-pressed', String(other === button));
+ });
+ }
+ for (const button of document.querySelectorAll('[data-toggle]')) {
+ button.setAttribute('aria-pressed', String(options[button.dataset.toggle]));
+ button.addEventListener('click', async () => {
+ options[button.dataset.toggle] = !options[button.dataset.toggle];
+ button.setAttribute('aria-pressed', String(options[button.dataset.toggle]));
+ lastProbe = null;
+ if (button.dataset.toggle === 'nearFit') markDirty();
+ else await build();
+ });
+ }
+ document.querySelector('#probe').addEventListener('click', probe);
+ document.querySelector('#clear').addEventListener('click', () => { lastProbe = null; markDirty(); });
+ window.addEventListener('dragover', event => event.preventDefault());
+ window.addEventListener('drop', async (event) => {
+ event.preventDefault();
+ const file = event.dataTransfer.files[0];
+ if (!file) return;
+ glbBytes = await file.arrayBuffer();
+ assetName = file.name;
+ await build();
+ frameWholeScene();
+ });
+}
+
+function frameWholeScene() {
+ if (!bounds) return;
+ camera.pivot = bounds.minimum.map((value, axis) => (value + bounds.maximum[axis]) / 2);
+ camera.distance = extent * 0.9;
+ camera.yaw = 0.8;
+ camera.pitch = -0.55;
+ markDirty();
+}
+
+async function loadFromUrl(url) {
+ setStatus('wait', 'Downloading the asset');
+ const response = await fetch(url);
+ if (!response.ok) throw new Error(`The server answered ${response.status} for ${url}. Allow the folder with VITE_FS_ALLOW.`);
+ glbBytes = await response.arrayBuffer();
+ assetName = decodeURIComponent(url.split('/').pop());
+ await build();
+ frameWholeScene();
+}
+
+bindControls();
+requestAnimationFrame(tick);
+document.querySelector('#speedValue').textContent = '';
+window.flicker = {
+ setCamera, probe, build, options, frameWholeScene,
+ get info() { return { depthMode: depthModeLabel(), ...(renderer ? nearAndFar() : {}), extent, bounds, canvas: [canvas.width, canvas.height], memory: renderer?.memoryReport?.() }; },
+ render: () => { markDirty(); renderer?.render(frameFor(0)); },
+ ready: parameters.get('asset')
+ ? loadFromUrl(parameters.get('asset')).catch(error => setStatus('bad', error.message))
+ : Promise.resolve(),
+};
diff --git a/changes/751.md b/changes/751.md
new file mode 100644
index 00000000..2f5cb47b
--- /dev/null
+++ b/changes/751.md
@@ -0,0 +1 @@
+- Depth precision by default (#751, phase 1 of 2): the colour pass draws with reversed-Z and a 32-bit float depth buffer wherever `EXT_clip_control` exists, at any far / near ratio, from the first frame; the 16-bit depth buffer is gone; without the extension the depth buffer is 24-bit and the near plane fits the visible bounds when the camera left near unset; `reversedDepth: false` opts out; `installDepthPrecision`, `hasFarOverlap` and `requestReversedDepth` are removed (use `installCoplanarDiagnostics` for the warning); `bench/flicker/index.html` is a viewer with a flicker probe
diff --git a/changes/751.size.md b/changes/751.size.md
new file mode 100644
index 00000000..650da559
--- /dev/null
+++ b/changes/751.size.md
@@ -0,0 +1,7 @@
+- entry:core: reversed-Z moved into the core (+1859 bytes gzip, 83284 to 85143) so the first frame is already drawn with the right depth; owner accepted the cost for flicker-free rendering, optimisation later
+- scene:lit-box: same core growth (+1880 bytes gzip); owner accepted the cost for flicker-free rendering, optimisation later
+- scene:gltf-box: same core growth (+2050 bytes gzip); owner accepted the cost for flicker-free rendering, optimisation later
+- scene:agent-scene: same core growth (+2035 bytes gzip); owner accepted the cost for flicker-free rendering, optimisation later
+- goal:lit-box: the growth is the reversed-Z code and the near-plane fit; owner accepted the cost for flicker-free rendering, optimisation later
+- goal:gltf-box: the growth is the reversed-Z code and the near-plane fit; owner accepted the cost for flicker-free rendering, optimisation later
+- goal:agent-scene: the growth is the reversed-Z code and the near-plane fit; owner accepted the cost for flicker-free rendering, optimisation later
diff --git a/docs/learn/contact-detection.md b/docs/learn/contact-detection.md
index 98a7130d..21f9132a 100644
--- a/docs/learn/contact-detection.md
+++ b/docs/learn/contact-detection.md
@@ -190,7 +190,7 @@ The coplanar code is not in the core bundle. Call `installCoplanarDiagnostics(re
### Depth precision far from the camera
-Far from the camera, depth precision is the other cause. `installReversedDepth(renderer, 'auto')` from `67js/addons/reversed-depth` switches on reversed-Z with a 32-bit float depth buffer and camera-relative drawing when a frame's far / near passes 10,000, or when `installDepthPrecision` finds a flush pair more than 40 units from the eye. It still has a float32 limit, because vertex positions are float32.
+Far from the camera, depth precision is the other cause. The renderer draws every colour pass with reversed-Z, a 32-bit float depth buffer and camera-relative vertices by default wherever `EXT_clip_control` exists, at any far / near ratio; pass `reversedDepth: false` to opt out. Without the extension it uses a 24-bit buffer and moves the near plane out to the visible bounds when the camera left near unset. It still has a float32 limit, because vertex positions are float32.
On the RTX 3060 a 0.1 mm gap at 500 m still draws the far surface on 6.9% of pixels, and a 1 mm gap at 500 m on 1.4%. At 50 m both stay under 1%. Keep surfaces that must not flicker at least 1 mm apart when they sit hundreds of metres from the camera, or mark the top one `decal: true`.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index e24a4143..a3315dd9 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -7,7 +7,7 @@ import { fogSkyVisibility } from '../src/fog-sky-visibility.js';
import { installCameraEffects, effectsWithFStop } from '../src/camera-effects.js';
import { installRenderPasses } from '../src/render-passes.js';
import { installMeshBlend, normalizeBlend } from '../src/mesh-blend.js';
-import { installDepthPrecision } from '../src/reversed-depth.js';
+import { installCoplanarDiagnostics } from '../src/coplanar-overlap.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';
@@ -399,7 +399,7 @@ function cascadesFor(scene) {
function initializeRenderer(scene, { memoryBudgetMiB, backend, transparent = false }) {
probeSnippets(scene);
const placement = agentGroundPlacement(scene.parts, scene.environment);
- const renderer = installDepthPrecision(installRenderPasses(installCameraEffects(new Renderer67(canvas, scene.parts, {
+ const renderer = installCoplanarDiagnostics(installRenderPasses(installCameraEffects(new Renderer67(canvas, scene.parts, {
ground: placement ? createAgentGround(placement) : false,
hdr: true,
depth: true,
diff --git a/src/near-plane-fit.js b/src/near-plane-fit.js
new file mode 100644
index 00000000..eb7cdad9
--- /dev/null
+++ b/src/near-plane-fit.js
@@ -0,0 +1,55 @@
+// Without EXT_clip_control a 24-bit depth buffer cannot be reversed, so its precision depends on the near plane (issue #751). A
+// camera that left near at its default 0.1 while the whole scene is 30 m or more away wastes most of the buffer on empty space, so
+// the near plane moves out to just in front of the nearest point of the scene bounds. The result depends only on the eye, the view
+// direction and the bounds, so it is deterministic and costs eight dot products per frame.
+import { geometryBoundingSphere } from './render-culling.js';
+
+export const DEFAULT_NEAR = 0.1;
+// The bounds are padded by this fraction of their size so that a sway, a shadow-only part or a rounding error never reaches the plane.
+const BOUNDS_PADDING = 0.05;
+// The plane stops at this share of the nearest depth, and never passes this share of the far plane.
+const NEAREST_DEPTH_SHARE = 0.9;
+const FAR_SHARE_LIMIT = 0.01;
+
+/** World-space box around every part (and an optional extra box such as the ground), or null when a part can move out of it. */
+export function sceneBoundsOfParts(parts) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const part of parts) {
+ if (part.skin || part.morph || part.crowd || !part.matrix) return null;
+ const box = geometryBoundingSphere(part.geometry);
+ for (let corner = 0; corner < 8; corner++) {
+ const x = corner & 1 ? box.maximum[0] : box.minimum[0];
+ const y = corner & 2 ? box.maximum[1] : box.minimum[1];
+ const z = corner & 4 ? box.maximum[2] : box.minimum[2];
+ const matrix = part.matrix;
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
+ minimum[axis] = Math.min(minimum[axis], value);
+ maximum[axis] = Math.max(maximum[axis], value);
+ }
+ }
+ }
+ if (!minimum.every(Number.isFinite) || !maximum.every(Number.isFinite)) return null;
+ const padding = Math.max(...maximum.map((value, axis) => value - minimum[axis])) * BOUNDS_PADDING;
+ return { minimum: minimum.map(value => value - padding), maximum: maximum.map(value => value + padding) };
+}
+
+/** Depth in front of the eye of the nearest corner of the box, along the view direction. */
+export function nearestDepthOfBounds(bounds, view) {
+ let nearest = Infinity;
+ for (let corner = 0; corner < 8; corner++) {
+ const x = corner & 1 ? bounds.maximum[0] : bounds.minimum[0];
+ const y = corner & 2 ? bounds.maximum[1] : bounds.minimum[1];
+ const z = corner & 4 ? bounds.maximum[2] : bounds.minimum[2];
+ nearest = Math.min(nearest, -(view[2] * x + view[6] * y + view[10] * z + view[14]));
+ }
+ return nearest;
+}
+
+/** The near plane for a frame whose camera left near at its default: the default, or further out when the scene is far from the eye. */
+export function fittedNearPlane(bounds, view, far) {
+ const nearestDepth = nearestDepthOfBounds(bounds, view);
+ if (!(nearestDepth > DEFAULT_NEAR / NEAREST_DEPTH_SHARE)) return DEFAULT_NEAR;
+ return Math.min(nearestDepth * NEAREST_DEPTH_SHARE, far * FAR_SHARE_LIMIT);
+}
diff --git a/src/render-target-ledger.js b/src/render-target-ledger.js
index 060642b0..d80e875c 100644
--- a/src/render-target-ledger.js
+++ b/src/render-target-ledger.js
@@ -1,6 +1,6 @@
// Lists the GPU render targets a renderer owns, so an agent can read what each one costs.
// Sizes follow the texel format, so they are the same on every machine, whatever padding a driver adds.
-const BYTES_PER_PIXEL = { R8: 1, RGBA8: 4, RGBA16F: 8, R11F_G11F_B10F: 4, R11F_G11F_B10F: 4, DEPTH_COMPONENT16: 2, DEPTH_COMPONENT24: 4 };
+const BYTES_PER_PIXEL = { R8: 1, RGBA8: 4, RGBA16F: 8, R11F_G11F_B10F: 4, R11F_G11F_B10F: 4, DEPTH_COMPONENT16: 2, DEPTH_COMPONENT24: 4, DEPTH_COMPONENT32F: 4 };
const BYTES_PER_MEGABYTE = 1048576;
export class RenderTargetLedger {
diff --git a/src/renderer.js b/src/renderer.js
index 2e0fb5e7..c14bd0ed 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -6,6 +6,8 @@ import { fullscreenVertex, startProgram, finishProgram, compileProgram } from '.
import { ambientOcclusionFragment } from './ambient-occlusion.js';
import { planRenderSize, estimateTextureBytes, estimateFrameBytes, memoryBudgetError } from './budget.js';
import { applyProjection } from './camera.js';
+import { fittedNearPlane, sceneBoundsOfParts } from './near-plane-fit.js';
+import { installReversedDepth, prepareCameraRelativeProgram } from './reversed-depth.js';
import { resolveEffects } from './effects.js';
import { frameDiagnostics } from './frame-diagnostics.js';
import { depthLayerOf } from './depth-layer.js';
@@ -566,10 +568,9 @@ export class Renderer67 {
this.shadowBounds = shadowBounds;
/** Set by installCoplanarDiagnostics (coplanar-overlap.js): called with the batches, returns coplanar-overlap warnings. */
this.coplanarDiagnostics = null;
- /** `false` keeps the standard depth buffer; `'auto'` (default) loads reversed-Z once a frame's far / near passes 10,000. */
+ /** `false` keeps the standard depth buffer; the default draws every colour pass with reversed-Z and a 32-bit float depth buffer where EXT_clip_control exists. */
this.reversedDepthMode = reversedDepth;
- /** Resolves once reversed depth is installed (set by the first frame with a stretched lens); `await` it to render with it from the start. */
- this.reversedDepthReady = null;
+ const reversedDepthWanted = reversedDepth !== false && !benchmark && Boolean(this.context.getExtension?.('EXT_clip_control'));
/** Warnings about the last frame drawn, in the shape of `agent-diagnostics.js`; see `frame-diagnostics.js`. */
this.diagnostics = [];
this.activeLightDirection = environment.lightDirection ?? [-3, 6, 4];
@@ -614,7 +615,8 @@ export class Renderer67 {
if (resolveCoplanar && typeof resolveCoplanar !== 'function') throw new TypeError('resolveCoplanar is resolveFlushParts from 67js/addons/coplanar-overlap.');
// Exact-flush pairs are left to a float depth buffer, so they are layered only when reversed depth is switched off.
if (resolveCoplanar && !benchmark) resolveCoplanar(parts, reversedDepth === false && { minimumGap: 0 });
- const groups = groupParts(this.groundPart ? [...parts, this.groundPart] : parts, batching);
+ this.fitParts = this.groundPart ? [...parts, this.groundPart] : parts;
+ const groups = groupParts(this.fitParts, batching);
const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);
this.hasSkins = groups.some(group => group[0].skin || group[0].crowd);
this.hasMorphs = groups.some(group => group[0].morph);
@@ -691,6 +693,8 @@ export class Renderer67 {
shaderFeaturesOfLighting(this.lighting).forEach(feature => this.shaderFeatures.add(feature));
if (shading === 'light') this.shaderFeatures.add(LIGHT_SHADING_FEATURE);
if (shadowCascades) this.shaderFeatures.add(shadowCascades.shaderFeature);
+ // The camera-relative vertex line is part of the first compile, so reversed depth does not compile the main program twice.
+ if (reversedDepthWanted) prepareCameraRelativeProgram(this);
const pending = {
main: this.startMainProgram(),
depth: startProgram(this.context, createDepthVertexShader(this.shaderFeatures), withDepthCode(depthFragmentShader, this.shaderFeatures)),
@@ -740,6 +744,7 @@ export class Renderer67 {
if (this.shaderFeatures.has('splat')) requireSplatSupport().initializePlaceholders(this);
this.initializeEnvironment(environment.map);
this.createShadowMap();
+ if (reversedDepth !== false && !benchmark) installReversedDepth(this, reversedDepth);
this.resize();
if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);
}
@@ -1110,6 +1115,8 @@ export class Renderer67 {
throw new TypeError('Scene parts must be an array with distinct object identities.');
}
const renderParts = this.groundPart ? [...parts, this.groundPart] : parts;
+ this.fitParts = renderParts;
+ this.fitBounds = undefined;
const groups = groupParts(renderParts, this.batching);
const geometries = new Set(renderParts.flatMap(partGeometries));
// Uploaded geometry was validated when it arrived; rechecking a large static scene every frame dominated streamed playback.
@@ -1546,6 +1553,20 @@ export class Renderer67 {
mat4.perspective(this.projection, this.world ? Math.PI / 4 : Math.PI / 5.5, width / height, 0.1, this.world ? 600 : 100);
}
+ /**
+ * Without reversed depth the 24-bit buffer needs a tight near plane: a camera that left near unset gets one just in front of the
+ * nearest scene bounds (near-plane-fit.js). A frame with its own near, an orthographic lens or a scene that can move out of its
+ * bounds keeps the frame as it is.
+ */
+ withFittedNear(frame) {
+ if (this.reversedDepth || frame.near !== undefined || frame.projection === 'orthographic') return frame;
+ if (this.fitBounds === undefined) this.fitBounds = sceneBoundsOfParts(this.fitParts);
+ if (!this.fitBounds) return frame;
+ const far = frame.far ?? (this.world ? 600 : 100);
+ const near = fittedNearPlane(this.fitBounds, this.view, far);
+ return near === 0.1 ? frame : { ...frame, near };
+ }
+
/** Every GPU render target this renderer holds: name, size, format, samples and bytes, largest first, with the total. */
memoryReport() {
return this.renderTargets.report();
@@ -1646,8 +1667,8 @@ export class Renderer67 {
context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.RENDERBUFFER, this.multisampleColor);
this.multisampleDepth = context.createRenderbuffer();
context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleDepth);
- // Without a depth texture nothing reads or resolves the depth, so the visibility test can use 16 bits; a depth texture needs the same format.
- const depthFormat = this.depth ? 'DEPTH_COMPONENT24' : 'DEPTH_COMPONENT16';
+ // 24 bits at least (issue #751): 16 bits is one step per 1.5 cm at 10 m. Reversed depth respecifies this store as 32-bit float.
+ const depthFormat = 'DEPTH_COMPONENT24';
context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, context[depthFormat], width, height);
context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, this.multisampleDepth);
if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Multisample framebuffer allocation failed. Choose a lower quality preset.');
@@ -2193,16 +2214,7 @@ export class Renderer67 {
this.fogFieldOverride = field === null ? null : validateFogField(field);
}
- // A 24-bit depth buffer cannot tell surfaces 2 micrometres apart at 2.6 m when far / near is this large (issue #593), so the
- // first such frame loads reversed-Z (reversed-depth.js, a separate chunk) and the frames after it use a float depth buffer.
- loadReversedDepthFor(frame) {
- if (this.reversedDepthMode === false || this.reversedDepth !== undefined || this.reversedDepthReady) return;
- if (!(frame.far / (frame.near ?? 0.1) > 1e4)) return;
- this.reversedDepthReady = import('./reversed-depth.js').then(({ installReversedDepth }) => installReversedDepth(this, this.reversedDepthMode));
- }
-
render(frame) {
- this.loadReversedDepthFor?.(frame);
const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;
const effects = resolveEffects(frame.effects);
const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };
@@ -2241,8 +2253,8 @@ export class Renderer67 {
this.updateLocalShadows(casterChanged);
const environmentMap = this.activateEnvironment(environment.map);
this.requireFeatureNames([environmentMap ? 'environmentMap' : 'studioLighting']);
- applyProjection(this.projection, frame, this.canvas.width / this.canvas.height, { world: this.world });
mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);
+ applyProjection(this.projection, this.withFittedNear(frame), this.canvas.width / this.canvas.height, { world: this.world });
mat4.multiply(this.viewProjection, this.projection, this.view);
mat4.invert(this.inverseViewProjection, this.viewProjection);
extractFrustumPlanes(this.viewProjection, this.frustumPlanes);
diff --git a/src/reversed-depth.js b/src/reversed-depth.js
index 17b89b2e..d9090ba1 100644
--- a/src/reversed-depth.js
+++ b/src/reversed-depth.js
@@ -2,22 +2,18 @@
// the far plane to 0, and the buffer is cleared to 0 and tested with GREATER. Floating point numbers are densest near 0, which is
// where the far surfaces land, so a 32-bit float buffer keeps its precision at distance instead of losing it as 1 / z does.
//
-// This is an addon: the renderer core carries none of it. `installReversedDepth(renderer)` wraps a few renderer steps, and the
-// mode decides when it switches on: `true` at once, `false` never, `'auto'` (the default) when a frame's far / near ratio passes
-// FAR_TO_NEAR_LIMIT or `renderer.requestReversedDepth()` is called (the coplanar check does, for a flush pair far from the eye).
-// Switching on reallocates the frame targets once, at the start of a frame.
+// The renderer constructor installs it (issue #751): `installReversedDepth(renderer)` wraps a few renderer steps and switches on at
+// once wherever EXT_clip_control exists, at any far / near ratio. `false` opts out, and a browser without the extension keeps the
+// standard path with a 24-bit buffer and a fitted near plane (near-plane-fit.js).
import { mat4 } from 'gl-matrix';
-import { installCoplanarDiagnostics } from './coplanar-overlap.js';
import { compileProgram, fullscreenVertex } from './gl-program.js';
import { shaderTransforms } from './shader-registry.js';
-export const FAR_TO_NEAR_LIMIT = 1e4;
// A float depth buffer resolves about 2^-23 of the value, so the constant part of a depth-layer offset moves a surface by well
// under a micrometre, less than the rounding of a part's own matrix (issue #593: 2 um flush pairs kept flickering). The slope
// part scales with the surface's own depth gradient, so it is the term that separates two flush faces; 16 cleared the metro film.
const REVERSED_LAYER_SLOPE_SCALE = 16;
const ZERO_VECTOR = new Float32Array(4);
-const DEFAULT_NEAR = 0.1;
/**
* Turns a projection that maps depth to -1..1 into one that maps it to 1..0 (the clip control range is 0..1).
@@ -51,11 +47,6 @@ function makeVertexCameraRelative(source) {
return source.replace('uniform mat4 lightProjection;', CAMERA_UNIFORMS).replace(WORLD_CLIP_LINE, CAMERA_RELATIVE_LINE);
}
-/** Whether a frame's lens is stretched enough that a 24-bit depth buffer cannot tell close surfaces apart far away. */
-export function exceedsFarToNearLimit(frame) {
- return frame.far / (frame.near ?? DEFAULT_NEAR) > FAR_TO_NEAR_LIMIT;
-}
-
// The depth texture the other passes read holds standard depth (1 at the far plane), so a stage right after the resolve turns the
// reversed depth back, through a copy, with gl_FragDepth. Ambient occlusion, depth of field, fog and line art then need no change.
const STANDARD_DEPTH_FRAGMENT = `#version 300 es
@@ -136,9 +127,11 @@ function useFloatDepthTargets(renderer) {
const { width, height } = renderer.canvas;
context.bindRenderbuffer(context.RENDERBUFFER, renderer.multisampleDepth);
context.renderbufferStorageMultisample(context.RENDERBUFFER, renderer.multisampleSamples, context.DEPTH_COMPONENT32F, width, height);
+ renderer.renderTargets?.record('multisampleDepth', { width, height, format: 'DEPTH_COMPONENT32F', samples: renderer.multisampleSamples });
if (renderer.depthTexture) {
context.bindTexture(context.TEXTURE_2D, renderer.depthTexture);
context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT32F, width, height, 0, context.DEPTH_COMPONENT, context.FLOAT, null);
+ renderer.renderTargets?.record('sceneDepth', { width, height, format: 'DEPTH_COMPONENT32F' });
}
for (const framebuffer of [renderer.multisampleFramebuffer, renderer.resolveFramebuffer]) {
context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);
@@ -148,8 +141,31 @@ function useFloatDepthTargets(renderer) {
}
/**
- * Wraps the renderer so its colour pass draws with reversed-Z once the mode asks for it. Returns the renderer.
- * `renderer.reversedDepth` is true once it is on. A browser without EXT_clip_control, or a benchmark renderer, stays standard.
+ * Makes the renderer's main vertex shader camera-relative from its first compile. The constructor calls this before it compiles, so
+ * switching reversed depth on does not compile the main program a second time.
+ */
+export function prepareCameraRelativeProgram(renderer) {
+ if (renderer.cameraRelativeMainProgram) return;
+ if (!transformInstalled) {
+ shaderTransforms.push(makeVertexCameraRelative);
+ transformInstalled = true;
+ }
+ const startMainProgram = renderer.startMainProgram;
+ renderer.startMainProgram = function startCameraRelativeMainProgram() {
+ patchingMainProgram = true;
+ try {
+ return startMainProgram.call(this);
+ } finally {
+ patchingMainProgram = false;
+ }
+ };
+ renderer.cameraRelativeMainProgram = true;
+}
+
+/**
+ * Wraps the renderer so its colour pass draws with reversed-Z and a float depth buffer. Returns the renderer.
+ * `mode` is `false` to opt out; anything else switches it on. `renderer.reversedDepth` is true once it is on. A browser without
+ * EXT_clip_control, or a benchmark renderer, stays standard.
*/
export function installReversedDepth(renderer, mode = 'auto') {
if (mode === false) renderer.reversedDepth ??= false;
@@ -167,7 +183,6 @@ export function installReversedDepth(renderer, mode = 'auto') {
const cameraOffset = new Float32Array([0, 0, 0, 1]);
const cameraShift = new Float32Array(4);
let clipControl = null;
- let requested = mode === true;
let inFrame = false;
let reversed = false;
let frameEye = null;
@@ -212,28 +227,17 @@ export function installReversedDepth(renderer, mode = 'auto') {
clipControl.active = true;
}
- // Compiles the main program again with the patched line, now and whenever a new shader feature rebuilds it.
+ // The program was compiled with the patched line (prepareCameraRelativeProgram) or is compiled again now, and again whenever a
+ // new shader feature rebuilds it.
function useCameraRelativeProgram() {
if (!renderer.shaderFeatures) return;
- if (!transformInstalled) {
- shaderTransforms.push(makeVertexCameraRelative);
- transformInstalled = true;
- }
- const startMainProgram = renderer.startMainProgram;
- renderer.startMainProgram = function startCameraRelativeMainProgram() {
- patchingMainProgram = true;
- try {
- return startMainProgram.call(this);
- } finally {
- patchingMainProgram = false;
- }
- };
+ if (renderer.cameraRelativeMainProgram) return;
+ prepareCameraRelativeProgram(renderer);
renderer.rebuildMainProgram();
}
function enable() {
const extension = renderer.benchmark ? null : context.getExtension?.('EXT_clip_control');
- requested = false;
if (!extension) {
renderer.reversedDepth = false;
return false;
@@ -267,12 +271,7 @@ export function installReversedDepth(renderer, mode = 'auto') {
return true;
}
- renderer.requestReversedDepth = () => {
- requested = true;
- };
renderer.render = function renderReversed(frame) {
- if (!reversed && renderer.reversedDepth === undefined && (requested || exceedsFarToNearLimit(frame))) enable();
- if (!reversed) return original.render.call(this, frame);
const outerEye = frameEye;
frameEye = frame.eye;
inFrame = true;
@@ -285,32 +284,6 @@ export function installReversedDepth(renderer, mode = 'auto') {
clearCameraRelative();
}
};
- if (requested) enable();
+ enable();
return renderer;
}
-
-// A 24-bit depth buffer with a 0.1 near plane cannot tell a 1 mm gap apart much beyond this many units from the eye.
-export const REVERSED_DEPTH_PAIR_DISTANCE = 40;
-
-/** Whether the smaller part of any coplanar pair is farther from the eye (the view matrix) than the distance limit. */
-export function hasFarOverlap(overlaps, view, distanceLimit = REVERSED_DEPTH_PAIR_DISTANCE) {
- if (!view) return false;
- return overlaps.some(({ smaller }) => {
- const [x, y, z] = smaller.matrix.slice(12, 15);
- const viewX = view[0] * x + view[4] * y + view[8] * z + view[12];
- const viewY = view[1] * x + view[5] * y + view[9] * z + view[13];
- const viewZ = view[2] * x + view[6] * y + view[10] * z + view[14];
- return Math.hypot(viewX, viewY, viewZ) > distanceLimit;
- });
-}
-
-/**
- * The coplanar-overlap warning (coplanar-overlap.js) together with reversed-Z: `reversedDepth` is `true`, `false` or `'auto'`, which
- * also switches it on when the coplanar check finds a flush pair far from the eye, besides the far / near rule.
- */
-export function installDepthPrecision(renderer, { reversedDepth = 'auto' } = {}) {
- installReversedDepth(renderer, reversedDepth);
- return installCoplanarDiagnostics(renderer, overlaps => {
- if (hasFarOverlap(overlaps, renderer.view)) renderer.requestReversedDepth?.();
- });
-}
diff --git a/tests/near-plane-fit.test.js b/tests/near-plane-fit.test.js
new file mode 100644
index 00000000..f35dc315
--- /dev/null
+++ b/tests/near-plane-fit.test.js
@@ -0,0 +1,39 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { fittedNearPlane, nearestDepthOfBounds, sceneBoundsOfParts } from '../src/near-plane-fit.js';
+
+function boxPart(translation, size = 2) {
+ const half = size / 2;
+ const positions = new Float32Array([-half, -half, -half, half, half, half]);
+ return { geometry: { positions }, matrix: mat4.fromTranslation(mat4.create(), translation) };
+}
+
+function lookingDownNegativeZ() {
+ return mat4.lookAt(mat4.create(), [0, 0, 0], [0, 0, -1], [0, 1, 0]);
+}
+
+test('scene bounds cover every part with a small padding', () => {
+ const bounds = sceneBoundsOfParts([boxPart([0, 0, -50]), boxPart([10, 0, -60])]);
+ assert.ok(bounds.minimum[2] < -61);
+ assert.ok(bounds.maximum[2] > -49);
+});
+
+test('a part that can leave its bounds disables the fit', () => {
+ assert.equal(sceneBoundsOfParts([{ ...boxPart([0, 0, -50]), skin: {} }]), null);
+ assert.equal(sceneBoundsOfParts([{ ...boxPart([0, 0, -50]), crowd: {} }]), null);
+});
+
+test('the near plane stays at the default when the eye is inside the scene and moves out when it is far', () => {
+ const view = lookingDownNegativeZ();
+ const close = sceneBoundsOfParts([boxPart([0, 0, 0])]);
+ assert.equal(fittedNearPlane(close, view, 100), 0.1);
+ const far = sceneBoundsOfParts([boxPart([0, 0, -80])]);
+ const near = fittedNearPlane(far, view, 10000);
+ assert.ok(near > 50 && near < nearestDepthOfBounds(far, view));
+});
+
+test('the near plane never passes one percent of the far plane', () => {
+ const bounds = sceneBoundsOfParts([boxPart([0, 0, -500])]);
+ assert.equal(fittedNearPlane(bounds, lookingDownNegativeZ(), 100), 1);
+});
diff --git a/tests/render-target-memory.test.js b/tests/render-target-memory.test.js
index 4111fdc6..0bef5882 100644
--- a/tests/render-target-memory.test.js
+++ b/tests/render-target-memory.test.js
@@ -80,12 +80,12 @@ function frameTargetRenderer(depth) {
return renderer;
}
-test('the multisampled depth uses 16 bits unless a depth texture needs the same format as its resolve', () => {
+test('the multisampled depth is never 16 bits, with or without a depth texture', () => {
const plain = frameTargetRenderer(false);
plain.allocateFrameTargets(960, 540);
const plainDepth = plain.memoryReport().targets.find(target => target.name === 'multisampleDepth');
- assert.equal(plainDepth.format, 'DEPTH_COMPONENT16');
- assert.equal(plainDepth.bytes, 960 * 540 * 4 * 2);
+ assert.equal(plainDepth.format, 'DEPTH_COMPONENT24');
+ assert.equal(plainDepth.bytes, 960 * 540 * 4 * 4);
const withTexture = frameTargetRenderer(true);
withTexture.allocateFrameTargets(960, 540);
const textureDepth = withTexture.memoryReport().targets.find(target => target.name === 'multisampleDepth');
diff --git a/tests/reversed-depth.test.js b/tests/reversed-depth.test.js
index 1e063d8b..cb271b89 100644
--- a/tests/reversed-depth.test.js
+++ b/tests/reversed-depth.test.js
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mat4, vec4 } from 'gl-matrix';
-import { exceedsFarToNearLimit, hasFarOverlap, installReversedDepth, reverseProjectionDepth } from '../src/reversed-depth.js';
+import { installReversedDepth, reverseProjectionDepth } from '../src/reversed-depth.js';
function depthAt(projection, eyeDistance) {
@@ -50,28 +50,13 @@ function fakeRenderer({ extension = {}, benchmark = false } = {}) {
return { renderer, drawn };
}
-test('the far to near rule: a lens over 10,000 to 1 asks for reversed depth, the default lens does not', () => {
- assert.equal(exceedsFarToNearLimit({ far: 600 }), false);
- assert.equal(exceedsFarToNearLimit({ far: 1000, near: 0.1 }), false);
- assert.equal(exceedsFarToNearLimit({ far: 2000, near: 0.1 }), true);
- assert.equal(exceedsFarToNearLimit({ far: 100, near: 0.001 }), true);
-});
-
-test('auto mode stays off until a frame or a request asks, true forces it and false never switches it on', () => {
+test('the default and true switch reversed depth on at once at any lens, and false never does', () => {
const automatic = fakeRenderer();
installReversedDepth(automatic.renderer);
- automatic.renderer.render({ far: 600 });
- assert.equal(automatic.renderer.reversedDepth, undefined);
- automatic.renderer.render({ far: 5000, near: 0.1 });
assert.equal(automatic.renderer.reversedDepth, true);
assert.equal(automatic.renderer.postStages.length, 1);
- assert.equal(automatic.drawn.length, 2);
-
- const requested = fakeRenderer();
- installReversedDepth(requested.renderer, 'auto');
- requested.renderer.requestReversedDepth();
- requested.renderer.render({ far: 600 });
- assert.equal(requested.renderer.reversedDepth, true);
+ automatic.renderer.render({ far: 600 });
+ assert.equal(automatic.drawn.length, 1);
const forced = fakeRenderer();
installReversedDepth(forced.renderer, true);
@@ -81,7 +66,7 @@ test('auto mode stays off until a frame or a request asks, true forces it and fa
installReversedDepth(off.renderer, false);
off.renderer.render({ far: 1e6, near: 0.1 });
assert.equal(off.renderer.reversedDepth, false);
- assert.equal(off.renderer.requestReversedDepth, undefined);
+ assert.equal(off.renderer.postStages.length, 0);
});
test('without the extension, or in benchmark mode, the standard path stays', () => {
@@ -90,19 +75,10 @@ test('without the extension, or in benchmark mode, the standard path stays', ()
assert.equal(missing.renderer.reversedDepth, false);
const benchmark = fakeRenderer({ benchmark: true });
installReversedDepth(benchmark.renderer, 'auto');
- benchmark.renderer.render({ far: 1e6, near: 0.1 });
assert.equal(benchmark.renderer.reversedDepth, false);
assert.equal(benchmark.renderer.postStages.length, 0);
});
-test('a flush pair far from the eye asks for reversed depth, a near one does not', () => {
- const view = mat4.create();
- const pairAt = z => [{ smaller: { matrix: new Float32Array(mat4.fromTranslation(mat4.create(), [0, 0, z])) } }];
- assert.equal(hasFarOverlap(pairAt(-5), view), false);
- assert.equal(hasFarOverlap(pairAt(-100), view), true);
- assert.equal(hasFarOverlap([], view), false);
-});
-
test('the main vertex shader is compiled camera-relative only through the addon, and only that program', async () => {
const { createVertexShader, SHADER_FEATURES } = await import('../src/shaders.js');
const { shaderTransforms } = await import('../src/shader-registry.js');
@@ -124,23 +100,3 @@ test('the main vertex shader is compiled camera-relative only through the addon,
assert.doesNotMatch(cameraRelative, /gl_Position = viewProjection \* world;/);
assert.equal(compile(mainSource), mainSource);
});
-
-test('the renderer loads reversed depth itself for a stretched lens, once, and not when the mode is false', async () => {
- const { Renderer67 } = await import('../src/renderer.js');
- const stretched = { far: 9000, near: 0.08 };
- const automatic = Object.create(Renderer67.prototype);
- automatic.reversedDepthMode = 'auto';
- automatic.loadReversedDepthFor({ far: 100, near: 0.1 });
- assert.equal(automatic.reversedDepthReady ?? null, null);
- automatic.loadReversedDepthFor(stretched);
- assert.ok(automatic.reversedDepthReady instanceof Promise);
- const first = automatic.reversedDepthReady;
- automatic.loadReversedDepthFor(stretched);
- assert.equal(automatic.reversedDepthReady, first);
- await first.catch(() => {});
-
- const disabled = Object.create(Renderer67.prototype);
- disabled.reversedDepthMode = false;
- disabled.loadReversedDepthFor(stretched);
- assert.equal(disabled.reversedDepthReady ?? null, null);
-});
diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjs
index feb1b93f..41044a8f 100644
--- a/tests/support/preview-harness.mjs
+++ b/tests/support/preview-harness.mjs
@@ -90,7 +90,7 @@ export function previewHarness() {
// The fault-injected renderer has no floor part; the automatic floor is covered by agent-ground.test.js and the live smokes.
agentGroundPlacement: () => null, createAgentGround: () => null, placeAgentGround: () => {}, FLOOR_COLOR: [0.22, 0.22, 0.21], groundBounceEnvironment: (parts, environment) => environment,
// The optional addons only plug stages into a real renderer; the fault-injected one needs none.
- installCameraEffects: renderer => renderer, effectsWithFStop, installRenderPasses: renderer => renderer, installDepthPrecision: renderer => renderer,
+ installCameraEffects: renderer => renderer, effectsWithFStop, installRenderPasses: renderer => renderer, installCoplanarDiagnostics: renderer => renderer,
installMeshBlend: renderer => Object.assign(renderer, { meshBlend: { radii: new Map() } }), normalizeBlend,
});
// Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.
diff --git a/vite.config.js b/vite.config.js
index 5114f715..06e7619c 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1,11 +1,36 @@
import { defineConfig } from 'vite';
+import fs from 'node:fs';
+import path from 'node:path';
const headers = {
'Cross-Origin-Opener-Policy': 'same-origin',
'Cross-Origin-Embedder-Policy': 'require-corp',
};
+// VITE_LOCAL_FOLDERS lists folders (separated by the platform path delimiter) that the dev server also serves, read only, under
+// /@local/<folder name>/..., for example the folder of a GLB opened in bench/flicker/index.html. Unset, nothing outside the project
+// is served. Vite's own /@fs/ route cannot reach another drive on Windows.
+function serveLocalFolders() {
+ const folders = (process.env.VITE_LOCAL_FOLDERS ?? '').split(path.delimiter).filter(Boolean).map(folder => path.resolve(folder));
+ return {
+ name: 'serve-local-folders',
+ configureServer(server) {
+ server.middlewares.use('/@local', (request, response, next) => {
+ const relative = decodeURIComponent(new URL(request.url, 'http://localhost').pathname).replace(/^\//, '');
+ const [folderName, ...rest] = relative.split('/');
+ const root = folders.find(folder => path.basename(folder) === folderName);
+ const file = root && path.resolve(root, ...rest);
+ if (!file || !file.startsWith(root + path.sep) || !fs.existsSync(file) || !fs.statSync(file).isFile()) return next();
+ response.setHeader('Content-Type', 'application/octet-stream');
+ response.setHeader('Content-Length', fs.statSync(file).size);
+ fs.createReadStream(file).pipe(response);
+ });
+ },
+ };
+}
+
export default defineConfig({
+ plugins: [serveLocalFolders()],
server: { headers, watch: { ignored: ['**/.claude/**'] } },
// Scan only the project's own pages. Agent worktrees under .claude hold hundreds of copies of them and made the first page load take 13 s.
// The browser denoiser page imports `denoiser`, which is installed by hand (bench/reference/denoise-browser.mjs). Scanning it