Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Expose clip layers, bone masks and name retargeting through MCP

Nguyen Xuan Ane8898992338a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 053f8484..95501e5a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Expose clip layers, bone masks and name retargeting through MCP, and morph clips in `createAssetPose` (issue #59, in part). An asset recipe's `motion.layers` (up to 8) plays the file's own clips at motion time with a bone `mask`, `weight`, `speed`, `offset`, `loop`, `additive` with `reference`, `bones` (clip track to another asset node) and `morph`, before tracks and IK, so a character walks and waves at once; everything is checked against the asset and bounded, and a seek equals playing. `morphClipFromGltfAnimation` and a layer's `morphs` put morph weights through `createAssetPose` (masks pick parts by their owning bone), `createAssetLayerEvaluator` serves hosts that stage the pose themselves, and `asset.stagePose` takes `morphWeights`. Add the `robot-walk-wave` task to the agent modeling suite and extend `npm run smoke:character`. Not done: foot tilt on slopes, full-body IK, and rest-pose retargeting from another asset through MCP. Raise `entry:skeleton-pose` to 19,000 and `entry:agent-asset` to 85,200 bytes gzip, and the tool schema budgets by 800 bytes (`scene_apply` to 47,800, `scene_create_asset` to 20,150, total to 190,700).
+
- Add a bounded material node graph (issue #50): material `pattern` of `type: "graph"` bakes noise, voronoi, wave, checker, gradient, ramp, maths and `uv` nodes on the CPU into base colour, roughness, metallic, emission and height (a normal map, so bump). The graph is data, never shader text; nodes, depth, ramp stops, texture size and work are checked before any pixel is computed. Add `mapping: "uv"` to every pattern so it follows `uv_unwrap` UVs instead of box projection; the emissive map now box-maps like the other maps. The 11 presets bake the same bytes as before. Covered in the MCP schema, `scene_capabilities` (`materialGraph`, `materialMappings`), GLB export, `docs/agent-scene.md`, `docs/material-maps.md` and the `brick-graph` reference scene.
- Add `decimate`, `remesh` and generated levels of detail (issue #40). `decimate` (a `ratio` of triangles) is a quadric edge collapse of our own that keeps open boundaries, the borders between tags and the tags themselves; it measured 0.25 to 0.85 of the Hausdorff error of meshoptimizer 1.3.0 on the same meshes and adds no dependency, but takes about 2.5 s on 100k triangles where meshoptimizer takes 0.09 s. `remesh` (`voxelSize` or `resolution`, at most 192 per side and 4,194,304 cells, checked before allocation) builds a closed quad surface from a BVH signed distance with surface nets. Both are edits and stack nodes, in the MCP schemas, and load on demand with the mesh code. `generateMeshLods`, `generateGeometryLods` and `generateAssetLods` (also in `67js/addons/mesh`) return levels with a measured error for runtime selection (issue #37). Four decimate and two remesh cases join the Blender comparison, compared by volume, area and Hausdorff distance because face counts differ.
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index b869cf4a..ef70a770 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -184,3 +184,7 @@ What this does and does not show:
The suite now finds tool friction and tracks cost, but does not measure how good an object looks. Tasks with free form,
such as organic shapes or a look to match, would need a score for appearance before they could test more.
+
+## Clip layers (2026-10-31)
+
+`robot-walk-wave` asks for a character that walks and waves at once through `motion.layers`. The check `assetWalkAndWave` reloads the exported recipe, plays each layer alone (keeping its own speed, offset and loop) and compares part matrices at two times: the legs must match Walking and move, the right arm must leave Walking, the left arm must keep walking. Cold Sonnet, no skill, `results/2026-10-31-11-40-sonnet-walk-wave-cold-fixed-grader.json`: 1 of 1, 7 tool calls (2 errors), $0.31. A first run, with a check that compared against Walking at speed 1 only, failed on a recipe the agent had correct (it set per-layer speeds); the check was fixed and that recipe grades as a pass. One run is not a rate.
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index 93e2f724..2fef623e 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -119,6 +119,22 @@ function checkOne(check, measures) {
case 'assetClip': {
return { pass: measures.clipName === check.name, detail: `clip ${measures.clipName ?? 'none'}` };
}
+ case 'assetWalkAndWave': {
+ const pose = measures.layerPose;
+ if (!pose) return { pass: false, detail: 'no motion layers in the recipe' };
+ const walking = pose.alone[check.walk];
+ const waving = pose.alone[check.wave];
+ if (!walking || !waving) return { pass: false, detail: `layers play ${pose.clipNames.join(', ')}; need ${check.walk} and ${check.wave}` };
+ const distance = (first, second) => Math.max(...first.map((value, index) => Math.abs(value - second[index])));
+ const legsFollowWalk = pose.combined.every((sample, time) => check.legs.every(part => distance(sample[part], walking[time][part]) < 1e-3));
+ const legsMove = check.legs.every(part => distance(pose.combined[0][part], pose.combined[1][part]) > 0.1);
+ const armLeavesWalk = pose.combined.some((sample, time) => distance(sample[check.arm], walking[time][check.arm]) > 1);
+ const otherArmWalks = pose.combined.every((sample, time) => distance(sample[check.otherArm], walking[time][check.otherArm]) < 1e-3);
+ return {
+ pass: legsFollowWalk && legsMove && armLeavesWalk && otherArmWalks,
+ detail: `legs follow ${check.walk} ${legsFollowWalk}, legs move ${legsMove}, ${check.arm} waves ${armLeavesWalk}, ${check.otherArm} keeps walking ${otherArmWalks}`,
+ };
+ }
case 'assetReach': {
const solver = measures.reachSolvers.find(candidate => candidate.endLabel === check.endLabel);
if (!solver) return { pass: false, detail: `no two-bone solver ending at ${check.endLabel}` };
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 761c2ab1..4a415bb0 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -191,11 +191,48 @@ function lineHits(geometries, axis, point) {
return hits;
}
+async function loadFixtureRobot() {
+ const bytes = await readFile(new URL('../../tests/fixtures/RobotExpressive.glb', import.meta.url));
+ return parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });
+}
+
+const LAYER_SAMPLE_TIMES = [0.15, 0.55];
+
+function matricesByPartName(scene, asset) {
+ return Object.fromEntries(asset.parts.map((part, index) => [part.name, Array.from(scene.parts[index].matrix)]));
+}
+
+/**
+ * Pose matrices of every part at fixed times, for the recipe and for each of its layers' clips played alone, so a check can
+ * tell which clip each part follows. Null when the recipe has no motion layers.
+ */
+async function measureLayerPose(recipe, asset) {
+ const layers = recipe.motion?.layers;
+ if (!layers?.length) return null;
+ const clipNames = layers.map(layer => asset.animations[layer.clip]?.name);
+ const duration = recipe.motion.duration;
+ const poseAt = async motion => {
+ const robot = await loadFixtureRobot();
+ const scene = createAgentAssetScene(robot, { ...recipe, animation: null, motion });
+ return LAYER_SAMPLE_TIMES.map(time => {
+ scene.sampleMotion(time);
+ return matricesByPartName(scene, robot);
+ });
+ };
+ const alone = {};
+ for (const [position, layer] of layers.entries()) {
+ // The layer keeps its own speed, offset and loop, so a clip played at another rate is still compared with itself.
+ const { mask, ...unmasked } = layer;
+ alone[clipNames[position]] = await poseAt({ duration, loop: recipe.motion.loop, layers: [{ ...unmasked, morph: false }] });
+ }
+ return { clipNames, times: LAYER_SAMPLE_TIMES, combined: await poseAt(recipe.motion), alone };
+}
+
/** Reload an exported recipe for the fixture robot and read which clip and which IK solvers it ended with. */
export async function measureAssetRecipe(recipe) {
- const bytes = await readFile(new URL('../../tests/fixtures/RobotExpressive.glb', import.meta.url));
- const asset = await parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });
+ const asset = await loadFixtureRobot();
const scene = createAgentAssetScene(asset, recipe);
+ const layerPose = await measureLayerPose(recipe, await loadFixtureRobot());
const labels = new Map(asset.nodes.map(node => [node.id, node.label]));
const reports = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk ?? [];
const solvers = recipe.motion?.ik ?? [];
@@ -206,6 +243,7 @@ export async function measureAssetRecipe(recipe) {
};
return {
clipName: recipe.animation ? asset.animations[recipe.animation.clip]?.name : null,
+ layerPose,
camera: recipe.camera ?? null,
reachSolvers: solvers.filter(solver => solver.type === 'two-bone').map(solver => {
const [firstTarget, lastTarget] = endpoints(solver.target);
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index c24a7970..f32859b6 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -222,6 +222,16 @@ export const REFERENCES = {
}],
},
},
+ 'robot-walk-wave': {
+ format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),
+ motion: {
+ duration: 2, loop: true,
+ layers: [
+ { clip: 10 },
+ { clip: 12, mask: { joints: ['node-37'] }, morph: false },
+ ],
+ },
+ },
'tray-drop': {
...scene(
[
diff --git a/bench/agent-modeling/results/2026-10-31-11-40-sonnet-walk-wave-cold-fixed-grader.json b/bench/agent-modeling/results/2026-10-31-11-40-sonnet-walk-wave-cold-fixed-grader.json
new file mode 100644
index 00000000..b48ce5f9
--- /dev/null
+++ b/bench/agent-modeling/results/2026-10-31-11-40-sonnet-walk-wave-cold-fixed-grader.json
@@ -0,0 +1,72 @@
+{
+ "run": "2026-10-31-11-40-sonnet-walk-wave-cold-fixed-grader",
+ "model": "claude-sonnet-5-5",
+ "date": "2026-10-31T11:41:23.921Z",
+ "skill": false,
+ "runsPerTask": 1,
+ "passed": 1,
+ "tasks": 1,
+ "toolCalls": 7,
+ "costUsd": 0.31,
+ "byModel": {
+ "claude-sonnet-5-5": {
+ "runs": 1,
+ "passed": 1,
+ "successRate": 1,
+ "toolCalls": 7,
+ "toolErrors": 2,
+ "inputTokens": 585852,
+ "outputTokens": 2294,
+ "costUsd": 0.31,
+ "tasks": {
+ "robot-walk-wave": {
+ "runs": 1,
+ "passed": 1,
+ "successRate": 1,
+ "toolCalls": 7,
+ "toolErrors": 2,
+ "inputTokens": 585852,
+ "outputTokens": 2294,
+ "costUsd": 0.31
+ }
+ }
+ }
+ },
+ "records": [
+ {
+ "task": "robot-walk-wave",
+ "attempt": 1,
+ "pass": true,
+ "passed": 1,
+ "total": 1,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 7,
+ "toolErrors": 2,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_asset_catalog": 1,
+ "scene_create_asset": 1,
+ "scene_inspect": 1,
+ "scene_apply": 3,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [],
+ "meshOperations": [],
+ "motionIk": [],
+ "motionTracks": 0
+ },
+ "look": {
+ "skipped": "asset recipes have no static silhouette"
+ },
+ "turns": 9,
+ "costUsd": 0.3115931,
+ "inputTokens": 585852,
+ "outputTokens": 2294,
+ "wallSeconds": 37,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index 8f729ac8..8bf99880 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -471,6 +471,18 @@ recipe is what gets graded.`,
{ kind: 'assetReach', endLabel: 'Palm2.R', from: [-1.3, 2.6, 0.8], to: [-1, 1.7, 1.1] },
],
},
+ {
+ id: 'robot-walk-wave',
+ assets: true,
+ prompt: `The asset catalog holds an imported robot character. Create a scene from it, then give it a 2 second looping motion in
+which it walks and waves at the same time: its legs and body play the Walking clip, and only its right arm (the
+joint labelled UpperArm.R and everything below it) plays the Wave clip instead. Find the clips and joints by inspecting the
+scene. When it is finished, call scene_export_recipe once: the exported recipe is what gets graded.`,
+ ownPreamble: true,
+ checks: [
+ { kind: 'assetWalkAndWave', walk: 'Walking', wave: 'Wave', legs: ['LegL', 'LegR', 'LowerLegL_1', 'LowerLegR_1'], arm: 'ArmR', otherArm: 'ArmL' },
+ ],
+ },
...LONG_TASKS,
];
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index 132a1512..d51f5448 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -39,9 +39,9 @@
"brotli": 7331
},
"entry:gltf": {
- "min": 152150,
- "gzip": 46704,
- "brotli": 39993
+ "min": 153176,
+ "gzip": 46991,
+ "brotli": 40335
},
"entry:modeling": {
"min": 15517,
@@ -94,9 +94,9 @@
"brotli": 12962
},
"entry:skeleton-pose": {
- "min": 55080,
- "gzip": 18056,
- "brotli": 15427
+ "min": 57354,
+ "gzip": 18778,
+ "brotli": 16077
},
"entry:vehicle": {
"min": 42067,
@@ -130,23 +130,23 @@
},
"entry:agent-scene": {
"min": 190633,
- "gzip": 57326,
- "brotli": 49610
+ "gzip": 57324,
+ "brotli": 49617
},
"entry:agent-scene+lazy": {
- "min": 498812,
- "gzip": 164401,
- "brotli": 143354
+ "min": 501545,
+ "gzip": 165243,
+ "brotli": 144083
},
"entry:agent-asset": {
- "min": 270394,
- "gzip": 82147,
- "brotli": 71444
+ "min": 278340,
+ "gzip": 84653,
+ "brotli": 73752
},
"entry:agent-asset+lazy": {
- "min": 525913,
- "gzip": 171671,
- "brotli": 149210
+ "min": 533859,
+ "gzip": 174177,
+ "brotli": 151519
},
"entry:hdri": {
"min": 8075,
@@ -159,9 +159,9 @@
"brotli": 47903
},
"scene:gltf-box": {
- "min": 264230,
- "gzip": 74991,
- "brotli": 64299
+ "min": 265256,
+ "gzip": 75253,
+ "brotli": 64620
},
"scene:agent-scene": {
"min": 294018,
@@ -169,9 +169,9 @@
"brotli": 72502
},
"scene:agent-scene+lazy": {
- "min": 602197,
- "gzip": 191435,
- "brotli": 166207
+ "min": 604930,
+ "gzip": 192275,
+ "brotli": 166938
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 9fb937a1..cf09ceb4 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -21,7 +21,7 @@
"entry:physics": 18000,
"entry:spume": 9000,
"entry:retarget": 15700,
- "entry:skeleton-pose": 18500,
+ "entry:skeleton-pose": 19000,
"entry:vehicle": 14700,
"entry:vegetation": 17900,
"entry:terrain": 3100,
@@ -30,7 +30,7 @@
"entry:texture-set": 900,
"entry:agent-scene": 58500,
"entry:agent-scene+lazy": 167700,
- "entry:agent-asset": 83800,
+ "entry:agent-asset": 85200,
"entry:agent-asset+lazy": 175200,
"entry:hdri": 3300,
"scene:lit-box": 57200,
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 93612b60..0bb88bdf 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,11 +1,11 @@
{
"measured": "2026-10-31, from scripts/measure-tool-cost.mjs; was 373388 schema bytes before shared IDs and recipe references",
- "schemaTotalBytes": 189900,
+ "schemaTotalBytes": 190700,
"schemaToolBytes": {
"scene_create": 60900,
- "scene_apply": 47400,
+ "scene_apply": 47800,
"mesh_edit": 34000,
- "scene_create_asset": 19750,
+ "scene_create_asset": 20150,
"mesh_stack": 11500
},
"schemaOtherToolBytes": 4000,
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index c86571ed..1a54ee88 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -115,7 +115,37 @@ On an imported asset, joints are its `node-N` IDs from `scene_inspect` with `kin
Each sample stages the clip and overrides, reads the local pose, solves, and stages again, so the rest of the body stays on
the selected clip and skins and rigid parts all follow. Targets are in world space, under the asset's `root`, which needs a
uniform scale. Some rigs have no chain to the foot: if the foot is not a descendant of the lower leg, two-bone IK refuses it.
-[Skeleton pose layers](skeleton-pose.md) add clip layers and masks in code.
+
+### Clip layers on an asset
+
+`motion.layers` plays the file's own clips at motion time, so a character can walk and wave at once. Up to 8 layers, in order,
+each blending over the pose so far, before tracks and IK:
+
+| Field | Meaning |
+| --- | --- |
+| `clip` | The `id` of an entry in `scene_inspect` `animations` |
+| `mask` | `{ joints, descendants = true, exclude }`, up to 32 node IDs or names each. The layer moves only these joints and what hangs below them; mesh parts follow their bone, and morph weights follow the bone that owns the mesh |
+| `weight` | 0 to 1, default 1 |
+| `speed`, `offset` | Layer time is `time * speed + offset`. `speed` 0.05 to 8, `offset` within 30 seconds |
+| `loop` | Default `true`: the clip repeats. `false` holds its last key |
+| `additive`, `reference` | Add the clip's change from `reference` seconds instead of replacing the pose |
+| `bones` | Retarget by name: `{ "UpperArmR": "node-20" }` makes the clip's track for `UpperArmR` move that node of this asset. Up to 64 entries; the clip must have the track |
+| `morph` | `false` leaves morph weights alone. Default: the clip's morph tracks play |
+
+```json
+"motion": { "duration": 2, "loop": true, "layers": [
+ { "clip": 10 },
+ { "clip": 12, "mask": { "joints": ["node-37"] }, "morph": false }
+] }
+```
+
+`tracks` can be left out when there are layers. Layers need an imported asset: a procedural recipe refuses them. Everything is
+checked against the asset (clip indexes, node IDs and names, track names) and bounded before anything is built, and the
+pose is rebuilt from the rest pose for each time, so a seek equals playing. `bones` renames tracks inside one asset; moving a
+clip from another rig (rest-pose retargeting with `retargetClip`) is code only, because the MCP holds one asset at a time.
+Foot tilt on slopes is not done.
+
+[Skeleton pose layers](skeleton-pose.md) have the same layers in code.
### Joint limits and sanity warnings
@@ -177,7 +207,7 @@ error. The operator names follow the field expressions of the mesh addon where t
For any time, the pose is built in this order and keeps no state between samples, so seeking gives the same pose as playing
to that time:
-1. Tracks, and for an asset the selected clip.
+1. For an asset, the selected clip, then `motion.layers`, then tracks.
2. IK, in list order.
3. Drivers. They read the pose from steps 1 and 2, so one driver never sees another's result.
4. Constraints, in list order. Each reads the pose the ones before it left. Expressions in `influence` read the pose from
diff --git a/docs/parity.md b/docs/parity.md
index bfd05810..2170a0f2 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -135,7 +135,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Armatures > Properties | partial | An armature has an id, a parent node, a transform, an optional bone-ID prefix and a `humanoid` or `quadruped` preset fitted to a mesh node or to bounds. No display settings or bone collections. | [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Structure | partial | Imported rigs keep their hierarchy, and recipes author one. A rig exports to GLB with its bones and a baked walk clip; Blender 5.2 opens it as 1 armature, 21 bones, 14 vertex-grouped meshes and 1 action. | [gltf](../tests/gltf.test.js), [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Skinning | partial | Four-influence GPU skinning, with automatic binding by distance to the bone segments. Not heat diffusion, so two limbs that pass close can share weights; `scene_inspect` reports unweighted vertices, bones with no vertices and joint axis problems. | [skinning](../tests/skinning.test.js), [rigging](../tests/rigging.test.js) | #46 |
-| Animation & Rigging > Armatures > Posing | partial | Layers, masks, additive poses and IK in code. MCP has IK and one clip. | [skeleton-pose](../tests/skeleton-pose.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js) | #58, #59 |
+| Animation & Rigging > Armatures > Posing | partial | Layers, masks, additive poses and IK in code. MCP asset recipes take `motion.layers` (clips, masks, weights, additive, rename retarget) beside IK; no foot tilt on slopes or full-body IK. | [skeleton-pose](../tests/skeleton-pose.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js) | #58, #59 |
| Animation & Rigging > Lattice | missing | No lattice. | | #42 |
| Animation & Rigging > Constraints > Interface | out of scope | Interface for a mouse. | | |
| Animation & Rigging > Constraints > Motion Tracking | out of scope | Motion tracking is out of scope in issue #23. | | |
@@ -165,10 +165,10 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Constraints > Relationship > Geometry Attribute Constraint | missing | No constraint. | | |
| Animation & Rigging > Constraints > Relationship > Pivot Constraint | missing | No constraint. | | |
| Animation & Rigging > Constraints > Relationship > Shrinkwrap Constraint | partial | `addons/surface-attachment` binds points to a surface in code. | [surface-attachment](../tests/surface-attachment.test.js) | |
-| Animation & Rigging > Actions | partial | Clips, weights and crossfades in code. An asset through MCP plays one clip at a time. | [animation-mixer](../tests/animation-mixer.test.js) | #59 |
+| Animation & Rigging > Actions | partial | Clips, weights and crossfades in code. An asset through MCP plays several clips as masked layers at motion time; there are no crossfades or state machines there. | [animation-mixer](../tests/animation-mixer.test.js), [agent-asset-layers](../tests/agent-asset-layers.test.js) | #59 |
| Animation & Rigging > Drivers | partial | `motion.drivers`: a node component or material property from a bounded expression over time and other nodes. No custom properties, shape keys or variables. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js) | #58 |
| Animation & Rigging > Markers | missing | No markers or events. | | #60 |
-| Animation & Rigging > Shape Keys | partial | Morph targets import, render and animate. Recipes can not author them. | [morph](../tests/morph.test.js) | #59 |
+| Animation & Rigging > Shape Keys | partial | Morph targets import, render and animate, and clip layers drive imported morph weights (`createAssetPose`, MCP `motion.layers`). Recipes can not author them. | [morph](../tests/morph.test.js), [agent-asset-layers](../tests/agent-asset-layers.test.js) | #59 |
| Animation & Rigging > Motion Paths | out of scope | Viewport display for hand work. `scene_inspect` reports motion as numbers. | | |
| Animation & Rigging > In-Betweens | out of scope | Pose tools for a hand. Agents write keyframes and IK targets. | | |
| 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 |
diff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.md
index 18dcf386..f2ed562e 100644
--- a/docs/skeleton-pose.md
+++ b/docs/skeleton-pose.md
@@ -38,7 +38,18 @@ are built that way, or have several skins. Targets are in the asset's world spac
armature above the bones.
`clipFromGltfAnimation(asset.animations[n], { loop })` converts a clip from the file. `asset.animations` holds three.js
-clips, which layers and `retargetClip` cannot read directly. Morph weight tracks are skipped.
+clips, which layers and `retargetClip` cannot read directly. `rename: { clipName: jointName }` sends a clip's track to another
+joint of the asset, a retarget by name. Morph weight tracks are not part of this clip.
+
+`morphClipFromGltfAnimation(asset.animations[n], { loop })` reads those morph weight tracks. Give the result as `morphs` on a
+layer of `createAssetPose` and the layer drives the face too, with the same `weight`, `speed`, `offset`, `additive` and `reference`.
+A layer's `mask` picks mesh parts by the bone that owns them: a mask on an arm leaves the face alone. A layer with `morphs` and
+no `clip` drives only morph weights. `asset.stagePose` takes the weights as `morphWeights: [{ part, weights }]`, by index into
+`asset.parts`, each between 0 and 1. The RobotExpressive clips carry morph tracks that are all zero, so a real face needs a clip
+that sets them.
+
+`createAssetLayerEvaluator(asset, layers).evaluate(time)` returns `{ nodeOverrides, morphWeights }` for a host that stages the
+pose itself (the MCP asset recipe does, before it solves IK). The same time always gives the same result.
`createSkeletonPose({ skin, rig, meshWorldMatrix, layers, ik })` is the lower level: it writes one skin's palette, or with
only a `rig` just computes joint positions. `rig` defaults to `createRigFromSkin(skin)` from `67js/addons/retarget`; pass
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 5e6bc698..f1a20120 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -443,7 +443,7 @@ const physics = z.strictObject({
}).describe('Rigid-body physics recorded offline with Rapier at 60 steps a second, then played back by time like motion: scene_look and scene_review motionTime seek into the recording, so a seek back shows the identical frame. Bodies are recipe nodes; scene_inspect reports contacts, sensor events and resting state as numbers. Needs the optional peer dependency @dimforge/rapier3d-compat. A node cannot have a physics body and a motion translation or rotation track.');
// 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.');
+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.');
const boneRecord = z.strictObject({
name: z.string().min(1).max(64).describe('Unique within the armature. Humanoid rigs use the canonical names (hips, spine, chest, neck, head, leftUpperArm, leftLowerArm, leftHand, leftUpperLeg, leftLowerLeg, leftFoot, leftToes, and right...) so retarget works.'),
parent: z.string().min(1).max(64).nullable().optional().describe('Parent bone name, or null for a root bone.'),
diff --git a/scripts/smoke-character.mjs b/scripts/smoke-character.mjs
index 10180967..d87b0e59 100644
--- a/scripts/smoke-character.mjs
+++ b/scripts/smoke-character.mjs
@@ -139,6 +139,41 @@ try {
const armMotionApplied = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion }] })).structuredContent;
revision = armMotionApplied.revision;
+ // Clip layers: the legs walk while a layer masked to the right arm waves, found by clip label and joint label.
+ const clips = (await call('scene_inspect', { sessionId })).structuredContent.animations;
+ const clipOf = label => {
+ const found = clips.find(clip => clip.label === label);
+ assert.ok(found, `no clip labelled ${label}`);
+ return found.id;
+ };
+ const walkOnlyMotion = { duration: 2, loop: true, layers: [{ clip: clipOf('Walking') }] };
+ const walkAndWaveMotion = {
+ duration: 2, loop: true,
+ layers: [{ clip: clipOf('Walking') }, { clip: clipOf('Wave'), mask: { joints: [idOf('UpperArm.R')] }, morph: false }],
+ };
+ const walkOnlyApplied = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion: walkOnlyMotion }] })).structuredContent;
+ assert.equal(walkOnlyApplied.renderSucceeded, true, walkOnlyApplied.renderError);
+ revision = walkOnlyApplied.revision;
+ const walkOnlyPicture = await look(sessionId, 'layers-walk', 0.5);
+ const layersApplied = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion: walkAndWaveMotion }] })).structuredContent;
+ assert.equal(layersApplied.renderSucceeded, true, layersApplied.renderError);
+ revision = layersApplied.revision;
+ assert.equal((await call('scene_inspect', { sessionId })).structuredContent.motion.layers, 2);
+ const walkAndWaveStart = await look(sessionId, 'layers-walk-wave', 0.5);
+ assert.notEqual(walkAndWaveStart, walkOnlyPicture, 'the masked wave layer changes the arm');
+ const walkAndWaveLater = await look(sessionId, null, 1.3);
+ assert.notEqual(walkAndWaveLater, walkAndWaveStart, 'the character keeps moving');
+ assert.equal(await look(sessionId, null, 0.5), walkAndWaveStart, 'seeking back gives the same picture with layers');
+ const refused = await client.callTool({ name: 'scene_apply', arguments: { sessionId, expectedRevision: revision, operations: [{
+ type: 'set-motion', motion: { duration: 2, layers: [{ clip: clipOf('Wave'), mask: { joints: ['NoSuchBone'] } }] },
+ }] } });
+ assert.equal(refused.isError, true, 'a mask joint that is not in the asset is refused');
+ report.layers = { clips: ['Walking', 'Wave'], mask: 'UpperArm.R' };
+ const layersExport = (await call('scene_export_recipe', { sessionId })).structuredContent;
+ assert.equal((layersExport.recipe ?? layersExport).motion.layers.length, 2);
+ const armAgain = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion }] })).structuredContent;
+ revision = armAgain.revision;
+
const restored = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: revision })).structuredContent;
revision = restored.revision;
assert.equal(await look(sessionId), base, 'restore gives back the exact picture from before the IK');
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 1870369f..c211299d 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -40,7 +40,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`. Your own look (bricks from noise and a ramp, stripes, a pattern that follows `uv_unwrap`) is `pattern: { type: "graph", graph, mapping: "uv" }`: a bounded JSON node graph baked to textures, never shader text; see "Material graphs" there.
- Glass, water, gems, car paint and cloth in a recipe use the material layer fields `transmission` (with `thickness` and `ior`), `clearcoat`, `sheenColor` and `specular`. A transmissive material needs a nonzero `thickness` to bend the view behind it, and does not show blended surfaces. Ranges and limits are in "Material layers" in the checkout's `docs/material-maps.md`.
- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `createAssetPose` from `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.
-- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`: besides `reached`, it lists `warnings` (`wrong-bend` when a knee or elbow bends the unnatural way, `hyperextended`) and `limited` (poses a joint limit changed). Give a leg or arm `bendToward` (a world direction, such as `[0, 0, 1]` for a knee on a character facing +z) and `limits` per joint in degrees, and fix any warning before you finish. `motion.constraints` (copy, limit, `track_to`, `child_of`, `floor`, Blender's meanings, Euler XYZ degrees) and `motion.drivers` (a node or material property from a bounded JSON expression) run after IK and give the same pose at any time. See "Inverse kinematics", "Constraints" and "Drivers" in the checkout's `docs/agent-motion.md`.
+- Jointed motion (an arm reaching, a lamp or head tracking a point) on a recipe or an imported character uses `motion.ik`, which needs no quaternions: on a recipe parent the joint nodes and put sizes on child mesh nodes, on an asset find `node-N` IDs with `scene_inspect` kind hierarchy and aim with `worldForward`. Read `motionIk` from `scene_inspect`: besides `reached`, it lists `warnings` (`wrong-bend` when a knee or elbow bends the unnatural way, `hyperextended`) and `limited` (poses a joint limit changed). Give a leg or arm `bendToward` (a world direction, such as `[0, 0, 1]` for a knee on a character facing +z) and `limits` per joint in degrees, and fix any warning before you finish. `motion.constraints` (copy, limit, `track_to`, `child_of`, `floor`, Blender's meanings, Euler XYZ degrees) and `motion.drivers` (a node or material property from a bounded JSON expression) run after IK and give the same pose at any time. On an imported asset, `motion.layers` plays its clips together (a walk layer plus a wave layer masked to `{ "joints": ["node-N"] }` for the arm): list clip ids with `scene_inspect` (`animations`), find joints with kind hierarchy, set `morph: false` on a layer that should not touch the face, and use `bones` to send a clip's track to another node. See "Inverse kinematics", "Clip layers on an asset", "Constraints" and "Drivers" in the checkout's `docs/agent-motion.md`.
- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.
- 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`.
diff --git a/src/agent-asset.js b/src/agent-asset.js
index fb59ae89..1771a3a8 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -6,6 +6,8 @@ import { fitPerspectiveDistance } from './camera.js';
import { validateSkinGeometry, validateSkinPose } from './skinning.js';
import { validateMorphGeometry, validateMorphTransform } from './morph.js';
import * as agentMotion from './agent-motion.js';
+import { clipLayerContextFromAsset } from './agent-clip-layers.js';
+import { clipFromGltfAnimation, createAssetLayerEvaluator, morphClipFromGltfAnimation } from './skeleton-pose.js';
import { registerAgentSceneModule } from './agent-scene-modules.js';
registerAgentSceneModule('motion', agentMotion);
@@ -296,6 +298,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
});
const materialRecords = new Map([...materials.values()].map(record => [record.id, record]));
const sourceNodes = new Map(asset.nodes.map(node => [node.id, structuredClone(node)]));
+ const clipLayerContext = clipLayerContextFromAsset(asset.animations, [...sourceNodes.values()]);
const initialRecipe = copiedJson(inputRecipe);
const assetId = initialRecipe?.assetId;
if (typeof assetId !== 'string' || !/^[a-f0-9]{64}$/i.test(assetId)) {
@@ -308,6 +311,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
let matrices = [];
let revision = 0;
let sampler = null;
+ let layerEvaluator = null;
let motionTime = null;
let sampledCamera;
const checkpoints = new Map();
@@ -433,7 +437,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
return {
nodes: [...sourceNodes.values()].filter(node => node.editable),
materials: [...baselines.values()], camera: candidate.camera,
- ikHierarchy: [...sourceNodes.values()],
+ ikHierarchy: [...sourceNodes.values()], clipLayerContext,
ikRootMatrix: Array.from(mat4.fromRotationTranslationScale(mat4.create(), root.rotation, root.translation, [root.scale[0], root.scale[0], root.scale[0]])),
};
}
@@ -448,6 +452,34 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
}
+ /** Layers of the motion as definitions for the pose code: decoded clips, renamed by `bones`, with their morph tracks. */
+ function layerDefinitions(layers) {
+ return layers.map(layer => {
+ const animation = asset.animations[layer.clip];
+ const loop = layer.loop !== false;
+ return {
+ clip: clipFromGltfAnimation(animation, { loop, rename: layer.bones }),
+ ...(layer.morph === false ? {} : { morphs: morphClipFromGltfAnimation(animation, { loop }) }),
+ weight: layer.weight, speed: layer.speed, offset: layer.offset, additive: layer.additive, reference: layer.reference, mask: layer.mask,
+ };
+ });
+ }
+
+ /** Evaluates the motion's clip layers at a time, or null when it has none. Stateless, so a seek equals playing. */
+ function compileLayers(motion) {
+ return motion?.layers?.length ? createAssetLayerEvaluator(asset, layerDefinitions(motion.layers)) : null;
+ }
+
+ /** Where tracks, layers and the recipe's own overrides meet: the recipe's overrides, then layers, then tracks on top. */
+ function poseOverrides(baseOverrides, layerEvaluator, sampled, time) {
+ const layered = layerEvaluator?.evaluate(time);
+ const withLayers = new Map(baseOverrides.map(override => [override.id, override]));
+ for (const override of layered?.nodeOverrides ?? []) {
+ withLayers.set(override.id, { ...withLayers.get(override.id), ...override });
+ }
+ return { nodeOverrides: trackOverrides([...withLayers.values()], sampled), morphWeights: layered?.morphWeights ?? [] };
+ }
+
function trackOverrides(baseOverrides, sampled) {
const nodeOverrides = new Map(baseOverrides.map(override => [override.id, override]));
for (const [id, patch] of sampled?.nodes ?? []) {
@@ -463,6 +495,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
candidate = { ...candidate, animation: transientAnimation };
}
let stagedSampler = transientTime === undefined ? agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate)) : sampler;
+ const stagedLayers = transientTime === undefined ? compileLayers(candidate.motion) : layerEvaluator;
const targetTime = transientTime === undefined ? (candidate.motion ? 0 : null) : transientTime;
if (targetTime !== null && !stagedSampler) {
throw new RangeError('The asset has no authored motion to sample.');
@@ -482,7 +515,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
throw new RangeError('Decoded resources and retained adapter matrices must not change identity or detach.');
}
}
- const nodeOverrides = trackOverrides(candidate.nodeOverrides, sampled);
+ const { nodeOverrides, morphWeights } = poseOverrides(candidate.nodeOverrides, targetTime === null ? null : stagedLayers, sampled, targetTime);
if (targetTime !== null && stagedSampler?.ikUsesStagedPose) {
const nodePoses = stagedNodePoses(candidate.animation, [...nodeOverrides.values()]);
for (const override of stagedSampler.solveStagedPose(targetTime, nodePoses)) {
@@ -491,7 +524,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
}
let transaction;
try {
- transaction = asset.stagePose({ animation: candidate.animation, nodeOverrides: [...nodeOverrides.values()] });
+ transaction = asset.stagePose({ animation: candidate.animation, nodeOverrides: [...nodeOverrides.values()], morphWeights });
const rootMatrix = mat4.fromRotationTranslationScale(mat4.create(), candidate.root.rotation, candidate.root.translation, candidate.root.scale);
const normal = mat3.create();
const stagedMatrices = records.map((record, index) => {
@@ -549,6 +582,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
if (transientTime === undefined) {
recipe = candidate;
sampler = stagedSampler;
+ layerEvaluator = stagedLayers;
}
materialSnapshots = stagedMaterials;
sampledCamera = stagedCamera;
@@ -582,7 +616,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
if (!recipe.motion?.ik?.length) return {};
const sweeper = agentMotion.compileAgentMotion(recipe.motion, motionRecipe(recipe));
return {
- motionIk: sweeper.sweepIk(time => stagedNodePoses(recipe.animation, [...trackOverrides(recipe.nodeOverrides, sweeper.sample(time)).values()])),
+ motionIk: sweeper.sweepIk(time => stagedNodePoses(recipe.animation, [...poseOverrides(recipe.nodeOverrides, layerEvaluator, sweeper.sample(time), time).nodeOverrides.values()])),
};
}
@@ -805,7 +839,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
revision, topologyRevision: 0, assetId: canonicalAssetId, ...diagnosticsReport(),
counts: { nodes: parts.length, parts: parts.length, geometries: geometries.size, materials: materials.size, vertices },
geometryBytes, animation: structuredClone(recipe.animation),
- motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null,
+ motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, layers: recipe.motion.layers?.length ?? 0, time: motionTime } : null,
animations: asset.animations.map((clip, index) => ({ id: index, label: String(clip.name ?? `Clip ${index}`).slice(0, 256), duration: clip.duration })),
nodes, offset, truncated: selected.length > offset + nodes.length,
};
diff --git a/src/agent-clip-layers.js b/src/agent-clip-layers.js
new file mode 100644
index 00000000..959dd62d
--- /dev/null
+++ b/src/agent-clip-layers.js
@@ -0,0 +1,99 @@
+import { bounded, denseArray, knownKeys } from './motion-validation.js';
+
+// Clip layers for an imported asset's motion: play clips the file ships, blend them over each other, and limit each to
+// some bones. Agent input is untrusted plain data, so everything here is named, bounded and checked against the asset.
+
+export const MAX_CLIP_LAYERS = 8;
+const MAX_MASK_JOINTS = 32;
+const MAX_BONE_MAP_ENTRIES = 64;
+const MAX_NAME_LENGTH = 128;
+const MAX_LAYER_SPEED = 8;
+const MAX_LAYER_OFFSET = 30;
+
+/**
+ * What the layers are checked against: `clips` (`{ duration, targets }` per clip, the node names its tracks move) and
+ * `nodes` (`{ id, name }` per node). Built by the asset from its decoded file.
+ */
+export function clipLayerContextFromAsset(animations, nodes) {
+ return {
+ clips: animations.map(animation => ({
+ duration: animation.duration,
+ targets: new Set(animation.tracks.map(track => track.name.slice(0, track.name.lastIndexOf('.')))),
+ })),
+ nodes: nodes.map(({ id, name }) => ({ id, name })),
+ };
+}
+
+function nodeNameResolver(context) {
+ const nameById = new Map(context.nodes.map(node => [node.id, node.name]));
+ const names = new Set(context.nodes.map(node => node.name));
+ return function resolveNode(value, label) {
+ if (typeof value !== 'string' || !value || value.length > MAX_NAME_LENGTH) {
+ throw new TypeError(`${label} needs a node ID or name of 1 to ${MAX_NAME_LENGTH} characters.`);
+ }
+ if (nameById.has(value)) return nameById.get(value);
+ if (names.has(value)) return value;
+ throw new RangeError(`${label}: ${value.slice(0, 64)} is not a node of this asset. Find IDs and names with scene_inspect kind hierarchy.`);
+ };
+}
+
+function normalizedMask(input, resolveNode, position) {
+ const label = `Motion layer ${position} mask`;
+ knownKeys(input, ['joints', 'descendants', 'exclude'], label);
+ denseArray(input.joints, MAX_MASK_JOINTS, `${label} joints`);
+ if (!input.joints.length) throw new RangeError(`${label} needs at least one joint.`);
+ const mask = { joints: input.joints.map(joint => resolveNode(joint, `${label} joint`)) };
+ if (input.descendants !== undefined) {
+ if (typeof input.descendants !== 'boolean') throw new TypeError(`${label} descendants must be boolean.`);
+ mask.descendants = input.descendants;
+ }
+ if (input.exclude !== undefined) {
+ denseArray(input.exclude, MAX_MASK_JOINTS, `${label} exclude`);
+ mask.exclude = input.exclude.map(joint => resolveNode(joint, `${label} exclude`));
+ }
+ return mask;
+}
+
+/** Retargeting by name: the clip's track target (a node name in the clip) mapped to the node of this asset it should move. */
+function normalizedBoneMap(input, clip, resolveNode, position) {
+ const label = `Motion layer ${position} bones`;
+ if (!input || Object.getPrototypeOf(input) !== Object.prototype) throw new TypeError(`${label} must be a plain object.`);
+ const entries = Object.entries(input);
+ if (!entries.length || entries.length > MAX_BONE_MAP_ENTRIES) throw new RangeError(`${label} needs 1 to ${MAX_BONE_MAP_ENTRIES} entries.`);
+ const resolved = entries.map(([from, to]) => {
+ if (!clip.targets.has(from)) throw new RangeError(`${label}: the clip has no track for ${from.slice(0, 64)}.`);
+ return [from, resolveNode(to, `${label} ${from.slice(0, 64)}`)];
+ });
+ const destinations = resolved.map(([, destination]) => destination);
+ if (new Set(destinations).size !== destinations.length) throw new RangeError(`${label} cannot send two clip nodes to the same node.`);
+ return Object.fromEntries(resolved);
+}
+
+function normalizedLayer(input, position, context, resolveNode) {
+ const label = `Motion layer ${position}`;
+ knownKeys(input, ['clip', 'loop', 'weight', 'speed', 'offset', 'additive', 'reference', 'mask', 'bones', 'morph'], label);
+ const clip = context.clips[input.clip];
+ if (!Number.isInteger(input.clip) || !clip) throw new RangeError(`${label} clip must be the index of a clip in the asset (0 to ${context.clips.length - 1}).`);
+ const layer = { clip: input.clip };
+ for (const flag of ['loop', 'additive', 'morph']) {
+ if (input[flag] === undefined) continue;
+ if (typeof input[flag] !== 'boolean') throw new TypeError(`${label} ${flag} must be boolean.`);
+ layer[flag] = input[flag];
+ }
+ if (input.weight !== undefined) layer.weight = bounded(input.weight, 0, 1, `${label} weight`);
+ if (input.speed !== undefined) layer.speed = bounded(input.speed, 0.05, MAX_LAYER_SPEED, `${label} speed`);
+ if (input.offset !== undefined) layer.offset = bounded(input.offset, -MAX_LAYER_OFFSET, MAX_LAYER_OFFSET, `${label} offset`);
+ if (input.reference !== undefined) layer.reference = bounded(input.reference, 0, clip.duration, `${label} reference`);
+ if (input.mask !== undefined) layer.mask = normalizedMask(input.mask, resolveNode, position);
+ if (input.bones !== undefined) layer.bones = normalizedBoneMap(input.bones, clip, resolveNode, position);
+ return layer;
+}
+
+/** Validate `motion.layers` against the asset. Returns plain data the asset turns into layer definitions. */
+export function normalizeClipLayers(input, context) {
+ if (!context) throw new RangeError('Motion layers play clips of an imported asset, so they need an asset recipe.');
+ denseArray(input, MAX_CLIP_LAYERS, 'Motion layers');
+ if (!input.length) throw new RangeError('Motion layers needs at least one layer. Leave it out to play none.');
+ const resolveNode = nodeNameResolver(context);
+ return input.map((layer, position) => normalizedLayer(layer, position, context, resolveNode));
+}
diff --git a/src/agent-motion.js b/src/agent-motion.js
index 0842299b..73798775 100644
--- a/src/agent-motion.js
+++ b/src/agent-motion.js
@@ -2,6 +2,7 @@ import { createAnimationClip, compileAnimationSampler } from './animation.js';
import { createCameraPath } from './camera-path.js';
import { createSkeletonPose } from './skeleton-pose.js';
import { createNodeConstraintEvaluator, normalizeConstraints, normalizeDrivers } from './node-constraints.js';
+import { normalizeClipLayers } from './agent-clip-layers.js';
import { bounded, denseArray, finite, knownKeys, valueFrom } from './motion-validation.js';
const PROPERTIES = {
@@ -269,21 +270,22 @@ export function normalizeAgentMotion(input, recipe) {
if (input === null || input === undefined) {
return null;
}
- knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers'], 'motion');
+ knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers', 'layers'], 'motion');
const duration = bounded(input.duration, 0.1, 30, 'Motion duration');
const loop = input.loop === undefined ? false : input.loop;
if (typeof loop !== 'boolean') {
throw new TypeError('Motion loop must be boolean.');
}
- denseArray(input.tracks, 128, 'Motion tracks');
- if (!input.tracks.length && !input.ik?.length && !input.constraints?.length && !input.drivers?.length) {
+ const inputTracks = input.tracks ?? [];
+ denseArray(inputTracks, 128, 'Motion tracks');
+ if (!inputTracks.length && !input.layers?.length && !input.ik?.length && !input.constraints?.length && !input.drivers?.length) {
throw new RangeError('Motion needs at least one track, IK solver, constraint or driver. Use null to clear it.');
}
const nodes = new Set((recipe.nodes ?? []).map(node => node.id));
const materials = new Set((recipe.materials ?? []).map(material => material.id));
const identities = new Set();
let keyframeCount = 0;
- const tracks = input.tracks.map((track, index) => {
+ const tracks = inputTracks.map((track, index) => {
knownKeys(track, ['kind', 'id', 'property', 'interpolation', 'keyframes'], 'motion track');
if (!Object.hasOwn(PROPERTIES, track.kind) || !Object.hasOwn(PROPERTIES[track.kind], track.property)) {
throw new RangeError('Unsupported motion target or property.');
@@ -332,6 +334,9 @@ export function normalizeAgentMotion(input, recipe) {
return result;
});
const result = { duration, loop, tracks };
+ if (input.layers !== undefined) {
+ result.layers = normalizeClipLayers(input.layers, recipe.clipLayerContext);
+ }
if (input.ik !== undefined) {
result.ik = normalizeIk(input.ik, recipe, tracks, duration);
if (keyframeCount + ikKeyframeCount(result.ik) > 2048) {
diff --git a/src/gltf.js b/src/gltf.js
index 1badd974..92e292fa 100644
--- a/src/gltf.js
+++ b/src/gltf.js
@@ -979,7 +979,7 @@ export async function parseGltf(data, options = {}) {
}
function normalizePose(input) {
- knownPoseFields(input, ['animation', 'nodeOverrides'], 'pose');
+ knownPoseFields(input, ['animation', 'nodeOverrides', 'morphWeights'], 'pose');
const animation = input.animation ?? null;
if (animation !== null) {
knownPoseFields(animation, ['clip', 'time'], 'pose animation');
@@ -1032,7 +1032,29 @@ export async function parseGltf(data, options = {}) {
}
overrides.push(result);
}
- return { animation: animation === null ? null : { ...animation }, overrides };
+ return { animation: animation === null ? null : { ...animation }, overrides, morphWeights: normalizeMorphWeights(input.morphWeights) };
+ }
+
+ /** Morph weights by part index: `[{ part, weights }]`, each part morphed and each weight finite and within 0 to 1. */
+ function normalizeMorphWeights(input) {
+ if (input === undefined) return [];
+ if (!Array.isArray(input) || input.length > morphBindings.length || Reflect.ownKeys(input).length !== input.length + 1) {
+ throw new RangeError(`Pose morphWeights must be a dense array with at most ${morphBindings.length} entries.`);
+ }
+ const seenParts = new Set();
+ return input.map((entry, position) => {
+ const descriptor = Object.getOwnPropertyDescriptor(input, position);
+ if (!descriptor || !Object.hasOwn(descriptor, 'value')) throw new TypeError('Pose morphWeights cannot contain holes or accessors.');
+ knownPoseFields(descriptor.value, ['part', 'weights'], 'morph weights');
+ const binding = morphBindings.find(candidate => parts[descriptor.value.part] === candidate.part);
+ if (!Number.isInteger(descriptor.value.part) || !binding || seenParts.has(descriptor.value.part)) {
+ throw new RangeError('Pose morphWeights need distinct part indices of parts that have morph targets.');
+ }
+ seenParts.add(descriptor.value.part);
+ const weights = poseVector(descriptor.value.weights, binding.weights.length, 'morph weights');
+ if (weights.some(weight => weight < 0 || weight > 1)) throw new RangeError('Pose morph weights must be within 0 and 1.');
+ return { binding, weights };
+ });
}
function stagePose(input) {
@@ -1064,6 +1086,11 @@ export async function parseGltf(data, options = {}) {
}
node.updateMatrix();
}
+ for (const { binding, weights } of candidate.morphWeights) {
+ weights.forEach((weight, index) => {
+ binding.node.morphTargetInfluences[index] = weight;
+ });
+ }
preparePose();
} catch (error) {
rollback();
diff --git a/src/skeleton-pose.js b/src/skeleton-pose.js
index cc968d5e..ee6a1c4f 100644
--- a/src/skeleton-pose.js
+++ b/src/skeleton-pose.js
@@ -411,6 +411,7 @@ const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim };
const GLTF_TRACK_PROPERTIES = { position: 'translation', quaternion: 'rotation', scale: 'scale' };
const GLTF_STEP_INTERPOLATION = 2300;
const GLTF_LINEAR_INTERPOLATION = 2301;
+const GLTF_CUBIC_INTERPOLATION = 2302;
const RESAMPLE_RATE = 30;
function trackKeyframes(track, size) {
@@ -434,7 +435,7 @@ function trackKeyframes(track, size) {
* Node tracks keep their decoded node names. Morph weight tracks are skipped. Step keys stay step; cubic keys are
* resampled at 30 frames per second.
*/
-export function clipFromGltfAnimation(animation, { loop = false } = {}) {
+export function clipFromGltfAnimation(animation, { loop = false, rename = {} } = {}) {
if (!Array.isArray(animation?.tracks) || !Number.isFinite(animation.duration)) throw new TypeError('clipFromGltfAnimation needs an animation from asset.animations.');
const tracks = [];
for (const track of animation.tracks) {
@@ -442,8 +443,9 @@ export function clipFromGltfAnimation(animation, { loop = false } = {}) {
const property = GLTF_TRACK_PROPERTIES[track.name.slice(separator + 1)];
if (!property || !track.times.length) continue;
const size = property === 'rotation' ? 4 : 3;
+ const trackTarget = track.name.slice(0, separator);
tracks.push({
- target: track.name.slice(0, separator), property,
+ target: Object.hasOwn(rename, trackTarget) ? rename[trackTarget] : trackTarget, property,
interpolation: track.getInterpolation?.() === GLTF_STEP_INTERPOLATION ? 'STEP' : 'LINEAR',
keyframes: trackKeyframes(track, size),
});
@@ -451,6 +453,85 @@ export function clipFromGltfAnimation(animation, { loop = false } = {}) {
return createAnimationClip({ duration: Math.max(animation.duration, 1e-3), loop, tracks });
}
+const MORPH_TRACK_SUFFIX = '.morphTargetInfluences';
+
+/**
+ * The morph weight tracks of a loaded glTF animation, which `clipFromGltfAnimation` leaves out. Each track names the mesh
+ * part it moves and is sampled with the decoder's own interpolant, so step, linear and cubic keys all play as authored.
+ * Pass the result as `morphs` on a layer of `createAssetPose`.
+ */
+export function morphClipFromGltfAnimation(animation, { loop = false } = {}) {
+ if (!Array.isArray(animation?.tracks) || !Number.isFinite(animation.duration)) throw new TypeError('morphClipFromGltfAnimation needs an animation from asset.animations.');
+ const tracks = animation.tracks
+ .filter(track => track.name.endsWith(MORPH_TRACK_SUFFIX) && track.times.length)
+ .map(track => {
+ const valuesPerKey = track.values.length / track.times.length;
+ const count = track.getInterpolation?.() === GLTF_CUBIC_INTERPOLATION ? valuesPerKey / 3 : valuesPerKey;
+ return { part: track.name.slice(0, -MORPH_TRACK_SUFFIX.length), count, interpolant: track.createInterpolant(new Float64Array(count)) };
+ });
+ return { duration: Math.max(animation.duration, 1e-3), loop, tracks };
+}
+
+function morphClipTime(morphs, layerTime) {
+ if (!morphs.loop) return Math.min(morphs.duration, Math.max(0, layerTime));
+ return ((layerTime % morphs.duration) + morphs.duration) % morphs.duration;
+}
+
+/** The deepest asset node that owns each mesh part, by index, so a layer mask can include or leave out a part by its bone. */
+function ownerNodeByPart(nodes) {
+ const owners = new Map();
+ nodes.forEach((node, index) => {
+ for (const meshId of node.meshIds ?? []) owners.set(Number(meshId.slice('mesh-'.length)), index);
+ });
+ return owners;
+}
+
+function createMorphLayers(asset, nodes, layers, rig) {
+ const prepared = prepareRigGeometry(rig, 'Pose');
+ const resolveJoint = jointResolver(rig, prepared);
+ const owners = ownerNodeByPart(nodes);
+ return layers.filter(layer => layer.morphs?.tracks.length).map(layer => {
+ const mask = maskWeights(prepared, resolveJoint, layer.mask);
+ const partIndices = new Map();
+ for (const track of layer.morphs.tracks) {
+ const matching = [...asset.parts.keys()].filter(index => {
+ const part = asset.parts[index];
+ return part.name === track.part && part.morph?.weights.length === track.count && mask[owners.get(index)] > 0;
+ });
+ partIndices.set(track, matching);
+ }
+ return {
+ morphs: layer.morphs, partIndices, mask, owners, additive: layer.additive === true,
+ speed: layer.speed ?? 1, offset: layer.offset ?? 0, weight: weightFunction(layer.weight ?? 1, 'Morph layer weight'),
+ reference: layer.reference ?? 0,
+ };
+ });
+}
+
+/** Blend each morph layer's weights over the ones before it. Returns [{ part, weights }] for the parts any layer drives. */
+function evaluateMorphLayers(morphLayers, time) {
+ const blended = new Map();
+ for (const layer of morphLayers) {
+ const layerWeight = checkedWeight(layer.weight, time, 'Morph layer weight');
+ if (layerWeight === 0) continue;
+ const layerTime = time * layer.speed + layer.offset;
+ for (const track of layer.morphs.tracks) {
+ const sampled = Array.from(track.interpolant.evaluate(morphClipTime(layer.morphs, layerTime)));
+ const reference = layer.additive ? Array.from(track.interpolant.evaluate(morphClipTime(layer.morphs, layer.reference))) : null;
+ for (const part of layer.partIndices.get(track)) {
+ const weights = blended.get(part) ?? new Array(track.count).fill(0);
+ const strength = layerWeight * layer.mask[layer.owners.get(part)];
+ weights.forEach((current, index) => {
+ const target = reference ? current + sampled[index] - reference[index] : sampled[index];
+ weights[index] = Math.min(1, Math.max(0, current + (target - current) * strength));
+ });
+ blended.set(part, weights);
+ }
+ }
+ }
+ return [...blended].map(([part, weights]) => ({ part, weights }));
+}
+
function rigFromAssetNodes(nodes) {
const indexById = new Map(nodes.map((node, index) => [node.id, index]));
const jointNames = nodes.filter(node => node.joint).map(node => node.name);
@@ -479,27 +560,50 @@ function checkAssetIkScales(rig, solvedNames) {
}
}
+function createAssetPoseParts(asset, layers, ik) {
+ if (typeof asset?.stagePose !== 'function' || !Array.isArray(asset.nodes)) throw new TypeError('createAssetPose needs an asset from loadGltf or parseGltf.');
+ if (!Array.isArray(layers) || !Array.isArray(ik)) throw new TypeError('layers and ik must be arrays.');
+ const nodes = asset.nodes;
+ const rig = rigFromAssetNodes(nodes);
+ const nodeLayers = layers.filter(layer => layer?.clip || !layer?.morphs);
+ const pose = createSkeletonPose({ rig, layers: nodeLayers, ik });
+ checkAssetIkScales(rig, pose.solvedJointNames);
+ const written = pose.writtenJoints.filter(({ index }) => nodes[index].editable);
+ const morphLayers = createMorphLayers(asset, nodes, layers, rig);
+ /** Rebuild the pose for a time and return what the asset needs to stage it. */
+ function evaluate(time) {
+ pose.apply(time);
+ const nodeOverrides = written.map(({ index, translation }) => {
+ const override = { id: nodes[index].id, rotation: Array.from(pose.localRotation(index)) };
+ if (translation) override.translation = Array.from(pose.localTranslation(index));
+ return override;
+ });
+ return { nodeOverrides, morphWeights: evaluateMorphLayers(morphLayers, time) };
+ }
+ return { pose, evaluate };
+}
+
+/**
+ * Evaluate layers alone, without IK and without committing anything: for a host that stages the result itself, as the
+ * MCP asset recipe does before it solves IK. `evaluate(time)` gives `{ nodeOverrides, morphWeights }` for
+ * `asset.stagePose`. The same time always gives the same result.
+ */
+export function createAssetLayerEvaluator(asset, layers) {
+ return { evaluate: createAssetPoseParts(asset, layers, []).evaluate };
+}
+
/**
* Pose a loaded glTF asset from { layers, ik }. Unlike a skin palette this moves every skin and every rigid part attached
* to the hierarchy, and IK targets are in the asset's world space. Joints are named by decoded node name or humanoid bone.
- * `apply(time)` commits the pose and returns `asset.parts`; pass them to `renderer.updateParts`.
+ * A layer may carry `morphs` from `morphClipFromGltfAnimation` to drive morph weights too; its mask picks parts by the
+ * bone that owns them. `apply(time)` commits the pose and returns `asset.parts`; pass them to `renderer.updateParts`.
*/
export function createAssetPose(asset, { layers = [], ik = [] } = {}) {
- if (typeof asset?.stagePose !== 'function' || !Array.isArray(asset.nodes)) throw new TypeError('createAssetPose needs an asset from loadGltf or parseGltf.');
- const { nodes } = asset;
- const rig = rigFromAssetNodes(nodes);
- const pose = createSkeletonPose({ rig, layers, ik });
- checkAssetIkScales(rig, pose.solvedJointNames);
- const written = pose.writtenJoints.filter(({ index }) => nodes[index].editable);
+ const { pose, evaluate } = createAssetPoseParts(asset, layers, ik);
return {
apply(time) {
- pose.apply(time);
- const nodeOverrides = written.map(({ index, translation }) => {
- const override = { id: nodes[index].id, rotation: Array.from(pose.localRotation(index)) };
- if (translation) override.translation = Array.from(pose.localTranslation(index));
- return override;
- });
- return asset.stagePose({ animation: null, nodeOverrides }).commit();
+ const { nodeOverrides, morphWeights } = evaluate(time);
+ return asset.stagePose({ animation: null, nodeOverrides, morphWeights }).commit();
},
jointWorld: pose.jointWorld,
get ikResults() {
diff --git a/tests/agent-asset-layers.test.js b/tests/agent-asset-layers.test.js
new file mode 100644
index 00000000..2c16d8ae
--- /dev/null
+++ b/tests/agent-asset-layers.test.js
@@ -0,0 +1,241 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { InterpolateDiscrete, NumberKeyframeTrack } from 'three';
+import { parseGltf } from '../src/gltf.js';
+import { createAgentAssetScene } from '../src/agent-asset.js';
+import { clipFromGltfAnimation, createAssetPose, morphClipFromGltfAnimation } from '../src/skeleton-pose.js';
+
+// A real character: CC0 RobotExpressive. Its clips Walking and Wave move different limbs, and every clip also animates
+// the face through morph weights on three head meshes.
+const bytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));
+const ASSET_ID = 'cd'.repeat(32);
+
+function loadRobot() {
+ return parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });
+}
+
+function clipIndex(asset, name) {
+ const index = asset.animations.findIndex(animation => animation.name === name);
+ assert.ok(index >= 0, `no clip ${name}`);
+ return index;
+}
+
+function assetScene(asset, motion) {
+ return createAgentAssetScene(asset, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID, motion });
+}
+
+function walkAndWave(asset, extraWave = {}) {
+ return {
+ duration: 2,
+ loop: true,
+ layers: [
+ { clip: clipIndex(asset, 'Walking') },
+ { clip: clipIndex(asset, 'Wave'), mask: { joints: ['UpperArmR'] }, morph: false, ...extraWave },
+ ],
+ };
+}
+
+const matrices = scene => scene.parts.map(part => Array.from(part.matrix));
+const matrixDistance = (first, second) => Math.max(...first.map((value, index) => Math.abs(value - second[index])));
+
+function changedParts(before, after) {
+ return before.map((matrix, index) => index).filter(index => matrixDistance(before[index], after[index]) > 1e-4);
+}
+
+async function sampledMatrices(motion, time) {
+ const asset = await loadRobot();
+ const scene = assetScene(asset, motion);
+ scene.sampleMotion(time);
+ return matrices(scene);
+}
+
+test('a wave layer masked to the right arm leaves every other part walking', async () => {
+ const asset = await loadRobot();
+ const time = 0.4;
+ const walkOnly = await sampledMatrices({ duration: 2, loop: true, layers: [{ clip: clipIndex(asset, 'Walking') }] }, time);
+ const both = await sampledMatrices(walkAndWave(asset), time);
+ const names = asset.parts.map(part => part.name);
+ const changed = changedParts(walkOnly, both).map(index => names[index]);
+ assert.deepEqual(changed, ['ArmR']);
+ assert.ok(matrixDistance(walkOnly[names.indexOf('ArmR')], both[names.indexOf('ArmR')]) > 1, 'the arm waves instead of swinging');
+ const walkingLegs = ['LegL', 'LegR', 'LowerLegL_1', 'LowerLegR_1', 'FootL_1', 'FootR_1'].map(name => names.indexOf(name));
+ const restPose = await sampledMatrices({ duration: 2, loop: true, layers: [{ clip: clipIndex(asset, 'Walking'), weight: 0 }] }, time);
+ assert.ok(walkingLegs.every(index => matrixDistance(restPose[index], both[index]) > 0.1), 'the legs are walking');
+});
+
+test('the layered pose matches the code API for every part', async () => {
+ const asset = await loadRobot();
+ const time = 0.7;
+ const scene = assetScene(asset, walkAndWave(asset));
+ scene.sampleMotion(time);
+ const reference = await loadRobot();
+ const pose = createAssetPose(reference, {
+ layers: [
+ { clip: clipFromGltfAnimation(reference.animations[clipIndex(reference, 'Walking')], { loop: true }), morphs: morphClipFromGltfAnimation(reference.animations[clipIndex(reference, 'Walking')], { loop: true }) },
+ { clip: clipFromGltfAnimation(reference.animations[clipIndex(reference, 'Wave')], { loop: true }), mask: { joints: ['UpperArmR'] } },
+ ],
+ });
+ pose.apply(time);
+ scene.parts.forEach((part, index) => {
+ const distance = matrixDistance(Array.from(part.matrix), Array.from(reference.parts[index].matrix));
+ assert.ok(distance < 1e-3, `${asset.parts[index].name}: ${distance}`);
+ });
+});
+
+test('seeking gives the same pose as playing: the same time twice is identical', async () => {
+ const asset = await loadRobot();
+ const scene = assetScene(asset, walkAndWave(asset));
+ scene.sampleMotion(0.4);
+ const first = matrices(scene);
+ const firstWeights = scene.parts.map(part => part.morph && Array.from(part.morph.weights));
+ scene.sampleMotion(1.3);
+ scene.sampleMotion(0.1);
+ scene.sampleMotion(0.4);
+ assert.deepEqual(matrices(scene), first);
+ assert.deepEqual(scene.parts.map(part => part.morph && Array.from(part.morph.weights)), firstWeights);
+});
+
+test('a layer with bones retargets the clip onto other nodes by name', async () => {
+ const asset = await loadRobot();
+ const time = 0.5;
+ const waveId = clipIndex(asset, 'Wave');
+ const leftArm = asset.nodes.find(node => node.name === 'UpperArmL').id;
+ const rest = await sampledMatrices({ duration: 2, layers: [{ clip: waveId, mask: { joints: ['UpperLegR'] }, morph: false }] }, time);
+ const waveRight = await sampledMatrices({ duration: 2, layers: [{ clip: waveId, mask: { joints: ['UpperArmR'] }, morph: false }] }, time);
+ const waveLeft = await sampledMatrices({
+ duration: 2, layers: [{ clip: waveId, mask: { joints: ['UpperArmL'] }, bones: { UpperArmR: leftArm }, morph: false }],
+ }, time);
+ const rightChanged = changedParts(rest, waveRight);
+ const leftChanged = changedParts(rest, waveLeft);
+ assert.ok(rightChanged.length > 0 && leftChanged.length > 0);
+ assert.notDeepEqual(rightChanged, leftChanged);
+});
+
+/** The robot's own morph tracks are all zero, so a real track with values goes through the decoder's own track class. */
+function faceAnimation(asset) {
+ const dance = asset.animations[clipIndex(asset, 'Dance')];
+ const smile = new NumberKeyframeTrack('Head_2.morphTargetInfluences', [0, 1], [0, 0, 0, 1, 0.5, 0.25]);
+ const frown = new NumberKeyframeTrack('Head_3.morphTargetInfluences', [0, 1], [0.8, 0, 0, 0.8, 0, 0], InterpolateDiscrete);
+ return { name: 'Face', duration: dance.duration, tracks: [...dance.tracks.filter(track => !track.name.includes('morph')), smile, frown] };
+}
+
+function faceWeights(asset, name) {
+ return Array.from(asset.parts.find(part => part.name === name).morph.weights, weight => Number(weight.toFixed(5)));
+}
+
+test('morph clips drive face weights as authored, and a mask can leave the face alone', async () => {
+ const asset = await loadRobot();
+ const face = faceAnimation(asset);
+ const morphs = morphClipFromGltfAnimation(face, { loop: false });
+ assert.equal(morphs.tracks.length, 2);
+ const pose = createAssetPose(asset, { layers: [{ clip: clipFromGltfAnimation(face), morphs }] });
+ pose.apply(0.5);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [0.5, 0.25, 0.125]);
+ assert.deepEqual(faceWeights(asset, 'Head_3'), [0.8, 0, 0]);
+ assert.deepEqual(faceWeights(asset, 'Head_4'), [0, 0, 0]);
+ pose.apply(2);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [1, 0.5, 0.25], 'a clip that does not loop holds its last key');
+
+ const halfWeight = createAssetPose(asset, { layers: [{ clip: clipFromGltfAnimation(face), morphs, weight: 0.5 }] });
+ halfWeight.apply(1);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [0.5, 0.25, 0.125]);
+
+ const additive = createAssetPose(asset, { layers: [{ clip: clipFromGltfAnimation(face), morphs, additive: true, reference: 0 }] });
+ additive.apply(1);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [1, 0.5, 0.25]);
+
+ const legsOnly = createAssetPose(asset, { layers: [{ clip: clipFromGltfAnimation(face), morphs, mask: { joints: ['UpperLegL'] } }] });
+ legsOnly.apply(1);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [0, 0, 0]);
+ const headOnly = createAssetPose(asset, { layers: [{ clip: clipFromGltfAnimation(face), morphs, mask: { joints: ['Head'] } }] });
+ headOnly.apply(1);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [1, 0.5, 0.25]);
+});
+
+test('the real clips load their zero morph tracks and keep the face at rest', async () => {
+ const asset = await loadRobot();
+ const dance = asset.animations[clipIndex(asset, 'Dance')];
+ const morphs = morphClipFromGltfAnimation(dance, { loop: true });
+ assert.deepEqual(morphs.tracks.map(track => [track.part, track.count]), [['Head_2', 3], ['Head_3', 3], ['Head_4', 3]]);
+ const pose = createAssetPose(asset, { layers: [{ clip: clipFromGltfAnimation(dance, { loop: true }), morphs }] });
+ pose.apply(1.2);
+ assert.deepEqual(faceWeights(asset, 'Head_2'), [0, 0, 0]);
+});
+
+test('layer input that is not bounded plain data is refused', async () => {
+ const asset = await loadRobot();
+ const walking = clipIndex(asset, 'Walking');
+ const hostile = {
+ 'not an array': { a: 1 },
+ 'too many layers': Array.from({ length: 9 }, () => ({ clip: walking })),
+ 'no layers': [],
+ 'unknown field': [{ clip: walking, script: 'alert(1)' }],
+ 'clip out of range': [{ clip: 999 }],
+ 'negative clip': [{ clip: -1 }],
+ 'fractional clip': [{ clip: 1.5 }],
+ 'weight above one': [{ clip: walking, weight: 2 }],
+ 'weight NaN': [{ clip: walking, weight: Number.NaN }],
+ 'zero speed': [{ clip: walking, speed: 0 }],
+ 'huge speed': [{ clip: walking, speed: 1e9 }],
+ 'huge offset': [{ clip: walking, offset: 1e9 }],
+ 'reference beyond the clip': [{ clip: walking, additive: true, reference: 1e6 }],
+ 'loop as a string': [{ clip: walking, loop: 'yes' }],
+ 'empty mask': [{ clip: walking, mask: { joints: [] } }],
+ 'mask joint that does not exist': [{ clip: walking, mask: { joints: ['NoSuchBone'] } }],
+ 'mask joint as an object': [{ clip: walking, mask: { joints: [{ name: 'Head' }] } }],
+ 'mask with too many joints': [{ clip: walking, mask: { joints: Array.from({ length: 33 }, () => 'Head') } }],
+ 'mask unknown field': [{ clip: walking, mask: { joints: ['Head'], deep: true } }],
+ 'bones key the clip does not have': [{ clip: walking, bones: { NoSuchTrack: 'Head' } }],
+ 'bones to a node that does not exist': [{ clip: walking, bones: { Head: 'NoSuchBone' } }],
+ 'bones that collide': [{ clip: walking, bones: { Head: 'Torso_3', Neck: 'Torso_3' } }],
+ 'bones empty': [{ clip: walking, bones: {} }],
+ 'bones as an array': [{ clip: walking, bones: ['Head'] }],
+ 'a url as a clip': [{ clip: 'https://example.com/walk.glb' }],
+ 'a null layer': [null],
+ };
+ for (const [label, layers] of Object.entries(hostile)) {
+ assert.throws(() => assetScene(asset, { duration: 2, layers }), Error, label);
+ }
+ const accessor = { clip: walking };
+ Object.defineProperty(accessor, 'weight', { enumerable: true, get() { return 1; } });
+ assert.throws(() => assetScene(asset, { duration: 2, layers: [accessor] }), Error, 'accessor');
+ const pollutedBones = JSON.parse('{"__proto__": "Head"}');
+ assert.throws(() => assetScene(asset, { duration: 2, layers: [{ clip: walking, bones: pollutedBones }] }), Error, '__proto__ key');
+ assert.equal(({}).polluted, undefined);
+});
+
+test('a recipe without an imported asset refuses layers', async () => {
+ const { createAgentScene } = await import('../src/agent-scene.js');
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'box', type: 'box', bevel: 0 }], materials: [{ id: 'paint', color: [0.5, 0.5, 0.5] }],
+ nodes: [{ id: 'cube', geometry: 'box', material: 'paint' }], motion: { duration: 1, layers: [{ clip: 0 }] },
+ };
+ assert.throws(() => createAgentScene(recipe), /imported asset|asset recipe/);
+});
+
+test('stagePose refuses morph weights that are not bounded', async () => {
+ const asset = await loadRobot();
+ const morphPart = asset.parts.findIndex(part => part.morph);
+ const plainPart = asset.parts.findIndex(part => !part.morph);
+ const count = asset.parts[morphPart].morph.weights.length;
+ const zeros = Array.from({ length: count }, () => 0);
+ const attempts = {
+ 'part without morph': [{ part: plainPart, weights: zeros }],
+ 'part out of range': [{ part: 9999, weights: zeros }],
+ 'duplicate part': [{ part: morphPart, weights: zeros }, { part: morphPart, weights: zeros }],
+ 'wrong length': [{ part: morphPart, weights: [0] }],
+ 'weight above one': [{ part: morphPart, weights: zeros.map(() => 2) }],
+ 'weight NaN': [{ part: morphPart, weights: zeros.map(() => Number.NaN) }],
+ 'extra field': [{ part: morphPart, weights: zeros, evil: true }],
+ 'not an array': { part: morphPart },
+ };
+ for (const [label, morphWeights] of Object.entries(attempts)) {
+ assert.throws(() => asset.stagePose({ animation: null, nodeOverrides: [], morphWeights }), Error, label);
+ }
+ const staged = asset.stagePose({ animation: null, nodeOverrides: [], morphWeights: [{ part: morphPart, weights: zeros.map(() => 0.5) }] });
+ staged.commit();
+ assert.deepEqual(Array.from(asset.parts[morphPart].morph.weights), zeros.map(() => 0.5));
+ asset.stagePose({ animation: null, nodeOverrides: [] }).commit();
+ assert.deepEqual(Array.from(asset.parts[morphPart].morph.weights), zeros);
+});
diff --git a/tests/agent-modeling-suite.test.js b/tests/agent-modeling-suite.test.js
index 25242896..9d0f6cab 100644
--- a/tests/agent-modeling-suite.test.js
+++ b/tests/agent-modeling-suite.test.js
@@ -91,6 +91,29 @@ test('the robot shot needs both hands on target and a side-on camera', async ()
assert.deepEqual(failedKinds(await gradeRecipe(task, noCamera)), ['shot']);
});
+test('the walk and wave check needs both clips, the legs walking and only the right arm waving', async () => {
+ const task = taskById('robot-walk-wave');
+ const noWave = structuredClone(REFERENCES['robot-walk-wave']);
+ noWave.motion.layers.pop();
+ assert.deepEqual(failedKinds(await gradeRecipe(task, noWave)), ['assetWalkAndWave']);
+
+ const waveEverywhere = structuredClone(REFERENCES['robot-walk-wave']);
+ delete waveEverywhere.motion.layers[1].mask;
+ assert.deepEqual(failedKinds(await gradeRecipe(task, waveEverywhere)), ['assetWalkAndWave']);
+
+ const wrongClip = structuredClone(REFERENCES['robot-walk-wave']);
+ wrongClip.motion.layers[1].clip = 2;
+ assert.deepEqual(failedKinds(await gradeRecipe(task, wrongClip)), ['assetWalkAndWave']);
+
+ const waveOnLegs = structuredClone(REFERENCES['robot-walk-wave']);
+ waveOnLegs.motion.layers[1].mask.joints = ['node-37', 'node-57'];
+ assert.deepEqual(failedKinds(await gradeRecipe(task, waveOnLegs)), ['assetWalkAndWave']);
+
+ const noMotion = structuredClone(REFERENCES['robot-walk-wave']);
+ delete noMotion.motion;
+ assert.deepEqual(failedKinds(await gradeRecipe(task, noMotion)), ['assetWalkAndWave']);
+});
+
test('tasks that change an existing scene carry their starting recipe in the prompt', () => {
for (const id of ['crate-revision', 'bracket-revision']) {
const task = taskById(id);