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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
video2motion: capture hands and solve all 30 finger bones
nirholas74733129a2fa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 20c5e38f6..6b4148976 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Concierge ships to npm and the MCP registry, with a full examples set** — The Concierge chat widget is now installable as the @three-ws/concierge npm package, and there is a companion Model Context Protocol server, @three-ws/concierge-mcp, on the official MCP registry. That server lets any AI assistant ask a website's concierge a question (it fetches the page and answers grounded in the real content), generate the copy-paste embed code for a site, and list the available 3D avatars. Six runnable examples now ship with the SDK, covering the one-tag install, the web component, the imperative API, a custom GLB avatar, a React wrapper, and pointing the widget at your own answer backend. (`/docs/concierge`) `[sdk, docs]`- **First autonomous agent trade, fully documented** — A platform agent closed its first fully autonomous trade: it sniped a brand-new pump.fun launch from its own wallet and exited at +42.38 percent, with every decision recorded on its hash-chained ledger. We published the complete postmortem: a blog post with the on-chain receipts, a deep-dive doc on the sniper architecture (entry gates, the simulate-the-sell trade firewall, the exit ladder), and a tutorial for arming a sniper on your own agent, including the take-profit lesson this trade taught us. (`/blog/first-autonomous-trade`) `[feature, docs]`- **Language links now always win, and the switcher stays out of the way** — Two fixes for the new 41-language experience. Opening a link with a language in the URL (like ?lang=te for Telugu) now always shows that language, even if you had previously browsed in another one; before, your first visit's language silently overrode every shared link. The floating language switcher also joins the site's shared bottom-corner layout, so it no longer overlaps the Getting Started guide. (`/what-is?lang=te`) `[fix, improvement]`+- **Motion Swap now captures hands and fingers** — Motion capture from video just got hands. When you swap yourself for your avatar at /motion-swap, the capture now tracks both hands (21 points each) and solves every finger joint, so waves, counting, pointing, and sign-language handshapes come through on your avatar instead of a stiff flat hand. Wrist rotation is also solved from the palm itself, making hand orientation far more faithful. Works with any rigged avatar; if your hands leave the frame the capture holds the last hand pose instead of snapping flat. (`/motion-swap`) `[improvement]`- **Motion Swap: replace yourself in a video with your 3D avatar** — Upload a video of yourself (a house tour, a demo, a walk-through) at /motion-swap and get it back with your avatar performing your exact motion instead of you. The platform tracks your body pose in every frame, masks you out, and pins your chosen avatar over you, matching your position and size; you stay pixelated underneath. Compositing and video export run right in your browser, and any rigged humanoid GLB works, including avatars you generated or captured from a selfie. (`/motion-swap`) `[feature]`- **Switch any coin chart between CoinGecko, TradingView, DexScreener, and GeckoTerminal** — The chart on every /coin page now has a source switcher. Start on the fast native CoinGecko line chart, then flip to TradingView's advanced candlesticks, or to the DexScreener or GeckoTerminal on-chain terminal for the token's live DEX pair. Each option only appears when it can actually chart that coin, your pick is remembered across coins and visits, and every view follows the site theme. (`/coin/bitcoin`) `[feature, improvement]`- **The assistant widget ships as an npm package and an MCP server** — The 3D avatar assistant widget is now installable three ways. Beyond the one-tag script, there is an npm package, @three-ws/assistant, for bundler projects (the one-tag build is generated from it, so they never drift), and a free MCP server, @three-ws/assistant-mcp, published to the official Model Context Protocol registry as io.github.nirholas/assistant-widget. Any AI agent (Claude Code, Cursor, Claude Desktop) can now ask for a widget in plain language and get back a paste-ready embed: build_assistant_widget turns a config into a script tag, a frame URL, and a ThreeAssistant.init() call, and list_assistant_options returns every avatar, background, and mode. Full developer docs at /docs/assistant-widget and a step-by-step tutorial walk through every option, the JavaScript API, and the agent workflow. (`/docs/assistant-widget`) `[sdk, feature, docs]`diff --git a/data/changelog.json b/data/changelog.jsonindex 3a67349c7..5cce70913 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -14856,6 +14856,15 @@"feature"],"link": "/motion-swap"+ },+ {+ "date": "2026-07-19",+ "title": "Motion Swap now captures hands and fingers",+ "summary": "Motion capture from video just got hands. When you swap yourself for your avatar at /motion-swap, the capture now tracks both hands (21 points each) and solves every finger joint, so waves, counting, pointing, and sign-language handshapes come through on your avatar instead of a stiff flat hand. Wrist rotation is also solved from the palm itself, making hand orientation far more faithful. Works with any rigged avatar; if your hands leave the frame the capture holds the last hand pose instead of snapping flat.",+ "tags": [+ "improvement"+ ],+ "link": "/motion-swap"}]}diff --git a/public/changelog.json b/public/changelog.jsonindex fbe641137..699ba8ad2 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T07:10:14.653Z",+ "generated_at": "2026-07-19T13:30:32.383Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -103,6 +103,16 @@"improvement"]},+ {+ "date": "2026-07-19",+ "type": "update",+ "title": "Motion Swap now captures hands and fingers",+ "summary": "Motion capture from video just got hands. When you swap yourself for your avatar at /motion-swap, the capture now tracks both hands (21 points each) and solves every finger joint, so waves, counting, pointing, and sign-language handshapes come through on your avatar instead of a stiff flat hand. Wrist rotation is also solved from the palm itself, making hand orientation far more faithful. Works with any rigged avatar; if your hands leave the frame the capture holds the last hand pose instead of snapping flat.",+ "link": "/motion-swap",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-07-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5289ce4c0..5f9985bda 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -78,6 +78,14 @@<category>fix</category><description>Two fixes for the new 41-language experience. Opening a link with a language in the URL (like ?lang=te for Telugu) now always shows that language, even if you had previously browsed in another one; before, your first visit's language silently overrode every shared link. The floating language switcher also joins the site's shared bottom-corner layout, so it no longer overlaps the Getting Started guide.</description></item>+ <item>+ <title>Motion Swap now captures hands and fingers</title>+ <link>https://three.ws/motion-swap</link>+ <guid isPermaLink="false">2026-07-19:Motion Swap now captures hands and fingers</guid>+ <pubDate>Sun, 19 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Motion capture from video just got hands. When you swap yourself for your avatar at /motion-swap, the capture now tracks both hands (21 points each) and solves every finger joint, so waves, counting, pointing, and sign-language handshapes come through on your avatar instead of a stiff flat hand. Wrist rotation is also solved from the palm itself, making hand orientation far more faithful. Works with any rigged avatar; if your hands leave the frame the capture holds the last hand pose instead of snapping flat.</description>+ </item><item><title>Motion Swap: replace yourself in a video with your 3D avatar</title><link>https://three.ws/motion-swap</link>diff --git a/public/features.json b/public/features.jsonindex fb495aabe..43bc36202 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-19T07:10:14.638Z",+ "generated_at": "2026-07-19T13:30:32.370Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/workers/model-video2motion/Dockerfile b/workers/model-video2motion/Dockerfileindex c2e3e8ac4..16c17d2fe 100644--- a/workers/model-video2motion/Dockerfile+++ b/workers/model-video2motion/Dockerfile@@ -16,6 +16,8 @@ RUN pip install -r /app/requirements.txtRUN mkdir -p /models \&& curl -fsSL -o /models/pose_landmarker_heavy.task \https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_heavy/float16/latest/pose_landmarker_heavy.task \+ && curl -fsSL -o /models/hand_landmarker.task \+ https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/latest/hand_landmarker.task \&& curl -fsSL -o /models/selfie_multiclass_256x256.tflite \https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/latest/selfie_multiclass_256x256.tflitediff --git a/workers/model-video2motion/README.md b/workers/model-video2motion/README.mdindex d30ccaa77..8f04268b7 100644--- a/workers/model-video2motion/README.md+++ b/workers/model-video2motion/README.md@@ -19,10 +19,12 @@ For one input video, four artifacts land in GCS under `motion-swap/<task_id>/`:The browser compositor does the rest: original footage underneath, subjectpixelated via the mask, avatar retargeted onto the clip and pinned per frame.-## Models (both Apache-2.0, baked into the image)+## Models (all Apache-2.0, baked into the image)- **MediaPipe PoseLandmarker (heavy)** — 33 world landmarks per frame, VIDEOmode with tracking.+- **MediaPipe HandLandmarker** — 21 landmarks per hand, up to 2 hands, VIDEO+ mode with tracking.- **MediaPipe ImageSegmenter (selfie)** — per-frame person confidence mask.The landmark → joint-rotation solve is ours: `pose_solver.py` builds global@@ -31,6 +33,16 @@ bend-plane to fix twist, converts to locals against the parent chain, and emitshemisphere-continuous quaternion tracks. Pure NumPy, unit-tested from syntheticposes (`test_pose_solver.py`) without mediapipe installed.+When hands are visible, the solver also emits full hand articulation: detected+hands are assigned to the subject's left/right side by proximity to the pose+wrists (the model's handedness label is only a mirrored-convention fallback),+the wrist gets a palm-frame orientation (fixing twist the body-only solve+cannot see), and all 30 canonical finger bones (`LeftHandIndex1` …+`RightHandThumb3`) are solved as hinge rotations per frame. A frame that loses+hand tracking holds the previous finger pose instead of snapping to rest. This+is what makes fine-gesture and sign-language capture work: a video of a signer+comes back as a clip whose handshapes retarget onto any rigged avatar.+## API```diff --git a/workers/model-video2motion/main.py b/workers/model-video2motion/main.pyindex 0505706d0..aaec75415 100644--- a/workers/model-video2motion/main.py+++ b/workers/model-video2motion/main.py@@ -4,10 +4,13 @@ plus the compositing plates for an avatar body swap.Given an https video URL, the worker:1. normalizes the video with ffmpeg (≤720p, capped fps + duration, H.264,original audio preserved),- 2. runs MediaPipe PoseLandmarker (VIDEO mode, heavy model, Apache-2.0) over- every frame → 33 world landmarks + image landmarks + visibility,+ 2. runs MediaPipe PoseLandmarker (VIDEO mode, heavy model, Apache-2.0) plus+ HandLandmarker (2 hands, 21 landmarks each) over every frame → body world+ landmarks + image landmarks + visibility + per-side hand world landmarks,3. solves the landmarks into local joint rotations on the canonical Wolf3D- skeleton (pose_solver.py) and emits a three.js AnimationClip JSON — the+ skeleton (pose_solver.py) — including palm-accurate wrists and all 30+ finger bones when hands are visible — and emits a three.js AnimationClip+ JSON — theSAME document shape the animation library and text2motion lane serve, sothe platform retargets it onto any rigged avatar with the existing engine(src/animation-retarget.js),@@ -54,7 +57,7 @@ from fastapi import BackgroundTasks, FastAPI, Header, HTTPExceptionfrom google.cloud import storagefrom pydantic import BaseModel, Field-from pose_solver import image_anchors, landmarks_to_clip+from pose_solver import image_anchors, landmarks_to_clip, match_hands_to_sidesfrom worker_security import fetch_remote_bytes, require_api_key, safe_errorlogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")@@ -81,7 +84,7 @@ async def lifespan(app: FastAPI):_bucket = storage.Client().bucket(GCS_BUCKET)_sem = asyncio.Semaphore(MAX_CONCURRENT)# Fail fast if the model bundles are missing from the image.- for f in ("pose_landmarker_heavy.task", "selfie_multiclass_256x256.tflite"):+ for f in ("pose_landmarker_heavy.task", "hand_landmarker.task", "selfie_multiclass_256x256.tflite"):path = os.path.join(MODELS_DIR, f)if not os.path.exists(path):raise RuntimeError(f"model bundle missing: {path}")@@ -197,12 +200,12 @@ def _process(task_id: str, video_url: str, fps: int, seconds: float) -> dict:])- world, image, vis, masks, width, height = _analyze(norm_path, fps)+ world, image, vis, hands, masks, width, height = _analyze(norm_path, fps)n_frames = world.shape[0]if n_frames < 2:raise RuntimeError("no person detected in the video")- clip = landmarks_to_clip(world, fps=fps, name=f"capture-{task_id[:8]}")+ clip = landmarks_to_clip(world, fps=fps, name=f"capture-{task_id[:8]}", hands=hands)anchors = image_anchors(image, vis)mask_path = os.path.join(workdir, "mask.mp4")@@ -245,12 +248,15 @@ def _process(task_id: str, video_url: str, fps: int, seconds: float) -> dict:def _analyze(video_path: str, fps: int):- """Run pose + segmentation over every frame of the normalized video.-- Returns (world (T,33,3), image (T,33,2), visibility (T,33), masks list of- uint8 HxW arrays, width, height). Frames where no person is detected reuse- the previous frame's landmarks and get visibility 0 (the anchor marks them- hidden; the solver stays continuous instead of snapping to rest).+ """Run pose + hands + segmentation over every frame of the normalized video.++ Returns (world (T,33,3), image (T,33,2), visibility (T,33), hands+ (T,2,21,3) with NaN where a hand went undetected, masks list of uint8 HxW+ arrays, width, height). Frames where no person is detected reuse the+ previous frame's landmarks and get visibility 0 (the anchor marks them+ hidden; the solver stays continuous instead of snapping to rest). Detected+ hands are assigned to the subject's left/right side by proximity to the+ pose wrists (see pose_solver.match_hands_to_sides)."""import cv2import mediapipe as mp@@ -266,6 +272,15 @@ def _analyze(video_path: str, fps: int):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,+ )# Multiclass person-part segmenter (background/hair/skin/face/clothes/other)# — the full-body person mask is 1 - background confidence, which holds up# far better than the selfie model on wide framing (house tours, rooms).@@ -286,13 +301,14 @@ def _analyze(video_path: str, fps: int):world_frames: list[np.ndarray] = []image_frames: list[np.ndarray] = []vis_frames: list[np.ndarray] = []+ hand_frames: list[np.ndarray] = []masks: list[np.ndarray] = []prev_world: Optional[np.ndarray] = Noneprev_image: Optional[np.ndarray] = None- with vision.PoseLandmarker.create_from_options(pose_opts) as pose, vision.ImageSegmenter.create_from_options(- seg_opts- ) as segmenter:+ with vision.PoseLandmarker.create_from_options(pose_opts) as pose, vision.HandLandmarker.create_from_options(+ hand_opts+ ) as hand_lm, vision.ImageSegmenter.create_from_options(seg_opts) as segmenter:frame_idx = 0while True:ok, frame_bgr = cap.read()@@ -320,6 +336,24 @@ def _analyze(video_path: str, fps: int):image_frames.append(image)vis_frames.append(vis)+ frame_hands = np.full((2, 21, 3), np.nan)+ hand_result = hand_lm.detect_for_video(mp_image, ts_ms)+ if hand_result.hand_world_landmarks:+ wrists = [+ (h[0].x, h[0].y) for h in hand_result.hand_landmarks+ ]+ labels = [+ (c[0].category_name if c else None) for c in hand_result.handedness+ ]+ assigned = match_hands_to_sides(wrists, labels, image)+ for si, side in enumerate(("Left", "Right")):+ idx = assigned[side]+ if idx is not None:+ frame_hands[si] = np.array(+ [[lm.x, lm.y, lm.z] for lm in hand_result.hand_world_landmarks[idx]]+ )+ hand_frames.append(frame_hands)+seg_result = segmenter.segment_for_video(mp_image, ts_ms)bg = seg_result.confidence_masks[0].numpy_view() # class 0 = backgroundperson = 1.0 - np.clip(bg, 0.0, 1.0)@@ -330,7 +364,15 @@ def _analyze(video_path: str, fps: int):cap.release()if not world_frames:- return np.zeros((0, 33, 3)), np.zeros((0, 33, 2)), np.zeros((0, 33)), masks, width, height+ return (+ np.zeros((0, 33, 3)),+ np.zeros((0, 33, 2)),+ np.zeros((0, 33)),+ np.zeros((0, 2, 21, 3)),+ masks,+ width,+ height,+ )# Leading undetected frames produced masks but no landmarks; pad the# landmark arrays at the front with the first detection so lengths match.@@ -338,11 +380,13 @@ def _analyze(video_path: str, fps: int):world = np.stack(world_frames)image = np.stack(image_frames)vis = np.stack(vis_frames)+ hands = np.stack(hand_frames)if pad > 0:world = np.concatenate([np.repeat(world[:1], pad, axis=0), world])image = np.concatenate([np.repeat(image[:1], pad, axis=0), image])vis = np.concatenate([np.zeros((pad, 33)), vis])- return world, image, vis, masks, width, height+ hands = np.concatenate([np.full((pad, 2, 21, 3), np.nan), hands])+ return world, image, vis, hands, masks, width, heightdef _encode_mask_video(masks: list[np.ndarray], fps: int, out_path: str, workdir: str) -> None:diff --git a/workers/model-video2motion/pose_solver.py b/workers/model-video2motion/pose_solver.pyindex 4240ad6ca..3dc58dc7e 100644--- a/workers/model-video2motion/pose_solver.py+++ b/workers/model-video2motion/pose_solver.py@@ -21,6 +21,12 @@ Method: per frame,5. smooth landmarks with a fps-aware exponential filter and keep quaternionhemisphere continuity across frames.+When HandLandmarker world landmarks are supplied alongside the pose (21 per+hand, same camera convention), the solver additionally replaces the swing-only+wrist orientation with a palm frame and solves all 30 canonical finger bones+(pure-swing hinges in each parent's local frame), so captured clips carry full+hand articulation — the requirement for sign language and fine gesture capture.+In the rig's rest space the character stands in a T-pose facing +Z: spine +Y,legs -Y, left arm +X, right arm -X, feet +Z. Zero local rotation everywherereproduces the rest pose, matching the SMPL-rest convention the text2motion@@ -51,6 +57,19 @@ LEFT_ANKLE, RIGHT_ANKLE = 27, 28LEFT_HEEL, RIGHT_HEEL = 29, 30LEFT_FOOT_INDEX, RIGHT_FOOT_INDEX = 31, 32+# HandLandmarker 21-landmark indices (subset used by the finger solver). Each+# finger chain lists the landmark path root→tip; consecutive pairs are the+# three canonical finger bones (e.g. Index MCP→PIP is LeftHandIndex1).+HAND_WRIST = 0+HAND_INDEX_MCP, HAND_MIDDLE_MCP, HAND_PINKY_MCP = 5, 9, 17+_HAND_CHAINS = (+ ("Thumb", (1, 2, 3, 4)),+ ("Index", (5, 6, 7, 8)),+ ("Middle", (9, 10, 11, 12)),+ ("Ring", (13, 14, 15, 16)),+ ("Pinky", (17, 18, 19, 20)),+)+# three.js AnimationBlendMode.NormalAnimationBlendMode_NORMAL_BLEND_MODE = 2500@@ -222,6 +241,23 @@ CLIP_BONES = ["RightHand",]+# Finger bones written to the clip when hand landmarks are supplied, in a+# stable order. Names match the canonical set in src/glb-canonicalize.js, so+# these tracks retarget exactly like the baked library clips' finger tracks.+FINGER_BONES = [+ f"{side}Hand{finger}{joint}"+ for side in ("Left", "Right")+ for finger, _ in _HAND_CHAINS+ for joint in (1, 2, 3)+]++_FINGER_PARENTS = {}+for _side in ("Left", "Right"):+ for _finger, _ in _HAND_CHAINS:+ _FINGER_PARENTS[f"{_side}Hand{_finger}1"] = f"{_side}Hand"+ _FINGER_PARENTS[f"{_side}Hand{_finger}2"] = f"{_side}Hand{_finger}1"+ _FINGER_PARENTS[f"{_side}Hand{_finger}3"] = f"{_side}Hand{_finger}2"+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)."""@@ -245,7 +281,88 @@ def _to_rig_space(world: np.ndarray) -> np.ndarray:return out-def solve_frame(p: np.ndarray, prev: Optional[dict] = None) -> dict:+def match_hands_to_sides(+ hand_wrists: list, labels: list, pose_image: np.ndarray, max_dist: float = 0.25+) -> dict:+ """Assign detected hands to the subject's Left/Right side.++ `hand_wrists` are normalized image (x, y) positions of each detected hand's+ wrist landmark; `labels` the model's handedness strings; `pose_image` one+ frame of (33, 2+) pose image landmarks. Proximity to the pose wrists is the+ primary signal because it cannot be confused by mirroring. The handedness+ label is only a fallback, FLIPPED: Tasks-API handedness assumes a mirrored+ selfie image, and the videos here are unmirrored. Returns+ {"Left": index|None, "Right": index|None} into the detected-hand list.+ """+ targets = {+ "Left": np.asarray(pose_image[LEFT_WRIST][:2], dtype=np.float64),+ "Right": np.asarray(pose_image[RIGHT_WRIST][:2], dtype=np.float64),+ }+ pairs = sorted(+ (float(np.linalg.norm(np.asarray(hand_wrists[i][:2], dtype=np.float64) - t)), i, side)+ for i in range(len(hand_wrists))+ for side, t in targets.items()+ )+ out = {"Left": None, "Right": None}+ used: set[int] = set()+ for dist, i, side in pairs:+ if dist > max_dist:+ break+ if out[side] is None and i not in used:+ out[side] = i+ used.add(i)+ for i in range(len(hand_wrists)):+ if i in used:+ continue+ side = {"Left": "Right", "Right": "Left"}.get(labels[i] if i < len(labels) else None)+ if side and out[side] is None:+ out[side] = i+ used.add(i)+ return out+++def _solve_hand(pts: np.ndarray, side: str, g: dict) -> None:+ """Solve one hand's (21, 3) rig-space landmarks into global orientations.++ Overwrites g["{side}Hand"] with a palm-frame orientation (the pose-only+ solve is swing-only; the palm plane pins the wrist twist, which finger+ poses depend on) and adds a global for each of the 15 finger bones.++ Finger joints are solved as pure swing in the parent's local frame: in the+ canonical rest every finger segment runs along the hand axis (thumb along+ its splayed axis), so the parent-local observed direction against that rest+ direction gives a hinge rotation about the anatomically correct axis with+ no twist accumulation down the chain.+ """+ sign = 1.0 if side == "Left" else -1.0+ axis_rest = np.array([sign, 0.0, 0.0])+ w = pts[HAND_WRIST]+ hand_dir = _normalize(pts[HAND_MIDDLE_MCP] - w)+ if np.linalg.norm(hand_dir) < 1e-6:+ return+ # Back-of-hand normal from the knuckle spread; +Y in the rest pose (T-pose+ # arms out, palms down). The cross product flips chirality per side.+ back = np.cross(pts[HAND_INDEX_MCP] - w, pts[HAND_PINKY_MCP] - w) * sign+ g[f"{side}Hand"] = _frame_quat(hand_dir, back, axis_rest, np.array([0.0, 1.0, 0.0]))+ # Rest thumb: splayed ~45° from the fingers toward the palm-forward (+Z)+ # direction. The retarget engine's per-bone bind correction absorbs the+ # residual mismatch against a specific rig's bind thumb, same as elsewhere.+ thumb_rest = _normalize(np.array([sign, 0.0, 1.0]))+ for finger, chain in _HAND_CHAINS:+ rest = thumb_rest if finger == "Thumb" else axis_rest+ parent_g = g[f"{side}Hand"]+ for joint in range(3):+ bone = f"{side}Hand{finger}{joint + 1}"+ d = _normalize(pts[chain[joint + 1]] - pts[chain[joint]])+ if np.linalg.norm(d) < 1e-6:+ g[bone] = parent_g.copy()+ else:+ d_local = _normalize(_rotate_vec(_quat_conjugate(parent_g), d))+ g[bone] = _quat_multiply(parent_g, _shortest_arc(rest, d_local))+ parent_g = g[bone]+++def solve_frame(p: np.ndarray, prev: Optional[dict] = None, hands: Optional[dict] = None) -> dict:"""Solve one frame of rig-space landmarks (33, 3) → {bone: [x,y,z,w]} locals."""hip_c = 0.5 * (p[LEFT_HIP] + p[RIGHT_HIP])sho_c = 0.5 * (p[LEFT_SHOULDER] + p[RIGHT_SHOULDER])@@ -341,6 +458,23 @@ def solve_frame(p: np.ndarray, prev: Optional[dict] = None) -> dict:swing = _shortest_arc(_rotate_vec(g[parent], rest_dir), d)g[hand] = _quat_multiply(swing, g[parent])+ # Fingers: replace the swing-only wrist with a palm frame and solve the+ # finger chains where hand landmarks are available; a side with no+ # detection this frame holds its previous finger locals (rest if never+ # seen), so dropped hand tracking degrades gracefully instead of snapping.+ solved_fingers: list[str] = []+ held_fingers: list[str] = []+ if hands is not None:+ for side in ("Left", "Right"):+ pts = hands.get(side)+ side_bones = [b for b in FINGER_BONES if b.startswith(side)]+ if pts is not None and np.isfinite(pts).all():+ _solve_hand(np.asarray(pts, dtype=np.float64), side, g)+ solved_fingers.extend(b for b in side_bones if b in g)+ held_fingers.extend(b for b in side_bones if b not in g)+ else:+ held_fingers.extend(side_bones)+parents = {"Hips": None,"Spine": "Hips",@@ -361,24 +495,59 @@ def solve_frame(p: np.ndarray, prev: Optional[dict] = None) -> dict:"RightForeArm": "RightArm","RightHand": "RightForeArm",}+ parents.update(_FINGER_PARENTS)locals_ = {}- for bone in CLIP_BONES:+ for bone in CLIP_BONES + solved_fingers:parent = parents[bone]if parent is None:locals_[bone] = _quat_normalize(g[bone])else:locals_[bone] = _quat_normalize(_quat_multiply(_quat_conjugate(g[parent]), g[bone]))+ for bone in held_fingers:+ if prev is not None and bone in prev.get("locals", {}):+ locals_[bone] = prev["locals"][bone]+ else:+ locals_[bone] = _IDENTITY.copy()return {"locals": locals_, "globals": g}+def _fill_missing_hand(seq: np.ndarray) -> np.ndarray:+ """Forward- then back-fill NaN frames of one hand's (T, 21, 3) sequence.++ A hand with zero detections stays all-NaN, which the solver renders as+ rest-pose fingers.+ """+ ok = np.isfinite(seq).all(axis=(1, 2))+ if not ok.any() or ok.all():+ return seq+ filled = seq.copy()+ last: Optional[int] = None+ for t in range(seq.shape[0]):+ if ok[t]:+ last = t+ elif last is not None:+ filled[t] = filled[last]+ first = int(np.where(ok)[0][0])+ filled[:first] = filled[first]+ return filled++def landmarks_to_clip(world: np.ndarray,*,fps: float,name: str = "captured",smooth: bool = True,+ hands: Optional[np.ndarray] = None,) -> dict:- """(T, 33, 3) MediaPipe world landmarks → three.js AnimationClip JSON."""+ """(T, 33, 3) MediaPipe world landmarks → three.js AnimationClip JSON.++ `hands`, when given, is (T, 2, 21, 3) HandLandmarker world landmarks in the+ same MediaPipe camera convention as `world` — index 0 the subject's left+ hand, 1 the right, NaN-filled where a hand was not detected that frame —+ and the clip additionally carries the 30 canonical finger-bone tracks plus+ palm-accurate wrist orientation.+ """world = np.asarray(world, dtype=np.float64)if world.ndim != 3 or world.shape[1] < 33 or world.shape[2] != 3:raise ValueError(f"landmarks must be (T, 33, 3); got {world.shape}")@@ -388,16 +557,35 @@ def landmarks_to_clip(if n_frames < 1:raise ValueError("motion has no frames")+ if hands is not None:+ hands = np.asarray(hands, dtype=np.float64)+ if hands.shape != (n_frames, 2, 21, 3):+ raise ValueError(f"hands must be ({n_frames}, 2, 21, 3); got {hands.shape}")+ hands = _to_rig_space(hands)+ sides = []+ for si in range(2):+ seq = _fill_missing_hand(hands[:, si])+ if smooth and np.isfinite(seq).all():+ seq = smooth_landmarks(seq, fps)+ sides.append(seq)+rig = _to_rig_space(world)if smooth:rig = smooth_landmarks(rig, fps)- per_bone: dict[str, list[np.ndarray]] = {b: [] for b in CLIP_BONES}+ track_bones = CLIP_BONES + FINGER_BONES if hands is not None else CLIP_BONES+ per_bone: dict[str, list[np.ndarray]] = {b: [] for b in track_bones}prev_solution: Optional[dict] = Noneprev_quats: dict[str, np.ndarray] = {}for t in range(n_frames):- sol = solve_frame(rig[t], prev_solution)- for bone in CLIP_BONES:+ frame_hands = None+ if hands is not None:+ frame_hands = {+ side: sides[si][t] if np.isfinite(sides[si][t]).all() else None+ for si, side in enumerate(("Left", "Right"))+ }+ sol = solve_frame(rig[t], prev_solution, frame_hands)+ for bone in track_bones:q = _hemisphere(prev_quats.get(bone), sol["locals"][bone])prev_quats[bone] = qper_bone[bone].append(q)@@ -406,7 +594,7 @@ def landmarks_to_clip(times = (np.arange(n_frames, dtype=np.float64) / float(fps)).tolist()duration = (n_frames - 1) / float(fps) if n_frames > 1 else 0.0tracks = []- for bone in CLIP_BONES:+ for bone in track_bones:values = np.stack(per_bone[bone], axis=0)tracks.append({diff --git a/workers/model-video2motion/test_pose_solver.py b/workers/model-video2motion/test_pose_solver.pyindex 0d4b8f1fd..25edf4fc8 100644--- a/workers/model-video2motion/test_pose_solver.py+++ b/workers/model-video2motion/test_pose_solver.py@@ -28,8 +28,10 @@ from pose_solver import (RIGHT_PINKY,RIGHT_SHOULDER,RIGHT_WRIST,+ FINGER_BONES,image_anchors,landmarks_to_clip,+ match_hands_to_sides,solve_frame,)@@ -166,6 +168,112 @@ def test_rejects_bad_shapes():landmarks_to_clip(np.zeros((5, 33, 3)), fps=0)+def flat_hand_world(side: str) -> np.ndarray:+ """A synthetic flat hand in MEDIAPIPE convention (y DOWN, z toward camera+ is negative z), matching the T-pose: palm down, fingers along ±x, thumb+ splayed toward the camera. Should solve to near-identity finger locals.+ """+ s = 1.0 if side == "Left" else -1.0+ h = np.zeros((21, 3))+ w = np.array([s * 0.70, -0.50, 0.0])+ h[0] = w+ mcps = {5: -0.025, 9: 0.0, 13: 0.022, 17: 0.045}+ for base, z in mcps.items():+ h[base] = w + [s * 0.09, 0.0, z]+ for j in range(1, 4):+ h[base + j] = h[base] + [s * 0.035 * j, 0.0, 0.0]+ thumb_dir = np.array([s * 0.707, 0.0, -0.707])+ h[1] = w + [s * 0.025, 0.0, -0.03]+ for j, step in ((2, 0.035), (3, 0.065), (4, 0.09)):+ h[j] = h[1] + step * thumb_dir+ return h+++def test_flat_hands_near_identity():+ hands = {"Left": _rig(flat_hand_world("Left")), "Right": _rig(flat_hand_world("Right"))}+ sol = solve_frame(_rig(t_pose_world()), None, hands)+ for bone in FINGER_BONES:+ q = sol["locals"][bone]+ assert _angle(q) < np.deg2rad(15.0), f"{bone} deviates {np.rad2deg(_angle(q)):.1f}° on a flat hand"+ for side in ("Left", "Right"):+ assert _angle(sol["locals"][f"{side}Hand"]) < np.deg2rad(15.0)+++def test_curled_finger_hinges_about_z():+ h = flat_hand_world("Left")+ # Bend the index 90° toward the palm at the PIP (palm down → curl is +y in+ # the y-down mediapipe convention); the tip continues in the bent direction.+ h[7] = h[6] + [0.0, 0.035, 0.0]+ h[8] = h[7] + [0.0, 0.030, 0.0]+ hands = {"Left": _rig(h), "Right": None}+ sol = solve_frame(_rig(t_pose_world()), None, hands)+ q = sol["locals"]["LeftHandIndex2"]+ assert _angle(q) > np.deg2rad(60.0)+ axis = np.abs(q[:3]) / max(np.linalg.norm(q[:3]), 1e-9)+ assert axis[2] > 0.9, f"index hinge should be about z; axis={axis}"+ assert _angle(sol["locals"]["LeftHandIndex1"]) < np.deg2rad(15.0)+ assert _angle(sol["locals"]["LeftHandIndex3"]) < np.deg2rad(15.0)+ # The undetected right hand holds rest, not garbage.+ assert _angle(sol["locals"]["RightHandIndex2"]) < 1e-6+++def test_clip_with_hands_carries_finger_tracks():+ frames = np.stack([t_pose_world()] * 6)+ hands = np.full((6, 2, 21, 3), np.nan)+ for t in range(6):+ hands[t, 0] = flat_hand_world("Left")+ clip = landmarks_to_clip(frames, fps=24, name="hands", hands=hands)+ track_names = {t["name"] for t in clip["tracks"]}+ for bone in FINGER_BONES:+ assert f"{bone}.quaternion" in track_names+ assert len(track_names) == len(CLIP_BONES) + len(FINGER_BONES) + 1+ for track in clip["tracks"]:+ if track["type"] != "quaternion":+ continue+ vals = np.asarray(track["values"]).reshape(-1, 4)+ assert np.allclose(np.linalg.norm(vals, axis=1), 1.0, atol=1e-6)+ # The never-detected right hand stays at rest for the whole clip.+ if track["name"].startswith("RightHandIndex"):+ assert np.allclose(np.abs(vals[:, 3]), 1.0, atol=1e-6)+ b = landmarks_to_clip(frames, fps=24, name="hands", hands=hands)+ assert clip == b+++def test_clip_without_hands_unchanged():+ frames = np.stack([t_pose_world()] * 4)+ clip = landmarks_to_clip(frames, fps=24, name="nohands")+ track_names = {t["name"] for t in clip["tracks"]}+ assert len(track_names) == len(CLIP_BONES) + 1+ assert not any("Index" in n or "Thumb" in n for n in track_names)+++def test_clip_rejects_bad_hands_shape():+ frames = np.stack([t_pose_world()] * 4)+ with pytest.raises(ValueError):+ landmarks_to_clip(frames, fps=24, hands=np.zeros((3, 2, 21, 3)))+ with pytest.raises(ValueError):+ landmarks_to_clip(frames, fps=24, hands=np.zeros((4, 2, 20, 3)))+++def test_match_hands_to_sides_by_proximity():+ pose_img = np.zeros((33, 2))+ pose_img[LEFT_WRIST] = [0.70, 0.50]+ pose_img[RIGHT_WRIST] = [0.30, 0.50]+ # Labels deliberately wrong: proximity must win.+ out = match_hands_to_sides([(0.31, 0.52), (0.69, 0.48)], ["Left", "Left"], pose_img)+ assert out == {"Left": 1, "Right": 0}+++def test_match_hands_falls_back_to_flipped_label():+ pose_img = np.zeros((33, 2))+ pose_img[LEFT_WRIST] = [0.70, 0.50]+ pose_img[RIGHT_WRIST] = [0.30, 0.50]+ # Too far from either pose wrist → the mirrored-convention label decides:+ # a reported "Left" is the subject's right hand in unmirrored video.+ out = match_hands_to_sides([(0.95, 0.95)], ["Left"], pose_img)+ assert out == {"Left": None, "Right": 0}++def test_image_anchors():img = np.zeros((2, 33, 2))img[:, LEFT_HIP] = [0.55, 0.55]