Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

WIP: rank near-coplanar triangles (#751)

Nguyen Xuan An0be00b0ad9ac
diff --git a/bench/flicker/index.html b/bench/flicker/index.html
index ecb7e7f0..5cc73069 100644
--- a/bench/flicker/index.html
+++ b/bench/flicker/index.html
@@ -37,7 +37,7 @@
<div class="row" id="toggles">
<button data-toggle="reversed" aria-pressed="true">Reversed-Z</button>
<button data-toggle="nearFit" aria-pressed="true">Near fit</button>
- <button data-toggle="offset" aria-pressed="false">Coplanar offset</button>
+ <button data-toggle="offset" aria-pressed="true">Flush ranks</button>
<button data-toggle="ids" aria-pressed="false">Part colours</button>
</div>
<div class="row"><button id="probe">Flicker probe</button><button id="clear">Clear</button></div>
diff --git a/bench/flicker/probe.mjs b/bench/flicker/probe.mjs
index 91dbe994..16dc8e09 100644
--- a/bench/flicker/probe.mjs
+++ b/bench/flicker/probe.mjs
@@ -2,6 +2,7 @@
// node bench/flicker/probe.mjs --url http://127.0.0.1:5210 --asset /@fs/D:/path/file.glb --out artifacts/flicker \
// --spots spots.json --configs "reversed=1,nearFit=1;reversed=0,nearFit=0"
// spots.json: [{ "name": "roofs", "eye": [x, y, z], "target": [x, y, z] }]. Without --spots it prints the scene bounds and exits.
+// node bench/flicker/probe.mjs --traps --configs "reversed=1;reversed=0" runs every trap scene of traps.js with its own camera.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { chromium } from 'playwright';
@@ -30,14 +31,32 @@ page.on('pageerror', error => console.error('pageerror', error.message));
page.on('console', message => { if (message.type() === 'error') console.error('console', message.text()); });
const results = [];
-async function open(configuration) {
- const query = new URLSearchParams({ asset, ...Object.fromEntries(Object.entries(configuration).map(([key, value]) => [key, value])) });
+async function open(configuration, trap = null) {
+ const query = new URLSearchParams({ ...(trap ? { trap } : { asset }), ...configuration });
await page.goto(`${baseUrl}/bench/flicker/index.html?${query}`);
await page.evaluate(() => window.flicker.ready);
}
+async function probeTraps() {
+ for (const configuration of configurations) {
+ const label = Object.entries(configuration).map(([key, value]) => `${key}${value}`).join('-');
+ await open(configuration, 'plaque-2m');
+ for (const trap of await page.evaluate(() => window.flicker.traps)) {
+ await open(configuration, trap);
+ await page.waitForTimeout(300);
+ const outcome = await page.evaluate(async () => ({ probe: await window.flicker.probe(), info: window.flicker.info }));
+ await page.screenshot({ path: path.join(outputFolder, `${prefix}-${trap}-${label}.png`) });
+ results.push({ trap, configuration: label, changed: outcome.probe.changed, moved: outcome.probe.totalChanged, depth: outcome.info.depthMode });
+ console.log(JSON.stringify(results.at(-1)));
+ }
+ }
+ writeFileSync(path.join(outputFolder, `${prefix}-results.json`), JSON.stringify(results, null, 1));
+}
+
try {
- if (!spotsFile) {
+ if (process.argv.includes('--traps')) {
+ await probeTraps();
+ } else if (!spotsFile) {
await open(configurations[0]);
console.log(JSON.stringify(await page.evaluate(() => window.flicker.info), null, 1));
} else {
diff --git a/bench/flicker/traps.js b/bench/flicker/traps.js
new file mode 100644
index 00000000..71eeb5bf
--- /dev/null
+++ b/bench/flicker/traps.js
@@ -0,0 +1,155 @@
+// Trap scenes for the flicker probe (issue #751): small scenes built to z-fight, each with the camera that shows it.
+// Open /bench/flicker/index.html?trap=<name>, or run probe.mjs with --traps. Every face has its own flat colour (vertex
+// colours), so the probe also sees two faces of one mesh trade places.
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+const DEGREES = Math.PI / 180;
+
+function faceColour(index) {
+ const hue = (index * 0.618034) % 1;
+ return [0, 1 / 3, 2 / 3].map(offset => 0.5 + 0.45 * Math.cos(2 * Math.PI * (hue + offset)));
+}
+
+function cross(first, second) {
+ return [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];
+}
+
+// A quad centred on `centre`, spanning `width` along `right` and `height` along `up` (unit vectors); it faces right x up.
+function quad(centre, right, up, width, height, colour) {
+ const corners = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([alongRight, alongUp]) => centre.map((value, axis) => value + right[axis] * alongRight * width / 2 + up[axis] * alongUp * height / 2));
+ return { corners, normal: cross(right, up), colour };
+}
+
+function wallQuad(centre, width, height, colour) {
+ return quad(centre, [1, 0, 0], [0, 1, 0], width, height, colour);
+}
+
+function floorQuad(centre, width, depth, colour) {
+ return quad(centre, [1, 0, 0], [0, 0, -1], width, depth, colour);
+}
+
+// The six faces of a box from `low` to `high`, each with the next colour.
+function boxQuads(low, high, firstColour) {
+ const centre = low.map((value, axis) => (value + high[axis]) / 2);
+ const size = low.map((value, axis) => high[axis] - value);
+ const faces = [
+ [[0, 0, 1], [1, 0, 0], [0, 1, 0], size[0], size[1]], [[0, 0, -1], [-1, 0, 0], [0, 1, 0], size[0], size[1]],
+ [[1, 0, 0], [0, 0, -1], [0, 1, 0], size[2], size[1]], [[-1, 0, 0], [0, 0, 1], [0, 1, 0], size[2], size[1]],
+ [[0, 1, 0], [1, 0, 0], [0, 0, -1], size[0], size[2]], [[0, -1, 0], [1, 0, 0], [0, 0, 1], size[0], size[2]],
+ ];
+ return faces.map(([normal, right, up, width, height], index) => quad(centre.map((value, axis) => value + normal[axis] * size[axis] / 2), right, up, width, height, faceColour(firstColour + index)));
+}
+
+function part(name, quads, extra = {}) {
+ const positions = [];
+ const normals = [];
+ const colors = [];
+ const indices = [];
+ quads.forEach((face, index) => {
+ for (const corner of face.corners) {
+ positions.push(...corner);
+ normals.push(...face.normal);
+ colors.push(...face.colour);
+ }
+ indices.push(index * 4, index * 4 + 1, index * 4 + 2, index * 4, index * 4 + 2, index * 4 + 3);
+ });
+ return {
+ name,
+ geometry: { positions: new Float32Array(positions), normals: new Float32Array(normals), colors: new Float32Array(colors), indices: new Uint32Array(indices) },
+ matrix: new Float32Array(IDENTITY),
+ material: { color: [1, 1, 1], metallic: 0, roughness: 1 },
+ ...extra,
+ };
+}
+
+function movedCopy(source, name, translation) {
+ const matrix = new Float32Array(IDENTITY);
+ matrix.set(translation, 12);
+ return { ...source, name, matrix };
+}
+
+function plaqueOnWall(distance) {
+ return {
+ parts: [part('wall', [wallQuad([0, 2, 0], 10, 4, faceColour(0))]), part('plaque', [wallQuad([0, 2, 0], 2, 1, faceColour(1))])],
+ eye: [distance * 0.3, 2 + distance * 0.1, distance],
+ target: [0, 2, 0],
+ };
+}
+
+function stackedSlabs() {
+ return {
+ parts: [
+ part('slabWest', boxQuads([-6, 0, -4], [2, 0.2, 4], 0)),
+ part('slabEast', boxQuads([-2, 0, -4], [6, 0.2, 4], 6)),
+ part('slabUpper', boxQuads([-3, 0.2, -4], [3, 0.4, 4], 12)),
+ part('slabUpperTwin', boxQuads([-1, 0.2, -4], [5, 0.4, 2], 18)),
+ ],
+ eye: [9, 7, 13],
+ target: [0, 0.2, 0],
+ };
+}
+
+// One mesh, as a kitbashed asset arrives: a wall, an exact duplicate, a staggered copy and trims that sit on the same plane.
+function kitbashedDuplicates() {
+ return {
+ parts: [part('kitbash', [
+ wallQuad([0, 2, 0], 8, 4, faceColour(0)), wallQuad([0, 2, 0], 8, 4, faceColour(1)), wallQuad([1.5, 2.5, 0], 8, 4, faceColour(2)),
+ wallQuad([-2, 2, 0], 1.5, 2.5, faceColour(3)), wallQuad([2, 1.5, 0], 3, 0.4, faceColour(4)), wallQuad([2, 1.5, 0], 1, 1.2, faceColour(5)),
+ ])],
+ eye: [4, 3, 12],
+ target: [0.5, 2, 0],
+ };
+}
+
+function grazingDecal() {
+ const distance = 30;
+ return {
+ parts: [part('ground', [floorQuad([0, 0, 0], 60, 60, faceColour(0))]), part('marking', [floorQuad([0, 0, 0], 6, 6, faceColour(1))], { decal: true })],
+ eye: [0, distance * Math.tan(2 * DEGREES), distance],
+ target: [0, 0, 0],
+ };
+}
+
+// Two walls 1.6 cm apart, seen from 1 km at 5 degrees to their plane. The front wall is a little smaller, so both show.
+function gappedWalls() {
+ const distance = 1000;
+ return {
+ parts: [part('backWall', [wallQuad([0, 30, 0], 240, 60, faceColour(0))]), part('frontWall', [wallQuad([0, 30, 0.016], 200, 40, faceColour(1))])],
+ eye: [-distance * Math.cos(5 * DEGREES), 30, distance * Math.sin(5 * DEGREES)],
+ target: [0, 30, 0],
+ };
+}
+
+// 30 quads on exactly one plane in one mesh, each a little smaller than the one before, so every one shows as a ring.
+function exactStack() {
+ return {
+ parts: [part('stack', Array.from({ length: 30 }, (unused, index) => wallQuad([0, 2, 0], 6 - index * 0.18, 4 - index * 0.12, faceColour(index))))],
+ eye: [3, 3, 9],
+ target: [0, 2, 0],
+ };
+}
+
+// Three instances of one box geometry; only the first has its front face in the plane of the wall.
+function instancedFlush() {
+ const crate = part('crateFlush', boxQuads([-0.5, 0, -1], [0.5, 1, 0], 2));
+ return {
+ parts: [
+ part('wall', [wallQuad([0, 2, 0], 10, 4, faceColour(0))]),
+ crate, movedCopy(crate, 'crateFree', [3, 0, 2]), movedCopy(crate, 'crateFar', [-3, 0, 3]),
+ ],
+ eye: [2, 2.5, 10],
+ target: [0, 1, 0],
+ };
+}
+
+export const TRAPS = {
+ 'plaque-2m': () => plaqueOnWall(2),
+ 'plaque-20m': () => plaqueOnWall(20),
+ 'plaque-200m': () => plaqueOnWall(200),
+ 'stacked-slabs': stackedSlabs,
+ 'kitbash-duplicates': kitbashedDuplicates,
+ 'decal-grazing-2deg': grazingDecal,
+ 'walls-16mm-1km-5deg': gappedWalls,
+ 'stack-30-exact': exactStack,
+ 'instanced-flush': instancedFlush,
+};
diff --git a/bench/flicker/viewer.js b/bench/flicker/viewer.js
index f0431421..7f29631b 100644
--- a/bench/flicker/viewer.js
+++ b/bench/flicker/viewer.js
@@ -4,6 +4,7 @@ import { vec3 } from 'gl-matrix';
import { Renderer67 } from '../../src/index.js';
import { parseGltf } from '../../src/gltf.js';
import { resolveFlushParts } from '../../src/coplanar-overlap.js';
+import { TRAPS } from './traps.js';
// One flat colour per part, no textures, so a pixel's colour says which part owns it and a changed colour is a changed owner.
function paintPartsByOwner(parts) {
@@ -52,9 +53,10 @@ const ICONS = {
const options = {
reversed: parameters.get('reversed') !== '0',
nearFit: parameters.get('nearFit') !== '0',
- offset: parameters.get('offset') === '1',
+ offset: parameters.get('offset') !== '0',
ids: parameters.get('ids') === '1',
};
+const trapName = parameters.get('trap');
const camera = { pivot: [0, 0, 0], yaw: 0.8, pitch: -0.5, distance: 10 };
let mode = 'orbit';
let glbBytes = null;
@@ -105,13 +107,24 @@ function frameFor(jitterPixels = 0) {
return frame;
}
+// A trap scene (traps.js) brings its own colour per face and its own camera.
+async function loadScene() {
+ if (!trapName) {
+ const loaded = await parseGltf(glbBytes.slice(0));
+ if (options.ids) paintPartsByOwner(loaded.parts);
+ return loaded;
+ }
+ if (!TRAPS[trapName]) throw new Error(`Unknown trap ${trapName}. Use one of: ${Object.keys(TRAPS).join(', ')}.`);
+ options.ids = true;
+ return TRAPS[trapName]();
+}
+
async function build() {
- if (!glbBytes) return;
+ if (!glbBytes && !trapName) return;
setStatus('wait', 'Building the scene');
renderer?.dispose();
renderer = null;
- const loaded = await parseGltf(glbBytes.slice(0));
- if (options.ids) paintPartsByOwner(loaded.parts);
+ const loaded = await loadScene();
bounds = measureBounds(loaded.parts);
const size = bounds.maximum.map((value, axis) => value - bounds.minimum[axis]);
extent = Math.max(...size);
@@ -331,6 +344,12 @@ async function loadFromUrl(url) {
frameWholeScene();
}
+async function loadTrap() {
+ assetName = trapName;
+ await build();
+ setCamera(TRAPS[trapName]());
+}
+
bindControls();
requestAnimationFrame(tick);
document.querySelector('#speedValue').textContent = '';
@@ -338,7 +357,8 @@ window.flicker = {
setCamera, probe, build, options, frameWholeScene,
get info() { return { depthMode: depthModeLabel(), ...(renderer ? nearAndFar() : {}), extent, bounds, canvas: [canvas.width, canvas.height], memory: renderer?.memoryReport?.() }; },
render: () => { markDirty(); renderer?.render(frameFor(0)); },
- ready: parameters.get('asset')
+ traps: Object.keys(TRAPS),
+ ready: trapName ? loadTrap().catch(error => setStatus('bad', error.message)) : parameters.get('asset')
? loadFromUrl(parameters.get('asset')).catch(error => setStatus('bad', error.message))
: Promise.resolve(),
};
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 50ed7822..42faa763 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -284,7 +284,7 @@ const environment = z.strictObject({
floorSkyTrace: z.boolean().optional().describe('false turns off the sky traced into floors of sun-lit closed rooms.'),
sunBounce: z.number().min(0).optional().describe('Sun bounce in a closed room: 0 off, 1 default.'),
specularAntiAliasing: z.number().min(0).max(4).optional().describe('Specular anti-aliasing: 0 off, 1 default; widens highlights that sparkle on grainy normal-mapped metal.'),
- resolveCoplanar: z.union([z.literal('offset'), z.literal(false)]).optional().describe("'offset' biases the smaller part of each coplanar pair at draw time; false clears."),
+ resolveCoplanar: z.union([z.literal('offset'), z.literal(false)]).optional().describe("Flush faces are ranked at draw time by default ('offset'); false opts out."),
viewTransform: z.enum(VIEW_TRANSFORM_NAMES).optional().describe('Display transform, for example agx to compare with Blender.'),
look: z.union([z.enum([...LOOK_NAMES, ...BUNDLED_CUBE_LOOK_NAMES]), z.string().regex(CATALOG_FILE_ID)]).nullable().optional().describe('Look preset or .cube; scene_capabilities catalogLooks. null clears.'),
sky: z.record(z.string(), z.unknown()).nullable().optional().describe('Physical sky: {type:"physical", sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective}; sets key light, sky and fog. Fields in scene_capabilities physicalSky.'),
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4945350b..37d9bfc0 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -255,9 +255,9 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
field: 'environment.viewTransform', names: VIEW_TRANSFORM_NAMES, default: 'aces', look: 'environment.look', looks: LOOK_NAMES,
choose: 'agx for lit scenes and Blender comparisons, neutral for product and brand colour, aces for contrast; needs loadAgentSceneModules',
}),
- // Flush surfaces flicker (z-fighting). scene_inspect and renderer.diagnostics warn with coplanar-overlap; these fix it at draw time.
+ // Flush surfaces flicker (z-fighting). They are ranked at draw time by default; coplanar-overlap warns about what is left.
renderFlags: Object.freeze({ nodeFields: Object.freeze(['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher']), motion: 'node track property visible: 1 or 0, STEP', note: 'visible:false hides a node and children; holdout and shadowCatcher need a transparent canvas (Renderer67 transparent:true); flags split batches.' }),
- depthBias: Object.freeze({ nodeFields: Object.freeze(['decal', 'depthLayer']), maxDepthLayer: 4, environment: 'environment.resolveCoplanar', modes: Object.freeze(['offset']), warning: 'coplanar-overlap', note: 'decal wins over the surface below; depthLayer stacks decals; resolveCoplanar offset biases the smaller part of a flagged pair.' }),
+ depthBias: Object.freeze({ nodeFields: Object.freeze(['decal', 'depthLayer']), maxDepthLayer: 4, environment: 'environment.resolveCoplanar', modes: Object.freeze(['offset', false]), default: 'offset', warning: 'coplanar-overlap', note: 'Automatic: flush or near-flush faces, inside one mesh or across parts, are ranked per triangle at draw time, the front face wins, geometry never moves; no field needed. resolveCoplanar false opts out. decal wins over the surface below; depthLayer stacks decals. scene_inspect flush.ranked counts ranked parts. A coplanar-overlap warning carries reason rank-overflow (over 15 stacked faces: remove duplicates), double-sided-gap, unchecked or collapsed-node.' }),
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim', 'chain', 'spline']),
// Authored rigs: armatures expand into bone nodes, and a node `skin` binds a mesh with automatic weights (four influences).
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 82d96445..3d64dba7 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -78,8 +78,9 @@ const MODULE_MARKERS = {
crowd: ['"crowd":{'],
lineArt: ['"lines":{', '"toon":'],
viewTransform: ['"viewTransform":"agx"', '"viewTransform":"neutral"', '"look":"'],
- // The coplanar-overlap warning in scene_inspect appears only once this is loaded, which loadAllAgentSceneModules does; a recipe with resolveCoplanar needs it.
- coplanar: ['"resolveCoplanar"'],
+ // Flush faces are ranked by default (issue #751), so every recipe loads this unless it opts out. A recipe that opted out still
+ // gets the coplanar-overlap warning in scene_inspect once loadAllAgentSceneModules has loaded it.
+ coplanar: [/^(?!.*"resolveCoplanar":false)/s],
// A closed room a sun lights gets the floor sky trace by default. The recipe text can not say whether a room is closed, so a recipe that names its sun loads it and the module skips an open scene.
floorSky: ['"keyColor"', '"keyIntensity"'],
physicalSky: ['"type":"physical"'],
diff --git a/src/agent-scene.js b/src/agent-scene.js
index b8f2e843..df753b83 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1458,27 +1458,38 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
return share !== null && share >= CLOSED_ROOM_SHARE ? [closedRoomDiagnostic(share, isLitByLampsOnly(state.recipe.environment))] : [];
}
- // environment.resolveCoplanar 'offset' puts the smaller part of each coplanar pair on the next depth layer, so the
- // renderer draws it with a polygon offset. Geometry never moves. The result is kept while the parts are the same objects.
- let coplanarCache = null;
+ // Near-coplanar triangles are ranked at draw time (issue #751) unless environment.resolveCoplanar is false, once the
+ // coplanar code is loaded. The ranks sit beside the parts, so the parts and their geometry stay as they are. The search
+ // runs again only when the parts are new objects.
+ let flushCache = null;
function stageCoplanarOffsets(recipe, parts) {
- if (recipe.environment.resolveCoplanar !== 'offset') {
+ if (!agentSceneModuleLoaded('coplanar')) {
return parts;
}
- if (coplanarCache?.parts === parts) {
- return coplanarCache.resolved;
+ const coplanar = agentSceneModule('coplanar');
+ if (recipe.environment.resolveCoplanar === false) {
+ if (flushCache) {
+ coplanar.clearFlushParts(flushCache.parts);
+ }
+ flushCache = null;
+ return parts;
}
- const resolved = Object.freeze(agentSceneModule('coplanar').resolveCoplanarParts(parts));
- coplanarCache = { parts, resolved };
- return resolved;
+ if (flushCache?.parts !== parts) {
+ flushCache = { parts, ...coplanar.resolveFlushParts(parts) };
+ }
+ return parts;
}
- // scene_inspect names coplanar pairs: the check is bounded, runs on inspect only, once the coplanar code is loaded, and is kept until the scene changes.
+ // scene_inspect names what the ranking could not settle. A scene that opted out gets the pairs of parts that fight instead:
+ // that check is bounded, runs on inspect only and is kept until the scene changes.
let coplanarReportCache = null;
function coplanarProblems() {
if (!agentSceneModuleLoaded('coplanar')) {
return [];
}
+ if (state.recipe.environment.resolveCoplanar !== false) {
+ return agentSceneModule('coplanar').flushLeftoverDiagnostics(flushCache?.leftovers ?? []);
+ }
if (coplanarReportCache?.revision !== revision) {
const coplanar = agentSceneModule('coplanar');
coplanarReportCache = { revision, problems: coplanar.coplanarOverlapDiagnostics(coplanar.findCoplanarOverlaps(state.parts)) };
@@ -1819,6 +1830,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
...(state.recipe.armatures ? { rig: rigReport(state.recipe, state.skinBindings) } : {}),
boundsSpace: 'authored-base-world',
...(diagnostics.length ? { diagnostics } : {}),
+ ...(flushCache?.ranked ? { flush: { ranked: flushCache.ranked } } : {}),
counts: {
nodes: state.recipe.nodes.length, parts: state.parts.length,
geometries: state.geometries.size, materials: state.recipe.materials.length,
diff --git a/src/coplanar-overlap.js b/src/coplanar-overlap.js
index c2b79fde..84059ce3 100644
--- a/src/coplanar-overlap.js
+++ b/src/coplanar-overlap.js
@@ -1,7 +1,11 @@
-import { depthLayerOf, MAXIMUM_DEPTH_LAYER, setFlushDepthLayers } from './depth-layer.js';
+import { depthLayerOf, flushOrderOf, setFlushOrder } from './depth-layer.js';
+import { resolveFlush } from './flush-resolve.js';
+import { boundsDiagonal as diagonal, determinantSign, worldBounds } from './flush-search.js';
-// The renderer runs resolveFlushParts once on the parts it is built with; the diagnostics and resolveCoplanar use the same search.
-// 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
+// Two jobs. resolveFlushParts ranks near-coplanar triangles so they stop z-fighting (flush-search.js, flush-resolve.js); the
+// renderer runs it once on the parts it is built with, and the agent scene whenever its parts change. findCoplanarOverlaps is
+// the report for a scene that opted out: it names the pairs of parts that fight and how to fix them.
+// It 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
// on asphalt, two boxes whose visible faces coincide. The work is bounded: a grid over part bounds, then triangles only
// inside the shared box of a pair, with a fixed budget for the whole scene (`truncated` says it ran out).
// Only faces that look the same way count, since a face against a floor looks away from it and is culled. A part with a
@@ -11,8 +15,6 @@ import { depthLayerOf, MAXIMUM_DEPTH_LAYER, setFlushDepthLayers } from './depth-
export const COPLANAR_TOLERANCE = 0.001;
/** Overlaps smaller than this (square metres) are edge contact, not a fight. */
export const COPLANAR_MINIMUM_AREA = 1e-4;
-/** Pairs on one plane to within this distance (metres) are left to the depth buffer by resolveFlushParts. */
-export const EXACT_FLUSH_DISTANCE = 1e-6;
/** The distance suggested in the fix text, in metres. */
export const SUGGESTED_OFFSET = 0.002;
const DEFAULT_WORK_BUDGET = 1_000_000;
@@ -23,47 +25,6 @@ const MAXIMUM_LISTED_PAIRS = 3_000_000;
const SAME_FACING = Math.cos(Math.PI / 180);
const REPORTED_PAIRS = 8;
-const localBoundsByGeometry = new WeakMap();
-
-function localBounds(geometry) {
- let bounds = localBoundsByGeometry.get(geometry);
- if (bounds) return bounds;
- bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
- const { positions } = geometry;
- for (let offset = 0; offset < positions.length; offset += 3) {
- for (let axis = 0; axis < 3; axis++) {
- bounds[axis] = Math.min(bounds[axis], positions[offset + axis]);
- bounds[3 + axis] = Math.max(bounds[3 + axis], positions[offset + axis]);
- }
- }
- localBoundsByGeometry.set(geometry, bounds);
- return bounds;
-}
-
-function worldBounds(part) {
- const local = localBounds(part.geometry);
- const matrix = part.matrix;
- const bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
- for (let corner = 0; corner < 8; corner++) {
- const x = corner & 1 ? local[3] : local[0];
- const y = corner & 2 ? local[4] : local[1];
- const z = corner & 4 ? local[5] : local[2];
- for (let axis = 0; axis < 3; axis++) {
- const value = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
- bounds[axis] = Math.min(bounds[axis], value);
- bounds[3 + axis] = Math.max(bounds[3 + axis], value);
- }
- }
- return bounds;
-}
-
-function determinantSign(matrix) {
- const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[6] * matrix[9])
- - matrix[4] * (matrix[1] * matrix[10] - matrix[2] * matrix[9])
- + matrix[8] * (matrix[1] * matrix[6] - matrix[2] * matrix[5]);
- return determinant < 0 ? -1 : 1;
-}
-
// A plane is hashed by its normal (sign folded, 0.01 steps) and its offset (buckets of twice the tolerance). Two triangles
// on one plane share a bucket or sit in neighbouring buckets (the offset is the lowest part of the key), so candidate pairs
// come from buckets, and the search scales with triangles instead of part pairs.
@@ -239,12 +200,9 @@ function boundsOverlapRegion(first, second, tolerance) {
return region;
}
-function diagonal(bounds) {
- return Math.hypot(bounds[3] - bounds[0], bounds[4] - bounds[1], bounds[5] - bounds[2]);
-}
-
+// A pair on different layers is a whole layer of ranks apart, and a part with a ranked order was settled by resolveFlushParts.
function resolvedByLayer(first, second) {
- return depthLayerOf(first) !== depthLayerOf(second);
+ return depthLayerOf(first) !== depthLayerOf(second) || Boolean(flushOrderOf(first) || flushOrderOf(second));
}
// Whether the boxes of two triangles touch, a cheap test before the plane and area checks.
@@ -438,7 +396,7 @@ export function coplanarOverlapDiagnostics({ overlaps, truncated }) {
parts: [smaller.name, larger.name],
area: Math.round(area * 10000) / 10000,
message: `${smaller.name} and ${larger.name} draw the same plane (${metres(distance * 1000)} mm apart, ${metres(area)} m2 overlap) and will flicker (z-fighting).`,
- fix: `Move ${smaller.name} ${metres(SUGGESTED_OFFSET * 1000)} mm along its normal [${normal.map(component => Math.round(component * 1000) / 1000).join(', ')}], or set decal: true on ${smaller.name}, or set environment.resolveCoplanar to 'offset' to bias it at draw time without moving it.`,
+ fix: `Move ${smaller.name} ${metres(SUGGESTED_OFFSET * 1000)} mm along its normal [${normal.map(component => Math.round(component * 1000) / 1000).join(', ')}], or set decal: true on ${smaller.name}, or drop resolveCoplanar: false from the environment so the faces are ranked at draw time without moving.`,
}));
if (overlaps.length > REPORTED_PAIRS || (truncated && overlaps.length)) {
problems.push({
@@ -446,40 +404,12 @@ export function coplanarOverlapDiagnostics({ overlaps, truncated }) {
severity: 'warning',
target: 'scene',
message: truncated ? `${overlaps.length} coplanar pairs found before the check hit its work budget; more may exist.` : `${overlaps.length - REPORTED_PAIRS} more coplanar pairs.`,
- fix: "Set environment.resolveCoplanar to 'offset' to bias every smaller part at draw time.",
+ fix: 'Drop resolveCoplanar: false from the environment so every flush face is ranked at draw time.',
});
}
return problems;
}
-/**
- * The layer each smaller part of a pair should draw on, as a Map from part to layer. A part that is the smaller one against
- * a part already on layer n gets n + 1. Parts that set their own layer are left alone.
- * A chain deeper than MAXIMUM_DEPTH_LAYER would pile parts on the top layer, where they fight each other again at the largest
- * offset, so a part that cannot clear its larger part stays where it is. Layers are settled by repeating until nothing moves,
- * because parts of equal size have no order that a single sweep could follow.
- * A pair closer than `minimumGap` (metres, default 0: every pair counts) is skipped. resolveFlushParts passes
- * EXACT_FLUSH_DISTANCE: such a pair lies on one plane to within rounding, which a float depth buffer (reversed depth, the
- * default) already breaks the same way every frame, while an offset moves the whole part and made the metro film flicker far
- * more (issue #593: 5 to 7633 flagged pixels), so only pairs with a real gap get a layer there.
- */
-export function coplanarLayers(overlaps, { minimumGap = 0 } = {}) {
- const layers = new Map();
- for (let pass = 0; pass <= MAXIMUM_DEPTH_LAYER + 1; pass++) {
- let moved = false;
- for (const { smaller, larger, distance } of overlaps) {
- if (distance < minimumGap) continue;
- if (smaller.decal !== undefined || smaller.depthLayer !== undefined) continue;
- const wanted = (layers.get(larger) ?? depthLayerOf(larger)) + 1;
- if (wanted > MAXIMUM_DEPTH_LAYER || wanted <= (layers.get(smaller) ?? 0)) continue;
- layers.set(smaller, wanted);
- moved = true;
- }
- if (!moved) break;
- }
- return layers;
-}
-
/**
* 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.
@@ -500,21 +430,47 @@ export function installCoplanarDiagnostics(renderer, onOverlaps = null) {
}
/**
- * Puts the smaller part of each coplanar pair on the next depth layer (a polygon offset at draw time, geometry never moves),
- * for the parts of one scene. The renderer calls it once when it is built; a part that sets `decal` or `depthLayer` keeps its own.
- * Pairs on one plane to within `minimumGap` (default EXACT_FLUSH_DISTANCE) are left to the depth buffer; the renderer passes
- * `{ minimumGap: 0 }` when `reversedDepth` is false. With 'auto', a scene whose far / near ratio stays low never switches
- * reversed depth on, and there exact-flush pairs rely on the plain depth buffer.
+ * Ranks the near-coplanar triangles of one scene's parts, inside a part and across parts, so the face in front wins at every
+ * distance (a depth-only bias at draw time; geometry, parts and matrices are untouched). The renderer calls it once when it is
+ * built, as its `resolveCoplanar` option. Returns `{ ranked, leftovers }` (see resolveFlush in flush-resolve.js).
*/
-export function resolveFlushParts(parts, { minimumGap = EXACT_FLUSH_DISTANCE } = {}) {
- const layers = coplanarLayers(findCoplanarOverlaps(parts).overlaps, { minimumGap });
- setFlushDepthLayers(layers);
- return layers.size;
+export function resolveFlushParts(parts, options) {
+ return resolveFlush(parts, options);
+}
+
+/** Drops the ranks resolveFlushParts gave these parts, for a scene that switches the resolution off. */
+export function clearFlushParts(parts) {
+ for (const part of parts) setFlushOrder(part, null);
}
-/** `parts` with `depthLayer` set on the smaller part of each coplanar pair; other parts are returned as they are. */
-export function resolveCoplanarParts(parts) {
- const layers = coplanarLayers(findCoplanarOverlaps(parts).overlaps);
- if (layers.size === 0) return parts;
- return parts.map(part => (layers.has(part) ? Object.freeze({ ...part, depthLayer: layers.get(part) }) : part));
+const LEFTOVER_TEXT = {
+ 'rank-overflow': {
+ message: (part, triangles) => `${part}: ${triangles} triangles sit in stacks deeper than 15 near-coplanar faces and may flicker far away.`,
+ fix: 'Remove the duplicate faces in the asset.',
+ },
+ 'double-sided-gap': {
+ message: (part, triangles) => `${part}: ${triangles} pairs of double-sided faces lie a small gap apart, facing opposite ways, and may flicker far away.`,
+ fix: 'Make the material single sided, or move the faces farther apart.',
+ },
+ unchecked: {
+ message: part => `${part} was not checked for flush faces: the scene is past the search budget.`,
+ fix: 'Split the scene, or set decal: true on the parts that lie flush on others.',
+ },
+ 'collapsed-node': {
+ message: part => `${part} has an axis scaled to nothing, so its faces fold onto one plane and flicker.`,
+ fix: 'Hide the node instead of scaling it to zero.',
+ },
+};
+
+/** Warnings in the shape of `agent-diagnostics.js` for what resolveFlushParts could not settle, the largest first. */
+export function flushLeftoverDiagnostics(leftovers) {
+ const largestFirst = [...leftovers].sort((first, second) => second.triangles - first.triangles);
+ return largestFirst.slice(0, REPORTED_PAIRS).map(({ reason, part, triangles }) => ({
+ kind: 'coplanar-overlap',
+ severity: 'warning',
+ target: part,
+ reason,
+ message: LEFTOVER_TEXT[reason].message(part, triangles),
+ fix: LEFTOVER_TEXT[reason].fix,
+ }));
}
diff --git a/src/depth-layer.js b/src/depth-layer.js
index cd4f1085..8fe68148 100644
--- a/src/depth-layer.js
+++ b/src/depth-layer.js
@@ -1,15 +1,26 @@
-/** Highest depth layer; the draw-time polygon offset grows with the layer. */
+/** Highest depth layer a part can ask for with `depthLayer`. */
export const MAXIMUM_DEPTH_LAYER = 4;
+/** Draw ranks one depth layer spans: ranks 0 to 15 order near-coplanar triangles, and a layer clears all of them. */
+export const RANKS_PER_LAYER = 16;
+/** Highest rank the flush search gives a triangle; a deeper stack is reported as `rank-overflow`. */
+export const MAXIMUM_FLUSH_RANK = RANKS_PER_LAYER - 1;
-// Layers the renderer gave to parts that draw the same plane as a larger part (coplanar-overlap.js), kept beside the part
-// so the part object, and its identity for updateParts, stay as the caller made it.
-const flushDepthLayers = new WeakMap();
+// The draw order flush-resolve.js found for a part: `{ indices, ranges: [{ start, count, rank }] }`, the part's triangles
+// sorted by rank. It is kept beside the part so the part object, its geometry and its identity for updateParts stay as the
+// caller made them.
+const flushOrders = new WeakMap();
-export function setFlushDepthLayers(layers) {
- for (const [part, layer] of layers) flushDepthLayers.set(part, layer);
+export function setFlushOrder(part, order) {
+ if (order) flushOrders.set(part, order);
+ else flushOrders.delete(part);
}
-/** The layer a part draws on: `depthLayer` if set, else 1 for `decal: true`, else the flush layer found for it, else 0. */
+/** The ranked index order of a part, or null when none of its triangles needs a rank. */
+export function flushOrderOf(part) {
+ return flushOrders.get(part) ?? null;
+}
+
+/** The layer a part draws on: `depthLayer` if set, else 1 for `decal: true`, else 0. */
export function depthLayerOf(part) {
- return part.depthLayer ?? (part.decal ? 1 : flushDepthLayers.get(part) ?? 0);
+ return part.depthLayer ?? (part.decal ? 1 : 0);
}
diff --git a/src/flush-resolve.js b/src/flush-resolve.js
new file mode 100644
index 00000000..973c06db
--- /dev/null
+++ b/src/flush-resolve.js
@@ -0,0 +1,140 @@
+// Turns the pairs of flush-search.js into a draw rank per triangle (issue #751). The triangle in front along the shared
+// normal gets the higher rank, and the renderer pulls each rank a little closer in depth only, so the same triangle wins
+// every frame and at every distance. Ranks are per triangle, not per part: a whole-part offset moved faces that had no
+// conflict and made things worse (issue #593).
+import { depthLayerOf, MAXIMUM_FLUSH_RANK, setFlushOrder } from './depth-layer.js';
+import { findFlushPairs } from './flush-search.js';
+
+const COLLAPSED_AXIS_SHARE = 1e-3;
+
+// Which triangle of a pair draws in front. A real gap decides; on one plane the smaller triangle is the detail (a plaque,
+// a trim, a duplicate face) and wins, then the later one.
+function frontOf(pair, areas) {
+ if (!pair.flush) return pair.gap > 0 ? pair.second : pair.first;
+ if (areas[pair.first] !== areas[pair.second]) return areas[pair.first] < areas[pair.second] ? pair.first : pair.second;
+ return pair.second;
+}
+
+// Rank = the longest chain of triangles behind this one. Each pass lifts the front triangle of every pair above its back
+// triangle; a chain longer than the top rank (or a cycle of slightly tilted planes) stops there and is marked.
+function rankTriangles(count, edges) {
+ const ranks = new Uint8Array(count);
+ const overflow = new Uint8Array(count);
+ let moved = true;
+ for (let pass = 0; moved && pass <= MAXIMUM_FLUSH_RANK + 1; pass++) {
+ moved = false;
+ for (let edge = 0; edge < edges.length; edge += 2) {
+ const front = edges[edge + 1];
+ const wanted = ranks[edges[edge]] + 1;
+ if (wanted <= ranks[front]) continue;
+ if (wanted > MAXIMUM_FLUSH_RANK) {
+ overflow[front] = 1;
+ continue;
+ }
+ ranks[front] = wanted;
+ moved = true;
+ }
+ }
+ return { ranks, overflow };
+}
+
+function sameRanks(first, second) {
+ if (first.length !== second.length) return false;
+ for (let index = 0; index < first.length; index++) {
+ if (first[index] !== second[index]) return false;
+ }
+ return true;
+}
+
+// The geometry's indices sorted by rank (triangles of one rank keep their order) and the index range of each rank.
+function createFlushOrder(indices, triangleRanks) {
+ const counts = new Uint32Array(MAXIMUM_FLUSH_RANK + 1);
+ for (const rank of triangleRanks) counts[rank]++;
+ const starts = new Uint32Array(MAXIMUM_FLUSH_RANK + 1);
+ const ranges = [];
+ let start = 0;
+ for (let rank = 0; rank <= MAXIMUM_FLUSH_RANK; rank++) {
+ starts[rank] = start;
+ if (counts[rank] > 0) ranges.push({ start: start * 3, count: counts[rank] * 3, rank });
+ start += counts[rank];
+ }
+ const ordered = new Uint32Array(indices.length);
+ for (let triangle = 0; triangle < triangleRanks.length; triangle++) {
+ const target = starts[triangleRanks[triangle]]++ * 3;
+ ordered[target] = indices[triangle * 3];
+ ordered[target + 1] = indices[triangle * 3 + 1];
+ ordered[target + 2] = indices[triangle * 3 + 2];
+ }
+ return { indices: ordered, ranges, triangleRanks };
+}
+
+function hasCollapsedAxis(matrix) {
+ const lengths = [0, 4, 8].map(column => Math.hypot(matrix[column], matrix[column + 1], matrix[column + 2]));
+ return Math.min(...lengths) < COLLAPSED_AXIS_SHARE * Math.max(...lengths);
+}
+
+/**
+ * Finds the near-coplanar triangles of `parts` and stores a ranked draw order beside every part that needs one
+ * (`flushOrderOf(part)` in depth-layer.js); parts, geometries and matrices are left as they are. Parts that share a geometry
+ * and agree on every rank share one order, so they still batch. Returns `{ ranked, leftovers }`: the number of parts with an
+ * order, and what could not be settled as `{ reason, part, triangles }` with reason `rank-overflow` (a stack deeper than 15
+ * faces), `double-sided-gap`, `unchecked` (past the search budget) or `collapsed-node` (an axis scaled to nothing).
+ */
+export function resolveFlush(parts, options) {
+ const found = findFlushPairs(parts, options);
+ const { owner, local, areas, pairs, count } = found;
+ const leftovers = new Map();
+ const note = (reason, part, triangles = 1) => {
+ const key = `${reason}\n${part.name}`;
+ const entry = leftovers.get(key) ?? { reason, part: part.name, triangles: 0 };
+ entry.triangles += triangles;
+ leftovers.set(key, entry);
+ };
+ const edges = [];
+ for (const pair of pairs) {
+ const firstPart = found.parts[owner[pair.first]];
+ const secondPart = found.parts[owner[pair.second]];
+ // Parts on different layers are already a whole layer of ranks apart.
+ if (depthLayerOf(firstPart) !== depthLayerOf(secondPart)) continue;
+ if (pair.opposite && !pair.flush) {
+ // Which of the two is in front depends on the side the camera is on, so no fixed rank is right.
+ note('double-sided-gap', secondPart);
+ continue;
+ }
+ const front = frontOf(pair, areas);
+ edges.push(front === pair.first ? pair.second : pair.first, front);
+ }
+ const { ranks, overflow } = rankTriangles(count, edges);
+ const partRanks = found.parts.map(() => null);
+ for (let id = 0; id < count; id++) {
+ if (overflow[id]) note('rank-overflow', found.parts[owner[id]]);
+ if (ranks[id] === 0) continue;
+ partRanks[owner[id]] ??= new Uint8Array(found.parts[owner[id]].geometry.indices.length / 3);
+ partRanks[owner[id]][local[id]] = ranks[id];
+ }
+ const ordersByGeometry = new Map();
+ const searched = new Map(found.parts.map((part, index) => [part, index]));
+ let ranked = 0;
+ for (const part of parts) {
+ const triangleRanks = searched.has(part) ? partRanks[searched.get(part)] : null;
+ if (!triangleRanks) {
+ setFlushOrder(part, null);
+ continue;
+ }
+ const orders = ordersByGeometry.get(part.geometry) ?? [];
+ ordersByGeometry.set(part.geometry, orders);
+ let order = orders.find(candidate => sameRanks(candidate.triangleRanks, triangleRanks));
+ if (!order) {
+ order = createFlushOrder(part.geometry.indices, triangleRanks);
+ orders.push(order);
+ }
+ setFlushOrder(part, order);
+ ranked++;
+ }
+ for (const part of found.unchecked) note('unchecked', part, part.geometry.indices.length / 3);
+ if (found.truncated) note('unchecked', { name: 'scene' }, 0);
+ for (const part of parts) {
+ if (part.matrix && part.geometry?.indices?.length && hasCollapsedAxis(part.matrix)) note('collapsed-node', part, part.geometry.indices.length / 3);
+ }
+ return { ranked, leftovers: [...leftovers.values()] };
+}
diff --git a/src/flush-search.js b/src/flush-search.js
new file mode 100644
index 00000000..988585a3
--- /dev/null
+++ b/src/flush-search.js
@@ -0,0 +1,488 @@
+// Finds pairs of triangles that draw the same plane in the same place (issue #751): inside one part and across parts, exactly
+// flush or a few millimetres to centimetres apart. Such pairs z-fight, since the rasteriser snaps two triangles on one plane to
+// slightly different depths. flush-resolve.js turns the pairs into a draw rank per triangle.
+//
+// Triangles are hashed by their normal (sign folded, so opposite faces meet) and by a grid over their boxes. A triangle is
+// native to the finest grid where it spans few cells and a guest in the coarser ones, so a wall of two triangles and the
+// thousand small faces on it meet without the wall being listed in a thousand cells. Nothing is cut short silently: parts
+// past the triangle budget come back in `unchecked`, and `truncated` says the pair budget ran out.
+
+/** Shared area under this share of the smaller triangle is edge contact or rounding, not a fight. */
+export const FLUSH_MINIMUM_AREA_SHARE = 1e-4;
+const FLUSH_MINIMUM_AREA = 1e-8;
+const DEFAULT_TRIANGLE_BUDGET = 2_000_000;
+const DEFAULT_PAIR_BUDGET = 4_000_000;
+const SAME_FACING = Math.cos(Math.PI / 180);
+// Normals one degree apart differ by at most 0.0175 per component. Each triangle is listed in every normal cell within half
+// of that, so two such triangles always share a cell.
+const NORMAL_STEPS = 20;
+const NORMAL_REACH = 0.0088;
+const NORMAL_RANGE = 2 * NORMAL_STEPS + 3;
+const NEAR_DOMINANT = 0.02;
+const NATIVE_CELL_LIMIT = 64;
+const GRID_LEVEL_SCALE = 16;
+const GRID_LEVELS = 2;
+const CELL_SAMPLES = 4096;
+// Tags whose vertex shader moves vertices (renderer.js DEFORMING_TAGS): their triangles are not where the geometry says.
+const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);
+
+const localBoundsByGeometry = new WeakMap();
+
+export function localBounds(geometry) {
+ let bounds = localBoundsByGeometry.get(geometry);
+ if (bounds) return bounds;
+ bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
+ const { positions } = geometry;
+ for (let offset = 0; offset < positions.length; offset += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ bounds[axis] = Math.min(bounds[axis], positions[offset + axis]);
+ bounds[3 + axis] = Math.max(bounds[3 + axis], positions[offset + axis]);
+ }
+ }
+ localBoundsByGeometry.set(geometry, bounds);
+ return bounds;
+}
+
+export function worldBounds(part) {
+ const local = localBounds(part.geometry);
+ const matrix = part.matrix;
+ const bounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
+ for (let corner = 0; corner < 8; corner++) {
+ const x = corner & 1 ? local[3] : local[0];
+ const y = corner & 2 ? local[4] : local[1];
+ const z = corner & 4 ? local[5] : local[2];
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * x + matrix[4 + axis] * y + matrix[8 + axis] * z + matrix[12 + axis];
+ bounds[axis] = Math.min(bounds[axis], value);
+ bounds[3 + axis] = Math.max(bounds[3 + axis], value);
+ }
+ }
+ return bounds;
+}
+
+export function determinantSign(matrix) {
+ const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[6] * matrix[9])
+ - matrix[4] * (matrix[1] * matrix[10] - matrix[2] * matrix[9])
+ + matrix[8] * (matrix[1] * matrix[6] - matrix[2] * matrix[5]);
+ return determinant < 0 ? -1 : 1;
+}
+
+export function boundsDiagonal(bounds) {
+ return Math.hypot(bounds[3] - bounds[0], bounds[4] - bounds[1], bounds[5] - bounds[2]);
+}
+
+/** Planes closer than this (metres) are one plane: 0.1 mm, or eight float32 steps of the largest coordinate when that is more. */
+export function flushTolerance(largestCoordinate) {
+ const step = 2 ** (Math.floor(Math.log2(Math.max(largestCoordinate, 1e-30))) - 23);
+ return Math.max(1e-4, 8 * step);
+}
+
+/** Same-facing planes up to this far apart (metres) can still fight far from the camera; `diagonal` spans both parts. */
+export function nearTolerance(diagonal) {
+ return Math.min(0.25, Math.max(0.002, 1.5e-4 * diagonal));
+}
+
+/** Whether a part's drawn triangles leave its geometry (skin, morph, crowd, wind, liquid), so a search of the geometry says nothing. */
+export function isDeformingPart(part) {
+ const { geometry, material } = part;
+ if (part.skin || part.morph || part.crowd || geometry.skinIndices || geometry.morphTargets) return true;
+ return DEFORMING_TAGS.has(material?.tag) || material?.transmission > 0;
+}
+
+// Parts with one geometry and one matrix are stacked copies (hundreds of dust motes parked at one spot). They draw the same
+// depth bit for bit, so two of them stand for the stack.
+function searchableParts(parts) {
+ const stacks = new Map();
+ const searchable = [];
+ for (const part of parts) {
+ if (!part.geometry?.indices?.length || isDeformingPart(part)) continue;
+ const stack = stacks.get(part.geometry) ?? new Map();
+ stacks.set(part.geometry, stack);
+ const pose = Array.prototype.join.call(part.matrix, ',');
+ const copies = stack.get(pose) ?? 0;
+ if (copies >= 2) continue;
+ stack.set(pose, copies + 1);
+ searchable.push(part);
+ }
+ return searchable;
+}
+
+// Past the budget the largest parts are searched, since a large flush face is the one people see; the rest is `unchecked`.
+function withinTriangleBudget(parts, triangleBudget) {
+ const entries = parts.map((part, order) => ({ part, order, bounds: worldBounds(part), triangles: part.geometry.indices.length / 3 }));
+ const total = entries.reduce((sum, entry) => sum + entry.triangles, 0);
+ if (total <= triangleBudget) return { entries, unchecked: [] };
+ const bySize = [...entries].sort((first, second) => boundsDiagonal(second.bounds) - boundsDiagonal(first.bounds));
+ const kept = [];
+ const unchecked = [];
+ let used = 0;
+ for (const entry of bySize) {
+ if (used + entry.triangles <= triangleBudget) {
+ used += entry.triangles;
+ kept.push(entry);
+ } else {
+ unchecked.push(entry.part);
+ }
+ }
+ kept.sort((first, second) => first.order - second.order);
+ return { entries: kept, unchecked };
+}
+
+// World-space corners (9 numbers), unit normal (3), box (6) and area of every non-degenerate triangle, part after part.
+function readTriangles(entries) {
+ const capacity = entries.reduce((sum, entry) => sum + entry.triangles, 0);
+ const table = {
+ count: 0,
+ corners: new Float64Array(capacity * 9),
+ normals: new Float64Array(capacity * 3),
+ boxes: new Float64Array(capacity * 6),
+ areas: new Float64Array(capacity),
+ owner: new Uint32Array(capacity),
+ local: new Uint32Array(capacity),
+ };
+ entries.forEach((entry, partIndex) => readPartTriangles(table, entry.part, partIndex));
+ return table;
+}
+
+function readPartTriangles(table, part, partIndex) {
+ const { positions, indices } = part.geometry;
+ const matrix = part.matrix;
+ const flip = determinantSign(matrix);
+ const { corners, normals, boxes } = table;
+ for (let triangle = 0; triangle < indices.length; triangle += 3) {
+ const base = table.count * 9;
+ for (let corner = 0; corner < 3; corner++) {
+ const vertex = indices[triangle + corner] * 3;
+ const x = positions[vertex];
+ const y = positions[vertex + 1];
+ const z = positions[vertex + 2];
+ corners[base + corner * 3] = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];
+ corners[base + corner * 3 + 1] = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];
+ corners[base + corner * 3 + 2] = matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14];
+ }
+ const edgeOneX = corners[base + 3] - corners[base];
+ const edgeOneY = corners[base + 4] - corners[base + 1];
+ const edgeOneZ = corners[base + 5] - corners[base + 2];
+ const edgeTwoX = corners[base + 6] - corners[base];
+ const edgeTwoY = corners[base + 7] - corners[base + 1];
+ const edgeTwoZ = corners[base + 8] - corners[base + 2];
+ const normalX = edgeOneY * edgeTwoZ - edgeOneZ * edgeTwoY;
+ const normalY = edgeOneZ * edgeTwoX - edgeOneX * edgeTwoZ;
+ const normalZ = edgeOneX * edgeTwoY - edgeOneY * edgeTwoX;
+ const length = Math.hypot(normalX, normalY, normalZ);
+ if (!(length > 1e-12)) continue;
+ const id = table.count;
+ const scale = flip / length;
+ normals[id * 3] = normalX * scale;
+ normals[id * 3 + 1] = normalY * scale;
+ normals[id * 3 + 2] = normalZ * scale;
+ for (let axis = 0; axis < 3; axis++) {
+ const low = Math.min(corners[base + axis], corners[base + 3 + axis], corners[base + 6 + axis]);
+ const high = Math.max(corners[base + axis], corners[base + 3 + axis], corners[base + 6 + axis]);
+ boxes[id * 6 + axis] = low;
+ boxes[id * 6 + 3 + axis] = high;
+ }
+ table.areas[id] = length / 2;
+ table.owner[id] = partIndex;
+ table.local[id] = triangle / 3;
+ table.count++;
+ }
+}
+
+// Twice the median triangle extent: most triangles then touch a handful of cells.
+function gridCellSize(table, reach) {
+ const extents = [];
+ const stride = Math.max(1, Math.floor(table.count / CELL_SAMPLES));
+ for (let id = 0; id < table.count; id += stride) {
+ const box = id * 6;
+ extents.push(Math.max(table.boxes[box + 3] - table.boxes[box], table.boxes[box + 4] - table.boxes[box + 1], table.boxes[box + 5] - table.boxes[box + 2]));
+ }
+ extents.sort((first, second) => first - second);
+ return Math.max(2 * extents[extents.length >> 1], 4 * reach, 1e-6);
+}
+
+// The normal cells a triangle is listed in. The sign is folded by the dominant component; when another component is nearly
+// as large and has the other sign, both folds are listed, so two near-equal normals never fold apart.
+function normalCellsOf(table, id, cells) {
+ const x = table.normals[id * 3];
+ const y = table.normals[id * 3 + 1];
+ const z = table.normals[id * 3 + 2];
+ const largest = Math.max(Math.abs(x), Math.abs(y), Math.abs(z));
+ let positive = false;
+ let negative = false;
+ for (const component of [x, y, z]) {
+ if (Math.abs(component) < largest - NEAR_DOMINANT) continue;
+ if (component < 0) negative = true;
+ else positive = true;
+ }
+ cells.length = 0;
+ for (const sign of [1, -1]) {
+ if (sign > 0 ? !positive : !negative) continue;
+ const lowX = Math.round((x * sign - NORMAL_REACH) * NORMAL_STEPS);
+ const highX = Math.round((x * sign + NORMAL_REACH) * NORMAL_STEPS);
+ const lowY = Math.round((y * sign - NORMAL_REACH) * NORMAL_STEPS);
+ const highY = Math.round((y * sign + NORMAL_REACH) * NORMAL_STEPS);
+ const lowZ = Math.round((z * sign - NORMAL_REACH) * NORMAL_STEPS);
+ const highZ = Math.round((z * sign + NORMAL_REACH) * NORMAL_STEPS);
+ for (let cellX = lowX; cellX <= highX; cellX++) {
+ for (let cellY = lowY; cellY <= highY; cellY++) {
+ for (let cellZ = lowZ; cellZ <= highZ; cellZ++) {
+ const cell = ((cellX + NORMAL_STEPS + 1) * NORMAL_RANGE + cellY + NORMAL_STEPS + 1) * NORMAL_RANGE + cellZ + NORMAL_STEPS + 1;
+ if (!cells.includes(cell)) cells.push(cell);
+ }
+ }
+ }
+ }
+ return cells;
+}
+
+const cellRange = new Int32Array(6);
+
+// The grid cells a triangle's box touches at one level, grown by half the reach so two boxes within the reach share a cell.
+// Returns how many cells that is.
+function cellRangeOf(table, id, cellSize, reach) {
+ let cells = 1;
+ for (let axis = 0; axis < 3; axis++) {
+ const low = Math.floor((table.boxes[id * 6 + axis] - reach / 2) / cellSize);
+ const high = Math.floor((table.boxes[id * 6 + 3 + axis] + reach / 2) / cellSize);
+ cellRange[axis] = low;
+ cellRange[3 + axis] = high;
+ cells *= high - low + 1;
+ }
+ return cells;
+}
+
+function cellKey(normalCell, level, cellX, cellY, cellZ) {
+ const mixed = Math.imul(cellX, 73856093) ^ Math.imul(cellY, 19349663) ^ Math.imul(cellZ, 83492791) ^ Math.imul(normalCell * GRID_LEVELS + level, 0x9e3779b1);
+ return mixed >>> 0;
+}
+
+// Lists every triangle in the cells of its own level (`natives`), then as a guest in the coarser cells that hold a native.
+// The last level is one cell per normal cell, for triangles too large for any grid.
+function buildCells(table, cellSize, reach) {
+ const levels = Array.from({ length: GRID_LEVELS + 1 }, () => new Map());
+ const nativeLevel = new Uint8Array(table.count);
+ const normalCells = [];
+ const visitCells = (id, level, visit) => {
+ normalCellsOf(table, id, normalCells);
+ if (level === GRID_LEVELS) {
+ for (const normalCell of normalCells) visit(normalCell);
+ return;
+ }
+ cellRangeOf(table, id, cellSize * GRID_LEVEL_SCALE ** level, reach);
+ const [lowX, lowY, lowZ, highX, highY, highZ] = cellRange;
+ for (const normalCell of normalCells) {
+ for (let cellX = lowX; cellX <= highX; cellX++) {
+ for (let cellY = lowY; cellY <= highY; cellY++) {
+ for (let cellZ = lowZ; cellZ <= highZ; cellZ++) visit(cellKey(normalCell, level, cellX, cellY, cellZ));
+ }
+ }
+ }
+ };
+ for (let id = 0; id < table.count; id++) {
+ let level = 0;
+ while (level < GRID_LEVELS && cellRangeOf(table, id, cellSize * GRID_LEVEL_SCALE ** level, reach) > NATIVE_CELL_LIMIT) level++;
+ nativeLevel[id] = level;
+ const cells = levels[level];
+ visitCells(id, level, key => {
+ const cell = cells.get(key);
+ if (cell) cell.natives.push(id);
+ else cells.set(key, { natives: [id], guests: [] });
+ });
+ }
+ for (let id = 0; id < table.count; id++) {
+ for (let level = nativeLevel[id] + 1; level <= GRID_LEVELS; level++) {
+ const cells = levels[level];
+ if (cells.size === 0) continue;
+ visitCells(id, level, key => cells.get(key)?.guests.push(id));
+ }
+ }
+ return levels.flatMap(cells => [...cells.values()]);
+}
+
+const clipFirst = new Float64Array(32);
+const clipSecond = new Float64Array(32);
+const sharedCentre = new Float64Array(2);
+
+// Clips triangle `second` against triangle `first` on the plane's two largest axes (Sutherland-Hodgman). Returns the shared
+// area in square metres and leaves the centre of the shared piece in `sharedCentre`.
+function sharedArea(table, first, second, dropped, axisU, axisV) {
+ const { corners, normals } = table;
+ let polygon = clipFirst;
+ let next = clipSecond;
+ let size = 3;
+ for (let corner = 0; corner < 3; corner++) {
+ polygon[corner * 2] = corners[second * 9 + corner * 3 + axisU];
+ polygon[corner * 2 + 1] = corners[second * 9 + corner * 3 + axisV];
+ }
+ const base = first * 9;
+ const turn = (corners[base + 3 + axisU] - corners[base + axisU]) * (corners[base + 6 + axisV] - corners[base + axisV])
+ - (corners[base + 3 + axisV] - corners[base + axisV]) * (corners[base + 6 + axisU] - corners[base + axisU]) >= 0 ? 1 : -1;
+ for (let edge = 0; edge < 3 && size > 0; edge++) {
+ const startU = corners[base + edge * 3 + axisU];
+ const startV = corners[base + edge * 3 + axisV];
+ const edgeU = corners[base + ((edge + 1) % 3) * 3 + axisU] - startU;
+ const edgeV = corners[base + ((edge + 1) % 3) * 3 + axisV] - startV;
+ let nextSize = 0;
+ let previousU = polygon[size * 2 - 2];
+ let previousV = polygon[size * 2 - 1];
+ let previousSide = turn * (edgeU * (previousV - startV) - edgeV * (previousU - startU));
+ for (let index = 0; index < size; index++) {
+ const currentU = polygon[index * 2];
+ const currentV = polygon[index * 2 + 1];
+ const currentSide = turn * (edgeU * (currentV - startV) - edgeV * (currentU - startU));
+ if ((currentSide >= 0) !== (previousSide >= 0)) {
+ const along = previousSide / (previousSide - currentSide);
+ next[nextSize * 2] = previousU + (currentU - previousU) * along;
+ next[nextSize * 2 + 1] = previousV + (currentV - previousV) * along;
+ nextSize++;
+ }
+ if (currentSide >= 0) {
+ next[nextSize * 2] = currentU;
+ next[nextSize * 2 + 1] = currentV;
+ nextSize++;
+ }
+ previousU = currentU;
+ previousV = currentV;
+ previousSide = currentSide;
+ }
+ const swap = polygon;
+ polygon = next;
+ next = swap;
+ size = nextSize;
+ }
+ if (size < 3) return 0;
+ let doubled = 0;
+ let centreU = 0;
+ let centreV = 0;
+ for (let index = 0; index < size; index++) {
+ const following = (index + 1) % size;
+ doubled += polygon[index * 2] * polygon[following * 2 + 1] - polygon[following * 2] * polygon[index * 2 + 1];
+ centreU += polygon[index * 2];
+ centreV += polygon[index * 2 + 1];
+ }
+ sharedCentre[0] = centreU / size;
+ sharedCentre[1] = centreV / size;
+ return Math.abs(doubled) / 2 / Math.max(Math.abs(normals[first * 3 + dropped]), 1e-12);
+}
+
+// Where a triangle's plane sits along the dropped axis above the point (u, v).
+function planeHeight(table, id, dropped, axisU, axisV, u, v) {
+ const { corners, normals } = table;
+ const slope = normals[id * 3 + axisU] * (u - corners[id * 9 + axisU]) + normals[id * 3 + axisV] * (v - corners[id * 9 + axisV]);
+ return corners[id * 9 + dropped] - slope / normals[id * 3 + dropped];
+}
+
+function createPairTest(table, entries, reach, pairBudget, result) {
+ const { corners, normals, boxes, areas, owner } = table;
+ const seen = new Set();
+ const tolerances = new Map();
+ const pairTolerance = (firstPart, secondPart) => {
+ const key = Math.min(firstPart, secondPart) * entries.length + Math.max(firstPart, secondPart);
+ let tolerance = tolerances.get(key);
+ if (tolerance === undefined) {
+ const first = entries[firstPart].bounds;
+ const second = entries[secondPart].bounds;
+ tolerance = nearTolerance(Math.hypot(
+ Math.max(first[3], second[3]) - Math.min(first[0], second[0]),
+ Math.max(first[4], second[4]) - Math.min(first[1], second[1]),
+ Math.max(first[5], second[5]) - Math.min(first[2], second[2]),
+ ));
+ tolerances.set(key, tolerance);
+ }
+ return tolerance;
+ };
+ return function testPair(one, other) {
+ // Two cells of one triangle can hash to one key, which lists it twice.
+ if (one === other) return;
+ const first = Math.min(one, other);
+ const second = Math.max(one, other);
+ for (let axis = 0; axis < 3; axis++) {
+ if (boxes[first * 6 + 3 + axis] < boxes[second * 6 + axis] - reach) return;
+ if (boxes[second * 6 + 3 + axis] < boxes[first * 6 + axis] - reach) return;
+ }
+ const normalX = normals[first * 3];
+ const normalY = normals[first * 3 + 1];
+ const normalZ = normals[first * 3 + 2];
+ const facing = normalX * normals[second * 3] + normalY * normals[second * 3 + 1] + normalZ * normals[second * 3 + 2];
+ if (Math.abs(facing) < SAME_FACING) return;
+ const opposite = facing < 0;
+ // A face against a floor looks away from it and is culled, unless one of the two shows both sides.
+ if (opposite && entries[owner[first]].part.material?.doubleSided !== true && entries[owner[second]].part.material?.doubleSided !== true) return;
+ const tolerance = pairTolerance(owner[first], owner[second]);
+ for (let corner = 0; corner < 3; corner++) {
+ const distance = (corners[second * 9 + corner * 3] - corners[first * 9]) * normalX
+ + (corners[second * 9 + corner * 3 + 1] - corners[first * 9 + 1]) * normalY
+ + (corners[second * 9 + corner * 3 + 2] - corners[first * 9 + 2]) * normalZ;
+ if (Math.abs(distance) > tolerance) return;
+ }
+ const pairKey = first * table.count + second;
+ if (seen.has(pairKey)) return;
+ seen.add(pairKey);
+ const absoluteX = Math.abs(normalX);
+ const absoluteY = Math.abs(normalY);
+ const absoluteZ = Math.abs(normalZ);
+ let dropped = 0;
+ if (absoluteY > absoluteX && absoluteY >= absoluteZ) dropped = 1;
+ else if (absoluteZ > absoluteX && absoluteZ > absoluteY) dropped = 2;
+ const axisU = (dropped + 1) % 3;
+ const axisV = (dropped + 2) % 3;
+ const area = sharedArea(table, first, second, dropped, axisU, axisV);
+ if (area < Math.max(FLUSH_MINIMUM_AREA, FLUSH_MINIMUM_AREA_SHARE * Math.min(areas[first], areas[second]))) return;
+ if (result.pairs.length >= pairBudget) {
+ result.truncated = true;
+ return;
+ }
+ const lift = planeHeight(table, second, dropped, axisU, axisV, sharedCentre[0], sharedCentre[1]) - planeHeight(table, first, dropped, axisU, axisV, sharedCentre[0], sharedCentre[1]);
+ const gap = lift * normals[first * 3 + dropped];
+ // The two planes are one plane when the gap is within the rounding of the coordinates of these two triangles, not of the
+ // whole scene: a far backdrop must not blur the order of faces near the origin.
+ let largestCoordinate = 0;
+ for (let value = 0; value < 6; value++) largestCoordinate = Math.max(largestCoordinate, Math.abs(boxes[first * 6 + value]), Math.abs(boxes[second * 6 + value]));
+ result.pairs.push({ first, second, gap, area, opposite, flush: Math.abs(gap) <= flushTolerance(largestCoordinate) });
+ };
+}
+
+// Natives are swept along x against each other; every native is also tested against every guest of the cell.
+function testCell(cell, boxes, reach, testPair) {
+ const { natives, guests } = cell;
+ if (natives.length > 2) natives.sort((first, second) => boxes[first * 6] - boxes[second * 6]);
+ for (let index = 0; index < natives.length; index++) {
+ const native = natives[index];
+ const end = boxes[native * 6 + 3] + reach;
+ for (let other = index + 1; other < natives.length; other++) {
+ if (boxes[natives[other] * 6] > end) break;
+ testPair(native, natives[other]);
+ }
+ for (let other = 0; other < guests.length; other++) testPair(native, guests[other]);
+ }
+}
+
+/**
+ * Pairs of triangles that draw the same plane in the same place. A part is `{ name, geometry: { positions, indices }, matrix,
+ * material? }`; deforming parts (isDeformingPart) are left out. Returns `{ parts, count, owner, local, areas, pairs, unchecked,
+ * truncated }`: `pairs` holds `{ first, second, gap, area, opposite, flush }` with triangle ids below `count`, `owner[id]` the
+ * index into `parts` and `local[id]` the triangle inside that part's geometry. `gap` is in metres along the first triangle's
+ * normal, positive when the second triangle is in front of it; `flush` says the gap is within rounding (flushTolerance), so the
+ * two lie on one plane; `opposite` marks a pair that faces opposite ways (one part is double sided). `unchecked` lists parts
+ * past `triangleBudget`.
+ */
+export function findFlushPairs(parts, { triangleBudget = DEFAULT_TRIANGLE_BUDGET, pairBudget = DEFAULT_PAIR_BUDGET } = {}) {
+ const { entries, unchecked } = withinTriangleBudget(searchableParts(parts), triangleBudget);
+ const table = readTriangles(entries);
+ const result = { parts: entries.map(entry => entry.part), count: table.count, owner: table.owner, local: table.local, areas: table.areas, pairs: [], unchecked, truncated: false };
+ if (table.count < 2) return result;
+ const sceneBounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
+ for (const { bounds } of entries) {
+ for (let axis = 0; axis < 3; axis++) {
+ sceneBounds[axis] = Math.min(sceneBounds[axis], bounds[axis]);
+ sceneBounds[3 + axis] = Math.max(sceneBounds[3 + axis], bounds[3 + axis]);
+ }
+ }
+ // No pair of parts spans more than the scene, so this is the widest gap any pair is tested with.
+ const reach = nearTolerance(boundsDiagonal(sceneBounds));
+ const testPair = createPairTest(table, entries, reach, pairBudget, result);
+ for (const cell of buildCells(table, gridCellSize(table, reach), reach)) testCell(cell, table.boxes, reach, testPair);
+ result.pairs.sort((first, second) => first.first - second.first || first.second - second.second);
+ return result;
+}
diff --git a/src/renderer.js b/src/renderer.js
index c14bd0ed..879912a5 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -10,7 +10,7 @@ import { fittedNearPlane, sceneBoundsOfParts } from './near-plane-fit.js';
import { installReversedDepth, prepareCameraRelativeProgram } from './reversed-depth.js';
import { resolveEffects } from './effects.js';
import { frameDiagnostics } from './frame-diagnostics.js';
-import { depthLayerOf } from './depth-layer.js';
+import { depthLayerOf, flushOrderOf, RANKS_PER_LAYER } from './depth-layer.js';
import { createLightingState, updateLightingState } from './lighting.js';
import { RenderTargetLedger } from './render-target-ledger.js';
import { SHADOW_ATLAS_WIDTH, SHADOW_TILE_SIZE, SHADOW_TILES_PER_ROW, tileViewport, writeShadowTile } from './local-shadows.js';
@@ -48,6 +48,13 @@ const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain'
// Tags whose vertices sway in the wind; the shadow pass must be redrawn when time moves.
const SWAYING_TAGS = new Set(['foliage', 'grass']);
+// One depth rank (applyDepthRank): 0.1 mm, plus 2^-19 of the distance (2 mm at 1 km), plus a quarter of a subpixel of
+// slope. On the 24-bit fallback a rank also moves two depth steps, since that buffer cannot hold the metric step far away.
+const FLUSH_STEP = 1e-4;
+const FLUSH_RELATIVE_STEP = 2 ** -19;
+const FLUSH_CLIP_STEP = 2 ** -22;
+const FLUSH_SLOPE_STEP = 4 / 256;
+const clipPerMetreScratch = new Float32Array(4);
// Tags whose vertex shader moves vertices away from the instance matrix, so a bounding sphere would not hold.
const DEFORMING_TAGS = new Set(['foliage', 'grass', 'water', 'fire', 'smoke']);
// The farthest a vertex of a swaying tag moves in the world, per unit of wind strength (windOffset in shaders.js): foliage
@@ -420,7 +427,7 @@ export function groupParts(parts, batching = true) {
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialAlphaState(part.material), part.material.aovMap ?? null, part.material.transmissionMap ?? null, ...(part.material.aov ?? ZERO_VECTOR)]) {
+ for (const value of [...materialMapState(part.material), ...materialLayerState(part.material), part.skin ?? null, part.material.snippet, part.crowd ?? null, part.morph ?? null, castsShadow(part), receivesShadow(part), compositeModeOf(part), depthLayerOf(part), flushOrderOf(part), renderPass(part.material), part.lods ?? null, part.shadowLods ?? null, isMirroredMatrix(part.matrix), ...materialAlphaState(part.material), part.material.aovMap ?? null, part.material.transmissionMap ?? null, ...(part.material.aov ?? ZERO_VECTOR)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@ -612,9 +619,9 @@ export class Renderer67 {
// The shadow map the constructor draws uses no assembly, so a first frame with none does not draw it again.
this.assemblyAmount = 0;
// `resolveCoplanar` is resolveFlushParts from the coplanar-overlap addon, passed in so the search stays out of the core bundle.
+ // It ranks near-coplanar triangles (flushOrderOf in depth-layer.js) before the parts are grouped into batches.
if (resolveCoplanar && typeof resolveCoplanar !== 'function') throw new TypeError('resolveCoplanar is resolveFlushParts from 67js/addons/coplanar-overlap.');
- // Exact-flush pairs are left to a float depth buffer, so they are layered only when reversed depth is switched off.
- if (resolveCoplanar && !benchmark) resolveCoplanar(parts, reversedDepth === false && { minimumGap: 0 });
+ if (resolveCoplanar && !benchmark) resolveCoplanar(parts);
this.fitParts = this.groundPart ? [...parts, this.groundPart] : parts;
const groups = groupParts(this.fitParts, batching);
const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);
@@ -798,7 +805,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'flushBias', 'clipPerMetre', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -1018,6 +1025,7 @@ export class Renderer67 {
const vertexArray = context.createVertexArray();
context.bindVertexArray(vertexArray);
this.bindGeometryAttributes(geometry, batch.parts[0].material);
+ if (batch.flushIndexBuffer && levelSet === batch && level === 0) context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, batch.flushIndexBuffer);
const instanceBuffer = context.createBuffer();
this.buffers.push(instanceBuffer);
context.bindBuffer(context.ARRAY_BUFFER, instanceBuffer);
@@ -1051,7 +1059,7 @@ export class Renderer67 {
});
}
- drawSelectedLevels(batch, selection, levelSet = batch) {
+ drawSelectedLevels(batch, selection, levelSet = batch, flushRanges = null) {
const context = this.context;
const stride = INSTANCE_STRIDE;
for (let level = 0; level < selection.counts.length; level++) {
@@ -1066,15 +1074,31 @@ export class Renderer67 {
context.bindBuffer(context.ARRAY_BUFFER, draw.instanceBuffer);
context.bufferSubData(context.ARRAY_BUFFER, 0, this.selectionScratch, 0, count * stride);
context.bindVertexArray(draw.vertexArray);
- context.drawElementsInstanced(context.TRIANGLES, draw.indexCount, context.UNSIGNED_INT, 0, count);
+ // Only level 0 holds the ranked index order; the simpler levels draw far away, as one range.
+ if (flushRanges && level === 0) this.drawFlushRanges(batch, flushRanges, count);
+ else context.drawElementsInstanced(context.TRIANGLES, draw.indexCount, context.UNSIGNED_INT, 0, count);
}
}
+ /** Draws a batch rank by rank from its ranked index order (flush-resolve.js), each rank a little closer in depth. */
+ drawFlushRanges(batch, ranges, instanceCount) {
+ const context = this.context;
+ const base = (batch.depthLayer ?? 0) * RANKS_PER_LAYER;
+ for (const range of ranges) {
+ this.applyDepthRank(base + range.rank);
+ context.drawElementsInstanced(context.TRIANGLES, range.count, context.UNSIGNED_INT, range.start * 4, instanceCount);
+ }
+ this.applyDepthRank(base);
+ }
+
uploadBatchData(parts, vertexArray) {
const context = this.context;
const geometry = parts[0].geometry;
context.bindVertexArray(vertexArray);
this.bindGeometryAttributes(geometry, parts[0].material);
+ // The ranked order replaces the geometry's index buffer in this vertex array only; the vertex buffers stay shared.
+ const flushOrder = flushOrderOf(parts[0]);
+ const flushIndexBuffer = flushOrder ? this.uploadBuffer(context.ELEMENT_ARRAY_BUFFER, flushOrder.indices) : null;
const stride = INSTANCE_STRIDE;
const instanceData = new Float32Array(parts.length * stride);
const normalMatrix = mat3.create();
@@ -1102,7 +1126,7 @@ export class Renderer67 {
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), pass: renderPass(parts[0].material) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: renderPass(parts[0].material) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
@@ -1131,7 +1155,7 @@ export class Renderer67 {
const mapState = materialMapState(first.material);
const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);
const alphaState = materialAlphaState(first.material);
- const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) && batch.receivesShadow === receivesShadow(first) && batch.compositeMode === compositeModeOf(first) && (batch.depthLayer ?? 0) === depthLayerOf(first) &&
+ const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) && batch.receivesShadow === receivesShadow(first) && batch.compositeMode === compositeModeOf(first) && (batch.depthLayer ?? 0) === depthLayerOf(first) && (batch.flushOrder ?? null) === flushOrderOf(first) &&
batch.floor === (first.material.tag === 'floor') && batchPass(batch) === renderPass(first.material) &&
[batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided].every((value, index) => value === alphaState[index]) &&
batch.mapState.every((value, index) => value === mapState[index]) &&
@@ -1207,6 +1231,7 @@ export class Renderer67 {
if (!retained.has(batch)) {
this.context.deleteVertexArray(batch.vertexArray);
releasedBuffers.add(batch.instanceBuffer);
+ if (batch.flushIndexBuffer) releasedBuffers.add(batch.flushIndexBuffer);
this.releaseLevelDraws(batch, releasedBuffers);
}
}
@@ -2008,7 +2033,7 @@ export class Renderer67 {
}
return;
}
- this.applyDepthLayer(batch.depthLayer);
+ this.applyDepthRank((batch.depthLayer ?? 0) * RANKS_PER_LAYER);
const useCoverage = masked && this.samples > 1 && !this.benchmark && !this.renderingPass;
if (useCoverage) {
context.enable(context.SAMPLE_ALPHA_TO_COVERAGE);
@@ -2023,17 +2048,33 @@ export class Renderer67 {
context.uniform1f(uniforms.doubleSided, batch.doubleSided ? 1 : 0);
}
- /** Sets the scoped polygon offset of a depth layer for the colour pass; layer 0 is the plain depth test. */
- applyDepthLayer(layer) {
+ /**
+ * Pulls what draws next `rank` steps toward the eye, in depth only, for the colour pass; rank 0 is the plain depth test.
+ * A step is a view-space distance (FLUSH_STEP metres plus FLUSH_RELATIVE_STEP of the depth), so it separates two faces the
+ * same way on every depth format, plus a slope-only polygon offset for the depth the rasteriser's snapping adds on a
+ * grazing face. `towardEye` is the sign of nearer depth values: -1 for standard depth, 1 for reversed depth.
+ */
+ applyDepthRank(rank, towardEye = -1) {
const context = this.context;
- if (layer) {
+ context.uniform3f(this.uniforms.flushBias, rank * FLUSH_STEP, rank * FLUSH_RELATIVE_STEP, towardEye < 0 && rank ? -rank * FLUSH_CLIP_STEP : 0);
+ if (rank) {
context.enable(context.POLYGON_OFFSET_FILL);
- context.polygonOffset(-layer, -layer * 4);
+ context.polygonOffset(towardEye * rank * FLUSH_SLOPE_STEP, 0);
} else {
context.disable(context.POLYGON_OFFSET_FILL);
}
}
+ /** Tells the main program how clip space moves per metre along the view direction, for the depth ranks. */
+ setFlushProjection(viewProjection) {
+ const view = this.view;
+ const forward = [-view[2], -view[6], -view[10]];
+ for (let row = 0; row < 4; row++) {
+ clipPerMetreScratch[row] = viewProjection[row] * forward[0] + viewProjection[4 + row] * forward[1] + viewProjection[8 + row] * forward[2];
+ }
+ this.context.uniform4fv(this.uniforms.clipPerMetre, clipPerMetreScratch);
+ }
+
/** Reorders a blend batch's instances back to front for this eye; translation columns stand in for object centers. */
uploadSortedInstances(batch, eye) {
if (batch.instanceCount < 2) return;
@@ -2102,7 +2143,7 @@ export class Renderer67 {
for (const batch of addBatches) this.drawAlphaBatch(batch, true);
}
context.depthMask(true);
- this.applyDepthLayer(0);
+ this.applyDepthRank(0);
context.disable(context.BLEND);
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
@@ -2190,11 +2231,14 @@ export class Renderer67 {
if (textured && !this.benchmark && this.shaderFeatures?.has('instanced') === false)this.setSingleInstanceUniforms(batch.instanceData);
// A reflecting matrix reverses screen winding: clockwise triangles are the front faces of a mirrored batch.
if (batch.mirrored) this.context.frontFace(this.context.CW);
+ // The shadow pass (not textured) draws the whole index buffer; its order does not matter there.
+ const flushRanges = textured && !this.benchmark ? batch.flushOrder?.ranges ?? null : null;
if (selection && !selection.isEverything) {
- this.drawSelectedLevels(batch, selection, levelSet);
+ this.drawSelectedLevels(batch, selection, levelSet, levelSet === batch ? flushRanges : null);
} else {
this.context.bindVertexArray(batch.vertexArray);
- this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);
+ if (flushRanges) this.drawFlushRanges(batch, flushRanges, batch.instanceCount);
+ else this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);
}
if (batch.mirrored) this.context.frontFace(this.context.CCW);
}
@@ -2286,6 +2330,7 @@ export class Renderer67 {
context.enable(context.CULL_FACE);
context.useProgram(this.program);
context.uniformMatrix4fv(this.uniforms.viewProjection, false, this.viewProjection);
+ this.setFlushProjection(this.viewProjection);
context.uniformMatrix4fv(this.uniforms.lightProjection, false, this.lightProjection);
context.uniform1f(this.uniforms.shadowBiasPerSlope, this.shadowBiasPerSlope);
context.uniform3fv(this.uniforms.eye, eye);
@@ -2336,7 +2381,7 @@ export class Renderer67 {
else this.drawAlphaBatch(batch, true, passMode !== OBJECT_ID_PASS_MODE);
}
}
- this.applyDepthLayer(0);
+ this.applyDepthRank(0);
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
context.bindVertexArray(null);
diff --git a/src/reversed-depth.js b/src/reversed-depth.js
index d9090ba1..512c24e0 100644
--- a/src/reversed-depth.js
+++ b/src/reversed-depth.js
@@ -9,10 +9,6 @@ import { mat4 } from 'gl-matrix';
import { compileProgram, fullscreenVertex } from './gl-program.js';
import { shaderTransforms } from './shader-registry.js';
-// A float depth buffer resolves about 2^-23 of the value, so the constant part of a depth-layer offset moves a surface by well
-// under a micrometre, less than the rounding of a part's own matrix (issue #593: 2 um flush pairs kept flickering). The slope
-// part scales with the surface's own depth gradient, so it is the term that separates two flush faces; 16 cleared the metro film.
-const REVERSED_LAYER_SLOPE_SCALE = 16;
const ZERO_VECTOR = new Float32Array(4);
/**
@@ -174,7 +170,7 @@ export function installReversedDepth(renderer, mode = 'auto') {
const original = {
render: renderer.render,
applyEnvironmentUniforms: renderer.applyEnvironmentUniforms,
- applyDepthLayer: renderer.applyDepthLayer,
+ applyDepthRank: renderer.applyDepthRank,
resolveFrame: renderer.resolveFrame,
allocateFrameTargets: renderer.allocateFrameTargets,
};
@@ -216,6 +212,7 @@ export function installReversedDepth(renderer, mode = 'auto') {
reverseProjectionDepth(rasterProjection, renderer.projection);
mat4.multiply(rasterViewProjection, rasterProjection, renderer.view);
context.uniformMatrix4fv(renderer.uniforms.viewProjection, false, rasterViewProjection);
+ renderer.setFlushProjection(rasterViewProjection);
cameraOffset.set(frameEye);
cameraShift.set(rasterProjection.subarray(12, 16));
setCameraRelative(cameraOffset, cameraShift);
@@ -252,10 +249,9 @@ export function installReversedDepth(renderer, mode = 'auto') {
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 * REVERSED_LAYER_SLOPE_SCALE, layer * 4);
+ // Reversed depth grows toward the eye, so a depth rank pulls the other way there.
+ renderer.applyDepthRank = function applyDepthRankReversed(rank) {
+ original.applyDepthRank.call(this, rank, clipControl.active ? 1 : -1);
};
renderer.resolveFrame = function resolveFrameStandard(...parameters) {
endReversed();
diff --git a/src/shaders.js b/src/shaders.js
index 2db9a71b..fc4e3131 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -65,6 +65,8 @@ layout(location=14) in vec4 vertexColor;
layout(location=15) in vec4 instanceEmissive;
uniform mat4 viewProjection;
uniform mat4 lightProjection;
+uniform vec3 flushBias;
+uniform vec4 clipPerMetre;
uniform float time;
uniform float wind;
uniform float explosionProgress;
@@ -127,6 +129,12 @@ void main() {
#endif
shadowPosition = lightProjection * world;
gl_Position = viewProjection * world;
+ // A depth rank (renderer applyDepthRank): the depth of this point moved toward the eye by flushBias.x metres plus
+ // flushBias.y of its distance, at the same place on screen, so ranked faces never crack or slide.
+ if (flushBias != vec3(0.0)) {
+ vec4 lifted = gl_Position - (flushBias.x + flushBias.y * gl_Position.w) * clipPerMetre;
+ gl_Position.z = (lifted.z / lifted.w + flushBias.z) * gl_Position.w;
+ }
}`;
}
diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.js
index 69e05a9a..2d20dab9 100644
--- a/tests/coplanar-overlap.test.js
+++ b/tests/coplanar-overlap.test.js
@@ -1,14 +1,14 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAgentScene } from '../src/agent-scene.js';
-import { coplanarLayers, findCoplanarOverlaps, coplanarOverlapDiagnostics, installCoplanarDiagnostics, resolveCoplanarParts, resolveFlushParts } from '../src/coplanar-overlap.js';
-import { depthLayerOf, MAXIMUM_DEPTH_LAYER } from '../src/depth-layer.js';
+import { clearFlushParts, findCoplanarOverlaps, coplanarOverlapDiagnostics, flushLeftoverDiagnostics, installCoplanarDiagnostics, resolveFlushParts } from '../src/coplanar-overlap.js';
+import { depthLayerOf, flushOrderOf } from '../src/depth-layer.js';
import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
import { frameDiagnostics } from '../src/frame-diagnostics.js';
-import { groupParts, Renderer67 } from '../src/renderer.js';
+import { groupParts } from '../src/renderer.js';
import { resolveEffects } from '../src/effects.js';
-await loadAgentSceneModules({ environment: { resolveCoplanar: 'offset' } });
+await loadAgentSceneModules({});
function node(id, translation, scale, extra = {}) {
return { id, geometry: 'box', material: 'paint', translation, scale, ...extra };
@@ -24,7 +24,8 @@ function recipe(nodes, environment) {
};
}
-function coplanarWarnings(nodes, environment) {
+// The pair report belongs to a scene that switched the ranking off; by default flush faces are ranked and nothing is left to report.
+function coplanarWarnings(nodes, environment = { resolveCoplanar: false }) {
const inspection = createAgentScene(recipe(nodes, environment)).inspect();
return (inspection.diagnostics ?? []).filter(entry => entry.kind === 'coplanar-overlap');
}
@@ -68,12 +69,49 @@ test('a gap of half a millimetre still fights, a gap of five millimetres does no
test('decal, depthLayer and resolveCoplanar all silence the pair without moving geometry', () => {
assert.deepEqual(coplanarWarnings([wall, { ...sign, decal: true }]), []);
assert.deepEqual(coplanarWarnings([wall, { ...sign, depthLayer: 2 }]), []);
- const scene = createAgentScene(recipe([wall, sign], { resolveCoplanar: 'offset' }));
- const [wallPart, signPart] = ['wall', 'sign'].map(name => scene.parts.find(part => part.name === name));
- assert.equal(depthLayerOf(wallPart), 0);
- assert.equal(depthLayerOf(signPart), 1);
- assert.deepEqual(Array.from(signPart.matrix), Array.from(createAgentScene(recipe([wall, sign])).parts.find(part => part.name === 'sign').matrix));
- assert.deepEqual((scene.inspect().diagnostics ?? []).filter(entry => entry.kind === 'coplanar-overlap'), []);
+ for (const environment of [undefined, { resolveCoplanar: 'offset' }]) {
+ const scene = createAgentScene(recipe([wall, sign], environment));
+ const [wallPart, signPart] = ['wall', 'sign'].map(name => scene.parts.find(part => part.name === name));
+ assert.equal(depthLayerOf(wallPart), 0);
+ assert.equal(depthLayerOf(signPart), 0);
+ assert.equal(flushOrderOf(wallPart), null);
+ assert.deepEqual(flushOrderOf(signPart).ranges.map(range => range.rank), [0, 1], 'only the face on the wall is ranked');
+ assert.deepEqual(Array.from(signPart.matrix), Array.from(createAgentScene(recipe([wall, sign], { resolveCoplanar: false })).parts.find(part => part.name === 'sign').matrix));
+ const inspection = scene.inspect();
+ assert.deepEqual((inspection.diagnostics ?? []).filter(entry => entry.kind === 'coplanar-overlap'), []);
+ assert.deepEqual(inspection.flush, { ranked: 1 });
+ }
+});
+
+test('switching resolveCoplanar off drops the ranks and brings the pair report back', () => {
+ const scene = createAgentScene(recipe([wall, sign]));
+ const signPart = scene.parts.find(part => part.name === 'sign');
+ assert.ok(flushOrderOf(signPart));
+ scene.apply([{ type: 'set-environment', environment: { resolveCoplanar: false } }], { expectedRevision: 0 });
+ for (const part of scene.parts) assert.equal(flushOrderOf(part), null);
+ assert.equal(flushOrderOf(signPart), null);
+ const inspection = scene.inspect();
+ assert.equal(inspection.diagnostics.filter(entry => entry.kind === 'coplanar-overlap').length, 1);
+ assert.equal(inspection.flush, undefined);
+});
+
+test('what the ranking leaves over is reported with its reason and a fix', () => {
+ const problems = flushLeftoverDiagnostics([
+ { reason: 'collapsed-node', part: 'Lid', triangles: 12 },
+ { reason: 'rank-overflow', part: 'BuildingWalls', triangles: 22 },
+ ]);
+ assert.deepEqual(problems.map(problem => [problem.kind, problem.severity, problem.target, problem.reason]), [
+ ['coplanar-overlap', 'warning', 'BuildingWalls', 'rank-overflow'],
+ ['coplanar-overlap', 'warning', 'Lid', 'collapsed-node'],
+ ]);
+ assert.equal(problems[0].message, 'BuildingWalls: 22 triangles sit in stacks deeper than 15 near-coplanar faces and may flicker far away.');
+ assert.equal(problems[0].fix, 'Remove the duplicate faces in the asset.');
+ for (const reason of ['double-sided-gap', 'unchecked']) {
+ const [problem] = flushLeftoverDiagnostics([{ reason, part: 'Leaf', triangles: 3 }]);
+ assert.match(problem.message, /Leaf/);
+ assert.ok(problem.fix.length > 10);
+ }
+ assert.equal(flushLeftoverDiagnostics(Array.from({ length: 20 }, (unused, index) => ({ reason: 'unchecked', part: `part${index}`, triangles: index }))).length, 8);
});
test('node decal and depthLayer are validated', () => {
@@ -83,34 +121,23 @@ test('node decal and depthLayer are validated', () => {
});
test('renderer diagnostics carry the same warning, and a decal batches apart from its wall', () => {
- const scene = createAgentScene(recipe([wall, sign]));
+ const scene = createAgentScene(recipe([wall, sign], { resolveCoplanar: false }));
const renderer = installCoplanarDiagnostics({});
const batches = [{ parts: scene.parts }];
const coplanarProblems = renderer.coplanarDiagnostics(batches);
assert.equal(renderer.coplanarDiagnostics(batches), coplanarProblems, 'the same layout is checked once');
const problems = frameDiagnostics({ world: false, depth: true, effects: resolveEffects({}), coplanarProblems });
assert.deepEqual(problems.map(problem => problem.kind), ['coplanar-overlap']);
- const resolved = resolveCoplanarParts(scene.parts);
assert.equal(groupParts(scene.parts).length, 1);
- assert.equal(groupParts(resolved).length, 2);
-});
-
-test('the polygon offset is scoped to the layer and switched off for layer 0', () => {
- const calls = [];
- const context = {
- POLYGON_OFFSET_FILL: 'fill',
- enable: capability => calls.push(['enable', capability]),
- disable: capability => calls.push(['disable', capability]),
- polygonOffset: (factor, units) => calls.push(['offset', factor, units]),
- };
- 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']]);
+ assert.equal(resolveFlushParts(scene.parts).ranked, 1);
+ assert.equal(groupParts(scene.parts).length, 2, 'the ranked sign draws in ranges, so it batches apart from the wall');
+ assert.deepEqual(installCoplanarDiagnostics({}).coplanarDiagnostics([{ parts: scene.parts }]), [], 'a ranked pair is settled, not reported');
+ clearFlushParts(scene.parts);
+ assert.equal(groupParts(scene.parts).length, 1);
});
test('the check is bounded: a work budget ends the sweep and says so', () => {
- const scene = createAgentScene(recipe([wall, sign]));
+ const scene = createAgentScene(recipe([wall, sign], { resolveCoplanar: false }));
const result = findCoplanarOverlaps(scene.parts, { workBudget: 0 });
assert.equal(result.truncated, true);
assert.deepEqual(coplanarOverlapDiagnostics({ overlaps: [], truncated: true }), []);
@@ -180,14 +207,15 @@ test('hundreds of copies parked at one spot cost two parts, not every pair among
assert.ok(work < 100);
});
-test('flush parts get a layer beside the part, so the part objects and updateParts keep working', () => {
+test('flush parts get their ranks beside the part, so the part objects and updateParts keep working', () => {
const road = gridPart('roadTwo', 4, 4, 0);
const marking = gridPart('markingTwo', 2, 2, 0.00005);
const far = gridPart('farAway', 4, 4, 30);
- assert.equal(resolveFlushParts([road, marking, far]), 1);
- assert.equal(depthLayerOf(marking), 1);
- assert.equal(depthLayerOf(road), 0);
- assert.equal(depthLayerOf(far), 0);
+ assert.deepEqual(resolveFlushParts([road, marking, far]), { ranked: 1, leftovers: [] });
+ assert.deepEqual(flushOrderOf(marking).ranges, [{ start: 0, count: marking.geometry.indices.length, rank: 1 }]);
+ assert.equal(flushOrderOf(road), null);
+ assert.equal(flushOrderOf(far), null);
+ assert.equal(depthLayerOf(marking), 0);
assert.equal(marking.depthLayer, undefined);
});
@@ -199,7 +227,7 @@ test('faces that share only an edge or a seam are not pairs, and a sliver under
assert.deepEqual(findCoplanarOverlaps([left, cornerOnly]).overlaps, []);
const sliver = movedPart(gridPart('sliver', 2, 2, 0), 'sliver', 1.99999, 0);
assert.deepEqual(findCoplanarOverlaps([left, sliver]).overlaps, []);
- assert.equal(resolveFlushParts([left, right, cornerOnly]), 0);
+ assert.deepEqual(resolveFlushParts([left, right, cornerOnly]), { ranked: 0, leftovers: [] });
});
test('two parts that really share area are a pair with that area', () => {
@@ -210,23 +238,29 @@ test('two parts that really share area are a pair with that area', () => {
assert.ok(Math.abs(overlaps[0].area - 4) < 1e-6);
});
-test('resolveFlushParts leaves exactly flush pairs to the depth buffer; coplanarLayers still layers them', () => {
+test('resolveFlushParts ranks exactly flush pairs too, on every depth format', () => {
const road = gridPart('roadExact', 4, 4, 0);
const marking = gridPart('markingExact', 2, 2, 0);
- assert.equal(resolveFlushParts([road, marking]), 0);
- assert.equal(coplanarLayers(findCoplanarOverlaps([road, marking]).overlaps).get(marking), 1);
- assert.equal(resolveFlushParts([road, marking], { minimumGap: 0 }), 1, 'the renderer passes a gap of 0 when reversedDepth is false');
- assert.equal(depthLayerOf(marking), 1);
+ assert.equal(findCoplanarOverlaps([road, marking]).overlaps.length, 1);
+ assert.equal(resolveFlushParts([road, marking]).ranked, 1);
+ assert.deepEqual(flushOrderOf(marking).ranges.map(range => range.rank), [1]);
+ assert.equal(flushOrderOf(road), null);
+ assert.deepEqual(findCoplanarOverlaps([road, marking]).overlaps, [], 'a ranked pair is no longer reported');
});
-test('layers settle in chains and never pile up on the top layer', () => {
+test('ranks settle in chains, and a stack deeper than the ranks is reported instead of piled on the top rank', () => {
const big = gridPart('chainBig', 10, 1, 0);
const middle = gridPart('chainMiddle', 5, 1, 0);
const small = gridPart('chainSmall', 2, 1, 0);
- const layers = coplanarLayers(findCoplanarOverlaps([small, middle, big]).overlaps);
- assert.equal(layers.get(middle), 1);
- assert.equal(layers.get(small), 2);
+ assert.equal(findCoplanarOverlaps([small, middle, big]).overlaps.length, 3);
+ const rankOf = part => flushOrderOf(part)?.ranges.at(-1).rank ?? 0;
+ assert.deepEqual(resolveFlushParts([small, middle, big]), { ranked: 2, leftovers: [] });
+ assert.deepEqual([big, middle, small].map(rankOf), [0, 1, 2]);
const stack = Array.from({ length: 8 }, (unused, index) => gridPart(`stack${index}`, 10 - index, 1, 0));
- const stackLayers = coplanarLayers(findCoplanarOverlaps(stack).overlaps);
- for (const layer of stackLayers.values()) assert.ok(layer <= MAXIMUM_DEPTH_LAYER);
+ assert.deepEqual(resolveFlushParts(stack).leftovers, []);
+ assert.deepEqual(stack.map(rankOf), [0, 1, 2, 3, 4, 5, 6, 7], 'every face of the stack has a rank of its own');
+ const deep = Array.from({ length: 20 }, (unused, index) => gridPart(`deep${index}`, 20 - index, 1, 0));
+ const { leftovers } = resolveFlushParts(deep);
+ assert.deepEqual(leftovers.map(leftover => leftover.reason), ['rank-overflow', 'rank-overflow', 'rank-overflow', 'rank-overflow']);
+ assert.ok(deep.every(part => rankOf(part) <= 15));
});
diff --git a/tests/flush-resolve.test.js b/tests/flush-resolve.test.js
new file mode 100644
index 00000000..238f0ae6
--- /dev/null
+++ b/tests/flush-resolve.test.js
@@ -0,0 +1,199 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { flushOrderOf, MAXIMUM_FLUSH_RANK } from '../src/depth-layer.js';
+import { resolveFlush } from '../src/flush-resolve.js';
+import { Renderer67 } from '../src/renderer.js';
+import { vertexShader } from '../src/shaders.js';
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+function quadCorners(x, z, width, depth, height) {
+ return [x, height, z, x, height, z + depth, x + width, height, z + depth, x + width, height, z];
+}
+
+function geometryOf(quads) {
+ const indices = [];
+ for (let quad = 0; quad < quads.length; quad++) indices.push(quad * 4, quad * 4 + 1, quad * 4 + 2, quad * 4, quad * 4 + 2, quad * 4 + 3);
+ return { positions: new Float32Array(quads.flat()), indices: new Uint32Array(indices) };
+}
+
+function partOf(name, quads, { matrix = IDENTITY, material = {}, ...extra } = {}) {
+ return { name, geometry: geometryOf(quads), matrix: new Float32Array(matrix), material, ...extra };
+}
+
+function movedTo(x, y, z) {
+ const matrix = [...IDENTITY];
+ matrix[12] = x;
+ matrix[13] = y;
+ matrix[14] = z;
+ return matrix;
+}
+
+function ranksOf(part) {
+ const order = flushOrderOf(part);
+ return order ? Array.from(order.triangleRanks) : null;
+}
+
+test('the surface in front along the normal gets the higher rank, whatever the part order or size', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 4, 4, 0)]);
+ const plaque = partOf('plaque', [quadCorners(1, 1, 1, 1, 0.001)]);
+ assert.deepEqual(resolveFlush([wall, plaque]), { ranked: 1, leftovers: [] });
+ assert.deepEqual(ranksOf(plaque), [1, 1]);
+ assert.equal(flushOrderOf(wall), null);
+ assert.equal(resolveFlush([plaque, wall]).ranked, 1);
+ assert.deepEqual(ranksOf(plaque), [1, 1]);
+ // A large sheet a millimetre in front of a small patch: the sheet is in front, so the sheet gets the rank.
+ const patch = partOf('patch', [quadCorners(1, 1, 1, 1, 0)]);
+ const sheet = partOf('sheet', [quadCorners(0, 0, 4, 4, 0.001)]);
+ resolveFlush([patch, sheet]);
+ assert.equal(flushOrderOf(patch), null);
+ assert.deepEqual(ranksOf(sheet), [1, 1]);
+ // Turned upside down the normal points down, and the face with the lower y is the one in front.
+ const upsideDown = [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 4, 1];
+ const ceiling = partOf('ceiling', [quadCorners(0, 0, 4, 4, 0)], { matrix: upsideDown });
+ const lamp = partOf('lamp', [quadCorners(1, 1, 1, 1, 0.001)], { matrix: upsideDown });
+ resolveFlush([ceiling, lamp]);
+ assert.deepEqual(ranksOf(lamp), [1, 1]);
+ assert.equal(flushOrderOf(ceiling), null);
+});
+
+test('on one plane the smaller face wins, then the later one, and chains count up', () => {
+ const kitbash = partOf('kitbash', [quadCorners(0, 0, 10, 1, 0), quadCorners(0, 0, 5, 1, 0), quadCorners(0, 0, 2, 1, 0)]);
+ resolveFlush([kitbash]);
+ assert.deepEqual(ranksOf(kitbash), [0, 0, 1, 1, 2, 2]);
+ const twin = partOf('twin', [quadCorners(0, 0, 1, 1, 0), quadCorners(0, 0, 1, 1, 0)]);
+ resolveFlush([twin]);
+ assert.deepEqual(ranksOf(twin), [0, 0, 1, 1]);
+});
+
+test('the ranked order holds every triangle once, sorted by rank, and leaves the geometry alone', () => {
+ const kitbash = partOf('kitbash', [quadCorners(0, 0, 2, 1, 0), quadCorners(0, 0, 10, 1, 0), quadCorners(0, 0, 5, 1, 0)]);
+ const original = Array.from(kitbash.geometry.indices);
+ const geometry = kitbash.geometry;
+ resolveFlush([kitbash]);
+ const order = flushOrderOf(kitbash);
+ assert.equal(kitbash.geometry, geometry);
+ assert.deepEqual(Array.from(kitbash.geometry.indices), original);
+ assert.deepEqual(order.ranges, [{ start: 0, count: 6, rank: 0 }, { start: 6, count: 6, rank: 1 }, { start: 12, count: 6, rank: 2 }]);
+ assert.deepEqual(Array.from(order.indices), [4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 0, 1, 2, 0, 2, 3]);
+});
+
+test('a stack of 20 faces fills the 16 ranks and reports the rest as rank-overflow', () => {
+ const stack = partOf('stack', Array.from({ length: 20 }, (unused, index) => quadCorners(0, 0, 20 - index, 1, 0)));
+ const { ranked, leftovers } = resolveFlush([stack]);
+ assert.equal(ranked, 1);
+ assert.deepEqual(leftovers, [{ reason: 'rank-overflow', part: 'stack', triangles: 8 }]);
+ const ranks = ranksOf(stack);
+ assert.equal(Math.max(...ranks), MAXIMUM_FLUSH_RANK);
+ assert.deepEqual(ranks.slice(0, 32), Array.from({ length: 32 }, (unused, index) => index >> 1));
+ const shallow = partOf('shallow', Array.from({ length: 16 }, (unused, index) => quadCorners(0, 0, 20 - index, 1, 0)));
+ assert.deepEqual(resolveFlush([shallow]).leftovers, []);
+});
+
+test('untouched parts keep their identity and get no order; a stale order is dropped on the next run', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 4, 4, 0)]);
+ const plaque = partOf('plaque', [quadCorners(1, 1, 1, 1, 0)]);
+ const far = partOf('far', [quadCorners(0, 0, 4, 4, 30)]);
+ const parts = [wall, plaque, far];
+ assert.equal(resolveFlush(parts).ranked, 1);
+ assert.equal(flushOrderOf(wall), null);
+ assert.equal(flushOrderOf(far), null);
+ assert.equal(plaque.depthLayer, undefined);
+ assert.deepEqual(Object.keys(plaque), ['name', 'geometry', 'matrix', 'material']);
+ assert.equal(resolveFlush([plaque, far]).ranked, 0, 'without the wall nothing lies under the plaque');
+ assert.equal(flushOrderOf(plaque), null);
+});
+
+test('instances that agree share one order, so they still batch; one that differs gets none', () => {
+ const floor = partOf('floor', [quadCorners(0, 0, 20, 4, 0)], { material: { tag: 'floor' } });
+ const tile = partOf('tile', [quadCorners(0, 0, 1, 1, 0)]);
+ const onFloorOne = { ...tile, name: 'onFloorOne', matrix: new Float32Array(movedTo(1, 0, 1)) };
+ const onFloorTwo = { ...tile, name: 'onFloorTwo', matrix: new Float32Array(movedTo(5, 0, 1)) };
+ const lifted = { ...tile, name: 'lifted', matrix: new Float32Array(movedTo(9, 1, 1)) };
+ assert.equal(resolveFlush([floor, onFloorOne, onFloorTwo, lifted]).ranked, 2);
+ assert.ok(flushOrderOf(onFloorOne));
+ assert.equal(flushOrderOf(onFloorOne), flushOrderOf(onFloorTwo));
+ assert.equal(flushOrderOf(lifted), null);
+});
+
+test('a decal or another depthLayer already clears the pair, so no rank is spent', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 4, 4, 0)]);
+ const sticker = partOf('sticker', [quadCorners(1, 1, 1, 1, 0)], { decal: true });
+ assert.deepEqual(resolveFlush([wall, sticker]), { ranked: 0, leftovers: [] });
+});
+
+test('what cannot be ranked is reported: double-sided gaps, parts past the budget, collapsed nodes', () => {
+ const floor = partOf('floor', [quadCorners(0, 0, 2, 2, 0)]);
+ const flipped = [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0.001, 2, 1];
+ const leaf = partOf('leaf', [quadCorners(0, 0, 2, 2, 0)], { matrix: flipped, material: { doubleSided: true } });
+ const gapped = resolveFlush([floor, leaf]);
+ assert.equal(gapped.ranked, 0);
+ assert.equal(gapped.leftovers.length, 1);
+ assert.equal(gapped.leftovers[0].reason, 'double-sided-gap');
+ assert.equal(gapped.leftovers[0].part, 'leaf');
+ const touching = partOf('touching', [quadCorners(0, 0, 1, 1, 0)], { matrix: [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 2, 1], material: { doubleSided: true } });
+ assert.deepEqual(resolveFlush([floor, touching]), { ranked: 1, leftovers: [] }, 'on one plane the smaller face wins from either side');
+ const pebble = partOf('pebble', [quadCorners(5, 5, 0.1, 0.1, 0)]);
+ assert.deepEqual(resolveFlush([floor, pebble], { triangleBudget: 2 }).leftovers, [{ reason: 'unchecked', part: 'pebble', triangles: 2 }]);
+ const squashed = partOf('squashed', [quadCorners(8, 8, 1, 1, 0)], { matrix: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.0001, 0, 0, 5, 0, 1] });
+ assert.deepEqual(resolveFlush([squashed]).leftovers, [{ reason: 'collapsed-node', part: 'squashed', triangles: 2 }]);
+});
+
+function recordingContext() {
+ const calls = [];
+ const context = {
+ POLYGON_OFFSET_FILL: 'fill', TRIANGLES: 'triangles', UNSIGNED_INT: 'uint',
+ enable: capability => calls.push(['enable', capability]),
+ disable: capability => calls.push(['disable', capability]),
+ polygonOffset: (factor, units) => calls.push(['offset', factor, units]),
+ uniform3f: (location, x, y, z) => calls.push(['bias', x, y, z]),
+ uniform4fv: (location, value) => calls.push(['clipPerMetre', Array.from(value)]),
+ drawElementsInstanced: (mode, count, type, offset, instances) => calls.push(['draw', count, offset, instances]),
+ };
+ return { calls, context };
+}
+
+test('a depth rank is a metric bias plus a slope-only offset, switched off for rank 0, mirrored for reversed depth', () => {
+ const { calls, context } = recordingContext();
+ const fake = { context, uniforms: {} };
+ Renderer67.prototype.applyDepthRank.call(fake, 2);
+ Renderer67.prototype.applyDepthRank.call(fake, 0);
+ Renderer67.prototype.applyDepthRank.call(fake, 16, 1);
+ assert.deepEqual(calls, [
+ ['bias', 2e-4, 2 * 2 ** -19, -2 * 2 ** -22], ['enable', 'fill'], ['offset', -2 / 64, 0],
+ ['bias', 0, 0, 0], ['disable', 'fill'],
+ ['bias', 16e-4, 16 * 2 ** -19, 0], ['enable', 'fill'], ['offset', 0.25, 0],
+ ]);
+});
+
+test('a ranked batch draws one range per rank above its own layer and ends on the layer', () => {
+ const { calls, context } = recordingContext();
+ const fake = { context, uniforms: {}, applyDepthRank: Renderer67.prototype.applyDepthRank };
+ const ranges = [{ start: 0, count: 6, rank: 0 }, { start: 6, count: 12, rank: 3 }];
+ Renderer67.prototype.drawFlushRanges.call(fake, { depthLayer: 1 }, ranges, 5);
+ assert.deepEqual(calls.filter(call => call[0] === 'draw'), [['draw', 6, 0, 5], ['draw', 12, 24, 5]]);
+ assert.deepEqual(calls.filter(call => call[0] === 'bias').map(call => Math.round(call[1] / 1e-4)), [16, 19, 16]);
+});
+
+test('the bias moves depth to where the point would be that much closer to the eye, and nothing else', () => {
+ const near = 0.1;
+ const far = 1000;
+ // A camera at the origin looking down -z: view is the identity, forward is [0, 0, -1].
+ const view = IDENTITY;
+ const perspective = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, (far + near) / (near - far), -1, 0, 0, 2 * far * near / (near - far), 0];
+ const { calls, context } = recordingContext();
+ Renderer67.prototype.setFlushProjection.call({ context, uniforms: {}, view }, perspective);
+ const clipPerMetre = calls[0][1];
+ const clip = point => [0, 1, 2, 3].map(row => perspective[row] * point[0] + perspective[4 + row] * point[1] + perspective[8 + row] * point[2] + perspective[12 + row]);
+ const point = [3, -2, -250];
+ const shift = 16 * (1e-4 + 2 ** -19 * 250);
+ const position = clip(point);
+ const lifted = position.map((value, row) => value - shift * clipPerMetre[row]);
+ const biasedDepth = lifted[2] / lifted[3];
+ const closer = clip([point[0], point[1], point[2] + shift]);
+ assert.ok(Math.abs(biasedDepth - closer[2] / closer[3]) < 1e-9);
+ assert.ok(biasedDepth < position[2] / position[3], 'standard depth shrinks toward the eye');
+ const source = vertexShader;
+ assert.match(source, /uniform vec3 flushBias;\s+uniform vec4 clipPerMetre;/);
+ assert.match(source, /gl_Position = viewProjection \* world;\s+\/\/[^\n]*\n[^\n]*\n\s+if \(flushBias != vec3\(0\.0\)\) \{\s+vec4 lifted = gl_Position - \(flushBias\.x \+ flushBias\.y \* gl_Position\.w\) \* clipPerMetre;\s+gl_Position\.z = \(lifted\.z \/ lifted\.w \+ flushBias\.z\) \* gl_Position\.w;/);
+});
diff --git a/tests/flush-search.test.js b/tests/flush-search.test.js
new file mode 100644
index 00000000..1c3ad31e
--- /dev/null
+++ b/tests/flush-search.test.js
@@ -0,0 +1,152 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { findFlushPairs, flushTolerance, isDeformingPart, nearTolerance } from '../src/flush-search.js';
+
+const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+
+// A quad on the plane y = height, facing up, from (x, z) to (x + width, z + depth).
+function quadCorners(x, z, width, depth, height) {
+ return [x, height, z, x, height, z + depth, x + width, height, z + depth, x + width, height, z];
+}
+
+function partOf(name, quads, { matrix = IDENTITY, material = {}, ...extra } = {}) {
+ const positions = quads.flat();
+ const indices = [];
+ for (let quad = 0; quad < quads.length; quad++) indices.push(quad * 4, quad * 4 + 1, quad * 4 + 2, quad * 4, quad * 4 + 2, quad * 4 + 3);
+ return { name, geometry: { positions: new Float32Array(positions), indices: new Uint32Array(indices) }, matrix: new Float32Array(matrix), material, ...extra };
+}
+
+function movedTo(x, y, z) {
+ const matrix = [...IDENTITY];
+ matrix[12] = x;
+ matrix[13] = y;
+ matrix[14] = z;
+ return matrix;
+}
+
+// The y axis turned by `degrees` about z, so a quad on y = 0 gets the normal [-sin, cos, 0].
+function tiltedAboutZ(degrees) {
+ const angle = degrees * Math.PI / 180;
+ return [Math.cos(angle), Math.sin(angle), 0, 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+}
+
+test('tolerances follow the coordinates and the size of the pair', () => {
+ assert.equal(flushTolerance(1), 1e-4);
+ assert.ok(Math.abs(flushTolerance(1000) - 8 * 2 ** -14) < 1e-12, 'eight float32 steps at 1 km');
+ assert.equal(nearTolerance(1), 0.002);
+ assert.ok(Math.abs(nearTolerance(200) - 0.03) < 1e-12);
+ assert.equal(nearTolerance(1e5), 0.25);
+});
+
+test('duplicate faces inside one geometry are found', () => {
+ const kitbash = partOf('kitbash', [quadCorners(0, 0, 4, 4, 0), quadCorners(1, 1, 1, 1, 0)]);
+ const found = findFlushPairs([kitbash]);
+ assert.equal(found.count, 4);
+ assert.equal(found.pairs.length, 2, 'both quads split along the same diagonal, so each small triangle lies on one wall triangle');
+ assert.ok(found.pairs.every(pair => found.owner[pair.first] === 0 && found.owner[pair.second] === 0));
+ assert.ok(found.pairs.every(pair => Math.abs(pair.gap) < 1e-9 && pair.flush && !pair.opposite));
+ const shared = found.pairs.reduce((sum, pair) => sum + pair.area, 0);
+ assert.ok(Math.abs(shared - 1) < 1e-9, 'the shared pieces add up to the small quad');
+});
+
+test('triangles of one flat mesh that only share edges are not pairs', () => {
+ const tiles = [];
+ for (let row = 0; row < 12; row++) {
+ for (let column = 0; column < 12; column++) tiles.push(quadCorners(column, row, 1, 1, 0));
+ }
+ assert.deepEqual(findFlushPairs([partOf('floor', tiles)]).pairs, []);
+});
+
+test('normals on two sides of a hash boundary still meet', () => {
+ // Normal x components of 0.0249 and 0.0251 round to different cells at 20 steps per unit.
+ const first = partOf('first', [quadCorners(-1, -1, 2, 2, 0)], { matrix: tiltedAboutZ(-Math.asin(0.0249) * 180 / Math.PI) });
+ const second = partOf('second', [quadCorners(-0.5, -0.5, 1, 1, 0)], { matrix: tiltedAboutZ(-Math.asin(0.0251) * 180 / Math.PI) });
+ assert.ok(findFlushPairs([first, second]).pairs.length >= 2);
+ // On a diagonal the dominant component changes, and with it the sign the normal is folded by.
+ const diagonal = partOf('diagonal', [quadCorners(-1, -1, 2, 2, 0)], { matrix: tiltedAboutZ(-135.004) });
+ const neighbour = partOf('neighbour', [quadCorners(-0.5, -0.5, 1, 1, 0)], { matrix: tiltedAboutZ(-134.996) });
+ assert.ok(findFlushPairs([diagonal, neighbour]).pairs.length >= 2);
+ const twoDegrees = partOf('twoDegrees', [quadCorners(-0.5, -0.5, 1, 1, 0)], { matrix: tiltedAboutZ(2) });
+ assert.deepEqual(findFlushPairs([partOf('level', [quadCorners(-1, -1, 2, 2, 0)]), twoDegrees]).pairs, [], 'planes two degrees apart cross, they do not lie flush');
+});
+
+test('the gap is signed along the normal: positive when the second triangle is in front', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 4, 4, 0)]);
+ const plaque = partOf('plaque', [quadCorners(1, 1, 1, 1, 0.001)]);
+ for (const pair of findFlushPairs([wall, plaque]).pairs) assert.ok(Math.abs(pair.gap - 0.001) < 1e-7 && !pair.flush);
+ for (const pair of findFlushPairs([plaque, wall]).pairs) assert.ok(Math.abs(pair.gap + 0.001) < 1e-7);
+ // A far backdrop in the scene does not widen what counts as one plane near the origin, but faces out there do get the wider band.
+ const backdrop = partOf('backdrop', [quadCorners(40000, 0, 100, 100, 5)]);
+ assert.ok(findFlushPairs([wall, plaque, backdrop]).pairs.every(pair => !pair.flush));
+ const distant = [partOf('distantWall', [quadCorners(40000, 0, 4, 4, 0)]), partOf('distantPlaque', [quadCorners(40001, 1, 1, 1, 0.001)])];
+ assert.ok(findFlushPairs(distant).pairs.length >= 2);
+ assert.ok(findFlushPairs(distant).pairs.every(pair => pair.flush), 'a millimetre is rounding 40 km out');
+ const farther = partOf('farther', [quadCorners(1, 1, 1, 1, 0.01)]);
+ assert.deepEqual(findFlushPairs([wall, farther]).pairs, [], 'a centimetre is clear of a wall this small');
+});
+
+test('a large pair of parts is searched with a wider gap than a small one', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 200, 60, 0)]);
+ const cladding = partOf('cladding', [quadCorners(0, 0, 200, 60, 0.016)]);
+ const found = findFlushPairs([wall, cladding]);
+ assert.ok(found.pairs.length >= 2);
+ assert.ok(found.pairs.every(pair => Math.abs(pair.gap - 0.016) < 1e-6));
+});
+
+test('faces that look opposite ways fight only when one of them shows both sides', () => {
+ const floor = partOf('floor', [quadCorners(0, 0, 2, 2, 0)]);
+ const flipped = [1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 2, 1];
+ const underside = partOf('underside', [quadCorners(0, 0, 2, 2, 0)], { matrix: flipped });
+ assert.deepEqual(findFlushPairs([floor, underside]).pairs, []);
+ const leaf = { ...underside, material: { doubleSided: true } };
+ const { pairs } = findFlushPairs([floor, leaf]);
+ assert.ok(pairs.length >= 2);
+ assert.ok(pairs.every(pair => pair.opposite));
+});
+
+test('a two-triangle wall meets hundreds of small faces spread over it', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 400, 400, 0)]);
+ const tiles = [];
+ for (let index = 0; index < 400; index++) tiles.push(quadCorners((index % 20) * 20 + 3, Math.floor(index / 20) * 20 + 3, 0.5, 0.5, 0));
+ const found = findFlushPairs([wall, partOf('tiles', tiles)]);
+ const touched = new Set(found.pairs.map(pair => pair.second));
+ assert.equal(touched.size, 800, 'every tile triangle is paired with the wall');
+ assert.equal(found.truncated, false);
+});
+
+test('parts past the triangle budget are returned as unchecked, the largest parts are searched', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 10, 10, 0)]);
+ const plaque = partOf('plaque', [quadCorners(1, 1, 2, 2, 0)]);
+ const pebble = partOf('pebble', [quadCorners(5, 5, 0.1, 0.1, 0)]);
+ const found = findFlushPairs([pebble, wall, plaque], { triangleBudget: 4 });
+ assert.deepEqual(found.unchecked.map(part => part.name), ['pebble']);
+ assert.deepEqual(found.parts.map(part => part.name), ['wall', 'plaque']);
+ assert.ok(found.pairs.length >= 2);
+ const cut = findFlushPairs([wall, plaque], { pairBudget: 1 });
+ assert.equal(cut.pairs.length, 1);
+ assert.equal(cut.truncated, true);
+});
+
+test('deforming parts and stacked copies are left out', () => {
+ const wall = partOf('wall', [quadCorners(0, 0, 4, 4, 0)]);
+ const banner = partOf('banner', [quadCorners(1, 1, 1, 1, 0)], { skin: {} });
+ const grass = partOf('grass', [quadCorners(1, 1, 1, 1, 0)], { material: { tag: 'grass' } });
+ const water = partOf('water', [quadCorners(1, 1, 1, 1, 0)], { material: { transmission: 1 } });
+ assert.ok([banner, grass, water].every(isDeformingPart));
+ assert.equal(isDeformingPart(wall), false);
+ assert.deepEqual(findFlushPairs([wall, banner, grass, water]).pairs, []);
+ const mote = partOf('mote', [quadCorners(0, 0, 1, 1, 0)]);
+ const parked = Array.from({ length: 300 }, (unused, index) => ({ ...mote, name: `mote${index}` }));
+ const found = findFlushPairs(parked);
+ assert.equal(found.parts.length, 2);
+ assert.ok(found.pairs.length <= 4);
+});
+
+test('a mirrored part keeps the facing its matrix gives it', () => {
+ const floor = partOf('floor', [quadCorners(0, 0, 2, 2, 0)]);
+ const mirrored = partOf('mirrored', [quadCorners(0, 0, 1, 1, 0)], { matrix: [-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1] });
+ const { pairs } = findFlushPairs([floor, mirrored]);
+ assert.ok(pairs.length >= 1);
+ assert.ok(pairs.every(pair => !pair.opposite));
+ assert.deepEqual(findFlushPairs([floor, { ...mirrored, matrix: new Float32Array(movedTo(10, 0, 0)) }]).pairs, []);
+});
diff --git a/tests/reversed-depth.test.js b/tests/reversed-depth.test.js
index cb271b89..56d41154 100644
--- a/tests/reversed-depth.test.js
+++ b/tests/reversed-depth.test.js
@@ -43,7 +43,7 @@ function fakeRenderer({ extension = {}, benchmark = false } = {}) {
context: { getExtension: name => (name === 'EXT_clip_control' ? extension : null) },
render: frame => drawn.push(frame),
applyEnvironmentUniforms() {},
- applyDepthLayer() {},
+ applyDepthRank() {},
resolveFrame() {},
allocateFrameTargets() {},
};