3D engine that AI agents drive
Retarget humanoid clips between catalog assets through MCP, with foot lock and keyed morph weights
Nguyen Xuan An99c7b92fb746
diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 459b421b..c0e37943 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -11,8 +11,8 @@"entry:nature": 13200,"entry:motion": 15260,"entry:canvas2d": 9400,- "entry:gltf": 57790,- "entry:gltf+lazy": 61120,+ "entry:gltf": 57902,+ "entry:gltf+lazy": 61230,"entry:modeling": 8700,"entry:sculpt": 2500,"entry:surface": 10100,@@ -23,7 +23,7 @@"entry:physics": 18000,"entry:spume": 9000,"entry:retarget": 17210,- "entry:skeleton-pose": 20640,+ "entry:skeleton-pose": 20784,"entry:vehicle": 14700,"entry:vegetation": 18600,"entry:terrain": 4100,@@ -35,9 +35,9 @@"entry:path-tracer": 15960,"entry:texture-set": 900,"entry:agent-scene": 80770,- "entry:agent-scene+lazy": 263350,- "entry:agent-asset": 112170,- "entry:agent-asset+lazy": 274720,+ "entry:agent-scene+lazy": 264437,+ "entry:agent-asset": 116333,+ "entry:agent-asset+lazy": 278882,"entry:hdri": 3300,"entry:camera-effects": 8600,"entry:water-reflection": 26580,@@ -47,9 +47,9 @@"entry:light-linking": 19720,"entry:cascaded-shadows": 28530,"scene:lit-box": 65870,- "scene:gltf-box": 90150,- "scene:gltf-box+lazy": 93480,+ "scene:gltf-box": 90267,+ "scene:gltf-box+lazy": 93594,"scene:agent-scene": 109670,- "scene:agent-scene+lazy": 292250+ "scene:agent-scene+lazy": 293337}}diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex 0ff57b3c..8c9ca4aa 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,11 +1,11 @@{- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681)",- "schemaTotalBytes": 191040,+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised for issue #325 (clip layers from another asset, foot lock, morph tracks described once in the shared motion reference): total 191565 to 191585, scene_apply 45303 to 45323, scene_create_asset 19412 to 19432 (measured plus 20); raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then the nine remaining modifiers (issue #42: screw, skin, wireframe, lattice, curve, hook, wave, weighted_normal, smooth_by_angle) added their notes to meshModifiers and a free modifier record replaced the modifier schema entry, so the schemas shrank and the scene_capabilities result rose to 15900 (measured 15814); path query of scene_inspect (issue #64): one record field of 205 bytes in the scene_inspect schema (total 190732, within its budget) and the navigation notes in scene_capabilities, so the result rose to 14500 (measured 14494); reflection probes (issue #55): the bake.probes line, and the scene_capabilities result raised to 16600 (measured 16541) after merging with main; volumeFog shadowAmbient (issue #165): scene_create raised to 62945 (measured 62940) and scene_apply to 45040 (measured 45037); keyframe easing (issue #286): one easing string field in each of the motion track schemas, scene_create raised to 63450 (measured 63444) and the total to 191000 (measured 190994); glTF import line gltfImport (issue #280): the scene_capabilities result raised to 16701 (measured 16681)",+ "schemaTotalBytes": 191585,"schemaToolBytes": {"scene_create": 63450,- "scene_apply": 45040,+ "scene_apply": 45323,"mesh_edit": 33980,- "scene_create_asset": 19310,+ "scene_create_asset": 19432,"mesh_stack": 11030},"schemaOtherToolBytes": 4000,diff --git a/changes/325.md b/changes/325.mdnew file mode 100644index 00000000..4bcd84dc--- /dev/null+++ b/changes/325.md@@ -0,0 +1 @@+- Retarget a clip from another catalog asset through MCP with `motion.layers[].from`, plant the feet with `motion.footLock` (two-bone IK on contact phases found from foot height and speed, soles turned to an optional ground normal), and key morph weights by target name with `{ kind: "morph" }` tracks (issue #325). `scene_inspect` hierarchy reports `retargets` (mapped, unmapped and missing bones), `footLock` phases and `morphTargetNames`; measured foot drift in planted phases under 2 cm on the test pair.diff --git a/docs/agent-character-motion.md b/docs/agent-character-motion.mdindex 9fad4244..8afb0dc7 100644--- a/docs/agent-character-motion.md+++ b/docs/agent-character-motion.md@@ -86,7 +86,16 @@ 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.+Imported morph animation remains attached to its clip. To key a face by hand, add `{ "kind": "morph", "id": "jawOpen",+"property": "weight", "keyframes": [...] }` tracks: the id is a morph target name from `morphTargetNames` in `scene_inspect`.++### Clips from another character++A layer with `from: { "asset": "<catalog ID>", "clip": 0 }` plays a clip of another humanoid file on this one, corrected for+the difference in rest pose and leg length (`retargetClip`). Add `footLock` to the motion to plant the feet, with a `ground`+plane and normal on a slope. Fields, limits and what `scene_inspect` reports (`retargets`, `footLock`) are in+[the motion contract](agent-motion.md#a-clip-from-another-catalog-asset); the library side is in [retarget.md](retarget.md).+The foot lock reads the layers, then your tracks and IK apply on top.`scene_look.motionTime` and `scene.sampleMotion(time)` sample motion without changing the recipe, revision or checkpoints.Explicit `null` restores the authored pose without procedural tracks.diff --git a/docs/agent-motion.md b/docs/agent-motion.mdindex e933ff19..f3715716 100644--- a/docs/agent-motion.md+++ b/docs/agent-motion.md@@ -158,12 +158,50 @@ each blending over the pose so far, before tracks and IK:`tracks` can be left out when there are layers. Layers need an imported asset: a procedural recipe refuses them. Everything ischecked against the asset (clip indexes, node IDs and names, track names) and bounded before anything is built, and the-pose is rebuilt from the rest pose for each time, so a seek equals playing. `bones` renames tracks inside one asset; moving a-clip from another rig (rest-pose retargeting with `retargetClip`) is code only, because the MCP holds one asset at a time.-Foot tilt on slopes is not done.+pose is rebuilt from the rest pose for each time, so a seek equals playing. `bones` renames tracks inside one asset.[Skeleton pose layers](skeleton-pose.md) have the same layers in code.+### A clip from another catalog asset++A layer takes `from: { "asset": "<catalog ID>", "clip": 0 }` instead of `clip`: the clip of another file in the catalog, moved+onto this asset with `retargetClip` and the humanoid bone map. Both skeletons must map the required bones (hips, spine, head,+arms and legs) or the call fails and lists what is missing. `scale` (0.1 to 10) and `rootMotion` (boolean) are the+`retargetClip` options of the same names. `from` replaces `clip` and `bones`, and morph tracks of the source are not carried.+The runtime reads the other asset by its catalog ID (at most 4 at once); a session made without a catalog cannot use it.+`scene_inspect` `kind: "hierarchy"` returns `retargets`: per `from` layer, `source` and `target` with `mapped` (bones+matched), `unmapped` (joints no bone claimed, up to 24, with `unmappedCount`) and `missing`.++```json+"motion": { "duration": 1, "loop": true, "layers": [{ "from": { "asset": "<id of the walking file>", "clip": 0 }, "scale": 1.1 }] }+```++### Foot lock++`motion.footLock` (opt-in, needs `layers`) plants the feet. The layers are sampled at 30 frames per second once, and a foot+counts as planted while its ankle is within `contactHeight` of its lowest point in the clip and its horizontal speed is under+`contactSpeed`, for at least three frames. During each planted phase the leg is solved with two-bone IK to where the ankle+touched down, faded in and out over `blend` seconds. The leg bones must map to the humanoid bones, and the root needs a+uniform scale. `true` takes the defaults:++| Field | Default | Meaning |+| --- | --- | --- |+| `contactHeight` | 0.05 | Metres above the lowest ankle height (0.001 to 1) |+| `contactSpeed` | 0.35 | Metres per second (0.01 to 5). A retargeted foot that slides may need a higher value to be found |+| `blend` | 0.1 | Seconds to fade the pin in and out (0.01 to 1) |+| `ground` | none | `{ height = 0, normal = [0, 1, 0] }` in world space: the planted ankle is put on that plane and the sole is turned to the normal. The normal must lean less than 60 degrees from +Y |++The lock reads the layers only: tracks and `ik` are applied after it. `scene_inspect` returns `footLock.feet` with the+planted phases per foot. The hips do not move, so a ground far from the character's floor can be out of reach.++### Morph weight tracks++A track `{ "kind": "morph", "id": "eyeBlinkLeft", "property": "weight", "keyframes": [...] }` keys the weight (0 to 1) of every+morph target of that name, with the interpolations and `easing` of any other track. It replaces what a layer or the file+gives that target; targets without a track keep theirs. Names come from the file (`extras.targetNames`, the glTF convention+that Blender and face rigs with ARKit names such as `eyeBlinkLeft` and `jawOpen` export); `scene_inspect` returns them as+`morphTargetNames`, and an unknown name fails with the first ones. Tracks can address morph targets only on an imported asset.+### Joint limits and sanity warningsA two-bone solver takes `limits: { "root": { "x": [min, max], "y": [...], "z": [...] }, "middle": {...} }` in degrees. Eachdiff --git a/docs/retarget.md b/docs/retarget.mdindex 4423cdd0..aeb7f2ce 100644--- a/docs/retarget.md+++ b/docs/retarget.md@@ -69,7 +69,11 @@ Assumptions and limits:- The clip is resampled at `frameRate`, so cubic-spline and step curves are baked to linear keys.- Source scale and non-hips translation tracks are ignored. Finger and toe bones transfer only when mapped in both rigs.- The source and target rest pose must be the bind pose (the node pose equals the inverse bind pose). A file that animates away from it is not detected.-- No foot-lock, no IK, no retargeting of rotation limits. Different proportions can make feet slide or arms intersect the body.+- No IK and no retargeting of rotation limits. Different proportions can make feet slide or arms intersect the body.+- Through MCP, an asset recipe plays a clip of another catalog asset with `motion.layers[].from`, and `motion.footLock` plants+ the feet afterwards (two-bone IK with the sole turned to a ground normal); see "A clip from another catalog asset" and+ "Foot lock" in [agent-motion.md](agent-motion.md). In code, `createFootLock` in `src/foot-lock.js` does the same over an+ asset's nodes.`createSkinClipPlayer(skin, clip, { rig, meshWorldMatrix })` applies a clip to a skin: `apply(seconds)` samples the clip, composes jointworld matrices and calls `updateSkinPose`. The renderer still needs `updateParts` afterwards.diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 9006d5ad..f19ab1a5 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -29,6 +29,26 @@ function requireSession(sessionId) {return active;}+function bytesFromBase64(data) {+ if (typeof Uint8Array.fromBase64 === 'function') return Uint8Array.fromBase64(data);+ const binary = atob(data);+ const bytes = new Uint8Array(binary.length);+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);+ return bytes;+}++// Other catalog assets whose clips a motion layer retargets: only their clips and nodes are kept, so the decoded+// meshes and textures are released at once.+async function decodeMotionSources(encoded = {}) {+ const decoded = {};+ for (const [assetId, data] of Object.entries(encoded)) {+ const source = await parseGltf(bytesFromBase64(data).buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });+ decoded[assetId] = { animations: source.animations, nodes: source.nodes };+ source.dispose();+ }+ return decoded;+}+function validatePreviewCamera(camera) {const view = mat4.lookAt(mat4.create(), camera.eye, camera.target, camera.up);for (const aspect of [1 / 16, 16]) {@@ -649,20 +669,13 @@ window.__agentPreview = {},async createAsset(input) {if (active) throw new Error('Dispose the current scene before creating another.');- let bytes;- if (typeof Uint8Array.fromBase64 === 'function') {- bytes = Uint8Array.fromBase64(input.data);- } else {- const binary = atob(input.data);- bytes = new Uint8Array(binary.length);- for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);- }+ const bytes = bytesFromBase64(input.data);let asset;try {// Labels, mesh reports and motion read the on-demand modules on any asset, not only one with mesh edits.await loadAllAgentSceneModules();asset = await parseGltf(bytes.buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });- return createPreview(createAgentAssetScene(asset, input.recipe), input, asset);+ return createPreview(createAgentAssetScene(asset, input.recipe, { sources: await decodeMotionSources(input.sources) }), input, asset);} catch (error) {asset?.dispose();throw error;@@ -680,6 +693,13 @@ window.__agentPreview = {return { sessionId, ...scene.inspectMeshes(options) };},apply(input) {+ if (input.sources) {+ const { scene } = requireSession(input.sessionId);+ return decodeMotionSources(input.sources).then(decoded => {+ scene.provideMotionSources?.(decoded);+ return afterMeshBooleans(input.operations, () => this.applyLoaded(input));+ });+ }return afterMeshBooleans(input.operations, () => this.applyLoaded(input));},applyLoaded({ sessionId, operations, expectedRevision }) {diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex c057a035..c5f96dec 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -21,6 +21,7 @@ import { sessionProblem } from '../src/agent-errors.js';const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;const MAXIMUM_IMAGE_BYTES = 1024 * 1024;+const MAXIMUM_MOTION_SOURCES = 4;// A job writes files, not MCP image responses, so a 1920x1080 PNG may be larger than an inline image.const MAXIMUM_JOB_FRAME_BYTES = 12 * 1024 * 1024;// The object ID pass lists the part behind each ID in the job metrics; longer lists are cut and flagged.@@ -129,6 +130,23 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browreturn catalogPromise;}+ // Motion layers can play a clip of another catalog asset (`from.asset`). The page gets those assets' bytes by catalog ID,+ // never a path, and keeps only their clips and nodes.+ async function motionSources(motions) {+ const ids = new Set();+ for (const motion of motions) {+ for (const layer of Array.isArray(motion?.layers) ? motion.layers : []) {+ const id = layer?.from?.asset;+ if (typeof id === 'string' && /^[a-f0-9]{64}$/i.test(id)) ids.add(id.toLowerCase());+ }+ }+ if (ids.size > MAXIMUM_MOTION_SOURCES) throw new RangeError(`Motion layers can retarget clips of at most ${MAXIMUM_MOTION_SOURCES} other assets at once.`);+ if (!ids.size) return {};+ const sources = {};+ for (const id of ids) sources[id] = (await (await catalog()).read(id)).toString('base64');+ return { sources };+ }+function enqueue(task) {if (closing || phase === 'closing' || phase === 'closed' || phase === 'failed') {return Promise.reject(new Error(`The agent runtime is ${phase}.`));@@ -336,7 +354,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browawait jobPage.goto(origin);await jobPage.waitForFunction(() => Boolean(window.__agentPreview));const input = { sessionId: jobId, recipe: snapshot.recipe, memoryBudgetMiB: memory, backend,- ...(snapshot.assetBytes ? { data: snapshot.assetBytes.toString('base64') } : {}) };+ ...(snapshot.assetBytes ? { data: snapshot.assetBytes.toString('base64'), ...(await motionSources([snapshot.recipe.motion])) } : {}) };const created = await jobPage.evaluate(({ method, input }) => window.__agentPreview[method](input),{ method: snapshot.assetBytes ? 'createAsset' : 'create', input });const width = settings.kind === 'video' ? Math.floor(created.render.width / 2) * 2 : created.render.width;@@ -540,7 +558,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browconst bytes = await (await catalog()).read(recipe.assetId);await boot();const sessionId = randomUUID();- const result = await evaluate('createAsset', { recipe, data: bytes.toString('base64'), sessionId, memoryBudgetMiB: memory, backend });+ const result = await evaluate('createAsset', { recipe, data: bytes.toString('base64'), sessionId, memoryBudgetMiB: memory, backend, ...(await motionSources([recipe.motion])) });activeSessionId = sessionId;return result;});@@ -572,7 +590,8 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}const bakeAfter = bakeAfterOperations(input.operations);const rebakes = activeSceneHasBake || bakeAfter === true;- const applied = await invoke('apply', input, rebakes ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);+ const motions = (input.operations ?? []).filter(operation => operation.type === 'set-motion').map(operation => operation.motion);+ const applied = await invoke('apply', { ...input, ...(await motionSources(motions)) }, rebakes ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);activeSceneHasBake = bakeAfter ?? activeSceneHasBake;return applied;});@@ -679,7 +698,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browprivateSessionId = randomUUID();await reviewEvaluate(branchRecipe || !assetBytes ? 'create' : 'createAsset', { sessionId: privateSessionId,recipe: branchRecipe ? branchRecipe.recipe : snapshot.recipe, memoryBudgetMiB: memory, backend,- ...(!branchRecipe && assetBytes ? { data: assetBytes.toString('base64') } : {}) });+ ...(!branchRecipe && assetBytes ? { data: assetBytes.toString('base64'), ...(await motionSources([snapshot.recipe.motion])) } : {}) });privateCreated = true;for (const index of group.shotIndexes) {const rendered = await reviewEvaluate('reviewShot', { sessionId: privateSessionId, shot: settings.shots[index], index,diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 71659f8d..16706ff0 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -505,7 +505,7 @@ const cloth = z.strictObject({}).describe('Cloth baked at 60 fps and seeked by motionTime. Units and defaults: scene_capabilities cloth.');// The full motion schema (tracks, ik, constraints, drivers) is in scene_create's recipe. scene_apply and asset recipes// take the same object, validated by the backend, without repeating about 35 KB of schema in each tool.-const recipeMotionReference = z.record(z.string(), z.unknown()).describe('The same object as recipe.motion in scene_create: duration, loop, tracks, ik, constraints, drivers. Read that tool for the fields. On an imported asset it also takes layers, up to 8 clips played at motion time before tracks and ik: { clip (scene_inspect animations id), mask: { joints, descendants, exclude } of node IDs, weight, speed, offset, loop, additive, reference, bones: { clip node: asset node } to retarget by name, morph }. A masked layer waves while another walks.');+const recipeMotionReference = z.record(z.string(), z.unknown()).describe('The same object as recipe.motion in scene_create: duration, loop, tracks, ik, constraints, drivers. Read that tool for the fields. On an imported asset it also takes layers, up to 8 clips played at motion time before tracks and ik: { clip (scene_inspect animations id), mask: { joints, descendants, exclude } of node IDs, weight, speed, offset, loop, additive, reference, bones: { clip node: asset node } to retarget by name, morph } or from: { asset, clip } for a clip of another catalog asset retargeted onto this humanoid (scale, rootMotion). motion also takes footLock (true or { contactHeight, contactSpeed, blend, ground }) and { kind: "morph", id: target name, property: "weight" } tracks. A masked layer waves while another walks.');const boneRecord = z.strictObject({name: z.string().min(1).max(64).describe('Unique within the armature. Humanoid rigs use the canonical names (hips, spine, chest, neck, head, leftUpperArm, leftLowerArm, leftHand, leftUpperLeg, leftLowerLeg, leftFoot, leftToes, and right...) so retarget works.'),parent: z.string().min(1).max(64).nullable().optional().describe('Parent bone name, or null for a root bone.'),diff --git a/src/agent-asset.js b/src/agent-asset.jsindex d8a6257a..d5cd47ad 100644--- a/src/agent-asset.js+++ b/src/agent-asset.js@@ -6,7 +6,9 @@ import { fitPerspectiveDistance } from './camera.js';import { validateSkinGeometry, validateSkinPose } from './skinning.js';import { validateMorphGeometry, validateMorphTransform } from './morph.js';import * as agentMotion from './agent-motion.js';-import { clipLayerContextFromAsset } from './agent-clip-layers.js';+import { clipLayerContextFromAsset, retargetSourceFromAsset } from './agent-clip-layers.js';+import { retargetAssetClip, retargetReport } from './agent-retarget.js';+import { createFootLock } from './foot-lock.js';import { clipFromGltfAnimation, createAssetLayerEvaluator, morphClipFromGltfAnimation } from './skeleton-pose.js';import { registerAgentSceneModule, agentSceneModule } from './agent-scene-modules.js';import { normalizeMeshEditEntries, meshEditEntriesAfter, realizeMeshEdits, meshEditSignature } from './agent-asset-mesh.js';@@ -258,7 +260,7 @@ function framedCamera(bounds) {}/** Own authoring state around one exclusively owned, decoded parseGltf asset. */-export function createAgentAssetScene(asset, inputRecipe) {+export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {if (!asset || !Array.isArray(asset.parts) || !asset.parts.length || !Array.isArray(asset.animations) ||typeof asset.stagePose !== 'function' || !Array.isArray(asset.nodes)) {throw new TypeError('createAgentAssetScene requires a decoded parseGltf asset.');@@ -303,6 +305,22 @@ export function createAgentAssetScene(asset, inputRecipe) {const materialRecords = new Map([...materials.values()].map(record => [record.id, record]));const sourceNodes = new Map(asset.nodes.map(node => [node.id, structuredClone(node)]));const clipLayerContext = clipLayerContextFromAsset(asset.animations, [...sourceNodes.values()]);+ /** Other catalog assets whose clips layers may retarget, by asset ID: decoded `{ animations, nodes }`. */+ function provideMotionSources(decodedSources) {+ for (const [sourceId, decoded] of Object.entries(decodedSources ?? {})) {+ if (/^[a-f0-9]{64}$/i.test(sourceId)) clipLayerContext.external.set(sourceId.toLowerCase(), retargetSourceFromAsset(decoded));+ }+ }+ provideMotionSources(sources);+ // Morph targets by the names the file gives them, so motion can key a weight by name; defaults fill a part no layer drives.+ const morphTargetIndex = new Map();+ const morphDefaults = sourceParts.map(part => (part.morph ? Float32Array.from(part.morph.weights) : null));+ sourceParts.forEach((part, partIndex) => {+ (part.morphTargetNames ?? []).forEach((name, index) => {+ if (!morphTargetIndex.has(name)) morphTargetIndex.set(name, []);+ morphTargetIndex.get(name).push({ part: partIndex, index });+ });+ });const initialRecipe = copiedJson(inputRecipe);const assetId = initialRecipe?.assetId;if (typeof assetId !== 'string' || !/^[a-f0-9]{64}$/i.test(assetId)) {@@ -318,6 +336,7 @@ export function createAgentAssetScene(asset, inputRecipe) {let physicsSampler = null;let physicsBake = null;let layerEvaluator = null;+ let footLockEvaluator = null;let motionTime = null;let sampledCamera;const checkpoints = new Map();@@ -478,8 +497,8 @@ export function createAgentAssetScene(asset, inputRecipe) {if (meshEdits.length) {result.meshEdits = meshEdits;}- 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.');+ if ((candidate.motion?.ik?.length || candidate.motion?.footLock) && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {+ throw new RangeError('Motion ik and footLock need a uniform asset root scale.');}result.motion = agentMotion.normalizeAgentMotion(candidate.motion, motionRecipe(result));if (candidate.physics !== undefined && candidate.physics !== null) {@@ -497,7 +516,7 @@ export function createAgentAssetScene(asset, inputRecipe) {return {nodes: [...sourceNodes.values()].filter(node => node.editable),materials: [...baselines.values()], camera: candidate.camera,- ikHierarchy: [...sourceNodes.values()], clipLayerContext,+ ikHierarchy: [...sourceNodes.values()], clipLayerContext, morphTargets: [...morphTargetIndex.keys()],ikRootMatrix: Array.from(mat4.fromRotationTranslationScale(mat4.create(), root.rotation, root.translation, [root.scale[0], root.scale[0], root.scale[0]])),};}@@ -512,11 +531,47 @@ export function createAgentAssetScene(asset, inputRecipe) {}}+ /** A clip of another catalog asset moved onto this asset's rest pose. Cached: the same layer always gives the same clip. */+ const retargetedClips = new Map();+ function retargetedLayerClip(layer, loop) {+ const key = JSON.stringify([layer.from, layer.scale, layer.rootMotion, loop]);+ if (!retargetedClips.has(key)) {+ const source = clipLayerContext.external.get(layer.from.asset);+ const sourceClip = clipFromGltfAnimation(source.animations[layer.from.clip], { loop });+ retargetedClips.set(key, retargetAssetClip(source.nodes, asset.nodes, sourceClip, { scale: layer.scale, rootMotion: layer.rootMotion }));+ }+ return retargetedClips.get(key);+ }++ /** Foot lock over the motion's layers, or null when the motion does not ask for it. */+ function compileFootLock(candidate) {+ const motion = candidate.motion;+ if (!motion?.footLock) return null;+ return createFootLock({+ settings: motion.footLock, nodes: asset.nodes, rootMatrix: motionRecipe(candidate).ikRootMatrix,+ layers: layerDefinitions(motion.layers), duration: motion.duration, loop: motion.loop,+ });+ }++ /** Weights keyed by morph target name replace what layers or the file's defaults give those targets. */+ function keyedMorphWeights(layerWeights, keyed) {+ if (!keyed?.size) return layerWeights;+ const byPart = new Map(layerWeights.map(({ part, weights }) => [part, weights]));+ for (const [name, patch] of keyed) {+ for (const { part, index } of morphTargetIndex.get(name) ?? []) {+ if (!byPart.has(part)) byPart.set(part, Array.from(morphDefaults[part]));+ byPart.get(part)[index] = patch.weight;+ }+ }+ return [...byPart].map(([part, weights]) => ({ part, weights }));+ }+/** Layers of the motion as definitions for the pose code: decoded clips, renamed by `bones`, with their morph tracks. */function layerDefinitions(layers) {return layers.map(layer => {- const animation = asset.animations[layer.clip];const loop = layer.loop !== false;+ if (layer.from) return { clip: retargetedLayerClip(layer, loop), weight: layer.weight, speed: layer.speed, offset: layer.offset, additive: layer.additive, reference: layer.reference, mask: layer.mask };+ const animation = asset.animations[layer.clip];return {clip: clipFromGltfAnimation(animation, { loop, rename: layer.bones }),...(layer.morph === false ? {} : { morphs: morphClipFromGltfAnimation(animation, { loop }) }),@@ -537,7 +592,7 @@ export function createAgentAssetScene(asset, inputRecipe) {for (const override of layered?.nodeOverrides ?? []) {withLayers.set(override.id, { ...withLayers.get(override.id), ...override });}- return { nodeOverrides: trackOverrides([...withLayers.values()], sampled), morphWeights: layered?.morphWeights ?? [] };+ return { nodeOverrides: trackOverrides([...withLayers.values()], sampled), morphWeights: keyedMorphWeights(layered?.morphWeights ?? [], sampled?.morphs) };}function trackOverrides(baseOverrides, sampled) {@@ -575,6 +630,7 @@ export function createAgentAssetScene(asset, inputRecipe) {}let stagedSampler = transientTime === undefined ? agentMotion.compileAgentMotion(candidate.motion, motionRecipe(candidate)) : sampler;const stagedLayers = transientTime === undefined ? compileLayers(candidate.motion) : layerEvaluator;+ const stagedFootLock = transientTime === undefined ? compileFootLock(candidate) : footLockEvaluator;const stagedPhysics = transientTime === undefined ? stageAssetPhysics(candidate) : physicsSampler;const targetTime = transientTime === undefined ? (candidate.motion || candidate.physics ? 0 : null) : transientTime;if (targetTime !== null && !stagedSampler && !stagedPhysics) {@@ -597,6 +653,12 @@ export function createAgentAssetScene(asset, inputRecipe) {}}const { nodeOverrides, morphWeights } = poseOverrides(candidate.nodeOverrides, targetTime === null ? null : stagedLayers, sampled, targetTime);+ if (targetTime !== null && stagedFootLock) {+ const nodePoses = stagedNodePoses(candidate.animation, [...nodeOverrides.values()]);+ for (const override of stagedFootLock.solve(targetTime, nodePoses)) {+ if (sourceNodes.get(override.id)?.editable) nodeOverrides.set(override.id, { ...nodeOverrides.get(override.id), ...override });+ }+ }if (targetTime !== null && stagedSampler?.ikUsesStagedPose) {const nodePoses = stagedNodePoses(candidate.animation, [...nodeOverrides.values()]);for (const override of stagedSampler.solveStagedPose(targetTime, nodePoses)) {@@ -677,6 +739,7 @@ export function createAgentAssetScene(asset, inputRecipe) {sampler = stagedSampler;physicsSampler = stagedPhysics;layerEvaluator = stagedLayers;+ footLockEvaluator = stagedFootLock;}materialSnapshots = stagedMaterials;sampledCamera = stagedCamera;@@ -706,6 +769,18 @@ export function createAgentAssetScene(asset, inputRecipe) {return diagnostics.length ? { diagnostics } : {};}+ /** scene_inspect's retargets (what the humanoid map matched for each layer taken from another asset), footLock (when feet are planted) and morph target names. */+ function motionLayerReport() {+ const retargets = (recipe.motion?.layers ?? []).flatMap((layer, position) => (layer.from+ ? [{ layer: position, from: layer.from, ...retargetReport(clipLayerContext.external.get(layer.from.asset).nodes, [...sourceNodes.values()], 'retarget') }]+ : []));+ return {+ ...(retargets.length ? { retargets } : {}),+ ...(footLockEvaluator ? { footLock: footLockEvaluator.report() } : {}),+ ...(morphTargetIndex.size ? { morphTargetNames: [...morphTargetIndex.keys()].slice(0, 128) } : {}),+ };+ }+function motionIkReport() {if (!recipe.motion?.ik?.length) return {};const sweeper = agentMotion.compileAgentMotion(recipe.motion, motionRecipe(recipe));@@ -751,6 +826,7 @@ export function createAgentAssetScene(asset, inputRecipe) {exportRecipe() {return structuredClone(recipe);},+ provideMotionSources,sampleMotion(time) {if (time !== null && (!Number.isFinite(time) || time < 0 || time > 3600)) {throw new RangeError('Motion sample time must be null or within zero and 3600.');@@ -895,7 +971,7 @@ export function createAgentAssetScene(asset, inputRecipe) {return sourceNodes.get(id);});const nodes = structuredClone(selected.slice(offset, offset + limit));- return { revision, topologyRevision, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(), ...diagnosticsReport(),+ return { revision, topologyRevision, assetId: canonicalAssetId, kind: 'hierarchy', ...motionIkReport(), ...motionLayerReport(), ...diagnosticsReport(),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-clip-layers.js b/src/agent-clip-layers.jsindex 959dd62d..841d77be 100644--- a/src/agent-clip-layers.js+++ b/src/agent-clip-layers.js@@ -1,4 +1,5 @@import { bounded, denseArray, knownKeys } from './motion-validation.js';+import { retargetReport } from './agent-retarget.js';// Clip layers for an imported asset's motion: play clips the file ships, blend them over each other, and limit each to// some bones. Agent input is untrusted plain data, so everything here is named, bounded and checked against the asset.@@ -21,6 +22,17 @@ export function clipLayerContextFromAsset(animations, nodes) {targets: new Set(animation.tracks.map(track => track.name.slice(0, track.name.lastIndexOf('.')))),})),nodes: nodes.map(({ id, name }) => ({ id, name })),+ hierarchy: nodes,+ external: new Map(),+ };+}++/** What a layer needs of another catalog asset: its clips' durations, its clips and its nodes. Add it to `context.external` by asset ID. */+export function retargetSourceFromAsset(decoded) {+ return {+ clips: decoded.animations.map(animation => ({ duration: animation.duration })),+ animations: decoded.animations,+ nodes: decoded.nodes.map(node => structuredClone(node)),};}@@ -69,12 +81,38 @@ function normalizedBoneMap(input, clip, resolveNode, position) {return Object.fromEntries(resolved);}+/** `from`: a clip of another catalog asset. It must be loaded for this session, and both skeletons must map to the humanoid bones. */+function normalizedSource(input, context, label) {+ knownKeys(input, ['asset', 'clip'], `${label} from`);+ const source = typeof input.asset === 'string' ? context.external.get(input.asset.toLowerCase()) : undefined;+ if (!source) throw new RangeError(`${label} from.asset is not a catalog asset available to this session. Use an asset ID from scene_asset_catalog other than this scene's own.`);+ const clip = source.clips[input.clip];+ if (!Number.isInteger(input.clip) || !clip) throw new RangeError(`${label} from.clip must be the index of a clip in that asset (0 to ${source.clips.length - 1}).`);+ retargetReport(source.nodes, context.hierarchy, label);+ return { from: { asset: input.asset.toLowerCase(), clip: input.clip }, clip };+}+function normalizedLayer(input, position, context, resolveNode) {const label = `Motion layer ${position}`;- knownKeys(input, ['clip', 'loop', 'weight', 'speed', 'offset', 'additive', 'reference', 'mask', 'bones', 'morph'], label);- const clip = context.clips[input.clip];- if (!Number.isInteger(input.clip) || !clip) throw new RangeError(`${label} clip must be the index of a clip in the asset (0 to ${context.clips.length - 1}).`);- const layer = { clip: input.clip };+ knownKeys(input, ['clip', 'from', 'scale', 'rootMotion', 'loop', 'weight', 'speed', 'offset', 'additive', 'reference', 'mask', 'bones', 'morph'], label);+ const layer = {};+ let clip;+ if (input.from !== undefined) {+ if (input.clip !== undefined || input.bones !== undefined || input.morph !== undefined) throw new TypeError(`${label} takes from or clip, and from has no bones or morph.`);+ const sourced = normalizedSource(input.from, context, label);+ clip = sourced.clip;+ layer.from = sourced.from;+ if (input.scale !== undefined) layer.scale = bounded(input.scale, 0.1, 10, `${label} scale`);+ if (input.rootMotion !== undefined) {+ if (typeof input.rootMotion !== 'boolean') throw new TypeError(`${label} rootMotion must be boolean.`);+ layer.rootMotion = input.rootMotion;+ }+ } else {+ clip = context.clips[input.clip];+ if (!Number.isInteger(input.clip) || !clip) throw new RangeError(`${label} clip must be the index of a clip in the asset (0 to ${context.clips.length - 1}).`);+ layer.clip = input.clip;+ if (input.scale !== undefined || input.rootMotion !== undefined) throw new TypeError(`${label} scale and rootMotion only apply to a layer with from.`);+ }for (const flag of ['loop', 'additive', 'morph']) {if (input[flag] === undefined) continue;if (typeof input[flag] !== 'boolean') throw new TypeError(`${label} ${flag} must be boolean.`);diff --git a/src/agent-motion.js b/src/agent-motion.jsindex 7367d251..a82ea539 100644--- a/src/agent-motion.js+++ b/src/agent-motion.js@@ -4,12 +4,15 @@ import { createSkeletonPose } from './skeleton-pose.js';import { createNodeConstraintEvaluator, normalizeConstraints, normalizeDrivers } from './node-constraints.js';import { normalizeClipLayers } from './agent-clip-layers.js';import { normalizeKeyframeEasing } from './easing.js';+import { normalizeFootLock } from './foot-lock.js';import { bounded, denseArray, finite, knownKeys, valueFrom } from './motion-validation.js';const PROPERTIES = {node: { translation: 3, rotation: 4, scale: 3 },material: { color: 3, emissiveColor: 3, emission: 1, metallic: 1, roughness: 1 },camera: { eye: 3, target: 3, fov: 1, roll: 1 },+ // An imported asset's morph target weight, addressed by the target's name.+ morph: { weight: 1 },};const INTERPOLATIONS = ['LINEAR', 'STEP', 'SMOOTH', 'CUBICSPLINE'];const MAX_IK_SOLVERS = 16;@@ -32,6 +35,9 @@ function validateValue(kind, property, value) {throw new RangeError(`Motion ${property} must stay within zero and one.`);}}+ if (kind === 'morph' && components.some(component => component < 0 || component > 1)) {+ throw new RangeError('Motion morph weight must stay within zero and one.');+ }if (kind === 'camera' && property === 'fov' && (Math.fround(value) <= 0 || Math.fround(value) >= 180)) {throw new RangeError('Motion fov must stay between zero and 180 at Float32 precision.');}@@ -277,7 +283,7 @@ export function normalizeAgentMotion(input, recipe) {if (input === null || input === undefined) {return null;}- knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers', 'layers'], 'motion');+ knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers', 'layers', 'footLock'], 'motion');const duration = bounded(input.duration, 0.1, 30, 'Motion duration');const loop = input.loop === undefined ? false : input.loop;if (typeof loop !== 'boolean') {@@ -290,6 +296,7 @@ export function normalizeAgentMotion(input, recipe) {}const nodes = new Set((recipe.nodes ?? []).map(node => node.id));const materials = new Set((recipe.materials ?? []).map(material => material.id));+ const morphTargets = new Set(recipe.morphTargets ?? []);const identities = new Set();let keyframeCount = 0;const tracks = inputTracks.map((track, index) => {@@ -305,9 +312,10 @@ export function normalizeAgentMotion(input, recipe) {if (typeof track.id !== 'string' || !track.id.trim() || track.id.length > 128) {throw new TypeError('Motion target IDs need 1 to 128 characters.');}- const references = track.kind === 'node' ? nodes : materials;+ const references = track.kind === 'node' ? nodes : track.kind === 'morph' ? morphTargets : materials;if (!references.has(track.id)) {- throw new RangeError(`Motion target was not found: ${track.id}.`);+ const hint = track.kind === 'morph' ? ` Morph targets of this asset: ${[...morphTargets].slice(0, 24).join(', ') || 'none'}.` : '';+ throw new RangeError(`Motion target was not found: ${track.id}.${hint}`);}}const identity = JSON.stringify([track.kind, track.id ?? null, track.property]);@@ -344,6 +352,10 @@ export function normalizeAgentMotion(input, recipe) {if (input.layers !== undefined) {result.layers = normalizeClipLayers(input.layers, recipe.clipLayerContext);}+ if (input.footLock !== undefined) {+ if (!result.layers?.length) throw new RangeError('Motion footLock plants the feet of the clips in motion.layers, so it needs layers.');+ result.footLock = normalizeFootLock(input.footLock);+ }if (input.ik !== undefined) {result.ik = normalizeIk(input.ik, recipe, tracks, duration);if (keyframeCount + ikKeyframeCount(result.ik) > 2048) {@@ -508,9 +520,10 @@ export function compileAgentMotion(input, recipe) {})),});const sampler = compileAnimationSampler(clip);- const output = { nodes: new Map(), materials: new Map(), camera: null };+ const output = { nodes: new Map(), materials: new Map(), morphs: new Map(), camera: null };+ const patchesByKind = { node: output.nodes, material: output.materials, morph: output.morphs };const bindings = ordinaryTracks.map((track, index) => {- const patches = track.kind === 'node' ? output.nodes : output.materials;+ const patches = patchesByKind[track.kind];if (!patches.has(track.id)) {patches.set(track.id, {});}diff --git a/src/agent-retarget.js b/src/agent-retarget.jsnew file mode 100644index 00000000..bfd441dc--- /dev/null+++ b/src/agent-retarget.js@@ -0,0 +1,37 @@+import { mapHumanoidBones, retargetClip } from './retarget.js';+import { rigFromAssetNodes } from './skeleton-pose.js';++// Retargeting a clip of one catalog asset onto another for the asset recipe's motion layers. The bone map and the rest-pose+// correction come from retarget.js; this file only adapts decoded asset nodes to it and reports what matched.++const MAX_REPORTED_JOINTS = 24;++function jointNamesOf(nodes) {+ return nodes.filter(node => node.joint).map(node => node.name);+}++/** What the humanoid map does with an asset's joints: how many bones matched, which joints did not, which bones are missing. */+export function humanoidMapReport(nodes) {+ const { mapping, unmapped, missing } = mapHumanoidBones(jointNamesOf(nodes));+ return { mapped: Object.keys(mapping).length, unmapped: unmapped.slice(0, MAX_REPORTED_JOINTS), unmappedCount: unmapped.length, missing };+}++/** Both reports for one retarget, or an error that names the required bones a side lacks. */+export function retargetReport(sourceNodes, targetNodes, label) {+ const source = humanoidMapReport(sourceNodes);+ const target = humanoidMapReport(targetNodes);+ for (const [side, report] of [['source', source], ['target', target]]) {+ if (report.missing.length) {+ throw new RangeError(`${label}: the ${side} asset is not humanoid to the bone map. Missing bones: ${report.missing.join(', ')}. ${report.unmappedCount} joints are unmapped.`);+ }+ }+ return { source, target };+}++/**+ * The source clip (already converted with clipFromGltfAnimation) moved onto the target asset's rest pose. Tracks come back+ * named after the target's joints, so they play like any clip of the target asset.+ */+export function retargetAssetClip(sourceNodes, targetNodes, clip, { scale = 1, rootMotion = true } = {}) {+ return retargetClip(rigFromAssetNodes(sourceNodes), rigFromAssetNodes(targetNodes), clip, { scale, rootMotion });+}diff --git a/src/foot-lock.js b/src/foot-lock.jsnew file mode 100644index 00000000..8b428b6b--- /dev/null+++ b/src/foot-lock.js@@ -0,0 +1,171 @@+import { createSkeletonPose, rigFromAssetNodes } from './skeleton-pose.js';+import { bounded, knownKeys, valueFrom } from './motion-validation.js';++// Foot lock for an asset's layered motion. The clip is sampled once to find when each foot is planted (low and slow), then+// every pose pins that foot where it touched down with the two-bone IK solver and, when a ground is known, lays the sole+// on the ground normal. Everything is a function of time, so a seek gives the same pose as playing.++const ANALYSIS_RATE = 30;+const MINIMUM_CONTACT_FRAMES = 3;+const SIDES = ['left', 'right'];+const DEFAULTS = Object.freeze({ contactHeight: 0.05, contactSpeed: 0.35, blend: 0.1 });++/** `true` or { contactHeight (m above the clip's lowest ankle), contactSpeed (m/s), blend (s), ground: { height, normal } }. */+export function normalizeFootLock(input) {+ if (input === true) return { ...DEFAULTS };+ knownKeys(input, ['contactHeight', 'contactSpeed', 'blend', 'ground'], 'Motion footLock');+ const result = {+ contactHeight: bounded(input.contactHeight ?? DEFAULTS.contactHeight, 0.001, 1, 'footLock contactHeight'),+ contactSpeed: bounded(input.contactSpeed ?? DEFAULTS.contactSpeed, 0.01, 5, 'footLock contactSpeed'),+ blend: bounded(input.blend ?? DEFAULTS.blend, 0.01, 1, 'footLock blend'),+ };+ if (input.ground !== undefined) {+ knownKeys(input.ground, ['height', 'normal'], 'Motion footLock ground');+ const normal = valueFrom(input.ground.normal ?? [0, 1, 0], 3, 'footLock ground normal');+ const length = Math.hypot(...normal);+ if (!(length > 0) || normal[1] / length < 0.5) throw new RangeError('footLock ground normal must point up within 60 degrees of +Y.');+ result.ground = { height: bounded(input.ground.height ?? 0, -1000, 1000, 'footLock ground height'), normal: normal.map(value => value / length) };+ }+ return result;+}++function smoothstep(fraction) {+ return fraction * fraction * (3 - 2 * fraction);+}++/** Contact runs of one foot from its sampled positions: low (within contactHeight of its lowest) and slow, for several frames. */+function contactPhases(positions, settings) {+ const step = 1 / ANALYSIS_RATE;+ const lowest = Math.min(...positions.map(position => position[1]));+ const contact = positions.map((position, index) => {+ const before = positions[Math.max(0, index - 1)];+ const after = positions[Math.min(positions.length - 1, index + 1)];+ const span = (Math.min(positions.length - 1, index + 1) - Math.max(0, index - 1)) * step;+ const speed = Math.hypot(after[0] - before[0], after[2] - before[2]) / span;+ return position[1] - lowest <= settings.contactHeight && speed <= settings.contactSpeed;+ });+ const phases = [];+ let first = null;+ for (let index = 0; index <= contact.length; index++) {+ if (contact[index] && first === null) first = index;+ if (!contact[index] && first !== null) {+ if (index - first >= MINIMUM_CONTACT_FRAMES) phases.push({ first, last: index - 1 });+ first = null;+ }+ }+ return { lowest, phases };+}++/** Where the ankle goes for a phase: where it touched down, or that point put on the ground plane at the clip's standing clearance. */+function plantedPoint(touchdown, lowest, ground) {+ if (!ground) return touchdown;+ const [normalX, normalY, normalZ] = ground.normal;+ const aboveGround = touchdown[0] * normalX + (touchdown[1] - ground.height) * normalY + touchdown[2] * normalZ;+ return ground.normal.map((component, axis) => touchdown[axis] - component * (aboveGround - lowest));+}++/**+ * Foot lock for `nodes` (an asset's decoded nodes) under `layers` (pose layer definitions with clips in the asset's joint+ * names). `rootMatrix` places the asset in the world; the ground is in that world, and the character's own floor is y = 0.+ */+export function createFootLock({ settings, nodes, rootMatrix, layers, duration, loop }) {+ const rig = rigFromAssetNodes(nodes, { rootMatrix });+ const chains = SIDES.map(side => {+ const bones = ['UpperLeg', 'LowerLeg', 'Foot'].map(name => rig.mapping[`${side}${name}`]);+ if (bones.some(bone => bone === undefined)) {+ throw new RangeError(`Motion footLock needs the ${side} leg mapped to the humanoid bones (${side}UpperLeg, ${side}LowerLeg, ${side}Foot). scene_inspect lists the unmapped joints.`);+ }+ return { side, root: bones[0], middle: bones[1], end: bones[2] };+ });+ const idByName = new Map(nodes.map(node => [node.name, node.id]));+ const nodeLayers = layers.map(({ morphs, ...layer }) => layer).filter(layer => layer.clip);+ let plan = null;++ function analyse() {+ const analysisPose = createSkeletonPose({ rig, layers: nodeLayers });+ const frames = Math.max(2, Math.round(duration * ANALYSIS_RATE) + 1);+ const positions = chains.map(() => []);+ for (let frame = 0; frame < frames; frame++) {+ analysisPose.apply(Math.min(duration, frame / ANALYSIS_RATE));+ chains.forEach((chain, slot) => positions[slot].push(analysisPose.jointWorld(chain.end).position));+ }+ return chains.map((chain, slot) => {+ const { lowest, phases } = contactPhases(positions[slot], settings);+ return phases.map(({ first, last }) => ({+ start: first / ANALYSIS_RATE, end: last / ANALYSIS_RATE,+ target: plantedPoint(positions[slot][first], lowest, settings.ground),+ }));+ });+ }++ function planned() {+ plan ??= analyse();+ return plan;+ }++ function clockTime(time) {+ return loop ? time % duration : Math.min(time, duration);+ }++ /** The phase that holds or is about to hold the foot at a time, and how strongly. */+ function holdAt(phases, time) {+ let best = { weight: 0, phase: phases[0] };+ for (const phase of phases) {+ let weight = 0;+ if (time >= phase.start && time <= phase.end) weight = 1;+ else if (time < phase.start && time >= phase.start - settings.blend) weight = smoothstep((time - (phase.start - settings.blend)) / settings.blend);+ else if (time > phase.end && time <= phase.end + settings.blend) weight = smoothstep(1 - (time - phase.end) / settings.blend);+ if (weight > best.weight) best = { weight, phase };+ }+ return best;+ }++ let solver = null;+ function createSolver() {+ const phasesByFoot = planned();+ const definitions = chains.map((chain, slot) => {+ const phases = phasesByFoot[slot];+ return {+ type: 'two-bone', root: chain.root, middle: chain.middle, end: chain.end,+ target: (time, current) => (phases.length ? holdAt(phases, clockTime(time)).phase.target : current),+ weight: time => (phases.length ? holdAt(phases, clockTime(time)).weight : 0),+ ...(settings.ground ? { groundNormal: settings.ground.normal } : {}),+ };+ });+ solver = createSkeletonPose({ rig, ik: definitions });+ return solver;+ }++ return {+ /** Node overrides ({ id, rotation }) that plant the feet in the staged pose ({ id, translation, rotation } per node). */+ solve(time, nodePoses) {+ const pose = solver ?? createSolver();+ const poseById = new Map(nodePoses.map(nodePose => [nodePose.id, nodePose]));+ pose.apply(time, (localRotations, localTranslations) => {+ rig.joints.forEach((joint, index) => {+ const nodePose = poseById.get(idByName.get(joint.name));+ localRotations[index].set(nodePose.rotation);+ localTranslations[index].set(nodePose.translation);+ });+ });+ const phasesByFoot = planned();+ const active = chains.some((chain, slot) => phasesByFoot[slot].length && holdAt(phasesByFoot[slot], clockTime(time)).weight > 0);+ if (!active) return [];+ const indexByName = new Map(rig.joints.map((joint, index) => [joint.name, index]));+ return chains.flatMap(chain => [chain.root, chain.middle, chain.end].map(name => ({+ id: idByName.get(name), rotation: Array.from(pose.localRotation(indexByName.get(name))),+ })));+ },+ /** For scene_inspect: when each foot is planted. */+ report() {+ const phasesByFoot = planned();+ return {+ feet: chains.map((chain, slot) => ({+ bone: `${chain.side}Foot`,+ phases: phasesByFoot[slot].map(phase => ({ start: Number(phase.start.toFixed(3)), end: Number(phase.end.toFixed(3)) })),+ })),+ ...(settings.ground ? { ground: settings.ground } : {}),+ };+ },+ };+}diff --git a/src/gltf.js b/src/gltf.jsindex 971da74b..834dd488 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -118,6 +118,14 @@ function documentFrom(data, maxBytes) {return JSON.parse(new TextDecoder().decode(new Uint8Array(data, 20, jsonLength)));}+/** Morph target names the file gives (extras.targetNames), in target order, or null when it names none. */+function morphTargetNamesOf(document, node, count) {+ const names = document.meshes?.[document.nodes?.[node.association?.nodes]?.mesh]?.extras?.targetNames;+ const valid = Array.isArray(names) && names.length === count && new Set(names).size === count &&+ names.every(name => typeof name === 'string' && name.length > 0 && name.length <= 128);+ return valid ? [...names] : null;+}+function morphCount(mesh) {return mesh?.primitives?.[0]?.targets?.length ?? 0;}@@ -1032,6 +1040,8 @@ export async function parseGltf(data, options = {}) {if (geometry.morphTargets) {const binding = makeMorphBinding(node, geometry, morphMetadata);part.morph = binding.pose;+ const targetNames = morphTargetNamesOf(document, node, binding.pose.weights.length);+ if (targetNames) part.morphTargetNames = targetNames;validateMorphTransform(binding.pose, binding.metadata, part.matrix, part.skin);morphBindings.push({ ...binding, part, pendingMatrix: transformBinding.pendingMatrix, pendingSkin });}diff --git a/src/skeleton-pose.js b/src/skeleton-pose.jsindex ee6a1c4f..c071d8f5 100644--- a/src/skeleton-pose.js+++ b/src/skeleton-pose.js@@ -263,8 +263,12 @@ function createSolver(definition, position, prepared, resolveJoint) {if (definition.pole !== undefined && typeof definition.pole !== 'function') checkedVector(definition.pole, `${label} pole`);const limits = createJointLimits(definition.limits, label, { root, middle }, prepared);const bendToward = definition.bendToward === undefined ? null : vec3.normalize(new Float64Array(3), checkedVector(definition.bendToward, `${label} bendToward`));+ if (definition.groundNormal !== undefined && typeof definition.groundNormal !== 'function') checkedVector(definition.groundNormal, `${label} groundNormal`);return {type: 'two-bone', label, weight, root, middle, end, target: definition.target, pole: definition.pole, limits, bendToward,+ groundNormal: definition.groundNormal,+ // A foot's sole faces up at rest, so this is where "up" sits in the end joint's own frame.+ endUp: vec3.transformQuat(new Float64Array(3), [0, 1, 0], quat.invert(new Float64Array(4), prepared.restWorld.rotations[end])),restBend: restBendInParentFrame(prepared, root, middle, end),keepEndRotation: definition.keepEndRotation !== false,};@@ -371,6 +375,13 @@ function solveTwoBone(solver, time, context) {const limited = applyJointLimits(solver.limits, prepared, localRotations);if (limited.length) update();if (solver.keepEndRotation) setWorldRotation(solver.end, endRotation, weight);+ if (solver.groundNormal !== undefined) {+ // Turn the end joint so its sole lies on the ground: its up axis goes to the normal by the shortest rotation.+ const normal = vec3.normalize(new Float64Array(3), resolvedPoint(solver.groundNormal, time, [0, 1, 0], `${solver.label} groundNormal`));+ const upNow = vec3.transformQuat(new Float64Array(3), solver.endUp, state.rotations[solver.end]);+ const turn = quat.rotationTo(new Float64Array(4), upNow, normal);+ setWorldRotation(solver.end, quat.multiply(new Float64Array(4), turn, state.rotations[solver.end]), weight);+ }const error = vec3.distance(state.positions[solver.end], target);return { reached: error <= margin * 2 + NEAR_ZERO, error, warnings: bendWarnings(solver, state, prepared), limited };}@@ -532,11 +543,13 @@ function evaluateMorphLayers(morphLayers, time) {return [...blended].map(([part, weights]) => ({ part, weights }));}-function rigFromAssetNodes(nodes) {+/** A rig from an asset's decoded nodes. Joints are named as the nodes are; `rootMatrix` places the asset in the world. */+export function rigFromAssetNodes(nodes, { rootMatrix } = {}) {const indexById = new Map(nodes.map((node, index) => [node.id, index]));const jointNames = nodes.filter(node => node.joint).map(node => node.name);return {mapping: mapHumanoidBones(jointNames).mapping,+ ...(rootMatrix ? { rootMatrix } : {}),joints: nodes.map(node => ({name: node.name,parent: node.parent === null ? -1 : indexById.get(node.parent),diff --git a/tests/agent-asset-retarget.test.js b/tests/agent-asset-retarget.test.jsnew file mode 100644index 00000000..e73d41da--- /dev/null+++ b/tests/agent-asset-retarget.test.js@@ -0,0 +1,126 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { parseGltf } from '../src/gltf.js';+import { createAgentAssetScene } from '../src/agent-asset.js';+import { FACE_TARGETS, MIXAMO_LIKE, UNREAL_LIKE, humanoidGlb, humanoidJoints, walkTracks } from './fixtures/humanoid-glb.js';++// Two humanoids that disagree on names, leg proportions and the rest pose of the arms (T-pose against a 30 degree A-pose).+// The source walks with each foot planted for half a cycle; the target is retargeted from it through an asset recipe.+const SOURCE_ID = 'ab'.repeat(32);+const TARGET_ID = 'cd'.repeat(32);+const SOURCE_JOINTS = humanoidJoints();+const TARGET_JOINTS = humanoidJoints({ hipsHeight: 1.1, thigh: 0.62, shin: 0.48, armTiltDegrees: 30 });++const parse = bytes => parseGltf(bytes, { maxVertices: 500000 });++async function sourceAsset() {+ const clips = [{ name: 'Walk', duration: 1, tracks: walkTracks(SOURCE_JOINTS) }];+ return parse(humanoidGlb({ names: MIXAMO_LIKE, joints: SOURCE_JOINTS, clips }));+}++async function createTarget(motion, { names = UNREAL_LIKE } = {}) {+ const asset = await parse(humanoidGlb({ names, joints: TARGET_JOINTS, face: true }));+ const recipe = { format: '67js.asset', schemaVersion: 1, assetId: TARGET_ID, ...(motion ? { motion } : {}) };+ const scene = createAgentAssetScene(asset, recipe,{ sources: { [SOURCE_ID]: await sourceAsset() } });+ const part = name => {+ const index = asset.parts.findIndex(candidate => candidate.name === name);+ assert.ok(index >= 0, `no part ${name}`);+ return scene.parts[index];+ };+ return { asset, scene, part };+}++const walkLayer = (extra = {}) => ({ from: { asset: SOURCE_ID, clip: 0 }, ...extra });+const motionOf = (extra = {}, layerExtra = {}) => ({ duration: 1, loop: true, layers: [walkLayer(layerExtra)], ...extra });+const hierarchyOf = target => target.scene.inspect({ kind: 'hierarchy' });++function footPosition(target, side, time) {+ target.scene.sampleMotion(time);+ return Array.from(target.part(`sole_${side}`).matrix.subarray(12, 15));+}++/** Biggest drift of a foot from where each of the given phases starts, in metres. */+function plantedDrift(target, side, phases) {+ let worst = 0;+ for (const phase of phases) {+ const anchor = footPosition(target, side, phase.start);+ for (let time = phase.start; time <= phase.end + 1e-9; time += 1 / 60) {+ const position = footPosition(target, side, Math.min(time, phase.end));+ worst = Math.max(worst, Math.hypot(position[0] - anchor[0], position[1] - anchor[1], position[2] - anchor[2]));+ }+ }+ return worst;+}++test('a walk from one humanoid file plays on another with different names, proportions and rest pose', async () => {+ const target = await createTarget(motionOf());+ const report = hierarchyOf(target);+ assert.equal(report.retargets.length, 1);+ assert.deepEqual(report.retargets[0].from, { asset: SOURCE_ID, clip: 0 });+ assert.deepEqual(report.retargets[0].source.missing, []);+ assert.deepEqual(report.retargets[0].target.missing, []);+ assert.equal(report.retargets[0].target.mapped, 15);+ const early = footPosition(target, 'left', 0.1);+ const later = footPosition(target, 'left', 0.6);+ assert.ok(Math.hypot(later[0] - early[0], later[2] - early[2]) > 0.2, 'the foot travels with the hips');+});++test('a layer from an unavailable clip, or between rigs without humanoid bones, says what is wrong', async () => {+ await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: 'ee'.repeat(32), clip: 0 } }] }), /not a catalog asset available/);+ await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: SOURCE_ID, clip: 5 } }] }), /from\.clip must be the index/);+ await assert.rejects(createTarget({ duration: 1, layers: [{ from: { asset: SOURCE_ID, clip: 0 }, clip: 0 }] }), /takes from or clip/);+ const broken = await createTarget(undefined, { names: { ...UNREAL_LIKE, leftLowerArm: 'misc', leftHand: 'misc2' } });+ const revision = hierarchyOf(broken).revision;+ assert.throws(() => broken.scene.apply([{ type: 'set-motion', motion: motionOf() }], { expectedRevision: revision }), /not humanoid to the bone map. Missing bones: leftLowerArm/);+});++test('foot lock holds a planted foot within 2 cm where the retargeted walk slides', async () => {+ const settings = { contactHeight: 0.06, contactSpeed: 1.2 };+ const loose = await createTarget(motionOf({}, { scale: 1.25 }));+ const locked = await createTarget(motionOf({ footLock: settings }, { scale: 1.25 }));+ const feet = hierarchyOf(locked).footLock.feet;+ assert.ok(feet.every(foot => foot.phases.length >= 1), JSON.stringify(feet));+ const slide = plantedDrift(loose, 'left', feet[0].phases);+ assert.ok(slide > 0.02, `without the lock the foot slides ${slide}`);+ feet.forEach((foot, slot) => {+ const drift = plantedDrift(locked, ['left', 'right'][slot], foot.phases);+ assert.ok(drift < 0.02, `with the lock the ${foot.bone} slides ${drift}`);+ });+});++test('on a slope the planted sole follows the ground normal', async () => {+ const angle = 10 * Math.PI / 180;+ const normal = [0, Math.cos(angle), -Math.sin(angle)];+ const target = await createTarget(motionOf({ footLock: { contactHeight: 0.06, contactSpeed: 1.2, ground: { height: 0, normal } } }));+ const phase = hierarchyOf(target).footLock.feet[0].phases[0];+ target.scene.sampleMotion((phase.start + phase.end) / 2);+ const sole = target.part('sole_left').matrix;+ const cosine = sole[4] * normal[0] + sole[5] * normal[1] + sole[6] * normal[2];+ const degrees = Math.acos(Math.min(1, cosine)) * 180 / Math.PI;+ assert.ok(degrees < 5, `the sole is ${degrees} degrees off the normal`);+});++test('keyed morph weights blink and open the jaw by target name, and seeking repeats', async () => {+ const motion = {+ duration: 2, loop: false,+ tracks: [+ { kind: 'morph', id: 'eyeBlinkLeft', property: 'weight', keyframes: [{ time: 0.5, value: 0 }, { time: 0.6, value: 1 }, { time: 0.7, value: 0 }] },+ { kind: 'morph', id: 'jawOpen', property: 'weight', interpolation: 'STEP', keyframes: [{ time: 0, value: 0 }, { time: 1, value: 0.5 }] },+ { kind: 'morph', id: 'mouthSmile', property: 'weight', keyframes: [{ time: 0, value: 0, easing: 'easeInQuad' }, { time: 1, value: 1 }] },+ ],+ };+ const target = await createTarget(motion);+ const face = () => Array.from(target.part('Face').morph.weights, weight => Number(weight.toFixed(4)));+ target.scene.sampleMotion(0.6);+ const atBlink = face();+ assert.equal(atBlink[0], 1);+ assert.equal(atBlink[2], 0);+ assert.ok(atBlink[3] > 0 && atBlink[3] < 0.6, `the smile eases in: ${atBlink[3]}`);+ target.scene.sampleMotion(1.5);+ assert.deepEqual(face(), [0, 0, 0.5, 1]);+ target.scene.sampleMotion(0.6);+ assert.deepEqual(face(), atBlink, 'seeking back repeats the earlier weights');+ assert.deepEqual(hierarchyOf(target).morphTargetNames, FACE_TARGETS);+ await assert.rejects(createTarget({ duration: 1, tracks: [{ kind: 'morph', id: 'cheekPuff', property: 'weight', keyframes: [{ time: 0, value: 1 }] }] }), /Morph targets of this asset: eyeBlinkLeft/);+ await assert.rejects(createTarget({ duration: 1, tracks: [{ kind: 'morph', id: 'jawOpen', property: 'weight', keyframes: [{ time: 0, value: 2 }] }] }), /within zero and one/);+});diff --git a/tests/fixtures/humanoid-glb.js b/tests/fixtures/humanoid-glb.jsnew file mode 100644index 00000000..333bf072--- /dev/null+++ b/tests/fixtures/humanoid-glb.js@@ -0,0 +1,172 @@+import { mat4, quat } from 'gl-matrix';+import { createSkeletonPose } from '../../src/skeleton-pose.js';++// Small skinned humanoids for the retargeting tests. Both are built here, so a test can change the proportions, the rest+// pose of the arms and the names without a second file: Mixamo-like names for one, Unreal-like names for the other.++export const MIXAMO_LIKE = {+ hips: 'Hips', spine: 'Spine', head: 'Head',+ leftUpperArm: 'LeftArm', leftLowerArm: 'LeftForeArm', leftHand: 'LeftHand',+ leftUpperLeg: 'LeftUpLeg', leftLowerLeg: 'LeftLeg', leftFoot: 'LeftFoot',+ rightUpperArm: 'RightArm', rightLowerArm: 'RightForeArm', rightHand: 'RightHand',+ rightUpperLeg: 'RightUpLeg', rightLowerLeg: 'RightLeg', rightFoot: 'RightFoot',+};++export const UNREAL_LIKE = {+ hips: 'pelvis', spine: 'spine_01', head: 'head',+ leftUpperArm: 'upperarm_l', leftLowerArm: 'lowerarm_l', leftHand: 'hand_l',+ leftUpperLeg: 'thigh_l', leftLowerLeg: 'calf_l', leftFoot: 'foot_l',+ rightUpperArm: 'upperarm_r', rightLowerArm: 'lowerarm_r', rightHand: 'hand_r',+ rightUpperLeg: 'thigh_r', rightLowerLeg: 'calf_r', rightFoot: 'foot_r',+};++export const FACE_TARGETS = ['eyeBlinkLeft', 'eyeBlinkRight', 'jawOpen', 'mouthSmile'];++/** The skeleton as { key, parent, translation, rotation } in order; parents come first. The first joint is the hips. */+export function humanoidJoints({ hipsHeight = 1, thigh = 0.5, shin = 0.5, armTiltDegrees = 0 } = {}) {+ const joints = [];+ const add = (key, parent, translation, rotation = [0, 0, 0, 1]) => joints.push({ key, parent, translation, rotation }) - 1;+ const hips = add('hips', -1, [0, hipsHeight, 0]);+ const spine = add('spine', hips, [0, 0.2, 0]);+ add('head', spine, [0, 0.5, 0]);+ for (const [side, sign] of [['left', 1], ['right', -1]]) {+ const tilt = Array.from(quat.setAxisAngle(new Float64Array(4), [0, 0, 1], -sign * armTiltDegrees * Math.PI / 180));+ const upperArm = add(`${side}UpperArm`, spine, [sign * 0.2, 0.3, 0], tilt);+ const lowerArm = add(`${side}LowerArm`, upperArm, [sign * 0.3, 0, 0]);+ add(`${side}Hand`, lowerArm, [sign * 0.25, 0, 0]);+ const upperLeg = add(`${side}UpperLeg`, hips, [sign * 0.1, 0, 0]);+ const lowerLeg = add(`${side}LowerLeg`, upperLeg, [0, -thigh, 0]);+ add(`${side}Foot`, lowerLeg, [0, -shin, 0]);+ }+ return joints;+}++/**+ * A walk that plants each foot for half a cycle: the feet's world paths are fixed, the hips move at `speed`, and the+ * engine's own two-bone IK finds the leg rotations. Returns glTF tracks for the clip.+ */+export function walkTracks(joints, { speed = 1.2, duration = 1, kneeLift = 0.12, hipsDrop = 0.08, frameRate = 30 } = {}) {+ const rig = { joints: joints.map(joint => ({ name: joint.key, parent: joint.parent, translation: joint.translation, rotation: joint.rotation, scale: [1, 1, 1] })) };+ const chains = [['left', 0], ['right', 0.5]].map(([side, phase]) => ({ side, phase }));+ const hipsHeight = joints[0].translation[1];+ const footOffsets = Object.fromEntries(['left', 'right'].map(side => [side, joints.find(joint => joint.key === `${side}UpperLeg`).translation[0]]));+ const phase = (time, shift) => time / duration + shift;+ function footTarget(side, shift, time) {+ const whole = Math.floor(phase(time, shift));+ const fraction = phase(time, shift) - whole;+ const centerOfStance = (whole + 0.25 - shift) * duration;+ const planted = speed * centerOfStance;+ if (fraction < 0.5) return [footOffsets[side], 0, planted];+ const swing = (fraction - 0.5) / 0.5;+ const eased = swing * swing * (3 - 2 * swing);+ return [footOffsets[side], kneeLift * Math.sin(Math.PI * swing), planted + speed * duration * eased];+ }+ const ik = chains.map(({ side, phase: shift }) => ({+ type: 'two-bone', root: `${side}UpperLeg`, middle: `${side}LowerLeg`, end: `${side}Foot`, bendToward: [0, 0, 1],+ target: time => footTarget(side, shift, time),+ }));+ const pose = createSkeletonPose({ rig, ik });+ const keyed = ['hips', 'leftUpperLeg', 'leftLowerLeg', 'leftFoot', 'rightUpperLeg', 'rightLowerLeg', 'rightFoot'];+ const indexOf = new Map(joints.map((joint, index) => [joint.key, index]));+ const tracks = new Map(keyed.map(key => [key, { times: [], values: [] }]));+ const frames = Math.round(duration * frameRate);+ for (let frame = 0; frame <= frames; frame++) {+ const time = frame / frameRate;+ pose.apply(time, (_rotations, translations) => translations[0].set([0, hipsHeight - hipsDrop, speed * time]));+ for (const key of keyed) {+ const track = tracks.get(key);+ track.times.push(time);+ track.values.push(...(key === 'hips' ? [0, hipsHeight - hipsDrop, speed * time] : pose.localRotation(indexOf.get(key))));+ }+ }+ return keyed.map(key => ({ joint: key, path: key === 'hips' ? 'translation' : 'rotation', ...tracks.get(key) }));+}++/**+ * A GLB of the humanoid: one skinned triangle over all joints, a small rigid mesh on each foot (named sole_left and+ * sole_right, so a test reads foot positions from their parts), and optionally a face mesh with named morph targets.+ * `clips` is [{ name, duration, tracks: [{ joint, path, times, values }], morphTracks: [{ times, values }] }].+ */+export function humanoidGlb({ names, joints = humanoidJoints(), clips = [], face = false }) {+ const nodes = [{ name: 'Character', children: [] }];+ const worlds = [];+ joints.forEach((joint, index) => {+ const node = { name: names[joint.key], translation: joint.translation, rotation: joint.rotation };+ nodes.push(node);+ if (joint.parent < 0) nodes[0].children.push(index + 1);+ else (nodes[joint.parent + 1].children ??= []).push(index + 1);+ const local = mat4.fromRotationTranslation(mat4.create(), joint.rotation, joint.translation);+ worlds.push(joint.parent < 0 ? local : mat4.multiply(mat4.create(), worlds[joint.parent], local));+ });+ const document = {+ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }], nodes, meshes: [], materials: [{ pbrMetallicRoughness: { baseColorFactor: [0.7, 0.7, 0.8, 1] } }],+ accessors: [], bufferViews: [], buffers: [{ byteLength: 0 }], skins: [], animations: [],+ };+ const chunks = [];+ let offset = 0;+ function append(data, type, extra = {}) {+ const components = { SCALAR: 1, VEC3: 3, VEC4: 4, MAT4: 16 }[type];+ chunks.push(data);+ document.bufferViews.push({ buffer: 0, byteOffset: offset, byteLength: data.byteLength });+ offset += Math.ceil(data.byteLength / 4) * 4;+ document.buffers[0].byteLength = offset;+ document.accessors.push({ bufferView: chunks.length - 1, componentType: data instanceof Uint16Array ? 5123 : 5126, count: data.length / components, type, ...extra });+ return document.accessors.length - 1;+ }+ const triangle = (size, targets) => {+ const attributes = {+ POSITION: append(new Float32Array([-size, 0, 0, size, 0, 0, 0, size, 0]), 'VEC3', { min: [-size, 0, 0], max: [size, size, 0] }),+ NORMAL: append(new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]), 'VEC3'),+ };+ return { attributes, indices: append(new Uint16Array([0, 1, 2]), 'SCALAR'), material: 0, ...(targets ? { targets } : {}) };+ };+ const addMeshNode = (name, mesh, parentIndex, extra = {}) => {+ document.meshes.push({ name, ...mesh });+ nodes.push({ name, mesh: document.meshes.length - 1, ...extra });+ (nodes[parentIndex].children ??= []).push(nodes.length - 1);+ return nodes.length - 1;+ };+ const body = triangle(0.1);+ body.attributes.JOINTS_0 = append(new Uint16Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 'VEC4');+ body.attributes.WEIGHTS_0 = append(new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]), 'VEC4');+ document.skins.push({+ joints: joints.map((_, index) => index + 1), skeleton: 1,+ inverseBindMatrices: append(new Float32Array(worlds.flatMap(world => Array.from(mat4.invert(mat4.create(), world)))), 'MAT4'),+ });+ addMeshNode('Body', { primitives: [body] }, 0, { skin: 0 });+ joints.forEach((joint, index) => {+ if (joint.key.endsWith('Foot')) addMeshNode(`sole_${joint.key.replace('Foot', '')}`, { primitives: [triangle(0.05)] }, index + 1);+ });+ if (face) {+ const headIndex = joints.findIndex(joint => joint.key === 'head') + 1;+ const targets = FACE_TARGETS.map(() => ({ POSITION: append(new Float32Array([0, 0.01, 0, 0, 0.01, 0, 0, 0.01, 0]), 'VEC3', { min: [0, 0.01, 0], max: [0, 0.01, 0] }) }));+ addMeshNode('Face', { primitives: [triangle(0.08, targets)], extras: { targetNames: FACE_TARGETS } }, headIndex);+ nodes[nodes.length - 1].weights = FACE_TARGETS.map(() => 0);+ document.meshes[document.meshes.length - 1].weights = FACE_TARGETS.map(() => 0);+ }+ const nodeIndexOf = new Map(joints.map((joint, index) => [joint.key, index + 1]));+ for (const clip of clips) {+ const animation = { name: clip.name, samplers: [], channels: [] };+ for (const track of clip.tracks) {+ animation.samplers.push({ input: append(new Float32Array(track.times), 'SCALAR', { min: [track.times[0]], max: [track.times.at(-1)] }), output: append(new Float32Array(track.values), track.path === 'rotation' ? 'VEC4' : 'VEC3'), interpolation: 'LINEAR' });+ animation.channels.push({ sampler: animation.samplers.length - 1, target: { node: nodeIndexOf.get(track.joint), path: track.path } });+ }+ document.animations.push(animation);+ }+ const json = new TextEncoder().encode(JSON.stringify(document));+ const jsonLength = Math.ceil(json.length / 4) * 4;+ const result = new ArrayBuffer(28 + jsonLength + offset);+ const header = new DataView(result);+ header.setUint32(0, 0x46546c67, true);+ header.setUint32(4, 2, true);+ header.setUint32(8, result.byteLength, true);+ header.setUint32(12, jsonLength, true);+ header.setUint32(16, 0x4e4f534a, true);+ const bytes = new Uint8Array(result);+ bytes.fill(32, 20, 20 + jsonLength);+ bytes.set(json, 20);+ header.setUint32(20 + jsonLength, offset, true);+ header.setUint32(24 + jsonLength, 0x004e4942, true);+ chunks.forEach((chunk, index) => bytes.set(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength), 28 + jsonLength + document.bufferViews[index].byteOffset));+ return result;+}