3D engine that AI agents drive
Add IK to imported assets and a character smoke
Nguyen Xuan Anebb53dfd488b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d93d290a..7d80ab5b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,10 @@# Changelog+## Unreleased++- Add `motion.ik` to imported assets: IK runs over the selected clip and overrides, moves every skin and rigid part, and takes `worldForward`, so agents can pose imported characters through MCP without writing quaternions+- Add `npm run smoke:character`, which takes a real CC0 character through the MCP server along the path an agent uses+## 0.13.1- Add `createAssetPose`, which poses a loaded glTF asset's whole hierarchy so every skin and rigid part moves, and `clipFromGltfAnimation`, which converts its clips for layers and `retargetClip`diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 376757f1..5b8a7479 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -31,6 +31,7 @@ Run these before you open a pull request:A renderer or shader change also needs a look at real pixels.Run `npm run smoke` or the `smoke:*` script for the area that you changed, and look at the screenshots that it saves under `artifacts/`.+A change to skinning, glTF loading, poses or IK also needs `npm run smoke:character`, which takes a real character through the MCP server. Run `npm run prepare:release` first.Screenshots and other output go to `artifacts/`, which Git ignores.Do not weaken a test to make it pass. If a test is flaky, find the cause and fix the test or the code.diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.mdindex 870fdd6f..8176a20e 100644--- a/bench/agent-modeling/README.md+++ b/bench/agent-modeling/README.md@@ -35,6 +35,7 @@ own mesh report:| 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` |+| robot-reach | The CC0 robot from `tests/fixtures`: IK over its Idle clip, found through the asset catalog and hierarchy || 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.mjsindex 809e0737..9f2bfa59 100644--- a/bench/agent-modeling/check.mjs+++ b/bench/agent-modeling/check.mjs@@ -1,7 +1,7 @@// Grades an exported recipe against a task's checks. CLI: node bench/agent-modeling/check.mjs <task-id> <recipe.json>import { readFile } from 'node:fs/promises';import { fileURLToPath } from 'node:url';-import { measureRecipe } from './measure.mjs';+import { measureAssetRecipe, measureRecipe } from './measure.mjs';import { taskById } from './tasks.mjs';const AXES = { x: 0, y: 1, z: 2 };@@ -69,6 +69,16 @@ function checkOne(check, measures) {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 'assetClip': {+ return { pass: measures.clipName === check.name, detail: `clip ${measures.clipName ?? 'none'}` };+ }+ case 'assetReach': {+ const solver = measures.reachSolvers.find(candidate => candidate.endLabel === check.endLabel);+ if (!solver) return { pass: false, detail: `no two-bone solver ending at ${check.endLabel}` };+ const close = (first, second) => first && Math.hypot(first[0] - second[0], first[1] - second[1], first[2] - second[2]) <= 0.02;+ 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 'tips':return { pass: measures.tips === check.equals, detail: `${measures.tips} tips` };case 'triangles':@@ -98,7 +108,7 @@ export function recipeFeatures(recipe) {export async function gradeRecipe(task, recipe) {let measures;try {- measures = await measureRecipe(recipe);+ measures = recipe.format === '67js.asset' ? await measureAssetRecipe(recipe) : await measureRecipe(recipe);} catch (error) {const results = task.checks.map(check => ({ kind: check.kind, label: check.label, pass: false, detail: `recipe failed: ${error.message}` }));return { pass: false, passed: 0, total: results.length, results };diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjsindex 61ade6e3..b428055f 100644--- a/bench/agent-modeling/measure.mjs+++ b/bench/agent-modeling/measure.mjs@@ -2,7 +2,10 @@// (genus), volume, cross-section loops, lines through the object, gear teeth and UV stretch. Shape measures use every// node's render triangles in world space. Lint, parts and genus come from the engine's own mesh report, the one the// agent sees: welding render triangles again can invent non-manifold edges that the polygon mesh does not have.+import { readFile } from 'node:fs/promises';+import { createAgentAssetScene } from '../../src/agent-asset.js';import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '../../src/agent-scene.js';+import { parseGltf } from '../../src/gltf.js';const WELD_DISTANCE = 1e-5;@@ -187,6 +190,29 @@ function lineHits(geometries, axis, point) {return hits;}+/** Reload an exported recipe for the fixture robot and read which clip and which IK solvers it ended with. */+export async function measureAssetRecipe(recipe) {+ const bytes = await readFile(new URL('../../tests/fixtures/RobotExpressive.glb', import.meta.url));+ const asset = await parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });+ const scene = createAgentAssetScene(asset, recipe);+ const labels = new Map(asset.nodes.map(node => [node.id, node.label]));+ const reports = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk ?? [];+ const solvers = recipe.motion?.ik ?? [];+ const endpoints = target => {+ if (Array.isArray(target)) return [target, target];+ const keyframes = target?.keyframes;+ return keyframes ? [keyframes[0].value, keyframes[keyframes.length - 1].value] : [null, null];+ };+ return {+ clipName: recipe.animation ? asset.animations[recipe.animation.clip]?.name : null,+ reachSolvers: solvers.filter(solver => solver.type === 'two-bone').map(solver => {+ const [firstTarget, lastTarget] = endpoints(solver.target);+ const report = reports[solvers.indexOf(solver)];+ return { endLabel: labels.get(solver.end), firstTarget, lastTarget, reached: report?.reached ?? false, worstError: report?.worstError ?? null };+ }),+ };+}+/** 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();diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjsindex 96ee74b3..f92f3ac8 100644--- a/bench/agent-modeling/references.mjs+++ b/bench/agent-modeling/references.mjs@@ -104,6 +104,17 @@ function boltHoleEdits() {}export const REFERENCES = {+ 'robot-reach': {+ format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),+ animation: { clip: 2, time: 0 },+ motion: {+ duration: 2, tracks: [],+ ik: [{+ type: 'two-bone', root: 'node-37', middle: 'node-39', end: 'node-40', keepEndRotation: false,+ target: { keyframes: [{ time: 0, value: [-1.3, 2.6, 0.8] }, { time: 2, value: [-1, 1.7, 1.1] }] },+ }],+ },+ },'arm-reach': {...scene([{ id: 'ball', type: 'sphere', segments: 16, rings: 8 }],diff --git a/bench/agent-modeling/results/2026-10-30-14-27-sonnet-asset-ik-cold.json b/bench/agent-modeling/results/2026-10-30-14-27-sonnet-asset-ik-cold.jsonnew file mode 100644index 00000000..6005a098--- /dev/null+++ b/bench/agent-modeling/results/2026-10-30-14-27-sonnet-asset-ik-cold.json@@ -0,0 +1,45 @@+{+ "run": "2026-10-30-14-27-sonnet-asset-ik-cold",+ "model": "claude-sonnet-5-5",+ "date": "2026-10-30T14:28:43.859Z",+ "skill": false,+ "passed": 1,+ "tasks": 1,+ "toolCalls": 7,+ "costUsd": 0.43,+ "records": [+ {+ "task": "robot-reach",+ "pass": true,+ "passed": 2,+ "total": 2,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 7,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_asset_catalog": 1,+ "scene_create_asset": 1,+ "scene_inspect": 3,+ "scene_apply": 1,+ "scene_export_recipe": 1+ },+ "features": {+ "geometryTypes": [],+ "meshOperations": [],+ "motionIk": [+ "two-bone"+ ],+ "motionTracks": 0+ },+ "turns": 9,+ "costUsd": 0.42946370000000006,+ "inputTokens": 707290,+ "outputTokens": 1926,+ "wallSeconds": 45,+ "exitCode": 0,+ "stopped": "success"+ }+ ]+}diff --git a/bench/agent-modeling/run.mjs b/bench/agent-modeling/run.mjsindex 8f07b431..122df7aa 100644--- a/bench/agent-modeling/run.mjs+++ b/bench/agent-modeling/run.mjs@@ -11,7 +11,7 @@// Raw transcripts and recipes go to artifacts/agent-modeling/<run>/ (ignored by Git); the summary goes to// bench/agent-modeling/results/<run>.json.import { spawn } from 'node:child_process';-import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { parseArgs } from 'node:util';@@ -47,10 +47,10 @@ async function skillPrompt() {return `${entryPoint}\n\n${meshReference}`;}-function mcpConfig() {+function mcpConfig(assetDirectory) {return { mcpServers: { [MCP_SERVER_NAME]: {command: process.execPath,- args: [join(repository, 'scripts', 'mcp-server.mjs'), '--backend', 'gpu', '--memory', '192'],+ args: [join(repository, 'scripts', 'mcp-server.mjs'), '--backend', 'gpu', '--memory', '192', ...(assetDirectory ? ['--assets', assetDirectory] : [])],} } };}@@ -146,8 +146,15 @@ async function runTask(task, systemPromptAddition) {const workingDirectory = await mkdtemp(join(tmpdir(), '67js-agent-task-'));try {const configPath = join(workingDirectory, 'mcp.json');- await writeFile(configPath, JSON.stringify(mcpConfig()));- const prompt = `${PROMPT_PREAMBLE}\n\n${task.prompt.replace(/\n/g, ' ')}`;+ let assetDirectory = null;+ if (task.assets) {+ assetDirectory = join(workingDirectory, 'assets');+ await mkdir(assetDirectory);+ await copyFile(join(repository, 'tests', 'fixtures', 'RobotExpressive.glb'), join(assetDirectory, 'robot.glb'));+ }+ await writeFile(configPath, JSON.stringify(mcpConfig(assetDirectory)));+ const taskPrompt = task.prompt.replace(/\n/g, ' ');+ const prompt = task.ownPreamble ? taskPrompt : `${PROMPT_PREAMBLE}\n\n${taskPrompt}`;const run = await runClaude(prompt, workingDirectory, configPath, systemPromptAddition);const transcript = readTranscript(run.output);await writeFile(join(rawDirectory, `${task.id}.jsonl`), run.output);diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjsindex 216ee424..83862405 100644--- a/bench/agent-modeling/tasks.mjs+++ b/bench/agent-modeling/tasks.mjs@@ -231,6 +231,20 @@ For this task the object does not need to rest on the ground.`,{ kind: 'nodeDistance', from: 'elbow', to: 'tip', time: 1, distance: 0.4 },],},+ {+ id: 'robot-reach',+ assets: true,+ prompt: `The asset catalog holds an imported robot character. Create a scene from it with its Idle clip selected at+time 0. Add a 2 second motion in which the robot's right hand reaches for a moving point: the palm joint (labelled+Palm2.R) is at world position [-1.3, 2.6, 0.8] at time 0 and [-1, 1.7, 1.1] at time 2, while the rest of the body stays on the clip.+Find the joints you need by inspecting the scene. When it is finished, call scene_export_recipe once: the exported+recipe is what gets graded.`,+ ownPreamble: true,+ checks: [+ { kind: 'assetClip', name: 'Idle' },+ { kind: 'assetReach', endLabel: 'Palm2.R', from: [-1.3, 2.6, 0.8], to: [-1, 1.7, 1.1] },+ ],+ },];export function taskById(id) {diff --git a/docs/agent-character-motion.md b/docs/agent-character-motion.mdindex 62944fe6..e6f2980e 100644--- a/docs/agent-character-motion.md+++ b/docs/agent-character-motion.md@@ -84,6 +84,7 @@ Pose evaluation starts from the decoded base on every seek.It applies the selected imported clip, static node overrides and authored motion in that order.The outer asset root transform applies last.Tracks replace specified components rather than adding rotations or translations.+IK then solves on that pose.Imported morph animation remains attached to its clip.@@ -133,5 +134,5 @@ Candidate buffers belong to the decoder. Their contents expire at the next stagiThe asset must remain exclusively owned by its adapter while transactions are active.This feature does not create a rig for a flat mesh collection.-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.+Imported asset recipes do not have retargeting, facial morph authoring or topology changes. For a hand reaching or a head looking at a point, use [`motion.ik`](agent-motion.md#inverse-kinematics) instead of writing rotations. In code, [skeleton pose layers](skeleton-pose.md) mix clips with masks 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.mdindex 314e3509..5fcf4240 100644--- a/docs/agent-motion.md+++ b/docs/agent-motion.md@@ -81,7 +81,7 @@ 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+works on procedural recipes and imported assets, and runs after the tracks and any selected clip at every sample, in list order. `tracks` can be empty when amotion has `ik`.```json@@ -96,7 +96,9 @@ point the middle node bends toward; give one, because a straight limb has no bendefaults 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.+`worldForward` is the world direction the character faces at rest, which is the one to use on imported rigs because their+bone axes vary. Otherwise `forward` is the aiming node's local axis (default `[0, 0, 1]`). `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@@ -109,8 +111,11 @@ Put sizes on a child node with the geometry, or on the last node of the chain, wclip. `worstError` is metres for two-bone and radians for aim, so a target out of reach shows up without looking at everyframe. 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.+On an imported asset, joints are its `node-N` IDs from `scene_inspect` with `kind: "hierarchy"`, and they must be editable.+Each sample stages the clip and overrides, reads the local pose, solves, and stages again, so the rest of the body stays on+the selected clip and skins and rigid parts all follow. Targets are in world space, under the asset's `root`, which needs a+uniform scale. Some rigs have no chain to the foot: if the foot is not a descendant of the lower leg, two-bone IK refuses it.+There are no joint angle limits. [Skeleton pose layers](skeleton-pose.md) add clip layers and masks in code.## Internal sampling helpersdiff --git a/docs/skeleton-pose.md b/docs/skeleton-pose.mdindex 5e5ddf5b..127a2fdf 100644--- a/docs/skeleton-pose.md+++ b/docs/skeleton-pose.md@@ -117,7 +117,6 @@ root rather than of the lower leg, so two-bone IK refuses them with an error; it- 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 thebody outward.-- Clip layers and masks are code only, and MCP has no IK for imported assets yet. 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).+- Clip layers and masks are code only. Recipes and imported assets get IK through MCP with [`motion.ik`](agent-motion.md#inverse-kinematics).- The [animation mixer](animation-mixer.md) works on rigid part transforms and has no layers, masks or IK. Use this addonfor skinned rigs.diff --git a/package.json b/package.jsonindex 4f6530f1..7938ac06 100644--- a/package.json+++ b/package.json@@ -127,6 +127,7 @@"smoke:enhancements": "node scripts/smoke-enhancements.mjs","smoke:site": "node scripts/smoke-site.mjs","publish:ci": "node scripts/publish-ci.mjs",+ "smoke:character": "node scripts/smoke-character.mjs","smoke:agent-character": "node scripts/smoke-agent-character.mjs","smoke:agent-review": "node scripts/smoke-agent-review.mjs"},diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex cb0bb62b..c6fa258f 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -219,7 +219,8 @@ const ikSolver = z.discriminatedUnion('type', [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].'),+ worldForward: vector3.optional().describe('The world direction the character faces in its rest pose, such as [0, 0, 1]. Use this on imported rigs, whose bone axes vary.'),+ forward: vector3.optional().describe('Instead of worldForward: the aiming node\'s local axis to point at the target. Defaults to [0, 0, 1], the front of an unrotated recipe node.'),target: ikPoint,maxAngle: z.number().min(0.001).max(180).optional().describe('Limits the whole turn, in degrees.'),weight: ikWeight,@@ -227,7 +228,7 @@ const ikSolver = z.discriminatedUnion('type', []);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.'),+ ik: z.array(ikSolver).max(16).optional().describe('Inverse kinematics run after the tracks and any selected clip, in order, on recipes and imported assets. IDs are recipe node IDs or an asset\'s node-N IDs; find them with scene_inspect kind hierarchy. 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),diff --git a/scripts/smoke-character.mjs b/scripts/smoke-character.mjsnew file mode 100644index 00000000..56c230aa--- /dev/null+++ b/scripts/smoke-character.mjs@@ -0,0 +1,148 @@+// A real character through the real MCP server, along the path an agent takes: find joints in the hierarchy, add IK over+// a clip, seek, checkpoint and render. Run `npm run prepare:release` first; the preview page comes from its build.+// Stills go to artifacts/character-*.png, for looking at, since these checks prove that things move but not that they look right.+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { copyFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { constants, setPriority, tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const backend = process.argv[2] ?? 'gpu';+const directory = await mkdtemp(join(tmpdir(), '67js-character-'));+const assets = join(directory, 'assets');+const jobs = join(directory, 'jobs');+await mkdir(assets);+await mkdir('artifacts', { recursive: true });+await copyFile(resolve('tests/fixtures/RobotExpressive.glb'), join(assets, 'robot.glb'));++const transport = new StdioClientTransport({+ command: process.execPath,+ args: [resolve('scripts/mcp-server.mjs'), '--backend', backend, '--memory', '192', '--assets', assets, '--jobs', jobs],+ stderr: 'pipe',+ cwd: process.cwd(),+});+let diagnostics = '';+transport.stderr.on('data', chunk => {+ diagnostics += chunk.toString();+});+const client = new Client({ name: '67js-character-smoke', version: '1' });++async function call(name, argumentsValue = {}) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 180000 });+ assert.ok(!result.isError, `${name}: ${JSON.stringify(result.content).slice(0, 700)}\n${diagnostics.slice(-500)}`);+ return result;+}++async function look(sessionId, label, motionTime) {+ const result = await call('scene_look', { sessionId, width: 480, height: 480, ...(motionTime === undefined ? {} : { motionTime }) });+ const { data } = result.content.find(block => block.type === 'image');+ if (label) await writeFile(`artifacts/character-${label}.png`, Buffer.from(data, 'base64'));+ return data;+}++async function allNodes(sessionId) {+ const nodes = [];+ let offset = 0;+ for (;;) {+ const page = (await call('scene_inspect', { sessionId, kind: 'hierarchy', offset, limit: 64 })).structuredContent;+ nodes.push(...page.nodes);+ if (!page.truncated) return nodes;+ offset += page.nodes.length;+ }+}++async function finished(jobId) {+ const deadline = Date.now() + 120000;+ while (Date.now() < deadline) {+ const record = (await call('scene_render_status', { jobId })).structuredContent;+ if (['completed', 'cancelled', 'failed', 'interrupted'].includes(record.state)) return record;+ await delay(200);+ }+ throw new Error('The render job did not finish within two minutes.');+}++const report = {};+try {+ await client.connect(transport);+ const catalog = (await call('scene_asset_catalog')).structuredContent;+ const created = (await call('scene_create_asset', { recipe: {+ format: '67js.asset', schemaVersion: 1, assetId: catalog.assets[0].assetId,+ camera: { eye: [1.5, 3, 11], target: [0, 2.6, 0], fov: 38, near: 0.1, far: 100 },+ animation: { clip: 10, time: 0.2 },+ } })).structuredContent;+ const { sessionId } = created;+ let { revision } = created;+ const base = await look(sessionId, 'base');++ const nodes = await allNodes(sessionId);+ const idOf = label => {+ const found = nodes.find(node => node.label === label && node.joint);+ assert.ok(found, `no joint labelled ${label}`);+ return found.id;+ };+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;+ const motion = {+ duration: 2,+ tracks: [],+ ik: [+ {+ type: 'two-bone', root: idOf('UpperArm.R'), middle: idOf('LowerArm.R'), end: idOf('Palm2.R'), keepEndRotation: false,+ target: { interpolation: 'SMOOTH', keyframes: [{ time: 0, value: [-1.3, 2.6, 0.8] }, { time: 1, value: [-1, 1.7, 1.1] }, { time: 2, value: [-1.3, 2.6, 0.8] }] },+ },+ { type: 'aim', joint: idOf('Head'), worldForward: [0, 0, 1], maxAngle: 60, target: { interpolation: 'SMOOTH', keyframes: [{ time: 0, value: [-4, 3, 6] }, { time: 2, value: [4, 3, 6] }] } },+ ],+ };+ const applied = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion }] })).structuredContent;+ assert.equal(applied.renderSucceeded, true, applied.renderError);+ revision = applied.revision;++ const inspected = (await call('scene_inspect', { sessionId, kind: 'hierarchy', limit: 1 })).structuredContent;+ assert.deepEqual(inspected.motionIk.map(result => result.type), ['two-bone', 'aim']);+ assert.ok(inspected.motionIk.every(result => result.reached), JSON.stringify(inspected.motionIk));+ report.motionIk = inspected.motionIk;++ const atStart = await look(sessionId, 'ik-start', 0);+ const atMiddle = await look(sessionId, 'ik-middle', 1);+ const atEnd = await look(sessionId, 'ik-end', 2);+ assert.notEqual(atStart, base, 'IK changes the picture');+ assert.notEqual(atMiddle, atStart, 'the target moves the arm');+ assert.notEqual(atEnd, atMiddle);+ assert.equal(await look(sessionId, null, 1), atMiddle, 'seeking back gives the same picture');++ const restored = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: revision })).structuredContent;+ revision = restored.revision;+ assert.equal(await look(sessionId), base, 'restore gives back the exact picture from before the IK');++ const again = (await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-motion', motion }] })).structuredContent;+ assert.equal(again.renderSucceeded, true, again.renderError);+ revision = again.revision;+ const held = await look(sessionId, null, 1);+ const submitted = (await call('scene_render_submit', { sessionId, expectedRevision: revision, settings: {+ kind: 'video', width: 320, height: 320, fps: 8, duration: 0.75, motion: { start: 0 }, animation: { clip: 10, start: 0 },+ } })).structuredContent;+ const record = await finished(submitted.jobId);+ assert.equal(record.state, 'completed', JSON.stringify(record));+ const result = (await call('scene_render_result', { jobId: submitted.jobId })).structuredContent;+ const videoPath = result.artifacts[0].path;+ const decoded = spawnSync('ffmpeg', ['-v', 'error', '-i', videoPath, '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-threads', '1', 'pipe:1'], { windowsHide: true, maxBuffer: 64 * 1024 ** 2 });+ assert.equal(decoded.status, 0, decoded.stderr.toString());+ const frameBytes = 320 * 320 * 3;+ assert.equal(decoded.stdout.length, frameBytes * 6, 'the video has every frame');+ assert.notDeepEqual(decoded.stdout.subarray(0, frameBytes), decoded.stdout.subarray(frameBytes * 5, frameBytes * 6), 'the video moves');+ const still = spawnSync('ffmpeg', ['-v', 'error', '-y', '-ss', '0.4', '-i', videoPath, '-frames:v', '1', 'artifacts/character-job-middle.png'], { windowsHide: true, encoding: 'utf8' });+ assert.equal(still.status, 0, still.stderr);+ assert.equal(await look(sessionId), held, 'a job leaves the preview pose exactly as it was');+ report.video = { frames: 6, bytes: result.artifacts[0].bytes };++ const exported = (await call('scene_export_recipe', { sessionId })).structuredContent;+ assert.equal((exported.recipe ?? exported).motion.ik.length, 2);+ await call('scene_dispose', { sessionId });+ console.log(`Character passed on ${backend}: ${JSON.stringify(report)}`);+} finally {+ await client.close();+ await rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 300 }).catch(error => console.warn(`Left ${directory}: ${error.code}`));+}diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex f7276373..1c7fe3b9 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -39,7 +39,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- 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 `createAssetPose` from `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`.+- 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.- 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.jsindex 55c2cb68..f8f671fa 100644--- a/src/agent-asset.js+++ b/src/agent-asset.js@@ -412,6 +412,9 @@ export function createAgentAssetScene(asset, inputRecipe) {camera: view.camera, environment: view.environment, effects: view.effects, shadow: view.shadow,root: rootFrom(candidate.root), animation, materialOverrides: normalizedOverrides, nodeOverrides: normalizedNodes,});+ if (candidate.motion?.ik?.length && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {+ throw new RangeError('Motion ik needs a uniform asset root scale.');+ }result.motion = normalizeAgentMotion(candidate.motion, motionRecipe(result));return copiedJson(result);}@@ -421,13 +424,34 @@ export function createAgentAssetScene(asset, inputRecipe) {for (const override of candidate.materialOverrides) {baselines.set(override.id, { ...baselines.get(override.id), ...override });}+ const root = candidate.root;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.',+ ikHierarchy: [...sourceNodes.values()],+ ikRootMatrix: Array.from(mat4.fromRotationTranslationScale(mat4.create(), root.rotation, root.translation, [root.scale[0], root.scale[0], root.scale[0]])),};}+ /** Stage clip and overrides without publishing them, and read the local pose IK must start from. */+ function stagedNodePoses(animation, overrides) {+ const probe = asset.stagePose({ animation, nodeOverrides: overrides });+ try {+ return probe.nodePoses();+ } finally {+ probe.discard();+ }+ }++ function trackOverrides(baseOverrides, sampled) {+ const nodeOverrides = new Map(baseOverrides.map(override => [override.id, override]));+ for (const [id, patch] of sampled?.nodes ?? []) {+ const copiedPatch = Object.fromEntries(Object.entries(patch).map(([field, value]) => [field, Array.from(value)]));+ nodeOverrides.set(id, { ...nodeOverrides.get(id), id, ...copiedPatch });+ }+ return nodeOverrides;+ }+function publish(input, autoFrame = false, increment = true, transientTime = undefined, transientAnimation = undefined) {let candidate = transientTime === undefined ? normalize(input) : recipe;if (transientAnimation !== undefined) {@@ -453,10 +477,12 @@ export function createAgentAssetScene(asset, inputRecipe) {throw new RangeError('Decoded resources and retained adapter matrices must not change identity or detach.');}}- const nodeOverrides = new Map(candidate.nodeOverrides.map(override => [override.id, override]));- for (const [id, patch] of sampled?.nodes ?? []) {- const copiedPatch = Object.fromEntries(Object.entries(patch).map(([field, value]) => [field, Array.from(value)]));- nodeOverrides.set(id, { ...nodeOverrides.get(id), id, ...copiedPatch });+ const nodeOverrides = trackOverrides(candidate.nodeOverrides, sampled);+ if (targetTime !== null && stagedSampler?.ikUsesStagedPose) {+ const nodePoses = stagedNodePoses(candidate.animation, [...nodeOverrides.values()]);+ for (const { id, rotation } of stagedSampler.solveStagedIk(targetTime, nodePoses)) {+ nodeOverrides.set(id, { ...nodeOverrides.get(id), id, rotation });+ }}let transaction;try {@@ -535,6 +561,15 @@ export function createAgentAssetScene(asset, inputRecipe) {}}+ /** scene_inspect's motionIk: how each solver fares across the clip, from a sampler that leaves the published pose alone. */+ function motionIkReport() {+ if (!recipe.motion?.ik?.length) return {};+ const sweeper = compileAgentMotion(recipe.motion, motionRecipe(recipe));+ return {+ motionIk: sweeper.sweepIk(time => stagedNodePoses(recipe.animation, [...trackOverrides(recipe.nodeOverrides, sweeper.sample(time)).values()])),+ };+ }+function expected(options) {knownKeys(options, ['expectedRevision'], 'transaction options');if (!Number.isSafeInteger(options.expectedRevision) || options.expectedRevision !== revision) {@@ -704,7 +739,7 @@ export function createAgentAssetScene(asset, inputRecipe) {return sourceNodes.get(id);});const nodes = structuredClone(selected.slice(offset, offset + limit));- return { revision, topologyRevision: 0, assetId: canonicalAssetId, kind: 'hierarchy',+ return { revision, topologyRevision: 0, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(),counts: { nodes: sourceNodes.size, joints: [...sourceNodes.values()].filter(node => node.joint).length },nodes, offset, truncated: offset + nodes.length < selected.length,motion: recipe.motion ? { duration: recipe.motion.duration, loop: recipe.motion.loop, tracks: recipe.motion.tracks.length, time: motionTime } : null };diff --git a/src/agent-motion.js b/src/agent-motion.jsindex 107dc969..e2486e41 100644--- a/src/agent-motion.js+++ b/src/agent-motion.js@@ -171,7 +171,7 @@ function ikWeight(input, duration, label) {return weight;}-function normalizeIkSolver(input, position, nodes, duration) {+function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {const label = `Motion ik ${position}`;if (input?.type === 'two-bone') {knownKeys(input, ['type', 'root', 'middle', 'end', 'target', 'pole', 'weight', 'keepEndRotation'], label);@@ -180,11 +180,11 @@ function normalizeIkSolver(input, position, nodes, duration) {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`),+ target: ikPoint(input.target, visibleNodes, duration, `${label} target`),weight: ikWeight(input.weight, duration, `${label} weight`),};if (input.pole !== undefined) {- solver.pole = ikPoint(input.pole, nodes, duration, `${label} pole`);+ solver.pole = ikPoint(input.pole, visibleNodes, duration, `${label} pole`);}if (input.keepEndRotation !== undefined) {if (typeof input.keepEndRotation !== 'boolean') {@@ -195,7 +195,10 @@ function normalizeIkSolver(input, position, nodes, duration) {return solver;}if (input?.type === 'aim') {- knownKeys(input, ['type', 'joint', 'joints', 'forward', 'target', 'maxAngle', 'weight'], label);+ knownKeys(input, ['type', 'joint', 'joints', 'forward', 'worldForward', 'target', 'maxAngle', 'weight'], label);+ if (input.forward !== undefined && input.worldForward !== undefined) {+ throw new TypeError(`${label} takes forward or worldForward, not both.`);+ }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.`);}@@ -206,10 +209,14 @@ function normalizeIkSolver(input, position, nodes, duration) {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`),+ target: ikPoint(input.target, visibleNodes, duration, `${label} target`),weight: ikWeight(input.weight, duration, `${label} weight`),};+ if (input.worldForward !== undefined) {+ solver.worldForward = valueFrom(input.worldForward, 3, `${label} worldForward`);+ } else {+ solver.forward = valueFrom(input.forward ?? [0, 0, 1], 3, `${label} forward`);+ }if (input.maxAngle !== undefined) {solver.maxAngle = bounded(input.maxAngle, 0.001, 180, `${label} maxAngle`);}@@ -239,7 +246,7 @@ function ancestorsOf(id, nodesById) {// 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 nodesById = new Map(ikHierarchy(recipe).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) {@@ -252,19 +259,22 @@ function checkIkScales(ik, tracks, recipe) {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)) {+ if (Math.max(...scale) - Math.min(...scale) > 1e-3 * 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.`);}}}+/** Every node IK can see. An imported asset's editable nodes can sit under fixed ones, which still carry them. */+function ikHierarchy(recipe) {+ return recipe.ikHierarchy ?? recipe.nodes;+}+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));+ const movableNodes = new Set(recipe.nodes.map(node => node.id));+ const visibleNodes = new Set(ikHierarchy(recipe).map(node => node.id));+ const ik = input.map((solver, position) => normalizeIkSolver(solver, position, movableNodes, visibleNodes, duration));checkIkScales(ik, tracks, recipe);return ik;}@@ -358,7 +368,8 @@ export function normalizeAgentMotion(input, recipe) {/** 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 hierarchy = ikHierarchy(recipe);+ const nodesById = new Map(hierarchy.map(node => [node.id, node]));const needed = new Set();for (const solver of ik) {for (const id of [...solverNodes(solver), ...pointNodes(solver)]) {@@ -366,11 +377,12 @@ function ikRig(ik, recipe) {ancestorsOf(id, nodesById).forEach(ancestor => needed.add(ancestor));}}- const members = recipe.nodes.filter(node => needed.has(node.id));+ const members = hierarchy.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: {},+ ...(recipe.ikRootMatrix ? { rootMatrix: recipe.ikRootMatrix } : {}),joints: members.map(node => ({name: node.id,parent: node.parent === undefined || node.parent === null ? -1 : indexById.get(node.parent),@@ -411,7 +423,7 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {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: 'aim', joints: solver.joints, forward: solver.forward, worldForward: solver.worldForward, maxAngle: solver.maxAngle };}return {...common, type: 'two-bone', root: solver.root, middle: solver.middle, end: solver.end,@@ -427,7 +439,7 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {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) {+ function setBaseFromTracks(localRotations, localTranslations) {for (const { index, tracks } of baseBindings) {if (tracks?.rotation) localRotations[index].set(tracks.rotation);if (tracks?.translation) localTranslations[index].set(tracks.translation);@@ -435,9 +447,21 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {}return {staged,- solve(time) {+ /** Solve for a time. `nodePoses` is a staged { id, translation, rotation } list; without it the base is the tracks. */+ solve(time, nodePoses) {channelSampler?.sample(time);- pose.apply(time, setBase);+ if (nodePoses) {+ const poseById = new Map(nodePoses.map(nodePose => [nodePose.id, nodePose]));+ pose.apply(time, (localRotations, localTranslations) => {+ rig.joints.forEach((joint, index) => {+ const nodePose = poseById.get(joint.name);+ localRotations[index].set(nodePose.rotation);+ localTranslations[index].set(nodePose.translation);+ });+ });+ } else {+ pose.apply(time, setBaseFromTracks);+ }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}.`);@@ -497,7 +521,9 @@ export function compileAgentMotion(input, recipe) {stagedNodeTracks.get(track.id)[track.property] = staged;}const ikEvaluator = motion.ik?.length ? createIkEvaluator(motion, recipe, stagedNodeTracks) : null;- if (ikEvaluator) {+ // An imported asset's base pose comes from its decoder, so it asks for IK itself with solveStagedIk.+ const ikUsesStagedPose = Boolean(ikEvaluator && recipe.ikHierarchy);+ if (ikEvaluator && !ikUsesStagedPose) {for (const id of ikEvaluator.staged.keys()) {if (!output.nodes.has(id)) output.nodes.set(id, {});const nodePatch = output.nodes.get(id);@@ -525,14 +551,23 @@ 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() {+ ikUsesStagedPose,+ /** Solve IK over a pose an asset staged for this time. Returns the node rotations to add. */+ solveStagedIk(time, nodePoses) {+ ikEvaluator.solve(time, nodePoses);+ return [...ikEvaluator.staged].map(([id, rotation]) => ({ id, rotation: Array.from(rotation) }));+ },+ /**+ * How IK fares across the whole clip: one { type, reached, worstError, atTime } per solver. Moves the sampler.+ * `stagedPoseAt(time)` supplies the base pose when the asset owns it.+ */+ sweepIk(stagedPoseAt) {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) => {+ ikEvaluator.solve(time, stagedPoseAt?.(time)).forEach((result, position) => {const record = worst[position];record.reached = record.reached && result.reached;if (result.error > record.worstError) {@@ -566,7 +601,7 @@ export function compileAgentMotion(input, recipe) {throw new RangeError('Sampled camera lens is invalid at Float32 precision.');}}- ikEvaluator?.solve(time);+ if (!ikUsesStagedPose) 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) {@@ -575,7 +610,7 @@ export function compileAgentMotion(input, recipe) {patch[track.property].set(staged);}}- if (ikEvaluator) {+ if (ikEvaluator && !ikUsesStagedPose) {for (const [id, rotation] of ikEvaluator.staged) output.nodes.get(id).rotation.set(rotation);}if (cameraPath) {diff --git a/src/gltf.js b/src/gltf.jsindex d75ad5cc..982d86d2 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -1239,6 +1239,11 @@ export async function parseGltf(data, options = {}) {}const transaction = Object.freeze({parts: candidateParts,+ /** Local transform of every source node in this candidate pose, after the clip and overrides. */+ nodePoses() {+ requirePending();+ return [...sourceNodes].map(([id, node]) => ({ id, translation: node.position.toArray(), rotation: node.quaternion.toArray() }));+ },commit() {requirePending();try {diff --git a/tests/agent-asset-ik.test.js b/tests/agent-asset-ik.test.jsnew file mode 100644index 00000000..669c57e3--- /dev/null+++ b/tests/agent-asset-ik.test.js@@ -0,0 +1,171 @@+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import test from 'node:test';+import { parseGltf } from '../src/gltf.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { clipFromGltfAnimation, createAssetPose } from '../src/skeleton-pose.js';++const bytes = readFileSync(new URL('./fixtures/RobotExpressive.glb', import.meta.url));+const ASSET_ID = 'ab'.repeat(32);+const ARM_TARGET = [-1.3, 2.1, 0.8];++function loadRobot() {+ return parseGltf(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), { maxVertices: 500000 });+}++function nodeId(asset, name) {+ const node = asset.nodes.find(candidate => candidate.name === name);+ assert.ok(node, `no node ${name}`);+ return node.id;+}++function armSolver(asset, target = ARM_TARGET) {+ return {+ type: 'two-bone', root: nodeId(asset, 'UpperArmR'), middle: nodeId(asset, 'LowerArmR'), end: nodeId(asset, 'Palm2R'),+ target, keepEndRotation: false,+ };+}++function assetScene(asset, motion, extra = {}) {+ return createAgentAssetScene(asset, { format: '67js.asset', schemaVersion: 1, assetId: ASSET_ID, motion, ...extra });+}++const partIndex = (asset, name) => asset.parts.findIndex(part => part.name === name);+const matrixOf = (scene, index) => Array.from(scene.parts[index].matrix);+const matrixDistance = (first, second) => Math.max(...first.map((value, index) => Math.abs(value - second[index])));++/** The same solve through the code API, as an independent reference for the part matrices. */+async function referenceAsset(layers, solverFor) {+ const asset = await loadRobot();+ const pose = createAssetPose(asset, { layers: layers(asset), ik: [solverFor(asset)] });+ return { asset, pose };+}++test('an imported character reaches a point, and every part agrees with the code API', async () => {+ const asset = await loadRobot();+ const scene = assetScene(asset, { duration: 1, tracks: [], ik: [armSolver(asset)] });+ scene.sampleMotion(0);+ const reference = await referenceAsset(() => [], candidate => ({+ type: 'two-bone', root: 'UpperArmR', middle: 'LowerArmR', end: 'Palm2R', target: ARM_TARGET, keepEndRotation: false,+ }));+ reference.pose.apply(0);+ assert.equal(reference.pose.ikResults[0].reached, true);+ asset.parts.forEach((part, index) => {+ const distance = matrixDistance(matrixOf(scene, index), Array.from(reference.asset.parts[index].matrix));+ assert.ok(distance < 1e-3, `${part.name}: ${distance}`);+ });+ const [report] = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk;+ assert.equal(report.reached, true);+ assert.ok(report.worstError < 1e-3);+});++test('IK runs on top of the selected clip, which still drives the rest of the body', async () => {+ const asset = await loadRobot();+ const idle = asset.animations.findIndex(animation => animation.name === 'Idle');+ const scene = assetScene(asset, { duration: 1, tracks: [], ik: [armSolver(asset)] }, { animation: { clip: idle, time: 0.5 } });+ scene.sampleMotion(0);+ const reference = await loadRobot();+ reference.applyAnimation(0.5, idle);+ const leg = partIndex(reference, 'LegL');+ assert.ok(matrixDistance(matrixOf(scene, leg), Array.from(reference.parts[leg].matrix)) < 1e-3, 'the leg stays on the clip');+ const arm = partIndex(reference, 'ArmR');+ assert.ok(matrixDistance(matrixOf(scene, arm), Array.from(reference.parts[arm].matrix)) > 1e-2, 'the arm left the clip');+});++test('a changed clip time moves the base pose under IK, with the arm still on target', async () => {+ const asset = await loadRobot();+ const walking = asset.animations.findIndex(animation => animation.name === 'Walking');+ const scene = assetScene(asset, { duration: 1, tracks: [], ik: [armSolver(asset)] }, { animation: { clip: walking, time: 0 } });+ const leg = partIndex(asset, 'LegL');+ scene.sampleFrame({ animation: { clip: walking, time: 0.2 }, motionTime: 0 });+ const early = matrixOf(scene, leg);+ scene.sampleFrame({ animation: { clip: walking, time: 0.7 }, motionTime: 0 });+ assert.ok(matrixDistance(early, matrixOf(scene, leg)) > 1e-3, 'the walk still moves the legs');+ const reference = await referenceAsset(candidate => [{ clip: clipFromGltfAnimation(candidate.animations[walking]) }], () => ({+ type: 'two-bone', root: 'UpperArmR', middle: 'LowerArmR', end: 'Palm2R', target: ARM_TARGET, keepEndRotation: false,+ }));+ reference.pose.apply(0.7);+ assert.equal(reference.pose.ikResults[0].reached, true);+ const hand = partIndex(asset, 'ArmR');+ assert.ok(matrixDistance(matrixOf(scene, hand), Array.from(reference.asset.parts[hand].matrix)) < 1e-2);+});++test('keyframed targets seek both ways, and clearing motion restores the base pose', async () => {+ const asset = await loadRobot();+ const arm = partIndex(asset, 'ArmR');+ const before = assetScene(await loadRobot(), null);+ const baseMatrix = matrixOf(before, arm);+ const scene = assetScene(asset, {+ duration: 2, tracks: [],+ ik: [armSolver(asset, { keyframes: [{ time: 0, value: [-1.3, 2.1, 0.8] }, { time: 2, value: [-1.2, 1.7, 1] }] })],+ });+ scene.sampleMotion(1);+ const middle = matrixOf(scene, arm);+ scene.sampleMotion(2);+ assert.ok(matrixDistance(middle, matrixOf(scene, arm)) > 1e-2, 'the arm follows the target');+ scene.sampleMotion(1);+ assert.ok(matrixDistance(middle, matrixOf(scene, arm)) < 1e-5);+ scene.sampleMotion(null);+ assert.ok(matrixDistance(baseMatrix, matrixOf(scene, arm)) < 1e-5);+});++test('inspecting does not disturb the published pose', async () => {+ const asset = await loadRobot();+ const scene = assetScene(asset, { duration: 2, tracks: [], ik: [armSolver(asset)] });+ scene.sampleMotion(1);+ const before = scene.parts.map(part => Array.from(part.matrix));+ const report = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk;+ assert.equal(report.length, 1);+ scene.parts.forEach((part, index) => assert.deepEqual(Array.from(part.matrix), before[index]));+});++test('an unreachable target is reported, with when it is worst', async () => {+ const asset = await loadRobot();+ const scene = assetScene(asset, {+ duration: 2, tracks: [],+ ik: [armSolver(asset, { keyframes: [{ time: 0, value: ARM_TARGET }, { time: 2, value: [-20, 2, 0] }] })],+ });+ const [report] = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk;+ assert.equal(report.reached, false);+ assert.equal(report.atTime, 2);+ assert.ok(report.worstError > 10);+});++test('targets are in world space, under the asset root', async () => {+ const shift = [5, 0, 0];+ const asset = await loadRobot();+ const moved = ARM_TARGET.map((value, axis) => value + shift[axis]);+ const scene = assetScene(asset, { duration: 1, tracks: [], ik: [armSolver(asset, moved)] }, { root: { translation: shift } });+ const [report] = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk;+ assert.equal(report.reached, true, `error ${report.worstError}`);+});++test('a target can follow a node of the character, and aim takes worldForward', async () => {+ const asset = await loadRobot();+ const scene = assetScene(asset, {+ duration: 1, tracks: [],+ ik: [{ type: 'aim', joint: nodeId(asset, 'Head'), worldForward: [0, 0, 1], target: [2, 3, 4] }],+ });+ const headPart = partIndex(asset, 'Head_2');+ const rest = await loadRobot();+ const restPose = createAssetPose(rest);+ restPose.apply(0);+ const [report] = scene.inspect({ kind: 'hierarchy', limit: 1 }).motionIk;+ assert.equal(report.reached, true);+ scene.sampleMotion(0);+ assert.ok(matrixDistance(matrixOf(scene, headPart), Array.from(rest.parts[headPart].matrix)) > 1e-2, 'the head turned');+ const following = assetScene(await loadRobot(), {+ duration: 1, tracks: [],+ ik: [armSolver(asset, { node: nodeId(asset, 'Head') })],+ });+ assert.ok(following.inspect({ kind: 'hierarchy', limit: 1 }).motionIk[0].worstError < 2);+});++test('asset IK mistakes say what to pass', async () => {+ const asset = await loadRobot();+ const motion = ik => ({ duration: 1, tracks: [], ik });+ assert.throws(() => assetScene(asset, motion([{ ...armSolver(asset), root: 'node-99999' }])), /root must be a node ID/);+ const feet = { type: 'two-bone', root: nodeId(asset, 'UpperLegL'), middle: nodeId(asset, 'LowerLegL'), end: nodeId(asset, 'FootL'), target: [0, 0, 0] };+ assert.throws(() => assetScene(asset, motion([feet])), /end must descend from middle/);+ assert.throws(() => assetScene(asset, motion([armSolver(asset)]), { root: { scale: [1, 2, 1] } }), /uniform asset root scale/);+});diff --git a/tests/agent-motion-ik.test.js b/tests/agent-motion-ik.test.jsindex 2b1efce1..e048c2ff 100644--- a/tests/agent-motion-ik.test.js+++ b/tests/agent-motion-ik.test.js@@ -174,6 +174,7 @@ test('mistakes say what to pass', () => {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.throws(() => create([{ type: 'aim', joint: 'lamp', target: [0, 0, 0], forward: [0, 0, 1], worldForward: [0, 0, 1] }]), /forward or worldForward, not both/);assert.deepEqual([...AGENT_SCENE_CAPABILITIES.motionIk], ['two-bone', 'aim']);});