3D engine that AI agents drive
Add terrain holes and a recipe terrain geometry
Nguyen Xuan And7d6a90ad948
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 127b693d..b51863d1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add terrain holes and a recipe `terrain` geometry (part of issue #64; layers beyond four and the navmesh are not built). `createTerrain({ holes: [{ center: [x, z], radius }] })` leaves no surface where a cell centre is inside a circle, and `terrain.isHole(x, z)` answers for a point; without `holes` the seeded meshes are byte-identical (a digest test). A recipe geometry `{ type: "terrain", size, resolution, seed, amplitude, holes }` builds one seeded ground mesh with the same holes; it loads on demand through the new `terrain` module (core did not grow), the tool schema entry is one line with the fields in `scene_capabilities` `terrain`, and the schema total budget did not change (scene_create and scene_apply rose by a few hundred bytes, mesh_edit fell by the same amount). New suite task `terrain-hole-walk` (ground with a 3 m opening and a walker that has to go around it) with the checks `groundRelief` and `walkPath`. Measured: Haiku passed it 2 of 2 (9 and 6 tool calls, $0.29 in all) and both exported recipes used the `terrain` geometry; there was no control run without the feature, so this shows agents find it, not how many could do without.+- Make the path tracer about 2.8 times faster per thread and draw normal and metallic-roughness maps (part of issue #129; a 1080p still of the 181,708 triangle demo room at 64 samples still does not fit the 240 s job limit). Profiling the demo room showed the ray query dominating: 54 percent of the time sat in the generic BVH visitor, which called a closure per box and per triangle and kept distances in a boxed array. `createTracer` in `src/ray-query.js` now walks the BVH with typed stacks, a slab test on inverse directions and triangles packed in leaf order; pixels are bit-identical to before (checksum of a band unchanged) and it runs 1.2 times faster alone. The larger gain is shadow rays: the demo room has 11 light sources, and every bounce traced all of them. The first hit of a path still samples every light; later hits draw one at random and divide by its chance (and the environment multiple importance weights use that chance), which gives 23,300 paths a second per thread against 9,800, with the average moved by less than 1 percent in the demo room and 3 percent allowed by a test. Image jobs now use 8 workers, up from 4 (the machine limit). `normalMap` (with `normalScale`, tangent frame from the UVs as in the rasterizer) and `metallicRoughnessMap` (green scales roughness, blue scales metallic) are drawn on UV-mapped materials; on box-projected materials (`boxMapScale`) they are still ignored and `report.ignored` says so. The `entry:path-tracer` size budget goes from 12,900 to 13,800 bytes gzip for the maps, light selection and the packed ray query; `entry:core` did not change. Tests: maps tilt and mask the light, one light drawn at random keeps the average, and bands drawn in any order give the pixels of the whole image.- Move the anisotropy and iridescence shader code out of the core bundle (part of issue #51). It lives in the new `addons/material-layer-shaders` entry, which registers it on import; the renderer asks for it only when a part uses a layer, so a lit box no longer pays for it. A scene that uses a layer in code must import the entry first, or the renderer throws a message that names the import. Recipes load it through `loadAgentSceneModules`, the MCP server does so itself, and the glTF loader loads it for a file that uses either extension. The unused short overloads of `environmentLighting` are gone. Pictures are unchanged.diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjsindex b0bb8d3d..0edee96f 100644--- a/bench/agent-modeling/check.mjs+++ b/bench/agent-modeling/check.mjs@@ -44,6 +44,27 @@ function checkWalk(rig, check) {return { pass: problems.length === 0, detail: [...new Set(problems)].slice(0, 4).join('; ') || `${rig.samples.length} samples: feet alternate, knees forward, elbows back, parts keep their size` };}+const WALK_SAMPLES = 41;++// A walker leaves one point to reach another, stays on the ground surface and keeps clear of a round opening.+function checkWalkPath(check, measures) {+ const problems = [];+ const planarDistance = (position, target) => Math.hypot(position[0] - target[0], position[2] - target[1]);+ for (let sample = 0; sample < WALK_SAMPLES; sample++) {+ const time = check.duration * sample / (WALK_SAMPLES - 1);+ const position = measures.nodePosition(check.node, time);+ if (!position) return { pass: false, detail: `no drawn node ${check.node}` };+ if (sample === 0 && planarDistance(position, check.from) > 0.75) problems.push(`starts ${round(planarDistance(position, check.from))} m from the start point`);+ if (sample === WALK_SAMPLES - 1 && planarDistance(position, check.to) > 0.75) problems.push(`ends ${round(planarDistance(position, check.to))} m from the end point`);+ const fromOpening = planarDistance(position, check.avoid.center) - check.avoid.radius;+ if (fromOpening < check.margin) problems.push(`${round(fromOpening)} m from the opening edge at t=${round(time)}`);+ const groundHeight = measures.surfaceHeight(check.ground, position[0], position[2]);+ if (groundHeight === null) problems.push(`no ground under it at t=${round(time)}`);+ else if (Math.abs(position[1] - groundHeight) > check.heightTolerance) problems.push(`${round(position[1] - groundHeight)} m off the ground at t=${round(time)}`);+ }+ return { pass: problems.length === 0, detail: [...new Set(problems)].slice(0, 3).join('; ') || `${WALK_SAMPLES} samples around the opening, on the ground` };+}+function checkOne(check, measures) {switch (check.kind) {case 'lint':@@ -125,6 +146,14 @@ function checkOne(check, measures) {const distance = Math.hypot(...from.map((value, axis) => value - to[axis]));return { pass: Math.abs(distance - check.distance) <= 0.01, detail: `${round(distance)} m apart at t=${check.time}` };}+ case 'groundRelief': {+ const bounds = measures.nodeBounds(check.node);+ if (!bounds) return { pass: false, detail: `no drawn node ${check.node}` };+ const relief = bounds.max[1] - bounds.min[1];+ return { pass: relief >= check.min && relief <= check.max, detail: `${check.node} spans ${round(relief)} m in height` };+ }+ case 'walkPath':+ return checkWalkPath(check, measures);case 'bendsToward': {const root = measures.nodePosition(check.from, check.time);const middle = measures.nodePosition(check.node, check.time);diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjsindex aec44cb4..1a1c3e4d 100644--- a/bench/agent-modeling/measure.mjs+++ b/bench/agent-modeling/measure.mjs@@ -184,6 +184,21 @@ function countTips(geometries, bounds) {}/** Number of triangles a line along `axis` crosses at the given coordinates of the other two axes, in axis order. */+// Height of the surface under (x, z): the first triangle that covers the point from above, or null over a hole.+function surfaceHeightAt({ positions, indices }, pointX, pointZ) {+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ const [first, second, third] = [indices[triangle], indices[triangle + 1], indices[triangle + 2]].map(vertex => [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]]);+ const determinant = (second[2] - third[2]) * (first[0] - third[0]) + (third[0] - second[0]) * (first[2] - third[2]);+ if (determinant === 0) continue;+ const weightFirst = ((second[2] - third[2]) * (pointX - third[0]) + (third[0] - second[0]) * (pointZ - third[2])) / determinant;+ const weightSecond = ((third[2] - first[2]) * (pointX - third[0]) + (first[0] - third[0]) * (pointZ - third[2])) / determinant;+ const weightThird = 1 - weightFirst - weightSecond;+ if (weightFirst < -1e-9 || weightSecond < -1e-9 || weightThird < -1e-9) continue;+ return weightFirst * first[1] + weightSecond * second[1] + weightThird * third[1];+ }+ return null;+}+function lineHits(geometries, axis, point) {const axisIndex = { x: 0, y: 1, z: 2 }[axis];const [firstAxis, secondAxis] = [0, 1, 2].filter(candidate => candidate !== axisIndex);@@ -419,6 +434,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;},+ surfaceHeight(name, pointX, pointZ) {+ const part = scene.parts.find(candidate => candidate.name === name);+ return part ? surfaceHeightAt(worldGeometry(part), pointX, pointZ) : null;+ },nodeBounds(name) {const part = scene.parts.find(candidate => candidate.name === name);return part ? boundsOfPositions(worldGeometry(part).positions) : null;diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjsindex c25c2a35..fe21fa2b 100644--- a/bench/agent-modeling/references.mjs+++ b/bench/agent-modeling/references.mjs@@ -372,6 +372,25 @@ export const REFERENCES = {],),'rigged-walker': walkerRecipe(),+ 'terrain-hole-walk': {+ format: '67js.scene', schemaVersion: 1,+ geometries: [+ { id: 'hills', type: 'terrain', size: 40, resolution: 64, seed: 3, amplitude: 1, holes: [{ center: [0, 0], radius: 3 }] },+ { id: 'body', type: 'box', bevel: 0 },+ ],+ materials: [{ id: 'grass', color: [0.3, 0.55, 0.2] }, { id: 'coat', color: [0.8, 0.3, 0.2] }],+ nodes: [+ { id: 'ground', geometry: 'hills', material: 'grass' },+ { id: 'walker', geometry: 'body', material: 'coat', translation: [-15, 0.5, -15], scale: [0.4, 1, 0.4] },+ ],+ motion: {+ duration: 10,+ tracks: [{+ kind: 'node', id: 'walker', property: 'translation', interpolation: 'LINEAR',+ keyframes: [[0, [-15, 0.5, -15]], [3, [-6, 0.5, -6]], [5, [6, 0.5, -6]], [10, [15, 0.5, 15]]].map(([time, value]) => ({ time, value })),+ }],+ },+ },'pillar-court': scene([{ id: 'pillar', type: 'box', bevel: 0 }],[{diff --git a/bench/agent-modeling/results/2026-10-31-22-05-haiku-terrain-hole-walk.json b/bench/agent-modeling/results/2026-10-31-22-05-haiku-terrain-hole-walk.jsonnew file mode 100644index 00000000..18215a71--- /dev/null+++ b/bench/agent-modeling/results/2026-10-31-22-05-haiku-terrain-hole-walk.json@@ -0,0 +1,139 @@+{+ "run": "2026-10-31-22-05-haiku-terrain-hole-walk",+ "model": "claude-haiku-5-5",+ "date": "2026-10-31T22:08:49.063Z",+ "skill": false,+ "runsPerTask": 2,+ "passed": 2,+ "tasks": 2,+ "toolCalls": 15,+ "costUsd": 0.29,+ "byModel": {+ "claude-haiku-5-5": {+ "runs": 2,+ "passed": 2,+ "successRate": 1,+ "toolCalls": 15,+ "toolErrors": 0,+ "inputTokens": 1664671,+ "outputTokens": 13676,+ "costUsd": 0.29,+ "tasks": {+ "terrain-hole-walk": {+ "runs": 2,+ "passed": 2,+ "successRate": 1,+ "toolCalls": 15,+ "toolErrors": 0,+ "inputTokens": 1664671,+ "outputTokens": 13676,+ "costUsd": 0.29+ }+ }+ }+ },+ "records": [+ {+ "task": "terrain-hole-walk",+ "attempt": 1,+ "pass": true,+ "passed": 3,+ "total": 3,+ "failed": [],+ "model": "claude-haiku-5-5",+ "toolCalls": 9,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_capabilities": 1,+ "scene_create": 2,+ "scene_inspect": 2,+ "scene_dispose": 2,+ "scene_look": 1,+ "scene_export_recipe": 1+ },+ "features": {+ "geometryTypes": [+ "terrain",+ "box"+ ],+ "meshOperations": [],+ "motionIk": [],+ "motionTracks": 1+ },+ "look": {+ "silhouette": {+ "views": {+ "front": 0.5151,+ "side": 0.6154,+ "three-quarter": 0.9611+ },+ "mean": 0.6972+ },+ "images": [+ "artifacts/agent-modeling/2026-10-31-22-05-haiku-terrain-hole-walk/look/1/terrain-hole-walk-front.png",+ "artifacts/agent-modeling/2026-10-31-22-05-haiku-terrain-hole-walk/look/1/terrain-hole-walk-side.png",+ "artifacts/agent-modeling/2026-10-31-22-05-haiku-terrain-hole-walk/look/1/terrain-hole-walk-three-quarter.png"+ ]+ },+ "turns": 11,+ "costUsd": 0.14956208000000001,+ "inputTokens": 840843,+ "outputTokens": 7097,+ "wallSeconds": 112,+ "exitCode": 0,+ "stopped": "success"+ },+ {+ "task": "terrain-hole-walk",+ "attempt": 2,+ "pass": true,+ "passed": 3,+ "total": 3,+ "failed": [],+ "model": "claude-haiku-5-5",+ "toolCalls": 6,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_capabilities": 1,+ "scene_create": 1,+ "scene_inspect": 1,+ "scene_look": 1,+ "scene_export_recipe": 1,+ "scene_dispose": 1+ },+ "features": {+ "geometryTypes": [+ "terrain",+ "box"+ ],+ "meshOperations": [],+ "motionIk": [],+ "motionTracks": 1+ },+ "look": {+ "silhouette": {+ "views": {+ "front": 0.5091,+ "side": 0.6258,+ "three-quarter": 0.9611+ },+ "mean": 0.6987+ },+ "images": [+ "artifacts/agent-modeling/2026-10-31-22-05-haiku-terrain-hole-walk/look/2/terrain-hole-walk-front.png",+ "artifacts/agent-modeling/2026-10-31-22-05-haiku-terrain-hole-walk/look/2/terrain-hole-walk-side.png",+ "artifacts/agent-modeling/2026-10-31-22-05-haiku-terrain-hole-walk/look/2/terrain-hole-walk-three-quarter.png"+ ]+ },+ "turns": 8,+ "costUsd": 0.14473128,+ "inputTokens": 823828,+ "outputTokens": 6579,+ "wallSeconds": 57,+ "exitCode": 0,+ "stopped": "success"+ }+ ]+}diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjsindex ae966b53..05b8535a 100644--- a/bench/agent-modeling/tasks.mjs+++ b/bench/agent-modeling/tasks.mjs@@ -4,6 +4,7 @@import { REFERENCES } from './references.mjs';import { KETTLE_START, KETTLE_START_PLAIN } from './kettle.mjs';import { DESK_START, DESK_START_PLAIN, DESK_CHECKS } from './desk.mjs';+import { TERRAIN_TASKS } from './terrain.mjs';export const PROMPT_PREAMBLE = `You are modeling with the 67js 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@@ -534,6 +535,7 @@ scene. When it is finished, call scene_export_recipe once: the exported recipe i],},...LONG_TASKS,+ ...TERRAIN_TASKS,];/** The task text an agent receives, with the starting recipe appended when the task changes an existing scene. */diff --git a/bench/agent-modeling/terrain.mjs b/bench/agent-modeling/terrain.mjsnew file mode 100644index 00000000..d3cf6b63--- /dev/null+++ b/bench/agent-modeling/terrain.mjs@@ -0,0 +1,26 @@+// The terrain-hole-walk task: rolling ground with a round opening cut through it, and a walker that has to go around+// the opening. Without a ground with holes the agent has to cut a hole into hand-made hills, which the mesh tools can+// do only by deleting faces; the exported recipe shows which way it went (recipeFeatures.geometryTypes).++const GROUND_SIZE = 40;+const OPENING_CENTER = [0, 0];+const OPENING_RADIUS = 3;+const WALK_FROM = [-15, -15];+const WALK_TO = [15, 15];+const WALK_SECONDS = 10;++export const TERRAIN_TASKS = [+ {+ id: 'terrain-hole-walk',+ prompt: `You are working with the 67js MCP tools. Units are metres and Y is up. Build a stretch of rolling ground ${GROUND_SIZE} m by ${GROUND_SIZE} m, centred on X = 0 and Z = 0, as a node named ground:+gentle hills whose highest and lowest points differ by about 1.2 m. A round opening of radius ${OPENING_RADIUS} m is cut clean through+the ground, centred on X = 0, Z = 0, like a cave mouth, with no surface left inside it. Add a node named walker (a small body that is itself drawn, say a box 0.4 m by 1 m by 0.4 m) that walks across the ground from [X = ${WALK_FROM[0]}, Z = ${WALK_FROM[1]}] to [X = ${WALK_TO[0]}, Z = ${WALK_TO[1]}] over a ${WALK_SECONDS} second motion that+starts at time 0. Keep the walker's node position within 1.5 m of the ground surface height and at least 0.3 m outside the opening's edge for the whole walk, so it goes around the opening instead of falling in. When it is finished, call scene_export_recipe once: the exported recipe is what gets graded.`,+ ownPreamble: true,+ checks: [+ { kind: 'groundRelief', node: 'ground', min: 0.6, max: 2.2 },+ { kind: 'through', axis: 'y', open: [[0.13, 0.07], [2.5, 0.11], [0.09, -2.5], [-1.8, 1.8]], solid: [[3.6, 0.13], [0.13, 3.6], [-3.6, 0.13], [10.13, -10.07], [-12.07, 12.11], [15.07, 5.11]] },+ { kind: 'walkPath', node: 'walker', ground: 'ground', from: WALK_FROM, to: WALK_TO, duration: WALK_SECONDS, avoid: { center: OPENING_CENTER, radius: OPENING_RADIUS }, margin: 0.3, heightTolerance: 1.5 },+ ],+ },+];diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex e04b838f..843f3558 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -26,14 +26,14 @@"entry:skeleton-pose": 19200,"entry:vehicle": 14700,"entry:vegetation": 17900,- "entry:terrain": 3100,+ "entry:terrain": 3330,"entry:grass": 4400,"entry:clutter": 5300,"entry:light-bake": 25400,"entry:path-tracer": 13800,"entry:texture-set": 900,"entry:agent-scene": 65300,- "entry:agent-scene+lazy": 217300,+ "entry:agent-scene+lazy": 217500,"entry:agent-asset": 96700,"entry:agent-asset+lazy": 228400,"entry:hdri": 3300,diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex 361284cd..376ca431 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -2,15 +2,15 @@"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); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168)","schemaTotalBytes": 190830,"schemaToolBytes": {- "scene_create": 62680,- "scene_apply": 44860,- "mesh_edit": 34300,+ "scene_create": 62930,+ "scene_apply": 45020,+ "mesh_edit": 33230,"scene_create_asset": 19310,"mesh_stack": 11690},"schemaOtherToolBytes": 4000,"resultBytes": {- "scene_capabilities": 12230,+ "scene_capabilities": 12430,"scene_create": 1400,"scene_inspect": 1400,"mesh_inspect": 1200,diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 0e724b60..68db6046 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`, `tube` and `curve` geometry, `text` geometry with its font, material `pattern`, `motion` and node `relations` load on demand, so a recipe of+Mesh editing, `lathe`, `extrude`, `tube` and `curve` geometry, `text` geometry with its font, `terrain` geometry, material `pattern`, `motion` and node `relations` load on demand, so a recipe ofprimitives 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.@@ -90,6 +90,9 @@ The generators also enforce their existing numeric and modeling constraints.| `tube` | `path`, `radius`, `segments`, `radialSegments`, `closed` | Required XYZ path, `0.1`, `64`, `12`, `false` || `curve` | `points`, `closed`, `radius`, `taper`, `profile`, `resolution`, `radialSegments` | Required points, `false`, `0.05`, none, round, `12`, `8` || `text` | `text`, `size`, `depth`, `font`, `align`, `curveSegments` | Required string, `1`, `0.2`, `default`, `left`, `4` |+| `terrain` | `size`, `resolution`, `seed`, `amplitude`, `holes` | `40` m, `64` cells, `1`, `1` m, none |++`terrain` is one seeded ground mesh from `-size / 2` to `size / 2` on X and Z with hills about y = 0 and up to 16 round `holes` (`{ center: [x, z], radius }`) that leave no surface; it loads on demand. Details are in `scene_capabilities` under `terrain`.`curve` and `text` are described in full by `scene_capabilities` under `curveText.details`; see [modeling.md](modeling.md).diff --git a/docs/parity.md b/docs/parity.mdindex 06ffb5df..87af8850 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -246,6 +246,6 @@ The goal also needs this work, and no page in the Blender manual covers it.| 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 `desk-resize` with plain twins (no gain in calls measured on Sonnet). No snapping to edges or vertices, no relation on the part's own tagged region. | #44 || Imported mesh editing | partial | `mesh_edit` takes an imported part ID. Skin weights, morph deltas and colours of new vertices come from the nearest original surface point, missing UVs from the nearest island; an edit that reaches too far on a skinned or morphed part is rejected. Not here: merging several parts into one mesh, tags from several material groups. Evidence: tests/agent-asset-mesh.test.js, scripts/smoke-imported-topology.mjs. | #48 || Rendering backend | missing | WebGL2 only. WebGPU was measured with three.js as a proxy and was slower on the RTX 3060 and on SwiftShader; decision: wait. See [webgpu-decision](webgpu-decision.md). | #56 |-| Terrain and navigation | partial | Terrain with 4 splat layers and no holes. There is no navmesh. | #64 |+| Terrain and navigation | partial | Terrain has round holes (`addons/terrain` `holes`, recipe geometry `terrain`), still with 4 splat layers. There is no navmesh. Evidence: tests/terrain-holes.test.js, suite task terrain-hole-walk. | #64 || Tool cost and errors | partial | Lint and errors exist. No budget limits schema size, and not every error is checked. | #65, #66 || Branches and labelled images | partial | `scene_apply` `branch` forks a variant over a deduplicated snapshot store (8 branches, scene and revision untouched), `scene_review` shots take a `branch`, `scene_restore` `branch` keeps one. `labels: true` on `scene_look` and `scene_review` prints part names, tags and lint problems and returns them with pixel positions. Procedural scenes only; no suite task yet measures calls. | #67 |diff --git a/docs/terrain.md b/docs/terrain.mdindex cea24596..29f35717 100644--- a/docs/terrain.md+++ b/docs/terrain.md@@ -84,6 +84,12 @@ Memory: three `TEXTURE_2D_ARRAY`s on units 11 to 13 (sRGB colour, normal, roughn- `update(eye)` picks a level per chunk from its distance (`lodDistance`, default 1.6 chunk sizes, doubling per level) and returns the parts whose geometry changed. Edges shared with a coarser neighbour are snapped onto the neighbour's edge, so there are no cracks and no skirts.- UVs are world metres `(x, z)`. Vertex normals are smooth and shared across chunk borders.+## Holes++`createTerrain({ holes: [{ center: [x, z], radius }] })` (up to 64 circles, radius in metres) leaves no surface where a cell centre falls inside a circle, so a cave mouth or a shaft opens through the ground. `terrain.isHole(x, z)` tells whether a point is inside one. `heightAt` and `normalAt` ignore holes and still return the surface that would be there, so check `isHole` before standing something on it. A coarser level of detail cuts a coarser hole (its cells are bigger), so give a hole a radius of a few finest cells at least. A hole that covers a whole chunk gives that chunk empty geometry. Without `holes` the meshes are byte-identical to before (a test keeps a digest).++In a recipe, the same ground is the `terrain` geometry (`size`, `resolution`, `seed`, `amplitude`, `holes`): see [agent-scene](agent-scene.md).+## MeasuredWindows, RTX 3060, headless Chrome, 1600x900, 4x MSAA, HDRI, shadows, bloom, 600 m terrain with 10x10 chunks at resolution 32 and about 1,000 to 1,750 trees:@@ -97,7 +103,8 @@ Splat textures take 68 MiB of 74 MiB texture memory at 1K per layer.## Limits-- Up to four layers; one splat material per draw (chunks share one).+- Up to four layers; one splat material per draw (chunks share one). More layers need a shader change and are not built.+- No navmesh or path query yet.- Overhangs are not represented: the terrain is a heightfield.- Changing `layers` or `splat` after the renderer exists needs a new renderer.- The weight texture follows its descriptor's filtering (mipmapped by default); 1024 square over 600 m gives 0.6 m texels.diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 1ee77b41..3c9f458c 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -219,6 +219,7 @@ function curveAndTextGeometries(id) {return [z.strictObject({ ...id, type: z.literal('curve'), points: z.array(z.unknown()).max(1024), closed: looseField, radius: looseField, taper: looseField, profile: looseField, resolution: looseField, radialSegments: looseField }).describe('Bezier sweep; see scene_capabilities curveText.'),z.strictObject({ ...id, type: z.literal('text'), text: z.string().max(256), size: looseField, depth: looseField, font: looseField, align: looseField, curveSegments: looseField }).describe('3D text; see scene_capabilities curveText.'),+ z.strictObject({ ...id, type: z.literal('terrain'), size: looseField, resolution: looseField, seed: looseField, amplitude: looseField, holes: z.array(z.unknown()).max(16).optional() }).describe('Hills with round holes; see scene_capabilities terrain.'),];}function primitiveGeometries(identified) {diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 22a5f517..49b7e308 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -38,6 +38,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.- Signs, labels and piping use recipe geometry `text` (bundled DejaVu Sans, printable ASCII; faces +Z, baseline on y=0, size is the em height) and `curve` (cubic Bezier points with optional absolute handles, `radius`, `taper`, `profile`). Their fields come from `scene_capabilities` `curveText.details`, not the tool schema; the MCP takes no font file or URL. Give a sign a board box a little deeper than the text `depth`, and keep text under about 40 characters at `curveSegments: 4`. See "Curve" and "Text" in the checkout's `docs/modeling.md`.+- Rolling ground with a cut-out opening (a cave mouth, a shaft) uses recipe geometry `terrain` with `holes: [{ center: [x, z], radius }]`; `scene_capabilities` `terrain` lists the fields. It is one mesh, so splat layers and a path query are not part of it (the `addons/terrain` library has `holes` too).- 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. Fields are in `scene_capabilities` `relations`; 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.diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 189e4586..d6a7e5fc 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -120,7 +120,8 @@ export const MESH_MODIFIER_NOTES = Object.freeze({export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'mesh']),+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'terrain', 'mesh']),+ terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),meshModifiers: MESH_MODIFIER_NOTES,diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex 02aa5c51..63c6bac1 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -1,5 +1,5 @@// Code that most recipes never run loads on demand, so the agent scene entry stays small. A recipe that uses mesh-// editing, procedural modeling, motion, material patterns or the anisotropy and iridescence layers needs its module loaded before createAgentScene runs:+// editing, procedural modeling, motion, material patterns, terrain or the anisotropy and iridescence layers needs its module loaded before createAgentScene runs:// call `await loadAgentSceneModules(recipe)` (or `loadAllAgentSceneModules()` in a host that does not mind the// size). createAgentScene is still synchronous; when a needed module is missing it says which call to make.@@ -16,6 +16,7 @@ const MODULE_LOADERS = {relations: () => import('./agent-relations.js'),timeline: () => import('./film-timeline.js'),layerShaders: () => import('./material-layer-shaders.js'),+ terrain: () => import('./agent-terrain.js'),};const loadedModules = {};@@ -37,6 +38,7 @@ const MODULE_MARKERS = {relations: ['"relations":'],timeline: ['"timeline":{'],layerShaders: ['"anisotropy"', '"iridescence"'],+ terrain: ['"type":"terrain"'],};/** 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.jsindex 9fe274d6..f37b47d9 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -344,6 +344,7 @@ const GEOMETRY_FIELDS = {curve: ['points', 'closed', 'radius', 'taper', 'profile', 'resolution', 'radialSegments'],text: ['text', 'size', 'depth', 'font', 'align', 'curveSegments'],mesh: ['base', 'edits', 'stack', 'smoothAngle'],+ terrain: ['size', 'resolution', 'seed', 'amplitude', 'holes'],};function geometryEstimate(value) {@@ -403,6 +404,8 @@ function geometryEstimate(value) {const perSegment = isDefaultFont ? CURVE_TEXT_LIMITS.verticesPerCharacterSegment : CURVE_TEXT_LIMITS.verticesPerCustomCharacterSegment;return visible * perSegment * detail('curveSegments', 4, 1, 16);}+ case 'terrain':+ return agentSceneModule('terrain').terrainVertexEstimate(value);case 'extrude': {const holes = value.holes ?? [];if (!Array.isArray(holes) || holes.length > 128) {@@ -474,6 +477,8 @@ function generateGeometry(value, maxVertices) {return agentSceneModule('modeling').curve(value.points, { ...value, maxVertices });case 'text':return agentSceneModule('text').text(value.text, { ...value, maxVertices });+ case 'terrain':+ return agentSceneModule('terrain').generateTerrainGeometry(value, maxVertices);case 'mesh':return agentSceneModule('mesh').generateMeshGeometry(() => generateGeometry(value.base, maxVertices), value.edits ?? [], {maxVertices, smoothAngle: value.smoothAngle ?? MESH_SMOOTH_ANGLE_DEFAULT,diff --git a/src/agent-terrain.js b/src/agent-terrain.jsnew file mode 100644index 00000000..7ac12033--- /dev/null+++ b/src/agent-terrain.js@@ -0,0 +1,61 @@+// Recipe terrain: a seeded rolling ground with optional round holes, built with the terrain addon as one mesh.+// It loads on demand with the recipes that contain a terrain geometry, so the scene entry does not carry it.+import { createTerrain } from './terrain.js';++export const TERRAIN_LIMITS = Object.freeze({+ size: [1, 2000],+ resolution: [2, 256],+ amplitude: [0, 200],+ defaultSize: 40,+ defaultResolution: 64,+ defaultAmplitude: 1,+ maximumHoles: 16,+});++function numberWithin(value, fallback, [minimum, maximum], label) {+ const resolved = value ?? fallback;+ if (!Number.isFinite(resolved) || resolved < minimum || resolved > maximum) {+ throw new RangeError(`terrain ${label} must be a number within ${minimum} and ${maximum}.`);+ }+ return resolved;+}++function integerWithin(value, fallback, [minimum, maximum], label) {+ const resolved = numberWithin(value, fallback, [minimum, maximum], label);+ if (!Number.isInteger(resolved)) throw new RangeError(`terrain ${label} must be a whole number.`);+ return resolved;+}++/** Vertex count of a terrain record, checked against the recipe limits before any ground is built. */+export function terrainVertexEstimate(value) {+ const resolution = integerWithin(value.resolution, TERRAIN_LIMITS.defaultResolution, TERRAIN_LIMITS.resolution, 'resolution');+ numberWithin(value.size, TERRAIN_LIMITS.defaultSize, TERRAIN_LIMITS.size, 'size');+ numberWithin(value.amplitude, TERRAIN_LIMITS.defaultAmplitude, TERRAIN_LIMITS.amplitude, 'amplitude');+ if (value.holes !== undefined && (!Array.isArray(value.holes) || value.holes.length > TERRAIN_LIMITS.maximumHoles)) {+ throw new RangeError(`terrain holes must be a list of at most ${TERRAIN_LIMITS.maximumHoles} circles.`);+ }+ return (resolution + 1) * (resolution + 1);+}++/** Render geometry of a terrain record: ground from -size / 2 to size / 2 on X and Z, hills of the given amplitude, holes cut out. */+export function generateTerrainGeometry(value, maxVertices) {+ const vertices = terrainVertexEstimate(value);+ if (vertices > maxVertices) throw new RangeError(`Terrain needs ${vertices} vertices, exceeding maxVertices ${maxVertices}. Lower resolution.`);+ const size = value.size ?? TERRAIN_LIMITS.defaultSize;+ const seed = Number.isInteger(value.seed) ? value.seed : 1;+ const terrain = createTerrain({+ size,+ chunks: 1,+ levels: 1,+ resolution: value.resolution ?? TERRAIN_LIMITS.defaultResolution,+ seed,+ holes: value.holes,+ height: {+ amplitude: value.amplitude ?? TERRAIN_LIMITS.defaultAmplitude,+ featureSize: size / 4,+ warp: 0,+ mountainMask: () => 0,+ },+ });+ return terrain.parts[0].geometry;+}diff --git a/src/terrain.js b/src/terrain.jsindex 4282277e..283a832a 100644--- a/src/terrain.js+++ b/src/terrain.js@@ -157,14 +157,40 @@ function validateOptions({ size, resolution, chunks, levels }) {}const SIDES = Object.freeze(['west', 'east', 'north', 'south']);+const MAXIMUM_HOLES = 64;++/** Checks the hole list ({ center: [x, z], radius } circles) and returns a copy, or null when there are none. */+export function normalizeTerrainHoles(holes) {+ if (holes === undefined) return null;+ if (!Array.isArray(holes) || holes.length > MAXIMUM_HOLES) throw new RangeError(`holes must be a list of at most ${MAXIMUM_HOLES} circles.`);+ if (holes.length === 0) return null;+ return holes.map(hole => {+ const center = hole?.center;+ const validCenter = Array.isArray(center) && center.length === 2 && center.every(Number.isFinite);+ if (!validCenter || !(hole.radius > 0) || !Number.isFinite(hole.radius)) {+ throw new RangeError('Each hole needs center [x, z] in metres and a positive radius.');+ }+ return { center: [center[0], center[1]], radius: hole.radius };+ });+}++function pointInsideHoles(holes, pointX, pointZ) {+ for (const hole of holes) {+ if (Math.hypot(pointX - hole.center[0], pointZ - hole.center[1]) < hole.radius) return true;+ }+ return false;+}/**- * Returns { parts, heightAt, normalAt, bounds, update, triangleCount }.+ * Returns { parts, heightAt, normalAt, isHole, bounds, update, triangleCount }.+ * `holes` ([{ center: [x, z], radius }]) cuts round openings through the ground; isHole(x, z) tells whether a point is in one.* Ground spans x and z from -size / 2 to size / 2. Call update(eye) each frame (or when the camera moves) and, when it* returns a non-empty list, pass the scene parts to renderer.replaceParts.*/-export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material = DEFAULT_MATERIAL, lodDistance, eye } = {}) {+export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels = 4, height, seed = 1, material = DEFAULT_MATERIAL, lodDistance, eye, holes } = {}) {validateOptions({ size, resolution, chunks, levels });+ const holeCircles = normalizeTerrainHoles(holes);+ const isHole = (worldX, worldZ) => holeCircles !== null && pointInsideHoles(holeCircles, worldX, worldZ);const heightFunction = resolveHeightFunction(height, size, seed);const chunkSize = size / chunks;const gridCells = chunks * resolution;@@ -259,6 +285,10 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levelslet cursor = 0;for (let row = 0; row < cells; row++) {for (let column = 0; column < cells; column++) {+ // A cell whose centre lies inside a hole is left out, so a coarser level cuts a coarser hole.+ const cellCenterX = origin + (firstColumn + (column + 0.5) * step) * spacing;+ const cellCenterZ = origin + (firstRow + (row + 0.5) * step) * spacing;+ if (isHole(cellCenterX, cellCenterZ)) continue;const corner00 = row * side + column;const corner10 = corner00 + 1;const corner01 = corner00 + side;@@ -267,7 +297,7 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levelscursor += 6;}}- return { positions, normals, uvs, indices };+ return { positions, normals, uvs, indices: cursor === indices.length ? indices : indices.slice(0, cursor) };}function snappedHeight(column, row, side, step, gridColumn, gridRow, edgeLevels, level) {@@ -330,7 +360,7 @@ export function createTerrain({ size = 512, resolution = 32, chunks = 8, levels}update(eye ?? [0, highest + size * 0.5, 0]);- return { parts, heightAt, normalAt, bounds, update, get triangleCount() { return triangleTotal; }, chunkSize, resolution, levels, chunkLevels: () => chunkStates.map(state => state.level) };+ return { parts, heightAt, normalAt, isHole, bounds, update, get triangleCount() { return triangleTotal; }, chunkSize, resolution, levels, chunkLevels: () => chunkStates.map(state => state.level) };}function identityMatrix() {diff --git a/tests/agent-modeling-suite.test.js b/tests/agent-modeling-suite.test.jsindex 9d0f6cab..0ea75793 100644--- a/tests/agent-modeling-suite.test.js+++ b/tests/agent-modeling-suite.test.js@@ -154,3 +154,22 @@ test('the tray-drop checks reject a box collider, a missing section and a body tfallingThrough.physics.bodies[0].collidesWith = [1];assert.deepEqual(failedKinds(await gradeRecipe(taskById('tray-drop'), fallingThrough)), ['balls rest on the pocket floor']);});++test('the terrain walk needs the opening, the hills and a walk that goes around the opening', async () => {+ const task = taskById('terrain-hole-walk');+ const closedGround = structuredClone(REFERENCES['terrain-hole-walk']);+ delete closedGround.geometries[0].holes;+ assert.deepEqual(failedKinds(await gradeRecipe(task, closedGround)), ['through']);++ const flatGround = structuredClone(REFERENCES['terrain-hole-walk']);+ flatGround.geometries[0].amplitude = 0;+ assert.deepEqual(failedKinds(await gradeRecipe(task, flatGround)), ['groundRelief']);++ const straightWalk = structuredClone(REFERENCES['terrain-hole-walk']);+ straightWalk.motion.tracks[0].keyframes = [{ time: 0, value: [-15, 0.5, -15] }, { time: 10, value: [15, 0.5, 15] }];+ assert.deepEqual(failedKinds(await gradeRecipe(task, straightWalk)), ['walkPath']);++ const hoveringWalker = structuredClone(REFERENCES['terrain-hole-walk']);+ for (const keyframe of hoveringWalker.motion.tracks[0].keyframes) keyframe.value[1] = 4;+ assert.deepEqual(failedKinds(await gradeRecipe(task, hoveringWalker)), ['walkPath']);+});diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex 8323d3b6..6d23ea55 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -149,7 +149,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'assert.equal(recipeSchema.properties.materials.maxItems, 256);assert.equal(recipeSchema.properties.geometries.maxItems, 256);const variants = recipeSchema.properties.geometries.items.oneOf ?? recipeSchema.properties.geometries.items.anyOf;- assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'mesh']);+ assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'terrain', 'grid', 'mesh']);assert.ok(variants.every(variant => variant.additionalProperties === false));assert.equal(recipeSchema.properties.environment.additionalProperties, false);assert.equal(recipeSchema.properties.environment.properties.pointLights.maxItems, 8);diff --git a/tests/terrain-holes.test.js b/tests/terrain-holes.test.jsnew file mode 100644index 00000000..4e5e589c--- /dev/null+++ b/tests/terrain-holes.test.js@@ -0,0 +1,123 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { createTerrain, normalizeTerrainHoles } from '../src/terrain.js';+import { createAgentScene, loadAgentSceneModules, agentSceneModulesNeeded, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';++const SEEDED_OPTIONS = { size: 128, chunks: 4, resolution: 16, levels: 3, height: { amplitude: 10, mountainAmplitude: 30, featureSize: 60 }, seed: 5, eye: [10, 20, 10] };+// Digest of the geometry the terrain made before holes existed. It must not move while the new fields are absent.+const SEEDED_TERRAIN_DIGEST = 'b292b9b25158063726e954d6968a7c538e292da166e5e5c480577b5f1859610e';++function digestOf(terrain) {+ const hash = createHash('sha256');+ for (const part of terrain.parts) {+ for (const key of ['positions', 'normals', 'uvs', 'indices']) {+ const array = part.geometry[key];+ hash.update(Buffer.from(array.buffer, array.byteOffset, array.byteLength));+ }+ }+ return hash.digest('hex');+}++function triangleCenters(geometry) {+ const centers = [];+ for (let offset = 0; offset < geometry.indices.length; offset += 3) {+ const center = [0, 0];+ for (let corner = 0; corner < 3; corner++) {+ center[0] += geometry.positions[geometry.indices[offset + corner] * 3] / 3;+ center[1] += geometry.positions[geometry.indices[offset + corner] * 3 + 2] / 3;+ }+ centers.push(center);+ }+ return centers;+}++function triangleTotal(terrain) {+ return terrain.parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);+}++test('seeded terrain is byte-identical while holes are absent, undefined or empty', () => {+ assert.equal(digestOf(createTerrain(SEEDED_OPTIONS)), SEEDED_TERRAIN_DIGEST);+ assert.equal(digestOf(createTerrain({ ...SEEDED_OPTIONS, holes: undefined })), SEEDED_TERRAIN_DIGEST);+ assert.equal(digestOf(createTerrain({ ...SEEDED_OPTIONS, holes: [] })), SEEDED_TERRAIN_DIGEST);+});++test('a hole leaves no surface inside it, keeps the rest and reports isHole', () => {+ const holes = [{ center: [6, -10], radius: 9 }];+ const whole = createTerrain(SEEDED_OPTIONS);+ const pierced = createTerrain({ ...SEEDED_OPTIONS, holes });+ assert.ok(triangleTotal(pierced) < triangleTotal(whole));+ assert.equal(pierced.isHole(6, -10), true);+ assert.equal(pierced.isHole(40, 40), false);+ assert.equal(whole.isHole(6, -10), false);+ for (const part of pierced.parts) {+ for (const [centerX, centerZ] of triangleCenters(part.geometry)) {+ assert.ok(Math.hypot(centerX - 6, centerZ + 10) > 9 - 8, 'no triangle sits deep inside the hole');+ }+ }+ assert.equal(pierced.heightAt(30, 30), whole.heightAt(30, 30));+});++test('a hole covering the whole ground gives empty geometry instead of throwing', () => {+ const terrain = createTerrain({ size: 16, chunks: 1, levels: 1, resolution: 8, holes: [{ center: [0, 0], radius: 100 }] });+ assert.equal(terrain.triangleCount, 0);+ assert.equal(terrain.parts[0].geometry.indices.length, 0);+});++test('hostile hole lists are rejected with a clear error', () => {+ const hostile = [+ 'holes', 5, {}, [null], [{}], [{ center: [0, 0] }], [{ radius: 2 }],+ [{ center: [0, 0], radius: 0 }], [{ center: [0, 0], radius: -3 }], [{ center: [0, 0], radius: Infinity }],+ [{ center: [NaN, 0], radius: 2 }], [{ center: [0], radius: 2 }], [{ center: [0, 0, 0], radius: 2 }], [{ center: 'ab', radius: 2 }],+ Array.from({ length: 65 }, () => ({ center: [0, 0], radius: 1 })),+ ];+ for (const holes of hostile) assert.throws(() => normalizeTerrainHoles(holes), RangeError, JSON.stringify(holes)?.slice(0, 40));+ assert.throws(() => createTerrain({ ...SEEDED_OPTIONS, holes: [{ center: [0, 0], radius: -1 }] }), RangeError);+});++const baseRecipe = terrain => ({+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'ground', ...terrain }],+ materials: [{ id: 'grass', color: [0.3, 0.6, 0.2] }],+ nodes: [{ id: 'ground', geometry: 'ground', material: 'grass' }],+});++async function sceneFor(terrain) {+ const recipe = baseRecipe(terrain);+ await loadAgentSceneModules(recipe);+ return createAgentScene(recipe);+}++test('a recipe terrain has hills, a hole and a stable seed', async () => {+ const description = { type: 'terrain', size: 40, resolution: 64, seed: 3, amplitude: 1.5, holes: [{ center: [0, 0], radius: 3 }] };+ assert.deepEqual(agentSceneModulesNeeded(baseRecipe(description)), ['terrain']);+ const scene = await sceneFor(description);+ const geometry = scene.parts[0].geometry;+ const heights = Array.from({ length: geometry.positions.length / 3 }, (_, index) => geometry.positions[index * 3 + 1]);+ assert.ok(Math.max(...heights) - Math.min(...heights) > 0.3, 'the ground rolls');+ assert.ok(Math.max(...heights.map(Math.abs)) <= 1.6, 'hills stay within the amplitude');+ assert.ok(triangleCenters(geometry).every(([centerX, centerZ]) => Math.hypot(centerX, centerZ) > 2), 'the hole is open');+ assert.ok(triangleCenters(geometry).some(([centerX, centerZ]) => Math.hypot(centerX - 8, centerZ - 8) < 1), 'the rest is solid');+ const again = await sceneFor(description);+ assert.deepEqual(Array.from(again.parts[0].geometry.positions), Array.from(geometry.positions));+ assert.equal(scene.exportRecipe().geometries[0].holes[0].radius, 3);+});++test('recipe terrain rejects out-of-range, hostile and unknown fields before building', async () => {+ const bad = [+ { type: 'terrain', size: 0 }, { type: 'terrain', size: 5000 }, { type: 'terrain', size: NaN },+ { type: 'terrain', resolution: 1 }, { type: 'terrain', resolution: 257 }, { type: 'terrain', resolution: 12.5 },+ { type: 'terrain', amplitude: -1 }, { type: 'terrain', amplitude: 1e9 },+ { type: 'terrain', holes: 'one' }, { type: 'terrain', holes: Array.from({ length: 17 }, () => ({ center: [0, 0], radius: 1 })) },+ { type: 'terrain', holes: [{ center: [0, 0], radius: -2 }] }, { type: 'terrain', holes: [null] },+ { type: 'terrain', unknown: 1 },+ ];+ for (const description of bad) {+ await assert.rejects(() => sceneFor(description), Error, JSON.stringify(description).slice(0, 60));+ }+});++test('the capabilities list the terrain geometry and its limits', () => {+ assert.ok(AGENT_SCENE_CAPABILITIES.geometryTypes.includes('terrain'));+ assert.match(AGENT_SCENE_CAPABILITIES.terrain, /holes/);+});