Turn any video into a Mixamo-rig animation - GVHMR estimator, spec-driven retarget, FK apply in Blender via MCP. Works with any Mixamo character; built to be operated end-to-end by an AI agent.
pipeline: SMPL-X rotation retarget, headless
Sachad2643465da24
diff --git a/pipeline/bl_motion.py b/pipeline/bl_motion.pynew file mode 100644index 0000000..47859c6--- /dev/null+++ b/pipeline/bl_motion.py@@ -0,0 +1,358 @@+"""Blender side of the SMPL-X retarget — runs HEADLESS (no MCP, no UI).++ blender -b <rig>_rest.blend -P pipeline/bl_motion.py -- dump-rig --profile rig_profiles/ybot.json+ blender -b <rig>_rest.blend -P pipeline/bl_motion.py -- apply --motion clips/<clip>/motion.npz [--save out.blend]+ blender -b <rig>_rest.blend -P pipeline/bl_motion.py -- render --motion clips/<clip>/motion.npz --view front --out <dir>+ blender -b <rig>_rest.blend -P pipeline/bl_motion.py -- render --motion ... --view camera (the plate's own camera,+ transparent film, for the overlay)+ blender -b <rig>_rest.blend -P pipeline/bl_motion.py -- render --curves clips/<old>/curves.json ...+ (re-key a legacy clip's dumped curves, for A/B)++`dump-rig` adds the armature's rest matrices (every bone, armature+space, centimetres) and the foot geometry to a rig profile, which is all+retarget_smplx.py needs from Blender. `apply` writes the retargeted+motion as keyframes in bulk (fcurve foreach_set — seconds, not the+minutes a keyframe_insert loop takes) and saves the .blend. `render`+applies and renders a PNG sequence through a temporary camera; nothing+is ever saved into the rest scene.++Everything the retarget computes is FK: quaternions on every bone,+location on Hips only (docs/RIG.md).+"""++from __future__ import annotations++import argparse+import json+import math+import sys+from pathlib import Path++import bpy+import numpy as np+from mathutils import Matrix, Vector++REPO = Path(__file__).resolve().parents[1]+LINEAR = 1 # Keyframe.interpolation enum index+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++def armature(name=None):+ if name:+ arm = bpy.data.objects.get(name)+ if arm is None or arm.type != "ARMATURE":+ raise SystemExit(f"armature {name!r} not in the scene")+ return arm+ arms = [o for o in bpy.data.objects if o.type == "ARMATURE"]+ if len(arms) != 1:+ raise SystemExit(f"expected one armature, found {[a.name for a in arms]} — pass --armature")+ return arms[0]+++# ---------------------------------------------------------------------------+# dump-rig++def rig_table(arm) -> dict:+ """What retarget_smplx.py needs from a rig, as JSON-able data: every+ bone's rest matrix in armature space (parents first), the armature's+ world matrix, and the rest mesh's floor and height (armature units)."""+ ordered, seen = [], set()++ def walk(b):+ if b.name in seen:+ return+ seen.add(b.name)+ ordered.append(b)+ for c in b.children:+ walk(c)++ for b in arm.data.bones:+ if b.parent is None:+ walk(b)+ bones = [{"name": b.name, "parent": b.parent.name if b.parent else None,+ "matrix_local": [[round(v, 7) for v in row] for row in b.matrix_local],+ "tail_local": [round(v, 5) for v in b.tail_local]} for b in ordered]+ inv = arm.matrix_world.inverted()+ lo, hi = float("inf"), float("-inf")+ meshes = [o for o in bpy.data.objects if o.type == "MESH" and o.find_armature() is arm]+ for m in meshes:+ M = inv @ m.matrix_world+ for v in m.data.vertices:+ y = (M @ v.co).y+ lo, hi = min(lo, y), max(hi, y)+ return {"armature": arm.name,+ "armature_matrix_world": [[round(v, 7) for v in row] for row in arm.matrix_world],+ "bones": bones,+ "mesh_floor_y": round(lo, 4), # armature units (cm on a Mixamo FBX import)+ "mesh_height": round(hi - lo, 4),+ "meshes": [m.name for m in meshes]}+++def dump_rig(args) -> None:+ arm = armature(args.armature)+ out = rpath(args.profile)+ prof = json.loads(out.read_text(encoding="utf-8")) if out.exists() else {}+ prof.update(rig_table(arm))+ out.write_text(json.dumps(prof, indent=1), encoding="utf-8")+ print(f"dump-rig: {len(prof['bones'])} bones, floor {prof['mesh_floor_y']:.3f}, "+ f"height {prof['mesh_height']:.2f} -> {out}")+++# ---------------------------------------------------------------------------+# apply++def make_action(arm, name):+ if name in bpy.data.actions:+ bpy.data.actions.remove(bpy.data.actions[name])+ action = bpy.data.actions.new(name)+ action.use_fake_user = True+ if arm.animation_data is None:+ arm.animation_data_create()+ arm.animation_data.action = action+ if hasattr(action, "slots"): # Blender 4.4+: layer / slot / channelbag+ slot = action.slots.new(id_type="OBJECT", name=arm.name)+ arm.animation_data.action_slot = slot+ strip = action.layers.new("Layer").strips.new(type="KEYFRAME")+ return action, strip.channelbag(slot, ensure=True)+ return action, action+++def key_curve(holder, path, index, group, frames, values):+ fc = holder.fcurves.new(path, index=index)+ try:+ fc.group = group+ except Exception:+ pass+ n = len(frames)+ fc.keyframe_points.add(n)+ co = np.empty(n * 2, dtype=np.float64)+ co[0::2] = frames+ co[1::2] = values+ fc.keyframe_points.foreach_set("co", co)+ fc.keyframe_points.foreach_set("interpolation", [LINEAR] * n)+ fc.update()+++def apply_motion(arm, motion: dict, action_name: str | None = None):+ """Key a motion dict (from motion.npz or legacy curves) onto `arm`."""+ names = [str(n) for n in motion["bone_names"]]+ quats = np.asarray(motion["quat"], dtype=np.float64) # (T, B, 4) wxyz+ hips = np.asarray(motion["hips_location"], dtype=np.float64) # (T, 3) pose-local+ T = quats.shape[0]+ name = action_name or str(motion.get("action_name", "SMPLX_Retarget"))+ action, holder = make_action(arm, name)+ frames = np.arange(1, T + 1, dtype=np.float64)+ missing = []+ for b, bn in enumerate(names):+ pb = arm.pose.bones.get(bn)+ if pb is None:+ missing.append(bn)+ continue+ pb.rotation_mode = "QUATERNION"+ grp = None+ if hasattr(holder, "groups"): # one channel group per bone, like a keyed rig+ grp = holder.groups.get(bn) or holder.groups.new(bn)+ base = f'pose.bones["{bn}"]'+ for c in range(4):+ key_curve(holder, base + ".rotation_quaternion", c, grp, frames, quats[:, b, c])+ loc = hips if bn == str(motion.get("root", "mixamorig:Hips")) else np.zeros((T, 3))+ for c in range(3):+ key_curve(holder, base + ".location", c, grp, frames, loc[:, c])+ scene = bpy.context.scene+ scene.render.fps = int(round(float(motion.get("fps", 30))))+ scene.frame_start = 1+ scene.frame_end = T+ if missing:+ print(f"apply: {len(missing)} bones not in this rig (skipped): {missing[:6]}")+ return action+++def load_motion(path: Path) -> dict:+ z = np.load(path, allow_pickle=False)+ return {k: z[k] for k in z.files}+++def load_curves(path: Path) -> dict:+ """A legacy clip's curves.json (apply_mixamo_fk.dump_curves) as a+ motion dict — lets old and new pipelines render through one path."""+ frames = json.loads(path.read_text(encoding="utf-8"))["frames"]+ names = list(frames[0]["bones"].keys())+ q = np.array([[fr["bones"][n]["rotation_quaternion"] for n in names] for fr in frames])+ hips = np.array([fr["bones"]["mixamorig:Hips"]["location"] for fr in frames])+ return {"bone_names": np.array(names), "quat": q, "hips_location": hips, "fps": 30,+ "root": "mixamorig:Hips"}+++def cmd_apply(args) -> None:+ arm = armature(args.armature)+ motion = load_motion(rpath(args.motion)) if args.motion else load_curves(rpath(args.curves))+ action = apply_motion(arm, motion, args.action)+ print(f"apply: action {action.name!r}, {bpy.context.scene.frame_end} frames")+ if args.save:+ bpy.ops.wm.save_as_mainfile(filepath=str(rpath(args.save)), copy=True)+ print("saved", rpath(args.save))+++# ---------------------------------------------------------------------------+# render++def setup_look(scene, transparent: bool, floor: bool, arm):+ scene.render.engine = "BLENDER_WORKBENCH"+ sh = scene.display.shading+ sh.light = "STUDIO"+ try:+ sh.studio_light = "paint.sl" # soft top light: lights the floor, not only the body+ except Exception:+ pass+ sh.color_type = "MATERIAL"+ sh.show_shadows = True+ sh.shadow_intensity = 0.8+ sh.show_cavity = True+ sh.cavity_type = "BOTH"+ try:+ sh.show_specular_highlight = True+ except Exception:+ pass+ scene.display.light_direction = (-0.3, 0.5, -0.8) # casts the shadow back-right onto a lit floor+ scene.display.shadow_shift = 0.02+ scene.render.film_transparent = transparent+ scene.render.image_settings.file_format = "PNG"+ scene.render.image_settings.color_mode = "RGBA" if transparent else "RGB"+ scene.view_settings.view_transform = "Standard"+ world = scene.world or bpy.data.worlds.new("World")+ scene.world = world+ world.color = (0.80, 0.81, 0.84)+ if floor and not transparent:+ me = bpy.data.meshes.new("QA_Floor")+ s = 30.0+ me.from_pydata([(-s, -s, 0), (s, -s, 0), (s, s, 0), (-s, s, 0)], [], [(0, 1, 2, 3)])+ ob = bpy.data.objects.new("QA_Floor", me)+ mat = bpy.data.materials.new("QA_FloorMat")+ mat.diffuse_color = (1.0, 1.0, 1.0, 1.0)+ me.materials.append(mat)+ scene.collection.objects.link(ob)+ # a 50 cm grid of thin lines so travel and foot skate read on screen+ gm = bpy.data.meshes.new("QA_Grid")+ verts, faces = [], []+ w = 0.006+ for k in range(-12, 13):+ x = k * 0.5+ for (a0, a1, b0, b1) in ((x - w, x + w, -6.0, 6.0), (-6.0, 6.0, x - w, x + w)):+ i = len(verts)+ verts += [(a0, b0, 0.001), (a1, b0, 0.001), (a1, b1, 0.001), (a0, b1, 0.001)]+ faces.append((i, i + 1, i + 2, i + 3))+ gm.from_pydata(verts, [], faces)+ go = bpy.data.objects.new("QA_Grid", gm)+ gmat = bpy.data.materials.new("QA_GridMat")+ gmat.diffuse_color = (0.66, 0.67, 0.70, 1.0)+ gm.materials.append(gmat)+ scene.collection.objects.link(go)+ # One fixed character look, so any two renders (old vs new pipeline)+ # differ by the motion and nothing else. Y Bot's joint spheres stay+ # light; everything else is the body tone.+ for m in bpy.data.objects:+ if m.type == "MESH" and m.find_armature() is arm:+ tone = (0.93, 0.93, 0.95, 1.0) if "Joints" in m.name else (0.30, 0.46, 0.78, 1.0)+ for slot in m.material_slots:+ if slot.material:+ slot.material.diffuse_color = tone+++def cmd_render(args) -> None:+ scene = bpy.context.scene+ arm = armature(args.armature)+ motion = load_motion(rpath(args.motion)) if args.motion else load_curves(rpath(args.curves))+ apply_motion(arm, motion, args.action)+ T = scene.frame_end+ if args.frames:+ a, b = (int(x) for x in args.frames.split(":"))+ scene.frame_start, scene.frame_end = max(1, a), min(T, b)++ cam_data = bpy.data.cameras.new("QA_Camera")+ cam = bpy.data.objects.new("QA_Camera", cam_data)+ scene.collection.objects.link(cam)+ scene.camera = cam+ transparent = args.view == "camera"+ setup_look(scene, transparent, floor=not transparent, arm=arm)++ if args.view == "camera":+ # The plate's own camera: intrinsics K and a static pose, both+ # written by retarget_smplx.py into the motion file in Blender+ # world coordinates. Renders the character where the performer is.+ K = np.asarray(motion["cam_K"], dtype=np.float64)+ W, H = int(motion["cam_wh"][0]), int(motion["cam_wh"][1])+ scene.render.resolution_x, scene.render.resolution_y = W, H+ cam_data.sensor_fit = "HORIZONTAL"+ cam_data.sensor_width = 36.0+ cam_data.lens = float(K[0, 0]) * 36.0 / W+ cam_data.shift_x = -(float(K[0, 2]) - W / 2.0) / W+ cam_data.shift_y = (float(K[1, 2]) - H / 2.0) / W+ cam_data.clip_start, cam_data.clip_end = 0.05, 100.0+ M = np.asarray(motion["cam_matrix_world"], dtype=np.float64)+ cam.matrix_world = Matrix([list(r) for r in M])+ else:+ # 16:9, framed like a 4:3 50 mm shot vertically (a 2.5 m tall window+ # at 4.6 m) so a jump or a head-high kick stays in frame+ scene.render.resolution_x, scene.render.resolution_y = 1280, 720+ cam_data.lens = 37.0+ # Frame on the hips' mean ground position over the clip so a+ # travelling performance stays in shot; fixed for the whole clip.+ hips_w = np.asarray(motion.get("hips_world", np.zeros((T, 3))), dtype=np.float64)+ cx, cy = (float(np.median(hips_w[:, 0])), float(np.median(hips_w[:, 1]))) if len(hips_w) else (0.0, 0.0)+ dist = args.distance+ if args.view == "front":+ cam.location = Vector((cx, cy - dist, 1.02))+ cam.rotation_euler = (math.radians(88.0), 0.0, 0.0)+ elif args.view == "side":+ cam.location = Vector((cx + dist, cy, 1.02))+ cam.rotation_euler = (math.radians(88.0), 0.0, math.radians(90.0))+ else: # three_quarter, slightly above+ a = math.radians(35.0)+ cam.location = Vector((cx + dist * math.sin(a), cy - dist * math.cos(a), 1.55))+ cam.rotation_euler = (math.radians(81.0), 0.0, a)+ scene.render.resolution_percentage = 100+ out = rpath(args.out)+ out.mkdir(parents=True, exist_ok=True)+ scene.render.filepath = str(out / "f####")+ bpy.ops.render.render(animation=True)+ print(f"render: {scene.frame_end - scene.frame_start + 1} frames ({args.view}) -> {out}")+++def main() -> None:+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []+ ap = argparse.ArgumentParser(prog="bl_motion.py")+ sub = ap.add_subparsers(dest="cmd", required=True)+ d = sub.add_parser("dump-rig")+ d.add_argument("--profile", required=True)+ d.add_argument("--armature")+ a = sub.add_parser("apply")+ r = sub.add_parser("render")+ for p in (a, r):+ g = p.add_mutually_exclusive_group(required=True)+ g.add_argument("--motion", help="motion.npz from retarget_smplx.py")+ g.add_argument("--curves", help="a legacy clip's curves.json")+ p.add_argument("--armature")+ p.add_argument("--action")+ a.add_argument("--save")+ r.add_argument("--view", default="front", choices=["front", "side", "three_quarter", "camera"])+ r.add_argument("--out", required=True)+ r.add_argument("--frames", help="first:last (1-based, inclusive)")+ r.add_argument("--distance", type=float, default=4.6)+ args = ap.parse_args(argv)+ {"dump-rig": dump_rig, "apply": cmd_apply, "render": cmd_render}[args.cmd](args)+++if __name__ == "__main__":+ try:+ main()+ except SystemExit as e:+ if e.code not in (0, None):+ print(f"ERROR: {e}", file=sys.stderr)+ sys.stdout.flush()+ import os+ os._exit(2)+ raisediff --git a/pipeline/detect_feet.py b/pipeline/detect_feet.pynew file mode 100644index 0000000..219e9bb--- /dev/null+++ b/pipeline/detect_feet.py@@ -0,0 +1,116 @@+"""2D foot keypoints (heel, toe tip) for a plate — what COCO-17 lacks.++ python pipeline/detect_feet.py --video plates/<p>/<p>.mp4 [--out plates/<p>/feet2d.npz]++GVHMR's detector (ViTPose, COCO-17) stops at the ankles, so nothing in+the estimate says which way a foot points or whether its heel is up —+and the retarget showed it: feet turned the wrong way, heels flat where+the performer stood on the ball of the foot. MediaPipe's Pose Landmarker+tracks the heel and the toe tip of each foot; refine_smplx.py fits the+SMPL-X feet to them.++Runs in any Python with `mediapipe` and `opencv-python` (it does not need+the GVHMR venv). The model (pose_landmarker_heavy.task) is looked up in+tools/models/, then downloaded from Google's model store if missing.+Solo plates only: one pose is tracked.++Writes feet2d.npz: `kp` (T, 33, 4) — x px, y px, visibility, presence —+for the MediaPipe landmarks, and `fps`. The refinement uses 27-32+(ankles, heels, toe tips), with ankles as a sanity check against ViTPose.+"""++from __future__ import annotations++import argparse+import urllib.request+from pathlib import Path++import cv2+import numpy as np++REPO = Path(__file__).resolve().parents[1]+MODEL_URL = ("https://storage.googleapis.com/mediapipe-models/pose_landmarker/"+ "pose_landmarker_heavy/float16/latest/pose_landmarker_heavy.task")+MODEL_PATHS = [REPO / "tools" / "models" / "pose_landmarker_heavy.task",+ REPO / "local" / "bible" / "scripts" / "models" / "pose_landmarker_heavy.task"]+# MediaPipe BlazePose landmark ids (person's own left/right)+FEET = {"L_ankle": 27, "R_ankle": 28, "L_heel": 29, "R_heel": 30, "L_toe": 31, "R_toe": 32}+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++def _is_task_file(p: Path) -> bool:+ """A .task model is a zip archive; a truncated or zero-filled copy+ (a failed download, a partial restore) is not."""+ try:+ with open(p, "rb") as f:+ return f.read(2) == b"PK"+ except OSError:+ return False+++def model_path(arg=None) -> Path:+ for p in ([rpath(arg)] if arg else []) + MODEL_PATHS:+ if p.exists() and _is_task_file(p):+ return p+ if p.exists():+ print(f"skipping {p}: not a valid .task archive")+ dst = MODEL_PATHS[0]+ dst.parent.mkdir(parents=True, exist_ok=True)+ print(f"downloading {MODEL_URL} -> {dst}")+ urllib.request.urlretrieve(MODEL_URL, dst)+ return dst+++def detect(video: Path, model: Path) -> tuple[np.ndarray, float]:+ import mediapipe as mp+ from mediapipe.tasks import python as mp_python+ from mediapipe.tasks.python import vision++ opts = vision.PoseLandmarkerOptions(+ base_options=mp_python.BaseOptions(model_asset_path=str(model)),+ running_mode=vision.RunningMode.VIDEO, num_poses=1,+ min_pose_detection_confidence=0.5, min_pose_presence_confidence=0.5,+ min_tracking_confidence=0.5)+ cap = cv2.VideoCapture(str(video))+ fps = cap.get(cv2.CAP_PROP_FPS) or 24.0+ W, H = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))+ out = []+ with vision.PoseLandmarker.create_from_options(opts) as lm:+ i = 0+ while True:+ ok, bgr = cap.read()+ if not ok:+ break+ img = mp.Image(image_format=mp.ImageFormat.SRGB, data=cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))+ res = lm.detect_for_video(img, int(round(i * 1000.0 / fps)))+ kp = np.zeros((33, 4))+ if res.pose_landmarks:+ for k, p in enumerate(res.pose_landmarks[0]):+ kp[k] = (p.x * W, p.y * H, p.visibility or 0.0, p.presence or 0.0)+ out.append(kp)+ i += 1+ cap.release()+ return np.stack(out), float(fps)+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("--video", required=True)+ ap.add_argument("--out", help="default: feet2d.npz next to the video")+ ap.add_argument("--model")+ args = ap.parse_args()+ video = rpath(args.video)+ out = rpath(args.out) if args.out else video.with_name("feet2d.npz")+ kp, fps = detect(video, model_path(args.model))+ np.savez_compressed(out, kp=kp, fps=np.array(fps))+ vis = kp[:, list(FEET.values()), 2]+ print(f"wrote {out}: {kp.shape[0]} frames, pose found on {(kp[:, 0, 3] > 0).mean() * 100:.0f}% "+ f"of them, mean foot visibility {vis.mean():.2f}")+++if __name__ == "__main__":+ main()diff --git a/pipeline/estimate_pose_gvhmr.py b/pipeline/estimate_pose_gvhmr.pyindex db85b0b..c77d7ae 100644--- a/pipeline/estimate_pose_gvhmr.py+++ b/pipeline/estimate_pose_gvhmr.py@@ -207,7 +207,57 @@ def side_track(tracker, video_path: str, person: str, n_people: int = 2):return out-def run_gvhmr(video: Path, person: str | None = None) -> dict:+def predict(model, data: dict, postproc: str) -> dict:+ """GVHMR inference, keeping the network's per-frame contact+ confidences (`static_conf_logits`) that DemoPL.predict throws away.++ postproc:+ full GVHMR's demo behaviour: the static-camera trajectory fix, then+ a CCD IK that pulls every joint the network calls "static"+ toward where it was the frame before — ankles, balls of the+ feet AND wrists. Built for hands resting on things; on a+ fighter it can hold a wrist back at the apex of a punch.+ feet the same, but wrists are never static (default for the+ SMPL-X retarget: feet cleaned, strikes untouched).+ none the raw network output.++ Returns the usual pred dict plus `static_conf` (L, 6): probabilities+ in smplx_body.STATIC_JOINTS order.+ """+ from hmr4d.model.gvhmr.utils.postprocess import pp_static_joint_cam, process_ik+ from hmr4d.utils.geo.hmr_cam import normalize_kp2d+ from hmr4d.utils.net_utils import detach_to_cpu++ batch = { # exactly DemoPL.predict's batch+ "length": data["length"][None],+ "obs": normalize_kp2d(data["kp2d"], data["bbx_xys"])[None],+ "bbx_xys": data["bbx_xys"][None],+ "K_fullimg": data["K_fullimg"][None],+ "cam_angvel": data["cam_angvel"][None],+ "f_imgseq": data["f_imgseq"][None],+ }+ batch = {k: v.cuda() for k, v in batch.items()}+ pipe = model.pipeline+ with torch.no_grad():+ out = pipe.forward(batch, train=False, postproc=False, static_cam=True)+ logits = out["static_conf_logits"].clone()+ if postproc in ("full", "feet"):+ if postproc == "feet":+ out["static_conf_logits"][..., 4:] = -1e4 # wrists: never static+ out["pred_smpl_params_global"]["transl"] = pp_static_joint_cam(out, pipe.endecoder)+ body_pose = process_ik(out, pipe.endecoder)+ out["pred_smpl_params_global"]["body_pose"] = body_pose+ out["pred_smpl_params_incam"]["body_pose"] = body_pose+ return detach_to_cpu({+ "smpl_params_global": {k: v[0] for k, v in out["pred_smpl_params_global"].items()},+ "smpl_params_incam": {k: v[0] for k, v in out["pred_smpl_params_incam"].items()},+ "K_fullimg": data["K_fullimg"],+ "static_conf": logits[0].float().sigmoid(),+ "postproc": postproc,+ })+++def run_gvhmr(video: Path, person: str | None = None, postproc: str = "full") -> dict:import hydrafrom hydra import compose, initialize_config_module@@ -215,7 +265,6 @@ def run_gvhmr(video: Path, person: str | None = None) -> dict:from hmr4d.model.gvhmr.gvhmr_pl_demo import DemoPLfrom hmr4d.utils.geo.hmr_cam import estimate_K, get_bbx_xys_from_xyxyfrom hmr4d.utils.geo_transform import compute_cam_angvel- from hmr4d.utils.net_utils import detach_to_cpufrom hmr4d.utils.preproc import Extractor, Tracker, VitPoseExtractorfrom hmr4d.utils.video_io_utils import get_video_lwh, get_video_reader, get_writer@@ -259,7 +308,14 @@ def run_gvhmr(video: Path, person: str | None = None) -> dict:torch.save(extractor.extract_video_features(cfg.video_path, bbx_xys), paths.vit_features)del extractor- if not Path(paths.hmr4d_results).exists():+ # `full` keeps GVHMR's own results file (the landmark pipeline's+ # historical input); the other modes cache beside it, so switching+ # modes never recomputes the preprocessing.+ results_path = Path(paths.hmr4d_results)+ if postproc != "full":+ results_path = results_path.with_name(f"hmr4d_results_pp-{postproc}.pt")+ pred = torch.load(results_path) if results_path.exists() else None+ if pred is None or "static_conf" not in pred:length, width, height = get_video_lwh(cfg.video_path)K_fullimg = estimate_K(width, height).repeat(length, 1, 1)data = {@@ -273,11 +329,70 @@ def run_gvhmr(video: Path, person: str | None = None) -> dict:model: DemoPL = hydra.utils.instantiate(cfg.model, _recursive_=False)model.load_pretrained_model(cfg.ckpt_path)model = model.eval().cuda()- pred = detach_to_cpu(model.predict(data, static_cam=True))- pred.pop("net_outputs", None) # heavy intermediates, not needed- torch.save(pred, paths.hmr4d_results)+ fresh = predict(model, data, postproc)+ if pred is None:+ pred = fresh+ else:+ # A cache written before the contact confidences were kept:+ # add them and leave the cached poses exactly as they were.+ pred["static_conf"] = fresh["static_conf"]+ pred["postproc"] = postproc+ torch.save(pred, results_path)- return {"pred": torch.load(paths.hmr4d_results), "cfg": cfg}+ pred["kp2d"] = torch.load(paths.vitpose)+ return {"pred": pred, "cfg": cfg}+++# ---------------------------------------------------------------------------+# Stage 1b — the SMPL-X parameters themselves, for retarget_smplx.py.++def export_smplx(pred: dict, out_path: Path, fps: float, wh: tuple[int, int]) -> dict:+ """Write smplx.npz: everything the rotation retarget needs, with no+ torch and no gated body model required downstream.++ The landmark export below reduces the body to 33 points and throws+ the joint rotations away — twist of the forearms, chest and head is+ not recoverable from positions. This keeps them.+ """+ sys.path.insert(0, str(REPO / "pipeline"))+ import smplx_body as SB++ def np64(t):+ return t.detach().cpu().numpy().astype(np.float64)++ g = {k: np64(v) for k, v in pred["smpl_params_global"].items()}+ c = {k: np64(v) for k, v in pred["smpl_params_incam"].items()}+ betas = g["betas"].mean(axis=0)+ rest = SB.shaped_rest(CHECKPOINTS["smplx_neutral"], betas)+ L = g["body_pose"].shape[0]+ static = np64(pred["static_conf"]) if "static_conf" in pred else np.full((L, 6), np.nan)+ kp2d = np64(pred["kp2d"]) if "kp2d" in pred else np.zeros((L, 17, 3))+ payload = {+ "source": np.array("gvhmr_siga24"),+ "postproc": np.array(str(pred.get("postproc", "full"))),+ "fps": np.array(float(fps)),+ "width": np.array(int(wh[0])), "height": np.array(int(wh[1])),+ # gravity-aligned world ("ay": y up, arbitrary yaw, metres)+ "global_orient": g["global_orient"], "body_pose": g["body_pose"], "transl": g["transl"],+ # camera frame (OpenCV: x right, y down, z forward)+ "incam_global_orient": c["global_orient"], "incam_transl": c["transl"],+ "incam_body_pose": c["body_pose"],+ "K": np64(pred["K_fullimg"][0]),+ "betas": betas,+ # performer-shaped rest skeleton (SMPL-X canonical axes, metres)+ "rest_joints": rest["joints"],+ "foot": np.array(json.dumps(rest["foot"])),+ "body_height": np.array(rest["height"]),+ # GVHMR's own contact detector: P(static) per frame for+ # L_ankle, L_foot, R_ankle, R_foot, L_wrist, R_wrist+ "static_conf": static,+ # ViTPose COCO-17 keypoints (pixels + confidence) — the 2D evidence+ # the fidelity check projects the retarget against+ "kp2d": kp2d,+ }+ out_path.parent.mkdir(parents=True, exist_ok=True)+ np.savez_compressed(out_path, **payload)+ return {"frames": L, "height_m": round(rest["height"], 3), "postproc": str(payload["postproc"])}# ---------------------------------------------------------------------------@@ -419,6 +534,42 @@ def project(p: np.ndarray, K: np.ndarray, wh: tuple[int, int]) -> np.ndarray:return np.array([u, v, 0.0])+def foot_keypoints(video: Path, out: Path, args):+ """Heel/toe 2D keypoints for the refinement (detect_feet.py, MediaPipe).++ MediaPipe does not live in the GVHMR venv, so the detector runs in+ whichever Python has it: this one, --feet-python, or `python` on PATH.+ Cached next to the plate; returns None (refinement without feet) when+ no detector is available or the plate has two performers.+ """+ import importlib.util+ import shutil+ import subprocess++ if out.exists():+ return np.load(out)["kp"]+ if args.person:+ print("foot keypoints: skipped (multi-person plate; MediaPipe tracks one pose)")+ return None+ script = REPO / "pipeline" / "detect_feet.py"+ if importlib.util.find_spec("mediapipe") is not None:+ cmd = [sys.executable]+ else:+ exe = args.feet_python or shutil.which("python") or shutil.which("python3")+ cmd = [exe] if exe else None+ if cmd is None:+ print("foot keypoints: no Python with mediapipe found (pass --feet-python); refining without feet")+ return None+ res = subprocess.run(cmd + [str(script), "--video", str(video), "--out", str(out)],+ capture_output=True, text=True)+ if res.returncode != 0 or not out.exists():+ print("foot keypoints: detect_feet.py failed; refining without feet\n" + res.stderr[-800:])+ return None+ if res.stdout.strip():+ print(res.stdout.strip().splitlines()[-1])+ return np.load(out)["kp"]++def main() -> None:ap = argparse.ArgumentParser(description="GVHMR -> MediaPipe-style landmarks.json")ap.add_argument("--video", required=True, type=Path)@@ -427,6 +578,20 @@ def main() -> None:ap.add_argument("--person", default=None,help="multi-person plates: which performer to estimate — 'left', 'right', ""or a 0-based slot index ordered left to right. Omit for a solo plate.")+ ap.add_argument("--postproc", choices=["full", "feet", "none"], default="feet",+ help="GVHMR post-processing (see predict()). 'feet' (default) cleans foot "+ "contacts without holding wrists back at the apex of a strike; 'full' is "+ "GVHMR's demo behaviour.")+ ap.add_argument("--smplx-only", action="store_true",+ help="write smplx.npz only (skip the 33-landmark export of the legacy lift)")+ ap.add_argument("--smplx-out", type=Path, default=None,+ help="where to write the SMPL-X parameters for retarget_smplx.py "+ "(default: smplx.npz — or smplx_<person>.npz — next to --out)")+ ap.add_argument("--feet-python", default=None,+ help="a Python with mediapipe for detect_feet.py (default: this one, else `python` on PATH)")+ ap.add_argument("--no-refine", action="store_true",+ help="skip the 2D-keypoint refinement (refine_smplx.py); the raw GVHMR "+ "parameters are always kept beside it as *_raw.npz")args = ap.parse_args()def rp(p: Path) -> Path:@@ -439,15 +604,44 @@ def main() -> None:preflight()fps = args.fps or video_fps(video)- res = run_gvhmr(video, args.person)+ res = run_gvhmr(video, args.person, args.postproc)pred = res["pred"]- joints_ayfz, joints_incam, K, face_ayfz, face_incam = smpl_joints(pred)- L = joints_ayfz.shape[0]cap = cv2.VideoCapture(str(video))wh = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1920, int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 1080)cap.release()+ smplx_out = rp(args.smplx_out) if args.smplx_out else out_path.with_name(+ f"smplx_{args.person}.npz" if args.person else "smplx.npz")+ raw_out = smplx_out.with_name(smplx_out.stem + "_raw.npz")+ info = export_smplx(pred, raw_out, fps, wh)+ print(f"wrote {raw_out} ({info['frames']} frames, performer {info['height_m']} m, "+ f"postproc {info['postproc']})")+ if args.no_refine:+ import shutil+ shutil.copyfile(raw_out, smplx_out)+ else:+ # GVHMR pulls the extremes of fast limbs toward the mean (a kick apex+ # 0.1-0.2 m low) and says little about feet (COCO-17 stops at the+ # ankle); fit the pose to the plate's own 2D keypoints, heels and+ # toe tips included when a foot detector is available.+ sys.path.insert(0, str(REPO / "pipeline"))+ import refine_smplx+ feet = foot_keypoints(video, smplx_out.with_name(+ f"feet2d_{args.person}.npz" if args.person else "feet2d.npz"), args)+ refined, st = refine_smplx.refine(dict(np.load(raw_out)), feet2d=feet, log=lambda *_: None)+ np.savez_compressed(smplx_out, **refined)+ feet_msg = (f", heel/toe {st['feet_before_cm']:.1f} -> {st['feet_after_cm']:.1f} cm"+ if feet is not None else ", no foot keypoints")+ print(f"wrote {smplx_out} (refined on 2D keypoints: error {st['reproj_before_cm']:.1f} -> "+ f"{st['reproj_after_cm']:.1f} cm, p95 {st['reproj_p95_before_cm']:.1f} -> "+ f"{st['reproj_p95_after_cm']:.1f} cm{feet_msg})")+ if args.smplx_only:+ return++ joints_ayfz, joints_incam, K, face_ayfz, face_incam = smpl_joints(pred)+ L = joints_ayfz.shape[0]+frames = []for i in range(L):mp_world = mp33_from_smpl(ayfz_to_mp(joints_ayfz[i]), ayfz_to_mp(face_ayfz[i]))diff --git a/pipeline/eval_fidelity.py b/pipeline/eval_fidelity.pynew file mode 100644index 0000000..5ad98cb--- /dev/null+++ b/pipeline/eval_fidelity.py@@ -0,0 +1,282 @@+"""How closely does a retargeted clip follow the VIDEO — measured, not eyeballed.++ python pipeline/eval_fidelity.py --spec action_specs/<motion>.json \+ --clip clips/<new_clip> [--vs clips/<legacy_clip>] [--out report.json]++The retarget is projected into the plate through the plate's own camera+(recovered by retarget_smplx.py, stored in motion.npz) and compared with+the 2D keypoints ViTPose detected on the video frames (smplx.npz `kp2d`).+That evidence is independent of any 3D retarget.++Measured per frame, per body segment (upper arms, forearms, thighs, shins,+shoulder line, hip line, torso, head):+ the ANGLE between the segment on screen in the retarget and in the+ video. Angles, not pixel distances: a Mixamo character is not the+ performer's size or shape, so joint positions can never coincide, but a+ forearm that points where the performer's forearm points reads right.+ Foreshortened segments (short on screen) and low-confidence keypoints+ are down-weighted/excluded — their 2D direction is noise.++Also reported: foot skate while planted (frames GVHMR's own contact+detector flags, not either retarget's locks), how far planted soles sit+off the floor, and jitter (mean joint jerk). A legacy clip (`--vs`, curves.json from apply_mixamo_fk) is+measured the same way. Legacy clips are in-place, so they are evaluated+with the new clip's ground trajectory added, which isolates the POSE.+"""++from __future__ import annotations++import argparse+import json+from pathlib import Path++import numpy as np++REPO = Path(__file__).resolve().parents[1]++# COCO-17 (ViTPose) index -> Mixamo bone whose head is that joint+COCO = {5: "LeftArm", 6: "RightArm", 7: "LeftForeArm", 8: "RightForeArm",+ 9: "LeftHand", 10: "RightHand", 11: "LeftUpLeg", 12: "RightUpLeg",+ 13: "LeftLeg", 14: "RightLeg", 15: "LeftFoot", 16: "RightFoot"}+SEGMENTS = {+ "L upper arm": (5, 7), "R upper arm": (6, 8), "L forearm": (7, 9), "R forearm": (8, 10),+ "L thigh": (11, 13), "R thigh": (12, 14), "L shin": (13, 15), "R shin": (14, 16),+ "shoulders": (5, 6), "hips": (11, 12), "torso": ("mid_hip", "mid_sh"), "head": ("mid_sh", 0),+}+GROUPS = {"arms": ["L upper arm", "R upper arm", "L forearm", "R forearm"],+ "legs": ["L thigh", "R thigh", "L shin", "R shin"],+ "torso": ["shoulders", "hips", "torso"], "head": ["head"]}+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++def load_clip(clip_dir: Path):+ """World joint positions (T, B, 3) + bone names, from motion.npz or curves.json."""+ m = clip_dir / "motion.npz"+ if m.exists():+ z = np.load(m)+ return [str(n) for n in z["bone_names"]], z["joints_world"], z+ frames = json.loads((clip_dir / "curves.json").read_text(encoding="utf-8"))["frames"]+ names = list(frames[0]["bones"].keys())+ J = np.array([[fr["bones"][n]["world_location"] for n in names] for fr in frames])+ return names, J, None+++def face_point(names, J, prefix):+ """A nose proxy: in front of and above the skull-base Head joint, along+ the head's own frame (from Head and HeadTop_End positions)."""+ h = J[:, names.index(prefix + "Head")]+ top = J[:, names.index(prefix + "HeadTop_End")]+ neck = J[:, names.index(prefix + "Neck")]+ up = top - h+ up /= np.linalg.norm(up, axis=-1, keepdims=True)+ return h + up * 0.07, h, neck+++def project(P, cam_mw, K):+ """Blender world points (..., 3) -> pixels (..., 2) through a Blender camera."""+ R, C = cam_mw[:3, :3], cam_mw[:3, 3]+ pc = np.einsum("ji,...j->...i", R, P - C) # camera coords (x right, y up, -z fwd)+ x, y, z = pc[..., 0], -pc[..., 1], -pc[..., 2] # OpenCV+ z = np.maximum(z, 1e-6)+ return np.stack([K[0, 0] * x / z + K[0, 2], K[1, 1] * y / z + K[1, 2]], -1)+++def keypoints_2d(names, J, cam_mw, K, prefix):+ """(T, 17, 2) projected COCO-style points for a retargeted clip (nose from the face proxy)."""+ T = J.shape[0]+ out = np.full((T, 17, 2), np.nan)+ for c, bone in COCO.items():+ out[:, c] = project(J[:, names.index(prefix + bone)], cam_mw, K)+ nose, _, _ = face_point(names, J, prefix)+ out[:, 0] = project(nose, cam_mw, K)+ return out+++def seg_vec(kp, seg):+ def pt(k):+ if k == "mid_hip":+ return 0.5 * (kp[:, 11] + kp[:, 12])+ if k == "mid_sh":+ return 0.5 * (kp[:, 5] + kp[:, 6])+ return kp[:, k]+ return pt(seg[1]) - pt(seg[0])+++def seg_conf(conf, seg):+ def c(k):+ if k == "mid_hip":+ return np.minimum(conf[:, 11], conf[:, 12])+ if k == "mid_sh":+ return np.minimum(conf[:, 5], conf[:, 6])+ return conf[:, k]+ return np.minimum(c(seg[0]), c(seg[1]))+++def angle_errors(kp_ret, kp_vid, conf, min_conf=0.6, min_len_frac=0.35):+ """Per-segment per-frame angle error (deg), NaN where the video segment+ is unreliable (low confidence, or foreshortened below `min_len_frac` of+ its own 90th-percentile screen length)."""+ out = {}+ for name, seg in SEGMENTS.items():+ a, b = seg_vec(kp_ret, seg), seg_vec(kp_vid, seg)+ la, lb = np.linalg.norm(a, axis=-1), np.linalg.norm(b, axis=-1)+ ok = (seg_conf(conf, seg) >= min_conf) & (lb >= min_len_frac * np.nanpercentile(lb, 90)) & (la > 1.0)+ cosang = np.sum(a * b, -1) / np.maximum(la * lb, 1e-9)+ err = np.degrees(np.arccos(np.clip(cosang, -1, 1)))+ out[name] = np.where(ok, err, np.nan)+ return out+++def summarize(errs):+ allv = np.concatenate([v[~np.isnan(v)] for v in errs.values()])+ rep = {"overall_mean_deg": round(float(allv.mean()), 2),+ "overall_median_deg": round(float(np.median(allv)), 2),+ "overall_p90_deg": round(float(np.percentile(allv, 90)), 2),+ "frames_over_20deg_pct": round(float((allv > 20).mean() * 100), 1)}+ rep["groups_mean_deg"] = {g: round(float(np.nanmean(np.concatenate([errs[s] for s in segs]))), 2)+ for g, segs in GROUPS.items()}+ rep["segments_mean_deg"] = {s: round(float(np.nanmean(v)), 2) for s, v in errs.items()}+ return rep+++FOOT_REST = {"ankle": 0.105, "ball": 0.033} # Y Bot; overridden by --rig-profile+++def contact_metrics(names, J, contacts, prefix, fps, floor=0.0):+ """Skate (cm/s, median over planted frames) and sole height error (cm)."""+ rep = {}+ for k, side in enumerate(("Left", "Right")):+ ank = J[:, names.index(prefix + side + "Foot")]+ ball = J[:, names.index(prefix + side + "ToeBase")]+ c = contacts[:, k]+ mm = c[1:] & c[:-1]+ va = np.linalg.norm(np.diff(ank[:, :2], axis=0), axis=1) * fps * 100+ vb = np.linalg.norm(np.diff(ball[:, :2], axis=0), axis=1) * fps * 100+ v = np.minimum(va, vb) # a pivot moves one of the two, a skate moves both+ rep[side] = {"skate_median_cm_s": round(float(np.median(v[mm])), 2) if mm.any() else None,+ "skate_p90_cm_s": round(float(np.percentile(v[mm], 90)), 2) if mm.any() else None,+ "lowest_point_cm": round(float(np.minimum(ank[:, 2] - FOOT_REST["ankle"],+ ball[:, 2] - FOOT_REST["ball"])[c].mean() * 100), 2)}+ return rep+++def jitter(J, fps):+ """Mean joint jerk magnitude (m/s^3) — lower is smoother."""+ jerk = np.diff(J, 3, axis=0) * fps ** 3+ return round(float(np.linalg.norm(jerk, axis=-1).mean()), 1)+++def foot_direction_errors(names, J_src, cam_mw, K, prefix, feet_kp, min_conf=0.6, min_len_px=12.0):+ """On-screen angle between each foot of the clip (ankle -> toe tip:+ Foot head -> Toe_End head) and the performer's foot as MediaPipe sees+ it (ankle 27/28 -> toe tip 31/32), per plate frame. NaN where the+ detection is weak or the foot points at the camera (too short on+ screen for its direction to mean anything)."""+ out = {}+ for side, (a_id, t_id) in (("L foot", (27, 31)), ("R foot", (28, 32))):+ pre = "Left" if side[0] == "L" else "Right"+ a = project(J_src[:, names.index(prefix + pre + "Foot")], cam_mw, K)+ t = project(J_src[:, names.index(prefix + pre + "Toe_End")], cam_mw, K)+ va, vb = t - a, feet_kp[:, t_id, :2] - feet_kp[:, a_id, :2]+ conf = np.minimum(feet_kp[:, a_id, 2] * feet_kp[:, a_id, 3], feet_kp[:, t_id, 2] * feet_kp[:, t_id, 3])+ la, lb = np.linalg.norm(va, axis=-1), np.linalg.norm(vb, axis=-1)+ ok = (conf >= min_conf) & (lb >= min_len_px) & (la > 1.0)+ cosang = np.sum(va * vb, -1) / np.maximum(la * lb, 1e-9)+ out[side] = np.where(ok, np.degrees(np.arccos(np.clip(cosang, -1, 1))), np.nan)+ return out+++def evaluate(spec, clip_dir, vs_dir=None, smplx=None):+ names, J, mot = load_clip(clip_dir)+ if mot is None:+ raise SystemExit(f"{clip_dir} has no motion.npz — the reference clip must come from retarget_smplx.py")+ prefix = "mixamorig:" if names[0].startswith("mixamorig:") else ""+ src = np.load(rpath(smplx or spec.get("smplx") or (rpath(spec["landmarks"]).parent / "smplx.npz")))+ kp = src["kp2d"] # (n_src, 17, 3), source clock+ fps_dst = float(mot["fps"])+ n_src = kp.shape[0]+ fps_src = float(src["fps"])+ # retarget sampled at the exact source times (linear in time)+ u = np.arange(n_src) / fps_src * fps_dst+ i0 = np.clip(np.floor(u).astype(int), 0, J.shape[0] - 1)+ i1 = np.minimum(i0 + 1, J.shape[0] - 1)+ w = (u - i0)[:, None, None]++ def at_src(X):+ return X[i0] * (1 - w) + X[i1] * w++ cam_mw, K = mot["cam_matrix_world"], mot["cam_K"]+ # Which frames a foot is planted: GVHMR's own contact flag on the plate+ # (static confidence > 0.9 on the ankle or the ball), resampled to the+ # clip clock. Independent of either retarget's own locks, so the slide+ # it measures cannot be zero by construction.+ st = np.asarray(src["static_conf"], dtype=np.float64)+ si = np.clip(np.round(np.arange(J.shape[0]) * fps_src / fps_dst).astype(int), 0, st.shape[0] - 1)+ contacts = np.stack([np.maximum(st[si, 0], st[si, 1]) > 0.9,+ np.maximum(st[si, 2], st[si, 3]) > 0.9], 1)+ result = {}+ clips = {"new": (names, J)}+ if vs_dir is not None:+ n2, J2 = load_clip(vs_dir)[:2]+ T = min(J2.shape[0], J.shape[0])+ J2 = J2[:T].copy()+ # in-place legacy clip: give it the new clip's ground trajectory so+ # only the pose is compared+ r_new = J[:T, names.index(prefix + "Hips"), :2]+ r_old = J2[:, n2.index(prefix + "Hips"), :2]+ J2[:, :, :2] += (r_new - r_old)[:, None, :]+ clips["legacy"] = (n2, J2)+ feet_path = rpath(smplx or spec.get("smplx") or (rpath(spec["landmarks"]).parent / "smplx.npz")).with_name("feet2d.npz")+ feet_kp = np.load(feet_path)["kp"] if feet_path.exists() else None+ for key, (nm, JJ) in clips.items():+ JJs = at_src(JJ[: J.shape[0]]) if JJ.shape[0] >= J.shape[0] else \+ at_src(np.concatenate([JJ, np.repeat(JJ[-1:], J.shape[0] - JJ.shape[0], 0)]))+ kp_r = keypoints_2d(nm, JJs, cam_mw, K, prefix)+ errs = angle_errors(kp_r, kp[..., :2], kp[..., 2])+ rep = summarize(errs)+ if feet_kp is not None:+ fe = foot_direction_errors(nm, JJs, cam_mw, K, prefix, feet_kp[: JJs.shape[0]])+ allf = np.concatenate([v[~np.isnan(v)] for v in fe.values()])+ rep["feet_mean_deg"] = round(float(allf.mean()), 2) if len(allf) else None+ rep["feet_p90_deg"] = round(float(np.percentile(allf, 90)), 2) if len(allf) else None+ rep["per_frame_mean_deg"] = [None if np.all(np.isnan(r)) else round(float(np.nanmean(r)), 2)+ for r in np.stack(list(errs.values()), 1)]+ rep["contacts"] = contact_metrics(nm, JJ, contacts[: JJ.shape[0]], prefix, fps_dst)+ rep["jitter_jerk"] = jitter(JJ, fps_dst)+ result[key] = rep+ return result+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("--spec", required=True)+ ap.add_argument("--clip", required=True, help="clip dir with motion.npz (retarget_smplx.py)")+ ap.add_argument("--vs", help="legacy clip dir (curves.json) to measure the same way")+ ap.add_argument("--smplx")+ ap.add_argument("--rig-profile", help="rig profile for the rest ankle/ball heights (default: spec's, else Y Bot)")+ ap.add_argument("--out")+ args = ap.parse_args()+ spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))+ prof = args.rig_profile or spec.get("rig_profile")+ if prof and rpath(prof).exists():+ rest = json.loads(rpath(prof).read_text(encoding="utf-8"))["rest"]+ FOOT_REST.update(ankle=float(rest["l_ankle"][2]), ball=float(rest["l_foot"][2]))+ res = evaluate(spec, rpath(args.clip), rpath(args.vs) if args.vs else None, args.smplx)+ for key, rep in res.items():+ print(f"[{key}] 2D segment angle vs video: mean {rep['overall_mean_deg']} deg, "+ f"median {rep['overall_median_deg']}, p90 {rep['overall_p90_deg']}, "+ f">20deg {rep['frames_over_20deg_pct']}%")+ print(f" groups {rep['groups_mean_deg']} | feet (ankle->toe vs MediaPipe) "+ f"mean {rep.get('feet_mean_deg')} p90 {rep.get('feet_p90_deg')}")+ print(f" contacts {rep['contacts']} | jerk {rep['jitter_jerk']}")+ if args.out:+ rpath(args.out).write_text(json.dumps(res, indent=1), encoding="utf-8")+ print("wrote", rpath(args.out))+++if __name__ == "__main__":+ main()diff --git a/pipeline/refine_smplx.py b/pipeline/refine_smplx.pynew file mode 100644index 0000000..d6891a2--- /dev/null+++ b/pipeline/refine_smplx.py@@ -0,0 +1,299 @@+"""Refine GVHMR's SMPL-X pose against the video's own 2D keypoints.++ tools\\GVHMR\\.venv\\Scripts\\python.exe pipeline\\refine_smplx.py \\+ --smplx plates\\<plate>\\smplx.npz [--out plates\\<plate>\\smplx_refined.npz]++GVHMR regresses a smooth, plausible motion — and, being a regressor+trained on typical motion, it pulls the EXTREMES of fast limbs toward the+mean: on the fight plate the kicking ankle at the apex sits 35-65 px+(0.10-0.18 m) below where ViTPose sees it in the very frames GVHMR was+fed. The legacy lift paid for this by hand (`leg_pose` corrections sized+from a comparison tool). This stage fixes it at the source, in the spirit+of SMPLify: the body pose is optimised so the model's COCO-17 keypoints,+projected through the plate's camera, land on the detected ones — while++ - staying close to GVHMR's pose (the prior: depth, twist, anything a+ 2D view cannot see is left to the estimator),+ - keeping the CORRECTION smooth in time (the motion itself is never+ smoothed: a strike keeps its snap),+ - trusting a keypoint only as much as its detection confidence, with a+ robust loss so one bad detection cannot drag a limb.++Keypoints come from the same mesh-based COCO-17 regressor GVHMR uses, so+the model and the detector name the same anatomical points (a SMPL-X+joint centre is not a COCO keypoint: the hips differ by ~8 cm on screen).++Writes a new smplx.npz (same schema) with the refined body pose and+camera-frame root; the world-frame root orientation receives the same+correction. Runs in the GVHMR venv (torch + CUDA).+"""++from __future__ import annotations++import argparse+import os+import sys+from pathlib import Path++import numpy as np++REPO = Path(__file__).resolve().parents[1]+GVHMR_ROOT = Path(os.environ.get("GVHMR_ROOT", REPO / "tools" / "GVHMR"))+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++# COCO-17: nose, eyes, ears, shoulders, elbows, wrists, hips, knees, ankles.+# Face points span ~25 px on a full-body plate: a 3 px detection error is a+# 10-degree head turn. They get a small weight, and the head and neck a+# strong prior, so the gaze stays GVHMR's (which sees the whole face).+KP_WEIGHT = np.array([0.15, 0.15, 0.15, 0.15, 0.15] + [1.0] * 12, dtype=np.float32)+# Heel and toe tip of each foot (detect_feet.py): they say which way a foot+# points and whether its heel is up. COCO-17 stops at the ankle.+FOOT_WEIGHT = 1.0+# prior weight per body joint (SMPL-X body_pose order, joints 1..21)+JOINT_PRIOR = np.ones(21, dtype=np.float32)+JOINT_PRIOR[[11, 14]] = 6.0 # neck, head+JOINT_PRIOR[[2, 5, 8]] = 2.0 # spine1-3: the torso is well estimated; keep its shape+++def aa_to_mat(aa):+ import torch+ theta = torch.linalg.norm(aa, dim=-1, keepdim=True).clamp_min(1e-8)+ k = aa / theta+ K = torch.zeros(aa.shape[:-1] + (3, 3), device=aa.device, dtype=aa.dtype)+ K[..., 0, 1], K[..., 0, 2] = -k[..., 2], k[..., 1]+ K[..., 1, 0], K[..., 1, 2] = k[..., 2], -k[..., 0]+ K[..., 2, 0], K[..., 2, 1] = -k[..., 1], k[..., 0]+ s, c = torch.sin(theta)[..., None], torch.cos(theta)[..., None]+ eye = torch.eye(3, device=aa.device, dtype=aa.dtype).expand_as(K)+ return eye + s * K + (1 - c) * (K @ K)+++def mat_to_aa(R):+ from pytorch3d.transforms import matrix_to_axis_angle+ return matrix_to_axis_angle(R)+++def gaussian_time(x, sigma: float):+ """Gaussian filter along dim 0 (time) with edge padding."""+ import torch+ if sigma <= 0:+ return x+ r = int(np.ceil(3 * sigma))+ k = torch.exp(-0.5 * (torch.arange(-r, r + 1, device=x.device, dtype=x.dtype) / sigma) ** 2)+ k = k / k.sum()+ pad = torch.cat([x[:1].expand(r, *x.shape[1:]), x, x[-1:].expand(r, *x.shape[1:])], 0)+ return sum(k[i] * pad[i:i + x.shape[0]] for i in range(2 * r + 1))+++# MediaPipe BlazePose ids of the foot keypoints fitted: heel and toe tip,+# per foot, in FOOT_ORDER. SMPL-X counterparts are mesh vertices (smplx+# vertex_ids, OpenPose foot convention); the toe tip sits between the big+# and the second toe, so it blends the big- and small-toe vertices.+FOOT_ORDER = [("L", "heel", 29), ("L", "toe", 31), ("R", "heel", 30), ("R", "toe", 32)]+FOOT_VIDS = {"L": {"heel": 8846, "big": 5770, "small": 5780},+ "R": {"heel": 8635, "big": 8463, "small": 8474}}+++def feet_targets(feet2d: np.ndarray, kp2d: np.ndarray, max_ankle_px: float = 25.0) -> np.ndarray:+ """(T, 4, 3) heel/toe targets (px, conf) from MediaPipe landmarks. A+ foot whose MediaPipe ankle strays from ViTPose's ankle is a tracking+ slip on that frame: its targets get zero weight."""+ T = min(feet2d.shape[0], kp2d.shape[0])+ out = np.zeros((kp2d.shape[0], 4, 3))+ for i, (side, _, mp_id) in enumerate(FOOT_ORDER):+ mp_ank, vit_ank = (27, 15) if side == "L" else (28, 16)+ conf = feet2d[:T, mp_id, 2] * feet2d[:T, mp_id, 3]+ slip = np.linalg.norm(feet2d[:T, mp_ank, :2] - kp2d[:T, vit_ank, :2], axis=-1) > max_ankle_px+ conf = np.where(slip & (kp2d[:T, vit_ank, 2] > 0.5), 0.0, conf)+ out[:T, i, :2] = feet2d[:T, mp_id, :2]+ out[:T, i, 2] = conf+ return out+++def make_model(device):+ """SMPL-X evaluated on just the vertices the fit needs: GVHMR's COCO-17+ regressor support plus the six foot vertices."""+ import torch+ from einops import einsum+ from hmr4d import PROJ_ROOT+ from hmr4d.utils.body_model.smplx_lite import SmplxLite++ class CocoFeet(SmplxLite):+ def __init__(self):+ super().__init__()+ smplx2smpl = torch.load(PROJ_ROOT / "hmr4d/utils/body_model/smplx2smpl_sparse.pt")+ reg = torch.load(PROJ_ROOT / "hmr4d/utils/body_model/smpl_coco17_J_regressor.pt")+ m = torch.matmul(reg, smplx2smpl.to_dense())+ jids, vids = torch.where(m != 0)+ wmat = torch.zeros(len(vids), 17)+ for i, (j, v) in enumerate(zip(jids, vids)):+ wmat[i, j] = m[j, v]+ self.register_buffer("w_coco", wmat, False)+ self.n_coco = len(vids)+ feet = [FOOT_VIDS[sd][k] for sd in ("L", "R") for k in ("heel", "big", "small")]+ allv = torch.cat([vids, torch.tensor(feet)])+ self.v_template = self.v_template[allv].clone()+ self.shapedirs = self.shapedirs[allv].clone()+ self.posedirs = self.posedirs[:, allv].clone()+ self.lbs_weights = self.lbs_weights[allv].clone()++ def forward(self, body_pose, betas, global_orient, transl):+ verts = super().forward(body_pose, betas, global_orient, transl)+ coco = einsum(self.w_coco, verts[..., :self.n_coco, :], "v j, ... v c -> ... j c")+ f = verts[..., self.n_coco:, :] # L heel, big, small, R heel, big, small+ feet = torch.stack([f[..., 0, :], 0.7 * f[..., 1, :] + 0.3 * f[..., 2, :],+ f[..., 3, :], 0.7 * f[..., 4, :] + 0.3 * f[..., 5, :]], -2)+ return torch.cat([coco, feet], -2) # (..., 21, 3)++ return CocoFeet().to(device)+++def refine(z: dict, iters: int = 400, w_prior: float = 4.0, w_smooth: float = 200.0,+ huber_m: float = 0.04, min_conf: float = 0.35, post_sigma: float = 1.0,+ feet2d: np.ndarray | None = None, w_floor: float = 3000.0,+ device: str = "cuda", log=print) -> dict:+ import torch+ os.chdir(GVHMR_ROOT)+ sys.path.insert(0, str(GVHMR_ROOT))++ T = z["body_pose"].shape[0]+ f32 = lambda a: torch.tensor(np.asarray(a), dtype=torch.float32, device=device)+ model = make_model(device)+ betas = f32(z["betas"])[None].repeat(T, 1)+ bp0 = f32(z["incam_body_pose"])+ go0 = f32(z["incam_global_orient"])+ tr0 = f32(z["incam_transl"])+ K = f32(z["K"])+ ft = feet_targets(feet2d, z["kp2d"]) if feet2d is not None else np.zeros((T, 4, 3))+ kp = f32(np.concatenate([z["kp2d"], ft], 1)) # (T, 21, 3): COCO-17 + heels/toes+ conf = kp[..., 2]+ kw = np.concatenate([KP_WEIGHT, np.full(4, FOOT_WEIGHT, dtype=np.float32)])+ w = torch.where(conf >= min_conf, conf ** 2, torch.zeros_like(conf)) * f32(kw)[None]++ # World "up" seen from the camera (GVHMR's world is gravity-aligned; the+ # camera is static, so one direction for the whole take).+ Rw = aa_to_mat(f32(z["global_orient"]))+ M = Rw @ aa_to_mat(go0).transpose(-1, -2) # world-from-camera, per frame+ up_c = M.transpose(-1, -2)[:, :, 1] # (T, 3): the retarget's up, per frame+ # Both feet planted (GVHMR's contact detector): the floor is flat, so+ # their lowest points share one height. A 2D fit cannot see depth, and+ # without this it tilts a wide stance — measured on the kung-fu plate:+ # one foot 12 cm above the other, not a pixel off in the image.+ st = np.nan_to_num(np.asarray(z["static_conf"], dtype=np.float64))+ both = np.minimum(st[:, [0, 1]].max(1), st[:, [2, 3]].max(1))+ w_both = f32(np.where(both > 0.5, both, 0.0))++ with torch.no_grad():+ J0 = model(body_pose=bp0, betas=betas, global_orient=go0, transl=tr0) # (T, 21, 3) camera+ depth = J0[..., 2].mean(-1, keepdim=True).clamp_min(0.5) # per-frame subject depth+ px_per_m = K[0, 0] / depth # (T, 1)++ jp = f32(JOINT_PRIOR)[None]+ d_bp = torch.zeros_like(bp0, requires_grad=True)+ d_go = torch.zeros_like(go0, requires_grad=True)+ d_tr = torch.zeros_like(tr0, requires_grad=True)+ opt = torch.optim.Adam([d_bp, d_go, d_tr], lr=0.01)++ def reproj(J):+ z_ = J[..., 2].clamp_min(0.1)+ return torch.stack([K[0, 0] * J[..., 0] / z_ + K[0, 2], K[1, 1] * J[..., 1] / z_ + K[1, 2]], -1)++ def second_diff(x):+ return x[2:] - 2 * x[1:-1] + x[:-2]++ def loss_terms():+ R0 = aa_to_mat(go0)+ go = mat_to_aa(aa_to_mat(d_go) @ R0)+ J = model(body_pose=bp0 + d_bp, betas=betas, global_orient=go, transl=tr0 + d_tr)+ r = (reproj(J) - kp[..., :2]).norm(dim=-1) / px_per_m # metres at the subject+ hub = torch.where(r < huber_m, 0.5 * r ** 2, huber_m * (r - 0.5 * huber_m))+ l2d = (w * hub).sum() / w.sum().clamp_min(1.0)+ lprior = (((d_bp.view(T, 21, 3) ** 2).sum(-1) * jp).mean() / 3.0 + 2.0 * (d_go ** 2).mean()+ + 4.0 * (d_tr ** 2).mean())+ h = (J[:, 17:21] * up_c[:, None, :]).sum(-1) # heights of heels / toe tips+ low_l, low_r = torch.minimum(h[:, 0], h[:, 1]), torch.minimum(h[:, 2], h[:, 3])+ lfloor = (w_both * (low_l - low_r) ** 2).sum() / w_both.sum().clamp_min(1.0)+ lsm = (second_diff(d_bp) ** 2).mean() + (second_diff(d_go) ** 2).mean() + 10.0 * (second_diff(d_tr) ** 2).mean()+ return l2d, lprior, lsm, r, lfloor++ with torch.no_grad():+ _, _, _, r_before, fl_before = loss_terms()+ for it in range(iters):+ opt.zero_grad()+ l2d, lprior, lsm, _, lfloor = loss_terms()+ loss = 1000.0 * l2d + w_prior * lprior + w_smooth * lsm + w_floor * lfloor+ loss.backward()+ opt.step()+ if it in (0, iters // 2, iters - 1):+ log(f" iter {it:4d} 2D {l2d.item() * 1000:.3f} prior {lprior.item():.5f} smooth {lsm.item():.6f}")+ with torch.no_grad():+ # A correction that lives for one frame is detector noise; one that+ # lasts (a kick apex spans 5-8 frames) is signal. Low-pass the+ # correction itself, never the motion.+ for d in (d_bp, d_go, d_tr):+ d.copy_(gaussian_time(d, float(post_sigma)))+ _, _, _, r_after, fl_after = loss_terms()+ go_new = mat_to_aa(aa_to_mat(d_go) @ aa_to_mat(go0))++ valid = (w > 0)+ fv = valid[:, 17:]+ stats = {"feet_before_cm": float(r_before[:, 17:][fv].mean() * 100) if fv.any() else float("nan"),+ "feet_after_cm": float(r_after[:, 17:][fv].mean() * 100) if fv.any() else float("nan"),+ "reproj_before_cm": float((r_before[valid]).mean() * 100),+ "reproj_after_cm": float((r_after[valid]).mean() * 100),+ "reproj_p95_before_cm": float(torch.quantile(r_before[valid], 0.95) * 100),+ "reproj_p95_after_cm": float(torch.quantile(r_after[valid], 0.95) * 100),+ "planted_feet_level_cm": [float(fl_before.sqrt() * 100), float(fl_after.sqrt() * 100)],+ "max_joint_change_deg": float(torch.linalg.norm(d_bp.view(T, 21, 3), dim=-1).max() * 57.2958)}++ out = dict(z)+ bp_new = (bp0 + d_bp).detach().cpu().numpy().astype(np.float64)+ out["body_pose"] = bp_new+ out["incam_body_pose"] = bp_new+ out["incam_global_orient"] = go_new.cpu().numpy().astype(np.float64)+ out["incam_transl"] = (tr0 + d_tr).detach().cpu().numpy().astype(np.float64)+ # world root: the same rotation correction, carried through the per-frame+ # world-from-camera rotation GVHMR implies (R_w = M R_c, M fixed)+ Rw = aa_to_mat(f32(z["global_orient"]))+ Rc_old, Rc_new = aa_to_mat(go0), aa_to_mat(go_new)+ Rw_new = Rw @ Rc_old.transpose(-1, -2) @ Rc_new+ out["global_orient"] = mat_to_aa(Rw_new).cpu().numpy().astype(np.float64)+ # ...and the root's move: the pelvis shifted by d_tr in the camera frame,+ # so by M d_tr in the world (rotations turn the body about the pelvis)+ out["transl"] = (f32(z["transl"]) + torch.einsum("tij,tj->ti", M, d_tr.detach())).cpu().numpy().astype(np.float64)+ out["refined"] = np.array(True)+ out["feet2d"] = ft # heel/toe targets used (px, conf)+ return out, stats+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("--smplx", required=True)+ ap.add_argument("--out", help="default: <smplx>_refined.npz beside the input")+ ap.add_argument("--iters", type=int, default=400)+ ap.add_argument("--prior", type=float, default=4.0, help="pull toward GVHMR's pose (higher = closer)")+ ap.add_argument("--smooth", type=float, default=200.0, help="smoothness of the correction over time")+ ap.add_argument("--feet", help="feet2d.npz from detect_feet.py (default: next to --smplx)")+ args = ap.parse_args()+ src = rpath(args.smplx)+ z = dict(np.load(src, allow_pickle=False))+ feet = rpath(args.feet) if args.feet else src.with_name("feet2d.npz")+ feet2d = np.load(feet)["kp"] if feet.exists() else None+ print(f"foot keypoints: {feet if feet2d is not None else 'none (run detect_feet.py for heel/toe fitting)'}")+ out, stats = refine(z, iters=args.iters, w_prior=args.prior, w_smooth=args.smooth, feet2d=feet2d)+ dst = rpath(args.out) if args.out else src.with_name(src.stem + "_refined.npz")+ np.savez_compressed(dst, **out)+ print(f"wrote {dst}")+ print(" keypoint error at the subject: mean {reproj_before_cm:.1f} -> {reproj_after_cm:.1f} cm, "+ "p95 {reproj_p95_before_cm:.1f} -> {reproj_p95_after_cm:.1f} cm; heel/toe "+ "{feet_before_cm:.1f} -> {feet_after_cm:.1f} cm; largest joint change "+ "{max_joint_change_deg:.1f} deg".format(**stats))+++if __name__ == "__main__":+ main()diff --git a/pipeline/render_review.py b/pipeline/render_review.pynew file mode 100644index 0000000..53dd96b--- /dev/null+++ b/pipeline/render_review.py@@ -0,0 +1,206 @@+"""Review videos for an SMPL-X clip — rendered headlessly, no Blender UI or MCP.++ python pipeline/render_review.py --spec action_specs/<motion>.json --clip clips/<clip> \+ [--legacy clips/<legacy_clip>] [--scene ybot_rest.blend] [--views front,three_quarter]++Writes into the clip folder, per view (front, three_quarter):+ review_<view>.mp4 a 2x2 grid, time-aligned and labelled:+ SOURCE plate | OVERLAY+ BEFORE (legacy clip) | AFTER (this clip)+ OVERLAY is this clip rendered through the PLATE'S OWN+ CAMERA (recovered by retarget_smplx.py) and composited+ over the video: where the character and the performer+ disagree, you see it. Without --legacy the bottom row+ shows this clip from two angles.+Frames are rendered with bl_motion.py in background Blender and removed+afterwards (--keep-frames to keep them). The legacy clip, if given, is+re-keyed from its curves.json onto the same rig and rendered with the+same camera and look, so the two differ by their motion only.+"""++from __future__ import annotations++import argparse+import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import av+import cv2+import numpy as np++REPO = Path(__file__).resolve().parents[1]+BLENDER_CANDIDATES = [+ os.environ.get("BLENDER", ""),+ r"C:\Program Files\Blender Foundation\Blender 5.1\blender.exe",+ r"C:\Program Files\Blender Foundation\Blender 5.2\blender.exe",+ "/Applications/Blender.app/Contents/MacOS/Blender",+ "blender",+]+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++def blender_exe(arg=None) -> str:+ for c in ([arg] if arg else []) + BLENDER_CANDIDATES:+ if c and (Path(c).exists() or shutil.which(c)):+ return c+ raise SystemExit("Blender not found — pass --blender or set BLENDER")+++def render(blender, scene, src_flag, src_path, view, out_dir, extra=()):+ out_dir.mkdir(parents=True, exist_ok=True)+ cmd = [blender, "-b", str(scene), "--python", str(REPO / "pipeline" / "bl_motion.py"), "--",+ "render", src_flag, str(src_path), "--view", view, "--out", str(out_dir), *extra]+ res = subprocess.run(cmd, capture_output=True, text=True)+ if res.returncode != 0 or not any(out_dir.glob("f*.png")):+ sys.stderr.write(res.stdout[-3000:] + res.stderr[-3000:])+ raise SystemExit(f"render failed: {view} {src_path}")+ return sorted(out_dir.glob("f*.png"))+++def read_plate(video: Path):+ cap = cv2.VideoCapture(str(video))+ fps = cap.get(cv2.CAP_PROP_FPS) or 24.0+ frames = []+ while True:+ ok, im = cap.read()+ if not ok:+ break+ frames.append(im)+ cap.release()+ return frames, fps+++def label(img, text, sub=None):+ """Title (+ subtitle) on a translucent dark band, legible on any frame."""+ (tw, _), _ = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, 0.75, 2)+ sw = cv2.getTextSize(sub, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)[0][0] if sub else 0+ x1, y1 = 10 + max(tw, sw) + 20, (68 if sub else 46)+ band = img[8:y1, 8:x1].astype(np.float32)+ img[8:y1, 8:x1] = (band * 0.35 + np.array([28, 24, 22], np.float32) * 0.65).astype(np.uint8)+ cv2.putText(img, text, (18, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (255, 255, 255), 2, cv2.LINE_AA)+ if sub:+ cv2.putText(img, sub, (18, 58), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (215, 215, 215), 1, cv2.LINE_AA)+ return img+++def fit_h(img, h):+ return cv2.resize(img, (int(round(img.shape[1] * h / img.shape[0])) // 2 * 2, h),+ interpolation=cv2.INTER_AREA)+++def encode(path: Path, frames_iter, fps: int, crf: int = 26):+ first = next(frames_iter)+ h, w = first.shape[:2]+ container = av.open(str(path), "w")+ stream = container.add_stream("libx264", rate=fps)+ stream.width, stream.height = w, h+ stream.pix_fmt = "yuv420p"+ stream.options = {"crf": str(crf), "preset": "slow", "movflags": "+faststart"}++ def put(img):+ fr = av.VideoFrame.from_ndarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), format="rgb24")+ for pkt in stream.encode(fr):+ container.mux(pkt)++ put(first)+ for img in frames_iter:+ put(img)+ for pkt in stream.encode():+ container.mux(pkt)+ container.close()+++def main():+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("--spec", required=True)+ ap.add_argument("--clip", required=True, help="clip dir holding motion.npz")+ ap.add_argument("--legacy", help="legacy clip dir (curves.json) to show next to it")+ ap.add_argument("--scene", default="ybot_rest.blend", help="the rig's rest scene (.blend)")+ ap.add_argument("--video", help="source plate (default: first .mp4 next to the spec's landmarks)")+ ap.add_argument("--views", default="front,three_quarter")+ ap.add_argument("--blender")+ ap.add_argument("--keep-frames", action="store_true")+ ap.add_argument("--reuse-frames", action="store_true", help="skip rendering where frames exist")+ args = ap.parse_args()++ spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))+ clip = rpath(args.clip)+ motion = clip / "motion.npz"+ if not motion.exists():+ raise SystemExit(f"{motion} missing — run retarget_smplx.py first")+ video = rpath(args.video) if args.video else sorted(rpath(spec["landmarks"]).parent.glob("*.mp4"))[0]+ blender = blender_exe(args.blender)+ scene = rpath(args.scene)+ plate, plate_fps = read_plate(video)+ fps = int(round(float(np.load(motion)["fps"])))+ work = clip / "_frames"+ views = [v for v in args.views.split(",") if v]++ def frames_of(flag, path, view, name):+ d = work / name+ if args.reuse_frames and any(d.glob("f*.png")):+ return sorted(d.glob("f*.png"))+ shutil.rmtree(d, ignore_errors=True)+ return render(blender, scene, flag, path, view, d)++ cam = frames_of("--motion", motion, "camera", "new_camera")+ new = {v: frames_of("--motion", motion, v, f"new_{v}") for v in views}+ old = ({v: frames_of("--curves", rpath(args.legacy) / "curves.json", v, f"old_{v}") for v in views}+ if args.legacy else None)+ W, H = 640, 360 # one cell of the 2x2 grid++ def plate_at(i):+ return plate[min(len(plate) - 1, int(round(i / fps * plate_fps)))]++ def cell(img):+ return cv2.resize(img, (W, H), interpolation=cv2.INTER_AREA)++ def overlay(i):+ src = plate_at(i).astype(np.float32)+ rgba = cv2.imread(str(cam[min(i, len(cam) - 1)]), cv2.IMREAD_UNCHANGED).astype(np.float32)+ if rgba.shape[:2] != src.shape[:2]:+ rgba = cv2.resize(rgba, (src.shape[1], src.shape[0]))+ a = rgba[..., 3:4] / 255.0 * 0.62+ return (src * (1 - a) + rgba[..., :3] * a).astype(np.uint8)++ def grid(view):+ for i in range(len(cam)):+ tl = label(cell(plate_at(i)), "SOURCE VIDEO")+ tr = label(cell(overlay(i)), "OVERLAY", "new retarget seen by the plate's camera")+ if old is not None:+ bl = label(cell(cv2.imread(str(old[view][min(i, len(old[view]) - 1)]))),+ "BEFORE", "landmark lift + FK aim")+ br = label(cell(cv2.imread(str(new[view][min(i, len(new[view]) - 1)]))),+ "AFTER", "SMPL-X rotation retarget")+ else:+ other = [v for v in views if v != view] or [view]+ bl = label(cell(cv2.imread(str(new[view][min(i, len(new[view]) - 1)]))),+ "AFTER", view.replace("_", "-"))+ br = label(cell(cv2.imread(str(new[other[0]][min(i, len(new[other[0]]) - 1)]))),+ "AFTER", other[0].replace("_", "-"))+ g = np.vstack([np.hstack([tl, tr]), np.hstack([bl, br])])+ g[H - 1:H + 1, :] = 24+ g[:, W - 1:W + 1] = 24+ yield g++ for view in views:+ out = clip / f"review_{view}.mp4"+ encode(out, grid(view), fps, crf=27)+ print("wrote", out)+ if old is None:+ break # one grid already shows both views++ if not args.keep_frames:+ shutil.rmtree(work, ignore_errors=True)+++if __name__ == "__main__":+ main()diff --git a/pipeline/retarget_smplx.py b/pipeline/retarget_smplx.pynew file mode 100644index 0000000..c2693ea--- /dev/null+++ b/pipeline/retarget_smplx.py@@ -0,0 +1,1113 @@+"""SMPL-X rotation retarget: GVHMR's joint ROTATIONS -> any Mixamo rig.++ python pipeline/retarget_smplx.py --spec action_specs/<motion>.json+ [--rig-profile rig_profiles/ybot.json] [--out-dir clips/<clip>]++Reads the estimator's SMPL-X parameters (smplx.npz, written by+estimate_pose_gvhmr.py) and writes <clip_dir>/motion.npz — quaternions+for every bone, Hips location, and the plate's camera — which+bl_motion.py keys onto the rig headlessly (`apply`, `render`).++Why rotations and not landmarks+ The legacy lift (lift_to_mixamo.py) reduces the body to 33 points+ and rebuilds the pose by aiming bones at them. Positions cannot say+ how a forearm, a chest or a head is TWISTED, so twist was invented:+ the spine was synthesized from the hip/shoulder lines, the hand was+ aimed along the forearm, the head re-aimed from gaze heuristics.+ SMPL-X already solved all of that. Here every Mixamo bone receives the+ rotation of its SMPL-X joint:++ P_b(t) = S_j(t) . A_b . B_b (armature space)++ S_j world rotation of SMPL-X joint j (identity at the SMPL-X rest)+ B_b rest rotation of Mixamo bone b+ A_b rest alignment: the minimal rotation taking the Mixamo bone's+ rest direction onto the SMPL-X one, for the LIMBS only. It+ cancels rest-pose differences (SMPL-X arms hang ~16 deg below a+ T-pose) so they don't bias every frame. Feet are aligned in yaw+ only, on the foot's visible heel-to-toes axis. Spine, neck, head+ and collars are left unaligned: there the skeletons differ in how+ they divide the body, not in pose, and "correcting" that injects+ error (a hunched spine, raised shoulders).++ A Mixamo armature's own space (inside its X+90 import rotation) is+ already SMPL-X's: X left, Y up, Z forward — no axis conversion.++What cannot be copied, and is solved instead+ - proportions: the root follows the performer's trajectory scaled by+ the LEG-length ratio; each leg is re-solved (two-bone IK, knee kept+ in the source's plane) so the ankle lands where the performer's+ scaled leg puts it.+ - the floor: GVHMR's world trajectory drifts vertically (a performer+ floating 15 cm above the floor mid-clip is typical). The camera+ removes the drift; frames with a planted foot put the lowest sole on+ the floor; flight frames keep the source arc.+ - foot contacts: a foot is planted when the network's contact detector+ says so, when its sole sits still on the floor, or when it does not+ move on screen. Planted segments lock flat, or pivot on the ball+ (heel raised) or briefly on the heel (toes up), with short ramps in+ and out; a real slide is left to slide.+ - hands: GVHMR estimates no fingers; they hold a relaxed curl, closing+ into the rig-validated fist inside the spec's `fists` windows.+"""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++import numpy as np++sys.path.insert(0, str(Path(__file__).resolve().parent))+import smplx_body as SB # noqa: E402++REPO = Path(__file__).resolve().parents[1]++# SMPL-X body joint -> Mixamo bone (without the "mixamorig:" prefix).+JOINT_TO_BONE = {+ 0: "Hips", 1: "LeftUpLeg", 2: "RightUpLeg", 3: "Spine", 4: "LeftLeg", 5: "RightLeg",+ 6: "Spine1", 7: "LeftFoot", 8: "RightFoot", 9: "Spine2", 10: "LeftToeBase",+ 11: "RightToeBase", 12: "Neck", 13: "LeftShoulder", 14: "RightShoulder", 15: "Head",+ 16: "LeftArm", 17: "RightArm", 18: "LeftForeArm", 19: "RightForeArm",+ 20: "LeftHand", 21: "RightHand",+}+# Joints whose rest DIRECTION is aligned (joint -> the child it points at).+ALIGN = {1: 4, 2: 5, 4: 7, 5: 8, 16: 18, 17: 19, 18: 20, 19: 21}+# Feet are aligned in YAW only (both rigs stand flat-footed at rest; only+# the toe-out differs), measured on the foot's visible axis — see+# foot_yaw_offset().+FEET = {7: "L", 8: "R"}+# Leaves carry their parent's alignment (a hand continues its forearm,+# toes continue their foot) — aligning a leaf on its own would measure+# the parent's geometry, not a pose difference.+INHERIT = {10: 7, 11: 8, 20: 18, 21: 19}++LEGS = {"L": (1, 4, 7, 10), "R": (2, 5, 8, 11)} # hip, knee, ankle, ball (SMPL-X)+STATIC = {"L": (0, 1), "R": (2, 3)} # static_conf columns (ankle, ball)+++def rpath(p) -> Path:+ p = Path(p)+ return p if p.is_absolute() else (REPO / p)+++def smootherstep(x):+ x = np.clip(x, 0.0, 1.0)+ return x * x * x * (x * (x * 6.0 - 15.0) + 10.0)+++def gaussian_smooth(x: np.ndarray, sigma: float) -> np.ndarray:+ """Gaussian smoothing along axis 0 with edge padding (no scipy)."""+ if sigma <= 0:+ return np.array(x, copy=True)+ r = int(np.ceil(3 * sigma))+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2)+ k /= k.sum()+ pad = np.concatenate([np.repeat(x[:1], r, 0), x, np.repeat(x[-1:], r, 0)], 0)+ out = np.zeros_like(np.asarray(x, dtype=np.float64))+ for i, w in enumerate(k):+ out += w * pad[i:i + x.shape[0]]+ return out+++def runs(mask: np.ndarray):+ """(start, end_inclusive) of each True run."""+ out, start = [], None+ for i, m in enumerate(mask):+ if m and start is None:+ start = i+ elif not m and start is not None:+ out.append((start, i - 1))+ start = None+ if start is not None:+ out.append((start, len(mask) - 1))+ return out+++def clean_mask(mask: np.ndarray, min_len: int, max_gap: int) -> np.ndarray:+ """Fill short gaps, then drop runs shorter than min_len."""+ m = mask.copy()+ for a, b in runs(~m):+ if a > 0 and b < len(m) - 1 and (b - a + 1) <= max_gap:+ m[a:b + 1] = True+ for a, b in runs(m):+ if b - a + 1 < min_len:+ m[a:b + 1] = False+ return m+++# ---------------------------------------------------------------------------+# the target rig++class Rig:+ """A Mixamo armature as retargeting needs it: rest rotations, rest+ head positions (METRES, armature space) and the parent table."""++ def __init__(self, profile: dict):+ if "bones" not in profile:+ raise SystemExit("rig profile has no bone table — run: blender -b <rig>_rest.blend "+ "-P pipeline/bl_motion.py -- dump-rig --profile <profile.json>")+ bones = profile["bones"]+ self.names = [b["name"] for b in bones]+ self.index = {n: i for i, n in enumerate(self.names)}+ self.parent = np.array([self.index[b["parent"]] if b["parent"] else -1 for b in bones])+ M = np.array([b["matrix_local"] for b in bones], dtype=np.float64)+ aw = np.array(profile["armature_matrix_world"], dtype=np.float64)+ self.unit = 1.0 / float(np.linalg.norm(aw[:3, 0])) # armature units per metre (100 on FBX)+ self.arm_rot = aw[:3, :3] / np.linalg.norm(aw[:3, 0]) # armature axes -> Blender world axes+ self.arm_loc = aw[:3, 3]+ self.R = M[:, :3, :3]+ self.head = M[:, :3, 3] / self.unit+ self.rest_rel = np.empty((len(bones), 3, 3))+ for i, p in enumerate(self.parent):+ self.rest_rel[i] = self.R[i] if p < 0 else self.R[p].T @ self.R[i]+ self.floor = float(profile.get("mesh_floor_y", 0.0)) / self.unit+ self.prefix = "mixamorig:" if any(n.startswith("mixamorig:") for n in self.names) else ""+ self.root = self.bone("Hips")+ self.joint_bone = {j: self.bone(b) for j, b in JOINT_TO_BONE.items()}+ missing = [JOINT_TO_BONE[j] for j, b in self.joint_bone.items() if b is None]+ if missing:+ raise SystemExit(f"rig lacks bones {missing}")++ def bone(self, short):+ return self.index.get(self.prefix + short, self.index.get(short))++ def leg_length(self, side="Left"):+ a, b, c = (self.head[self.bone(f"{side}{n}")] for n in ("UpLeg", "Leg", "Foot"))+ return float(np.linalg.norm(b - a) + np.linalg.norm(c - b))++ def chain_positions(self, P: np.ndarray, root_pos: np.ndarray) -> np.ndarray:+ """Head position of every bone (T,B,3) from world rotations P (T,B,3,3)."""+ T, B = P.shape[:2]+ pos = np.empty((T, B, 3))+ for i in range(B):+ p = self.parent[i]+ if p < 0:+ pos[:, i] = root_pos+ else:+ local = self.R[p].T @ (self.head[i] - self.head[p])+ pos[:, i] = pos[:, p] + np.einsum("tij,j->ti", P[:, p], local)+ return pos++ def attached(self, P, pos, b, rest_point):+ """World position of a point rigidly attached to bone b (rest coords)."""+ local = self.R[b].T @ (np.asarray(rest_point, dtype=np.float64) - self.head[b])+ return pos[:, b] + np.einsum("tij,j->ti", P[:, b], local)+++# ---------------------------------------------------------------------------+# procedural hands (no finger data in GVHMR)++def fist_quats() -> dict:+ """The rig-validated procedural fist of apply_mixamo_fk (curl = +X on+ this skeleton, thumb folds on a negative-X mix). Local rotations."""+ seg1 = (0.766044, 0.642788, 0.0, 0.0)+ seg2 = (0.67559, 0.737277, 0.0, 0.0)+ seg3 = (0.906308, 0.422618, 0.0, 0.0)+ out = {}+ for side, zs in (("Left", -1.0), ("Right", 1.0)):+ out[f"{side}HandThumb1"] = (0.961, 0.069, 0.165 * zs, 0.207 * zs)+ out[f"{side}HandThumb2"] = (0.766, -0.399, 0.161 * zs, 0.476 * zs)+ out[f"{side}HandThumb3"] = (0.940, -0.210, 0.136 * zs, 0.231 * zs)+ for fn in ("Index", "Middle", "Ring", "Pinky"):+ out[f"{side}Hand{fn}1"] = seg1+ out[f"{side}Hand{fn}2"] = seg2+ out[f"{side}Hand{fn}3"] = seg3+ return out+++def window_amount(frames_src: np.ndarray, rise, fall) -> np.ndarray:+ """0 -> 1 over `rise` (src frames), 1 -> 0 over `fall`, smooth edges."""+ up = smootherstep((frames_src - rise[0]) / max(1e-6, rise[1] - rise[0]))+ down = 1.0 - smootherstep((frames_src - fall[0]) / max(1e-6, fall[1] - fall[0]))+ return np.minimum(up, down)+++# ---------------------------------------------------------------------------+# the retarget++def load_source(path: Path) -> dict:+ z = np.load(path, allow_pickle=False)+ src = {k: z[k] for k in z.files}+ src["foot"] = json.loads(str(src["foot"]))+ return src+++def catmull_rom(x: np.ndarray, u: np.ndarray) -> np.ndarray:+ """Interpolate samples x[0..n-1] (axis 0) at fractional positions u with+ a C1 Catmull-Rom spline. Linear interpolation between 24 fps samples+ puts a velocity kink at every source frame — a jerk spike every fourth+ frame at 30 fps, which reads as a faint stutter."""+ n = x.shape[0]+ i = np.clip(np.floor(u).astype(int), 0, n - 1)+ t = (u - i).reshape(-1, *([1] * (x.ndim - 1)))+ p0, p1 = x[np.clip(i - 1, 0, n - 1)], x[i]+ p2, p3 = x[np.clip(i + 1, 0, n - 1)], x[np.clip(i + 2, 0, n - 1)]+ return 0.5 * (2 * p1 + (p2 - p0) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t ** 2+ + (3 * p1 - p0 - 3 * p2 + p3) * t ** 3)+++def one_euro(x: np.ndarray, fps: float, min_cutoff: float, beta: float, d_cutoff: float = 1.0):+ """Zero-phase One-Euro filter along axis 0 of (T, J, D): an adaptive+ low-pass whose cutoff rises with speed. Holds and slow drifts are+ smoothed hard (that is where estimator jitter shows); a punch or a kick+ raises the cutoff and passes almost untouched — a fixed smoothing+ window cannot do both (docs/PITFALLS.md #18, #32). Run forward then+ backward so it adds no lag."""+ def alpha(cutoff):+ tau = 1.0 / (2.0 * np.pi * cutoff)+ return 1.0 / (1.0 + tau * fps)++ def one_pass(v):+ out = np.empty_like(v)+ out[0] = v[0]+ dx_prev = np.zeros(v.shape[1:])+ ad = alpha(d_cutoff)+ for t in range(1, v.shape[0]):+ dx = (v[t] - out[t - 1]) * fps+ dx_hat = ad * dx + (1.0 - ad) * dx_prev+ speed = np.linalg.norm(dx_hat, axis=-1, keepdims=True)+ a = alpha(min_cutoff + beta * speed)+ out[t] = a * v[t] + (1.0 - a) * out[t - 1]+ dx_prev = dx_hat+ return out++ return one_pass(one_pass(x)[::-1])[::-1]+++def resample_source(src: dict, dst_fps: float, smooth: dict | None = None):+ """Source clock (plate fps) -> destination clock. Local rotations are+ interpolated as unrolled quaternions on a C1 spline (then normalised),+ translation on the same spline, confidences linearly. Optional One-Euro+ smoothing runs on the source samples first (`smooth`)."""+ fps = float(src["fps"])+ n = src["body_pose"].shape[0]+ local_aa = np.concatenate([src["global_orient"].reshape(n, 1, 3),+ src["body_pose"].reshape(n, 21, 3)], axis=1)+ q = SB.quat_unroll(SB.matrix_to_quat(SB.axis_angle_to_matrix(local_aa)))+ transl = np.asarray(src["transl"], dtype=np.float64)+ if smooth:+ q = one_euro(q, fps, float(smooth["min_cutoff"]), float(smooth["beta"]))+ q /= np.linalg.norm(q, axis=-1, keepdims=True)+ transl = one_euro(transl[:, None, :], fps, float(smooth["min_cutoff"]) * 1.5,+ float(smooth["beta"]) * 2.0)[:, 0]+ duration = (n - 1) / fps+ n_dst = int(round(duration * dst_fps)) + 1+ u = np.clip(np.arange(n_dst) / dst_fps * fps, 0, n - 1)+ qd = catmull_rom(q, u)+ qd /= np.linalg.norm(qd, axis=-1, keepdims=True)+ i0 = np.floor(u).astype(int)+ i1 = np.minimum(i0 + 1, n - 1)+ w = u - i0+ static = src["static_conf"]+ if np.isnan(static).any():+ static = np.zeros_like(static)+ static_d = static[i0] * (1 - w)[:, None] + static[i1] * w[:, None]+ return {"local": SB.quat_to_matrix(qd), "transl": catmull_rom(transl, u),+ "static": static_d, "src_frame": u + 1.0, "n": n_dst}+++def static_camera(src: dict, rest_joints: np.ndarray, frames: slice):+ """The plate's (static) camera in GVHMR's world: camera->world rotation+ and position, fitted over `frames` (rotation: chordal L2 mean)."""+ Rw = SB.axis_angle_to_matrix(src["global_orient"])+ Rc = SB.axis_angle_to_matrix(src["incam_global_orient"])+ pw = rest_joints[0] + src["transl"]+ pc = rest_joints[0] + src["incam_transl"]+ Rc2w = Rw @ np.transpose(Rc, (0, 2, 1))+ U, _, Vt = np.linalg.svd(Rc2w[frames].sum(0))+ R = U @ Vt+ if np.linalg.det(R) < 0:+ U[:, -1] *= -1+ R = U @ Vt+ t = (pw[frames] - np.einsum("ij,tj->ti", R, pc[frames])).mean(0)+ return R, t+++def ramp_weights(segs, T: int, ramp: int, select=None):+ """Per-frame weight and owning segment of contact segments: 1 inside,+ easing to 0 over `ramp` frames outside; the nearest segment wins."""+ w = np.zeros(T)+ owner = np.full(T, -1)+ for k, (a, b) in enumerate(segs):+ if select is not None and not select(k):+ continue+ for t in range(max(0, a - ramp), min(T, b + ramp + 1)):+ d = 0 if a <= t <= b else (a - t if t < a else t - b)+ wt = 1.0 if d == 0 else float(smootherstep(1.0 - d / (ramp + 1)))+ if wt > w[t]:+ w[t], owner[t] = wt, k+ return w, owner+++def still_in_image(src: dict, rs: dict, still_px: float, min_conf: float = 0.5):+ """(T, 2) bool per foot (L, R) at the destination clock: the foot does+ not move ON SCREEN. The camera is static, so a foot still in the image+ is still in the world — the most direct contact evidence there is, and+ independent of GVHMR's contact flag and of the 3D fit (both of which+ can move a foot the video shows planted). Uses the ankle (ViTPose) and,+ when detect_feet.py ran, the heel and toe tip (MediaPipe): the median+ speed of the confident points, in pixels per second."""+ fps = float(src["fps"])+ kp = np.asarray(src["kp2d"], dtype=np.float64)+ pts = {"L": [kp[:, 15]], "R": [kp[:, 16]]}+ if "feet2d" in src:+ f2 = np.asarray(src["feet2d"], dtype=np.float64)+ pts["L"] += [f2[:, 0], f2[:, 1]]+ pts["R"] += [f2[:, 2], f2[:, 3]]+ n = kp.shape[0]+ out = np.zeros((rs["n"], 2), dtype=bool)+ u = np.clip(np.round(rs["src_frame"] - 1.0).astype(int), 0, n - 1)+ for k, side in enumerate(("L", "R")):+ speeds = []+ for p in pts[side]:+ v = np.zeros(n)+ v[1:] = np.linalg.norm(np.diff(p[:, :2], axis=0), axis=1) * fps+ ok = np.minimum(p[:, 2], np.r_[p[:1, 2], p[:-1, 2]]) >= min_conf+ speeds.append(np.where(ok, v, np.nan))+ sp = np.nanmedian(np.stack(speeds, 1), axis=1)+ sp = np.where(np.isnan(sp), np.inf, sp)+ sp = np.minimum(sp, 1e6)+ sp = gaussian_smooth(sp, 1.0)+ out[:, k] = sp[u] < still_px+ return out+++def source_contacts(Ps, Rs, rj, foot, static, fps, opts, floor_known=False, still2d=None):+ """When is each foot planted? GVHMR's own contact detector, CHECKED+ against the geometry.++ `static_conf` is the network's probability that a joint is not moving.+ It is right most of the time and confidently wrong at two moments that+ matter: a foot that slides back under the body (kung-fu plate, end: the+ right foot travels 0.2 m while the network still calls it static — a+ lock there left the character in a frog stance for the whole T-pose),+ and a raised foot held still. So a point only counts as planted when+ the network says static AND it is slow AND its sole is within a few+ centimetres of the lowest sole of that frame.++ With `floor_known` (the source has been grounded, floor at y = 0) a+ second, purely geometric rule is OR-ed in: a sole within a few+ centimetres of the floor that is not moving is planted whatever the+ network says. On the spin plate the network's confidence stays under+ 0.4 for 200 frames of turning footwork with the feet on the floor.++ Returns per foot the heel and ball masks, plus the lowest source sole+ per frame (the grounding reference).+ """+ thr = float(opts["contact_threshold"])+ vmax = float(opts["contact_max_speed"])+ hmax = float(opts["contact_max_height"])++ def attached(j, point):+ return Ps[:, j] + np.einsum("tij,j->ti", Rs[:, j], np.asarray(point, dtype=np.float64) - rj[j])++ pts = {}+ for side, (hip, knee, ank, ball) in LEGS.items():+ f = foot[side]+ pts[side] = {"heel": attached(ank, [rj[ank, 0], f["sole_y"], rj[ank, 2]]),+ "ball": attached(ank, [rj[ball, 0], f["sole_y"], rj[ball, 2]]),+ "tip": attached(ball, [rj[ball, 0], f["sole_y"], f["toe_tip_z"]])}+ low = np.min(np.stack([p[:, 1] for side in pts for p in pts[side].values()], 1), 1)++ def speed(x):+ v = np.zeros(len(x))+ v[1:] = np.linalg.norm(np.diff(x[:, [0, 2]], axis=0), axis=1) * fps+ v[0] = v[1] if len(v) > 1 else 0.0+ return gaussian_smooth(v, 1.0)++ out = {}+ for side in LEGS:+ ca, cb = STATIC[side]+ heel_h = pts[side]["heel"][:, 1] - low+ ball_h = np.minimum(pts[side]["ball"][:, 1], pts[side]["tip"][:, 1]) - low+ v_heel, v_ball = speed(pts[side]["heel"]), speed(pts[side]["ball"])+ # A heel can be perfectly still and still be UP (a boxer's rear foot+ # on its ball): only a heel near the floor makes a flat contact.+ flat_h = float(opts["contact_heel_height"])+ heel_c = (static[:, ca] > thr) & (v_heel < vmax) & (heel_h < flat_h)+ ball_c = (static[:, cb] > thr) & (v_ball < vmax) & (ball_h < hmax)+ # A foot the network holds still, and that is not moving, is planted+ # even when its sole is not flat on the floor (an extended leg's foot+ # rolled on an edge, a toe-up heel plant): it locks on its lowest point.+ still = ((np.maximum(static[:, ca], static[:, cb]) > 0.8)+ & (np.minimum(v_heel, v_ball) < 0.5 * vmax)+ & (np.minimum(heel_h, ball_h) < hmax))+ if still2d is not None:+ # still on screen and low: planted, whatever the 3D track says+ still |= still2d[:, 0 if side == "L" else 1] & (np.minimum(heel_h, ball_h) < hmax)+ if floor_known:+ g_h, g_v = float(opts["contact_geo_height"]), float(opts["contact_geo_speed"])+ heel_c |= (pts[side]["heel"][:, 1] < g_h) & (v_heel < g_v)+ ball_c |= (np.minimum(pts[side]["ball"][:, 1], pts[side]["tip"][:, 1]) < g_h) & (v_ball < g_v)+ heel_c, ball_c = clean_mask(heel_c, 3, 2), clean_mask(ball_c, 3, 2)+ out[side] = {"heel": heel_c, "ball": ball_c,+ # flat = heel AND ball near the floor; otherwise a pivot+ "flat": heel_c & (ball_h < flat_h + 0.02),+ "heel_lower": heel_h <= ball_h,+ "any": clean_mask(heel_c | ball_c | still, 3, 2)}+ return out, low+++def camera_drift(src, rj, rs, R_c2w, t_c2w, Ry, opts):+ """Camera-derived pelvis minus GVHMR's world pelvis, per destination+ frame, in the normalised source frame (T, 3).++ GVHMR's world trajectory is integrated from predicted velocities and+ drifts — measured over whole takes that end where they began: 0.3 m in+ depth (fight), 0.4 m sideways (kung-fu), 0.07-0.12 m vertically (spin,+ combo). The camera-frame position is noisy frame to frame but does not+ drift: after this correction the feet of every plate come back to the+ height they started at within 1 cm, and the combo's jump is 0.22 m+ instead of the 0.10 m the world track reports.+ """+ n = src["transl"].shape[0]+ pc = rj[0] + gaussian_smooth(src["incam_transl"], float(opts["camera_smooth"]))+ u = rs["src_frame"] - 1.0+ i0 = np.clip(np.floor(u).astype(int), 0, n - 1)+ i1 = np.minimum(i0 + 1, n - 1)+ w = (u - i0)[:, None]+ pc = pc[i0] * (1 - w) + pc[i1] * w # camera-frame pelvis, destination clock+ pw = rj[0] + rs["transl"] # world pelvis (after pin_static_feet)+ d = np.einsum("ij,tj->ti", R_c2w, pc) + t_c2w - pw+ return np.einsum("ij,tj->ti", Ry, d)+++def pin_static_feet(local, transl, rj, static):+ """Keep the feet GVHMR calls static still in the world, by moving the+ body instead (horizontal only; the floor solver owns height).++ GVHMR does this itself in its post-processing, but on ITS pose. The 2D+ refinement changes the legs frame by frame: a foot that stands still in+ the image then creeps in the world (measured: 12 cm over 0.8 s on the+ kung-fu plate). Re-applying the same rule on the refined pose restores+ it. Returns the corrected translation.+ """+ P, _ = SB.fk_local(local, transl, rj)+ joints = [7, 10, 8, 11] # ankles and balls, static_conf order+ ok = np.minimum(static[1:, :4], static[:-1, :4]) > 0.5 # static in both frames+ d = P[1:, joints] - P[:-1, joints] # (T-1, 4, 3)+ d[:, :, 1] = 0.0+ # The anchor is the stillest flagged joint, not an average: a foot that+ # starts to lift while still flagged static would drag the other one.+ mag = np.where(ok, np.linalg.norm(d, axis=-1), np.inf)+ k = mag.argmin(1)+ step = np.where(np.isfinite(mag.min(1))[:, None], d[np.arange(len(d)), k], 0.0)+ return transl - np.concatenate([np.zeros((1, 3)), np.cumsum(step, 0)])+++def bridge_contacts(contacts, Ps, max_gap: int = 12, max_move: float = 0.03):+ """Join two contact runs of the same foot when the foot did not move+ in between (a dip in the network's confidence, not a step).++ Left split, a planted foot is two footfalls: each takes its own camera+ correction, and the difference between them — 12 cm on the kung-fu+ plate — slides a foot that never moved.+ """+ ank = {"L": 7, "R": 8}+ for side, c in contacts.items():+ xz = Ps[:, ank[side]][:, [0, 2]]+ segs = runs(c["any"])+ for (a0, b0), (a1, b1) in zip(segs[:-1], segs[1:]):+ if a1 - b0 - 1 <= max_gap and np.linalg.norm(xz[a1] - xz[b0]) < max_move \+ and np.ptp(xz[b0:a1 + 1], axis=0).max() < max_move:+ c["any"][b0 + 1:a1] = True+ return contacts+++def camera_footfalls(d, contacts, opts):+ """Horizontal drift correction applied one FOOTFALL at a time.++ Correcting the root continuously would drag every planted foot with+ it (skate). Instead each contact segment takes the camera correction+ measured while it lasts as a CONSTANT offset: the foot lands where the+ camera saw it and stays there. The root follows the planted feet+ (weighted by contact); with no foot down it follows the camera itself.+ Drift is paid for in the length of steps, never in slides.++ Returns the root correction (T, 3) (vertical untouched) and the+ per-footfall offsets {side: [(3,), ...]}.+ """+ d = d.copy()+ d[:, 1] = 0.0+ T = d.shape[0]+ ramp = int(opts["contact_ramp"])+ num, den = np.zeros((T, 3)), np.zeros(T)+ deltas = {}+ for side, c in contacts.items():+ segs = runs(c["any"])+ # A foot is placed when it lands: the camera correction measured then+ # is the footfall's. Later disagreement while it stays planted is the+ # camera's depth estimate breathing with the pose (a deep stance+ # moved it 0.2 m on the kung-fu plate), not the foot moving.+ land = int(opts.get("camera_landing_frames", 6))+ deltas[side] = [np.median(d[a:min(b + 1, a + land)], 0) for a, b in segs]+ wt, owner = ramp_weights(segs, T, ramp)+ m = owner >= 0+ if m.any():+ num[m] += wt[m, None] * np.array(deltas[side])[owner[m]]+ den[m] += wt[m]+ planted = np.clip(den, 0.0, 1.0)[:, None]+ feet = np.where(den[:, None] > 1e-6, num / np.maximum(den[:, None], 1e-6), d)+ return gaussian_smooth(planted * feet + (1.0 - planted) * d, 1.5), deltas+++def foot_yaw_offset(rig, rj, foot, side):+ """Toe-out difference between the performer's rest foot and the rig's.++ Measured on the foot a viewer sees — heel to toes on the SMPL-X mesh —+ not on the ankle->ball JOINT direction, which reads 18-22 degrees of+ toe-out on a template whose feet point 5-6 degrees out. Aligning on the+ joint direction turned every retargeted foot out by ~15 degrees.+ The rig's foot axis is its Foot->ToeBase->Toe_End bone line.+ """+ f = foot[side]+ ank, ball = (7, 10) if side == "L" else (8, 11)+ if "heel" in f:+ d_s = 0.5 * (np.asarray(f["big_toe"]) + np.asarray(f["small_toe"])) - np.asarray(f["heel"])+ else: # smplx.npz from before the mesh points+ d_s = rj[ball] - rj[ank]+ pre = "Left" if side == "L" else "Right"+ b_foot, b_end = rig.bone(pre + "Foot"), rig.bone(pre + "Toe_End") or rig.bone(pre + "ToeBase")+ d_t = rig.head[b_end] - rig.head[b_foot]+ return float(np.arctan2(d_s[0], d_s[2]) - np.arctan2(d_t[0], d_t[2]))+++def rotate_subtree(P, rig, bone, delta):+ """Pre-multiply world rotation `delta` (T,3,3) onto `bone` and every+ bone below it, so a corrected limb carries its hand and fingers."""+ todo = [bone]+ while todo:+ b = todo.pop()+ P[:, b] = delta @ P[:, b]+ todo += [i for i in range(len(rig.parent)) if rig.parent[i] == b]+++def two_bone(root, mid, target, l1, l2, fallback_pole):+ """Vectorised two-bone solve. Returns (new mid, reached end); the bend+ stays in the plane the current `mid` defines."""+ d = target - root+ dist = np.linalg.norm(d, axis=-1)+ lo, hi = abs(l1 - l2) * 1.001 + 1e-6, (l1 + l2) * 0.9995+ dc = np.clip(dist, lo, hi)+ n = d / np.maximum(dist, 1e-9)[:, None]+ pole = (mid - root) - n * np.sum((mid - root) * n, -1, keepdims=True)+ pn = np.linalg.norm(pole, axis=-1, keepdims=True)+ fb = fallback_pole - n * np.sum(fallback_pole * n, -1, keepdims=True)+ pole = np.where(pn > 1e-6, pole, fb)+ pole /= np.maximum(np.linalg.norm(pole, axis=-1, keepdims=True), 1e-12)+ cos_a = np.clip((l1 * l1 + dc * dc - l2 * l2) / (2 * l1 * dc), -1, 1)+ sin_a = np.sqrt(1 - cos_a * cos_a)+ new_mid = root + l1 * (n * cos_a[:, None] + pole * sin_a[:, None])+ return new_mid, root + n * dc[:, None], int(np.count_nonzero(dist > hi))+++def retarget(spec: dict, src: dict, rig: Rig, opts: dict) -> dict:+ dst_fps = float(spec.get("dst_fps", 30))+ rs = resample_source(src, dst_fps, opts.get("smooth"))+ T = rs["n"]+ rj = np.asarray(src["rest_joints"], dtype=np.float64)+ B = len(rig.names)++ # -- 1. source FK, heading + origin normalisation ------------------------+ n_src = src["global_orient"].shape[0]+ still2d = still_in_image(src, rs, float(opts["contact_still_px"]))+ if opts.get("pin_static_feet", True):+ pin_w = np.maximum(rs["static"][:, :4], np.repeat(still2d.astype(float), 2, axis=1))+ rs["transl"] = pin_static_feet(rs["local"], rs["transl"], rj, pin_w)+ Ps, Rs = SB.fk_local(rs["local"], rs["transl"], rj)+ h0 = float(SB.heading(Rs[0, 0]))+ Ry = SB.yaw_matrix(np.array(-h0))+ origin = np.array([Ps[0, 0, 0], 0.0, Ps[0, 0, 2]])+ Ps = np.einsum("ij,tkj->tki", Ry, Ps - origin)+ Rs = np.einsum("ij,tkjl->tkil", Ry, Rs)+ foot = src["foot"]+ src_floor_rest = min(foot["L"]["sole_y"], foot["R"]["sole_y"])+ static = rs["static"]++ # -- 2. camera-consistent trajectory, contacts, floor ---------------------+ R_c2w, t_c2w = static_camera(src, rj, slice(0, max(2, min(n_src, int(opts["camera_fit_frames"])))))+ use_cam = bool(opts.get("camera_root", True))+ d_cam = camera_drift(src, rj, rs, R_c2w, t_c2w, Ry, opts) if use_cam else np.zeros((T, 3))+ # Height: the camera sees it directly (image row x depth), so GVHMR's+ # vertical drift is removed continuously — it moves no foot sideways.+ Ps[:, :, 1] += d_cam[:, 1:2]+ # Floor: on every frame a foot is planted (network + geometry), the+ # lowest sole goes on the floor; flight keeps the (camera-true) arc.+ contacts, low_src = source_contacts(Ps, Rs, rj, foot, static, dst_fps, opts, still2d=still2d)+ grounded = contacts["L"]["any"] | contacts["R"]["any"]+ if grounded.sum() >= 2:+ idx = np.nonzero(grounded)[0]+ g = gaussian_smooth(np.interp(np.arange(T), idx, -low_src[idx]), float(opts["ground_sigma"]))+ else:+ g = np.full(T, -low_src.min())+ Ps[:, :, 1] += g[:, None]+ # Second contact pass against the now-known floor: a sole on the floor+ # that does not move is planted, whatever the network says.+ contacts, _ = source_contacts(Ps, Rs, rj, foot, static, dst_fps, opts, floor_known=True, still2d=still2d)+ contacts = bridge_contacts(contacts, Ps)+ grounded = contacts["L"]["any"] | contacts["R"]["any"]+ if use_cam:+ cam_corr, deltas = camera_footfalls(d_cam, contacts, opts)+ else:+ cam_corr = np.zeros((T, 3))+ deltas = {side: [np.zeros(3)] * len(runs(c["any"])) for side, c in contacts.items()}+ Ps = Ps + cam_corr[:, None, :]++ # -- 3. scale + rest alignment -----------------------------------------+ src_leg = float(np.mean([np.linalg.norm(rj[k] - rj[h]) + np.linalg.norm(rj[a] - rj[k])+ for h, k, a, _ in LEGS.values()]))+ s = float(np.mean([rig.leg_length("Left"), rig.leg_length("Right")])) / src_leg+ align = np.tile(np.eye(3), (B, 1, 1))+ for j, child in ALIGN.items():+ b, bc = rig.joint_bone[j], rig.joint_bone[child]+ align[b] = SB.align_rotation(rig.head[bc] - rig.head[b], rj[child] - rj[j])+ foot_yaw = {side: foot_yaw_offset(rig, rj, src["foot"], side) for side in ("L", "R")}+ for j, side in FEET.items():+ align[rig.joint_bone[j]] = SB.yaw_matrix(np.array(foot_yaw[side]))+ for j, parent_j in INHERIT.items():+ align[rig.joint_bone[j]] = align[rig.joint_bone[parent_j]]++ # -- 4. world rotations of every bone ------------------------------------+ fists = fist_quats()+ src_frames = rs["src_frame"]+ fist_amt = np.zeros(T)+ if spec.get("fists"):+ fist_amt = window_amount(src_frames, spec["fists"]["rise_src"], spec["fists"]["fall_src"])+ hand_amt = np.maximum(float(opts["hand_relaxed"]), fist_amt)+ P = np.empty((T, B, 3, 3))+ bone_joint = {b: j for j, b in rig.joint_bone.items()}+ for i in range(B):+ if i in bone_joint:+ P[:, i] = Rs[:, bone_joint[i]] @ align[i] @ rig.R[i]+ else:+ p = rig.parent[i]+ local = np.tile(np.eye(3), (T, 1, 1))+ short = rig.names[i][len(rig.prefix):]+ if short in fists:+ fq = np.asarray(fists[short], dtype=np.float64)+ qt = SB.slerp(np.tile([1.0, 0, 0, 0], (T, 1)), np.tile(fq / np.linalg.norm(fq), (T, 1)), hand_amt)+ local = SB.quat_to_matrix(qt)+ P[:, i] = (P[:, p] if p >= 0 else np.eye(3)) @ rig.rest_rel[i] @ local++ # -- 5. root: the performer's trajectory, scaled; rest maps to rest ------+ src_pelvis_h = rj[0, 1] - src_floor_rest+ tgt_hips_h = rig.head[rig.root][1] - rig.floor+ root = Ps[:, 0] * s+ root[:, 1] += rig.floor + tgt_hips_h - s * src_pelvis_h+ root[:, [0, 2]] += rig.head[rig.root][[0, 2]]+ pos = rig.chain_positions(P, root)++ # -- 6. legs: ankle where the performer's scaled leg puts it -------------+ ik_clamped = 0++ def solve_leg(side, ankle_target):+ """Two-bone solve of one leg onto `ankle_target`, knee kept in the+ plane the rotation copy chose. Thigh and shin are re-aimed with the+ minimal rotation; the foot keeps its absolute (world) rotation."""+ nonlocal ik_clamped+ hip_j, knee_j, ank_j, _ = LEGS[side]+ b_hip, b_knee, b_ank = rig.joint_bone[hip_j], rig.joint_bone[knee_j], rig.joint_bone[ank_j]+ l1 = float(np.linalg.norm(rig.head[b_knee] - rig.head[b_hip]))+ l2 = float(np.linalg.norm(rig.head[b_ank] - rig.head[b_knee]))+ cur = rig.chain_positions(P, root)+ hip_p, knee_p = cur[:, b_hip], cur[:, b_knee]+ fwd = np.einsum("tij,j->ti", P[:, rig.root] @ rig.R[rig.root].T, np.array([0, 0, 1.0]))+ knee_new, ank_new, n_cl = two_bone(hip_p, knee_p, ankle_target, l1, l2, fwd)+ ik_clamped += n_cl+ P[:, b_hip] = SB.align_rotation(knee_p - hip_p, knee_new - hip_p) @ P[:, b_hip]+ shin = np.einsum("tij,j->ti", P[:, b_knee] @ rig.R[b_knee].T, rig.head[b_ank] - rig.head[b_knee])+ P[:, b_knee] = SB.align_rotation(shin, ank_new - knee_new) @ P[:, b_knee]++ for side, (hip_j, knee_j, ank_j, _) in LEGS.items():+ b_hip = rig.joint_bone[hip_j]+ want = pos[:, b_hip] + (Ps[:, ank_j] - Ps[:, hip_j]) * s+ solve_leg(side, want)+ pos = rig.chain_positions(P, root)++ # -- 6b. authored arm overrides (spec `arm_overrides`) --------------------+ # For beats where a human's read of the video beats the estimator — an+ # arm hidden behind the torso comes back from any monocular estimator as+ # a guess. Same schema as the legacy lift: wrist/elbow targets in METRES+ # in the hip basis (x = character left, y = back, z = up), ramped. The+ # arm is re-solved with its own bone lengths and the hand rides along.+ for ov in spec.get("arm_overrides", []):+ ramp_src = ov.get("ramp_src", 6)+ amt = window_amount(src_frames, [ov["src"][0], ov["src"][0] + ramp_src],+ [ov["src"][1] - ramp_src, ov["src"][1]])+ if not (amt > 1e-4).any():+ continue+ side = "Left" if ov["side"] == "left" else "Right"+ b_up, b_fore, b_hand = rig.bone(side + "Arm"), rig.bone(side + "ForeArm"), rig.bone(side + "Hand")+ cur = rig.chain_positions(P, root)+ Q = P[:, rig.root] @ rig.R[rig.root].T # pelvis frame (x left, y up, z fwd)++ def hip_local(v):+ v = np.array([v[0], v[2], -v[1]], dtype=np.float64) # (left, back, up) -> (left, up, fwd)+ return cur[:, rig.root] + np.einsum("tij,j->ti", Q, v)++ sh = cur[:, b_up]+ l1 = float(np.linalg.norm(rig.head[b_fore] - rig.head[b_up]))+ l2 = float(np.linalg.norm(rig.head[b_hand] - rig.head[b_fore]))+ e_t = sh + (hip_local(ov["elbow_local"]) - sh) / np.maximum(+ np.linalg.norm(hip_local(ov["elbow_local"]) - sh, axis=1, keepdims=True), 1e-9) * l1+ w_t = hip_local(ov["wrist_local"])+ elbow, wrist, _ = two_bone(sh, e_t, w_t, l1, l2, np.tile([0.0, -1.0, 0.0], (T, 1)))+ m = amt > 1e-4+ for b, a_pos, want in ((b_up, sh, elbow), (b_fore, None, wrist)):+ cur = rig.chain_positions(P, root)+ start = cur[:, b]+ child = b_fore if b == b_up else b_hand+ have = cur[:, child] - start+ full = SB.align_rotation(have, want - start)+ q = SB.slerp(np.tile([1.0, 0, 0, 0], (T, 1)), SB.matrix_to_quat(full), amt)+ delta = SB.quat_to_matrix(q)+ delta[~m] = np.eye(3)+ rotate_subtree(P, rig, b, delta)+ pos = rig.chain_positions(P, root)++ # -- 7. target grounding + contact locks ---------------------------------+ tgt_probes = {}+ for side, (hip_j, knee_j, ank_j, ball_j) in LEGS.items():+ b_ank, b_ball = rig.joint_bone[ank_j], rig.joint_bone[ball_j]+ toe_end = rig.bone(("Left" if side == "L" else "Right") + "Toe_End")+ ha, hb = rig.head[b_ank], rig.head[b_ball]+ ht = rig.head[toe_end] if toe_end is not None else hb + (hb - ha) * 0.6+ tgt_probes[side] = [(b_ank, [ha[0], rig.floor, ha[2]]),+ (b_ank, [hb[0], rig.floor, hb[2]]),+ (b_ball, [ht[0], rig.floor, ht[2]])]++ def lowest(pos_):+ ys = [rig.attached(P, pos_, b, p)[:, 1] for side in tgt_probes for b, p in tgt_probes[side]]+ return np.min(np.stack(ys, 1), 1)++ low = lowest(pos)+ if grounded.sum() >= 2:+ idx = np.nonzero(grounded)[0]+ pull = gaussian_smooth(np.interp(np.arange(T), idx, -low[idx]), 2.0)+ else:+ pull = np.full(T, -low.min())+ root[:, 1] += pull+ pos = rig.chain_positions(P, root)++ ramp = int(opts["contact_ramp"])+ contact_report = {}+ contact_masks = np.zeros((T, 2), dtype=bool)+ feet = {}+ for k, (side, (hip_j, knee_j, ank_j, ball_j)) in enumerate(LEGS.items()):+ b_ank, b_ball = rig.joint_bone[ank_j], rig.joint_bone[ball_j]+ flat_c, c = contacts[side]["flat"], contacts[side]["any"]+ segs0 = runs(c)+ flat0 = [flat_c[a_:b_ + 1].mean() >= 0.5 for a_, b_ in segs0]+ # a pivot locks whichever point carries the weight: the heel for a+ # toe-up plant, the ball for a raised heel+ heel0 = [(not fl) and contacts[side]["heel_lower"][a_:b_ + 1].mean() > 0.5+ for (a_, b_), fl in zip(segs0, flat0)]+ # A toe-up heel plant is a moment: a heel strike, a turn on the heel.+ # Held longer, it is the estimator's reading, not the performer's —+ # GVHMR returns the planted rear foot of a long stance with its toes+ # 20-30 degrees up and rolled on its edge (kung-fu bow stance, 4 s)+ # where the video shows it flat. The image cannot tell the two apart+ # (the difference is in depth); weight-bearing can: lay it flat.+ long_heel = int(round(float(opts["contact_heel_max_s"]) * dst_fps))+ laid_flat = 0+ for k0, (a_, b_) in enumerate(segs0):+ if heel0[k0] and b_ - a_ + 1 > long_heel:+ flat0[k0], heel0[k0] = True, False+ laid_flat += 1+ # A lock holds one point still for the whole segment, so a segment+ # whose planted point creeps in the source (a foot slid across the+ # floor, slow enough to pass as "static") is cut where the drift+ # exceeds `contact_max_drift`: each piece locks where the foot is.+ f_src = src["foot"][side]+ refs = {"ankle": Ps[:, ank_j],+ "heel": Ps[:, ank_j] + np.einsum("tij,j->ti", Rs[:, ank_j],+ np.array([rj[ank_j, 0], f_src["sole_y"], rj[ank_j, 2]]) - rj[ank_j]),+ "ball": Ps[:, ank_j] + np.einsum("tij,j->ti", Rs[:, ank_j],+ np.array([rj[ball_j, 0], f_src["sole_y"], rj[ball_j, 2]]) - rj[ank_j])}+ max_drift = float(opts["contact_max_drift"])+ slide_v = float(opts["contact_slide_speed"])+ segs, flat, on_heel, parent = [], [], [], []+ for k0, ((a_, b_), fl, oh) in enumerate(zip(segs0, flat0, heel0)):+ ref = refs["ankle" if fl else "heel" if oh else "ball"][:, [0, 2]]+ # speed over a third of a second: frame-to-frame jitter of a+ # planted foot averages out, a real slide does not+ i_lo = np.maximum(np.arange(T) - 5, 0)+ i_hi = np.minimum(np.arange(T) + 5, T - 1)+ v = np.linalg.norm(ref[i_hi] - ref[i_lo], axis=1) / np.maximum(i_hi - i_lo, 1) * dst_fps+ # frames where the planted point slides are left free: the foot+ # follows the source there (smoothly), and only the still runs+ # lock. A foot the IMAGE shows still counts as still even when+ # the 3D track creeps.+ steady = (v < slide_v) | still2d[:, k]+ for a2, b2 in runs(steady[a_:b_ + 1]):+ a2, b2 = a2 + a_, b2 + a_+ start, t = a2, a2+ while t <= b2:+ if np.linalg.norm(ref[t] - ref[start]) > max_drift and not still2d[t, k]:+ if t - 1 - start >= 2:+ segs.append((start, t - 1)); flat.append(fl); on_heel.append(oh); parent.append(k0)+ start = t+ t += 1+ if b2 - start >= 2:+ segs.append((start, b2)); flat.append(fl); on_heel.append(oh); parent.append(k0)+ c = np.zeros(T, dtype=bool)+ for a_, b_ in segs:+ c[a_:b_ + 1] = True+ contact_masks[:, k] = c+ # A planted foot is flat on the floor at a FIXED heading: the rig+ # rest foot, turned to the heading of the source foot laid flat (a+ # foot rolled onto its edge keeps the direction it points in; the+ # heading of its tilted axis does not), median over the stance.+ ha, hb = rig.head[b_ank], rig.head[b_ball]+ yaw_align = foot_yaw[side]+ src_yaw = np.unwrap(SB.heading(Rs[:, ank_j]))+ R_lay = SB.align_rotation(np.einsum("tij,j->ti", Rs[:, ank_j], [0.0, 1.0, 0.0]),+ np.tile([0.0, 1.0, 0.0], (T, 1))) @ Rs[:, ank_j]+ lay_yaw = np.unwrap(SB.heading(R_lay))+ seg_yaw = [float(np.median(lay_yaw[a_:b_ + 1])) for a_, b_ in segs]+ flat_w, flat_owner = ramp_weights(segs, T, ramp, lambda k_: flat[k_])+ toe_w, _ = ramp_weights(segs, T, ramp, lambda k_: not on_heel[k_])+ if segs:+ yaw = np.where(flat_owner >= 0, np.array(seg_yaw + [0.0])[flat_owner], src_yaw)+ flatA = SB.yaw_matrix(yaw + yaw_align) @ rig.R[b_ank]+ P[:, b_ank] = SB.quat_to_matrix(SB.slerp(SB.matrix_to_quat(P[:, b_ank]),+ SB.matrix_to_quat(flatA), flat_w))+ # toes lie on the floor in any contact, along the foot heading+ foot_heading = SB.heading(P[:, b_ank] @ rig.R[b_ank].T)+ flatB = SB.yaw_matrix(foot_heading) @ rig.R[b_ball]+ P[:, b_ball] = SB.quat_to_matrix(SB.slerp(SB.matrix_to_quat(P[:, b_ball]),+ SB.matrix_to_quat(flatB), toe_w))+ # Each footfall sits where the camera saw it: its own correction+ # minus what the root already carries at that frame.+ resid = [s * (np.asarray(deltas[side][parent[k_]])[None, :] - cam_corr[a_:b_ + 1])+ for k_, (a_, b_) in enumerate(segs)]+ feet[side] = dict(b_ank=b_ank, b_ball=b_ball, b_hip=rig.joint_bone[hip_j],+ b_knee=rig.joint_bone[knee_j], segs=segs, flat=flat, on_heel=on_heel,+ ha=ha, hb=hb, w=ramp_weights(segs, T, ramp), resid=resid)+ contact_report[side] = {"segments": len(segs), "flat_segments": int(sum(flat)),+ "heel_pivots": int(sum(on_heel)),+ "long_heel_plants_laid_flat": laid_flat,+ "detail": [[int(a_), int(b_), "flat" if fl else "heel" if oh else "ball"]+ for (a_, b_), fl, oh in zip(segs, flat, on_heel)],+ "planted_fraction": round(float(c.mean()), 3)}++ # Lock positions, from the grounded free pose: the ankle of a flat foot+ # (at rest ankle height: sole on the floor), the ball of a pivoting one.+ pos = rig.chain_positions(P, root)+ for side, f in feet.items():+ ankle_free = pos[:, f["b_ank"]]+ ball_free = rig.attached(P, pos, f["b_ank"], [f["hb"][0], rig.floor, f["hb"][2]])+ f["locks"] = []+ heel_free = rig.attached(P, pos, f["b_ank"], [f["ha"][0], rig.floor, f["ha"][2]])+ for (a_, b_), is_flat, on_heel_, r_ in zip(f["segs"], f["flat"], f["on_heel"], f["resid"]):+ ref = (ankle_free if is_flat else heel_free if on_heel_ else ball_free)[a_:b_ + 1]+ lk = np.median(ref + r_, 0)+ lk[1] = f["ha"][1] if is_flat else rig.floor+ f["locks"].append(lk)++ def ankle_targets(pos_):+ """Free ankles move with the body; locked ones stay put in the world."""+ out = {}+ for side, f in feet.items():+ ankle_free = pos_[:, f["b_ank"]]+ if not f["segs"]:+ out[side] = ankle_free.copy()+ continue+ ball_free = rig.attached(P, pos_, f["b_ank"], [f["hb"][0], rig.floor, f["hb"][2]])+ heel_free = rig.attached(P, pos_, f["b_ank"], [f["ha"][0], rig.floor, f["ha"][2]])+ w, owner = f["w"]+ off = np.zeros((T, 3))+ for t in np.nonzero(owner >= 0)[0]:+ k_ = owner[t]+ a_, b_ = f["segs"][k_]+ tt = min(max(t, a_), b_) # ramps hold the boundary offset+ ref = (ankle_free if f["flat"][k_] else heel_free if f["on_heel"][k_] else ball_free)[tt]+ off[t] = (f["locks"][k_] - ref) * w[t]+ out[side] = ankle_free + off+ return out++ # A locked foot the leg cannot reach means the pelvis is too high for+ # that stance: lower it (smoothly) instead of letting the foot float.+ tg = ankle_targets(pos)+ drop = np.zeros(T)+ for side, f in feet.items():+ l1 = float(np.linalg.norm(rig.head[f["b_knee"]] - rig.head[f["b_hip"]]))+ l2 = float(np.linalg.norm(rig.head[f["b_ank"]] - rig.head[f["b_knee"]]))+ L = (l1 + l2) * 0.998+ v = tg[side] - pos[:, f["b_hip"]]+ h2 = v[:, 0] ** 2 + v[:, 2] ** 2+ need = -v[:, 1] - np.sqrt(np.maximum(L * L - h2, 0.0))+ drop = np.maximum(drop, np.where(np.linalg.norm(v, axis=1) > L, np.maximum(need, 0.0), 0.0))+ if drop.any():+ # capped: a lock that would need more is a lock in the wrong place,+ # and a sinking character is worse than a foot short of it+ wide = np.array([drop[max(0, t - 3):t + 4].max() for t in range(T)])+ drop = gaussian_smooth(np.minimum(wide, float(opts["max_hips_drop"])), 1.5)+ root[:, 1] -= drop+ pos = rig.chain_positions(P, root)+ tg = ankle_targets(pos)+ for side in feet:+ solve_leg(side, tg[side])+ pos = rig.chain_positions(P, root)+ reach_err = {side: round(float(np.linalg.norm(pos[:, f["b_ank"]] - tg[side], axis=1).max() * 100), 2)+ for side, f in feet.items()}++ # -- 8. rest blends (T-pose bookends lock to the exact rig rest) ---------+ rest_w = np.zeros(T)+ if spec.get("rest_blend_end"):+ rb = spec["rest_blend_end"]+ rest_w = np.maximum(rest_w, smootherstep((src_frames - rb["start_src"]) / max(1e-6, rb["full_src"] - rb["start_src"])))+ if spec.get("rest_blend_start"):+ rb = spec["rest_blend_start"]+ rest_w = np.maximum(rest_w, 1.0 - smootherstep((src_frames - rb["full_src"]) / max(1e-6, rb["release_src"] - rb["full_src"])))++ # -- 9. world rotations -> local pose quaternions -------------------------+ basis = np.empty((T, B, 3, 3))+ for i in range(B):+ p = rig.parent[i]+ parent = P[:, p] if p >= 0 else np.eye(3)+ basis[:, i] = np.swapaxes(parent @ rig.rest_rel[i], -1, -2) @ P[:, i]+ quat = SB.matrix_to_quat(basis) # (T, B, 4)+ hips_loc = np.einsum("ji,tj->ti", rig.R[rig.root], root - rig.head[rig.root]) * rig.unit+ if rest_w.any():+ # Upper body only: the arms, spine and head settle into the rig's+ # exact T-pose, while the legs and root keep the performer's real+ # stance. Forcing the legs to rest would drag planted feet across+ # the floor during the blend.+ spine = rig.bone("Spine")+ upper = np.zeros(B, dtype=bool)+ for i in range(B):+ k_ = i+ while k_ >= 0 and not upper[i]:+ upper[i] = k_ == spine+ k_ = rig.parent[k_]+ n_up = int(upper.sum())+ ident = np.tile([1.0, 0.0, 0.0, 0.0], (T, n_up, 1))+ quat[:, upper] = SB.slerp(quat[:, upper], ident, np.repeat(rest_w[:, None], n_up, 1))+ quat = SB.quat_unroll(quat)++ # final pose for QA / framing (recomputed from what will be keyed)+ Pq = np.empty((T, B, 3, 3))+ Lq = SB.quat_to_matrix(quat)+ for i in range(B):+ p = rig.parent[i]+ Pq[:, i] = (Pq[:, p] if p >= 0 else np.eye(3)) @ rig.rest_rel[i] @ Lq[:, i]+ root_final = rig.head[rig.root] + np.einsum("ij,tj->ti", rig.R[rig.root], hips_loc / rig.unit)+ pos_final = rig.chain_positions(Pq, root_final)++ def to_world(p_arm_m): # armature space (m) -> Blender world (m)+ return np.einsum("ij,...j->...i", rig.arm_rot, p_arm_m) + rig.arm_loc++ joints_world = to_world(pos_final)++ # -- 10. the plate's camera, in the same (scaled, grounded) world --------+ # the camera stays where it was at frame 1; the body was moved onto it+ C = Ry @ (t_c2w - origin) + cam_corr[0]+ C[1] += g[0] + d_cam[0, 1]+ R_cam = Ry @ R_c2w # OpenCV camera axes -> normalised source world+ cam_pos_arm = C * s+ cam_pos_arm[1] += rig.floor + tgt_hips_h - s * src_pelvis_h + pull[0]+ cam_pos_arm[[0, 2]] += rig.head[rig.root][[0, 2]]+ R_bl = rig.arm_rot @ R_cam @ np.diag([1.0, -1.0, -1.0]) # Blender camera looks down -Z, +Y up+ cam_mw = np.eye(4)+ cam_mw[:3, :3] = R_bl+ cam_mw[:3, 3] = to_world(cam_pos_arm)++ # -- 11. QA numbers ---------------------------------------------------------+ qa = {"scale": round(s, 4), "frames": T, "ik_clamped_frames": ik_clamped,+ "contact_reach_error_cm": reach_err, "hips_drop_cm": round(float(drop.max() * 100), 2),+ "ground_drift_m": [round(float(g.min()), 3), round(float(g.max()), 3)],+ "target_pull_m": [round(float(pull.min()), 3), round(float(pull.max()), 3)],+ "grounded_fraction": round(float(grounded.mean()), 3), "contacts": contact_report,+ "heading0_deg": round(float(np.degrees(h0)), 2),+ "camera_root": {"footfalls": int(sum(len(v) for v in deltas.values())),+ "end_correction_m": [round(float(v), 3) for v in cam_corr[-1]],+ "max_correction_m": round(float(np.abs(cam_corr).max()), 3),+ "max_footfall_offset_m": round(float(max(+ [np.abs(r_).max() / s for f in feet.values() for r_ in f["resid"]] or [0.0])), 3)}}+ feet_w = {side: joints_world[:, rig.joint_bone[LEGS[side][2]]] for side in LEGS}+ skate = {}+ for k, side in enumerate(LEGS):+ m = contact_masks[:, k]+ v = np.linalg.norm(np.diff(feet_w[side][:, :2], axis=0), axis=1) * dst_fps+ mm = m[1:] & m[:-1]+ skate[side] = round(float(np.median(v[mm]) * 100), 2) if mm.any() else None+ qa["contact_skate_cm_s"] = skate+ qa["travel_m"] = round(float(np.linalg.norm(joints_world[-1, rig.root, :2] - joints_world[0, rig.root, :2])), 3)++ return {+ "bone_names": np.array(rig.names), "quat": quat.astype(np.float64),+ "hips_location": hips_loc, "fps": np.array(dst_fps), "root": np.array(rig.names[rig.root]),+ "action_name": np.array(spec.get("action_name", "SMPLX_Retarget")),+ "hips_world": joints_world[:, rig.root], "joints_world": joints_world,+ "contacts": contact_masks, "rest_amount": rest_w, "fist_amount": fist_amt,+ "src_frame": src_frames,+ "cam_K": np.asarray(src["K"], dtype=np.float64),+ "cam_wh": np.array([int(src["width"]), int(src["height"])]),+ "cam_matrix_world": cam_mw,+ "qa": np.array(json.dumps(qa)),+ "_face_dir": to_world(np.einsum("tij,j->ti", Pq[:, rig.bone("Head")] @ rig.R[rig.bone("Head")].T, [0, 0, 1.0])) - rig.arm_loc,+ "_body_fwd": to_world(np.einsum("tij,j->ti", Pq[:, rig.root] @ rig.R[rig.root].T, [0, 0, 1.0])) - rig.arm_loc,+ }+++def write_curves(out: dict, path: Path) -> None:+ """curves.json in apply_mixamo_fk.dump_curves' format, so the legacy+ QA / compare tools read an SMPL-X clip without Blender."""+ names = [str(n) for n in out["bone_names"]]+ root = str(out["root"])+ frames = []+ for t in range(out["quat"].shape[0]):+ bones = {}+ for b, n in enumerate(names):+ loc = out["hips_location"][t] if n == root else (0.0, 0.0, 0.0)+ bones[n] = {"location": [round(float(v), 6) for v in loc],+ "rotation_quaternion": [round(float(v), 6) for v in out["quat"][t, b]],+ "world_location": [round(float(v), 6) for v in out["joints_world"][t, b]]}+ fd, bf = out["_face_dir"][t], out["_body_fwd"][t]+ frames.append({"frame": t + 1, "bones": bones,+ "face_dir": [round(float(v), 5) for v in fd / np.linalg.norm(fd)],+ "body_forward": [round(float(v), 5) for v in bf / np.linalg.norm(bf)]})+ path.write_text(json.dumps({"frames": frames}), encoding="utf-8")+++def main() -> None:+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ ap.add_argument("--spec", required=True)+ ap.add_argument("--smplx", help="SMPL-X parameters (default: spec 'smplx', else smplx.npz next to the landmarks)")+ ap.add_argument("--rig-profile", help="override the spec's rig_profile")+ ap.add_argument("--out-dir", help="override the spec's clip_dir")+ ap.add_argument("--no-curves", action="store_true", help="skip curves.json")+ args = ap.parse_args()++ spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))+ smplx_path = rpath(args.smplx or spec.get("smplx") or (rpath(spec["landmarks"]).parent / "smplx.npz"))+ if not smplx_path.exists():+ raise SystemExit(f"{smplx_path} not found — run estimate_pose_gvhmr.py on the plate first")+ prof_path = rpath(args.rig_profile or spec.get("rig_profile") or "rig_profile.json")+ rig = Rig(json.loads(prof_path.read_text(encoding="utf-8")))+ opts = {"contact_threshold": 0.5, "contact_max_speed": 0.3, "contact_max_height": 0.06,+ "contact_geo_height": 0.025, "contact_geo_speed": 0.2, "contact_heel_height": 0.03,+ "contact_max_drift": 0.04, "contact_slide_speed": 0.12, "contact_still_px": 15.0, "max_hips_drop": 0.05,+ "contact_heel_max_s": 0.5, "ground_sigma": 3.0, "contact_ramp": 4, "hand_relaxed": 0.3,+ "camera_fit_frames": 12, "camera_root": True, "camera_smooth": 5.0}+ opts.update(spec.get("smplx_retarget", {}))++ src = load_source(smplx_path)+ out = retarget(spec, src, rig, opts)+ clip_dir = rpath(args.out_dir or spec["clip_dir"])+ clip_dir.mkdir(parents=True, exist_ok=True)+ np.savez_compressed(clip_dir / "motion.npz", **{k: v for k, v in out.items() if not k.startswith("_")})+ if not args.no_curves:+ write_curves(out, clip_dir / "curves.json")+ qa = json.loads(str(out["qa"]))+ print(f"wrote {clip_dir / 'motion.npz'} ({qa['frames']} frames @ {float(out['fps']):.0f} fps, "+ f"rig {prof_path.name}, scale {qa['scale']})")+ print(json.dumps(qa, indent=1))+++if __name__ == "__main__":+ main()diff --git a/pipeline/setup_rig.py b/pipeline/setup_rig.pyindex f58e36f..1e03365 100644--- a/pipeline/setup_rig.py+++ b/pipeline/setup_rig.py@@ -116,6 +116,11 @@ def dump_rig_profile(arm, out_path: Path) -> dict:"rest": rest,"lengths": lengths,}+ # The SMPL-X retarget (retarget_smplx.py) needs every bone's rest+ # matrix, not just joint positions.+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ import bl_motion+ profile.update(bl_motion.rig_table(arm))out_path.write_text(json.dumps(profile, indent=1), encoding="utf-8")return profilediff --git a/pipeline/smplx_body.py b/pipeline/smplx_body.pynew file mode 100644index 0000000..be20578--- /dev/null+++ b/pipeline/smplx_body.py@@ -0,0 +1,247 @@+"""SMPL-X body maths in plain numpy: shaped rest skeleton, forward+kinematics, rotation helpers.++The retarget (retarget_smplx.py) runs on the estimator's SMPL-X+PARAMETERS — per-joint rotations, not joint positions. A position track+cannot describe how a forearm, a chest or a head is twisted; the+rotations can, so they are what gets transferred to the Mixamo rig.++Conventions+ SMPL-X canonical axes: X = character left, Y = up, Z = character+ forward. At the rest pose every joint's WORLD rotation is identity, so+ a joint's FK world rotation is exactly "how far this body part turned+ away from rest".++ A Mixamo armature, inside its X+90 / 0.01 import transform, uses the+ same axes (X left, Y up, Z forward) in centimetres — the retarget needs+ no axis conversion, only the unit.++Nothing here needs torch or the gated SMPL-X model file at retarget+time: the estimator bakes the performer's shaped rest joints and foot+geometry into smplx.npz (see estimate_pose_gvhmr.py).+"""++from __future__ import annotations++import numpy as np++# SMPL-X body joints (the first 22 of the 55), in model order.+NAMES = [+ "pelvis", "L_hip", "R_hip", "spine1", "L_knee", "R_knee", "spine2",+ "L_ankle", "R_ankle", "spine3", "L_foot", "R_foot", "neck", "L_collar",+ "R_collar", "head", "L_shoulder", "R_shoulder", "L_elbow", "R_elbow",+ "L_wrist", "R_wrist",+]+PARENT = np.array([-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19])+J = {n: i for i, n in enumerate(NAMES)}++# GVHMR's static-confidence head, in the network's joint order+# (hmr4d/model/gvhmr/utils/postprocess.py).+STATIC_JOINTS = ["L_ankle", "L_foot", "R_ankle", "R_foot", "L_wrist", "R_wrist"]++# SMPL-X mesh vertices of the foot keypoints (the smplx package's+# vertex_ids['smplx'], OpenPose foot convention). The ankle->ball JOINT+# direction is not the foot's axis: on the template it reads 18-22 degrees+# of toe-out where the heel->toes line of the mesh reads 5-6.+FOOT_VERTS = {"L": {"heel": 8846, "big_toe": 5770, "small_toe": 5780},+ "R": {"heel": 8635, "big_toe": 8463, "small_toe": 8474}}+++# --------------------------------------------------------------------------+# rotations++def axis_angle_to_matrix(aa: np.ndarray) -> np.ndarray:+ """(..., 3) axis-angle -> (..., 3, 3), Rodrigues, vectorised."""+ aa = np.asarray(aa, dtype=np.float64)+ theta = np.linalg.norm(aa, axis=-1, keepdims=True)+ k = aa / np.maximum(theta, 1e-12)+ x, y, z = k[..., 0], k[..., 1], k[..., 2]+ zero = np.zeros_like(x)+ K = np.stack([zero, -z, y, z, zero, -x, -y, x, zero], -1).reshape(aa.shape[:-1] + (3, 3))+ s = np.sin(theta)[..., None]+ c = np.cos(theta)[..., None]+ eye = np.broadcast_to(np.eye(3), K.shape)+ return eye + s * K + (1.0 - c) * (K @ K)+++def matrix_to_quat(R: np.ndarray) -> np.ndarray:+ """(..., 3, 3) -> (..., 4) quaternions, WXYZ (Blender order), w >= 0."""+ R = np.asarray(R, dtype=np.float64)+ m = R+ t = m[..., 0, 0] + m[..., 1, 1] + m[..., 2, 2]+ q = np.empty(R.shape[:-2] + (4,))+ c0 = t > 0.0+ c1 = ~c0 & (m[..., 0, 0] >= m[..., 1, 1]) & (m[..., 0, 0] >= m[..., 2, 2])+ c2 = ~c0 & ~c1 & (m[..., 1, 1] >= m[..., 2, 2])+ c3 = ~c0 & ~c1 & ~c2+ s = np.sqrt(np.maximum(t + 1.0, 1e-20)) * 2.0+ q0 = np.stack([0.25 * s, (m[..., 2, 1] - m[..., 1, 2]) / s,+ (m[..., 0, 2] - m[..., 2, 0]) / s, (m[..., 1, 0] - m[..., 0, 1]) / s], -1)+ s = np.sqrt(np.maximum(1.0 + m[..., 0, 0] - m[..., 1, 1] - m[..., 2, 2], 1e-20)) * 2.0+ q1 = np.stack([(m[..., 2, 1] - m[..., 1, 2]) / s, 0.25 * s,+ (m[..., 0, 1] + m[..., 1, 0]) / s, (m[..., 0, 2] + m[..., 2, 0]) / s], -1)+ s = np.sqrt(np.maximum(1.0 - m[..., 0, 0] + m[..., 1, 1] - m[..., 2, 2], 1e-20)) * 2.0+ q2 = np.stack([(m[..., 0, 2] - m[..., 2, 0]) / s, (m[..., 0, 1] + m[..., 1, 0]) / s,+ 0.25 * s, (m[..., 1, 2] + m[..., 2, 1]) / s], -1)+ s = np.sqrt(np.maximum(1.0 - m[..., 0, 0] - m[..., 1, 1] + m[..., 2, 2], 1e-20)) * 2.0+ q3 = np.stack([(m[..., 1, 0] - m[..., 0, 1]) / s, (m[..., 0, 2] + m[..., 2, 0]) / s,+ (m[..., 1, 2] + m[..., 2, 1]) / s, 0.25 * s], -1)+ q[c0], q[c1], q[c2], q[c3] = q0[c0], q1[c1], q2[c2], q3[c3]+ q /= np.linalg.norm(q, axis=-1, keepdims=True)+ return np.where(q[..., :1] < 0.0, -q, q)+++def quat_to_matrix(q: np.ndarray) -> np.ndarray:+ """(..., 4) WXYZ -> (..., 3, 3)."""+ q = np.asarray(q, dtype=np.float64)+ q = q / np.maximum(np.linalg.norm(q, axis=-1, keepdims=True), 1e-12)+ w, x, y, z = q[..., 0], q[..., 1], q[..., 2], q[..., 3]+ return np.stack([+ 1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),+ 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y),+ ], -1).reshape(q.shape[:-1] + (3, 3))+++def quat_unroll(q: np.ndarray) -> np.ndarray:+ """Flip signs along axis 0 so consecutive keys take the short way round+ (q and -q are the same rotation; an interpolating player is not told)."""+ q = np.array(q, dtype=np.float64, copy=True)+ for t in range(1, q.shape[0]):+ flip = np.sum(q[t] * q[t - 1], axis=-1) < 0.0+ q[t][flip] *= -1.0+ return q+++def slerp(q0: np.ndarray, q1: np.ndarray, u: np.ndarray) -> np.ndarray:+ """Spherical interpolation, broadcast over leading dims; u in [0, 1]."""+ q0 = np.asarray(q0, dtype=np.float64)+ q1 = np.asarray(q1, dtype=np.float64)+ u = np.asarray(u, dtype=np.float64)[..., None]+ d = np.sum(q0 * q1, axis=-1, keepdims=True)+ q1 = np.where(d < 0.0, -q1, q1)+ d = np.abs(d)+ theta = np.arccos(np.clip(d, -1.0, 1.0))+ s = np.sin(theta)+ small = s < 1e-6+ w0 = np.where(small, 1.0 - u, np.sin((1.0 - u) * theta) / np.where(small, 1.0, s))+ w1 = np.where(small, u, np.sin(u * theta) / np.where(small, 1.0, s))+ out = w0 * q0 + w1 * q1+ return out / np.linalg.norm(out, axis=-1, keepdims=True)+++def align_rotation(src: np.ndarray, dst: np.ndarray) -> np.ndarray:+ """Minimal rotation carrying unit vector(s) `src` onto `dst`,+ vectorised over leading dims."""+ src = np.asarray(src, dtype=np.float64)+ dst = np.asarray(dst, dtype=np.float64)+ src = src / np.maximum(np.linalg.norm(src, axis=-1, keepdims=True), 1e-12)+ dst = dst / np.maximum(np.linalg.norm(dst, axis=-1, keepdims=True), 1e-12)+ v = np.cross(src, dst)+ c = np.sum(src * dst, axis=-1)+ s2 = np.sum(v * v, axis=-1)+ x, y, z = v[..., 0], v[..., 1], v[..., 2]+ zero = np.zeros_like(x)+ K = np.stack([zero, -z, y, z, zero, -x, -y, x, zero], -1).reshape(v.shape[:-1] + (3, 3))+ f = np.where(s2 > 1e-18, (1.0 - c) / np.maximum(s2, 1e-18), 0.0)[..., None, None]+ R = np.broadcast_to(np.eye(3), K.shape) + K + (K @ K) * f+ # antiparallel: rotate pi about any axis perpendicular to src+ anti = (s2 <= 1e-18) & (c < 0.0)+ if np.any(anti):+ a = src[anti]+ seed = np.where(np.abs(a[:, :1]) > 0.9, [[0.0, 1.0, 0.0]], [[1.0, 0.0, 0.0]])+ ax = np.cross(a, seed)+ ax /= np.linalg.norm(ax, axis=-1, keepdims=True)+ R = np.array(R, copy=True)+ R[anti] = 2.0 * ax[:, :, None] * ax[:, None, :] - np.eye(3)+ return R+++def yaw_matrix(angle: np.ndarray) -> np.ndarray:+ """Rotation(s) about +Y (up) by `angle` radians."""+ a = np.asarray(angle, dtype=np.float64)+ c, s = np.cos(a), np.sin(a)+ one, zero = np.ones_like(a), np.zeros_like(a)+ return np.stack([c, zero, s, zero, one, zero, -s, zero, c], -1).reshape(a.shape + (3, 3))+++def heading(R: np.ndarray) -> np.ndarray:+ """Yaw angle (radians about +Y) of a body frame's forward (+Z) axis."""+ f = R[..., :, 2]+ return np.arctan2(f[..., 0], f[..., 2])+++# --------------------------------------------------------------------------+# the body model (estimator side only: needs the gated SMPLX_NEUTRAL.npz)++def shaped_rest(model_npz, betas) -> dict:+ """Performer-shaped rest skeleton + the foot geometry the ground+ solver needs, from SMPLX_NEUTRAL.npz and 10 betas.++ Joints are regressed from the SHAPED rest mesh — exactly how SMPL-X+ places them — so the skeleton has the performer's real proportions+ (leg length, shoulder width), not the template's.+ """+ z = np.load(model_npz, allow_pickle=True)+ betas = np.asarray(betas, dtype=np.float64).reshape(-1)+ nb = betas.shape[0]+ v = z["v_template"].astype(np.float64) + np.einsum(+ "vck,k->vc", z["shapedirs"][:, :, :nb].astype(np.float64), betas)+ Jr = z["J_regressor"].astype(np.float64)+ joints = Jr[:22] @ v+ parents = z["kintree_table"][0][:22].astype(np.int64)+ parents[0] = -1+ if not np.array_equal(parents, PARENT):+ raise ValueError(f"unexpected SMPL-X kinematic tree {parents.tolist()}")+ # Sole = the lowest vertices under each foot. The ankle and the ball+ # joints sit INSIDE the foot; their height above the sole is what maps+ # a planted SMPL-X foot onto a planted Mixamo foot.+ weights = z["weights"].astype(np.float64)+ foot = {}+ for side, (ank, ball) in (("L", (7, 10)), ("R", (8, 11))):+ owned = (weights[:, ank] + weights[:, ball]) > 0.5+ sole = float(v[owned, 1].min())+ heel, big, small = (v[FOOT_VERTS[side][k]] for k in ("heel", "big_toe", "small_toe"))+ foot[side] = {"sole_y": sole,+ "ankle_h": float(joints[ank, 1] - sole),+ "ball_h": float(joints[ball, 1] - sole),+ "toe_tip_z": float(v[owned, 2].max()),+ "heel_z": float(v[owned, 2].min()),+ # the foot as a reader sees it: heel to toes, on the mesh+ "heel": heel.tolist(), "big_toe": big.tolist(), "small_toe": small.tolist()}+ return {"joints": joints, "foot": foot, "floor_y": float(min(foot["L"]["sole_y"], foot["R"]["sole_y"])),+ "height": float(v[:, 1].max() - v[:, 1].min())}+++def fk(global_orient: np.ndarray, body_pose: np.ndarray, transl: np.ndarray,+ rest_joints: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ """SMPL-X forward kinematics for the 22 body joints.++ global_orient (T,3), body_pose (T,63) axis-angle; transl (T,3).+ Returns world joint positions (T,22,3) and world rotations (T,22,3,3).+ SMPL-X rotates the whole body about the ROOT JOINT and then adds+ `transl`, so the pelvis sits at rest_joints[0] + transl.+ """+ T = global_orient.shape[0]+ local = axis_angle_to_matrix(np.concatenate(+ [global_orient.reshape(T, 1, 3), body_pose.reshape(T, 21, 3)], axis=1))+ return fk_local(local, transl, rest_joints)+++def fk_local(local: np.ndarray, transl: np.ndarray, rest_joints: np.ndarray):+ """FK from local rotation matrices (T,22,3,3)."""+ T = local.shape[0]+ R = np.empty((T, 22, 3, 3))+ P = np.empty((T, 22, 3))+ R[:, 0] = local[:, 0]+ P[:, 0] = rest_joints[0] + transl+ for j in range(1, 22):+ p = PARENT[j]+ R[:, j] = R[:, p] @ local[:, j]+ P[:, j] = P[:, p] + np.einsum("tij,j->ti", R[:, p], rest_joints[j] - rest_joints[p])+ return P, R+++def rest_direction(rest_joints: np.ndarray, j: int, child: int) -> np.ndarray:+ d = rest_joints[child] - rest_joints[j]+ return d / np.linalg.norm(d)