3D engine that AI agents drive
Add recipe cloth: position-based sheets with pins, wind and colliders
Nguyen Xuan Anac497f44967e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9a353fe8..d757d5d6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Add recipe cloth (part of issue #62, no new tool). A `cloth` section records sheets with a position-based solver (`src/cloth.js`, loaded on demand with the new `cloth` module, no peer dependency): pinned edges, gravity, steady wind, ball and box colliders, thickness and friction, 60 frames a second, bounded by particle, frame and solver-operation limits. A seek blends two recorded frames, so the same time gives the same positions and a seek backwards repeats them (`npm run smoke:agent-cloth` repeats the PNG bytes through the MCP preview). New `grid` geometry (a flat sheet, 1 to 64 segments), `set-cloth` operation and a `cloth` report in `scene_inspect`. The tool schemas stay within the total budget: `set-physics` now takes the same record reference as `set-motion`, and the physics descriptions are shorter. A hanging sheet matches a Blender cloth bake (`scripts/blender-cloth.py`) to 0.08 percent of its height; a sheet dropped on a ball does not match, and no parity is claimed. No self collision and no soft bodies yet.- Edit the topology of imported GLB parts (part of issue #48, no new tool). `mesh_edit` and `mesh_inspect` take a part ID such as `mesh-10` of an imported asset: the part becomes a welded polygon mesh with axis tags and a `material-<n>` tag, the edit log is kept in the asset recipe as `meshEdits` (checkpoints, export and replay work), and every result passes `validateTopology`. New vertices take skin weights, morph deltas and vertex colours from the nearest original surface point and faces left without UVs read the nearest UV island; on a skinned or morphed part an edit more than a quarter of the part's bounds diagonal from the original surface is rejected with the next action. `mesh_inspect` reports `localToWorldScale` and `localAxesInWorld`. Measured on RobotExpressive through MCP (`npm run smoke:imported-topology`): a through hole in the closed left leg (98 to 210 triangles, still one closed part), a cut in the skinned right hand (124 to 109) and the morphed head (154 to 134), a 3 m extrude on the head rejected, GLB export and checkpoint restore intact. Suite task `robot-leg-hole`.- Make room in the npm package (part of issue #36). The MCP preview page, `build/mcp/preview.js`, is now an entry of the library build and imports the engine chunks that the package entries already ship, instead of bundling its own copy of the engine. The archive drops from 904,975 to 666,214 bytes. `build/mcp/manifest.json` lists those chunks under `previewChunks` with their hashes, the MCP runtime serves them next to `preview.js`, and `bench/size/budgets.json` gains `archiveBytes`, which `npm run smoke:package` checks.- Add six whole-mesh modifiers as edits and stack nodes (part of issue #42): `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform` (twist, bend, taper, stretch) and `cast` (sphere). Each has Blender cases in `tests/fixtures/blender/` that match with no listed difference, `triangulate` and `edge_split` check their output size before building it, and their fields are described in `scene_capabilities` `meshModifiers` so the tool schemas grow by one compact entry. Left for later slices: screw, skin, wireframe, lattice, curve, hook, wave, shrinkwrap, weighted normal, smooth by angle and the other cast shapes. `npm run parity` now prints the modifier coverage.diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex 200aeec1..15d720e2 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 283167,- "gzip": 80916,- "brotli": 68973+ "min": 283224,+ "gzip": 80927,+ "brotli": 68972},"entry:model": {"min": 40093,@@ -129,24 +129,24 @@"brotli": 762},"entry:agent-scene": {- "min": 198967,- "gzip": 60544,- "brotli": 52395+ "min": 40965,+ "gzip": 12546,+ "brotli": 10153},"entry:agent-scene+lazy": {- "min": 562293,- "gzip": 188049,- "brotli": 163604+ "min": 577871,+ "gzip": 194206,+ "brotli": 169059},"entry:agent-asset": {- "min": 293075,- "gzip": 90918,- "brotli": 79136+ "min": 40965,+ "gzip": 12546,+ "brotli": 10153},"entry:agent-asset+lazy": {- "min": 598140,- "gzip": 198448,- "brotli": 172252+ "min": 613648,+ "gzip": 204603,+ "brotli": 177784},"entry:hdri": {"min": 8075,@@ -174,14 +174,14 @@"brotli": 67034},"scene:agent-scene": {- "min": 308505,- "gzip": 89813,- "brotli": 77080+ "min": 40965,+ "gzip": 12546,+ "brotli": 10153},"scene:agent-scene+lazy": {- "min": 671831,- "gzip": 217321,- "brotli": 188240+ "min": 687346,+ "gzip": 223454,+ "brotli": 193846}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 195a732c..2f3ac69a 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -1,5 +1,5 @@{- "archiveBytes": 717978,+ "archiveBytes": 721300,"goals": {"lit-box": 50000,"gltf-box": 80000,@@ -30,15 +30,15 @@"entry:clutter": 5300,"entry:texture-set": 900,"entry:agent-scene": 61800,- "entry:agent-scene+lazy": 191900,+ "entry:agent-scene+lazy": 194600,"entry:agent-asset": 92800,- "entry:agent-asset+lazy": 202500,+ "entry:agent-asset+lazy": 205000,"entry:hdri": 3300,"entry:camera-effects": 8600,"entry:render-passes": 1700,"scene:lit-box": 60200,"scene:gltf-box": 79700,"scene:agent-scene": 91700,- "scene:agent-scene+lazy": 221700+ "scene:agent-scene+lazy": 223850}}diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex ba453682..0575c20c 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,16 +1,16 @@{- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits",+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details","schemaTotalBytes": 190480,"schemaToolBytes": {- "scene_create": 61220,- "scene_apply": 46850,+ "scene_create": 62150,+ "scene_apply": 44130,"mesh_edit": 34300,"scene_create_asset": 19310,"mesh_stack": 11690},"schemaOtherToolBytes": 4000,"resultBytes": {- "scene_capabilities": 7520,+ "scene_capabilities": 8190,"scene_create": 1400,"scene_inspect": 1400,"mesh_inspect": 1200,diff --git a/docs/parity.md b/docs/parity.mdindex 77a1de48..ff620e43 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -110,7 +110,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Modifiers > Normals > Normal Edit Modifier | missing | No equivalent. | | || Modeling > Modifiers > Normals > Weighted Normal Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 || Modeling > Modifiers > Normals > Smooth By Angle Modifier | partial | `smoothAngle` is a geometry setting. It is not a stack node. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |-| Modeling > Modifiers > Physics > Cloth Modifier | missing | No cloth. | | #62 |+| Modeling > Modifiers > Physics > Cloth Modifier | partial | Recipe `cloth`: a position-based sheet solver with pinned edges, steady wind, gravity and fixed ball or box colliders, recorded at 60 frames a second so a seek repeats exactly. No self collision, no per-vertex stiffness or pin weights. A hanging sheet matches a Blender bake to 0.08 percent of its height; a sheet dropped on a ball does not match (see docs/physics.md). | [cloth](../tests/cloth.test.js), [cloth-blender](../tests/cloth-blender.test.js) | #62 || Modeling > Modifiers > Physics > Collision Modifier | partial | Rapier colliders fitted to recipe geometry as box, ball, capsule, convex hull or trimesh, so a body rests on an authored mesh. | [agent-physics](../tests/agent-physics.test.js) | #61 || Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | || Modeling > Modifiers > Physics > Explode Modifier | missing | No equivalent. | | |@@ -176,7 +176,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Physics > Rigid Body > Rigid Body Properties | partial | Dynamic, fixed and kinematic bodies with mass, density, friction, restitution and velocity, in code and in recipes. Trimesh and convex colliders, no bone-bound bodies yet. | [physics-colliders](../tests/physics-colliders.test.js) | #61 || Physics > Rigid Body > Rigid Body World | partial | Recorded simulation with deterministic seeks, in code and in a recipe `physics` section (MCP, a seek back repeats the PNG). | [agent-physics](../tests/agent-physics.test.js) | #61 || Physics > Rigid Body > Rigid Body Constraints | partial | Fixed, spherical, revolute and prismatic joints, with limits and motors, in code. | [physics](../tests/physics.test.js) | #61 |-| Physics > Cloth | missing | No cloth. | | #62 |+| Physics > Cloth | partial | Same solver as the Cloth Modifier row: gravity, wind, pins, ball and box collisions, thickness and friction, and a `scene_inspect` report. Blender's tension, compression, shear and bending stiffness map to one `stiffness` and one `bend`. | [cloth](../tests/cloth.test.js) | #62 || Physics > Soft Body | missing | No soft bodies. | | #62 || Physics > Fluid | partial | `addons/spume` plays back a liquid baked outside the browser. There is no smoke or fire. | [spume](../tests/spume.test.js) | #63 || Physics > Particle System | missing | No shared particle system. Sparks exist only in the demo film. | | #63 |diff --git a/docs/physics.md b/docs/physics.mdindex 4f9c24b2..df6b550a 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -385,6 +385,38 @@ Rapier is loaded on demand, an optional peer dependency. The MCP runtime serves`scene_inspect` returns a `physics` report: per body the `finalPosition`, `finalSpeed` and `restsAtTime` (null while moving), the `contacts` between bodies with `firstTime`, `count` and `touchingAtEnd`, and the sensor `enter` and `leave` events with times.An agent can check that a ball came to rest on a mesh from these numbers, without a picture.+## Recipe cloth++A recipe `cloth` section records deformable sheets with a position-based solver (`src/cloth.js`, `src/agent-cloth.js`). It needs no peer dependency and loads on demand with the `cloth` module, so a scene without cloth pays nothing.++```json+{ "geometries": [{ "id": "flag", "type": "grid", "segments": 20 }, { "id": "ball", "type": "sphere" }],+ "nodes": [{ "id": "flag", "geometry": "flag", "material": "cloth", "translation": [0, 2.5, 0], "scale": [2, 1.2, 1] },+ { "id": "ball", "geometry": "ball", "material": "stone", "translation": [0.2, 1.4, 0.35], "scale": [0.3, 0.3, 0.3] }],+ "cloth": { "duration": 3, "wind": [4, 0, 2],+ "sheets": [{ "node": "flag", "pin": ["left"] }],+ "colliders": [{ "node": "ball", "shape": "ball" }] } }+```++- A sheet is a root node with any triangle mesh. The `grid` geometry (`segments` 1 to 64) is a flat unit sheet in XY facing +Z, sized by the node scale. Vertices at one position share a particle, so a seam does not tear.+- `pin` holds edges of the local bounds in place: `top`, `bottom`, `left`, `right` or a corner such as `topLeft`.+- Sheet fields: `stiffness` (0.01 to 1, default 0.9), `bend` (0 to 1, default 0.1), `density` in kg/m2 (default 0.2), `damping` in 1/s (default 0.3), `friction` (default 0.3) and `thickness` in metres (default 0.01). `gravity` and a steady `wind` in m/s sit on the section.+- Colliders are fixed root nodes fitted to their geometry bounds as a `ball` or an oriented `box` (default). A thin box is a floor.+- A sheet or collider cannot have a motion translation or rotation track or a physics body. No cloth-to-cloth or self collision, and no soft bodies yet.+- The bake runs when the scene is created: 60 frames a second, 4 substeps and 8 constraint passes a frame, constraints solved in a fixed order with no random numbers. `sample(time)` blends the two nearest frames, so the same time always gives the same positions and a seek backwards repeats them. Time zero is the authored sheet and a time past `duration` holds the last frame.+- Limits: 8 sheets, 16 colliders, 10 seconds, 5000 particles a sheet, 3 million recorded particle positions and 150 million solver operations a bake (about 3 seconds). Larger input is rejected with the limit in the message. A 32 by 32 grid for 4 seconds bakes in about 1.4 s.+- A seek replaces the sheet's part, so the renderer sees a topology change (`topologyRevision`); the MCP preview uses `replaceParts` and `scene_look` with `motionTime` repeats the same PNG bytes (`npm run smoke:agent-cloth`).+- `scene_inspect` returns a `cloth` report: particles, triangles, pinned count and the final bounds of each sheet.++Blender comparison (`scripts/blender-cloth.py`, Blender 5.2.2, default stiffness, mass set from the same kg/m2; `tests/cloth-blender.test.js`):++| Case | Result |+| --- | --- |+| 2 x 1.5 m sheet pinned along its top, 2 s | Mean vertex distance 0.08 percent of the height, free edge 1.2485 m against 1.25 m. Both hang straight, so this is a weak test. |+| 1.6 m sheet dropped on a 0.4 m ball, 2 s | Does not match: the lowest point is -0.47 m in 67.js and 0.35 m in Blender, and the mean vertex distance is 63 percent of the sheet size. Neither enters the ball. Raising `stiffness` and `bend` to 1 changes it to 57 percent. The cause is not found; it may be Blender's cloth damping and collision margins, so no parity is claimed for draping. |++Solvers differ in kind (Blender uses springs with implicit integration; this is position-based), and a reviewer's by-eye comparison of a drape is still open.+Repeat recordings require identical inputs, creation order, timestep, solver options, and Rapier version.Rapier documents cross-platform determinism for its WASM solver under identical initial conditions.Input calculations such as `Math.sin` can differ across platforms and invalidate that guarantee.diff --git a/package.json b/package.jsonindex 394c1ddf..079da078 100644--- a/package.json+++ b/package.json@@ -104,6 +104,7 @@"smoke:render-passes": "node scripts/smoke-render-passes.mjs","smoke:agent-motion": "node scripts/smoke-agent-motion.mjs","smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",+ "smoke:agent-cloth": "node scripts/smoke-agent-cloth.mjs","smoke:frame-encoder": "node scripts/smoke-frame-encoder.mjs","smoke:enhancements": "node scripts/smoke-enhancements.mjs","smoke:site": "node scripts/smoke-site.mjs",diff --git a/scripts/blender-cloth.py b/scripts/blender-cloth.pynew file mode 100644index 00000000..7330a1d6--- /dev/null+++ b/scripts/blender-cloth.py@@ -0,0 +1,110 @@+"""Bake the two cloth cases of tests/cloth-blender.test.js with Blender's cloth solver and write the final positions.++Run from the repo root:+ PATH="/c/Program Files/Blender Foundation/Blender 5.2:$PATH" blender -b --factory-startup --python scripts/blender-cloth.py++Positions are written in 67.js axes (Y up): Blender (x, y, z) becomes (x, z, -y). Vertex order matches the grid+geometry of 67.js: rows from the top down, columns left to right.+"""+import json+import math+import pathlib++import bpy+import bmesh++SEGMENTS = 12+SECONDS = 2+FRAMES_PER_SECOND = 60+OUTPUT = pathlib.Path("tests/fixtures/blender/cloth-golden.json")+++def reset_scene():+ bpy.ops.wm.read_factory_settings(use_empty=True)+ scene = bpy.context.scene+ scene.render.fps = FRAMES_PER_SECOND+ scene.frame_start = 1+ scene.frame_end = SECONDS * FRAMES_PER_SECOND + 1+ scene.gravity = (0.0, 0.0, -9.81)+ return scene+++def grid_object(name, center, width, height, plane):+ """A (SEGMENTS + 1)^2 vertex sheet. plane 'vertical' lies in XZ (67.js XY), 'horizontal' in XY (67.js XZ)."""+ mesh = bpy.data.meshes.new(name)+ builder = bmesh.new()+ vertices = []+ for row in range(SEGMENTS + 1):+ for column in range(SEGMENTS + 1):+ across = (column / SEGMENTS - 0.5) * width+ down = (0.5 - row / SEGMENTS) * height+ if plane == "vertical":+ vertices.append(builder.verts.new((center[0] + across, 0.0, center[1] + down)))+ else:+ vertices.append(builder.verts.new((center[0] + across, -(center[2] + down), center[1])))+ for row in range(SEGMENTS):+ for column in range(SEGMENTS):+ first = row * (SEGMENTS + 1) + column+ below = first + SEGMENTS + 1+ builder.faces.new((vertices[first], vertices[first + 1], vertices[below + 1], vertices[below]))+ builder.to_mesh(mesh)+ builder.free()+ obj = bpy.data.objects.new(name, mesh)+ bpy.context.scene.collection.objects.link(obj)+ return obj+++def add_cloth(obj, pinned_indices, vertex_mass):+ if pinned_indices:+ group = obj.vertex_groups.new(name="pin")+ group.add(pinned_indices, 1.0, "REPLACE")+ modifier = obj.modifiers.new("Cloth", "CLOTH")+ settings = modifier.settings+ settings.quality = 8+ settings.mass = vertex_mass+ settings.air_damping = 1.0+ if pinned_indices:+ settings.vertex_group_mass = "pin"+ modifier.collision_settings.use_self_collision = False+ modifier.collision_settings.distance_min = 0.01+ modifier.point_cache.frame_start = 1+ modifier.point_cache.frame_end = SECONDS * FRAMES_PER_SECOND + 1+ return modifier+++def final_positions(obj):+ scene = bpy.context.scene+ for frame in range(scene.frame_start, scene.frame_end + 1):+ scene.frame_set(frame)+ evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())+ return [[round(v.co.x, 5), round(v.co.z, 5), round(-v.co.y, 5)] for v in evaluated.data.vertices]+++def hanging_flag():+ reset_scene()+ width, height, center_y = 2.0, 1.5, 2.0+ flag = grid_object("flag", (0.0, center_y, 0.0), width, height, "vertical")+ top_row = list(range(SEGMENTS + 1))+ area = width * height+ vertex_mass = 0.2 * area / ((SEGMENTS + 1) ** 2)+ add_cloth(flag, top_row, vertex_mass)+ return {"positions": final_positions(flag), "vertexMass": vertex_mass}+++def drape_over_ball():+ reset_scene()+ size = 1.6+ sheet = grid_object("sheet", (0.0, 1.0, 0.0), size, size, "horizontal")+ bpy.ops.mesh.primitive_uv_sphere_add(radius=0.4, location=(0.0, 0.0, 0.0), segments=48, ring_count=24)+ ball = bpy.context.active_object+ ball.modifiers.new("Collision", "COLLISION")+ ball.collision.thickness_outer = 0.01+ vertex_mass = 0.2 * size * size / ((SEGMENTS + 1) ** 2)+ add_cloth(sheet, [], vertex_mass)+ return {"positions": final_positions(sheet), "vertexMass": vertex_mass}+++cases = {"hanging-flag": hanging_flag(), "drape-over-ball": drape_over_ball()}+OUTPUT.parent.mkdir(parents=True, exist_ok=True)+OUTPUT.write_text(json.dumps({"blender": bpy.app.version_string, "seconds": SECONDS, "segments": SEGMENTS, "cases": cases}, indent=1))+print("wrote", OUTPUT, "blender", bpy.app.version_string)diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 824ee9bd..4786ef80 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -334,6 +334,7 @@ const recipeMeshEdits = z.array(z.record(z.string(), z.unknown())).max(64);const recipeMeshStack = z.array(z.record(z.string(), z.unknown())).max(16);const geometry = z.discriminatedUnion('type', [...primitiveGeometries(true),+ z.strictObject({ id: identifier, type: z.literal('grid'), segments: detail(1, 64) }),z.strictObject({ id: identifier, type: z.literal('mesh'), base: z.discriminatedUnion('type', primitiveGeometries(false)).describe('Starting shape, converted to welded quads with axis face tags.'), edits: recipeMeshEdits.optional().describe('Replayable edit log, applied in order. Each item has the shape of one mesh_edit edit; read that tool for every op and field.'), stack: recipeMeshStack.optional().describe('Non-destructive modifier stack evaluated after the edits. Each item has the shape of one mesh_stack node; read that tool for the ops.'), smoothAngle: bounded(0, 180).optional().describe('Edges bending more than this many degrees render hard. Defaults to 30.') }),]);function motionTrack(kind, property, value, tangent) {@@ -434,18 +435,18 @@ const motion = z.strictObject({])).max(128),}).describe('One absolute-time procedural clip. Local node transforms propagate through parents. Cubic tangents are derivatives per second. Backend checks references, duplicate tracks, 2048 total keys and every sampled pose.');const physicsBody = z.strictObject({- node: identifier.describe('A root recipe node with a geometry. The collider is fitted to that geometry at the node scale, and the body drives the node pose.'),- type: z.enum(['dynamic', 'fixed', 'kinematic']).optional().describe('Defaults to dynamic. Fixed bodies never move.'),- shape: z.enum(['box', 'ball', 'capsule', 'convex', 'trimesh']).optional().describe('Collider fitted to the geometry. Defaults: box for dynamic bodies and sensors, trimesh for fixed ones. Trimesh follows every triangle (at most 20000) and needs a fixed or kinematic body; convex wraps at most 2048 distinct vertices.'),- mass: positive.optional().describe('Kilograms. Give mass or density, not both.'),+ node: identifier.describe('Root node with a geometry; the collider is fitted to it and the body drives its pose.'),+ type: z.enum(['dynamic', 'fixed', 'kinematic']).optional().describe('Defaults to dynamic.'),+ shape: z.enum(['box', 'ball', 'capsule', 'convex', 'trimesh']).optional().describe('Defaults: box for dynamic and sensors, trimesh for fixed. Trimesh (at most 20000 triangles) needs a fixed or kinematic body; convex takes at most 2048 distinct vertices.'),+ mass: positive.optional().describe('Kilograms; mass or density, not both.'),density: positive.optional().describe('Defaults to 1.'),friction: nonnegative.optional(),restitution: unit.optional(),- sensor: z.boolean().optional().describe('A trigger volume: nothing bounces off it, and scene_inspect lists enter and leave times.'),+ sensor: z.boolean().optional().describe('Trigger volume; scene_inspect lists enter and leave times.'),velocity: vector3.optional(),angularVelocity: vector3.optional(),- layer: z.number().int().min(0).max(15).optional().describe('Collision layer, 0 to 15. Defaults to 0.'),- collidesWith: z.array(z.number().int().min(0).max(15)).max(16).optional().describe('Layers this body hits. Two bodies collide only when each lists the other\'s layer. Defaults to all.'),+ layer: z.number().int().min(0).max(15).optional(),+ collidesWith: z.array(z.number().int().min(0).max(15)).max(16).optional().describe('Layers hit; both bodies must list each other. Defaults to all.'),});const physicsJoint = z.strictObject({type: z.enum(['spherical', 'revolute', 'prismatic', 'fixed']),@@ -461,7 +462,19 @@ const physics = z.strictObject({gravity: vector3.optional().describe('Defaults to [0, -9.81, 0].'),bodies: z.array(physicsBody).min(1).max(64),joints: z.array(physicsJoint).max(64).optional().describe('Joint bodies are the node IDs of physics bodies.'),-}).describe('Rigid-body physics recorded offline with Rapier at 60 steps a second and played back by time: motionTime seeks into the recording. Bodies are recipe nodes; scene_inspect reports contacts and resting state. Needs the optional peer @dimforge/rapier3d-compat. A node cannot have both a body and a motion translation or rotation track.');+}).describe('Rigid bodies recorded offline with Rapier (optional peer) at 60 fps and seeked by motionTime. scene_inspect reports contacts and resting state. A node cannot have a body and a motion translation or rotation track.');+const clothSheet = z.strictObject({+ node: identifier.describe('Root mesh node that stays put, such as a grid.'),+ pin: z.array(z.enum(['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'])).max(8).optional(),+ stiffness: unit.optional(), bend: unit.optional(), density: positive.optional(), damping: nonnegative.optional(), friction: unit.optional(), thickness: nonnegative.optional(),+});+const cloth = z.strictObject({+ duration: z.number().min(0.1).max(10),+ gravity: vector3.optional(),+ wind: vector3.optional(),+ sheets: z.array(clothSheet).min(1).max(8),+ colliders: z.array(z.strictObject({ node: identifier, shape: z.enum(['ball', 'box']).optional() })).max(16).optional(),+}).describe('Cloth baked at 60 fps and seeked by motionTime. Units and defaults: scene_capabilities cloth.');// The full motion schema (tracks, ik, constraints, drivers) is in scene_create's recipe. scene_apply and asset recipes// take the same object, validated by the backend, without repeating about 35 KB of schema in each tool.const recipeMotionReference = z.record(z.string(), z.unknown()).describe('The same object as recipe.motion in scene_create: duration, loop, tracks, ik, constraints, drivers. Read that tool for the fields. On an imported asset it also takes layers, up to 8 clips played at motion time before tracks and ik: { clip (scene_inspect animations id), mask: { joints, descendants, exclude } of node IDs, weight, speed, offset, loop, additive, reference, bones: { clip node: asset node } to retarget by name, morph }. A masked layer waves while another walks.');@@ -498,6 +511,7 @@ const recipe = z.strictObject({shadow: shadow.optional(),motion: motion.nullable().optional(),physics: physics.nullable().optional(),+ cloth: cloth.nullable().optional(),}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');const assetRecipe = z.strictObject({format: z.literal('67js.asset'),@@ -522,7 +536,8 @@ const operation = z.discriminatedUnion('type', [z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),z.strictObject({ type: z.literal('set-motion'), motion: recipeMotionReference.nullable() }),z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),- z.strictObject({ type: z.literal('set-physics'), physics: physics.nullable() }),+ z.strictObject({ type: z.literal('set-physics'), physics: z.record(z.string(), z.unknown()).nullable().describe('Same object as recipe.physics in scene_create.') }),+ z.strictObject({ type: z.literal('set-cloth'), cloth: z.record(z.string(), z.unknown()).nullable() }),z.strictObject({ type: z.literal('set-environment'), environment }),z.strictObject({ type: z.literal('set-effects'), effects }),z.strictObject({ type: z.literal('set-shadow'), shadow }),diff --git a/scripts/smoke-agent-cloth.mjs b/scripts/smoke-agent-cloth.mjsnew file mode 100644index 00000000..d775113f--- /dev/null+++ b/scripts/smoke-agent-cloth.mjs@@ -0,0 +1,94 @@+// Recipe cloth through the real MCP server: the sheet is baked when the scene is created, the SwiftShader preview swaps+// the deformed part for each seek, and seeking back must reproduce the same PNG bytes.+import assert from 'node:assert/strict';+import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';+import { tmpdir, constants, setPriority } from 'node:os';+import { join, resolve } from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-cloth-'));+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');+const transport = new StdioClientTransport({ command: process.execPath,+ args: [cli, '--backend', 'cpu', '--memory', '96', '--jobs', join(directory, 'jobs')],+ cwd: directory, stderr: 'pipe' });+let diagnostics = '';+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });+const client = new Client({ name: '67js-cloth-proof', version: '1' });++async function call(name, argumentsValue = {}, timeout = 60000) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);+ return result;+}++async function look(sessionId, motionTime) {+ const result = await call('scene_look', { sessionId, width: 480, height: 480, ...(motionTime !== undefined ? { motionTime } : {}) });+ assert.match(result.structuredContent.graphics, /swiftshader/i);+ return result.content.find(item => item.type === 'image').data;+}++// A red flag pinned along its top edge, blown by wind, beside a pole and a ball it can touch.+const recipe = {+ format: '67js.scene', schemaVersion: 1,+ geometries: [+ { id: 'flag', type: 'grid', segments: 20 },+ { id: 'pole', type: 'box', bevel: 0 },+ { id: 'ball', type: 'sphere' },+ ],+ materials: [{ id: 'cloth', color: [0.85, 0.15, 0.12], doubleSided: true, roughness: 0.9 }, { id: 'metal', color: [0.6, 0.6, 0.65] }],+ nodes: [+ { id: 'pole', geometry: 'pole', material: 'metal', translation: [-1.05, 1.5, 0], scale: [0.08, 3, 0.08] },+ { id: 'flag', geometry: 'flag', material: 'cloth', translation: [0, 2.5, 0], scale: [2, 1.2, 1] },+ { id: 'ball', geometry: 'ball', material: 'metal', translation: [0.2, 1.4, 0.35], scale: [0.3, 0.3, 0.3] },+ ],+ camera: { eye: [2.5, 2, 5], target: [0, 1.8, 0] },+ cloth: { duration: 3, wind: [4, 0, 2], sheets: [{ node: 'flag', pin: ['left'] }], colliders: [{ node: 'ball', shape: 'ball' }] },+};++try {+ await client.connect(transport);+ const capabilities = (await call('scene_capabilities')).structuredContent;+ assert.deepEqual(capabilities.scene.cloth.limits.maxSheets, 8);+ const created = (await call('scene_create', { recipe }, 180000)).structuredContent;+ const sessionId = created.sessionId;+ const report = (await call('scene_inspect', { sessionId })).structuredContent.cloth;+ assert.equal(report.sheets[0].particles, 21 * 21);+ assert.equal(report.sheets[0].pinned, 21);++ const start = await look(sessionId, 0);+ const middle = await look(sessionId, 1);+ const end = await look(sessionId, 3);+ assert.notEqual(start, middle);+ assert.notEqual(middle, end);+ for (const [time, expected] of [[2.2, null], [0, start], [1, middle], [3, end], [0.4, null], [1, middle]]) {+ const actual = await look(sessionId, time);+ if (expected) {+ assert.equal(actual, expected, `Seek to ${time} s must reproduce the same PNG bytes.`);+ }+ }+ await mkdir('artifacts', { recursive: true });+ for (const [name, data] of [['start', start], ['middle', middle], ['end', end]]) {+ await writeFile(`artifacts/agent-cloth-${name}.png`, Buffer.from(data, 'base64'));+ }+ await call('scene_dispose', { sessionId });+ const processId = transport.pid;+ await client.close();+ const deadline = Date.now() + 7000;+ let exited = false;+ while (Date.now() < deadline && !exited) {+ try {+ process.kill(processId, 0);+ await delay(50);+ } catch (error) {+ assert.equal(error.code, 'ESRCH');+ exited = true;+ }+ }+ assert.equal(exited, true, `Owned MCP process must exit: ${diagnostics}`);+ console.log(JSON.stringify({ shuffledPngSeeksExact: true, particles: report.sheets[0].particles, eofCleanup: true }));+} finally {+ await client.close();+}diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex d576856a..e4469790 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -47,6 +47,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.- A character or creature that must move (a walker, a quadruped) gets a recipe `armatures` entry and a `skin` on each mesh node: `{ "id": "rig", "preset": "humanoid", "fit": { "bounds": { "min": [...], "max": [...] } } }` (or `fit.node`), then `skin: { "armature": "rig" }` on every body part. Bones are nodes named `hips`, `leftUpperLeg`, `leftLowerLeg` and so on, so rotation tracks and `motion.ik` address them directly (rotation is local, about the bone head; positive X swings a hanging limb backward). Build the mesh at rest in the preset's pose (facing +Z, arms down), and read `rig` in `scene_inspect`: unweighted vertices, bones with no vertices, joint axis problems. Weights are by distance to the bone segments, so give limbs the same loops you want to bend. See "Authored rigs" in `docs/agent-motion.md`.- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; bodies bound to bones for ragdolls are not supported. See "Recipe physics" in the checkout's `docs/physics.md`.+- Flags, curtains, capes and cloths draped over props use the recipe `cloth` section: a `grid` geometry node (flat sheet in XY, `segments` up to 64) listed in `sheets` with `pin` edges (`top`, `left`, a corner...), `wind` in m/s, and fixed `colliders` (`ball` or `box` fitted to their node). Seek with `motionTime`; a flag needs wind along its length (+x for a left pin), not across it. No peer needed, no self collision, no soft bodies. Units, defaults and limits are in `scene_capabilities` under `cloth`; see "Recipe cloth" in `docs/physics.md`.- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.- To pick between variants, fork each with `scene_apply` and a `branch` name (the scene and revision stay put), compare them in one `scene_review` with a `branch` per shot, then keep the winner with `scene_restore` and its `branch`. Add `labels: true` to `scene_look` or `scene_review` to match node names and lint problems to what the image shows. Docs: `docs/agent-review.md`.diff --git a/src/agent-cloth.js b/src/agent-cloth.jsnew file mode 100644index 00000000..ee82778c--- /dev/null+++ b/src/agent-cloth.js@@ -0,0 +1,266 @@+import { mat4 } from 'gl-matrix';+import { bakeCloth, sampleClothFrames, weldVertices } from './cloth.js';+import { recomputeNormals } from './geometry-normals.js';++const FRAMES_PER_SECOND = 60;+const MAX_DURATION_SECONDS = 10;+const MAX_SHEETS = 8;+const MAX_COLLIDERS = 16;+const PIN_EDGES = ['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'];+const COLLIDER_SHAPES = ['ball', 'box'];+const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'sheets', 'colliders'];+const SHEET_FIELDS = ['node', 'pin', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];+const COLLIDER_FIELDS = ['node', 'shape'];+const PIN_TOLERANCE = 1e-4;++function knownKeys(value, fields, label) {+ if (!value || Object.getPrototypeOf(value) !== Object.prototype) {+ throw new TypeError(`${label} must be a plain object.`);+ }+ for (const key of Object.keys(value)) {+ if (!fields.includes(key)) {+ throw new TypeError(`Unknown or unsupported ${label} field: ${key}. Allowed fields: ${fields.join(', ')}.`);+ }+ }+}++function finiteNumber(value, label, minimum, maximum) {+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isFinite(Math.fround(value)) || value < minimum || value > maximum) {+ throw new RangeError(`${label} must be a finite number within ${minimum} and ${maximum}.`);+ }+ return value;+}++function vectorOfThree(value, label, limit) {+ if (!Array.isArray(value) || value.length !== 3) {+ throw new TypeError(`${label} needs 3 numbers.`);+ }+ return value.map(component => finiteNumber(component, label, -limit, limit));+}++function boundedArray(value, maximum, label) {+ if (!Array.isArray(value) || value.length > maximum) {+ throw new TypeError(`${label} must be an array of at most ${maximum} entries.`);+ }+ return value;+}++function rootNodeWithGeometry(nodeId, recipeNodes, claimedNodes, motionNodeIds, physicsNodeIds, label) {+ const node = typeof nodeId === 'string' ? recipeNodes.get(nodeId) : undefined;+ if (!node) {+ throw new RangeError(`${label} node was not found: ${String(nodeId).slice(0, 64)}.`);+ }+ if (node.geometry === undefined) {+ throw new RangeError(`${label} node ${nodeId} has no geometry.`);+ }+ if (node.parent !== null) {+ throw new RangeError(`${label} node ${nodeId} must be a root node; reparent it first.`);+ }+ if (claimedNodes.has(nodeId)) {+ throw new RangeError(`Node ${nodeId} is used twice in cloth.`);+ }+ if (motionNodeIds.has(nodeId) || physicsNodeIds.has(nodeId)) {+ throw new RangeError(`Node ${nodeId} has a motion translation or rotation track or a physics body. Cloth needs a node that stays where it is.`);+ }+ claimedNodes.add(nodeId);+}++function normalizeSheet(input, context) {+ knownKeys(input, SHEET_FIELDS, 'cloth sheet');+ rootNodeWithGeometry(input.node, context.recipeNodes, context.claimedNodes, context.motionNodeIds, context.physicsNodeIds, 'Cloth sheet');+ const sheet = { node: input.node };+ if (input.pin !== undefined) {+ const edges = boundedArray(input.pin, PIN_EDGES.length, 'Cloth pin');+ for (const edge of edges) {+ if (!PIN_EDGES.includes(edge)) {+ throw new RangeError(`Cloth pin must be one of ${PIN_EDGES.join(', ')}.`);+ }+ }+ sheet.pin = [...new Set(edges)];+ }+ const ranges = { stiffness: [0.01, 1], bend: [0, 1], density: [0.01, 10], damping: [0, 20], friction: [0, 1], thickness: [0, 0.5] };+ for (const [field, [minimum, maximum]] of Object.entries(ranges)) {+ if (input[field] !== undefined) sheet[field] = finiteNumber(input[field], `Cloth ${field}`, minimum, maximum);+ }+ return sheet;+}++function normalizeCollider(input, context) {+ knownKeys(input, COLLIDER_FIELDS, 'cloth collider');+ rootNodeWithGeometry(input.node, context.recipeNodes, context.claimedNodes, context.motionNodeIds, context.physicsNodeIds, 'Cloth collider');+ const shape = input.shape ?? 'box';+ if (!COLLIDER_SHAPES.includes(shape)) {+ throw new RangeError(`Cloth collider shape must be one of ${COLLIDER_SHAPES.join(', ')}.`);+ }+ return { node: input.node, shape };+}++/** Validate a recipe cloth section against its nodes. Returns the plain, bounded form stored in the recipe. */+export function normalizeAgentCloth(input, recipe) {+ if (input === null || input === undefined) {+ return null;+ }+ knownKeys(input, CLOTH_FIELDS, 'cloth');+ const context = {+ recipeNodes: new Map(recipe.nodes.map(node => [node.id, node])),+ claimedNodes: new Set(),+ motionNodeIds: new Set((recipe.motion?.tracks ?? [])+ .filter(track => track.kind === 'node' && (track.property === 'translation' || track.property === 'rotation'))+ .map(track => track.id)),+ physicsNodeIds: new Set((recipe.physics?.bodies ?? []).map(body => body.node)),+ };+ const result = { duration: finiteNumber(input.duration, 'Cloth duration', 0.1, MAX_DURATION_SECONDS) };+ result.sheets = boundedArray(input.sheets, MAX_SHEETS, 'Cloth sheets').map(sheet => normalizeSheet(sheet, context));+ if (!result.sheets.length) {+ throw new RangeError('Cloth needs at least one sheet. Use null to clear it.');+ }+ if (input.gravity !== undefined) result.gravity = vectorOfThree(input.gravity, 'Cloth gravity', 1000);+ if (input.wind !== undefined) result.wind = vectorOfThree(input.wind, 'Cloth wind', 100);+ if (input.colliders !== undefined) {+ result.colliders = boundedArray(input.colliders, MAX_COLLIDERS, 'Cloth colliders').map(collider => normalizeCollider(collider, context));+ }+ return result;+}++function localBounds(positions) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < positions.length; index += 3) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], positions[index + axis]);+ maximum[axis] = Math.max(maximum[axis], positions[index + axis]);+ }+ }+ return { minimum, maximum };+}++function nodeMatrix(node) {+ return mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale);+}++function colliderFor(collider, node, geometry) {+ const matrix = nodeMatrix(node);+ const { minimum, maximum } = localBounds(geometry.positions);+ const localCenter = minimum.map((value, axis) => (value + maximum[axis]) / 2);+ const halfExtents = minimum.map((value, axis) => Math.max(((maximum[axis] - value) / 2) * Math.abs(node.scale[axis]), 1e-4));+ const center = [+ matrix[0] * localCenter[0] + matrix[4] * localCenter[1] + matrix[8] * localCenter[2] + matrix[12],+ matrix[1] * localCenter[0] + matrix[5] * localCenter[1] + matrix[9] * localCenter[2] + matrix[13],+ matrix[2] * localCenter[0] + matrix[6] * localCenter[1] + matrix[10] * localCenter[2] + matrix[14],+ ];+ if (collider.shape === 'ball') {+ return { kind: 'ball', center, radius: Math.max(...halfExtents) };+ }+ const axes = [0, 1, 2].map(column => {+ const axis = [matrix[column * 4], matrix[column * 4 + 1], matrix[column * 4 + 2]];+ const length = Math.hypot(...axis);+ return axis.map(component => component / length);+ });+ return { kind: 'box', center, axes, halfExtents };+}++// Particles on the requested edges of the sheet's local bounds, so 'top' is the row of highest local y.+function pinnedParticles(localPositions, representatives, pin) {+ if (!pin?.length) return [];+ const particlePositions = representatives.map(vertex => localPositions.subarray(vertex * 3, vertex * 3 + 3));+ const { minimum, maximum } = localBounds(particlePositions.reduce((all, point) => [...all, ...point], []));+ const tolerance = PIN_TOLERANCE * Math.max(maximum[0] - minimum[0], maximum[1] - minimum[1], 1e-6);+ const at = (point, axis, extreme) => Math.abs(point[axis] - (extreme === 'min' ? minimum[axis] : maximum[axis])) <= tolerance;+ const tests = {+ top: point => at(point, 1, 'max'), bottom: point => at(point, 1, 'min'),+ left: point => at(point, 0, 'min'), right: point => at(point, 0, 'max'),+ topLeft: point => at(point, 1, 'max') && at(point, 0, 'min'), topRight: point => at(point, 1, 'max') && at(point, 0, 'max'),+ bottomLeft: point => at(point, 1, 'min') && at(point, 0, 'min'), bottomRight: point => at(point, 1, 'min') && at(point, 0, 'max'),+ };+ const pinned = [];+ particlePositions.forEach((point, particle) => {+ if (pin.some(edge => tests[edge](point))) pinned.push(particle);+ });+ return pinned;+}++function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount) {+ const welded = weldVertices(geometry.positions, geometry.indices);+ const matrix = nodeMatrix(node);+ const worldPositions = new Float64Array(welded.representatives.length * 3);+ welded.representatives.forEach((vertex, particle) => {+ const source = geometry.positions.subarray(vertex * 3, vertex * 3 + 3);+ const world = [0, 0, 0];+ for (let axis = 0; axis < 3; axis++) {+ world[axis] = matrix[axis] * source[0] + matrix[4 + axis] * source[1] + matrix[8 + axis] * source[2] + matrix[12 + axis];+ }+ worldPositions.set(world, particle * 3);+ });+ const recording = bakeCloth(worldPositions, welded.triangles, {+ pinned: pinnedParticles(geometry.positions, welded.representatives, sheet.pin),+ gravity: cloth.gravity, wind: cloth.wind, stiffness: sheet.stiffness, bend: sheet.bend,+ density: sheet.density, damping: sheet.damping, friction: sheet.friction, thickness: sheet.thickness,+ colliders, frameCount, framesPerSecond: FRAMES_PER_SECOND,+ });+ return { recording, welded, inverse: mat4.invert(mat4.create(), matrix), geometry, particleScratch: new Float32Array(recording.particleCount * 3) };+}++function frozenGeometry(baked, time) {+ const { recording, welded, inverse, geometry, particleScratch } = baked;+ sampleClothFrames(recording, time, particleScratch);+ const positions = new Float32Array(geometry.positions.length);+ for (let vertex = 0; vertex < welded.particleOfVertex.length; vertex++) {+ const source = welded.particleOfVertex[vertex] * 3;+ for (let axis = 0; axis < 3; axis++) {+ positions[vertex * 3 + axis] = inverse[axis] * particleScratch[source] + inverse[4 + axis] * particleScratch[source + 1] + inverse[8 + axis] * particleScratch[source + 2] + inverse[12 + axis];+ }+ }+ const normals = recomputeNormals(geometry, positions);+ return Object.freeze({ ...geometry, positions, normals });+}++function sheetReport(baked, node, sheet) {+ const { recording, welded, geometry } = baked;+ const last = new Float32Array(recording.particleCount * 3);+ sampleClothFrames(recording, Infinity, last);+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ for (let index = 0; index < last.length; index += 3) {+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], last[index + axis]);+ maximum[axis] = Math.max(maximum[axis], last[index + axis]);+ }+ }+ const round = values => values.map(value => Number(value.toFixed(4)));+ return {+ node: node.id, particles: recording.particleCount, triangles: welded.triangles.length / 3, vertices: geometry.positions.length / 3,+ pinned: pinnedParticles(geometry.positions, welded.representatives, sheet.pin).length,+ finalBoundsMin: round(minimum), finalBoundsMax: round(maximum),+ };+}++/**+ * Bake the cloth section. The result is a pure function of time: `sample(t)` returns the deformed geometry of each+ * sheet node (null at time zero, where the sheet is at rest), and a seek never runs the solver again.+ */+export function bakeAgentCloth(cloth, recipe, geometries) {+ const nodes = new Map(recipe.nodes.map(node => [node.id, node]));+ const frameCount = Math.round(cloth.duration * FRAMES_PER_SECOND) + 1;+ const colliders = (cloth.colliders ?? []).map(collider => colliderFor(collider, nodes.get(collider.node), geometries.get(nodes.get(collider.node).geometry)));+ const baked = new Map(cloth.sheets.map(sheet => {+ const node = nodes.get(sheet.node);+ return [sheet.node, bakeSheet(sheet, cloth, node, geometries.get(node.geometry), colliders, frameCount)];+ }));+ let reportCache = null;+ return Object.freeze({+ duration: cloth.duration,+ sample(time) {+ if (time <= 0) return null;+ const clamped = Math.min(time, cloth.duration);+ return new Map([...baked].map(([nodeId, sheetBake]) => [nodeId, frozenGeometry(sheetBake, clamped)]));+ },+ /** Particle counts and where each sheet ends, as numbers an agent can read without a picture. */+ report() {+ reportCache ??= {+ duration: cloth.duration, frames: frameCount, gravity: cloth.gravity ?? [0, -9.81, 0], wind: cloth.wind ?? [0, 0, 0],+ sheets: cloth.sheets.map(sheet => sheetReport(baked.get(sheet.node), nodes.get(sheet.node), sheet)),+ };+ return structuredClone(reportCache);+ },+ });+}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 6db86852..4333c2e9 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -77,7 +77,7 @@ export const MESH_MODIFIER_NOTES = Object.freeze({export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'mesh']),+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', '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 }),meshModifiers: MESH_MODIFIER_NOTES,@@ -89,7 +89,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({operations: Object.freeze(['set-node', 'set-material', 'set-camera', 'add-node', 'remove-node','add-geometry', 'remove-geometry', 'add-material', 'remove-material',- 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'edit-mesh', 'set-mesh-stack',+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'edit-mesh', 'set-mesh-stack',]),materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),alphaModes: RECIPE_ALPHA_MODES,@@ -145,6 +145,13 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({sensors: true, collisionLayers: 16, boneBodies: false,limits: Object.freeze({ maxBodies: 64, maxJoints: 64, maxDuration: 10, framesPerSecond: 60, maxTrimeshTriangles: 20000, maxHullPoints: 2048 }),}),+ // Recipe cloth: a position-based solver (no peer dependency) records any root mesh node as a deformable sheet.+ cloth: Object.freeze({+ sheetGeometry: 'grid { segments 1-64 }: unit sheet in XY facing +Z, sized by node scale; any triangle mesh works',+ defaults: Object.freeze({ stiffness: 0.9, bend: 0.1, density: 0.2, damping: 0.3, friction: 0.3, thickness: 0.01, colliderShape: 'box' }),+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders are fixed ball or box fits to geometry bounds. No self collision, no soft bodies. Sheets and colliders are root nodes with no motion track or physics body.',+ limits: Object.freeze({ maxSheets: 8, maxColliders: 16, maxDuration: 10, maxParticles: 5000, framesPerSecond: 60, substeps: 4, iterations: 8 }),+ }),motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),});diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex c1b666a8..1cf6d690 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -9,6 +9,7 @@ const MODULE_LOADERS = {text: () => import('./text-geometry.js'),motion: () => import('./agent-motion.js'),physics: () => import('./agent-physics.js'),+ cloth: () => import('./agent-cloth.js'),patterns: () => import('./material-patterns.js'),relations: () => import('./agent-relations.js'),};@@ -25,6 +26,7 @@ const MODULE_MARKERS = {text: ['"type":"text"'],motion: ['"motion":{'],physics: ['"physics":{'],+ cloth: ['"cloth":{'],patterns: ['"pattern"'],relations: ['"relations":'],};diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 54bdc14e..a86cc44d 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1,5 +1,5 @@import { mat4, mat3 } from 'gl-matrix';-import { box, cylinder, sphere, torus } from './geometry.js';+import { box, cylinder, grid, sphere, torus } from './geometry.js';import { createSceneGraph } from './scene-graph.js';import { applyProjection } from './camera.js';import { normalizeAgentLook, environmentPatchWithSetup } from './agent-look.js';@@ -336,7 +336,7 @@ function cameraFrom(value = {}) {const GEOMETRY_FIELDS = {box: ['bevel', 'subdivisions'], cylinder: ['segments', 'bevel', 'bevelSegments'],- sphere: ['segments', 'rings'], torus: ['tubeRadius', 'segments', 'sides', 'arc', 'start'],+ sphere: ['segments', 'rings'], grid: ['segments'], torus: ['tubeRadius', 'segments', 'sides', 'arc', 'start'],lathe: ['profile', 'segments', 'startAngle', 'sweep'],extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],@@ -374,6 +374,8 @@ function geometryEstimate(value) {return (detail('segments', 80, 3, 2048) + 1) * 2 * (detail('bevelSegments', 6, 1, 128) + 1) + 2 * ((value.segments ?? 80) + 2);case 'sphere':return (detail('segments', 64, 3, 2048) + 1) * (detail('rings', 40, 2, 2048) + 1);+ case 'grid':+ return (detail('segments', 16, 1, 64) + 1) ** 2;case 'torus':return (detail('segments', 96, 3, 2048) + 1) * (detail('sides', 24, 3, 128) + 1) + 2 * ((value.sides ?? 24) + 2);case 'lathe':@@ -457,6 +459,8 @@ function generateGeometry(value, maxVertices) {return cylinder(value.segments, value.bevel, value.bevelSegments);case 'sphere':return sphere(value.segments, value.rings);+ case 'grid':+ return grid(value.segments);case 'torus':return torus(value.tubeRadius, value.segments, value.sides, value.arc, value.start);case 'lathe':@@ -575,7 +579,7 @@ function addArmatures(recipe, limits) {function normalizeRecipe(input, limits) {let recipe = copiedJson(input, limits.maxRecipeBytes);- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics'], 'recipe');+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth'], 'recipe');if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {throw new RangeError('Expected 67js.scene schemaVersion 1.');}@@ -622,6 +626,9 @@ function normalizeRecipe(input, limits) {if (Object.hasOwn(recipe, 'physics')) {recipe.physics = agentSceneModule('physics').normalizeAgentPhysics(recipe.physics, recipe);}+ if (Object.hasOwn(recipe, 'cloth')) {+ recipe.cloth = agentSceneModule('cloth').normalizeAgentCloth(recipe.cloth, recipe);+ }recipe = copiedJson(recipe, limits.maxRecipeBytes);return recipe;}@@ -739,11 +746,24 @@ function stagePose(stagedState, time) {}const camera = sampled?.camera ? cameraPoseFrom(sampled.camera) : stagedState.recipe.camera;retainedMatrices(stagedState.parts);- return { graph, materialUpdates, camera, time };+ const clothGeometries = time === null ? null : stagedState.clothSampler?.sample(time) ?? null;+ return { graph, materialUpdates, camera, time, clothGeometries };+}++// Deformed cloth is a new geometry per sampled time, so those parts are replaced and the renderer sees a topology change.+function partsWithCloth(restParts, clothGeometries) {+ if (!clothGeometries) {+ return restParts;+ }+ return Object.freeze(restParts.map(part => {+ const geometry = clothGeometries.get(part.name);+ return geometry ? Object.freeze({ ...part, geometry }) : part;+ }));}+/** Returns true when the parts handed to a renderer changed, which the caller counts as a topology change. */function publishPose(stagedState, pose) {- for (const part of stagedState.parts) {+ for (const part of stagedState.restParts) {Float32Array.prototype.set.call(part.matrix, pose.graph.getNode(part.name).worldMatrix);}for (const update of pose.materialUpdates) {@@ -752,6 +772,10 @@ function publishPose(stagedState, pose) {publishSkinPoses(stagedState.skinStages);stagedState.renderCamera = pose.camera;stagedState.motionTime = pose.time;+ const nextParts = partsWithCloth(stagedState.restParts, pose.clothGeometries);+ const partsChanged = nextParts !== stagedState.parts;+ stagedState.parts = nextParts;+ return partsChanged;}function removeNode(candidate, operation) {@@ -796,6 +820,7 @@ export function createAgentScene(input, inputLimits = {}) {let revision = 0;let topologyRevision = 0;let physicsBake = null;+ let clothBake = null;const skinCache = new Map();const checkpoints = new Map();@@ -888,8 +913,8 @@ export function createAgentScene(input, inputLimits = {}) {const handle = existing ?? materialHandle(snapshot);materialHandles.set(material.id, handle);}- const activeParts = new Map(state?.parts.map(part => [part.name, part]) ?? []);- const preferredParts = new Map(preferred?.parts.map(part => [part.name, part]) ?? []);+ const activeParts = new Map(state?.restParts.map(part => [part.name, part]) ?? []);+ const preferredParts = new Map(preferred?.restParts.map(part => [part.name, part]) ?? []);const nextParts = recipe.nodes.filter(node => node.geometry !== undefined).map(node => {const binding = skinBindings.get(node.id);const geometry = binding?.geometry ?? geometries.get(node.geometry);@@ -904,12 +929,14 @@ export function createAgentScene(input, inputLimits = {}) {});});retainedMatrices(nextParts);- const sameParts = state && state.parts.length === nextParts.length &&- state.parts.every((part, index) => part === nextParts[index]);+ const sameParts = state && state.restParts.length === nextParts.length &&+ state.restParts.every((part, index) => part === nextParts[index]);+ const restParts = sameParts ? state.restParts : Object.freeze(nextParts);const stagedState = {recipe, geometryRecords, geometries, graph, materialHandles,- parts: sameParts ? state.parts : Object.freeze(nextParts),- topologyChanged: Boolean(state && !sameParts),+ parts: restParts, restParts,+ // A renderer holding the deformed cloth parts of the old state needs the rest parts back as a topology change.+ topologyChanged: Boolean(state && (!sameParts || state.parts !== state.restParts)),stats: geometryStats(geometryRecords.values()),};stagedState.localBounds = localBounds;@@ -917,7 +944,8 @@ export function createAgentScene(input, inputLimits = {}) {stagedState.skinStages = createSkinStages(skinBindings);stagedState.motionSampler = recipe.motion ? agentSceneModule('motion').compileAgentMotion(recipe.motion, recipe) : null;stagedState.physicsSampler = stagePhysics(recipe, geometryRecords);- const animated = Boolean(stagedState.motionSampler || stagedState.physicsSampler);+ stagedState.clothSampler = stageCloth(recipe, geometryRecords);+ const animated = Boolean(stagedState.motionSampler || stagedState.physicsSampler || stagedState.clothSampler);stagedState.poseGraph = animated ? compile(recipe, geometries, localBounds, limits) : null;stagedState.initialPose = stagePose(stagedState, animated ? 0 : null);return stagedState;@@ -937,6 +965,21 @@ export function createAgentScene(input, inputLimits = {}) {return physicsBake.sampler;}+ // Same rule as physics: an unchanged cloth section on unchanged geometry and nodes reuses the last bake.+ function stageCloth(recipe, geometryRecords) {+ if (!recipe.cloth) {+ return null;+ }+ const involved = new Set([...recipe.cloth.sheets, ...(recipe.cloth.colliders ?? [])].map(entry => entry.node));+ const involvedNodes = recipe.nodes.filter(node => involved.has(node.id));+ const key = JSON.stringify([recipe.cloth, involvedNodes, involvedNodes.map(node => geometryRecords.get(node.geometry).signature)]);+ if (clothBake?.key !== key) {+ const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));+ clothBake = { key, sampler: agentSceneModule('cloth').bakeAgentCloth(recipe.cloth, recipe, geometries) };+ }+ return clothBake.sampler;+ }+function commit(stagedState, incrementRevision) {publishPose(stagedState, stagedState.initialPose);if (stagedState.topologyChanged) {@@ -979,10 +1022,12 @@ export function createAgentScene(input, inputLimits = {}) {if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {throw new RangeError('Motion time must be null or within zero and 3600 seconds.');}- if (time !== null && !state.motionSampler && !state.physicsSampler) {- throw new RangeError('This procedural recipe has no motion or physics.');+ if (time !== null && !state.motionSampler && !state.physicsSampler && !state.clothSampler) {+ throw new RangeError('This procedural recipe has no motion, physics or cloth.');+ }+ if (publishPose(state, stagePose(state, time))) {+ topologyRevision++;}- publishPose(state, stagePose(state, time));return state.motionTime;},get environment() {@@ -1044,6 +1089,14 @@ export function createAgentScene(input, inputLimits = {}) {candidate.physics = operation.physics;continue;}+ if (operation.type === 'set-cloth') {+ knownKeys(operation, ['type', 'cloth'], 'operation');+ if (!Object.hasOwn(operation, 'cloth')) {+ throw new TypeError('set-cloth requires cloth; use null to clear it.');+ }+ candidate.cloth = operation.cloth;+ continue;+ }const lookField = Object.hasOwn(LOOK_OPERATION_FIELDS, operation.type) ? LOOK_OPERATION_FIELDS[operation.type] : null;if (lookField) {knownKeys(operation, ['type', lookField], 'operation');@@ -1153,7 +1206,7 @@ export function createAgentScene(input, inputLimits = {}) {fields = CAMERA_FIELDS;target = candidate.camera;} else {- throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);+ throw new TypeError(`Unsupported operation type: ${operation.type}. Use one of set-node, set-material, set-camera, set-motion, set-physics, set-cloth, set-environment, set-effects, set-shadow, add-node, add-geometry, add-material, remove-node, remove-geometry, remove-material, edit-mesh, set-mesh-stack.`);}knownKeys(operation, ['type', ...(operation.type === 'set-camera' ? [] : ['id']), ...fields], 'operation');if (!target) {@@ -1204,6 +1257,7 @@ export function createAgentScene(input, inputLimits = {}) {...(state.recipe.motion?.ik?.length ? { motionIk: agentSceneModule('motion').compileAgentMotion(state.recipe.motion, state.recipe).sweepIk() } : {}),motion: state.recipe.motion ? { duration: state.recipe.motion.duration, loop: state.recipe.motion.loop, tracks: state.recipe.motion.tracks.length, time: state.motionTime } : null,physics: state.physicsSampler ? state.physicsSampler.report() : null,+ ...(state.clothSampler ? { cloth: state.clothSampler.report() } : {}),...(state.recipe.armatures ? { rig: rigReport(state.recipe, state.skinBindings) } : {}),boundsSpace: 'authored-base-world',...(diagnostics.length ? { diagnostics } : {}),@@ -1254,7 +1308,7 @@ export function createAgentScene(input, inputLimits = {}) {recipe: structuredClone(state.recipe),geometryRecords: new Map(state.geometryRecords),materialHandles: new Map(state.materialHandles),- parts: state.parts,+ restParts: state.restParts,});return handle;},diff --git a/src/cloth.js b/src/cloth.jsnew file mode 100644index 00000000..8b0d9446--- /dev/null+++ b/src/cloth.js@@ -0,0 +1,351 @@+// Position-based cloth (Muller et al., "Position Based Dynamics", 2007), recorded offline as frames.+// Constraints are solved in a fixed order with no random numbers, so the same input always gives the same frames,+// and playback is an interpolation between two recorded frames: a seek never runs the solver.++export const CLOTH_LIMITS = Object.freeze({+ maxParticles: 5000,+ maxFrameParticles: 3_000_000,+ // About 18 ns an operation measured on the dev machine, so the cap is a bake of roughly three seconds.+ maxWork: 1.5e8,+ substeps: 4,+ iterations: 8,+});++const AIR_DENSITY = 1.2;+const WELD_DIGITS = 5;+const GRAVITY_DEFAULT = Object.freeze([0, -9.81, 0]);++/** Unique particles of a triangle mesh: vertices at the same position share one, so a seam does not tear open. */+export function weldVertices(positions, indices) {+ const particleOfKey = new Map();+ const particleOfVertex = new Uint32Array(positions.length / 3);+ const representatives = [];+ for (let vertex = 0; vertex < particleOfVertex.length; vertex++) {+ const offset = vertex * 3;+ const key = `${positions[offset].toFixed(WELD_DIGITS)},${positions[offset + 1].toFixed(WELD_DIGITS)},${positions[offset + 2].toFixed(WELD_DIGITS)}`;+ let particle = particleOfKey.get(key);+ if (particle === undefined) {+ particle = representatives.length;+ particleOfKey.set(key, particle);+ representatives.push(vertex);+ }+ particleOfVertex[vertex] = particle;+ }+ const triangles = [];+ for (let corner = 0; corner < indices.length; corner += 3) {+ const first = particleOfVertex[indices[corner]];+ const second = particleOfVertex[indices[corner + 1]];+ const third = particleOfVertex[indices[corner + 2]];+ if (first !== second && second !== third && first !== third) {+ triangles.push(first, second, third);+ }+ }+ return { particleOfVertex, representatives, triangles: Uint32Array.from(triangles) };+}++function edgeKey(first, second, particleCount) {+ return first < second ? first * particleCount + second : second * particleCount + first;+}++// Stretch constraints along every edge, bend constraints between the far corners of two triangles sharing an edge.+function buildConstraints(positions, triangles, particleCount, bendStiffness, stretchStiffness) {+ const edgeNeighbours = new Map();+ for (let corner = 0; corner < triangles.length; corner += 3) {+ for (let side = 0; side < 3; side++) {+ const first = triangles[corner + side];+ const second = triangles[corner + (side + 1) % 3];+ const opposite = triangles[corner + (side + 2) % 3];+ const key = edgeKey(first, second, particleCount);+ const entry = edgeNeighbours.get(key) ?? { first: Math.min(first, second), second: Math.max(first, second), opposites: [] };+ entry.opposites.push(opposite);+ edgeNeighbours.set(key, entry);+ }+ }+ const firsts = [];+ const seconds = [];+ const stiffnesses = [];+ const add = (first, second, stiffness) => {+ firsts.push(first);+ seconds.push(second);+ stiffnesses.push(stiffness);+ };+ const orderedEntries = [...edgeNeighbours.entries()].sort((left, right) => left[0] - right[0]);+ for (const [, entry] of orderedEntries) {+ add(entry.first, entry.second, stretchStiffness);+ }+ if (bendStiffness > 0) {+ for (const [, entry] of orderedEntries) {+ if (entry.opposites.length === 2 && entry.opposites[0] !== entry.opposites[1]) {+ add(entry.opposites[0], entry.opposites[1], bendStiffness);+ }+ }+ }+ const restLengths = new Float64Array(firsts.length);+ for (let constraint = 0; constraint < firsts.length; constraint++) {+ const a = firsts[constraint] * 3;+ const b = seconds[constraint] * 3;+ restLengths[constraint] = Math.hypot(positions[a] - positions[b], positions[a + 1] - positions[b + 1], positions[a + 2] - positions[b + 2]);+ }+ return { count: firsts.length, firsts: Uint32Array.from(firsts), seconds: Uint32Array.from(seconds), stiffnesses: Float64Array.from(stiffnesses), restLengths };+}++// Rest area each particle represents (a third of its triangles), used to turn wind pressure into acceleration.+function particleAreas(positions, triangles, particleCount) {+ const areas = new Float64Array(particleCount);+ for (let corner = 0; corner < triangles.length; corner += 3) {+ const area = triangleNormal(positions, triangles[corner], triangles[corner + 1], triangles[corner + 2], [0, 0, 0]) / 2;+ for (let side = 0; side < 3; side++) {+ areas[triangles[corner + side]] += area / 3;+ }+ }+ return areas;+}++// Writes the unit normal into `normal` and returns twice the triangle area.+function triangleNormal(positions, first, second, third, normal) {+ const a = first * 3;+ const b = second * 3;+ const c = third * 3;+ const edgeOne = [positions[b] - positions[a], positions[b + 1] - positions[a + 1], positions[b + 2] - positions[a + 2]];+ const edgeTwo = [positions[c] - positions[a], positions[c + 1] - positions[a + 1], positions[c + 2] - positions[a + 2]];+ const x = edgeOne[1] * edgeTwo[2] - edgeOne[2] * edgeTwo[1];+ const y = edgeOne[2] * edgeTwo[0] - edgeOne[0] * edgeTwo[2];+ const z = edgeOne[0] * edgeTwo[1] - edgeOne[1] * edgeTwo[0];+ const length = Math.sqrt(x * x + y * y + z * z);+ if (length > 0) {+ normal[0] = x / length;+ normal[1] = y / length;+ normal[2] = z / length;+ }+ return length;+}++function applyWind(state, wind, areas, triangles, secondsPerSubstep, density) {+ const { positions, velocities, particleCount } = state;+ const pressures = state.windScratch;+ pressures.fill(0);+ const normal = [0, 0, 0];+ for (let corner = 0; corner < triangles.length; corner += 3) {+ const first = triangles[corner];+ const second = triangles[corner + 1];+ const third = triangles[corner + 2];+ const doubleArea = triangleNormal(positions, first, second, third, normal);+ if (doubleArea === 0) continue;+ let relative = 0;+ for (let axis = 0; axis < 3; axis++) {+ const velocity = (velocities[first * 3 + axis] + velocities[second * 3 + axis] + velocities[third * 3 + axis]) / 3;+ relative += (wind[axis] - velocity) * normal[axis];+ }+ const pressure = 0.5 * AIR_DENSITY * relative * Math.abs(relative);+ const force = pressure * doubleArea / 2 / 3;+ for (const particle of [first, second, third]) {+ for (let axis = 0; axis < 3; axis++) {+ pressures[particle * 3 + axis] += force * normal[axis];+ }+ }+ }+ for (let particle = 0; particle < particleCount; particle++) {+ const mass = Math.max(areas[particle], 1e-9) * density;+ for (let axis = 0; axis < 3; axis++) {+ velocities[particle * 3 + axis] += pressures[particle * 3 + axis] / mass * secondsPerSubstep;+ }+ }+}++function solveDistances(positions, inverseMasses, constraints) {+ const { count, firsts, seconds, stiffnesses, restLengths } = constraints;+ for (let constraint = 0; constraint < count; constraint++) {+ const first = firsts[constraint];+ const second = seconds[constraint];+ const weightSum = inverseMasses[first] + inverseMasses[second];+ if (weightSum === 0) continue;+ const a = first * 3;+ const b = second * 3;+ const dx = positions[b] - positions[a];+ const dy = positions[b + 1] - positions[a + 1];+ const dz = positions[b + 2] - positions[a + 2];+ const length = Math.sqrt(dx * dx + dy * dy + dz * dz);+ if (length < 1e-12) continue;+ const correction = stiffnesses[constraint] * (length - restLengths[constraint]) / (length * weightSum);+ positions[a] += dx * correction * inverseMasses[first];+ positions[a + 1] += dy * correction * inverseMasses[first];+ positions[a + 2] += dz * correction * inverseMasses[first];+ positions[b] -= dx * correction * inverseMasses[second];+ positions[b + 1] -= dy * correction * inverseMasses[second];+ positions[b + 2] -= dz * correction * inverseMasses[second];+ }+}++// Each collider pushes a point to its surface plus `thickness` and reports the outward normal, or null when clear.+function pushOutOfBall(point, ball, thickness, normal) {+ const dx = point[0] - ball.center[0];+ const dy = point[1] - ball.center[1];+ const dz = point[2] - ball.center[2];+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);+ const reach = ball.radius + thickness;+ if (distance >= reach) return false;+ if (distance > 1e-12) {+ normal[0] = dx / distance;+ normal[1] = dy / distance;+ normal[2] = dz / distance;+ } else {+ normal[0] = 0;+ normal[1] = 1;+ normal[2] = 0;+ }+ for (let axis = 0; axis < 3; axis++) {+ point[axis] = ball.center[axis] + normal[axis] * reach;+ }+ return true;+}++function pushOutOfBox(point, box, thickness, normal) {+ const { center, axes, halfExtents } = box;+ const offset = [point[0] - center[0], point[1] - center[1], point[2] - center[2]];+ const local = axes.map(axis => offset[0] * axis[0] + offset[1] * axis[1] + offset[2] * axis[2]);+ const closest = local.map((value, index) => Math.min(Math.max(value, -halfExtents[index]), halfExtents[index]));+ const delta = local.map((value, index) => value - closest[index]);+ const distance = Math.hypot(...delta);+ const pushed = [...local];+ const localNormal = [0, 0, 0];+ if (distance > 1e-12) {+ if (distance >= thickness) return false;+ for (let index = 0; index < 3; index++) {+ localNormal[index] = delta[index] / distance;+ pushed[index] = closest[index] + localNormal[index] * thickness;+ }+ } else {+ let shallowest = 0;+ for (let index = 1; index < 3; index++) {+ if (halfExtents[index] - Math.abs(local[index]) < halfExtents[shallowest] - Math.abs(local[shallowest])) shallowest = index;+ }+ const sign = local[shallowest] >= 0 ? 1 : -1;+ localNormal[shallowest] = sign;+ pushed[shallowest] = sign * (halfExtents[shallowest] + thickness);+ }+ for (let axis = 0; axis < 3; axis++) {+ normal[axis] = 0;+ point[axis] = center[axis];+ for (let index = 0; index < 3; index++) {+ normal[axis] += axes[index][axis] * localNormal[index];+ point[axis] += axes[index][axis] * pushed[index];+ }+ }+ return true;+}++function collide(state, previous, colliders, thickness, friction) {+ const { positions, inverseMasses, particleCount } = state;+ const point = [0, 0, 0];+ const normal = [0, 0, 0];+ for (let particle = 0; particle < particleCount; particle++) {+ if (inverseMasses[particle] === 0) continue;+ const offset = particle * 3;+ point[0] = positions[offset];+ point[1] = positions[offset + 1];+ point[2] = positions[offset + 2];+ for (const collider of colliders) {+ const touched = collider.kind === 'ball' ? pushOutOfBall(point, collider, thickness, normal) : pushOutOfBox(point, collider, thickness, normal);+ if (!touched) continue;+ // Friction removes part of the sideways travel this substep, so cloth drags over a surface instead of skating.+ const travel = [point[0] - previous[offset], point[1] - previous[offset + 1], point[2] - previous[offset + 2]];+ const along = travel[0] * normal[0] + travel[1] * normal[1] + travel[2] * normal[2];+ for (let axis = 0; axis < 3; axis++) {+ point[axis] -= (travel[axis] - along * normal[axis]) * friction;+ }+ }+ positions[offset] = point[0];+ positions[offset + 1] = point[1];+ positions[offset + 2] = point[2];+ }+}++function checkWork(particleCount, constraintCount, triangleCount, colliderCount, frameCount) {+ const work = frameCount * CLOTH_LIMITS.substeps * (CLOTH_LIMITS.iterations * constraintCount + triangleCount + particleCount * (colliderCount + 1));+ if (particleCount > CLOTH_LIMITS.maxParticles) {+ throw new RangeError(`Cloth has ${particleCount} particles; the limit is ${CLOTH_LIMITS.maxParticles}. Use a coarser grid.`);+ }+ if (particleCount * frameCount > CLOTH_LIMITS.maxFrameParticles) {+ throw new RangeError(`Cloth would record ${particleCount * frameCount} particle positions; the limit is ${CLOTH_LIMITS.maxFrameParticles}. Use a shorter duration or a coarser grid.`);+ }+ if (work > CLOTH_LIMITS.maxWork) {+ throw new RangeError(`Cloth needs ${Math.round(work)} solver operations; the limit is ${CLOTH_LIMITS.maxWork}. Use a shorter duration or a coarser grid.`);+ }+}++/**+ * Simulate one sheet. `positions` are world-space rest positions (3 numbers per particle), `triangles` index them.+ * Options: pinned (particle indices that stay put), gravity, wind (m/s), stiffness and bend (0 to 1), density (kg/m2),+ * damping (1/s), friction (0 to 1), thickness (m), colliders ({ kind: 'ball', center, radius } or+ * { kind: 'box', center, axes, halfExtents }), frameCount and framesPerSecond.+ * Returns the recorded frames: Float32Array of frameCount * particleCount * 3.+ */+export function bakeCloth(positions, triangles, options) {+ const particleCount = positions.length / 3;+ const colliders = options.colliders ?? [];+ const constraints = buildConstraints(positions, triangles, particleCount, options.bend ?? 0.1, options.stiffness ?? 0.9);+ checkWork(particleCount, constraints.count, triangles.length / 3, colliders.length, options.frameCount);+ const gravity = options.gravity ?? GRAVITY_DEFAULT;+ const wind = options.wind ?? [0, 0, 0];+ const density = options.density ?? 0.2;+ const damping = options.damping ?? 0.3;+ const friction = options.friction ?? 0.3;+ const thickness = options.thickness ?? 0.01;+ const hasWind = wind.some(component => component !== 0);+ const frameSeconds = 1 / (options.framesPerSecond ?? 60);+ const substepSeconds = frameSeconds / CLOTH_LIMITS.substeps;+ const dampingFactor = Math.exp(-damping * substepSeconds);+ const areas = hasWind ? particleAreas(positions, triangles, particleCount) : null;+ const inverseMasses = new Float64Array(particleCount).fill(1);+ for (const particle of options.pinned ?? []) {+ inverseMasses[particle] = 0;+ }+ const state = {+ particleCount, inverseMasses, positions: Float64Array.from(positions),+ velocities: new Float64Array(positions.length), windScratch: new Float64Array(positions.length),+ };+ const previous = new Float64Array(positions.length);+ const frames = new Float32Array(options.frameCount * positions.length);+ frames.set(Float32Array.from(positions), 0);+ for (let frame = 1; frame < options.frameCount; frame++) {+ for (let substep = 0; substep < CLOTH_LIMITS.substeps; substep++) {+ if (hasWind) applyWind(state, wind, areas, triangles, substepSeconds, density);+ previous.set(state.positions);+ for (let particle = 0; particle < particleCount; particle++) {+ if (inverseMasses[particle] === 0) continue;+ for (let axis = 0; axis < 3; axis++) {+ const index = particle * 3 + axis;+ state.velocities[index] += gravity[axis] * substepSeconds;+ state.positions[index] += state.velocities[index] * substepSeconds;+ }+ }+ for (let iteration = 0; iteration < CLOTH_LIMITS.iterations; iteration++) {+ solveDistances(state.positions, inverseMasses, constraints);+ collide(state, previous, colliders, thickness, friction);+ }+ for (let index = 0; index < positions.length; index++) {+ state.velocities[index] = (state.positions[index] - previous[index]) / substepSeconds * dampingFactor;+ }+ }+ if (!state.positions.every(Number.isFinite)) {+ throw new RangeError('Cloth became unstable (non-finite positions). Lower the wind, raise density or use a finer grid.');+ }+ frames.set(Float32Array.from(state.positions), frame * positions.length);+ }+ return Object.freeze({ particleCount, frameCount: options.frameCount, framesPerSecond: options.framesPerSecond ?? 60, frames, constraintCount: constraints.count });+}++/** Write the particle positions at `time` into `target`, a linear blend of the two nearest recorded frames. */+export function sampleClothFrames(recording, time, target) {+ const stride = recording.particleCount * 3;+ const position = Math.min(Math.max(time * recording.framesPerSecond, 0), recording.frameCount - 1);+ const lower = Math.floor(position);+ const upper = Math.min(lower + 1, recording.frameCount - 1);+ const blend = position - lower;+ for (let index = 0; index < stride; index++) {+ const before = recording.frames[lower * stride + index];+ const after = recording.frames[upper * stride + index];+ target[index] = before + (after - before) * blend;+ }+ return target;+}diff --git a/src/geometry.js b/src/geometry.jsindex c07ecb29..ccb2ced4 100644--- a/src/geometry.js+++ b/src/geometry.js@@ -85,6 +85,12 @@ export function sphere(segments = 64, rings = 40) {return result;}+// A flat unit sheet in XY facing +Z with a regular grid of vertices: the rest shape for cloth and for flat banners.+export function grid(segments = 16) {+ integer(segments, 1, 64, 'segments');+ return surface(segments, segments, (across, down) => ({ position: [across - 0.5, 0.5 - down, 0], normal: [0, 0, 1] }));+}+// The torus lies in XY, facing +Z. Partial arcs are useful for interrupted armor rings.export function torus(tubeRadius = 0.08, segments = 96, sides = 24, arc = FULL_TURN, start = 0) {finiteFloat(tubeRadius, 'tubeRadius');diff --git a/tests/cloth-blender.test.js b/tests/cloth-blender.test.jsnew file mode 100644index 00000000..4cb02d06--- /dev/null+++ b/tests/cloth-blender.test.js@@ -0,0 +1,58 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import { createAgentScene } from '../src/agent-scene.js';++// Golden positions come from scripts/blender-cloth.py (Blender's cloth solver, default stiffness, same mass per area).+const golden = JSON.parse(readFileSync(new URL('./fixtures/blender/cloth-golden.json', import.meta.url), 'utf8'));+const SEGMENTS = golden.segments;+const BALL_RADIUS = 0.4;++function recipe(nodes, cloth) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'sheet', type: 'grid', segments: SEGMENTS }, { id: 'ball', type: 'sphere' }],+ materials: [{ id: 'paint', color: [1, 1, 1] }],+ nodes, cloth,+ };+}++function worldPositions(scene) {+ const part = scene.parts[0];+ const positions = part.geometry.positions;+ const matrix = part.matrix;+ const points = [];+ for (let index = 0; index < positions.length; index += 3) {+ points.push([0, 1, 2].map(axis => matrix[axis] * positions[index] + matrix[4 + axis] * positions[index + 1] + matrix[8 + axis] * positions[index + 2] + matrix[12 + axis]));+ }+ return points;+}++function meanDistance(ours, theirs) {+ const total = ours.reduce((sum, point, index) => sum + Math.hypot(...point.map((value, axis) => value - theirs[index][axis])), 0);+ return total / ours.length;+}++test('a hanging sheet ends where Blender hangs it, within 1 percent of the sheet height', () => {+ const scene = createAgentScene(recipe(+ [{ id: 'flag', geometry: 'sheet', material: 'paint', translation: [0, 2, 0], scale: [2, 1.5, 1] }],+ { duration: golden.seconds, sheets: [{ node: 'flag', pin: ['top'] }] },+ ));+ scene.sampleMotion(golden.seconds);+ const ours = worldPositions(scene);+ const theirs = golden.cases['hanging-flag'].positions;+ assert.ok(meanDistance(ours, theirs) / 1.5 < 0.01, 'mean vertex distance to the Blender bake');+ assert.ok(Math.abs(Math.min(...ours.map(point => point[1])) - Math.min(...theirs.map(point => point[1]))) < 0.01, 'free edge height');+});++test('a sheet dropped on a ball stays outside it in 67.js and in Blender, though the drape shapes differ', () => {+ const scene = createAgentScene(recipe(+ [{ id: 'sheet', geometry: 'sheet', material: 'paint', translation: [0, 1, 0], rotation: [-0.7071068, 0, 0, 0.7071068], scale: [1.6, 1.6, 1] },+ { id: 'ball', geometry: 'ball', material: 'paint', scale: [BALL_RADIUS, BALL_RADIUS, BALL_RADIUS] }],+ { duration: golden.seconds, sheets: [{ node: 'sheet' }], colliders: [{ node: 'ball', shape: 'ball' }] },+ ));+ scene.sampleMotion(golden.seconds);+ const nearest = points => Math.min(...points.map(point => Math.hypot(...point)));+ assert.ok(nearest(worldPositions(scene)) > BALL_RADIUS - 0.01, 'no 67.js particle inside the ball');+ assert.ok(nearest(golden.cases['drape-over-ball'].positions) > BALL_RADIUS - 0.03, 'no Blender vertex inside the ball');+});diff --git a/tests/cloth.test.js b/tests/cloth.test.jsnew file mode 100644index 00000000..2442c985--- /dev/null+++ b/tests/cloth.test.js@@ -0,0 +1,278 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene, agentSceneModulesNeeded } from '../src/agent-scene.js';+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';+import { bakeCloth, sampleClothFrames, weldVertices, CLOTH_LIMITS } from '../src/cloth.js';++function flagRecipe(cloth, extraNodes = [], segments = 12) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [+ { id: 'sheet', type: 'grid', segments },+ { id: 'ball', type: 'sphere' },+ { id: 'slab', type: 'box', bevel: 0 },+ ],+ materials: [{ id: 'fabric', color: [0.7, 0.2, 0.2], doubleSided: true }, { id: 'stone', color: [0.5, 0.5, 0.5] }],+ nodes: [+ { id: 'flag', geometry: 'sheet', material: 'fabric', translation: [0, 2, 0], scale: [2, 1.5, 1] },+ ...extraNodes,+ ],+ cloth,+ };+}++const hangingFlag = { duration: 2, sheets: [{ node: 'flag', pin: ['top'] }] };++function clothPositions(scene, nodeId = 'flag') {+ return Array.from(scene.parts.find(part => part.name === nodeId).geometry.positions);+}++function worldY(scene, nodeId, localY) {+ const matrix = scene.parts.find(part => part.name === nodeId).matrix;+ return matrix[5] * localY + matrix[13];+}++test('the same time gives the same cloth positions, and a seek backwards reproduces them', () => {+ const scene = createAgentScene(flagRecipe({ ...hangingFlag, wind: [0, 0, 6] }));+ scene.sampleMotion(1.3);+ const first = clothPositions(scene);+ scene.sampleMotion(0.4);+ const earlier = clothPositions(scene);+ assert.notDeepEqual(earlier, first);+ scene.sampleMotion(1.3);+ assert.deepEqual(clothPositions(scene), first, 'seeking back to the same time repeats the positions');+ scene.sampleMotion(2);+ scene.sampleMotion(0.4);+ assert.deepEqual(clothPositions(scene), earlier, 'seeking backwards from the end repeats the earlier frame');+ const fresh = createAgentScene(flagRecipe({ ...hangingFlag, wind: [0, 0, 6] }));+ fresh.sampleMotion(1.3);+ assert.deepEqual(clothPositions(fresh), first, 'a second scene from the same recipe bakes identical frames');+});++test('time zero is the rest sheet, null restores it and a seek counts as a topology change', () => {+ const scene = createAgentScene(flagRecipe(hangingFlag));+ const restGeometry = scene.parts[0].geometry;+ const initialTopology = scene.topologyRevision;+ scene.sampleMotion(1);+ assert.notEqual(scene.parts[0].geometry, restGeometry);+ assert.ok(scene.topologyRevision > initialTopology, 'renderers must swap the deformed part');+ scene.sampleMotion(0);+ assert.equal(scene.parts[0].geometry, restGeometry);+ scene.sampleMotion(1);+ scene.sampleMotion(null);+ assert.equal(scene.parts[0].geometry, restGeometry);+ scene.sampleMotion(1);+ scene.sampleMotion(99);+ const held = clothPositions(scene);+ scene.sampleMotion(2);+ assert.deepEqual(clothPositions(scene), held, 'cloth holds its last frame after its duration');+});++test('pinned particles stay put while the rest of the sheet falls and hangs below the pins', () => {+ const scene = createAgentScene(flagRecipe(hangingFlag));+ scene.sampleMotion(2);+ const positions = clothPositions(scene);+ let topY = -Infinity;+ let bottomY = Infinity;+ for (let index = 0; index < positions.length; index += 3) {+ topY = Math.max(topY, positions[index + 1]);+ bottomY = Math.min(bottomY, positions[index + 1]);+ }+ assert.ok(Math.abs(topY - 0.5) < 1e-4, `the pinned top row did not move, got ${topY}`);+ assert.ok(bottomY < -0.1 && bottomY > -0.75, `the free edge hangs, got ${bottomY}`);+ assert.ok(worldY(scene, 'flag', topY) > 2.7, 'pinned row stays at its authored height');+});++test('stretch stays bounded under gravity and wind', () => {+ const recording = bakeSheet({ wind: [0, 0, 8], frames: 121, pinned: 'top' });+ const { positions, triangles } = recording.rest;+ const last = new Float32Array(recording.result.particleCount * 3);+ sampleClothFrames(recording.result, 2, last);+ let longest = 0;+ for (let corner = 0; corner < triangles.length; corner += 3) {+ for (let side = 0; side < 3; side++) {+ const first = triangles[corner + side] * 3;+ const second = triangles[corner + (side + 1) % 3] * 3;+ const restLength = Math.hypot(positions[first] - positions[second], positions[first + 1] - positions[second + 1], positions[first + 2] - positions[second + 2]);+ const length = Math.hypot(last[first] - last[second], last[first + 1] - last[second + 1], last[first + 2] - last[second + 2]);+ longest = Math.max(longest, length / restLength);+ }+ }+ assert.ok(longest < 1.25, `edges stretch at most 25 percent, got ${longest}`);+});++test('wind pushes the sheet along the wind and a calm sheet stays in its plane', () => {+ const calm = createAgentScene(flagRecipe(hangingFlag));+ const windy = createAgentScene(flagRecipe({ ...hangingFlag, wind: [0, 0, 8] }));+ calm.sampleMotion(1.5);+ windy.sampleMotion(1.5);+ const depth = scene => {+ const positions = clothPositions(scene);+ let total = 0;+ for (let index = 2; index < positions.length; index += 3) total += positions[index];+ return total / (positions.length / 3);+ };+ assert.ok(Math.abs(depth(calm)) < 1e-3, 'no wind, no sideways drift');+ assert.ok(depth(windy) > 0.05, `wind along +z pushes the sheet, got ${depth(windy)}`);+});++test('a sheet dropped on a ball drapes over it and never enters it', () => {+ const recipe = flagRecipe(+ { duration: 2, sheets: [{ node: 'flag' }], colliders: [{ node: 'ball', shape: 'ball' }] },+ [{ id: 'ball', geometry: 'ball', material: 'stone', translation: [0, 0, 0], scale: [0.5, 0.5, 0.5] }],+ );+ recipe.nodes[0] = { id: 'flag', geometry: 'sheet', material: 'fabric', translation: [0, 1, 0], rotation: [-0.7071068, 0, 0, 0.7071068], scale: [1.6, 1.6, 1] };+ const scene = createAgentScene(recipe);+ scene.sampleMotion(2);+ const matrix = scene.parts[0].matrix;+ const localPositions = clothPositions(scene);+ let nearest = Infinity;+ let lowest = Infinity;+ for (let index = 0; index < localPositions.length; index += 3) {+ const x = matrix[0] * localPositions[index] + matrix[4] * localPositions[index + 1] + matrix[8] * localPositions[index + 2] + matrix[12];+ const y = matrix[1] * localPositions[index] + matrix[5] * localPositions[index + 1] + matrix[9] * localPositions[index + 2] + matrix[13];+ const z = matrix[2] * localPositions[index] + matrix[6] * localPositions[index + 1] + matrix[10] * localPositions[index + 2] + matrix[14];+ nearest = Math.min(nearest, Math.hypot(x, y, z));+ lowest = Math.min(lowest, y);+ }+ assert.ok(nearest > 0.5 - 0.01, `no particle is inside the ball, nearest ${nearest}`);+ assert.ok(lowest < 0.4, `the edges fall past the ball's equator, lowest ${lowest}`);+});++test('a box collider acts as a floor the sheet stops on', () => {+ const recipe = flagRecipe(+ { duration: 2, sheets: [{ node: 'flag' }], colliders: [{ node: 'floor' }] },+ [{ id: 'floor', geometry: 'slab', material: 'stone', translation: [0, 0.5, 0], scale: [8, 0.2, 8] }],+ );+ recipe.nodes[0] = { id: 'flag', geometry: 'sheet', material: 'fabric', translation: [0, 2, 0], rotation: [-0.7071068, 0, 0, 0.7071068], scale: [1, 1, 1] };+ const scene = createAgentScene(recipe);+ scene.sampleMotion(2);+ const matrix = scene.parts[0].matrix;+ const positions = clothPositions(scene);+ let lowest = Infinity;+ for (let index = 0; index < positions.length; index += 3) {+ lowest = Math.min(lowest, matrix[1] * positions[index] + matrix[5] * positions[index + 1] + matrix[9] * positions[index + 2] + matrix[13]);+ }+ assert.ok(lowest >= 0.6 - 1e-3, `the sheet rests on the floor top at 0.6, lowest ${lowest}`);+});++test('the report lists particles, pinned count and final bounds', () => {+ const scene = createAgentScene(flagRecipe(hangingFlag));+ const report = scene.inspect().cloth;+ assert.equal(report.sheets[0].node, 'flag');+ assert.equal(report.sheets[0].particles, 13 * 13);+ assert.equal(report.sheets[0].pinned, 13);+ assert.equal(report.frames, 121);+ assert.equal(createAgentScene({ ...flagRecipe(null) }).inspect().cloth, undefined);+});++test('cloth recipes need the cloth module and plain recipes do not', () => {+ assert.deepEqual(agentSceneModulesNeeded(flagRecipe(hangingFlag)), ['cloth']);+ assert.deepEqual(agentSceneModulesNeeded(flagRecipe(null)), []);+});++test('set-cloth edits the section, null clears it and the recipe round trips', () => {+ const scene = createAgentScene(flagRecipe(null));+ assert.throws(() => scene.sampleMotion(1), /no motion, physics or cloth/);+ scene.apply([{ type: 'set-cloth', cloth: hangingFlag }], { expectedRevision: scene.revision });+ scene.sampleMotion(1);+ const exported = scene.exportRecipe();+ assert.equal(exported.cloth.sheets[0].node, 'flag');+ const again = createAgentScene(exported);+ again.sampleMotion(1);+ assert.deepEqual(clothPositions(again), clothPositions(scene));+ scene.apply([{ type: 'set-cloth', cloth: null }], { expectedRevision: scene.revision });+ assert.equal(scene.exportRecipe().cloth, null);+ assert.equal(scene.parts[0].geometry.positions.length, createAgentScene(flagRecipe(null)).parts[0].geometry.positions.length);+});++test('editing a scene while the cloth is posed returns the rest sheet and tells renderers', () => {+ const scene = createAgentScene(flagRecipe(hangingFlag));+ scene.sampleMotion(1);+ const topology = scene.topologyRevision;+ scene.apply([{ type: 'set-material', id: 'fabric', roughness: 0.4 }], { expectedRevision: scene.revision });+ assert.ok(scene.topologyRevision > topology);+ assert.equal(scene.parts[0].geometry.positions.length, 13 * 13 * 3);+});++test('hostile cloth sections are rejected before any solver runs', () => {+ const bad = (cloth, pattern, nodes) => assert.throws(() => createAgentScene(flagRecipe(cloth, nodes)), pattern);+ bad({ duration: 2, sheets: [] }, /at least one sheet/);+ bad({ duration: 0, sheets: [{ node: 'flag' }] }, /duration/);+ bad({ duration: 11, sheets: [{ node: 'flag' }] }, /duration/);+ bad({ duration: 2, sheets: [{ node: 'missing' }] }, /not found/);+ bad({ duration: 2, sheets: [{ node: 'flag' }, { node: 'flag' }] }, /twice/);+ bad({ duration: 2, sheets: [{ node: 'flag', stiffness: 2 }] }, /stiffness/);+ bad({ duration: 2, sheets: [{ node: 'flag', density: 0 }] }, /density/);+ bad({ duration: 2, sheets: [{ node: 'flag', pin: ['middle'] }] }, /pin/);+ bad({ duration: 2, sheets: [{ node: 'flag', surprise: 1 }] }, /Unknown/);+ bad({ duration: 2, surprise: 1, sheets: [{ node: 'flag' }] }, /Unknown/);+ bad({ duration: 2, wind: [0, 0, NaN], sheets: [{ node: 'flag' }] }, /finite/);+ bad({ duration: 2, wind: [0, 0, 1e9], sheets: [{ node: 'flag' }] }, /wind/);+ bad({ duration: 2, gravity: [0, -Infinity, 0], sheets: [{ node: 'flag' }] }, /finite/);+ bad({ duration: 2, sheets: Array.from({ length: 9 }, () => ({ node: 'flag' })) }, /at most 8/);+ bad({ duration: 2, sheets: [{ node: 'flag' }], colliders: Array.from({ length: 17 }, () => ({ node: 'flag' })) }, /at most 16/);+ bad({ duration: 2, sheets: [{ node: 'flag' }], colliders: [{ node: 'flag' }] }, /twice/);+ bad({ duration: 2, sheets: [{ node: 'flag' }], colliders: [{ node: 'stone', shape: 'cone' }] }, /shape/, [{ id: 'stone', geometry: 'ball', material: 'stone' }]);+ bad({ duration: 2, sheets: [{ node: 'flag' }], colliders: [{ node: 'child' }] }, /root node/, [{ id: 'child', parent: 'flag', geometry: 'ball', material: 'stone' }]);+ bad('cloth', /plain object/);+ bad({ duration: 2, sheets: 'flag' }, /array/);+});++test('particle and frame limits reject oversized bakes with a clear error', () => {+ const huge = flagRecipe({ duration: 10, sheets: [{ node: 'flag' }] }, [], 64);+ assert.throws(() => createAgentScene(huge), /solver operations|particle positions/);+ assert.throws(() => bakeCloth(new Float64Array(3 * (CLOTH_LIMITS.maxParticles + 1)), new Uint32Array([0, 1, 2]), { frameCount: 2 }), /particles/);+ const bounded = flagRecipe({ duration: 1, sheets: [{ node: 'flag' }] }, [], 64);+ assert.ok(createAgentScene(bounded).parts.length === 1, 'a 64 by 64 grid for one second fits');+});++test('a cloth node cannot also carry motion or a physics body', () => {+ const withMotion = flagRecipe(hangingFlag);+ withMotion.motion = { duration: 1, loop: false, tracks: [{ kind: 'node', id: 'flag', property: 'translation', interpolation: 'linear', keys: [{ time: 0, value: [0, 2, 0] }, { time: 1, value: [1, 2, 0] }] }] };+ assert.throws(() => createAgentScene(withMotion), /motion/);+});++test('welding joins vertices at one position so a seam cannot tear', () => {+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]);+ const welded = weldVertices(positions, new Uint32Array([0, 1, 2, 3, 4, 5]));+ assert.equal(welded.representatives.length, 4);+ assert.equal(welded.particleOfVertex[1], welded.particleOfVertex[3]);+ assert.equal(welded.triangles.length, 6);+});++test('capabilities describe cloth limits that match the solver', () => {+ assert.equal(AGENT_SCENE_CAPABILITIES.cloth.limits.maxParticles, CLOTH_LIMITS.maxParticles);+ assert.equal(AGENT_SCENE_CAPABILITIES.cloth.limits.substeps, CLOTH_LIMITS.substeps);+ assert.equal(AGENT_SCENE_CAPABILITIES.cloth.limits.iterations, CLOTH_LIMITS.iterations);+ assert.ok(AGENT_SCENE_CAPABILITIES.operations.includes('set-cloth'));+ assert.ok(AGENT_SCENE_CAPABILITIES.geometryTypes.includes('grid'));+});++function bakeSheet({ wind, frames, pinned }) {+ const segments = 8;+ const positions = [];+ for (let row = 0; row <= segments; row++) {+ for (let column = 0; column <= segments; column++) {+ positions.push(column / segments - 0.5, 2 - row / segments, 0);+ }+ }+ const triangles = [];+ for (let row = 0; row < segments; row++) {+ for (let column = 0; column < segments; column++) {+ const first = row * (segments + 1) + column;+ const below = first + segments + 1;+ triangles.push(first, first + 1, below, first + 1, below + 1, below);+ }+ }+ const rest = { positions: Float64Array.from(positions), triangles: Uint32Array.from(triangles) };+ const topRow = pinned === 'top' ? Array.from({ length: segments + 1 }, (_, column) => column) : [];+ const result = bakeCloth(rest.positions, rest.triangles, { wind, pinned: topRow, frameCount: frames });+ return { rest, result };+}++test('the solver is bit-exact between runs', () => {+ const first = bakeSheet({ wind: [1, 0, 4], frames: 61, pinned: 'top' }).result.frames;+ const second = bakeSheet({ wind: [1, 0, 4], frames: 61, pinned: 'top' }).result.frames;+ assert.deepEqual(Buffer.from(first.buffer), Buffer.from(second.buffer));+});diff --git a/tests/fixtures/blender/cloth-golden.json b/tests/fixtures/blender/cloth-golden.jsonnew file mode 100644index 00000000..4dc25d3a--- /dev/null+++ b/tests/fixtures/blender/cloth-golden.json@@ -0,0 +1,1707 @@+{+ "blender": "5.2.2 LTS",+ "seconds": 2,+ "segments": 12,+ "cases": {+ "hanging-flag": {+ "positions": [+ [+ -1.0,+ 2.75,+ -0.0+ ],+ [+ -0.83333,+ 2.75,+ -0.0+ ],+ [+ -0.66667,+ 2.75,+ -0.0+ ],+ [+ -0.5,+ 2.75,+ -0.0+ ],+ [+ -0.33333,+ 2.75,+ -0.0+ ],+ [+ -0.16667,+ 2.75,+ -0.0+ ],+ [+ 0.0,+ 2.75,+ -0.0+ ],+ [+ 0.16667,+ 2.75,+ -0.0+ ],+ [+ 0.33333,+ 2.75,+ -0.0+ ],+ [+ 0.5,+ 2.75,+ -0.0+ ],+ [+ 0.66667,+ 2.75,+ -0.0+ ],+ [+ 0.83333,+ 2.75,+ -0.0+ ],+ [+ 1.0,+ 2.75,+ -0.0+ ],+ [+ -1.0,+ 2.625,+ -0.0+ ],+ [+ -0.83333,+ 2.625,+ -0.0+ ],+ [+ -0.66667,+ 2.625,+ -0.0+ ],+ [+ -0.5,+ 2.625,+ -0.0+ ],+ [+ -0.33333,+ 2.625,+ -0.0+ ],+ [+ -0.16667,+ 2.625,+ -0.0+ ],+ [+ 0.0,+ 2.625,+ -0.0+ ],+ [+ 0.16667,+ 2.625,+ -0.0+ ],+ [+ 0.33333,+ 2.625,+ -0.0+ ],+ [+ 0.5,+ 2.625,+ -0.0+ ],+ [+ 0.66667,+ 2.625,+ -0.0+ ],+ [+ 0.83333,+ 2.625,+ -0.0+ ],+ [+ 1.0,+ 2.625,+ -0.0+ ],+ [+ -1.0,+ 2.49999,+ -0.0+ ],+ [+ -0.83333,+ 2.49999,+ -0.0+ ],+ [+ -0.66667,+ 2.49999,+ -0.0+ ],+ [+ -0.5,+ 2.49999,+ -0.0+ ],+ [+ -0.33333,+ 2.49999,+ -0.0+ ],+ [+ -0.16667,+ 2.49999,+ -0.0+ ],+ [+ 0.0,+ 2.49999,+ -0.0+ ],+ [+ 0.16667,+ 2.49999,+ -0.0+ ],+ [+ 0.33333,+ 2.49999,+ -0.0+ ],+ [+ 0.5,+ 2.49999,+ -0.0+ ],+ [+ 0.66667,+ 2.49999,+ -0.0+ ],+ [+ 0.83333,+ 2.49999,+ -0.0+ ],+ [+ 1.0,+ 2.49999,+ -0.0+ ],+ [+ -1.0,+ 2.37499,+ -0.0+ ],+ [+ -0.83333,+ 2.37499,+ -0.0+ ],+ [+ -0.66666,+ 2.37499,+ -0.0+ ],+ [+ -0.5,+ 2.37499,+ -0.0+ ],+ [+ -0.33333,+ 2.37499,+ -0.0+ ],+ [+ -0.16667,+ 2.37499,+ -0.0+ ],+ [+ 0.0,+ 2.37499,+ -0.0+ ],+ [+ 0.16667,+ 2.37499,+ -0.0+ ],+ [+ 0.33333,+ 2.37499,+ -0.0+ ],+ [+ 0.5,+ 2.37499,+ -0.0+ ],+ [+ 0.66666,+ 2.37499,+ -0.0+ ],+ [+ 0.83333,+ 2.37499,+ -0.0+ ],+ [+ 1.0,+ 2.37499,+ -0.0+ ],+ [+ -1.0,+ 2.24999,+ -0.0+ ],+ [+ -0.83333,+ 2.24999,+ -0.0+ ],+ [+ -0.66666,+ 2.24999,+ -0.0+ ],+ [+ -0.5,+ 2.24999,+ -0.0+ ],+ [+ -0.33333,+ 2.24999,+ -0.0+ ],+ [+ -0.16667,+ 2.24999,+ -0.0+ ],+ [+ 0.0,+ 2.24999,+ -0.0+ ],+ [+ 0.16667,+ 2.24999,+ -0.0+ ],+ [+ 0.33333,+ 2.24999,+ -0.0+ ],+ [+ 0.5,+ 2.24999,+ -0.0+ ],+ [+ 0.66666,+ 2.24999,+ -0.0+ ],+ [+ 0.83333,+ 2.24999,+ -0.0+ ],+ [+ 1.0,+ 2.24999,+ -0.0+ ],+ [+ -1.0,+ 2.12499,+ -0.0+ ],+ [+ -0.83333,+ 2.12499,+ -0.0+ ],+ [+ -0.66666,+ 2.12499,+ -0.0+ ],+ [+ -0.5,+ 2.12499,+ -0.0+ ],+ [+ -0.33333,+ 2.12499,+ -0.0+ ],+ [+ -0.16667,+ 2.12499,+ -0.0+ ],+ [+ -0.0,+ 2.12499,+ -0.0+ ],+ [+ 0.16667,+ 2.12499,+ -0.0+ ],+ [+ 0.33333,+ 2.12499,+ -0.0+ ],+ [+ 0.5,+ 2.12499,+ -0.0+ ],+ [+ 0.66666,+ 2.12499,+ -0.0+ ],+ [+ 0.83333,+ 2.12499,+ -0.0+ ],+ [+ 1.0,+ 2.12499,+ -0.0+ ],+ [+ -1.0,+ 1.99998,+ -0.0+ ],+ [+ -0.83333,+ 1.99998,+ -0.0+ ],+ [+ -0.66667,+ 1.99998,+ -0.0+ ],+ [+ -0.5,+ 1.99998,+ -0.0+ ],+ [+ -0.33333,+ 1.99998,+ -0.0+ ],+ [+ -0.16667,+ 1.99998,+ -0.0+ ],+ [+ -0.0,+ 1.99998,+ -0.0+ ],+ [+ 0.16667,+ 1.99998,+ -0.0+ ],+ [+ 0.33333,+ 1.99998,+ -0.0+ ],+ [+ 0.5,+ 1.99998,+ -0.0+ ],+ [+ 0.66667,+ 1.99998,+ -0.0+ ],+ [+ 0.83333,+ 1.99998,+ -0.0+ ],+ [+ 1.0,+ 1.99998,+ -0.0+ ],+ [+ -1.0,+ 1.87498,+ -0.0+ ],+ [+ -0.83333,+ 1.87498,+ -0.0+ ],+ [+ -0.66667,+ 1.87498,+ -0.0+ ],+ [+ -0.5,+ 1.87498,+ -0.0+ ],+ [+ -0.33333,+ 1.87498,+ -0.0+ ],+ [+ -0.16667,+ 1.87498,+ -0.0+ ],+ [+ -0.0,+ 1.87498,+ -0.0+ ],+ [+ 0.16667,+ 1.87498,+ -0.0+ ],+ [+ 0.33333,+ 1.87498,+ -0.0+ ],+ [+ 0.5,+ 1.87498,+ -0.0+ ],+ [+ 0.66667,+ 1.87498,+ -0.0+ ],+ [+ 0.83333,+ 1.87498,+ -0.0+ ],+ [+ 1.0,+ 1.87498,+ -0.0+ ],+ [+ -1.0,+ 1.74998,+ -0.0+ ],+ [+ -0.83333,+ 1.74998,+ -0.0+ ],+ [+ -0.66667,+ 1.74998,+ -0.0+ ],+ [+ -0.5,+ 1.74998,+ -0.0+ ],+ [+ -0.33333,+ 1.74998,+ -0.0+ ],+ [+ -0.16667,+ 1.74998,+ -0.0+ ],+ [+ -0.0,+ 1.74998,+ -0.0+ ],+ [+ 0.16667,+ 1.74998,+ -0.0+ ],+ [+ 0.33333,+ 1.74998,+ -0.0+ ],+ [+ 0.5,+ 1.74998,+ -0.0+ ],+ [+ 0.66667,+ 1.74998,+ -0.0+ ],+ [+ 0.83333,+ 1.74998,+ -0.0+ ],+ [+ 1.0,+ 1.74998,+ -0.0+ ],+ [+ -1.0,+ 1.62498,+ -0.0+ ],+ [+ -0.83333,+ 1.62498,+ -0.0+ ],+ [+ -0.66667,+ 1.62498,+ -0.0+ ],+ [+ -0.5,+ 1.62498,+ -0.0+ ],+ [+ -0.33333,+ 1.62498,+ -0.0+ ],+ [+ -0.16667,+ 1.62498,+ -0.0+ ],+ [+ -0.0,+ 1.62498,+ -0.0+ ],+ [+ 0.16667,+ 1.62498,+ -0.0+ ],+ [+ 0.33333,+ 1.62498,+ -0.0+ ],+ [+ 0.5,+ 1.62498,+ -0.0+ ],+ [+ 0.66667,+ 1.62498,+ -0.0+ ],+ [+ 0.83333,+ 1.62498,+ -0.0+ ],+ [+ 1.0,+ 1.62498,+ -0.0+ ],+ [+ -1.0,+ 1.49998,+ -0.0+ ],+ [+ -0.83333,+ 1.49998,+ -0.0+ ],+ [+ -0.66667,+ 1.49998,+ -0.0+ ],+ [+ -0.5,+ 1.49998,+ -0.0+ ],+ [+ -0.33333,+ 1.49998,+ -0.0+ ],+ [+ -0.16667,+ 1.49998,+ -0.0+ ],+ [+ 0.0,+ 1.49998,+ -0.0+ ],+ [+ 0.16667,+ 1.49998,+ -0.0+ ],+ [+ 0.33333,+ 1.49998,+ -0.0+ ],+ [+ 0.5,+ 1.49998,+ -0.0+ ],+ [+ 0.66667,+ 1.49998,+ -0.0+ ],+ [+ 0.83333,+ 1.49998,+ -0.0+ ],+ [+ 1.0,+ 1.49998,+ -0.0+ ],+ [+ -1.0,+ 1.37498,+ -0.0+ ],+ [+ -0.83333,+ 1.37498,+ -0.0+ ],+ [+ -0.66667,+ 1.37498,+ -0.0+ ],+ [+ -0.5,+ 1.37498,+ -0.0+ ],+ [+ -0.33333,+ 1.37498,+ -0.0+ ],+ [+ -0.16667,+ 1.37498,+ -0.0+ ],+ [+ -0.0,+ 1.37498,+ -0.0+ ],+ [+ 0.16667,+ 1.37498,+ -0.0+ ],+ [+ 0.33333,+ 1.37498,+ -0.0+ ],+ [+ 0.5,+ 1.37498,+ -0.0+ ],+ [+ 0.66667,+ 1.37498,+ -0.0+ ],+ [+ 0.83333,+ 1.37498,+ -0.0+ ],+ [+ 1.0,+ 1.37498,+ -0.0+ ],+ [+ -1.0,+ 1.24998,+ -0.0+ ],+ [+ -0.83333,+ 1.24998,+ -0.0+ ],+ [+ -0.66667,+ 1.24998,+ -0.0+ ],+ [+ -0.5,+ 1.24998,+ -0.0+ ],+ [+ -0.33333,+ 1.24998,+ -0.0+ ],+ [+ -0.16667,+ 1.24998,+ -0.0+ ],+ [+ 0.0,+ 1.24998,+ -0.0+ ],+ [+ 0.16667,+ 1.24998,+ -0.0+ ],+ [+ 0.33333,+ 1.24998,+ -0.0+ ],+ [+ 0.5,+ 1.24998,+ -0.0+ ],+ [+ 0.66667,+ 1.24998,+ -0.0+ ],+ [+ 0.83333,+ 1.24998,+ -0.0+ ],+ [+ 1.0,+ 1.24998,+ -0.0+ ]+ ],+ "vertexMass": 0.0035502958579881664+ },+ "drape-over-ball": {+ "positions": [+ [+ -0.76012,+ 0.6454,+ 0.78212+ ],+ [+ -0.65109,+ 0.71789,+ 0.75432+ ],+ [+ -0.53398,+ 0.78221,+ 0.739+ ],+ [+ -0.40325,+ 0.80699,+ 0.73676+ ],+ [+ -0.27668,+ 0.76321,+ 0.74568+ ],+ [+ -0.14605,+ 0.73843,+ 0.75493+ ],+ [+ -0.01324,+ 0.73616,+ 0.7611+ ],+ [+ 0.11848,+ 0.75307,+ 0.76835+ ],+ [+ 0.25183,+ 0.76943,+ 0.76804+ ],+ [+ 0.37905,+ 0.81248,+ 0.76371+ ],+ [+ 0.48984,+ 0.88595,+ 0.75309+ ],+ [+ 0.61361,+ 0.93833,+ 0.74293+ ],+ [+ 0.73545,+ 0.99337,+ 0.73312+ ],+ [+ -0.74071,+ 0.57598,+ 0.66913+ ],+ [+ -0.6243,+ 0.63905,+ 0.64962+ ],+ [+ -0.52325,+ 0.72215,+ 0.62031+ ],+ [+ -0.38928,+ 0.73231,+ 0.62448+ ],+ [+ -0.26393,+ 0.77946,+ 0.61336+ ],+ [+ -0.13871,+ 0.72853,+ 0.62022+ ],+ [+ -0.0075,+ 0.76357,+ 0.6289+ ],+ [+ 0.1254,+ 0.73501,+ 0.63487+ ],+ [+ 0.24831,+ 0.79232,+ 0.6361+ ],+ [+ 0.38136,+ 0.78843,+ 0.63197+ ],+ [+ 0.49317,+ 0.86173,+ 0.62182+ ],+ [+ 0.62625,+ 0.88774,+ 0.61997+ ],+ [+ 0.74417,+ 0.95262,+ 0.60615+ ],+ [+ -0.73698,+ 0.53131,+ 0.54382+ ],+ [+ -0.63704,+ 0.61845,+ 0.51661+ ],+ [+ -0.51996,+ 0.67952,+ 0.49467+ ],+ [+ -0.39324,+ 0.72068,+ 0.48992+ ],+ [+ -0.26711,+ 0.76452,+ 0.48131+ ],+ [+ -0.13395,+ 0.76303,+ 0.48902+ ],+ [+ -0.0007,+ 0.77022,+ 0.49517+ ],+ [+ 0.12911,+ 0.73423,+ 0.50123+ ],+ [+ 0.24563,+ 0.80302,+ 0.50312+ ],+ [+ 0.37715,+ 0.77636,+ 0.49914+ ],+ [+ 0.4945,+ 0.84014,+ 0.48988+ ],+ [+ 0.62534,+ 0.8704,+ 0.48718+ ],+ [+ 0.75686,+ 0.89521,+ 0.48401+ ],+ [+ -0.74323,+ 0.49745,+ 0.41537+ ],+ [+ -0.61877,+ 0.54449,+ 0.40435+ ],+ [+ -0.49554,+ 0.59302,+ 0.39283+ ],+ [+ -0.37063,+ 0.63824,+ 0.38402+ ],+ [+ -0.25553,+ 0.70362,+ 0.36253+ ],+ [+ -0.12637,+ 0.67724,+ 0.38497+ ],+ [+ 0.00395,+ 0.70453,+ 0.37737+ ],+ [+ 0.13498,+ 0.72833,+ 0.36807+ ],+ [+ 0.24459,+ 0.80653,+ 0.36968+ ],+ [+ 0.37233,+ 0.76632,+ 0.36579+ ],+ [+ 0.50528,+ 0.77837,+ 0.3718+ ],+ [+ 0.63806,+ 0.79278,+ 0.37757+ ],+ [+ 0.76227,+ 0.84182,+ 0.36147+ ],+ [+ -0.7515,+ 0.48927,+ 0.28343+ ],+ [+ -0.63878,+ 0.56324,+ 0.27113+ ],+ [+ -0.51623,+ 0.61732,+ 0.26156+ ],+ [+ -0.38295,+ 0.62015,+ 0.2519+ ],+ [+ -0.25001,+ 0.63657,+ 0.24723+ ],+ [+ -0.14237,+ 0.71741,+ 0.2571+ ],+ [+ -0.01445,+ 0.75656,+ 0.25357+ ],+ [+ 0.11625,+ 0.78006,+ 0.24459+ ],+ [+ 0.24299,+ 0.81958,+ 0.23716+ ],+ [+ 0.3758,+ 0.80844,+ 0.2387+ ],+ [+ 0.50908,+ 0.80394,+ 0.23973+ ],+ [+ 0.64259,+ 0.79542,+ 0.24245+ ],+ [+ 0.77417,+ 0.77149,+ 0.24947+ ],+ [+ -0.75953,+ 0.50689,+ 0.15153+ ],+ [+ -0.62481,+ 0.51431,+ 0.14532+ ],+ [+ -0.49776,+ 0.55505,+ 0.14274+ ],+ [+ -0.39001,+ 0.63253,+ 0.11965+ ],+ [+ -0.26125,+ 0.6695,+ 0.1177+ ],+ [+ -0.12685,+ 0.6632,+ 0.13406+ ],+ [+ -0.00923,+ 0.72581,+ 0.12313+ ],+ [+ 0.12407,+ 0.71493,+ 0.12646+ ],+ [+ 0.24849,+ 0.76555,+ 0.11582+ ],+ [+ 0.37289,+ 0.71917,+ 0.13725+ ],+ [+ 0.5062,+ 0.72102,+ 0.13301+ ],+ [+ 0.63918,+ 0.71907,+ 0.13078+ ],+ [+ 0.77267,+ 0.71813,+ 0.12726+ ],+ [+ -0.76001,+ 0.4881,+ 0.01987+ ],+ [+ -0.63715,+ 0.54171,+ 0.01348+ ],+ [+ -0.50789,+ 0.57889,+ 0.01117+ ],+ [+ -0.37398,+ 0.57067,+ 0.00037+ ],+ [+ -0.24545,+ 0.60697,+ -0.00127+ ],+ [+ -0.13374,+ 0.68185,+ 0.0012+ ],+ [+ -0.00085,+ 0.66119,+ 0.00655+ ],+ [+ 0.12503,+ 0.70645,+ -0.0072+ ],+ [+ 0.25634,+ 0.73229,+ -0.01255+ ],+ [+ 0.38003,+ 0.6818,+ 0.00914+ ],+ [+ 0.50313,+ 0.73582,+ -0.00069+ ],+ [+ 0.63658,+ 0.7246,+ -0.00454+ ],+ [+ 0.76703,+ 0.68804,+ -0.00204+ ],+ [+ -0.76605,+ 0.5121,+ -0.11219+ ],+ [+ -0.63197,+ 0.51445,+ -0.11683+ ],+ [+ -0.52058,+ 0.58834,+ -0.12452+ ],+ [+ -0.3883,+ 0.61906,+ -0.1246+ ],+ [+ -0.25813,+ 0.64713,+ -0.12883+ ],+ [+ -0.12955,+ 0.68235,+ -0.13303+ ],+ [+ 0.00426,+ 0.66272,+ -0.1262+ ],+ [+ 0.13648,+ 0.64185,+ -0.12307+ ],+ [+ 0.26111,+ 0.69044,+ -0.13927+ ],+ [+ 0.38667,+ 0.64357,+ -0.11878+ ],+ [+ 0.49987,+ 0.71628,+ -0.133+ ],+ [+ 0.62942,+ 0.6776,+ -0.13127+ ],+ [+ 0.76311,+ 0.6667,+ -0.13272+ ],+ [+ -0.77246,+ 0.53798,+ -0.24331+ ],+ [+ -0.63917,+ 0.54884,+ -0.24649+ ],+ [+ -0.50547,+ 0.54537,+ -0.25194+ ],+ [+ -0.37685,+ 0.58616,+ -0.25449+ ],+ [+ -0.24412,+ 0.57757,+ -0.24271+ ],+ [+ -0.12819,+ 0.64543,+ -0.26239+ ],+ [+ 0.00643,+ 0.64506,+ -0.25822+ ],+ [+ 0.13424,+ 0.60733,+ -0.25175+ ],+ [+ 0.26359,+ 0.64316,+ -0.26458+ ],+ [+ 0.39383,+ 0.6078,+ -0.24749+ ],+ [+ 0.49592,+ 0.69546,+ -0.26528+ ],+ [+ 0.63113,+ 0.68092,+ -0.26563+ ],+ [+ 0.76242,+ 0.65326,+ -0.26481+ ],+ [+ -0.7694,+ 0.52892,+ -0.37722+ ],+ [+ -0.63794,+ 0.50315,+ -0.37291+ ],+ [+ -0.51046,+ 0.54331,+ -0.38542+ ],+ [+ -0.37749,+ 0.52678,+ -0.37381+ ],+ [+ -0.254,+ 0.5776,+ -0.3767+ ],+ [+ -0.12264,+ 0.60013,+ -0.38867+ ],+ [+ 0.01047,+ 0.57852,+ -0.37402+ ],+ [+ 0.14126,+ 0.6095,+ -0.38538+ ],+ [+ 0.26902,+ 0.57372,+ -0.379+ ],+ [+ 0.40235,+ 0.57264,+ -0.37624+ ],+ [+ 0.49327,+ 0.67205,+ -0.39726+ ],+ [+ 0.62656,+ 0.64707,+ -0.39483+ ],+ [+ 0.75443,+ 0.69001,+ -0.39285+ ],+ [+ -0.77264,+ 0.48767,+ -0.50452+ ],+ [+ -0.64019,+ 0.50275,+ -0.50721+ ],+ [+ -0.50721,+ 0.4859,+ -0.50618+ ],+ [+ -0.38152,+ 0.53121,+ -0.50947+ ],+ [+ -0.25329,+ 0.49998,+ -0.48563+ ],+ [+ -0.12299,+ 0.52392,+ -0.4987+ ],+ [+ 0.00849,+ 0.54778,+ -0.50584+ ],+ [+ 0.14167,+ 0.52726,+ -0.49213+ ],+ [+ 0.26668,+ 0.57755,+ -0.51228+ ],+ [+ 0.39879,+ 0.54847,+ -0.5074+ ],+ [+ 0.49095,+ 0.64628,+ -0.52841+ ],+ [+ 0.62083,+ 0.67841,+ -0.52558+ ],+ [+ 0.7491,+ 0.71636,+ -0.52385+ ],+ [+ -0.77006,+ 0.45071,+ -0.63315+ ],+ [+ -0.6355,+ 0.44888,+ -0.62958+ ],+ [+ -0.50424,+ 0.47657,+ -0.63925+ ],+ [+ -0.37002,+ 0.48646,+ -0.63471+ ],+ [+ -0.23736,+ 0.47257,+ -0.61837+ ],+ [+ -0.1126,+ 0.42425,+ -0.5863+ ],+ [+ 0.00959,+ 0.47262,+ -0.61577+ ],+ [+ 0.14529,+ 0.46845,+ -0.61213+ ],+ [+ 0.26275,+ 0.53468,+ -0.63904+ ],+ [+ 0.39769,+ 0.5197,+ -0.63765+ ],+ [+ 0.50854,+ 0.59545,+ -0.65091+ ],+ [+ 0.64024,+ 0.61739,+ -0.64284+ ],+ [+ 0.76588,+ 0.66333,+ -0.64705+ ],+ [+ -0.76644,+ 0.40324,+ -0.75803+ ],+ [+ -0.63231,+ 0.39603,+ -0.75278+ ],+ [+ -0.49769,+ 0.38097,+ -0.73331+ ],+ [+ -0.3612,+ 0.40871,+ -0.74455+ ],+ [+ -0.24371,+ 0.36045,+ -0.69506+ ],+ [+ -0.11018,+ 0.35233,+ -0.69904+ ],+ [+ 0.0208,+ 0.38297,+ -0.71513+ ],+ [+ 0.14378,+ 0.42833,+ -0.74068+ ],+ [+ 0.26978,+ 0.4673,+ -0.75593+ ],+ [+ 0.39645,+ 0.5039,+ -0.77078+ ],+ [+ 0.52762,+ 0.52506,+ -0.76284+ ],+ [+ 0.65018,+ 0.57881,+ -0.77114+ ],+ [+ 0.77572,+ 0.62593,+ -0.77532+ ]+ ],+ "vertexMass": 0.003029585798816569+ }+ }+}\ No newline at end of filediff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex 894a46ca..edf2efa2 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -148,7 +148,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'assert.equal(recipeSchema.properties.materials.maxItems, 256);assert.equal(recipeSchema.properties.geometries.maxItems, 256);const variants = recipeSchema.properties.geometries.items.oneOf ?? recipeSchema.properties.geometries.items.anyOf;- assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'mesh']);+ assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'mesh']);assert.ok(variants.every(variant => variant.additionalProperties === false));assert.equal(recipeSchema.properties.environment.additionalProperties, false);assert.equal(recipeSchema.properties.environment.properties.pointLights.maxItems, 8);