3D engine that AI agents drive
Make reversed-Z an addon that switches on when a scene needs it (part of #310)
Nguyen Xuan An46a0691c0f09
diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 646b9b47..a3308d1c 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -1537,9 +1537,9 @@ Fix: `harness.js` renders the reference frame with `wind: 0`. Re-run with 67js o## Reversed-Z depth (2026-11-03, issue #310)-Where `EXT_clip_control` exists, the colour pass of the renderer now draws with reversed-Z: clip depth 0 to 1 with the near plane at 1, depth cleared to 0, `GREATER`, and a `DEPTH_COMPONENT32F` multisample buffer and scene depth texture. Everything else keeps the standard path: shadow maps (the sun, cascades and the local atlas), the sky and environment backgrounds and the post passes switch clip control back before they draw, so their projections do not change. The reversed projection is the standard one with its third row replaced by `(w - z) / 2` (`src/reversed-depth.js`), used only by the draw (`renderer.rasterProjection`, `rasterViewProjection`); culling, fog, inverse matrices and the CPU rasterizer keep the standard matrices. Shaders that read the depth texture (ambient occlusion, depth of field and the other camera effects, volume fog, line art outlines and lines) turn a sample back into the standard 0 to 1 value with `standardDepth`, which is `1 - depth` exactly when reversed, so their decoding is unchanged. The water mirror, render passes (their depth pass is eye distance, not buffer depth), liquid and foam, blended parts and Gaussian splats run inside the reversed window. A decal's polygon offset flips sign with it. `new Renderer67(canvas, parts, { reversedDepth: false })` keeps the old path, as does benchmark mode and a browser without the extension (`renderer.capabilities.reversedDepth` says which one is in use).+`installReversedDepth(renderer, mode)` (`src/reversed-depth.js`, an addon: the renderer core carries none of it, so a scene that does not install it pays nothing in size) makes the colour pass draw with reversed-Z where `EXT_clip_control` exists. `mode` is `true` (on at once), `false` (off) or `'auto'`, which switches it on, once, at the start of a frame, when that frame's far / near passes 10,000, or when `renderer.requestReversedDepth()` is called; `installCoplanarDiagnostics(renderer, { reversedDepth })` installs it and calls that request when the coplanar check finds a flush pair more than 40 units from the eye (a 24-bit buffer with a 0.1 near plane cannot separate a 1 mm gap much beyond that). Switching on respecifies the two depth stores as float and adds one stage that turns the resolved depth back to standard depth for the passes that read it. What it does: clip depth 0 to 1 with the near plane at 1, depth cleared to 0, `GREATER`, and a `DEPTH_COMPONENT32F` multisample buffer and scene depth texture. Everything else keeps the standard path: shadow maps (the sun, cascades and the local atlas), the sky and environment backgrounds and the post passes switch clip control back before they draw, so their projections do not change. The reversed projection is the standard one with its third row replaced by `(w - z) / 2` (`src/reversed-depth.js`), used only by the draw (`renderer.rasterProjection`, `rasterViewProjection`); culling, fog, inverse matrices and the CPU rasterizer keep the standard matrices. The passes that read the depth texture (ambient occlusion, depth of field and the other camera effects, volume fog, line art outlines and lines) are unchanged: a stage right after the resolve copies the depth and writes `1 - depth` back with `gl_FragDepth`, which is exactly the standard 0 to 1 value. The water mirror, render passes (their depth pass is eye distance, not buffer depth), liquid and foam, blended parts and Gaussian splats run inside the reversed window. A decal's polygon offset flips sign with it. `installReversedDepth(renderer, false)`, benchmark mode and a browser without the extension keep the old path (`renderer.reversedDepth` and `renderer.capabilities.reversedDepth` say which one is in use).-Measured by `node bench/reference/depth-precision.mjs [gpu|cpu]` (scene in `depth-precision.js`): two 2.2-times-distance-wide planes at 1, 50 and 500 m, the near one `gap` closer (0, 0.1 and 1 mm), seen at about 30 degrees from their normal with the default near 0.1 and far 600, 8 camera positions about 1 to 10 cm apart per case. The number is the share of the red or blue pixels where the far (blue) plane wins, mean of the 8; 0 is right. Before is `reversedDepth: false`, after is on, same build. GPU is the RTX 3060 through Chrome (ANGLE), where the extension is present; the run was made without the GPU queue lock because it was busy and takes seconds, and is to be repeated through `gpu-lock.sh`.+Measured by `node bench/reference/depth-precision.mjs [gpu|cpu]` (scene in `depth-precision.js`): two 2.2-times-distance-wide planes at 1, 50 and 500 m, the near one `gap` closer (0, 0.1 and 1 mm), seen at about 30 degrees from their normal with the default near 0.1 and far 600, 8 camera positions about 1 to 10 cm apart per case. The number is the share of the red or blue pixels where the far (blue) plane wins, mean of the 8; 0 is right. Before is the renderer as it is, after is `installReversedDepth(renderer, true)`, same build. GPU is the RTX 3060 through Chrome (ANGLE), where the extension is present; the run was made without the GPU queue lock because it was busy and takes seconds, and is to be repeated through `gpu-lock.sh`.| Distance | Gap | Before (24-bit) | After (reversed, float) || --- | --- | --- | --- |@@ -1551,6 +1551,6 @@ Measured by `node bench/reference/depth-precision.mjs [gpu|cpu]` (scene in `dept| 500 m | 0.1 mm | 0.190 | 0.134 || 500 m | 1 mm | 0.188 | 0.015 |-The gap-0 pair is two identical boxes, so every pixel ties and the first one drawn keeps it; it never flickers, and a coplanar pair of different size is what `decal` and `resolveCoplanar` are for. The wrong share falls to 1 percent or less at 50 m (0.1 and 1 mm) and at 500 m with a 1 mm gap, but not to zero: at 500 m the 0.1 mm case is still wrong on 13 percent of pixels, because a Float32 world position has a step of 0.03 mm there and the vertex transform adds more, which no depth buffer format removes (camera-relative vertex transform in the shader would). SwiftShader also has the extension (the same page ran there). Its numbers are noisier and are not a precision measure: before 0.20 and 0.10 (50 m, 0.1 and 1 mm), 0.10 and 0.41 (500 m); after 0, 0.16, 0 and 0, with whole frames wrong in some jitters at 50 m and 1 mm. Both sets are 8 frames per case and move with the camera positions.+The gap-0 pair is two identical boxes, so every pixel ties and the first one drawn keeps it; it never flickers, and a coplanar pair of different size is what `decal` and `resolveCoplanar` are for. The wrong share falls to 1 percent or less at 50 m (0.1 and 1 mm) and at 500 m with a 1 mm gap, but not to zero: at 500 m the 0.1 mm case is still wrong on 13 percent of pixels, because a Float32 world position has a step of 0.03 mm there and the vertex transform adds more, which no depth buffer format removes. The next step, not done here, is a camera-relative vertex transform (the view translation applied to the instance matrix in double precision before the projection). SwiftShader also has the extension (the same page ran there). Its numbers are noisier and are not a precision measure: before 0.20 and 0.10 (50 m, 0.1 and 1 mm), 0.10 and 0.41 (500 m); after 0, 0.16, 0 and 0, with whole frames wrong in some jitters at 50 m and 1 mm. Both sets are 8 frames per case and move with the camera positions.-Pictures: `glass`, `brick-flat`, `outdoor-hdri` and `mountain-valley` drawn by SwiftShader with `render-gpu.mjs --cpu`, with and without `--standard-depth`: the first three are byte for byte the same; `mountain-valley` differs on 0.055 percent of its pixels by more than 2 of 255 (largest step 31), the edges of far trees where the depth test breaks a tie differently. With `--ambient-occlusion 1` (which reads the depth texture) `brick-flat` is identical and `mountain-valley` differs on 0.13 percent, largest step 28. The GPU renders of the same four scenes are queued behind a path-tracer job and are not in these numbers.+Pictures: `glass`, `brick-flat`, `outdoor-hdri` and `mountain-valley` drawn by SwiftShader with `render-gpu.mjs --cpu` (standard depth, then reversed through the installed addon), with and without `--reversed-depth`: the first three are byte for byte the same; `mountain-valley` differs on 0.055 percent of its pixels by more than 2 of 255 (largest step 31), the edges of far trees where the depth test breaks a tie differently. With `--ambient-occlusion 1` (which reads the depth texture) `brick-flat` is identical and `mountain-valley` differs on 0.13 percent, largest step 28. The GPU renders of the same four scenes are queued behind a path-tracer job and are not in these numbers.diff --git a/bench/reference/depth-precision.js b/bench/reference/depth-precision.jsindex 82542110..32d87294 100644--- a/bench/reference/depth-precision.js+++ b/bench/reference/depth-precision.js@@ -2,6 +2,7 @@// The near plane is red and the far plane is blue; each pair is a pair of identical boxes whose near face sits `gap` closer to the camera.import { Renderer67 } from '/src/renderer.js';import { box } from '/src/geometry.js';+import { installReversedDepth } from '/src/reversed-depth.js';const DISTANCES = [1, 50, 500];const GAPS_IN_METRES = [0, 0.0001, 0.001];@@ -45,7 +46,8 @@ function measure(reversedDepth) {for (const distance of DISTANCES) {for (const gap of GAPS_IN_METRES) {const canvas = document.querySelector('canvas');- const renderer = new Renderer67(canvas, pairOfPlanes(distance, gap), { ground: false, hdr: false, depth: false, samples: 1, pixelRatio: 1, world: true, environment: { fogDensity: 0 }, reversedDepth });+ const renderer = new Renderer67(canvas, pairOfPlanes(distance, gap), { ground: false, hdr: false, depth: false, samples: 1, pixelRatio: 1, world: true, environment: { fogDensity: 0 } });+ if (reversedDepth) installReversedDepth(renderer, true);renderer.resize();const fractions = [];const covered = [];@@ -67,7 +69,8 @@ function measure(reversedDepth) {// One frame as a PNG data URL, to look at where the far plane wins.window.drawDepthCase = (distance, gapMillimetres, jitter, reversedDepth) => {const canvas = document.querySelector('canvas');- const renderer = new Renderer67(canvas, pairOfPlanes(distance, gapMillimetres / 1000), { ground: false, hdr: false, depth: false, samples: 1, pixelRatio: 1, world: true, environment: { fogDensity: 0 }, reversedDepth });+ const renderer = new Renderer67(canvas, pairOfPlanes(distance, gapMillimetres / 1000), { ground: false, hdr: false, depth: false, samples: 1, pixelRatio: 1, world: true, environment: { fogDensity: 0 } });+ if (reversedDepth) installReversedDepth(renderer, true);renderer.resize();renderer.render(jitteredFrame(distance, jitter));renderer.render(jitteredFrame(distance, jitter));diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 5553ff1f..5ab641a9 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -17,6 +17,7 @@ import { applyLightLinks } from '/src/light-linking.js';import { applyWaterReflection, attachWaterReflection } from '/src/water-reflection.js';import { attachScreenSpaceWater } from './ssr-water.js';import { groundBounceEnvironment } from '/src/ground-bounce.js';+import { installReversedDepth } from '/src/reversed-depth.js';// Water reflection is on the way a recipe gets it: found from the materials, no field. ?water=off draws the scenes without it, ?water=ssr with the screen-space reflection it was compared with.// Ground bounce is on the way a recipe gets it: found from the floor part, no field. ?groundBounce=off draws the scenes without it.@@ -27,8 +28,8 @@ function withDerivedGroundBounce(scene, drawnParts) {return GROUND_BOUNCE ? groundBounceEnvironment(drawnParts, scene.environment) : scene.environment;}-// ?reversedDepth=off draws with the standard depth buffer, to compare against reversed-Z (issue #310).-const REVERSED_DEPTH = new URLSearchParams(location.search).get('reversedDepth') !== 'off';+// ?reversedDepth=on draws with reversed-Z (issue #310); the scenes draw with the standard depth buffer otherwise.+const REVERSED_DEPTH = new URLSearchParams(location.search).get('reversedDepth') === 'on';const WATER_REFLECTION = { off: false, ssr: 'ssr' }[new URLSearchParams(location.search).get('water')] ?? 'planar';@@ -156,9 +157,10 @@ async function bakeScenePreset(scene, preset) {function createSceneRenderer(parts, scene, cascades, { water = WATER_REFLECTION } = {}) {const reflecting = water === 'planar' ? applyWaterReflection(parts) : { parts, surface: null };const renderer = new Renderer67(document.querySelector('canvas'), applyLightLinks(reflecting.parts, scene.environment), {- ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true, reversedDepth: REVERSED_DEPTH,+ ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,environment: scene.environment, shadowBounds: scene.shadow, shadowCascades: cascades ? createCascadedShadows({ count: cascades }) : null, skyOpenness, fogSkyVisibility,});+ if (REVERSED_DEPTH) installReversedDepth(renderer, true);attachWaterReflection(renderer, reflecting.surface);if (water === 'ssr') {attachScreenSpaceWater(renderer, parts);diff --git a/bench/reference/render-gpu.mjs b/bench/reference/render-gpu.mjsindex 6c9ae1e5..ee2bce71 100644--- a/bench/reference/render-gpu.mjs+++ b/bench/reference/render-gpu.mjs@@ -1,6 +1,6 @@// Draws chosen reference scenes with 67js on the GPU only, into a directory of your choice, with measurement switches. No Blender, no scoring.// node bench/reference/render-gpu.mjs <output directory> <scene id>,<scene id> [--ambient <scale>] [--fill <scale>] [--key <scale>]-// [--ambient-occlusion <strength>] [--ambient-occlusion-radius <units>] [--standard-depth] [--cpu]+// [--ambient-occlusion <strength>] [--ambient-occlusion-radius <units>] [--reversed-depth] [--cpu]// Files are <output directory>/<scene id>-gpu.png, the names measure-depth.py and score.py read. Used to find what makes shadows light (issue #197).import { mkdir, writeFile } from 'node:fs/promises';import { constants, setPriority } from 'node:os';@@ -18,7 +18,7 @@ const sceneIds = argumentsGiven[1].split(',');const setOf = id => (/-[abc]$/.test(id) ? 'grand' : null);const waterIndex = argumentsGiven.indexOf('--water');const waterOption = waterIndex >= 0 ? argumentsGiven[waterIndex + 1] : null;-const standardDepth = argumentsGiven.includes('--standard-depth');+const reversedDepth = argumentsGiven.includes('--reversed-depth');function numberAfter(flag) {const index = argumentsGiven.indexOf(flag);@@ -43,7 +43,7 @@ try {const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT } });page.on('pageerror', error => console.log('PAGE ERROR', error.message));for (const id of sceneIds) {- await page.goto(`${serverUrl}/bench/reference/harness.html?${[setOf(id) ? `set=${setOf(id)}` : '', waterOption ? `water=${waterOption}` : '', standardDepth ? 'reversedDepth=off' : ''].filter(Boolean).join('&')}`, { timeout: 180000 });+ await page.goto(`${serverUrl}/bench/reference/harness.html?${[setOf(id) ? `set=${setOf(id)}` : '', waterOption ? `water=${waterOption}` : '', reversedDepth ? 'reversedDepth=on' : ''].filter(Boolean).join('&')}`, { timeout: 180000 });await page.waitForFunction(() => window.renderReferenceScene, null, { timeout: 180000 });const result = await page.evaluate(([sceneId, renderOptions]) => window.renderReferenceScene(sceneId, { describe: false, ...renderOptions }), [id, options]);if (result.glError !== 0) throw new Error(`${id} gave WebGL error ${result.glError}.`);diff --git a/changes/310.md b/changes/310.mdindex dc938dc2..23a88486 100644--- a/changes/310.md+++ b/changes/310.md@@ -1,2 +1,2 @@- Stop z-fighting on flush surfaces (part of #310): `renderer.diagnostics` and `scene_inspect` warn `coplanar-overlap` with both part names, the shared area and a fix, and a node's `decal: true` or `depthLayer` (0 to 4), or `environment.resolveCoplanar: 'offset'`, draws the smaller part with a scoped polygon offset in the colour pass and render passes without moving geometry.-- Draw with reversed-Z where `EXT_clip_control` exists (part of #310): depth 1 at the near plane, a 32-bit float depth buffer and `GREATER`, in the colour pass, water mirror, render passes, liquids, blended parts and splats, with the shadow maps, backgrounds and post passes unchanged and ambient occlusion, depth of field, volume fog and line art decoding the depth as before. Where the extension is missing, in benchmark mode or with `reversedDepth: false`, the standard path draws. On the RTX 3060 the share of pixels where the far plane of a pair wins falls from 0.15 to 0.009 (50 m, 0.1 mm gap), 0.079 to 0 (50 m, 1 mm) and 0.188 to 0.015 (500 m, 1 mm); 500 m with 0.1 mm stays at 0.13 (`bench/reference/README.md`). `renderer.capabilities.reversedDepth` reports it.+- Add reversed-Z depth as an addon (part of #310): `installReversedDepth(renderer, mode)` in `src/reversed-depth.js` draws the colour pass with depth 1 at the near plane, a 32-bit float depth buffer and `GREATER` where `EXT_clip_control` exists, and leaves the shadow maps, backgrounds and post passes on the standard range. `mode` is `true`, `false` or `'auto'`, which switches it on when a frame's far / near passes 10,000 or the coplanar check (`installCoplanarDiagnostics`) finds a flush pair more than 40 units from the eye. The renderer core is unchanged, so a scene that does not install it pays no bytes. On the RTX 3060 the share of pixels where the far plane of a pair wins falls from 0.15 to 0.009 (50 m, 0.1 mm gap), 0.079 to 0 (50 m, 1 mm) and 0.188 to 0.015 (500 m, 1 mm); 500 m with 0.1 mm stays at 0.13 (`bench/reference/README.md`).diff --git a/changes/310.size.md b/changes/310.size.mddeleted file mode 100644index 0e7b838a..00000000--- a/changes/310.size.md+++ /dev/null@@ -1,6 +0,0 @@-- entry:core: reversed-Z (issue #310) adds the clip control switch, the reversed projection and the depth-sample uniform in six programs, about 0.5 KB gzip; it has to load with the renderer because the first scene frame already clears and tests depth.-- scene:lit-box: the reversed-Z switch, projection and depth-sample uniforms load with the renderer (about 0.5 KB gzip); lit-box was 49,934 and is now about 50,434.-- scene:gltf-box: the reversed-Z switch and projection load with the renderer (about 0.5 KB gzip).-- scene:gltf-box+lazy: the reversed-Z switch and projection load with the renderer (about 0.5 KB gzip).-- scene:agent-scene: the reversed-Z switch and projection load with the renderer (about 0.5 KB gzip).-- scene:agent-scene+lazy: the reversed-Z switch and projection load with the renderer (about 0.5 KB gzip).diff --git a/src/ambient-occlusion.js b/src/ambient-occlusion.jsindex bfcc6f38..9d0679e8 100644--- a/src/ambient-occlusion.js+++ b/src/ambient-occlusion.js@@ -1,4 +1,3 @@-import { STANDARD_DEPTH_GLSL } from './reversed-depth.js';export const AMBIENT_OCCLUSION_SAMPLES = 12;/**@@ -16,7 +15,7 @@ uniform float radius;uniform float projectionScale;uniform float aspect;uniform float orthographic;-${STANDARD_DEPTH_GLSL}out vec4 occlusion;+out vec4 occlusion;vec3 worldPosition(vec2 uv, float depth) {vec4 point = inverseViewProjection * vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);@@ -28,7 +27,7 @@ float interleavedNoise(vec2 pixel) {}void main() {- float depth = standardDepth(texture(sceneDepth, textureCoordinate).r);+ float depth = texture(sceneDepth, textureCoordinate).r;if (depth >= 1.0) {occlusion = vec4(1.0);return;@@ -45,7 +44,7 @@ void main() {float angle = rotation + float(index) * 2.3999632;vec2 offset = vec2(cos(angle), sin(angle)) * sqrt(fraction) * screenRadius;vec2 sampleUv = textureCoordinate + vec2(offset.x / aspect, offset.y);- float sampleDepth = standardDepth(texture(sceneDepth, sampleUv).r);+ float sampleDepth = texture(sceneDepth, sampleUv).r;if (sampleDepth >= 1.0) continue;vec3 toSample = worldPosition(sampleUv, sampleDepth) - position;float sampleDistance = length(toSample);diff --git a/src/camera-effects.js b/src/camera-effects.jsindex a084dd0c..59aa0e03 100644--- a/src/camera-effects.js+++ b/src/camera-effects.js@@ -1,4 +1,3 @@-import { STANDARD_DEPTH_GLSL } from './reversed-depth.js';import { mat4 } from 'gl-matrix';import { applyProjection } from './camera.js';import { compileProgram, fullscreenVertex } from './gl-program.js';@@ -24,12 +23,12 @@ uniform sampler2D sourceTexture;uniform sampler2D sceneDepth;uniform mat4 inverseViewProjection;uniform vec2 resolution;-${STANDARD_DEPTH_GLSL}out vec4 outputColor;+out vec4 outputColor;float pixelRotation() {return 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));}vec3 worldPointAt(vec2 coordinate) {- float depth = standardDepth(texture(sceneDepth, coordinate).r);+ float depth = texture(sceneDepth, coordinate).r;vec4 point = inverseViewProjection * vec4(coordinate * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);return point.xyz / point.w;}@@ -132,7 +131,7 @@ export function createStage({ name, fragment, uniformNames, isActive, setUniformconst context = renderer.context;if (!program) {program = compileProgram(context, fullscreenVertex, fragment);- const names = ['sourceTexture', 'sceneDepth', 'inverseViewProjection', 'resolution', 'depthReversed', ...uniformNames];+ const names = ['sourceTexture', 'sceneDepth', 'inverseViewProjection', 'resolution', ...uniformNames];uniforms = Object.fromEntries(names.map(uniformName => [uniformName, context.getUniformLocation(program, uniformName)]));}target ??= createTarget(renderer);@@ -148,7 +147,6 @@ export function createStage({ name, fragment, uniformNames, isActive, setUniformcontext.activeTexture(context.TEXTURE1);context.bindTexture(context.TEXTURE_2D, renderer.depthTexture);context.uniform1i(uniforms.sceneDepth, 1);- context.uniform1f(uniforms.depthReversed, renderer.reversedDepth ? 1 : 0);context.uniformMatrix4fv(uniforms.inverseViewProjection, false, renderer.inverseViewProjection);context.uniform2f(uniforms.resolution, renderer.canvas.width, renderer.canvas.height);setUniforms(context, uniforms, renderer, frame, effects);diff --git a/src/coplanar-overlap.js b/src/coplanar-overlap.jsindex 2c030179..fca7b2a3 100644--- a/src/coplanar-overlap.js+++ b/src/coplanar-overlap.js@@ -1,4 +1,5 @@import { depthLayerOf, MAXIMUM_DEPTH_LAYER } from './depth-layer.js';+import { installReversedDepth } from './reversed-depth.js';// Loaded on demand (renderer diagnostics, scene_inspect, resolveCoplanar), never part of the core bundle.// Finds pairs of parts that draw the same plane in the same place, which z-fight: a sign flush with a wall, a road marking@@ -328,17 +329,37 @@ function diagonalOfPart(part) {return diagonal(worldBounds(part));}+// 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 pair is farther from the eye than a 24-bit depth buffer can separate it from the larger one. */+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;+ });+}+/*** Adds the coplanar-overlap warning to `renderer.diagnostics`. The check is bounded (see findCoplanarOverlaps) and runs once* per layout, when the renderer's batches change, not per frame, so parts that move later are not rechecked.+ * It also installs reversed-Z depth (reversed-depth.js): `reversedDepth` is `true` (always), `false` (never) or `'auto'`, which+ * switches it on for a very long lens (far / near over 10,000) or for a flush pair far from the eye.*/-export function installCoplanarDiagnostics(renderer) {+export function installCoplanarDiagnostics(renderer, { reversedDepth = 'auto' } = {}) {let checkedBatches = null;let problems = null;+ installReversedDepth(renderer, reversedDepth);renderer.coplanarDiagnostics = batches => {if (batches !== checkedBatches) {checkedBatches = batches;- problems = coplanarOverlapDiagnostics(findCoplanarOverlaps(batches.flatMap(batch => batch.parts)));+ const { overlaps, truncated } = findCoplanarOverlaps(batches.flatMap(batch => batch.parts));+ problems = coplanarOverlapDiagnostics({ overlaps, truncated });+ if (hasFarOverlap(overlaps, renderer.view)) renderer.requestReversedDepth?.();}return problems;};diff --git a/src/gaussian-splats.js b/src/gaussian-splats.jsindex 6aaa1a32..0a71a0f2 100644--- a/src/gaussian-splats.js+++ b/src/gaussian-splats.js@@ -214,7 +214,7 @@ function prepareState(renderer, attachment, frame) {context.blendFuncSeparate(context.ONE, context.ONE_MINUS_SRC_ALPHA, context.ONE, context.ONE_MINUS_SRC_ALPHA);context.useProgram(attachment.program);const { uniforms } = attachment;- context.uniformMatrix4fv(uniforms.projection, false, renderer.rasterProjection);+ context.uniformMatrix4fv(uniforms.projection, false, renderer.rasterProjection ?? renderer.projection);context.uniform2f(uniforms.focal, renderer.projection[0] * width * 0.5, renderer.projection[5] * height * 0.5);context.uniform2f(uniforms.viewport, width, height);context.uniform1f(uniforms.hdrEnabled, renderer.hdr ? 1 : 0);diff --git a/src/line-art.js b/src/line-art.jsindex c934f2b4..75e94b08 100644--- a/src/line-art.js+++ b/src/line-art.js@@ -1,4 +1,3 @@-import { STANDARD_DEPTH_GLSL } from './reversed-depth.js';import './toon-shader.js';// gl-program.js is not imported on purpose: this module loads on demand, and sharing a module with the scene entry makes@@ -161,7 +160,6 @@ uniform sampler2D sceneDepth;uniform sampler2D partTexture;uniform sampler2D normalTexture;uniform vec3 projectionDepth;-${STANDARD_DEPTH_GLSL}uniform float halfWidth;uniform vec3 lineColor;uniform float useBoundaries;@@ -172,7 +170,7 @@ ivec2 lastPixel;vec3 partAt(ivec2 pixel) { return texelFetch(partTexture, clamp(pixel, ivec2(0), lastPixel), 0).rgb; }vec3 normalAt(ivec2 pixel) { return normalize(texelFetch(normalTexture, clamp(pixel, ivec2(0), lastPixel), 0).rgb * 2.0 - 1.0); }float depthAt(ivec2 pixel) {- float ndc = standardDepth(texelFetch(sceneDepth, clamp(pixel, ivec2(0), lastPixel), 0).r) * 2.0 - 1.0;+ float ndc = texelFetch(sceneDepth, clamp(pixel, ivec2(0), lastPixel), 0).r * 2.0 - 1.0;return projectionDepth.z > 0.5 ? -(ndc - projectionDepth.y) / projectionDepth.x : (ndc + projectionDepth.x) / projectionDepth.y;}bool hasPart(vec3 part) { return dot(part, vec3(1.0)) > 0.0; }@@ -258,7 +256,6 @@ const polylineFragment = `#version 300 esprecision highp float;uniform sampler2D sceneDepth;uniform vec3 projectionDepth;-${STANDARD_DEPTH_GLSL}uniform float lineWidth;uniform vec3 lineColor;uniform float depthTest;@@ -274,7 +271,7 @@ void main() {float alpha = clamp(lineWidth * 0.5 - distanceToSegment + 0.5, 0.0, 1.0);if (alpha <= 0.0) discard;if (depthTest > 0.5) {- float sceneDistance = eyeDepth(standardDepth(texelFetch(sceneDepth, ivec2(gl_FragCoord.xy), 0).r));+ float sceneDistance = eyeDepth(texelFetch(sceneDepth, ivec2(gl_FragCoord.xy), 0).r);if (eyeDepth(gl_FragCoord.z) > sceneDistance * 1.005 + 0.002) discard;}outputColor = vec4(lineColor * alpha, alpha);@@ -382,10 +379,9 @@ function createLineArtStage(state) {if (!outlineProgram) {outlineProgram = compileProgram(context, fullscreenVertex, outlineFragment);outlineUniforms = uniformLocations(context, outlineProgram, ['sourceTexture', 'sceneDepth', 'partTexture', 'normalTexture',- 'projectionDepth', 'halfWidth', 'lineColor', 'useBoundaries', 'creaseCosine', 'depthJump', 'depthReversed']);+ 'projectionDepth', 'halfWidth', 'lineColor', 'useBoundaries', 'creaseCosine', 'depthJump']);}context.useProgram(outlineProgram);- context.uniform1f(outlineUniforms.depthReversed, renderer.reversedDepth ? 1 : 0);const bindings = [[sourceTexture, 'sourceTexture'], [renderer.depthTexture, 'sceneDepth'], [guideTarget(renderer, 'part').texture, 'partTexture'], [guideTarget(renderer, 'normal').texture, 'normalTexture']];bindings.forEach(([texture, uniform], unit) => {context.activeTexture(context.TEXTURE0 + unit);@@ -420,7 +416,7 @@ function createLineArtStage(state) {if (!polylineProgram) {polylineProgram = compileProgram(context, polylineVertex, polylineFragment);polylineUniforms = uniformLocations(context, polylineProgram, ['viewProjection', 'resolution', 'lineWidth', 'sceneDepth',- 'projectionDepth', 'lineColor', 'depthTest', 'depthReversed']);+ 'projectionDepth', 'lineColor', 'depthTest']);vertexArray = context.createVertexArray();}context.useProgram(polylineProgram);@@ -430,7 +426,6 @@ function createLineArtStage(state) {context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, renderer.depthTexture);context.uniform1i(polylineUniforms.sceneDepth, 0);- context.uniform1f(polylineUniforms.depthReversed, renderer.reversedDepth ? 1 : 0);context.uniformMatrix4fv(polylineUniforms.viewProjection, false, renderer.viewProjection);context.uniform2f(polylineUniforms.resolution, canvas.width, canvas.height);context.uniform3fv(polylineUniforms.projectionDepth, projectionDepth(renderer));diff --git a/src/liquid-renderer.js b/src/liquid-renderer.jsindex 938e629e..701a8645 100644--- a/src/liquid-renderer.js+++ b/src/liquid-renderer.js@@ -40,7 +40,7 @@ export function drawLiquidPass(renderer, { frame, environment, assemblyAmount, econtext.enable(context.CULL_FACE);context.useProgram(renderer.liquidProgram);const uniforms = renderer.liquidUniforms;- context.uniformMatrix4fv(uniforms.viewProjection, false, renderer.rasterViewProjection);+ context.uniformMatrix4fv(uniforms.viewProjection, false, renderer.rasterViewProjection ?? renderer.viewProjection);context.uniformMatrix4fv(uniforms.lightProjection, false, renderer.lightProjection);context.uniform3fv(uniforms.eye, frame.eye);context.uniform2f(uniforms.resolution, width, height);diff --git a/src/post.js b/src/post.jsindex 75622d17..ca5f5f57 100644--- a/src/post.js+++ b/src/post.js@@ -1,4 +1,3 @@-import { STANDARD_DEPTH_GLSL } from './reversed-depth.js';import { registeredFeatureCode } from './shader-registry.js';export { fullscreenVertex } from './gl-program.js';@@ -47,7 +46,6 @@ uniform highp sampler3D fogSkyVisibility;uniform sampler2D occlusionTexture;uniform float occlusionStrength;uniform vec2 occlusionTexel;-${STANDARD_DEPTH_GLSL}out vec4 outputColor;float luminance(vec3 color) { return dot(color, vec3(0.299, 0.587, 0.114)); }float hash(vec3 position) { return fract(sin(dot(position, vec3(127.1, 311.7, 74.7))) * 43758.5453); }@@ -66,7 +64,7 @@ vec3 volumeFog(vec3 background) {vec4 nearPoint = inverseViewProjection * vec4(clipXY, -1.0, 1.0);vec3 origin = orthographic > 0.5 ? nearPoint.xyz / nearPoint.w : eye;vec3 direction = normalize(farPoint.xyz - origin * farPoint.w);- float depth = standardDepth(texture(sceneDepth, textureCoordinate).r);+ float depth = texture(sceneDepth, textureCoordinate).r;vec4 surfacePoint = inverseViewProjection * vec4(clipXY, depth * 2.0 - 1.0, 1.0);float surfaceDistance = volumeMaxDistance;if (surfacePoint.w > 0.0) surfaceDistance = max(0.0, dot(surfacePoint.xyz - origin * surfacePoint.w, direction) / surfacePoint.w);diff --git a/src/render-target-ledger.js b/src/render-target-ledger.jsindex 737b24cc..f391e1bd 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, DEPTH_COMPONENT24: 4, DEPTH_COMPONENT32F: 4 };+const BYTES_PER_PIXEL = { R8: 1, RGBA8: 4, RGBA16F: 8, DEPTH_COMPONENT24: 4 };const BYTES_PER_MEGABYTE = 1048576;export class RenderTargetLedger {diff --git a/src/renderer.js b/src/renderer.jsindex 4b9aa1a0..7e85b4d3 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -6,7 +6,6 @@ import { fullscreenVertex, startProgram, finishProgram, compileProgram } from '.import { ambientOcclusionFragment } from './ambient-occlusion.js';import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';import { applyProjection } from './camera.js';-import { reverseProjectionDepth } from './reversed-depth.js';import { resolveEffects } from './effects.js';import { frameDiagnostics } from './frame-diagnostics.js';import { depthLayerOf } from './depth-layer.js';@@ -48,7 +47,7 @@ const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);// strength, so they can be culled and given levels like rigid parts.const SWAY_REACH_PER_STRENGTH = 0.56;-const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'depthReversed', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeShadowAmbient', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'fogSkyVisibility', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];+const POST_UNIFORMS = ['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeShadowAmbient', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'fogSkyVisibility', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'];function postUniformLocations(context, program) {return Object.fromEntries(POST_UNIFORMS.map(name => [name, context.getUniformLocation(program, name)]));@@ -381,9 +380,9 @@ export function textureDescriptorInfo(map, maximumSize = Infinity) {return { width, height, wrapS, wrapT, minFilter, magFilter, mipmaps, bytes: estimateTextureBytes(width, height, { mipmaps }) };}-function sampleCount(context, format, requested, depthFormat) {+function sampleCount(context, format, requested) {const colorCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, format, context.SAMPLES));- const depthCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, depthFormat, context.SAMPLES));+ const depthCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, context.DEPTH_COMPONENT24, context.SAMPLES));return Math.max(0, ...colorCounts.filter(count => count <= requested && depthCounts.includes(count)));}@@ -456,7 +455,7 @@ function allFinite(values) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, reversedDepth = true, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null, skyOpenness = null, fogSkyVisibility = null, shading = 'full', viewTransform = 'aces', look = null } = {}) {this.canvas = canvas;this.sceneParts = parts;// `skyOpenness` from closed-room.js is passed in, which keeps the ray code out of scenes without volume fog.@@ -506,12 +505,8 @@ export class Renderer67 {this.memoryBudgetMiB = memoryBudgetMiB;this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));if (volume.density > 0 && !this.hdr) throw new Error('Volume fog requires EXT_color_buffer_float for HDR rendering');- // Reversed-Z (issue #310) needs EXT_clip_control; without it, or in benchmark mode, the standard path draws.- this.clipControl = reversedDepth && !benchmark ? this.context.getExtension?.('EXT_clip_control') ?? null : null;- this.reversedDepth = Boolean(this.clipControl);- this.depthFormat = this.reversedDepth ? 'DEPTH_COMPONENT32F' : 'DEPTH_COMPONENT24';- this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(shading === 'light' ? Math.min(samples, LIGHT_SHADING_MAXIMUM_SAMPLES) : samples, this.context.getParameter(this.context.MAX_SAMPLES)), this.context[this.depthFormat]);- this.capabilities = { reversedDepth: this.reversedDepth, hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };+ this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(shading === 'light' ? Math.min(samples, LIGHT_SHADING_MAXIMUM_SAMPLES) : samples, this.context.getParameter(this.context.MAX_SAMPLES)));+ this.capabilities = { hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };this.geometryBytes = 0;this.geometryBuffers = new Map();this.batching = batching;@@ -604,10 +599,6 @@ export class Renderer67 {this.view = mat4.create();this.projection = mat4.create();this.viewProjection = mat4.create();- // What the rasterizer sees: the same matrices with depth reversed when EXT_clip_control is in use, else the very same arrays.- this.rasterProjection = this.reversedDepth ? mat4.create() : this.projection;- this.rasterViewProjection = this.reversedDepth ? mat4.create() : this.viewProjection;- this.depthSign = 1;this.lightProjection = mat4.create();this.shadowBiasPerSlope = 0;this.inverseViewProjection = mat4.create();@@ -1498,7 +1489,7 @@ export class Renderer67 {const context = this.context;if (!this.occlusionProgram) {this.occlusionProgram = compileProgram(context, fullscreenVertex, ambientOcclusionFragment);- const names = ['sceneDepth', 'inverseViewProjection', 'eye', 'radius', 'projectionScale', 'aspect', 'orthographic', 'depthReversed'];+ const names = ['sceneDepth', 'inverseViewProjection', 'eye', 'radius', 'projectionScale', 'aspect', 'orthographic'];this.occlusionUniforms = Object.fromEntries(names.map(name => [name, context.getUniformLocation(this.occlusionProgram, name)]));}if (this.occlusionTarget) return;@@ -1531,7 +1522,6 @@ export class Renderer67 {context.activeTexture(context.TEXTURE1);context.bindTexture(context.TEXTURE_2D, this.depthTexture);context.uniform1i(uniforms.sceneDepth, 1);- context.uniform1f(uniforms.depthReversed, this.reversedDepth ? 1 : 0);context.uniformMatrix4fv(uniforms.inverseViewProjection, false, this.inverseViewProjection);context.uniform3fv(uniforms.eye, frame.eye);context.uniform1f(uniforms.radius, effects.ambientOcclusionRadius);@@ -1552,11 +1542,11 @@ export class Renderer67 {context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.RENDERBUFFER, this.multisampleColor);this.multisampleDepth = context.createRenderbuffer();context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleDepth);- context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, context[this.depthFormat], width, height);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, context.DEPTH_COMPONENT24, 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.');this.renderTargets.record('multisampleColor', { width, height, format: this.hdr ? 'RGBA16F' : 'RGBA8', samples: this.multisampleSamples });- this.renderTargets.record('multisampleDepth', { width, height, format: this.depthFormat, samples: this.multisampleSamples });+ this.renderTargets.record('multisampleDepth', { width, height, format: 'DEPTH_COMPONENT24', samples: this.multisampleSamples });this.renderTargets.record('frameColor', { width, height, format: this.hdr ? 'RGBA16F' : 'RGBA8' });this.frameTexture = context.createTexture();context.bindTexture(context.TEXTURE_2D, this.frameTexture);@@ -1571,13 +1561,13 @@ export class Renderer67 {if (this.depth) {this.depthTexture = context.createTexture();context.bindTexture(context.TEXTURE_2D, this.depthTexture);- context.texImage2D(context.TEXTURE_2D, 0, context[this.depthFormat], width, height, 0, context.DEPTH_COMPONENT, this.reversedDepth ? context.FLOAT : context.UNSIGNED_INT, null);+ context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, width, height, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, this.depthTexture, 0);- this.renderTargets.record('sceneDepth', { width, height, format: this.depthFormat });+ this.renderTargets.record('sceneDepth', { width, height, format: 'DEPTH_COMPONENT24' });}if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Resolve framebuffer allocation failed. Choose a lower quality preset.');this.bloomWidth = Math.max(1, Math.ceil(width / 2));@@ -1801,7 +1791,6 @@ export class Renderer67 {context.uniform1f(post.uniforms.volumeNoiseScale, volume.noiseScale);context.uniform1f(post.uniforms.volumeMaxDistance, volume.maxDistance);context.uniform1f(post.uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);- context.uniform1f(post.uniforms.depthReversed, this.reversedDepth ? 1 : 0);context.uniform1i(post.uniforms.fogSkyVisibility, 5);context.activeTexture(context.TEXTURE2);context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);@@ -1924,7 +1913,7 @@ export class Renderer67 {const context = this.context;if (layer) {context.enable(context.POLYGON_OFFSET_FILL);- context.polygonOffset(-layer * this.depthSign, -layer * 4 * this.depthSign);+ context.polygonOffset(-layer, -layer * 4);} else {context.disable(context.POLYGON_OFFSET_FILL);}@@ -2087,7 +2076,6 @@ export class Renderer67 {this.diagnostics = frameDiagnostics({ world: this.world, depth: this.depth, effects, lightDirection: environment.lightDirection, shadowBounds: this.shadowBounds, coplanarProblems: this.coplanarDiagnostics?.(this.batches) });const start = performance.now();const context = this.context;- this.endReversedDepth();this.beginGpuTiming();const assemblyAmount = Math.max(0, Math.min(1, frame.assemblyAmount ?? 0));// Swaying foliage moves every frame, so its shadow map is redrawn whenever time or wind changes.@@ -2107,10 +2095,6 @@ export class Renderer67 {mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);mat4.multiply(this.viewProjection, this.projection, this.view);mat4.invert(this.inverseViewProjection, this.viewProjection);- if (this.reversedDepth) {- reverseProjectionDepth(this.rasterProjection, this.projection);- mat4.multiply(this.rasterViewProjection, this.rasterProjection, this.view);- }extractFrustumPlanes(this.viewProjection, this.frustumPlanes);this.viewForward = [-this.view[2], -this.view[6], -this.view[10]];// The water mirror is a cheap draw: it reuses the cascades of the last lit frame and leaves their redraw to the lit frame that follows.@@ -2133,15 +2117,13 @@ export class Renderer67 {}// The environment background covers every pixel, so the colour clear before it would be overwritten.const backgroundCoversFrame = !passMode && Boolean(environmentMap?.showBackground) && !this.transparent;- if (this.reversedDepth) context.clearDepth(0);context.clear(backgroundCoversFrame ? context.DEPTH_BUFFER_BIT : context.COLOR_BUFFER_BIT | context.DEPTH_BUFFER_BIT);const environmentBackgroundDrawn = !passMode && this.drawEnvironmentBackground(environmentMap, frame, exposure);if (this.world && !this.benchmark && !passMode && !environmentBackgroundDrawn) this.drawSky(frame);- this.beginReversedDepth();context.enable(context.DEPTH_TEST);context.enable(context.CULL_FACE);context.useProgram(this.program);- context.uniformMatrix4fv(this.uniforms.viewProjection, false, this.rasterViewProjection);+ context.uniformMatrix4fv(this.uniforms.viewProjection, false, this.viewProjection);context.uniformMatrix4fv(this.uniforms.lightProjection, false, this.lightProjection);context.uniform1f(this.uniforms.shadowBiasPerSlope, this.shadowBiasPerSlope);context.uniform3fv(this.uniforms.eye, eye);@@ -2193,18 +2175,15 @@ export class Renderer67 {context.enable(context.CULL_FACE);context.bindVertexArray(null);if (mirrorTarget) {- this.endReversedDepth();this.renderingPass = false;this.endGpuTiming();return;}if (passMode) {- this.endReversedDepth();this.passSupport.copyToCanvas();} else if (!this.benchmark) {this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);this.drawBlendBatches(frame);- this.endReversedDepth();this.resolveFrame(frame, effects, environment, volume);}this.renderingPass = false;@@ -2212,25 +2191,6 @@ export class Renderer67 {this.cpuMilliseconds = performance.now() - start;}- // The rasterizer runs reversed (depth 1 at the near plane, GREATER) only while the scene is drawn. The shadow maps, the- // backgrounds and the post passes keep the standard clip range, so none of their projections or depth reads change.- beginReversedDepth() {- if (!this.reversedDepth) return;- const context = this.context;- this.clipControl.clipControlEXT(this.clipControl.LOWER_LEFT_EXT, this.clipControl.ZERO_TO_ONE_EXT);- context.depthFunc(context.GREATER);- this.depthSign = -1;- }-- endReversedDepth() {- if (!this.reversedDepth || this.depthSign > 0) return;- const context = this.context;- this.clipControl.clipControlEXT(this.clipControl.LOWER_LEFT_EXT, this.clipControl.NEGATIVE_ONE_TO_ONE_EXT);- context.depthFunc(context.LESS);- context.clearDepth(1);- this.depthSign = 1;- }-beginGpuTiming() {if (this.gpuTimer === undefined) this.gpuTimer = this.createGpuTimer?.(this.context) ?? null;this.gpuTimer?.begin();diff --git a/src/reversed-depth.js b/src/reversed-depth.jsindex 3e83e117..29d80f99 100644--- a/src/reversed-depth.js+++ b/src/reversed-depth.js@@ -1,6 +1,16 @@// Reversed-Z depth (issue #310): with EXT_clip_control the depth range is zero to one, the projection maps the near plane to 1 and// 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.+import { mat4 } from 'gl-matrix';+import { compileProgram, fullscreenVertex } from './gl-program.js';++export const FAR_TO_NEAR_LIMIT = 1e4;+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).@@ -19,9 +29,193 @@ export function reverseProjectionDepth(out, projection) {return out;}-/** GLSL that turns a depth texture sample into the standard 0 (near) to 1 (far) value the rest of the shader decodes. */-export const STANDARD_DEPTH_GLSL = `uniform float depthReversed;-float standardDepth(float depth) {- return mix(depth, 1.0 - depth, depthReversed);+/** 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+precision highp float;+uniform highp sampler2D reversedDepth;+void main() {+ gl_FragDepth = 1.0 - texelFetch(reversedDepth, ivec2(gl_FragCoord.xy), 0).r;+}`;++function createDepthConversionStage() {+ let program = null;+ let uniform = null;+ let copy = null;++ function releaseTargets(context) {+ if (!copy) return;+ context.deleteTexture(copy.texture);+ context.deleteFramebuffer(copy.framebuffer);+ copy = null;+ }++ function createCopy(context, width, height) {+ const texture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, texture);+ context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT32F, width, height, 0, context.DEPTH_COMPONENT, context.FLOAT, null);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);+ const framebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, texture, 0);+ return { texture, framebuffer, width, height };+ }++ function apply(renderer) {+ if (!renderer.depthTexture) return null;+ const context = renderer.context;+ const { width, height } = renderer.canvas;+ if (!program) {+ program = compileProgram(context, fullscreenVertex, STANDARD_DEPTH_FRAGMENT);+ uniform = context.getUniformLocation(program, 'reversedDepth');+ }+ if (copy && (copy.width !== width || copy.height !== height)) releaseTargets(context);+ copy ??= createCopy(context, width, height);+ context.bindFramebuffer(context.READ_FRAMEBUFFER, renderer.resolveFramebuffer);+ context.bindFramebuffer(context.DRAW_FRAMEBUFFER, copy.framebuffer);+ context.blitFramebuffer(0, 0, width, height, 0, 0, width, height, context.DEPTH_BUFFER_BIT, context.NEAREST);+ context.bindFramebuffer(context.FRAMEBUFFER, renderer.resolveFramebuffer);+ context.viewport(0, 0, width, height);+ context.useProgram(program);+ context.activeTexture(context.TEXTURE0);+ context.bindTexture(context.TEXTURE_2D, copy.texture);+ context.uniform1i(uniform, 0);+ context.enable(context.DEPTH_TEST);+ context.depthFunc(context.ALWAYS);+ context.colorMask(false, false, false, false);+ context.disable(context.CULL_FACE);+ context.bindVertexArray(null);+ context.drawArrays(context.TRIANGLES, 0, 3);+ context.colorMask(true, true, true, true);+ context.depthFunc(context.LESS);+ context.disable(context.DEPTH_TEST);+ return null;+ }++ function dispose(context) {+ releaseTargets(context);+ if (program) context.deleteProgram(program);+ program = null;+ }++ return { name: 'Reversed depth', apply, releaseTargets, dispose };+}++// The frame targets are allocated with 24-bit depth by the core; this respecifies the two depth stores as 32-bit float.+function useFloatDepthTargets(renderer) {+ const context = renderer.context;+ if (!renderer.multisampleFramebuffer) return;+ const { width, height } = renderer.canvas;+ context.bindRenderbuffer(context.RENDERBUFFER, renderer.multisampleDepth);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, renderer.multisampleSamples, context.DEPTH_COMPONENT32F, width, height);+ 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);+ }+ for (const framebuffer of [renderer.multisampleFramebuffer, renderer.resolveFramebuffer]) {+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Reversed depth targets failed to allocate. Pass reversedDepth: false to the install.');+ }+ context.bindFramebuffer(context.FRAMEBUFFER, null);+}++/**+ * 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.+ */+export function installReversedDepth(renderer, mode = 'auto') {+ if (mode === false || renderer.reversedDepth !== undefined) return renderer;+ const context = renderer.context;+ const original = {+ render: renderer.render,+ applyEnvironmentUniforms: renderer.applyEnvironmentUniforms,+ applyDepthLayer: renderer.applyDepthLayer,+ resolveFrame: renderer.resolveFrame,+ allocateFrameTargets: renderer.allocateFrameTargets,+ };+ const rasterProjection = mat4.create();+ const rasterViewProjection = mat4.create();+ let clipControl = null;+ let requested = mode === true;+ let inFrame = false;+ let reversed = false;++ // Back to the standard range before the backgrounds, the post passes and the shadow maps draw.+ function endReversed() {+ if (!reversed || clipControl.active === false) return;+ clipControl.extension.clipControlEXT(clipControl.extension.LOWER_LEFT_EXT, clipControl.extension.NEGATIVE_ONE_TO_ONE_EXT);+ context.depthFunc(context.LESS);+ clipControl.active = false;+ }++ // Called with the main program in use, after its standard matrix is set: swap in the reversed one and clear to the far value.+ function beginReversed() {+ reverseProjectionDepth(rasterProjection, renderer.projection);+ mat4.multiply(rasterViewProjection, rasterProjection, renderer.view);+ context.uniformMatrix4fv(renderer.uniforms.viewProjection, false, rasterViewProjection);+ context.clearDepth(0);+ context.clear(context.DEPTH_BUFFER_BIT);+ context.clearDepth(1);+ clipControl.extension.clipControlEXT(clipControl.extension.LOWER_LEFT_EXT, clipControl.extension.ZERO_TO_ONE_EXT);+ context.depthFunc(context.GREATER);+ clipControl.active = true;+ }++ function enable() {+ const extension = renderer.benchmark ? null : context.getExtension?.('EXT_clip_control');+ requested = false;+ if (!extension) {+ renderer.reversedDepth = false;+ return false;+ }+ clipControl = { extension, active: false };+ reversed = true;+ renderer.reversedDepth = true;+ renderer.rasterProjection = rasterProjection;+ renderer.rasterViewProjection = rasterViewProjection;+ if (renderer.capabilities) renderer.capabilities.reversedDepth = true;+ renderer.applyEnvironmentUniforms = function applyEnvironmentUniformsReversed(map, uniforms) {+ original.applyEnvironmentUniforms.call(this, map, uniforms);+ if (inFrame && !clipControl.active && uniforms === undefined) beginReversed();+ };+ // The core pulls a decal toward the eye with a negative offset; reversed depth grows toward the eye, so the sign flips.+ renderer.applyDepthLayer = function applyDepthLayerReversed(layer) {+ original.applyDepthLayer.call(this, layer);+ if (layer && clipControl.active) context.polygonOffset(layer, layer * 4);+ };+ renderer.resolveFrame = function resolveFrameStandard(...parameters) {+ endReversed();+ return original.resolveFrame.apply(this, parameters);+ };+ renderer.allocateFrameTargets = function allocateFloatDepthTargets(width, height) {+ original.allocateFrameTargets.call(this, width, height);+ useFloatDepthTargets(this);+ };+ renderer.postStages.unshift(createDepthConversionStage());+ useFloatDepthTargets(renderer);+ 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);+ inFrame = true;+ try {+ return original.render.call(this, frame);+ } finally {+ inFrame = false;+ endReversed();+ }+ };+ if (requested) enable();+ return renderer;}-`;diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.jsindex c1f44463..4bb78695 100644--- a/tests/coplanar-overlap.test.js+++ b/tests/coplanar-overlap.test.js@@ -103,14 +103,10 @@ test('the polygon offset is scoped to the layer and switched off for layer 0', (disable: capability => calls.push(['disable', capability]),polygonOffset: (factor, units) => calls.push(['offset', factor, units]),};- const fake = { context, depthSign: 1 };+ const fake = { context };Renderer67.prototype.applyDepthLayer.call(fake, 2);Renderer67.prototype.applyDepthLayer.call(fake, 0);assert.deepEqual(calls, [['enable', 'fill'], ['offset', -2, -8], ['disable', 'fill']]);- // Reversed-Z puts the near plane at depth 1, so pulling a layer closer takes the opposite sign.- calls.length = 0;- Renderer67.prototype.applyDepthLayer.call({ context, depthSign: -1 }, 2);- assert.deepEqual(calls, [['enable', 'fill'], ['offset', 2, 8]]);});test('the check is bounded: a work budget ends the sweep and says so', () => {diff --git a/tests/reversed-depth.test.js b/tests/reversed-depth.test.jsindex 189b20ea..c483bf99 100644--- a/tests/reversed-depth.test.js+++ b/tests/reversed-depth.test.js@@ -1,7 +1,8 @@import test from 'node:test';import assert from 'node:assert/strict';import { mat4, vec4 } from 'gl-matrix';-import { reverseProjectionDepth } from '../src/reversed-depth.js';+import { exceedsFarToNearLimit, installReversedDepth, reverseProjectionDepth } from '../src/reversed-depth.js';+import { hasFarOverlap } from '../src/coplanar-overlap.js';function depthAt(projection, eyeDistance) {const clip = vec4.transformMat4(vec4.create(), [0, 0, -eyeDistance, 1], projection);@@ -16,7 +17,7 @@ test('a reversed perspective projection maps the near plane to 1 and the far plaassert.ok(depthAt(reversed, 5) > depthAt(reversed, 50));});-test('the reversed depth is one minus the standard depth mapped to 0..1, so shaders can undo it', () => {+test('the reversed depth is one minus the standard depth mapped to 0..1, so a pass can turn it back', () => {const standard = mat4.perspective(mat4.create(), Math.PI / 3, 1, 0.1, 100);const reversed = reverseProjectionDepth(mat4.create(), standard);for (const distance of [0.5, 3, 40, 99]) {@@ -32,3 +33,72 @@ test('an orthographic projection reverses too, and x, y and w are untouched', ()assert.ok(Math.abs(depthAt(reversed, 100)) < 1e-5);for (const index of [0, 1, 3, 4, 5, 7, 8, 9, 11, 12, 13, 15]) assert.equal(reversed[index], standard[index]);});++function fakeRenderer({ extension = {}, benchmark = false } = {}) {+ const drawn = [];+ const renderer = {+ benchmark,+ capabilities: {},+ postStages: [],+ context: { getExtension: name => (name === 'EXT_clip_control' ? extension : null) },+ render: frame => drawn.push(frame),+ applyEnvironmentUniforms() {},+ applyDepthLayer() {},+ resolveFrame() {},+ allocateFrameTargets() {},+ };+ 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', () => {+ 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);++ const forced = fakeRenderer();+ installReversedDepth(forced.renderer, true);+ assert.equal(forced.renderer.reversedDepth, true);++ const off = fakeRenderer();+ installReversedDepth(off.renderer, false);+ off.renderer.render({ far: 1e6, near: 0.1 });+ assert.equal(off.renderer.reversedDepth, undefined);+ assert.equal(off.renderer.requestReversedDepth, undefined);+});++test('without the extension, or in benchmark mode, the standard path stays', () => {+ const missing = fakeRenderer({ extension: null });+ installReversedDepth(missing.renderer, true);+ 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);+});