Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add a look score to the agent task suite

Nguyen Xuan Anf9140542c60c
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index 8176a20e..636aaec5 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -61,6 +61,34 @@ the session, goes to `results/<run>.json`. Grade one recipe by hand with
Compare runs only when they use the same model and suite version. A single run per task is noisy, so read differences
of one or two tasks as noise.
+## Look score
+
+The checks read the exported recipe, so a task can pass and still look wrong. The look score measures what a person
+sees. It is reported in each record under `look`, beside the checks, and is never merged with them into one number.
+
+- **Cameras.** Three fixed orthographic cameras (front, side, three-quarter), placed from the task's reference recipe in
+ `references.mjs` (`look-cameras.mjs`). The reference sets the framing, so a candidate that is too big, too small or
+ off centre shows it in every view. Motion is sampled at time zero.
+- **Silhouette score.** The candidate and the reference are rasterized from each camera (`silhouette.mjs`, plain
+ JavaScript, no GPU, 256 by 256 pixels). Each view scores intersection over union; a task scores the mean in
+ `look.silhouette`. 1 is the reference's own outline. `robot-reach` has no silhouette, because an imported asset needs
+ its skin pose; its record says `skipped`.
+- **Images.** The same cameras drawn by the engine in headless Chrome on SwiftShader, 512 by 512, saved to
+ `artifacts/agent-modeling/<run>/look/` and listed in `look.images`. `run.mjs` and `regrade.mjs` write them. Reference
+ images come from `node bench/agent-modeling/look.mjs --references`.
+- **Vision judge.** `rubric.md` scores shape, proportions, features and surface from 0 to 3. Nothing here calls a model.
+ `node bench/agent-modeling/judge.mjs prompt <run> <task>` prints the rubric, the task prompt and the candidate and
+ reference image paths for each camera; give those to a vision model with no other context. Store its answer with
+ `judge.mjs record <run> <task> --model <name> --scores 3,2,3,1 --note "..."`. It lands in `look.judges.<name>`, so
+ scores from different judges stay apart. Judge scores are not comparable across judge models.
+
+Score one recipe with `node bench/agent-modeling/look.mjs <task> <recipe.json> [--images <directory>]`.
+`tests/agent-look-score.test.js` checks that a widened or incomplete table scores below the correct one, on silhouette
+masks alone.
+
+The results before 2026-10-31 hold no recipes (`artifacts/` is ignored by Git and was not kept), so they have no look
+score and cannot be regraded. The next run records one.
+
## Baseline
`results/2026-10-30-07-48-sonnet-baseline.json`: `claude-sonnet-5-5`, one run per task, without the `build-67js-scene` skill, 67.js 0.11.0.
diff --git a/bench/agent-modeling/judge.mjs b/bench/agent-modeling/judge.mjs
new file mode 100644
index 00000000..7db0dde3
--- /dev/null
+++ b/bench/agent-modeling/judge.mjs
@@ -0,0 +1,74 @@
+// The vision judge's side of the look score. This script never calls a model: it prints what a judge needs, and
+// stores what a judge answered, under the judge's model name.
+//
+// node bench/agent-modeling/judge.mjs prompt <run> <task>
+// node bench/agent-modeling/judge.mjs record <run> <task> --model <name> --scores <shape,proportions,features,surface> [--note <text>]
+//
+// `prompt` prints the rubric, the task prompt and the image paths (candidate, then reference, per camera). Give them
+// to a vision model with no other context. Images come from `look.mjs` (run it first: regrade.mjs does) and
+// `node bench/agent-modeling/look.mjs --references`.
+import { readFile, writeFile } from 'node:fs/promises';
+import { join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { parseArgs } from 'node:util';
+import { LOOK_VIEWS } from './look-cameras.mjs';
+import { taskById } from './tasks.mjs';
+
+const repository = resolve(import.meta.dirname, '../..');
+export const CRITERIA = ['shape', 'proportions', 'features', 'surface'];
+export const CRITERION_MAXIMUM = 3;
+
+function summaryPathOf(runName) {
+ return join(repository, 'bench', 'agent-modeling', 'results', `${runName}.json`);
+}
+
+/** Turns the four criterion scores into one judge record. Throws on a missing, fractional or out-of-range score. */
+export function judgeRecord(scores, note) {
+ if (scores.length !== CRITERIA.length) throw new RangeError(`Give ${CRITERIA.length} scores: ${CRITERIA.join(', ')}.`);
+ for (const score of scores) {
+ if (!Number.isInteger(score) || score < 0 || score > CRITERION_MAXIMUM) throw new RangeError(`Each score is a whole number from 0 to ${CRITERION_MAXIMUM}.`);
+ }
+ const total = scores.reduce((sum, score) => sum + score, 0);
+ return {
+ criteria: Object.fromEntries(CRITERIA.map((name, index) => [name, scores[index]])),
+ total,
+ score: Number((total / (CRITERIA.length * CRITERION_MAXIMUM)).toFixed(4)),
+ ...(note ? { note } : {}),
+ };
+}
+
+async function printPrompt(runName, taskId) {
+ const summary = JSON.parse(await readFile(summaryPathOf(runName), 'utf8'));
+ const record = summary.records.find(candidate => candidate.task === taskId);
+ if (!record?.look?.images?.length) throw new Error(`No look images for ${taskId} in ${runName}. Run regrade.mjs first.`);
+ const rubric = await readFile(join(import.meta.dirname, 'rubric.md'), 'utf8');
+ console.log(rubric);
+ console.log(`Task prompt:\n${taskById(taskId).prompt}\n`);
+ for (const [index, { name }] of LOOK_VIEWS.entries()) {
+ console.log(`Camera ${name}:`);
+ console.log(` candidate: ${record.look.images[index]}`);
+ console.log(` reference: artifacts/agent-modeling/references/${taskId}-${name}.png`);
+ }
+}
+
+async function storeRecord(runName, taskId, { model, scores, note }) {
+ if (!model || !scores) throw new Error('record needs --model and --scores.');
+ const summaryPath = summaryPathOf(runName);
+ const summary = JSON.parse(await readFile(summaryPath, 'utf8'));
+ const record = summary.records.find(candidate => candidate.task === taskId);
+ if (!record?.look) throw new Error(`No look record for ${taskId} in ${runName}.`);
+ record.look.judges = { ...record.look.judges, [model]: judgeRecord(scores.split(',').map(Number), note) };
+ await writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`);
+ console.log(`${taskId} judged by ${model}: ${record.look.judges[model].total}/${CRITERIA.length * CRITERION_MAXIMUM}`);
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const { values, positionals } = parseArgs({
+ allowPositionals: true,
+ options: { model: { type: 'string' }, scores: { type: 'string' }, note: { type: 'string' } },
+ });
+ const [command, runName, taskId] = positionals;
+ if (command === 'prompt') await printPrompt(runName, taskId);
+ else if (command === 'record') await storeRecord(runName, taskId, values);
+ else throw new Error('Use: prompt <run> <task>, or record <run> <task> --model <name> --scores a,b,c,d');
+}
diff --git a/bench/agent-modeling/look-cameras.mjs b/bench/agent-modeling/look-cameras.mjs
new file mode 100644
index 00000000..717f8111
--- /dev/null
+++ b/bench/agent-modeling/look-cameras.mjs
@@ -0,0 +1,47 @@
+// The fixed cameras of the look score. They are placed from the reference's bounds, not the candidate's, so a
+// candidate that is too big, too small or off centre shows it in every view.
+
+const PADDING = 1.2;
+const DISTANCE_FACTOR = 4;
+
+export const LOOK_VIEWS = [
+ { name: 'front', direction: [0, 0, 1] },
+ { name: 'side', direction: [1, 0, 0] },
+ { name: 'three-quarter', direction: [0.58, 0.4, 0.71] },
+];
+
+export function boundsOfGeometries(geometries) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const { positions } of geometries) {
+ for (let index = 0; index < positions.length; index++) {
+ const axis = index % 3;
+ minimum[axis] = Math.min(minimum[axis], positions[index]);
+ maximum[axis] = Math.max(maximum[axis], positions[index]);
+ }
+ }
+ return { minimum, maximum };
+}
+
+/** One orthographic camera per view, all framing the same sphere around the reference. */
+export function lookCameras(referenceBounds) {
+ const target = referenceBounds.minimum.map((value, axis) => (value + referenceBounds.maximum[axis]) / 2);
+ const diameter = Math.hypot(...referenceBounds.maximum.map((value, axis) => value - referenceBounds.minimum[axis]));
+ const distance = diameter * DISTANCE_FACTOR;
+ return LOOK_VIEWS.map(({ name, direction }) => {
+ const length = Math.hypot(...direction);
+ return {
+ name,
+ camera: {
+ eye: target.map((value, axis) => value + direction[axis] / length * distance),
+ target,
+ up: [0, 1, 0],
+ projection: 'orthographic',
+ orthographicHeight: diameter * PADDING,
+ fov: 45,
+ near: 0.1,
+ far: distance * 3,
+ },
+ };
+ });
+}
diff --git a/bench/agent-modeling/look-harness.html b/bench/agent-modeling/look-harness.html
new file mode 100644
index 00000000..b157f4bd
--- /dev/null
+++ b/bench/agent-modeling/look-harness.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+<head>
+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>
+</head>
+<body>
+<canvas></canvas>
+<script type="module" src="./look-harness.js"></script>
+</body>
+</html>
diff --git a/bench/agent-modeling/look-harness.js b/bench/agent-modeling/look-harness.js
new file mode 100644
index 00000000..f3bb64f8
--- /dev/null
+++ b/bench/agent-modeling/look-harness.js
@@ -0,0 +1,35 @@
+// Runs in the page: draws a recipe from each fixed camera, the way the MCP preview draws a scene.
+import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '/src/agent-scene.js';
+import { resolveAgentShadow } from '/src/agent-look.js';
+import { Renderer67 } from '/src/renderer.js';
+
+async function renderLookViews(recipe, views) {
+ if (needsMeshBooleans(recipe)) await loadMeshBooleans();
+ const scene = createAgentScene(recipe);
+ if (recipe.motion) scene.sampleMotion(0);
+ const canvas = document.querySelector('canvas');
+ const environment = scene.environment;
+ const effects = scene.effects;
+ const renderer = new Renderer67(canvas, scene.parts, {
+ ground: false, hdr: true, depth: true, samples: 1, pixelRatio: 1, memoryBudgetMiB: 512,
+ world: environment.world, environment,
+ shadowBounds: resolveAgentShadow(scene.shadow, environment.lightDirection),
+ });
+ const images = [];
+ try {
+ for (const { name, camera } of views) {
+ renderer.resize();
+ renderer.updateParts(scene.parts);
+ renderer.render({ ...camera, environment, effects, exposure: effects.exposure, time: 0 });
+ renderer.render({ ...camera, environment, effects, exposure: effects.exposure, time: 0 });
+ const glError = renderer.context.getError();
+ if (glError !== 0) throw new Error(`${name} gave WebGL error ${glError}.`);
+ images.push({ name, image: canvas.toDataURL('image/png').split(',')[1] });
+ }
+ } finally {
+ renderer.dispose();
+ }
+ return images;
+}
+
+window.renderLookViews = renderLookViews;
diff --git a/bench/agent-modeling/look.mjs b/bench/agent-modeling/look.mjs
new file mode 100644
index 00000000..032da350
--- /dev/null
+++ b/bench/agent-modeling/look.mjs
@@ -0,0 +1,139 @@
+// The look score of the agent modeling suite: how the finished object looks, kept beside the recipe checks and
+// never merged with them.
+//
+// Silhouette score: the recipe and the task's reference are both seen from the same three fixed cameras (placed
+// from the reference), and each view scores the intersection over union of what they cover. A task scores the mean.
+// Images: the same cameras, drawn by the engine in a headless browser on SwiftShader, for the vision judge (judge.mjs).
+//
+// node bench/agent-modeling/look.mjs <task-id> <recipe.json> [--images <directory>]
+// node bench/agent-modeling/look.mjs --references
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import { join, relative, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '../../src/agent-scene.js';
+import { boundsOfGeometries, lookCameras } from './look-cameras.mjs';
+import { worldGeometry } from './measure.mjs';
+import { REFERENCES } from './references.mjs';
+import { intersectionOverUnion, rasterizeSilhouette } from './silhouette.mjs';
+import { TASKS } from './tasks.mjs';
+
+const repository = resolve(import.meta.dirname, '../..');
+const IMAGE_SIZE = 512;
+const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const SWIFTSHADER_ARGUMENTS = ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=swiftshader', '--enable-unsafe-swiftshader'];
+
+const roundScore = value => Number(value.toFixed(4));
+
+/** World-space triangles of every drawn node, with motion sampled at time zero. Asset recipes have none here. */
+export async function worldGeometriesOf(recipe) {
+ if (recipe.format === '67js.asset') return null;
+ if (needsMeshBooleans(recipe)) await loadMeshBooleans();
+ const scene = createAgentScene(recipe);
+ if (recipe.motion) scene.sampleMotion(0);
+ return scene.parts.map(worldGeometry);
+}
+
+/** The three fixed cameras of a task, placed from its reference recipe. Null for asset tasks. */
+export async function camerasForTask(taskId) {
+ const referenceGeometries = await worldGeometriesOf(REFERENCES[taskId]);
+ return referenceGeometries ? lookCameras(boundsOfGeometries(referenceGeometries)) : null;
+}
+
+/** Per-view silhouette overlap with the task's reference, and its mean. Null for asset tasks. */
+export async function scoreSilhouette(taskId, recipe) {
+ const views = await camerasForTask(taskId);
+ if (!views) return null;
+ const referenceGeometries = await worldGeometriesOf(REFERENCES[taskId]);
+ const candidateGeometries = await worldGeometriesOf(recipe);
+ const overlap = {};
+ for (const { name, camera } of views) {
+ overlap[name] = roundScore(intersectionOverUnion(rasterizeSilhouette(candidateGeometries, camera), rasterizeSilhouette(referenceGeometries, camera)));
+ }
+ const values = Object.values(overlap);
+ return { views: overlap, mean: roundScore(values.reduce((sum, value) => sum + value, 0) / values.length) };
+}
+
+async function withLookPage(callback) {
+ const { chromium } = await import('playwright');
+ const { createServer } = await import('vite');
+ const server = await createServer({ root: repository, server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });
+ await server.listen();
+ const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: SWIFTSHADER_ARGUMENTS });
+ try {
+ const page = await browser.newPage({ viewport: { width: IMAGE_SIZE, height: IMAGE_SIZE } });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/bench/agent-modeling/look-harness.html`);
+ await page.waitForFunction(() => window.renderLookViews);
+ const result = await callback(page);
+ if (errors.length) throw new Error(errors.join('\n'));
+ return result;
+ } finally {
+ await browser.close();
+ await server.close();
+ }
+}
+
+/** Draws jobs ([{ recipe, taskId, prefix, directory }]) from the task cameras; returns repository-relative PNG paths per job. */
+export async function renderLookImages(jobs) {
+ return withLookPage(async page => {
+ const written = [];
+ for (const { recipe, taskId, prefix, directory } of jobs) {
+ const views = await camerasForTask(taskId);
+ if (!views) {
+ written.push([]);
+ continue;
+ }
+ const images = await page.evaluate(([sceneRecipe, cameraViews]) => window.renderLookViews(sceneRecipe, cameraViews), [recipe, views]);
+ await mkdir(directory, { recursive: true });
+ const paths = [];
+ for (const { name, image } of images) {
+ const path = join(directory, `${prefix}-${name}.png`);
+ await writeFile(path, Buffer.from(image, 'base64'));
+ paths.push(relative(repository, path).replaceAll('\\', '/'));
+ }
+ written.push(paths);
+ }
+ return written;
+ });
+}
+
+/** The look record of one finished task: silhouette scores and the images they came from. Judges are added later. */
+export async function scoreLook(taskId, recipe, { imageDirectory } = {}) {
+ const silhouette = await scoreSilhouette(taskId, recipe);
+ if (!silhouette) return { skipped: 'asset recipes have no static silhouette' };
+ const look = { silhouette };
+ if (imageDirectory) {
+ const [images] = await renderLookImages([{ recipe, taskId, prefix: taskId, directory: imageDirectory }]);
+ look.images = images;
+ }
+ return look;
+}
+
+/** Like scoreLook, but an invalid recipe or a render failure becomes a recorded error, so one task cannot stop a run. */
+export async function scoreLookSafely(taskId, recipe, options) {
+ try {
+ return await scoreLook(taskId, recipe, options);
+ } catch (error) {
+ return { error: error.message.split('\n')[0] };
+ }
+}
+
+/** Renders every reference from its own cameras, the images a judge sees as the target. */
+export async function renderReferenceImages() {
+ const directory = join(repository, 'artifacts', 'agent-modeling', 'references');
+ const jobs = TASKS.map(task => ({ recipe: REFERENCES[task.id], taskId: task.id, prefix: task.id, directory }));
+ return renderLookImages(jobs);
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const [first, second, flag, directory] = process.argv.slice(2);
+ if (first === '--references') {
+ const paths = await renderReferenceImages();
+ console.log(`${paths.flat().length} reference images in artifacts/agent-modeling/references`);
+ } else {
+ const recipe = JSON.parse(await readFile(second, 'utf8'));
+ const look = await scoreLook(first, recipe, { imageDirectory: flag === '--images' ? resolve(directory) : undefined });
+ console.log(JSON.stringify(look, null, 2));
+ }
+}
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index b428055f..af190bed 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -17,7 +17,7 @@ function transformPoint(matrix, x, y, z) {
];
}
-function worldGeometry(part) {
+export function worldGeometry(part) {
const source = part.geometry;
const positions = new Float32Array(source.positions.length);
for (let vertex = 0; vertex < source.positions.length / 3; vertex++) {
diff --git a/bench/agent-modeling/regrade.mjs b/bench/agent-modeling/regrade.mjs
index bb02369e..cdcd9c8f 100644
--- a/bench/agent-modeling/regrade.mjs
+++ b/bench/agent-modeling/regrade.mjs
@@ -3,6 +3,7 @@
import { readFile, writeFile } from 'node:fs/promises';
import { join, resolve } from 'node:path';
import { gradeRecipe, recipeFeatures } from './check.mjs';
+import { scoreLookSafely } from './look.mjs';
import { taskById } from './tasks.mjs';
const repository = resolve(import.meta.dirname, '../..');
@@ -18,11 +19,16 @@ for (const record of summary.records) {
}
const grade = await gradeRecipe(taskById(record.task), recipe);
record.features = recipeFeatures(recipe);
+ // Keep a judge's score when the same recipe is scored again.
+ const judges = record.look?.judges;
+ record.look = await scoreLookSafely(record.task, recipe, { imageDirectory: join(repository, 'artifacts', 'agent-modeling', runName, 'look') });
+ if (judges) record.look.judges = judges;
record.pass = grade.pass;
record.passed = grade.passed;
record.total = grade.total;
record.failed = grade.results.filter(result => !result.pass).map(result => `${result.label ?? result.kind}: ${result.detail}`);
- console.log(`${record.task.padEnd(9)} ${record.pass ? 'PASS' : 'FAIL'} ${record.passed}/${record.total}${record.failed.length ? ` ${record.failed.join(' | ')}` : ''}`);
+ const lookText = record.look?.silhouette ? `look ${record.look.silhouette.mean}` : 'look n/a';
+ console.log(`${record.task.padEnd(9)} ${record.pass ? 'PASS' : 'FAIL'} ${record.passed}/${record.total} ${lookText}${record.failed.length ? ` ${record.failed.join(' | ')}` : ''}`);
}
summary.passed = summary.records.filter(record => record.pass).length;
await writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`);
diff --git a/bench/agent-modeling/rubric.md b/bench/agent-modeling/rubric.md
new file mode 100644
index 00000000..131ca141
--- /dev/null
+++ b/bench/agent-modeling/rubric.md
@@ -0,0 +1,20 @@
+You judge how well a 3D object matches a task. You see the task prompt, then for each of three fixed cameras (front,
+side, three-quarter) two images: the candidate, and a reference built by hand for the same task. The machine checks
+already measure exact sizes, so judge only what a person sees. Do not reward detail the prompt did not ask for.
+
+Score four criteria from 0 to 3, then add them for a total from 0 to 12.
+
+1. Shape: the object is the thing the prompt names, and its main forms match the reference in every view.
+ 0 = unrecognisable or the wrong object, 1 = recognisable but a main form is missing or wrong,
+ 2 = right forms with a visible flaw, 3 = matches the reference.
+2. Proportions: parts have the right size and position relative to each other and the ground.
+ 0 = badly off, 1 = clearly off in one view, 2 = slightly off, 3 = matches.
+3. Features: every feature the prompt asks for is present, in the right place and count (holes, teeth, recesses,
+ handles, rails), and none is added or fused.
+ 0 = most missing, 1 = some missing or wrong, 2 = all present with a flaw, 3 = all correct.
+4. Surface: the surface reads as one clean object. Look for gaps, floating or overlapping parts, flipped or dark faces,
+ stretched patterns and rough edges that the reference does not have.
+ 0 = broken, 1 = obvious faults, 2 = minor faults, 3 = clean.
+
+Answer with the four criterion scores, the total, and one sentence naming the largest difference from the reference.
+Judge from the images only. If an image is missing or blank, score every criterion 0 and say so.
diff --git a/bench/agent-modeling/run.mjs b/bench/agent-modeling/run.mjs
index 122df7aa..c5cfee39 100644
--- a/bench/agent-modeling/run.mjs
+++ b/bench/agent-modeling/run.mjs
@@ -16,6 +16,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { parseArgs } from 'node:util';
import { gradeRecipe, recipeFeatures } from './check.mjs';
+import { scoreLookSafely } from './look.mjs';
import { PROMPT_PREAMBLE, TASKS, taskById } from './tasks.mjs';
const repository = resolve(import.meta.dirname, '../..');
@@ -175,6 +176,7 @@ async function runTask(task, systemPromptAddition) {
toolErrors: transcript.toolErrors,
toolsByName: transcript.toolsByName,
features: transcript.recipe ? recipeFeatures(transcript.recipe) : null,
+ look: transcript.recipe ? await scoreLookSafely(task.id, transcript.recipe, { imageDirectory: join(rawDirectory, 'look') }) : null,
turns: transcript.result?.num_turns ?? null,
costUsd: transcript.result?.total_cost_usd ?? null,
inputTokens: (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0),
diff --git a/bench/agent-modeling/silhouette.mjs b/bench/agent-modeling/silhouette.mjs
new file mode 100644
index 00000000..47aaf508
--- /dev/null
+++ b/bench/agent-modeling/silhouette.mjs
@@ -0,0 +1,93 @@
+// Silhouette masks and their overlap. The look score compares what the object covers from a fixed camera, so a
+// recipe that passes every size check but is shaped wrongly still scores lower.
+//
+// The cameras are orthographic: a pixel is covered when any triangle of the object lands on it, which needs no GPU
+// and gives the same mask on every machine.
+
+export const MASK_SIZE = 256;
+
+function subtract(first, second) {
+ return first.map((value, axis) => value - second[axis]);
+}
+
+function cross(first, second) {
+ return [
+ first[1] * second[2] - first[2] * second[1],
+ first[2] * second[0] - first[0] * second[2],
+ first[0] * second[1] - first[1] * second[0],
+ ];
+}
+
+function normalize(vector) {
+ const length = Math.hypot(...vector);
+ return vector.map(value => value / length);
+}
+
+function dot(first, second) {
+ return first.reduce((sum, value, axis) => sum + value * second[axis], 0);
+}
+
+function cameraBasis(camera) {
+ const forward = normalize(subtract(camera.target, camera.eye));
+ const right = normalize(cross(forward, camera.up));
+ const up = cross(right, forward);
+ return { right, up };
+}
+
+/** Projects a world point to pixel coordinates; y grows downward like an image. */
+export function projectToPixel(camera, point, size = MASK_SIZE) {
+ const { right, up } = cameraBasis(camera);
+ const offset = subtract(point, camera.target);
+ const height = camera.orthographicHeight;
+ return [
+ size / 2 + dot(offset, right) / height * size,
+ size / 2 - dot(offset, up) / height * size,
+ ];
+}
+
+function fillTriangle(mask, size, corners) {
+ const [first, second, third] = corners;
+ const minimumX = Math.max(0, Math.floor(Math.min(first[0], second[0], third[0])));
+ const maximumX = Math.min(size - 1, Math.ceil(Math.max(first[0], second[0], third[0])));
+ const minimumY = Math.max(0, Math.floor(Math.min(first[1], second[1], third[1])));
+ const maximumY = Math.min(size - 1, Math.ceil(Math.max(first[1], second[1], third[1])));
+ const area = (second[0] - first[0]) * (third[1] - first[1]) - (third[0] - first[0]) * (second[1] - first[1]);
+ if (area === 0) return;
+ for (let y = minimumY; y <= maximumY; y++) {
+ for (let x = minimumX; x <= maximumX; x++) {
+ const pointX = x + 0.5;
+ const pointY = y + 0.5;
+ const weightFirst = ((second[0] - pointX) * (third[1] - pointY) - (third[0] - pointX) * (second[1] - pointY)) / area;
+ const weightSecond = ((third[0] - pointX) * (first[1] - pointY) - (first[0] - pointX) * (third[1] - pointY)) / area;
+ const weightThird = 1 - weightFirst - weightSecond;
+ if (weightFirst >= 0 && weightSecond >= 0 && weightThird >= 0) mask[y * size + x] = 1;
+ }
+ }
+}
+
+/** Rasterizes world-space geometries ({ positions, indices }) into a 0/1 mask. */
+export function rasterizeSilhouette(geometries, camera, size = MASK_SIZE) {
+ const mask = new Uint8Array(size * size);
+ for (const { positions, indices } of geometries) {
+ const pixels = [];
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ pixels.push(projectToPixel(camera, [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]], size));
+ }
+ for (let triangle = 0; triangle < indices.length; triangle += 3) {
+ fillTriangle(mask, size, [pixels[indices[triangle]], pixels[indices[triangle + 1]], pixels[indices[triangle + 2]]]);
+ }
+ }
+ return mask;
+}
+
+/** Intersection over union of two masks of equal size. Two empty masks count as a perfect match. */
+export function intersectionOverUnion(first, second) {
+ if (first.length !== second.length) throw new RangeError('Masks must have the same size.');
+ let intersection = 0;
+ let union = 0;
+ for (let pixel = 0; pixel < first.length; pixel++) {
+ if (first[pixel] && second[pixel]) intersection++;
+ if (first[pixel] || second[pixel]) union++;
+ }
+ return union === 0 ? 1 : intersection / union;
+}
diff --git a/tests/agent-look-score.test.js b/tests/agent-look-score.test.js
new file mode 100644
index 00000000..48d662da
--- /dev/null
+++ b/tests/agent-look-score.test.js
@@ -0,0 +1,72 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { judgeRecord } from '../bench/agent-modeling/judge.mjs';
+import { scoreSilhouette } from '../bench/agent-modeling/look.mjs';
+import { REFERENCES } from '../bench/agent-modeling/references.mjs';
+import { intersectionOverUnion, rasterizeSilhouette } from '../bench/agent-modeling/silhouette.mjs';
+import { TASKS } from '../bench/agent-modeling/tasks.mjs';
+
+const frontCamera = {
+ eye: [0, 0, 10], target: [0, 0, 0], up: [0, 1, 0], projection: 'orthographic', orthographicHeight: 4,
+};
+
+function square(halfSize, centreX = 0) {
+ return {
+ positions: [-halfSize + centreX, -halfSize, 0, halfSize + centreX, -halfSize, 0, halfSize + centreX, halfSize, 0, -halfSize + centreX, halfSize, 0],
+ indices: [0, 1, 2, 0, 2, 3],
+ };
+}
+
+const coveredPixels = mask => mask.reduce((sum, pixel) => sum + pixel, 0);
+
+test('the rasterizer covers the area a square takes in an orthographic view', () => {
+ const mask = rasterizeSilhouette([square(1)], frontCamera, 100);
+ assert.ok(Math.abs(coveredPixels(mask) - 2500) <= 200, `covered ${coveredPixels(mask)} of 10000`);
+});
+
+test('intersection over union is 1 for equal masks, 0 for disjoint masks and a fraction for partial overlap', () => {
+ const left = rasterizeSilhouette([square(1, -1.5)], frontCamera, 100);
+ const same = rasterizeSilhouette([square(1, -1.5)], frontCamera, 100);
+ const farRight = rasterizeSilhouette([square(0.2, 1.8)], frontCamera, 100);
+ const shifted = rasterizeSilhouette([square(1, -0.5)], frontCamera, 100);
+ assert.equal(intersectionOverUnion(left, same), 1);
+ assert.equal(intersectionOverUnion(left, farRight), 0);
+ const partial = intersectionOverUnion(left, shifted);
+ assert.ok(partial > 0.25 && partial < 0.45, `partial overlap ${partial}`);
+ assert.equal(intersectionOverUnion(new Uint8Array(4), new Uint8Array(4)), 1);
+ assert.throws(() => intersectionOverUnion(new Uint8Array(4), new Uint8Array(9)), RangeError);
+});
+
+test('every scene reference scores 1 against itself', async () => {
+ for (const task of TASKS) {
+ const silhouette = await scoreSilhouette(task.id, REFERENCES[task.id]);
+ if (task.id === 'robot-reach') {
+ assert.equal(silhouette, null);
+ } else {
+ assert.equal(silhouette.mean, 1, task.id);
+ }
+ }
+});
+
+test('a broken table scores lower than a correct one, and each flaw lowers it', async () => {
+ const widened = structuredClone(REFERENCES.table);
+ widened.nodes[0].scale = [1.4, 1, 1];
+ const missingLeg = structuredClone(REFERENCES.table);
+ const lastLeg = missingLeg.nodes.findLastIndex(node => node.id?.includes('leg'));
+ missingLeg.nodes.splice(lastLeg, 1);
+ const correct = await scoreSilhouette('table', REFERENCES.table);
+ const wide = await scoreSilhouette('table', widened);
+ const short = await scoreSilhouette('table', missingLeg);
+ assert.ok(wide.mean < correct.mean - 0.05, `widened ${wide.mean} vs ${correct.mean}`);
+ assert.ok(short.mean < correct.mean, `missing leg ${short.mean} vs ${correct.mean}`);
+});
+
+test('a judge record needs four whole scores in range and keeps its criteria apart from the total', () => {
+ const record = judgeRecord([3, 2, 3, 1], 'handle too thin');
+ assert.deepEqual(record.criteria, { shape: 3, proportions: 2, features: 3, surface: 1 });
+ assert.equal(record.total, 9);
+ assert.equal(record.score, 0.75);
+ assert.throws(() => judgeRecord([3, 2, 3]), RangeError);
+ assert.throws(() => judgeRecord([4, 0, 0, 0]), RangeError);
+ assert.throws(() => judgeRecord([1.5, 0, 0, 0]), RangeError);
+});