3D engine that AI agents drive
Add bounded field expressions, set_position, displace and instances on points
Nguyen Xuan Ana57919ef7bd3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7534a5ad..4f6caa84 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add bounded field expressions: a JSON language of math, comparison, logic, vectors, seeded noise and attributes (position, normal, index, tags) that compiles once to closures over typed arrays and never executes a string. It limits nodes (64), depth (12), elements (250,000) and node-evaluations (8 million) before it evaluates, and only reads operator names from a fixed table. It drives a `{ "field": expression }` face selection rule, `set_position` and `displace` as edits and stack nodes, and a `where` filter for instances. `displace` and `set_position` match Blender's Displace modifier and a Geometry Nodes Set Position node in five new golden cases+- Add `instances` on a recipe node: repeat its geometry at the points of a grid, a seeded scatter in a box or the surface of a geometry, with `where`, `yaw`, `alignToNormal` and `scale`, at most 2048 candidate points. It expands to ordinary nodes that share geometry and material, so the renderer draws one instanced batch. Add the `pillar-court` task to the agent modeling suite- Add spot lights (`environment.spotLights`, 8), rectangular area lights (`environment.areaLights`, 4) and shadows for point and spot lights (`castShadow: true`). Intensity of a spot light is candela, as for a point light, with Blender's cone mask. Area lights use a representative point, within 1.2 percent of Cycles on the axis. Shadows share one 2048 x 3072 depth atlas of 24 tiles (24 MiB, allocated on first use): a point light takes 6 and a spot light 1, and a request for more is an error. The shader code and the atlas exist only in a scene that uses them. Recipes get all of it through `set-environment`, the MCP schema and `scene_capabilities` (`maxSpotLights`, `maxAreaLights`, `localShadows`). Cascaded directional shadows and light linking are not part of this- Add ten cutting and repair edits: `fill_holes`, `dissolve_faces`, `dissolve_edges`, `dissolve_verts`, `dissolve_limited`, `bisect_plane` (with `fill`, `clearInner`, `clearOuter`), `bridge_edge_loops` (with `segments`), `subdivide_edges`, `grid_fill` and `knife_project`. Each tags what it makes, and the edge rule `{ "open": true }` picks boundary edges. The lint message for an open boundary now suggests `fill_holes`. 18 new cases match Blender in counts, face sizes, area, volume and positions; the knife is compared only with a straight plane cut and differs where a face runs along the projection directiondiff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjsindex 7753e9dd..b985661c 100644--- a/bench/agent-modeling/references.mjs+++ b/bench/agent-modeling/references.mjs@@ -184,6 +184,14 @@ export const REFERENCES = {{ id: 'head', geometry: 'head', translation: [0, 0.12, 0], rotation: axisRotation('x', -Math.PI / 2) },],),+ 'pillar-court': scene(+ [{ id: 'pillar', type: 'box', bevel: 0 }],+ [{+ id: 'court', geometry: 'pillar', translation: [0, 0.25, 0], scale: [0.1, 0.5, 0.1],+ // The group's scale is 0.1 by 0.5 by 0.1, so a grid step of 4 by 5 is 0.4 m by 0.5 m.+ instances: { grid: { counts: [5, 1, 3], spacing: [4, 1, 5] } },+ }],+ ),window: scene([{id: 'frame', type: 'extrude', depth: 0.08,diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjsindex 2ae774c9..f6945c7f 100644--- a/bench/agent-modeling/tasks.mjs+++ b/bench/agent-modeling/tasks.mjs@@ -245,6 +245,21 @@ For this task the object does not need to rest on the ground.`,{ kind: 'nodeDistance', from: 'elbow', to: 'tip', time: 1, distance: 0.4 },],},+ {+ id: 'pillar-court',+ prompt: `A pillar court: a grid of 5 pillars along X by 3 along Z. Each pillar is a square column 0.1 m wide and+0.5 m tall. Pillars are 0.4 m apart along X and 0.5 m apart along Z, centre to centre, the whole grid centred on+X = 0 and Z = 0, every pillar standing on the ground. Repeat one pillar over the grid instead of modelling fifteen.`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [1.7, 0.5, 1.1] },+ { kind: 'ground' },+ { kind: 'holes', equals: 0 },+ { kind: 'volume', min: 0.0725, max: 0.0775 },+ { kind: 'section', axis: 'y', at: 0.25, equals: 15, label: 'fifteen pillars' },+ { kind: 'section', axis: 'x', at: 0.4, equals: 3, label: 'three pillars along Z in the column at X = 0.4' },+ ],+ },{id: 'robot-reach',assets: true,diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 1524ddf8..0d088513 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -15,7 +15,7 @@"entry:sculpt": 2500,"entry:surface": 10100,"entry:mesh-query": 15900,- "entry:mesh": 44700,+ "entry:mesh": 48400,"entry:shrinkwrap": 18300,"entry:surface-attachment": 11800,"entry:physics": 16500,@@ -28,11 +28,11 @@"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 109400,- "entry:agent-asset": 116900,+ "entry:agent-scene": 113700,+ "entry:agent-asset": 121100,"entry:hdri": 3300,"scene:lit-box": 54200,"scene:gltf-box": 73300,- "scene:agent-scene": 135800+ "scene:agent-scene": 139500}}diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex dd84d0a8..a85a4d79 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -150,6 +150,29 @@ View and projection matrices must remain finite and nonsingular at Float32 preciProjection validation uses aspect one because the renderer owns the actual target aspect.An explicit top view can use `eye: [0, 3, 0]`, `target: [0, 0, 0]`, and `up: [0, 0, -1]`.+### Instances on points++A node with `instances` repeats its geometry and material at points. At `scene_create` it becomes a group node (the+node's id, with its transform and parent) and one child node per point (`<id>.0`, `<id>.1`, and so on), all sharing+the geometry and material, so the renderer draws them as one instanced batch. After that they are ordinary nodes.+`instances` is accepted in the recipe, not in an `add-node` operation.++```text+{ "id": "grass", "geometry": "blade", "material": "green", "parent": "ground",+ "instances": { "surface": { "geometry": "ground-shape", "count": 300 }, "seed": 3,+ "where": { "gt": [{ "attr": "position", "component": "x" }, 0] },+ "yaw": true, "scale": [0.7, 1.3] } }+```++Give exactly one point source. `grid` is `{ counts: [nx, ny, nz], spacing: [dx, dy, dz] }`, centred on the group.+`scatter` is `{ count, min, max }`, seeded random points in a box. `surface` is `{ geometry, count }`, seeded points+on the triangles of a recipe geometry in proportion to their area; they are in that geometry's own space, so parent+the group to the node that carries it. `seed` (default 0) fixes the placement. `where` is a number+[field expression](mesh.md#field-expressions) over the points (position, normal, index): points where it is 0 are+dropped. `yaw` turns each instance randomly about up, `alignToNormal` (surface only) tilts up to the surface normal, and `scale`+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.+## Transactions and ownership`apply(operations, { expectedRevision })` requires the current revision and returns the new revision.diff --git a/docs/mesh.md b/docs/mesh.mdindex 1128d954..fc7544ca 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -119,6 +119,7 @@ Selection rules:| `{ "and": [...] }`, `{ "or": [...] }`, `{ "not": rule }` | combinations || `{ "grow": rule, "steps": 1 }` | the selection plus faces sharing an edge, repeated || `{ "boundary": rule }` | selected faces that touch an unselected face or an open edge |+| `{ "field": expression }` | faces where a [field expression](#field-expressions) is not 0 |Edits (names follow Blender's `bmesh.ops` where they match):@@ -196,7 +197,7 @@ These three (and `bevel`, below) work as edits and as stack nodes:### Modifier stack-A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide` and `uv_unwrap` nodes (up to 16) evaluated after the+A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position` and `displace` nodes (up to 16) evaluated after theedits without changing them, as Blender's modifier stack. Every prefix (the edit result, then each node) is cachedby its recipe text in a least-recently-used cache bounded at 64 entries and 64 MiB, so changing a late node reusesthe earlier work. Results list one entry per node with `cached: true` when reused. `meshCacheStats()` reports hits@@ -205,6 +206,51 @@ and misses. `evaluateMeshStack(mesh, stack, { cache, cacheKey })` runs a stack oThe `mesh_stack` tool sets the whole stack in one revision. `apply: n` moves the first `n` nodes into the edit log,as Blender's Apply modifier, which leaves the result unchanged.+### Field expressions++A field expression is plain JSON that computes one number, or one vector, for each point or face of a mesh. It is+data and never code: `src/mesh-fields.js` reads it against a fixed table of operators, compiles it once into+closures over typed arrays, and checks the limits before it evaluates anything. No string is executed, and no input+string is used as a property name, so a recipe written by an agent that follows injected instructions cannot run code+or reach `__proto__` or `constructor`. The same expression gives the same bytes on every run.++```json+{ "mul": [{ "attr": "position", "component": "y" }, 0.5] }+{ "noise": { "scale": 3, "seed": 7, "octaves": 2 } }+{ "gt": [{ "dot": [{ "attr": "normal" }, [0, 1, 0]] }, 0.9] }+```++A number is a constant, `true` and `false` are 1 and 0, and an array of three numbers is a constant vector.+Operators that take numbers also take vectors and work on each component; a number spreads to all three.++| Group | Operators |+| --- | --- |+| Math | `add` `mul` `min` `max` (2 to 8 operands), `sub` `div` `mod` `pow`, `clamp` `mix` `smoothstep` (3), `neg` `abs` `sqrt` `sin` `cos` `floor` `ceil` `round` `fract` `sign` (1). `div` and `mod` by 0 give 0. |+| Comparison and logic | `lt` `lte` `gt` `gte` `eq` give 1 or 0; `and` `or` `not`; `if: [condition, a, b]` |+| Vectors | `vec: [x, y, z]`, `dot` `cross` `distance`, `length` `normalize`, `x` `y` `z` read a component |+| Attributes | `{ "attr": "position" \| "normal" }` with optional `component`, `{ "attr": "index" }`, `{ "attr": "tag", "name": "top" }` |+| Random | `{ "noise": { "scale", "seed", "octaves", "at" } }` smooth value noise in 0 to 1 at a position (default the element's), `{ "random": { "seed" } }` a number in 0 to 1 per element |++Limits, checked before evaluation: 64 nodes, depth 12, 250,000 elements, and 8,000,000 node-evaluations (nodes times+elements). Numbers stay within 1e6, noise scale within 1000 and octaves within 4. An expression over faces reads a+point attribute as the face centre or the face normal, and over points reads a tag as the mean of the faces around+the point.++Uses:++- `{ "field": expression }` is a selection rule for any face edit: the faces where the expression is not 0.+- `set_position` (`select`, `position`, `offset`) is Blender's Set Position. `position` and `offset` are vector+ expressions evaluated on the input positions, so vertex order never matters. It moves the vertices of the selected faces.+- `displace` (`select`, `field`, `strength`, `midlevel`, `direction`) is Blender's Displace modifier with a field as+ the texture: each vertex moves by `(field - midlevel) * strength` along `normal` (default), `x`, `y` or `z`.+- Both are also stack nodes, so a late change reuses the cached earlier nodes.+- `instances` on a recipe node repeats its geometry at points; see [agent-scene.md](agent-scene.md#instances-on-points).++Blender comparison: `tests/blender-golden.test.js` runs `set_position` against a Geometry Nodes Set Position node+and `displace` against the Displace modifier, with a constant and with a Blend texture, and the vertex positions+match within 1e-3. `noise` has no direct match, because Blender's noise texture is a different function; the fields+in those cases use only arithmetic and position.+### Bevel`bevel` rounds or chamfers edges, as an edit or as a stack node:diff --git a/docs/parity.md b/docs/parity.mdindex e764f57b..6b4f8d85 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -79,7 +79,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Generate > Mirror Modifier | done | Stack node with axis and merge. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | || Modeling > Modifiers > Generate > Multiresolution Modifier | missing | No multiresolution. | | || Modeling > Modifiers > Generate > Remesh Modifier | missing | No remesh. | | #40 |-| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `addons/clutter` and `addons/grass` scatter in code. Recipes have no scatter node. | | #42 |+| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. No minimum distance or density map, and `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #42 || Modeling > Modifiers > Generate > Screw Modifier | partial | `lathe` covers a full turn. There is no stack node or screw offset. | | #42 || Modeling > Modifiers > Generate > Skin Modifier | missing | No equivalent. | | #42 || Modeling > Modifiers > Generate > Solidify Modifier | done | Stack node with thickness, offset and even thickness. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |@@ -91,7 +91,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Deform > Armature Modifier | partial | GPU skinning for imported rigs. Recipes can not bind a mesh. | [skinning](../tests/skinning.test.js) | #46 || Modeling > Modifiers > Deform > Cast Modifier | missing | No equivalent. | | #42 || Modeling > Modifiers > Deform > Curve Modifier | missing | No equivalent. | | #42 |-| Modeling > Modifiers > Deform > Displace Modifier | missing | No stack node. `addons/sculpt` displaces in code. | | #42 |+| Modeling > Modifiers > Deform > Displace Modifier | done | `displace` edit and stack node with a field as the texture, along the normal or an axis, with strength, midlevel and a face selection. Positions match Blender with a constant and with a Blend texture. | [src/mesh-field-edits.js](../src/mesh-field-edits.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #43 || Modeling > Modifiers > Deform > Hook Modifier | missing | No equivalent. | | #42 || Modeling > Modifiers > Deform > Laplacian Deform Modifier | missing | No equivalent. | | || Modeling > Modifiers > Deform > Lattice Modifier | missing | No lattice. | | #42 |@@ -117,8 +117,8 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Physics > Particle Instance Modifier | missing | No particle system. | | #63 || Modeling > Modifiers > Physics > Particle System Modifier | missing | No particle system. | | #63 || Modeling > Modifiers > Physics > Soft Body Modifier | missing | No soft bodies. | | #62 |-| Modeling > Modifiers > Geometry Nodes Modifier | missing | No node graph. | | #43 |-| Modeling > Geometry Nodes | missing | No fields or node graph. Issue #43 adds bounded JSON expressions and not a visual editor. | | #43 |+| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 |+| Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface) and Displace. Noise is not Blender's noise function, and there is no Blender comparison for instancing. Issue #43 chose bounded JSON expressions and not a visual editor. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js) | #43 || Modeling > Transform | partial | Node transforms, and `translate` on a selection with falloff. There is no rotate or scale on a selection. | | || Sculpting & Painting > Brushes | out of scope | Brush settings for a hand. Strokes have explicit parameters. | | || Sculpting & Painting > Selection & Visibility | out of scope | Interface for a person in a paint mode. | | |diff --git a/scripts/blender-golden.py b/scripts/blender-golden.pyindex 28c5f3ba..a8aebe5b 100644--- a/scripts/blender-golden.py+++ b/scripts/blender-golden.py@@ -341,7 +341,69 @@ def add_subdivision(mesh_object, edit, _inputs):modifier.boundary_smooth = "PRESERVE_CORNERS"+# Set Position through a Geometry Nodes modifier. Only the part of the field language the cases use is translated:+# numbers, "vec", position components, add, sub and mul. Anything else raises, so a case can never silently differ.+def field_socket(tree, expression, position_xyz):+ if isinstance(expression, (int, float)):+ node = tree.nodes.new("ShaderNodeValue")+ node.outputs[0].default_value = float(expression)+ return node.outputs[0]+ if "attr" in expression and expression["attr"] == "position" and "component" in expression:+ return position_xyz.outputs["xyz".index(expression["component"])]+ operations = {"add": "ADD", "sub": "SUBTRACT", "mul": "MULTIPLY"}+ for name, operation in operations.items():+ if name in expression:+ left, right = expression[name]+ node = tree.nodes.new("ShaderNodeMath")+ node.operation = operation+ tree.links.new(field_socket(tree, left, position_xyz), node.inputs[0])+ tree.links.new(field_socket(tree, right, position_xyz), node.inputs[1])+ return node.outputs[0]+ raise ValueError(f"Unsupported field expression for the Blender golden: {expression}")+++def add_set_position(mesh_object, edit, _inputs):+ tree = bpy.data.node_groups.new("SetPosition", "GeometryNodeTree")+ tree.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")+ tree.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")+ group_input = tree.nodes.new("NodeGroupInput")+ group_output = tree.nodes.new("NodeGroupOutput")+ set_position = tree.nodes.new("GeometryNodeSetPosition")+ position = tree.nodes.new("GeometryNodeInputPosition")+ position_xyz = tree.nodes.new("ShaderNodeSeparateXYZ")+ tree.links.new(position.outputs["Position"], position_xyz.inputs["Vector"])+ combine = tree.nodes.new("ShaderNodeCombineXYZ")+ for axis, component in enumerate(edit["offset"]["vec"]):+ tree.links.new(field_socket(tree, component, position_xyz), combine.inputs[axis])+ tree.links.new(group_input.outputs[0], set_position.inputs["Geometry"])+ tree.links.new(combine.outputs["Vector"], set_position.inputs["Offset"])+ tree.links.new(set_position.outputs["Geometry"], group_output.inputs[0])+ modifier = mesh_object.modifiers.new("SetPosition", "NODES")+ modifier.node_group = tree+++# Displace with a field as the texture. A constant field means no texture. The one varying field the cases use, a+# linear gradient along local x, is Blender's Blend texture, whose value is (x + 1) / 2.+LINEAR_GRADIENT_X = {"mul": [{"add": [{"attr": "position", "component": "x"}, 1]}, 0.5]}+++def add_displace(mesh_object, edit, _inputs):+ modifier = mesh_object.modifiers.new("Displace", "DISPLACE")+ modifier.strength = edit.get("strength", 1)+ modifier.mid_level = edit.get("midlevel", 0.5)+ modifier.direction = edit.get("direction", "normal").upper()+ if edit["field"] != 1:+ if edit["field"] != LINEAR_GRADIENT_X:+ raise ValueError(f"Unsupported field for the Blender golden: {edit['field']}")+ texture = bpy.data.textures.new("Gradient", "BLEND")+ texture.progression = "LINEAR"+ modifier.texture = texture+ modifier.texture_coords = "LOCAL"++MODIFIERS = {+ "set_position": add_set_position,+ "displace": add_displace,"mirror": add_mirror,"array": add_array,"solidify": add_solidify,diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 5631385e..b5999e6a 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -26,7 +26,19 @@ const nodeFields = {rotation: quaternion.optional().describe('Nonzero local XYZW quaternion. The backend normalizes it.'),scale: z.tuple([positive, positive, positive]).optional().describe('Positive local XYZ scale.'),};-const nodeRecord = z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields });+const fieldExpression = z.union([finite, z.boolean(), vector3, z.record(z.string(), z.unknown())]).describe('Field expression, plain JSON and never code. A number, a boolean or [x,y,z] is a constant; an object holds one operator: math add mul sub div mod pow min max clamp mix smoothstep neg abs sqrt sin cos floor ceil round fract sign; comparison lt lte gt gte eq; logic and or not if [cond,a,b]; vectors vec [x,y,z] dot cross distance length normalize x y z; sources {"attr":"position"|"normal"|"index"|"tag","component":"x"|"y"|"z","name":tag}, {"noise":{"scale":3,"seed":7,"octaves":1}} in 0..1, {"random":{"seed":1}} per element in 0..1. Example: {"mul":[{"attr":"position","component":"y"},0.5]}. At most 64 nodes, depth 12, 250000 elements.');+const instanceCount = z.number().int().min(1).max(2048);+const instanceSpec = z.strictObject({+ grid: z.strictObject({ counts: z.tuple([instanceCount, instanceCount, instanceCount]), spacing: vector3 }).optional().describe('Grid of counts[0] x counts[1] x counts[2] points centred on the group.'),+ scatter: z.strictObject({ count: instanceCount, min: vector3, max: vector3 }).optional().describe('Seeded random points in a box.'),+ surface: z.strictObject({ geometry: identifier, count: instanceCount }).optional().describe("Seeded random points on the surface of a recipe geometry, in that geometry's own space; parent the instanced node to the node that carries it."),+ seed: z.number().int().min(0).max(2147483647).optional(),+ where: fieldExpression.optional().describe('Number expression over the points (position, normal, index); points where it is 0 are dropped.'),+ yaw: z.boolean().optional().describe('Random turn about up.'),+ alignToNormal: z.boolean().optional().describe('Surface only: tilt up to the surface normal.'),+ scale: z.tuple([z.number().min(0.001).max(1000), z.number().min(0.001).max(1000)]).optional().describe('Random uniform scale range [min, max].'),+}).describe('Exactly one of grid, scatter or surface. Expands at scene_create into a group node plus one child node per point (<id>.0, <id>.1, ...) that share geometry and material and draw as one instanced batch. At most 2048 candidate points.');+const nodeRecord = z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: instanceSpec.optional().describe('Repeat geometry and material at points; needs both ids. Only in the recipe given to scene_create, not in add-node.'), ...nodeFields });const materialPattern = z.strictObject({type: z.enum(MATERIAL_PATTERN_TYPES).describe('Surface look. Directional types (wood, planks, metal) run along axis.'),colors: z.array(color).min(2).max(3).optional().describe('Linear RGB colours to mix, darker first. Bricks take a third for the mortar. Each type has good defaults.'),@@ -155,7 +167,7 @@ function primitiveGeometries(identified) {z.strictObject({ ...id, type: z.literal('tube'), path: z.array(vector3).min(2).max(4096), radius: finite.optional(), segments, radialSegments: detail(3, 128), closed: z.boolean().optional() }),];}-const selectRule = z.record(z.string(), z.unknown()).describe('Face selection rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10} (degrees), {"inside":{"min":[x,y,z],"max":[x,y,z]}} (face centroids), {"faces":[indices]}, {"and":[rules]}, {"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}. Tags come from the base (top, bottom, side, left, right, front, back) and from earlier edits (<name>.cap, <name>.side, <name>.rim, or a tag op).');+const selectRule = z.record(z.string(), z.unknown()).describe('Face selection rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10} (degrees), {"inside":{"min":[x,y,z],"max":[x,y,z]}} (face centroids), {"faces":[indices]}, {"and":[rules]}, {"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}, {"field":expression} (faces where a field expression is nonzero, evaluated at face centroids). Tags come from the base (top, bottom, side, left, right, front, back) and from earlier edits (<name>.cap, <name>.side, <name>.rim, or a tag op).');const editName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).optional().describe('Prefix for the tags this edit creates. Defaults to <op>-<index>.');const edgeRule = z.record(z.string(), z.unknown()).describe('Edge rule: {"all":true}, {"angle":30}, {"along":[x,y,z]}, {"between":[faceRule,faceRule]}, {"boundaryOf":faceRule} or {"open":true} for boundary edges (also {"open":{"inside":{"min":[x,y,z],"max":[x,y,z]}}}).');const meshEdit = z.discriminatedUnion('op', [@@ -204,6 +216,17 @@ const meshEdit = z.discriminatedUnion('op', [}).describe('Manifold boolean. Both the mesh and the cutter must be closed; mesh_inspect lists open edges.'),]);const stackNodes = [+ z.strictObject({+ op: z.literal('set_position'), select: selectRule.optional(),+ position: fieldExpression.optional().describe('Vector expression for the new position of each selected vertex. Defaults to the current position.'),+ offset: fieldExpression.optional().describe('Vector expression added after position, for example {"vec":[0,{"noise":{"scale":3}},0]}. Give position, offset or both.'),+ }).describe('Blender Set Position with field expressions, evaluated on the input positions, for the vertices of the selected faces.'),+ z.strictObject({+ op: z.literal('displace'), select: selectRule.optional(),+ field: fieldExpression.describe('Number expression used as the texture.'),+ strength: finite.optional().describe('Defaults to 1.'), midlevel: finite.optional().describe('Field value that does not move. Defaults to 0.5, the middle of noise.'),+ direction: z.enum(['normal', 'x', 'y', 'z']).optional().describe('Defaults to normal.'),+ }).describe('Blender Displace with a field as the texture: each vertex moves by (field - midlevel) * strength.'),z.strictObject({ op: z.literal('mirror'), name: editName, axis: z.enum(['x', 'y', 'z']).optional().describe('Mirror across the plane through the local origin perpendicular to this axis. Defaults to x.'), merge: bounded(0, 1000).optional().describe('Vertices this close to the plane are shared by both halves. Defaults to 0.001. Faces lying in the plane are removed, so a closed half becomes a closed whole.') }),z.strictObject({ op: z.literal('array'), name: editName, count: z.number().int().min(1).max(256).optional(), offset: vector3.optional().describe('Constant step between copies.'), relativeOffset: vector3.optional().describe('Step in bounding-box sizes. Defaults to [1, 0, 0] unless offset is given.'), merge: bounded(0, 1000).optional().describe('Weld touching copies and remove the faces between them.') }),z.strictObject({ op: z.literal('solidify'), name: editName, thickness: finite.describe('Wall thickness, positive.'), offset: bounded(-1, 1).optional().describe('-1 grows inward (default), 1 outward, 0 centred.'), evenThickness: z.boolean().optional() }),@@ -391,8 +414,8 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));- register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));- register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel, uv_unwrap, subdivide), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));+ register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace driven by field expressions (math, noise, attributes; also a {"field":expr} selection rule), and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));+ register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel, uv_unwrap, subdivide, set_position, displace), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);diff --git a/skills/build-67js-scene/references/mesh-modeling.md b/skills/build-67js-scene/references/mesh-modeling.mdindex add1d7d4..f4f881b8 100644--- a/skills/build-67js-scene/references/mesh-modeling.md+++ b/skills/build-67js-scene/references/mesh-modeling.md@@ -197,6 +197,46 @@ bounds and rescale the node.] }```+## Fields: noise, gradients and repeats++A field expression is a small JSON formula over each vertex or face. `displace` and `set_position` take one, and+`{ "field": expression }` selects faces by one. The formula is plain JSON, so write it as data and never as code.+Use `{"attr":"position","component":"y"}` for a coordinate, `{"noise":{"scale":3,"seed":7}}` for smooth noise in 0 to+1 (use `midlevel: 0.5` so it pushes both ways), and `mul`, `add`, `clamp`, `gt` and `if` to shape it. Full list in+`docs/mesh.md#field-expressions`; the limits are 64 nodes and depth 12.++A lumpy boulder from one expression (a sphere keeps its topology, so it stays closed):++```json+{ "id": "boulder", "type": "mesh", "base": { "type": "sphere", "segments": 24, "rings": 12 }, "edits": [+ { "op": "displace", "field": { "noise": { "scale": 2, "seed": 3, "octaves": 2 } }, "strength": 0.5 }+] }+```++Taper a box into a tower by scaling x and z with height, then inset the top face, picked by a field on its normal:++```json+{ "id": "tower", "type": "mesh", "base": { "type": "box", "bevel": 0 }, "edits": [+ { "op": "set_position", "position": { "vec": [+ { "mul": [{ "attr": "position", "component": "x" }, { "sub": [1, { "mul": [0.5, { "add": [{ "attr": "position", "component": "y" }, 0.5] }] }] }] },+ { "attr": "position", "component": "y" },+ { "mul": [{ "attr": "position", "component": "z" }, { "sub": [1, { "mul": [0.5, { "add": [{ "attr": "position", "component": "y" }, 0.5] }] }] }] }+ ] } },+ { "op": "inset_region", "select": { "field": { "gt": [{ "dot": [{ "attr": "normal" }, [0, 1, 0]] }, 0.9] } }, "thickness": 0.05, "name": "top" }+] }+```++Do not model fifteen pillars: repeat one. Put `instances` on the node, with a `grid`, a `scatter` or a `surface`+source, a `seed`, and an optional `where` field. A node's scale applies to the grid spacing, so scale the group to the+size of one pillar and give the spacing in pillar units:++```text+{ "id": "court", "geometry": "pillar", "material": "stone", "translation": [0, 0.25, 0], "scale": [0.1, 0.5, 0.1],+ "instances": { "grid": { "counts": [5, 1, 3], "spacing": [4, 1, 5] } } }+```++That gives 15 pillars 0.4 m by 0.5 m apart, drawn as one batch. `instances` goes in the recipe given to `scene_create`.+## Cutting and repairingUse these when a part has a hole, needs an opening or has too many faces. Each names what it makes with `<name>.<tag>`.diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 09462f2c..4a6d9717 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -1,4 +1,7 @@-import { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-operations.js';+import {+ MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES,+ FIELD_OPERATOR_NAMES, FIELD_ATTRIBUTES, MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES,+} from './mesh-operations.js';// What agent scenes support and their default limits, as plain data. The MCP server reads these without bundling// the scene engine (geometry, three.js decoders, the mesh core), which runs in the preview page instead.@@ -20,6 +23,11 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),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 }),+ fieldExpressions: Object.freeze({+ operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,+ maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxElements: MAX_FIELD_ELEMENTS,+ }),+ instancing: Object.freeze({ sources: INSTANCE_SOURCES, maxCandidatePoints: MAX_INSTANCE_CANDIDATES }),operations: Object.freeze(['set-node', 'set-material', 'set-camera', 'add-node', 'remove-node','add-geometry', 'remove-geometry', 'add-material', 'remove-material',diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 5280641f..327e724b 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -7,6 +7,7 @@ import { normalizeAgentLook } from './agent-look.js';import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';+import { expandInstancedNodes } from './mesh-instances.js';import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };@@ -495,6 +496,14 @@ function normalizeRecipe(input, limits) {if (distinctPatterns.size > MAX_MATERIAL_PATTERNS) {throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse a pattern and tint it with color.`);}+ recipe.nodes = expandInstancedNodes(recipe.nodes, {+ maxNodes: limits.maxNodes,+ resolveSurface: id => {+ const definition = recipe.geometries.find(geometry => geometry.id === id);+ if (!definition) throw new RangeError(`Instances surface geometry ${JSON.stringify(id.slice(0, 48))} is not in geometries.`);+ return generateGeometry(definition, Math.min(limits.maxVertices, 1_000_000));+ },+ });recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);recipe.camera = cameraFrom(recipe.camera);const look = {};diff --git a/src/mesh-field-edits.js b/src/mesh-field-edits.jsnew file mode 100644index 00000000..a4942802--- /dev/null+++ b/src/mesh-field-edits.js@@ -0,0 +1,78 @@+import { createMeshData } from './mesh-data.js';+import { evaluateField, meshFieldContext } from './mesh-fields.js';+import { vertexNormals } from './mesh-normals.js';+import { selectFaces } from './mesh-select.js';++// Edits driven by field expressions (see mesh-fields.js). Every expression is evaluated on the input positions+// before anything moves, so the result does not depend on vertex order.++export const DISPLACE_DIRECTIONS = Object.freeze(['normal', 'x', 'y', 'z']);+const AXIS_DIRECTIONS = new Map([['x', [1, 0, 0]], ['y', [0, 1, 0]], ['z', [0, 0, 1]]]);++function withPositions(mesh, positions) {+ return createMeshData({+ positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes: mesh.attributes,+ });+}++/** One flag per vertex: set when the vertex belongs to a face the rule selects. Without a rule, every vertex. */+function selectedVertices(mesh, rule) {+ const flags = new Uint8Array(mesh.vertexCount);+ if (!rule) {+ flags.fill(1);+ return flags;+ }+ const faceMask = selectFaces(mesh, rule);+ for (let face = 0; face < mesh.faceCount; face++) {+ if (!faceMask[face]) continue;+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) flags[mesh.cornerVertices[corner]] = 1;+ }+ return flags;+}++/**+ * Blender's Set Position: `position` (a vector expression, default the current position) and then `offset` (a vector+ * expression added to it) for the vertices of the selected faces.+ */+export function setPosition(mesh, { select, position, offset }) {+ const context = meshFieldContext(mesh, 'point');+ const target = position === undefined ? null : evaluateField(position, context, { kind: 'vector' }).values;+ const shift = offset === undefined ? null : evaluateField(offset, context, { kind: 'vector' }).values;+ const flags = selectedVertices(mesh, select);+ const positions = new Float32Array(mesh.positions);+ let movedVertices = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!flags[vertex]) continue;+ movedVertices++;+ for (let axis = 0; axis < 3; axis++) {+ const base = target ? target[vertex * 3 + axis] : mesh.positions[vertex * 3 + axis];+ positions[vertex * 3 + axis] = base + (shift ? shift[vertex * 3 + axis] : 0);+ }+ }+ return { mesh: withPositions(mesh, positions), movedVertices };+}++/**+ * Blender's Displace modifier with a field as the texture: each vertex of the selected faces moves by+ * (field - midlevel) * strength along its normal or an axis.+ */+export function displaceMesh(mesh, { select, field, strength = 1, midlevel = 0.5, direction = 'normal' }) {+ const context = meshFieldContext(mesh, 'point');+ const { values } = evaluateField(field, context, { kind: 'scalar' });+ const normals = direction === 'normal' ? vertexNormals(mesh) : null;+ const axis = AXIS_DIRECTIONS.get(direction);+ const flags = selectedVertices(mesh, select);+ const positions = new Float32Array(mesh.positions);+ let movedVertices = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!flags[vertex]) continue;+ movedVertices++;+ const distance = (values[vertex] - midlevel) * strength;+ for (let component = 0; component < 3; component++) {+ const along = normals ? normals[vertex * 3 + component] : axis[component];+ positions[vertex * 3 + component] += distance * along;+ }+ }+ return { mesh: withPositions(mesh, positions), movedVertices };+}diff --git a/src/mesh-fields.js b/src/mesh-fields.jsnew file mode 100644index 00000000..a5f074e5--- /dev/null+++ b/src/mesh-fields.js@@ -0,0 +1,513 @@+import { TAG_PREFIX, meshTags } from './mesh-data.js';+import { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK, FIELD_ATTRIBUTES } from './mesh-operations.js';+import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';++// Bounded field expressions: a small JSON language that computes one value per mesh element (a number, or a vector+// of three numbers) from attributes, noise and math. Agents may be following instructions injected into their input,+// so an expression is data and never code: it is read by walking plain objects against a fixed table of operators,+// compiled once into closures over typed arrays, and checked against its limits before anything is evaluated.+// No string is ever executed or used as a property name: operators come from a Map, and the only other strings+// allowed are the attribute names listed below and tag names, which are matched against existing tags.+//+// { "mul": [{ "attr": "position", "component": "y" }, 0.5] }+// { "noise": { "scale": 3, "seed": 7 } }+// { "gt": [{ "dot": [{ "attr": "normal" }, [0, 1, 0]] }, 0.9] }+//+// A number is a constant, true and false are 1 and 0, and an array of three numbers is a constant vector.+// Scalar operators accept vectors and work on each component, with a scalar spread to all three.++const MAX_LITERAL = 1e6;+const MAX_NOISE_OCTAVES = 4;+const MAX_NOISE_SCALE = 1000;+const MAX_SEED = 0x7fffffff;+const MAX_REPORTED_KEY_LENGTH = 24;+const TAG_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;+const KIND_NAMES = Object.freeze({ scalar: 'number', vector: 'vector' });+const COMPONENTS = Object.freeze({ x: 0, y: 1, z: 2 });++function fieldError(message) {+ return new TypeError(`Field expression: ${message}`);+}++function describeKey(key) {+ const clipped = key.length > MAX_REPORTED_KEY_LENGTH ? `${key.slice(0, MAX_REPORTED_KEY_LENGTH)}...` : key;+ return JSON.stringify(clipped);+}++// ---------------------------------------------------------------------------------------------------------------+// Hashing and noise. Integer hashing keeps results identical on every platform.++function hashCell(cellX, cellY, cellZ, seed) {+ let hash = Math.imul(cellX, 0x27d4eb2d) ^ Math.imul(cellY, 0x165667b1) ^ Math.imul(cellZ, 0x85ebca77) ^ Math.imul(seed, 0x9e3779b1);+ hash = Math.imul(hash ^ (hash >>> 15), 0x85ebca6b);+ hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);+ return ((hash ^ (hash >>> 16)) >>> 0) / 4294967296;+}++function fade(fraction) {+ return fraction * fraction * fraction * (fraction * (fraction * 6 - 15) + 10);+}++function interpolate(start, end, fraction) {+ return start + (end - start) * fraction;+}++/** Smooth value noise in 0 to 1. */+export function valueNoise(x, y, z, seed) {+ const cellX = Math.floor(x);+ const cellY = Math.floor(y);+ const cellZ = Math.floor(z);+ const fractionX = fade(x - cellX);+ const fractionY = fade(y - cellY);+ const fractionZ = fade(z - cellZ);+ const corner = (offsetX, offsetY, offsetZ) => hashCell(cellX + offsetX, cellY + offsetY, cellZ + offsetZ, seed);+ const nearY0 = interpolate(interpolate(corner(0, 0, 0), corner(1, 0, 0), fractionX), interpolate(corner(0, 1, 0), corner(1, 1, 0), fractionX), fractionY);+ const nearY1 = interpolate(interpolate(corner(0, 0, 1), corner(1, 0, 1), fractionX), interpolate(corner(0, 1, 1), corner(1, 1, 1), fractionX), fractionY);+ return interpolate(nearY0, nearY1, fractionZ);+}++/** Per-element random number in 0 to 1 from a whole-number key and a seed. */+export function seededRandom(key, channel, seed) {+ return hashCell(key, channel, 0, seed);+}++function fractalNoise(x, y, z, seed, octaves) {+ let total = 0;+ let amplitude = 1;+ let amplitudeSum = 0;+ let frequency = 1;+ for (let octave = 0; octave < octaves; octave++) {+ total += valueNoise(x * frequency, y * frequency, z * frequency, seed + octave) * amplitude;+ amplitudeSum += amplitude;+ amplitude *= 0.5;+ frequency *= 2;+ }+ return total / amplitudeSum;+}++// ---------------------------------------------------------------------------------------------------------------+// Compiled values: { kind: 'scalar', evaluate(index) } or { kind: 'vector', parts: [evaluateX, evaluateY, evaluateZ] }.++const scalarValue = evaluate => ({ kind: 'scalar', evaluate });+const vectorValue = (partX, partY, partZ) => ({ kind: 'vector', parts: [partX, partY, partZ] });+const constantScalar = number => scalarValue(() => number);++function partsOf(value) {+ return value.kind === 'vector' ? value.parts : [value.evaluate, value.evaluate, value.evaluate];+}++function requireScalar(value, label) {+ if (value.kind !== 'scalar') throw fieldError(`${label} needs a number, not a vector.`);+ return value.evaluate;+}++function requireVector(value, label) {+ if (value.kind !== 'vector') throw fieldError(`${label} needs a vector.`);+ return value.parts;+}++function liftUnary(compute) {+ return ([operand]) => {+ if (operand.kind === 'scalar') return scalarValue(index => compute(operand.evaluate(index)));+ const [partX, partY, partZ] = operand.parts;+ return vectorValue(index => compute(partX(index)), index => compute(partY(index)), index => compute(partZ(index)));+ };+}++function liftBinary(compute) {+ return ([left, right]) => {+ if (left.kind === 'scalar' && right.kind === 'scalar') {+ return scalarValue(index => compute(left.evaluate(index), right.evaluate(index)));+ }+ const [leftX, leftY, leftZ] = partsOf(left);+ const [rightX, rightY, rightZ] = partsOf(right);+ return vectorValue(+ index => compute(leftX(index), rightX(index)),+ index => compute(leftY(index), rightY(index)),+ index => compute(leftZ(index), rightZ(index)),+ );+ };+}++function liftTernary(compute) {+ return ([first, second, third]) => {+ if (first.kind === 'scalar' && second.kind === 'scalar' && third.kind === 'scalar') {+ return scalarValue(index => compute(first.evaluate(index), second.evaluate(index), third.evaluate(index)));+ }+ const [firstX, firstY, firstZ] = partsOf(first);+ const [secondX, secondY, secondZ] = partsOf(second);+ const [thirdX, thirdY, thirdZ] = partsOf(third);+ return vectorValue(+ index => compute(firstX(index), secondX(index), thirdX(index)),+ index => compute(firstY(index), secondY(index), thirdY(index)),+ index => compute(firstZ(index), secondZ(index), thirdZ(index)),+ );+ };+}++function foldBinary(compute) {+ const combine = liftBinary(compute);+ return args => args.slice(1).reduce((total, next) => combine([total, next]), args[0]);+}++function finiteOrZero(number) {+ return Number.isFinite(number) ? number : 0;+}++function smoothstep(edgeStart, edgeEnd, input) {+ if (edgeStart === edgeEnd) return input < edgeStart ? 0 : 1;+ const fraction = Math.min(1, Math.max(0, (input - edgeStart) / (edgeEnd - edgeStart)));+ return fraction * fraction * (3 - 2 * fraction);+}++function compareScalars(compute) {+ return ([left, right]) => {+ const leftEvaluate = requireScalar(left, 'a comparison');+ const rightEvaluate = requireScalar(right, 'a comparison');+ return scalarValue(index => (compute(leftEvaluate(index), rightEvaluate(index)) ? 1 : 0));+ };+}++function combineLogic(isAnd) {+ return args => {+ const evaluators = args.map(argument => requireScalar(argument, 'a logic operator'));+ return scalarValue(index => {+ for (const evaluate of evaluators) {+ const truthy = evaluate(index) !== 0;+ if (isAnd && !truthy) return 0;+ if (!isAnd && truthy) return 1;+ }+ return isAnd ? 1 : 0;+ });+ };+}++function dotValues([left, right]) {+ const [leftX, leftY, leftZ] = requireVector(left, 'dot');+ const [rightX, rightY, rightZ] = requireVector(right, 'dot');+ return scalarValue(index => leftX(index) * rightX(index) + leftY(index) * rightY(index) + leftZ(index) * rightZ(index));+}++function crossValues([left, right]) {+ const [leftX, leftY, leftZ] = requireVector(left, 'cross');+ const [rightX, rightY, rightZ] = requireVector(right, 'cross');+ return vectorValue(+ index => leftY(index) * rightZ(index) - leftZ(index) * rightY(index),+ index => leftZ(index) * rightX(index) - leftX(index) * rightZ(index),+ index => leftX(index) * rightY(index) - leftY(index) * rightX(index),+ );+}++function lengthValue([operand]) {+ const [partX, partY, partZ] = requireVector(operand, 'length');+ return scalarValue(index => Math.hypot(partX(index), partY(index), partZ(index)));+}++function distanceValues([left, right]) {+ const [leftX, leftY, leftZ] = requireVector(left, 'distance');+ const [rightX, rightY, rightZ] = requireVector(right, 'distance');+ return scalarValue(index => Math.hypot(leftX(index) - rightX(index), leftY(index) - rightY(index), leftZ(index) - rightZ(index)));+}++function normalizeValue([operand]) {+ const [partX, partY, partZ] = requireVector(operand, 'normalize');+ const lengthAt = index => Math.hypot(partX(index), partY(index), partZ(index));+ const scaled = part => index => {+ const length = lengthAt(index);+ return length === 0 ? 0 : part(index) / length;+ };+ return vectorValue(scaled(partX), scaled(partY), scaled(partZ));+}++function buildVector([partX, partY, partZ]) {+ return vectorValue(+ requireScalar(partX, 'vec'),+ requireScalar(partY, 'vec'),+ requireScalar(partZ, 'vec'),+ );+}++function selectComponent(componentIndex) {+ return ([operand]) => scalarValue(requireVector(operand, 'a component read')[componentIndex]);+}++function branch([condition, whenTrue, whenFalse]) {+ const test = requireScalar(condition, 'if');+ const [trueX, trueY, trueZ] = partsOf(whenTrue);+ const [falseX, falseY, falseZ] = partsOf(whenFalse);+ if (whenTrue.kind === 'scalar' && whenFalse.kind === 'scalar') {+ return scalarValue(index => (test(index) !== 0 ? trueX(index) : falseX(index)));+ }+ return vectorValue(+ index => (test(index) !== 0 ? trueX(index) : falseX(index)),+ index => (test(index) !== 0 ? trueY(index) : falseY(index)),+ index => (test(index) !== 0 ? trueZ(index) : falseZ(index)),+ );+}++// name -> { arguments: 'list' with min and max, or 'single', build(compiledArguments) }.+// Operators live in a Map so that input keys such as "__proto__" or "constructor" are plain unknown names.+const LIST = 'list';+const SINGLE = 'single';+const OPERATORS = new Map([+ ['add', { form: LIST, min: 2, max: 8, build: foldBinary((left, right) => left + right) }],+ ['mul', { form: LIST, min: 2, max: 8, build: foldBinary((left, right) => left * right) }],+ ['min', { form: LIST, min: 2, max: 8, build: foldBinary(Math.min) }],+ ['max', { form: LIST, min: 2, max: 8, build: foldBinary(Math.max) }],+ ['sub', { form: LIST, min: 2, max: 2, build: liftBinary((left, right) => left - right) }],+ ['div', { form: LIST, min: 2, max: 2, build: liftBinary((left, right) => (right === 0 ? 0 : left / right)) }],+ ['mod', { form: LIST, min: 2, max: 2, build: liftBinary((left, right) => (right === 0 ? 0 : left - right * Math.floor(left / right))) }],+ ['pow', { form: LIST, min: 2, max: 2, build: liftBinary((base, exponent) => finiteOrZero(Math.pow(base, exponent))) }],+ ['clamp', { form: LIST, min: 3, max: 3, build: liftTernary((input, low, high) => Math.min(high, Math.max(low, input))) }],+ ['mix', { form: LIST, min: 3, max: 3, build: liftTernary((start, end, fraction) => start + (end - start) * fraction) }],+ ['smoothstep', { form: LIST, min: 3, max: 3, build: liftTernary(smoothstep) }],+ ['neg', { form: SINGLE, build: liftUnary(number => -number) }],+ ['abs', { form: SINGLE, build: liftUnary(Math.abs) }],+ ['sqrt', { form: SINGLE, build: liftUnary(number => (number < 0 ? 0 : Math.sqrt(number))) }],+ ['sin', { form: SINGLE, build: liftUnary(Math.sin) }],+ ['cos', { form: SINGLE, build: liftUnary(Math.cos) }],+ ['floor', { form: SINGLE, build: liftUnary(Math.floor) }],+ ['ceil', { form: SINGLE, build: liftUnary(Math.ceil) }],+ ['round', { form: SINGLE, build: liftUnary(Math.round) }],+ ['fract', { form: SINGLE, build: liftUnary(number => number - Math.floor(number)) }],+ ['sign', { form: SINGLE, build: liftUnary(Math.sign) }],+ ['lt', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left < right) }],+ ['lte', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left <= right) }],+ ['gt', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left > right) }],+ ['gte', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left >= right) }],+ ['eq', { form: LIST, min: 2, max: 2, build: compareScalars((left, right) => left === right) }],+ ['and', { form: LIST, min: 2, max: 8, build: combineLogic(true) }],+ ['or', { form: LIST, min: 2, max: 8, build: combineLogic(false) }],+ ['not', { form: SINGLE, build: ([operand]) => {+ const evaluate = requireScalar(operand, 'not');+ return scalarValue(index => (evaluate(index) === 0 ? 1 : 0));+ } }],+ ['if', { form: LIST, min: 3, max: 3, build: branch }],+ ['vec', { form: LIST, min: 3, max: 3, build: buildVector }],+ ['dot', { form: LIST, min: 2, max: 2, build: dotValues }],+ ['cross', { form: LIST, min: 2, max: 2, build: crossValues }],+ ['distance', { form: LIST, min: 2, max: 2, build: distanceValues }],+ ['length', { form: SINGLE, build: lengthValue }],+ ['normalize', { form: SINGLE, build: normalizeValue }],+ ['x', { form: SINGLE, build: selectComponent(0) }],+ ['y', { form: SINGLE, build: selectComponent(1) }],+ ['z', { form: SINGLE, build: selectComponent(2) }],+]);++export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };+const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random']);+export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);++// ---------------------------------------------------------------------------------------------------------------+// Compiling an expression against an element context: { count, positions(), normals(), tag(name) }.++function isPlainObject(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const prototype = Object.getPrototypeOf(value);+ return prototype === Object.prototype || prototype === null;+}++function integerInRange(value, minimum, maximum, label) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) throw fieldError(`${label} must be an integer from ${minimum} to ${maximum}.`);+ return value;+}++function onlyKeys(node, allowed, label) {+ for (const key of Object.keys(node)) {+ if (!allowed.includes(key)) throw fieldError(`${label} does not take ${describeKey(key)}; fields: ${allowed.join(', ')}.`);+ }+}++function compileAttribute(node, context) {+ onlyKeys(node, ['attr', 'component', 'name'], 'attr');+ if (typeof node.attr !== 'string' || !FIELD_ATTRIBUTES.includes(node.attr)) throw fieldError(`attr must be one of ${FIELD_ATTRIBUTES.join(', ')}.`);+ if (node.attr === 'index') {+ if (node.component !== undefined || node.name !== undefined) throw fieldError('index takes no component or name.');+ return scalarValue(index => index);+ }+ if (node.attr === 'tag') {+ if (typeof node.name !== 'string' || !TAG_NAME_PATTERN.test(node.name) || node.component !== undefined) {+ throw fieldError('tag needs a name of 1 to 48 letters, digits, dots, dashes or underscores.');+ }+ const values = context.tag(node.name);+ return scalarValue(index => values[index]);+ }+ if (node.name !== undefined) throw fieldError(`${node.attr} takes no name.`);+ const data = node.attr === 'position' ? context.positions() : context.normals();+ if (node.component === undefined) {+ return vectorValue(index => data[index * 3], index => data[index * 3 + 1], index => data[index * 3 + 2]);+ }+ if (typeof node.component !== 'string' || !Object.hasOwn(COMPONENTS, node.component)) throw fieldError('component must be x, y or z.');+ const offset = COMPONENTS[node.component];+ return scalarValue(index => data[index * 3 + offset]);+}++function compileNoise(node, state, depth) {+ const settings = node.noise;+ if (!isPlainObject(settings) || Object.keys(node).length !== 1) throw fieldError('noise takes { scale, seed, octaves, at }.');+ onlyKeys(settings, ['scale', 'seed', 'octaves', 'at'], 'noise');+ const scale = settings.scale ?? 1;+ if (typeof scale !== 'number' || !(scale > 0) || scale > MAX_NOISE_SCALE) throw fieldError(`noise scale must be above 0 and at most ${MAX_NOISE_SCALE}.`);+ const seed = integerInRange(settings.seed ?? 0, 0, MAX_SEED, 'noise seed');+ const octaves = integerInRange(settings.octaves ?? 1, 1, MAX_NOISE_OCTAVES, 'noise octaves');+ const at = settings.at === undefined ? compileAttribute({ attr: 'position' }, state.context) : compileNode(settings.at, state, depth + 1);+ const [partX, partY, partZ] = requireVector(at, 'noise "at"');+ return scalarValue(index => fractalNoise(partX(index) * scale, partY(index) * scale, partZ(index) * scale, seed, octaves));+}++function compileRandom(node) {+ const settings = node.random;+ if (!isPlainObject(settings) || Object.keys(node).length !== 1) throw fieldError('random takes { seed }.');+ onlyKeys(settings, ['seed'], 'random');+ const seed = integerInRange(settings.seed ?? 0, 0, MAX_SEED, 'random seed');+ return scalarValue(index => seededRandom(index, 0, seed));+}++function compileOperator(operator, name, operand, state, depth) {+ let compiledArguments;+ if (operator.form === SINGLE) {+ compiledArguments = [compileNode(operand, state, depth + 1)];+ } else {+ if (!Array.isArray(operand) || operand.length < operator.min || operand.length > operator.max) {+ throw fieldError(`${name} needs ${operator.min === operator.max ? operator.min : `${operator.min} to ${operator.max}`} arguments in an array.`);+ }+ compiledArguments = operand.map(argument => compileNode(argument, state, depth + 1));+ }+ return operator.build(compiledArguments);+}++function compileNode(node, state, depth) {+ state.nodeCount++;+ if (state.nodeCount > MAX_FIELD_NODES) throw fieldError(`more than ${MAX_FIELD_NODES} nodes.`);+ if (depth > MAX_FIELD_DEPTH) throw fieldError(`nesting deeper than ${MAX_FIELD_DEPTH}.`);+ if (typeof node === 'number') {+ if (!Number.isFinite(node) || Math.abs(node) > MAX_LITERAL) throw fieldError(`numbers must be finite and within ${MAX_LITERAL}.`);+ return constantScalar(node);+ }+ if (typeof node === 'boolean') return constantScalar(node ? 1 : 0);+ if (Array.isArray(node)) {+ if (node.length !== 3 || !node.every(component => typeof component === 'number' && Number.isFinite(component) && Math.abs(component) <= MAX_LITERAL)) {+ throw fieldError('a vector literal is three finite numbers; build one from expressions with "vec".');+ }+ const [literalX, literalY, literalZ] = node;+ return vectorValue(() => literalX, () => literalY, () => literalZ);+ }+ if (!isPlainObject(node)) throw fieldError('each node is a number, a boolean, a vector of three numbers or an object with one operator.');+ const keys = Object.keys(node);+ if (Object.hasOwn(node, 'attr')) return compileAttribute(node, state.context);+ if (keys.length !== 1) throw fieldError(`a node holds exactly one operator; got ${keys.length}.`);+ const name = keys[0];+ if (name === 'noise') return compileNoise(node, state, depth);+ if (name === 'random') return compileRandom(node);+ const operator = OPERATORS.get(name);+ if (!operator) throw fieldError(`unknown operator ${describeKey(name)}. Use one of ${FIELD_OPERATORS.join(', ')}.`);+ return compileOperator(operator, name, node[name], state, depth);+}++/**+ * Compile an expression against a context. The context is { count, positions(), normals(), tag(name) }, or null to+ * only validate. Limits on nodes, depth and elements are enforced here, before any element is evaluated.+ * Returns { kind, nodeCount, evaluate(index), parts }.+ */+export function compileField(expression, context = null) {+ const state = { nodeCount: 0, context: context ?? VALIDATION_CONTEXT };+ const compiled = compileNode(expression, state, 0);+ if (context) {+ if (context.count > MAX_FIELD_ELEMENTS) throw new RangeError(`Field expression: ${context.count} elements is over the limit of ${MAX_FIELD_ELEMENTS}.`);+ if (context.count * state.nodeCount > MAX_FIELD_WORK) throw new RangeError(`Field expression: ${state.nodeCount} nodes over ${context.count} elements is over the work limit of ${MAX_FIELD_WORK}.`);+ }+ return { ...compiled, nodeCount: state.nodeCount };+}++/** Check an expression without a mesh and say whether it is a number or a vector. Throws a TypeError naming the problem. */+export function validateField(expression, { kind } = {}) {+ const compiled = compileField(expression);+ if (kind && compiled.kind !== kind) throw fieldError(`expected a ${KIND_NAMES[kind]} expression, got a ${KIND_NAMES[compiled.kind]}.`);+ return compiled.kind;+}++const EMPTY = new Float64Array(0);+const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY });++function finiteValues(source, count, width) {+ const values = new Float64Array(count * width);+ for (let index = 0; index < values.length; index++) values[index] = finiteOrZero(source[index]);+ return values;+}++// ---------------------------------------------------------------------------------------------------------------+// Contexts: the elements an expression runs over.++/** A mesh domain: "point" (one element per vertex) or "face" (one per face). Face values average from points and back. */+export function meshFieldContext(mesh, domain) {+ if (domain !== 'point' && domain !== 'face') throw fieldError('domain must be point or face.');+ const isPoint = domain === 'point';+ const cache = {};+ return {+ count: isPoint ? mesh.vertexCount : mesh.faceCount,+ positions: () => (cache.positions ??= isPoint ? mesh.positions : faceCentroids(mesh)),+ normals: () => (cache.normals ??= isPoint ? vertexNormals(mesh) : faceNormals(mesh).normals),+ tag: name => {+ const attribute = mesh.attributes.face[TAG_PREFIX + name];+ if (!attribute) throw new RangeError(`Unknown tag ${name}. Known tags: ${meshTags(mesh).join(', ') || 'none'}.`);+ return isPoint ? pointTagAverage(mesh, attribute.data) : attribute.data;+ },+ };+}++function pointTagAverage(mesh, faceValues) {+ const sums = new Float64Array(mesh.vertexCount);+ const counts = new Uint32Array(mesh.vertexCount);+ for (let face = 0; face < mesh.faceCount; face++) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ const vertex = mesh.cornerVertices[corner];+ sums[vertex] += faceValues[face];+ counts[vertex]++;+ }+ }+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) sums[vertex] = counts[vertex] ? sums[vertex] / counts[vertex] : 0;+ return sums;+}++/** A free point set (instance candidates): positions and optional normals, flat arrays of three numbers per point. */+export function pointSetContext(positions, normals) {+ return {+ count: positions.length / 3,+ positions: () => positions,+ normals: () => normals,+ tag: name => {+ throw new RangeError(`Unknown tag ${name}. Point sets carry no tags.`);+ },+ };+}++/**+ * Evaluate an expression over a context. Returns Float64Array: one number per element for a number expression,+ * three per element (x, y, z interleaved) for a vector expression. Non-finite results become 0.+ */+export function evaluateField(expression, context, { kind } = {}) {+ const compiled = compileField(expression, context);+ if (kind && compiled.kind !== kind) throw fieldError(`expected a ${KIND_NAMES[kind]} expression, got a ${KIND_NAMES[compiled.kind]}.`);+ const count = context.count;+ if (compiled.kind === 'scalar') {+ const values = new Float64Array(count);+ for (let index = 0; index < count; index++) values[index] = compiled.evaluate(index);+ return { kind: compiled.kind, values: finiteValues(values, count, 1), nodeCount: compiled.nodeCount };+ }+ const [partX, partY, partZ] = compiled.parts;+ const values = new Float64Array(count * 3);+ for (let index = 0; index < count; index++) {+ values[index * 3] = partX(index);+ values[index * 3 + 1] = partY(index);+ values[index * 3 + 2] = partZ(index);+ }+ return { kind: compiled.kind, values: finiteValues(values, count, 3), nodeCount: compiled.nodeCount };+}++/** Faces for which a number expression is nonzero, as a Uint8Array mask (the "field" selection rule). */+export function fieldFaceMask(mesh, expression) {+ const { values } = evaluateField(expression, meshFieldContext(mesh, 'face'), { kind: 'scalar' });+ const mask = new Uint8Array(mesh.faceCount);+ for (let face = 0; face < mesh.faceCount; face++) mask[face] = values[face] !== 0 ? 1 : 0;+ return mask;+}diff --git a/src/mesh-instances.js b/src/mesh-instances.jsnew file mode 100644index 00000000..94d4de69--- /dev/null+++ b/src/mesh-instances.js@@ -0,0 +1,234 @@+import { quat } from 'gl-matrix';+import { INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES } from './mesh-operations.js';+import { evaluateField, pointSetContext, seededRandom } from './mesh-fields.js';++// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all+// sharing the node's geometry and material, so the renderer draws them in one instanced call. Points come from a+// grid, a seeded scatter in a box, or the surface of a geometry. Placement is deterministic from the seed, and a+// bounded count is checked before any point is made.+//+// { "id": "grass", "geometry": "blade", "material": "green", "parent": "ground",+// "instances": { "surface": { "geometry": "ground-shape", "count": 300 }, "seed": 3,+// "where": { "gt": [{ "attr": "position", "component": "x" }, 0] },+// "yaw": true, "alignToNormal": false, "scale": [0.7, 1.3] } }+//+// Points are in the group's own space: the group takes the node's translation, rotation and scale, and its parent.+// Put the group under the node that carries the surface geometry to place instances on that node's surface.++export { MAX_INSTANCE_CANDIDATES };+const MAX_COORDINATE = 1e6;+const SOURCES = INSTANCE_SOURCES;+const INSTANCE_FIELDS = Object.freeze([...SOURCES, 'seed', 'where', 'yaw', 'alignToNormal', 'scale']);+const MAX_SEED = 0x7fffffff;+const UP = Object.freeze([0, 1, 0]);++const CHANNEL_SCATTER = 20;+const CHANNEL_YAW = 10;+const CHANNEL_SCALE = 11;+const CHANNEL_SURFACE_TRIANGLE = 30;+const CHANNEL_SURFACE_U = 31;+const CHANNEL_SURFACE_V = 32;++function instanceError(message) {+ return new TypeError(`Instances: ${message}`);+}++function plainRecord(value, label, allowed) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw instanceError(`${label} must be an object.`);+ for (const key of Object.keys(value)) {+ if (!allowed.includes(key)) throw instanceError(`${label} does not take ${JSON.stringify(key.slice(0, 24))}; fields: ${allowed.join(', ')}.`);+ }+ return value;+}++function coordinates(value, label) {+ if (!Array.isArray(value) || value.length !== 3 || !value.every(entry => typeof entry === 'number' && Number.isFinite(entry) && Math.abs(entry) <= MAX_COORDINATE)) {+ throw instanceError(`${label} needs three finite numbers.`);+ }+ return value;+}++function wholeNumber(value, minimum, maximum, label) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) throw instanceError(`${label} must be an integer from ${minimum} to ${maximum}.`);+ return value;+}++function gridPoints(source) {+ plainRecord(source, 'grid', ['counts', 'spacing']);+ const counts = coordinates(source.counts, 'grid counts').map(count => wholeNumber(count, 1, MAX_INSTANCE_CANDIDATES, 'grid count'));+ const total = counts[0] * counts[1] * counts[2];+ if (total > MAX_INSTANCE_CANDIDATES) throw instanceError(`a grid of ${total} points is over the limit of ${MAX_INSTANCE_CANDIDATES}.`);+ const spacing = coordinates(source.spacing, 'grid spacing');+ const positions = new Float64Array(total * 3);+ let index = 0;+ for (let z = 0; z < counts[2]; z++) {+ for (let y = 0; y < counts[1]; y++) {+ for (let x = 0; x < counts[0]; x++) {+ positions[index * 3] = (x - (counts[0] - 1) / 2) * spacing[0];+ positions[index * 3 + 1] = (y - (counts[1] - 1) / 2) * spacing[1];+ positions[index * 3 + 2] = (z - (counts[2] - 1) / 2) * spacing[2];+ index++;+ }+ }+ }+ return { positions, normals: null };+}++function scatterPoints(source, seed) {+ plainRecord(source, 'scatter', ['count', 'min', 'max']);+ const count = wholeNumber(source.count, 1, MAX_INSTANCE_CANDIDATES, 'scatter count');+ const minimum = coordinates(source.min, 'scatter min');+ const maximum = coordinates(source.max, 'scatter max');+ const positions = new Float64Array(count * 3);+ for (let index = 0; index < count; index++) {+ for (let axis = 0; axis < 3; axis++) {+ const fraction = seededRandom(index, CHANNEL_SCATTER + axis, seed);+ positions[index * 3 + axis] = minimum[axis] + (maximum[axis] - minimum[axis]) * fraction;+ }+ }+ return { positions, normals: null };+}++function triangleAreas(geometry) {+ const triangleCount = geometry.indices.length / 3;+ const cumulative = new Float64Array(triangleCount);+ let total = 0;+ for (let triangle = 0; triangle < triangleCount; triangle++) {+ const [first, second, third] = [0, 1, 2].map(corner => geometry.indices[triangle * 3 + corner] * 3);+ const edgeOne = [0, 1, 2].map(axis => geometry.positions[second + axis] - geometry.positions[first + axis]);+ const edgeTwo = [0, 1, 2].map(axis => geometry.positions[third + axis] - geometry.positions[first + axis]);+ const area = Math.hypot(+ edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1],+ edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2],+ edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0],+ ) / 2;+ total += area;+ cumulative[triangle] = total;+ }+ return { cumulative, total };+}++function triangleAtFraction(cumulative, target) {+ let low = 0;+ let high = cumulative.length - 1;+ while (low < high) {+ const middle = (low + high) >> 1;+ if (cumulative[middle] >= target) high = middle;+ else low = middle + 1;+ }+ return low;+}++/** Points spread over the triangles of a render geometry in proportion to their area, with interpolated normals. */+export function surfacePoints(geometry, count, seed) {+ const { cumulative, total } = triangleAreas(geometry);+ if (!(total > 0)) throw instanceError('the surface geometry has no area.');+ const positions = new Float64Array(count * 3);+ const normals = new Float64Array(count * 3);+ for (let index = 0; index < count; index++) {+ const triangle = triangleAtFraction(cumulative, seededRandom(index, CHANNEL_SURFACE_TRIANGLE, seed) * total);+ const rootU = Math.sqrt(seededRandom(index, CHANNEL_SURFACE_U, seed));+ const fractionV = seededRandom(index, CHANNEL_SURFACE_V, seed);+ const weights = [1 - rootU, rootU * (1 - fractionV), rootU * fractionV];+ const corners = [0, 1, 2].map(corner => geometry.indices[triangle * 3 + corner] * 3);+ for (let axis = 0; axis < 3; axis++) {+ positions[index * 3 + axis] = corners.reduce((sum, corner, slot) => sum + geometry.positions[corner + axis] * weights[slot], 0);+ normals[index * 3 + axis] = corners.reduce((sum, corner, slot) => sum + geometry.normals[corner + axis] * weights[slot], 0);+ }+ const length = Math.hypot(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2]) || 1;+ for (let axis = 0; axis < 3; axis++) normals[index * 3 + axis] /= length;+ }+ return { positions, normals };+}++function candidatePoints(spec, seed, resolveSurface) {+ const sourceName = SOURCES.filter(name => Object.hasOwn(spec, name));+ if (sourceName.length !== 1) throw instanceError(`give exactly one point source: ${SOURCES.join(', ')}.`);+ if (sourceName[0] === 'grid') return gridPoints(spec.grid);+ if (sourceName[0] === 'scatter') return scatterPoints(spec.scatter, seed);+ const source = plainRecord(spec.surface, 'surface', ['geometry', 'count']);+ const count = wholeNumber(source.count, 1, MAX_INSTANCE_CANDIDATES, 'surface count');+ if (typeof source.geometry !== 'string') throw instanceError('surface needs a geometry id.');+ return surfacePoints(resolveSurface(source.geometry), count, seed);+}++function keptIndices(spec, points) {+ const count = points.positions.length / 3;+ const kept = [];+ if (spec.where === undefined) {+ for (let index = 0; index < count; index++) kept.push(index);+ return kept;+ }+ const normals = points.normals ?? Float64Array.from({ length: count * 3 }, (unused, position) => UP[position % 3]);+ const { values } = evaluateField(spec.where, pointSetContext(points.positions, normals), { kind: 'scalar' });+ for (let index = 0; index < count; index++) {+ if (values[index] !== 0) kept.push(index);+ }+ return kept;+}++function instanceRotation(spec, seed, candidate, normals) {+ const rotation = quat.create();+ if (spec.alignToNormal && normals) {+ const normal = [normals[candidate * 3], normals[candidate * 3 + 1], normals[candidate * 3 + 2]];+ quat.rotationTo(rotation, UP, normal);+ }+ if (spec.yaw) {+ const turn = quat.setAxisAngle(quat.create(), UP, seededRandom(candidate, CHANNEL_YAW, seed) * Math.PI * 2);+ quat.multiply(rotation, rotation, turn);+ }+ return Array.from(rotation);+}++function instanceScale(spec, seed, candidate) {+ if (spec.scale === undefined) return 1;+ return spec.scale[0] + (spec.scale[1] - spec.scale[0]) * seededRandom(candidate, CHANNEL_SCALE, seed);+}++function checkedSpec(spec) {+ plainRecord(spec, 'instances', INSTANCE_FIELDS);+ const seed = spec.seed === undefined ? 0 : wholeNumber(spec.seed, 0, MAX_SEED, 'seed');+ for (const flag of ['yaw', 'alignToNormal']) {+ if (spec[flag] !== undefined && typeof spec[flag] !== 'boolean') throw instanceError(`${flag} must be boolean.`);+ }+ if (spec.alignToNormal && !Object.hasOwn(spec, 'surface')) throw instanceError('alignToNormal needs a surface source, because only a surface has normals.');+ if (spec.scale !== undefined) {+ const range = spec.scale;+ if (!Array.isArray(range) || range.length !== 2 || !range.every(entry => typeof entry === 'number' && Number.isFinite(entry) && entry > 0 && entry <= 1000) || range[0] > range[1]) {+ throw instanceError('scale is [minimum, maximum] with 0 < minimum <= maximum <= 1000.');+ }+ }+ return seed;+}++/**+ * Replace each node that has an `instances` record with a group node and its instance children. `resolveSurface(id)`+ * returns the render geometry ({ positions, normals, indices }) for a surface source. Nodes without `instances` pass+ * through untouched.+ */+export function expandInstancedNodes(nodes, { resolveSurface, maxNodes }) {+ if (!Array.isArray(nodes)) return nodes;+ const expanded = [];+ for (const node of nodes) {+ if (!node || typeof node !== 'object' || !Object.hasOwn(node, 'instances')) {+ expanded.push(node);+ continue;+ }+ const { instances: spec, geometry, material, ...group } = node;+ if (typeof geometry !== 'string' || typeof material !== 'string') throw instanceError(`node ${JSON.stringify(String(node.id).slice(0, 48))} needs geometry and material ids to instance.`);+ const seed = checkedSpec(spec);+ const points = candidatePoints(spec, seed, resolveSurface);+ expanded.push(group);+ for (const [slot, candidate] of keptIndices(spec, points).entries()) {+ const scale = instanceScale(spec, seed, candidate);+ expanded.push({+ id: `${node.id}.${slot}`, parent: node.id, geometry, material,+ translation: [points.positions[candidate * 3], points.positions[candidate * 3 + 1], points.positions[candidate * 3 + 2]],+ rotation: instanceRotation(spec, seed, candidate, points.normals),+ scale: [scale, scale, scale],+ });+ if (expanded.length > maxNodes) throw new RangeError(`Instances expand past the limit of ${maxNodes} nodes.`);+ }+ }+ return expanded;+}diff --git a/src/mesh-normals.js b/src/mesh-normals.jsindex 003d6f30..c3d27241 100644--- a/src/mesh-normals.js+++ b/src/mesh-normals.js@@ -135,3 +135,48 @@ export function cornerNormals(mesh, { sharpAngle = Infinity } = {}) {};}+export function faceCentroids(mesh) {+ const centroids = new Float64Array(mesh.faceCount * 3);+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const vertex = mesh.cornerVertices[corner] * 3;+ centroids[face * 3] += mesh.positions[vertex];+ centroids[face * 3 + 1] += mesh.positions[vertex + 1];+ centroids[face * 3 + 2] += mesh.positions[vertex + 2];+ }+ const size = end - start;+ centroids[face * 3] /= size;+ centroids[face * 3 + 1] /= size;+ centroids[face * 3 + 2] /= size;+ }+ return centroids;+}++/** Angle-weighted vertex normals from face normals. */+export function vertexNormals(mesh) {+ const { normals } = faceNormals(mesh);+ const sums = new Float64Array(mesh.vertexCount * 3);+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const previous = mesh.cornerVertices[corner === start ? end - 1 : corner - 1] * 3;+ const current = mesh.cornerVertices[corner] * 3;+ const next = mesh.cornerVertices[corner + 1 === end ? start : corner + 1] * 3;+ const first = [0, 1, 2].map(axis => mesh.positions[previous + axis] - mesh.positions[current + axis]);+ const second = [0, 1, 2].map(axis => mesh.positions[next + axis] - mesh.positions[current + axis]);+ const lengths = Math.hypot(...first) * Math.hypot(...second);+ const angle = lengths > 0 ? Math.acos(Math.max(-1, Math.min(1, (first[0] * second[0] + first[1] * second[1] + first[2] * second[2]) / lengths))) : 0;+ for (let axis = 0; axis < 3; axis++) sums[current + axis] += normals[face * 3 + axis] * angle;+ }+ }+ const result = new Float64Array(mesh.vertexCount * 3);+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const length = Math.hypot(sums[vertex * 3], sums[vertex * 3 + 1], sums[vertex * 3 + 2]);+ if (length === 0) continue;+ for (let axis = 0; axis < 3; axis++) result[vertex * 3 + axis] = sums[vertex * 3 + axis] / length;+ }+ return result;+}diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 35b28f99..7facf2d7 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -31,7 +31,26 @@ export const MESH_EDIT_OPERATIONS = Object.freeze({subdivide_edges: { fields: ['edges', 'name', 'cuts'], tags: ['split'] },grid_fill: { fields: ['edges', 'name'], tags: ['fill'] },knife_project: { fields: ['name', 'path', 'direction'], tags: ['cut'] },+ set_position: { fields: ['select', 'position', 'offset'], tags: [] },+ displace: { fields: ['select', 'field', 'strength', 'midlevel', 'direction'], tags: [] },});-export const STACK_OPERATIONS = Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'subdivide']);+export const STACK_OPERATIONS = Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'subdivide', 'set_position', 'displace']);export const MAX_STACK_NODES = 16;++// Field expressions (mesh-fields.js) and instancing (mesh-instances.js): limits and names as plain data. A test+// keeps FIELD_OPERATOR_NAMES equal to the operators the language really has.+export const MAX_FIELD_NODES = 64;+export const MAX_FIELD_DEPTH = 12;+export const MAX_FIELD_ELEMENTS = 250_000;+export const MAX_FIELD_WORK = 8_000_000;+export const FIELD_ATTRIBUTES = Object.freeze(['position', 'normal', 'index', 'tag']);+export const FIELD_OPERATOR_NAMES = Object.freeze([+ 'add', 'mul', 'min', 'max', 'sub', 'div', 'mod', 'pow', 'clamp', 'mix', 'smoothstep',+ 'neg', 'abs', 'sqrt', 'sin', 'cos', 'floor', 'ceil', 'round', 'fract', 'sign',+ 'lt', 'lte', 'gt', 'gte', 'eq', 'and', 'or', 'not', 'if',+ 'vec', 'dot', 'cross', 'distance', 'length', 'normalize', 'x', 'y', 'z',+ 'attr', 'noise', 'random',+]);+export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface']);+export const MAX_INSTANCE_CANDIDATES = 2048;diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex f08aafb9..494603ac 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -11,6 +11,8 @@ import { bevelEdges } from './mesh-bevel.js';import { loopCut } from './mesh-loopcut.js';import { CUT_OPERATIONS, normalizeCutEdit, runCutEdit, checkCutBudget } from './mesh-cut-edits.js';import { unwrapUv } from './mesh-uv.js';+import { validateField } from './mesh-fields.js';+import { setPosition, displaceMesh, DISPLACE_DIRECTIONS } from './mesh-field-edits.js';import { subdivideMesh, subdivisionSize, MAX_SUBDIVISION_LEVELS, MAX_CREASE_SHARPNESS } from './mesh-subdivide.js';import { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-operations.js';export { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES };@@ -37,6 +39,15 @@ function vector(value, index, label) {return value.map(component => finiteNumber(component, index, label));}+function checkedField(expression, index, label, kind) {+ try {+ validateField(expression, { kind });+ } catch (error) {+ throw editError(index, `${label}: ${error.message}`);+ }+ return expression;+}+/** Validate an edit list without running it. Returns normalized copies with default names filled in. */export function normalizeMeshEdits(edits) {if (!Array.isArray(edits)) throw new TypeError('edits must be an array.');@@ -178,8 +189,20 @@ export function normalizeMeshEdits(edits) {throw editError(index, 'sharpness needs a crease rule');}break;+ case 'set_position':+ if (edit.position === undefined && edit.offset === undefined) throw editError(index, 'set_position needs a position or an offset expression');+ if (edit.position !== undefined) normalized.position = checkedField(edit.position, index, 'position', 'vector');+ if (edit.offset !== undefined) normalized.offset = checkedField(edit.offset, index, 'offset', 'vector');+ break;+ case 'displace':+ normalized.field = checkedField(edit.field, index, 'field', 'scalar');+ normalized.strength = edit.strength === undefined ? 1 : finiteNumber(edit.strength, index, 'strength');+ normalized.midlevel = edit.midlevel === undefined ? 0.5 : finiteNumber(edit.midlevel, index, 'midlevel');+ if (edit.direction !== undefined && !DISPLACE_DIRECTIONS.includes(edit.direction)) throw editError(index, `direction must be one of ${DISPLACE_DIRECTIONS.join(', ')}`);+ normalized.direction = edit.direction ?? 'normal';+ break;case 'merge_by_distance':- normalized.distance = finiteNumber(edit.distance ?? 1e-4, index, 'distance', { minimum: 0, maximum: 1e3 });+ normalized.distance =finiteNumber(edit.distance ?? 1e-4, index, 'distance', { minimum: 0, maximum: 1e3 });break;}if (CUT_OPERATIONS.includes(edit.op)) normalizeCutEdit(edit, normalized, index, { finiteNumber, vector });@@ -304,6 +327,16 @@ function runEdit(current, edit, index, { resolveCutter }) {if (Object.keys(tags).length) result.tags = tags;return { mesh: outcome.mesh, result };}+ if (edit.op === 'set_position' || edit.op === 'displace') {+ let outcome;+ try {+ outcome = edit.op === 'set_position' ? setPosition(current, edit) : displaceMesh(current, edit);+ } catch (error) {+ throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);+ }+ result.movedVertices = outcome.movedVertices;+ return { mesh: outcome.mesh, result };+ }if (edit.op === 'subdivide') {let subdivided;try {diff --git a/src/mesh-select.js b/src/mesh-select.jsindex dc31938c..b4cdce6c 100644--- a/src/mesh-select.js+++ b/src/mesh-select.js@@ -1,5 +1,6 @@import { TAG_PREFIX, meshTags } from './mesh-data.js';-import { faceNormals } from './mesh-normals.js';+import { fieldFaceMask } from './mesh-fields.js';+import { faceNormals, faceCentroids } from './mesh-normals.js';import { cornerFaces, edgeCornerTable } from './mesh-topology.js';// Semantic face selection for agents. A rule is plain JSON; the result is a Uint8Array mask with one byte per face.@@ -11,11 +12,12 @@ import { cornerFaces, edgeCornerTable } from './mesh-topology.js';// { "faces": [0, 4, 7] } explicit face indices// { "and": [rule, ...] }, { "or": [rule, ...] }, { "not": rule }// { "grow": rule, "steps": 1 } add faces sharing an edge, repeated-// { "boundary": rule } faces of the selection that touch an unselected face or an open edge+// { "field": expression } faces where a field expression (mesh-fields.js) is nonzero+// { "boundary": rule } faces of the selection that touch an unselected face or an open edgeexport const MAX_RULE_DEPTH = 16;const MAX_RULE_NODES = 256;-const RULE_KEYS = ['all', 'tag', 'normal', 'inside', 'faces', 'and', 'or', 'not', 'grow', 'boundary'];+const RULE_KEYS = ['all', 'tag', 'normal', 'inside', 'faces', 'and', 'or', 'not', 'grow', 'boundary', 'field'];function ruleError(message) {return new TypeError(`Selection rule: ${message}`);@@ -26,25 +28,6 @@ function vector3(value, label) {return value;}-function faceCentroids(mesh) {- const centroids = new Float64Array(mesh.faceCount * 3);- for (let face = 0; face < mesh.faceCount; face++) {- const start = mesh.faceOffsets[face];- const end = mesh.faceOffsets[face + 1];- for (let corner = start; corner < end; corner++) {- const vertex = mesh.cornerVertices[corner] * 3;- centroids[face * 3] += mesh.positions[vertex];- centroids[face * 3 + 1] += mesh.positions[vertex + 1];- centroids[face * 3 + 2] += mesh.positions[vertex + 2];- }- const size = end - start;- centroids[face * 3] /= size;- centroids[face * 3 + 1] /= size;- centroids[face * 3 + 2] /= size;- }- return centroids;-}-/** Faces sharing an edge with each face, as compressed rows (built lazily once per selection call). */function faceAdjacency(mesh) {const table = edgeCornerTable(mesh);@@ -173,6 +156,10 @@ export function selectFaces(mesh, rule) {}return mask;}+ case 'field': {+ if (keys.length !== 1) throw ruleError('"field" takes one expression.');+ return fieldFaceMask(mesh, node.field);+ }case 'boundary': {if (keys.length !== 1) throw ruleError('"boundary" takes one rule.');const inner = evaluate(node.boundary, depth + 1);diff --git a/src/mesh-stack.js b/src/mesh-stack.jsindex 3d0490ea..e1dfd2c4 100644--- a/src/mesh-stack.js+++ b/src/mesh-stack.js@@ -1,5 +1,5 @@import { createMeshData, deriveEdges, TAG_PREFIX, meshBounds } from './mesh-data.js';-import { faceNormals } from './mesh-normals.js';+import { faceNormals, vertexNormals } from './mesh-normals.js';import { edgeCornerTable } from './mesh-topology.js';import { mergeByDistance } from './mesh-ops.js';@@ -254,33 +254,6 @@ export function arrayMesh(mesh, { count = 2, offset = [0, 0, 0], relativeOffsetreturn result;}-/** Angle-weighted vertex normals from face normals. */-function vertexNormals(mesh) {- const { normals } = faceNormals(mesh);- const sums = new Float64Array(mesh.vertexCount * 3);- for (let face = 0; face < mesh.faceCount; face++) {- const start = mesh.faceOffsets[face];- const end = mesh.faceOffsets[face + 1];- for (let corner = start; corner < end; corner++) {- const previous = mesh.cornerVertices[corner === start ? end - 1 : corner - 1] * 3;- const current = mesh.cornerVertices[corner] * 3;- const next = mesh.cornerVertices[corner + 1 === end ? start : corner + 1] * 3;- const first = [0, 1, 2].map(axis => mesh.positions[previous + axis] - mesh.positions[current + axis]);- const second = [0, 1, 2].map(axis => mesh.positions[next + axis] - mesh.positions[current + axis]);- const lengths = Math.hypot(...first) * Math.hypot(...second);- const angle = lengths > 0 ? Math.acos(Math.max(-1, Math.min(1, (first[0] * second[0] + first[1] * second[1] + first[2] * second[2]) / lengths))) : 0;- for (let axis = 0; axis < 3; axis++) sums[current + axis] += normals[face * 3 + axis] * angle;- }- }- const result = new Float64Array(mesh.vertexCount * 3);- for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {- const length = Math.hypot(sums[vertex * 3], sums[vertex * 3 + 1], sums[vertex * 3 + 2]);- if (length === 0) continue;- for (let axis = 0; axis < 3; axis++) result[vertex * 3 + axis] = sums[vertex * 3 + axis] / length;- }- return result;-}-/*** Give a surface thickness, as Blender's Solidify (simple mode): a second shell along the vertex normals, reversed,* and rim quads along open edges. offset -1 grows inward from the surface (Blender's default), 1 outward, 0 centred.diff --git a/tests/agent-modeling-suite.test.js b/tests/agent-modeling-suite.test.jsindex b4b4a3ae..687bf13e 100644--- a/tests/agent-modeling-suite.test.js+++ b/tests/agent-modeling-suite.test.js@@ -36,6 +36,18 @@ test('checks reject objects that miss the asked-for features', async () => {assert.ok(failedKinds(await gradeRecipe(taskById('gear'), elevenTeeth)).includes('tips'));});+test('the pillar court check rejects a grid with a wrong count or spacing', async () => {+ const fourByThree = structuredClone(REFERENCES['pillar-court']);+ fourByThree.nodes[0].instances.grid.counts = [4, 1, 3];+ const missingColumn = failedKinds(await gradeRecipe(taskById('pillar-court'), fourByThree));+ assert.ok(missingColumn.includes('fifteen pillars'), missingColumn.join(', '));+ assert.ok(missingColumn.includes('size'));++ const tooTight = structuredClone(REFERENCES['pillar-court']);+ tooTight.nodes[0].instances.grid.spacing = [3, 1, 5];+ assert.ok(failedKinds(await gradeRecipe(taskById('pillar-court'), tooTight)).includes('size'));+});+test('an invalid recipe fails every check with the reason', async () => {const grade = await gradeRecipe(taskById('bolt'), { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [{ id: 'x', geometry: 'missing' }] });assert.equal(grade.passed, 0);diff --git a/tests/fixtures/blender/cases.json b/tests/fixtures/blender/cases.jsonindex e36abc68..ca208d30 100644--- a/tests/fixtures/blender/cases.json+++ b/tests/fixtures/blender/cases.json@@ -98,6 +98,11 @@{ "id": "subdivide-edges-grid-along", "input": "grid", "edit": {"op":"subdivide_edges","edges":{"along":[1,0,0]},"cuts":2} },{ "id": "grid-fill-grid-hole", "input": "grid-hole", "edit": {"op":"grid_fill","edges":{"open":{"inside":{"min":[0.9,0.9,-1],"max":[3.1,3.1,1]}}}} },{ "id": "grid-fill-cylinder-open", "input": "cylinder-open", "edit": {"op":"grid_fill","edges":{"open":{"inside":{"min":[-2,-2,0.9],"max":[2,2,1.1]}}}} },- { "id": "knife-project-cube-line", "input": "cube", "edit": {"op":"knife_project","path":[[-1,0,0],[1,0,0]],"direction":[0,0,-1]} }+ { "id": "knife-project-cube-line", "input": "cube", "edit": {"op":"knife_project","path":[[-1,0,0],[1,0,0]],"direction":[0,0,-1]} },+ { "id": "set-position-grid-shear", "input": "grid", "edit": {"op":"set_position","offset":{"vec":[{"mul":[{"attr":"position","component":"y"},0.5]},0,{"mul":[{"attr":"position","component":"x"},{"attr":"position","component":"x"}]}]}} },+ { "id": "set-position-cube-scale-sum", "input": "cube", "edit": {"op":"set_position","offset":{"vec":[{"sub":[{"attr":"position","component":"z"},{"attr":"position","component":"x"}]},{"add":[{"mul":[{"attr":"position","component":"y"},2]},0.25]},0]}} },+ { "id": "displace-cube-constant-normal", "input": "cube", "edit": {"op":"displace","field":1,"strength":0.4,"midlevel":0.5,"direction":"normal"} },+ { "id": "displace-cube-gradient-z", "input": "cube", "edit": {"op":"displace","field":{"mul":[{"add":[{"attr":"position","component":"x"},1]},0.5]},"strength":0.8,"midlevel":0.5,"direction":"z"} },+ { "id": "displace-grid-gradient-normal", "input": "grid", "edit": {"op":"displace","field":{"mul":[{"add":[{"attr":"position","component":"x"},1]},0.5]},"strength":-0.6,"midlevel":0.25,"direction":"normal"} }]}diff --git a/tests/fixtures/blender/golden.json b/tests/fixtures/blender/golden.jsonindex 6bc6db1b..31aff9b7 100644--- a/tests/fixtures/blender/golden.json+++ b/tests/fixtures/blender/golden.json@@ -22884,6 +22884,346 @@0.5]]+ },+ "set-position-grid-shear": {+ "vertexCount": 16,+ "edgeCount": 24,+ "faceCount": 9,+ "faceSizes": {+ "4": 9+ },+ "volume": 8.0,+ "area": 32.036725,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.5,+ 1.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 1.0+ ],+ [+ 1.0,+ 2.0,+ 0.0+ ],+ [+ 1.5,+ 1.0,+ 1.0+ ],+ [+ 1.5,+ 3.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 4.0+ ],+ [+ 2.0,+ 2.0,+ 1.0+ ],+ [+ 2.5,+ 1.0,+ 4.0+ ],+ [+ 2.5,+ 3.0,+ 1.0+ ],+ [+ 3.0,+ 0.0,+ 9.0+ ],+ [+ 3.0,+ 2.0,+ 4.0+ ],+ [+ 3.5,+ 1.0,+ 9.0+ ],+ [+ 3.5,+ 3.0,+ 4.0+ ],+ [+ 4.0,+ 2.0,+ 9.0+ ],+ [+ 4.5,+ 3.0,+ 9.0+ ]+ ]+ },+ "set-position-cube-scale-sum": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 0.0,+ "area": 8.485281,+ "positions": [+ [+ -0.5,+ -1.25,+ -0.5+ ],+ [+ -0.5,+ -1.25,+ -0.5+ ],+ [+ -0.5,+ 1.75,+ -0.5+ ],+ [+ -0.5,+ 1.75,+ -0.5+ ],+ [+ 0.5,+ -1.25,+ 0.5+ ],+ [+ 0.5,+ -1.25,+ 0.5+ ],+ [+ 0.5,+ 1.75,+ 0.5+ ],+ [+ 0.5,+ 1.75,+ 0.5+ ]+ ]+ },+ "displace-cube-constant-normal": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 1.865137,+ "area": 9.091281,+ "positions": [+ [+ -0.61547,+ -0.61547,+ -0.61547+ ],+ [+ -0.61547,+ -0.61547,+ 0.61547+ ],+ [+ -0.61547,+ 0.61547,+ -0.61547+ ],+ [+ -0.61547,+ 0.61547,+ 0.61547+ ],+ [+ 0.61547,+ -0.61547,+ -0.61547+ ],+ [+ 0.61547,+ -0.61547,+ 0.61547+ ],+ [+ 0.61547,+ 0.61547,+ -0.61547+ ],+ [+ 0.61547,+ 0.61547,+ 0.61547+ ]+ ]+ },+ "displace-cube-gradient-z": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 1.0,+ "area": 6.154066,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.7+ ],+ [+ -0.5,+ -0.5,+ 0.3+ ],+ [+ -0.5,+ 0.5,+ -0.7+ ],+ [+ -0.5,+ 0.5,+ 0.3+ ],+ [+ 0.5,+ -0.5,+ -0.3+ ],+ [+ 0.5,+ -0.5,+ 0.7+ ],+ [+ 0.5,+ 0.5,+ -0.3+ ],+ [+ 0.5,+ 0.5,+ 0.7+ ]+ ]+ },+ "displace-grid-gradient-normal": {+ "vertexCount": 16,+ "edgeCount": 24,+ "faceCount": 9,+ "faceSizes": {+ "4": 9+ },+ "volume": 0.45,+ "area": 9.396276,+ "positions": [+ [+ 0.0,+ 0.0,+ -0.15+ ],+ [+ 0.0,+ 1.0,+ -0.15+ ],+ [+ 0.0,+ 2.0,+ -0.15+ ],+ [+ 0.0,+ 3.0,+ -0.15+ ],+ [+ 1.0,+ 0.0,+ -0.45+ ],+ [+ 1.0,+ 1.0,+ -0.45+ ],+ [+ 1.0,+ 2.0,+ -0.45+ ],+ [+ 1.0,+ 3.0,+ -0.45+ ],+ [+ 2.0,+ 0.0,+ -0.75+ ],+ [+ 2.0,+ 1.0,+ -0.75+ ],+ [+ 2.0,+ 2.0,+ -0.75+ ],+ [+ 2.0,+ 3.0,+ -0.75+ ],+ [+ 3.0,+ 0.0,+ -1.05+ ],+ [+ 3.0,+ 1.0,+ -1.05+ ],+ [+ 3.0,+ 2.0,+ -1.05+ ],+ [+ 3.0,+ 3.0,+ -1.05+ ]+ ]}}}diff --git a/tests/mesh-fields.test.js b/tests/mesh-fields.test.jsnew file mode 100644index 00000000..971ad0a7--- /dev/null+++ b/tests/mesh-fields.test.js@@ -0,0 +1,256 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { box, sphere } from '../src/geometry.js';+import { meshFromGeometry, applyMeshEdits, evaluateMeshStack } from '../src/mesh.js';+import { createAgentScene } from '../src/agent-scene.js';+import {+ FIELD_OPERATORS, MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, compileField, evaluateField, meshFieldContext, validateField, valueNoise,+} from '../src/mesh-fields.js';+import { expandInstancedNodes, surfacePoints } from '../src/mesh-instances.js';+import { FIELD_OPERATOR_NAMES } from '../src/mesh-operations.js';++const cube = () => meshFromGeometry(box(0, 1));+const ball = () => meshFromGeometry(sphere(16, 8));++function nested(depth, leaf = 1) {+ let expression = leaf;+ for (let level = 0; level < depth; level++) expression = { abs: expression };+ return expression;+}++function bytesOf(mesh) {+ return Buffer.from(mesh.positions.buffer, mesh.positions.byteOffset, mesh.positions.byteLength).toString('hex');+}++test('hostile expressions are rejected at the boundary and nothing runs', () => {+ globalThis.fieldExpressionRan = false;+ const cyclic = { abs: null };+ cyclic.abs = cyclic;+ const hostile = [+ ['a string that looks like code', 'globalThis.fieldExpressionRan = true'],+ ['an operator that is code', { 'globalThis.fieldExpressionRan = true': [1, 2] }],+ ['a function body as an operand', { add: ['(() => { globalThis.fieldExpressionRan = true; })()', 1] }],+ ['__proto__ as an own key', JSON.parse('{"__proto__": [1, 2]}')],+ ['constructor as an operator', JSON.parse('{"constructor": {"constructor": "globalThis.fieldExpressionRan = true"}}')],+ ['toString as an operator', { toString: [1, 2] }],+ ['hasOwnProperty as an operator', { hasOwnProperty: 'x' }],+ ['attr named __proto__', { attr: '__proto__' }],+ ['attr named constructor', { attr: 'constructor' }],+ ['a component that is a prototype member', { attr: 'position', component: 'constructor' }],+ ['a component that is a prototype member of an array', { attr: 'position', component: 'length' }],+ ['a tag with a code-like name', { attr: 'tag', name: 'x; globalThis.fieldExpressionRan = true' }],+ ['a noise seed that is a string', { noise: { seed: 'globalThis.fieldExpressionRan = true' } }],+ ['a noise with an unknown key', { noise: { scale: 1, __proto__: 1, constructor: 2 } }],+ ['nesting past the depth limit', nested(MAX_FIELD_DEPTH + 1)],+ ['a thousand levels of nesting', nested(1000)],+ ['a cyclic object', cyclic],+ ['more nodes than allowed', { add: Array.from({ length: 8 }, () => ({ add: Array.from({ length: 8 }, () => ({ add: [1, 2] })) })) }],+ ['a million operands', { add: new Array(1_000_000).fill(1) }],+ ['an operand list that is a string', { add: 'abcdef' }],+ ['a noise scale of a trillion', { noise: { scale: 1e12 } }],+ ['a noise with a billion octaves', { noise: { octaves: 1e9 } }],+ ['a literal that is Infinity', { add: [Infinity, 1] }],+ ['a literal that is NaN', { add: [NaN, 1] }],+ ['a literal past the range', { add: [1e12, 1] }],+ ['null', null],+ ['undefined', undefined],+ ['a function', () => 1],+ ['an array that is not a vector', [1, 2, 3, 4]],+ ['a vector with a string', [1, 2, 'x']],+ ['two operators in one node', { add: [1, 2], mul: [1, 2] }],+ ['an object with a custom prototype', Object.create({ add: [1, 2] })],+ ];+ for (const [label, expression] of hostile) {+ assert.throws(() => validateField(expression), error => error instanceof TypeError || error instanceof RangeError, label);+ }+ assert.equal(globalThis.fieldExpressionRan, false);+ assert.equal({}.polluted, undefined);+ assert.equal(Object.prototype.hasOwnProperty.call(Object.prototype, 'fieldExpressionRan'), false);+ delete globalThis.fieldExpressionRan;+});++test('limits on elements and work are checked before any element is evaluated', () => {+ const tooMany = { count: MAX_FIELD_ELEMENTS + 1, positions: () => assert.fail('read positions'), normals: () => assert.fail('read normals'), tag: () => assert.fail('read tags') };+ assert.throws(() => compileField({ attr: 'index' }, tooMany), /elements/);+ const widest = Array.from({ length: MAX_FIELD_NODES - 1 }, () => 1);+ const manyNodes = { add: widest.slice(0, 7).map(() => ({ add: widest.slice(0, 7).map(() => ({ add: widest.slice(0, 1).concat(1) })) })) };+ assert.throws(() => validateField(manyNodes), /nodes/);+ const heavy = { count: MAX_FIELD_ELEMENTS, positions: () => new Float64Array(0), normals: () => new Float64Array(0), tag: () => new Float64Array(0) };+ const sixtyFourNodes = { add: [1, 2, 3, 4, 5, 6, 7].map(number => ({ add: [number, number, number, number, number, number, number] })) };+ assert.ok(compileField(sixtyFourNodes).nodeCount <= MAX_FIELD_NODES);+ assert.throws(() => compileField(sixtyFourNodes, heavy), /work limit/);+ assert.equal(compileField({ add: [1, { abs: 2 }] }, heavy).nodeCount, 4);+});++test('the language has no way to run code', () => {+ const source = readFileSync(new URL('../src/mesh-fields.js', import.meta.url), 'utf8');+ const forbidden = /\beval\s*\(|new\s+Function|\bFunction\s*\(|\bimport\s*\(|\brequire\s*\(|\bvm\b|\bprocess\b|\bglobalThis\b|__proto__|\.constructor\b/;+ const code = source.split('\n').filter(line => !line.trim().startsWith('//')).join('\n');+ assert.doesNotMatch(code, forbidden);+});++test('the operator list in the plain-data module matches the language', () => {+ assert.deepEqual([...FIELD_OPERATORS].sort(), [...FIELD_OPERATOR_NAMES].sort());+});++test('expressions compute attributes, math, comparison, logic and vectors', () => {+ const mesh = cube();+ const points = meshFieldContext(mesh, 'point');+ const evaluate = expression => evaluateField(expression, points).values;+ const heights = evaluate({ mul: [{ attr: 'position', component: 'y' }, 0.5] });+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) assert.equal(heights[vertex], mesh.positions[vertex * 3 + 1] * 0.5);+ assert.deepEqual(Array.from(evaluate({ attr: 'index' })), Array.from({ length: mesh.vertexCount }, (_, index) => index));+ assert.deepEqual(Array.from(evaluate({ if: [{ gt: [1, 2] }, 10, 20] }).slice(0, 2)), [20, 20]);+ assert.deepEqual(Array.from(evaluate({ div: [1, 0] }).slice(0, 2)), [0, 0], 'division by zero gives 0, not infinity');+ assert.deepEqual(Array.from(evaluateField({ add: [[1, 2, 3], 1] }, points).values.slice(0, 3)), [2, 3, 4]);+ assert.equal(evaluateField({ length: [3, 4, 0] }, points).values[0], 5);+ assert.equal(evaluateField({ and: [true, { lt: [1, 2] }, { not: 0 }] }, points).values[0], 1);+ assert.throws(() => evaluateField({ add: [{ attr: 'position' }, 1] }, points, { kind: 'scalar' }), /number expression/);+ assert.throws(() => evaluateField({ gt: [{ attr: 'position' }, 1] }, points), /number, not a vector/);+ assert.throws(() => evaluateField({ attr: 'tag', name: 'nothing' }, points), /Unknown tag nothing/);+});++test('the field selection rule picks faces from attributes', () => {+ const mesh = cube();+ const topOnly = { gt: [{ dot: [{ attr: 'normal' }, [0, 1, 0]] }, 0.9] };+ const top = applyMeshEdits(mesh, [{ op: 'delete', select: { field: topOnly } }]);+ assert.equal(top.results[0].deletedFaces, 1);+ const upperHalf = applyMeshEdits(mesh, [{ op: 'delete', select: { field: { gt: [{ attr: 'position', component: 'y' }, 0.2] } } }]);+ assert.equal(upperHalf.results[0].deletedFaces, 1);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'delete', select: { field: { attr: 'position' } } }]), /number, not a vector|number expression/);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'delete', select: { field: topOnly, tag: 'top' } }]), /one expression/);+});++test('set_position moves vertices by a field and leaves the rest alone', () => {+ const mesh = cube();+ const lifted = applyMeshEdits(mesh, [{ op: 'set_position', select: { tag: 'top' }, offset: [0, 1, 0] }]);+ assert.equal(lifted.results[0].movedVertices, 4);+ const stretched = applyMeshEdits(mesh, [{ op: 'set_position', position: { vec: [{ attr: 'position', component: 'x' }, { mul: [{ attr: 'position', component: 'y' }, 2] }, { attr: 'position', component: 'z' }] } }]).mesh;+ assert.equal(stretched.positions[1], mesh.positions[1] * 2);+ assert.equal(stretched.faceCount, mesh.faceCount);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position' }]), /position or an offset/);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position', offset: 1 }]), /vector/);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'set_position', offset: { eval: 'x' } }]), /unknown operator/);+});++test('displace moves a sphere along its normals by (field - midlevel) * strength', () => {+ const mesh = ball();+ const grown = applyMeshEdits(mesh, [{ op: 'displace', field: 1, strength: 0.2, midlevel: 0.5 }]).mesh;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const before = Math.hypot(mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]);+ const after = Math.hypot(grown.positions[vertex * 3], grown.positions[vertex * 3 + 1], grown.positions[vertex * 3 + 2]);+ assert.ok(Math.abs(after - before - 0.1) < 0.02, `vertex ${vertex}: ${before} to ${after}`);+ }+ const raised = applyMeshEdits(cube(), [{ op: 'displace', field: 1, strength: 0.4, midlevel: 0, direction: 'y' }]).mesh;+ assert.ok(Math.abs(raised.positions[1] - (cube().positions[1] + 0.4)) < 1e-6);+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'displace', field: 1, direction: 'sideways' }]), /direction must be/);+});++test('noise is smooth, stays in 0 to 1 and changes with the seed', () => {+ let minimum = 1;+ let maximum = 0;+ for (let step = 0; step < 2000; step++) {+ const value = valueNoise(step * 0.173, step * 0.071, step * 0.331, 3);+ minimum = Math.min(minimum, value);+ maximum = Math.max(maximum, value);+ }+ assert.ok(minimum >= 0 && maximum <= 1 && maximum - minimum > 0.5);+ assert.ok(Math.abs(valueNoise(0.5, 0.5, 0.5, 3) - valueNoise(0.5001, 0.5, 0.5, 3)) < 0.01);+ assert.notEqual(valueNoise(0.37, 0.52, 0.11, 1), valueNoise(0.37, 0.52, 0.11, 2));+});++test('the same expression gives identical bytes on every run', () => {+ const edits = [+ { op: 'displace', field: { noise: { scale: 3, seed: 7, octaves: 3 } }, strength: 0.3 },+ { op: 'set_position', offset: { vec: [0, { mul: [{ random: { seed: 5 } }, 0.05] }, 0] } },+ ];+ const first = applyMeshEdits(ball(), edits).mesh;+ const second = applyMeshEdits(ball(), edits).mesh;+ assert.equal(bytesOf(first), bytesOf(second));+ const otherSeed = applyMeshEdits(ball(), [{ ...edits[0], field: { noise: { scale: 3, seed: 8, octaves: 3 } } }, edits[1]]).mesh;+ assert.notEqual(bytesOf(first), bytesOf(otherSeed));+});++test('field nodes in a stack reuse earlier nodes from the cache', () => {+ const entries = new Map();+ const cache = { get: key => entries.get(key), set: (key, value) => entries.set(key, value) };+ const stack = last => [+ { op: 'displace', field: { noise: { scale: 2, seed: 1 } }, strength: 0.2 },+ { op: 'set_position', offset: [0, last, 0] },+ ];+ const first = evaluateMeshStack(ball(), stack(0.1), { cache, cacheKey: 'ball' });+ assert.deepEqual(first.results.map(result => result.cached), [undefined, undefined]);+ const second = evaluateMeshStack(ball(), stack(0.2), { cache, cacheKey: 'ball' });+ assert.deepEqual(second.results.map(result => result.cached), [true, undefined]);+ assert.equal(bytesOf(evaluateMeshStack(ball(), stack(0.1), { cache, cacheKey: 'ball' }).mesh), bytesOf(first.mesh));+});++test('instances on a grid, a scatter and a surface are seeded, bounded and filterable', () => {+ const base = { id: 'rock', geometry: 'stone', material: 'paint' };+ const surfaceGeometry = { ...sphere(16, 8) };+ const options = { maxNodes: 4096, resolveSurface: () => surfaceGeometry };+ const grid = expandInstancedNodes([{ ...base, instances: { grid: { counts: [3, 1, 2], spacing: [1, 1, 1] } } }], options);+ assert.equal(grid.length, 1 + 6);+ assert.deepEqual(grid[1].translation, [-1, 0, -0.5]);+ assert.equal(grid[1].parent, 'rock');+ const half = expandInstancedNodes([{ ...base, instances: { grid: { counts: [4, 1, 1], spacing: [1, 1, 1] }, where: { gt: [{ attr: 'position', component: 'x' }, 0] } } }], options);+ assert.equal(half.length, 1 + 2);+ const scatter = { ...base, instances: { scatter: { count: 50, min: [0, 0, 0], max: [2, 0, 2] }, seed: 4, yaw: true, scale: [0.5, 1.5] } };+ const first = expandInstancedNodes([scatter], options);+ assert.equal(JSON.stringify(first), JSON.stringify(expandInstancedNodes([scatter], options)));+ assert.notEqual(JSON.stringify(first), JSON.stringify(expandInstancedNodes([{ ...scatter, instances: { ...scatter.instances, seed: 5 } }], options)));+ for (const node of first.slice(1)) {+ assert.ok(node.translation[0] >= 0 && node.translation[0] <= 2 && node.translation[1] === 0);+ assert.ok(node.scale[0] >= 0.5 && node.scale[0] <= 1.5);+ }+ const { positions, normals } = surfacePoints(surfaceGeometry, 100, 9);+ for (let point = 0; point < 100; point++) {+ const radius = Math.hypot(positions[point * 3], positions[point * 3 + 1], positions[point * 3 + 2]);+ assert.ok(radius > 0.9 && radius <= 1.0001, `radius ${radius}`);+ assert.ok(Math.hypot(normals[point * 3], normals[point * 3 + 1], normals[point * 3 + 2]) > 0.99);+ }+ const grass = expandInstancedNodes([{ ...base, instances: { surface: { geometry: 'ground', count: 20 }, alignToNormal: true } }], options);+ assert.equal(grass.length, 21);+});++test('hostile instance records are rejected before any point is made', () => {+ const base = { id: 'rock', geometry: 'stone', material: 'paint' };+ const options = { maxNodes: 4096, resolveSurface: () => assert.fail('resolved a surface') };+ const hostile = [+ { grid: { counts: [1e9, 1, 1], spacing: [1, 1, 1] } },+ { grid: { counts: [100, 100, 100], spacing: [1, 1, 1] } },+ { scatter: { count: 1e9, min: [0, 0, 0], max: [1, 1, 1] } },+ { scatter: { count: 5, min: [0, 0, 0], max: [1, 1, 'x'] } },+ { surface: { geometry: 'ground', count: 1e9 } },+ { grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, scatter: { count: 1, min: [0, 0, 0], max: [1, 1, 1] } },+ {},+ JSON.parse('{"__proto__": {"grid": 1}, "constructor": 1}'),+ { grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, where: { eval: 'process.exit()' } },+ { grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, alignToNormal: true },+ { grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, scale: [2, 1] },+ { grid: { counts: [1, 1, 1], spacing: [1, 1, 1] }, seed: -1 },+ ];+ for (const spec of hostile) {+ assert.throws(() => expandInstancedNodes([{ ...base, instances: spec }], options), error => error instanceof TypeError || error instanceof RangeError, JSON.stringify(spec).slice(0, 80));+ }+ assert.throws(() => expandInstancedNodes([{ id: 'bare', instances: { grid: { counts: [1, 1, 1], spacing: [1, 1, 1] } } }], options), /geometry and material/);+ assert.throws(() => expandInstancedNodes([{ ...base, instances: { grid: { counts: [30, 30, 2], spacing: [1, 1, 1] } } }], { ...options, maxNodes: 100 }), /past the limit/);+});++test('a recipe with an instanced node creates one instanced batch of ordinary nodes', () => {+ const recipe = {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'stone', type: 'sphere' }, { id: 'floor', type: 'box' }],+ materials: [{ id: 'paint' }],+ nodes: [+ { id: 'floor', geometry: 'floor', material: 'paint', scale: [4, 0.1, 4] },+ { id: 'rocks', geometry: 'stone', material: 'paint', scale: [0.1, 0.1, 0.1], instances: { scatter: { count: 30, min: [-15, 1, -15], max: [15, 1, 15] }, seed: 2 } },+ ],+ };+ const session = createAgentScene(recipe);+ assert.equal(session.parts.length, 1 + 30);+ assert.equal(new Set(session.parts.map(part => part.geometry)).size, 2);+ assert.throws(() => createAgentScene({ ...recipe, nodes: [{ ...recipe.nodes[1], instances: { scatter: { count: 10_000_000, min: [0, 0, 0], max: [1, 1, 1] } } }] }), /scatter count/);+ assert.throws(() => createAgentScene({ ...recipe, nodes: [{ ...recipe.nodes[1], instances: { surface: { geometry: 'missing', count: 3 } } }] }), /not in geometries/);+});