Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a wireframe render pass for topology review

Nguyen Xuan An72c70075c4d8
diff --git a/changes/732-wireframe-pass.size.md b/changes/732-wireframe-pass.size.md
new file mode 100644
index 00000000..fd6b96d8
--- /dev/null
+++ b/changes/732-wireframe-pass.size.md
@@ -0,0 +1 @@
+- goal:agent-scene: 60 bytes gzip for the pass name and its one-line colour legend in scene_capabilities, which an agent needs to read the wireframe picture; the drawing code loads only for a job that asks for the pass
diff --git a/changes/732.md b/changes/732.md
new file mode 100644
index 00000000..1b5f5f85
--- /dev/null
+++ b/changes/732.md
@@ -0,0 +1 @@
+- Render jobs take a `wireframe` pass that draws polygon edges over the shaded surface and colours boundary, non-manifold, flipped and degenerate edges for visual review (#732)
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index eb5ca96e..c16efc5b 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -105,7 +105,7 @@ and a click placed on a cut in a WAV lands on the decoded cut frame within a fra
## Render passes
-`image` and `stills` jobs accept `settings.passes`, a list of `albedo`, `normal`, `emission`, `depth`, `objectId`, `diffuse`, `glossy`, `shadow`, `ao`, `mist`, `position`, `velocity`, `uv`, `transmission`, `volume`, `environment`, `cryptomatte` and `aov`.
+`image` and `stills` jobs accept `settings.passes`, a list of `albedo`, `normal`, `emission`, `depth`, `objectId`, `diffuse`, `glossy`, `shadow`, `ao`, `mist`, `position`, `velocity`, `uv`, `transmission`, `volume`, `environment`, `cryptomatte`, `aov` and `wireframe`.
Each frame writes its lit image and then one PNG per pass: `render.png` and `render-<pass>.png` for an image, `frame-N.png` and `frame-N-<pass>.png` for stills.
Passes are raw data at the lit image's size: no tone mapping, grading, bloom, depth of field or antialiasing, so values stay exact at silhouettes.
Only opaque and cutout geometry appears. Liquid, foam and blended parts, the sky and the environment background do not.
@@ -130,6 +130,24 @@ Only opaque and cutout geometry appears. Liquid, foam and blended parts, the sky
| `environment` | Image-based / sky environment lighting contribution times exposure. Background 0 |
| `cryptomatte` | Deterministic float hash per object in red, per material in green and coverage `1` in blue (`metrics.cryptomatte` holds the `{ objects, materials }` manifest). Background 0 |
| `aov` | Custom material AOV from `material.aov` (`0..1` scalar or RGB) and/or a material graph's `aov` output. Background 0 |
+| `wireframe` | The `diffuse` surface with every polygon edge drawn over it, for reviewing topology; see below. Background light grey |
+
+### Wireframe pass
+
+The wireframe pass shows the topology of the mesh a part really has, without changing its geometry or vertex count. It draws the polygon edges of each part (a recipe mesh's own quads and n-gons, or the welded, quad-joined view of other geometry, the same view `mesh_inspect` reads), so the diagonals that triangulation adds inside a planar quad are never drawn and a quad reads as a quad. Edges hidden behind a surface stay hidden.
+
+| Edge colour | Meaning | `mesh_inspect` problem |
+| --- | --- | --- |
+| dark | Regular edge: two faces, wound the same way round it | |
+| orange | Boundary edge: one face, an open rim | `boundary-edge` |
+| red | Non-manifold edge: three or more faces | `non-manifold-edge` |
+| cyan | Flipped edge: two faces that run the same way along it, so one normal points the wrong way | `inconsistent-winding` |
+| magenta | Edge of a degenerate (zero-area) face | `degenerate-face` |
+
+Fault edges are drawn about twice as wide as regular ones. An edge with several faults shows the most urgent one: non-manifold, then degenerate, then flipped, then boundary.
+The job metrics carry `metrics.wireframe`: `edges` (the count of each kind over the drawn parts), `faultyParts` (up to 20 parts, worst first, each with its fault counts so a coloured edge maps to a node name), `faultyPartsOmitted`, `partsOmitted` and `partsSkipped`, and `truncated`.
+Output is bounded: a mesh contributes at most 200,000 edges and a frame at most 1,000,000. Fault edges are kept before regular ones, a part past the frame limit is left out and counted in `partsOmitted`, and a part with no polygon view (every triangle collapses) is counted in `partsSkipped`.
+The pass is 8-bit like the others, works with `png16` and `exr` and packs into a `multilayer` EXR. It shows rest geometry: skinning and morph targets are not applied to the edges.
The lighting passes hold linear values above 1, so write them as `exr` (a `png` or `png16` file clamps at 1). They add back to the lit image: `diffuse + glossy + emission * exposure` is the radiance before fog, and with an open world the lit image is that radiance mixed toward the fog colour by `mist`, then tone mapped. `tests/lighting-passes.test.js` checks the sum against the beauty frame (mean difference under 1.5 display levels, under 2% of samples off by more than 4). Not covered: unlit parts, the editor floor, parts that a probe or irradiance grid changes after the sky term, and anything the lit image adds after the shader (bloom, grading, depth of field).
diff --git a/package.json b/package.json
index 3a073c50..953e2a13 100644
--- a/package.json
+++ b/package.json
@@ -162,6 +162,7 @@
"smoke:agent-material-snippet": "node scripts/smoke-agent-material-snippet.mjs",
"smoke:agent-texture-sequence": "node scripts/smoke-agent-texture-sequence.mjs",
"smoke:render-passes": "node scripts/smoke-render-passes.mjs",
+ "smoke:wireframe-pass": "node scripts/smoke-wireframe-pass.mjs",
"smoke:object-motion-blur": "node scripts/smoke-object-motion-blur.mjs",
"smoke:path-tracer": "node scripts/smoke-path-tracer.mjs",
"smoke:film-timeline": "node scripts/smoke-film-timeline.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index a3315dd9..29c5f8ae 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -824,12 +824,14 @@ window.__agentPreview = {
? { ...record.scene.effects, depthOfField: { ...record.scene.effects.depthOfField, ...depthOfFieldOverrides } }
: undefined;
const outputFramebuffer = floatOutput && !pass ? record.floatModule.outputFor(record, canvas).framebuffer : undefined;
- draw(record, rendererTime, shotCamera, { pass, passDepthRange, passFloat, previousCamera, outputFramebuffer, ...(objectMotion ? { objectMotion } : {}),
+ const drawFrame = () => draw(record, rendererTime, shotCamera, { pass, passDepthRange, passFloat, previousCamera, outputFramebuffer, ...(objectMotion ? { objectMotion } : {}),
...(brightness === 1 ? {} : { exposure }), ...(shotEffects ? { effects: shotEffects } : {}) });
+ const wireframe = pass === 'wireframe' ? record.wireframeModule.withWireframe(record.renderer, drawFrame) : drawFrame();
// The first lit frame of a job is checked; a pass or a fade has no exposure to judge.
const checkLitFrame = diagnose && !pass && !floatOutput && brightness === 1;
const info = renderInfo(record.renderer, pass ? [] : viewProblems(record, shotCamera ?? record.scene.camera, checkLitFrame ? record.scene.effects.exposure : undefined));
- return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() }
+ return pass === 'wireframe' ? { ...info, wireframe }
+ : pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() }
: pass === 'cryptomatte' ? { ...info, cryptomatte: record.renderer.passSupport.cryptomatteManifest() }
: info;
},
@@ -839,6 +841,10 @@ window.__agentPreview = {
async prepareFloatOutput({ sessionId }) {
requireSession(sessionId).floatModule = await import('../src/float-output.js');
},
+ // The wireframe pass draws its edges with this module, loaded here so a scene that never asks for it does not carry it.
+ async prepareWireframe({ sessionId }) {
+ requireSession(sessionId).wireframeModule = await import('../src/wireframe-pass.js');
+ },
readFloat({ sessionId, source, region }) {
const record = requireSession(sessionId);
return record.floatModule.readFrame(record, canvas, source, region);
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 5be00e48..58d6808b 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -442,6 +442,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
const session = await jobPage.context().newCDPSession(jobPage);
const region = settings.region;
if (settings.format && settings.format !== 'png') await jobPage.evaluate(prepareInput => window.__agentPreview.prepareFloatOutput(prepareInput), { sessionId: jobId });
+ if (settings.passes?.includes('wireframe')) await jobPage.evaluate(prepareInput => window.__agentPreview.prepareWireframe(prepareInput), { sessionId: jobId });
// A memory budget can shrink the frame below the size the region was chosen for.
if (region && (region.x + region.width > width || region.y + region.height > height)) {
throw new Error(`The region lies outside the rendered frame, which the memory budget reduced to ${width}x${height}.`);
@@ -627,6 +628,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
metrics.objectNamesTruncated = passInfo.objectNames.length > MAXIMUM_OBJECT_NAMES;
}
if (pass === 'cryptomatte') metrics.cryptomatte = passInfo.cryptomatte;
+ if (pass === 'wireframe') metrics.wireframe = passInfo.wireframe;
}
const encodedBytes = encodeMultilayerExr({ width: beautyRead.width, height: beautyRead.height, beauty: beautyRead.pixels, passes: passPixels, hasAlpha: settings.transparent === true, depthRange: RENDER_PASS_DEPTH_RANGE });
metrics.captureSeconds += (performance.now() - captureStarted) / 1000;
@@ -640,6 +642,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
{ ...frameInput, floatOutput: false, pass, passDepthRange: RENDER_PASS_DEPTH_RANGE, ...(highPrecision ? { passFloat: true } : {}) });
await writeArtifact(`${stem}-${pass}.${artifactExtension}`, highPrecision ? await captureHighPrecisionBytes(pass) : await captureFrameBytes());
if (pass === 'cryptomatte') metrics.cryptomatte = passInfo.cryptomatte;
+ if (pass === 'wireframe') metrics.wireframe = passInfo.wireframe;
if (pass === 'depth') metrics.depthRangeMetres = RENDER_PASS_DEPTH_RANGE;
if (pass === 'objectId') {
metrics.objectNames = passInfo.objectNames.slice(0, MAXIMUM_OBJECT_NAMES);
diff --git a/scripts/smoke-wireframe-pass.mjs b/scripts/smoke-wireframe-pass.mjs
new file mode 100644
index 00000000..c305c994
--- /dev/null
+++ b/scripts/smoke-wireframe-pass.mjs
@@ -0,0 +1,151 @@
+// Proves the wireframe pass through the real MCP runtime and a browser: a clean box, a box with its top deleted and a box with
+// one flipped face are drawn in one render job, and the picture holds the fault colours in the right amounts.
+import assert from 'node:assert/strict';
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { inflateSync } from 'node:zlib';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-wireframe-'));
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const backend = process.argv[3] ?? 'cpu';
+const SIZE = 320;
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', backend, '--memory', '128', '--jobs', join(directory, 'jobs')], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-wireframe-proof', version: '1' });
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function finished(jobId) {
+ const deadline = Date.now() + 120000;
+ while (Date.now() < deadline) {
+ const record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) return record;
+ await delay(100);
+ }
+ throw new Error('Job did not finish within 120 seconds.');
+}
+
+function paeth(left, up, upLeft) {
+ const estimate = left + up - upLeft;
+ const toLeft = Math.abs(estimate - left);
+ const toUp = Math.abs(estimate - up);
+ const toUpLeft = Math.abs(estimate - upLeft);
+ if (toLeft <= toUp && toLeft <= toUpLeft) return left;
+ return toUp <= toUpLeft ? up : upLeft;
+}
+
+// Reads an 8-bit RGB or RGBA PNG, the only kind the render jobs write here.
+function decodePng(bytes) {
+ let offset = 8;
+ let header = null;
+ const chunks = [];
+ while (offset < bytes.length) {
+ const length = bytes.readUInt32BE(offset);
+ const type = bytes.toString('latin1', offset + 4, offset + 8);
+ const data = bytes.subarray(offset + 8, offset + 8 + length);
+ if (type === 'IHDR') header = { width: data.readUInt32BE(0), height: data.readUInt32BE(4), depth: data[8], colorType: data[9] };
+ if (type === 'IDAT') chunks.push(data);
+ offset += 12 + length;
+ }
+ assert.equal(header.depth, 8);
+ const channels = header.colorType === 6 ? 4 : 3;
+ const stride = header.width * channels;
+ const raw = inflateSync(Buffer.concat(chunks));
+ const pixels = Buffer.alloc(stride * header.height);
+ for (let row = 0; row < header.height; row++) {
+ const filter = raw[row * (stride + 1)];
+ for (let column = 0; column < stride; column++) {
+ const value = raw[row * (stride + 1) + 1 + column];
+ const left = column >= channels ? pixels[row * stride + column - channels] : 0;
+ const up = row > 0 ? pixels[(row - 1) * stride + column] : 0;
+ const upLeft = row > 0 && column >= channels ? pixels[(row - 1) * stride + column - channels] : 0;
+ pixels[row * stride + column] = (value + [0, left, up, (left + up) >> 1, paeth(left, up, upLeft)][filter]) & 255;
+ }
+ }
+ return { channels, pixels };
+}
+
+function countNear(png, color) {
+ let count = 0;
+ for (let offset = 0; offset < png.pixels.length; offset += png.channels) {
+ if (color.every((value, channel) => Math.abs(png.pixels[offset + channel] - value) <= 24)) count++;
+ }
+ return count;
+}
+
+function recipe() {
+ const box = edits => ({ type: 'mesh', base: { type: 'box', bevel: 0 }, ...(edits ? { edits } : {}) });
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'clean', ...box() },
+ { id: 'open', ...box([{ op: 'delete', select: { tag: 'top' } }]) },
+ { id: 'flipped', ...box([{ op: 'flip_normals', select: { tag: 'top' } }]) },
+ ],
+ materials: [{ id: 'grey', color: [0.7, 0.7, 0.7], roughness: 0.8 }],
+ nodes: [
+ { id: 'clean-box', geometry: 'clean', material: 'grey', translation: [-2.4, 0.5, 0] },
+ { id: 'open-box', geometry: 'open', material: 'grey', translation: [0, 0.5, 0] },
+ { id: 'flipped-box', geometry: 'flipped', material: 'grey', translation: [2.4, 0.5, 0] },
+ ],
+ environment: { ground: false },
+ camera: { eye: [0, 3.2, 6.5], target: [0, 0.5, 0], fov: 55 },
+ };
+}
+
+async function runJob(sessionId, settings) {
+ const submitted = (await call('scene_render_submit', { sessionId, expectedRevision: 0, settings })).structuredContent;
+ const record = await finished(submitted.jobId);
+ assert.equal(record.state, 'completed', record.reason);
+ const result = (await call('scene_render_result', { jobId: submitted.jobId })).structuredContent;
+ const files = new Map();
+ for (const artifact of result.artifacts) files.set(artifact.path.split(/[\\/]/).pop(), await readFile(artifact.path));
+ await call('scene_render_release', { jobId: submitted.jobId });
+ return { files, metrics: result.metrics ?? record.metrics };
+}
+
+try {
+ await client.connect(transport);
+ const created = (await call('scene_create', { recipe: recipe() }, 180000)).structuredContent;
+ const { files, metrics } = await runJob(created.sessionId, { kind: 'image', width: SIZE, height: SIZE, passes: ['wireframe', 'diffuse'] });
+ if (process.env.WIREFRAME_COPY_DIRECTORY) await writeFile(join(process.env.WIREFRAME_COPY_DIRECTORY, 'render-wireframe.png'), files.get('render-wireframe.png'));
+ assert.equal(metrics.wireframe.edges.boundary, 4, 'The open box has one rim of four boundary edges.');
+ assert.equal(metrics.wireframe.edges.flipped, 4, 'The flipped top shares four edges with its neighbours.');
+ assert.equal(metrics.wireframe.edges.nonManifold, 0);
+ assert.equal(metrics.wireframe.edges.regular, 12 + 8 + 8);
+ assert.deepEqual(metrics.wireframe.faultyParts.map(part => part.part).sort(), ['flipped-box', 'open-box']);
+
+ const picture = decodePng(files.get('render-wireframe.png'));
+ assert.notDeepEqual(files.get('render-wireframe.png'), files.get('render-diffuse.png'), 'The wireframe pass must differ from the diffuse pass.');
+ const orange = countNear(picture, [255, 140, 0]);
+ const cyan = countNear(picture, [0, 217, 255]);
+ const dark = countNear(picture, [15, 18, 23]);
+ assert.ok(orange > 20, `Boundary edges should show in orange (${orange} pixels).`);
+ assert.ok(cyan > 20, `Flipped edges should show in cyan (${cyan} pixels).`);
+ assert.ok(dark > 100, `Regular edges should show dark (${dark} pixels).`);
+
+ // The pass also goes through the float target of 16-bit PNG and EXR output.
+ for (const format of ['png16', 'exr']) {
+ const highPrecision = await runJob(created.sessionId, { kind: 'image', width: SIZE, height: SIZE, format, passes: ['wireframe'] });
+ const filename = `render-wireframe.${format === 'exr' ? 'exr' : 'png'}`;
+ assert.ok(highPrecision.files.get(filename)?.length > 0, `${filename} is missing.`);
+ assert.deepEqual(highPrecision.metrics.wireframe.edges, metrics.wireframe.edges);
+ }
+ console.log(`wireframe pass smoke passed on ${backend}: orange ${orange}, cyan ${cyan}, dark ${dark} pixels, edges ${JSON.stringify(metrics.wireframe.edges)}`);
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close();
+}
diff --git a/src/agent-mesh.js b/src/agent-mesh.js
index 9ff4bbe4..88aafc72 100644
--- a/src/agent-mesh.js
+++ b/src/agent-mesh.js
@@ -165,6 +165,11 @@ function roundedBounds(bounds) {
return { min: bounds.min.map(round), max: bounds.max.map(round) };
}
+/** The polygon mesh behind renderer geometry: the recipe's own mesh when it has one, else the welded, quad-joined view. */
+export function polygonMeshOf(geometry) {
+ return polygonMeshes.get(geometry)?.mesh ?? meshFromGeometry(geometry);
+}
+
/**
* Polygon view and lint of renderer geometry: counts, face sizes, connected parts, face tags, bounds and problems
* with suggested fixes. The geometry is welded and joined into quads first, as meshFromGeometry does.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4e0225bc..50450f4a 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -98,8 +98,8 @@ export const LIGHTING_SETUP_NAMES = Object.freeze(['daylight', 'overcast', 'suns
export const DEFAULT_LIGHTING_SETUP = 'daylight';
export const DEFAULT_AMBIENT_OCCLUSION = 0;
-// Render passes a render job can write next to the lit image (see RENDER_PASS_MODES in renderer.js, which must list the same names).
-export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission', 'depth', 'objectId', 'diffuse', 'glossy', 'shadow', 'ao', 'mist', 'position', 'velocity', 'uv', 'transmission', 'volume', 'environment', 'cryptomatte', 'aov']);
+// Render passes a render job can write next to the lit image (see RENDER_PASS_MODES in render-passes.js, which lists the same names, wireframe being drawn as its diffuse mode).
+export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission', 'depth', 'objectId', 'diffuse', 'glossy', 'shadow', 'ao', 'mist', 'position', 'velocity', 'uv', 'transmission', 'volume', 'environment', 'cryptomatte', 'aov', 'wireframe']);
// Video encoders a render job can choose (nvenc is h264_nvenc and fails the job when the GPU or ffmpeg lacks it), the
// longest video, and the audio file names a job may mix in from the --audio folder: one path segment with a known
// extension, no drive or protocol syntax.
@@ -235,7 +235,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
materialMappings: MATERIAL_MAPPINGS,
- renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png/.exr or frame-N-<pass>.png/.exr (multilayer: true packs all into render.exr)', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; metrics.objectNames lists parts', cryptomatte: 'R object hash, G material hash, B coverage; metrics.cryptomatte holds manifests', aov: 'material.aov or pattern.graph.aov linear RGB' }),
+ renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png/.exr or frame-N-<pass>.png/.exr (multilayer: true packs all into render.exr)', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; metrics.objectNames lists parts', cryptomatte: 'R object hash, G material hash, B coverage; metrics.cryptomatte holds manifests', aov: 'material.aov or pattern.graph.aov linear RGB', wireframe: 'polygon edges over diffuse; open orange, non-manifold red, flipped cyan, degenerate magenta; metrics.wireframe' }),
// Recipe timeline (src/film-timeline.js), rendered with settings.timeline; the rest is in docs/agent-render-jobs.md.
filmTimeline: Object.freeze({
maxShots: 64, maxTotalSeconds: 60, maxShotSeconds: 30,
diff --git a/src/mesh-wireframe.js b/src/mesh-wireframe.js
new file mode 100644
index 00000000..4fe03fb0
--- /dev/null
+++ b/src/mesh-wireframe.js
@@ -0,0 +1,81 @@
+import { meshBounds } from './mesh-data.js';
+import { faceNormals } from './mesh-normals.js';
+import { edgeCornerTable } from './mesh-topology.js';
+
+// The polygon edges of a mesh, each tagged with what it shows, for the wireframe render pass. Edges are the edges of
+// the polygons, so the diagonals that triangulation adds inside a quad or n-gon never appear.
+
+/** The edge kinds, in the order of the numbers written into the segment buffer. */
+export const WIREFRAME_KINDS = Object.freeze(['regular', 'boundary', 'nonManifold', 'flipped', 'degenerate']);
+/** Floats per segment: two local-space endpoints and the kind number. */
+export const WIREFRAME_SEGMENT_STRIDE = 7;
+/** The most segments one mesh contributes; fault edges are kept first and regular edges fill what is left. */
+export const MAXIMUM_WIREFRAME_SEGMENTS = 200_000;
+
+const REGULAR = 0;
+const BOUNDARY = 1;
+const NON_MANIFOLD = 2;
+const FLIPPED = 3;
+const DEGENERATE = 4;
+// An edge that is several faults shows the one that matters most for a repair.
+const KIND_PRIORITY = Object.freeze([0, 1, 4, 2, 3]);
+
+function edgeKinds(mesh, table) {
+ const kinds = new Uint8Array(mesh.edgeCount);
+ for (let edge = 0; edge < mesh.edgeCount; edge++) {
+ const start = table.edgeOffsets[edge];
+ const faceCount = table.edgeOffsets[edge + 1] - start;
+ if (faceCount === 1) {
+ kinds[edge] = BOUNDARY;
+ } else if (faceCount > 2) {
+ kinds[edge] = NON_MANIFOLD;
+ } else if (mesh.cornerVertices[table.edgeCorners[start]] === mesh.cornerVertices[table.edgeCorners[start + 1]]) {
+ // Two faces that run the same way along a shared edge: one of them is flipped.
+ kinds[edge] = FLIPPED;
+ }
+ }
+ return kinds;
+}
+
+function markDegenerateFaces(mesh, kinds) {
+ const bounds = meshBounds(mesh);
+ const diagonal = Math.hypot(...bounds.max.map((value, axis) => value - bounds.min[axis]));
+ const minimumArea = (diagonal * 1e-7) ** 2;
+ const { areas } = faceNormals(mesh);
+ for (let face = 0; face < mesh.faceCount; face++) {
+ if (areas[face] > minimumArea) continue;
+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {
+ const edge = mesh.cornerEdges[corner];
+ if (KIND_PRIORITY[DEGENERATE] > KIND_PRIORITY[kinds[edge]]) kinds[edge] = DEGENERATE;
+ }
+ }
+}
+
+/**
+ * Segments of every polygon edge of `mesh`: `segments` holds WIREFRAME_SEGMENT_STRIDE floats each (ax, ay, az, bx, by, bz, kind),
+ * `counts` how many edges of each kind the mesh has, and `truncated` is true when regular edges were dropped to stay within
+ * `maximumSegments`. Faults are never dropped before regular edges.
+ */
+export function meshWireframe(mesh, { maximumSegments = MAXIMUM_WIREFRAME_SEGMENTS } = {}) {
+ if (!Number.isInteger(maximumSegments) || maximumSegments < 1) throw new RangeError('maximumSegments must be a positive integer.');
+ const table = edgeCornerTable(mesh);
+ const kinds = edgeKinds(mesh, table);
+ markDegenerateFaces(mesh, kinds);
+ const counts = Object.fromEntries(WIREFRAME_KINDS.map(name => [name, 0]));
+ for (const kind of kinds) counts[WIREFRAME_KINDS[kind]]++;
+ const faultCount = mesh.edgeCount - counts.regular;
+ const written = Math.min(mesh.edgeCount, maximumSegments);
+ const segments = new Float32Array(written * WIREFRAME_SEGMENT_STRIDE);
+ let cursor = 0;
+ for (const wantFaults of [true, false]) {
+ for (let edge = 0; edge < mesh.edgeCount && cursor < written; edge++) {
+ if ((kinds[edge] !== REGULAR) !== wantFaults) continue;
+ const base = cursor * WIREFRAME_SEGMENT_STRIDE;
+ segments.set(mesh.positions.subarray(mesh.edgeVertices[edge * 2] * 3, mesh.edgeVertices[edge * 2] * 3 + 3), base);
+ segments.set(mesh.positions.subarray(mesh.edgeVertices[edge * 2 + 1] * 3, mesh.edgeVertices[edge * 2 + 1] * 3 + 3), base + 3);
+ segments[base + 6] = kinds[edge];
+ cursor++;
+ }
+ }
+ return { segments, count: cursor, counts, truncated: cursor < mesh.edgeCount, droppedFaults: Math.max(0, faultCount - cursor) };
+}
diff --git a/src/render-passes.js b/src/render-passes.js
index 6223cd3d..560b029a 100644
--- a/src/render-passes.js
+++ b/src/render-passes.js
@@ -13,8 +13,11 @@ export const RENDER_PASS_MODES = Object.freeze({
diffuse: 6, glossy: 7, shadow: 8, ao: 9, mist: 10,
position: 11, velocity: 12, uv: 13, transmission: 14, volume: 15, environment: 16, cryptomatte: 17, aov: 18,
});
-// Background pixels: depth reads as the far limit, and shadow, ao and mist as open sky (one); every other pass reads zero, and object ID zero means no object.
-const PASS_BACKGROUNDS = Object.freeze({ depth: [1, 1, 0, 1], shadow: [1, 1, 1, 1], ao: [1, 1, 1, 1], mist: [1, 1, 1, 1] });
+// Passes drawn as another pass and then finished by their own addon: wireframe is the diffuse pass with polygon edges over it (wireframe-pass.js).
+const COMPOSED_PASSES = Object.freeze({ wireframe: 'diffuse' });
+// Background pixels: depth reads as the far limit, and shadow, ao and mist as open sky (one), wireframe as light grey for dark edges
+// to read against; every other pass reads zero, and object ID zero means no object.
+const PASS_BACKGROUNDS = Object.freeze({ depth: [1, 1, 0, 1], shadow: [1, 1, 1, 1], ao: [1, 1, 1, 1], mist: [1, 1, 1, 1], wireframe: [0.82, 0.84, 0.86, 1] });
// Modes above this one run the lit shader (lighting-pass-shader.js).
const LAST_RAW_PASS_MODE = 5;
const DEFAULT_BACKGROUND = Object.freeze([0, 0, 0, 1]);
@@ -120,8 +123,8 @@ export function installRenderPasses(renderer) {
}
function prepare(frame) {
- const mode = RENDER_PASS_MODES[frame.pass];
- if (!mode) throw new RangeError(`Unknown render pass: ${frame.pass}. Use ${Object.keys(RENDER_PASS_MODES).join(', ')}.`);
+ const mode = RENDER_PASS_MODES[COMPOSED_PASSES[frame.pass] ?? frame.pass];
+ if (!mode) throw new RangeError(`Unknown render pass: ${frame.pass}. Use ${[...Object.keys(RENDER_PASS_MODES), ...Object.keys(COMPOSED_PASSES)].join(', ')}.`);
if (renderer.benchmark) throw new Error('Render passes are unavailable in benchmark mode.');
const depthRange = frame.passDepthRange ?? 1;
if (!Number.isFinite(depthRange) || depthRange <= 0) throw new RangeError('Pass depth range must be positive and finite.');
@@ -144,6 +147,8 @@ export function installRenderPasses(renderer) {
function copyToCanvas() {
const context = renderer.context;
+ // An addon finishes the pass in its target first, while the depth state of the pass is still set (wireframe-pass.js).
+ renderer.passSupport.overlay?.();
context.bindFramebuffer(context.FRAMEBUFFER, null);
context.viewport(0, 0, renderer.canvas.width, renderer.canvas.height);
context.disable(context.DEPTH_TEST);
@@ -262,6 +267,7 @@ export function installRenderPasses(renderer) {
}
renderer.passSupport = {
+ overlay: null,
prepare,
get framebuffer() { return target.framebuffer; },
// The pass colour of the last pass frame; object motion blur reads the object IDs from it.
diff --git a/src/wireframe-pass.js b/src/wireframe-pass.js
new file mode 100644
index 00000000..b6c69348
--- /dev/null
+++ b/src/wireframe-pass.js
@@ -0,0 +1,205 @@
+import { mat4 } from 'gl-matrix';
+import { compileProgram } from './gl-program.js';
+import { polygonMeshOf } from './agent-mesh.js';
+import { MAXIMUM_WIREFRAME_SEGMENTS, WIREFRAME_KINDS, WIREFRAME_SEGMENT_STRIDE, meshWireframe } from './mesh-wireframe.js';
+
+// The wireframe render pass: the shaded surface of the diffuse pass with every polygon edge drawn over it, and the edges
+// that need repair in a colour of their own (see docs/render-passes.md). It draws into the pass target of render-passes.js
+// after that pass, so the recipe, its geometry and the lit image are untouched.
+
+/** The most segments one frame draws over all parts. Parts after the limit are left out and listed in the report. */
+export const MAXIMUM_WIREFRAME_FRAME_SEGMENTS = 1_000_000;
+/** The most parts the report lists by name. */
+export const MAXIMUM_WIREFRAME_REPORTED_PARTS = 20;
+/** Edge colours by kind number (WIREFRAME_KINDS order): regular dark, boundary orange, non-manifold red, flipped cyan, degenerate magenta. */
+export const WIREFRAME_COLORS = Object.freeze([[0.06, 0.07, 0.09], [1, 0.55, 0], [1, 0.05, 0.05], [0, 0.85, 1], [1, 0, 0.9]]);
+// Half the line width in pixels, so a fault is drawn about twice as wide as a regular edge.
+const HALF_WIDTHS = Object.freeze([0.7, 1.6, 1.6, 1.6, 1.6]);
+// Pulls edges toward the camera in normalized depth so they win against the surface they lie on.
+const DEPTH_BIAS = 2e-4;
+
+const wireframeVertex = `#version 300 es
+precision highp float;
+layout(location = 0) in vec3 endpointA;
+layout(location = 1) in vec3 endpointB;
+layout(location = 2) in float kind;
+uniform mat4 modelViewProjection;
+uniform vec2 viewportSize;
+uniform float halfWidths[5];
+uniform float depthBias;
+flat out float edgeKind;
+void main() {
+ const vec2 corners[6] = vec2[6](vec2(0.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(0.0, -1.0), vec2(1.0, 1.0), vec2(0.0, 1.0));
+ vec4 clipA = modelViewProjection * vec4(endpointA, 1.0);
+ vec4 clipB = modelViewProjection * vec4(endpointB, 1.0);
+ edgeKind = kind;
+ const float nearW = 1e-4;
+ if (clipA.w < nearW && clipB.w < nearW) {
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ return;
+ }
+ if (clipA.w < nearW) clipA = mix(clipA, clipB, (nearW - clipA.w) / (clipB.w - clipA.w));
+ if (clipB.w < nearW) clipB = mix(clipB, clipA, (nearW - clipB.w) / (clipA.w - clipB.w));
+ vec2 screenA = clipA.xy / clipA.w * viewportSize * 0.5;
+ vec2 screenB = clipB.xy / clipB.w * viewportSize * 0.5;
+ vec2 along = screenB - screenA;
+ vec2 direction = length(along) > 1e-6 ? normalize(along) : vec2(1.0, 0.0);
+ vec2 side = vec2(-direction.y, direction.x);
+ vec2 corner = corners[gl_VertexID];
+ vec4 clip = mix(clipA, clipB, corner.x);
+ vec2 offset = (side * corner.y + direction * (corner.x * 2.0 - 1.0)) * halfWidths[int(kind + 0.5)] / (viewportSize * 0.5);
+ clip.xy += offset * clip.w;
+ clip.z -= depthBias * clip.w;
+ gl_Position = clip;
+}`;
+
+const wireframeFragment = `#version 300 es
+precision highp float;
+uniform vec3 colors[5];
+flat in float edgeKind;
+out vec4 outputColor;
+void main() { outputColor = vec4(colors[int(edgeKind + 0.5)], 1.0); }`;
+
+const programs = new WeakMap();
+const meshBuffers = new WeakMap();
+
+function programFor(renderer) {
+ let program = programs.get(renderer);
+ if (program) return program;
+ const context = renderer.context;
+ const handle = compileProgram(context, wireframeVertex, wireframeFragment);
+ program = {
+ handle,
+ modelViewProjection: context.getUniformLocation(handle, 'modelViewProjection'),
+ viewportSize: context.getUniformLocation(handle, 'viewportSize'),
+ halfWidths: context.getUniformLocation(handle, 'halfWidths[0]'),
+ depthBias: context.getUniformLocation(handle, 'depthBias'),
+ colors: context.getUniformLocation(handle, 'colors[0]'),
+ };
+ programs.set(renderer, program);
+ return program;
+}
+
+// One instanced vertex array per geometry: each segment is an instance of the six corners of a screen-space quad.
+function buffersFor(renderer, geometry) {
+ let perContext = meshBuffers.get(renderer);
+ if (!perContext) {
+ perContext = new WeakMap();
+ meshBuffers.set(renderer, perContext);
+ }
+ let entry = perContext.get(geometry);
+ if (entry) return entry;
+ let wireframe;
+ try {
+ wireframe = meshWireframe(polygonMeshOf(geometry), { maximumSegments: MAXIMUM_WIREFRAME_SEGMENTS });
+ } catch (error) {
+ // Geometry that has no polygon view (every triangle collapses, no triangles) is listed as skipped instead of failing the job.
+ if (!(error instanceof RangeError || error instanceof TypeError)) throw error;
+ entry = { unreadable: true, count: 0 };
+ perContext.set(geometry, entry);
+ return entry;
+ }
+ const context = renderer.context;
+ const buffer = context.createBuffer();
+ context.bindBuffer(context.ARRAY_BUFFER, buffer);
+ context.bufferData(context.ARRAY_BUFFER, wireframe.segments, context.STATIC_DRAW);
+ const vertexArray = context.createVertexArray();
+ context.bindVertexArray(vertexArray);
+ const stride = WIREFRAME_SEGMENT_STRIDE * 4;
+ for (const [location, size, offset] of [[0, 3, 0], [1, 3, 12], [2, 1, 24]]) {
+ context.enableVertexAttribArray(location);
+ context.vertexAttribPointer(location, size, context.FLOAT, false, stride, offset);
+ context.vertexAttribDivisor(location, 1);
+ }
+ entry = { vertexArray, count: wireframe.count, counts: wireframe.counts, truncated: wireframe.truncated };
+ perContext.set(geometry, entry);
+ return entry;
+}
+
+function drawnParts(renderer) {
+ return renderer.batches.filter(batch => renderer.drawsInOpaqueLoop(batch)).flatMap(batch => batch.parts);
+}
+
+function faultCounts(counts) {
+ const { regular, ...faults } = counts;
+ return faults;
+}
+
+// Draws the edges into the pass target while the pass is still in its depth state: reversed-Z (cleared to 0, GREATER, a
+// reversed projection) where EXT_clip_control exists, standard depth otherwise.
+function drawWireframe(renderer) {
+ const context = renderer.context;
+ const program = programFor(renderer);
+ const reversed = renderer.reversedDepth === true;
+ const viewProjection = reversed ? renderer.rasterViewProjection : renderer.viewProjection;
+ context.bindFramebuffer(context.FRAMEBUFFER, renderer.passSupport.framebuffer);
+ context.viewport(0, 0, renderer.canvas.width, renderer.canvas.height);
+ context.useProgram(program.handle);
+ context.uniform2f(program.viewportSize, renderer.canvas.width, renderer.canvas.height);
+ context.uniform1fv(program.halfWidths, HALF_WIDTHS);
+ context.uniform1f(program.depthBias, reversed ? -DEPTH_BIAS : DEPTH_BIAS);
+ context.uniform3fv(program.colors, WIREFRAME_COLORS.flat());
+ context.enable(context.DEPTH_TEST);
+ context.depthFunc(reversed ? context.GEQUAL : context.LEQUAL);
+ context.depthMask(false);
+ context.disable(context.CULL_FACE);
+ const totals = Object.fromEntries(WIREFRAME_KINDS.map(name => [name, 0]));
+ const faulty = [];
+ const modelViewProjection = mat4.create();
+ let drawn = 0;
+ let partsOmitted = 0;
+ let partsSkipped = 0;
+ let truncated = false;
+ for (const part of drawnParts(renderer)) {
+ const entry = buffersFor(renderer, part.geometry);
+ if (entry.unreadable) {
+ partsSkipped++;
+ continue;
+ }
+ if (drawn + entry.count > MAXIMUM_WIREFRAME_FRAME_SEGMENTS) {
+ partsOmitted++;
+ continue;
+ }
+ drawn += entry.count;
+ truncated ||= entry.truncated;
+ for (const name of WIREFRAME_KINDS) totals[name] += entry.counts[name];
+ const faults = faultCounts(entry.counts);
+ if (Object.values(faults).some(count => count > 0)) faulty.push({ part: part.name, ...faults });
+ mat4.multiply(modelViewProjection, viewProjection, part.matrix);
+ context.uniformMatrix4fv(program.modelViewProjection, false, modelViewProjection);
+ context.bindVertexArray(entry.vertexArray);
+ context.drawArraysInstanced(context.TRIANGLES, 0, 6, entry.count);
+ }
+ context.bindVertexArray(null);
+ context.depthMask(true);
+ context.depthFunc(reversed ? context.GREATER : context.LESS);
+ context.enable(context.CULL_FACE);
+ const faultTotal = part => part.boundary + part.nonManifold + part.flipped + part.degenerate;
+ faulty.sort((first, second) => faultTotal(second) - faultTotal(first));
+ return {
+ edges: totals,
+ faultyParts: faulty.slice(0, MAXIMUM_WIREFRAME_REPORTED_PARTS),
+ faultyPartsOmitted: Math.max(0, faulty.length - MAXIMUM_WIREFRAME_REPORTED_PARTS),
+ partsOmitted,
+ partsSkipped,
+ truncated,
+ };
+}
+
+/**
+ * Runs `renderFrame`, which must draw one `wireframe` pass frame with this renderer, and draws the polygon edges of every part
+ * the pass shows over its surface before the frame reaches the canvas. Returns what the agent needs to read the picture: edge
+ * counts by kind over the drawn parts, the parts that have faults (up to MAXIMUM_WIREFRAME_REPORTED_PARTS, worst first) and
+ * whether anything was left out to stay within the limits.
+ */
+export function withWireframe(renderer, renderFrame) {
+ let report = null;
+ renderer.passSupport.overlay = () => { report = drawWireframe(renderer); };
+ try {
+ renderFrame();
+ } finally {
+ renderer.passSupport.overlay = null;
+ }
+ if (!report) throw new Error('The wireframe pass drew no frame.');
+ return report;
+}
diff --git a/tests/mesh-wireframe.test.js b/tests/mesh-wireframe.test.js
new file mode 100644
index 00000000..7a8ba833
--- /dev/null
+++ b/tests/mesh-wireframe.test.js
@@ -0,0 +1,87 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createMeshData } from '../src/mesh-data.js';
+import { meshFromGeometry } from '../src/mesh-convert.js';
+import { MAXIMUM_WIREFRAME_SEGMENTS, WIREFRAME_KINDS, WIREFRAME_SEGMENT_STRIDE, meshWireframe } from '../src/mesh-wireframe.js';
+
+const CUBE_POSITIONS = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1];
+// Outward-wound quads: bottom, top, front, back, left, right.
+const CUBE_FACES = [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [2, 3, 7, 6], [0, 4, 7, 3], [1, 2, 6, 5]];
+
+function meshOf(positions, faces) {
+ const faceOffsets = new Uint32Array(faces.length + 1);
+ faces.forEach((face, index) => { faceOffsets[index + 1] = faceOffsets[index] + face.length; });
+ return createMeshData({ positions: new Float32Array(positions), faceOffsets, cornerVertices: new Uint32Array(faces.flat()) });
+}
+
+function kindsOf(wireframe) {
+ const kinds = [];
+ for (let segment = 0; segment < wireframe.count; segment++) kinds.push(WIREFRAME_KINDS[wireframe.segments[segment * WIREFRAME_SEGMENT_STRIDE + 6]]);
+ return kinds;
+}
+
+test('a clean cube is twelve regular polygon edges with no fault', () => {
+ const wireframe = meshWireframe(meshOf(CUBE_POSITIONS, CUBE_FACES));
+ assert.equal(wireframe.count, 12);
+ assert.deepEqual(wireframe.counts, { regular: 12, boundary: 0, nonManifold: 0, flipped: 0, degenerate: 0 });
+ assert.equal(wireframe.truncated, false);
+ assert.equal(wireframe.segments.length, 12 * WIREFRAME_SEGMENT_STRIDE);
+});
+
+test('triangulation diagonals of planar quads are not drawn, whether the cube is quads or triangle pairs', () => {
+ const triangles = [];
+ for (const [a, b, c, d] of CUBE_FACES) triangles.push(a, b, c, a, c, d);
+ const positions = new Float32Array(CUBE_POSITIONS);
+ const geometry = { positions, normals: new Float32Array(positions.length), indices: new Uint32Array(triangles) };
+ const wireframe = meshWireframe(meshFromGeometry(geometry));
+ assert.equal(wireframe.count, 12);
+ assert.equal(wireframe.counts.regular, 12);
+});
+
+test('an open box marks the rim as boundary edges', () => {
+ const wireframe = meshWireframe(meshOf(CUBE_POSITIONS, CUBE_FACES.slice(0, 5)));
+ assert.equal(wireframe.counts.boundary, 4);
+ assert.equal(wireframe.counts.regular, 12 - 4);
+ assert.equal(kindsOf(wireframe).slice(0, 4).every(kind => kind === 'boundary'), true);
+});
+
+test('a third face on an edge makes it non-manifold', () => {
+ const positions = [...CUBE_POSITIONS, 0.5, -1, 0.5, 0.5, -1, 0.9];
+ const mesh = meshOf(positions, [...CUBE_FACES, [0, 1, 8]]);
+ const wireframe = meshWireframe(mesh);
+ assert.equal(wireframe.counts.nonManifold, 1);
+ assert.equal(wireframe.counts.boundary, 2);
+});
+
+test('a flipped face turns the edges it shares with its neighbours into flipped edges', () => {
+ const faces = CUBE_FACES.map((face, index) => (index === 1 ? [...face].reverse() : face));
+ const wireframe = meshWireframe(meshOf(CUBE_POSITIONS, faces));
+ assert.equal(wireframe.counts.flipped, 4);
+ assert.equal(wireframe.counts.regular, 8);
+});
+
+test('a zero-area face shows its edges as degenerate', () => {
+ const positions = [0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 1, 0, 1, 1, 0];
+ const wireframe = meshWireframe(meshOf(positions, [[0, 1, 2], [0, 1, 4, 3]]));
+ assert.ok(wireframe.counts.degenerate >= 2);
+});
+
+test('faults are kept before regular edges when the limit cuts the mesh', () => {
+ const wireframe = meshWireframe(meshOf(CUBE_POSITIONS, CUBE_FACES.slice(0, 5)), { maximumSegments: 6 });
+ assert.equal(wireframe.count, 6);
+ assert.equal(wireframe.truncated, true);
+ assert.equal(wireframe.droppedFaults, 0);
+ assert.equal(kindsOf(wireframe).filter(kind => kind === 'boundary').length, 4);
+ assert.equal(wireframe.counts.regular, 8);
+});
+
+test('the segment limit is validated and bounded by default', () => {
+ assert.throws(() => meshWireframe(meshOf(CUBE_POSITIONS, CUBE_FACES), { maximumSegments: 0 }), /maximumSegments/);
+ assert.ok(MAXIMUM_WIREFRAME_SEGMENTS <= 200_000);
+});
+
+test('the same mesh gives the same segments', () => {
+ const first = meshWireframe(meshOf(CUBE_POSITIONS, CUBE_FACES));
+ const second = meshWireframe(meshOf(CUBE_POSITIONS, CUBE_FACES));
+ assert.deepEqual(first.segments, second.segments);
+});
diff --git a/tests/render-passes.test.js b/tests/render-passes.test.js
index 855c79c1..23618afa 100644
--- a/tests/render-passes.test.js
+++ b/tests/render-passes.test.js
@@ -16,8 +16,8 @@ import { bakeMaterialGraph } from '../src/material-graph.js';
const limits = { maxOutputBytes: 1024, maxFrameBytes: 128, maxStoreBytes: 1024 ** 2, cleanupMs: 100 };
-test('capabilities and the renderer list the same passes in the same order', () => {
- assert.deepEqual(Object.keys(RENDER_PASS_MODES), [...RENDER_PASS_NAMES]);
+test('capabilities and the renderer list the same passes in the same order, wireframe last as a composed pass', () => {
+ assert.deepEqual([...Object.keys(RENDER_PASS_MODES), 'wireframe'], [...RENDER_PASS_NAMES]);
assert.deepEqual(Object.values(RENDER_PASS_MODES), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]);
});
diff --git a/tests/wireframe-pass.test.js b/tests/wireframe-pass.test.js
new file mode 100644
index 00000000..c6e49b40
--- /dev/null
+++ b/tests/wireframe-pass.test.js
@@ -0,0 +1,110 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { installRenderPasses } from '../src/render-passes.js';
+import { withWireframe, MAXIMUM_WIREFRAME_REPORTED_PARTS } from '../src/wireframe-pass.js';
+import { RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
+
+// A context that records every call; constants read back as their own names and shader and program checks succeed.
+function recordingContext(calls) {
+ const answers = { getShaderParameter: () => true, getProgramParameter: () => true, checkFramebufferStatus: () => 'FRAMEBUFFER_COMPLETE', getUniformLocation: (_program, name) => name, getExtension: () => ({}), isContextLost: () => false };
+ return new Proxy({}, {
+ get(_target, name) {
+ if (name in answers) return answers[name];
+ if (name === name.toUpperCase()) return name;
+ return (...parameters) => {
+ calls.push([name, ...parameters]);
+ return {};
+ };
+ },
+ });
+}
+
+// An open box (five quads as ten triangles) as renderer geometry: four boundary edges, no triangulation diagonals drawn.
+function openBoxGeometry() {
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1]);
+ const quads = [[0, 3, 2, 1], [0, 1, 5, 4], [2, 3, 7, 6], [0, 4, 7, 3], [1, 2, 6, 5]];
+ const indices = quads.flatMap(([a, b, c, d]) => [a, b, c, a, c, d]);
+ return { positions, normals: new Float32Array(positions.length), indices: new Uint32Array(indices) };
+}
+
+function rendererWith(parts, calls, extra = {}) {
+ const batch = { parts, layerState: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], textures: [] };
+ const renderer = {
+ context: recordingContext(calls),
+ canvas: { width: 8, height: 8 },
+ benchmark: false,
+ program: {},
+ viewProjection: mat4.create(),
+ renderTargets: { record: () => {}, release: () => {} },
+ requireFeatureNames: () => {},
+ drawsInOpaqueLoop: () => true,
+ batches: [batch],
+ ...extra,
+ };
+ installRenderPasses(renderer);
+ renderer.passSupport.prepare({ pass: 'wireframe' });
+ return renderer;
+}
+
+const identity = () => mat4.create();
+
+test('wireframe is a named pass that draws as the diffuse pass on a light background', () => {
+ assert.equal(RENDER_PASS_NAMES.at(-1), 'wireframe');
+ const renderer = rendererWith([], []);
+ assert.equal(renderer.passSupport.prepare({ pass: 'wireframe' }), renderer.passSupport.prepare({ pass: 'diffuse' }));
+ assert.deepEqual(renderer.passSupport.background('wireframe'), [0.82, 0.84, 0.86, 1]);
+ assert.throws(() => renderer.passSupport.prepare({ pass: 'beauty' }), /Unknown render pass: beauty\. Use .*wireframe/);
+});
+
+test('the overlay runs only while a wireframe frame renders and reports edge counts and faulty parts', () => {
+ const calls = [];
+ const geometry = openBoxGeometry();
+ const renderer = rendererWith([{ name: 'open-box', geometry, matrix: identity() }, { name: 'second', geometry, matrix: identity() }], calls);
+ renderer.passSupport.copyToCanvas();
+ assert.equal(calls.some(call => call[0] === 'drawArraysInstanced'), false, 'A plain pass frame draws no edges.');
+ const report = withWireframe(renderer, () => renderer.passSupport.copyToCanvas());
+ assert.equal(renderer.passSupport.overlay, null);
+ assert.deepEqual(report.edges, { regular: 16, boundary: 8, nonManifold: 0, flipped: 0, degenerate: 0 });
+ assert.deepEqual(report.faultyParts.map(part => part.part), ['open-box', 'second']);
+ assert.equal(report.partsOmitted, 0);
+ const draws = calls.filter(call => call[0] === 'drawArraysInstanced');
+ assert.deepEqual(draws.map(call => call.slice(1)), [['TRIANGLES', 0, 6, 12], ['TRIANGLES', 0, 6, 12]]);
+});
+
+test('depth state follows the pass: reversed-Z tests GEQUAL with a projection of its own, standard depth tests LEQUAL', () => {
+ const part = { name: 'open-box', geometry: openBoxGeometry(), matrix: identity() };
+ const standardCalls = [];
+ const standard = rendererWith([part], standardCalls);
+ withWireframe(standard, () => standard.passSupport.copyToCanvas());
+ assert.deepEqual(standardCalls.find(call => call[0] === 'depthFunc').slice(1), ['LEQUAL']);
+ const reversedCalls = [];
+ const reversed = rendererWith([part], reversedCalls, { reversedDepth: true, rasterViewProjection: mat4.create() });
+ withWireframe(reversed, () => reversed.passSupport.copyToCanvas());
+ assert.deepEqual(reversedCalls.filter(call => call[0] === 'depthFunc').map(call => call[1]), ['GEQUAL', 'GREATER']);
+ assert.deepEqual(standardCalls.filter(call => call[0] === 'depthFunc').map(call => call[1]), ['LEQUAL', 'LESS']);
+});
+
+test('a part with no polygon view is skipped and counted instead of failing the frame', () => {
+ const collapsed = { positions: new Float32Array(9), normals: new Float32Array(9), indices: new Uint32Array([0, 1, 2]) };
+ const renderer = rendererWith([{ name: 'flat', geometry: collapsed, matrix: identity() }], []);
+ const report = withWireframe(renderer, () => renderer.passSupport.copyToCanvas());
+ assert.equal(report.partsSkipped, 1);
+ assert.equal(report.edges.regular, 0);
+});
+
+test('the report names at most the worst parts and says how many it left out', () => {
+ const parts = Array.from({ length: MAXIMUM_WIREFRAME_REPORTED_PARTS + 3 }, (_unused, index) => ({ name: `part-${index}`, geometry: openBoxGeometry(), matrix: identity() }));
+ const renderer = rendererWith(parts, []);
+ const report = withWireframe(renderer, () => renderer.passSupport.copyToCanvas());
+ assert.equal(report.faultyParts.length, MAXIMUM_WIREFRAME_REPORTED_PARTS);
+ assert.equal(report.faultyPartsOmitted, 3);
+});
+
+test('a frame that never reaches the canvas copy is an error, and the overlay is removed', () => {
+ const renderer = rendererWith([], []);
+ assert.throws(() => withWireframe(renderer, () => {}), /drew no frame/);
+ assert.equal(renderer.passSupport.overlay, null);
+ assert.throws(() => withWireframe(renderer, () => { throw new Error('boom'); }), /boom/);
+ assert.equal(renderer.passSupport.overlay, null);
+});