Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add authored rigs: armatures, presets and automatic skin weights (#46)

Nguyen Xuan An6605476d358b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4df02c5f..e1c81fe8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add authored rigs (#46): a recipe `armatures` list (bones with a name, parent, head and tail, or a `humanoid` or `quadruped` preset fitted to a mesh node's bounds, with `landmarks` to move bones), and a `skin` on a mesh node that binds it with automatic weights, plus a `set-armatures` operation. Each bone becomes a recipe node, so keyframed bone rotation and `motion.ik` run through the same paths as imported rigs, and humanoid bones carry the `HUMANOID_BONES` names so `retargetClip` maps them. Weights are the distance to each bone segment with an inverse-fourth-power falloff, the nearest four kept; they depend only on position, so hard-edge seams never open. `scene_inspect` gains `rig`: unweighted vertices, bones with no vertices, and joint axis problems (zero-length bones, straight limb chains, knees that bend backward). `scene_export_glb` writes the bones and a walk clip baked at 30 frames a second from tracks and IK. Add the `rigged-walker` task to the agent modeling suite, with a reference and three failing variants. Blender 5.2 opens the exported walker as 1 armature, 21 bones, 14 meshes with 21 vertex groups each and 1 action of 24 frames; three.js loads 14 skinned meshes and the clip.
+
- Reach Rapier from recipes: a `physics` section (and a `set-physics` operation) puts rigid bodies on node IDs with box, ball, capsule, convex or trimesh colliders fitted to their geometry, joints, gravity and a duration of up to 10 seconds. It is recorded once at 60 steps a second and seeks like `motion`, so a seek back repeats the same frame (checked as identical PNG bytes on SwiftShader through MCP). `scene_inspect` reports per-body final positions and resting times, contacts and sensor enter and leave events. Rapier stays an optional peer, served to the preview from `node_modules` like Manifold, so the MCP server bundle does not grow.
- Add trimesh and convex-hull colliders (bounded triangle and point counts, checked before allocation), sensors with enter and leave events, and 16-bit collision groups and masks to `addons/physics`, plus `contactEvents`, `restFrames`, `bakePhysicsScene`, `loadPhysicsEngine` and `setPhysicsModuleLoader`. A collider with `sensor` now bakes instead of throwing.
- Add the `tray-drop` task to the agent modeling suite: balls dropped into a pocket cut in an authored mesh, graded on a fixed trimesh body, balls resting on the pocket floor and a repeatable seek. Raise four size budgets for the physics code (`entry:physics` to 17,900, `entry:agent-scene` to 121,100, `entry:agent-asset` to 128,500, `scene:agent-scene` to 147,300 bytes gzip).
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index f2268e0b..839aa1de 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -3,6 +3,7 @@ import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { measureAssetRecipe, measureRecipe } from './measure.mjs';
import { taskById } from './tasks.mjs';
+import { REQUIRED_HUMANOID_BONES } from '../../src/retarget.js';
const AXES = { x: 0, y: 1, z: 2 };
const SIZE_TOLERANCE = 0.03;
@@ -11,6 +12,37 @@ const GROUND_TOLERANCE = 0.005;
const round = value => Number(value.toPrecision(4));
+const forwardOf = point => point[2];
+
+// A walk moves both feet far, in opposite phase, bends knees forward and elbows back, and no limb part collapses or stretches.
+function checkWalk(rig, check) {
+ if (!rig?.samples.length) return { pass: false, detail: 'no armature or no motion' };
+ const problems = [];
+ for (const foot of ['leftFoot', 'rightFoot']) {
+ const travel = rig.samples.map(sample => forwardOf(sample.joints[foot] ?? [0, 0, 0]));
+ if (Math.max(...travel) - Math.min(...travel) < check.footTravel) problems.push(`${foot} moves ${round(Math.max(...travel) - Math.min(...travel))} m`);
+ }
+ const first = rig.samples[0];
+ const half = rig.samples[rig.samples.length / 2];
+ if (!first.joints.leftFoot || !half.joints.leftFoot || (forwardOf(first.joints.leftFoot) - forwardOf(first.joints.rightFoot)) * (forwardOf(half.joints.leftFoot) - forwardOf(half.joints.rightFoot)) >= 0) problems.push('the feet do not alternate');
+ const bends = [['LowerLeg', 'UpperLeg', 'Foot', 1], ['LowerArm', 'UpperArm', 'Hand', -1]];
+ for (const sample of rig.samples) {
+ for (const side of ['left', 'right']) {
+ for (const [middle, root, end, direction] of bends) {
+ const [rootZ, middleZ, endZ] = [root, middle, end].map(name => forwardOf(sample.joints[`${side}${name}`] ?? [0, 0, 0]));
+ if ((middleZ - (rootZ + endZ) / 2) * direction < -0.005) problems.push(`${side}${middle} bends the wrong way at t=${round(sample.time)}`);
+ }
+ }
+ }
+ for (const sample of rig.samples) {
+ for (const [name, diagonal] of Object.entries(sample.diagonals)) {
+ const ratio = diagonal / rig.restDiagonals[name];
+ if (ratio < 0.7 || ratio > 1.4) problems.push(`${name} is ${round(ratio)}x its size at t=${round(sample.time)}`);
+ }
+ }
+ return { pass: problems.length === 0, detail: [...new Set(problems)].slice(0, 4).join('; ') || `${rig.samples.length} samples: feet alternate, knees forward, elbows back, parts keep their size` };
+}
+
function checkOne(check, measures) {
switch (check.kind) {
case 'lint':
@@ -79,6 +111,22 @@ function checkOne(check, measures) {
const onPath = close(solver.firstTarget, check.from) && close(solver.lastTarget, check.to);
return { pass: onPath && solver.reached, detail: `targets ${JSON.stringify(solver.firstTarget)} to ${JSON.stringify(solver.lastTarget)}, reached ${solver.reached}, worst ${solver.worstError}` };
}
+ case 'rigBones': {
+ const missing = REQUIRED_HUMANOID_BONES.filter(bone => !measures.rig?.bones.includes(bone));
+ return { pass: Boolean(measures.rig) && missing.length === 0, detail: measures.rig ? (missing.length ? `missing bones ${missing.join(', ')}` : `${measures.rig.bones.length} bones, all humanoid bones present`) : 'no armature' };
+ }
+ case 'rigSkinned': {
+ const rig = measures.rig;
+ const problems = [];
+ if (!rig) problems.push('no armature');
+ else {
+ if (rig.skinnedNodes !== rig.meshNodes) problems.push(`${rig.meshNodes - rig.skinnedNodes} of ${rig.meshNodes} mesh nodes have no skin`);
+ if (rig.unweightedVertices > 0) problems.push(`${rig.unweightedVertices} unweighted vertices`);
+ }
+ return { pass: problems.length === 0, detail: problems.join('; ') || `${rig.skinnedNodes} mesh nodes skinned, no unweighted vertices` };
+ }
+ case 'rigWalk':
+ return checkWalk(measures.rig, check);
case 'physicsBody': {
const body = measures.physics?.bodies.find(candidate => candidate.node === check.node);
return { pass: body?.type === check.type && body?.shape === check.shape, detail: body ? `${body.node} is ${body.type} ${body.shape}` : `no physics body on ${check.node}` };
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 47e6cecc..31b454e9 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -226,6 +226,54 @@ function seekIsStable(scene, duration) {
return JSON.stringify(first) === JSON.stringify(second);
}
+const RIG_SAMPLES = 8;
+
+function skinnedDiagonal(part) {
+ const { positions, skinIndices, skinWeights } = part.geometry;
+ const palette = part.skin.jointMatrices;
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ const blended = [0, 0, 0];
+ for (let influence = 0; influence < 4; influence++) {
+ const weight = skinWeights[vertex * 4 + influence];
+ if (weight === 0) continue;
+ const moved = transformPoint(palette.subarray(skinIndices[vertex * 4 + influence] * 16), positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]);
+ for (let axis = 0; axis < 3; axis++) blended[axis] += moved[axis] * weight;
+ }
+ const world = transformPoint(part.matrix, ...blended);
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], world[axis]);
+ maximum[axis] = Math.max(maximum[axis], world[axis]);
+ }
+ }
+ return Math.hypot(...maximum.map((value, axis) => value - minimum[axis]));
+}
+
+/** Bones, skinning, and the walk sampled at even times: joint world positions and each skinned part's deformed size. */
+function measureRig(scene, duration) {
+ const recipe = scene.exportRecipe();
+ const inspected = scene.inspect({}).rig;
+ const meshNodes = recipe.nodes.filter(node => node.geometry);
+ const skinnedParts = () => scene.parts.filter(part => part.skin);
+ const samples = Array.from({ length: duration > 0 ? RIG_SAMPLES : 0 }, (_, step) => {
+ const time = duration * step / RIG_SAMPLES;
+ scene.sampleMotion(time);
+ const skin = skinnedParts()[0]?.skin;
+ const joints = Object.fromEntries((skin?.joints ?? []).map((joint, index) => [joint.name, Array.from(skin.jointWorldMatrices.subarray(index * 16 + 12, index * 16 + 15))]));
+ return { time, joints, diagonals: Object.fromEntries(skinnedParts().map(part => [part.name, skinnedDiagonal(part)])) };
+ });
+ scene.sampleMotion(null);
+ const restDiagonals = Object.fromEntries(skinnedParts().map(part => [part.name, skinnedDiagonal(part)]));
+ return {
+ bones: recipe.armatures.flatMap(armature => armature.bones.map(bone => `${armature.prefix}${bone.name}`)),
+ meshNodes: meshNodes.length, skinnedNodes: meshNodes.filter(node => node.skin).length,
+ unweightedVertices: inspected.reduce((total, armature) => total + armature.skinned.reduce((sum, skinned) => sum + skinned.unweightedVertices, 0), 0),
+ problems: inspected.flatMap(armature => armature.jointAxisProblems),
+ samples, restDiagonals,
+ };
+}
+
/** Load the recipe and measure what it builds. Throws if the recipe itself is invalid. */
export async function measureRecipe(recipe) {
if (needsMeshBooleans(recipe)) await loadMeshBooleans();
@@ -277,6 +325,7 @@ export async function measureRecipe(recipe) {
nodes: geometries.length,
physics,
physicsSeekStable,
+ rig: recipe.armatures ? measureRig(scene, recipe.motion?.duration ?? 0) : null,
patternTypes: scene.exportRecipe().materials.filter(material => material.pattern).map(material => material.pattern.type),
parts,
closedParts,
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index 6d301a97..daad1f46 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -5,6 +5,8 @@
const SUBDIVIDED_CUBE_SPAN = 0.8492;
const PEBBLE_SIZE = [0.08, 0.03, 0.05];
+import { walkerRecipe } from './walker.mjs';
+
const material = [{ id: 'paint', color: [0.6, 0.55, 0.5] }];
function scene(geometries, nodes) {
@@ -210,6 +212,7 @@ export const REFERENCES = {
{ id: 'head', geometry: 'head', translation: [0, 0.12, 0], rotation: axisRotation('x', -Math.PI / 2) },
],
),
+ 'rigged-walker': walkerRecipe(),
'pillar-court': scene(
[{ id: 'pillar', type: 'box', bevel: 0 }],
[{
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index dfd2ca06..f8f6638a 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -276,6 +276,23 @@ X = 0 and Z = 0, every pillar standing on the ground. Repeat one pillar over the
{ kind: 'section', axis: 'x', at: 0.4, equals: 3, label: 'three pillars along Z in the column at X = 0.4' },
],
},
+ {
+ id: 'rigged-walker',
+ prompt: `A blocky humanoid character 1.8 m tall, facing +Z, built from rounded blocks: a torso 0.34 m wide, 0.5 m tall and
+0.2 m deep (centre at 1.15 m), a head, and for each side an upper arm, lower arm and hand (the arms hang at the sides)
+and an upper leg, lower leg and foot, the feet flat on the ground. Give it a humanoid armature fitted to its height, bind
+every block to it with automatic weights, and give it a looping 1 second walk: legs and arms swing in opposite phase,
+knees bend forward and elbows bend back, and nothing stretches or collapses. Name the bones in the canonical humanoid
+way (hips, spine, head, leftUpperArm, leftLowerLeg, rightFoot and so on).`,
+ checks: [
+ { kind: 'lint' },
+ { kind: 'size', expected: [null, 1.8, null] },
+ { kind: 'ground', centred: false },
+ { kind: 'rigBones' },
+ { kind: 'rigSkinned' },
+ { kind: 'rigWalk', footTravel: 0.3, label: 'walk cycle' },
+ ],
+ },
{
id: 'robot-reach',
assets: true,
diff --git a/bench/agent-modeling/walker.mjs b/bench/agent-modeling/walker.mjs
new file mode 100644
index 00000000..86163fc2
--- /dev/null
+++ b/bench/agent-modeling/walker.mjs
@@ -0,0 +1,69 @@
+// The reference for the rigged-walker task: a blocky character built from subdivided mesh boxes, a humanoid armature
+// fitted to it, every part skinned with automatic weights, and a one second walk cycle that loops.
+
+// A box subdivided three times spans 0.8492 on each axis, so a scale of size / 0.8492 gives the wanted size.
+const SUBDIVIDED_CUBE_SPAN = 0.8492;
+const CHARACTER_HEIGHT = 1.8;
+const WALK_SECONDS = 1;
+
+function xRotation(degrees) {
+ const half = degrees * Math.PI / 360;
+ return [Math.sin(half), 0, 0, Math.cos(half)];
+}
+
+function part(id, center, size) {
+ return { id: `${id}-mesh`, geometry: 'block', material: 'cloth', skin: { armature: 'rig' }, translation: center, scale: size.map(extent => extent / SUBDIVIDED_CUBE_SPAN) };
+}
+
+function characterParts() {
+ const parts = [
+ part('torso', [0, 1.15, 0], [0.34, 0.5, 0.2]),
+ part('head', [0, 1.65, 0], [0.2, 0.3, 0.22]),
+ ];
+ for (const [side, sign] of [['left', 1], ['right', -1]]) {
+ parts.push(
+ part(`${side}-upper-arm`, [sign * 0.2, 1.233, 0], [0.09, 0.34, 0.09]),
+ part(`${side}-lower-arm`, [sign * 0.23, 0.945, 0], [0.08, 0.3, 0.08]),
+ part(`${side}-hand`, [sign * 0.255, 0.74, 0], [0.08, 0.14, 0.05]),
+ part(`${side}-upper-leg`, [sign * 0.112, 0.7, 0], [0.15, 0.42, 0.15]),
+ part(`${side}-lower-leg`, [sign * 0.12, 0.3, 0], [0.12, 0.42, 0.12]),
+ part(`${side}-foot`, [sign * 0.12, 0.04, 0.09], [0.11, 0.08, 0.26]),
+ );
+ }
+ return parts;
+}
+
+function rotationTrack(id, degrees) {
+ const keyframes = degrees.map((angle, step) => ({ time: step * WALK_SECONDS / (degrees.length - 1), value: xRotation(angle) }));
+ return { kind: 'node', id, property: 'rotation', interpolation: 'SMOOTH', keyframes };
+}
+
+// Positive X rotation swings a hanging limb backward. A thigh swings from forward (-) to back (+); a knee only folds the shin back (+).
+const THIGH = [-25, 0, 25, 0, -25];
+const SHIN = [5, 5, 10, 45, 5];
+const UPPER_ARM = [20, 0, -20, 0, 20];
+const FOREARM = [-10, -10, -30, -10, -10];
+
+function walkTracks() {
+ const halfCycle = values => [...values.slice(2, 4), ...values.slice(0, 2), values[2]];
+ return [
+ rotationTrack('leftUpperLeg', THIGH), rotationTrack('leftLowerLeg', SHIN),
+ rotationTrack('rightUpperLeg', halfCycle(THIGH)), rotationTrack('rightLowerLeg', halfCycle(SHIN)),
+ rotationTrack('leftUpperArm', UPPER_ARM), rotationTrack('leftLowerArm', FOREARM),
+ rotationTrack('rightUpperArm', halfCycle(UPPER_ARM)), rotationTrack('rightLowerArm', halfCycle(FOREARM)),
+ ];
+}
+
+export function walkerRecipe() {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'mesh', base: { type: 'box', bevel: 0 }, stack: [{ op: 'subdivide', levels: 3 }] }],
+ materials: [{ id: 'cloth', color: [0.55, 0.5, 0.45] }],
+ armatures: [{ id: 'rig', preset: 'humanoid', fit: { bounds: { min: [-0.3, 0, -0.1], max: [0.3, CHARACTER_HEIGHT, 0.1] } } }],
+ nodes: characterParts(),
+ motion: {
+ duration: WALK_SECONDS, loop: true, tracks: walkTracks(),
+ ik: [{ type: 'aim', joint: 'head', worldForward: [0, 0, 1], target: { keyframes: [{ time: 0, value: [1, 1.7, 3] }, { time: 0.5, value: [-1, 1.7, 3] }, { time: 1, value: [1, 1.7, 3] }] }, maxAngle: 25 }],
+ },
+ };
+}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 52cf5d30..55612b49 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -28,11 +28,11 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 129200,
- "entry:agent-asset": 136600,
+ "entry:agent-scene": 132000,
+ "entry:agent-asset": 139300,
"entry:hdri": 3300,
"scene:lit-box": 56000,
"scene:gltf-box": 75300,
- "scene:agent-scene": 155700
+ "scene:agent-scene": 158000
}
}
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index c60de4da..fd01efe0 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -117,6 +117,36 @@ the selected clip and skins and rigid parts all follow. Targets are in world spa
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.
There are no joint angle limits. [Skeleton pose layers](skeleton-pose.md) add clip layers and masks in code.
+## Authored rigs
+
+A recipe `armatures` list holds skeletons. Each bone has a `name`, a `parent` (a bone name or `null`), a rest `head` in the
+armature's own space and an optional `tail`; without one the tail is the mean of the children's heads. Instead of
+`bones`, give `preset: "humanoid"` or `"quadruped"` and `fit: { node }` (a mesh node whose bounds size the rig) or
+`fit: { bounds: { min, max } }`. `fit.landmarks` moves a bone head by name, or its tail as `<name>Tail`. Presets are
+resolved to explicit bones when the recipe is read, so a stored recipe does not change when the mesh does. A humanoid
+faces +Z with Y up and uses the `HUMANOID_BONES` names, so `retargetClip` maps it without overrides. Its knees sit a little
+forward of the leg line and its elbows a little behind, so a two-bone solve without a pole folds them the right way.
+A quadruped lies along Z and names its legs `leftFrontUpperLeg`, `rightHindFoot` and so on.
+
+Every bone becomes a recipe node (ID is `prefix` plus the name; the armature root is a node with the armature's ID), parented
+like the bones and carrying the `armature` field. Those nodes are regenerated from `armatures` each time the recipe is read, so edit
+bones with `set-armatures`, not `set-node`. Node rotation tracks and `motion.ik` address bones like any node; rotation is local
+to the bone head, and at rest it is the identity. Positive X rotation swings a hanging limb backward, so a thigh swings from
+negative to positive and a shin folds with positive values.
+
+A mesh node binds with `skin: { armature, maxInfluences, maxDistance }`. Weights are the distance from each vertex to each bone
+segment, `((nearest + softness) / (distance + softness))^4`, with the nearest four kept and normalised. Bone heat diffusion
+or a geodesic falloff would be smoother where two limbs pass close, but needs a sparse solve per bone; this method depends only on
+position, so vertices split at a hard edge get identical weights and seams never open. A vertex farther than `maxDistance`
+(default a quarter of the rig's size) from every bone still binds to its nearest bones and is reported as unweighted.
+`scene_inspect` returns `rig` per armature with `skinned` (vertices and `unweightedVertices` per node), `bonesWithNoVertices`
+and `jointAxisProblems` (`zero-length`, `straight-chain`, `knee-bends-backward`, `elbow-bends-forward`).
+
+`scene_export_glb` writes the bones at rest, the skins and a clip named `motion` baked at 30 frames a second from tracks and
+IK (bone nodes only). In code, `scene.rigExport()` returns the `nodes` and `clips` options for `exportGlb`. Skinned parts render and export their
+bone-driven shape; the node transform of a skinned mesh does not move it, move the armature instead. The `rigged-walker`
+task in `bench/agent-modeling` builds and walks a character this way.
+
## Internal sampling helpers
`normalizeAgentMotion(input, recipe)` returns canonical plain JSON, or `null` for absent motion.
diff --git a/docs/parity.md b/docs/parity.md
index 7c80bc69..bd6abf1d 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -88,7 +88,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Generate > Volume to Mesh Modifier | missing | No volume objects. | | |
| Modeling > Modifiers > Generate > Weld Modifier | partial | `merge_by_distance` is an edit. It is not a stack node. | | #42 |
| Modeling > Modifiers > Generate > Wireframe Modifier | missing | No equivalent. | | #42 |
-| Modeling > Modifiers > Deform > Armature Modifier | partial | GPU skinning for imported rigs. Recipes can not bind a mesh. | [skinning](../tests/skinning.test.js) | #46 |
+| Modeling > Modifiers > Deform > Armature Modifier | partial | A node `skin` binds a recipe mesh to an armature with automatic weights, and imported rigs keep GPU skinning. No envelope mode and no hand-edited weights. | [rigging](../tests/rigging.test.js), [skinning](../tests/skinning.test.js) | #46 |
| Modeling > Modifiers > Deform > Cast Modifier | missing | No equivalent. | | #42 |
| Modeling > Modifiers > Deform > Curve Modifier | missing | No equivalent. | | #42 |
| Modeling > Modifiers > Deform > Displace Modifier | done | `displace` edit and stack node with a field as the texture, along the normal or an axis, with strength, midlevel and a face selection. Positions match Blender with a constant and with a Blend texture. | [src/mesh-field-edits.js](../src/mesh-field-edits.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #43 |
@@ -126,15 +126,15 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Sculpting & Painting > Sculpting | partial | Inflate, displace and smooth strokes in code. Recipes can not reach them, and there is no remesh during a stroke. | [sculpt](../tests/sculpt.test.js) | #47 |
| Sculpting & Painting > Texture Paint | missing | No painting into textures. | | |
| Sculpting & Painting > Vertex Paint | partial | Imported vertex colors render. Recipes can not author them. | | |
-| Sculpting & Painting > Weight Paint | missing | No vertex groups in recipes. Automatic weights replace painting by hand. | | #46 |
+| Sculpting & Painting > Weight Paint | partial | Automatic weights replace painting by hand. Skin weights are a mesh attribute, but there are no named vertex groups and no painting. | [rigging](../tests/rigging.test.js) | #46 |
| Sculpting & Painting > Curves Sculpting | missing | No hair curves. | | #63 |
| Grease Pencil | out of scope | Decided in issue #23. | | |
| Animation & Rigging > Animation Editors | out of scope | Interface for a mouse. | | |
| Animation & Rigging > Keyframes | partial | Linear, step, smooth and Hermite curves with deterministic seeks. There are no other easing types or keying sets. | [animation](../tests/animation.test.js) | |
-| Animation & Rigging > Armatures > Bones | missing | Recipes can not author bones. | | #46 |
-| Animation & Rigging > Armatures > Properties | missing | Recipes can not author armatures. | | #46 |
-| Animation & Rigging > Armatures > Structure | partial | Imported rigs keep their hierarchy. Recipes can not author one. | [gltf](../tests/gltf.test.js) | #46 |
-| Animation & Rigging > Armatures > Skinning | partial | Four-influence GPU skinning. There is no automatic binding. | [skinning](../tests/skinning.test.js) | #46 |
+| Animation & Rigging > Armatures > Bones | partial | Recipe `armatures` list bones with a name, parent, head and tail, and each bone is a recipe node that tracks and `motion.ik` address. No roll, bone shapes or custom properties. | [rigging](../tests/rigging.test.js) | #46 |
+| 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 > Lattice | missing | No lattice. | | #42 |
| Animation & Rigging > Constraints > Interface | out of scope | Interface for a mouse. | | |
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 98814e37..103ac2ed 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -210,7 +210,8 @@ function seekForExport(record, motionTime) {
// The scene's parts already carry the current pose, including IK and node overrides, so skinned parts export it as is.
function posedExport(record) {
- return { parts: record.scene.parts.map(withoutRoundoffShear), options: {} };
+ const rig = record.scene.rigExport?.() ?? { nodes: [], clips: [] };
+ return { parts: record.scene.parts.map(withoutRoundoffShear), options: rig.nodes.length ? rig : {} };
}
// Chains of bone transforms leave world matrices with Float32 roundoff that the exporter reads as shear. Real shear
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 367054d1..15a6ba15 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -20,7 +20,13 @@ const point2 = z.tuple([finite, finite]);
const detail = (minimum, maximum) => z.number().int().min(minimum).max(maximum).optional();
const segments = detail(3, 2048);
const ring = z.array(point2).min(3).max(4096);
+const skinSpec = z.strictObject({
+ armature: identifier.describe('ID of an entry in recipe armatures.'),
+ maxInfluences: z.number().int().min(1).max(4).optional().describe('Bones that move one vertex. Defaults to 4.'),
+ maxDistance: positive.optional().describe('Metres from the nearest bone beyond which a vertex counts as unweighted in scene_inspect rig. Defaults to a quarter of the rig size.'),
+}).describe('Bind this mesh node to an armature with automatic weights: each vertex follows its nearest bones, by distance to the bone segments. Needs the armature at rest where the mesh is.');
const nodeFields = {
+ skin: skinSpec.optional(),
label: z.string().max(256).optional().describe('Human-readable label. Identity remains the node ID.'),
parent: identifier.nullable().optional().describe('Parent node ID, or null for a root. Local transforms stay unchanged.'),
translation: vector3.optional().describe('Local XYZ translation.'),
@@ -39,7 +45,7 @@ const instanceSpec = z.strictObject({
alignToNormal: z.boolean().optional().describe('Surface only: tilt up to the surface normal.'),
scale: z.tuple([z.number().min(0.001).max(1000), z.number().min(0.001).max(1000)]).optional().describe('Random uniform scale range [min, max].'),
}).describe('Exactly one of grid, scatter or surface. Expands at scene_create into a group node plus one child node per point (<id>.0, <id>.1, ...) that share geometry and material and draw as one instanced batch. At most 2048 candidate points.');
-const nodeRecord = z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: instanceSpec.optional().describe('Repeat geometry and material at points; needs both ids. Only in the recipe given to scene_create, not in add-node.'), ...nodeFields });
+const nodeRecord = z.strictObject({ armature: identifier.optional().describe('Set on nodes an armature generates, and ignored on input. Edit bones through armatures.'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), instances: instanceSpec.optional().describe('Repeat geometry and material at points; needs both ids. Only in the recipe given to scene_create, not in add-node.'), ...nodeFields });
const materialPattern = z.strictObject({
type: z.enum(MATERIAL_PATTERN_TYPES).describe('Surface look. Directional types (wood, planks, metal) run along axis.'),
colors: z.array(color).min(2).max(3).optional().describe('Linear RGB colours to mix, darker first. Bricks take a third for the mortar. Each type has good defaults.'),
@@ -377,12 +383,32 @@ const physics = z.strictObject({
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, 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.');
+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.'),
+ head: vector3.describe('Rest position of the joint in armature space.'),
+ tail: vector3.optional().describe('Where the bone ends. Defaults to the mean of its children, so give it on leaf bones.'),
+});
+const armature = z.strictObject({
+ id: identifier,
+ parent: identifier.nullable().optional().describe('Node the armature hangs from.'),
+ translation: vector3.optional(), rotation: quaternion.optional(),
+ prefix: z.string().max(64).optional().describe('Prepended to each bone node ID, for a second character or a clash with another node.'),
+ preset: z.enum(['humanoid', 'quadruped']).optional().describe('Places bones from fit. A humanoid faces +Z with Y up; its knees sit slightly forward of the leg line and its elbows slightly behind, so poleless two-bone IK bends the right way. A quadruped lies along Z.'),
+ fit: z.strictObject({
+ node: identifier.optional().describe('A mesh node whose bounds size the preset.'),
+ bounds: z.strictObject({ min: vector3, max: vector3 }).optional().describe('Or explicit bounds in armature space.'),
+ landmarks: z.record(z.string(), vector3).optional().describe('Move a bone head by bone name, or its tail as <name>Tail, for arms held out or an odd shape.'),
+ }).optional(),
+ bones: z.array(boneRecord).min(1).max(128).optional().describe('Explicit bones, instead of a preset.'),
+}).describe('A skeleton. Each bone becomes a recipe node named after it (parented like the bones, rotating about its head), so motion tracks, motion.ik and set-node address bones by name. Mesh nodes bind with skin. scene_inspect rig lists unweighted vertices, bones with no vertices and joint axis problems.');
const recipe = z.strictObject({
format: z.literal('67js.scene'),
schemaVersion: z.literal(1),
geometries: z.array(geometry).max(256),
materials: z.array(z.strictObject({ id: identifier, tag: materialTag, ...materialFields })).max(256),
nodes: z.array(nodeRecord).max(4096),
+ armatures: z.array(armature).max(16).optional(),
camera: z.strictObject(cameraFields).optional(),
environment: environment.optional(),
effects: effects.optional(),
@@ -412,6 +438,7 @@ const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),
z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),
z.strictObject({ type: z.literal('set-motion'), motion: motion.nullable() }),
+ z.strictObject({ type: z.literal('set-armatures'), armatures: z.array(armature).max(16).nullable() }),
z.strictObject({ type: z.literal('set-physics'), physics: physics.nullable() }),
z.strictObject({ type: z.literal('set-environment'), environment }),
z.strictObject({ type: z.literal('set-effects'), effects }),
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 8cfd4ce6..56b3cdda 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -43,6 +43,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- 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`. See "Inverse kinematics" 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`.
- 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`.
- 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.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 5be08100..032d7176 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -31,7 +31,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-physics', 'edit-mesh', 'set-mesh-stack',
+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'edit-mesh', 'set-mesh-stack',
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
alphaModes: RECIPE_ALPHA_MODES,
@@ -45,6 +45,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
lightLinking: false,
proceduralMotion: true,
motionIk: Object.freeze(['two-bone', 'aim']),
+ // Authored rigs: armatures expand into bone nodes, and a node `skin` binds a mesh with automatic weights (four influences).
+ rigging: Object.freeze({ presets: Object.freeze(['humanoid', 'quadruped']), maxArmatures: 16, maxBones: 128, maxInfluences: 4, weights: 'bone-distance' }),
// Recipe physics: Rapier (an optional peer) bakes bodies on nodes offline; playback is a seek into the bake.
physics: Object.freeze({
bodyTypes: Object.freeze(['dynamic', 'fixed', 'kinematic']),
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 25d1500c..f8554d51 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -12,6 +12,7 @@ import { expandInstancedNodes } from './mesh-instances.js';
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
import { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';
+import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
export { needsMeshBooleans } from './agent-mesh.js';
@@ -22,7 +23,7 @@ export { loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader } from '.
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
-const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material'];
+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin'];
const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
@@ -279,6 +280,19 @@ function nodeFrom(value) {
identifier(value.geometry);
identifier(value.material);
}
+ if (value.skin !== undefined) {
+ if (value.geometry === undefined) {
+ throw new TypeError('Only mesh nodes can have a skin.');
+ }
+ knownKeys(value.skin, ['armature', 'maxInfluences', 'maxDistance'], 'skin');
+ identifier(value.skin.armature);
+ if (value.skin.maxInfluences !== undefined) {
+ integer(value.skin.maxInfluences, 1, 4, 'skin maxInfluences');
+ }
+ if (value.skin.maxDistance !== undefined && !(Number.isFinite(value.skin.maxDistance) && value.skin.maxDistance > 0)) {
+ throw new RangeError('skin maxDistance must be a positive number of metres.');
+ }
+ }
return result;
}
@@ -488,9 +502,49 @@ function boundsFor(geometry, matrix) {
return { min: minimum, max: maximum };
}
+// An armature's nodes come first and are regenerated from it each time, so edits go through armatures, not through bone nodes.
+function addArmatures(recipe, limits) {
+ if (!Object.hasOwn(recipe, 'armatures')) {
+ for (const node of recipe.nodes) {
+ if (node.skin) {
+ throw new RangeError(`Node ${node.id} has a skin but the recipe has no armatures.`);
+ }
+ }
+ return;
+ }
+ const userNodes = new Map(recipe.nodes.map(node => [node.id, node]));
+ const resolveBounds = (armature, nodeId) => {
+ const node = userNodes.get(nodeId);
+ if (!node?.geometry) {
+ throw new RangeError(`Armature ${armature.id} fit node ${JSON.stringify(String(nodeId).slice(0, 48))} must be a mesh node.`);
+ }
+ const definition = recipe.geometries.find(geometry => geometry.id === node.geometry);
+ const bounds = boundsFor(generateGeometry(definition, Math.min(limits.maxVertices, 1_000_000)), mat4.create());
+ const toArmature = mat4.invert(mat4.create(), restWorldMatrix(armature.id, userNodes, [armature]));
+ const toWorld = restWorldMatrix(node.id, userNodes);
+ return transformedBounds(bounds, mat4.multiply(mat4.create(), toArmature, toWorld));
+ };
+ recipe.armatures = normalizeArmatures(recipe.armatures, { resolveBounds });
+ const derived = recipe.armatures.flatMap(armatureNodes);
+ for (const node of derived) {
+ if (userNodes.has(node.id)) {
+ throw new RangeError(`Armature node ${node.id} collides with a node of the same ID. Give the armature a prefix.`);
+ }
+ }
+ if (new Set(derived.map(node => node.id)).size !== derived.length) {
+ throw new RangeError('Two armatures generate the same node ID. Give one a prefix.');
+ }
+ for (const node of recipe.nodes) {
+ if (node.skin && !recipe.armatures.some(armature => armature.id === node.skin.armature)) {
+ throw new RangeError(`Node ${node.id} skin names armature ${node.skin.armature}, which is not in armatures.`);
+ }
+ }
+ recipe.nodes = [...derived, ...recipe.nodes];
+}
+
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
- knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics'], 'recipe');
+ knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics'], 'recipe');
if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {
throw new RangeError('Expected 67js.scene schemaVersion 1.');
}
@@ -509,7 +563,7 @@ function normalizeRecipe(input, limits) {
if (distinctPatterns.size > MAX_MATERIAL_PATTERNS) {
throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse a pattern and tint it with color.`);
}
- recipe.nodes = expandInstancedNodes(recipe.nodes, {
+ recipe.nodes = expandInstancedNodes(withoutArmatureNodes(recipe.nodes), {
maxNodes: limits.maxNodes,
resolveSurface: id => {
const definition = recipe.geometries.find(geometry => geometry.id === id);
@@ -518,6 +572,7 @@ function normalizeRecipe(input, limits) {
},
});
recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);
+ addArmatures(recipe, limits);
recipe.camera = cameraFrom(recipe.camera);
const look = {};
for (const field of ['environment', 'effects', 'shadow']) {
@@ -631,6 +686,7 @@ function stagePose(stagedState, time) {
graph.update();
validateGraph(graph, stagedState.localBounds);
}
+ stageSkinPoses(stagedState.skinStages, graph);
const materialUpdates = [];
for (const material of stagedState.recipe.materials) {
const patch = sampled?.materials.get(material.id);
@@ -658,6 +714,7 @@ function publishPose(stagedState, pose) {
for (const update of pose.materialUpdates) {
update.holder.snapshot = update.snapshot;
}
+ publishSkinPoses(stagedState.skinStages);
stagedState.renderCamera = pose.camera;
stagedState.motionTime = pose.time;
}
@@ -704,6 +761,7 @@ export function createAgentScene(input, inputLimits = {}) {
let revision = 0;
let topologyRevision = 0;
let physicsBake = null;
+ const skinCache = new Map();
const checkpoints = new Map();
function ownedGeometryRecords() {
@@ -777,6 +835,7 @@ export function createAgentScene(input, inputLimits = {}) {
const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));
const localBounds = new Map([...geometryRecords.values()].map(record => [record.geometry, record.bounds]));
const graph = compile(recipe, geometries, localBounds, limits);
+ const skinBindings = bindSkins({ recipe, graph, geometryRecords, cache: skinCache });
const materialHandles = new Map();
for (const material of recipe.materials) {
const snapshot = immutableMaterial(material);
@@ -790,14 +849,16 @@ export function createAgentScene(input, inputLimits = {}) {
const activeParts = new Map(state?.parts.map(part => [part.name, part]) ?? []);
const preferredParts = new Map(preferred?.parts.map(part => [part.name, part]) ?? []);
const nextParts = recipe.nodes.filter(node => node.geometry !== undefined).map(node => {
- const geometry = geometries.get(node.geometry);
+ const binding = skinBindings.get(node.id);
+ const geometry = binding?.geometry ?? geometries.get(node.geometry);
const material = materialHandles.get(node.material).output;
const activePart = removedNodes.has(node.id) ? null : activeParts.get(node.id);
const existing = [activePart, preferredParts.get(node.id)]
- .find(part => part?.geometry === geometry && part.material === material);
+ .find(part => part?.geometry === geometry && part.material === material && part.skin === binding?.skin);
return existing ?? Object.freeze({
name: node.id, geometry, material,
matrix: new Float32Array(graph.getNode(node.id).worldMatrix),
+ ...(binding ? { skin: binding.skin } : {}),
});
});
retainedMatrices(nextParts);
@@ -810,6 +871,8 @@ export function createAgentScene(input, inputLimits = {}) {
stats: geometryStats(geometryRecords.values()),
};
stagedState.localBounds = localBounds;
+ stagedState.skinBindings = skinBindings;
+ stagedState.skinStages = createSkinStages(skinBindings);
stagedState.motionSampler = compileAgentMotion(recipe.motion ?? null, recipe);
stagedState.physicsSampler = stagePhysics(recipe, geometryRecords);
const animated = Boolean(stagedState.motionSampler || stagedState.physicsSampler);
@@ -892,6 +955,15 @@ export function createAgentScene(input, inputLimits = {}) {
exportRecipe() {
return structuredClone(state.recipe);
},
+ /** Bone nodes at rest and a clip baked from motion, as `exportGlb` options. Leaves the pose where it was. */
+ rigExport(options = {}) {
+ if (!state.recipe.armatures) {
+ return { nodes: [], clips: [] };
+ }
+ const exported = bakeRigExport(state.recipe, state.graph, state.motionSampler, options);
+ publishPose(state, stagePose(state, state.motionTime));
+ return exported;
+ },
apply(inputOperations, options = {}) {
expected(options);
if (!Array.isArray(inputOperations) || inputOperations.length === 0 || inputOperations.length > limits.maxOperations) {
@@ -910,6 +982,18 @@ export function createAgentScene(input, inputLimits = {}) {
candidate.motion = operation.motion;
continue;
}
+ if (operation.type === 'set-armatures') {
+ knownKeys(operation, ['type', 'armatures'], 'operation');
+ if (!Object.hasOwn(operation, 'armatures')) {
+ throw new TypeError('set-armatures requires armatures; use null to clear them.');
+ }
+ if (operation.armatures === null) {
+ delete candidate.armatures;
+ } else {
+ candidate.armatures = operation.armatures;
+ }
+ continue;
+ }
if (operation.type === 'set-physics') {
knownKeys(operation, ['type', 'physics'], 'operation');
if (!Object.hasOwn(operation, 'physics')) {
@@ -1077,6 +1161,7 @@ export function createAgentScene(input, inputLimits = {}) {
...(state.recipe.motion?.ik?.length ? { motionIk: 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.recipe.armatures ? { rig: rigReport(state.recipe, state.skinBindings) } : {}),
boundsSpace: 'authored-base-world',
counts: {
nodes: state.recipe.nodes.length, parts: state.parts.length,
diff --git a/src/rig-presets.js b/src/rig-presets.js
new file mode 100644
index 00000000..6c849184
--- /dev/null
+++ b/src/rig-presets.js
@@ -0,0 +1,87 @@
+// Rig presets place bones from a bounding box. Y is up and the character faces +Z, the recipe's forward axis.
+// Humanoid bone names are the canonical names of `HUMANOID_BONES`, so `retargetClip` maps an authored rig without overrides.
+
+export const RIG_PRESETS = Object.freeze(['humanoid', 'quadruped']);
+
+// Knees point forward and elbows point back at rest: a two-bone solver with no pole bends toward the way the middle joint
+// already sits off the line from root to end.
+const KNEE_BEND = 0.012;
+const ELBOW_BEND = -0.012;
+
+function boundsFrame(bounds) {
+ const size = bounds.max.map((value, axis) => value - bounds.min[axis]);
+ const center = bounds.max.map((value, axis) => (value + bounds.min[axis]) / 2);
+ return { size, center, floorY: bounds.min[1], minimumZ: bounds.min[2] };
+}
+
+function humanoidLayout(bounds) {
+ const { size, center, floorY } = boundsFrame(bounds);
+ const height = size[1];
+ const place = (x, y, z) => [center[0] + x * height, floorY + y * height, center[2] + z * height];
+ const bones = [
+ { name: 'hips', parent: null, head: place(0, 0.52, 0) },
+ { name: 'spine', parent: 'hips', head: place(0, 0.58, 0) },
+ { name: 'chest', parent: 'spine', head: place(0, 0.68, 0) },
+ { name: 'neck', parent: 'chest', head: place(0, 0.8, 0) },
+ { name: 'head', parent: 'neck', head: place(0, 0.86, 0), tail: place(0, 1, 0) },
+ ];
+ for (const [side, sign] of [['left', 1], ['right', -1]]) {
+ const name = bone => `${side}${bone}`;
+ bones.push(
+ { name: name('Shoulder'), parent: 'chest', head: place(sign * 0.03, 0.77, 0) },
+ { name: name('UpperArm'), parent: name('Shoulder'), head: place(sign * 0.1, 0.77, 0) },
+ { name: name('LowerArm'), parent: name('UpperArm'), head: place(sign * 0.12, 0.6, ELBOW_BEND) },
+ { name: name('Hand'), parent: name('LowerArm'), head: place(sign * 0.135, 0.45, 0), tail: place(sign * 0.145, 0.37, 0) },
+ { name: name('UpperLeg'), parent: 'hips', head: place(sign * 0.06, 0.5, 0) },
+ { name: name('LowerLeg'), parent: name('UpperLeg'), head: place(sign * 0.065, 0.28, KNEE_BEND) },
+ { name: name('Foot'), parent: name('LowerLeg'), head: place(sign * 0.065, 0.05, 0) },
+ { name: name('Toes'), parent: name('Foot'), head: place(sign * 0.065, 0.02, 0.07), tail: place(sign * 0.065, 0.02, 0.12) },
+ );
+ }
+ return bones;
+}
+
+function quadrupedLayout(bounds) {
+ const { size, center, floorY, minimumZ } = boundsFrame(bounds);
+ const [width, height, length] = size;
+ const place = (x, y, z) => [center[0] + x * width, floorY + y * height, minimumZ + z * length];
+ const bones = [
+ { name: 'hips', parent: null, head: place(0, 0.62, 0.25) },
+ { name: 'spine', parent: 'hips', head: place(0, 0.64, 0.45) },
+ { name: 'chest', parent: 'spine', head: place(0, 0.64, 0.65) },
+ { name: 'neck', parent: 'chest', head: place(0, 0.72, 0.78) },
+ { name: 'head', parent: 'neck', head: place(0, 0.85, 0.86), tail: place(0, 0.85, 1) },
+ { name: 'tail1', parent: 'hips', head: place(0, 0.64, 0.18) },
+ { name: 'tail2', parent: 'tail1', head: place(0, 0.6, 0.1) },
+ { name: 'tail3', parent: 'tail2', head: place(0, 0.55, 0.04), tail: place(0, 0.5, 0) },
+ ];
+ for (const [side, sign] of [['left', 1], ['right', -1]]) {
+ const legX = sign * 0.28;
+ bones.push(
+ { name: `${side}FrontUpperLeg`, parent: 'chest', head: place(legX, 0.6, 0.65) },
+ { name: `${side}FrontLowerLeg`, parent: `${side}FrontUpperLeg`, head: place(legX, 0.33, 0.65 + ELBOW_BEND) },
+ { name: `${side}FrontFoot`, parent: `${side}FrontLowerLeg`, head: place(legX, 0.1, 0.65), tail: place(legX, 0, 0.68) },
+ { name: `${side}HindUpperLeg`, parent: 'hips', head: place(legX, 0.6, 0.25) },
+ { name: `${side}HindLowerLeg`, parent: `${side}HindUpperLeg`, head: place(legX, 0.33, 0.25 + KNEE_BEND * 4) },
+ { name: `${side}HindFoot`, parent: `${side}HindLowerLeg`, head: place(legX, 0.1, 0.25), tail: place(legX, 0, 0.28) },
+ );
+ }
+ return bones;
+}
+
+const LAYOUTS = { humanoid: humanoidLayout, quadruped: quadrupedLayout };
+
+/** Bones for a preset fitted to `bounds` ({ min, max } in armature space). `landmarks` replace a bone's head by name, or its tail as `<name>Tail`. */
+export function presetBones(preset, bounds, landmarks = {}) {
+ if (!Object.hasOwn(LAYOUTS, preset)) throw new RangeError(`Armature preset must be one of ${RIG_PRESETS.join(', ')}.`);
+ const names = new Set();
+ const bones = LAYOUTS[preset](bounds).map(bone => {
+ names.add(bone.name);
+ return { ...bone, head: landmarks[bone.name] ?? bone.head, ...(bone.tail || landmarks[`${bone.name}Tail`] ? { tail: landmarks[`${bone.name}Tail`] ?? bone.tail } : {}) };
+ });
+ for (const landmark of Object.keys(landmarks)) {
+ const bone = landmark.endsWith('Tail') ? landmark.slice(0, -4) : landmark;
+ if (!names.has(bone)) throw new RangeError(`Landmark ${landmark} does not name a ${preset} bone. Bones: ${[...names].join(', ')}.`);
+ }
+ return bones;
+}
diff --git a/src/rig.js b/src/rig.js
new file mode 100644
index 00000000..5ede59e9
--- /dev/null
+++ b/src/rig.js
@@ -0,0 +1,462 @@
+import { mat4, vec3 } from 'gl-matrix';
+import { createAnimationClip } from './animation.js';
+import { createSkinPose, updateSkinPose } from './skinning.js';
+import { presetBones, RIG_PRESETS } from './rig-presets.js';
+
+// Authored rigs. An armature expands into plain recipe nodes (one per bone, parented like the bones), so keyframed bone
+// rotation and `motion.ik` run through the same code as for any node. A node with `skin` binds its mesh to those bones.
+//
+// Weight method: distance to each bone segment with an inverse-power falloff, the nearest four bones kept. It depends only
+// on a vertex's position, so the split vertices of a hard edge get identical weights and seams never open. Bone heat
+// diffusion would need a sparse solve per bone, and a geodesic falloff would cost a mesh graph walk, for a result that
+// differs only where two limbs pass close to each other; the unweighted-vertex and unused-bone diagnostics cover the rest.
+
+export const MAX_ARMATURES = 16;
+export const MAX_BONES = 128;
+const MAX_INFLUENCES = 4;
+const FALLOFF_POWER = 4;
+const SOFTNESS_OF_SPAN = 0.02;
+const DEFAULT_REACH_OF_SPAN = 0.25;
+const STRAIGHT_CHAIN_RATIO = 0.002;
+const ZERO_LENGTH = 1e-6;
+const MAX_ANCESTOR_DEPTH = 256;
+const FORWARD = [0, 0, 1];
+
+function plainObject(value, label) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${label} must be an object.`);
+}
+
+function allowKeys(value, allowed, label) {
+ plainObject(value, label);
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key)) throw new TypeError(`${label} has an unsupported field: ${JSON.stringify(key.slice(0, 48))}.`);
+ }
+}
+
+function checkedName(value, label) {
+ if (typeof value !== 'string' || !value.trim() || value.length > 64) throw new TypeError(`${label} must be a name of 1 to 64 characters.`);
+ return value;
+}
+
+function checkedVector(value, size, label) {
+ if (!Array.isArray(value) || value.length !== size || value.some(component => !Number.isFinite(component))) {
+ throw new TypeError(`${label} must be an array of ${size} finite numbers.`);
+ }
+ return value.slice();
+}
+
+function checkedBounds(value, label) {
+ allowKeys(value, ['min', 'max'], label);
+ const bounds = { min: checkedVector(value.min, 3, `${label} min`), max: checkedVector(value.max, 3, `${label} max`) };
+ if (bounds.max.some((component, axis) => component <= bounds.min[axis])) throw new RangeError(`${label} must have max above min on every axis.`);
+ return bounds;
+}
+
+function orderBones(bones, armatureId) {
+ const byName = new Map(bones.map(bone => [bone.name, bone]));
+ const ordered = [];
+ const state = new Map();
+ function visit(bone) {
+ if (state.get(bone.name) === 2) return;
+ if (state.get(bone.name) === 1) throw new RangeError(`Armature ${armatureId} bones form a cycle at ${bone.name}.`);
+ state.set(bone.name, 1);
+ if (bone.parent !== null) visit(byName.get(bone.parent));
+ state.set(bone.name, 2);
+ ordered.push(bone);
+ }
+ bones.forEach(visit);
+ return ordered;
+}
+
+function normalizeBones(input, armatureId) {
+ if (!Array.isArray(input) || input.length < 1 || input.length > MAX_BONES) throw new RangeError(`Armature ${armatureId} needs 1 to ${MAX_BONES} bones.`);
+ const names = new Set();
+ const bones = input.map((value, position) => {
+ const label = `Armature ${armatureId} bone ${position}`;
+ allowKeys(value, ['name', 'parent', 'head', 'tail'], label);
+ const name = checkedName(value.name, `${label} name`);
+ if (names.has(name)) throw new RangeError(`Armature ${armatureId} repeats bone ${name}.`);
+ names.add(name);
+ const bone = { name, parent: value.parent === undefined || value.parent === null ? null : checkedName(value.parent, `${label} parent`), head: checkedVector(value.head, 3, `${label} head`) };
+ if (value.tail !== undefined) bone.tail = checkedVector(value.tail, 3, `${label} tail`);
+ return bone;
+ });
+ for (const bone of bones) {
+ if (bone.parent !== null && !names.has(bone.parent)) throw new RangeError(`Armature ${armatureId} bone ${bone.name} names an unknown parent ${bone.parent}.`);
+ }
+ return orderBones(bones, armatureId);
+}
+
+function fitBounds(armature, fit, resolveBounds) {
+ if (fit === undefined) throw new TypeError(`Armature ${armature.id} preset needs fit: { node } or fit: { bounds }.`);
+ allowKeys(fit, ['node', 'bounds', 'landmarks'], `Armature ${armature.id} fit`);
+ if ((fit.node === undefined) === (fit.bounds === undefined)) throw new TypeError(`Armature ${armature.id} fit takes node or bounds, not both.`);
+ return fit.bounds === undefined ? resolveBounds(armature, fit.node) : checkedBounds(fit.bounds, `Armature ${armature.id} fit bounds`);
+}
+
+function checkedLandmarks(value, armatureId) {
+ if (value === undefined) return {};
+ plainObject(value, `Armature ${armatureId} landmarks`);
+ return Object.fromEntries(Object.entries(value).map(([name, point]) => [name, checkedVector(point, 3, `Armature ${armatureId} landmark ${name}`)]));
+}
+
+/**
+ * Validate the recipe `armatures` list. Presets are resolved to explicit bones here, so a stored recipe never changes when
+ * the mesh does. `resolveBounds(armature, nodeId)` returns a node's bounds in the armature's own space.
+ */
+export function normalizeArmatures(input, { resolveBounds }) {
+ if (!Array.isArray(input) || input.length > MAX_ARMATURES) throw new RangeError(`armatures must be an array of at most ${MAX_ARMATURES}.`);
+ const ids = new Set();
+ return input.map(value => {
+ allowKeys(value, ['id', 'parent', 'translation', 'rotation', 'prefix', 'preset', 'fit', 'bones'], 'armature');
+ const id = checkedName(value.id, 'armature id');
+ if (ids.has(id)) throw new RangeError(`Duplicate armature ID: ${id}.`);
+ ids.add(id);
+ const rotation = checkedVector(value.rotation ?? [0, 0, 0, 1], 4, `Armature ${id} rotation`);
+ const length = Math.hypot(...rotation);
+ if (length === 0) throw new RangeError(`Armature ${id} rotation must be nonzero.`);
+ const armature = {
+ id, parent: value.parent === undefined || value.parent === null ? null : checkedName(value.parent, `Armature ${id} parent`),
+ translation: checkedVector(value.translation ?? [0, 0, 0], 3, `Armature ${id} translation`),
+ rotation: rotation.map(component => component / length),
+ prefix: value.prefix === undefined || value.prefix === '' ? '' : checkedName(value.prefix, `Armature ${id} prefix`),
+ };
+ if ((value.preset === undefined) === (value.bones === undefined)) throw new TypeError(`Armature ${id} needs preset or bones, not both.`);
+ if (value.preset === undefined) {
+ if (value.fit !== undefined) throw new TypeError(`Armature ${id} fit only applies to a preset.`);
+ return { ...armature, bones: normalizeBones(value.bones, id) };
+ }
+ if (!RIG_PRESETS.includes(value.preset)) throw new RangeError(`Armature ${id} preset must be one of ${RIG_PRESETS.join(', ')}.`);
+ const bounds = fitBounds(armature, value.fit, resolveBounds);
+ return { ...armature, bones: normalizeBones(presetBones(value.preset, bounds, checkedLandmarks(value.fit.landmarks, id)), id) };
+ });
+}
+
+/** Node ID of a bone. */
+export function boneNodeId(armature, boneName) {
+ return `${armature.prefix}${boneName}`;
+}
+
+/** The nodes an armature stands for: its root, then each bone parented to the bone before it, placed by head offsets. */
+export function armatureNodes(armature) {
+ const headByName = new Map(armature.bones.map(bone => [bone.name, bone.head]));
+ const rootNode = { id: armature.id, parent: armature.parent, translation: armature.translation, rotation: armature.rotation, scale: [1, 1, 1], armature: armature.id };
+ const boneNodes = armature.bones.map(bone => {
+ const parentHead = bone.parent === null ? [0, 0, 0] : headByName.get(bone.parent);
+ return {
+ id: boneNodeId(armature, bone.name), parent: bone.parent === null ? armature.id : boneNodeId(armature, bone.parent),
+ translation: bone.head.map((component, axis) => component - parentHead[axis]), rotation: [0, 0, 0, 1], scale: [1, 1, 1], armature: armature.id,
+ };
+ });
+ return [rootNode, ...boneNodes];
+}
+
+/** Drop the nodes armatures generated, so the armatures regenerate them. */
+export function withoutArmatureNodes(nodes) {
+ return Array.isArray(nodes) ? nodes.filter(node => !Object.hasOwn(node ?? {}, 'armature')) : nodes;
+}
+
+/** Where a bone ends: its tail, the mean of its children's heads, or its parent's direction continued half as far. */
+export function boneTails(armature) {
+ const children = new Map();
+ for (const bone of armature.bones) {
+ if (bone.parent !== null) children.set(bone.parent, [...(children.get(bone.parent) ?? []), bone]);
+ }
+ const headByName = new Map(armature.bones.map(bone => [bone.name, bone.head]));
+ return armature.bones.map(bone => {
+ if (bone.tail) return bone.tail;
+ const kids = children.get(bone.name);
+ if (kids) return [0, 1, 2].map(axis => kids.reduce((total, kid) => total + kid.head[axis], 0) / kids.length);
+ if (bone.parent !== null) return bone.head.map((component, axis) => component + (component - headByName.get(bone.parent)[axis]) * 0.5);
+ return [bone.head[0], bone.head[1] + 0.1, bone.head[2]];
+ });
+}
+
+/** World rest matrix of a node or armature root, from the recipe's own transforms. */
+export function restWorldMatrix(nodeId, nodesById, armatures = []) {
+ let matrix = mat4.create();
+ let currentId = nodeId;
+ for (let depth = 0; currentId !== null && currentId !== undefined; depth++) {
+ if (depth > MAX_ANCESTOR_DEPTH) throw new RangeError(`Node ${nodeId} has a parent chain that never ends.`);
+ const record = nodesById.get(currentId) ?? armatures.find(armature => armature.id === currentId);
+ if (!record) throw new RangeError(`Unknown node or armature ${JSON.stringify(String(currentId).slice(0, 48))} in a parent chain.`);
+ mat4.multiply(matrix, mat4.fromRotationTranslationScale(mat4.create(), record.rotation, record.translation, record.scale ?? [1, 1, 1]), matrix);
+ currentId = record.parent;
+ }
+ return matrix;
+}
+
+/** Bounds of a local box carried through `matrix`. */
+export function transformedBounds(bounds, matrix) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let corner = 0; corner < 8; corner++) {
+ const point = vec3.transformMat4(vec3.create(), [0, 1, 2].map(axis => (corner & (1 << axis) ? bounds.max[axis] : bounds.min[axis])), matrix);
+ point.forEach((component, axis) => {
+ minimum[axis] = Math.min(minimum[axis], component);
+ maximum[axis] = Math.max(maximum[axis], component);
+ });
+ }
+ return { min: minimum, max: maximum };
+}
+
+function squaredDistanceToSegment(px, py, pz, head, tail) {
+ const dx = tail[0] - head[0];
+ const dy = tail[1] - head[1];
+ const dz = tail[2] - head[2];
+ const lengthSquared = dx * dx + dy * dy + dz * dz;
+ const along = lengthSquared === 0 ? 0 : ((px - head[0]) * dx + (py - head[1]) * dy + (pz - head[2]) * dz) / lengthSquared;
+ const clamped = Math.min(1, Math.max(0, along));
+ const ex = px - (head[0] + dx * clamped);
+ const ey = py - (head[1] + dy * clamped);
+ const ez = pz - (head[2] + dz * clamped);
+ return ex * ex + ey * ey + ez * ez;
+}
+
+function strongestInfluences(weights, count) {
+ const chosen = [];
+ const taken = new Set();
+ for (let slot = 0; slot < count; slot++) {
+ let best = -1;
+ for (let bone = 0; bone < weights.length; bone++) {
+ if (!taken.has(bone) && (best < 0 || weights[bone] > weights[best])) best = bone;
+ }
+ if (best < 0 || weights[best] <= 0) break;
+ taken.add(best);
+ chosen.push(best);
+ }
+ return chosen;
+}
+
+/**
+ * Automatic weights. `segments` are bone { head, tail } in world space and `meshMatrix` carries positions there. A vertex
+ * farther than `maxDistance` from every bone still binds to its nearest ones (so it never collapses to the origin) and is
+ * counted as unweighted. Returns skin indices and weights (four per vertex), unweighted vertices and each bone's weight total.
+ */
+export function computeSkinWeights({ positions, meshMatrix, segments, maxInfluences = MAX_INFLUENCES, maxDistance, softness }) {
+ const vertexCount = positions.length / 3;
+ const indices = new Uint16Array(vertexCount * 4);
+ const weights = new Float32Array(vertexCount * 4);
+ const boneTotals = new Float64Array(segments.length);
+ const falloff = new Float64Array(segments.length);
+ const distances = new Float64Array(segments.length);
+ const point = vec3.create();
+ const unweighted = [];
+ for (let vertex = 0; vertex < vertexCount; vertex++) {
+ vec3.transformMat4(point, [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]], meshMatrix);
+ let nearest = Infinity;
+ segments.forEach((segment, bone) => {
+ distances[bone] = Math.sqrt(squaredDistanceToSegment(point[0], point[1], point[2], segment.head, segment.tail));
+ nearest = Math.min(nearest, distances[bone]);
+ });
+ if (nearest > maxDistance) unweighted.push(vertex);
+ for (let bone = 0; bone < segments.length; bone++) falloff[bone] = ((nearest + softness) / (distances[bone] + softness)) ** FALLOFF_POWER;
+ const chosen = strongestInfluences(falloff, maxInfluences);
+ const total = chosen.reduce((sum, bone) => sum + falloff[bone], 0);
+ chosen.forEach((bone, slot) => {
+ indices[vertex * 4 + slot] = bone;
+ weights[vertex * 4 + slot] = falloff[bone] / total;
+ boneTotals[bone] += falloff[bone] / total;
+ });
+ }
+ return { indices, weights, unweighted, boneTotals };
+}
+
+function skinOptions(skin, span) {
+ return {
+ maxInfluences: skin.maxInfluences ?? MAX_INFLUENCES,
+ maxDistance: skin.maxDistance ?? span * DEFAULT_REACH_OF_SPAN,
+ softness: span * SOFTNESS_OF_SPAN,
+ };
+}
+
+function worldSegments(armature, armatureWorld) {
+ const tails = boneTails(armature);
+ return armature.bones.map((bone, index) => ({
+ head: Array.from(vec3.transformMat4(vec3.create(), bone.head, armatureWorld)),
+ tail: Array.from(vec3.transformMat4(vec3.create(), tails[index], armatureWorld)),
+ }));
+}
+
+function armatureSpan(segments) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (const { head, tail } of segments) {
+ for (const point of [head, tail]) {
+ point.forEach((component, axis) => {
+ minimum[axis] = Math.min(minimum[axis], component);
+ maximum[axis] = Math.max(maximum[axis], component);
+ });
+ }
+ }
+ return Math.max(...maximum.map((component, axis) => component - minimum[axis]), 1e-6);
+}
+
+function createSkin(armature, boneWorlds, meshWorld) {
+ const count = armature.bones.length;
+ const skin = createSkinPose(count);
+ const inverseBindMatrices = new Float32Array(count * 16);
+ boneWorlds.forEach((world, index) => inverseBindMatrices.set(mat4.invert(mat4.create(), world), index * 16));
+ return Object.assign(skin, {
+ joints: armature.bones.map(bone => ({ name: boneNodeId(armature, bone.name), parent: bone.parent === null ? -1 : armature.bones.findIndex(candidate => candidate.name === bone.parent) })),
+ inverseBindMatrices, bindMatrix: Float32Array.from(meshWorld), jointWorldMatrices: new Float32Array(count * 16),
+ });
+}
+
+/**
+ * Bind every `skin` node of the rest `graph`. `cache` maps node ID to the last result, so an unchanged binding keeps the
+ * same geometry and skin objects. Returns { bindings: Map(nodeId -> { geometry, skin, armature, boneIds, report }) }.
+ */
+export function bindSkins({ recipe, graph, geometryRecords, cache }) {
+ const bindings = new Map();
+ for (const node of recipe.nodes.filter(candidate => candidate.skin)) {
+ const armature = recipe.armatures?.find(candidate => candidate.id === node.skin.armature);
+ if (!armature) throw new RangeError(`Node ${node.id} skin names armature ${node.skin.armature}, which is not in armatures.`);
+ const record = geometryRecords.get(node.geometry);
+ const meshWorld = graph.getNode(node.id).worldMatrix;
+ const boneIds = armature.bones.map(bone => boneNodeId(armature, bone.name));
+ const boneWorlds = boneIds.map(id => graph.getNode(id).worldMatrix);
+ const key = JSON.stringify([record.signature, armature, node.skin, Array.from(meshWorld), boneWorlds.map(world => Array.from(world))]);
+ const cached = cache.get(node.id);
+ if (cached?.key === key) {
+ bindings.set(node.id, cached);
+ continue;
+ }
+ const segments = worldSegments(armature, graph.getNode(armature.id).worldMatrix);
+ const span = armatureSpan(segments);
+ const weights = computeSkinWeights({ positions: record.geometry.positions, meshMatrix: meshWorld, segments, ...skinOptions(node.skin, span) });
+ const geometry = Object.freeze({ ...record.geometry, skinIndices: weights.indices, skinWeights: weights.weights });
+ const report = { node: node.id, armature: armature.id, vertices: record.geometry.positions.length / 3, unweightedVertices: weights.unweighted.length, boneWeight: weights.boneTotals };
+ const binding = { key, geometry, skin: createSkin(armature, boneWorlds, meshWorld), armature, boneIds, report };
+ cache.set(node.id, binding);
+ bindings.set(node.id, binding);
+ }
+ return bindings;
+}
+
+/** Palettes for a pose graph. Writes into `scratch` skins; `publish` copies them to the part skins once the whole pose is valid. */
+export function stageSkinPoses(skinned, graph) {
+ for (const { binding, scratch, jointWorlds, meshNodeId } of skinned) {
+ binding.boneIds.forEach((id, index) => jointWorlds.set(graph.getNode(id).worldMatrix, index * 16));
+ updateSkinPose(scratch, jointWorlds, binding.skin.inverseBindMatrices, graph.getNode(meshNodeId).worldMatrix, binding.skin.bindMatrix);
+ }
+}
+
+export function publishSkinPoses(skinned) {
+ for (const { binding, scratch, jointWorlds } of skinned) {
+ binding.skin.jointMatrices.set(scratch.jointMatrices);
+ binding.skin.jointWorldMatrices.set(jointWorlds);
+ }
+}
+
+export function createSkinStages(bindings) {
+ return [...bindings].map(([meshNodeId, binding]) => ({
+ meshNodeId, binding, scratch: createSkinPose(binding.boneIds.length), jointWorlds: new Float32Array(binding.boneIds.length * 16),
+ }));
+}
+
+function chainProblem(armature, tails, middleName, endName, bendsBackward) {
+ const byName = new Map(armature.bones.map((bone, index) => [bone.name, { bone, tail: tails[index] }]));
+ const middle = byName.get(middleName);
+ const end = byName.get(endName);
+ const root = byName.get(middle.bone.parent);
+ const rootToEnd = vec3.subtract(vec3.create(), end.bone.head, root.bone.head);
+ const rootToMiddle = vec3.subtract(vec3.create(), middle.bone.head, root.bone.head);
+ const length = vec3.length(rootToEnd);
+ if (length < ZERO_LENGTH) return null;
+ const alongLine = vec3.scale(vec3.create(), rootToEnd, vec3.dot(rootToMiddle, rootToEnd) / (length * length));
+ const offset = vec3.subtract(vec3.create(), rootToMiddle, alongLine);
+ if (vec3.length(offset) / length < STRAIGHT_CHAIN_RATIO) {
+ return { bone: middleName, problem: 'straight-chain', detail: `${root.bone.name}, ${middleName} and ${endName} are collinear at rest, so a two-bone solve has no bend direction unless it gets a pole.` };
+ }
+ const forward = vec3.dot(offset, FORWARD);
+ if (bendsBackward ? forward < 0 : forward > 0) {
+ return { bone: middleName, problem: bendsBackward ? 'knee-bends-backward' : 'elbow-bends-forward', detail: `${middleName} sits ${bendsBackward ? 'behind' : 'in front of'} the line from ${root.bone.name} to ${endName} on a character facing +Z, so a poleless solve folds the joint the wrong way.` };
+ }
+ return null;
+}
+
+/** Problems with a bone layout alone: zero-length bones and limb chains whose rest bend is missing or the wrong way. */
+export function armatureProblems(armature) {
+ const tails = boneTails(armature);
+ const problems = [];
+ armature.bones.forEach((bone, index) => {
+ if (vec3.distance(bone.head, tails[index]) < ZERO_LENGTH) problems.push({ bone: bone.name, problem: 'zero-length', detail: `${bone.name} has its tail at its head.` });
+ });
+ for (const bone of armature.bones) {
+ const child = armature.bones.find(candidate => candidate.parent === bone.name);
+ if (!child || bone.parent === null) continue;
+ const isKnee = /LowerLeg$/.test(bone.name) && !/Front/.test(bone.name);
+ const isElbow = /LowerArm$/.test(bone.name) || /FrontLowerLeg$/.test(bone.name);
+ if (!isKnee && !isElbow) continue;
+ const found = chainProblem(armature, tails, bone.name, child.name, isKnee);
+ if (found) problems.push(found);
+ }
+ return problems;
+}
+
+/** Everything `scene_inspect` says about rigs: layout problems, and per skinned node unweighted vertices and unused bones. */
+export function rigReport(recipe, bindings) {
+ return recipe.armatures.map(armature => {
+ const skinned = [...bindings.values()].filter(binding => binding.armature.id === armature.id);
+ const weightTotals = armature.bones.map((_, index) => skinned.reduce((sum, binding) => sum + binding.report.boneWeight[index], 0));
+ return {
+ id: armature.id, bones: armature.bones.length,
+ skinned: skinned.map(binding => ({ node: binding.report.node, vertices: binding.report.vertices, unweightedVertices: binding.report.unweightedVertices })),
+ bonesWithNoVertices: skinned.length ? armature.bones.filter((_, index) => weightTotals[index] < 1e-3).map(bone => bone.name) : [],
+ jointAxisProblems: armatureProblems(armature),
+ };
+ });
+}
+
+function bakedTracks(motionSampler, duration, frameRate) {
+ const frameCount = Math.max(1, Math.ceil(duration * frameRate));
+ const keyframesByTrack = new Map();
+ for (let frame = 0; frame <= frameCount; frame++) {
+ const time = Math.min(duration, frame / frameRate);
+ for (const [id, patch] of motionSampler.sample(time).nodes) {
+ for (const property of ['rotation', 'translation']) {
+ if (!patch[property]) continue;
+ const key = `${id}\u0000${property}`;
+ if (!keyframesByTrack.has(key)) keyframesByTrack.set(key, { target: id, property, interpolation: 'LINEAR', keyframes: [] });
+ keyframesByTrack.get(key).keyframes.push({ time, value: Array.from(patch[property]) });
+ }
+ }
+ }
+ return [...keyframesByTrack.values()];
+}
+
+/**
+ * What `exportGlb` needs for an authored rig: bone nodes at rest (the exporter writes their hierarchy and inverse binds)
+ * and, when the recipe has motion, one clip baked at `frameRate` from tracks and IK. Only bone nodes are baked.
+ */
+export function bakeRigExport(recipe, restGraph, motionSampler, { frameRate = 30 } = {}) {
+ const nodes = recipe.nodes.filter(node => Object.hasOwn(node, 'armature')).map(node => {
+ const isRoot = recipe.armatures.some(armature => armature.id === node.id);
+ const world = isRoot ? restGraph.getNode(node.id).worldMatrix : null;
+ return {
+ id: node.id, name: node.id, meshIds: [],
+ parent: isRoot ? null : node.parent,
+ translation: world ? Array.from(mat4.getTranslation(vec3.create(), world)) : node.translation,
+ rotation: world ? Array.from(mat4.getRotation([0, 0, 0, 1], world)) : node.rotation,
+ scale: world ? Array.from(mat4.getScaling(vec3.create(), world)) : node.scale,
+ };
+ });
+ const boneIds = new Set(nodes.map(node => node.id));
+ const tracks = motionSampler ? bakedTracks(motionSampler, recipe.motion.duration, frameRate).filter(track => boneIds.has(track.target)) : [];
+ const clip = tracks.length ? { ...createAnimationClip({ duration: recipe.motion.duration, loop: recipe.motion.loop, tracks }), name: 'motion' } : null;
+ return { nodes, clips: clip ? [clip] : [] };
+}
+
+/** A rig for `retargetClip` and `createSkeletonPose`: joints in bone order, named by node ID, resting with identity rotation. */
+export function createRigFromArmature(armature) {
+ const indexByName = new Map(armature.bones.map((bone, index) => [bone.name, index]));
+ const headByName = new Map(armature.bones.map(bone => [bone.name, bone.head]));
+ return {
+ joints: armature.bones.map(bone => ({
+ name: boneNodeId(armature, bone.name), parent: bone.parent === null ? -1 : indexByName.get(bone.parent),
+ translation: bone.head.map((component, axis) => component - (bone.parent === null ? 0 : headByName.get(bone.parent)[axis])),
+ rotation: [0, 0, 0, 1], scale: [1, 1, 1],
+ })),
+ };
+}
diff --git a/tests/rigging.test.js b/tests/rigging.test.js
new file mode 100644
index 00000000..4ff3e73b
--- /dev/null
+++ b/tests/rigging.test.js
@@ -0,0 +1,141 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+import { createAgentScene } from '../src/agent-scene.js';
+import { exportGlb } from '../src/export.js';
+import { mapHumanoidBones } from '../src/retarget.js';
+import { computeSkinWeights, createRigFromArmature, armatureProblems } from '../src/rig.js';
+import { gradeRecipe } from '../bench/agent-modeling/check.mjs';
+import { taskById } from '../bench/agent-modeling/tasks.mjs';
+import { walkerRecipe } from '../bench/agent-modeling/walker.mjs';
+
+const failedLabels = grade => grade.results.filter(result => !result.pass).map(result => result.label ?? result.kind);
+const task = taskById('rigged-walker');
+
+test('a rig with a missing leg bone, an unskinned arm or a backward elbow fails its own check', async () => {
+ const missingBone = walkerRecipe();
+ missingBone.armatures = [{ id: 'rig', bones: walkerRecipe().armatures.length ? [] : [] }];
+ const scene = createAgentScene(walkerRecipe());
+ const bones = scene.exportRecipe().armatures[0].bones.filter(bone => bone.name !== 'leftLowerLeg').map(bone => (bone.parent === 'leftLowerLeg' ? { ...bone, parent: 'leftUpperLeg' } : bone));
+ missingBone.armatures = [{ id: 'rig', bones }];
+ missingBone.motion.tracks = missingBone.motion.tracks.filter(track => track.id !== 'leftLowerLeg');
+ assert.ok(failedLabels(await gradeRecipe(task, missingBone)).includes('rigBones'));
+
+ const unskinnedArm = walkerRecipe();
+ delete unskinnedArm.nodes.find(node => node.id === 'left-upper-arm-mesh').skin;
+ assert.deepEqual(failedLabels(await gradeRecipe(task, unskinnedArm)), ['rigSkinned']);
+
+ const backwardElbow = walkerRecipe();
+ backwardElbow.armatures[0].fit.landmarks = { leftLowerArm: [0.216, 1.08, 0.04] };
+ assert.ok(failedLabels(await gradeRecipe(task, backwardElbow)).includes('walk cycle'));
+});
+
+test('the walker reference passes every check', async () => {
+ const grade = await gradeRecipe(task, walkerRecipe());
+ assert.equal(grade.pass, true, JSON.stringify(grade.results.filter(result => !result.pass)));
+});
+
+test('automatic weights give four influences that sum to one, and seams share weights', () => {
+ const scene = createAgentScene(walkerRecipe());
+ for (const part of scene.parts.filter(candidate => candidate.skin)) {
+ const { skinIndices, skinWeights, positions } = part.geometry;
+ const seen = new Map();
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ const total = skinWeights.slice(vertex * 4, vertex * 4 + 4).reduce((sum, weight) => sum + weight, 0);
+ assert.ok(Math.abs(total - 1) < 1e-5);
+ const key = Array.from(positions.subarray(vertex * 3, vertex * 3 + 3)).map(value => value.toFixed(5)).join(',');
+ const weights = `${Array.from(skinIndices.subarray(vertex * 4, vertex * 4 + 4))}|${Array.from(skinWeights.subarray(vertex * 4, vertex * 4 + 4))}`;
+ assert.equal(seen.get(key) ?? weights, weights);
+ seen.set(key, weights);
+ }
+ }
+});
+
+test('scene_inspect reports unweighted vertices, bones with no vertices and joint axis problems', () => {
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint' }],
+ armatures: [{ id: 'rig', bones: [
+ { name: 'root', parent: null, head: [0, 0, 0], tail: [0, 0.5, 0] },
+ { name: 'leftUpperLeg', parent: 'root', head: [0, 0.5, 0] },
+ { name: 'leftLowerLeg', parent: 'leftUpperLeg', head: [0, 0.25, 0] },
+ { name: 'leftFoot', parent: 'leftLowerLeg', head: [0, 0, 0], tail: [0, 0, 0] },
+ { name: 'antenna', parent: 'root', head: [0, 9, 0], tail: [0, 9.5, 0] },
+ ] }],
+ nodes: [{ id: 'block', geometry: 'block', material: 'paint', scale: [0.2, 0.2, 0.2], translation: [0, 0.4, 0], skin: { armature: 'rig', maxDistance: 0.05 } }],
+ };
+ const report = createAgentScene(recipe).inspect({}).rig[0];
+ assert.ok(report.skinned[0].unweightedVertices > 0);
+ assert.ok(report.bonesWithNoVertices.includes('antenna'));
+ const problems = report.jointAxisProblems.map(problem => `${problem.bone}:${problem.problem}`);
+ assert.ok(problems.includes('leftFoot:zero-length'));
+ assert.ok(problems.includes('leftLowerLeg:straight-chain'));
+});
+
+test('a straight-legged humanoid and a backward knee are both flagged', () => {
+ const rig = createAgentScene(walkerRecipe()).exportRecipe().armatures[0];
+ assert.deepEqual(armatureProblems(rig), []);
+ const backward = structuredClone(rig);
+ backward.bones.find(bone => bone.name === 'leftLowerLeg').head[2] = -0.05;
+ assert.deepEqual(armatureProblems(backward).map(problem => problem.problem), ['knee-bends-backward']);
+});
+
+test('armature bones are recipe nodes, and an exported recipe loads back unchanged', () => {
+ const scene = createAgentScene(walkerRecipe());
+ const recipe = scene.exportRecipe();
+ assert.ok(recipe.nodes.some(node => node.id === 'leftLowerLeg' && node.armature === 'rig'));
+ const reloaded = createAgentScene(recipe).exportRecipe();
+ assert.equal(reloaded.nodes.length, recipe.nodes.length);
+ assert.deepEqual(reloaded.armatures, recipe.armatures);
+});
+
+test('a preset armature maps to humanoid bones without overrides', () => {
+ const rig = createRigFromArmature(createAgentScene(walkerRecipe()).exportRecipe().armatures[0]);
+ assert.deepEqual(mapHumanoidBones(rig.joints.map(joint => joint.name)).missing, []);
+});
+
+test('a quadruped preset fits the bounds of a mesh node', () => {
+ const scene = createAgentScene({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }], materials: [{ id: 'paint' }],
+ armatures: [{ id: 'dog', preset: 'quadruped', fit: { node: 'body' } }],
+ nodes: [{ id: 'body', geometry: 'block', material: 'paint', translation: [0, 0.4, 0], scale: [0.4, 0.8, 1.2], skin: { armature: 'dog' } }],
+ });
+ const bones = scene.exportRecipe().armatures[0].bones;
+ assert.equal(bones.length, 20);
+ assert.ok(bones.find(bone => bone.name === 'head').head[2] > bones.find(bone => bone.name === 'hips').head[2]);
+});
+
+test('weights depend on position only and unweighted vertices still bind to a bone', () => {
+ const identity = Float32Array.from([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
+ const result = computeSkinWeights({
+ positions: Float32Array.from([0, 5, 0]), meshMatrix: identity, maxInfluences: 4, maxDistance: 1, softness: 0.02,
+ segments: [{ head: [0, 0, 0], tail: [0, 1, 0] }, { head: [0, 1, 0], tail: [0, 2, 0] }],
+ });
+ assert.equal(result.unweighted.length, 1);
+ assert.ok(result.weights[0] > 0.5 && result.indices[0] === 1);
+});
+
+test('the walker exports to a GLB that three.js loads with its skeleton and walk clip', async () => {
+ const scene = createAgentScene(walkerRecipe());
+ const rig = scene.rigExport();
+ assert.equal(rig.clips.length, 1);
+ const binary = exportGlb(scene.parts, rig);
+ const gltf = await new GLTFLoader().parseAsync(binary, '');
+ const skinned = [];
+ gltf.scene.traverse(object => {
+ if (object.isSkinnedMesh) skinned.push(object);
+ });
+ assert.equal(skinned.length, 14);
+ assert.equal(skinned[0].skeleton.bones.length, 21);
+ assert.equal(gltf.animations.length, 1);
+ assert.ok(gltf.animations[0].tracks.length >= 8);
+});
+
+test('set-armatures replaces the rig and refuses to leave a skin without one', () => {
+ const scene = createAgentScene(walkerRecipe());
+ assert.throws(() => scene.apply([{ type: 'set-armatures', armatures: null }], { expectedRevision: scene.revision }), /skin/);
+ scene.apply([{ type: 'set-armatures', armatures: [{ id: 'rig', preset: 'humanoid', fit: { bounds: { min: [-0.3, 0, -0.1], max: [0.3, 2, 0.1] } } }] }], { expectedRevision: scene.revision });
+ assert.equal(scene.exportRecipe().armatures[0].bones.find(bone => bone.name === 'head').tail[1], 2);
+});