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.

video2motion: hierarchical FK fixes the folded-avatar pose

nirholas89e073b2e551
diff --git a/scripts/motion-filmstrip-harness.html b/scripts/motion-filmstrip-harness.html
index dde0413fb..7294df4d1 100644
--- a/scripts/motion-filmstrip-harness.html
+++ b/scripts/motion-filmstrip-harness.html
@@ -38,8 +38,8 @@
clipHipBaselineY,
} from '/src/animation-retarget.js';
- const CELL_W = 220;
- const CELL_H = 360;
+ let CELL_W = 220;
+ let CELL_H = 360;
const MODEL_URL = '/avatars/cz.glb';
const renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true });
@@ -161,6 +161,15 @@
function renderFilmstrip(clipJson, name, opts = {}) {
const count = opts.count ?? 8;
const views = opts.views ?? ['front', 'side'];
+ if (opts.cellW) {
+ CELL_W = opts.cellW;
+ CELL_H = opts.cellH ?? Math.round(opts.cellW * 1.6);
+ renderer.setSize(CELL_W, CELL_H);
+ camera.aspect = CELL_W / CELL_H;
+ camera.updateProjectionMatrix();
+ }
+ const t0 = opts.t0 ?? 0;
+ const t1 = opts.t1 ?? null; // null → full duration
restoreRestPose();
const clip = parseClipJSON(clipJson, name);
let hipScale = 1;
@@ -186,19 +195,31 @@
ctx.font = '12px monospace';
ctx.fillStyle = '#7f8ea3';
+ const hi = t1 == null ? bound.duration : Math.min(t1, bound.duration);
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);
+ const t = t0 + ((hi - t0) * i) / Math.max(1, count - 1);
restoreRestPose();
const action = mixer.clipAction(bound);
+ action.setLoop(THREE.LoopOnce);
+ action.clampWhenFinished = true;
action.play();
mixer.setTime(0);
- mixer.update(Math.max(0.0001, t));
+ // Sample just shy of duration so the mixer doesn't loop-wrap to
+ // frame 0 at exactly t=duration.
+ mixer.update(Math.min(bound.duration - 1e-3, Math.max(0.0001, t)));
model.updateMatrixWorld(true);
renderer.render(scene, camera);
ctx.drawImage(renderer.domElement, i * CELL_W, r * CELL_H);
action.stop();
+ // Plumb line: faint vertical through the cell centre so any
+ // lean off true vertical is measurable by eye.
+ ctx.strokeStyle = 'rgba(255,80,80,0.35)';
+ ctx.beginPath();
+ ctx.moveTo(i * CELL_W + CELL_W / 2, r * CELL_H);
+ ctx.lineTo(i * CELL_W + CELL_W / 2, r * CELL_H + CELL_H);
+ ctx.stroke();
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);
}
diff --git a/scripts/motion-filmstrip.mjs b/scripts/motion-filmstrip.mjs
index 2aa1ec81e..ae1d7c1ff 100644
--- a/scripts/motion-filmstrip.mjs
+++ b/scripts/motion-filmstrip.mjs
@@ -70,14 +70,24 @@ async function ensureServer() {
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`);
+ console.log(`harness ready: ${boot.bones} bones, ${boot.canonical} canonical, height ${boot.height.toFixed(2)}m`);
+ const range = typeof flags.range === 'string' ? flags.range.split(',').map(Number) : [];
const { dataUrl, coverage, duration } = await page.evaluate(
- ({ clipJson, count, views }) =>
- window.__film.renderFilmstrip(clipJson, 'debug', { count, views }),
- { clipJson, count: COUNT, views: VIEWS },
+ ({ clipJson, count, views, opts }) =>
+ window.__film.renderFilmstrip(clipJson, 'debug', { count, views, ...opts }),
+ {
+ clipJson,
+ count: COUNT,
+ views: VIEWS,
+ opts: {
+ cellW: flags.cell ? Number(flags.cell) : undefined,
+ t0: range[0],
+ t1: range[1],
+ },
+ },
);
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`);
+ 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();
diff --git a/workers/model-video2motion/pose_solver.py b/workers/model-video2motion/pose_solver.py
index ea4d9c71e..18709a4c0 100644
--- a/workers/model-video2motion/pose_solver.py
+++ b/workers/model-video2motion/pose_solver.py
@@ -17,7 +17,10 @@ Method: per frame,
direction onto the observed parent→child landmark direction, using the
limb's bend plane (upper/lower segment cross product) to fix the twist
about the bone axis where the geometry defines it,
- 4. convert globals to locals against the parent chain,
+ 4. convert the per-bone globals to canonical-rig LOCALS by hierarchical
+ forward kinematics: each child is resolved against its parent's ANIMATED
+ world (not its rest world), so a swinging chain (upper arm to forearm)
+ stays intact instead of folding by the parent's rotation,
5. smooth landmarks with a fps-aware exponential filter and keep quaternion
hemisphere continuity across frames.
@@ -265,8 +268,16 @@ _BODY_PARENTS = {
"Neck": "Spine2", "Head": "Neck",
"LeftUpLeg": "Hips", "LeftLeg": "LeftUpLeg", "LeftFoot": "LeftLeg",
"RightUpLeg": "Hips", "RightLeg": "RightUpLeg", "RightFoot": "RightLeg",
- "LeftArm": "Spine2", "LeftForeArm": "LeftArm", "LeftHand": "LeftForeArm",
- "RightArm": "Spine2", "RightForeArm": "RightArm", "RightHand": "RightForeArm",
+ # The canonical (Wolf3D/Mixamo) skeleton has a clavicle bone between the
+ # chest and the upper arm: Spine2 → {Left,Right}Shoulder → {Left,Right}Arm.
+ # The arm's canonical LOCAL rest is expressed relative to that clavicle, so
+ # _to_canonical_local must transport the world delta through the clavicle's
+ # rest frame, not Spine2's. Using Spine2 as the parent skipped the ~120°
+ # clavicle rotation and sent every arm pose off by that much (arms folded up
+ # by the head). The solver does not animate the clavicle (it barely moves in
+ # real motion), so its rest world orientation is the correct fixed frame.
+ "LeftArm": "LeftShoulder", "LeftForeArm": "LeftArm", "LeftHand": "LeftForeArm",
+ "RightArm": "RightShoulder", "RightForeArm": "RightArm", "RightHand": "RightForeArm",
}
_ALL_PARENTS = {**_BODY_PARENTS, **_FINGER_PARENTS}
@@ -342,22 +353,65 @@ def _rest_globals() -> dict:
return _REST_GLOBALS_CACHE
-def _to_canonical_local(bone: str, g: np.ndarray, rest_globals: dict) -> np.ndarray:
- """World orientation `g` of `bone` → canonical-convention local keyframe."""
- rs = REST_LOCAL.get(bone)
- if rs is None:
- return _IDENTITY.copy()
- rs = np.asarray(rs, dtype=np.float64)
+def _canonical_world_anim(bone: str, globals_: dict, rest_globals: dict, cache: dict) -> np.ndarray:
+ """Animated WORLD orientation of `bone` on the canonical rig.
+
+ A bone the solver observed this frame is rotated from its canonical rest
+ world by the physical world delta it underwent from ITS OWN rest
+ (delta = g · grest⁻¹, frame-independent). A bone the solver does not drive
+ (the clavicles, an undetected finger) rides its animated parent at its bind
+ local, so it follows the torso/hand instead of freezing in world space.
+ """
+ cached = cache.get(bone)
+ if cached is not None:
+ return cached
+ wr = REST_WORLD.get(bone)
+ if wr is None:
+ cache[bone] = _IDENTITY.copy()
+ return cache[bone]
+ wr = np.asarray(wr, dtype=np.float64)
+ g = globals_.get(bone)
grest = rest_globals.get(bone)
- if grest is None:
- return rs
- # D = g · grest⁻¹ (physical world delta from rest)
- delta = _quat_multiply(g, _quat_conjugate(grest))
- parent = _ALL_PARENTS.get(bone)
- wsp = np.asarray(REST_WORLD[parent], dtype=np.float64) if parent else _IDENTITY
- wsp_inv = _quat_conjugate(wsp)
- q = _quat_multiply(_quat_multiply(_quat_multiply(wsp_inv, delta), wsp), rs)
- return _quat_normalize(q)
+ if g is not None and grest is not None:
+ delta = _quat_multiply(g, _quat_conjugate(grest))
+ w = _quat_multiply(delta, wr)
+ else:
+ parent = _ALL_PARENTS.get(bone)
+ rl = np.asarray(REST_LOCAL.get(bone, _IDENTITY), dtype=np.float64)
+ w = _quat_multiply(_canonical_world_anim(parent, globals_, rest_globals, cache), rl) if parent else wr
+ w = _quat_normalize(w)
+ cache[bone] = w
+ return w
+
+
+def _globals_to_canonical_locals(globals_: dict, rest_globals: dict, bones: list) -> dict:
+ """Batch-convert a frame of solver world orientations → canonical-rig LOCAL
+ keyframes via true hierarchical FK.
+
+ Each bone's local is taken against its parent's ANIMATED world, not its rest
+ world. This is the difference that keeps a swinging chain intact: the
+ forearm's parent (the upper arm) rotates up to 180° in real motion, so
+ resolving the forearm against the arm's REST frame folds it by that much
+ (hands snapping to the head). Resolving it against the arm's animated frame
+ keeps the elbow where the video puts it.
+ """
+ cache: dict = {}
+ out = {}
+ for bone in bones:
+ wb = _canonical_world_anim(bone, globals_, rest_globals, cache)
+ parent = _ALL_PARENTS.get(bone)
+ if parent is None:
+ # Armature offset A = W_rest · L_rest⁻¹ (identity when the root sits
+ # at world origin); L_root = A⁻¹ · W_anim keeps the root track in the
+ # model's own root-local frame.
+ wr = np.asarray(REST_WORLD.get(bone, _IDENTITY), dtype=np.float64)
+ rl = np.asarray(REST_LOCAL.get(bone, _IDENTITY), dtype=np.float64)
+ a_inv = _quat_conjugate(_quat_multiply(wr, _quat_conjugate(rl)))
+ out[bone] = _quat_normalize(_quat_multiply(a_inv, wb))
+ else:
+ wp = _canonical_world_anim(parent, globals_, rest_globals, cache)
+ out[bone] = _quat_normalize(_quat_multiply(_quat_conjugate(wp), wb))
+ return out
def _smooth_quaternion_track(values: np.ndarray, fps: float) -> np.ndarray:
@@ -395,6 +449,48 @@ def _smooth_quaternion_track(values: np.ndarray, fps: float) -> np.ndarray:
return out
+def _hold_unsettled_ends(world: np.ndarray, max_frames: int = 12) -> np.ndarray:
+ """Replace leading/trailing frames from before MediaPipe's tracker locked on
+ with the first/last settled frame.
+
+ The VIDEO-mode landmarker needs a frame or two to converge, and the tail of
+ a clip can end on a half-lost detection. Those frames read as a body that
+ teleports (limbs flung, torso inverted) for ~0.1s at each end. We can't drop
+ them (the compositor pins clip frame t to video frame t via the anchors),
+ so we HOLD the nearest settled pose instead, keeping the frame count and
+ timing intact. A frame is "unsettled" when its whole-body jump to its
+ neighbour is a gross outlier (teleport) versus the clip's median jump.
+ """
+ world = np.asarray(world, dtype=np.float64)
+ n = world.shape[0]
+ if n < 5:
+ return world
+ jump = np.linalg.norm(np.diff(world, axis=0), axis=2).mean(axis=1) # (n-1,)
+ med = float(np.median(jump))
+ # A mostly-static clip has median jump ≈ 0; fall back to the absolute floor
+ # so a genuine lock-on teleport is still caught rather than skipped.
+ thresh = max(6.0 * med, 0.15)
+ cap = min(max_frames, n // 4)
+ out = world.copy()
+ # A lock-on failure often repeats the same bad frame (no detection reuses the
+ # previous frame), so the teleport is the jump OUT of the garbage, not into
+ # it. Hold everything up to the frame after the LAST leading teleport within
+ # the window (and symmetrically at the tail), not just the first.
+ lead_settle = 0
+ for k in range(min(cap, jump.shape[0])):
+ if jump[k] > thresh:
+ lead_settle = k + 1
+ for t in range(lead_settle):
+ out[t] = world[lead_settle]
+ tail_settle = 0
+ for k in range(min(cap, jump.shape[0])):
+ if jump[n - 2 - k] > thresh:
+ tail_settle = k + 1
+ for t in range(tail_settle):
+ out[n - 1 - t] = world[n - 1 - tail_settle]
+ return out
+
+
def smooth_landmarks(world: np.ndarray, fps: float, cutoff_hz: float = 4.0) -> np.ndarray:
"""fps-aware exponential smoothing over the time axis of (T, 33, 3)."""
world = np.asarray(world, dtype=np.float64)
@@ -706,6 +802,7 @@ def landmarks_to_clip(
sides.append(seq)
rig = _to_rig_space(world)
+ rig = _hold_unsettled_ends(rig)
if smooth:
rig = smooth_landmarks(rig, fps)
@@ -722,17 +819,14 @@ def landmarks_to_clip(
for si, side in enumerate(("Left", "Right"))
}
sol = solve_frame(rig[t], prev_solution, frame_hands)
+ # Author in the canonical rig convention via hierarchical FK (see
+ # _globals_to_canonical_locals), not the solver's own T-pose frame, so
+ # the browser retarget round-trips instead of folding the skeleton, and
+ # each child resolves against its parent's ANIMATED pose (the fix that
+ # keeps forearms/lower legs from snapping when the parent swings).
+ locals_canon = _globals_to_canonical_locals(sol["globals"], rest_globals, track_bones)
for bone in track_bones:
- # Author in the canonical rig convention (see _to_canonical_local),
- # not the solver's own T-pose frame, so the browser retarget
- # round-trips instead of folding the skeleton. A held bone (no global
- # this frame, e.g. an undetected finger) rests at its bind local.
- gb = sol["globals"].get(bone)
- if gb is None:
- q = np.asarray(REST_LOCAL.get(bone, _IDENTITY), dtype=np.float64)
- else:
- q = _to_canonical_local(bone, gb, rest_globals)
- q = _hemisphere(prev_quats.get(bone), q)
+ q = _hemisphere(prev_quats.get(bone), locals_canon[bone])
prev_quats[bone] = q
per_bone[bone].append(q)
prev_solution = sol
diff --git a/workers/model-video2motion/test_pose_solver.py b/workers/model-video2motion/test_pose_solver.py
index 002a50ac7..32cf4b799 100644
--- a/workers/model-video2motion/test_pose_solver.py
+++ b/workers/model-video2motion/test_pose_solver.py
@@ -263,6 +263,67 @@ def test_rest_pose_emits_canonical_bind_local():
assert abs(up[3]) < 0.1, "LeftUpLeg bind must be a large rotation, not identity"
+def _canonical_fk_dir(clip, bone, start, chain):
+ """World direction of `bone` when the clip's first frame is applied to the
+ canonical rig, starting from `start`'s rest world and walking `chain`
+ (each bone's authored local; clavicles fall back to their bind local).
+ Returns the unit world dir of the bone's rest axis (+X for arms in the
+ T-pose rest)."""
+ from canonical_rest import REST_LOCAL, REST_WORLD
+ import pose_solver as ps
+
+ tracks = {t["name"].split(".")[0]: t for t in clip["tracks"]}
+
+ def local(b):
+ if b in tracks:
+ return np.asarray(tracks[b]["values"]).reshape(-1, 4)[0]
+ return np.asarray(REST_LOCAL[b], float)
+
+ w = np.asarray(REST_WORLD[start], float)
+ for b in chain:
+ w = ps._quat_multiply(w, local(b))
+ axl = ps._rotate_vec(ps._quat_conjugate(np.asarray(REST_WORLD[bone], float)), np.array([1.0, 0, 0]))
+ return ps._rotate_vec(w, axl)
+
+
+def test_arm_hang_down_does_not_fold():
+ """The regression that broke the feature: with the arm hanging straight down,
+ the forearm must also point DOWN. Resolving a child against its parent's REST
+ frame (instead of its animated frame) folded the elbow ~90-180°, snapping the
+ hand up to the head. Author a full clip and forward-kinematic the canonical
+ arm chain to prove the elbow stays where the video put it."""
+ p = t_pose_world()
+ # Left arm hanging straight down (y-down world: down = positive y), wrist
+ # below elbow below shoulder.
+ p[LEFT_ELBOW] = [0.20, -0.25, 0.0]
+ p[LEFT_WRIST] = [0.20, 0.00, 0.0]
+ p[LEFT_INDEX] = [0.20, 0.10, 0.0]
+ p[LEFT_PINKY] = [0.22, 0.10, 0.02]
+ clip = landmarks_to_clip(np.stack([p] * 4), fps=24, name="hang")
+ # Chain from Spine2 (rest) through the (unanimated) clavicle to the arm.
+ arm = _canonical_fk_dir(clip, "LeftArm", "Spine2", ["LeftShoulder", "LeftArm"])
+ fore = _canonical_fk_dir(clip, "LeftForeArm", "Spine2", ["LeftShoulder", "LeftArm", "LeftForeArm"])
+ # -Y is straight down in the rig (y-up) space.
+ assert arm[1] < -0.9, f"upper arm should hang down, got {np.round(arm,2)}"
+ assert fore[1] < -0.9, f"forearm should hang down (no fold), got {np.round(fore,2)}"
+
+
+def test_unsettled_boundary_frames_are_held():
+ """A garbage lock-on frame at the very start (and its no-detection repeat)
+ must be replaced by the first settled pose, not left inverting the body."""
+ from pose_solver import _hold_unsettled_ends
+
+ good = t_pose_world()
+ seq = np.stack([good] * 20)
+ # Frame 0 garbage + frame 1 a verbatim repeat (mediapipe reuses the previous
+ # frame when it detects nothing) → the teleport is 1→2, not 0→1.
+ seq[0] = good + 3.0
+ seq[1] = seq[0].copy()
+ held = _hold_unsettled_ends(seq)
+ assert np.allclose(held[0], good) and np.allclose(held[1], good), "leading garbage not held"
+ assert np.allclose(held[5], good), "interior frame must be untouched"
+
+
def test_clip_without_hands_unchanged():
frames = np.stack([t_pose_world()] * 4)
clip = landmarks_to_clip(frames, fps=24, name="nohands")