3D engine that AI agents drive
Cut hidden flush faces so stacks on one plane stop flickering
Nguyen Xuan An2e8f68883483
diff --git a/bench/flicker/probe.mjs b/bench/flicker/probe.mjsindex 4921c140..f9bea085 100644--- a/bench/flicker/probe.mjs+++ b/bench/flicker/probe.mjs@@ -46,7 +46,7 @@ async function probeTraps() {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, clear: outcome.probe.clearOfEdges, changed: outcome.probe.changed, moved: outcome.probe.totalChanged, depth: outcome.info.depthMode });+ results.push({ trap, configuration: label, clear: outcome.probe.clearOfEdges, changed: outcome.probe.changed, moved: outcome.probe.totalChanged, ...(outcome.probe.open === undefined ? {} : { open: outcome.probe.open }), depth: outcome.info.depthMode });console.log(JSON.stringify(results.at(-1)));}}@@ -64,6 +64,7 @@ try {for (const configuration of configurations) {await open(configuration);await page.waitForTimeout(1500);+ console.log(JSON.stringify({ flush: await page.evaluate(() => window.flicker.info.flush) }));const label = Object.entries(configuration).map(([key, value]) => `${key}${value}`).join('-');for (const spot of spots) {const outcome = await page.evaluate(async ({ eye, target }) => {diff --git a/bench/flicker/traps.js b/bench/flicker/traps.jsindex 71eeb5bf..10bf78f3 100644--- a/bench/flicker/traps.js+++ b/bench/flicker/traps.js@@ -142,6 +142,31 @@ function instancedFlush() {};}+// A plaque flush on a wall, turned off the axes and far from round coordinates, seen from half a metre at the corner of the+// plaque: the wall is cut around the plaque there. A white backdrop stands behind the dark wall, so a seam a cut left open+// shows as a pixel that is neither face (`countOpen` asks the probe for that count).+function plaqueCloseUp() {+ const length = Math.hypot(0.83, 0.07, -0.55);+ const right = [0.83 / length, 0.07 / length, -0.55 / length];+ const sideways = cross(right, [0, 1, 0]);+ const normal = sideways.map(value => value / Math.hypot(...sideways));+ const up = cross(normal, right);+ const along = (origin, alongRight, alongUp, alongNormal = 0) => origin.map((value, axis) => value + right[axis] * alongRight + up[axis] * alongUp + normal[axis] * alongNormal);+ const centre = [137.37, 21.93, -64.11];+ const plaqueCentre = along(centre, 0.31, 0.17);+ const corner = along(plaqueCentre, 0.65, 0.35);+ return {+ parts: [+ part('backdrop', [quad(along(centre, 0, 0, -0.3), right, up, 30, 30, [1, 1, 1])]),+ part('wall', [quad(centre, right, up, 9.7, 3.9, [0.05, 0.2, 0.05])]),+ part('plaque', [quad(plaqueCentre, right, up, 1.3, 0.7, [0.05, 0.05, 0.25])]),+ ],+ eye: along(corner, 0.04, -0.03, 0.5),+ target: corner,+ countOpen: true,+ };+}+export const TRAPS = {'plaque-2m': () => plaqueOnWall(2),'plaque-20m': () => plaqueOnWall(20),@@ -152,4 +177,5 @@ export const TRAPS = {'walls-16mm-1km-5deg': gappedWalls,'stack-30-exact': exactStack,'instanced-flush': instancedFlush,+ 'plaque-closeup-0.5m': plaqueCloseUp,};diff --git a/bench/flicker/viewer.js b/bench/flicker/viewer.jsindex 98c4720f..21669e27 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 { flushOrderOf } from '../../src/depth-layer.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.@@ -36,6 +37,7 @@ function measureBounds(parts) {const JITTER_PIXELS = 0.125;const CHANGE_THRESHOLD = 24;const EDGE_THRESHOLD = 48;+const OPEN_THRESHOLD = 10;const FIELD_OF_VIEW = 45;const canvas = document.querySelector('#viewport');@@ -119,6 +121,25 @@ async function loadScene() {return TRAPS[trapName]();}+// What the flush pass did to the scene: how long it took, what it could not settle and how much it cut.+let flushReport = null;+function resolveAndReport(parts) {+ const started = performance.now();+ const resolved = resolveFlushParts(parts);+ const cutParts = parts.filter(part => flushOrderOf(part)?.geometry);+ const count = (geometry, field, size) => geometry[field].length / size;+ flushReport = {+ milliseconds: Math.round(performance.now() - started),+ ranked: resolved.ranked,+ leftovers: resolved.leftovers,+ cutParts: cutParts.length,+ trianglesBefore: cutParts.reduce((sum, part) => sum + count(part.geometry, 'indices', 3), 0),+ trianglesAfter: cutParts.reduce((sum, part) => sum + count(flushOrderOf(part).geometry, 'indices', 3), 0),+ verticesAdded: cutParts.reduce((sum, part) => sum + count(flushOrderOf(part).geometry, 'positions', 3) - count(part.geometry, 'positions', 3), 0),+ };+ return resolved;+}+async function build() {if (!glbBytes && !trapName) return;setStatus('wait', 'Building the scene');@@ -131,7 +152,7 @@ async function build() {renderer = new Renderer67(canvas, loaded.parts, {ground: false, hdr: true, samples: 4, pixelRatio: Math.min(devicePixelRatio, 1.5), memoryBudgetMiB: 1024,reversedDepth: options.reversed ? 'auto' : false,- resolveCoplanar: options.offset ? resolveFlushParts : false,+ resolveCoplanar: options.offset ? resolveAndReport : false,});window.flickerRenderer = renderer;window.flickerParts = loaded.parts;@@ -216,11 +237,30 @@ async function probe() {paint.putImageData(image, 0, 0);renderer.render(frameFor(0));lastProbe = { changed, clearOfEdges, totalChanged, total: width * height, fraction: changed / (width * height), width, height };+ if (trapName && TRAPS[trapName]().countOpen) lastProbe.open = countOpenPixels(first, width, height);setStatus(changed === 0 ? 'ok' : 'bad', changed === 0 ? 'No flicker in this view' : `${changed} pixels flicker`);updateReadout();return lastProbe;}+// Pixels that let the backdrop through a seam: a channel is brighter or darker than in all eight pixels around it. A face is+// lit smoothly and an anti-aliased edge lies between the colours on its two sides, so neither stands out like that.+function countOpenPixels(data, width, height) {+ let open = 0;+ for (let y = 1; y < height - 1; y++) {+ for (let x = 1; x < width - 1; x++) {+ const index = (y * width + x) * 4;+ const neighbours = [-1, 0, 1].flatMap(row => [-1, 0, 1].map(column => index + (row * width + column) * 4)).filter(neighbour => neighbour !== index);+ const standsOut = [0, 1, 2].some(channel => {+ const values = neighbours.map(neighbour => data[neighbour + channel]);+ return data[index + channel] > Math.max(...values) + OPEN_THRESHOLD || data[index + channel] < Math.min(...values) - OPEN_THRESHOLD;+ });+ if (standsOut) open++;+ }+ }+ return open;+}+function colourDistance(a, b, index, otherIndex = index) {return Math.max(Math.abs(a[index] - b[otherIndex]), Math.abs(a[index + 1] - b[otherIndex + 1]), Math.abs(a[index + 2] - b[otherIndex + 2]));}@@ -372,7 +412,7 @@ requestAnimationFrame(tick);document.querySelector('#speedValue').textContent = '';window.flicker = {setCamera, probe, build, options, frameWholeScene,- get info() { return { depthMode: depthModeLabel(), ...(renderer ? nearAndFar() : {}), extent, bounds, canvas: [canvas.width, canvas.height], memory: renderer?.memoryReport?.() }; },+ get info() { return { depthMode: depthModeLabel(), ...(renderer ? nearAndFar() : {}), extent, bounds, canvas: [canvas.width, canvas.height], memory: renderer?.memoryReport?.(), flush: flushReport }; },render: () => { markDirty(); renderer?.render(frameFor(0)); },traps: Object.keys(TRAPS),ready: trapName ? loadTrap().catch(error => setStatus('bad', error.message)) : parameters.get('asset')diff --git a/changes/751-flush-clip.size.md b/changes/751-flush-clip.size.mdnew file mode 100644index 00000000..a381f0ee--- /dev/null+++ b/changes/751-flush-clip.size.md@@ -0,0 +1,10 @@+- entry:coplanar-overlap: cutting hidden flush faces (flush-clip.js: subtract the covering triangle, interpolate the vertex arrays, give every seam vertex to both sides of its edge); an addon chunk, loaded by agent scenes and by renderers that pass resolveCoplanar; it is what settles stacks deeper than the 16 ranks and gives the path tracer one face per plane+- entry:core: the renderer draws a cut geometry beside the part and the path tracer reads it (a few lines in renderer.js and path-tracer-scene.js)+- scene:lit-box: same core growth; accepted for flicker-free rendering+- scene:gltf-box: same core growth; accepted for flicker-free rendering+- scene:gltf-box+lazy: same core growth; accepted for flicker-free rendering+- scene:agent-scene: same core growth; accepted for flicker-free rendering+- scene:agent-scene+lazy: the core growth plus the larger flush chunk; it is the fix, so it has to load+- goal:lit-box: the growth is the cut-geometry lookup in the core; accepted for flicker-free rendering+- goal:gltf-box: the growth is the cut-geometry lookup in the core; accepted for flicker-free rendering+- goal:agent-scene: the growth is the cut-geometry lookup in the core; accepted for flicker-free renderingdiff --git a/changes/751.md b/changes/751.mdindex 81f59aee..e97ecedf 100644--- a/changes/751.md+++ b/changes/751.md@@ -1,2 +1,3 @@- Depth precision by default (#751, phase 1 of 2): the colour pass draws with reversed-Z and a 32-bit float depth buffer wherever `EXT_clip_control` exists, at any far / near ratio, from the first frame; the 16-bit depth buffer is gone; without the extension the depth buffer is 24-bit and the near plane fits the visible bounds when the camera left near unset; `reversedDepth: false` opts out; `installDepthPrecision`, `hasFarOverlap` and `requestReversedDepth` are removed (use `installCoplanarDiagnostics` for the warning); `bench/flicker/index.html` is a viewer with a flicker probe- Flush faces stop flickering by default (#751, phase 2, step 1 of 2): faces that lie on one plane or a few millimetres apart, inside one mesh or across parts, are ranked per triangle and drawn with a small view-space depth bias, so the face in front wins at every distance and on every depth format; agent scenes do it unless `environment.resolveCoplanar` is `false`, a renderer does it with `resolveCoplanar: resolveFlushParts`; `decal` and `depthLayer` use the same bias; what cannot be ranked (more than 15 faces stacked on one plane, double-sided faces a gap apart) comes back as a `coplanar-overlap` warning with a `reason`; `coplanarLayers`, `resolveCoplanarParts` and `EXACT_FLUSH_DISTANCE` are removed; `bench/flicker` has trap scenes (`?trap=`, `probe.mjs --traps`)+- Hidden flush faces are cut away (#751, phase 2, step 2 of 2): where an opaque face covers another on exactly the same plane (1 cm2 or more), the covered part is cut out of the copy the hidden face draws with, every vertex array interpolated, so a stack of any depth on one plane stops flickering and no longer reports `rank-overflow`; parts and their geometry stay as they are (`flushOrderOf(part).geometry` holds the cut copy), instances of one geometry share a cut, and the path tracer traces the cut geometry; a face under a blended or masked face, or a double-sided face under a one-sided one, is still ranked; `bench/flicker` gains the `plaque-closeup-0.5m` trap with an open-pixel countdiff --git a/docs/agent-look.md b/docs/agent-look.mdindex 2e273eed..40fa31e3 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -121,7 +121,7 @@ Sky colors use display RGB, matching the renderer's existing environment contrac| `world` | `false` | Boolean world presentation flag. With `true` the setup environment is also the background || `hdri` | absent | A shipped HDRI (`sky-clouds`, `studio-softbox`) or the 64-character ID of a `.hdr` file in `scene_asset_catalog`. It lights, reflects and (with `world: true`) forms the background instead of the setup sky; `environmentIntensity` is its strength and `environmentRotation` turns it about the vertical axis. The setup still gives the key light, so set `keyIntensity: 0` when the HDRI has its own sun. `null` clears. See [Catalog HDRIs and looks](#catalog-hdris-and-looks) || `ground` | on | Absent unless set. `false` removes the preview's automatic floor and contact shadow |-| `resolveCoplanar` | `'offset'` | Flush and near-flush faces, inside one mesh or across parts, are ranked per triangle and drawn with a small depth-only bias, so the face in front wins at every distance and nothing flickers. Geometry never moves. `false` opts out, and `scene_inspect` then lists each pair as a `coplanar-overlap` warning. Parts that set `decal` or `depthLayer` keep their own layer. What cannot be ranked comes back as a `coplanar-overlap` warning with a `reason`: `rank-overflow` (more than 15 faces stacked on one plane), `double-sided-gap`, `unchecked` or `collapsed-node` |+| `resolveCoplanar` | `'offset'` | Flush and near-flush faces, inside one mesh or across parts, are ranked per triangle and drawn with a small depth-only bias, so the face in front wins at every distance and nothing flickers. Geometry never moves. `false` opts out, and `scene_inspect` then lists each pair as a `coplanar-overlap` warning. Parts that set `decal` or `depthLayer` keep their own layer. Where an opaque face covers another on exactly the same plane, the covered part is cut out of the drawn copy of the hidden face (the part and its geometry stay as you made them), so a stack of any depth on one plane is settled and the path tracer sees one face. What cannot be settled comes back as a `coplanar-overlap` warning with a `reason`: `rank-overflow` (more than 16 faces a small gap apart), `double-sided-gap`, `unchecked` or `collapsed-node` || `objectReflections` | on | Absent unless set. Each smooth metal part (`metallic` 0.5 or more, `roughness` 0.6 or less; at most 8 such parts, in a scene with at most 256 other parts) gets a reflection probe of the scene around it, so a chrome sphere shows the floor and its neighbours. `false` turns it off. Probes are traced at rest, so a part that moves reflects the scene as it started. `scene_inspect` names them in `reflections` || `sky` | absent | Absent unless set. `{ type: 'physical', sunElevation, sunRotation, turbidity, groundAlbedo, aerialPerspective, ozone, sunDisc }`: one time-of-day control. `sunElevation` -90 to 90 degrees (default 45), `sunRotation` degrees clockwise from -Z seen from above (0), `turbidity` 1 to 10 haze (3), `groundAlbedo` 0 to 1 (0.3), `aerialPerspective` 0 to 4 scales the distance haze (1; 0 for none), `ozone` 0 to 10 Chappuis-band absorption (1), `sunDisc` boolean (true). The sky sets `lightDirection`, `keyColor` (the sun reddens and dims with air mass and sets below the horizon), `skyTop`, `skyBottom`, `fogColor` and `fogDensity`, and replaces the setup's environment map with the sky, so those fields no longer take your values while a sky is set. `environment` motion tracks can animate `sunElevation`, `sunRotation`, `turbidity`, `groundAlbedo`, `aerialPerspective` and `ozone` for time-of-day arcs. A `set-environment` patch changes the fields it names and keeps the rest; `sky: null` in a patch keeps the last derived values as plain fields. It is an analytic single-scattering approximation (Rayleigh, aerosol and ozone, Kasten-Young air mass), not Blender's Nishita integration: no clouds. Raster first: the path tracer backends read the same environment map and key light, but are not yet checked against it. || `floorSkyTrace` | on | Absent unless set. A closed room a sun lights gets the sky each floor texel sees traced into its floor (`applyFloorSkyVisibility`, strength 0.2), so shadowed floors under a roof or between walls get less world and sky light; it makes the dark end of halls closer to Cycles. Open scenes and rooms lit by lamps alone are left as they are. `false` turns it off; a value that is not a boolean is refused. It loads lazily with a recipe that names its sun (`keyColor` or `keyIntensity`), costs about 1 s of trace when the scene is built and adds triangles to the floor (0.1 to 0.4 ms per frame in the reference halls). |diff --git a/docs/learn/contact-detection.md b/docs/learn/contact-detection.mdindex b0c02909..7ca10b86 100644--- a/docs/learn/contact-detection.md+++ b/docs/learn/contact-detection.md@@ -186,7 +186,7 @@ Both parts draw the plane `y = 0.1`, so the patch flickers against the slab. TheUse a real offset along the normal when the gap should be visible in exports or the path tracer.-The coplanar code is not in the core bundle. Call `installCoplanarDiagnostics(renderer)` from `67js/addons/coplanar-overlap` to add the warning to `renderer.diagnostics` (checked once per layout). To fix the flicker instead of naming it, pass `resolveCoplanar: resolveFlushParts` (same addon) to `new Renderer67`: it ranks flush and near-flush triangles, inside one part and across parts, and draws each rank with a small depth-only bias, so the face in front wins at every distance; ranked pairs leave the warning. Agent scenes do this by default wherever the code is loaded (the MCP preview always has it; elsewhere call `loadAllAgentSceneModules()`), and `environment.resolveCoplanar: false` opts out.+The coplanar code is not in the core bundle. Call `installCoplanarDiagnostics(renderer)` from `67js/addons/coplanar-overlap` to add the warning to `renderer.diagnostics` (checked once per layout). To fix the flicker instead of naming it, pass `resolveCoplanar: resolveFlushParts` (same addon) to `new Renderer67`: it ranks flush and near-flush triangles, inside one part and across parts, and draws each rank with a small depth-only bias, so the face in front wins at every distance; ranked pairs leave the warning. Where an opaque face covers another on exactly the same plane (shared area of 1 cm2 or more), the covered part is cut away instead: the part keeps its geometry, and the cut copy it draws with sits beside it (`flushOrderOf(part).geometry` in `depth-layer.js`), which the path tracer reads too. A face under a blended or masked face, and a double-sided face under a one-sided one, is ranked and not cut. Agent scenes do this by default wherever the code is loaded (the MCP preview always has it; elsewhere call `loadAllAgentSceneModules()`), and `environment.resolveCoplanar: false` opts out.### Depth precision far from the cameradiff --git a/src/depth-layer.js b/src/depth-layer.jsindex 8fe68148..17a144c1 100644--- a/src/depth-layer.js+++ b/src/depth-layer.js@@ -5,8 +5,9 @@ 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;-// 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+// The draw order flush-resolve.js found for a part: `{ indices, ranges: [{ start, count, rank }], geometry? }`, the part's+// triangles sorted by rank. A part with hidden flush faces cut away also has `geometry`, the cut geometry those indices+// belong to. 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();diff --git a/src/flush-clip.js b/src/flush-clip.jsnew file mode 100644index 00000000..aeeddcff--- /dev/null+++ b/src/flush-clip.js@@ -0,0 +1,431 @@+// Cuts away the part of a triangle that an opaque triangle on the same plane covers (issue #751). Two faces on one plane+// fight for every pixel they share; once the hidden one is gone there is nothing left to fight, at any depth precision and+// however deep the stack is. flush-resolve.js picks the pairs and the winner; this file does the cutting.+//+// Two rules keep the cut from showing. A cut stops a few float32 steps inside the winner, so the two faces overlap by a hair+// instead of meeting on a line that rounding could open. And a vertex a cut puts on an edge is given to every triangle on+// that edge, in this face and in the next one, so no edge has a vertex on one side only (a T-junction leaks single pixels).+import { float32Step } from './flush-search.js';++/** Numbers per cut: the triangle that is cut, then the three corners (x, y, z) of the winner in the geometry's own space. */+export const FLUSH_CUT_STRIDE = 10;+/** Shared area (square metres) under which a pair is ranked instead of cut: 1 cm2. */+export const FLUSH_CUT_MINIMUM_AREA = 1e-4;+const PER_VERTEX_FIELDS = ['positions', 'normals', 'uvs', 'lightUvs', 'colors', 'skyVisibility'];+const MARGIN_STEPS = 4;+const DEGENERATE_AREA_SHARE = 1e-12;+const CACHED_CUTS_PER_GEOMETRY = 8;++const clippedByGeometry = new WeakMap();++export function sameNumbers(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;+}++function createPiece(points) {+ const piece = { points, minU: Infinity, minV: Infinity, maxU: -Infinity, maxV: -Infinity };+ for (const point of points) {+ piece.minU = Math.min(piece.minU, point.u);+ piece.minV = Math.min(piece.minV, point.v);+ piece.maxU = Math.max(piece.maxU, point.u);+ piece.maxV = Math.max(piece.maxV, point.v);+ }+ return piece;+}++function doubledArea(points) {+ let doubled = 0;+ for (let index = 0; index < points.length; index++) {+ const following = points[(index + 1) % points.length];+ doubled += points[index].u * following.v - following.u * points[index].v;+ }+ return Math.abs(doubled);+}++// The points of one triangle while it is cut. A point's weights say where it sits in the uncut triangle, so every vertex+// array can be interpolated for it later. Two cuts that reach the same spot get the same point: the grid finds it again.+function createPointSet(tolerance) {+ const cells = new Map();+ const all = [];+ const cellOf = value => Math.round(value / tolerance);+ function find(u, v) {+ const cellU = cellOf(u);+ const cellV = cellOf(v);+ for (let offsetU = -1; offsetU <= 1; offsetU++) {+ for (let offsetV = -1; offsetV <= 1; offsetV++) {+ const point = cells.get(`${cellU + offsetU},${cellV + offsetV}`);+ if (point && Math.abs(point.u - u) <= tolerance && Math.abs(point.v - v) <= tolerance) return point;+ }+ }+ return null;+ }+ function add(u, v, weights, vertex = -1) {+ const point = { u, v, weights, vertex, position: null, seam: null };+ cells.set(`${cellOf(u)},${cellOf(v)}`, point);+ all.push(point);+ return point;+ }+ function between(start, end, along) {+ const u = start.u + (end.u - start.u) * along;+ const v = start.v + (end.v - start.v) * along;+ return find(u, v) ?? add(u, v, [0, 1, 2].map(corner => start.weights[corner] + (end.weights[corner] - start.weights[corner]) * along));+ }+ return { all, add, between, tolerance };+}++// Splits a convex polygon along the line where `distances` is zero. A point within the tolerance of the line is on it and+// belongs to both sides, so a line through a vertex makes no second vertex beside it.+function splitPolygon(points, distances, pointSet) {+ const inside = [];+ const outside = [];+ const sides = distances.map(distance => (distance > pointSet.tolerance ? 1 : distance < -pointSet.tolerance ? -1 : 0));+ for (let index = 0; index < points.length; index++) {+ const following = (index + 1) % points.length;+ if (sides[index] >= 0) inside.push(points[index]);+ if (sides[index] <= 0) outside.push(points[index]);+ if (sides[index] * sides[following] < 0) {+ const crossing = pointSet.between(points[index], points[following], distances[index] / (distances[index] - distances[following]));+ if (inside.at(-1) !== crossing) inside.push(crossing);+ if (outside.at(-1) !== crossing) outside.push(crossing);+ }+ }+ return { inside, outside, reaches: sides.includes(1) };+}++function winnerCorners(cuts, cut, axisU, axisV) {+ const offset = cut * FLUSH_CUT_STRIDE + 1;+ return [0, 1, 2].map(corner => ({ u: cuts[offset + corner * 3 + axisU], v: cuts[offset + corner * 3 + axisV] }));+}++function edgeKey(start, end) {+ const forward = start.u < end.u || (start.u === end.u && start.v <= end.v);+ const [low, high] = forward ? [start, end] : [end, start];+ return `${low.u},${low.v},${high.u},${high.v}`;+}++// The winner's three edges on the plane's two largest axes, each as a start and a unit direction turned so that the+// inside of the winner is at positive distance. An edge is moved `margin` into the winner where the cut face goes on+// beyond it. It stays where it is when two winners share it (it is inside the covered area) and when the whole cut face+// lies on the winner's side of it (nothing goes on beyond it, so moving it would only leave a strip under the winner).+// Null for a winner that is a line on these axes.+function winnerEdges(corners, sharedEdges, margin, facePoints, tolerance) {+ const turn = (corners[1].u - corners[0].u) * (corners[2].v - corners[0].v) - (corners[1].v - corners[0].v) * (corners[2].u - corners[0].u) >= 0 ? 1 : -1;+ const edges = [];+ for (let index = 0; index < 3; index++) {+ const start = corners[index];+ const end = corners[(index + 1) % 3];+ const length = Math.hypot(end.u - start.u, end.v - start.v);+ if (!(length > 0)) return null;+ const edge = { u: start.u, v: start.v, directionU: turn * (end.u - start.u) / length, directionV: turn * (end.v - start.v) / length, margin };+ if (sharedEdges.get(edgeKey(start, end)) > 1 || facePoints.every(point => edgeDistance(edge, point) >= -tolerance)) edge.margin = 0;+ edges.push(edge);+ }+ edges.minU = Math.min(corners[0].u, corners[1].u, corners[2].u);+ edges.maxU = Math.max(corners[0].u, corners[1].u, corners[2].u);+ edges.minV = Math.min(corners[0].v, corners[1].v, corners[2].v);+ edges.maxV = Math.max(corners[0].v, corners[1].v, corners[2].v);+ return edges;+}++function edgeDistance(edge, point) {+ return edge.directionU * (point.v - edge.v) - edge.directionV * (point.u - edge.u);+}++function isCovered(points, edges, margin) {+ return points.every(point => edges.every(edge => edgeDistance(edge, point) >= -margin));+}++// What is left of a convex piece outside the winner, as convex pieces; null when the winner does not reach into it. Each+// edge line splits off the part beyond it; what is inside all three is the hidden part.+function subtractWinner(piece, edges, margin, pointSet) {+ if (piece.maxU < edges.minU || piece.minU > edges.maxU || piece.maxV < edges.minV || piece.minV > edges.maxV) return null;+ let remaining = piece.points;+ const kept = [];+ for (const edge of edges) {+ const { inside, outside, reaches } = splitPolygon(remaining, remaining.map(point => edgeDistance(edge, point) - edge.margin), pointSet);+ if (!reaches || inside.length < 3) return null;+ // A sliver between an edge of the winner and its moved line lies under the winner: it is hidden, not left over.+ if (outside.length >= 3 && !isCovered(outside, edges, margin)) kept.push(createPiece(outside));+ remaining = inside;+ }+ if (doubledArea(remaining) <= margin * margin) return null;+ return kept;+}++// The frame one triangle is cut in: its corners on the plane's two largest axes, and the largest coordinate in play.+function triangleFrame(geometry, triangle) {+ const { positions, indices } = geometry;+ const offsets = [0, 1, 2].map(corner => indices[triangle * 3 + corner] * 3);+ const edgeOne = [0, 1, 2].map(axis => positions[offsets[1] + axis] - positions[offsets[0] + axis]);+ const edgeTwo = [0, 1, 2].map(axis => positions[offsets[2] + axis] - positions[offsets[0] + axis]);+ const normal = [edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]];+ const dropped = normal.reduce((best, value, axis) => (Math.abs(value) > Math.abs(normal[best]) ? axis : best), 0);+ let largest = 0;+ for (const offset of offsets) largest = Math.max(largest, Math.abs(positions[offset]), Math.abs(positions[offset + 1]), Math.abs(positions[offset + 2]));+ return { offsets, axisU: (dropped + 1) % 3, axisV: (dropped + 2) % 3, largest };+}++function cornerPoints(geometry, frame, pointSet) {+ return frame.offsets.map((offset, corner) => pointSet.add(geometry.positions[offset + frame.axisU], geometry.positions[offset + frame.axisV], [0, 1, 2].map(index => (index === corner ? 1 : 0)), offset / 3));+}++// One triangle after its cuts as `{ frame, pointSet, pieces, corners }`, or null when no cut reached it.+function cutTriangle(geometry, triangle, cuts, cutStart, cutEnd, coordinateStep) {+ const frame = triangleFrame(geometry, triangle);+ let largest = frame.largest;+ for (let value = cutStart * FLUSH_CUT_STRIDE; value < cutEnd * FLUSH_CUT_STRIDE; value++) {+ if (value % FLUSH_CUT_STRIDE !== 0) largest = Math.max(largest, Math.abs(cuts[value]));+ }+ const step = Math.max(coordinateStep, float32Step(largest));+ const margin = MARGIN_STEPS * step;+ const pointSet = createPointSet(step);+ const corners = cornerPoints(geometry, frame, pointSet);+ const whole = createPiece(corners);+ const wholeArea = doubledArea(corners);+ const winners = [];+ const sharedEdges = new Map();+ for (let cut = cutStart; cut < cutEnd; cut++) {+ const winner = winnerCorners(cuts, cut, frame.axisU, frame.axisV);+ winners.push(winner);+ for (let index = 0; index < 3; index++) {+ const key = edgeKey(winner[index], winner[(index + 1) % 3]);+ sharedEdges.set(key, (sharedEdges.get(key) ?? 0) + 1);+ }+ }+ let pieces = [whole];+ for (const winner of winners) {+ const edges = winnerEdges(winner, sharedEdges, margin, corners, step);+ if (!edges) continue;+ const next = [];+ for (const piece of pieces) {+ const left = subtractWinner(piece, edges, margin, pointSet);+ if (left) next.push(...left);+ else next.push(piece);+ }+ pieces = next;+ }+ if (pieces.length === 1 && pieces[0] === whole) return null;+ pieces = pieces.filter(piece => doubledArea(piece.points) > DEGENERATE_AREA_SHARE * wholeArea);+ return { frame, pointSet, pieces, corners };+}++function positionKey(positions, offset) {+ return `${positions[offset]},${positions[offset + 1]},${positions[offset + 2]}`;+}++// One side of a triangle as the mesh edge it lies on: a key that every triangle on that edge agrees on, whatever its own+// vertex numbers, and whether this triangle runs along it from the lower end.+function meshEdge(geometry, frame, opposite) {+ const start = frame.offsets[(opposite + 1) % 3];+ const end = frame.offsets[(opposite + 2) % 3];+ const startKey = positionKey(geometry.positions, start);+ const endKey = positionKey(geometry.positions, end);+ const forward = startKey <= endKey;+ return { key: forward ? `${startKey}|${endKey}` : `${endKey}|${startKey}`, forward, start, end };+}++// The corner a point lies opposite of when it sits on a side of the uncut triangle and is not a corner itself, else -1.+function sideOf(point) {+ const zeros = point.weights.filter(weight => weight === 0).length;+ return zeros === 1 ? point.weights.indexOf(0) : -1;+}++// Notes every vertex a cut put on a mesh edge in `seams`, so the triangles on the other side of that edge get it too. Two+// triangles that were cut at the same spot of an edge share one position, to the bit.+function noteSeamPoints(geometry, cut, seams) {+ const { positions } = geometry;+ for (const point of new Set(cut.pieces.flatMap(piece => piece.points))) {+ const opposite = sideOf(point);+ if (opposite < 0) continue;+ const edge = meshEdge(geometry, cut.frame, opposite);+ const along = edge.forward ? point.weights[(opposite + 2) % 3] : point.weights[(opposite + 1) % 3];+ const [low, high] = edge.forward ? [edge.start, edge.end] : [edge.end, edge.start];+ const length = Math.hypot(positions[high] - positions[low], positions[high + 1] - positions[low + 1], positions[high + 2] - positions[low + 2]);+ const entries = seams.get(edge.key) ?? [];+ seams.set(edge.key, entries);+ let entry = entries.find(candidate => Math.abs(candidate.along - along) * length <= cut.pointSet.tolerance);+ if (!entry) {+ entry = { along, position: [0, 1, 2].map(axis => Math.fround(positions[low + axis] + (positions[high + axis] - positions[low + axis]) * along)) };+ entries.push(entry);+ }+ point.seam = entry;+ point.position = entry.position;+ }+}++// Gives a triangle the seam vertices of its three sides that it does not have yet.+function addSeamPoints(geometry, cut, seams) {+ for (let opposite = 0; opposite < 3; opposite++) {+ const edge = meshEdge(geometry, cut.frame, opposite);+ const entries = seams.get(edge.key);+ if (!entries) continue;+ const start = cut.corners[(opposite + 1) % 3];+ const end = cut.corners[(opposite + 2) % 3];+ for (const entry of entries) {+ if (cut.pointSet.all.some(point => point.seam === entry)) continue;+ const along = edge.forward ? entry.along : 1 - entry.along;+ const point = cut.pointSet.between(start, end, along);+ if (point.seam || point.vertex >= 0) continue;+ point.seam = entry;+ point.position = entry.position;+ }+ }+}++// The points of a piece with every other point of the triangle that lies on one of its sides put in between, so the piece+// and its neighbours have the same vertices along the side they share.+function withPointsOnSides(piece, pointSet) {+ const own = new Set(piece.points);+ const ring = [];+ for (let index = 0; index < piece.points.length; index++) {+ const start = piece.points[index];+ const end = piece.points[(index + 1) % piece.points.length];+ const length = Math.hypot(end.u - start.u, end.v - start.v);+ ring.push(start);+ if (!(length > 0)) continue;+ const onSide = [];+ for (const point of pointSet.all) {+ if (own.has(point)) continue;+ const along = ((point.u - start.u) * (end.u - start.u) + (point.v - start.v) * (end.v - start.v)) / length;+ if (along <= pointSet.tolerance || along >= length - pointSet.tolerance) continue;+ const away = Math.abs((end.u - start.u) * (point.v - start.v) - (end.v - start.v) * (point.u - start.u)) / length;+ if (away <= pointSet.tolerance) onSide.push({ point, along });+ }+ onSide.sort((one, other) => one.along - other.along);+ for (const { point } of onSide) ring.push(point);+ }+ return ring;+}++function hasPointOnSide(ring, tolerance) {+ return ring.some((point, index) => {+ const previous = ring[(index + ring.length - 1) % ring.length];+ const following = ring[(index + 1) % ring.length];+ const length = Math.hypot(following.u - previous.u, following.v - previous.v);+ return Math.abs((following.u - previous.u) * (point.v - previous.v) - (following.v - previous.v) * (point.u - previous.u)) <= tolerance * length;+ });+}++// A convex ring as triangles. A ring with points along its sides is fanned from its middle: a fan from a corner would+// leave those points beside a long edge, held only by a triangle with no area.+function fanRing(ring, pointSet) {+ if (!hasPointOnSide(ring, pointSet.tolerance)) return ring.slice(1, -1).map((point, index) => [ring[0], point, ring[index + 2]]);+ const middle = pointSet.add(+ ring.reduce((sum, point) => sum + point.u, 0) / ring.length,+ ring.reduce((sum, point) => sum + point.v, 0) / ring.length,+ [0, 1, 2].map(corner => ring.reduce((sum, point) => sum + point.weights[corner], 0) / ring.length),+ );+ return ring.map((point, index) => [middle, point, ring[(index + 1) % ring.length]]);+}++// Every per-vertex array grown by the new vertices, each the weighted mix of the three corners of the triangle it was cut+// from. A vertex on a seam takes the position the seam holds, so both sides of the seam get the same bits.+function extendVertexArrays(geometry, added) {+ const vertexCount = geometry.positions.length / 3;+ const extended = {};+ for (const field of PER_VERTEX_FIELDS) {+ const values = geometry[field];+ if (!values) continue;+ const stride = values.length / vertexCount;+ const grown = new values.constructor(values.length + added.length * stride);+ grown.set(values);+ added.forEach(({ corners, point }, vertex) => {+ const target = values.length + vertex * stride;+ if (field === 'positions' && point.position) {+ grown.set(point.position, target);+ return;+ }+ for (let component = 0; component < stride; component++) {+ grown[target + component] = values[corners[0] * stride + component] * point.weights[0]+ + values[corners[1] * stride + component] * point.weights[1]+ + values[corners[2] * stride + component] * point.weights[2];+ }+ });+ extended[field] = grown;+ }+ return extended;+}++function clipGeometry(geometry, cuts, coordinateStep) {+ const { indices } = geometry;+ const triangleCount = indices.length / 3;+ const vertexCount = geometry.positions.length / 3;+ const cutCount = cuts.length / FLUSH_CUT_STRIDE;+ const cutTriangles = new Map();+ const seams = new Map();+ let cut = 0;+ for (let triangle = 0; triangle < triangleCount && cut < cutCount; triangle++) {+ const cutStart = cut;+ while (cut < cutCount && cuts[cut * FLUSH_CUT_STRIDE] === triangle) cut++;+ if (cut === cutStart) continue;+ const result = cutTriangle(geometry, triangle, cuts, cutStart, cut, coordinateStep);+ if (!result) continue;+ cutTriangles.set(triangle, result);+ noteSeamPoints(geometry, result, seams);+ }+ if (cutTriangles.size === 0) return { geometry, sources: null };+ const clippedIndices = [];+ const sources = [];+ const added = [];+ for (let triangle = 0; triangle < triangleCount; triangle++) {+ let result = cutTriangles.get(triangle);+ if (!result && seams.size > 0) {+ // An uncut triangle on a seam is split at the seam's vertices too.+ const frame = triangleFrame(geometry, triangle);+ if ([0, 1, 2].some(opposite => seams.has(meshEdge(geometry, frame, opposite).key))) {+ const pointSet = createPointSet(Math.max(coordinateStep, float32Step(frame.largest)));+ const corners = cornerPoints(geometry, frame, pointSet);+ result = { frame, pointSet, pieces: [createPiece(corners)], corners };+ }+ }+ if (!result) {+ clippedIndices.push(indices[triangle * 3], indices[triangle * 3 + 1], indices[triangle * 3 + 2]);+ sources.push(triangle);+ continue;+ }+ addSeamPoints(geometry, result, seams);+ const corners = [indices[triangle * 3], indices[triangle * 3 + 1], indices[triangle * 3 + 2]];+ for (const piece of result.pieces) {+ const ring = withPointsOnSides(piece, result.pointSet);+ for (const fan of fanRing(ring, result.pointSet)) {+ for (const point of fan) {+ if (point.vertex >= 0) continue;+ point.vertex = vertexCount + added.length;+ added.push({ corners, point });+ }+ clippedIndices.push(fan[0].vertex, fan[1].vertex, fan[2].vertex);+ sources.push(triangle);+ }+ }+ }+ return {+ geometry: { ...geometry, ...extendVertexArrays(geometry, added), indices: new Uint32Array(clippedIndices) },+ sources: new Uint32Array(sources),+ };+}++/**+ * Cuts the hidden part out of the triangles of `geometry`. `cuts` is a Float64Array of FLUSH_CUT_STRIDE numbers per cut,+ * sorted by the triangle that is cut: that triangle's number, then the corners of the triangle that covers it, in the+ * geometry's own space. `coordinateStep` is the float32 step of the coordinates the part is drawn at, in the geometry's+ * units; a cut stops a few of those steps (or of the geometry's own, when larger) inside the winner. Returns+ * `{ geometry, sources }`: a new geometry with every per-vertex array interpolated for the new vertices and `sources[n]`+ * the uncut triangle that clipped triangle n came from; or the same `geometry` and `sources: null` when nothing was cut.+ * A fully covered triangle is dropped. The result is kept per geometry, so the same cuts return the same object.+ */+export function clipFlushOverlaps(geometry, cuts, coordinateStep = 0) {+ if (cuts.length === 0) return { geometry, sources: null };+ const cached = clippedByGeometry.get(geometry) ?? [];+ clippedByGeometry.set(geometry, cached);+ let entry = cached.find(candidate => sameNumbers(candidate.cuts, cuts));+ if (!entry) {+ entry = { cuts, clipped: clipGeometry(geometry, cuts, coordinateStep) };+ cached.push(entry);+ if (cached.length > CACHED_CUTS_PER_GEOMETRY) cached.shift();+ }+ return entry.clipped;+}diff --git a/src/flush-resolve.js b/src/flush-resolve.jsindex 973c06db..d69f00a2 100644--- a/src/flush-resolve.js+++ b/src/flush-resolve.js@@ -1,11 +1,18 @@-// 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).+// Settles the pairs of flush-search.js (issue #751). Two faces on one plane: the hidden one is cut away where the other+// covers it (flush-clip.js), so nothing is left to fight. Two faces a small gap apart: the one in front along the shared+// normal gets the higher draw 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 { mat4 } from 'gl-matrix';import { depthLayerOf, MAXIMUM_FLUSH_RANK, setFlushOrder } from './depth-layer.js';-import { findFlushPairs } from './flush-search.js';+import { clipFlushOverlaps, FLUSH_CUT_MINIMUM_AREA, FLUSH_CUT_STRIDE, sameNumbers } from './flush-clip.js';+import { findFlushPairs, float32Step, worldBounds } from './flush-search.js';const COLLAPSED_AXIS_SHARE = 1e-3;+const CACHED_ORDERS_PER_GEOMETRY = 8;++// Kept between runs, so a part whose ranks and cuts did not change keeps its order object and the renderer keeps its batch.+const ordersByGeometry = new WeakMap();// 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.@@ -15,35 +22,124 @@ function frontOf(pair, areas) {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) {+// Lifts the front triangle of every pair above its back triangle, once. Returns whether a rank moved.+function liftFronts(ranks, edges, overflow) {+ let 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) {+ if (overflow) overflow[front] = 1;+ continue;+ }+ ranks[front] = wanted;+ moved = true;+ }+ return moved;+}++// Rank = the longest chain of triangles behind this one. A chain longer than the top rank (or a cycle of slightly tilted+// planes) stops there and is marked. `seamEdges` are pairs that were cut: what is left of them shares only the hair of+// overlap a cut leaves, so they take a rank where one is free and are dropped without a mark where the ranks ran out.+function rankTriangles(count, edges, seamEdges) {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;+ for (let pass = 0; pass <= MAXIMUM_FLUSH_RANK + 1 && liftFronts(ranks, edges, overflow); pass++);+ for (let pass = 0; pass <= MAXIMUM_FLUSH_RANK + 1; pass++) {+ const seamMoved = liftFronts(ranks, seamEdges, null);+ const moved = liftFronts(ranks, edges, null);+ if (!seamMoved && !moved) break;+ }+ return { ranks, overflow };+}++// Whether the back triangle of a pair can be cut away under the front one: they lie on one plane and face the same way, the+// front one hides what is under it, and no side of the back one stays in view where the front one is culled.+function canCut(pair, frontPart, backPart) {+ if (!pair.flush || pair.opposite || pair.area < FLUSH_CUT_MINIMUM_AREA) return false;+ if ((frontPart.material?.alphaMode ?? 'opaque') !== 'opaque') return false;+ return backPart.material?.doubleSided !== true || frontPart.material?.doubleSided === true;+}++function columnLength(matrix, column) {+ return Math.hypot(matrix[column], matrix[column + 1], matrix[column + 2]);+}++// The float32 step of the world coordinates a part is drawn at, in the units of its geometry.+function coordinateStep(part) {+ const largest = worldBounds(part).reduce((most, value) => Math.max(most, Math.abs(value)), 0);+ return float32Step(largest) / Math.min(columnLength(part.matrix, 0), columnLength(part.matrix, 4), columnLength(part.matrix, 8));+}++// The cuts of one part for clipFlushOverlaps, sorted by the triangle that is cut; null when the part's matrix has no inverse.+// A winner in the same part is read from the geometry, so instances of one geometry get the same cuts and share the result.+function cutRecords(found, partIndex, cutPairs) {+ const part = found.parts[partIndex];+ const { positions, indices } = part.geometry;+ const inverse = mat4.invert(new Float64Array(16), part.matrix);+ if (!inverse) return null;+ cutPairs.sort((one, other) => found.local[one.back] - found.local[other.back] || one.front - other.front);+ const cuts = new Float64Array(cutPairs.length * FLUSH_CUT_STRIDE);+ cutPairs.forEach(({ back, front }, index) => {+ const offset = index * FLUSH_CUT_STRIDE;+ cuts[offset] = found.local[back];+ for (let corner = 0; corner < 3; corner++) {+ const target = offset + 1 + corner * 3;+ if (found.owner[front] === partIndex) {+ const vertex = indices[found.local[front] * 3 + corner] * 3;+ cuts.set(positions.subarray(vertex, vertex + 3), target);continue;}- ranks[front] = wanted;- moved = true;+ const x = found.corners[front * 9 + corner * 3];+ const y = found.corners[front * 9 + corner * 3 + 1];+ const z = found.corners[front * 9 + corner * 3 + 2];+ cuts[target] = inverse[0] * x + inverse[4] * y + inverse[8] * z + inverse[12];+ cuts[target + 1] = inverse[1] * x + inverse[5] * y + inverse[9] * z + inverse[13];+ cuts[target + 2] = inverse[2] * x + inverse[6] * y + inverse[10] * z + inverse[14];}+ });+ return cuts;+}++// A part's geometry with its hidden flush faces cut away, as `{ geometry, sources }` of clipFlushOverlaps. A part that+// cannot be cut, or that would lose every triangle, keeps its geometry and its pairs are ranked instead. A pair whose back+// triangle is still partly there goes to `seamEdges`.+function clipPart(found, partIndex, cutPairs, edges, seamEdges) {+ const part = found.parts[partIndex];+ const uncut = { geometry: part.geometry, sources: null };+ if (cutPairs.length === 0) return uncut;+ const cuts = cutRecords(found, partIndex, cutPairs);+ const clipped = cuts ? clipFlushOverlaps(part.geometry, cuts, coordinateStep(part)) : uncut;+ if (!cuts || clipped.geometry.indices.length === 0) {+ for (const { back, front } of cutPairs) edges.push(back, front);+ return uncut;}- return { ranks, overflow };+ if (!clipped.sources) return clipped;+ const left = new Uint8Array(part.geometry.indices.length / 3);+ for (const source of clipped.sources) left[source] = 1;+ for (const { back, front } of cutPairs) {+ if (left[found.local[back]]) seamEdges.push(back, front);+ }+ return clipped;}-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;+// The order a part draws with, or null when it has neither a cut nor a rank. `triangleRanks` counts the uncut triangles.+function flushOrderFor({ geometry, sources }, triangleRanks) {+ if (!sources && !triangleRanks) return null;+ let drawnRanks = triangleRanks;+ if (sources) drawnRanks = triangleRanks ? Uint8Array.from(sources, source => triangleRanks[source]) : new Uint8Array(sources.length);+ const orders = ordersByGeometry.get(geometry) ?? [];+ ordersByGeometry.set(geometry, orders);+ let order = orders.find(candidate => sameNumbers(candidate.triangleRanks, drawnRanks));+ if (!order) {+ order = createFlushOrder(geometry.indices, drawnRanks);+ // A cut part draws its cut vertices; the order's indices are that geometry's triangles, sorted by rank.+ if (sources) order.geometry = { ...geometry, indices: order.indices };+ orders.push(order);+ if (orders.length > CACHED_ORDERS_PER_GEOMETRY) orders.shift();}- return true;+ return order;}// The geometry's indices sorted by rank (triangles of one rank keep their order) and the index range of each rank.@@ -74,11 +170,13 @@ function hasCollapsedAxis(matrix) {}/**- * 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).+ * Finds the near-coplanar triangles of `parts` and stores a draw order beside every part that needs one (`flushOrderOf(part)`+ * in depth-layer.js); parts, geometries and matrices are left as they are. An order holds the triangles sorted by rank and,+ * for a part with faces cut away, the cut `geometry` they index. Parts that share a geometry and agree on every cut and 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` (more than 16 faces a small gap apart), `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);@@ -91,6 +189,8 @@ export function resolveFlush(parts, options) {leftovers.set(key, entry);};const edges = [];+ const seamEdges = [];+ const cutPairs = found.parts.map(() => []);for (const pair of pairs) {const firstPart = found.parts[owner[pair.first]];const secondPart = found.parts[owner[pair.second]];@@ -102,9 +202,12 @@ export function resolveFlush(parts, options) {continue;}const front = frontOf(pair, areas);- edges.push(front === pair.first ? pair.second : pair.first, front);+ const back = front === pair.first ? pair.second : pair.first;+ if (canCut(pair, found.parts[owner[front]], found.parts[owner[back]])) cutPairs[owner[back]].push({ back, front });+ else edges.push(back, front);}- const { ranks, overflow } = rankTriangles(count, edges);+ const clippedParts = found.parts.map((part, partIndex) => clipPart(found, partIndex, cutPairs[partIndex], edges, seamEdges));+ const { ranks, overflow } = rankTriangles(count, edges, seamEdges);const partRanks = found.parts.map(() => null);for (let id = 0; id < count; id++) {if (overflow[id]) note('rank-overflow', found.parts[owner[id]]);@@ -112,24 +215,13 @@ export function resolveFlush(parts, options) {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);- }+ const partIndex = searched.get(part);+ const order = partIndex === undefined ? null : flushOrderFor(clippedParts[partIndex], partRanks[partIndex]);setFlushOrder(part, order);- ranked++;+ if (order) ranked++;}for (const part of found.unchecked) note('unchecked', part, part.geometry.indices.length / 3);if (found.truncated) note('unchecked', { name: 'scene' }, 0);diff --git a/src/flush-search.js b/src/flush-search.jsindex 988585a3..14a370f0 100644--- a/src/flush-search.js+++ b/src/flush-search.js@@ -71,10 +71,14 @@ export function boundsDiagonal(bounds) {return Math.hypot(bounds[3] - bounds[0], bounds[4] - bounds[1], bounds[5] - bounds[2]);}+/** The distance between neighbouring float32 values at this magnitude. */+export function float32Step(magnitude) {+ return 2 ** (Math.floor(Math.log2(Math.max(magnitude, 1e-30))) - 23);+}+/** 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);+ return Math.max(1e-4, 8 * float32Step(largestCoordinate));}/** Same-facing planes up to this far apart (metres) can still fight far from the camera; `diagonal` spans both parts. */@@ -460,8 +464,8 @@ function testCell(cell, boxes, reach, testPair) {/*** 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+ * material? }`; deforming parts (isDeformingPart) are left out. Returns `{ parts, count, owner, local, areas, corners, pairs,+ * unchecked, truncated }`: `corners` holds nine world coordinates per triangle, `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@@ -470,7 +474,7 @@ function testCell(cell, boxes, reach, testPair) {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 };+ const result = { parts: entries.map(entry => entry.part), count: table.count, owner: table.owner, local: table.local, areas: table.areas, corners: table.corners, pairs: [], unchecked, truncated: false };if (table.count < 2) return result;const sceneBounds = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];for (const { bounds } of entries) {diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.jsindex aa156359..b92faf4e 100644--- a/src/path-tracer-scene.js+++ b/src/path-tracer-scene.js@@ -5,6 +5,7 @@ import { boxProjectedGeometry, columnLengths } from './export-box-uv.js';import { resolveTraceVolume } from './path-tracer-volume.js';import { resolveTraceSubsurface } from './path-tracer-subsurface.js';import { lightShapeSupport } from './shader-registry.js';+import { flushOrderOf } from './depth-layer.js';// The scene a path trace reads: every part flattened into one world-space triangle soup with per-vertex normals, UVs// and colours, one resolved material per part, the lights in plain arrays, and the environment map as a sampling table.@@ -174,7 +175,9 @@ function validatePart(part, geometry) {* ones the glTF export writes), and every map then reads them like those of an authored material.*/function traceGeometry(part) {- const geometry = part.skin ? skinnedGeometry(part) : part.geometry;+ // Faces hidden under a face on the same plane are cut away for the rasteriser (flush-resolve.js); rays get the same+ // geometry, or the two faces would split the hits between them.+ const geometry = part.skin ? skinnedGeometry(part) : flushOrderOf(part)?.geometry ?? part.geometry;const { boxMapScale = 0, boxMapAxis = 1 } = part.material ?? {};if (!(boxMapScale > 0)) return geometry;return boxProjectedGeometry(geometry, columnLengths(part.matrix ?? IDENTITY_MATRIX), boxMapScale, boxMapAxis);diff --git a/src/renderer.js b/src/renderer.jsindex 879912a5..274a059a 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -350,7 +350,11 @@ function validateLods(part, levels) {/** Every geometry a part can draw: its own, the levels of `lods` and the levels of `shadowLods`. */function partGeometries(part) {- return [part.geometry, ...(part.lods ?? []).map(level => level.geometry), ...(part.shadowLods ?? []).map(level => level.geometry)];+ const drawn = [part.geometry, ...(part.lods ?? []).map(level => level.geometry), ...(part.shadowLods ?? []).map(level => level.geometry)];+ // A part with hidden flush faces cut away draws its cut geometry, which lives and is released like any other.+ const clipped = flushOrderOf(part)?.geometry;+ if (clipped) drawn.push(clipped);+ return drawn;}/** The state of one list of levels: errors, geometries, the draw of each level once it is first needed, and a selection. */@@ -1021,11 +1025,12 @@ export class Renderer67 {levelDraw(batch, level, levelSet = batch) {if (levelSet.levelDraws[level]) return levelSet.levelDraws[level];const context = this.context;- const geometry = levelSet.levelGeometries[level];+ const ranked = levelSet === batch && level === 0;+ const geometry = (ranked && batch.flushOrder?.geometry) || levelSet.levelGeometries[level];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);+ if (batch.flushIndexBuffer && ranked) context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, batch.flushIndexBuffer);const instanceBuffer = context.createBuffer();this.buffers.push(instanceBuffer);context.bindBuffer(context.ARRAY_BUFFER, instanceBuffer);@@ -1095,10 +1100,11 @@ export class Renderer67 {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;+ // A cut geometry carries the ranked order as its own indices. Without cuts the ranked order replaces the geometry's+ // index buffer in this vertex array only; the vertex buffers stay shared.+ this.bindGeometryAttributes(flushOrder?.geometry ?? geometry, parts[0].material);+ const flushIndexBuffer = flushOrder && !flushOrder.geometry ? this.uploadBuffer(context.ELEMENT_ARRAY_BUFFER, flushOrder.indices) : null;const stride = INSTANCE_STRIDE;const instanceData = new Float32Array(parts.length * stride);const normalMatrix = mat3.create();@@ -1126,7 +1132,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]), flushOrder, flushIndexBuffer, 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: flushOrder?.indices.length ?? 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) }));diff --git a/tests/coplanar-overlap.test.js b/tests/coplanar-overlap.test.jsindex 8b3f9c6f..0c3e320e 100644--- a/tests/coplanar-overlap.test.js+++ b/tests/coplanar-overlap.test.js@@ -74,22 +74,24 @@ test('decal, depthLayer and resolveCoplanar all silence the pair without movingconst [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.ok(flushOrderOf(wallPart).geometry, 'the wall is cut where the faces of the sign cover it');+ assert.deepEqual(flushOrderOf(wallPart).ranges.map(range => range.rank), [0]);+ assert.deepEqual(flushOrderOf(signPart).ranges.map(range => range.rank), [0, 1], 'the faces of the sign on the wall win the hair of overlap a cut leaves');+ assert.equal(flushOrderOf(signPart).geometry, undefined);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 });+ assert.deepEqual(inspection.flush, { ranked: 2 });}});-test('switching resolveCoplanar off drops the ranks and brings the pair report back', () => {+test('switching resolveCoplanar off drops the cuts and 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));+ const wallPart = scene.parts.find(part => part.name === 'wall');+ assert.ok(flushOrderOf(wallPart));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);+ assert.equal(flushOrderOf(wallPart), null);const inspection = scene.inspect();assert.equal(inspection.diagnostics.filter(entry => entry.kind === 'coplanar-overlap').length, 1);assert.equal(inspection.flush, undefined);@@ -129,8 +131,8 @@ test('renderer diagnostics carry the same warning, and a decal batches apart froconst problems = frameDiagnostics({ world: false, depth: true, effects: resolveEffects({}), coplanarProblems });assert.deepEqual(problems.map(problem => problem.kind), ['coplanar-overlap']);assert.equal(groupParts(scene.parts).length, 1);- 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.equal(resolveFlushParts(scene.parts).ranked, 2);+ assert.equal(groupParts(scene.parts).length, 2, 'the cut wall draws its own geometry, so it batches apart from the sign');assert.deepEqual(installCoplanarDiagnostics({}).coplanarDiagnostics([{ parts: scene.parts }]), [], 'a ranked pair is settled, not reported');clearFlushParts(scene.parts);assert.equal(groupParts(scene.parts).length, 1);@@ -207,13 +209,15 @@ test('hundreds of copies parked at one spot cost two parts, not every pair amongassert.ok(work < 100);});-test('flush parts get their ranks beside the part, so the part objects and updateParts keep working', () => {+test('flush parts get their order 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);+ const roadGeometry = road.geometry;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(road.geometry, roadGeometry);+ assert.equal(flushOrderOf(road).geometry.indices.length, (16 - 4) * 2 * 3, 'the four road cells under the marking are gone');+ assert.equal(flushOrderOf(marking), null);assert.equal(flushOrderOf(far), null);assert.equal(depthLayerOf(marking), 0);assert.equal(marking.depthLayer, undefined);@@ -238,29 +242,31 @@ 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 ranks exactly flush pairs too, on every depth format', () => {+test('resolveFlushParts settles exactly flush pairs too, on every depth format', () => {const road = gridPart('roadExact', 4, 4, 0);const marking = gridPart('markingExact', 2, 2, 0);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');+ assert.deepEqual(flushOrderOf(road).ranges.map(range => range.rank), [0]);+ assert.equal(flushOrderOf(marking), null);+ assert.deepEqual(findCoplanarOverlaps([road, marking]).overlaps, [], 'a settled pair is no longer reported');});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 middle = gridPart('chainMiddle', 5, 1, 0.0002);+ const small = gridPart('chainSmall', 2, 1, 0.0004);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 stack = Array.from({ length: 8 }, (unused, index) => gridPart(`stack${index}`, 10 - index, 1, index * 0.0005));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 deep = Array.from({ length: 20 }, (unused, index) => gridPart(`deep${index}`, 20 - index, 1, index * 0.0005));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));+ const onOnePlane = Array.from({ length: 20 }, (unused, index) => gridPart(`plane${index}`, 20 - index, 1, 0));+ assert.deepEqual(resolveFlushParts(onOnePlane).leftovers, [], 'on one plane the hidden faces are cut away, however deep the stack');});diff --git a/tests/flush-clip.test.js b/tests/flush-clip.test.jsnew file mode 100644index 00000000..26ec0abf--- /dev/null+++ b/tests/flush-clip.test.js@@ -0,0 +1,130 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { clipFlushOverlaps, FLUSH_CUT_STRIDE } from '../src/flush-clip.js';++// A unit square on the plane y = 0 as two triangles, with a UV, a colour and a sky value that are linear in x and z.+function squareGeometry() {+ const corners = [[0, 0], [0, 1], [1, 1], [1, 0]];+ return {+ positions: new Float32Array(corners.flatMap(([x, z]) => [x, 0, z])),+ normals: new Float32Array(corners.flatMap(() => [0, 1, 0])),+ uvs: new Float32Array(corners.flatMap(([x, z]) => [x, z])),+ colors: new Float32Array(corners.flatMap(([x, z]) => [x, z, 0.5])),+ skyVisibility: new Float32Array(corners.map(([x, z]) => 0.25 * x + 0.5 * z)),+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),+ };+}++// One cut per triangle of the square for every winner, sorted by the triangle that is cut.+function cutsOf(winners, triangles = [0, 1]) {+ const cuts = [];+ for (const triangle of triangles) {+ for (const winner of winners) cuts.push(triangle, ...winner.flatMap(([x, z]) => [x, 0, z]));+ }+ assert.equal(cuts.length % FLUSH_CUT_STRIDE, 0);+ return new Float64Array(cuts);+}++function triangleNormalAndArea(positions, indices, triangle) {+ const [first, second, third] = [0, 1, 2].map(corner => indices[triangle * 3 + corner] * 3);+ const edgeOne = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);+ const edgeTwo = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);+ const normal = [edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]];+ return { normal, area: Math.hypot(...normal) / 2 };+}++function areaOf(geometry) {+ let area = 0;+ for (let triangle = 0; triangle < geometry.indices.length / 3; triangle++) area += triangleNormalAndArea(geometry.positions, geometry.indices, triangle).area;+ return area;+}++const INSIDE = [[0.25, 0.25], [0.25, 0.75], [0.75, 0.25]];+const ACROSS_THE_CORNER = [[0.5, 0.5], [0.5, 1.5], [1.5, 0.5]];++test('what is left of the cut face and the face that covers it add up to the area of their union', () => {+ for (const { winner, shared } of [{ winner: INSIDE, shared: 0.125 }, { winner: ACROSS_THE_CORNER, shared: 0.25 }]) {+ const square = squareGeometry();+ const { geometry, sources } = clipFlushOverlaps(square, cutsOf([winner]));+ assert.notEqual(geometry, square);+ const winnerArea = 0.5 * (winner[1][1] - winner[0][1]) * (winner[2][0] - winner[0][0]);+ const union = 1 + winnerArea - shared;+ assert.ok(Math.abs(areaOf(geometry) + winnerArea - union) < 1e-6, `clipped ${areaOf(geometry)} against ${1 - shared}`);+ assert.equal(sources.length, geometry.indices.length / 3);+ assert.ok(sources.every(source => source === 0 || source === 1));+ }+});++test('two winners that overlap each other are still cut out once', () => {+ const square = squareGeometry();+ const second = [[0.25, 0.25], [0.75, 0.25], [0.75, 0.75]].map(([x, z]) => [x, z]);+ // INSIDE and `second` share the triangle between the centre and the edge z = 0.25: their union is 3/16.+ const { geometry } = clipFlushOverlaps(square, cutsOf([INSIDE, [second[0], second[2], second[1]]]));+ // Each cut stops four float32 steps inside its winner, which is worth about 1e-6 of area along these edges.+ assert.ok(Math.abs(areaOf(geometry) - (1 - 3 / 16)) < 2e-6);+});++test('every per-vertex array is interpolated for the new vertices, and the old vertices are kept as they were', () => {+ const square = squareGeometry();+ const { geometry } = clipFlushOverlaps(square, cutsOf([INSIDE]));+ const vertexCount = geometry.positions.length / 3;+ assert.ok(vertexCount > 4);+ assert.deepEqual(Array.from(geometry.positions.subarray(0, 12)), Array.from(square.positions));+ for (const [field, stride] of [['normals', 3], ['uvs', 2], ['colors', 3], ['skyVisibility', 1]]) {+ assert.equal(geometry[field].length, vertexCount * stride, field);+ assert.ok(geometry[field] instanceof Float32Array);+ }+ for (let vertex = 0; vertex < vertexCount; vertex++) {+ const x = geometry.positions[vertex * 3];+ const z = geometry.positions[vertex * 3 + 2];+ assert.equal(geometry.positions[vertex * 3 + 1], 0);+ assert.deepEqual(Array.from(geometry.normals.subarray(vertex * 3, vertex * 3 + 3)), [0, 1, 0]);+ assert.ok(Math.abs(geometry.uvs[vertex * 2] - x) < 1e-6 && Math.abs(geometry.uvs[vertex * 2 + 1] - z) < 1e-6);+ assert.ok(Math.abs(geometry.colors[vertex * 3] - x) < 1e-6 && Math.abs(geometry.colors[vertex * 3 + 2] - 0.5) < 1e-6);+ assert.ok(Math.abs(geometry.skyVisibility[vertex] - (0.25 * x + 0.5 * z)) < 1e-6);+ }+});++test('the pieces keep the winding of the face they were cut from', () => {+ const { geometry } = clipFlushOverlaps(squareGeometry(), cutsOf([ACROSS_THE_CORNER]));+ for (let triangle = 0; triangle < geometry.indices.length / 3; triangle++) {+ assert.ok(triangleNormalAndArea(geometry.positions, geometry.indices, triangle).normal[1] > 0);+ }+});++test('untouched geometry keeps its identity', () => {+ const square = squareGeometry();+ assert.deepEqual(clipFlushOverlaps(square, new Float64Array(0)), { geometry: square, sources: null });+ const beside = [[2, 0], [2, 1], [3, 0]];+ assert.equal(clipFlushOverlaps(square, cutsOf([beside])).geometry, square, 'a winner that does not reach the face cuts nothing');+ const alongTheEdge = [[1, 0], [1, 1], [2, 0]];+ assert.equal(clipFlushOverlaps(square, cutsOf([alongTheEdge])).geometry, square, 'sharing an edge is not covering');+});++test('a fully covered triangle is dropped, and the other triangles keep their vertices', () => {+ const square = squareGeometry();+ const firstTriangle = [[0, 0], [0, 1], [1, 1]];+ const { geometry, sources } = clipFlushOverlaps(square, cutsOf([firstTriangle], [0]));+ assert.deepEqual(Array.from(geometry.indices), [0, 2, 3]);+ assert.deepEqual(Array.from(sources), [1]);+ assert.equal(geometry.positions.length, square.positions.length, 'no vertex was needed');+ const everything = [[-1, -1], [-1, 3], [3, -1]];+ assert.equal(clipFlushOverlaps(square, cutsOf([everything])).geometry.indices.length, 0);+});++test('the same cuts on the same geometry return the same object', () => {+ const square = squareGeometry();+ const first = clipFlushOverlaps(square, cutsOf([INSIDE]));+ assert.equal(clipFlushOverlaps(square, cutsOf([INSIDE])), first);+ assert.notEqual(clipFlushOverlaps(square, cutsOf([ACROSS_THE_CORNER])), first);+ assert.notEqual(clipFlushOverlaps(squareGeometry(), cutsOf([INSIDE])), first);+});++test('a cut stops a few float32 steps inside the winner, so the two faces overlap instead of opening a seam', () => {+ const square = squareGeometry();+ const { geometry } = clipFlushOverlaps(square, cutsOf([INSIDE]), 1e-4);+ // With a coordinate step of 0.1 mm the hole is the winner pulled in by 0.4 mm on each of its three edges.+ const inradius = 2 * 0.125 / (0.5 + 0.5 + Math.SQRT1_2);+ const shrunk = 0.125 * ((inradius - 4e-4) / inradius) ** 2;+ assert.ok(Math.abs(1 - areaOf(geometry) - shrunk) < 1e-6);+});diff --git a/tests/flush-resolve.test.js b/tests/flush-resolve.test.jsindex 238f0ae6..925cd73d 100644--- a/tests/flush-resolve.test.js+++ b/tests/flush-resolve.test.js@@ -34,6 +34,19 @@ function ranksOf(part) {return order ? Array.from(order.triangleRanks) : null;}+// The area a part draws: its cut geometry when it has one.+function drawnArea(part) {+ const { positions, indices } = flushOrderOf(part)?.geometry ?? part.geometry;+ let area = 0;+ for (let index = 0; index < indices.length; index += 3) {+ const [first, second, third] = [indices[index] * 3, indices[index + 1] * 3, indices[index + 2] * 3];+ const edgeOne = [0, 1, 2].map(axis => positions[second + axis] - positions[first + axis]);+ const edgeTwo = [0, 1, 2].map(axis => positions[third + axis] - positions[first + axis]);+ area += Math.hypot(edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1], edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2], edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0]) / 2;+ }+ return area;+}+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)]);@@ -57,17 +70,43 @@ test('the surface in front along the normal gets the higher rank, whatever the passert.equal(flushOrderOf(ceiling), null);});-test('on one plane the smaller face wins, then the later one, and chains count up', () => {+test('on one plane the smaller face wins, then the later one, and the face under it is cut away instead of ranked', () => {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]);+ assert.deepEqual(resolveFlush([kitbash]), { ranked: 1, leftovers: [] });+ assert.equal(Math.max(...ranksOf(kitbash)), 2, 'the faces keep their order for the hair of overlap a cut leaves');+ assert.ok(Math.abs(drawnArea(kitbash) - 10) < 1e-3, 'the three faces draw the area of their union once');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]);+ assert.deepEqual(Array.from(flushOrderOf(twin).geometry.indices), [4, 5, 6, 4, 6, 7], 'the earlier twin is dropped whole');+ const tiny = partOf('tiny', [quadCorners(0, 0, 0.009, 0.009, 0), quadCorners(0, 0, 0.009, 0.009, 0)]);+ resolveFlush([tiny]);+ assert.deepEqual(ranksOf(tiny), [0, 0, 1, 1], 'a shared area under 1 cm2 is ranked, not cut');+ assert.equal(flushOrderOf(tiny).geometry, undefined);+});++test('a face is only cut under a face that hides it from every side it shows', () => {+ const glass = partOf('glass', [quadCorners(1, 1, 1, 1, 0)], { material: { alphaMode: 'blend' } });+ const wall = partOf('wall', [quadCorners(0, 0, 4, 4, 0)]);+ resolveFlush([wall, glass]);+ assert.equal(flushOrderOf(wall), null, 'the wall stays whole behind a blended face');+ assert.deepEqual(ranksOf(glass), [1, 1]);+ const leaf = partOf('leaf', [quadCorners(0, 0, 4, 4, 0)], { material: { doubleSided: true } });+ const patch = partOf('patch', [quadCorners(1, 1, 1, 1, 0)]);+ resolveFlush([leaf, patch]);+ assert.equal(flushOrderOf(leaf), null, 'the back of a double-sided face shows where a one-sided patch is culled');+ assert.deepEqual(ranksOf(patch), [1, 1]);+});++test('a part hidden whole keeps its geometry and is ranked under what hides it', () => {+ const lower = partOf('lower', [quadCorners(0, 0, 1, 1, 0)]);+ const upper = partOf('upper', [quadCorners(0, 0, 1, 1, 0)]);+ assert.deepEqual(resolveFlush([lower, upper]), { ranked: 1, leftovers: [] });+ assert.equal(flushOrderOf(lower), null);+ assert.deepEqual(ranksOf(upper), [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 kitbash = partOf('kitbash', [quadCorners(0, 0, 2, 1, 0.002), quadCorners(0, 0, 10, 1, 0), quadCorners(0, 0, 5, 1, 0.001)]);const original = Array.from(kitbash.geometry.indices);const geometry = kitbash.geometry;resolveFlush([kitbash]);@@ -78,15 +117,26 @@ test('the ranked order holds every triangle once, sorted by rank, and leaves theassert.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)));+test('a stack of 20 or 30 faces on one plane is cut down to what shows and reports nothing', () => {+ for (const depth of [20, 30]) {+ const staggered = partOf('staggered', Array.from({ length: depth }, (unused, index) => quadCorners(0, 0, depth - index, 1, 0)));+ assert.deepEqual(resolveFlush([staggered]), { ranked: 1, leftovers: [] });+ assert.ok(Math.abs(drawnArea(staggered) - depth) < 1e-2);+ const exact = partOf('exact', Array.from({ length: depth }, () => quadCorners(0, 0, 3, 2, 0)));+ assert.deepEqual(resolveFlush([exact]), { ranked: 1, leftovers: [] });+ assert.deepEqual(Array.from(flushOrderOf(exact).geometry.indices), [0, 1, 2, 0, 2, 3].map(index => index + (depth - 1) * 4), 'only the last face is drawn');+ }+});++test('a stack of 20 faces half a millimetre apart 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, index * 0.0005)));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)));+ const shallow = partOf('shallow', Array.from({ length: 16 }, (unused, index) => quadCorners(0, 0, 20 - index, 1, index * 0.0005)));assert.deepEqual(resolveFlush([shallow]).leftovers, []);});@@ -95,25 +145,41 @@ test('untouched parts keep their identity and get no order; a stale order is droconst 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);+ const wallGeometry = wall.geometry;+ const wallIndices = Array.from(wall.geometry.indices);+ assert.equal(resolveFlush(parts).ranked, 2);+ const cut = flushOrderOf(wall);+ assert.ok(cut.geometry, 'the wall is cut under the plaque');+ assert.ok(Math.abs(drawnArea(wall) - 15) < 1e-4);+ assert.equal(wall.geometry, wallGeometry, 'the cut geometry sits beside the part');+ assert.deepEqual(Array.from(wall.geometry.indices), wallIndices);+ assert.deepEqual(ranksOf(plaque), [1, 1]);+ assert.equal(flushOrderOf(plaque).geometry, undefined);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);+ assert.deepEqual(Object.keys(wall), ['name', 'geometry', 'matrix', 'material']);+ assert.equal(resolveFlush(parts).ranked, 2);+ assert.equal(flushOrderOf(wall), cut, 'the same cuts give the same order, so the renderer keeps its batch');+ assert.equal(resolveFlush([wall, far]).ranked, 0, 'without the plaque nothing covers the wall');+ assert.equal(flushOrderOf(wall), 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 onFloorOne = { ...tile, name: 'onFloorOne', matrix: new Float32Array(movedTo(1, 0.001, 1)) };+ const onFloorTwo = { ...tile, name: 'onFloorTwo', matrix: new Float32Array(movedTo(5, 0.001, 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);+ // Faces cut inside one geometry are the same cut in every instance, wherever it stands.+ const doubled = partOf('doubled', [quadCorners(0, 0, 2, 2, 0), quadCorners(0.5, 0.5, 1, 1, 0)]);+ const copy = { ...doubled, name: 'copy', matrix: new Float32Array(movedTo(40, 3, -7)) };+ assert.equal(resolveFlush([doubled, copy]).ranked, 2);+ assert.ok(flushOrderOf(doubled).geometry);+ assert.equal(flushOrderOf(doubled), flushOrderOf(copy));});test('a decal or another depthLayer already clears the pair, so no rank is spent', () => {