Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add IK to recipe motion

Nguyen Xuan An0eb5cbb7bc0f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1fd408d7..8f637e27 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Add `motion.ik` to procedural recipes: two-bone and aim solvers on node hierarchies, with fixed, keyframed or node-following targets, so agents can animate jointed models without writing quaternions; `scene_inspect` reports whether each solver reaches its target across the clip
- Add `67js/addons/skeleton-pose`: clip layers for skinned rigs with joint masks and additive blending, two-bone IK with poles and aim IK with angle limits and shared chains, all seekable, with joints named by rig name or humanoid bone
## 0.12.0
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index 66e6ce76..870fdd6f 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -34,6 +34,7 @@ own mesh report:
| soap | Rounding every edge (bevel) |
| crate-uv | The crate with even UVs |
| crate-wood | The crate with a wood material pattern, to see whether agents find `pattern` |
+| arm-reach | A jointed arm whose tip moves between two points, to see whether agents find `motion.ik` |
| dice | Rounded edges plus 21 recessed pips, in one piece (harder) |
| flange | A hollow pipe with flanges and 12 bolt holes, in one piece (harder) |
| chair | Many exact parts, with open gaps between back slats (harder) |
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index f074324a..809e0737 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -56,6 +56,19 @@ function checkOne(check, measures) {
const found = measures.patternTypes.filter(type => check.types.includes(type));
return { pass: found.length > 0, detail: measures.patternTypes.join(', ') || 'no material pattern' };
}
+ case 'nodeAt': {
+ const position = measures.nodePosition(check.node, check.time);
+ if (!position) return { pass: false, detail: `no drawn node ${check.node}` };
+ const distance = Math.hypot(...position.map((value, axis) => value - check.position[axis]));
+ return { pass: distance <= 0.01, detail: `${check.node} is ${round(distance)} m away at t=${check.time}` };
+ }
+ case 'nodeDistance': {
+ const from = measures.nodePosition(check.from, check.time);
+ const to = measures.nodePosition(check.to, check.time);
+ if (!from || !to) return { pass: false, detail: `no drawn node ${check.from} or ${check.to}` };
+ const distance = Math.hypot(...from.map((value, axis) => value - to[axis]));
+ return { pass: Math.abs(distance - check.distance) <= 0.01, detail: `${round(distance)} m apart at t=${check.time}` };
+ }
case 'tips':
return { pass: measures.tips === check.equals, detail: `${measures.tips} tips` };
case 'triangles':
@@ -73,7 +86,12 @@ function checkOne(check, measures) {
export function recipeFeatures(recipe) {
const geometries = recipe.geometries ?? [];
const operations = geometries.flatMap(geometry => [...(geometry.edits ?? []), ...(geometry.stack ?? [])].map(edit => edit.op));
- return { geometryTypes: [...new Set(geometries.map(geometry => geometry.type))], meshOperations: [...new Set(operations)] };
+ return {
+ geometryTypes: [...new Set(geometries.map(geometry => geometry.type))],
+ meshOperations: [...new Set(operations)],
+ motionIk: (recipe.motion?.ik ?? []).map(solver => solver.type),
+ motionTracks: recipe.motion?.tracks?.length ?? 0,
+ };
}
/** Grade a recipe: { pass, passed, total, results: [{ kind, label, pass, detail }] }. An invalid recipe fails every check. */
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 3b9e389b..61ade6e3 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -246,6 +246,11 @@ export async function measureRecipe(recipe) {
uv: { parts: uvParts, of: geometries.length, stretch: worstUvStretch },
tips: countTips(geometries, bounds),
section: (axis, at) => sectionLoops(geometries, axis, at),
+ nodePosition(name, time) {
+ scene.sampleMotion(time);
+ const part = scene.parts.find(candidate => candidate.name === name);
+ return part ? [part.matrix[12], part.matrix[13], part.matrix[14]] : null;
+ },
lineHits: (axis, point) => lineHits(geometries, axis, point),
};
}
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index b7763a0e..96ee74b3 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -104,6 +104,23 @@ function boltHoleEdits() {
}
export const REFERENCES = {
+ 'arm-reach': {
+ ...scene(
+ [{ id: 'ball', type: 'sphere', segments: 16, rings: 8 }],
+ [
+ { id: 'shoulder', geometry: 'ball', translation: [0, 1, 0], scale: [0.03, 0.03, 0.03] },
+ { id: 'elbow', geometry: 'ball', parent: 'shoulder', translation: [0.5 / 0.03, 0, 0] },
+ { id: 'tip', geometry: 'ball', parent: 'elbow', translation: [0.4 / 0.03, 0, 0] },
+ ],
+ ),
+ motion: {
+ duration: 2, tracks: [],
+ ik: [{
+ type: 'two-bone', root: 'shoulder', middle: 'elbow', end: 'tip', pole: [0, 3, 0],
+ target: { keyframes: [{ time: 0, value: [0.4, 1.5, 0.3] }, { time: 2, value: [0.2, 1.2, -0.5] }] },
+ }],
+ },
+ },
dice: scene(
[{ id: 'die', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: dieEdits() }],
[{ id: 'die', geometry: 'die', translation: [0, 0.05, 0], scale: [0.1, 0.1, 0.1] }],
diff --git a/bench/agent-modeling/results/2026-10-30-13-37-sonnet-ik-cold.json b/bench/agent-modeling/results/2026-10-30-13-37-sonnet-ik-cold.json
new file mode 100644
index 00000000..03538b4b
--- /dev/null
+++ b/bench/agent-modeling/results/2026-10-30-13-37-sonnet-ik-cold.json
@@ -0,0 +1,44 @@
+{
+ "run": "2026-10-30-13-37-sonnet-ik-cold",
+ "model": "claude-sonnet-5-5",
+ "date": "2026-10-30T13:38:36.155Z",
+ "skill": false,
+ "passed": 1,
+ "tasks": 1,
+ "toolCalls": 2,
+ "costUsd": 0.45,
+ "records": [
+ {
+ "task": "arm-reach",
+ "pass": true,
+ "passed": 5,
+ "total": 5,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 2,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "lathe"
+ ],
+ "meshOperations": [],
+ "motionIk": [
+ "two-bone"
+ ],
+ "motionTracks": 0
+ },
+ "turns": 4,
+ "costUsd": 0.45418630000000004,
+ "inputTokens": 382721,
+ "outputTokens": 2157,
+ "wallSeconds": 40,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index 7dad6ac7..216ee424 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -216,6 +216,21 @@ heights 0.6 m, 0.7 m and 0.8 m.`,
{ kind: 'volume', min: 9.4e-3, max: 1.28e-2 },
],
},
+ {
+ id: 'arm-reach',
+ prompt: `A two-segment robot arm that reaches between two points. Use three nodes with these exact IDs, each with a
+small visible geometry: shoulder at [0, 1, 0], elbow 0.5 m from the shoulder, and tip 0.4 m from the elbow. Make elbow a child of
+shoulder and tip a child of elbow, so they stay connected. Add a 2 second motion in which the tip is exactly at
+[0.4, 1.5, 0.3] at time 0 and exactly at [0.2, 1.2, -0.5] at time 2, with the segments keeping their lengths throughout.
+For this task the object does not need to rest on the ground.`,
+ checks: [
+ { kind: 'nodeAt', node: 'tip', time: 0, position: [0.4, 1.5, 0.3] },
+ { kind: 'nodeAt', node: 'tip', time: 2, position: [0.2, 1.2, -0.5] },
+ { kind: 'nodeAt', node: 'shoulder', time: 1, position: [0, 1, 0] },
+ { kind: 'nodeDistance', from: 'shoulder', to: 'elbow', time: 1, distance: 0.5 },
+ { kind: 'nodeDistance', from: 'elbow', to: 'tip', time: 1, distance: 0.4 },
+ ],
+ },
];
export function taskById(id) {
diff --git a/docs/agent-character-motion.md b/docs/agent-character-motion.md
index 23c3369d..62944fe6 100644
--- a/docs/agent-character-motion.md
+++ b/docs/agent-character-motion.md
@@ -133,5 +133,5 @@ Candidate buffers belong to the decoder. Their contents expire at the next stagi
The asset must remain exclusively owned by its adapter while transactions are active.
This feature does not create a rig for a flat mesh collection.
-Agent recipes do not have IK, retargeting, facial morph authoring or topology changes. In code, [skeleton pose layers](skeleton-pose.md) add IK and [retargeting](retarget.md) moves clips between rigs.
+Imported asset recipes do not have IK, retargeting, facial morph authoring or topology changes. Procedural recipes have [`motion.ik`](agent-motion.md#inverse-kinematics). In code, [skeleton pose layers](skeleton-pose.md) add IK to skinned rigs and [retargeting](retarget.md) moves clips between rigs.
The current WALL·E asset has separate mesh roots and no skeleton. It supports rigid part movement through source-node tracks.
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index 659490de..314e3509 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -78,6 +78,40 @@ Quaternion values normalize through the existing animation core.
Quaternion tangents retain their authored values.
Other interpolation modes reject tangents.
+## Inverse kinematics
+
+`motion.ik` computes node rotations from a goal, so a recipe can say where a hand should be without any quaternions. It
+works on procedural recipes, and runs after the tracks at every sample, in list order. `tracks` can be empty when a
+motion has `ik`.
+
+```json
+{ "duration": 2, "tracks": [], "ik": [
+ { "type": "two-bone", "root": "shoulder", "middle": "elbow", "end": "wrist", "target": { "node": "ball" }, "pole": [0, 3, -1] },
+ { "type": "aim", "joint": "lamp", "target": { "node": "ball" }, "maxAngle": 120 }
+] }
+```
+
+A `two-bone` solver takes `root`, `middle` and `end` node IDs, each a descendant of the one before. `pole` is the world
+point the middle node bends toward; give one, because a straight limb has no bend direction of its own. `keepEndRotation`
+defaults to `true`, so a gripper or foot keeps its world rotation.
+
+An `aim` solver takes `joint`, or `joints` from the base of a chain to the aiming node, which then share the turn.
+`forward` is the aiming node's local axis (default `[0, 0, 1]`), and `maxAngle` limits the whole turn in degrees.
+
+`target` and `pole` are each `[x, y, z]` in world metres, `{ "node": id }` to follow a node, or
+`{ "keyframes": [{ "time", "value" }], "interpolation" }`. `weight` is 0 to 1 (default 1), or keyframes to fade a solve in
+or out. Keyframes count toward the motion's limit of 2048. A motion holds at most 16 solvers.
+
+A node with IK nodes below it needs uniform scale and no scale track, because a non-uniform parent would shear the chain.
+Put sizes on a child node with the geometry, or on the last node of the chain, whose own scale does not matter.
+
+`scene_inspect` returns `motionIk`, one `{ type, reached, worstError, atTime }` per solver, from 33 samples across the
+clip. `worstError` is metres for two-bone and radians for aim, so a target out of reach shows up without looking at every
+frame. A limb that cannot reach stretches toward the target.
+
+Imported assets reject `ik`, because their pose depends on the selected clip. In code, [skeleton pose layers](skeleton-pose.md)
+solve IK on skinned rigs. There are no joint angle limits.
+
## Internal sampling helpers
`normalizeAgentMotion(input, recipe)` returns canonical plain JSON, or `null` for absent motion.
diff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.md
index 235e88e7..4ef3fde9 100644
--- a/docs/skeleton-pose.md
+++ b/docs/skeleton-pose.md
@@ -93,7 +93,7 @@ two-bone and radians off target for aim.
- No joint angle limits. A pole keeps a knee on the right side, but nothing stops a target from bending it too far.
- No full-body solve: moving a hand does not move the hips. Solvers run one at a time, so order them from the base of the
body outward.
-- MCP recipes cannot use this yet. Agent tools still author joints by rotation tracks, as in
- [imported character motion](agent-character-motion.md).
+- Clip layers and masks are code only. Procedural recipes get IK through [`motion.ik`](agent-motion.md#inverse-kinematics);
+ imported assets through MCP still author joints by rotation tracks, as in [imported character motion](agent-character-motion.md).
- The [animation mixer](animation-mixer.md) works on rigid part transforms and has no layers, masks or IK. Use this addon
for skinned rigs.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index e2c2cdb9..cb0bb62b 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -196,8 +196,38 @@ function motionTrack(kind, property, value, tangent) {
})).min(1).max(64),
});
}
+const ikKeyframes = (value, description) => z.strictObject({
+ interpolation: z.enum(['LINEAR', 'STEP', 'SMOOTH']).optional(),
+ keyframes: z.array(z.strictObject({ time: z.number().min(0).max(30), value })).min(1).max(64),
+}).describe(description);
+const ikPoint = z.union([
+ vector3,
+ z.strictObject({ node: identifier }).describe('Follow this node\'s world position.'),
+ ikKeyframes(vector3, 'A moving world position.'),
+]);
+const ikWeight = z.union([unit, ikKeyframes(unit, 'Fade the solve in or out over time.')]).optional();
+const ikSolver = z.discriminatedUnion('type', [
+ z.strictObject({
+ type: z.literal('two-bone'),
+ root: identifier, middle: identifier, end: identifier,
+ target: ikPoint.describe('Where end should reach: [x, y, z] in world metres, {"node":id}, or keyframes.'),
+ pole: ikPoint.optional().describe('World point the middle joint bends toward. Give one, or a straight limb has no bend direction.'),
+ weight: ikWeight,
+ keepEndRotation: z.boolean().optional().describe('Default true: end keeps its world rotation, so a foot or gripper stays level.'),
+ }).describe('Limb of three nodes, each a descendant of the one before: shoulder, elbow, wrist. Computes their rotations, so you need no quaternions. Nodes with IK nodes below them must have uniform scale: put sizes on child mesh nodes.'),
+ z.strictObject({
+ type: z.literal('aim'),
+ joint: identifier.optional(),
+ joints: z.array(identifier).min(1).max(16).optional().describe('A chain from its base to the aiming node, sharing the turn.'),
+ forward: vector3.optional().describe('Local axis of the aiming node to point at the target. Defaults to [0, 0, 1].'),
+ target: ikPoint,
+ maxAngle: z.number().min(0.001).max(180).optional().describe('Limits the whole turn, in degrees.'),
+ weight: ikWeight,
+ }).describe('Point a node, such as a head, lamp or camera, at a target.'),
+]);
const motion = z.strictObject({
duration: z.number().min(0.1).max(30),
+ ik: z.array(ikSolver).max(16).optional().describe('Inverse kinematics run after the tracks, in order, on procedural recipes. scene_inspect reports motionIk: whether each solver reaches its target across the clip.'),
loop: z.boolean().optional(),
tracks: z.array(z.union([
motionTrack('node', 'translation', vector3, vector3),
@@ -212,7 +242,7 @@ const motion = z.strictObject({
motionTrack('camera', 'target', vector3, vector3),
motionTrack('camera', 'fov', finite.gt(0).lt(180), finite),
motionTrack('camera', 'roll', finite, finite),
- ])).min(1).max(128),
+ ])).max(128),
}).describe('One absolute-time procedural clip. Local node transforms propagate through parents. Cubic tangents are derivatives per second. Backend checks references, duplicate tracks, 2048 total keys and every sampled pose.');
const recipe = z.strictObject({
format: z.literal('67js.scene'),
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 9f858443..a2f5ccf6 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -38,7 +38,8 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.
- Polygon modeling by an agent (extrude, inset, loop cut, bevel, booleans, mirror, array, solidify) uses the recipe `mesh` geometry and the MCP tools `mesh_inspect`, `mesh_edit` and `mesh_stack`. Read [mesh-modeling.md](references/mesh-modeling.md) before the first edit; check that the checkout's `docs/mesh.md` exists, since it is unreleased after npm 0.10.0.
- 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`.
-- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. It is not available through MCP.
+- Layered skeletal animation in code (a clip on some joints only, additive clips, foot planting, reaching, looking at a point) uses `src/skeleton-pose.js` and the checkout's `docs/skeleton-pose.md`. Clip layers are not available through MCP.
+- Jointed recipe motion (an arm reaching, a lamp or head tracking a point) uses `motion.ik`, which needs no quaternions: parent the joint nodes, put sizes on child mesh nodes, and 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.
- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.
diff --git a/src/agent-asset.js b/src/agent-asset.js
index 0a039005..55c2cb68 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -424,6 +424,7 @@ export function createAgentAssetScene(asset, inputRecipe) {
return {
nodes: [...sourceNodes.values()].filter(node => node.editable),
materials: [...baselines.values()], camera: candidate.camera,
+ ikUnavailable: 'Motion ik works on procedural recipes, not imported assets, whose pose depends on the selected clip. Author node rotation tracks here.',
};
}
diff --git a/src/agent-motion.js b/src/agent-motion.js
index 811bc7f0..107dc969 100644
--- a/src/agent-motion.js
+++ b/src/agent-motion.js
@@ -1,5 +1,6 @@
import { createAnimationClip, compileAnimationSampler } from './animation.js';
import { createCameraPath } from './camera-path.js';
+import { createSkeletonPose } from './skeleton-pose.js';
const PROPERTIES = {
node: { translation: 3, rotation: 4, scale: 3 },
@@ -7,6 +8,8 @@ const PROPERTIES = {
camera: { eye: 3, target: 3, fov: 1, roll: 1 },
};
const INTERPOLATIONS = ['LINEAR', 'STEP', 'SMOOTH', 'CUBICSPLINE'];
+const MAX_IK_SOLVERS = 16;
+const IK_SWEEP_SAMPLES = 33;
const CAMERA_DEFAULTS = { eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 };
function knownKeys(value, fields, label) {
@@ -117,20 +120,179 @@ function normalizedKeyframe(keyframe, track, duration, interpolation) {
return result;
}
+function nodeIdFrom(value, nodes, label) {
+ if (typeof value !== 'string' || !nodes.has(value)) {
+ throw new RangeError(`${label} must be a node ID in this recipe; got ${JSON.stringify(value)}.`);
+ }
+ return value;
+}
+
+/** Keyframed IK channels share the motion's clip clock and keyframe budget. */
+function ikKeyframes(input, size, duration, label) {
+ knownKeys(input, ['keyframes', 'interpolation'], label);
+ const interpolation = input.interpolation ?? 'LINEAR';
+ if (!['LINEAR', 'STEP', 'SMOOTH'].includes(interpolation)) {
+ throw new RangeError(`${label} interpolation must be LINEAR, STEP or SMOOTH.`);
+ }
+ denseArray(input.keyframes, 64, `${label} keyframes`);
+ if (!input.keyframes.length) {
+ throw new RangeError(`${label} needs at least one keyframe.`);
+ }
+ const keyframes = input.keyframes.map(keyframe => {
+ knownKeys(keyframe, ['time', 'value'], `${label} keyframe`);
+ return { time: bounded(keyframe.time, 0, duration, 'Keyframe time'), value: valueFrom(keyframe.value, size, `${label} value`) };
+ });
+ return { interpolation, keyframes };
+}
+
+function ikPoint(input, nodes, duration, label) {
+ if (Array.isArray(input)) {
+ return valueFrom(input, 3, label);
+ }
+ if (input && Object.hasOwn(input, 'node')) {
+ knownKeys(input, ['node'], label);
+ return { node: nodeIdFrom(input.node, nodes, `${label} node`) };
+ }
+ if (input && Object.hasOwn(input, 'keyframes')) {
+ return ikKeyframes(input, 3, duration, label);
+ }
+ throw new TypeError(`${label} must be [x, y, z], { "node": id } or { "keyframes": [{ "time", "value" }] }.`);
+}
+
+function ikWeight(input, duration, label) {
+ if (input === undefined) {
+ return 1;
+ }
+ if (typeof input === 'number') {
+ return bounded(input, 0, 1, label);
+ }
+ const weight = ikKeyframes(input, 1, duration, label);
+ weight.keyframes.forEach(keyframe => bounded(keyframe.value, 0, 1, label));
+ return weight;
+}
+
+function normalizeIkSolver(input, position, nodes, duration) {
+ const label = `Motion ik ${position}`;
+ if (input?.type === 'two-bone') {
+ knownKeys(input, ['type', 'root', 'middle', 'end', 'target', 'pole', 'weight', 'keepEndRotation'], label);
+ const solver = {
+ type: 'two-bone',
+ root: nodeIdFrom(input.root, nodes, `${label} root`),
+ middle: nodeIdFrom(input.middle, nodes, `${label} middle`),
+ end: nodeIdFrom(input.end, nodes, `${label} end`),
+ target: ikPoint(input.target, nodes, duration, `${label} target`),
+ weight: ikWeight(input.weight, duration, `${label} weight`),
+ };
+ if (input.pole !== undefined) {
+ solver.pole = ikPoint(input.pole, nodes, duration, `${label} pole`);
+ }
+ if (input.keepEndRotation !== undefined) {
+ if (typeof input.keepEndRotation !== 'boolean') {
+ throw new TypeError(`${label} keepEndRotation must be boolean.`);
+ }
+ solver.keepEndRotation = input.keepEndRotation;
+ }
+ return solver;
+ }
+ if (input?.type === 'aim') {
+ knownKeys(input, ['type', 'joint', 'joints', 'forward', 'target', 'maxAngle', 'weight'], label);
+ if ((input.joint === undefined) === (input.joints === undefined)) {
+ throw new TypeError(`${label} needs joint, or joints listed from the base of the chain to the aiming node.`);
+ }
+ const names = input.joints === undefined ? [input.joint] : denseArray(input.joints, 16, `${label} joints`);
+ if (!names.length) {
+ throw new RangeError(`${label} joints cannot be empty.`);
+ }
+ const solver = {
+ type: 'aim',
+ joints: names.map(name => nodeIdFrom(name, nodes, `${label} joint`)),
+ forward: valueFrom(input.forward ?? [0, 0, 1], 3, `${label} forward`),
+ target: ikPoint(input.target, nodes, duration, `${label} target`),
+ weight: ikWeight(input.weight, duration, `${label} weight`),
+ };
+ if (input.maxAngle !== undefined) {
+ solver.maxAngle = bounded(input.maxAngle, 0.001, 180, `${label} maxAngle`);
+ }
+ return solver;
+ }
+ throw new RangeError(`${label} type must be two-bone or aim.`);
+}
+
+function solverNodes(solver) {
+ return solver.type === 'two-bone' ? [solver.root, solver.middle, solver.end] : solver.joints;
+}
+
+function pointNodes(solver) {
+ return [solver.target, solver.pole].filter(point => point?.node).map(point => point.node);
+}
+
+function ancestorsOf(id, nodesById) {
+ const found = [];
+ let current = nodesById.get(id)?.parent;
+ while (current !== undefined && current !== null) {
+ found.push(current);
+ current = nodesById.get(current)?.parent;
+ }
+ return found;
+}
+
+// The rig math assumes uniform scale. A non-uniform parent would shear what the solver thinks is a rigid chain. A node's
+// own scale only reaches its children, so the end of a chain or a lone aimed box can have any size.
+function checkIkScales(ik, tracks, recipe) {
+ const nodesById = new Map(recipe.nodes.map(node => [node.id, node]));
+ const scaledByTrack = new Set(tracks.filter(track => track.kind === 'node' && track.property === 'scale').map(track => track.id));
+ const uniformRequired = new Set();
+ for (const solver of ik) {
+ for (const id of [...solverNodes(solver), ...pointNodes(solver)]) {
+ ancestorsOf(id, nodesById).forEach(ancestor => uniformRequired.add(ancestor));
+ }
+ }
+ for (const id of uniformRequired) {
+ if (scaledByTrack.has(id)) {
+ throw new RangeError(`Motion ik: node ${id} has IK nodes below it, so it cannot have a scale track.`);
+ }
+ const scale = nodesById.get(id).scale ?? [1, 1, 1];
+ if (Math.max(...scale) - Math.min(...scale) > 1e-6 * Math.max(...scale)) {
+ throw new RangeError(`Motion ik: node ${id} has non-uniform scale ${JSON.stringify(scale)}. It has IK nodes below it, so keep it at uniform scale and put the size on a child node with the geometry.`);
+ }
+ }
+}
+
+function normalizeIk(input, recipe, tracks, duration) {
+ if (recipe.ikUnavailable) {
+ throw new RangeError(recipe.ikUnavailable);
+ }
+ denseArray(input, MAX_IK_SOLVERS, 'Motion ik');
+ const nodes = new Set(recipe.nodes.map(node => node.id));
+ const ik = input.map((solver, position) => normalizeIkSolver(solver, position, nodes, duration));
+ checkIkScales(ik, tracks, recipe);
+ return ik;
+}
+
+function ikKeyframeCount(ik) {
+ let count = 0;
+ for (const solver of ik) {
+ for (const channel of [solver.target, solver.pole, solver.weight]) {
+ count += channel?.keyframes?.length ?? 0;
+ }
+ }
+ return count;
+}
+
/** Normalize bounded authored data without storing bindings or sampled poses. */
export function normalizeAgentMotion(input, recipe) {
if (input === null || input === undefined) {
return null;
}
- knownKeys(input, ['duration', 'loop', 'tracks'], 'motion');
+ knownKeys(input, ['duration', 'loop', 'tracks', 'ik'], '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) {
- throw new RangeError('Motion needs at least one track. Use null to clear it.');
+ if (!input.tracks.length && !input.ik?.length) {
+ throw new RangeError('Motion needs at least one track or IK solver. 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));
@@ -184,7 +346,105 @@ export function normalizeAgentMotion(input, recipe) {
}
return result;
});
- return { duration, loop, tracks };
+ const result = { duration, loop, tracks };
+ if (input.ik !== undefined) {
+ result.ik = normalizeIk(input.ik, recipe, tracks, duration);
+ if (keyframeCount + ikKeyframeCount(result.ik) > 2048) {
+ throw new RangeError('Motion exceeds 2048 total keyframes.');
+ }
+ }
+ return result;
+}
+
+/** A rig of just the nodes IK needs: chains, the nodes their targets follow, and all their ancestors. */
+function ikRig(ik, recipe) {
+ const nodesById = new Map(recipe.nodes.map(node => [node.id, node]));
+ const needed = new Set();
+ for (const solver of ik) {
+ for (const id of [...solverNodes(solver), ...pointNodes(solver)]) {
+ needed.add(id);
+ ancestorsOf(id, nodesById).forEach(ancestor => needed.add(ancestor));
+ }
+ }
+ const members = recipe.nodes.filter(node => needed.has(node.id));
+ const indexById = new Map(members.map((node, index) => [node.id, index]));
+ return {
+ // Identifying joints by node ID alone keeps a node named like a humanoid bone from being mapped to another one.
+ mapping: {},
+ joints: members.map(node => ({
+ name: node.id,
+ parent: node.parent === undefined || node.parent === null ? -1 : indexById.get(node.parent),
+ translation: node.translation ?? [0, 0, 0],
+ rotation: node.rotation ?? [0, 0, 0, 1],
+ scale: node.scale ?? [1, 1, 1],
+ })),
+ };
+}
+
+function ikChannelClip(ik, duration, loop) {
+ const tracks = [];
+ ik.forEach((solver, position) => {
+ if (solver.target.keyframes) tracks.push({ target: `target ${position}`, property: 'translation', interpolation: solver.target.interpolation, keyframes: solver.target.keyframes });
+ if (solver.pole?.keyframes) tracks.push({ target: `pole ${position}`, property: 'translation', interpolation: solver.pole.interpolation, keyframes: solver.pole.keyframes });
+ if (solver.weight.keyframes) tracks.push({ target: `weight ${position}`, property: 'value', interpolation: solver.weight.interpolation, keyframes: solver.weight.keyframes });
+ });
+ return tracks.length ? createAnimationClip({ duration, loop, tracks }) : null;
+}
+
+/** Solve a motion's IK on top of its sampled node tracks. Returns staged rotations per node ID. */
+function createIkEvaluator(motion, recipe, stagedNodeTracks) {
+ const rig = ikRig(motion.ik, recipe);
+ const clip = ikChannelClip(motion.ik, motion.duration, motion.loop);
+ const channelSampler = clip ? compileAnimationSampler(clip) : null;
+ const channelOutput = name => channelSampler.tracks.find(track => track.target === name).output;
+ let pose = null;
+ const pointReader = (point, name) => {
+ if (Array.isArray(point)) return () => point;
+ if (point.node) return () => pose.jointWorld(point.node).position;
+ const output = channelOutput(name);
+ return () => output;
+ };
+ const definitions = motion.ik.map((solver, position) => {
+ const weightOutput = solver.weight.keyframes ? channelOutput(`weight ${position}`) : null;
+ const common = {
+ target: pointReader(solver.target, `target ${position}`),
+ weight: weightOutput ? () => Math.min(1, Math.max(0, weightOutput[0])) : solver.weight,
+ };
+ if (solver.type === 'aim') {
+ return { ...common, type: 'aim', joints: solver.joints, forward: solver.forward, maxAngle: solver.maxAngle };
+ }
+ return {
+ ...common, type: 'two-bone', root: solver.root, middle: solver.middle, end: solver.end,
+ ...(solver.pole ? { pole: pointReader(solver.pole, `pole ${position}`) } : {}),
+ keepEndRotation: solver.keepEndRotation,
+ };
+ });
+ pose = createSkeletonPose({ rig, ik: definitions });
+ const indexById = new Map(rig.joints.map((joint, index) => [joint.name, index]));
+ const baseBindings = rig.joints.map((joint, index) => ({ index, tracks: stagedNodeTracks.get(joint.name) }));
+ const solvedIds = new Set(motion.ik.flatMap(solver => {
+ if (solver.type === 'aim') return solver.joints;
+ return solver.keepEndRotation === false ? [solver.root, solver.middle] : [solver.root, solver.middle, solver.end];
+ }));
+ const staged = new Map([...solvedIds].map(id => [id, new Float64Array(4)]));
+ function setBase(localRotations, localTranslations) {
+ for (const { index, tracks } of baseBindings) {
+ if (tracks?.rotation) localRotations[index].set(tracks.rotation);
+ if (tracks?.translation) localTranslations[index].set(tracks.translation);
+ }
+ }
+ return {
+ staged,
+ solve(time) {
+ channelSampler?.sample(time);
+ pose.apply(time, setBase);
+ for (const [id, rotation] of staged) {
+ rotation.set(pose.localRotation(indexById.get(id)));
+ if (!rotation.every(Number.isFinite)) throw new RangeError(`Motion ik produced an invalid rotation for node ${id}.`);
+ }
+ return pose.ikResults;
+ },
+ };
}
function validateRadiance(material) {
@@ -230,6 +490,20 @@ export function compileAgentMotion(input, recipe) {
patch[track.property] = size === 1 ? 0 : new Float64Array(size);
return { track, patch, staged: sampler.tracks[index].output };
});
+ const stagedNodeTracks = new Map();
+ for (const { track, staged } of bindings) {
+ if (track.kind !== 'node') continue;
+ if (!stagedNodeTracks.has(track.id)) stagedNodeTracks.set(track.id, {});
+ stagedNodeTracks.get(track.id)[track.property] = staged;
+ }
+ const ikEvaluator = motion.ik?.length ? createIkEvaluator(motion, recipe, stagedNodeTracks) : null;
+ if (ikEvaluator) {
+ for (const id of ikEvaluator.staged.keys()) {
+ if (!output.nodes.has(id)) output.nodes.set(id, {});
+ const nodePatch = output.nodes.get(id);
+ if (!nodePatch.rotation) nodePatch.rotation = new Float64Array(4);
+ }
+ }
const baselines = new Map((recipe.materials ?? []).map(material => [material.id, structuredClone(material)]));
const cameraTracks = motion.tracks.filter(track => track.kind === 'camera');
const cameraInput = {
@@ -251,6 +525,24 @@ export function compileAgentMotion(input, recipe) {
}
const materialSamples = new Map([...output.materials.keys()].map(id => [id, { ...baselines.get(id) }]));
return Object.freeze({
+ /** How IK fares across the whole clip: one { type, reached, worstError, atTime } per solver. Moves the sampler. */
+ sweepIk() {
+ if (!ikEvaluator) return [];
+ const worst = motion.ik.map(solver => ({ type: solver.type, reached: true, worstError: 0, atTime: 0 }));
+ for (let sample = 0; sample < IK_SWEEP_SAMPLES; sample++) {
+ const time = motion.duration * sample / (IK_SWEEP_SAMPLES - 1);
+ sampler.sample(time);
+ ikEvaluator.solve(time).forEach((result, position) => {
+ const record = worst[position];
+ record.reached = record.reached && result.reached;
+ if (result.error > record.worstError) {
+ record.worstError = Number(result.error.toFixed(6));
+ record.atTime = Number(time.toFixed(3));
+ }
+ });
+ }
+ return worst;
+ },
sample(time) {
bounded(time, 0, 3600, 'Motion sample time');
sampler.sample(time);
@@ -274,7 +566,8 @@ export function compileAgentMotion(input, recipe) {
throw new RangeError('Sampled camera lens is invalid at Float32 precision.');
}
}
- // Publish only after every track, material product and camera pose passes.
+ ikEvaluator?.solve(time);
+ // Publish only after every track, material product, camera pose and IK solve passes.
for (const { track, patch, staged } of bindings) {
if (staged.length === 1) {
patch[track.property] = staged[0];
@@ -282,6 +575,9 @@ export function compileAgentMotion(input, recipe) {
patch[track.property].set(staged);
}
}
+ if (ikEvaluator) {
+ for (const [id, rotation] of ikEvaluator.staged) output.nodes.get(id).rotation.set(rotation);
+ }
if (cameraPath) {
for (const field of ['eye', 'target', 'up']) {
output.camera[field].set(stagedCamera[field]);
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index de5696ec..792fd683 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -31,5 +31,6 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
authoredLook: true, maxPointLights: 8,
proceduralMotion: true,
+ motionIk: Object.freeze(['two-bone', 'aim']),
motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),
});
diff --git a/src/agent-scene.js b/src/agent-scene.js
index f1fa6147..d767db71 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -1018,6 +1018,7 @@ export function createAgentScene(input, inputLimits = {}) {
const resident = geometryStats(ownedGeometryRecords());
return {
revision, topologyRevision,
+ ...(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,
boundsSpace: 'authored-base-world',
counts: {
diff --git a/src/skeleton-pose.js b/src/skeleton-pose.js
index 62e192ed..91cd5d06 100644
--- a/src/skeleton-pose.js
+++ b/src/skeleton-pose.js
@@ -329,13 +329,17 @@ export function createSkeletonPose({ skin, rig = skin && createRigFromSkin(skin)
}
return {
- /** Rebuild the pose for an absolute time in seconds. Returns the skin when there is one. */
- apply(time) {
+ /**
+ * Rebuild the pose for an absolute time in seconds. Returns the skin when there is one. `setBase`, if given, receives
+ * the local rotation and translation arrays (by rig joint index) to replace the rest pose before layers and IK.
+ */
+ apply(time, setBase) {
if (!Number.isFinite(time)) throw new RangeError('Pose time must be finite.');
for (let index = 0; index < jointCount; index++) {
localRotations[index].set(prepared.restRotations[index]);
localTranslations[index].set(prepared.restTranslations[index]);
}
+ setBase?.(localRotations, localTranslations);
for (const layer of compiledLayers) applyLayer(layer, time, localRotations, localTranslations);
context.update();
solvers.forEach((solver, position) => {
@@ -346,6 +350,10 @@ export function createSkeletonPose({ skin, rig = skin && createRigFromSkin(skin)
},
/** World position and rotation of a joint after the last apply. */
jointWorld,
+ /** Local rotation of a joint by rig index after the last apply. The array is reused by the next apply. */
+ localRotation(index) {
+ return localRotations[index];
+ },
/** One { reached, error } per IK solver from the last apply: metres for two-bone, radians for aim. */
get ikResults() {
return results;
diff --git a/tests/agent-motion-ik.test.js b/tests/agent-motion-ik.test.js
new file mode 100644
index 00000000..2b1efce1
--- /dev/null
+++ b/tests/agent-motion-ik.test.js
@@ -0,0 +1,188 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mat4, vec3 } from 'gl-matrix';
+import { createAgentScene } from '../src/agent-scene.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+
+const SEGMENT_MATERIALS = [{ id: 'paint', color: [0.6, 0.6, 0.6] }];
+
+/** A planar arm: shoulder at (0, 1, 0), 0.5 m to the elbow, 0.4 m to the tip, plus a ball and a head. */
+function armRecipe(motion, nodeOverrides = {}) {
+ const nodes = [
+ { id: 'base', translation: [0, 1, 0] },
+ { id: 'shoulder', parent: 'base' },
+ { id: 'upper-mesh', parent: 'shoulder', geometry: 'box', material: 'paint', translation: [0.25, 0, 0], scale: [0.5, 0.05, 0.05] },
+ { id: 'elbow', parent: 'shoulder', translation: [0.5, 0, 0] },
+ { id: 'lower-mesh', parent: 'elbow', geometry: 'box', material: 'paint', translation: [0.2, 0, 0], scale: [0.4, 0.04, 0.04] },
+ { id: 'tip', parent: 'elbow', translation: [0.4, 0, 0], geometry: 'box', material: 'paint', scale: [0.03, 0.03, 0.03] },
+ { id: 'ball', geometry: 'box', material: 'paint', translation: [0.3, 1.5, 0.3], scale: [0.05, 0.05, 0.05] },
+ { id: 'lamp', geometry: 'box', material: 'paint', translation: [-1, 1, 0], scale: [0.1, 0.1, 0.1] },
+ ].map(node => ({ ...node, ...nodeOverrides[node.id] }));
+ return { format: '67js.scene', schemaVersion: 1, geometries: [{ id: 'box', type: 'box', bevel: 0 }], materials: SEGMENT_MATERIALS, nodes, ...(motion ? { motion } : {}) };
+}
+
+function worldPosition(scene, name) {
+ const part = scene.parts.find(candidate => candidate.name === name);
+ return Array.from(mat4.getTranslation(new Float64Array(3), part.matrix));
+}
+
+function assertClose(actual, expected, tolerance = 1e-3, label = '') {
+ for (let index = 0; index < expected.length; index++) {
+ assert.ok(Math.abs(actual[index] - expected[index]) <= tolerance, `${label} ${JSON.stringify(actual)} vs ${JSON.stringify(expected)}`);
+ }
+}
+
+const armIk = (target, extra = {}) => ({ type: 'two-bone', root: 'shoulder', middle: 'elbow', end: 'tip', target, pole: [0, 3, 0], ...extra });
+
+test('a recipe arm reaches a fixed point with no rotation tracks, and bone lengths hold', () => {
+ const target = [0.4, 1.5, 0.3];
+ const scene = createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [armIk(target)] }));
+ scene.sampleMotion(0);
+ assertClose(worldPosition(scene, 'tip'), target);
+ const elbow = worldPosition(scene, 'lower-mesh');
+ const shoulder = worldPosition(scene, 'upper-mesh');
+ assert.ok(Math.abs(vec3.distance(shoulder, [0, 1, 0]) - 0.25) < 1e-3);
+ assert.ok(Math.abs(vec3.distance(elbow, worldPosition(scene, 'tip')) - 0.2) < 1e-3);
+});
+
+test('a keyframed target moves through time, and seeking back gives the same pose', () => {
+ const start = [0.4, 1.5, 0.3];
+ const end = [0.2, 1.2, -0.5];
+ const scene = createAgentScene(armRecipe({
+ duration: 2, tracks: [],
+ ik: [armIk({ keyframes: [{ time: 0, value: start }, { time: 2, value: end }] })],
+ }));
+ scene.sampleMotion(0);
+ assertClose(worldPosition(scene, 'tip'), start);
+ scene.sampleMotion(2);
+ assertClose(worldPosition(scene, 'tip'), end);
+ scene.sampleMotion(1);
+ const middle = worldPosition(scene, 'tip');
+ assertClose(middle, [0.3, 1.35, -0.1]);
+ scene.sampleMotion(2);
+ scene.sampleMotion(1);
+ assertClose(worldPosition(scene, 'tip'), middle, 1e-9);
+});
+
+test('a target can follow another node, including one moved by a track', () => {
+ const scene = createAgentScene(armRecipe({
+ duration: 2,
+ tracks: [{ kind: 'node', id: 'ball', property: 'translation', keyframes: [{ time: 0, value: [0.3, 1.5, 0.3] }, { time: 2, value: [0.5, 1.2, 0] }] }],
+ ik: [armIk({ node: 'ball' })],
+ }));
+ scene.sampleMotion(0);
+ assertClose(worldPosition(scene, 'tip'), [0.3, 1.5, 0.3]);
+ scene.sampleMotion(2);
+ assertClose(worldPosition(scene, 'tip'), [0.5, 1.2, 0]);
+});
+
+test('IK runs on top of tracks: a moving base carries the shoulder and the tip still reaches', () => {
+ const scene = createAgentScene(armRecipe({
+ duration: 1,
+ tracks: [{ kind: 'node', id: 'base', property: 'translation', keyframes: [{ time: 0, value: [0, 1, 0] }, { time: 1, value: [0.2, 1, 0] }] }],
+ ik: [armIk([0.5, 1.4, 0])],
+ }));
+ scene.sampleMotion(1);
+ assertClose(worldPosition(scene, 'tip'), [0.5, 1.4, 0]);
+ assertClose(worldPosition(scene, 'upper-mesh').slice(0, 1), [0.2], 0.3);
+});
+
+test('the pole picks the side the elbow bends to', () => {
+ const elbowZ = pole => {
+ const scene = createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [armIk([0.6, 1, 0], { pole })] }));
+ scene.sampleMotion(0);
+ return worldPosition(scene, 'lower-mesh')[2];
+ };
+ assert.ok(elbowZ([0.3, 1, 2]) > 0.05);
+ assert.ok(elbowZ([0.3, 1, -2]) < -0.05);
+});
+
+test('keyframed weight fades IK in, with tracks showing through', () => {
+ const scene = createAgentScene(armRecipe({
+ duration: 2, tracks: [],
+ ik: [armIk([0.4, 1.5, 0.3], { weight: { keyframes: [{ time: 0, value: 0 }, { time: 2, value: 1 }] } })],
+ }));
+ scene.sampleMotion(0);
+ assertClose(worldPosition(scene, 'tip'), [0.9, 1, 0]);
+ scene.sampleMotion(2);
+ assertClose(worldPosition(scene, 'tip'), [0.4, 1.5, 0.3]);
+});
+
+test('aim points a node at a target and honours maxAngle', () => {
+ const forwardOf = scene => {
+ const part = scene.parts.find(candidate => candidate.name === 'lamp');
+ const rotated = vec3.transformMat4(new Float64Array(3), [0, 0, 1], part.matrix);
+ return vec3.normalize(new Float64Array(3), vec3.subtract(new Float64Array(3), rotated, mat4.getTranslation(new Float64Array(3), part.matrix)));
+ };
+ const scene = createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [{ type: 'aim', joint: 'lamp', target: { node: 'ball' } }] }));
+ scene.sampleMotion(0);
+ const toBall = vec3.normalize(new Float64Array(3), [1.3, 0.5, 0.3]);
+ assertClose(Array.from(forwardOf(scene)), Array.from(toBall));
+ const limited = createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [{ type: 'aim', joint: 'lamp', target: [5, 1, 0], maxAngle: 20 }] }));
+ limited.sampleMotion(0);
+ assert.ok(Math.abs(vec3.angle(forwardOf(limited), [0, 0, 1]) - 20 * Math.PI / 180) < 1e-3);
+});
+
+test('scene_inspect reports where IK falls short across the clip', () => {
+ const reachable = createAgentScene(armRecipe({ duration: 2, tracks: [], ik: [armIk([0.4, 1.5, 0.3])] }));
+ assert.deepEqual(reachable.inspect().motionIk.map(result => [result.type, result.reached]), [['two-bone', true]]);
+ const tooFar = createAgentScene(armRecipe({
+ duration: 2, tracks: [],
+ ik: [armIk({ keyframes: [{ time: 0, value: [0.4, 1.5, 0.3] }, { time: 2, value: [5, 1, 0] }] })],
+ }));
+ const [result] = tooFar.inspect().motionIk;
+ assert.equal(result.reached, false);
+ assert.equal(result.atTime, 2);
+ assert.ok(Math.abs(result.worstError - 4.1) < 0.01, `${result.worstError}`);
+ assert.equal(createAgentScene(armRecipe()).inspect().motionIk, undefined);
+});
+
+test('inspecting does not disturb the sampled pose', () => {
+ const scene = createAgentScene(armRecipe({ duration: 2, tracks: [], ik: [armIk({ keyframes: [{ time: 0, value: [0.4, 1.5, 0.3] }, { time: 2, value: [0.2, 1.2, -0.5] }] })] }));
+ scene.sampleMotion(1);
+ const before = worldPosition(scene, 'tip');
+ scene.inspect();
+ assertClose(worldPosition(scene, 'tip'), before, 1e-12);
+});
+
+test('recipes export and reload with their ik', () => {
+ const scene = createAgentScene(armRecipe({ duration: 1, tracks: [], ik: [armIk([0.4, 1.5, 0.3])] }));
+ const exported = scene.exportRecipe();
+ assert.equal(exported.motion.ik[0].type, 'two-bone');
+ const reloaded = createAgentScene(exported);
+ reloaded.sampleMotion(0);
+ assertClose(worldPosition(reloaded, 'tip'), [0.4, 1.5, 0.3]);
+ const plain = createAgentScene(armRecipe({ duration: 1, tracks: [{ kind: 'node', id: 'ball', property: 'translation', keyframes: [{ time: 0, value: [0, 0, 0] }] }] }));
+ assert.equal(plain.exportRecipe().motion.ik, undefined);
+});
+
+test('mistakes say what to pass', () => {
+ const create = (ik, overrides) => createAgentScene(armRecipe({ duration: 1, tracks: [], ik }, overrides));
+ assert.throws(() => createAgentScene(armRecipe({ duration: 1, tracks: [] })), /at least one track or IK solver/);
+ assert.throws(() => create([{ type: 'fabrik', target: [0, 0, 0] }]), /type must be two-bone or aim/);
+ assert.throws(() => create([armIk([0, 0, 0], { root: 'nope' })]), /root must be a node ID/);
+ assert.throws(() => create([armIk({ node: 'nope' })]), /target node must be a node ID/);
+ assert.throws(() => create([armIk('here')]), /target must be \[x, y, z\]/);
+ assert.throws(() => create([armIk([0, 0, 0], { end: 'ball' })]), /end must descend from middle/);
+ assert.throws(() => create([armIk([0, 0, 0], { weight: 3 })]), /weight must be within/);
+ assert.throws(() => create([{ type: 'aim', target: [0, 0, 0] }]), /needs joint, or joints/);
+ assert.throws(() => create([armIk([0, 0, 0])], { elbow: { scale: [1, 2, 1] } }), /non-uniform scale.*child node/);
+ assert.doesNotThrow(() => create([armIk([0.4, 1.5, 0.3])], { tip: { scale: [0.1, 0.2, 0.3] } }));
+ assert.doesNotThrow(() => create([{ type: 'aim', joint: 'lamp', target: [0, 0, 0] }], { lamp: { scale: [0.2, 0.2, 0.3] } }));
+ assert.throws(() => createAgentScene(armRecipe({
+ duration: 1,
+ tracks: [{ kind: 'node', id: 'elbow', property: 'scale', keyframes: [{ time: 0, value: [1, 1, 1] }] }],
+ ik: [armIk([0, 0, 0])],
+ })), /cannot have a scale track/);
+ assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionIk], ['two-bone', 'aim']);
+});
+
+test('a node named like a humanoid bone is not mapped to another node', () => {
+ const recipe = armRecipe({ duration: 1, tracks: [], ik: [{ type: 'two-bone', root: 'hips', middle: 'elbow', end: 'tip', target: [0.4, 1.5, 0.3], pole: [0, 3, 0] }] }, { shoulder: { id: 'hips' } });
+ recipe.nodes.forEach(node => {
+ if (node.parent === 'shoulder') node.parent = 'hips';
+ });
+ const scene = createAgentScene(recipe);
+ scene.sampleMotion(0);
+ assertClose(worldPosition(scene, 'tip'), [0.4, 1.5, 0.3]);
+});