Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Draw with reversed-Z where EXT_clip_control exists (part of #310)

Nguyen Xuan Anf46e25072f4d
diff --git a/bench/reference/README.md b/bench/reference/README.md
index 50530a73..646b9b47 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -1534,3 +1534,23 @@ Fix: `harness.js` renders the reference frame with `wind: 0`. Re-run with 67js o
| mountain-valley-c (grand) | 0.1836 to 0.1775 | 0.223 to 0.2182 | 0.1522 |
`foliage` now sits 0.0086 under EEVEE against Cycles (was 0.0055 over). Every other default and grand scene has no leaf cards and was not re-rendered; the only score that rose is a GPU against CPU difference (`gpu-vs-cpu` of `foliage` 0.0095 to 0.0097, `mountain-valley-b` 0.0158 to 0.0164). The Cycles and EEVEE columns did not move, so this is a change on the 67js side of the comparison and not a new reference. The score no longer includes the wind, which a real scene still has by default (`wind` 0.3); that is by design and is not scored here.
+
+## 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).
+
+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`.
+
+| Distance | Gap | Before (24-bit) | After (reversed, float) |
+| --- | --- | --- | --- |
+| 1 m | 0, 0.1, 1 mm | 0, 0, 0 | 0, 0, 0 |
+| 50 m | 0 mm | 0 | 0 |
+| 50 m | 0.1 mm | 0.150 | 0.009 |
+| 50 m | 1 mm | 0.079 | 0.000 |
+| 500 m | 0 mm | 0 | 0 |
+| 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.
+
+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.
diff --git a/bench/reference/depth-precision-image.mjs b/bench/reference/depth-precision-image.mjs
new file mode 100644
index 00000000..e71cb031
--- /dev/null
+++ b/bench/reference/depth-precision-image.mjs
@@ -0,0 +1,27 @@
+// One frame of the depth precision scene as a PNG, to look at where the far plane wins (issue #310).
+// node bench/reference/depth-precision-image.mjs <output.png> <distance> <gap in millimetres> <jitter 0-7> <reversed: 1|0> [gpu|cpu]
+import { writeFile } from 'node:fs/promises';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const BACKEND_ARGUMENTS = {
+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],
+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+};
+const [outputPath, distance, gap, jitter, reversed, backend = 'gpu'] = process.argv.slice(2);
+
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
+try {
+ const page = await browser.newPage({ viewport: { width: 480, height: 270 } });
+ await page.goto(`${serverUrl}/bench/reference/depth-precision.html`, { timeout: 180000 });
+ await page.waitForFunction(() => window.drawDepthCase, null, { timeout: 180000 });
+ const dataUrl = await page.evaluate(([d, g, j, r]) => window.drawDepthCase(d, g, j, r), [Number(distance), Number(gap), Number(jitter), reversed === '1']);
+ await writeFile(outputPath, Buffer.from(dataUrl.split(',')[1], 'base64'));
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/bench/reference/depth-precision.html b/bench/reference/depth-precision.html
new file mode 100644
index 00000000..b50f60b2
--- /dev/null
+++ b/bench/reference/depth-precision.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+<head>
+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>
+</head>
+<body>
+<canvas></canvas>
+<script type="module" src="./depth-precision.js"></script>
+</body>
+</html>
diff --git a/bench/reference/depth-precision.js b/bench/reference/depth-precision.js
new file mode 100644
index 00000000..82542110
--- /dev/null
+++ b/bench/reference/depth-precision.js
@@ -0,0 +1,82 @@
+// Runs in the page: draws pairs of flush and near-flush planes and counts the pixels where the far plane wins (issue #310).
+// 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';
+
+const DISTANCES = [1, 50, 500];
+const GAPS_IN_METRES = [0, 0.0001, 0.001];
+const CAMERA_JITTERS = 8;
+
+function plane(name, color, distance, size) {
+ const matrix = new Float32Array([size, 0, 0, 0, 0, size, 0, 0, 0, 0, 0.05, 0, distance * 0.85, 0, -distance, 1]);
+ return { name, geometry: box(0, 32), matrix, material: { tag: 'surface', metallic: 0, roughness: 0.5, emission: 0, color } };
+}
+
+// The far plane is drawn second, which is the order that lets a tie go to the wrong surface under a LESS test.
+function pairOfPlanes(distance, gap) {
+ const size = distance * 2.2;
+ return [plane('near', [1, 0, 0], distance - gap, size), plane('far', [0, 0, 1], distance, size)];
+}
+
+function countFarWins(context, width, height) {
+ const pixels = new Uint8Array(width * height * 4);
+ context.bindFramebuffer(context.FRAMEBUFFER, null);
+ context.readPixels(0, 0, width, height, context.RGBA, context.UNSIGNED_BYTE, pixels);
+ let farPixels = 0;
+ let nearPixels = 0;
+ for (let offset = 0; offset < pixels.length; offset += 4) {
+ const red = pixels[offset];
+ const blue = pixels[offset + 2];
+ // The sky is neither, and a shadowed pixel is dark but keeps its hue: only a clearly red or clearly blue pixel counts.
+ if (blue > 12 && blue > red * 2) farPixels++;
+ if (red > 12 && red > blue * 2) nearPixels++;
+ }
+ return { farPixels, nearPixels };
+}
+
+// The camera looks across the planes at about 60 degrees from their normal, where the depth changes quickly from pixel to pixel.
+function jitteredFrame(distance, jitter) {
+ const offset = jitter * 0.013 * Math.min(distance, 10);
+ return { eye: [offset, offset * 0.5, 0], target: [distance * 0.5 + offset, 0, -distance], up: [0, 1, 0], time: 0, wind: 0, exposure: 1 };
+}
+
+function measure(reversedDepth) {
+ const results = [];
+ 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 });
+ renderer.resize();
+ const fractions = [];
+ const covered = [];
+ for (let jitter = 0; jitter < CAMERA_JITTERS; jitter++) {
+ renderer.render(jitteredFrame(distance, jitter));
+ renderer.render(jitteredFrame(distance, jitter));
+ const { farPixels, nearPixels } = countFarWins(renderer.context, canvas.width, canvas.height);
+ fractions.push(farPixels / Math.max(1, farPixels + nearPixels));
+ covered.push((farPixels + nearPixels) / (canvas.width * canvas.height));
+ }
+ const mean = fractions.reduce((total, value) => total + value, 0) / fractions.length;
+ results.push({ distance, gapMillimetres: gap * 1000, farWinsMean: mean, perJitter: fractions.map(value => Number(value.toFixed(3))), farWinsMinimum: Math.min(...fractions), farWinsMaximum: Math.max(...fractions), coveredMinimum: Math.min(...covered), glError: renderer.context.getError(), reversedDepth: renderer.reversedDepth });
+ renderer.dispose();
+ }
+ }
+ return results;
+}
+
+// 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 });
+ renderer.resize();
+ renderer.render(jitteredFrame(distance, jitter));
+ renderer.render(jitteredFrame(distance, jitter));
+ const image = canvas.toDataURL('image/png');
+ renderer.dispose();
+ return image;
+};
+
+window.measureDepthPrecision = () => {
+ const probe = document.createElement('canvas').getContext('webgl2');
+ return { extension: Boolean(probe.getExtension('EXT_clip_control')), before: measure(false), after: measure(true) };
+};
diff --git a/bench/reference/depth-precision.mjs b/bench/reference/depth-precision.mjs
new file mode 100644
index 00000000..fe3b5033
--- /dev/null
+++ b/bench/reference/depth-precision.mjs
@@ -0,0 +1,30 @@
+// Depth error of flush and near-flush planes, with the standard depth buffer and with reversed-Z (issue #310).
+// node bench/reference/depth-precision.mjs [gpu|cpu]
+// Prints JSON: for each distance and gap, the share of pixels where the far plane wins, averaged over camera jitters.
+import { constants, setPriority } from 'node:os';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const BACKEND_ARGUMENTS = {
+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],
+ cpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'],
+};
+const backend = process.argv[2] ?? 'gpu';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+await server.listen();
+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
+try {
+ const page = await browser.newPage({ viewport: { width: 480, height: 270 } });
+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));
+ await page.goto(`${serverUrl}/bench/reference/depth-precision.html`, { timeout: 180000 });
+ await page.waitForFunction(() => window.measureDepthPrecision, null, { timeout: 180000 });
+ const result = await page.evaluate(() => window.measureDepthPrecision());
+ console.log(JSON.stringify({ backend, ...result }));
+} finally {
+ await browser.close();
+ await server.close();
+}
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index 85bc1614..5553ff1f 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -27,6 +27,9 @@ 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';
+
const WATER_REFLECTION = { off: false, ssr: 'ssr' }[new URLSearchParams(location.search).get('water')] ?? 'planar';
// ?set=khronos draws the Khronos sample assets (npm run reference -- --khronos) and ?set=cloth the cloth scenes
@@ -153,7 +156,7 @@ 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,
+ ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true, reversedDepth: REVERSED_DEPTH,
environment: scene.environment, shadowBounds: scene.shadow, shadowCascades: cascades ? createCascadedShadows({ count: cascades }) : null, skyOpenness, fogSkyVisibility,
});
attachWaterReflection(renderer, reflecting.surface);
diff --git a/bench/reference/render-gpu.mjs b/bench/reference/render-gpu.mjs
index 41a873ff..6c9ae1e5 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>]
+// [--ambient-occlusion <strength>] [--ambient-occlusion-radius <units>] [--standard-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,6 +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');
function numberAfter(flag) {
const index = argumentsGiven.indexOf(flag);
@@ -37,12 +38,12 @@ await mkdir(outputDirectory, { recursive: true });
const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
await server.listen();
const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;
-const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'] });
+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding', ...(argumentsGiven.includes('--cpu') ? ['--use-angle=swiftshader', '--enable-unsafe-swiftshader'] : [])] });
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}` : ''].filter(Boolean).join('&')}`, { timeout: 180000 });
+ 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.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.md
index 82fc21c7..dc938dc2 100644
--- a/changes/310.md
+++ b/changes/310.md
@@ -1 +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. Reversed-Z depth stays open.
+- 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.
diff --git a/changes/310.size.md b/changes/310.size.md
new file mode 100644
index 00000000..0e7b838a
--- /dev/null
+++ b/changes/310.size.md
@@ -0,0 +1,6 @@
+- 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.js
index 9d0679e8..bfcc6f38 100644
--- a/src/ambient-occlusion.js
+++ b/src/ambient-occlusion.js
@@ -1,3 +1,4 @@
+import { STANDARD_DEPTH_GLSL } from './reversed-depth.js';
export const AMBIENT_OCCLUSION_SAMPLES = 12;
/**
@@ -15,7 +16,7 @@ uniform float radius;
uniform float projectionScale;
uniform float aspect;
uniform float orthographic;
-out vec4 occlusion;
+${STANDARD_DEPTH_GLSL}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);
@@ -27,7 +28,7 @@ float interleavedNoise(vec2 pixel) {
}
void main() {
- float depth = texture(sceneDepth, textureCoordinate).r;
+ float depth = standardDepth(texture(sceneDepth, textureCoordinate).r);
if (depth >= 1.0) {
occlusion = vec4(1.0);
return;
@@ -44,7 +45,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 = texture(sceneDepth, sampleUv).r;
+ float sampleDepth = standardDepth(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.js
index 59aa0e03..a084dd0c 100644
--- a/src/camera-effects.js
+++ b/src/camera-effects.js
@@ -1,3 +1,4 @@
+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';
@@ -23,12 +24,12 @@ uniform sampler2D sourceTexture;
uniform sampler2D sceneDepth;
uniform mat4 inverseViewProjection;
uniform vec2 resolution;
-out vec4 outputColor;
+${STANDARD_DEPTH_GLSL}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 = texture(sceneDepth, coordinate).r;
+ float depth = standardDepth(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;
}
@@ -131,7 +132,7 @@ export function createStage({ name, fragment, uniformNames, isActive, setUniform
const context = renderer.context;
if (!program) {
program = compileProgram(context, fullscreenVertex, fragment);
- const names = ['sourceTexture', 'sceneDepth', 'inverseViewProjection', 'resolution', ...uniformNames];
+ const names = ['sourceTexture', 'sceneDepth', 'inverseViewProjection', 'resolution', 'depthReversed', ...uniformNames];
uniforms = Object.fromEntries(names.map(uniformName => [uniformName, context.getUniformLocation(program, uniformName)]));
}
target ??= createTarget(renderer);
@@ -147,6 +148,7 @@ export function createStage({ name, fragment, uniformNames, isActive, setUniform
context.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/gaussian-splats.js b/src/gaussian-splats.js
index 9cea8321..6aaa1a32 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.projection);
+ context.uniformMatrix4fv(uniforms.projection, false, renderer.rasterProjection);
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.js
index 75e94b08..c934f2b4 100644
--- a/src/line-art.js
+++ b/src/line-art.js
@@ -1,3 +1,4 @@
+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
@@ -160,6 +161,7 @@ uniform sampler2D sceneDepth;
uniform sampler2D partTexture;
uniform sampler2D normalTexture;
uniform vec3 projectionDepth;
+${STANDARD_DEPTH_GLSL}
uniform float halfWidth;
uniform vec3 lineColor;
uniform float useBoundaries;
@@ -170,7 +172,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 = texelFetch(sceneDepth, clamp(pixel, ivec2(0), lastPixel), 0).r * 2.0 - 1.0;
+ float ndc = standardDepth(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; }
@@ -256,6 +258,7 @@ const polylineFragment = `#version 300 es
precision highp float;
uniform sampler2D sceneDepth;
uniform vec3 projectionDepth;
+${STANDARD_DEPTH_GLSL}
uniform float lineWidth;
uniform vec3 lineColor;
uniform float depthTest;
@@ -271,7 +274,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(texelFetch(sceneDepth, ivec2(gl_FragCoord.xy), 0).r);
+ float sceneDistance = eyeDepth(standardDepth(texelFetch(sceneDepth, ivec2(gl_FragCoord.xy), 0).r));
if (eyeDepth(gl_FragCoord.z) > sceneDistance * 1.005 + 0.002) discard;
}
outputColor = vec4(lineColor * alpha, alpha);
@@ -379,9 +382,10 @@ function createLineArtStage(state) {
if (!outlineProgram) {
outlineProgram = compileProgram(context, fullscreenVertex, outlineFragment);
outlineUniforms = uniformLocations(context, outlineProgram, ['sourceTexture', 'sceneDepth', 'partTexture', 'normalTexture',
- 'projectionDepth', 'halfWidth', 'lineColor', 'useBoundaries', 'creaseCosine', 'depthJump']);
+ 'projectionDepth', 'halfWidth', 'lineColor', 'useBoundaries', 'creaseCosine', 'depthJump', 'depthReversed']);
}
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);
@@ -416,7 +420,7 @@ function createLineArtStage(state) {
if (!polylineProgram) {
polylineProgram = compileProgram(context, polylineVertex, polylineFragment);
polylineUniforms = uniformLocations(context, polylineProgram, ['viewProjection', 'resolution', 'lineWidth', 'sceneDepth',
- 'projectionDepth', 'lineColor', 'depthTest']);
+ 'projectionDepth', 'lineColor', 'depthTest', 'depthReversed']);
vertexArray = context.createVertexArray();
}
context.useProgram(polylineProgram);
@@ -426,6 +430,7 @@ 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.js
index 3aa75413..938e629e 100644
--- a/src/liquid-renderer.js
+++ b/src/liquid-renderer.js
@@ -40,7 +40,7 @@ export function drawLiquidPass(renderer, { frame, environment, assemblyAmount, e
context.enable(context.CULL_FACE);
context.useProgram(renderer.liquidProgram);
const uniforms = renderer.liquidUniforms;
- context.uniformMatrix4fv(uniforms.viewProjection, false, renderer.viewProjection);
+ context.uniformMatrix4fv(uniforms.viewProjection, false, renderer.rasterViewProjection);
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.js
index ca5f5f57..75622d17 100644
--- a/src/post.js
+++ b/src/post.js
@@ -1,3 +1,4 @@
+import { STANDARD_DEPTH_GLSL } from './reversed-depth.js';
import { registeredFeatureCode } from './shader-registry.js';
export { fullscreenVertex } from './gl-program.js';
@@ -46,6 +47,7 @@ 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); }
@@ -64,7 +66,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 = texture(sceneDepth, textureCoordinate).r;
+ float depth = standardDepth(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.js
index f391e1bd..737b24cc 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 };
+const BYTES_PER_PIXEL = { R8: 1, RGBA8: 4, RGBA16F: 8, 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 7e85b4d3..4b9aa1a0 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -6,6 +6,7 @@ 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';
@@ -47,7 +48,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', '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', 'depthReversed', '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)]));
@@ -380,9 +381,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) {
+function sampleCount(context, format, requested, depthFormat) {
const colorCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, format, context.SAMPLES));
- const depthCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, context.DEPTH_COMPONENT24, context.SAMPLES));
+ const depthCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, depthFormat, context.SAMPLES));
return Math.max(0, ...colorCounts.filter(count => count <= requested && depthCounts.includes(count)));
}
@@ -455,7 +456,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, 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, reversedDepth = true, 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.
@@ -505,8 +506,12 @@ 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');
- 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 };
+ // 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.geometryBytes = 0;
this.geometryBuffers = new Map();
this.batching = batching;
@@ -599,6 +604,10 @@ 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();
@@ -1489,7 +1498,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'];
+ const names = ['sceneDepth', 'inverseViewProjection', 'eye', 'radius', 'projectionScale', 'aspect', 'orthographic', 'depthReversed'];
this.occlusionUniforms = Object.fromEntries(names.map(name => [name, context.getUniformLocation(this.occlusionProgram, name)]));
}
if (this.occlusionTarget) return;
@@ -1522,6 +1531,7 @@ 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);
@@ -1542,11 +1552,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.DEPTH_COMPONENT24, width, height);
+ context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, context[this.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.');
this.renderTargets.record('multisampleColor', { width, height, format: this.hdr ? 'RGBA16F' : 'RGBA8', samples: this.multisampleSamples });
- this.renderTargets.record('multisampleDepth', { width, height, format: 'DEPTH_COMPONENT24', samples: this.multisampleSamples });
+ this.renderTargets.record('multisampleDepth', { width, height, format: this.depthFormat, 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);
@@ -1561,13 +1571,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.DEPTH_COMPONENT24, width, height, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);
+ context.texImage2D(context.TEXTURE_2D, 0, context[this.depthFormat], width, height, 0, context.DEPTH_COMPONENT, this.reversedDepth ? context.FLOAT : 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: 'DEPTH_COMPONENT24' });
+ this.renderTargets.record('sceneDepth', { width, height, format: this.depthFormat });
}
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));
@@ -1791,6 +1801,7 @@ 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);
@@ -1913,7 +1924,7 @@ export class Renderer67 {
const context = this.context;
if (layer) {
context.enable(context.POLYGON_OFFSET_FILL);
- context.polygonOffset(-layer, -layer * 4);
+ context.polygonOffset(-layer * this.depthSign, -layer * 4 * this.depthSign);
} else {
context.disable(context.POLYGON_OFFSET_FILL);
}
@@ -2076,6 +2087,7 @@ 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.
@@ -2095,6 +2107,10 @@ 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.
@@ -2117,13 +2133,15 @@ 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.viewProjection);
+ context.uniformMatrix4fv(this.uniforms.viewProjection, false, this.rasterViewProjection);
context.uniformMatrix4fv(this.uniforms.lightProjection, false, this.lightProjection);
context.uniform1f(this.uniforms.shadowBiasPerSlope, this.shadowBiasPerSlope);
context.uniform3fv(this.uniforms.eye, eye);
@@ -2175,15 +2193,18 @@ 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;
@@ -2191,6 +2212,25 @@ 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.js
new file mode 100644
index 00000000..3e83e117
--- /dev/null
+++ b/src/reversed-depth.js
@@ -0,0 +1,27 @@
+// 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.
+
+/**
+ * Turns a projection that maps depth to -1..1 into one that maps it to 1..0 (the clip control range is 0..1).
+ * Only the third row changes: the new z is (w - z) / 2, so it works for perspective, orthographic and oblique matrices.
+ */
+export function reverseProjectionDepth(out, projection) {
+ for (let column = 0; column < 4; column++) {
+ const depthIndex = column * 4 + 2;
+ const clipDepth = projection[depthIndex];
+ const clipW = projection[depthIndex + 1];
+ out[column * 4] = projection[column * 4];
+ out[column * 4 + 1] = projection[column * 4 + 1];
+ out[depthIndex] = (clipW - clipDepth) / 2;
+ out[depthIndex + 1] = clipW;
+ }
+ 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);
+}
+`;
diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.js
index 4bb78695..c1f44463 100644
--- a/tests/coplanar-overlap.test.js
+++ b/tests/coplanar-overlap.test.js
@@ -103,10 +103,14 @@ 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 };
+ const fake = { context, depthSign: 1 };
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.js
new file mode 100644
index 00000000..189b20ea
--- /dev/null
+++ b/tests/reversed-depth.test.js
@@ -0,0 +1,34 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4, vec4 } from 'gl-matrix';
+import { reverseProjectionDepth } from '../src/reversed-depth.js';
+
+function depthAt(projection, eyeDistance) {
+ const clip = vec4.transformMat4(vec4.create(), [0, 0, -eyeDistance, 1], projection);
+ return clip[2] / clip[3];
+}
+
+test('a reversed perspective projection maps the near plane to 1 and the far plane to 0', () => {
+ const standard = mat4.perspective(mat4.create(), Math.PI / 4, 1.5, 0.1, 600);
+ const reversed = reverseProjectionDepth(mat4.create(), standard);
+ assert.ok(Math.abs(depthAt(reversed, 0.1) - 1) < 1e-5);
+ assert.ok(Math.abs(depthAt(reversed, 600)) < 1e-5);
+ assert.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', () => {
+ 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]) {
+ const standardDepth = (depthAt(standard, distance) + 1) / 2;
+ assert.ok(Math.abs(1 - depthAt(reversed, distance) - standardDepth) < 1e-5);
+ }
+});
+
+test('an orthographic projection reverses too, and x, y and w are untouched', () => {
+ const standard = mat4.ortho(mat4.create(), -2, 2, -1, 1, 0.1, 100);
+ const reversed = reverseProjectionDepth(mat4.create(), standard);
+ assert.ok(Math.abs(depthAt(reversed, 0.1) - 1) < 1e-5);
+ 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]);
+});