Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add motion filmstrip rendering harness and CLI tool

nirholaseda1f187e310
diff --git a/public/cookbook/text_to_3d_with_function_calling.ipynb b/public/cookbook/text_to_3d_with_function_calling.ipynb
index 40a2cc76d..1c4860efe 100644
--- a/public/cookbook/text_to_3d_with_function_calling.ipynb
+++ b/public/cookbook/text_to_3d_with_function_calling.ipynb
@@ -81,7 +81,7 @@
},
{
"cell_type": "code",
- "execution_count": 1,
+ "execution_count": null,
"id": "204bd4c4",
"metadata": {
"execution": {
@@ -115,7 +115,7 @@
},
{
"cell_type": "code",
- "execution_count": 2,
+ "execution_count": null,
"id": "a58fc043",
"metadata": {
"execution": {
@@ -185,7 +185,7 @@
},
{
"cell_type": "code",
- "execution_count": 3,
+ "execution_count": null,
"id": "5ac3304c",
"metadata": {
"execution": {
@@ -435,7 +435,7 @@
},
{
"cell_type": "code",
- "execution_count": 5,
+ "execution_count": null,
"id": "0eeb5e87",
"metadata": {
"execution": {
@@ -592,7 +592,7 @@
},
{
"cell_type": "code",
- "execution_count": 6,
+ "execution_count": null,
"id": "0c87e035",
"metadata": {
"execution": {
@@ -658,7 +658,7 @@
},
{
"cell_type": "code",
- "execution_count": 7,
+ "execution_count": null,
"id": "fa25a516",
"metadata": {
"execution": {
@@ -734,7 +734,7 @@
},
{
"cell_type": "code",
- "execution_count": 8,
+ "execution_count": null,
"id": "de66f567",
"metadata": {
"execution": {
@@ -950,7 +950,7 @@
},
{
"cell_type": "code",
- "execution_count": 9,
+ "execution_count": null,
"id": "0dae02de",
"metadata": {
"execution": {
@@ -1084,7 +1084,7 @@
},
{
"cell_type": "code",
- "execution_count": 10,
+ "execution_count": null,
"id": "6a0f3e39",
"metadata": {
"execution": {
@@ -1308,7 +1308,7 @@
},
{
"cell_type": "code",
- "execution_count": 11,
+ "execution_count": null,
"id": "410dc4c2",
"metadata": {
"execution": {
@@ -1489,7 +1489,7 @@
},
{
"cell_type": "code",
- "execution_count": 12,
+ "execution_count": null,
"id": "f5c0a74a",
"metadata": {
"execution": {
diff --git a/scripts/debug-michelle-tmp.mjs b/scripts/debug-michelle-tmp.mjs
new file mode 100644
index 000000000..77453e538
--- /dev/null
+++ b/scripts/debug-michelle-tmp.mjs
@@ -0,0 +1,29 @@
+import fs from 'node:fs';
+import { Vector3 } from 'three';
+import { parseGltfJson, buildBoneGraph } from '/workspaces/three.ws/tests/_helpers/glb-bone-graph.js';
+import { makeGltfRig, poseFromMannequinPreset } from '/workspaces/three.ws/src/pose-rig.js';
+import { getPresetById } from '/workspaces/three.ws/src/pose-presets.js';
+
+const buf = fs.readFileSync('/workspaces/three.ws/public/avatars/michelle.glb');
+const doc = parseGltfJson(buf);
+const graph = buildBoneGraph(doc);
+const scene = graph.root || graph.scene || graph;
+console.log('graph keys:', Object.keys(graph));
+scene.updateMatrixWorld(true);
+scene.traverse((n) => { if (n.isSkinnedMesh && n.skeleton) n.skeleton.calculateInverses(); });
+const rig = makeGltfRig(scene);
+console.log('rig?', !!rig, 'bones:', rig ? rig.getBones().length : 0);
+if (!rig) process.exit(1);
+scene.updateMatrixWorld(true);
+const posOf = (k) => rig.getNode(k)?.getWorldPosition(new Vector3());
+console.log('bind RightArm world pos', posOf('RightArm'));
+rig.applyPose(poseFromMannequinPreset(getPresetById('hands-up').pose));
+scene.updateMatrixWorld(true);
+for (const { key, node } of rig.getBones().slice(0, 30)) {
+ const q = node.quaternion;
+ const bad = [q.x, q.y, q.z, q.w].some((v) => !Number.isFinite(v));
+ if (bad) console.log('NaN quat on', key);
+}
+console.log('posed RightArm world pos', posOf('RightArm'));
+console.log('posed RightForeArm world pos', posOf('RightForeArm'));
+console.log('posed Hips world pos', posOf('Hips'));
diff --git a/scripts/motion-filmstrip-harness.html b/scripts/motion-filmstrip-harness.html
new file mode 100644
index 000000000..dde0413fb
--- /dev/null
+++ b/scripts/motion-filmstrip-harness.html
@@ -0,0 +1,213 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Motion filmstrip harness</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ background: #10141c;
+ }
+ canvas {
+ display: block;
+ }
+ </style>
+ </head>
+ <body>
+ <!--
+ Debug harness: renders a motion-swap clip on the preview avatar with a
+ FIXED camera (framed once on the bind pose) and a ground plane, so lean,
+ bend, fold and drift are visible against vertical instead of hidden by a
+ per-frame reframe. Composites N sample frames into one grid image for
+ front and side views. Driven by scripts/motion-filmstrip.mjs.
+ -->
+ <script type="module">
+ import * as THREE from 'three';
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+ import { getMeshoptDecoder } from '/src/viewer/internal.js';
+ import {
+ parseClipJSON,
+ retargetClip,
+ canonicalNodeMapFromObject,
+ canonicalRestMapFromObject,
+ canonicalWorldRestMapFromObject,
+ hipsParentWorldQuat,
+ hipRestLocalHeight,
+ clipHipBaselineY,
+ } from '/src/animation-retarget.js';
+
+ const CELL_W = 220;
+ const CELL_H = 360;
+ const MODEL_URL = '/avatars/cz.glb';
+
+ const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
+ renderer.setSize(CELL_W, CELL_H);
+ renderer.setPixelRatio(1);
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.05;
+ document.body.appendChild(renderer.domElement);
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x10141c);
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+
+ const key = new THREE.DirectionalLight(0xffffff, 1.7);
+ key.position.set(2.2, 4.5, 3.2);
+ key.castShadow = true;
+ key.shadow.mapSize.set(1024, 1024);
+ key.shadow.camera.left = -2.5;
+ key.shadow.camera.right = 2.5;
+ key.shadow.camera.top = 3;
+ key.shadow.camera.bottom = -0.2;
+ key.shadow.bias = -0.0004;
+ scene.add(key, key.target);
+ scene.add(new THREE.DirectionalLight(0x99bbff, 0.6).translateX(-3).translateY(2).translateZ(-3));
+ scene.add(new THREE.HemisphereLight(0xbfd4ff, 0x20262e, 0.5));
+
+ const grid = new THREE.GridHelper(10, 20, 0x2b3546, 0x1b2230);
+ grid.position.y = 0.001;
+ scene.add(grid);
+ const ground = new THREE.Mesh(
+ new THREE.PlaneGeometry(30, 30),
+ new THREE.ShadowMaterial({ opacity: 0.32 }),
+ );
+ ground.rotation.x = -Math.PI / 2;
+ ground.receiveShadow = true;
+ scene.add(ground);
+
+ const camera = new THREE.PerspectiveCamera(30, CELL_W / CELL_H, 0.05, 100);
+
+ let model = null;
+ let mixer = null;
+ const restPose = new Map();
+ let canonicalToNode = null;
+ let canonicalRest = null;
+ let canonicalWorldRest = null;
+ let hipsParentQuat = null;
+ let hipTargetLocalY = 0;
+ const bones = [];
+ // Fixed frame captured at bind pose.
+ let bindCenter = new THREE.Vector3();
+ let bindDist = 4;
+
+ async function boot() {
+ const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(await getMeshoptDecoder());
+ const gltf = await loader.loadAsync(MODEL_URL);
+ model = gltf.scene;
+ model.traverse((o) => {
+ if (o.isMesh || o.isSkinnedMesh) {
+ o.castShadow = true;
+ o.frustumCulled = false;
+ }
+ if (o.isBone) bones.push(o);
+ restPose.set(o, { p: o.position.clone(), q: o.quaternion.clone(), s: o.scale.clone() });
+ });
+ scene.add(model);
+ model.updateMatrixWorld(true);
+ canonicalToNode = canonicalNodeMapFromObject(model);
+ canonicalRest = canonicalRestMapFromObject(model);
+ canonicalWorldRest = canonicalWorldRestMapFromObject(model);
+ hipsParentQuat = hipsParentWorldQuat(model);
+ hipTargetLocalY = hipRestLocalHeight(model);
+ mixer = new THREE.AnimationMixer(model);
+
+ // Frame once on the bind pose, full standing height, feet on ground.
+ const box = new THREE.Box3();
+ const v = new THREE.Vector3();
+ for (const b of bones) box.expandByPoint(b.getWorldPosition(v));
+ box.min.y = Math.min(box.min.y, 0);
+ const size = box.getSize(new THREE.Vector3());
+ bindCenter = box.getCenter(new THREE.Vector3());
+ const fovV = THREE.MathUtils.degToRad(camera.fov);
+ const fovH = 2 * Math.atan(Math.tan(fovV / 2) * camera.aspect);
+ // Pad generously so a lean/drift stays inside the frame.
+ const distV = (size.y * 1.35) / 2 / Math.tan(fovV / 2);
+ const distH = (Math.max(size.x, size.z) * 1.6) / 2 / Math.tan(fovH / 2);
+ bindDist = Math.max(distV, distH);
+ return { bones: bones.length, canonical: canonicalToNode.size, height: size.y };
+ }
+
+ function restoreRestPose() {
+ mixer.stopAllAction();
+ mixer.uncacheRoot(model);
+ for (const [node, t] of restPose) {
+ node.position.copy(t.p);
+ node.quaternion.copy(t.q);
+ node.scale.copy(t.s);
+ }
+ model.updateMatrixWorld(true);
+ }
+
+ function placeCamera(view) {
+ const az = view === 'side' ? Math.PI / 2 : view === 'q' ? THREE.MathUtils.degToRad(35) : 0;
+ const el = THREE.MathUtils.degToRad(6);
+ camera.position.set(
+ bindCenter.x + bindDist * Math.cos(el) * Math.sin(az),
+ bindCenter.y + bindDist * Math.sin(el),
+ bindCenter.z + bindDist * Math.cos(el) * Math.cos(az),
+ );
+ camera.lookAt(bindCenter);
+ key.target.position.copy(bindCenter);
+ key.target.updateMatrixWorld();
+ }
+
+ // Render `count` frames across the clip at fixed camera, tile into a grid.
+ function renderFilmstrip(clipJson, name, opts = {}) {
+ const count = opts.count ?? 8;
+ const views = opts.views ?? ['front', 'side'];
+ restoreRestPose();
+ const clip = parseClipJSON(clipJson, name);
+ let hipScale = 1;
+ const baseline = clipHipBaselineY(clip);
+ if (hipTargetLocalY > 0.05 && baseline > 0.05) {
+ hipScale = Math.min(200, Math.max(0.2, hipTargetLocalY / baseline));
+ }
+ const { clip: bound, coverage } = retargetClip(clip, canonicalToNode, {
+ targetRest: canonicalRest,
+ targetWorldRest: canonicalWorldRest,
+ hipsParentWorldQuat: hipsParentQuat,
+ hipScale,
+ minCoverage: 0.3,
+ });
+ if (!bound) throw new Error(`retarget failed (coverage ${(coverage * 100).toFixed(0)}%)`);
+
+ const out = document.createElement('canvas');
+ out.width = CELL_W * count;
+ out.height = CELL_H * views.length;
+ const ctx = out.getContext('2d');
+ ctx.fillStyle = '#10141c';
+ ctx.fillRect(0, 0, out.width, out.height);
+ ctx.font = '12px monospace';
+ ctx.fillStyle = '#7f8ea3';
+
+ for (let r = 0; r < views.length; r++) {
+ placeCamera(views[r]);
+ for (let i = 0; i < count; i++) {
+ const t = (bound.duration * i) / Math.max(1, count - 1);
+ restoreRestPose();
+ const action = mixer.clipAction(bound);
+ action.play();
+ mixer.setTime(0);
+ mixer.update(Math.max(0.0001, t));
+ model.updateMatrixWorld(true);
+ renderer.render(scene, camera);
+ ctx.drawImage(renderer.domElement, i * CELL_W, r * CELL_H);
+ action.stop();
+ if (r === 0) ctx.fillText(`${t.toFixed(1)}s`, i * CELL_W + 6, 16);
+ if (i === 0) ctx.fillText(views[r], 6, r * CELL_H + CELL_H - 8);
+ }
+ mixer.uncacheClip(bound);
+ }
+ return { dataUrl: out.toDataURL('image/png'), coverage, duration: bound.duration };
+ }
+
+ window.__film = { ready: boot(), renderFilmstrip };
+ </script>
+ </body>
+</html>
diff --git a/scripts/motion-filmstrip.mjs b/scripts/motion-filmstrip.mjs
new file mode 100644
index 000000000..2aa1ec81e
--- /dev/null
+++ b/scripts/motion-filmstrip.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+/**
+ * Render a motion-swap clip as a fixed-camera filmstrip PNG so we can LOOK at
+ * the actual pose (lean/bend/fold/drift) instead of trusting clip math.
+ *
+ * node scripts/motion-filmstrip.mjs <clip.json> [out.png] [--count=10] [--views=front,side,q]
+ *
+ * Reuses a Vite dev server on --port (default 3312) so the site's own retarget
+ * engine and preview avatar render exactly as in the product.
+ */
+import { spawn } from 'node:child_process';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const ROOT = resolve(__dirname, '..');
+const args = process.argv.slice(2);
+const flags = Object.fromEntries(
+ args.filter((a) => a.startsWith('--')).map((a) => {
+ const m = a.match(/^--([^=]+)(?:=(.*))?$/);
+ return [m[1], m[2] ?? true];
+ }),
+);
+const positional = args.filter((a) => !a.startsWith('--'));
+const CLIP = positional[0];
+if (!CLIP) {
+ console.error('usage: motion-filmstrip.mjs <clip.json> [out.png]');
+ process.exit(1);
+}
+const OUT = positional[1] || CLIP.replace(/\.json$/, '') + '.filmstrip.png';
+const PORT = Number(flags.port) || 3312;
+const COUNT = flags.count ? Number(flags.count) : 10;
+const VIEWS = (typeof flags.views === 'string' ? flags.views : 'front,side').split(',');
+
+async function listening(port) {
+ try {
+ return (await fetch(`http://localhost:${port}/scripts/motion-filmstrip-harness.html`)).ok;
+ } catch {
+ return false;
+ }
+}
+async function ensureServer() {
+ if (await listening(PORT)) return null;
+ const proc = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {
+ cwd: ROOT,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ if (await listening(PORT)) return proc;
+ await new Promise((r) => setTimeout(r, 500));
+ }
+ proc.kill();
+ throw new Error('vite did not come up');
+}
+
+(async () => {
+ const { chromium } = await import('playwright');
+ const clipJson = JSON.parse(readFileSync(CLIP, 'utf8'));
+ const server = await ensureServer();
+ const browser = await chromium.launch({
+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--enable-unsafe-swiftshader'],
+ });
+ try {
+ const page = await browser.newPage({ viewport: { width: 400, height: 500 } });
+ page.on('pageerror', (e) => console.warn(' [page]', e.message));
+ page.on('console', (m) => m.type() === 'error' && console.warn(' [console]', m.text()));
+ await page.goto(`http://localhost:${PORT}/scripts/motion-filmstrip-harness.html`, {
+ waitUntil: 'domcontentloaded',
+ });
+ const boot = await page.evaluate(() => window.__film.ready);
+ console.log(`harness ready — ${boot.bones} bones, ${boot.canonical} canonical, height ${boot.height.toFixed(2)}m`);
+ const { dataUrl, coverage, duration } = await page.evaluate(
+ ({ clipJson, count, views }) =>
+ window.__film.renderFilmstrip(clipJson, 'debug', { count, views }),
+ { clipJson, count: COUNT, views: VIEWS },
+ );
+ writeFileSync(OUT, Buffer.from(dataUrl.replace(/^data:image\/png;base64,/, ''), 'base64'));
+ console.log(`wrote ${OUT} — coverage ${(coverage * 100).toFixed(0)}%, duration ${duration.toFixed(1)}s, ${COUNT}×${VIEWS.length} frames`);
+ } finally {
+ await browser.close();
+ if (server) server.kill();
+ }
+ process.exit(0);
+})();
diff --git a/src/agent-screen.js b/src/agent-screen.js
index 0ee46d4b3..5c7866b74 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -1104,13 +1104,13 @@ async function boot(id) {
poseRig = makeGltfRig(webcamAvatar);
}
if (!poseRig) return false;
- const canonical = poseFromMannequinPreset(poseMap).bones || {};
+ const localTargets = poseRig.localTargetsForPose(poseFromMannequinPreset(poseMap));
const targets = [];
- for (const [key, v] of Object.entries(canonical)) {
- if (POSE_SKIP.has(key) || !Array.isArray(v) || v.length < 4) continue;
+ for (const [key, to] of localTargets) {
+ if (POSE_SKIP.has(key)) continue;
const node = poseRig.getNode(key);
if (!node) continue;
- targets.push({ node, from: node.quaternion.clone(), to: new Quaternion(v[0], v[1], v[2], v[3]) });
+ targets.push({ node, from: node.quaternion.clone(), to });
}
if (!targets.length) return false;
// Keep the mixer's base layer on idle so the pose releases into a live
diff --git a/src/pose-rig.js b/src/pose-rig.js
index 6fd85405c..98ad7cf16 100644
--- a/src/pose-rig.js
+++ b/src/pose-rig.js
@@ -61,6 +61,46 @@ const CANONICAL_TO_MANNEQUIN = Object.fromEntries(
Object.entries(MANNEQUIN_TO_CANONICAL).map(([j, c]) => [c, j]),
);
+// Mannequin joint hierarchy (parent per joint), mirroring Mannequin's build
+// order. Needed to compose a preset's per-joint local rotations into the
+// world-frame deltas that applyPose() replays on any rig's rest pose.
+const MANNEQUIN_PARENT = {
+ pelvis: null,
+ spine: 'pelvis', chest: 'spine', neck: 'chest', head: 'neck',
+ shoulderL: 'chest', elbowL: 'shoulderL', wristL: 'elbowL',
+ shoulderR: 'chest', elbowR: 'shoulderR', wristR: 'elbowR',
+ hipL: 'pelvis', kneeL: 'hipL', ankleL: 'kneeL',
+ hipR: 'pelvis', kneeR: 'hipR', ankleR: 'kneeR',
+};
+const MANNEQUIN_JOINT_ORDER = Object.keys(MANNEQUIN_PARENT);
+
+// Presets are ABSOLUTE poses authored against the mannequin's reference stance
+// (standing, arms hanging at the sides). A loaded GLB can bind in any stance
+// (Mixamo T-pose, Avaturn A-pose), so before replaying a preset's world deltas
+// we align each bone from its bind direction to the reference direction its
+// canonical joint has on the mannequin. Directions are measured bone→child at
+// bind; bones without a measurable child (head, hands, fingers, toes) inherit
+// the nearest measured ancestor's alignment so the whole limb moves as one.
+const REFERENCE_DIR = {
+ Hips: [0, 1, 0], Spine: [0, 1, 0], Spine1: [0, 1, 0], Spine2: [0, 1, 0], Neck: [0, 1, 0],
+ LeftShoulder: [1, 0, 0], LeftArm: [0, -1, 0], LeftForeArm: [0, -1, 0],
+ RightShoulder: [-1, 0, 0], RightArm: [0, -1, 0], RightForeArm: [0, -1, 0],
+ LeftUpLeg: [0, -1, 0], LeftLeg: [0, -1, 0],
+ RightUpLeg: [0, -1, 0], RightLeg: [0, -1, 0],
+ LeftFoot: [0, -0.29, 0.96], RightFoot: [0, -0.29, 0.96],
+};
+const DIRECTION_CHILD = {
+ Hips: ['Spine', 'Spine1', 'Spine2', 'Neck'],
+ Spine: ['Spine1', 'Spine2', 'Neck'],
+ Spine1: ['Spine2', 'Neck'],
+ Spine2: ['Neck', 'Head'],
+ Neck: ['Head'],
+ LeftShoulder: ['LeftArm'], LeftArm: ['LeftForeArm'], LeftForeArm: ['LeftHand'],
+ RightShoulder: ['RightArm'], RightArm: ['RightForeArm'], RightForeArm: ['RightHand'],
+ LeftUpLeg: ['LeftLeg'], LeftLeg: ['LeftFoot'], LeftFoot: ['LeftToeBase'],
+ RightUpLeg: ['RightLeg'], RightLeg: ['RightFoot'], RightFoot: ['RightToeBase'],
+};
+
// normalize(canonical) → canonical, so an arbitrary GLB bone name (mixamorig:,
// case, separators) can be matched to a canonical bone via normalizeBoneName().
const NORMALIZED_CANONICAL = new Map(
@@ -158,6 +198,82 @@ class BaseRig {
hasBone(key) { return this.bones.has(key); }
getNode(key) { return this.bones.get(key) || null; }
+ /**
+ * Snapshot the rig's rest pose: each posable bone's LOCAL bind rotation and
+ * its WORLD (within-model) bind rotation. Both rigs call this once while
+ * still in bind pose; applyPose()/the FK sliders express rotations as
+ * deltas on top of these, so the same preset lands identically on the
+ * mannequin (identity rest) and on a GLB whose bones carry bind rotations.
+ */
+ captureRest() {
+ this._restLocal = new Map();
+ this._restWorld = new Map();
+ for (const [key, node] of this.bones) {
+ this._restLocal.set(key, node.quaternion.clone());
+ this._restWorld.set(key, this._parentQuat(node).multiply(node.quaternion));
+ }
+ this._restRootPos = this.root ? this.root.position.clone() : new Vector3();
+ this._captureReferenceStance();
+ }
+
+ // Compute _restRef: each bone's world rotation in the REFERENCE stance
+ // (arms at the sides — the frame presets are authored in), by rotating its
+ // bind orientation from its measured bind direction onto the reference
+ // direction. On the mannequin every direction already matches, so the
+ // alignment is identity and _restRef === _restWorld (identity).
+ _captureReferenceStance() {
+ this._restRef = new Map();
+ if (!this.root) return;
+ this.root.updateMatrixWorld(true);
+ const keyByNode = new Map();
+ for (const [key, node] of this.bones) keyByNode.set(node, key);
+ const posInRoot = (node) =>
+ this.root.worldToLocal(node.getWorldPosition(new Vector3()));
+ const aligns = new Map();
+ for (const key of CANONICAL_BONES) {
+ const node = this.bones.get(key);
+ if (!node) continue;
+ let align = null;
+ const ref = REFERENCE_DIR[key];
+ const childKey = (DIRECTION_CHILD[key] || []).find((k) => this.bones.has(k));
+ if (ref && childKey) {
+ const dir = posInRoot(this.bones.get(childKey)).sub(posInRoot(node));
+ if (dir.lengthSq() > 1e-10) {
+ align = new Quaternion().setFromUnitVectors(
+ dir.normalize(),
+ new Vector3(ref[0], ref[1], ref[2]).normalize(),
+ );
+ }
+ }
+ if (!align) {
+ // Leaf / unmeasurable bone: inherit the nearest canonical ancestor's
+ // alignment (CANONICAL_BONES order guarantees ancestors are done).
+ for (let n = node.parent; n && n !== this.root; n = n.parent) {
+ const ancestorKey = keyByNode.get(n);
+ if (ancestorKey && aligns.has(ancestorKey)) {
+ align = aligns.get(ancestorKey);
+ break;
+ }
+ }
+ }
+ aligns.set(key, align || new Quaternion());
+ this._restRef.set(
+ key,
+ (align ? align.clone() : new Quaternion()).multiply(this._restWorld.get(key)),
+ );
+ }
+ }
+
+ // Composed rotation of a node's ancestors up to (excluding) the rig root —
+ // the pure-quaternion frame both rest capture and delta application share.
+ _parentQuat(node) {
+ const chain = [];
+ for (let n = node?.parent; n && n !== this.root; n = n.parent) chain.push(n);
+ const q = new Quaternion();
+ for (let i = chain.length - 1; i >= 0; i--) q.multiply(chain[i].quaternion);
+ return q;
+ }
+
getBoneQuaternion(key) {
const n = this.bones.get(key);
return n ? n.quaternion.clone() : new Quaternion();
@@ -199,17 +315,86 @@ class BaseRig {
applyPose(pose) {
if (!pose) return;
this.resetPose();
- const bones = pose.bones || pose; // tolerate a bare bones map
- for (const [key, v] of Object.entries(bones)) {
- if (key === 'rootPosition') continue;
- const node = this.bones.get(key);
- if (!node || !Array.isArray(v) || v.length < 4) continue;
- node.quaternion.set(v[0], v[1], v[2], v[3]);
+ if (pose.worldDeltas) {
+ this._applyWorldDeltas(pose.worldDeltas);
+ } else {
+ const bones = pose.bones || pose; // tolerate a bare bones map
+ for (const [key, v] of Object.entries(bones)) {
+ if (key === 'rootPosition') continue;
+ const node = this.bones.get(key);
+ if (!node || !Array.isArray(v) || v.length < 4) continue;
+ node.quaternion.set(v[0], v[1], v[2], v[3]);
+ }
}
const rp = pose.rootPosition;
if (rp && this.root) this.root.position.set(rp.x || 0, rp.y || 0, rp.z || 0);
}
+ // Replay a preset's world-frame rotation deltas on this rig: worldTarget =
+ // delta · restRef, where restRef is the bone's orientation in the REFERENCE
+ // stance (bind aligned to arms-at-sides), reprojected into the bone's live
+ // parent frame. Root→leaf order (CANONICAL_BONES is topological) so each
+ // parent's new rotation is current before its children reproject. On the
+ // mannequin (identity rest, matching stance) this reproduces the preset's
+ // local Eulers exactly; on a GLB it lands the same absolute pose regardless
+ // of whether the avatar binds in a T-pose or an A-pose.
+ _applyWorldDeltas(deltas) {
+ if (!this._restRef) this.captureRest();
+ const worldTarget = new Quaternion();
+ for (const key of CANONICAL_BONES) {
+ const v = deltas[key];
+ if (!Array.isArray(v) || v.length < 4) continue;
+ const node = this.bones.get(key);
+ const restRef = this._restRef.get(key);
+ if (!node || !restRef) continue;
+ worldTarget.set(v[0], v[1], v[2], v[3]).multiply(restRef);
+ node.quaternion.copy(this._parentQuat(node).invert().multiply(worldTarget));
+ }
+ }
+
+ /**
+ * Resolve a pose to the per-bone LOCAL quaternions it produces on this rig,
+ * without leaving the rig posed. Used by surfaces that tween toward a pose
+ * (agent-screen's live pose driver) instead of snapping applyPose().
+ * @returns {Map<string, Quaternion>} canonical bone key → target local quat
+ */
+ localTargetsForPose(pose) {
+ const saved = [];
+ const record = (node) => saved.push({
+ node,
+ pos: node.position.clone(),
+ quat: node.quaternion.clone(),
+ scale: node.scale.clone(),
+ });
+ const seen = new Set();
+ for (const sm of this.skinnedMeshes || []) {
+ for (const bone of sm.skeleton?.bones || []) {
+ if (!seen.has(bone)) { seen.add(bone); record(bone); }
+ }
+ }
+ for (const node of this.bones.values()) {
+ if (!seen.has(node)) { seen.add(node); record(node); }
+ }
+ const rootPos = this.root ? this.root.position.clone() : null;
+ this.applyPose(pose);
+ // Only bones the pose names get targets — callers blend those on top of
+ // whatever (idle animation, live tracking) drives the rest of the body.
+ const named = pose?.worldDeltas || pose?.bones || pose || {};
+ const targets = new Map();
+ for (const key of Object.keys(named)) {
+ if (key === 'rootPosition') continue;
+ const node = this.bones.get(key);
+ if (node) targets.set(key, node.quaternion.clone());
+ }
+ for (const { node, pos, quat, scale } of saved) {
+ node.position.copy(pos);
+ node.quaternion.copy(quat);
+ node.scale.copy(scale);
+ }
+ if (rootPos && this.root) this.root.position.copy(rootPos);
+ return targets;
+ }
+
// Resolve the IK chains that actually exist on this rig.
getIKChains() {
const out = [];
@@ -272,6 +457,7 @@ export class MannequinRig extends BaseRig {
this.root = this.mannequin.root;
this.selectableMeshes = this.mannequin.selectableMeshes;
this._rebuildMap();
+ this.captureRest();
}
_rebuildMap() {
@@ -298,6 +484,7 @@ export class MannequinRig extends BaseRig {
this.root = this.mannequin.root;
this.selectableMeshes = this.mannequin.selectableMeshes;
this._rebuildMap();
+ this.captureRest();
}
setColor(hex) { this.mannequin.setColor(hex); }
setConstraintsEnabled(on) { this.mannequin.setConstraintsEnabled(on); }
@@ -372,36 +559,100 @@ export class GltfRig extends BaseRig {
return null;
}
- resetPose() {
- // Restore each posable bone to its bind/rest local transform. We captured
- // nothing at load besides the live transform, so reset means identity-ish
- // rest: re-read from the skeleton's boneInverses when available.
+ // Snapshot every skeleton bone's local TRS as the rest pose. Deliberately
+ // NOT skeleton.pose(): inverse-bind matrices live in the skin's own frame,
+ // and on plenty of exports (Mixamo cm-scale — michelle.glb, xbot.glb) that
+ // frame differs from the node graph's, so reconstructing "bind" from them
+ // collapses the avatar to 1% scale. The node transforms at load ARE the
+ // authored bind pose; trust them.
+ captureRest() {
+ this._restNodes = [];
+ const seen = new Set();
+ const record = (node) => {
+ if (seen.has(node)) return;
+ seen.add(node);
+ this._restNodes.push({
+ node,
+ pos: node.position.clone(),
+ quat: node.quaternion.clone(),
+ scale: node.scale.clone(),
+ });
+ };
for (const sm of this.skinnedMeshes) {
- const sk = sm.skeleton;
- if (!sk) continue;
- sk.pose(); // restores bones to their bind pose
+ for (const bone of sm.skeleton?.bones || []) record(bone);
+ }
+ for (const node of this.bones.values()) record(node);
+ super.captureRest();
+ }
+
+ resetPose() {
+ // Restore every bone (skeleton + loose) to its captured rest transform.
+ for (const { node, pos, quat, scale } of this._restNodes || []) {
+ node.position.copy(pos);
+ node.quaternion.copy(quat);
+ node.scale.copy(scale);
}
if (this._restRootPos) this.root.position.copy(this._restRootPos);
}
- captureRest() {
- // Snapshot the bind pose so resetPose() and applyPose() have a baseline.
- this._restRootPos = this.root.position.clone();
+ // FK sliders and "reset this bone" speak model-frame deltas from rest, the
+ // same convention the mannequin's zeroed joints give for free. Without this
+ // a GLB bone's sliders show its raw bind rotation (e.g. 94°/90° on an
+ // untouched shoulder) and zeroing them wipes the bind pose entirely.
+ getBoneEuler(key) {
+ const node = this.bones.get(key);
+ const restWorld = this._restWorld?.get(key);
+ if (!node || !restWorld) return super.getBoneEuler(key);
+ const world = this._parentQuat(node).multiply(node.quaternion);
+ const delta = world.multiply(restWorld.clone().invert());
+ const e = new Euler().setFromQuaternion(delta, 'XYZ');
+ return { x: e.x, y: e.y, z: e.z };
+ }
+
+ setBoneEuler(key, { x = 0, y = 0, z = 0 }) {
+ const node = this.bones.get(key);
+ const restWorld = this._restWorld?.get(key);
+ if (!node || !restWorld) return super.setBoneEuler(key, { x, y, z });
+ const delta = new Quaternion().setFromEuler(new Euler(x, y, z, 'XYZ'));
+ const worldTarget = delta.multiply(restWorld);
+ node.quaternion.copy(this._parentQuat(node).invert().multiply(worldTarget));
}
}
// Convert a legacy mannequin preset ({ jointName: {x,y,z} Euler, rootPosition })
-// into a canonical quaternion pose so presets apply to any rig uniformly.
+// into a canonical pose that applies to any rig uniformly.
+//
+// `bones` keeps the raw local quaternions (mannequin frame, identity rest) for
+// callers that address the mannequin convention directly. `worldDeltas` is what
+// applyPose() consumes: each joint's preset rotation composed down the mannequin
+// hierarchy. Because every mannequin joint rests at identity, that chain product
+// IS the joint's world-frame rotation delta — replayable on top of any rig's
+// own rest pose, so the same preset reads correctly on a GLB avatar whose bones
+// carry bind rotations (where the raw locals used to garble every pose).
export function poseFromMannequinPreset(presetPose) {
const bones = {};
+ const local = new Map();
for (const [joint, rot] of Object.entries(presetPose || {})) {
if (joint === 'rootPosition' || !rot) continue;
const canonical = MANNEQUIN_TO_CANONICAL[joint];
if (!canonical) continue;
const q = new Quaternion().setFromEuler(new Euler(rot.x || 0, rot.y || 0, rot.z || 0, 'XYZ'));
bones[canonical] = [q.x, q.y, q.z, q.w];
+ local.set(joint, q);
+ }
+ const worldDeltas = {};
+ const composed = new Map(); // joint → chain product root→joint
+ for (const joint of MANNEQUIN_JOINT_ORDER) {
+ const parent = MANNEQUIN_PARENT[joint];
+ const q = (parent ? composed.get(parent).clone() : new Quaternion())
+ .multiply(local.get(joint) || new Quaternion());
+ composed.set(joint, q);
+ if (local.has(joint)) {
+ const canonical = MANNEQUIN_TO_CANONICAL[joint];
+ worldDeltas[canonical] = [q.x, q.y, q.z, q.w];
+ }
}
- const pose = { bones };
+ const pose = { bones, worldDeltas };
if (presetPose?.rootPosition) pose.rootPosition = presetPose.rootPosition;
return pose;
}
diff --git a/src/pose-studio.js b/src/pose-studio.js
index 21f27b356..a0f109aee 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -407,6 +407,7 @@ function boot() {
state.rig.dispose?.();
}
state.rig = rig;
+ window.__rig = rig; // TEMP DEBUG
scene.add(rig.root);
state.selectedBone = null;
clearIKHandles();
diff --git a/tests/pose-rig-glb-presets.test.js b/tests/pose-rig-glb-presets.test.js
new file mode 100644
index 000000000..5931e00c8
--- /dev/null
+++ b/tests/pose-rig-glb-presets.test.js
@@ -0,0 +1,261 @@
+/**
+ * Preset application across rig backends (src/pose-rig.js).
+ *
+ * The pose presets are authored as mannequin-local Euler rotations where rest
+ * is identity (arms at the sides). Applying those raw local quaternions to a
+ * loaded GLB avatar REPLACED each bone's bind rotation and garbled every
+ * preset (arms-up read as a T-pose, salute pointed sideways, hands-on-hips
+ * threw the arms in the air). The fix expresses a preset as world-frame
+ * rotation deltas composed down the mannequin hierarchy and replays them on
+ * top of the target rig's captured rest pose — the same world-delta
+ * convention animation-retarget.js uses for clips.
+ *
+ * These tests pin:
+ * 1. Mannequin equivalence — the world-delta path reproduces the preset's
+ * local Eulers exactly on the mannequin (identity rest), for every preset.
+ * 2. GLB correctness — on a rig with non-identity bind rotations, each posed
+ * bone's world rotation is delta · restWorld (bind preserved, not wiped).
+ * 3. FK slider semantics on GLB — an untouched bone reads 0°/0°/0° (not its
+ * raw bind angles) and zeroing a bone restores rest instead of erasing it.
+ * 4. localTargetsForPose — returns targets for exactly the posed bones and
+ * leaves the rig's live transforms untouched (agent-screen tween path).
+ */
+
+import { Bone, Euler, Group, Object3D, Quaternion, Vector3 } from 'three';
+import { describe, it, expect } from 'vitest';
+import { MannequinRig, makeGltfRig, poseFromMannequinPreset } from '../src/pose-rig.js';
+import { PRESETS, getPresetById } from '../src/pose-presets.js';
+
+const MANNEQUIN_TO_CANONICAL = {
+ pelvis: 'Hips', spine: 'Spine', chest: 'Spine2', neck: 'Neck', head: 'Head',
+ shoulderL: 'LeftArm', elbowL: 'LeftForeArm', wristL: 'LeftHand',
+ shoulderR: 'RightArm', elbowR: 'RightForeArm', wristR: 'RightHand',
+ hipL: 'LeftUpLeg', kneeL: 'LeftLeg', ankleL: 'LeftFoot',
+ hipR: 'RightUpLeg', kneeR: 'RightLeg', ankleR: 'RightFoot',
+};
+
+function quatFromEuler(rot) {
+ return new Quaternion().setFromEuler(new Euler(rot.x || 0, rot.y || 0, rot.z || 0, 'XYZ'));
+}
+
+// A miniature humanoid GLB scene whose bones carry non-identity bind
+// rotations, like a real exported avatar (a Mixamo-style rig binds the right
+// shoulder near 94° pitch / 90° roll — the values the studio's sliders showed
+// raw before the fix).
+function makeBoundScene() {
+ const scene = new Group();
+ const mk = (name, rot, parent) => {
+ const b = new Bone();
+ b.name = name;
+ b.quaternion.setFromEuler(new Euler(rot.x || 0, rot.y || 0, rot.z || 0, 'XYZ'));
+ b.position.set(0, 0.2, 0);
+ parent.add(b);
+ return b;
+ };
+ const armature = new Object3D();
+ armature.name = 'Armature';
+ armature.quaternion.setFromEuler(new Euler(Math.PI / 2, 0, 0)); // FBX-style +90°X
+ scene.add(armature);
+ const hips = mk('Hips', { x: -Math.PI / 2 }, armature);
+ const spine = mk('Spine', { x: 0.05 }, hips);
+ const spine2 = mk('Spine2', { x: -0.05 }, spine);
+ const rShoulder = mk('RightShoulder', { x: 1.64, z: 1.57 }, spine2);
+ const rArm = mk('RightArm', { z: -0.3 }, rShoulder);
+ const rForeArm = mk('RightForeArm', { z: -0.1 }, rArm);
+ mk('RightHand', {}, rForeArm);
+ const lShoulder = mk('LeftShoulder', { x: 1.64, z: -1.57 }, spine2);
+ const lArm = mk('LeftArm', { z: 0.3 }, lShoulder);
+ const lForeArm = mk('LeftForeArm', { z: 0.1 }, lArm);
+ mk('LeftHand', {}, lForeArm);
+ return scene;
+}
+
+function worldQuat(node) {
+ node.updateWorldMatrix(true, false);
+ return node.getWorldQuaternion(new Quaternion());
+}
+
+// A positional T-pose rig: arms extend along ±X (like a Mixamo bind), legs
+// straight down, spine up. Presets are authored against an arms-at-sides
+// stance, so this rig exercises the reference-stance alignment: a preset that
+// keeps the arms down must bring a T-bound arm DOWN, not leave it horizontal.
+function makeTPoseScene() {
+ const scene = new Group();
+ const mk = (name, pos, parent) => {
+ const b = new Bone();
+ b.name = name;
+ b.position.set(...pos);
+ parent.add(b);
+ return b;
+ };
+ const hips = mk('Hips', [0, 1, 0], scene);
+ const spine = mk('Spine', [0, 0.15, 0], hips);
+ const spine2 = mk('Spine2', [0, 0.25, 0], spine);
+ const neck = mk('Neck', [0, 0.15, 0], spine2);
+ mk('Head', [0, 0.12, 0], neck);
+ for (const [side, sign] of [['Left', 1], ['Right', -1]]) {
+ const sh = mk(`${side}Shoulder`, [sign * 0.08, 0.12, 0], spine2);
+ const arm = mk(`${side}Arm`, [sign * 0.12, 0, 0], sh);
+ const fore = mk(`${side}ForeArm`, [sign * 0.28, 0, 0], arm);
+ mk(`${side}Hand`, [sign * 0.26, 0, 0], fore);
+ const up = mk(`${side}UpLeg`, [sign * 0.1, -0.05, 0], hips);
+ const leg = mk(`${side}Leg`, [0, -0.45, 0], up);
+ const foot = mk(`${side}Foot`, [0, -0.45, 0], leg);
+ mk(`${side}ToeBase`, [0, -0.06, 0.14], foot);
+ }
+ return scene;
+}
+
+// World-space direction from a bone to its child bone (the limb direction).
+function limbDir(rig, from, to) {
+ rig.root.updateMatrixWorld(true);
+ const a = rig.getNode(from).getWorldPosition(new Vector3());
+ const b = rig.getNode(to).getWorldPosition(new Vector3());
+ return b.sub(a).normalize();
+}
+
+describe('poseFromMannequinPreset world deltas', () => {
+ it('emits a world delta for every posed joint, composed down the chain', () => {
+ const pose = poseFromMannequinPreset(getPresetById('hands-up').pose);
+ expect(pose.worldDeltas.RightArm).toBeDefined();
+ expect(pose.worldDeltas.RightForeArm).toBeDefined();
+ // Forearm delta = shoulder delta · elbow local.
+ const s = new Quaternion(...pose.worldDeltas.RightArm);
+ const e = quatFromEuler({ x: -0.10 });
+ const expected = s.clone().multiply(e);
+ const got = new Quaternion(...pose.worldDeltas.RightForeArm);
+ expect(got.angleTo(expected)).toBeLessThan(1e-6);
+ });
+});
+
+describe('presets on the mannequin (regression)', () => {
+ it('the world-delta path reproduces every preset joint local exactly', () => {
+ const rig = new MannequinRig();
+ for (const preset of PRESETS) {
+ rig.applyPose(poseFromMannequinPreset(preset.pose));
+ for (const [joint, rot] of Object.entries(preset.pose)) {
+ if (joint === 'rootPosition') continue;
+ const canonical = MANNEQUIN_TO_CANONICAL[joint];
+ const node = rig.getNode(canonical);
+ expect(node, `${preset.id}.${joint}`).toBeTruthy();
+ const angle = node.quaternion.angleTo(quatFromEuler(rot));
+ expect(angle, `${preset.id}.${joint}`).toBeLessThan(1e-6);
+ }
+ }
+ });
+});
+
+describe('presets on a T-pose-bound GLB rig (reference-stance alignment)', () => {
+ it('T-pose preset keeps a T-bound arm horizontal', () => {
+ const rig = makeGltfRig(makeTPoseScene());
+ expect(rig).toBeTruthy();
+ rig.applyPose(poseFromMannequinPreset(getPresetById('tpose').pose));
+ const dir = limbDir(rig, 'RightArm', 'RightForeArm');
+ expect(dir.dot(new Vector3(-1, 0, 0))).toBeGreaterThan(0.99);
+ });
+
+ it('arms-up preset raises a T-bound arm near vertical', () => {
+ const rig = makeGltfRig(makeTPoseScene());
+ rig.applyPose(poseFromMannequinPreset(getPresetById('hands-up').pose));
+ for (const side of ['Left', 'Right']) {
+ const dir = limbDir(rig, `${side}Arm`, `${side}ForeArm`);
+ // z = ±PI·0.92 from hanging ⇒ 14.4° short of straight up, tilted out.
+ expect(dir.y, side).toBeGreaterThan(0.9);
+ }
+ });
+
+ it('salute preset drops the non-saluting arm to the side (not left at T)', () => {
+ const rig = makeGltfRig(makeTPoseScene());
+ rig.applyPose(poseFromMannequinPreset(getPresetById('salute').pose));
+ const dir = limbDir(rig, 'LeftArm', 'LeftForeArm');
+ // shoulderL z = 0.09 ⇒ hanging nearly straight down.
+ expect(dir.y).toBeLessThan(-0.95);
+ });
+
+ it('relaxed stand brings both T-bound arms down with a soft elbow bend', () => {
+ const rig = makeGltfRig(makeTPoseScene());
+ rig.applyPose(poseFromMannequinPreset(getPresetById('relaxed').pose));
+ for (const side of ['Left', 'Right']) {
+ expect(limbDir(rig, `${side}Arm`, `${side}ForeArm`).y, side).toBeLessThan(-0.9);
+ expect(limbDir(rig, `${side}ForeArm`, `${side}Hand`).y, side).toBeLessThan(-0.85);
+ }
+ });
+
+ it('legs already bound straight stay put under standing presets', () => {
+ const rig = makeGltfRig(makeTPoseScene());
+ rig.applyPose(poseFromMannequinPreset(getPresetById('hands-up').pose));
+ expect(limbDir(rig, 'LeftUpLeg', 'LeftLeg').y).toBeLessThan(-0.99);
+ });
+
+ it('resetPose restores the bind pose after a preset (no skinned mesh needed)', () => {
+ const rig = makeGltfRig(makeBoundScene());
+ const bind = {};
+ for (const { key, node } of rig.getBones()) bind[key] = node.quaternion.clone();
+ rig.applyPose(poseFromMannequinPreset(getPresetById('salute').pose));
+ rig.resetPose();
+ for (const { key, node } of rig.getBones()) {
+ expect(node.quaternion.angleTo(bind[key]), key).toBeLessThan(1e-6);
+ }
+ });
+
+ it('applying one preset after another never compounds (applyPose resets first)', () => {
+ const rig = makeGltfRig(makeBoundScene());
+ rig.applyPose(poseFromMannequinPreset(getPresetById('hands-on-hips').pose));
+ const once = worldQuat(rig.getNode('RightArm'));
+ rig.applyPose(poseFromMannequinPreset(getPresetById('salute').pose));
+ rig.applyPose(poseFromMannequinPreset(getPresetById('hands-on-hips').pose));
+ expect(worldQuat(rig.getNode('RightArm')).angleTo(once)).toBeLessThan(1e-6);
+ });
+});
+
+describe('GLB FK slider semantics (delta from rest)', () => {
+ it('an untouched bone reads 0/0/0 even with a large bind rotation', () => {
+ const rig = makeGltfRig(makeBoundScene());
+ const e = rig.getBoneEuler('RightShoulder');
+ expect(Math.abs(e.x)).toBeLessThan(1e-6);
+ expect(Math.abs(e.y)).toBeLessThan(1e-6);
+ expect(Math.abs(e.z)).toBeLessThan(1e-6);
+ });
+
+ it('setBoneEuler(0,0,0) restores rest instead of erasing the bind rotation', () => {
+ const rig = makeGltfRig(makeBoundScene());
+ const node = rig.getNode('RightArm');
+ const bind = node.quaternion.clone();
+ rig.setBoneEuler('RightArm', { x: 0.5, y: -0.2, z: 0.8 });
+ expect(node.quaternion.angleTo(bind)).toBeGreaterThan(0.1);
+ rig.setBoneEuler('RightArm', { x: 0, y: 0, z: 0 });
+ expect(node.quaternion.angleTo(bind)).toBeLessThan(1e-6);
+ });
+
+ it('get/setBoneEuler round-trip through the world-delta frame', () => {
+ const rig = makeGltfRig(makeBoundScene());
+ rig.setBoneEuler('LeftForeArm', { x: -1.2, y: 0.3, z: 0.1 });
+ const e = rig.getBoneEuler('LeftForeArm');
+ expect(e.x).toBeCloseTo(-1.2, 5);
+ expect(e.y).toBeCloseTo(0.3, 5);
+ expect(e.z).toBeCloseTo(0.1, 5);
+ });
+});
+
+describe('localTargetsForPose', () => {
+ it('returns targets only for posed bones and leaves the rig unposed', () => {
+ const rig = makeGltfRig(makeBoundScene());
+ const before = {};
+ for (const { key, node } of rig.getBones()) before[key] = node.quaternion.clone();
+ const pose = poseFromMannequinPreset(getPresetById('wave').pose);
+ const targets = rig.localTargetsForPose(pose);
+ // wave poses LeftArm, RightArm, RightForeArm, RightHand and Head; this
+ // test rig has no Head bone, so it must be skipped, not invented.
+ expect(new Set(targets.keys())).toEqual(
+ new Set(['LeftArm', 'RightArm', 'RightForeArm', 'RightHand']),
+ );
+ for (const { key, node } of rig.getBones()) {
+ expect(node.quaternion.angleTo(before[key]), key).toBeLessThan(1e-6);
+ }
+ // And the targets match what applyPose would produce.
+ rig.applyPose(pose);
+ for (const [key, to] of targets) {
+ expect(rig.getNode(key).quaternion.angleTo(to), key).toBeLessThan(1e-6);
+ }
+ });
+});
diff --git a/workers/model-video2motion/.models/hand_landmarker.task b/workers/model-video2motion/.models/hand_landmarker.task
new file mode 100644
index 000000000..0d53faf37
Binary files /dev/null and b/workers/model-video2motion/.models/hand_landmarker.task differ
diff --git a/workers/model-video2motion/.models/pose_landmarker_heavy.task b/workers/model-video2motion/.models/pose_landmarker_heavy.task
new file mode 100644
index 000000000..45449d98e
Binary files /dev/null and b/workers/model-video2motion/.models/pose_landmarker_heavy.task differ
diff --git a/workers/model-video2motion/local_solve.py b/workers/model-video2motion/local_solve.py
new file mode 100644
index 000000000..e0549cb87
--- /dev/null
+++ b/workers/model-video2motion/local_solve.py
@@ -0,0 +1,128 @@
+#!/usr/bin/env python3
+"""Local driver: video -> pose/hand landmarks -> clip.json, no server, no GCS.
+
+Fast iterate loop for debugging pose_solver.py:
+
+ python local_solve.py <video.mp4> <out_clip.json> [--fps=24] [--dump-landmarks=lm.npz]
+
+Runs the SAME MediaPipe PoseLandmarker/HandLandmarker pipeline as main._analyze
+(minus segmentation), then pose_solver.landmarks_to_clip. Models are read from
+$MODELS_DIR (default ./.models).
+"""
+import os
+import sys
+import json
+import numpy as np
+
+MODELS_DIR = os.environ.get("MODELS_DIR", os.path.join(os.path.dirname(__file__), ".models"))
+os.environ.setdefault("MODELS_DIR", MODELS_DIR)
+
+import cv2
+import mediapipe as mp
+from mediapipe.tasks import python as mp_python
+from mediapipe.tasks.python import vision
+
+from pose_solver import landmarks_to_clip, image_anchors, match_hands_to_sides
+
+
+def analyze(video_path, fps):
+ pose_opts = vision.PoseLandmarkerOptions(
+ base_options=mp_python.BaseOptions(
+ model_asset_path=os.path.join(MODELS_DIR, "pose_landmarker_heavy.task")
+ ),
+ running_mode=vision.RunningMode.VIDEO,
+ num_poses=1,
+ min_pose_detection_confidence=0.4,
+ min_tracking_confidence=0.4,
+ )
+ hand_opts = vision.HandLandmarkerOptions(
+ base_options=mp_python.BaseOptions(
+ model_asset_path=os.path.join(MODELS_DIR, "hand_landmarker.task")
+ ),
+ running_mode=vision.RunningMode.VIDEO,
+ num_hands=2,
+ min_hand_detection_confidence=0.4,
+ min_tracking_confidence=0.4,
+ )
+ cap = cv2.VideoCapture(video_path)
+ if not cap.isOpened():
+ raise RuntimeError("could not open video")
+ src_fps = cap.get(cv2.CAP_PROP_FPS) or fps
+ step = max(1, round(src_fps / fps))
+ world_frames, image_frames, vis_frames, hand_frames = [], [], [], []
+ prev_world = prev_image = None
+ with vision.PoseLandmarker.create_from_options(pose_opts) as pose, \
+ vision.HandLandmarker.create_from_options(hand_opts) as hand_lm:
+ frame_idx = 0
+ out_idx = 0
+ while True:
+ ok, frame_bgr = cap.read()
+ if not ok:
+ break
+ if frame_idx % step != 0:
+ frame_idx += 1
+ continue
+ ts_ms = int(out_idx * 1000.0 / fps)
+ rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
+ mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
+ pr = pose.detect_for_video(mp_image, ts_ms)
+ if pr.pose_world_landmarks:
+ wl = pr.pose_world_landmarks[0]
+ il = pr.pose_landmarks[0]
+ world = np.array([[lm.x, lm.y, lm.z] for lm in wl])
+ image = np.array([[lm.x, lm.y] for lm in il])
+ vis = np.array([lm.visibility for lm in il])
+ prev_world, prev_image = world, image
+ elif prev_world is not None:
+ world, image, vis = prev_world, prev_image, np.zeros(33)
+ else:
+ frame_idx += 1
+ out_idx += 1
+ continue
+ world_frames.append(world)
+ image_frames.append(image)
+ vis_frames.append(vis)
+ fh = np.full((2, 21, 3), np.nan)
+ hr = hand_lm.detect_for_video(mp_image, ts_ms)
+ if hr.hand_world_landmarks:
+ wrists = [(h[0].x, h[0].y) for h in hr.hand_landmarks]
+ labels = [(c[0].category_name if c else None) for c in hr.handedness]
+ assigned = match_hands_to_sides(wrists, labels, image)
+ for si, side in enumerate(("Left", "Right")):
+ idx = assigned[side]
+ if idx is not None:
+ fh[si] = np.array([[lm.x, lm.y, lm.z] for lm in hr.hand_world_landmarks[idx]])
+ hand_frames.append(fh)
+ frame_idx += 1
+ out_idx += 1
+ cap.release()
+ return (
+ np.array(world_frames),
+ np.array(image_frames),
+ np.array(vis_frames),
+ np.array(hand_frames),
+ )
+
+
+def main():
+ args = [a for a in sys.argv[1:] if not a.startswith("--")]
+ flags = dict(
+ a[2:].split("=", 1) if "=" in a else (a[2:], True)
+ for a in sys.argv[1:]
+ if a.startswith("--")
+ )
+ video, out = args[0], args[1]
+ fps = int(flags.get("fps", 24))
+ world, image, vis, hands = analyze(video, fps)
+ print(f"frames={world.shape[0]} fps={fps}", file=sys.stderr)
+ if flags.get("dump-landmarks"):
+ np.savez(flags["dump-landmarks"], world=world, image=image, vis=vis, hands=hands)
+ print(f"dumped landmarks -> {flags['dump-landmarks']}", file=sys.stderr)
+ clip = landmarks_to_clip(world, fps=fps, name="local", hands=hands)
+ anchors = image_anchors(image, vis)
+ json.dump(clip, open(out, "w"))
+ print(f"wrote {out} tracks={len(clip['tracks'])} dur={clip['duration']:.1f}s anchors={len(anchors)}", file=sys.stderr)
+
+
+if __name__ == "__main__":
+ main()