Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Compare outlines with Blender Freestyle and check width across sizes

Nguyen Xuan An0057cd8d9b35
diff --git a/bench/reference/images/line-art-67js-vs-blender-freestyle.webp b/bench/reference/images/line-art-67js-vs-blender-freestyle.webp
new file mode 100644
index 00000000..a7c204bd
Binary files /dev/null and b/bench/reference/images/line-art-67js-vs-blender-freestyle.webp differ
diff --git a/bench/reference/line-art-blender.py b/bench/reference/line-art-blender.py
new file mode 100644
index 00000000..c394e7c1
--- /dev/null
+++ b/bench/reference/line-art-blender.py
@@ -0,0 +1,117 @@
+# Builds bench/reference/line-art-scene.json in Blender 5.2 and renders it twice, without and with Freestyle lines.
+# blender --background --factory-startup -t 6 --python bench/reference/line-art-blender.py -- <scene json> <output directory> <width> <height> <line width in pixels>
+# Files are <output directory>/blender-off.png and blender-on.png. Blender's Line Art modifier needs its bake operator, which
+# is missing in background mode, so the outlines come from Freestyle (silhouette, border and crease edges, crease angle 35).
+import json
+import math
+import sys
+
+import bpy
+from mathutils import Vector
+
+sceneFile, outputDirectory, width, height, lineWidth = sys.argv[sys.argv.index("--") + 1:]
+width = int(width)
+height = int(height)
+lineWidth = float(lineWidth)
+recipe = json.load(open(sceneFile))
+
+
+def toBlender(vector):
+ # 67js is Y up, Blender is Z up.
+ return Vector((vector[0], -vector[2], vector[1]))
+
+
+def scaleToBlender(vector):
+ return Vector((vector[0], vector[2], vector[1]))
+
+
+bpy.ops.wm.read_factory_settings(use_empty=True)
+scene = bpy.context.scene
+scene.render.resolution_x = width
+scene.render.resolution_y = height
+scene.render.resolution_percentage = 100
+# Cycles on the CPU with few samples: the lines come from Freestyle, and this keeps the GPU free for other sessions.
+scene.render.engine = "CYCLES"
+scene.cycles.device = "CPU"
+scene.cycles.samples = 24
+scene.cycles.use_denoising = False
+scene.view_settings.view_transform = "Standard"
+scene.render.image_settings.file_format = "PNG"
+scene.render.image_settings.color_mode = "RGB"
+
+world = bpy.data.worlds.new("World")
+scene.world = world
+world.use_nodes = True
+skyColor = recipe["environment"]["skyTop"]
+world.node_tree.nodes["Background"].inputs["Color"].default_value = (*skyColor, 1.0)
+world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.8
+
+materials = {}
+for material in recipe["materials"]:
+ blenderMaterial = bpy.data.materials.new(material["id"])
+ blenderMaterial.use_nodes = True
+ principled = blenderMaterial.node_tree.nodes["Principled BSDF"]
+ principled.inputs["Base Color"].default_value = (*material["color"], 1.0)
+ principled.inputs["Roughness"].default_value = material.get("roughness", 0.5)
+ materials[material["id"]] = blenderMaterial
+
+geometryTypes = {geometry["id"]: geometry["type"] for geometry in recipe["geometries"]}
+for node in recipe["nodes"]:
+ kind = geometryTypes[node["geometry"]]
+ if kind == "box":
+ bpy.ops.mesh.primitive_cube_add(size=1.0)
+ else:
+ bpy.ops.mesh.primitive_uv_sphere_add(segments=64, ring_count=40, radius=1.0)
+ bpy.ops.object.shade_smooth()
+ blenderObject = bpy.context.active_object
+ blenderObject.name = node["id"]
+ blenderObject.location = toBlender(node["translation"])
+ blenderObject.scale = scaleToBlender(node["scale"])
+ blenderObject.data.materials.append(materials[node["material"]])
+
+sunData = bpy.data.lights.new("Sun", "SUN")
+sunData.energy = 1.2
+sun = bpy.data.objects.new("Sun", sunData)
+scene.collection.objects.link(sun)
+towardLight = toBlender(recipe["environment"]["lightDirection"])
+sun.rotation_euler = (-towardLight).to_track_quat("-Z", "Y").to_euler()
+
+cameraSpec = recipe["camera"]
+cameraData = bpy.data.cameras.new("Camera")
+cameraData.sensor_fit = "VERTICAL"
+cameraData.angle = math.radians(cameraSpec["fov"])
+cameraData.clip_start = cameraSpec["near"]
+cameraData.clip_end = cameraSpec["far"]
+camera = bpy.data.objects.new("Camera", cameraData)
+scene.collection.objects.link(camera)
+camera.location = toBlender(cameraSpec["eye"])
+direction = toBlender(cameraSpec["target"]) - camera.location
+camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
+scene.camera = camera
+
+scene.render.use_freestyle = False
+scene.render.filepath = f"{outputDirectory}/blender-off.png"
+bpy.ops.render.render(write_still=True)
+
+scene.render.use_freestyle = True
+scene.render.line_thickness_mode = "ABSOLUTE"
+scene.render.line_thickness = lineWidth
+viewLayer = scene.view_layers[0]
+viewLayer.use_freestyle = True
+settings = viewLayer.freestyle_settings
+settings.crease_angle = math.radians(35)
+lineSet = settings.linesets.new("Outlines") if len(settings.linesets) == 0 else settings.linesets[0]
+lineSet.select_silhouette = True
+lineSet.select_border = True
+lineSet.select_crease = True
+lineSet.select_contour = True
+lineSet.select_external_contour = False
+lineSet.select_edge_mark = False
+lineSet.visibility = "VISIBLE"
+if lineSet.linestyle is None:
+ lineSet.linestyle = bpy.data.linestyles.new("OutlineStyle")
+lineSet.linestyle.color = (0.02, 0.02, 0.02)
+lineSet.linestyle.thickness = 1.0
+scene.render.filepath = f"{outputDirectory}/blender-on.png"
+bpy.ops.render.render(write_still=True)
+print("LINE_ART_DONE", bpy.app.version_string, "freestyle strokes via", lineSet.name)
diff --git a/bench/reference/line-art-harness.html b/bench/reference/line-art-harness.html
new file mode 100644
index 00000000..55b0582f
--- /dev/null
+++ b/bench/reference/line-art-harness.html
@@ -0,0 +1,52 @@
+<!doctype html>
+<html>
+<head>
+<style>html,body{margin:0;height:100%}canvas{width:100vw;height:100vh;display:block}</style>
+</head>
+<body>
+<canvas></canvas>
+<script type="module">
+// Draws bench/reference/line-art-scene.json once, with or without lines, at the viewport size.
+import { createAgentScene, loadAllAgentSceneModules } from '/src/agent-scene.js';
+import { resolveAgentShadow } from '/src/agent-look.js';
+import { Renderer67 } from '/src/renderer.js';
+import { installRenderPasses } from '/src/render-passes.js';
+import { installLineArt, resolveLineArt } from '/src/line-art.js';
+
+await loadAllAgentSceneModules();
+const recipe = await (await fetch('/bench/reference/line-art-scene.json')).json();
+const session = createAgentScene(recipe);
+const canvas = document.querySelector('canvas');
+const baseRenderer = new Renderer67(canvas, session.parts, { ground: false, hdr: true, depth: true, samples: 1, pixelRatio: 1, memoryBudgetMiB: 512 });
+const renderer = installLineArt(installRenderPasses(baseRenderer));
+const context = renderer.context;
+
+// lineWidth 0 draws the scene without lines. Returns the frame as a PNG data URL.
+window.drawLineArtScene = function drawLineArtScene(lineWidth) {
+ const environment = session.environment;
+ const effects = session.effects;
+ renderer.shadowBounds = resolveAgentShadow(session.shadow, environment.lightDirection);
+ renderer.shadowsDirty = true;
+ renderer.world = environment.world;
+ renderer.resize();
+ renderer.updateParts(session.parts);
+ const lines = lineWidth > 0 ? resolveLineArt({ width: lineWidth }) : undefined;
+ renderer.render({ ...session.camera, environment, effects, exposure: effects.exposure, time: 0, lines });
+ const width = context.drawingBufferWidth;
+ const height = context.drawingBufferHeight;
+ const rows = new Uint8ClampedArray(width * height * 4);
+ context.readPixels(0, 0, width, height, context.RGBA, context.UNSIGNED_BYTE, rows);
+ const flipped = new Uint8ClampedArray(rows.length);
+ for (let row = 0; row < height; row++) {
+ flipped.set(rows.subarray((height - 1 - row) * width * 4, (height - row) * width * 4), row * width * 4);
+ }
+ const flatCanvas = document.createElement('canvas');
+ flatCanvas.width = width;
+ flatCanvas.height = height;
+ flatCanvas.getContext('2d').putImageData(new ImageData(flipped, width, height), 0, 0);
+ return { width, height, glError: context.getError(), png: flatCanvas.toDataURL('image/png') };
+};
+window.lineArtReady = true;
+</script>
+</body>
+</html>
diff --git a/bench/reference/line-art-measure.mjs b/bench/reference/line-art-measure.mjs
new file mode 100644
index 00000000..66af6d53
--- /dev/null
+++ b/bench/reference/line-art-measure.mjs
@@ -0,0 +1,101 @@
+// Measures outlines from two renders of the same frame, one without lines and one with. The difference of the two is the
+// line mask, so shading, sky and tone mapping drop out.
+import sharp from 'sharp';
+
+export async function readPixels(pngBuffer) {
+ const { data, info } = await sharp(pngBuffer).removeAlpha().raw().toBuffer({ resolveWithObject: true });
+ return { data, width: info.width, height: info.height };
+}
+
+// Per pixel: the largest channel change from the frame without lines to the frame with them, 0 to 1.
+export function lineStrength(withoutLines, withLines) {
+ const strength = new Float32Array(withLines.width * withLines.height);
+ for (let pixel = 0; pixel < strength.length; pixel++) {
+ let largest = 0;
+ for (let channel = 0; channel < 3; channel++) {
+ const index = pixel * 3 + channel;
+ largest = Math.max(largest, Math.abs(withLines.data[index] - withoutLines.data[index]));
+ }
+ strength[pixel] = largest / 255;
+ }
+ return strength;
+}
+
+export function lineMask(strength, threshold = 0.15) {
+ return strength.map(value => (value >= threshold ? 1 : 0));
+}
+
+// Intersection over union of two masks of the same size.
+export function maskOverlap(maskA, maskB) {
+ let both = 0;
+ let either = 0;
+ for (let pixel = 0; pixel < maskA.length; pixel++) {
+ if (maskA[pixel] && maskB[pixel]) both++;
+ if (maskA[pixel] || maskB[pixel]) either++;
+ }
+ return { intersection: both, union: either, iou: either ? both / either : 1 };
+}
+
+// Mask A dilated by `radius` pixels, so a line that sits one or two pixels off still counts as found.
+export function dilate(mask, width, height, radius) {
+ const result = new Uint8Array(mask.length);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ if (!mask[y * width + x]) continue;
+ for (let dy = -radius; dy <= radius; dy++) {
+ for (let dx = -radius; dx <= radius; dx++) {
+ const nx = x + dx;
+ const ny = y + dy;
+ if (nx >= 0 && nx < width && ny >= 0 && ny < height) result[ny * width + nx] = 1;
+ }
+ }
+ }
+ }
+ return result;
+}
+
+// Line width in pixels across near-vertical edges. Each scan row is cut into runs of line pixels; a run counts only when
+// the same edge sits at nearly the same x a few rows further down (a vertical edge, not a diagonal one), and its width is
+// the strength summed over the run divided by the strongest pixel in it, so a half covered pixel counts as half.
+export function verticalEdgeWidths(strength, width, height, { rowStep = 1, slopeRows = 6, minimum = 0.08 } = {}) {
+ const widths = [];
+ const runsInRow = row => {
+ const runs = [];
+ let x = 0;
+ while (x < width) {
+ if (strength[row * width + x] < minimum) {
+ x++;
+ continue;
+ }
+ let end = x;
+ let sum = 0;
+ let peak = 0;
+ let weighted = 0;
+ while (end < width && strength[row * width + end] >= minimum) {
+ const value = strength[row * width + end];
+ sum += value;
+ weighted += value * end;
+ peak = Math.max(peak, value);
+ end++;
+ }
+ runs.push({ center: weighted / sum, width: sum / peak, length: end - x });
+ x = end;
+ }
+ return runs;
+ };
+ const margin = Math.round(height * 0.05);
+ for (let row = margin; row < height - margin - slopeRows; row += rowStep) {
+ const here = runsInRow(row);
+ const below = runsInRow(row + slopeRows);
+ for (const run of here) {
+ const partner = below.find(candidate => Math.abs(candidate.center - run.center) <= 0.1 * slopeRows);
+ if (partner && Math.abs(partner.width - run.width) < 0.5) widths.push(run.width);
+ }
+ }
+ widths.sort((a, b) => a - b);
+ return widths;
+}
+
+export function median(sorted) {
+ return sorted.length ? sorted[Math.floor(sorted.length / 2)] : 0;
+}
diff --git a/bench/reference/line-art-scene.json b/bench/reference/line-art-scene.json
new file mode 100644
index 00000000..d4eb22fd
--- /dev/null
+++ b/bench/reference/line-art-scene.json
@@ -0,0 +1,35 @@
+{
+ "format": "67js.scene",
+ "schemaVersion": 1,
+ "geometries": [
+ { "id": "box", "type": "box", "bevel": 0 },
+ { "id": "ball", "type": "sphere", "segments": 64, "rings": 40 }
+ ],
+ "materials": [
+ { "id": "slab", "color": [0.6, 0.6, 0.6], "roughness": 0.9 },
+ { "id": "block", "color": [0.8, 0.8, 0.8], "roughness": 0.9 },
+ { "id": "sphere", "color": [0.85, 0.85, 0.85], "roughness": 0.9 },
+ { "id": "twin-left", "color": [0.8, 0.8, 0.8], "roughness": 0.9 },
+ { "id": "twin-right", "color": [0.7, 0.7, 0.7], "roughness": 0.9 }
+ ],
+ "nodes": [
+ { "id": "slab", "geometry": "box", "material": "slab", "translation": [0, -0.1, 0], "scale": [5, 0.2, 3.4] },
+ { "id": "step-1", "geometry": "box", "material": "block", "translation": [0.3, 0.25, -0.3], "scale": [2, 0.5, 2] },
+ { "id": "step-2", "geometry": "box", "material": "block", "translation": [0.3, 0.75, -0.3], "scale": [1.4, 0.5, 1.4] },
+ { "id": "step-3", "geometry": "box", "material": "block", "translation": [0.3, 1.25, -0.3], "scale": [0.8, 0.5, 0.8] },
+ { "id": "ball", "geometry": "ball", "material": "sphere", "translation": [1.9, 0.6, 0.8], "scale": [0.6, 0.6, 0.6] },
+ { "id": "twin-left", "geometry": "box", "material": "twin-left", "translation": [-1.8, 0.3, 0.2], "scale": [0.6, 0.6, 0.6] },
+ { "id": "twin-right", "geometry": "box", "material": "twin-right", "translation": [-1.8, 0.3, 0.8], "scale": [0.6, 0.6, 0.6] }
+ ],
+ "camera": { "eye": [4.6, 3.4, 5.6], "target": [0, 0.5, 0], "fov": 34, "near": 0.1, "far": 40 },
+ "environment": {
+ "world": true,
+ "lightDirection": [-3, 6, 4],
+ "keyColor": [2.4, 2.3, 2.2],
+ "fillIntensity": 0.3,
+ "ambientIntensity": 0.5,
+ "skyTop": [0.9, 0.92, 0.95],
+ "skyBottom": [0.9, 0.92, 0.95],
+ "fogDensity": 0
+ }
+}
diff --git a/bench/reference/line-art.mjs b/bench/reference/line-art.mjs
new file mode 100644
index 00000000..e95069f2
--- /dev/null
+++ b/bench/reference/line-art.mjs
@@ -0,0 +1,90 @@
+// Line art reference for issue #285: draws bench/reference/line-art-scene.json with outlines in 67js at a preview size and
+// at 4K, draws the same scene in Blender 5.2 with Freestyle, and compares the line masks.
+// node bench/reference/line-art.mjs [--backend gpu|cpu] [--skip-blender] [--reuse-67js] [--width <pixels>]
+// Writes PNGs and a side-by-side sheet to artifacts/line-art/ (gitignored) and prints the numbers.
+import { spawnSync } from 'node:child_process';
+import { mkdir, writeFile } from 'node:fs/promises';
+import { constants, setPriority } from 'node:os';
+import { resolve } from 'node:path';
+import sharp from 'sharp';
+import { chromium } from 'playwright';
+import { createServer } from 'vite';
+import { readPixels, lineStrength, lineMask, maskOverlap, dilate, verticalEdgeWidths, median } from './line-art-measure.mjs';
+
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const BLENDER = process.env.BLENDER_PATH ?? 'C:/Program Files/Blender Foundation/Blender 5.2/blender.exe';
+const argumentsGiven = process.argv.slice(2);
+const backend = argumentsGiven.includes('--backend') ? argumentsGiven[argumentsGiven.indexOf('--backend') + 1] : 'gpu';
+const lineWidth = argumentsGiven.includes('--width') ? Number(argumentsGiven[argumentsGiven.indexOf('--width') + 1]) : 2;
+const SIZES = [{ name: 'preview', width: 960, height: 540 }, { name: '4k', width: 3840, height: 2160 }];
+const output = resolve('artifacts/line-art');
+const BACKEND_ARGUMENTS = {
+ gpu: ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'],
+ cpu: ['--enable-webgl', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
+};
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+await mkdir(output, { recursive: true });
+
+async function drawWithJs67() {
+ const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+ await server.listen();
+ const url = `http://127.0.0.1:${server.httpServer.address().port}/bench/reference/line-art-harness.html`;
+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: BACKEND_ARGUMENTS[backend] });
+ try {
+ for (const size of SIZES) {
+ const page = await browser.newPage({ viewport: { width: size.width, height: size.height } });
+ page.on('pageerror', error => console.log('PAGE ERROR', error.message));
+ await page.goto(url, { timeout: 180000 });
+ await page.waitForFunction(() => window.lineArtReady, null, { timeout: 180000 });
+ for (const [label, requestedWidth] of [['off', 0], ['on', lineWidth]]) {
+ const frame = await page.evaluate(width => window.drawLineArtScene(width), requestedWidth);
+ if (frame.glError !== 0) throw new Error(`WebGL error ${frame.glError}`);
+ if (frame.width !== size.width || frame.height !== size.height) throw new Error(`Drew ${frame.width}x${frame.height}, wanted ${size.width}x${size.height}`);
+ await writeFile(`${output}/js67-${size.name}-${label}.png`, Buffer.from(frame.png.split(',')[1], 'base64'));
+ }
+ await page.close();
+ }
+ } finally {
+ await browser.close();
+ await server.close();
+ }
+}
+
+async function loadPair(prefix) {
+ const [withoutLines, withLines] = await Promise.all(['off', 'on'].map(label => sharp(`${output}/${prefix}-${label}.png`).toBuffer().then(readPixels)));
+ return { withoutLines, withLines, strength: lineStrength(withoutLines, withLines) };
+}
+
+if (!argumentsGiven.includes('--reuse-67js')) await drawWithJs67();
+const widthRows = [];
+for (const size of SIZES) {
+ const pair = await loadPair(`js67-${size.name}`);
+ const widths = verticalEdgeWidths(pair.strength, size.width, size.height, { rowStep: 3, slopeRows: Math.round(6 * size.width / 960) });
+ widthRows.push({ size: size.name, edges: widths.length, median: median(widths) });
+ console.log(`67js ${size.name} ${size.width}x${size.height}: requested width ${lineWidth}, median vertical-edge width ${median(widths).toFixed(2)} px over ${widths.length} samples`);
+}
+
+if (!argumentsGiven.includes('--skip-blender')) {
+ const preview = SIZES[0];
+ const run = spawnSync(BLENDER, ['--background', '--factory-startup', '-t', '6', '--python', 'bench/reference/line-art-blender.py', '--', 'bench/reference/line-art-scene.json', output, String(preview.width), String(preview.height), String(lineWidth)], { encoding: 'utf8' });
+ if (!run.stdout.includes('LINE_ART_DONE')) throw new Error(`Blender failed:\n${run.stdout.slice(-1500)}\n${run.stderr.slice(-1500)}`);
+ const js67 = await loadPair('js67-preview');
+ const blender = await loadPair('blender');
+ const blenderWidths = verticalEdgeWidths(blender.strength, preview.width, preview.height, { rowStep: 3 });
+ console.log(`Blender Freestyle ${preview.width}x${preview.height}: median vertical-edge width ${median(blenderWidths).toFixed(2)} px over ${blenderWidths.length} samples`);
+ const maskJs = lineMask(js67.strength);
+ const maskBlender = lineMask(blender.strength);
+ const exact = maskOverlap(maskJs, maskBlender);
+ const tolerant = {
+ js67Found: maskOverlap(maskJs, dilate(maskBlender, preview.width, preview.height, 2)).intersection / maskJs.reduce((sum, value) => sum + value, 0),
+ blenderFound: maskOverlap(maskBlender, dilate(maskJs, preview.width, preview.height, 2)).intersection / maskBlender.reduce((sum, value) => sum + value, 0),
+ };
+ console.log(`edge mask IoU ${exact.iou.toFixed(3)}; with 2 px tolerance, ${(tolerant.js67Found * 100).toFixed(1)}% of 67js line pixels lie on a Blender line and ${(tolerant.blenderFound * 100).toFixed(1)}% of Blender line pixels lie on a 67js line`);
+ const sheet = await sharp({ create: { width: preview.width * 2, height: preview.height, channels: 3, background: '#fff' } })
+ .composite([{ input: `${output}/js67-preview-on.png`, left: 0, top: 0 }, { input: `${output}/blender-on.png`, left: preview.width, top: 0 }])
+ .png().toBuffer();
+ await writeFile(`${output}/side-by-side.png`, sheet);
+ await sharp(sheet).webp({ quality: 80 }).toFile(`${output}/side-by-side.webp`);
+ await writeFile(`${output}/result.json`, JSON.stringify({ lineWidth, widthRows, iou: exact.iou, tolerant, blenderWidth: median(blenderWidths) }, null, 2));
+}
diff --git a/changes/285-reference.md b/changes/285-reference.md
new file mode 100644
index 00000000..246ba2a9
--- /dev/null
+++ b/changes/285-reference.md
@@ -0,0 +1 @@
+- Compare outlines with Blender and check their width across sizes (part of #285). `npm run reference:line-art` draws a reference scene of unbevelled boxes, a stepped block, a sphere and two touching parts with `environment.lines`, draws the same scene in Blender 5.2 with Freestyle, and prints the edge mask overlap and the line width at preview size and at 4K. Details in `docs/line-art.md`.
diff --git a/docs/line-art.md b/docs/line-art.md
index 07f6d4f2..a2b3381e 100644
--- a/docs/line-art.md
+++ b/docs/line-art.md
@@ -56,3 +56,13 @@ renderer.render({ ...camera, lines: resolveLineArt({ width: 2, toon: 3 }) });
```
A recipe host loads the code with `await loadAgentSceneModules(recipe)`. The preview and render jobs install it themselves.
+
+## Compared with Blender (2026-11-04)
+
+`npm run reference:line-art` draws `bench/reference/line-art-scene.json` (unbevelled boxes, a three-step block, a sphere, two touching parts on a slab) with `lines.width` 2, and draws the same scene in Blender 5.2.2 with Freestyle (silhouette, border and crease edges, crease angle 35, 2 px). Blender's Line Art modifier gave 0 strokes in background mode, with or without a camera, so Freestyle is the reference. Each side is drawn with and without lines, and the difference of the two is the line mask.
+
+![67js outlines on the left, Blender Freestyle on the right](../bench/reference/images/line-art-67js-vs-blender-freestyle.webp)
+
+- Silhouettes, creases and the boundary between the two touching parts appear in both. Every Blender line pixel lies within 2 px of a 67js line (100%).
+- The edge masks overlap with an IoU of 0.50 at 960x540. 64% of the 67js line pixels lie within 2 px of a Blender line. In the side-by-side the lines only 67js draws are the contact lines where a block stands on the slab or one step sits on the next (Freestyle draws no edge there, probably because the edge lies in the surface below it).
+- Width, measured on near-vertical edges as the strength of the line summed across the edge: 1.65 px in 67js at 960x540 and 1.60 px at 3840x2160 (requested 2), against 1.73 px in Blender at 960x540. The pixel width holds across sizes (ratio 0.97), and both tools draw a requested 2 px a little thinner at the strongest pixel.
diff --git a/docs/parity.md b/docs/parity.md
index 7f3ac6a3..9c8ef12f 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -197,7 +197,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Materials > Assignment | done | A node names one material. | [agent-scene](../tests/agent-scene.test.js) | |
| Rendering > Materials > Preview | out of scope | Interface for a person. Agents use `scene_look`. | | |
| Rendering > Materials > Settings | partial | Opaque and blend in recipes, and mask on imported assets, with double-sided support. | [gltf-extensions](../tests/gltf-extensions.test.js) | #51 |
-| Rendering > Materials > Line Art | partial | `toon` on a material bands the light. Outlines come from screen-space guides (object ID, normal, depth) at a fixed pixel width. Line Art modifier options (occlusion levels, intersections, chaining, hatching) do not exist. Not yet compared with a Blender Line Art render. | [line-art](../tests/line-art.test.js), [guide](line-art.md) | |
+| Rendering > Materials > Line Art | partial | `toon` on a material bands the light. Outlines come from screen-space guides (object ID, normal, depth) at a fixed pixel width. Line Art modifier options (occlusion levels, intersections, chaining, hatching) do not exist. On a reference scene the edge mask overlaps a Blender Freestyle render with an IoU of 0.50 (Blender Line Art gives no strokes in background mode); 67js draws extra contact lines. | [line-art](../tests/line-art.test.js), [guide](line-art.md), [reference script](../bench/reference/line-art.mjs) | |
| Rendering > Materials > Legacy Textures | out of scope | Blender keeps these for old files. | | |
| Rendering > Shader Nodes > Input | partial | `uv` coordinates only. There is no object, geometry, camera or light-path input. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Output | partial | A graph makes base colour, roughness, metallic, emission and height. It is baked to textures on the CPU, so it can not react to light, view or position. The `brick-graph` reference scene scores 0.2269 against Cycles; its `brick-flat` control (the graph's average colour, no maps) is the baseline it is compared with, and a bump of 0 would score 0.2065, so the bump is stronger than Blender's, not weaker. | [material-graph](../tests/material-graph.test.js), [brick-graph scene](../bench/reference/scenes.js) | #50 |
@@ -208,7 +208,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Shader Nodes > Utilities | partial | Maths on numbers and vectors: add, sub, mul, div, min, max, pow, abs, floor, fract, sqrt, clamp and smoothstep. There is no vector maths, mapping, map range or separate and combine nodes. | [material-graph](../tests/material-graph.test.js) | #50 |
| Rendering > Shader Nodes > Group | missing | No node graph. | | #50 |
| Rendering > Color Management | partial | View transforms `aces` (default), `agx` and `neutral` (Khronos PBR Neutral) in the rasterizer and the path tracer, and `.cube` look LUTs or four named looks; grading as before. Neutral matches Blender 5.2 within 0.01 on a ramp, AgX within 0.026 (a fit of Blender 5.2's AgX LUT; saturated colour is the part that is off). No choice of working color space or display device; no Filmic or Standard. | [view transforms](../tests/view-transform.test.js), [effects](../tests/effects.test.js) | AgX looks |
-| Rendering > Freestyle | partial | `environment.lines` draws silhouette, boundary and crease lines in screen space, and `polylines` draws screen-width lines in the world. There are no line sets, styles or strokes along curves. | [line-art](../tests/line-art.test.js), [guide](line-art.md) | |
+| Rendering > Freestyle | partial | `environment.lines` draws silhouette, boundary and crease lines in screen space, and `polylines` draws screen-width lines in the world. There are no line sets, styles or strokes along curves. Outline width is 1.65 px at 960x540 and 1.60 px at 3840x2160 for a requested 2 px, against 1.73 px in Freestyle ([comparison](line-art.md)). | [line-art](../tests/line-art.test.js), [guide](line-art.md), [reference script](../bench/reference/line-art.mjs) | |
| Rendering > View Layers & Passes | partial | Render jobs write albedo, normal, emission, depth and object ID passes as PNG files. There are no view layers, no cryptomatte and no lighting passes (diffuse, glossy, shadow). | [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Render Output > Output Properties | partial | PNG and MP4, frame rate, duration (to 60 s) and size, and a CPU or NVENC encoder. There is no stereo or metadata. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | #60 |
| Rendering > Render Output > Audio Rendering | partial | A video job mixes one local WAV, MP3, OGG or FLAC file with an offset and reports measured sync. No several tracks, mixing, gain or generated sound. | [film-timeline](../tests/film-timeline.test.js), `npm run smoke:film-timeline` | #60 |
diff --git a/package.json b/package.json
index aefc8f21..7b8b1c2e 100644
--- a/package.json
+++ b/package.json
@@ -150,6 +150,7 @@
"smoke:agent-branches": "node scripts/smoke-agent-branches.mjs",
"parity": "node scripts/parity-report.mjs",
"reference": "node bench/reference/run.mjs",
+ "reference:line-art": "node bench/reference/line-art.mjs",
"size": "node scripts/measure-size.mjs",
"size:release": "node scripts/measure-size.mjs --set-budgets",
"tool-cost": "node scripts/check-tool-cost.mjs",
diff --git a/tests/line-art-reference.test.js b/tests/line-art-reference.test.js
new file mode 100644
index 00000000..b23830ed
--- /dev/null
+++ b/tests/line-art-reference.test.js
@@ -0,0 +1,51 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { createAgentScene } from '../src/agent-scene.js';
+import { loadAgentSceneModules } from '../src/agent-scene-modules.js';
+import { verticalEdgeWidths, median, maskOverlap, dilate } from '../bench/reference/line-art-measure.mjs';
+
+// A vertical line of the given width (in pixels, fractions allowed) centred at x, as a strength map.
+function verticalLine(imageWidth, imageHeight, centreX, lineWidth) {
+ const strength = new Float32Array(imageWidth * imageHeight);
+ for (let row = 0; row < imageHeight; row++) {
+ for (let column = 0; column < imageWidth; column++) {
+ const overlap = Math.min(column + 1, centreX + lineWidth / 2) - Math.max(column, centreX - lineWidth / 2);
+ strength[row * imageWidth + column] = Math.max(0, Math.min(1, overlap));
+ }
+ }
+ return strength;
+}
+
+test('the width measure reads whole and fractional pixel widths of a vertical edge', () => {
+ // Below 2 px no pixel is fully covered, so the strongest pixel under-reads the full line colour and the width reads high.
+ for (const lineWidth of [2, 2.5, 4, 8]) {
+ const widths = verticalEdgeWidths(verticalLine(200, 100, 100.3, lineWidth), 200, 100, { rowStep: 5 });
+ assert.ok(Math.abs(median(widths) - lineWidth) < 0.05, `width ${lineWidth} measured ${median(widths)}`);
+ }
+});
+
+test('the width measure skips diagonal edges', () => {
+ const strength = new Float32Array(200 * 100);
+ for (let row = 0; row < 100; row++) {
+ for (let column = row; column < row + 3; column++) strength[row * 200 + column] = 1;
+ }
+ assert.equal(verticalEdgeWidths(strength, 200, 100, { rowStep: 5 }).length, 0);
+});
+
+test('mask overlap counts a line one pixel off only after dilation', () => {
+ const first = new Uint8Array(20 * 4).map((value, index) => (index % 20 === 5 ? 1 : 0));
+ const second = new Uint8Array(20 * 4).map((value, index) => (index % 20 === 6 ? 1 : 0));
+ assert.equal(maskOverlap(first, second).iou, 0);
+ assert.equal(maskOverlap(first, dilate(second, 20, 4, 1)).intersection, 4);
+});
+
+test('the reference scene is a valid recipe with real hard creases', async () => {
+ const recipe = JSON.parse(await readFile(new URL('../bench/reference/line-art-scene.json', import.meta.url), 'utf8'));
+ const withLines = { ...recipe, environment: { ...recipe.environment, lines: { width: 2 } } };
+ await loadAgentSceneModules(withLines);
+ const scene = createAgentScene(withLines);
+ assert.equal(scene.environment.lines.width, 2);
+ assert.equal(scene.parts.length, recipe.nodes.length);
+ assert.equal(recipe.geometries.find(geometry => geometry.id === 'box').bevel, 0);
+});