Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add relations between parts to agent recipes

Nguyen Xuan An04a94d0a3c79
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a7a607b..22f09a38 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add relations between parts (part of issue #44, no new tool): a mesh node takes `relations` (`attach`, `gap`, `flush`, `align`, `centered`, up to 8) against other mesh nodes, or against the faces of one carrying a mesh tag (`region`). They work on world bounds, are solved after geometry exists and again on every `scene_apply`, so one edit to a body keeps the parts that sit against it. Unknown IDs and tags, two relations on one axis and cycles (a part waiting on its own child included) are rejected with the next action; solving is deterministic and independent of node order. The code loads on demand (`relations`). The `scene_create` and `scene_apply` schemas grew by about 1.3 KB each (budgets raised by 2600 bytes in total). The agent modeling suite gains `kettle-resize` and `kettle-resize-plain` and a `touches` check; on Sonnet both pass 3 of 3 in 3 to 4 calls each, so relations did not cut tool calls on a task that one batched `scene_apply` already solves.
+
- Add branches and labelled images to the agent tools (part of issue #67, no new tool). `scene_apply` with a `branch` name runs the operations on a scratch copy and stores the result in a snapshot store that holds one copy per distinct recipe (8 branches), leaving the scene, its revision and its checkpoints untouched. `scene_review` shots take a `branch` and render it in a private scene; `scene_restore` with `branch` keeps one. `labels: true` on `scene_look` and `scene_review` draws part names, material tags and mesh lint problems on the image and returns them as JSON with pixel positions. Branch names are bounded (`^[a-z][a-z0-9_-]{0,23}$`). The tool-schema budget rose by 800 bytes in total (150 for `scene_apply`). `npm run smoke:agent-branches` drives it through MCP on SwiftShader.
- Add a bounded material node graph (issue #50): material `pattern` of `type: "graph"` bakes noise, voronoi, wave, checker, gradient, ramp, maths and `uv` nodes on the CPU into base colour, roughness, metallic, emission and height (a normal map, so bump). The graph is data, never shader text; nodes, depth, ramp stops, texture size and work are checked before any pixel is computed. Add `mapping: "uv"` to every pattern so it follows `uv_unwrap` UVs instead of box projection; the emissive map now box-maps like the other maps. The 11 presets bake the same bytes as before. Covered in the MCP schema, `scene_capabilities` (`materialGraph`, `materialMappings`), GLB export, `docs/agent-scene.md`, `docs/material-maps.md` and the `brick-graph` reference scene.
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index b869cf4a..75c67f58 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -34,6 +34,7 @@ own mesh report:
| soap | Rounding every edge (bevel) |
| pebble | A smooth solid from a box (subdivision) |
| crate-uv | The crate with even UVs |
+| kettle-resize, kettle-resize-plain | Resize a kettle body so the lid, handle and spout stay against it. The first start recipe holds `relations`, the second absolute positions; the difference in tool calls is what relations are worth |
| crate-wood | The crate with a wood material pattern, to see whether agents find `pattern` |
| arm-reach | A jointed arm whose tip moves between two points, to see whether agents find `motion.ik` |
| leg-plant | A leg that plants its foot on two points with the knee bending forward: `motion.ik` with `bendToward`, `pole` and `limits` |
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index 93e2f724..acf614ae 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -8,6 +8,7 @@ import { REQUIRED_HUMANOID_BONES } from '../../src/retarget.js';
const AXES = { x: 0, y: 1, z: 2 };
const SIZE_TOLERANCE = 0.03;
const SIZE_FLOOR = 0.003;
+const TOUCH_TOLERANCE = 0.003;
const GROUND_TOLERANCE = 0.005;
const round = value => Number(value.toPrecision(4));
@@ -94,6 +95,16 @@ function checkOne(check, measures) {
const everyPart = measures.uv.parts === measures.uv.of;
return { pass: followsUvs && everyPart && measures.uv.stretch <= check.maxStretch, detail: followsUvs ? `graph on UVs, stretch ${round(measures.uv.stretch)}, ${measures.uv.parts}/${measures.uv.of} parts with UVs` : 'no graph material with mapping uv' };
}
+ case 'touches': {
+ const node = measures.nodeBounds(check.node);
+ const against = measures.nodeBounds(check.against);
+ if (!node || !against) return { pass: false, detail: `no drawn node ${check.node} or ${check.against}` };
+ const axis = AXES[check.side[1]];
+ const gap = check.side[0] === '+' ? node.min[axis] - against.max[axis] : against.min[axis] - node.max[axis];
+ const otherAxes = [0, 1, 2].filter(other => other !== axis);
+ const overlaps = otherAxes.every(other => node.min[other] < against.max[other] && node.max[other] > against.min[other]);
+ return { pass: Math.abs(gap) <= TOUCH_TOLERANCE && overlaps, detail: `${check.node} is ${round(gap)} m from ${check.against}${overlaps ? '' : ' and does not overlap it'}` };
+ }
case 'nodeAt': {
const position = measures.nodePosition(check.node, check.time);
if (!position) return { pass: false, detail: `no drawn node ${check.node}` };
diff --git a/bench/agent-modeling/kettle.mjs b/bench/agent-modeling/kettle.mjs
new file mode 100644
index 00000000..7a9489b4
--- /dev/null
+++ b/bench/agent-modeling/kettle.mjs
@@ -0,0 +1,43 @@
+// A kettle whose lid, handle and spout sit against its body. The relations version states that in the recipe, so the
+// body can be resized with one edit; the plain version holds the same parts as absolute positions.
+
+const LID_SIZE = [0.12, 0.02, 0.1];
+const HANDLE_SIZE = [0.03, 0.1, 0.04];
+const SPOUT_SIZE = [0.04, 0.03, 0.03];
+
+function relationsIf(withRelations, relation) {
+ return withRelations ? { relations: [relation] } : {};
+}
+
+export function kettleRecipe(bodySize, withRelations) {
+ const [bodyWidth, bodyHeight] = bodySize;
+ const bodyCentreY = bodyHeight / 2;
+ const sideCentreX = bodyWidth / 2;
+ const parts = [
+ { id: 'body', geometry: 'block', translation: [0, bodyCentreY, 0], scale: bodySize },
+ {
+ id: 'lid', geometry: 'block', scale: LID_SIZE, translation: [0, bodyHeight + LID_SIZE[1] / 2, 0],
+ ...relationsIf(withRelations, { kind: 'attach', to: 'body', side: '+y' }),
+ },
+ {
+ id: 'handle', geometry: 'block', scale: HANDLE_SIZE, translation: [sideCentreX + HANDLE_SIZE[0] / 2, bodyCentreY, 0],
+ ...relationsIf(withRelations, { kind: 'attach', to: 'body', side: '+x' }),
+ },
+ {
+ id: 'spout', geometry: 'block', scale: SPOUT_SIZE, translation: [-sideCentreX - SPOUT_SIZE[0] / 2, bodyCentreY, 0],
+ ...relationsIf(withRelations, { kind: 'attach', to: 'body', side: '-x' }),
+ },
+ ];
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.6, 0.55, 0.5] }],
+ nodes: parts.map(part => ({ material: 'paint', ...part })),
+ };
+}
+
+/** The kettle as the task starts: a 0.2 x 0.16 x 0.12 m body, with or without relations on its parts. */
+export const KETTLE_START = kettleRecipe([0.2, 0.16, 0.12], true);
+export const KETTLE_START_PLAIN = kettleRecipe([0.2, 0.16, 0.12], false);
+export const KETTLE_RESIZED = kettleRecipe([0.3, 0.24, 0.12], true);
+export const KETTLE_RESIZED_PLAIN = kettleRecipe([0.3, 0.24, 0.12], false);
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 761c2ab1..4f8abae9 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -4,7 +4,7 @@
// agent sees: welding render triangles again can invent non-manifold edges that the polygon mesh does not have.
import { readFile } from 'node:fs/promises';
import { createAgentAssetScene } from '../../src/agent-asset.js';
-import { createAgentScene, loadMeshBooleans, needsMeshBooleans, loadPhysicsEngine, needsPhysics } from '../../src/agent-scene.js';
+import { createAgentScene, loadAllAgentSceneModules, loadMeshBooleans, needsMeshBooleans, loadPhysicsEngine, needsPhysics } from '../../src/agent-scene.js';
import { parseGltf } from '../../src/gltf.js';
import { GEOMETRY_PROBLEMS } from '../../src/mesh-lint.js';
@@ -18,6 +18,16 @@ function transformPoint(matrix, x, y, z) {
];
}
+function boundsOfPositions(positions) {
+ const bounds = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };
+ for (let index = 0; index < positions.length; index++) {
+ const axis = index % 3;
+ bounds.min[axis] = Math.min(bounds.min[axis], positions[index]);
+ bounds.max[axis] = Math.max(bounds.max[axis], positions[index]);
+ }
+ return bounds;
+}
+
export function worldGeometry(part) {
const source = part.geometry;
const positions = new Float32Array(source.positions.length);
@@ -278,6 +288,7 @@ function measureRig(scene, duration) {
/** Load the recipe and measure what it builds. Throws if the recipe itself is invalid. */
export async function measureRecipe(recipe) {
+ await loadAllAgentSceneModules();
if (needsMeshBooleans(recipe)) await loadMeshBooleans();
if (needsPhysics(recipe)) await loadPhysicsEngine();
const scene = createAgentScene(recipe);
@@ -349,6 +360,10 @@ export async function measureRecipe(recipe) {
const part = scene.parts.find(candidate => candidate.name === name);
return part ? [part.matrix[12], part.matrix[13], part.matrix[14]] : null;
},
+ nodeBounds(name) {
+ const part = scene.parts.find(candidate => candidate.name === name);
+ return part ? boundsOfPositions(worldGeometry(part).positions) : null;
+ },
lineHits: (axis, point) => lineHits(geometries, axis, point),
};
}
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index c24a7970..ecd320ee 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -6,6 +6,7 @@ const SUBDIVIDED_CUBE_SPAN = 0.8492;
const PEBBLE_SIZE = [0.08, 0.03, 0.05];
import { walkerRecipe } from './walker.mjs';
+import { KETTLE_RESIZED, KETTLE_RESIZED_PLAIN } from './kettle.mjs';
const material = [{ id: 'paint', color: [0.6, 0.55, 0.5] }];
@@ -161,6 +162,8 @@ function robotArmSolver(root, middle, end, target) {
}
export const REFERENCES = {
+ 'kettle-resize': KETTLE_RESIZED,
+ 'kettle-resize-plain': KETTLE_RESIZED_PLAIN,
'chamfer-plate': scene(
[{
id: 'plate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [
diff --git a/bench/agent-modeling/results/2026-10-31-11-43-sonnet-relations-kettle.json b/bench/agent-modeling/results/2026-10-31-11-43-sonnet-relations-kettle.json
new file mode 100644
index 00000000..dc72381d
--- /dev/null
+++ b/bench/agent-modeling/results/2026-10-31-11-43-sonnet-relations-kettle.json
@@ -0,0 +1,294 @@
+{
+ "run": "2026-10-31-11-43-sonnet-relations-kettle",
+ "model": "claude-sonnet-5-5",
+ "date": "2026-10-31T11:46:03.448Z",
+ "skill": false,
+ "runsPerTask": 3,
+ "passed": 6,
+ "tasks": 6,
+ "toolCalls": 19,
+ "costUsd": 2.01,
+ "byModel": {
+ "claude-sonnet-5-5": {
+ "runs": 6,
+ "passed": 6,
+ "successRate": 1,
+ "toolCalls": 19,
+ "toolErrors": 0,
+ "inputTokens": 2318082,
+ "outputTokens": 8250,
+ "costUsd": 2.01,
+ "tasks": {
+ "kettle-resize": {
+ "runs": 3,
+ "passed": 3,
+ "successRate": 1,
+ "toolCalls": 10,
+ "toolErrors": 0,
+ "inputTokens": 1132314,
+ "outputTokens": 4135,
+ "costUsd": 0.98
+ },
+ "kettle-resize-plain": {
+ "runs": 3,
+ "passed": 3,
+ "successRate": 1,
+ "toolCalls": 9,
+ "toolErrors": 0,
+ "inputTokens": 1185768,
+ "outputTokens": 4115,
+ "costUsd": 1.03
+ }
+ }
+ }
+ },
+ "records": [
+ {
+ "task": "kettle-resize",
+ "attempt": 1,
+ "pass": true,
+ "passed": 6,
+ "total": 6,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 3,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_apply": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "error": "page.evaluate: Error: This recipe needs the relations code, which loads on demand: await loadAgentSceneModules(recipe) before createAgentScene or apply."
+ },
+ "turns": 5,
+ "costUsd": 0.3010621,
+ "inputTokens": 355832,
+ "outputTokens": 1297,
+ "wallSeconds": 20,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "kettle-resize-plain",
+ "attempt": 1,
+ "pass": true,
+ "passed": 6,
+ "total": 6,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 3,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_apply": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "silhouette": {
+ "views": {
+ "front": 1,
+ "side": 1,
+ "three-quarter": 1
+ },
+ "mean": 1
+ },
+ "images": [
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/1/kettle-resize-plain-front.png",
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/1/kettle-resize-plain-side.png",
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/1/kettle-resize-plain-three-quarter.png"
+ ]
+ },
+ "turns": 5,
+ "costUsd": 0.3657444,
+ "inputTokens": 415248,
+ "outputTokens": 1394,
+ "wallSeconds": 24,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "kettle-resize",
+ "attempt": 2,
+ "pass": true,
+ "passed": 6,
+ "total": 6,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 3,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_apply": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "error": "page.evaluate: Error: This recipe needs the relations code, which loads on demand: await loadAgentSceneModules(recipe) before createAgentScene or apply."
+ },
+ "turns": 5,
+ "costUsd": 0.3696424,
+ "inputTokens": 418810,
+ "outputTokens": 1373,
+ "wallSeconds": 22,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "kettle-resize-plain",
+ "attempt": 2,
+ "pass": true,
+ "passed": 6,
+ "total": 6,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 3,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_apply": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "silhouette": {
+ "views": {
+ "front": 1,
+ "side": 1,
+ "three-quarter": 1
+ },
+ "mean": 1
+ },
+ "images": [
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/2/kettle-resize-plain-front.png",
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/2/kettle-resize-plain-side.png",
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/2/kettle-resize-plain-three-quarter.png"
+ ]
+ },
+ "turns": 5,
+ "costUsd": 0.30121159999999997,
+ "inputTokens": 355264,
+ "outputTokens": 1389,
+ "wallSeconds": 25,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "kettle-resize",
+ "attempt": 3,
+ "pass": true,
+ "passed": 6,
+ "total": 6,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 4,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_apply": 1,
+ "scene_inspect": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "error": "page.evaluate: Error: This recipe needs the relations code, which loads on demand: await loadAgentSceneModules(recipe) before createAgentScene or apply."
+ },
+ "turns": 6,
+ "costUsd": 0.3065453,
+ "inputTokens": 357672,
+ "outputTokens": 1465,
+ "wallSeconds": 24,
+ "exitCode": 0,
+ "stopped": "success"
+ },
+ {
+ "task": "kettle-resize-plain",
+ "attempt": 3,
+ "pass": true,
+ "passed": 6,
+ "total": 6,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 3,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_apply": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "box"
+ ],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "silhouette": {
+ "views": {
+ "front": 1,
+ "side": 1,
+ "three-quarter": 1
+ },
+ "mean": 1
+ },
+ "images": [
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/3/kettle-resize-plain-front.png",
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/3/kettle-resize-plain-side.png",
+ "artifacts/agent-modeling/2026-10-31-11-43-sonnet-relations-kettle/look/3/kettle-resize-plain-three-quarter.png"
+ ]
+ },
+ "turns": 5,
+ "costUsd": 0.3651057,
+ "inputTokens": 415256,
+ "outputTokens": 1332,
+ "wallSeconds": 26,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index 8f729ac8..07eeb830 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -2,6 +2,7 @@
// the agent exports (see measure.mjs and check.mjs); none of them looks at how the object was built.
import { REFERENCES } from './references.mjs';
+import { KETTLE_START, KETTLE_START_PLAIN } from './kettle.mjs';
export const PROMPT_PREAMBLE = `You are modeling with the 67.js MCP tools. Build the object described below as a procedural recipe scene:
start it with scene_create, refine it with mesh_edit, mesh_stack and scene_apply, and look at it with scene_look when
@@ -25,6 +26,25 @@ const crateChecks = [
const START_INSTRUCTION = 'Start by calling scene_create with exactly this recipe, then change that scene (do not start over):';
const compactRecipe = recipe => JSON.stringify(recipe);
+// The same resize twice: the start recipe either states where the lid, handle and spout sit (relations) or holds
+// absolute positions. The difference in tool calls is what relations are worth to an agent.
+const KETTLE_PROMPT = `The kettle scene below has a body with a lid, a handle and a spout against it. Make the body 0.3 m wide (X)
+and 0.24 m tall (Y), still 0.12 m deep, resting on the ground and centred on X = 0. The lid must still sit on top of the body,
+the handle against its +X side and the spout against its -X side, each touching the body and centred on it as before. Keep
+the lid, handle and spout the size they are.`;
+const KETTLE_CHECKS = [
+ { kind: 'lint' },
+ { kind: 'size', expected: [0.37, 0.26, 0.12] },
+ { kind: 'ground' },
+ { kind: 'touches', node: 'lid', against: 'body', side: '+y' },
+ { kind: 'touches', node: 'handle', against: 'body', side: '+x' },
+ { kind: 'touches', node: 'spout', against: 'body', side: '-x' },
+];
+const KETTLE_TASKS = [
+ { id: 'kettle-resize', startRecipe: KETTLE_START, prompt: KETTLE_PROMPT, checks: KETTLE_CHECKS },
+ { id: 'kettle-resize-plain', startRecipe: KETTLE_START_PLAIN, prompt: KETTLE_PROMPT, checks: KETTLE_CHECKS },
+];
+
const LONG_TASKS = [
{
id: 'chamfer-plate',
@@ -471,6 +491,7 @@ recipe is what gets graded.`,
{ kind: 'assetReach', endLabel: 'Palm2.R', from: [-1.3, 2.6, 0.8], to: [-1, 1.7, 1.1] },
],
},
+ ...KETTLE_TASKS,
...LONG_TASKS,
];
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index 132a1512..245eca36 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 274345,
- "gzip": 77993,
- "brotli": 66486
+ "min": 274408,
+ "gzip": 78007,
+ "brotli": 66600
},
"entry:model": {
"min": 40093,
@@ -129,24 +129,24 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 190633,
- "gzip": 57326,
- "brotli": 49610
+ "min": 191009,
+ "gzip": 57473,
+ "brotli": 49639
},
"entry:agent-scene+lazy": {
- "min": 498812,
- "gzip": 164401,
- "brotli": 143354
+ "min": 506697,
+ "gzip": 167503,
+ "brotli": 146027
},
"entry:agent-asset": {
- "min": 270394,
- "gzip": 82147,
- "brotli": 71444
+ "min": 270689,
+ "gzip": 82267,
+ "brotli": 71609
},
"entry:agent-asset+lazy": {
- "min": 525913,
- "gzip": 171671,
- "brotli": 149210
+ "min": 533717,
+ "gzip": 174748,
+ "brotli": 152144
},
"entry:hdri": {
"min": 8075,
@@ -164,14 +164,14 @@
"brotli": 64299
},
"scene:agent-scene": {
- "min": 294018,
- "gzip": 84354,
- "brotli": 72502
+ "min": 294313,
+ "gzip": 84458,
+ "brotli": 72526
},
"scene:agent-scene+lazy": {
- "min": 602197,
- "gzip": 191435,
- "brotli": 166207
+ "min": 610001,
+ "gzip": 194494,
+ "brotli": 168859
}
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 6afa0d4d..d75adf40 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,9 +1,9 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); was 373388 schema bytes before shared IDs and recipe references",
- "schemaTotalBytes": 190700,
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool), then by 2600 total, 1300 for scene_create and 1350 for scene_apply for the node relations field (no new tool); was 373388 schema bytes before shared IDs and recipe references",
+ "schemaTotalBytes": 193300,
"schemaToolBytes": {
- "scene_create": 60900,
- "scene_apply": 47550,
+ "scene_create": 62200,
+ "scene_apply": 48900,
"mesh_edit": 34000,
"scene_create_asset": 19750,
"mesh_stack": 11500
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index f0c2eae0..fd7ed50d 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -47,7 +47,7 @@ The normal frame loop can render retained parts without calling inspection or ex
### On-demand code
-Mesh editing, `lathe`, `extrude` and `tube` geometry, material `pattern` and `motion` load on demand, so a recipe of
+Mesh editing, `lathe`, `extrude` and `tube` geometry, material `pattern`, `motion` and node `relations` load on demand, so a recipe of
primitives pays about half the bytes. `createAgentScene` and `apply` stay synchronous. When a recipe uses one of them,
load its code first; a missing module throws an error that names this call.
@@ -232,6 +232,38 @@ dropped. `yaw` turns each instance randomly about up, `alignToNormal` (surface o
is a random uniform `[min, max]`. At most 2048 candidate points per node, and the scene's node limit still applies.
The group's own scale applies to the spacing and the points, because they are in its space.
+### Relations between parts
+
+A mesh node can list `relations` that place it against other mesh nodes, so a resized body keeps its handle where it
+belongs. They work on world bounds, are solved after the geometry exists, and are solved again on every `scene_apply`
+(a `set-node` that moves or resizes the target, an `edit-mesh` that changes its faces), so one edit to the body moves
+every part that sits against it.
+
+```text
+{ "id": "handle", "geometry": "grip", "material": "steel",
+ "relations": [ { "kind": "attach", "to": "body", "side": "+x" } ] }
+```
+
+| `kind` | Fields | Decides |
+| --- | --- | --- |
+| `attach` | `side`, `offset` | Touches the target's face on `side` (`+x`, `-x`, `+y`, `-y`, `+z`, `-z`) and centres on the other two axes. |
+| `gap` | `side`, `offset` | Only the touching axis: `offset` metres from the face, negative sinks into the target. |
+| `flush` | `side`, `offset` | Puts its own face on `side` level with the same face of the target. |
+| `align` | `axis`, `at`, `offset` | Puts its `min`, `center` or `max` on that axis at the target's. |
+| `centered` | `axes` (default all three) | Centres on those axes. |
+
+Every relation takes `to` (a mesh node ID) and an optional `region`, a mesh tag: only the faces of the target that carry
+that tag count as its bounds, so a part can sit on the tagged top of a tank and not on its tallest point. A relation
+decides only its own axes and replaces the node's `translation` on them; the other axes keep the authored value.
+
+Limits: at most 8 relations per node and 256 nodes with relations. Targets and nodes must be mesh nodes. Two relations
+on one node cannot decide the same axis. Relations form a graph over parts and parents; a loop (a part waiting on its own
+child included) is rejected with the loop spelled out. Solving is deterministic: the same recipe gives the same
+translations, whatever the order of the nodes. A relation that cannot be satisfied, such as an unknown tag, rejects the
+whole edit and names the relation. `relations: []` in `set-node` removes them and keeps the part where it is. The
+exported recipe holds both the relations and the solved translations. Motion and physics move nodes after the solve and
+know nothing of relations. The code loads on demand (`relations`, see On-demand code).
+
## Transactions and ownership
`apply(operations, { expectedRevision })` requires the current revision and returns the new revision.
diff --git a/docs/parity.md b/docs/parity.md
index f54dd37f..fd7c7ae0 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -241,7 +241,7 @@ The goal also needs this work, and no page in the Blender manual covers it.
| Runtime speed | partial | `bench/runtime` compares 7 scenes, and three.js wins most of them. There is no culling, LOD selection or adaptive quality, and bakes run on the main thread. | #28, #37, #38, #74 |
| Agent measurement | partial | A task suite runs on one model and reads recipes only. | #29, #30, #31, #69 |
| Pull request checks | partial | The `Test` workflow reports a status and does not block a merge. | #32 |
-| Relations between parts | missing | The agent version of snapping. | #44 |
+| Relations between parts | partial | The agent version of snapping: node `relations` (`attach`, `gap`, `flush`, `align`, `centered`) over world bounds or a tagged region, solved again on every edit, cycles rejected. Tests in [part-relations](../tests/part-relations.test.js); suite tasks `kettle-resize` and `kettle-resize-plain`. No snapping to edges or vertices, no relation on the part's own tagged region. | #44 |
| Imported mesh editing | missing | Imported assets accept poses and transforms. Their topology is fixed. | #48 |
| Rendering backend | missing | WebGL2 only. WebGPU is not evaluated. | #56 |
| Terrain and navigation | partial | Terrain with 4 splat layers and no holes. There is no navmesh. | #64 |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index d6c5959a..ce1369c4 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -26,7 +26,19 @@ const skinSpec = z.strictObject({
maxInfluences: z.number().int().min(1).max(4).optional().describe('Bones that move one vertex. Defaults to 4.'),
maxDistance: positive.optional().describe('Metres from the nearest bone beyond which a vertex counts as unweighted in scene_inspect rig. Defaults to a quarter of the rig size.'),
}).describe('Bind this mesh node to an armature with automatic weights: each vertex follows its nearest bones, by distance to the bone segments. Needs the armature at rest where the mesh is.');
+const relationSpec = z.strictObject({
+ kind: z.enum(['attach', 'flush', 'align', 'centered', 'gap']),
+ to: identifier.describe('Mesh node to place against.'),
+ region: z.string().min(1).max(128).optional().describe('A mesh tag: use only those faces of the target.'),
+ side: z.enum(['+x', '-x', '+y', '-y', '+z', '-z']).optional(),
+ axis: z.enum(['x', 'y', 'z']).optional(),
+ at: z.enum(['min', 'center', 'max']).optional(),
+ axes: z.array(z.enum(['x', 'y', 'z'])).max(3).optional(),
+ offset: z.number().optional().describe('Metres; for attach and gap the distance from the face, negative sinks in.'),
+}).meta({ id: 'Relation' });
+const relationList = z.array(relationSpec).max(8).describe('Place this mesh node from other nodes in world space, solved again after each edit. attach and gap take side (target face): attach touches it and centres on the other axes, gap touches on that axis only. flush takes side: same face level. align takes axis and at. centered takes axes. One relation per axis, no loops, overrides translation on its axes. [] removes them.').meta({ id: 'Relations' });
const nodeFields = {
+ relations: relationList.optional(),
skin: skinSpec.optional(),
label: z.string().max(256).optional().describe('Human-readable label. Identity remains the node ID.'),
parent: identifier.nullable().optional().describe('Parent node ID, or null for a root. Local transforms stay unchanged.'),
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index a8738552..38555aca 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -37,6 +37,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.
- Polygon modeling by an agent (extrude, inset, loop cut, bevel, booleans, mirror, array, solidify) uses the recipe `mesh` geometry and the MCP tools `mesh_inspect`, `mesh_edit` and `mesh_stack`. Read [mesh-modeling.md](references/mesh-modeling.md) before the first edit; check that the checkout's `docs/mesh.md` exists, since it is unreleased after npm 0.10.0.
+- Parts that sit against each other (a handle on a body, a lid on a tank, legs under a top) use the node `relations` field: `attach`, `gap`, `flush`, `align` or `centered` against another mesh node, optionally a tagged `region` of it. They are solved again after every edit, so resize the body with one `set-node` instead of recomputing each part's translation. One relation per axis, no loops. See "Relations between parts" in the checkout's `docs/agent-scene.md`.
- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`. Your own look (bricks from noise and a ramp, stripes, a pattern that follows `uv_unwrap`) is `pattern: { type: "graph", graph, mapping: "uv" }`: a bounded JSON node graph baked to textures, never shader text; see "Material graphs" there.
- Glass, water, gems, car paint and cloth in a recipe use the material layer fields `transmission` (with `thickness` and `ior`), `clearcoat`, `sheenColor` and `specular`. A transmissive material needs a nonzero `thickness` to bend the view behind it, and does not show blended surfaces. Ranges and limits are in "Material layers" in the checkout's `docs/material-maps.md`.
- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `createAssetPose` from `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.
diff --git a/src/agent-mesh-engine.js b/src/agent-mesh-engine.js
index 04bb728e..9c7deee0 100644
--- a/src/agent-mesh-engine.js
+++ b/src/agent-mesh-engine.js
@@ -1,5 +1,5 @@
// Everything the agent scene needs for mesh geometry, behind one on-demand import (see agent-scene-modules.js).
-export { meshReport, generateMeshGeometry } from './agent-mesh.js';
+export { meshReport, generateMeshGeometry, taggedFacePositions } from './agent-mesh.js';
export { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';
export { generateMeshLods, generateGeometryLods, generateAssetLods } from './mesh-lod.js';
export { expandInstancedNodes } from './mesh-instances.js';
diff --git a/src/agent-mesh.js b/src/agent-mesh.js
index d10ee6bd..183d290b 100644
--- a/src/agent-mesh.js
+++ b/src/agent-mesh.js
@@ -1,4 +1,5 @@
import { meshFromGeometry } from './mesh-convert.js';
+import { facesWithTag } from './mesh-data.js';
import { lintMesh } from './mesh-lint.js';
import { applyMeshEdits, evaluateMeshStack } from './mesh-recipe.js';
import { extractRender } from './mesh-render.js';
@@ -104,6 +105,29 @@ export function generateMeshGeometry(baseGeometry, edits, {
return geometry;
}
+/**
+ * Local-space positions of the faces that carry a mesh tag, shaped like geometry so bounds code can read them. Throws a
+ * message naming the next step when the part is a plain shape, or the tag is unknown or on no faces.
+ */
+export function taggedFacePositions(geometry, tag) {
+ const polygon = polygonMeshes.get(geometry);
+ if (!polygon) {
+ throw new RangeError('this part is a plain shape with no tagged faces. Use a mesh geometry and tag faces with a mesh_edit tag op, or drop region.');
+ }
+ const { mesh } = polygon;
+ const positions = [];
+ for (const face of facesWithTag(mesh, tag)) {
+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {
+ const vertex = mesh.cornerVertices[corner];
+ positions.push(mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]);
+ }
+ }
+ if (positions.length === 0) {
+ throw new RangeError(`tag ${tag} is on no faces. Tag some faces, or use another region.`);
+ }
+ return { positions: Float32Array.from(positions) };
+}
+
function faceSizeHistogram(mesh) {
const histogram = { triangles: 0, quads: 0, ngons: 0 };
for (let face = 0; face < mesh.faceCount; face++) {
diff --git a/src/agent-relations.js b/src/agent-relations.js
new file mode 100644
index 00000000..1a44c7b1
--- /dev/null
+++ b/src/agent-relations.js
@@ -0,0 +1,301 @@
+import { mat4, vec3 } from 'gl-matrix';
+
+// Relations place a part against another part's bounds, so a resized body keeps its handle where it belongs.
+// A node lists relations; each one fixes the node's world bounds on one or more axes from the bounds of another
+// mesh node (or from the faces that carry one of its tags). Relations are solved after geometry exists, in
+// dependency order, and again on every edit. The same recipe always solves to the same translations.
+
+export const RELATION_KINDS = Object.freeze(['attach', 'flush', 'align', 'centered', 'gap']);
+export const RELATION_SIDES = Object.freeze(['+x', '-x', '+y', '-y', '+z', '-z']);
+export const RELATION_LIMITS = Object.freeze({ maxPerNode: 8, maxNodes: 256, maxOffset: 1e6 });
+
+const AXES = Object.freeze(['x', 'y', 'z']);
+const ANCHORS = Object.freeze(['min', 'center', 'max']);
+const KIND_FIELDS = Object.freeze({
+ attach: ['side', 'offset'],
+ gap: ['side', 'offset'],
+ flush: ['side', 'offset'],
+ align: ['axis', 'at', 'offset'],
+ centered: ['axes'],
+});
+
+function axisIndex(axis) {
+ return AXES.indexOf(axis);
+}
+
+function sideAxis(side) {
+ return axisIndex(side[1]);
+}
+
+function describe(nodeId, index, relation) {
+ return `Relation ${index} of node ${JSON.stringify(nodeId.slice(0, 48))} (${relation.kind} to ${JSON.stringify(String(relation.to).slice(0, 48))})`;
+}
+
+function normalizeRelation(node, index, relation) {
+ if (!relation || typeof relation !== 'object' || Array.isArray(relation)) {
+ throw new TypeError(`Relation ${index} of node ${node.id} must be an object such as { "kind": "attach", "to": "body", "side": "+x" }.`);
+ }
+ if (!RELATION_KINDS.includes(relation.kind)) {
+ throw new TypeError(`Relation ${index} of node ${node.id} has kind ${JSON.stringify(String(relation.kind).slice(0, 48))}. Use one of ${RELATION_KINDS.join(', ')}.`);
+ }
+ const allowed = ['kind', 'to', 'region', ...(KIND_FIELDS[relation.kind] ?? [])];
+ for (const key of Object.keys(relation)) {
+ if (!allowed.includes(key)) {
+ throw new TypeError(`${describe(node.id, index, relation)} has unknown field ${JSON.stringify(key.slice(0, 48))}. A ${relation.kind} relation takes: ${allowed.join(', ')}.`);
+ }
+ }
+ if (typeof relation.to !== 'string' || !relation.to) {
+ throw new TypeError(`${describe(node.id, index, relation)} needs "to", the ID of the part it is placed against.`);
+ }
+ if (relation.region !== undefined && (typeof relation.region !== 'string' || !relation.region || relation.region.length > 128)) {
+ throw new TypeError(`${describe(node.id, index, relation)} region must be a mesh tag name of at most 128 characters.`);
+ }
+ const offset = relation.offset ?? 0;
+ if (!Number.isFinite(offset) || Math.abs(offset) > RELATION_LIMITS.maxOffset) {
+ throw new RangeError(`${describe(node.id, index, relation)} offset must be a finite number of metres within +-${RELATION_LIMITS.maxOffset}.`);
+ }
+ const result = { kind: relation.kind, to: relation.to };
+ if (relation.region !== undefined) {
+ result.region = relation.region;
+ }
+ if (offset !== 0) {
+ result.offset = offset;
+ }
+ if (KIND_FIELDS[relation.kind].includes('side')) {
+ if (!RELATION_SIDES.includes(relation.side)) {
+ throw new TypeError(`${describe(node.id, index, relation)} needs side, one of ${RELATION_SIDES.join(', ')}: the face of "${relation.to}" it sits against.`);
+ }
+ result.side = relation.side;
+ }
+ if (relation.kind === 'align') {
+ if (!AXES.includes(relation.axis) || !ANCHORS.includes(relation.at)) {
+ throw new TypeError(`${describe(node.id, index, relation)} needs axis (x, y or z) and at (${ANCHORS.join(', ')}).`);
+ }
+ result.axis = relation.axis;
+ result.at = relation.at;
+ }
+ if (relation.kind === 'centered') {
+ const axes = relation.axes ?? AXES;
+ if (!Array.isArray(axes) || axes.length === 0 || axes.length > 3 || axes.some(axis => !AXES.includes(axis)) || new Set(axes).size !== axes.length) {
+ throw new TypeError(`${describe(node.id, index, relation)} axes must list each of x, y, z at most once, or be left out for all three.`);
+ }
+ result.axes = [...axes].sort();
+ }
+ return result;
+}
+
+/** The world axes a normalized relation decides: indices 0 to 2. */
+export function relationAxes(relation) {
+ switch (relation.kind) {
+ case 'attach':
+ return [0, 1, 2];
+ case 'gap':
+ case 'flush':
+ return [sideAxis(relation.side)];
+ case 'align':
+ return [axisIndex(relation.axis)];
+ default:
+ return relation.axes.map(axisIndex);
+ }
+}
+
+// Depth-first walk over the things a node's world position waits for: its relation targets and its parent chain.
+function dependencyOrder(nodesById, relatedIds) {
+ const order = [];
+ const finished = new Set();
+ const path = [];
+ function visit(nodeId) {
+ if (finished.has(nodeId)) {
+ return;
+ }
+ const position = path.indexOf(nodeId);
+ if (position !== -1) {
+ const cycle = [...path.slice(position), nodeId].map(id => JSON.stringify(id.slice(0, 48))).join(' -> ');
+ throw new RangeError(`Relations form a cycle: ${cycle} (each part waits for the next, parents included). Remove one relation in the loop with set-node relations, or place one part with translation instead.`);
+ }
+ path.push(nodeId);
+ const node = nodesById.get(nodeId);
+ if (node.parent !== null && nodesById.has(node.parent)) {
+ visit(node.parent);
+ }
+ for (const relation of node.relations ?? []) {
+ visit(relation.to);
+ }
+ path.pop();
+ finished.add(nodeId);
+ if (relatedIds.has(nodeId)) {
+ order.push(nodeId);
+ }
+ }
+ for (const nodeId of relatedIds) {
+ visit(nodeId);
+ }
+ return order;
+}
+
+function indexNodes(nodes) {
+ return new Map(nodes.map(node => [node.id, node]));
+}
+
+/**
+ * Validate the relations of a list of normalized nodes and return the nodes with each relations list normalized
+ * (an empty list is dropped). Throws on unknown fields, unknown or non-mesh targets, two relations deciding the same
+ * axis, and cycles. Every message names what to change.
+ */
+export function normalizeRelations(nodes) {
+ const related = nodes.filter(node => node.relations !== undefined);
+ if (related.length === 0) {
+ return nodes;
+ }
+ const nodesById = indexNodes(nodes);
+ const result = nodes.map(node => ({ ...node }));
+ const resultById = indexNodes(result);
+ let relatedCount = 0;
+ for (const node of related) {
+ if (!Array.isArray(node.relations) || node.relations.length > RELATION_LIMITS.maxPerNode) {
+ throw new RangeError(`Node ${node.id} relations must be an array of at most ${RELATION_LIMITS.maxPerNode} entries. Merge or drop relations.`);
+ }
+ const normalized = node.relations.map((relation, index) => normalizeRelation(node, index, relation));
+ const target = resultById.get(node.id);
+ if (normalized.length === 0) {
+ delete target.relations;
+ continue;
+ }
+ relatedCount++;
+ if (relatedCount > RELATION_LIMITS.maxNodes) {
+ throw new RangeError(`At most ${RELATION_LIMITS.maxNodes} nodes can carry relations. Group repeated parts or place the rest with translation.`);
+ }
+ if (node.geometry === undefined) {
+ throw new TypeError(`Node ${node.id} is a group, and relations place mesh nodes. Put the relations on a mesh node inside the group.`);
+ }
+ const decided = new Map();
+ normalized.forEach((relation, index) => {
+ const referenced = nodesById.get(relation.to);
+ if (relation.to === node.id) {
+ throw new RangeError(`${describe(node.id, index, relation)} points at its own node. Point "to" at another part.`);
+ }
+ if (!referenced) {
+ throw new RangeError(`${describe(node.id, index, relation)}: no node has that ID. Use a node ID from scene_inspect, or drop the relation.`);
+ }
+ if (referenced.geometry === undefined) {
+ throw new RangeError(`${describe(node.id, index, relation)}: the target is a group with no geometry. Point "to" at a mesh node.`);
+ }
+ for (const axis of relationAxes(relation)) {
+ if (decided.has(axis)) {
+ throw new RangeError(`${describe(node.id, index, relation)} decides the ${AXES[axis]} axis, which relation ${decided.get(axis)} already decides. Keep one relation per axis.`);
+ }
+ decided.set(axis, index);
+ }
+ });
+ target.relations = normalized;
+ }
+ dependencyOrder(resultById, new Set(related.filter(node => resultById.get(node.id).relations).map(node => node.id)));
+ return result;
+}
+
+function worldMatrixOf(nodeId, nodesById, cache) {
+ const cached = cache.get(nodeId);
+ if (cached) {
+ return cached;
+ }
+ const node = nodesById.get(nodeId);
+ const local = mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale);
+ const world = node.parent !== null && nodesById.has(node.parent)
+ ? mat4.multiply(local, worldMatrixOf(node.parent, nodesById, cache), local)
+ : local;
+ cache.set(nodeId, world);
+ return world;
+}
+
+function targetValue(bounds, axis, anchor) {
+ if (anchor === 'min') {
+ return bounds.min[axis];
+ }
+ if (anchor === 'max') {
+ return bounds.max[axis];
+ }
+ return (bounds.min[axis] + bounds.max[axis]) / 2;
+}
+
+// Each constraint says: this part's `anchor` on `axis` should sit at `value`.
+function constraintsFor(relation, selfBounds, targetBounds) {
+ const offset = relation.offset ?? 0;
+ const wanted = [];
+ const sideAnchors = side => {
+ const axis = sideAxis(side);
+ const outward = side[0] === '+';
+ return { axis, outward };
+ };
+ if (relation.kind === 'gap' || relation.kind === 'attach') {
+ const { axis, outward } = sideAnchors(relation.side);
+ wanted.push(outward
+ ? { axis, anchor: 'min', value: targetBounds.max[axis] + offset }
+ : { axis, anchor: 'max', value: targetBounds.min[axis] - offset });
+ }
+ if (relation.kind === 'attach') {
+ const { axis: sideAxisIndex } = sideAnchors(relation.side);
+ for (const axis of [0, 1, 2].filter(candidate => candidate !== sideAxisIndex)) {
+ wanted.push({ axis, anchor: 'center', value: targetValue(targetBounds, axis, 'center') });
+ }
+ }
+ if (relation.kind === 'flush') {
+ const { axis, outward } = sideAnchors(relation.side);
+ const anchor = outward ? 'max' : 'min';
+ wanted.push({ axis, anchor, value: targetValue(targetBounds, axis, anchor) + offset });
+ }
+ if (relation.kind === 'align') {
+ const axis = axisIndex(relation.axis);
+ wanted.push({ axis, anchor: relation.at, value: targetValue(targetBounds, axis, relation.at) + offset });
+ }
+ if (relation.kind === 'centered') {
+ for (const axis of relation.axes.map(axisIndex)) {
+ wanted.push({ axis, anchor: 'center', value: targetValue(targetBounds, axis, 'center') });
+ }
+ }
+ return wanted.map(constraint => ({ ...constraint, delta: constraint.value - targetValue(selfBounds, constraint.axis, constraint.anchor) }));
+}
+
+/**
+ * Solve every relation and return nodes whose translations satisfy them (unrelated nodes are returned as is).
+ * `worldBounds(node, worldMatrix, region)` returns the axis-aligned world bounds `{ min, max }` of a mesh node, or of
+ * the faces carrying the tag `region`, and throws a message that names the tag when it does not exist.
+ */
+export function solveRelations(nodes, worldBounds) {
+ const related = nodes.filter(node => node.relations?.length);
+ if (related.length === 0) {
+ return nodes;
+ }
+ const result = nodes.map(node => ({ ...node }));
+ const nodesById = indexNodes(result);
+ const cache = new Map();
+ for (const nodeId of dependencyOrder(nodesById, new Set(related.map(node => node.id)))) {
+ const node = nodesById.get(nodeId);
+ const delta = [0, 0, 0];
+ const selfBounds = worldBounds(node, worldMatrixOf(nodeId, nodesById, cache), undefined);
+ node.relations.forEach((relation, index) => {
+ const target = nodesById.get(relation.to);
+ let targetBounds;
+ try {
+ targetBounds = worldBounds(target, worldMatrixOf(target.id, nodesById, cache), relation.region);
+ } catch (error) {
+ throw new RangeError(`${describe(nodeId, index, relation)} cannot be satisfied: ${error.message}`);
+ }
+ for (const constraint of constraintsFor(relation, selfBounds, targetBounds)) {
+ delta[constraint.axis] = constraint.delta;
+ }
+ });
+ const parentWorld = node.parent !== null && nodesById.has(node.parent) ? worldMatrixOf(node.parent, nodesById, cache) : mat4.create();
+ const inverse = mat4.invert(mat4.create(), parentWorld);
+ if (!inverse) {
+ throw new RangeError(`Node ${nodeId} sits under a parent with a singular transform, so its relations cannot be solved. Fix the parent scale.`);
+ }
+ const local = vec3.transformMat4(vec3.create(), delta, inverse);
+ const origin = vec3.transformMat4(vec3.create(), [0, 0, 0], inverse);
+ node.translation = node.translation.map((value, axis) => value + local[axis] - origin[axis]);
+ if (!node.translation.every(Number.isFinite)) {
+ throw new RangeError(`Relations on node ${nodeId} produce a translation outside the number range. Reduce offsets or part sizes.`);
+ }
+ cache.clear();
+ }
+ return result;
+}
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 5358c49c..48fdeb8f 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -9,6 +9,7 @@ const MODULE_LOADERS = {
motion: () => import('./agent-motion.js'),
physics: () => import('./agent-physics.js'),
patterns: () => import('./material-patterns.js'),
+ relations: () => import('./agent-relations.js'),
};
const loadedModules = {};
@@ -23,6 +24,7 @@ const MODULE_MARKERS = {
motion: ['"motion":{'],
physics: ['"physics":{'],
patterns: ['"pattern"'],
+ relations: ['"relations":'],
};
/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 8bdb0199..0687bd95 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -19,7 +19,7 @@ export {
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
-const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin'];
+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations'];
const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
@@ -577,6 +577,9 @@ function normalizeRecipe(input, limits) {
});
recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);
addArmatures(recipe, limits);
+ if (recipe.nodes.some(node => node.relations !== undefined)) {
+ recipe.nodes = agentSceneModule('relations').normalizeRelations(recipe.nodes);
+ }
recipe.camera = cameraFrom(recipe.camera);
const look = {};
for (const field of ['environment', 'effects', 'shadow']) {
@@ -838,6 +841,13 @@ export function createAgentScene(input, inputLimits = {}) {
}
const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));
const localBounds = new Map([...geometryRecords.values()].map(record => [record.geometry, record.bounds]));
+ if (recipe.nodes.some(node => node.relations?.length)) {
+ recipe.nodes = agentSceneModule('relations').solveRelations(recipe.nodes, (node, worldMatrix, region) => {
+ const geometry = geometries.get(node.geometry);
+ const regionGeometry = region === undefined ? geometry : agentSceneModule('mesh').taggedFacePositions(geometry, region);
+ return boundsFor(regionGeometry, worldMatrix);
+ });
+ }
const graph = compile(recipe, geometries, localBounds, limits);
const skinBindings = bindSkins({ recipe, graph, geometryRecords, cache: skinCache });
const materialHandles = new Map();
diff --git a/tests/kettle-tasks.test.js b/tests/kettle-tasks.test.js
new file mode 100644
index 00000000..d4e6c4b1
--- /dev/null
+++ b/tests/kettle-tasks.test.js
@@ -0,0 +1,26 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { gradeRecipe } from '../bench/agent-modeling/check.mjs';
+import { taskById } from '../bench/agent-modeling/tasks.mjs';
+import { REFERENCES } from '../bench/agent-modeling/references.mjs';
+import { KETTLE_START, KETTLE_START_PLAIN } from '../bench/agent-modeling/kettle.mjs';
+
+const failedKinds = grade => grade.results.filter(result => !result.pass).map(result => result.label ?? result.kind);
+
+test('both kettle tasks accept their reference and reject a resized body whose parts were left behind', async () => {
+ for (const id of ['kettle-resize', 'kettle-resize-plain']) {
+ assert.equal((await gradeRecipe(taskById(id), REFERENCES[id])).pass, true, id);
+ }
+ const strandedParts = structuredClone(REFERENCES['kettle-resize-plain']);
+ strandedParts.nodes = strandedParts.nodes.map(node => (node.id === 'body' ? node : structuredClone(KETTLE_START_PLAIN.nodes.find(start => start.id === node.id))));
+ const failures = failedKinds(await gradeRecipe(taskById('kettle-resize-plain'), strandedParts));
+ assert.ok(failures.includes('size'));
+ assert.ok(failures.includes('touches'));
+});
+
+test('the unchanged kettle fails the resize task, and its relations recipe is the one the task starts from', async () => {
+ assert.ok(failedKinds(await gradeRecipe(taskById('kettle-resize'), KETTLE_START)).includes('size'));
+ assert.equal(taskById('kettle-resize').startRecipe, KETTLE_START);
+ assert.ok(KETTLE_START.nodes.some(node => node.relations));
+ assert.ok(!KETTLE_START_PLAIN.nodes.some(node => node.relations));
+});
diff --git a/tests/part-relations.test.js b/tests/part-relations.test.js
new file mode 100644
index 00000000..afbf993d
--- /dev/null
+++ b/tests/part-relations.test.js
@@ -0,0 +1,223 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+
+function recipeWith(nodes, geometries = []) {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'cube', type: 'box' }, ...geometries],
+ materials: [{ id: 'grey', color: [0.6, 0.6, 0.6] }],
+ nodes: nodes.map(node => ({ geometry: 'cube', material: 'grey', ...node })),
+ };
+}
+
+function worldBounds(scene, id) {
+ return scene.inspect({ ids: [id], includeBounds: true }).nodes[0].bounds;
+}
+
+function near(actual, expected, label) {
+ assert.ok(Math.abs(actual - expected) < 1e-5, `${label}: ${actual} is not ${expected}`);
+}
+
+function handleRecipe() {
+ return recipeWith([
+ { id: 'body', scale: [2, 1, 1] },
+ { id: 'handle', scale: [0.2, 0.2, 0.2], translation: [9, 9, 9], relations: [{ kind: 'attach', to: 'body', side: '+x' }] },
+ ]);
+}
+
+test('a resized body keeps its attached handle against it', () => {
+ const scene = createAgentScene(handleRecipe());
+ let body = worldBounds(scene, 'body');
+ let handle = worldBounds(scene, 'handle');
+ near(handle.min[0], body.max[0], 'handle touches the +x face');
+ near((handle.min[1] + handle.max[1]) / 2, 0, 'handle centred on y');
+ scene.apply([{ type: 'set-node', id: 'body', scale: [5, 3, 1], translation: [1, 2, 0] }], { expectedRevision: scene.revision });
+ body = worldBounds(scene, 'body');
+ handle = worldBounds(scene, 'handle');
+ near(handle.min[0], body.max[0], 'handle follows the new +x face');
+ near((handle.min[1] + handle.max[1]) / 2, 2, 'handle follows the new centre');
+});
+
+test('gap, flush, align and centered place parts on their own axes', () => {
+ const scene = createAgentScene(recipeWith([
+ { id: 'base', scale: [2, 1, 2] },
+ { id: 'lamp', scale: [0.5, 0.5, 0.5], relations: [
+ { kind: 'gap', to: 'base', side: '+y', offset: 0.25 },
+ { kind: 'align', to: 'base', axis: 'x', at: 'min', offset: 0.1 },
+ { kind: 'centered', to: 'base', axes: ['z'] },
+ ] },
+ { id: 'post', scale: [0.2, 3, 0.2], translation: [0, 0, 5], relations: [{ kind: 'flush', to: 'base', side: '-y' }] },
+ ]));
+ const base = worldBounds(scene, 'base');
+ const lamp = worldBounds(scene, 'lamp');
+ const post = worldBounds(scene, 'post');
+ near(lamp.min[1], base.max[1] + 0.25, 'gap above');
+ near(lamp.min[0], base.min[0] + 0.1, 'align min x');
+ near((lamp.min[2] + lamp.max[2]) / 2, 0, 'centred z');
+ near(post.min[1], base.min[1], 'flush bottoms');
+ near(post.min[2] + 0.1, 5, 'post keeps its own z');
+});
+
+test('relations under a rotated and scaled parent still solve in world space', () => {
+ const scene = createAgentScene(recipeWith([
+ { id: 'rig', rotation: [0, 0.7071068, 0, 0.7071068], scale: [2, 2, 2], translation: [1, 0, 0] },
+ { id: 'body', parent: 'rig' },
+ { id: 'knob', parent: 'rig', scale: [0.1, 0.1, 0.1], relations: [{ kind: 'attach', to: 'body', side: '+y' }] },
+ ]));
+ const body = worldBounds(scene, 'body');
+ const knob = worldBounds(scene, 'knob');
+ near(knob.min[1], body.max[1], 'knob sits on the top');
+ near((knob.min[0] + knob.max[0]) / 2, (body.min[0] + body.max[0]) / 2, 'centred x');
+});
+
+test('a chain of relations solves in dependency order whatever the node order', () => {
+ const scene = createAgentScene(recipeWith([
+ { id: 'c', scale: [0.2, 0.2, 0.2], relations: [{ kind: 'attach', to: 'b', side: '+x' }] },
+ { id: 'b', scale: [0.5, 0.5, 0.5], relations: [{ kind: 'attach', to: 'a', side: '+x' }] },
+ { id: 'a', scale: [1, 1, 1], translation: [3, 0, 0] },
+ ]));
+ near(worldBounds(scene, 'b').min[0], worldBounds(scene, 'a').max[0], 'b on a');
+ near(worldBounds(scene, 'c').min[0], worldBounds(scene, 'b').max[0], 'c on b');
+});
+
+test('a tagged region of the target is the reference, not the whole part', () => {
+ const body = { id: 'tank', type: 'mesh', base: { type: 'box' }, edits: [
+ { op: 'extrude_face_region', select: { normal: [0, 1, 0], maxAngle: 5 }, offset: 1 },
+ { op: 'tag', select: { normal: [0, 1, 0], maxAngle: 5 }, name: 'top' },
+ ] };
+ const scene = createAgentScene(recipeWith([
+ { id: 'tank', geometry: 'tank' },
+ { id: 'cap', scale: [0.2, 0.2, 0.2], relations: [{ kind: 'gap', to: 'tank', region: 'top', side: '+y' }] },
+ ], [body]));
+ near(worldBounds(scene, 'cap').min[1], worldBounds(scene, 'tank').max[1], 'cap rests on the tagged top');
+ const bad = recipeWith([
+ { id: 'tank', geometry: 'tank' },
+ { id: 'cap', relations: [{ kind: 'gap', to: 'tank', region: 'lid', side: '+y' }] },
+ ], [body]);
+ assert.throws(() => createAgentScene(bad), /cannot be satisfied.*Unknown tag lid.*Known tags: .*top/s);
+ const plain = recipeWith([{ id: 'a' }, { id: 'b', relations: [{ kind: 'gap', to: 'a', region: 'top', side: '+y' }] }]);
+ assert.throws(() => createAgentScene(plain), /plain shape.*tag faces with a mesh_edit tag op/s);
+});
+
+test('relations solve the same every time and again after an edit moves a referenced region', () => {
+ const first = createAgentScene(handleRecipe()).exportRecipe();
+ const second = createAgentScene(handleRecipe()).exportRecipe();
+ assert.deepEqual(first, second);
+ const scene = createAgentScene(handleRecipe());
+ const before = worldBounds(scene, 'handle');
+ scene.apply([{ type: 'set-node', id: 'body', translation: [0, 0, 4] }], { expectedRevision: scene.revision });
+ const after = worldBounds(scene, 'handle');
+ near(after.min[2] - before.min[2], 4, 'handle moved with the body');
+ assert.deepEqual(scene.exportRecipe().nodes.find(node => node.id === 'handle').relations, [{ kind: 'attach', to: 'body', side: '+x' }]);
+});
+
+test('set-node with an empty list removes relations and the part stays where it is', () => {
+ const scene = createAgentScene(handleRecipe());
+ const solved = worldBounds(scene, 'handle');
+ scene.apply([{ type: 'set-node', id: 'handle', relations: [] }, { type: 'set-node', id: 'body', translation: [0, 0, 4] }], { expectedRevision: scene.revision });
+ assert.deepEqual(worldBounds(scene, 'handle'), solved);
+ assert.equal(Object.hasOwn(scene.exportRecipe().nodes.find(node => node.id === 'handle'), 'relations'), false);
+});
+
+function rejects(nodes, pattern) {
+ assert.throws(() => createAgentScene(recipeWith(nodes)), pattern);
+}
+
+test('cycles, unknown parts and self references are rejected with the next action', () => {
+ rejects([
+ { id: 'a', relations: [{ kind: 'attach', to: 'b', side: '+x' }] },
+ { id: 'b', relations: [{ kind: 'attach', to: 'a', side: '+x' }] },
+ ], /cycle: "a" -> "b" -> "a".*Remove one relation/s);
+ rejects([
+ { id: 'a', relations: [{ kind: 'attach', to: 'ghost', side: '+x' }] },
+ ], /no node has that ID.*scene_inspect/s);
+ rejects([
+ { id: 'a', relations: [{ kind: 'centered', to: 'a' }] },
+ ], /its own node.*another part/s);
+ rejects([
+ { id: 'a', relations: [{ kind: 'attach', to: 'loop', side: '+x' }] },
+ { id: 'a2', relations: [{ kind: 'attach', to: 'a', side: '+x' }] },
+ { id: 'loop', parent: 'a2' },
+ ], /cycle/);
+});
+
+test('a part cannot be placed against its own child, which would move with it', () => {
+ rejects([
+ { id: 'parent', relations: [{ kind: 'attach', to: 'kid', side: '+x' }] },
+ { id: 'kid', parent: 'parent' },
+ ], /cycle.*parents included/s);
+});
+
+test('group nodes, group targets and two relations on one axis are rejected', () => {
+ const noGeometry = recipeWith([{ id: 'g' }, { id: 'a', relations: [{ kind: 'centered', to: 'g' }] }]);
+ noGeometry.nodes[0] = { id: 'g' };
+ assert.throws(() => createAgentScene(noGeometry), /group with no geometry.*mesh node/s);
+ noGeometry.nodes[0] = { id: 'g', geometry: 'cube', material: 'grey' };
+ noGeometry.nodes[1] = { id: 'a', relations: [{ kind: 'centered', to: 'g' }] };
+ assert.throws(() => createAgentScene(noGeometry), /group, and relations place mesh nodes/s);
+ rejects([
+ { id: 'a' },
+ { id: 'b', relations: [{ kind: 'gap', to: 'a', side: '+x' }, { kind: 'align', to: 'a', axis: 'x', at: 'min' }] },
+ ], /decides the x axis.*already decides.*one relation per axis/is);
+ rejects([
+ { id: 'a' },
+ { id: 'b', relations: [{ kind: 'attach', to: 'a', side: '+x' }, { kind: 'centered', to: 'a', axes: ['y'] }] },
+ ], /decides the y axis/);
+});
+
+test('hostile relation input is rejected without leaking or hanging', () => {
+ const attach = { kind: 'attach', to: 'a', side: '+x' };
+ const cases = [
+ [{ ...attach, kind: 'weld' }, /Use one of attach, flush, align, centered, gap/],
+ [{ ...attach, side: '+w' }, /needs side/],
+ [{ ...attach, offset: Infinity }, /Copy|finite|JSON/],
+ [{ ...attach, offset: 1e12 }, /finite number of metres/],
+ [{ ...attach, offset: '1' }, /finite number of metres/],
+ [{ ...attach, to: 7 }, /needs "to"/],
+ [{ ...attach, to: '' }, /needs "to"/],
+ [{ ...attach, region: 5 }, /region must be a mesh tag name/],
+ [{ ...attach, axis: 'x' }, /unknown field "axis".*takes: kind, to, region, side, offset/s],
+ [{ kind: 'align', to: 'a', axis: 'q', at: 'min' }, /needs axis/],
+ [{ kind: 'centered', to: 'a', axes: ['x', 'x'] }, /each of x, y, z at most once/],
+ [{ kind: 'centered', to: 'a', axes: [] }, /each of x, y, z at most once/],
+ [{ kind: 'centered', to: 'a', axes: 'x' }, /each of x, y, z at most once/],
+ [{ ...attach, to: 'x'.repeat(5000) }, /no node has that ID|maxRecipeBytes|IDs/],
+ [null, /must be an object/],
+ ['attach', /must be an object/],
+ [[attach], /must be an object/],
+ ];
+ for (const [relation, pattern] of cases) {
+ rejects([{ id: 'a' }, { id: 'b', relations: [relation] }], pattern);
+ }
+ rejects([{ id: 'a' }, { id: 'b', relations: 'attach' }], /array of at most 8/);
+ rejects([{ id: 'a' }, { id: 'b', relations: Array.from({ length: 9 }, () => attach) }], /at most 8/);
+ const polluted = JSON.parse('{"kind":"attach","to":"a","side":"+x","__proto__":{"kind":"gap"}}');
+ rejects([{ id: 'a' }, { id: 'b', relations: [polluted] }], /Invalid JSON key/);
+});
+
+test('relation nodes are bounded', () => {
+ const nodes = [{ id: 'anchor' }];
+ for (let index = 0; index < 257; index++) {
+ nodes.push({ id: `part${index}`, scale: [0.1, 0.1, 0.1], relations: [{ kind: 'attach', to: 'anchor', side: '+x' }] });
+ }
+ rejects(nodes, /At most 256 nodes can carry relations/);
+});
+
+test('a long chain of relations solves quickly', () => {
+ const nodes = [{ id: 'part0', scale: [0.1, 0.1, 0.1] }];
+ for (let index = 1; index < 200; index++) {
+ nodes.push({ id: `part${index}`, scale: [0.1, 0.1, 0.1], relations: [{ kind: 'attach', to: `part${index - 1}`, side: '+x' }] });
+ }
+ const started = performance.now();
+ const scene = createAgentScene(recipeWith(nodes.reverse()));
+ assert.ok(performance.now() - started < 3000);
+ near(worldBounds(scene, 'part199').min[0], worldBounds(scene, 'part198').max[0], 'end of the chain');
+});
+
+test('relations on a rejected edit leave the scene unchanged', () => {
+ const scene = createAgentScene(handleRecipe());
+ const revision = scene.revision;
+ assert.throws(() => scene.apply([{ type: 'set-node', id: 'body', relations: [{ kind: 'attach', to: 'handle', side: '+x' }] }], { expectedRevision: revision }), /cycle/);
+ assert.equal(scene.revision, revision);
+});