Skip to content

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: two-character mocap from a single plate

Sachac809eeff9e97
diff --git a/.gitignore b/.gitignore
index d151248..e9730e6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -24,3 +24,7 @@ tools/
# Python
__pycache__/
*.pyc
+
+# Per-character rig measurements (setup_rig.py / setup_duo.py). Derived
+# from your own Mixamo downloads, same as rig_profile.json above.
+rig_profiles/
diff --git a/action_specs/duel_ninja.json b/action_specs/duel_ninja.json
new file mode 100644
index 0000000..b301d4e
--- /dev/null
+++ b/action_specs/duel_ninja.json
@@ -0,0 +1,77 @@
+{
+ "name": "duel_ninja",
+ "action_name": "Ninja_DuelFromVideo",
+ "clip_dir": "clips/duel/ninja",
+ "landmarks": "plates/duel/landmarks_white.json",
+ "joints_out": "plates/duel/joints_ninja.json",
+ "beatsheet": "plates/duel/BEATSHEET.md",
+ "estimator": "gvhmr_siga24",
+ "src_fps": 24,
+ "dst_fps": 30,
+ "prefilter_window": 5,
+ "_prefilter_note": "the roundhouse peaks over ~6 source frames; the default 7-frame landmark prefilter cost 5 deg of shin angle there (0.04 m of foot height). 5 costs 1.4 deg.",
+ "armature": "Armature_Ninja",
+ "rig_profile": "rig_profiles/ninja.json",
+ "root_motion": true,
+ "stage_x": 0.943,
+ "root_scale": 0.9715,
+ "_root_scale_note": "one stage, one scale: the initial separation and both travel distances must share a factor or the geometry does not close. 0.9715 is the mean of the two characters' leg/performer ratios (YBot 1.0102, Ninja 0.9328).",
+ "_stage_note": "the defender (white shirt, screen-right). Same stage separation as duel_ybot, opposite side.",
+ "rest_blend_start": {
+ "full_src": 32,
+ "release_src": 44
+ },
+ "rest_blend_end": {
+ "start_src": 200,
+ "full_src": 212
+ },
+ "fists": {
+ "rise_src": [
+ 42,
+ 54
+ ],
+ "fall_src": [
+ 174,
+ 190
+ ]
+ },
+ "plant": [
+ {
+ "src": [
+ 1,
+ 241
+ ],
+ "support": "both",
+ "comment": "the defender never leaves the ground: both ankles stay between 0.05 and 0.14 m for the whole take. The fold over the body shot (pelvis 0.84 -> 0.75 @ src123) and the duck under the kick (pelvis 0.85 -> 0.46 @ src149) are pure knee bend, which a both-feet plant resolves by hip-height search."
+ }
+ ],
+ "gaze_max_offset_deg": 70,
+ "qa_src_frames": [
+ 1,
+ 45,
+ 65,
+ 97,
+ 110,
+ 123,
+ 135,
+ 149,
+ 157,
+ 170,
+ 190,
+ 220,
+ 241
+ ],
+ "_rest_blend_note": "was 195/209: the arms reached full T-pose span ~4 source frames ahead of the performer (wrist span +0.121 m at src200).",
+ "arm_follow": [
+ {
+ "src": [
+ 45,
+ 180
+ ],
+ "ramp_src": 6,
+ "side": "both",
+ "anchor": "shoulders",
+ "comment": "the guard measured 0.063-0.070 m narrower than the performer's for the whole fight. Not proportion - this character's shoulders are 0.008 m WIDER than the performer's scaled - it is the direction-preserving retarget landing on an unusual arm ratio (upper 0.210 / fore 0.308). arm_follow places the wrists at the performer's own shoulder-relative geometry and re-solves the chain at exact bone lengths."
+ }
+ ]
+}
diff --git a/action_specs/duel_ybot.json b/action_specs/duel_ybot.json
new file mode 100644
index 0000000..9d14d41
--- /dev/null
+++ b/action_specs/duel_ybot.json
@@ -0,0 +1,141 @@
+{
+ "name": "duel_ybot",
+ "action_name": "YBot_DuelFromVideo",
+ "clip_dir": "clips/duel/ybot",
+ "landmarks": "plates/duel/landmarks_grey.json",
+ "joints_out": "plates/duel/joints_ybot.json",
+ "beatsheet": "plates/duel/BEATSHEET.md",
+ "estimator": "gvhmr_siga24",
+ "src_fps": 24,
+ "dst_fps": 30,
+ "prefilter_window": 5,
+ "_prefilter_note": "the roundhouse peaks over ~6 source frames; the default 7-frame landmark prefilter cost 5 deg of shin angle there (0.04 m of foot height). 5 costs 1.4 deg.",
+ "armature": "Armature_YBot",
+ "rig_profile": "rig_profiles/ybot.json",
+ "root_motion": true,
+ "stage_x": -0.943,
+ "root_scale": 0.9715,
+ "root_offset": [
+ {
+ "src": [
+ 116,
+ 185
+ ],
+ "ramp_src": 23,
+ "dx": -0.2,
+ "comment": "0.20 m of extra room through the kick. Ramped across src 116-139 and 162-185, where he is already retreating 0.24 m of his own accord, so nothing slides: his support foot is planted from src 139 and a step change there would skate. Reads as making range before a head kick, which is what a fighter does."
+ },
+ {
+ "src": [
+ 186,
+ 241
+ ],
+ "ramp_src": 18,
+ "dx": -0.07,
+ "comment": "the closing bind. These characters' arms are ~4% longer relative to their legs than the performers', so at a leg-scaled stage separation their fingertips cross while the arms swing out into the T-pose (3 frames, dest 255-257). The settled T-poses were always clear at 0.09-0.13 m; only the spread collided."
+ }
+ ],
+ "_root_scale_note": "one stage, one scale: the initial separation and both travel distances must share a factor or the geometry does not close. 0.9715 is the mean of the two characters' leg/performer ratios (YBot 1.0102, Ninja 0.9328).",
+ "_stage_note": "the attacker (grey shirt, screen-left). Stage marks are the performers' measured T-pose separation (1.941 m in camera space) scaled to these two characters' legs: 1.886 m, split either side of the origin.",
+ "rest_blend_start": {
+ "full_src": 30,
+ "release_src": 42
+ },
+ "rest_blend_end": {
+ "start_src": 198,
+ "full_src": 212
+ },
+ "fists": {
+ "rise_src": [
+ 40,
+ 52
+ ],
+ "fall_src": [
+ 174,
+ 188
+ ]
+ },
+ "plant": [
+ {
+ "src": [
+ 1,
+ 86
+ ],
+ "support": "both",
+ "comment": "T-pose, turn-in, guard. Feet shift within the stance and step in; both ankles stay under 0.22 m."
+ },
+ {
+ "src": [
+ 87,
+ 96
+ ],
+ "support": "left",
+ "comment": "right foot lifts to 0.17-0.20 m driving the step into punch 1"
+ },
+ {
+ "src": [
+ 97,
+ 116
+ ],
+ "support": "both"
+ },
+ {
+ "src": [
+ 117,
+ 126
+ ],
+ "support": "left",
+ "comment": "right foot lifts to 0.21 m on the last punch"
+ },
+ {
+ "src": [
+ 127,
+ 138
+ ],
+ "support": "both"
+ },
+ {
+ "src": [
+ 139,
+ 158
+ ],
+ "support": "left",
+ "comment": "right roundhouse: right ankle 0.18 -> 1.09 m @ src147, left ankle stays 0.06-0.09"
+ },
+ {
+ "src": [
+ 159,
+ 241
+ ],
+ "support": "both"
+ }
+ ],
+ "leg_pose": [
+ {
+ "src": [
+ 142,
+ 150
+ ],
+ "ramp_src": 3,
+ "side": "right",
+ "lift_m": 0.37,
+ "comment": "sized against the real MESHES, not a capsule proxy. 0.18 restores the reference ankle trajectory to +/-0.035 m and still put the foot through the Ninja's head: these characters are thicker than the performers and the video itself only clears by ~2 cm. 0.37 is 0.18 (faithful) + 0.19 (clearance), the minimum that clears every frame together with root_offset."
+ }
+ ],
+ "gaze_max_offset_deg": 70,
+ "qa_src_frames": [
+ 1,
+ 40,
+ 60,
+ 89,
+ 97,
+ 105,
+ 115,
+ 125,
+ 147,
+ 160,
+ 190,
+ 220,
+ 241
+ ]
+}
diff --git a/pipeline/apply_mixamo_fk.py b/pipeline/apply_mixamo_fk.py
index 6c4a34a..7c9031d 100644
--- a/pipeline/apply_mixamo_fk.py
+++ b/pipeline/apply_mixamo_fk.py
@@ -36,16 +36,29 @@ GROUND_Z = 0.105 # Y Bot rest ankle height (flat-foot contact)
HIP_HEIGHT = 0.99792 # Y Bot rest hip height
FPS = 30
-# Character-specific overrides from rig_profile.json (setup_rig.py) —
-# any Mixamo character, not just Y Bot.
-_PROFILE = REPO / "rig_profile.json"
-if _PROFILE.exists():
- try:
- _p = json.loads(_PROFILE.read_text(encoding="utf-8"))
- GROUND_Z = float(_p["ground_z"])
- HIP_HEIGHT = float(_p["hip_height"])
- except Exception:
- pass
+
+def use_profile(path=None) -> str:
+ """Adopt one character's measured ground/hip heights.
+
+ Solo scenes fall back to rig_profile.json at the repo root; a
+ multi-character scene names a profile per character in its spec
+ (`rig_profile`), because two characters in one file do NOT share a
+ hip height and planting the Ninja at the Y Bot's ground offset
+ buries its feet.
+ """
+ global GROUND_Z, HIP_HEIGHT
+ p = (Path(path) if Path(path).is_absolute() else REPO / path) if path else (REPO / "rig_profile.json")
+ if not p.exists():
+ if path:
+ raise RuntimeError(f"rig profile not found: {p}")
+ return "built-in Y Bot"
+ _p = json.loads(p.read_text(encoding="utf-8"))
+ GROUND_Z = float(_p["ground_z"])
+ HIP_HEIGHT = float(_p["hip_height"])
+ return p.name
+
+
+use_profile()
AIM = [
("mixamorig:Spine", "spine1"),
@@ -106,6 +119,17 @@ def rpath(p) -> Path:
return p if p.is_absolute() else (REPO / p)
+def get_armature(spec: dict):
+ """The armature this spec animates. Multi-character scenes name it
+ (`"armature": "Armature_YBot"`); solo scenes keep "Armature"."""
+ name = spec.get("armature", "Armature")
+ arm = bpy.data.objects.get(name)
+ if arm is None or arm.type != "ARMATURE":
+ have = [o.name for o in bpy.data.objects if o.type == "ARMATURE"]
+ raise RuntimeError(f"armature {name!r} not in the scene (have: {have})")
+ return arm
+
+
def v(seq) -> Vector:
return Vector((float(seq[0]), float(seq[1]), float(seq[2])))
@@ -416,7 +440,8 @@ def run(spec_path: str) -> dict:
src_fps = float(payload.get("src_fps", 24))
dst_fps = float(payload.get("dst_fps", 30))
- arm = bpy.data.objects["Armature"]
+ use_profile(spec.get("rig_profile"))
+ arm = get_armature(spec)
bpy.context.view_layer.objects.active = arm
if bpy.context.mode != "POSE":
bpy.ops.object.mode_set(mode="POSE")
@@ -539,7 +564,7 @@ def run_stills_render(spec_path: str, dest_frames) -> dict:
spec = json.loads(rpath(spec_path).read_text(encoding="utf-8"))
pose_dir = rpath(spec["clip_dir"]) / "poses"
pose_dir.mkdir(parents=True, exist_ok=True)
- arm = bpy.data.objects["Armature"]
+ arm = get_armature(spec)
scene = bpy.context.scene
cam_data = bpy.data.cameras.new("QA_Camera")
@@ -588,7 +613,7 @@ def run_stills_render(spec_path: str, dest_frames) -> dict:
def dump_curves(spec_path: str) -> dict:
"""Every bone, every frame: pose channels + world location."""
spec = json.loads(rpath(spec_path).read_text(encoding="utf-8"))
- arm = bpy.data.objects["Armature"]
+ arm = get_armature(spec)
end = bpy.context.scene.frame_end
out = []
for f in range(1, end + 1):
@@ -614,3 +639,73 @@ def dump_curves(spec_path: str) -> dict:
clip_dir = rpath(spec["clip_dir"])
(clip_dir / "curves.json").write_text(json.dumps({"frames": out}), encoding="utf-8")
return {"curves_frames": len(out)}
+
+def pair_mesh_contact(spec_a: str, spec_b: str, f0: int = 1, f1: int = 0, step: int = 1) -> dict:
+ """Real mesh-vs-mesh contact between two characters, per frame.
+
+ The capsule proxies in compare_pair.py (a 0.16 m torso cylinder, a
+ 0.11 m head sphere) are a cheap stand-in that runs outside Blender.
+ They are also OPTIMISTIC: a hood, a shoulder pad or a wide chest all
+ live outside the cylinder, so a limb can clear every capsule and
+ still visibly pass through the character. This is the ground truth —
+ the evaluated (posed, skinned) meshes, tested for actual
+ intersection.
+
+ Returns per frame: the number of intersecting face pairs, and the
+ minimum surface-to-surface distance when they do not intersect.
+ """
+ import bmesh
+ from mathutils.bvhtree import BVHTree
+
+ spec_a = json.loads(rpath(spec_a).read_text(encoding="utf-8"))
+ spec_b = json.loads(rpath(spec_b).read_text(encoding="utf-8"))
+ scene = bpy.context.scene
+ f1 = f1 or scene.frame_end
+ deps = bpy.context.evaluated_depsgraph_get()
+
+ def meshes_of(spec):
+ arm = get_armature(spec)
+ return [o for o in bpy.data.objects
+ if o.type == "MESH" and o.find_armature() is arm and not o.hide_render]
+
+ mesh_a, mesh_b = meshes_of(spec_a), meshes_of(spec_b)
+ if not mesh_a or not mesh_b:
+ raise RuntimeError(f"need meshes for both characters (found {len(mesh_a)} / {len(mesh_b)})")
+
+ def bvh_of(objs):
+ bm = bmesh.new()
+ for o in objs:
+ ev = o.evaluated_get(deps)
+ me = ev.to_mesh()
+ bm.from_mesh(me)
+ # to_mesh() gives object-local coordinates; the tree must be world.
+ ev.to_mesh_clear()
+ bm.transform(objs[0].matrix_world)
+ tree = BVHTree.FromBMesh(bm)
+ verts = [v.co.copy() for v in bm.verts]
+ bm.free()
+ return tree, verts
+
+ out = []
+ for f in range(f0, f1 + 1, step):
+ scene.frame_set(f)
+ bpy.context.view_layer.update()
+ deps = bpy.context.evaluated_depsgraph_get()
+ tree_a, verts_a = bvh_of(mesh_a)
+ tree_b, _ = bvh_of(mesh_b)
+ pairs = tree_a.overlap(tree_b)
+ best = 1e9
+ if not pairs:
+ for v in verts_a[::7]: # sampled: we only need the minimum
+ hit = tree_b.find_nearest(v)
+ if hit and hit[3] is not None:
+ best = min(best, float(hit[3]))
+ out.append({"frame": f, "overlaps": len(pairs),
+ "min_dist": round(best, 4) if best < 1e8 else None})
+ clip_dir = rpath(spec_a["clip_dir"]).parent
+ clip_dir.mkdir(parents=True, exist_ok=True)
+ (clip_dir / "pair_contact.json").write_text(json.dumps({"frames": out}), encoding="utf-8")
+ hits = [r for r in out if r["overlaps"]]
+ return {"frames": len(out), "intersecting_frames": len(hits),
+ "worst": max((r["overlaps"] for r in out), default=0),
+ "sample": hits[:12] or out[:6]}
diff --git a/pipeline/compare_pair.py b/pipeline/compare_pair.py
new file mode 100644
index 0000000..bb5b64b
--- /dev/null
+++ b/pipeline/compare_pair.py
@@ -0,0 +1,404 @@
+"""Two-character check: does the retargeted pair stand, reach and miss
+each other the way the two performers did?
+
+ tools\\GVHMR\\.venv\\Scripts\\python.exe pipeline\\compare_pair.py ^
+ --spec action_specs\\duel_ybot.json --spec action_specs\\duel_ninja.json
+ ... --from-src 80 --to-src 160 limit to a beat
+ ... --detail per-frame table
+
+`qa_clip.py` proves one clip is not broken. `compare_reference.py`
+proves one clip looks like its performer. Neither can see the thing a
+two-fighter scene is entirely about: the RELATIONSHIP between the two
+characters. A pair of individually perfect retargets still fails if the
+attacker stands a metre too far away (every punch swings through empty
+air) or a metre too close (his fist ends up inside the other's skull).
+
+Three measurements, in the order they matter:
+
+ separation hip-to-hip distance, reference vs retarget. The
+ reference figure is exact — both performers were
+ estimated in the same camera frame, so `incam_root`
+ puts them on one floor with no assumptions.
+ reach gap from the striking hand/foot to the other
+ character's body (spine axis and head). A punch that
+ stopped 5 cm from the guard in the video should stop
+ ~5 cm from it here.
+ intrusion absolute defect check: an extremity INSIDE the other
+ character's torso or head. No reference needed — it
+ is wrong however the video looked.
+
+Both performers are read in the estimator's CAMERA frame (`incam` in
+landmarks.json), the one frame two independently-estimated people
+actually share. Their `world` landmarks cannot be used here: those are
+normalised per performer so frame 0's facing becomes forward, so two
+performers' limbs sit in two differently-yawed frames.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import numpy as np
+
+REPO = Path(__file__).resolve().parents[1]
+
+TOL = {
+ "separation": 0.10, # metres, hip to hip
+ "reach": 0.09, # metres, striking extremity to the other body
+}
+MIN_RUN = 3
+TORSO_R = 0.16 # metres from the spine axis
+HEAD_R = 0.11 # metres from the head joint
+
+STRIKERS = {
+ "l_hand": "mixamorig:LeftHand", "r_hand": "mixamorig:RightHand",
+ "l_foot": "mixamorig:LeftToeBase", "r_foot": "mixamorig:RightToeBase",
+}
+
+# Whole limb segments, for the intrusion test.
+LIMBS = {
+ "l_forearm": ("mixamorig:LeftForeArm", "mixamorig:LeftHand"),
+ "r_forearm": ("mixamorig:RightForeArm", "mixamorig:RightHand"),
+ "l_upperarm": ("mixamorig:LeftArm", "mixamorig:LeftForeArm"),
+ "r_upperarm": ("mixamorig:RightArm", "mixamorig:RightForeArm"),
+ "l_shin": ("mixamorig:LeftLeg", "mixamorig:LeftFoot"),
+ "r_shin": ("mixamorig:RightLeg", "mixamorig:RightFoot"),
+ "l_foot": ("mixamorig:LeftFoot", "mixamorig:LeftToeBase"),
+ "r_foot": ("mixamorig:RightFoot", "mixamorig:RightToeBase"),
+ "l_thigh": ("mixamorig:LeftUpLeg", "mixamorig:LeftLeg"),
+ "r_thigh": ("mixamorig:RightUpLeg", "mixamorig:RightLeg"),
+}
+# Paired deliberately: Blender reports a bone's HEAD, so `mixamorig:*Hand`
+# is at the wrist — matching the performer's wrist landmark, not their
+# fingertips (docs/PITFALLS.md #21).
+REF_STRIKERS = {
+ "l_hand": "left_wrist", "r_hand": "right_wrist",
+ "l_foot": "left_foot_index", "r_foot": "right_foot_index",
+}
+
+
+def rpath(p) -> Path:
+ p = Path(p)
+ return p if p.is_absolute() else (REPO / p)
+
+
+def unit(v):
+ n = np.linalg.norm(v)
+ return v / n if n > 1e-9 else np.zeros(3)
+
+
+def seg_dist(p, a, b) -> float:
+ """Distance from point p to segment a-b."""
+ ab = b - a
+ L = float(np.dot(ab, ab))
+ t = 0.0 if L < 1e-12 else float(np.clip(np.dot(p - a, ab) / L, 0.0, 1.0))
+ return float(np.linalg.norm(p - (a + ab * t)))
+
+
+def seg_seg(p1, q1, p2, q2, samples: int = 12) -> float:
+ """Distance between two segments (sampled — exact enough at cm scale).
+
+ Limb-vs-limb, not point-vs-limb: a kick that passes THROUGH a head
+ can easily keep both its toe and its knee outside the skull while the
+ shin goes straight through the middle. Checking only the endpoints of
+ a limb is how that ships.
+ """
+ ts = np.linspace(0.0, 1.0, samples)
+ best = 1e9
+ for t in ts:
+ pt = p1 + (q1 - p1) * t
+ best = min(best, seg_dist(pt, p2, q2))
+ return float(best)
+
+
+class Fighter:
+ """One character: its retargeted curves and its performer's landmarks."""
+
+ def __init__(self, spec_path: Path):
+ self.spec = json.loads(rpath(spec_path).read_text(encoding="utf-8"))
+ self.name = self.spec["name"]
+ self.curves = json.loads(
+ (rpath(self.spec["clip_dir"]) / "curves.json").read_text(encoding="utf-8"))["frames"]
+ self.lm = json.loads(rpath(self.spec["landmarks"]).read_text(encoding="utf-8"))["frames"]
+ prof = json.loads(rpath(self.spec.get("rig_profile", "rig_profile.json")).read_text(encoding="utf-8"))
+ L = prof["lengths"]
+ self.arm = L["l_arm"] + L["l_fore"]
+ self.leg = L["l_upleg"] + L["l_leg"]
+ self.src_fps = float(self.spec.get("src_fps", 24))
+ self.dst_fps = float(self.spec.get("dst_fps", 30))
+ ref_leg = float(np.mean([
+ np.linalg.norm(self.ref(i, "left_hip") - self.ref(i, "left_knee"))
+ + np.linalg.norm(self.ref(i, "left_knee") - self.ref(i, "left_ankle"))
+ for i in range(0, len(self.lm), 5)]))
+ self.scale = self.leg / max(ref_leg, 1e-6)
+
+ def dest(self, sf: int) -> int:
+ return int(round((sf - 1) * self.dst_fps / self.src_fps + 1))
+
+ def ref(self, i: int, n: str) -> np.ndarray:
+ p = self.lm[i]["world"][n]
+ return np.array([p["x"], p["y"], p["z"]])
+
+ def cam_pt(self, i: int, n: str) -> np.ndarray:
+ """A performer landmark in raw camera space (y down)."""
+ q = self.lm[i]["incam"][n]
+ return np.array([q["x"], q["y"], q["z"]])
+
+ def gravity_in_camera(self, every: int = 4) -> np.ndarray:
+ """Which way is UP, expressed in camera space.
+
+ Solved, not assumed. Each performer is delivered in two frames:
+ `world` (gravity-aligned — that is what makes foot planting work
+ at all) and `incam` (the camera's). Fitting the rotation between
+ them for one performer and pushing the world frame's up axis
+ through it says where gravity points in the camera's frame.
+ """
+ Wm, Cm = [], []
+ for i in range(0, len(self.lm), every):
+ hw = 0.5 * (self.ref(i, "left_hip") + self.ref(i, "right_hip"))
+ hc = 0.5 * (self.cam_pt(i, "left_hip") + self.cam_pt(i, "right_hip"))
+ for n in ("left_shoulder", "right_shoulder", "left_hip", "right_hip",
+ "left_knee", "right_knee", "left_ankle", "right_ankle",
+ "left_elbow", "right_elbow", "left_wrist", "right_wrist", "nose"):
+ Wm.append(self.ref(i, n) - hw)
+ Cm.append(self.cam_pt(i, n) - hc)
+ Wm, Cm = np.array(Wm), np.array(Cm)
+ U, _, Vt = np.linalg.svd(Cm.T @ Wm) # camera ~= R @ world
+ d = np.sign(np.linalg.det(U @ Vt))
+ R = U @ np.diag([1.0, 1.0, d]) @ Vt
+ return R @ np.array([0.0, -1.0, 0.0]) # world y is DOWN
+
+
+ def ref_pt(self, i: int, n: str) -> np.ndarray:
+ """A performer landmark in the shared, gravity-aligned stage frame."""
+ return self.basis @ self.cam_pt(i, n)
+
+ def bone(self, f: int, b: str) -> np.ndarray:
+ return np.array(self.curves[f - 1]["bones"][b]["world_location"])
+
+
+def stage_basis(up_cam: np.ndarray) -> np.ndarray:
+ """A gravity-aligned frame shared by both performers.
+
+ z = true up, x = the camera's right flattened into the ground plane
+ (which is the fighting line in a side-on plate), y = depth.
+ """
+ ez = up_cam / np.linalg.norm(up_cam)
+ ex = np.array([1.0, 0.0, 0.0])
+ ex = ex - ez * float(np.dot(ex, ez))
+ ex /= np.linalg.norm(ex)
+ ey = np.cross(ez, ex)
+ return np.stack([ex, ey, ez])
+
+
+def body_gap(pt, hips, neck, head) -> float:
+ """Signed clearance from a point to a body: negative = inside it.
+
+ `head` must be the SKULL CENTRE on both sides of the comparison. The
+ obvious pair — the performer's nose and the character's Head bone —
+ are not the same landmark (one is on the face, the other sits at the
+ base of the skull) and pairing them bakes a fixed ~10 cm error into
+ every strike that is aimed at a head.
+ """
+ return min(seg_dist(pt, hips, neck) - TORSO_R, float(np.linalg.norm(pt - head)) - HEAD_R)
+
+
+def ref_body(f, i, S):
+ """A performer's torso axis and skull centre, in character metres."""
+ hips = 0.5 * (f.ref_pt(i, "left_hip") + f.ref_pt(i, "right_hip")) * S
+ neck = 0.5 * (f.ref_pt(i, "left_shoulder") + f.ref_pt(i, "right_shoulder")) * S
+ head = 0.5 * (f.ref_pt(i, "left_ear") + f.ref_pt(i, "right_ear")) * S
+ return hips, neck, head
+
+
+def app_body(f, df):
+ """A character's torso axis and skull centre.
+
+ The axis tops out at the SHOULDER LINE, not at `mixamorig:Neck`.
+ Neck sits above the shoulder joints, so a hips-to-neck capsule is
+ 5-10 cm longer than the hips-to-shoulder-mid capsule the reference
+ side can build from landmarks — and that surplus length reaches out
+ to meet an incoming limb, manufacturing an intrusion that is really
+ just two different definitions of "torso".
+ """
+ hips = f.bone(df, "mixamorig:Hips")
+ neck = 0.5 * (f.bone(df, "mixamorig:LeftArm") + f.bone(df, "mixamorig:RightArm"))
+ try:
+ head = 0.5 * (f.bone(df, "mixamorig:Head") + f.bone(df, "mixamorig:HeadTop_End"))
+ except KeyError:
+ head = f.bone(df, "mixamorig:Head")
+ return hips, neck, head
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--spec", action="append", required=True,
+ help="action_spec per character (give it twice)")
+ ap.add_argument("--from-src", type=int, default=None)
+ ap.add_argument("--to-src", type=int, default=None)
+ ap.add_argument("--detail", action="store_true")
+ ap.add_argument("--step", type=int, default=1)
+ args = ap.parse_args()
+ if len(args.spec) != 2:
+ raise SystemExit("compare_pair needs exactly two --spec arguments")
+
+ A, B = Fighter(args.spec[0]), Fighter(args.spec[1])
+ # One frame for both, with a real vertical. Measuring height in raw
+ # camera space costs whatever the camera's pitch is: on this plate it
+ # inflated the reference kick's peak by 0.14 m, which is most of a
+ # "the foot is too low" finding that does not exist.
+ up = 0.5 * (A.gravity_in_camera() + B.gravity_in_camera())
+ basis = stage_basis(up)
+ A.basis = B.basis = basis
+ tilt = np.degrees(np.arccos(np.clip(np.dot(up / np.linalg.norm(up), [0, -1, 0]), -1, 1)))
+ S = 0.5 * (A.scale + B.scale) # one stage, one scale
+ print(f"camera tilt vs gravity: {tilt:.1f} deg")
+ n_src = min(len(A.lm), len(B.lm))
+ print(f"pair: {A.name} vs {B.name} | stage scale {S:.4f} "
+ f"({A.name} {A.scale:.4f}, {B.name} {B.scale:.4f})")
+
+ s0 = args.from_src or 1
+ s1 = min(args.to_src or n_src, n_src)
+ rows = []
+ for sf in range(s0, s1 + 1, args.step):
+ fa, fb = A.dest(sf), B.dest(sf)
+ if fa > len(A.curves) or fb > len(B.curves):
+ continue
+ i = sf - 1
+
+ ref_sep = float(np.linalg.norm(
+ 0.5 * (A.ref_pt(i, "left_hip") + A.ref_pt(i, "right_hip"))
+ - 0.5 * (B.ref_pt(i, "left_hip") + B.ref_pt(i, "right_hip")))) * S
+ app_sep = float(np.linalg.norm(A.bone(fa, "mixamorig:Hips") - B.bone(fb, "mixamorig:Hips")))
+
+ row = {"src": sf, "ref_sep": ref_sep, "app_sep": app_sep, "strikes": {}, "limbs": {}}
+ for att, dfn, other, dfo, side in ((A, fa, B, fb, "A"), (B, fb, A, fa, "B")):
+ o_hips, o_neck, o_head = app_body(other, dfo)
+ for lname, (b0, b1) in LIMBS.items():
+ try:
+ p0, p1 = att.bone(dfn, b0), att.bone(dfn, b1)
+ except KeyError:
+ continue
+ row["limbs"][f"{side}:{lname}"] = min(
+ seg_seg(p0, p1, o_hips, o_neck) - TORSO_R,
+ seg_dist(o_head, p0, p1) - HEAD_R)
+ for tag, bone_name in STRIKERS.items():
+ rn = REF_STRIKERS[tag]
+ for att, dfn, other, dfo, side in ((A, fa, B, fb, "A"), (B, fb, A, fa, "B")):
+ gap_a = body_gap(att.bone(dfn, bone_name), *app_body(other, dfo))
+ gap_r = body_gap(att.ref_pt(i, rn) * S, *ref_body(other, i, S))
+ row["strikes"][f"{side}:{tag}"] = (gap_r, gap_a)
+ rows.append(row)
+
+ if not rows:
+ raise SystemExit("no overlapping frames")
+
+ if args.detail:
+ print("\n src | separation ref->app | closest strike gap ref->app (limb)")
+ for r in rows:
+ k, (gr, ga) = min(r["strikes"].items(), key=lambda kv: kv[1][1])
+ print(f" {r['src']:3d} | {r['ref_sep']:.2f} -> {r['app_sep']:.2f}"
+ f" | {gr:+.3f} -> {ga:+.3f} {k}")
+ print()
+
+ print("\nFINDINGS")
+ found = False
+
+ def windows(vals, tol):
+ bad = np.abs(np.asarray(vals)) > tol
+ i = 0
+ while i < len(bad):
+ if not bad[i]:
+ i += 1
+ continue
+ j = i
+ while j + 1 < len(bad) and bad[j + 1]:
+ j += 1
+ if rows[j]["src"] - rows[i]["src"] >= MIN_RUN:
+ yield i, j
+ i = j + 1
+
+ # A spec may DECLARE a clearance offset (two characters are bulkier
+ # than two humans; see docs/PITFALLS.md #33). Report those windows as
+ # declared rather than as an unexplained defect — but still report
+ # them, because the number is the departure from the video.
+ declared = []
+ for f in (A, B):
+ for ro in f.spec.get("root_offset", []):
+ declared.append((ro["src"][0], ro["src"][1],
+ float(ro.get("dx", 0.0)), float(ro.get("dy", 0.0))))
+
+ def is_declared(s0, s1):
+ return any(a - 5 <= s0 and s1 <= b + 5 for a, b, _, _ in declared)
+
+ sep_err = [r["app_sep"] - r["ref_sep"] for r in rows]
+ for i, j in windows(sep_err, TOL["separation"]):
+ seg = np.array(sep_err[i:j + 1])
+ k = int(np.argmax(np.abs(seg)))
+ found = True
+ tag = " [declared root_offset]" if is_declared(rows[i]["src"], rows[j]["src"]) else ""
+ print(f" src {rows[i]['src']:3d}-{rows[j]['src']:3d} separation: mean {seg.mean():+.3f} m, "
+ f"worst {seg[k]:+.3f} @ src {rows[i + k]['src']} "
+ f"({'too far apart' if seg.mean() > 0 else 'too close'}){tag}")
+
+ for key in sorted(rows[0]["strikes"]):
+ gaps_r = [r["strikes"][key][0] for r in rows]
+ gaps_a = [r["strikes"][key][1] for r in rows]
+ # Only judge a limb where the reference actually brings it near
+ # the other body — a guard hand resting by the chest is not a
+ # strike and its "gap" carries no information.
+ err = [(a - r) if (r < 0.35 or a < 0.35) else 0.0 for r, a in zip(gaps_r, gaps_a)]
+ for i, j in windows(err, TOL["reach"]):
+ seg = np.array(err[i:j + 1])
+ k = int(np.argmax(np.abs(seg)))
+ found = True
+ print(f" src {rows[i]['src']:3d}-{rows[j]['src']:3d} {key} reach: mean {seg.mean():+.3f} m, "
+ f"worst {seg[k]:+.3f} @ src {rows[i + k]['src']} "
+ f"({'stops short' if seg.mean() > 0 else 'reaches too far'})"
+ f" | ref gap {gaps_r[i + k]:+.3f} -> {gaps_a[i + k]:+.3f}")
+
+ # Absolute defect: a limb inside the other character. No reference
+ # needed and no minimum run — two frames of a shin through a skull is
+ # still two frames of a shin through a skull.
+ for key in sorted(rows[0].get("limbs", {})):
+ pen = np.array([r["limbs"].get(key, 9.0) for r in rows])
+ bad = pen < 0.0
+ i = 0
+ while i < len(bad):
+ if not bad[i]:
+ i += 1
+ continue
+ j = i
+ while j + 1 < len(bad) and bad[j + 1]:
+ j += 1
+ k = i + int(np.argmin(pen[i:j + 1]))
+ found = True
+ print(f" src {rows[i]['src']:3d}-{rows[j]['src']:3d} {key} INSIDE the other character: "
+ f"worst {pen[k]:.3f} m past the surface @ src {rows[k]['src']}")
+ i = j + 1
+
+ if not found:
+ print(" none — separation, reach and clearance all track the reference")
+
+ print("\nCLOSEST APPROACH (the beats where the two actually meet)")
+ for key in sorted(rows[0]["strikes"]):
+ gr = np.array([r["strikes"][key][0] for r in rows])
+ ga = np.array([r["strikes"][key][1] for r in rows])
+ if gr.min() > 0.30 and ga.min() > 0.30:
+ continue # this limb never came near the other fighter
+ kr, ka = int(np.argmin(gr)), int(np.argmin(ga))
+ flag = "" if abs(ga.min() - gr.min()) < 0.10 else " <-- differs"
+ print(f" {key:10s} reference {gr.min():+.3f} m @ src {rows[kr]['src']:3d}"
+ f" | retarget {ga.min():+.3f} m @ src {rows[ka]['src']:3d}{flag}")
+
+ sep_r = np.array([r["ref_sep"] for r in rows])
+ sep_a = np.array([r["app_sep"] for r in rows])
+ print(f"\nseparation: reference {sep_r.min():.2f}-{sep_r.max():.2f} m, "
+ f"retarget {sep_a.min():.2f}-{sep_a.max():.2f} m, "
+ f"mean error {np.mean(sep_a - sep_r):+.3f} m")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/pipeline/compare_reference.py b/pipeline/compare_reference.py
index 48dab49..6df0143 100644
--- a/pipeline/compare_reference.py
+++ b/pipeline/compare_reference.py
@@ -71,7 +71,8 @@ def main() -> None:
spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))
lm = json.loads(rpath(spec["landmarks"]).read_text(encoding="utf-8"))["frames"]
curves = json.loads((rpath(spec["clip_dir"]) / "curves.json").read_text(encoding="utf-8"))["frames"]
- profile = json.loads((REPO / "rig_profile.json").read_text(encoding="utf-8"))
+ prof_path = spec.get("rig_profile", "rig_profile.json")
+ profile = json.loads(rpath(prof_path).read_text(encoding="utf-8"))
src_fps = float(spec.get("src_fps", 24))
dst_fps = float(spec.get("dst_fps", 30))
diff --git a/pipeline/estimate_pose_gvhmr.py b/pipeline/estimate_pose_gvhmr.py
index faad3db..db85b0b 100644
--- a/pipeline/estimate_pose_gvhmr.py
+++ b/pipeline/estimate_pose_gvhmr.py
@@ -124,7 +124,90 @@ def video_fps(path: Path) -> float:
# Stage 1 — GVHMR demo pipeline (preprocess + predict), no rendering.
# Results are cached in <GVHMR_ROOT>/outputs/demo/<video_name>/.
-def run_gvhmr(video: Path) -> dict:
+def side_track(tracker, video_path: str, person: str, n_people: int = 2):
+ """Bounding boxes for ONE performer in a multi-person plate, selected
+ by the side of frame they occupy.
+
+ GVHMR's own `get_one_track` keeps the single largest track, which is
+ useless when two people fight. Selecting by YOLO track id is fragile:
+ ids swap when two bodies touch, and a swap silently splices half of
+ each performer into one "track". Screen side is a fact instead of a
+ guess — as long as the plate never lets them cross (see the duel
+ plate's SOURCE.md), left stays left for the whole take.
+
+ Detections are assigned per frame to `n_people` slots ordered by x,
+ with nearest-centroid continuity so a momentarily missed detection
+ does not shift everyone one slot over.
+ """
+ import numpy as _np
+ import torch as _torch
+ from hmr4d.utils.seq_utils import (frame_id_to_mask, get_frame_id_list_from_mask,
+ linear_interpolate_frame_ids, rearrange_by_mask)
+ from hmr4d.utils.net_utils import moving_average_smooth
+ from hmr4d.utils.video_io_utils import get_video_lwh
+
+ history = tracker.track(video_path)
+ length = get_video_lwh(video_path)[0]
+
+ def cx(b):
+ return 0.5 * (float(b[0]) + float(b[2]))
+
+ # Seed the slots from the first frame that sees everyone.
+ seed = None
+ for frame in history:
+ if len(frame) >= n_people:
+ seed = sorted(frame, key=lambda d: cx(d["bbx_xyxy"]))[:n_people]
+ break
+ if seed is None:
+ raise SystemExit(f"never saw {n_people} people in the same frame — is this a solo plate?")
+ slots_x = [cx(d["bbx_xyxy"]) for d in seed]
+
+ boxes = _np.zeros((n_people, length, 4), dtype=_np.float32)
+ seen = [[] for _ in range(n_people)]
+ for f, frame in enumerate(history[:length]):
+ dets = sorted(frame, key=lambda d: cx(d["bbx_xyxy"]))
+ if len(dets) >= n_people:
+ # Enough boxes: order alone identifies them.
+ chosen = list(range(n_people))
+ if len(dets) > n_people:
+ # Extra detections (reflections, a bystander): keep the
+ # n_people whose centres are closest to the known slots.
+ chosen = []
+ for sx in slots_x:
+ k = min(range(len(dets)), key=lambda j: abs(cx(dets[j]["bbx_xyxy"]) - sx) + 1e6 * (j in chosen))
+ chosen.append(k)
+ chosen = sorted(chosen, key=lambda j: cx(dets[j]["bbx_xyxy"]))
+ for s, j in enumerate(chosen):
+ boxes[s, f] = dets[j]["bbx_xyxy"]
+ slots_x[s] = cx(dets[j]["bbx_xyxy"])
+ seen[s].append(f)
+ else:
+ for d in dets: # partial frame: nearest slot wins
+ s = min(range(n_people), key=lambda k: abs(cx(d["bbx_xyxy"]) - slots_x[k]))
+ boxes[s, f] = d["bbx_xyxy"]
+ slots_x[s] = cx(d["bbx_xyxy"])
+ seen[s].append(f)
+
+ order = {"left": 0, "right": n_people - 1}
+ slot = order[person] if person in order else int(person)
+ if not (0 <= slot < n_people):
+ raise SystemExit(f"--person {person} out of range for {n_people} people")
+
+ frame_ids = _torch.tensor(sorted(set(seen[slot])))
+ if len(frame_ids) < length * 0.5:
+ raise SystemExit(f"person '{person}' detected in only {len(frame_ids)}/{length} frames")
+ bbx = _torch.tensor(boxes[slot][frame_ids.numpy()])
+ mask = frame_id_to_mask(frame_ids, length)
+ out = rearrange_by_mask(bbx, mask)
+ out = linear_interpolate_frame_ids(out, get_frame_id_list_from_mask(~mask))
+ out = moving_average_smooth(out, window_size=5, dim=0)
+ out = moving_average_smooth(out, window_size=5, dim=0)
+ print(f"person '{person}' -> slot {slot}: detected in {len(frame_ids)}/{length} frames, "
+ f"mean centre x {boxes[slot][:, [0, 2]].mean():.0f} px")
+ return out
+
+
+def run_gvhmr(video: Path, person: str | None = None) -> dict:
import hydra
from hydra import compose, initialize_config_module
@@ -140,7 +223,8 @@ def run_gvhmr(video: Path) -> dict:
register_store_gvhmr()
cfg = compose(
config_name="demo",
- overrides=[f"video_name={video.stem}", "static_cam=True", "verbose=False", "use_dpvo=False"],
+ overrides=[f"video_name={video.stem if not person else video.stem + '_' + person}",
+ "static_cam=True", "verbose=False", "use_dpvo=False"],
)
Path(cfg.output_dir).mkdir(parents=True, exist_ok=True)
Path(cfg.preprocess_dir).mkdir(parents=True, exist_ok=True)
@@ -158,7 +242,8 @@ def run_gvhmr(video: Path) -> dict:
paths = cfg.paths
if not Path(paths.bbx).exists():
tracker = Tracker()
- bbx_xyxy = tracker.get_one_track(cfg.video_path).float()
+ bbx_xyxy = (side_track(tracker, cfg.video_path, person) if person
+ else tracker.get_one_track(cfg.video_path)).float()
bbx_xys = get_bbx_xys_from_xyxy(bbx_xyxy, base_enlarge=1.2).float()
torch.save({"bbx_xyxy": bbx_xyxy, "bbx_xys": bbx_xys}, paths.bbx)
del tracker
@@ -339,6 +424,9 @@ def main() -> None:
ap.add_argument("--video", required=True, type=Path)
ap.add_argument("--out", required=True, type=Path)
ap.add_argument("--fps", type=float, default=None, help="source fps for the t clock (default: probe the video)")
+ 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.")
args = ap.parse_args()
def rp(p: Path) -> Path:
@@ -351,7 +439,7 @@ def main() -> None:
preflight()
fps = args.fps or video_fps(video)
- res = run_gvhmr(video)
+ res = run_gvhmr(video, args.person)
pred = res["pred"]
joints_ayfz, joints_incam, K, face_ayfz, face_incam = smpl_joints(pred)
L = joints_ayfz.shape[0]
@@ -372,21 +460,44 @@ def main() -> None:
gaze = mp_world["nose"] - ear_mid
gn = float(np.linalg.norm(gaze)) or 1.0
gaze = gaze / gn
+ # Ground trajectory. `world` below is re-centred on the hips every
+ # frame (MediaPipe convention), which throws the performer's travel
+ # away — fine for a solo in-place clip, fatal for two fighters whose
+ # whole relationship IS the distance between them. `root` keeps it:
+ # the hip mid's ground position in the same frame as `world`,
+ # starting at (0, 0) because the estimator normalises frame 0's
+ # pelvis to the origin. `incam_root` is the pelvis in CAMERA space,
+ # which is the only frame two separately-estimated performers share
+ # — that is what measures how far apart they actually stand.
+ incam_pelvis = joints_incam[i][J["pelvis"]]
rec = {"frame": i + 1, "t": i / fps, "ok": True,
"pelvis_height": round(float(-hip_mid[1]), 5),
+ "root": [round(float(hip_mid[0]), 5), round(float(hip_mid[2]), 5)],
+ "incam_root": [round(float(x), 5) for x in incam_pelvis],
"gaze": [round(float(x), 5) for x in gaze],
- "image": {}, "world": {}}
+ "image": {}, "world": {}, "incam": {}}
for n in MP_NAMES:
w = mp_world[n] - hip_mid # per-frame mid-hip centered
im = project(mp_img[n], K, wh)
rec["world"][n] = {"x": round(float(w[0]), 6), "y": round(float(w[1]), 6), "z": round(float(w[2]), 6),
"visibility": 1.0, "presence": 1.0}
+ # Camera-space landmark. `world` above is normalised into the
+ # performer's OWN frame (frame 0's facing becomes forward),
+ # which is what makes a solo retarget camera-independent — and
+ # exactly what makes two performers incomparable: each one's
+ # frame carries its own yaw, so stitching their limbs onto a
+ # shared root misplaces them by however much those yaws differ.
+ # The camera frame is the one frame both genuinely share.
+ rec["incam"][n] = {"x": round(float(mp_img[n][0]), 6),
+ "y": round(float(mp_img[n][1]), 6),
+ "z": round(float(mp_img[n][2]), 6)}
rec["image"][n] = {"x": round(float(im[0]), 6), "y": round(float(im[1]), 6), "z": 0.0,
"visibility": 1.0, "presence": 1.0}
frames.append(rec)
payload = {
"source": "gvhmr_siga24",
+ "person": args.person,
"model": str(CHECKPOINTS["gvhmr"]),
"fps": fps,
"frame_count": L,
diff --git a/pipeline/lift_to_mixamo.py b/pipeline/lift_to_mixamo.py
index e1d4fd2..671dcd2 100644
--- a/pipeline/lift_to_mixamo.py
+++ b/pipeline/lift_to_mixamo.py
@@ -95,15 +95,26 @@ LEN = {
"r_foot": 0.15722,
}
-# A character-specific rig_profile.json (written by pipeline/setup_rig.py
-# when you build the scene) overrides the built-in Y Bot measurements —
-# this is what makes the lift work with any Mixamo character's
-# proportions.
-_PROFILE = REPO / "rig_profile.json"
-if _PROFILE.exists():
- _p = json.loads(_PROFILE.read_text(encoding="utf-8"))
- REST = {k: np.array(v, dtype=float) for k, v in _p["rest"].items()}
- LEN = {k: float(v) for k, v in _p["lengths"].items()}
+def load_profile(path=None) -> Path | None:
+ """Adopt a character's measured proportions.
+
+ A rig profile (written by setup_rig.py / setup_duo.py) overrides the
+ built-in Y Bot measurements — this is what makes the lift work with
+ any Mixamo character. A multi-character scene has one profile per
+ character, named by the spec's `rig_profile`; a solo scene falls back
+ to rig_profile.json at the repo root.
+ """
+ global REST, LEN, HIP_Z
+ p = (Path(path) if Path(path).is_absolute() else REPO / path) if path else (REPO / "rig_profile.json")
+ if p.exists():
+ _p = json.loads(p.read_text(encoding="utf-8"))
+ REST = {k: np.array(v, dtype=float) for k, v in _p["rest"].items()}
+ LEN = {k: float(v) for k, v in _p["lengths"].items()}
+ HIP_Z = float(REST["hips"][2])
+ return p
+ if path:
+ raise SystemExit(f"rig profile not found: {p}")
+ return None
MP_USED = [
"nose",
@@ -146,7 +157,11 @@ def mp_to_mix(p):
return np.array([p[0], p[2], -p[1] + HIP_Z], dtype=np.float64)
-def smooth_series(arr, window=7, poly=2):
+PREFILTER = 7 # default landmark prefilter width, in SOURCE frames
+
+
+def smooth_series(arr, window=None, poly=2):
+ window = PREFILTER if window is None else window
n = arr.shape[0]
w = min(window, n if n % 2 == 1 else n - 1)
if w < 5:
@@ -164,16 +179,25 @@ def load_mp(path: Path):
times = np.zeros(len(frames))
pelvis_h = np.zeros(len(frames))
gaze = np.zeros((len(frames), 3))
+ # Ground trajectory, two independent estimates (see main()).
+ root = np.zeros((len(frames), 2))
+ incam = np.zeros((len(frames), 3))
for i, f in enumerate(frames):
times[i] = f["t"]
pelvis_h[i] = float(f.get("pelvis_height", 0.0))
g = f.get("gaze")
if g:
gaze[i] = g
+ r = f.get("root")
+ if r:
+ root[i] = r
+ ic = f.get("incam_root")
+ if ic:
+ incam[i] = ic
for n in MP_USED:
w = f["world"][n]
world[n][i] = (w["x"], w["y"], w["z"])
- return data["fps"], times, world, pelvis_h, gaze
+ return data["fps"], times, world, pelvis_h, gaze, root, incam
def resample(times, series, dst_times):
@@ -297,8 +321,15 @@ def reconstruct(mp, i):
l_foot = l_ankle + seg(mp, i, "left_ankle", "left_foot_index") * LEN["l_foot"]
r_foot = r_ankle + seg(mp, i, "right_ankle", "right_foot_index") * LEN["r_foot"]
- l_fwd = unit(np.array([*(mp["left_foot_index"][i] - mp["left_heel"][i])[:2], 0.0]))
- r_fwd = unit(np.array([*(mp["right_foot_index"][i] - mp["right_heel"][i])[:2], 0.0]))
+ # Toe direction in FULL 3D. Flattening it to the ground plane is
+ # right for a planted foot and wrong for a kicking one: it drags a
+ # foot pointed 40 deg up back to horizontal, which both lowers the
+ # toe and throws it forward into whatever the foot is aimed at. A
+ # grounded foot does not need the flattening here anyway — the FK
+ # apply re-aims any foot below 0.20 m along its own heading
+ # (`flatten_foot`), so the ground case is already handled downstream.
+ l_fwd = unit(mp["left_foot_index"][i] - mp["left_heel"][i])
+ r_fwd = unit(mp["right_foot_index"][i] - mp["right_heel"][i])
if np.linalg.norm(l_fwd) < 0.1:
l_fwd = -y
if np.linalg.norm(r_fwd) < 0.1:
@@ -339,8 +370,16 @@ def main():
ap.add_argument("--spec", required=True, type=Path)
args = ap.parse_args()
spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))
-
- fps, times, world, pelvis_h, gaze_src = load_mp(rpath(spec["landmarks"]))
+ used_profile = load_profile(spec.get("rig_profile"))
+ # Landmark prefilter width. 7 frames is right for ordinary motion and
+ # measurably expensive on a fast strike: on the duel plate's roundhouse
+ # it cost 5 deg of shin angle at the peak — the same lesson as
+ # docs/PITFALLS.md #18, one stage earlier. Narrow it for plates whose
+ # money shot is a single fast beat.
+ global PREFILTER
+ PREFILTER = int(spec.get("prefilter_window", PREFILTER))
+
+ fps, times, world, pelvis_h, gaze_src, root_src, incam_src = load_mp(rpath(spec["landmarks"]))
dst_fps = float(spec.get("dst_fps", 30))
duration = float(times[-1])
n_dst = int(round(duration * dst_fps)) + 1
@@ -369,9 +408,82 @@ def main():
for k in range(0, len(times), 5)]))
ref_scale = (LEN["l_arm"] + LEN["l_fore"]) / max(_ref_arm, 1e-6)
+ # Ground trajectory. A solo clip is retargeted in place (Mixamo
+ # convention, and the estimator's landmarks are hip-centred every
+ # frame anyway). Two fighters are a different problem: the whole
+ # scene IS the distance between them, and this plate closes from
+ # 1.95 m to 0.88 m — retargeted in place, every punch would land a
+ # metre short of the other character. `root_motion` restores the
+ # performer's real travel, scaled by LEG length so a shorter
+ # character takes proportionally shorter steps rather than
+ # over-striding into its partner.
+ root_motion = bool(spec.get("root_motion", False))
+ _ref_leg = float(np.mean([
+ np.linalg.norm(world["left_hip"][k] - world["left_knee"][k])
+ + np.linalg.norm(world["left_knee"][k] - world["left_ankle"][k])
+ for k in range(0, len(times), 5)]))
+ root_scale = float(spec.get("root_scale", (LEN["l_upleg"] + LEN["l_leg"]) / max(_ref_leg, 1e-6)))
+ # TWO estimates of where the performer stood, and they disagree:
+ #
+ # "global" the pelvis in the estimator's gravity-aligned world
+ # frame. Physically consistent, but it is a PREDICTED
+ # trajectory and it drifts — measured on the duel plate it
+ # under-reported a 0.92 m step-in as 0.68 m and left the
+ # performer 0.16 m off his mark at the closing T-pose.
+ # "incam" the pelvis in camera space, which is tied to what the
+ # camera actually saw. On the same plate it tracked an
+ # independent image-space measurement (hip pixels over
+ # body pixels) to within 2 cm across all 241 frames.
+ #
+ # So `incam` is the default wherever the estimator emits it. Only its
+ # lateral component is trusted: depth is the ill-conditioned axis of a
+ # single-camera fit, and a deep crouch pushed it 0.22 m in one frame
+ # on this very plate.
+ has_incam = bool(np.abs(incam_src).sum() > 1e-6)
+ root_source = spec.get("root_source", "incam" if has_incam else "global")
+ root = np.zeros((n_dst, 2))
+ if root_motion:
+ if root_source == "incam":
+ if not has_incam:
+ raise SystemExit("root_source 'incam' needs incam_root in landmarks.json — re-run the estimator")
+ rs = incam_src[:, [0, 2]].copy() # camera x -> stage X, camera depth -> stage Y
+ if not spec.get("root_depth", False):
+ rs[:, 1] = 0.0
+ else:
+ rs = root_src.copy()
+ if len(rs) >= 9:
+ rs = np.stack([savgol_filter(rs[:, c], 9, 2, mode="interp") for c in range(2)], axis=1)
+ root = np.stack([np.interp(dst_times, times, rs[:, c]) for c in range(2)], axis=1) * root_scale
+ root -= root[0] # the clip starts at the character's stage mark
+ # Where this character stands. Not an object transform: the FK apply
+ # aims bones in armature space, so a translated armature object would
+ # silently offset every aim target (docs/RIG.md). The stage offset is
+ # baked into the animation instead, carried by Hips like any other
+ # translation on a Mixamo rig.
+ stage = np.array([float(spec.get("stage_x", 0.0)), float(spec.get("stage_y", 0.0))])
+
def src2dest(sf):
return (sf - 1) * dst_fps / fps + 1
+ # Windowed clearance offset (spec "root_offset"): a ramped shift of
+ # this character's ground trajectory. It exists because two Mixamo
+ # characters are not two humans: their limbs and heads are thicker
+ # than the performers', so a strike the video clears by 2 cm goes
+ # THROUGH the other character. Reproducing the video exactly is then
+ # the wrong answer, and no pose correction fixes it — the clearance
+ # has to come from the stage. Ramp it in and out across frames where
+ # the character is already travelling, or a planted foot will skate.
+ for ro in spec.get("root_offset", []):
+ d = np.array([float(ro.get("dx", 0.0)), float(ro.get("dy", 0.0))])
+ ramp = ro.get("ramp_src", 8)
+ for i in range(n_dst):
+ amt = window_amount(i + 1,
+ [ro["src"][0], ro["src"][0] + ramp],
+ [ro["src"][1] - ramp, ro["src"][1]], src2dest)
+ if amt > 1e-6:
+ root[i] = root[i] + d * amt
+
+
rb = spec["rest_blend_end"]
rest = rest_pose()
@@ -534,6 +646,62 @@ def main():
v = rodrigues(v, up, a_yaw)
rec[k] = sock + v
+ # Windowed leg-chain rotation (spec "leg_pose"): rotate a whole
+ # leg rigidly about its hip socket so the foot rises (or drops) by
+ # a measured amount. The leg analogue of `arm_pose`, added for the
+ # same reason (docs/PITFALLS.md #20) — rotating a chain cannot
+ # distort it, translating its joints and re-normalising lengths
+ # does.
+ #
+ # What it is for: the estimator's gravity-aligned pose and its
+ # in-camera pose disagree about a fast limb at its peak, and the
+ # retarget follows the gravity-aligned one (it has to — that is
+ # what makes feet plant). On a head-high roundhouse that showed up
+ # as a shin ~9 deg low, dropping the foot 0.15 m and putting it
+ # through the other fighter instead of over him.
+ for lp in spec.get("leg_pose", []):
+ amt = window_amount(
+ f,
+ [lp["src"][0], lp["src"][0] + lp.get("ramp_src", 4)],
+ [lp["src"][1] - lp.get("ramp_src", 4), lp["src"][1]],
+ src2dest,
+ )
+ if amt <= 1e-4:
+ continue
+ lift = float(lp.get("lift_m", 0.0)) * amt
+ pitch = np.radians(float(lp.get("pitch_deg", 0.0))) * amt
+ if abs(lift) < 1e-4 and abs(pitch) < 1e-5:
+ continue
+ sides = ("l", "r") if lp.get("side", "both") == "both" else (lp["side"][0],)
+ for s in sides:
+ sock = np.asarray(rec[f"{s}_upleg"], float)
+ v = np.asarray(rec[f"{s}_ankle"], float) - sock
+ r = float(np.linalg.norm(v))
+ if r < 1e-4:
+ continue
+ # Raise the foot VERTICALLY whichever plane the leg swings
+ # in: the axis is the horizontal one perpendicular to the
+ # leg itself, not the character's lateral axis. A roundhouse
+ # and a front kick travel in different planes and a fixed
+ # axis would skew one of them sideways.
+ axis = np.cross(v, np.array([0.0, 0.0, 1.0]))
+ if np.linalg.norm(axis) < 1e-4:
+ continue
+ axis = unit(axis)
+ ang = pitch
+ if abs(lift) > 1e-4:
+ want = float(np.clip(v[2] + lift, -0.98 * r, 0.98 * r))
+ lo, hi = np.radians(-70.0), np.radians(70.0)
+ for _ in range(28): # monotone in this range
+ mid = 0.5 * (lo + hi)
+ if rodrigues(v, axis, mid)[2] < want:
+ lo = mid
+ else:
+ hi = mid
+ ang += 0.5 * (lo + hi)
+ for k in (f"{s}_knee", f"{s}_ankle", f"{s}_foot", f"{s}_toe"):
+ rec[k] = sock + rodrigues(np.asarray(rec[k], float) - sock, axis, ang)
+
# Windowed reach scaling (spec "reach"): push the hand further
# from the shoulder socket along its own direction and re-place
# the chain with exact bone lengths (current elbow as pole).
@@ -666,10 +834,18 @@ def main():
recs[f - 1][k] = series[j] * (1.0 - blend) + smoothed[j] * blend
# Support-ankle pinning (see module docstring).
+ #
+ # The skate this corrects is an ARTEFACT of hip-centred landmarks:
+ # with the body's travel discarded, a planted foot appears to slide
+ # backwards whenever the pelvis leans over it. When `root_motion`
+ # restores that travel the artefact is gone at the source, and
+ # re-pinning on top would fight the real trajectory — cancelling the
+ # step inside every stance and then snapping it back as the window
+ # released. QA's single-support check measures what is left.
RELEASE = 10
pos_keys = [k for k in recs[0] if not k.startswith("basis_")]
for a_src, b_src, sup in plant_windows:
- if sup not in ("left", "right"):
+ if sup not in ("left", "right") or root_motion:
continue
a = max(1, int(round(src2dest(a_src))))
b = min(n_dst, int(round(src2dest(b_src))))
@@ -688,6 +864,16 @@ def main():
recs[f - 1][k] = np.asarray(recs[f - 1][k], float)
recs[f - 1][k][:2] += fade
+ # Stage placement + ground trajectory, applied last so the rest blend
+ # still resolves to the character's exact rest pose (blending toward
+ # REST after this would drag the character back to the origin).
+ if root_motion or stage.any():
+ for i, rec in enumerate(recs):
+ delta = stage + root[i]
+ for k in pos_keys:
+ rec[k] = np.asarray(rec[k], float)
+ rec[k][:2] += delta
+
joints = []
for rec, ex in zip(recs, extras):
out = {k: [round(float(v), 5) for v in np.asarray(val)] for k, val in rec.items()}
@@ -717,6 +903,13 @@ def main():
out_path = rpath(spec["joints_out"])
out_path.write_text(json.dumps(payload), encoding="utf-8")
print("wrote", out_path, "frames", n_dst)
+ print(f"profile: {used_profile.name if used_profile else 'built-in Y Bot'} "
+ f"(hip {HIP_Z:.3f} m, arm {LEN['l_arm'] + LEN['l_fore']:.3f} m)")
+ if root_motion or stage.any():
+ print(f"stage x={stage[0]:+.3f} y={stage[1]:+.3f} | root motion "
+ f"{'ON (' + root_source + ')' if root_motion else 'off'} scale {root_scale:.3f} "
+ f"travel {np.linalg.norm(root[-1] - root[0]):.3f} m, "
+ f"max {np.abs(root).max():.3f} m")
for sfq in spec.get("qa_src_frames", []):
f = int(round(src2dest(sfq)))
diff --git a/pipeline/qa_clip.py b/pipeline/qa_clip.py
index 0d7a164..687dc8b 100644
--- a/pipeline/qa_clip.py
+++ b/pipeline/qa_clip.py
@@ -22,12 +22,21 @@ REPO = Path(__file__).resolve().parents[1]
GROUND_Z = 0.105
REST_LW = (0.7378, 1.4357)
REST_RW = (-0.7378, 1.4356)
-_PROFILE = REPO / "rig_profile.json"
-if _PROFILE.exists():
- _p = json.loads(_PROFILE.read_text(encoding="utf-8"))
+
+
+def use_profile(path=None) -> str:
+ """This character's measured rest geometry (see setup_rig.py)."""
+ global GROUND_Z, REST_LW, REST_RW
+ p = (Path(path) if Path(path).is_absolute() else REPO / path) if path else (REPO / "rig_profile.json")
+ if not p.exists():
+ if path:
+ raise SystemExit(f"rig profile not found: {p}")
+ return "built-in Y Bot"
+ _p = json.loads(p.read_text(encoding="utf-8"))
GROUND_Z = float(_p["ground_z"])
REST_LW = (_p["rest"]["l_wrist"][0], _p["rest"]["l_wrist"][2])
REST_RW = (_p["rest"]["r_wrist"][0], _p["rest"]["r_wrist"][2])
+ return p.name
def rpath(p) -> Path:
@@ -40,6 +49,7 @@ def main():
ap.add_argument("--spec", required=True, type=Path)
args = ap.parse_args()
spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))
+ print("profile:", use_profile(spec.get("rig_profile")))
clip_dir = rpath(spec["clip_dir"])
curves = json.loads((clip_dir / "curves.json").read_text(encoding="utf-8"))
frames = curves["frames"]
@@ -51,6 +61,9 @@ def main():
return np.array(frames[i]["bones"][bone]["world_location"], dtype=float)
names = list(frames[0]["bones"].keys())
+ # A staged character stands off the origin by design; widen the
+ # explosion test around its stage mark instead of around (0, 0).
+ BOUND = 2.0 + abs(float(spec.get("stage_x", 0.0))) + abs(float(spec.get("stage_y", 0.0)))
ok = True
# 1. World bounds, all bones all frames.
@@ -58,7 +71,7 @@ def main():
for i in range(n):
for b in names:
p = w(i, b)
- if abs(p[0]) > 2 or abs(p[1]) > 2 or not (-0.5 < p[2] < 3):
+ if abs(p[0]) > BOUND or abs(p[1]) > BOUND or not (-0.5 < p[2] < 3):
bad.append((i + 1, b, p.round(2).tolist()))
print(f"[{'OK' if not bad else 'FAIL'}] world bounds: {len(bad)} violations" + (f" e.g. {bad[:3]}" if bad else ""))
ok &= not bad
@@ -74,7 +87,13 @@ def main():
hy = np.array([w(i, "mixamorig:Hips")[1] for i in range(n)])
travel = float(np.hypot(hx[-1] - hx[0], hy[-1] - hy[0]))
drift = float(max(np.ptp(hx), np.ptp(hy)))
- print(f"[{'OK' if travel < 0.05 else 'WARN'}] in-place: end-to-end hip XZ travel {travel:.4f} m, max drift {drift:.3f} m")
+ if spec.get("root_motion"):
+ # This clip is meant to travel (two fighters closing distance);
+ # what would be a defect in a solo in-place clip is the point here.
+ print(f"[OK] root motion: end-to-end hip travel {travel:.4f} m, range {drift:.3f} m "
+ f"(stage x {spec.get('stage_x', 0.0):+.2f})")
+ else:
+ print(f"[{'OK' if travel < 0.05 else 'WARN'}] in-place: end-to-end hip XZ travel {travel:.4f} m, max drift {drift:.3f} m")
# 4. Support feet during plant windows.
for wnd in spec.get("plant", []):
@@ -103,6 +122,12 @@ def main():
# 5. End pose == rest.
lh, rh = w(n - 1, "mixamorig:LeftHand"), w(n - 1, "mixamorig:RightHand")
+ # Hips-relative: with root motion the character ends the clip on a
+ # different spot on the floor, and an absolute comparison would call
+ # a perfect T-pose a failure.
+ hip_end = w(n - 1, "mixamorig:Hips")
+ lh = lh - np.array([hip_end[0], hip_end[1], 0.0])
+ rh = rh - np.array([hip_end[0], hip_end[1], 0.0])
rest_err = max(abs(lh[0] - REST_LW[0]) + abs(lh[2] - REST_LW[1]), abs(rh[0] - REST_RW[0]) + abs(rh[2] - REST_RW[1]))
print(f"[{'OK' if rest_err < 0.03 else 'FAIL'}] end frame is rest: hand error {rest_err:.4f} (hips z {hz[-1]:.4f})")
ok &= rest_err < 0.03
diff --git a/pipeline/render_preview.py b/pipeline/render_preview.py
index a822505..20d8788 100644
--- a/pipeline/render_preview.py
+++ b/pipeline/render_preview.py
@@ -40,22 +40,27 @@ RENDER_SEQ = """import bpy, math
from mathutils import Vector
scene = bpy.context.scene
-# Bind the SPEC's action before rendering — the live scene holds
-# whatever action was applied last, which may be a different clip.
-arm = bpy.data.objects["Armature"]
-act = bpy.data.actions.get("{action}")
-assert act is not None, "action '{action}' not found in the scene - run the apply first"
-if arm.animation_data is None:
- arm.animation_data_create()
-arm.animation_data.action = act
-try:
- for slot in act.slots:
- arm.animation_data.action_slot = slot
- break
-except Exception:
- pass
+# Bind EVERY character's action before rendering — the live scene holds
+# whatever action was applied last, which may be a different clip, and a
+# two-character scene needs both bound or one fighter renders frozen in
+# its T-pose while the other fights it.
+end = 1
+for arm_name, act_name in {bindings}:
+ arm = bpy.data.objects[arm_name]
+ act = bpy.data.actions.get(act_name)
+ assert act is not None, "action %s not found in the scene - run the apply first" % act_name
+ if arm.animation_data is None:
+ arm.animation_data_create()
+ arm.animation_data.action = act
+ try:
+ for slot in act.slots:
+ arm.animation_data.action_slot = slot
+ break
+ except Exception:
+ pass
+ end = max(end, int(act.frame_range[1]))
scene.frame_start = 1
-scene.frame_end = int(act.frame_range[1])
+scene.frame_end = end
cam_data = bpy.data.cameras.new("QA_Camera")
cam = bpy.data.objects.new("QA_Camera", cam_data)
@@ -64,12 +69,12 @@ old = (scene.camera, scene.render.engine, scene.render.filepath,
scene.render.resolution_x, scene.render.resolution_y)
try:
scene.camera = cam
- cam.location = Vector((0.0, -4.6, 1.05))
+ cam.location = Vector(({cam_x}, {cam_y}, {cam_z}))
cam.rotation_euler = (math.radians(90), 0.0, 0.0)
scene.render.engine = "BLENDER_WORKBENCH"
scene.display.shading.light = "STUDIO"
scene.display.shading.color_type = "TEXTURE"
- scene.render.resolution_x, scene.render.resolution_y = 960, 720
+ scene.render.resolution_x, scene.render.resolution_y = {res_x}, {res_y}
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = "PNG"
scene.render.filepath = r"{outdir}" + "\\\\f####"
@@ -83,6 +88,40 @@ result = {{"frames": scene.frame_end}}
"""
+def frame_camera(specs, res_x: int, res_y: int):
+ """Pull the camera back until every character fits, every frame.
+
+ A solo clip is always framed by the same fixed camera; two fighters
+ two metres apart, one of them kicking head-high, are not. The bounds
+ come from the dumped curves (every bone, every frame), so the framing
+ is measured rather than guessed — and it holds for the whole clip
+ instead of drifting with the action.
+ """
+ lo = [1e9, 1e9]
+ hi = [-1e9, -1e9]
+ for spec in specs:
+ cpath = rpath(spec["clip_dir"]) / "curves.json"
+ if not cpath.exists():
+ continue
+ for fr in json.loads(cpath.read_text(encoding="utf-8"))["frames"]:
+ for b in fr["bones"].values():
+ x, _, z = b["world_location"]
+ lo[0], hi[0] = min(lo[0], x), max(hi[0], x)
+ lo[1], hi[1] = min(lo[1], z), max(hi[1], z)
+ if lo[0] > hi[0]:
+ return 0.0, -4.6, 1.05
+ cx, cz = 0.5 * (lo[0] + hi[0]), 0.5 * (lo[1] + hi[1])
+ half_w = 0.5 * (hi[0] - lo[0]) * 1.10 + 0.15
+ half_h = 0.5 * (hi[1] - lo[1]) * 1.10 + 0.20
+ # Blender's default 50 mm lens on a 36 mm sensor, fit to the long axis.
+ tan_h = 0.5 * 36.0 / 50.0
+ aspect = res_x / res_y
+ tan_x = tan_h if aspect >= 1.0 else tan_h * aspect
+ tan_y = tan_h / aspect if aspect >= 1.0 else tan_h
+ dist = max(half_w / tan_x, half_h / tan_y)
+ return round(cx, 4), round(-dist, 4), round(cz, 4)
+
+
def rpath(p) -> Path:
p = Path(p)
return p if p.is_absolute() else (REPO / p)
@@ -117,17 +156,39 @@ def main() -> None:
help="with --showcase: also write showcase_social.mp4, 1920x1080 letterboxed "
"(social platforms reject >1920 width / >2.39:1 aspect)")
ap.add_argument("--video", help="source plate video (default: first .mp4 next to the spec's landmarks)")
+ ap.add_argument("--also", action="append",
+ help="another action_spec whose character shares this scene (repeatable) — "
+ "renders every fighter of a multi-character plate in one pass")
+ ap.add_argument("--out-dir", help="write the videos here instead of the primary spec's clip_dir")
+ ap.add_argument("--fit-camera", action="store_true",
+ help="fit the camera to the animation instead of the fixed solo framing")
ap.add_argument("--keep-frames", action="store_true")
args = ap.parse_args()
spec = json.loads(rpath(args.spec).read_text(encoding="utf-8"))
- clip_dir = rpath(spec["clip_dir"])
+ specs = [spec] + [json.loads(rpath(q).read_text(encoding="utf-8")) for q in (args.also or [])]
+ clip_dir = rpath(args.out_dir) if args.out_dir else rpath(spec["clip_dir"])
clip_dir.mkdir(parents=True, exist_ok=True)
frames_dir = clip_dir / "preview_frames"
frames_dir.mkdir(exist_ok=True)
+ res_x, res_y = ((1280, 720) if len(specs) > 1 else (960, 720))
+ # Solo clips keep the fixed camera they were always shot with — the
+ # published showcases were framed by it and auto-fitting would
+ # silently reframe them. Multi-character scenes have no single right
+ # answer, so they are fitted from the dumped curves.
+ if len(specs) > 1 or args.fit_camera:
+ cam_x, cam_y, cam_z = frame_camera(specs, res_x, res_y)
+ else:
+ cam_x, cam_y, cam_z = 0.0, -4.6, 1.05
+ bindings = [(sp.get("armature", "Armature"), sp["action_name"]) for sp in specs]
+ print(f"camera ({cam_x}, {cam_y}, {cam_z}) {res_x}x{res_y} | " +
+ ", ".join(f"{a} <- {b}" for a, b in bindings))
+
# 1. PNG sequence from the live Blender.
- code = RENDER_SEQ.format(outdir=str(frames_dir), action=spec["action_name"])
+ code = RENDER_SEQ.format(outdir=str(frames_dir), bindings=repr(bindings),
+ cam_x=cam_x, cam_y=cam_y, cam_z=cam_z,
+ res_x=res_x, res_y=res_y)
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:
f.write(code)
tmp = f.name
@@ -144,7 +205,7 @@ def main() -> None:
# 2. preview.mp4
dst_fps = int(spec.get("dst_fps", 30))
- encode(files, clip_dir / "preview.mp4", dst_fps, 960, 720,
+ encode(files, clip_dir / "preview.mp4", dst_fps, res_x, res_y,
lambda i, f: np.asarray(Image.open(f).convert("RGB")))
print("wrote", clip_dir / "preview.mp4", f"({len(files)} frames)")
@@ -167,23 +228,25 @@ def main() -> None:
src.append(img)
cap.release()
sh, sw = src[0].shape[:2]
- scale = 720.0 / sh
- sw = int(sw * scale)
- W = sw + 4 + 960
+ scale = float(res_y) / sh
+ # h.264 rejects odd dimensions; the plate's width rarely scales to
+ # an even number on its own.
+ sw = int(sw * scale) // 2 * 2
+ W = sw + 4 + res_x
def make(i, f):
si = min(len(src) - 1, int(round(i / dst_fps * src_fps)))
- left = label(cv2.resize(src[si], (sw, 720)), "SOURCE")
+ left = label(cv2.resize(src[si], (sw, res_y)), "SOURCE")
right = label(cv2.imread(str(f)), "MIXAMO RETARGET")
- canvas = np.hstack([left, np.full((720, 4, 3), 40, np.uint8), right])
+ canvas = np.hstack([left, np.full((res_y, 4, 3), 40, np.uint8), right])
return cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
- encode(files, clip_dir / "showcase.mp4", dst_fps, W, 720, make)
+ encode(files, clip_dir / "showcase.mp4", dst_fps, W, res_y, make)
print("wrote", clip_dir / "showcase.mp4", f"(source: {video.name})")
if args.social:
# 16:9 letterboxed variant within platform limits.
- sh2 = int(round(720 * 1920 / W))
+ sh2 = int(round(res_y * 1920 / W))
def make_social(i, f):
content = cv2.resize(
diff --git a/pipeline/run_in_blender.py b/pipeline/run_in_blender.py
index a72bc33..b3fabaa 100644
--- a/pipeline/run_in_blender.py
+++ b/pipeline/run_in_blender.py
@@ -40,9 +40,10 @@ BODIES = {
'result = {{"action": r["action"], "frames": r["frames"], "constraints": r["constraints"]}}',
"curves": 'result = apply_mixamo_fk.dump_curves("{spec}")',
"stills": 'result = apply_mixamo_fk.run_stills_render("{spec}", {frames})',
+ "contact": 'result = apply_mixamo_fk.pair_mesh_contact("{spec}", "{other}")',
}
-TIMEOUTS = {"apply": 600.0, "curves": 400.0, "stills": 400.0}
+TIMEOUTS = {"apply": 600.0, "curves": 400.0, "stills": 400.0, "contact": 1800.0}
def dest_frames_from_spec(spec: dict) -> list[int]:
@@ -52,8 +53,9 @@ def dest_frames_from_spec(spec: dict) -> list[int]:
for sf in spec.get("qa_src_frames", [1])})
-def run_stage(stage: str, spec_path: str, frames: list[int]) -> None:
- body = BODIES[stage].format(spec=spec_path.replace("\\", "/"), frames=frames)
+def run_stage(stage: str, spec_path: str, frames: list[int], other: str = "") -> None:
+ body = BODIES[stage].format(spec=spec_path.replace("\\", "/"), frames=frames,
+ other=other.replace("\\", "/"))
code = TEMPLATE.format(pipeline=PIPELINE, body=body)
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:
f.write(code)
@@ -70,18 +72,21 @@ def run_stage(stage: str, spec_path: str, frames: list[int]) -> None:
def main() -> None:
ap = argparse.ArgumentParser()
- ap.add_argument("stage", choices=["apply", "curves", "stills", "all"])
+ ap.add_argument("stage", choices=["apply", "curves", "stills", "contact", "all"])
ap.add_argument("spec")
ap.add_argument("--frames", help="comma-separated dest frames for stills (default: spec qa frames)")
+ ap.add_argument("--with", dest="other", help="second character's spec, for the `contact` stage")
args = ap.parse_args()
spec_path = args.spec
spec = json.loads((Path(spec_path) if Path(spec_path).is_absolute() else REPO / spec_path).read_text(encoding="utf-8"))
frames = ([int(x) for x in args.frames.split(",")] if args.frames else dest_frames_from_spec(spec))
+ if args.stage == "contact" and not args.other:
+ raise SystemExit("contact needs a second character: --with action_specs/<other>.json")
stages = ["apply", "curves", "stills"] if args.stage == "all" else [args.stage]
for s in stages:
- run_stage(s, spec_path, frames)
+ run_stage(s, spec_path, frames, args.other or "")
if __name__ == "__main__":
diff --git a/pipeline/setup_duo.py b/pipeline/setup_duo.py
new file mode 100644
index 0000000..f432fa8
--- /dev/null
+++ b/pipeline/setup_duo.py
@@ -0,0 +1,144 @@
+"""Build a multi-character rest scene — two (or more) Mixamo characters
+in one Blender file, each with its own measured rig profile.
+
+ "C:\\Program Files\\Blender Foundation\\Blender 5.1\\blender.exe" ^
+ --background --python pipeline\\setup_duo.py -- ^
+ --char YBot=ybot.fbx --char Ninja=ninja_rest.blend ^
+ --out duel_rest.blend
+
+Each `--char Name=source` takes a Mixamo FBX (imported) or an existing
+rest .blend built by setup_rig.py (appended). Every character gets:
+
+ - its armature renamed `Armature_<Name>` (bone names untouched — the
+ pipeline's whole contract is that they stay `mixamorig:*`)
+ - its own `rig_profiles/<name>.json`, so the lift/apply/QA use THAT
+ character's proportions rather than one global profile
+
+**Both armature objects stay at the origin with identity transforms.**
+Stage placement (who stands where) is not an object transform: it is
+baked into the animation by the lift's `stage_x`, exactly like the root
+trajectory. Keeping the objects at the origin is what lets the FK apply
+go on aiming bones in armature space with no offset bookkeeping — the
+one place this rig punishes mistakes (docs/RIG.md).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+
+import bpy
+
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from setup_rig import dump_rig_profile # noqa: E402
+
+
+def load_character(source: Path) -> list:
+ """Import an FBX or append every object from a rest .blend."""
+ before = set(bpy.data.objects)
+ if source.suffix.lower() == ".fbx":
+ bpy.ops.import_scene.fbx(filepath=str(source))
+ elif source.suffix.lower() == ".blend":
+ with bpy.data.libraries.load(str(source), link=False) as (src, dst):
+ dst.objects = list(src.objects)
+ for obj in dst.objects:
+ if obj is not None:
+ bpy.context.scene.collection.objects.link(obj)
+ else:
+ raise SystemExit(f"unsupported character source: {source}")
+ return [o for o in bpy.data.objects if o not in before]
+
+
+def validate(arm, name: str) -> None:
+ errors = []
+ if abs(arm.rotation_euler[0] - math.pi / 2) > 1e-3:
+ errors.append(f"armature X rotation {math.degrees(arm.rotation_euler[0]):.1f} deg, expected 90")
+ if abs(arm.scale[0] - 0.01) > 1e-5:
+ errors.append(f"armature scale {arm.scale[0]}, expected 0.01")
+ if "mixamorig:Hips" not in arm.pose.bones:
+ errors.append("mixamorig:Hips missing (never strip the mixamorig: prefix)")
+ bad = [b.name for b in arm.pose.bones if not b.name.startswith("mixamorig:")]
+ if bad:
+ errors.append(f"non-mixamorig bones: {bad[:5]}")
+ if errors:
+ raise SystemExit(f"character '{name}' does not match Mixamo conventions:\n " + "\n ".join(errors))
+ if len(arm.pose.bones) != 65:
+ print(f"WARNING: {name} has {len(arm.pose.bones)} pose bones (standard is 65)")
+
+
+def main() -> None:
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--char", action="append", required=True,
+ help="Name=source.fbx or Name=rest.blend (repeat per character)")
+ ap.add_argument("--out", default="duel_rest.blend")
+ ap.add_argument("--profile-dir", default="rig_profiles")
+ args = ap.parse_args(argv)
+
+ def rp(p) -> Path:
+ p = Path(p)
+ return p if p.is_absolute() else REPO / p
+
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ scene = bpy.context.scene
+ scene.render.fps = 30
+ scene.frame_start = 1
+
+ profile_dir = rp(args.profile_dir)
+ profile_dir.mkdir(parents=True, exist_ok=True)
+ summary = {}
+
+ for entry in args.char:
+ if "=" not in entry:
+ raise SystemExit(f"--char expects Name=source, got {entry!r}")
+ name, source = entry.split("=", 1)
+ src = rp(source)
+ if not src.exists():
+ raise SystemExit(f"character source not found: {src}")
+
+ created = load_character(src)
+ arms = [o for o in created if o.type == "ARMATURE"]
+ if len(arms) != 1:
+ raise SystemExit(f"expected exactly one armature in {src.name}, found {len(arms)}")
+ arm = arms[0]
+ validate(arm, name)
+
+ arm.name = f"Armature_{name}"
+ arm.location = (0.0, 0.0, 0.0)
+ for obj in created:
+ if obj.type == "MESH":
+ obj.name = f"{name}_{obj.name.split('_', 1)[-1] if obj.name.startswith(name) else obj.name}"
+ # Drop anything that is not the armature or its meshes: the scene
+ # must stay renderable by the pipeline's temporary-camera path.
+ for obj in created:
+ if obj.type not in ("ARMATURE", "MESH"):
+ bpy.data.objects.remove(obj)
+
+ bpy.context.view_layer.update()
+ profile_path = profile_dir / f"{name.lower()}.json"
+ profile = dump_rig_profile(arm, profile_path)
+ summary[name] = {
+ "armature": arm.name,
+ "profile": str(profile_path.relative_to(REPO)).replace("\\", "/"),
+ "hip_height": profile["hip_height"],
+ "ground_z": profile["ground_z"],
+ "arm_reach": round(profile["lengths"]["l_arm"] + profile["lengths"]["l_fore"], 4),
+ "leg_length": round(profile["lengths"]["l_upleg"] + profile["lengths"]["l_leg"], 4),
+ "meshes": profile["character"],
+ }
+ print(f"{name}: {arm.name}, hip {profile['hip_height']:.3f} m, "
+ f"arm {summary[name]['arm_reach']:.3f} m, leg {summary[name]['leg_length']:.3f} m")
+
+ out = rp(args.out)
+ bpy.ops.wm.save_as_mainfile(filepath=str(out))
+ (profile_dir / "_scene.json").write_text(json.dumps(summary, indent=1), encoding="utf-8")
+ print(f"saved {out} with {len(summary)} characters: {', '.join(summary)}")
+
+
+if __name__ == "__main__":
+ main()