Skip to content

[SIGGRAPH Asia 2026] UniMate: One Unified Model to Animate Diverse Skeletons

Python

Add standalone asset preprocessing and manual LBS animation

Friedrich-M8154d8cabd9d
diff --git a/data_process/README.md b/data_process/README.md
index c2dfeda..3c31601 100644
--- a/data_process/README.md
+++ b/data_process/README.md
@@ -73,7 +73,7 @@ flowchart LR
| 2b. Caption | `run_caption_motion.sh`, `run_caption_category.sh` | multi-view renders | `motion_captions.json`, `category_groups.json` |
| 3. Joints | `run_joints_*.sh` | `joint_names.json` | `clean_joint_names.json`, `face_joint_names.json` |
| 4. Extract | `run_extract_features.sh` | export NPZs + stage-2/3 JSONs | per-clip NPZs, `cond.npy`, `captions.json` |
-| 5. Animate | `run_animate_{motion,npz,fbx,mixamo}.sh` | motion clip + rigged mesh | animated `.glb` / `.fbx` |
+| 5. Animate | `run_animate_{motion,npz,fbx,mixamo,lbs}.sh`, `run_preprocess_char.sh` | motion clip + rigged mesh | animated `.glb` / `.fbx` |
Stage 4 reads the caption and joint-annotation JSONs from the export directory, so stages 2 and 3 must run first.
@@ -105,7 +105,8 @@ data_process/
├── vlm_caption/ Stage 2b multi-view renders → captions / body-plan categories (VLM)
├── joint_annotation/ Stage 3 joint-name cleanup + facing-direction joint selection
├── feature_extraction/ Stage 4 NPZ + metadata → canonical training clips + cond.npy
-├── mesh_animation/ Stage 5 motion clip + rigged mesh → animated GLB/FBX (Blender)
+├── mesh_animation/ Stage 5 motion clip + rigged mesh → animated GLB/FBX (Blender);
+│ single-asset preprocessing + manual NumPy FK/LBS
├── tools/ Standalone utilities (summary merging, FBX→GLB, QA visualizers)
└── utils/ Shared library code (no entry points)
```
@@ -254,7 +255,7 @@ bash data_process/scripts/run_joints_names_correct_llm.sh objaverse # re-chec
bash data_process/scripts/run_joints_face_correct_llm.sh objaverse # retry rigs whose facing pair came back "empty"
```
-`names_correct_llm` sends each `{raw, current}` label pair back to the LLM to keep or fix (most useful for rigs that fell back to the rules — restrict with `FAILED_LIST=.../failed_clean_names.txt`); `face_correct_llm` re-attempts only `source == "empty"` entries. Both edit in place and create a `.bak` sibling on first run.
+`names_correct_llm` sends each `{raw, current}` label pair back to the LLM to keep or fix (most useful for rigs that fell back to the rules — restrict with `FAILED_LIST=.../failed_clean_names.txt`; long rigs are chunked with the full rig attached as read-only context). `face_correct_llm` re-attempts only `source == "empty"` entries by default; pass `--force_reattempt` to also retry the rule-fallback rigs recorded in `failed_face_joints.txt` — the correction pass re-derives from scratch (no rule hint, higher reasoning budget) and only a clean non-empty LLM win replaces an existing entry. Both edit in place and create a `.bak` sibling on first run.
Pure rule-based variants exist as `run_joints_names_clean_rule.sh` / `run_joints_face_select_rule.sh` (no API needed — useful offline or as a fast first pass). The QA visualizers behind this stage live in `data_process/tools/`: `run_joints_vis_tpose.sh` renders annotated T-pose PNGs (`tools/vis_tpose.py`), and to sanity-check a picked pair on an actual clip, `python -m data_process.tools.vis_motion <motion.npz> --direction face --face-joints I J` renders an MP4 with the implied heading arrow.
@@ -300,6 +301,27 @@ CHAR_PATH=dataset/raw/mixamo/character_refined/Amy.fbx \
The character is auto-resolved for truebones / objaverse. For mixamo it defaults to `character_refined/Y_Bot.fbx` — the character whose skeleton the animation FBXs are authored on (identical 65-bone rig, so no bone reconciliation is needed); override with `CHAR_PATH` to use a different character. Armature bones absent from the motion are handled by `--extra_bones_strategy` (`merge` weights into the nearest kept ancestor, `remove` bones and their vertices, or `keep` them un-keyed).
+#### Standalone assets: preprocess once, animate cond-free
+
+For a single user-provided rigged asset, `run_preprocess_char.sh` runs the export + extraction stages in-process and bakes the result into a self-contained canonical asset:
+
+```bash
+CHAR_PATH=asset.glb OUTPUT_DIR=outputs/asset \
+ FACE_R=R_Thigh FACE_L=L_Thigh FORMATS=glb,fbx \
+ bash data_process/scripts/run_preprocess_char.sh
+```
+
+This leaves exactly three deliverables: `<name>_canonical.{glb,fbx}` (rest-pose asset rebuilt to the canonical T-pose — no animation, canonical joint order stored as a custom property), `cond.npy` (the model-side topology conditioning), and `motions/<clip>.npz` (one motion-feature NPZ per action). Assets **without** any action fall back to a rest-only cond (full skeleton — the export stage's motion-driven pruning needs animations — and no `motions/`).
+
+A feature-format motion NPZ — generated by the model or extracted above — then drives the canonical asset directly, with no `cond.npy` or export NPZ at animate time:
+
+```bash
+CHAR_PATH=outputs/asset/<name>_canonical.glb ANIM_PATH=<motion.npz-or-directory> \
+ bash data_process/scripts/run_animate_lbs.sh # one animated GLB per action
+```
+
+`animate_lbs` computes FK and Linear Blend Skinning manually in NumPy (Blender only parses the asset; the math is numerically identical to Blender's armature modifier) and exports the animated rigged GLB/FBX through the same path as `animate_npz`; `SAVE=npz,obj` additionally dumps raw deformed vertex sequences / per-frame OBJs. It also accepts stage-1 export NPZs and, with `DATASET_TYPE`/`COND_PATH`, cond-resolved feature NPZs on non-preprocessed assets.
+
## Data Formats
**Stage-1 export NPZ** (`dataset/export/<dataset>/motions/*.npz`) — one file per clip:
diff --git a/data_process/joint_annotation/face_correct_llm.py b/data_process/joint_annotation/face_correct_llm.py
index d31d328..70d78e0 100644
--- a/data_process/joint_annotation/face_correct_llm.py
+++ b/data_process/joint_annotation/face_correct_llm.py
@@ -1,15 +1,26 @@
-"""Re-run LLM face-joint selection on rigs whose ``source == "empty"``.
+"""Re-run LLM face-joint selection on rigs the first pass got wrong.
:mod:`face_select_llm` writes the empty sentinel
``{r_hip: {raw:"", clean:""}, l_hip: {raw:"", clean:""}, source: "empty"}``
whenever neither the rule-based hint nor the LLM finds a bilateral pair or
-a head/tail body axis. This script re-attempts those rigs only (by default
-every ``source == "empty"`` entry in ``--face``; optionally a subset listed
-in ``--failed_list``) and, when the LLM now finds a valid pair, overwrites
-the entry in place. Rigs that still fail keep their existing empty entry.
+a head/tail body axis. This script re-attempts those rigs (by default every
+``source == "empty"`` entry in ``--face``; optionally a subset listed in
+``--failed_list``) and, when the LLM now finds a valid pair, overwrites the
+entry in place. Rigs that still fail keep their existing entry.
-A ``.bak`` sibling of ``--face`` is created on first run. Rigs that remain
-empty are written to ``still_empty_face_joints.txt``.
+Unlike a plain re-run, this pass actually changes the odds: it uses a
+correction system prompt (re-derive from scratch, 'empty' only as a last
+resort), OMITS the rule-based hint that anchored the first pass, and
+defaults to a larger token/reasoning/timeout budget. Pair it with a
+stronger ``--model`` for best effect.
+
+NOTE on ``--failed_list``: ``failed_face_joints.txt`` records rigs that
+fell back to the RULE-BASED resolver — most of their entries are non-empty,
+so by default they are skipped. Pass ``--force_reattempt`` to re-attempt
+them; only a clean non-empty LLM win replaces an existing entry.
+
+A ``.bak`` sibling of ``--face`` is created on first run. Rigs that were
+empty and remain empty are appended to ``still_empty_face_joints.txt``.
Usage:
python -m data_process.joint_annotation.face_correct_llm \\
@@ -45,6 +56,39 @@ from data_process.joint_annotation.llm import ( # noqa: E402
)
+# ─────────────────────────────────────────────────────────────────────────────
+# Correction-mode system prompt addendum
+# ─────────────────────────────────────────────────────────────────────────────
+#
+# Re-running the selection prompt verbatim on a rig it already got wrong
+# mostly reproduces the same answer. This pass therefore (a) appends the
+# preamble below and (b) omits the rule-based hint from the user prompt
+# (resolve_rig include_hint=False) — the hint IS the failed answer.
+
+CORRECTION_PREAMBLE = (
+ "=========================================================================\n"
+ "CORRECTION PASS — A PREVIOUS RUN FAILED ON THIS RIG.\n"
+ "=========================================================================\n"
+ "An earlier pass could not produce a confident answer for this rig: it "
+ "returned the 'empty' sentinel, or silently fell back to the "
+ "deterministic resolver. No rule-based hint is shown in this pass — "
+ "re-derive the answer from scratch by executing the ALGORITHM above, "
+ "with extra care:\n"
+ " - STEP 1: compare suffixes AFTER stripping the side prefix AND any "
+ "trailing ' <digits>' — 'Right Thigh 1' / 'Left Thigh 2' DO overlap "
+ "(suffix 'Thigh'). Digits and chain position never break a pair.\n"
+ " - STEP 3: HEAD/TAIL rows also match ignoring trailing ' <digits>' "
+ "('Tail 30' is a valid TAIL endpoint).\n"
+ " - Return 'empty' ONLY when, after honestly executing steps 1-3, "
+ "OVERLAP is empty AND no HEAD+TAIL axis exists. Vehicles, props and "
+ "abstract rigs are legitimately empty; anything with mirrored limbs, "
+ "fins, wings or a head-to-tail chain is not.\n"
+ "The OUTPUT contract, PRIORITY order and INVARIANTS above are unchanged."
+)
+
+CORRECTION_SYSTEM_PROMPT = SYSTEM_PROMPT + "\n\n" + CORRECTION_PREAMBLE
+
+
# ─────────────────────────────────────────────────────────────────────────────
# Entry classification
# ─────────────────────────────────────────────────────────────────────────────
@@ -83,16 +127,19 @@ def is_empty_entry(entry):
# Driver
# ─────────────────────────────────────────────────────────────────────────────
-def correct_all(raw_path, clean_path, face_path, client, system_prompt=SYSTEM_PROMPT,
- failed_list_path=None, max_tokens=512, max_retries=MAX_RETRIES,
- timeout_seconds=15, still_empty_path=None, only_if_currently_empty=True):
+def correct_all(raw_path, clean_path, face_path, client,
+ system_prompt=CORRECTION_SYSTEM_PROMPT,
+ failed_list_path=None, max_tokens=2048, max_retries=MAX_RETRIES,
+ timeout_seconds=60, still_empty_path=None, only_if_currently_empty=True):
# type: (...) -> Dict[str, Dict]
"""Re-run LLM face-joint selection and write results back IN-PLACE to
``face_path``.
Targets every ``source == "empty"`` rig in ``face_path``, or only the
ids in ``failed_list_path`` when given. Rigs where the LLM fails or
- still returns an empty entry are left untouched.
+ still returns an empty entry are left untouched. The LLM runs with the
+ correction system prompt and WITHOUT the rule-based hint (the hint is
+ the very answer that already failed).
A missing ``failed_list_path`` is a hard error: a typo must not silently
escalate a targeted repair into a full sweep.
@@ -126,7 +173,7 @@ def correct_all(raw_path, clean_path, face_path, client, system_prompt=SYSTEM_PR
logger.info("Re-attempting {} (in-place update of {})".format(scope_desc, face_path))
- updated = skipped_not_empty = missing = 0
+ updated = skipped_not_empty = missing = kept_existing = 0
still_empty = [] # type: List[str]
pbar = tqdm(target_ids, desc="Correcting", unit="rig", dynamic_ncols=True)
for rig_id in pbar:
@@ -138,7 +185,8 @@ def correct_all(raw_path, clean_path, face_path, client, system_prompt=SYSTEM_PR
continue
# The failed list may be stale: only touch entries still empty now.
- if only_if_currently_empty and not is_empty_entry(face_data.get(rig_id)):
+ was_empty = is_empty_entry(face_data.get(rig_id))
+ if only_if_currently_empty and not was_empty:
skipped_not_empty += 1
continue
@@ -147,22 +195,27 @@ def correct_all(raw_path, clean_path, face_path, client, system_prompt=SYSTEM_PR
rig_id, raw_data[rig_id], clean_data[rig_id], client,
system_prompt=system_prompt, max_tokens=max_tokens,
max_retries=max_retries, timeout_seconds=timeout_seconds,
- fallback_on_error=False,
+ fallback_on_error=False, include_hint=False,
)
- except Exception as err: # noqa: BLE001 — exhausted retries: keep the empty entry
+ except Exception as err: # noqa: BLE001 — exhausted retries: keep the entry
logger.warning("[{}] LLM resolve failed: {}".format(rig_id, err))
entry, used_fallback = None, True
# Accept only clean non-empty LLM wins. used_fallback=True means the
- # rule-based hint came back on timeout — the same hint that already
- # produced the empty entry.
+ # rule-based hint came back on timeout — the same answer that already
+ # failed the first pass.
if entry is not None and not used_fallback and is_non_empty_entry(entry):
face_data[rig_id] = entry
updated += 1
- else:
+ # Save on update only: an unchanged entry doesn't warrant
+ # rewriting the whole (MB-sized) JSON on shared storage.
+ save_json(face_data, face_path)
+ elif was_empty:
still_empty.append(rig_id)
-
- save_json(face_data, face_path)
+ else:
+ # --force_reattempt on a non-empty (rule-fallback) entry that the
+ # LLM couldn't beat: keep it, but don't log it as "still empty".
+ kept_existing += 1
# Append (like every other id log in this stage) rather than truncate: a
# --failed_list run only sees a subset, and a truncating write would
@@ -181,10 +234,20 @@ def correct_all(raw_path, clean_path, face_path, client, system_prompt=SYSTEM_PR
"from earlier runs — it may be stale.".format(
still_empty_path, len(known_empty)))
+ if (failed_list_path and only_if_currently_empty and target_ids
+ and skipped_not_empty >= len(target_ids) / 2):
+ logger.warning(
+ "{}/{} listed rigs were skipped because their current entry is "
+ "not 'empty'. failed_face_joints.txt records rule-based "
+ "FALLBACKS, whose entries are usually non-empty — pass "
+ "--force_reattempt to re-attempt them.".format(
+ skipped_not_empty, len(target_ids)))
+
logger.info(
- "Done. updated={} | still_empty={} | skipped_not_empty={} | "
- "missing_raw_or_clean={} | total={}".format(
- updated, len(still_empty), skipped_not_empty, missing, len(target_ids)))
+ "Done. updated={} | still_empty={} | kept_existing={} | "
+ "skipped_not_empty={} | missing_raw_or_clean={} | total={}".format(
+ updated, len(still_empty), kept_existing, skipped_not_empty,
+ missing, len(target_ids)))
return face_data
@@ -203,19 +266,31 @@ def main():
"is made on first run.")
parser.add_argument("--failed_list", default=None,
help="Optional txt file with one rig id per line. Default: every "
- "rig whose entry in --face has source=='empty'.")
+ "rig whose entry in --face has source=='empty'. NOTE: "
+ "failed_face_joints.txt lists rule-based FALLBACKS, whose "
+ "entries are usually non-empty — combine with "
+ "--force_reattempt or they will all be skipped.")
parser.add_argument("--still_empty_log", default=None,
help="Path to write rig ids the LLM still couldn't fill (default: "
"sibling 'still_empty_face_joints.txt').")
parser.add_argument("--force_reattempt", action="store_true",
- help="Re-run even if the current entry isn't source=='empty' anymore.")
- parser.add_argument("--rig_timeout", type=int, default=15,
+ help="Re-run even if the current entry isn't source=='empty' anymore. "
+ "Existing non-empty entries are only replaced by a clean "
+ "non-empty LLM win, never by 'empty'.")
+ parser.add_argument("--rig_timeout", type=int, default=60,
help="Per-rig wall-time budget in seconds (SIGALRM). 0 disables.")
- add_llm_args(parser, default_max_tokens=512)
+ add_llm_args(parser, default_max_tokens=2048)
args = parser.parse_args()
+ if getattr(args, "reasoning_effort", None) is None:
+ # This is the try-harder pass: default one notch above the selection
+ # stage's forced-minimal effort (still overridable via the flag).
+ args.reasoning_effort = "medium"
+ logger.info("Correction pass: defaulting --reasoning_effort to 'medium'")
+
client = LLMClient.from_args(args)
- logger.info("{} | Writing in-place to: {}".format(client, args.face))
+ logger.info("{} | Correction prompt active (rule hint omitted) | "
+ "Writing in-place to: {}".format(client, args.face))
correct_all(
raw_path=args.raw,
diff --git a/data_process/joint_annotation/face_select_llm.py b/data_process/joint_annotation/face_select_llm.py
index 0d2b5d2..3eb3e60 100644
--- a/data_process/joint_annotation/face_select_llm.py
+++ b/data_process/joint_annotation/face_select_llm.py
@@ -289,10 +289,14 @@ def build_user_prompt(rig_id, candidates, rule_hint=None, correction=None):
json.dumps(rule_hint, ensure_ascii=False, indent=2),
"",
])
- sections.append(
- "Apply rules A -> B -> C and return the JSON object only. If the "
- "hint already satisfies A/B/C, return it verbatim; otherwise override."
- )
+ sections.append(
+ "Apply rules A -> B -> C and return the JSON object only. If the "
+ "hint already satisfies A/B/C, return it verbatim; otherwise override."
+ )
+ else:
+ sections.append(
+ "Apply rules A -> B -> C and return the JSON object only."
+ )
prompt = "\n".join(sections)
if correction:
prompt += "\n\nIMPORTANT: " + correction
@@ -436,7 +440,7 @@ def parse_response(text, raw_names, clean_names):
def resolve_rig(rig_id, raw_names, clean_names, client, system_prompt=SYSTEM_PROMPT,
max_tokens=512, max_retries=MAX_RETRIES, timeout_seconds=15,
- fallback_on_error=True):
+ fallback_on_error=True, include_hint=True):
# type: (...) -> Tuple[Dict, bool]
"""Pick the face-direction joint pair for one rig.
@@ -445,6 +449,11 @@ def resolve_rig(rig_id, raw_names, clean_names, client, system_prompt=SYSTEM_PRO
call. On exhausted retries or timeout the rule-based pick is returned
(or ``RuntimeError`` is raised when ``fallback_on_error`` is False and
no timeout occurred).
+
+ ``include_hint=False`` omits the rule-based hint from the prompt (it is
+ still computed for the fallback path). The correction pass uses this:
+ re-showing the very hint that already produced a wrong/empty entry
+ anchors the model on it.
"""
if not raw_names:
return empty_entry(), False
@@ -476,7 +485,8 @@ def resolve_rig(rig_id, raw_names, clean_names, client, system_prompt=SYSTEM_PRO
try:
raw_text = client.generate(
system_prompt,
- build_user_prompt(rig_id, candidates, rule_hint=rule_hint,
+ build_user_prompt(rig_id, candidates,
+ rule_hint=rule_hint if include_hint else None,
correction=correction),
max_tokens)
return parse_response(raw_text, raw_names, clean_names), False
diff --git a/data_process/joint_annotation/names_correct_llm.py b/data_process/joint_annotation/names_correct_llm.py
index 578db7b..6ccd681 100644
--- a/data_process/joint_annotation/names_correct_llm.py
+++ b/data_process/joint_annotation/names_correct_llm.py
@@ -27,6 +27,7 @@ Usage:
import argparse
import json
import os
+import re
import shutil
import sys
import time
@@ -43,6 +44,7 @@ from data_process.joint_annotation.names_clean_llm import ( # noqa: E402
parse_response,
rule_based_clean,
)
+from data_process.joint_annotation.vocab import is_canonical_label # noqa: E402
from data_process.joint_annotation.llm import ( # noqa: E402
FatalLLMError,
LLMClient,
@@ -63,7 +65,8 @@ from data_process.joint_annotation.llm import ( # noqa: E402
CORRECTION_PREAMBLE = (
"=========================================================================\n"
- "CHECK & CORRECT MODE — INPUT/OUTPUT SHAPE OVERRIDES THE ABOVE.\n"
+ "CHECK & CORRECT MODE — INPUT SHAPE OVERRIDES THE ABOVE; OUTPUT SHAPE "
+ "IS UNCHANGED.\n"
"=========================================================================\n"
"INPUT change: instead of a plain JSON array of raw names you receive a "
"JSON array of objects, one per joint:\n"
@@ -74,23 +77,36 @@ CORRECTION_PREAMBLE = (
"PROCESS EACH JOINT IN TWO STEPS.\n\n"
"STEP 1 — VALIDATE the current label against ALL cleaning rules above. "
"The label is VALID only if every check below passes:\n"
- " (a) It appears verbatim in the CANONICAL VOCABULARY (exact term, "
- "Title Case, single spaces).\n"
+ " (a) Its BASE PART appears in the CANONICAL VOCABULARY (exact term, "
+ "Title Case, single spaces). The base part is the label minus any "
+ "'Left '/'Right ' side prefix, minus any Front/Back/Middle/Rear/Inner/"
+ "Outer/Upper/Lower qualifier, minus a trailing ' End' — composed "
+ "labels like 'Left Thigh', 'Right Front Shoulder', 'Leg End', "
+ "'Inner Toe' are valid. EXCEPTION: a raw name that is ONLY digits "
+ "(optionally with a leading underscore) keeps its numeric passthrough "
+ "label unchanged ('_00' -> '_00') — rule 8.\n"
" (b) It contains NO digits, underscores, dots, or Blender '.NNN' "
- "counters — rule 1.\n"
+ "counters — rule 1 — except the rule-8 numeric passthrough in (a).\n"
" (c) It carries NO leftover namespace (mixamorig:, Mutant:, Sif:, ...) "
"or rig/Maya prefix/suffix (Bip01_, BN_, NPC_, jt_, DEF-, _jnt, _C, "
"...) — rules 2-4.\n"
- " (d) If the raw name encodes a side (L_/R_, Lt_/Rt_, Left<Word>, "
- "'Bip001 L/R ', trailing L/R on Japanese roots, F_/B_ for quadrupeds), "
- "the label starts with 'Left '/'Right ' (and includes the Front/Back "
- "marker between side and part when applicable) — rule 5.\n"
+ " (d) Sides agree with the raw name — rule 5. If the raw encodes a "
+ "side (L_/R_, Lt_/Rt_, Left<Word>, 'Bip001 L/R ', trailing L/R on "
+ "Japanese roots, F_/B_ for quadrupeds), the label starts with "
+ "'Left '/'Right ' (with the Front/Back marker between side and part "
+ "when applicable); if the raw encodes NO side, the label must NOT "
+ "start with one. A trailing .L/.R/_L/_R token OVERRIDES a stale "
+ "leading side word ('mixamorig:LeftShoulder.R' -> 'Right Shoulder').\n"
" (e) If the raw name clearly encodes a recognisable body part, the "
- "label is NOT the 'Bone'/'Appendage' fallback — rules 6-9.\n"
- " (f) Finger roots, mixamo chain bones (UpLeg/Leg/Foot → Thigh/Shin/"
- "Foot), 3ds Max Biped finger codes (Finger0*=Thumb, 1*=Index, ...), "
- "Japanese roots, and 'Hair*/Ponytail*/Cape*/Skirt*' → 'Appendage' are "
- "all resolved correctly — rules 6-7.\n\n"
+ "label is NOT the 'Bone' placeholder — rules 6-9 ('Appendage' is "
+ "correct only for humanoid accessory chains, rule 7).\n"
+ " (f) Convention-dependent names are resolved correctly: finger roots "
+ "and mixamo chain bones (UpLeg/Leg/Foot -> Thigh/Shin/Foot) — rule 6; "
+ "3ds Max Biped 0-based finger codes (Finger0*=Thumb, 1*=Index, ...) — "
+ "rule 6b; 1-based mocap segmented fingers (Finger1Metacarpal=Thumb, "
+ "..., segment words dropped) — rule 6c; animal 'Hair*/Mane*' -> 'Mane' "
+ "but humanoid accessories 'Ponytail*/Cape*/Cloth*/Skirt*' -> "
+ "'Appendage' — rule 7; Japanese roots — rule 9.\n\n"
"STEP 2 — DECIDE:\n"
" - If VALID on every check in Step 1: OUTPUT THE CURRENT LABEL "
"VERBATIM (skip — do not rewrite).\n"
@@ -124,31 +140,96 @@ CORRECTION_PREAMBLE = (
" raw='Hair_03', current='Hair' -> 'Mane' (INVALID: animal Hair->Mane)\n"
" raw='Reins_02', current='Reins' -> 'Reins' (VALID: equipment label)\n"
" raw='LegTip_R', current='Right Leg Tip' -> 'Right Leg End' (INVALID: Tip not canonical)\n"
+ " raw='_00', current='_00' -> '_00' (VALID: numeric passthrough)\n"
+ " raw='mixamorig:LeftShoulder.R',\n"
+ " current='Left Shoulder' -> 'Right Shoulder' (INVALID: .R overrides stale prefix)\n"
+ " raw='Thigh_03', current='Left Thigh' -> 'Thigh' (INVALID: raw encodes no side)\n"
)
CORRECTION_SYSTEM_PROMPT = SYSTEM_PROMPT + "\n\n" + CORRECTION_PREAMBLE
-def build_correction_prompt(rig_id, raw_names, current_labels, correction=None):
- # type: (str, List[str], List[str], Optional[str]) -> str
+def build_correction_prompt(rig_id, raw_names, current_labels, correction=None,
+ chunk_start=0, rig_raw_names=None):
+ # type: (str, List[str], List[str], Optional[str], int, Optional[List[str]]) -> str
+ """Build the user prompt for one chunk of a rig.
+
+ When ``rig_raw_names`` (the FULL rig's raw list) is longer than this
+ chunk, the prompt says so and includes it as read-only context —
+ chain-dependent decisions (mixamo mid-bone 'Leg', 6b/6c finger
+ conventions) need the neighbours a chunk boundary would otherwise
+ hide, and 'Joint count: 16' on an 80-joint rig would mislead.
+ """
pairs = [{"raw": raw, "current": current}
for raw, current in zip(raw_names, current_labels)]
+ header = ["Rig identifier: {}".format(rig_id)]
+ if rig_raw_names is not None and len(rig_raw_names) > len(raw_names):
+ header.append("Rig joint count: {}".format(len(rig_raw_names)))
+ header.append(
+ "This request covers joints {}..{} (0-based) — a consecutive "
+ "slice of the rig, not the whole rig.".format(
+ chunk_start, chunk_start + len(raw_names) - 1))
+ header.append(
+ "Full rig raw joint list (READ-ONLY context for chain/side "
+ "decisions; do NOT emit labels for it):\n{}".format(
+ json.dumps(rig_raw_names, ensure_ascii=False)))
+ else:
+ header.append("Joint count: {}".format(len(raw_names)))
prompt = (
- "Rig identifier: {rig}\n"
- "Joint count: {n}\n\n"
+ "{header}\n\n"
"Joints (JSON array of {{raw, current}} objects, order matters):\n"
"{pairs}\n\n"
"For each joint: validate the 'current' label against the cleaning "
"rules. If VALID, output it verbatim; if INVALID, output a corrected "
"canonical label. Return a FLAT JSON array of EXACTLY {n} STRINGS, "
"same order as the input. Do NOT output objects; strings only."
- ).format(rig=rig_id, n=len(raw_names),
+ ).format(header="\n".join(header), n=len(raw_names),
pairs=json.dumps(pairs, ensure_ascii=False, indent=2))
if correction:
prompt += "\n\nIMPORTANT: " + correction
return prompt
+# ─────────────────────────────────────────────────────────────────────────────
+# Vocabulary check on LLM output (warn-only)
+# ─────────────────────────────────────────────────────────────────────────────
+
+_SIDE_RE = re.compile(r'^(Left|Right)\s+')
+_QUALIFIER_RE = re.compile(
+ r'^(Front|Back|Middle|Rear|Hind|Inner|Outer|Upper|Lower)\s+')
+
+
+def _is_vocab_label(label):
+ # type: (str) -> bool
+ """``vocab.is_canonical_label`` extended over composed qualifier forms
+ the cleaners emit ('Right Front Shoulder', 'Back Hip') whose bare part
+ is not itself a vocabulary value."""
+ if is_canonical_label(label):
+ return True
+ base = _SIDE_RE.sub('', label)
+ base = re.sub(r'\s+End$', '', base)
+ stripped = _QUALIFIER_RE.sub('', base)
+ return stripped != base and is_canonical_label(stripped)
+
+
+def _warn_non_canonical(rig_id, chunk_tag, chunk_raw, labels):
+ # type: (str, str, List[str], List[str]) -> None
+ """Warn-only guard: flag LLM outputs outside the canonical vocabulary.
+
+ Deliberately not a hard retry — ``canonical_parts`` under-covers a few
+ legitimate composed labels, and a false reject would burn retries on a
+ correct answer. The warning makes vocabulary drift visible in the log
+ before it lands in clean_joint_names.json."""
+ bad = [(raw, lbl) for raw, lbl in zip(chunk_raw, labels)
+ if not _is_vocab_label(lbl)]
+ if bad:
+ shown = ", ".join("{!r}->{!r}".format(r, l) for r, l in bad[:5])
+ logger.warning("[{}{}] {} label(s) outside the canonical vocabulary "
+ "(kept as-is): {}{}".format(
+ rig_id, chunk_tag, len(bad), shown,
+ ", ..." if len(bad) > 5 else ""))
+
+
# ─────────────────────────────────────────────────────────────────────────────
# Per-chunk + per-rig corrector (with retry + keep-rule-based fallback)
# ─────────────────────────────────────────────────────────────────────────────
@@ -161,7 +242,8 @@ def build_correction_prompt(rig_id, raw_names, current_labels, correction=None):
# already-corrected chunks and leaves the rest as rule-based.
def _run_chunk(rig_id, chunk_raw, chunk_current, client, system_prompt,
- max_tokens, max_retries, chunk_tag=""):
+ max_tokens, max_retries, chunk_tag="", chunk_start=0,
+ rig_raw_names=None):
# type: (...) -> Optional[List[str]]
"""Retry loop for a single chunk. Returns the parsed list on success, or
``None`` after exhausting retries. Lets ``RigTimeout`` propagate so the
@@ -171,9 +253,12 @@ def _run_chunk(rig_id, chunk_raw, chunk_current, client, system_prompt,
for attempt in range(1, max_retries + 1):
try:
user_prompt = build_correction_prompt(
- rig_id, chunk_raw, chunk_current, correction=correction)
+ rig_id, chunk_raw, chunk_current, correction=correction,
+ chunk_start=chunk_start, rig_raw_names=rig_raw_names)
raw_text = client.generate(system_prompt, user_prompt, max_tokens)
- return parse_response(raw_text, len(chunk_raw))
+ parsed = parse_response(raw_text, len(chunk_raw))
+ _warn_non_canonical(rig_id, chunk_tag, chunk_raw, parsed)
+ return parsed
except (RigTimeout, FatalLLMError):
raise
except Exception as err: # noqa: BLE001 — retry on any backend/parse error
@@ -201,8 +286,10 @@ def correct_rig(rig_id, raw_names, current_labels, client,
Rigs longer than ``chunk_size`` are split into consecutive chunks; each
chunk is an independent LLM call with its own retries. ``timeout_seconds``
- is the total SIGALRM budget for the whole rig; successfully-corrected
- chunks stay corrected even if a later chunk times out.
+ is the PER-CHUNK share of the rig's SIGALRM budget (total = it times the
+ chunk count — a flat per-rig budget starves long rigs, whose later
+ chunks would never run); successfully-corrected chunks stay corrected
+ even if a later chunk times out.
"""
if not raw_names:
return [], False
@@ -214,7 +301,8 @@ def correct_rig(rig_id, raw_names, current_labels, client,
failed_chunks = 0
timed_out = False
- prev_handler = install_rig_alarm(timeout_seconds)
+ budget = timeout_seconds * n_chunks if timeout_seconds else 0
+ prev_handler = install_rig_alarm(budget)
try:
for i in range(n_chunks):
start = i * chunk_size
@@ -223,7 +311,8 @@ def correct_rig(rig_id, raw_names, current_labels, client,
if n_chunks > 1 else "")
chunk_out = _run_chunk(
rig_id, raw_names[start:end], current_labels[start:end],
- client, system_prompt, max_tokens, max_retries, chunk_tag=chunk_tag)
+ client, system_prompt, max_tokens, max_retries,
+ chunk_tag=chunk_tag, chunk_start=start, rig_raw_names=raw_names)
if chunk_out is not None:
result[start:end] = chunk_out
else:
@@ -235,7 +324,7 @@ def correct_rig(rig_id, raw_names, current_labels, client,
if timed_out:
logger.warning("[{}] exceeded {}s budget; keeping current labels for "
- "unfinished chunks".format(rig_id, timeout_seconds))
+ "unfinished chunks".format(rig_id, budget))
elif failed_chunks:
logger.warning("[{}] {}/{} chunks still failed; keeping current labels "
"for those".format(rig_id, failed_chunks, n_chunks))
@@ -329,9 +418,14 @@ def correct_all(raw_path, cleaned_path, client, system_prompt=CORRECTION_SYSTEM_
save_json(cleaned_data, cleaned_path)
if still_failed:
- append_id_list(still_failed_path, still_failed)
- logger.info("{} rigs still failed; appended to {}".format(
- len(still_failed), still_failed_path))
+ # Dedup against earlier runs (same convention as face_correct_llm).
+ known = (set(read_id_list(still_failed_path))
+ if os.path.exists(still_failed_path) else set())
+ new_ids = [rig_id for rig_id in still_failed if rig_id not in known]
+ if new_ids:
+ append_id_list(still_failed_path, new_ids)
+ logger.info("{} rigs still failed ({} newly recorded) -> {}".format(
+ len(still_failed), len(new_ids), still_failed_path))
logger.info("Done. Corrected {}/{} rigs (still failed: {}).".format(
corrected_count, len(target_ids), len(still_failed)))
@@ -352,7 +446,8 @@ def main():
help="Append rig ids the LLM still couldn't fix (default: "
"sibling 'still_failed_clean_names.txt').")
parser.add_argument("--rig_timeout", type=int, default=15,
- help="Per-rig wall-time budget in seconds (SIGALRM). 0 disables.")
+ help="Per-CHUNK wall-time budget in seconds (SIGALRM; a rig's "
+ "total budget is this times its chunk count). 0 disables.")
parser.add_argument("--chunk_size", type=int, default=16,
help="Joints per LLM call. Smaller chunks avoid length drift on "
"long arrays; larger chunks save API calls.")
diff --git a/data_process/mesh_animation/__init__.py b/data_process/mesh_animation/__init__.py
index e69de29..ab99b0b 100644
--- a/data_process/mesh_animation/__init__.py
+++ b/data_process/mesh_animation/__init__.py
@@ -0,0 +1,18 @@
+"""Mesh animation: drive rigged characters with motion data and export GLB/FBX.
+
+Entry points (all run under Blender headless, ``blender -b -P <script> -- <args>``):
+
+- ``animate_motion`` — feature-format clip (stage-4 / generated) + ``cond.npy``
+- ``animate_npz`` — export-stage motion NPZ (bone names carried in the file)
+- ``animate_fbx`` — raw animation FBX/GLB clips, action transfer by bone name
+- ``animate_mixamo`` — batch wrapper pairing one character with a directory of NPZs
+- ``animate_lbs`` — manual NumPy FK+LBS: deform a rigged asset's skinned mesh
+ directly with a motion NPZ (either flavor) and save the vertex animation
+- ``preprocess_char`` — run one rigged, animated asset through the real export +
+ feature pipeline in-process: writes export NPZs, motion-feature NPZs, the
+ model-side ``cond.npy``, and a canonical rest-pose GLB/FBX that feature NPZs
+ drive through ``animate_lbs`` cond-free
+
+Shared plumbing lives in :mod:`.common`; rig primitives in
+:mod:`data_process.utils.blender_rig`.
+"""
diff --git a/data_process/mesh_animation/animate_fbx.py b/data_process/mesh_animation/animate_fbx.py
index 53d26b6..e617c56 100644
--- a/data_process/mesh_animation/animate_fbx.py
+++ b/data_process/mesh_animation/animate_fbx.py
@@ -26,17 +26,20 @@ import sys
import bpy
from loguru import logger
-from tqdm import tqdm
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
-from data_process.utils.blender_export import reset_scene # noqa: E402
+from data_process.mesh_animation.common import ( # noqa: E402
+ clip_output_path,
+ load_character,
+ parse_blender_argv,
+ run_clip_batch,
+)
from data_process.utils.blender_rig import ( # noqa: E402
RECONSTRUCTED_ACTION_NAME,
export_animated_character,
get_armature_obj,
load_file,
- repair_and_pack_textures,
update_scene,
)
@@ -89,16 +92,13 @@ def animate_character_fbx(char_path, anim_path, output_dir, char_anim_type='glb'
character (1.0 = every animated bone landed).
"""
anim_base = os.path.splitext(os.path.basename(anim_path))[0]
- output_path = os.path.join(output_dir, f"{anim_base}.{char_anim_type}")
+ output_path = clip_output_path(anim_path, output_dir, char_anim_type)
if skip_if_exists and os.path.exists(output_path):
logger.info(f"Output already exists, skipping: {output_path}")
return 1.0
os.makedirs(output_dir, exist_ok=True)
- reset_scene()
- char_armature = get_armature_obj(load_file(char_path))
- assert char_armature is not None, "No armature found in character file"
- repair_and_pack_textures(char_path)
+ char_armature = load_character(char_path)
anim_objs = load_file(anim_path)
anim_armature = get_armature_obj(anim_objs)
@@ -119,6 +119,8 @@ def animate_character_fbx(char_path, anim_path, output_dir, char_anim_type='glb'
for obj in anim_objs:
bpy.data.objects.remove(obj, do_unlink=True)
+ # Unlike the NPZ paths, the clip's own frame range is kept (it need not
+ # start at 0), so the scene timing is set directly here.
frame_start, frame_end = action.frame_range
scene = bpy.context.scene
scene.render.fps = int(fps)
@@ -148,8 +150,7 @@ def parse_args():
help="Scene frame rate for the export (Mixamo is 30).")
parser.add_argument("--overwrite", action='store_true',
help="Re-export clips whose output already exists.")
- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
- return parser.parse_args(argv)
+ return parse_blender_argv(parser)
if __name__ == "__main__":
@@ -165,20 +166,16 @@ if __name__ == "__main__":
clips = [args.anim_path]
logger.info(f"Baking {len(clips)} clip(s) onto {args.char_path}")
- os.makedirs(args.output_dir, exist_ok=True)
- err_log = os.path.join(args.output_dir, "animate_errors.log")
-
- for clip in tqdm(clips, desc="Animating character"):
- try:
- animate_character_fbx(
- char_path=args.char_path,
- anim_path=clip,
- output_dir=args.output_dir,
- char_anim_type=args.char_anim_type,
- fps=args.fps,
- skip_if_exists=not args.overwrite,
- )
- except Exception as e: # noqa: BLE001 — keep the batch going
- logger.error(f"Error processing {os.path.basename(clip)}: {e}")
- with open(err_log, "a") as f:
- f.write(f"{os.path.basename(clip)}: {e}\n")
+ run_clip_batch(
+ clips,
+ lambda clip: animate_character_fbx(
+ char_path=args.char_path,
+ anim_path=clip,
+ output_dir=args.output_dir,
+ char_anim_type=args.char_anim_type,
+ fps=args.fps,
+ skip_if_exists=not args.overwrite,
+ ),
+ output_dir=args.output_dir,
+ desc="Animating character",
+ )
diff --git a/data_process/mesh_animation/animate_lbs.py b/data_process/mesh_animation/animate_lbs.py
new file mode 100644
index 0000000..c971005
--- /dev/null
+++ b/data_process/mesh_animation/animate_lbs.py
@@ -0,0 +1,404 @@
+"""Animate a rigged asset by applying Linear Blend Skinning manually in NumPy.
+
+Instead of building a Blender Action and letting Blender's armature modifier
+deform the mesh (the :mod:`animate_motion` / :mod:`animate_npz` path), this
+extracts the skinning data from the rigged asset once — vertices, weights,
+bind pose — computes per-frame bone matrices from the motion, and runs the
+LBS equation itself:
+
+ v[f] = sum_b w[v,b] * (G[f,b] @ inv(bind[b])) @ v_rest
+
+Blender is used ONLY to parse the asset (GLB/FBX mesh + weights + rest bones);
+all skinning math is plain NumPy, so the result doubles as a reference
+implementation and feeds pipelines that want raw deformed vertices (point
+clouds, custom renderers, geometry losses) rather than a re-exported rig.
+
+Accepts both motion formats, auto-detected from the NPZ keys:
+ - export-stage NPZ (``anim_local_rot`` / ``names`` / ...), self-contained;
+ - feature-format NPZ (``local_rotations`` + ``global_positions``, the
+ generated-motion format):
+ * with ``--dataset_type`` (and optionally ``--cond_path``) the motion
+ skeleton is resolved through ``cond.npy`` exactly like
+ :mod:`animate_motion`;
+ * WITHOUT them, the asset itself is taken as the canonical motion
+ skeleton — the cond-free path for assets baked by
+ :mod:`preprocess_char` (joint order = bone order, rest = the
+ asset's rest, scale = 1).
+
+Bones are matched to the asset by name. Asset bones missing from the motion
+keep their rest local transform (they follow their parent, the ``'keep'``
+strategy); motion bones missing from the asset are ignored with a warning.
+
+Outputs (per ``--save``; default ``glb``):
+ - ``glb`` / ``fbx``: ``<clip>_lbs.<fmt>`` — the animated RIGGED asset,
+ exported through the same keyframe path as :mod:`animate_npz` (the
+ manual LBS and Blender's armature modifier are numerically equivalent,
+ so this is the playable twin of the vertex outputs).
+ - ``npz``: ``<clip>_lbs.npz`` with ``vertices (F, V, 3)`` (world space),
+ ``faces``, ``fps``, ``frame_count`` — opt-in, for pipelines that want
+ raw deformed vertices.
+ - ``obj``: one OBJ per frame under ``<clip>_lbs/`` — opt-in.
+
+Usage (Blender headless or plain python with pip bpy):
+ blender -b -P data_process/mesh_animation/animate_lbs.py -- \\
+ --char_path my_rigged_asset.glb \\
+ --anim_path <export_dir>/motions/<clip>.npz \\
+ --output_dir outputs/lbs
+"""
+
+import argparse
+import os
+import sys
+
+import numpy as np
+from loguru import logger
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
+
+from Animation import transforms_local # noqa: E402
+
+from data_process.mesh_animation.common import ( # noqa: E402
+ load_character,
+ npz_scalar,
+ parse_blender_argv,
+ quat_pos_to_mats,
+)
+from data_process.utils.blender_rig import ( # noqa: E402
+ compute_bone_keyframes,
+ export_animated_character,
+ find_skinned_meshes,
+ rebuild_action_from_data,
+ set_scene_timing,
+ update_scene,
+)
+
+
+# ---------------------------------------------------------------------------
+# Skin extraction (the only bpy-dependent step)
+# ---------------------------------------------------------------------------
+
+def extract_skin(char_armature):
+ """Extract everything LBS needs from a loaded rigged asset.
+
+ Returns a dict with:
+ bone_names : list of N bone names (armature order)
+ parents : (N,) parent indices, -1 for roots
+ rest_global : (N, 4, 4) armature-space bind matrices
+ rest_local : (N, 4, 4) parent-relative rest transforms
+ vertices : (V, 4) homogeneous rest vertices in ARMATURE space
+ weights : (V, N) normalized skinning weights (rows may be all
+ zero for unskinned vertices — those stay at rest)
+ faces : list of per-polygon vertex-index tuples
+ arm_world : (4, 4) armature object world matrix
+ """
+ bones = list(char_armature.data.bones)
+ bone_names = [b.name for b in bones]
+ bone_index = {n: i for i, n in enumerate(bone_names)}
+ parents = np.array(
+ [bone_index[b.parent.name] if b.parent else -1 for b in bones])
+ rest_global = np.stack([np.array(b.matrix_local) for b in bones])
+ rest_local = np.stack([
+ np.array(b.matrix_local) if b.parent is None
+ else np.linalg.inv(np.array(b.parent.matrix_local)) @ np.array(b.matrix_local)
+ for b in bones])
+
+ arm_world = np.array(char_armature.matrix_world)
+ arm_world_inv = np.linalg.inv(arm_world)
+
+ all_verts, all_weights, all_faces = [], [], []
+ offset = 0
+ meshes = find_skinned_meshes(char_armature)
+ assert meshes, "No mesh with an Armature modifier targeting the asset's armature"
+ for mesh_obj in meshes:
+ mesh = mesh_obj.data
+ to_arm = arm_world_inv @ np.array(mesh_obj.matrix_world)
+
+ v = np.ones((len(mesh.vertices), 4))
+ for i, vert in enumerate(mesh.vertices):
+ v[i, :3] = vert.co
+ all_verts.append(v @ to_arm.T)
+
+ group_to_bone = {g.index: bone_index.get(g.name) for g in mesh_obj.vertex_groups}
+ w = np.zeros((len(mesh.vertices), len(bones)))
+ for i, vert in enumerate(mesh.vertices):
+ for g in vert.groups:
+ b = group_to_bone.get(g.group)
+ if b is not None and g.weight > 0.0:
+ w[i, b] += g.weight
+ all_weights.append(w)
+
+ all_faces.extend(tuple(idx + offset for idx in poly.vertices)
+ for poly in mesh.polygons)
+ offset += len(mesh.vertices)
+
+ vertices = np.concatenate(all_verts)
+ weights = np.concatenate(all_weights)
+ sums = weights.sum(axis=1, keepdims=True)
+ skinned = sums[:, 0] > 0
+ weights[skinned] /= sums[skinned]
+ logger.info(f"Extracted {len(vertices)} vertices ({(~skinned).sum()} unskinned), "
+ f"{len(all_faces)} faces, {len(bones)} bones from {len(meshes)} mesh(es)")
+
+ # Canonical joint order baked in by preprocess_char (glTF extras carry
+ # object-level custom properties); bone enumeration order itself is not
+ # stable across glTF round trips.
+ import json
+ order = (char_armature.get('canonical_joint_order')
+ or char_armature.data.get('canonical_joint_order'))
+ if isinstance(order, str):
+ order = json.loads(order)
+
+ return {
+ 'bone_names': bone_names, 'parents': parents,
+ 'rest_global': rest_global, 'rest_local': rest_local,
+ 'vertices': vertices, 'weights': weights, 'faces': all_faces,
+ 'arm_world': arm_world, 'canonical_order': order,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Motion loading (both NPZ flavors)
+# ---------------------------------------------------------------------------
+
+def load_motion_local_mats(anim_path, dataset_type=None, cond_path=None):
+ """Return ``(anim_local (F,J,4,4), rest_local (J,4,4), bone_names, fps)``.
+
+ Auto-detects the NPZ flavor: export-stage (self-contained) vs
+ feature-format (generated motion; resolved through ``cond.npy`` exactly
+ like :mod:`animate_motion`).
+ """
+ data = np.load(anim_path, allow_pickle=True)
+ if 'anim_local_rot' in data:
+ from data_process.mesh_animation.animate_npz import build_anims_from_export_npz
+ anim, rest_anim, names = build_anims_from_export_npz(data)
+ fps = npz_scalar(data, 'fps', 30)
+ elif 'local_rotations' in data:
+ from data_process.mesh_animation.animate_motion import (
+ COND_PATH_TEMPLATE,
+ build_anim_from_npz,
+ load_cond_data,
+ )
+ assert dataset_type, "--dataset_type is required for feature-format motion"
+ cond_path = cond_path or COND_PATH_TEMPLATE.format(dataset_type=dataset_type)
+ cond_data = load_cond_data(cond_path, anim_path, dataset_type)
+ anim, rest_anim, _tpos, raw = build_anim_from_npz(anim_path, cond_data)
+ names = list(cond_data['joint_names'])
+ fps = npz_scalar(raw, 'fps', 30)
+ else:
+ raise RuntimeError(
+ f"Unrecognized motion NPZ (keys: {sorted(data.keys())}); expected "
+ "export-stage ('anim_local_rot', ...) or feature format "
+ "('local_rotations', ...)")
+ return (transforms_local(anim), transforms_local(rest_anim)[0],
+ [str(n) for n in names], fps)
+
+
+def motion_from_canonical_char(data, skin):
+ """Feature NPZ driving a canonical asset (:mod:`preprocess_char` output).
+
+ The asset's own skeleton IS the motion skeleton: joint order = bone
+ order, rest pose = the asset's rest, scale = 1 — so no ``cond.npy`` is
+ needed. Root positions come from ``global_positions``; every other joint
+ keeps its rest offset (rigid bones), rotations from ``local_rotations``.
+ """
+ q = np.asarray(data['local_rotations'], dtype=np.float64) # (F, J, 4) wxyz
+ gp = np.asarray(data['global_positions'], dtype=np.float64) # (F, J, 3)
+
+ order = skin.get('canonical_order')
+ if order is None:
+ logger.warning("Asset carries no canonical_joint_order property (not "
+ "produced by preprocess_char?); assuming its bone "
+ "enumeration order matches the motion's joint order")
+ order = list(skin['bone_names'])
+ J = len(order)
+ assert q.shape[1] == J, (
+ f"motion has {q.shape[1]} joints but the asset's canonical skeleton "
+ f"has {J} bones; the cond-free path needs an asset baked to the "
+ f"motion skeleton (see preprocess_char.py) — or pass "
+ f"--dataset_type/--cond_path")
+ missing = [n for n in order if n not in skin['bone_names']]
+ assert not missing, f"canonical_joint_order names missing from armature: {missing}"
+
+ idx = [skin['bone_names'].index(n) for n in order]
+ rest_local = skin['rest_local'][idx] # motion joint order
+ pos = np.repeat(rest_local[None, :, :3, 3], q.shape[0], axis=0)
+ pos[:, 0] = gp[:, 0]
+ anim_local = quat_pos_to_mats(q, pos)
+ return anim_local, rest_local, list(order), npz_scalar(data, 'fps', 30)
+
+
+# ---------------------------------------------------------------------------
+# Manual LBS
+# ---------------------------------------------------------------------------
+
+def lbs_deform(skin, anim_local, motion_rest_local, motion_bone_names):
+ """Run manual Linear Blend Skinning; returns world-space ``(F, V, 3)``.
+
+ Per frame and asset bone::
+
+ pose_local[b] = rest_local[b] @ inv(m_rest[b]) @ m_anim[f, b] (driven)
+ pose_local[b] = rest_local[b] (undriven)
+ G[f, b] = G[f, parent] @ pose_local[b]
+ skin_mat[b] = G[f, b] @ inv(rest_global[b])
+ v[f] = sum_b w[v, b] * skin_mat[b] @ v_rest
+
+ which is exactly what the Blender armature modifier evaluates for the
+ Action built by the keyframe path, so the two pipelines are
+ interchangeable.
+ """
+ bone_names = skin['bone_names']
+ parents = skin['parents']
+ nframes = anim_local.shape[0]
+ nbones = len(bone_names)
+
+ motion_idx = {n: i for i, n in enumerate(motion_bone_names)}
+ driven = [(b, motion_idx[n]) for b, n in enumerate(bone_names) if n in motion_idx]
+ missing = [n for n in motion_bone_names if n not in set(bone_names)]
+ if missing:
+ logger.warning(f"{len(missing)} motion bones not on the asset "
+ f"(ignored): {missing[:8]}{'...' if len(missing) > 8 else ''}")
+ undriven = nbones - len(driven)
+ if undriven:
+ logger.info(f"{undriven} asset bones not in the motion keep their rest "
+ f"local transform (follow parent)")
+ assert driven, "No motion bone matches the asset's armature by name"
+
+ # Per-frame local transforms for every asset bone.
+ pose_local = np.broadcast_to(skin['rest_local'], (nframes, nbones, 4, 4)).copy()
+ for b, j in driven:
+ rel = np.linalg.inv(motion_rest_local[j])[None] @ anim_local[:, j]
+ pose_local[:, b] = skin['rest_local'][b][None] @ rel
+
+ # FK to armature space (bones are stored parent-before-child in Blender).
+ glob = np.empty_like(pose_local)
+ for b in range(nbones):
+ p = parents[b]
+ glob[:, b] = pose_local[:, b] if p < 0 else glob[:, p] @ pose_local[:, b]
+
+ skin_mats = glob @ np.linalg.inv(skin['rest_global'])[None] # (F, N, 4, 4)
+
+ # LBS: blend matrices per vertex, then transform.
+ verts = skin['vertices'] # (V, 4)
+ weights = skin['weights'] # (V, N)
+ unskinned = weights.sum(axis=1) == 0
+ out = np.empty((nframes, len(verts), 3))
+ for f in range(nframes):
+ vert_mats = np.einsum('vb,bij->vij', weights, skin_mats[f])
+ deformed = np.einsum('vij,vj->vi', vert_mats, verts)
+ deformed[unskinned] = verts[unskinned]
+ out[f] = (deformed @ skin['arm_world'].T)[:, :3]
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Output
+# ---------------------------------------------------------------------------
+
+def save_obj_sequence(dirpath, vertices, faces):
+ os.makedirs(dirpath, exist_ok=True)
+ face_lines = ["f " + " ".join(str(i + 1) for i in poly) for poly in faces]
+ for f in range(vertices.shape[0]):
+ with open(os.path.join(dirpath, f"{f:04d}.obj"), 'w') as fh:
+ fh.write("\n".join(f"v {x:.6f} {y:.6f} {z:.6f}" for x, y, z in vertices[f]))
+ fh.write("\n" + "\n".join(face_lines) + "\n")
+ logger.info(f"Saved {vertices.shape[0]} OBJ frames to {dirpath}")
+
+
+def animate_lbs(char_path, anim_path, output_dir, dataset_type=None,
+ cond_path=None, save=('glb',)):
+ """Deform a rigged asset with a motion NPZ via manual LBS and save."""
+ assert os.path.exists(anim_path), f"Animation file not found: {anim_path}"
+ os.makedirs(output_dir, exist_ok=True)
+
+ rig_formats = tuple(f for f in save if f in ('glb', 'fbx'))
+ char_armature = load_character(char_path, pack_textures=bool(rig_formats))
+ skin = extract_skin(char_armature)
+
+ data = np.load(anim_path, allow_pickle=True)
+ if 'local_rotations' in data and dataset_type is None and cond_path is None:
+ logger.info("Feature NPZ with no cond: treating the asset as the "
+ "canonical motion skeleton (preprocess_char output)")
+ anim_local, rest_local, motion_names, fps = motion_from_canonical_char(data, skin)
+ else:
+ anim_local, rest_local, motion_names, fps = load_motion_local_mats(
+ anim_path, dataset_type=dataset_type, cond_path=cond_path)
+
+ vertices = lbs_deform(skin, anim_local, rest_local, motion_names)
+
+ stem = os.path.splitext(os.path.basename(anim_path))[0] + '_lbs'
+ faces_arr = np.array(skin['faces'], dtype=object)
+ if 'npz' in save:
+ out = os.path.join(output_dir, stem + '.npz')
+ np.savez_compressed(out, vertices=vertices.astype(np.float32),
+ faces=faces_arr, fps=fps,
+ frame_count=vertices.shape[0])
+ logger.info(f"Saved LBS vertex animation: {out} "
+ f"(F={vertices.shape[0]}, V={vertices.shape[1]})")
+ if 'obj' in save:
+ save_obj_sequence(os.path.join(output_dir, stem), vertices, skin['faces'])
+ if rig_formats:
+ # Rigged export via the same keyframe path animate_npz uses: the
+ # relative keyframes inv(rest) @ anim land on the asset's own rest,
+ # exactly what lbs_deform evaluates. Bones absent from the motion
+ # keep their rest local transform (no keyframes = follow parent),
+ # matching the LBS 'keep' semantics.
+ set_scene_timing(anim_local.shape[0], fps)
+ keyframes = compute_bone_keyframes(rest_local, anim_local, motion_names)
+ rebuild_action_from_data(char_armature, keyframes)
+ update_scene()
+ export_animated_character(os.path.join(output_dir, stem),
+ formats=rig_formats)
+ return vertices
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(
+ description="Animate a rigged asset via manual NumPy LBS.")
+ parser.add_argument("--char_path", type=str, required=True,
+ help="Rigged asset GLB/FBX (mesh + armature + weights).")
+ parser.add_argument("--anim_path", type=str, required=True,
+ help="Motion NPZ (export-stage or feature-format, auto-detected), "
+ "or a DIRECTORY of NPZs — one output set per action clip.")
+ parser.add_argument("--dataset_type", type=str, default=None,
+ choices=['truebones', 'objaverse', 'mixamo'],
+ help="For feature-format motion: resolves cond.npy. Omit it "
+ "(and --cond_path) to drive a canonical asset baked by "
+ "preprocess_char.py cond-free.")
+ parser.add_argument("--cond_path", type=str, default=None,
+ help="cond.npy override for feature-format motion.")
+ parser.add_argument("--output_dir", type=str, default='outputs/lbs')
+ parser.add_argument("--save", type=str, default='glb',
+ help="Comma-separated outputs: glb / fbx (animated rigged "
+ "asset via the animate_npz keyframe path; default), "
+ "npz (vertex animation), obj (per-frame OBJ files).")
+ return parse_blender_argv(parser)
+
+
+if __name__ == "__main__":
+ args = parse_args()
+ save = tuple(s.strip() for s in args.save.split(',') if s.strip())
+
+ if os.path.isdir(args.anim_path):
+ import glob as _glob
+ from data_process.mesh_animation.common import run_clip_batch
+ clips = sorted(_glob.glob(os.path.join(args.anim_path, '*.npz')))
+ logger.info(f"Animating {len(clips)} clip(s) from {args.anim_path} — "
+ f"one output set per action")
+ run_clip_batch(
+ clips,
+ lambda clip: animate_lbs(
+ char_path=args.char_path, anim_path=clip,
+ output_dir=args.output_dir, dataset_type=args.dataset_type,
+ cond_path=args.cond_path, save=save),
+ output_dir=args.output_dir,
+ desc="LBS animating",
+ )
+ else:
+ animate_lbs(
+ char_path=args.char_path,
+ anim_path=args.anim_path,
+ output_dir=args.output_dir,
+ dataset_type=args.dataset_type,
+ cond_path=args.cond_path,
+ save=save,
+ )
diff --git a/data_process/mesh_animation/animate_mixamo.py b/data_process/mesh_animation/animate_mixamo.py
index 32c0838..ce7d803 100644
--- a/data_process/mesh_animation/animate_mixamo.py
+++ b/data_process/mesh_animation/animate_mixamo.py
@@ -19,9 +19,12 @@ import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from loguru import logger # noqa: E402
-from tqdm import tqdm # noqa: E402
from data_process.mesh_animation.animate_npz import animate_character # noqa: E402
+from data_process.mesh_animation.common import ( # noqa: E402
+ parse_blender_argv,
+ run_clip_batch,
+)
def parse_args():
@@ -35,8 +38,9 @@ def parse_args():
help="Output directory for animated GLB/FBX files.")
parser.add_argument("--char_anim_type", type=str, default='glb', choices=['glb', 'fbx'],
help="Export format for the animated character.")
- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
- return parser.parse_args(argv)
+ parser.add_argument("--overwrite", action='store_true',
+ help="Re-export clips whose output already exists.")
+ return parse_blender_argv(parser)
if __name__ == "__main__":
@@ -44,23 +48,19 @@ if __name__ == "__main__":
assert os.path.exists(args.char_path), f"Character file not found: {args.char_path}"
assert os.path.isdir(args.npz_dir), f"NPZ directory not found: {args.npz_dir}"
- os.makedirs(args.output_dir, exist_ok=True)
- err_log = os.path.join(args.output_dir, "animate_errors.log")
-
- npz_files = sorted(f for f in os.listdir(args.npz_dir) if f.endswith(".npz"))
+ npz_files = sorted(os.path.join(args.npz_dir, f)
+ for f in os.listdir(args.npz_dir) if f.endswith(".npz"))
logger.info(f"Found {len(npz_files)} NPZ files in {args.npz_dir}")
- for npz_file in tqdm(npz_files, desc="Animating meshes"):
- npz_path = os.path.join(args.npz_dir, npz_file)
- try:
- animate_character(
- char_path=args.char_path,
- anim_path=npz_path,
- output_dir=args.output_dir,
- char_anim_type=args.char_anim_type,
- skip_if_exists=True,
- )
- except Exception as e: # noqa: BLE001 — keep the batch going
- logger.error(f"Error processing {npz_file}: {e}")
- with open(err_log, "a") as f:
- f.write(f"{npz_file}: {e}\n")
+ run_clip_batch(
+ npz_files,
+ lambda npz_path: animate_character(
+ char_path=args.char_path,
+ anim_path=npz_path,
+ output_dir=args.output_dir,
+ char_anim_type=args.char_anim_type,
+ skip_if_exists=not args.overwrite,
+ ),
+ output_dir=args.output_dir,
+ desc="Animating meshes",
+ )
diff --git a/data_process/mesh_animation/animate_motion.py b/data_process/mesh_animation/animate_motion.py
index 7533a7c..039d763 100644
--- a/data_process/mesh_animation/animate_motion.py
+++ b/data_process/mesh_animation/animate_motion.py
@@ -33,21 +33,15 @@ from loguru import logger
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
-from Animation import Animation, Quaternions, transforms_local # noqa: E402
-
-from data_process.utils.blender_export import reset_scene # noqa: E402
-from data_process.utils.blender_rig import ( # noqa: E402
- EXTRA_BONES_STRATEGIES,
- compute_bone_keyframes,
- export_animated_character,
- get_armature_obj,
- load_file,
- rebuild_action_from_data,
- repair_and_pack_textures,
- set_scene_timing,
- sync_armature_bones,
- update_scene,
+from Animation import Animation, Quaternions # noqa: E402
+
+from data_process.mesh_animation.common import ( # noqa: E402
+ drive_and_export,
+ load_character,
+ npz_scalar,
+ parse_blender_argv,
)
+from data_process.utils.blender_rig import EXTRA_BONES_STRATEGIES # noqa: E402
from data_process.utils.skeleton import scale_anim # noqa: E402
@@ -65,16 +59,11 @@ COND_PATH_TEMPLATE = 'dataset/features/{dataset_type}/cond.npy'
# Animation loading
# ---------------------------------------------------------------------------
-def _get_scalar(d, key, default):
- """Read a scalar from an NpzFile / dict, falling back to *default*."""
- return float(d[key]) if key in d else default
-
-
def build_anim_from_npz(anim_path, cond_data):
"""Build ``(anim, rest_anim, tpos_global_rot, raw_anim_data)`` from a
feature-format NPZ (``global_positions`` + ``local_rotations``)."""
parents = cond_data['parents']
- scale_factor = _get_scalar(cond_data, 'scale_factor', 1.0)
+ scale_factor = npz_scalar(cond_data, 'scale_factor', 1.0)
offsets_scaled = cond_data['offsets'] / scale_factor
tpos_local_rot = cond_data['tpos_local_rotations']
@@ -125,7 +114,7 @@ def build_anim_from_npy(anim_path, cond_data, anim_mode):
) from exc
parents = cond_data['parents']
- scale_factor = _get_scalar(cond_data, 'scale_factor', 1.0)
+ scale_factor = npz_scalar(cond_data, 'scale_factor', 1.0)
tpos_global_rot = cond_data['tpos_global_rotations']
offsets = cond_data['tpos_offsets']
@@ -263,37 +252,26 @@ def animate_character(char_path, anim_path, cond_path, output_dir,
extra_bones_strategy: How to handle armature bones not present in
the animation (see :func:`sync_armature_bones`).
"""
- assert os.path.exists(char_path), f"Character file not found: {char_path}"
assert os.path.exists(anim_path), f"Animation file not found: {anim_path}"
assert os.path.exists(cond_path), f"Condition file not found: {cond_path}"
os.makedirs(output_dir, exist_ok=True)
anim_base = os.path.splitext(os.path.basename(anim_path))[0]
- output_path_no_ext = os.path.join(output_dir, anim_base)
- reset_scene()
- char_armature = get_armature_obj(load_file(char_path))
- assert char_armature is not None, "No armature found in character file"
- repair_and_pack_textures(char_path)
+ char_armature = load_character(char_path)
cond_data = load_cond_data(cond_path, anim_path, dataset_type)
- bone_names = cond_data['joint_names']
anim, rest_anim, tpos_global_rot, anim_data = load_animation(
anim_path, cond_data, anim_mode)
- anim_local_mat = transforms_local(anim) # (nframes, nbones, 4, 4)
- rest_local_mat = transforms_local(rest_anim)[0] # (nbones, 4, 4)
-
- sync_armature_bones(char_armature, bone_names,
- extra_bones_strategy=extra_bones_strategy)
- set_scene_timing(anim_local_mat.shape[0], _get_scalar(anim_data, 'fps', 30))
-
- keyframes = compute_bone_keyframes(
- rest_local_mat, anim_local_mat, bone_names, tpos_global_rot)
- rebuild_action_from_data(char_armature, keyframes)
- update_scene()
-
- export_animated_character(output_path_no_ext, formats=('glb', 'fbx'))
+ drive_and_export(
+ char_armature, anim, rest_anim, cond_data['joint_names'],
+ fps=npz_scalar(anim_data, 'fps', 30),
+ output_path_no_ext=os.path.join(output_dir, anim_base),
+ formats=('glb', 'fbx'),
+ extra_bones_strategy=extra_bones_strategy,
+ tpos_global_rot=tpos_global_rot,
+ )
def parse_args():
@@ -322,8 +300,7 @@ def parse_args():
"the nearest kept ancestor, then remove the bones. "
"'remove': delete bones AND mesh vertices dominantly "
"weighted to them. 'keep': leave in place, no keyframes.")
- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
- return parser.parse_args(argv)
+ return parse_blender_argv(parser)
if __name__ == "__main__":
diff --git a/data_process/mesh_animation/animate_npz.py b/data_process/mesh_animation/animate_npz.py
index d5d9943..052151f 100644
--- a/data_process/mesh_animation/animate_npz.py
+++ b/data_process/mesh_animation/animate_npz.py
@@ -25,31 +25,23 @@ from loguru import logger
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
-from Animation import Animation, Quaternions, transforms_local # noqa: E402
-
-from data_process.utils.blender_export import reset_scene # noqa: E402
-from data_process.utils.blender_rig import ( # noqa: E402
- compute_bone_keyframes,
- export_animated_character,
- get_armature_obj,
- load_file,
- rebuild_action_from_data,
- set_scene_timing,
- sync_armature_bones,
- update_scene,
+from Animation import Animation, Quaternions # noqa: E402
+
+from data_process.mesh_animation.common import ( # noqa: E402
+ clip_output_path,
+ drive_and_export,
+ load_character,
+ npz_scalar,
+ parse_blender_argv,
)
-
-
-def _npz_get_scalar(npz, key, default):
- """Read a scalar from an NpzFile, falling back to *default*."""
- return float(npz[key]) if key in npz else default
+from data_process.utils.blender_rig import EXTRA_BONES_STRATEGIES # noqa: E402
def build_anims_from_export_npz(anim_data):
- """Build ``(anim, rest_anim)`` Animation objects from an export NPZ."""
+ """Build ``(anim, rest_anim, bone_names)`` from an export-stage NPZ."""
bone_names = anim_data['names'].tolist()
nbones = anim_data['anim_local_rot'].shape[1]
- scale_factor = _npz_get_scalar(anim_data, 'scale_factor', 1.0)
+ scale_factor = npz_scalar(anim_data, 'scale_factor', 1.0)
anim_positions = anim_data['anim_local_pos'] / scale_factor
rest_positions = anim_data['rest_local_pos'][None] / scale_factor
@@ -86,34 +78,26 @@ def animate_character(char_path, anim_path, output_dir, char_anim_type='glb',
animation (see :func:`sync_armature_bones`).
skip_if_exists: Return early when the output file already exists.
"""
- assert os.path.exists(char_path), f"Character file not found: {char_path}"
assert os.path.exists(anim_path), f"Animation file not found: {anim_path}"
- anim_base = os.path.splitext(os.path.basename(anim_path))[0]
- output_path = os.path.join(output_dir, f"{anim_base}.{char_anim_type}")
+ output_path = clip_output_path(anim_path, output_dir, char_anim_type)
if skip_if_exists and os.path.exists(output_path):
logger.info(f"Output already exists, skipping: {output_path}")
return
os.makedirs(output_dir, exist_ok=True)
- reset_scene()
- char_armature = get_armature_obj(load_file(char_path))
- assert char_armature is not None, "No armature found in character file"
+ char_armature = load_character(char_path)
anim_data = np.load(anim_path, allow_pickle=True)
anim, rest_anim, bone_names = build_anims_from_export_npz(anim_data)
- anim_local_mat = transforms_local(anim) # (nframes, nbones, 4, 4)
- rest_local_mat = transforms_local(rest_anim)[0] # (nbones, 4, 4)
-
- sync_armature_bones(char_armature, bone_names,
- extra_bones_strategy=extra_bones_strategy)
- set_scene_timing(anim_local_mat.shape[0], _npz_get_scalar(anim_data, 'fps', 30))
- keyframes = compute_bone_keyframes(rest_local_mat, anim_local_mat, bone_names)
- rebuild_action_from_data(char_armature, keyframes)
- update_scene()
-
- export_animated_character(os.path.splitext(output_path)[0], formats=(char_anim_type,))
+ drive_and_export(
+ char_armature, anim, rest_anim, bone_names,
+ fps=npz_scalar(anim_data, 'fps', 30),
+ output_path_no_ext=os.path.splitext(output_path)[0],
+ formats=(char_anim_type,),
+ extra_bones_strategy=extra_bones_strategy,
+ )
def parse_args():
@@ -126,10 +110,9 @@ def parse_args():
parser.add_argument("--output_dir", type=str, default='outputs/animated')
parser.add_argument("--char_anim_type", type=str, default='glb', choices=['glb', 'fbx'])
parser.add_argument("--extra_bones_strategy", type=str, default='merge',
- choices=['keep', 'merge', 'remove'],
+ choices=list(EXTRA_BONES_STRATEGIES),
help="What to do with armature bones missing from the animation.")
- argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
- return parser.parse_args(argv)
+ return parse_blender_argv(parser)
if __name__ == "__main__":
diff --git a/data_process/mesh_animation/common.py b/data_process/mesh_animation/common.py
new file mode 100644
index 0000000..dd5ab70
--- /dev/null
+++ b/data_process/mesh_animation/common.py
@@ -0,0 +1,172 @@
+"""Shared plumbing for the mesh-animation entry points.
+
+Every entry script in this package runs under Blender headless
+(``blender -b -P <script>.py -- <args>``), loads a rigged character, binds a
+driving animation onto its armature, and exports GLB/FBX. They differ only in
+where the driving animation comes from:
+
+ animate_motion feature NPZ (or legacy model ``.npy``) + ``cond.npy``
+ animate_npz export-stage NPZ (bone names carried in the file)
+ animate_fbx raw animation FBX/GLB clips (action transfer by name)
+ animate_mixamo batch wrapper over ``animate_npz``
+
+This module holds the pieces they share: Blender-style CLI parsing, character
+loading, the keyframe-and-export core, and the error-logged batch loop. Rig
+primitives (keyframe math, armature reconciliation, exporters) stay in
+:mod:`data_process.utils.blender_rig`.
+"""
+
+import os
+import sys
+
+from loguru import logger
+from tqdm import tqdm
+
+from Animation import transforms_local
+
+from data_process.utils.blender_export import reset_scene
+from data_process.utils.blender_rig import (
+ compute_bone_keyframes,
+ export_animated_character,
+ get_armature_obj,
+ load_file,
+ rebuild_action_from_data,
+ repair_and_pack_textures,
+ set_scene_timing,
+ sync_armature_bones,
+ update_scene,
+)
+
+ERROR_LOG_NAME = 'animate_errors.log'
+
+
+# ---------------------------------------------------------------------------
+# CLI / small helpers
+# ---------------------------------------------------------------------------
+
+def parse_blender_argv(parser):
+ """Parse CLI args for a script run via ``blender -b -P script.py -- <args>``.
+
+ Blender consumes everything before the ``--`` separator; only what
+ follows belongs to the script. Plain ``python script.py <args>`` (no
+ separator) also works, so the entry points run under pip ``bpy`` too.
+ """
+ argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
+ return parser.parse_args(argv)
+
+
+def npz_scalar(data, key, default):
+ """Read a scalar from an NpzFile / dict, falling back to *default*.
+
+ Mapping-free inputs (e.g. the legacy ``.npy`` ndarray in
+ ``animate_motion``) have no keys and always yield *default*.
+ """
+ if hasattr(data, 'keys') and key in data:
+ return float(data[key])
+ return default
+
+
+def clip_output_path(anim_path, output_dir, ext=None):
+ """``<output_dir>/<clip stem>[.<ext>]`` for a driving-animation file."""
+ base = os.path.splitext(os.path.basename(anim_path))[0]
+ return os.path.join(output_dir, base + (f'.{ext}' if ext else ''))
+
+
+def quat_pos_to_mats(q, pos):
+ """Batch (…, 4) wxyz quaternions + (…, 3) translations -> (…, 4, 4)."""
+ import numpy as np
+ q = q / np.linalg.norm(q, axis=-1, keepdims=True)
+ w, x, y, z = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
+ m = np.zeros(q.shape[:-1] + (4, 4))
+ m[..., 0, 0] = 1 - 2 * (y * y + z * z)
+ m[..., 0, 1] = 2 * (x * y - w * z)
+ m[..., 0, 2] = 2 * (x * z + w * y)
+ m[..., 1, 0] = 2 * (x * y + w * z)
+ m[..., 1, 1] = 1 - 2 * (x * x + z * z)
+ m[..., 1, 2] = 2 * (y * z - w * x)
+ m[..., 2, 0] = 2 * (x * z - w * y)
+ m[..., 2, 1] = 2 * (y * z + w * x)
+ m[..., 2, 2] = 1 - 2 * (x * x + y * y)
+ m[..., :3, 3] = pos
+ m[..., 3, 3] = 1.0
+ return m
+
+
+# ---------------------------------------------------------------------------
+# Character loading
+# ---------------------------------------------------------------------------
+
+def load_character(char_path, pack_textures=True):
+ """Reset the scene, import the character file and return its armature.
+
+ ``pack_textures`` re-links missing texture files found next to the
+ character and packs images into memory so the exporters don't silently
+ drop them (see :func:`repair_and_pack_textures`).
+ """
+ assert os.path.exists(char_path), f"Character file not found: {char_path}"
+ reset_scene()
+ armature = get_armature_obj(load_file(char_path))
+ assert armature is not None, f"No armature found in character file: {char_path}"
+ if pack_textures:
+ repair_and_pack_textures(char_path)
+ return armature
+
+
+# ---------------------------------------------------------------------------
+# Keyframe-and-export core (shared by animate_motion / animate_npz)
+# ---------------------------------------------------------------------------
+
+def drive_and_export(char_armature, anim, rest_anim, bone_names, fps,
+ output_path_no_ext, formats=('glb',),
+ extra_bones_strategy='merge', tpos_global_rot=None):
+ """Bind an ``(anim, rest_anim)`` pair onto the armature and export.
+
+ Args:
+ char_armature: The character's ARMATURE object (see
+ :func:`load_character`).
+ anim: ``Animation`` with the animated local transforms.
+ rest_anim: Single-frame ``Animation`` with the rest pose the
+ character's bind pose corresponds to.
+ bone_names: Bone names, index-aligned with the animations.
+ fps: Scene frame rate for the export.
+ output_path_no_ext: Output path without extension.
+ formats: Iterable of export formats (``'glb'`` / ``'fbx'``).
+ extra_bones_strategy: How to treat armature bones absent from
+ *bone_names* (see :func:`sync_armature_bones`).
+ tpos_global_rot: Optional ``(nbones, 4)`` T-pose global rotations to
+ conjugate keyframes by (legacy ``.npy`` path in animate_motion).
+ """
+ anim_local_mat = transforms_local(anim) # (nframes, nbones, 4, 4)
+ rest_local_mat = transforms_local(rest_anim)[0] # (nbones, 4, 4)
+
+ sync_armature_bones(char_armature, bone_names,
+ extra_bones_strategy=extra_bones_strategy)
+ set_scene_timing(anim_local_mat.shape[0], fps)
+
+ keyframes = compute_bone_keyframes(
+ rest_local_mat, anim_local_mat, bone_names, tpos_global_rot)
+ rebuild_action_from_data(char_armature, keyframes)
+ update_scene()
+
+ export_animated_character(output_path_no_ext, formats=formats)
+
+
+# ---------------------------------------------------------------------------
+# Batch driver (shared by animate_fbx / animate_mixamo)
+# ---------------------------------------------------------------------------
+
+def run_clip_batch(clips, process_one, output_dir, desc):
+ """Process clips one by one; failures are logged, not fatal.
+
+ Each failed clip is recorded (with its error) in
+ ``<output_dir>/animate_errors.log`` and the batch continues.
+ """
+ os.makedirs(output_dir, exist_ok=True)
+ err_log = os.path.join(output_dir, ERROR_LOG_NAME)
+ for clip in tqdm(clips, desc=desc):
+ try:
+ process_one(clip)
+ except Exception as e: # noqa: BLE001 — keep the batch going
+ logger.error(f"Error processing {os.path.basename(clip)}: {e}")
+ with open(err_log, "a") as f:
+ f.write(f"{os.path.basename(clip)}: {e}\n")
diff --git a/data_process/mesh_animation/preprocess_char.py b/data_process/mesh_animation/preprocess_char.py
new file mode 100644
index 0000000..8f44487
--- /dev/null
+++ b/data_process/mesh_animation/preprocess_char.py
@@ -0,0 +1,387 @@
+"""Preprocess one rigged, animated asset through the real export + feature pipeline.
+
+Runs the actual pipeline stages in-process on a single GLB/FBX:
+
+ 1. EXPORT (:func:`export_general.export_asset`) — discover the asset's
+ pose actions, extract rest + animations, motion-driven skeleton pruning,
+ Z-up -> Y-up; writes export-stage NPZs.
+ 2. EXTRACT (:func:`motion_features.process_object`) — canonical T-pose
+ (BFS order, facing -> center -> diameter scale -> ground), per-clip
+ motion FEATURES, and the full topology conditioning dict the model
+ consumes.
+ 3. BAKE — rebuild the asset's armature to the canonical T-pose taken
+ straight from the cond (same joint order, rest, scale), transform the
+ skinned mesh by the same similarity, and save GLB/FBX. The canonical
+ joint order rides inside the file as a custom property.
+
+Outputs under ``--output_dir`` (exactly three by default):
+ <name>_canonical.{glb,fbx} canonical rest-pose asset (drives cond-free)
+ cond.npy ``{asset_name: topology cond}`` — model-side input
+ motions/<clip>.npz motion features (``global_positions`` /
+ ``local_rotations`` / ``root_facing_quat`` / ``fps``)
+Intermediates (export-stage NPZs, T-pose/preview visuals) are cleaned up on
+success; pass ``--keep_intermediate`` to keep them (also makes reruns skip
+the export stage via its completion markers).
+
+Animate afterwards with ONLY a motion-feature NPZ (generated or extracted):
+
+ python -m data_process.mesh_animation.animate_lbs \\
+ --char_path <output_dir>/<name>_canonical.glb \\
+ --anim_path <feature_motion.npz>
+
+Facing canonicalization needs the asset's face-joint pair (``--face_r`` /
+``--face_l`` raw bone names); omit for identity facing (pipeline sentinel).
+
+Assets WITHOUT any action are supported too: a rest-only fallback builds the
+cond from the rest pose (full armature skeleton — motion-driven pruning
+needs animations — and no ``motions/`` output).
+
+Usage (Blender headless):
+ blender -b -P data_process/mesh_animation/preprocess_char.py -- \\
+ --char_path my_asset.glb --output_dir outputs/my_asset \\
+ --face_r R_Thigh --face_l L_Thigh --formats glb,fbx
+"""
+
+import argparse
+import glob
+import json
+import math
+import os
+import sys
+
+import bpy
+import numpy as np
+from loguru import logger
+from mathutils import Matrix
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
+
+from data_process.joint_annotation.names_clean_rule import ( # noqa: E402
+ clean_joint_name,
+ post_process,
+)
+from data_process.mesh_animation.common import ( # noqa: E402
+ load_character,
+ parse_blender_argv,
+ quat_pos_to_mats,
+)
+from data_process.motion_export.export_general import export_asset # noqa: E402
+from data_process.utils.blender_export import ( # noqa: E402
+ apply_zup_to_yup,
+ build_rest_animation,
+ build_skeleton_arrays,
+ clear_animation_state,
+)
+from data_process.utils.blender_rig import ( # noqa: E402
+ export_selected_to_file,
+ find_skinned_meshes,
+ select_objs,
+ sync_armature_bones,
+ update_scene,
+)
+from data_process.utils.motion_features import ( # noqa: E402
+ build_topology_cond,
+ process_object,
+ process_tpose,
+)
+
+
+def _umeyama(X, Y):
+ """Similarity (s, R, t) with ``Y ~= s * X @ R + t``; returns (4x4, residual)."""
+ muX, muY = X.mean(0), Y.mean(0)
+ Xc, Yc = X - muX, Y - muY
+ U, S, Vt = np.linalg.svd(Xc.T @ Yc)
+ D = np.eye(3)
+ D[2, 2] = np.sign(np.linalg.det(U @ Vt))
+ R = U @ D @ Vt
+ s = (S * D.diagonal()).sum() / (Xc ** 2).sum()
+ M = np.eye(4)
+ M[:3, :3] = s * R.T
+ M[:3, 3] = muY - s * muX @ R
+ resid = np.abs(s * X @ R + (muY - s * muX @ R) - Y).max()
+ return M, resid
+
+
+# ---------------------------------------------------------------------------
+# Rest-only fallback: cond from the rest pose alone (asset has no actions)
+# ---------------------------------------------------------------------------
+
+def cond_from_rest(char_path, name, face_joints=None, target_diameter=2.0):
+ """Build the topology cond from the asset's rest pose alone.
+
+ Used when the asset carries no animation: the export stage's
+ motion-driven skeleton pruning cannot run, so the FULL armature skeleton
+ is kept; everything else (world-applied rest, Z-up -> Y-up, BFS reorder,
+ facing/scale/ground canonicalization, cond fields) matches the pipeline.
+ """
+ from Animation import positions_global, rotations_global
+
+ armature = load_character(char_path)
+ names, parents, rest_pos, rest_rot, _ = build_skeleton_arrays(
+ armature, None, apply_world=True)
+ rest_anim = build_rest_animation(parents, rest_pos, rest_rot, len(names))
+ _, rest_anim = apply_zup_to_yup(rest_anim, rest_anim)
+
+ tpos_data = {
+ 'names': np.array(names), 'parents': np.asarray(parents),
+ 'rest_local_pos': np.asarray(rest_anim.positions[0]),
+ 'rest_local_rot': np.asarray(rest_anim.rotations.qs[0]),
+ 'fps': np.array(30),
+ }
+ clean = [post_process(clean_joint_name(n, name)) for n in names]
+
+ (canon_anim, offsets, scale_factor, _gh, canon_parents, names_bfs,
+ _fps, bfs, face_idxs, baxis) = process_tpose(
+ tpos_data, face_joints=face_joints, target_diameter=target_diameter)
+ clean_bfs = [clean[i] for i in bfs]
+
+ cond = build_topology_cond(
+ name, canon_parents, offsets, names_bfs, clean_bfs,
+ positions_global(canon_anim)[0],
+ canon_anim.rotations.qs[0],
+ rotations_global(canon_anim).qs[0],
+ face_joint_idxs=face_idxs, body_axis=baxis,
+ scale_factor=scale_factor, ground_height=None)
+ logger.warning(
+ f"'{name}' has no animation: canonical skeleton = FULL armature "
+ f"({len(names_bfs)} joints, no motion-driven pruning) and no motion "
+ f"features are produced.")
+ return cond
+
+
+# ---------------------------------------------------------------------------
+# Stage 3: bake the canonical rest pose into the asset
+# ---------------------------------------------------------------------------
+
+def bake_canonical_asset(char_path, cond, out_base, formats=('glb',)):
+ """Rebuild the asset's armature to the cond's canonical T-pose and save.
+
+ The canonical skeleton (joint order, rest positions/orientations) is
+ taken verbatim from the topology cond so the baked asset and the motion
+ features agree by construction. The skinned mesh gets the same
+ similarity transform, so binding is untouched; asset bones outside the
+ motion skeleton are weight-merged away first.
+ """
+ names = list(cond['joint_names'])
+ canon_parents = [int(p) for p in cond['parents']]
+ canon_pos = np.asarray(cond['tpos_first_frame'], dtype=np.float64)
+ canon_mats = quat_pos_to_mats(
+ np.asarray(cond['tpos_global_rotations'], dtype=np.float64), canon_pos)
+
+ armature = load_character(char_path)
+ meshes = find_skinned_meshes(armature)
+ assert meshes, "No mesh with an Armature modifier targeting the asset's armature"
+
+ # The canonical asset holds ONLY the rigged character: drop unskinned
+ # props, lights, cameras, helper empties (e.g. the egg Icosphere in
+ # Truebones' Chicken-EggLaying) — they can't be driven by the motion and
+ # would linger as static junk in the export.
+ keep = {armature.name} | {m.name for m in meshes}
+ dropped = [o.name for o in bpy.context.scene.objects if o.name not in keep]
+ for name_ in dropped:
+ bpy.data.objects.remove(bpy.data.objects[name_], do_unlink=True)
+ if dropped:
+ logger.info(f"Dropped {len(dropped)} non-skinned scene object(s): {dropped[:6]}")
+
+ missing = [n for n in names if n not in armature.data.bones]
+ assert not missing, f"cond joints missing from the asset: {missing}"
+ sync_armature_bones(armature, names, extra_bones_strategy='merge')
+
+ # Similarity mapping Blender world -> canonical frame: the whole export +
+ # extract chain is one similarity of the world frame; fit it exactly on
+ # the bone heads and verify the residual.
+ arm_world = np.array(armature.matrix_world)
+ bones = armature.data.bones
+ world_pos = np.stack([
+ (arm_world @ np.array(bones[n].matrix_local))[:3, 3] for n in names])
+ M, _ = _umeyama(world_pos, canon_pos)
+ check = (np.concatenate([world_pos, np.ones((len(names), 1))], 1) @ M.T)[:, :3]
+ resid = np.abs(check - canon_pos).max() / max(np.abs(canon_pos).max(), 1e-9)
+ assert resid < 1e-4, (
+ f"world->canonical is not a clean similarity (residual {resid:.2e}); "
+ f"non-uniform armature scale, or the cond belongs to another asset?")
+ sim_scale = float(np.cbrt(abs(np.linalg.det(M[:3, :3]))))
+
+ # Transform every skinned mesh into the canonical frame. Un-parent BEFORE
+ # zeroing transforms: the meshes hang under the armature, so identity-ing
+ # the armature afterwards would shift any still-parented mesh again.
+ for mesh_obj in meshes:
+ T = M @ np.array(mesh_obj.matrix_world)
+ for vert in mesh_obj.data.vertices:
+ v = T @ np.array([*vert.co, 1.0])
+ vert.co = v[:3]
+ mesh_obj.data.update()
+ mesh_obj.parent = None
+ mesh_obj.matrix_world = Matrix.Identity(4)
+
+ # Rebuild the armature: canonical rest, canonical (BFS) bone order.
+ old_lengths = {n: bones[n].length for n in names}
+ bpy.context.view_layer.objects.active = armature
+ bpy.ops.object.mode_set(mode='EDIT')
+ edit_bones = armature.data.edit_bones
+ for eb in list(edit_bones):
+ edit_bones.remove(eb)
+ child_of = {p: j for j, p in enumerate(canon_parents) if p >= 0}
+ for j, name in enumerate(names):
+ eb = edit_bones.new(name)
+ eb.head = (0.0, 0.0, 0.0)
+ eb.tail = (0.0, 1.0, 0.0)
+ length = (np.linalg.norm(canon_pos[child_of[j]] - canon_pos[j])
+ if j in child_of else old_lengths[name] * sim_scale)
+ eb.matrix = Matrix(canon_mats[j].tolist())
+ eb.length = max(float(length), 1e-5)
+ for j, name in enumerate(names):
+ if canon_parents[j] >= 0:
+ eb = edit_bones[name]
+ eb.use_connect = False
+ eb.parent = edit_bones[names[canon_parents[j]]]
+ bpy.ops.object.mode_set(mode='OBJECT')
+ # ARMATURE-SPACE data stays exactly canonical (Y-up feature frame) — the
+ # cond-free animate math lives there. The +90°X OBJECT rotation stands
+ # the asset up in Blender's Z-up world; verified with an independent
+ # glTF evaluator, the exported file is upright BOTH in standard Y-up
+ # viewers and when re-imported into Blender.
+ yup_to_zup = Matrix.Rotation(math.radians(90.0), 4, 'X')
+ armature.matrix_world = yup_to_zup
+ for mesh_obj in meshes: # re-parent with identity LOCAL transforms
+ mesh_obj.parent = armature
+ mesh_obj.matrix_world = yup_to_zup.copy()
+
+ # Strip animation; store the canonical joint ORDER as an OBJECT-level
+ # custom property (glTF extras / FBX user properties) — importers do not
+ # keep bone enumeration order stable.
+ clear_animation_state(armature)
+ for obj in meshes:
+ if obj.animation_data:
+ obj.animation_data_clear()
+ # Unbinding is not enough: the glTF exporter's default animation mode
+ # exports every matchable ACTION datablock, bound or not — delete them
+ # all so the canonical asset is truly rest-only.
+ for action in list(bpy.data.actions):
+ bpy.data.actions.remove(action)
+ update_scene()
+ armature['canonical_joint_order'] = json.dumps(names)
+
+ select_objs([armature] + meshes, deselect_first=True)
+ for fmt in formats:
+ assert fmt in ('glb', 'fbx'), f"unsupported output format: {fmt}"
+ export_selected_to_file(f'{out_base}.{fmt}', fmt, custom_props=True)
+
+
+# ---------------------------------------------------------------------------
+# Full per-asset preprocessing
+# ---------------------------------------------------------------------------
+
+def preprocess_asset(char_path, output_dir, face_r=None, face_l=None,
+ body_axis=False, target_diameter=2.0, formats=('glb',),
+ save_vis=False, apply_clip=False, max_clip_len=10 ** 8,
+ keep_intermediate=False):
+ """Export + extract + bake one asset; see the module docstring."""
+ assert os.path.exists(char_path), f"Asset not found: {char_path}"
+ name = os.path.splitext(os.path.basename(char_path))[0]
+ os.makedirs(output_dir, exist_ok=True)
+
+ face_joints = None
+ if face_r and face_l:
+ face_joints = {'r_hip': {'raw': face_r}, 'l_hip': {'raw': face_l},
+ 'body_axis': body_axis}
+ else:
+ logger.info("No face joints given; identity facing (pipeline sentinel).")
+
+ # --- 1. Export stage (real pipeline; resumes via its own markers) ------
+ export_dir = os.path.join(output_dir, 'export')
+ export_asset(char_path, export_dir, save_name=name, save_vis=False)
+ npzs = sorted(glob.glob(os.path.join(export_dir, 'motions', f'{name}-*.npz')))
+
+ if npzs:
+ # --- 2a. Feature stage (real pipeline) ------------------------------
+ logger.info(f"Export stage: {len(npzs)} clip NPZ(s)")
+ tpos_data = np.load(npzs[0], allow_pickle=True) # first sorted = T-pose ref
+ raw_names = tpos_data['names'].tolist()
+ clean_names = [post_process(clean_joint_name(n, name)) for n in raw_names]
+
+ cond, n_clips, n_frames, n_joints, _filtered = process_object(
+ name, npzs, save_dir=output_dir,
+ face_joints=face_joints, clean_names=clean_names,
+ expected_names=raw_names,
+ apply_clip=apply_clip, max_clip_len=max_clip_len,
+ target_diameter=target_diameter, save_vis=save_vis)
+ assert cond is not None, ("feature extraction skipped this asset "
+ "(degenerate skeleton or no usable clips — see log)")
+ logger.info(f"Feature stage: {n_clips} clip(s), {n_frames} frames, "
+ f"{n_joints} joints")
+ else:
+ # --- 2b. Rest-only fallback: asset carries no animation -------------
+ cond = cond_from_rest(char_path, name, face_joints=face_joints,
+ target_diameter=target_diameter)
+
+ cond_path = os.path.join(output_dir, 'cond.npy')
+ np.save(cond_path, {name: cond})
+ logger.info(f"Saved cond -> {cond_path}")
+
+ # --- 3. Bake the canonical rest pose into the asset ---------------------
+ bake_canonical_asset(char_path, cond,
+ os.path.join(output_dir, f'{name}_canonical'),
+ formats=formats)
+
+ # --- 4. Keep only the three deliverables --------------------------------
+ if not keep_intermediate:
+ import shutil
+ for sub in ('export', 'tpose', 'videos', 'animations'):
+ shutil.rmtree(os.path.join(output_dir, sub), ignore_errors=True)
+ motions_dir = os.path.join(output_dir, 'motions')
+ if os.path.isdir(motions_dir) and not os.listdir(motions_dir):
+ os.rmdir(motions_dir) # rest-only run: no motion features
+ logger.info("Removed intermediates; kept: "
+ f"{name}_canonical.{{{','.join(formats)}}}, cond.npy, motions/")
+ return cond
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(
+ description="Preprocess a rigged, animated asset: export + feature "
+ "extraction + canonical rest-pose bake.")
+ parser.add_argument("--char_path", type=str, required=True,
+ help="Rigged asset GLB/FBX (mesh + armature + weights). "
+ "Assets WITH actions get the full pipeline incl. "
+ "motion-driven skeleton pruning and motion features; "
+ "action-less assets fall back to a rest-only cond "
+ "(full skeleton, no motions/).")
+ parser.add_argument("--output_dir", type=str, required=True,
+ help="Output directory (export/, motions/, cond.npy, "
+ "<name>_canonical.{glb,fbx}).")
+ parser.add_argument("--face_r", type=str, default=None,
+ help="Raw name of the right face joint (facing canonicalization).")
+ parser.add_argument("--face_l", type=str, default=None,
+ help="Raw name of the left face joint.")
+ parser.add_argument("--body_axis", action='store_true',
+ help="Face pair is a head/tail body axis (serpentine rigs).")
+ parser.add_argument("--target_diameter", type=float, default=2.0,
+ help="Canonical skeleton diameter (pipeline default: 2.0).")
+ parser.add_argument("--formats", type=str, default='glb',
+ help="Comma-separated canonical-asset formats (glb,fbx).")
+ parser.add_argument("--save_vis", action='store_true',
+ help="Also render per-clip preview MP4s (slow).")
+ parser.add_argument("--apply_clip", action='store_true',
+ help="Crop motions into overlapping training-length clips "
+ "instead of one full-length feature NPZ per motion.")
+ parser.add_argument("--keep_intermediate", action='store_true',
+ help="Keep export/ NPZs and T-pose/preview visuals (default: "
+ "only canonical asset + cond.npy + motions/ remain).")
+ return parse_blender_argv(parser)
+
+
+if __name__ == "__main__":
+ args = parse_args()
+ preprocess_asset(
+ char_path=args.char_path,
+ output_dir=args.output_dir,
+ face_r=args.face_r,
+ face_l=args.face_l,
+ body_axis=args.body_axis,
+ target_diameter=args.target_diameter,
+ formats=tuple(f.strip().lower() for f in args.formats.split(',') if f.strip()),
+ save_vis=args.save_vis,
+ apply_clip=args.apply_clip,
+ keep_intermediate=args.keep_intermediate,
+ )
diff --git a/data_process/scripts/run_animate_lbs.sh b/data_process/scripts/run_animate_lbs.sh
new file mode 100644
index 0000000..d52280b
--- /dev/null
+++ b/data_process/scripts/run_animate_lbs.sh
@@ -0,0 +1,41 @@
+#!/bin/bash
+# Stage 5 — deform a rigged asset with a motion NPZ via manual NumPy LBS and
+# save the vertex animation (NPZ, optionally per-frame OBJ).
+#
+# Accepts both motion flavors (auto-detected): export-stage NPZ, or
+# feature-format (generated) NPZ — the latter needs DATASET_TYPE.
+#
+# Usage:
+# CHAR_PATH=asset.glb ANIM_PATH=clip.npz bash data_process/scripts/run_animate_lbs.sh
+# CHAR_PATH=asset.glb ANIM_PATH=gen.npz DATASET_TYPE=objaverse bash data_process/scripts/run_animate_lbs.sh
+#
+# Env overrides:
+# CHAR_PATH (required — rigged asset GLB/FBX with skinning weights)
+# ANIM_PATH (required — motion NPZ, or a directory of NPZs: one output
+# set per action clip)
+# DATASET_TYPE truebones|objaverse|mixamo (feature-format motion only)
+# COND_PATH cond.npy override (feature-format motion only)
+# OUTPUT_DIR (default: outputs/lbs)
+# SAVE comma-separated: glb,fbx,npz,obj (default: glb)
+# glb/fbx = animated rigged asset via the animate_npz keyframe path
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+
+handle_help "$@"
+
+CHAR_PATH=${CHAR_PATH:?Set CHAR_PATH to a rigged asset GLB/FBX}
+ANIM_PATH=${ANIM_PATH:?Set ANIM_PATH to a motion NPZ}
+OUTPUT_DIR=${OUTPUT_DIR:-outputs/lbs}
+SAVE=${SAVE:-glb}
+
+EXTRA_ARGS=()
+[[ -n "${DATASET_TYPE:-}" ]] && EXTRA_ARGS+=(--dataset_type="$DATASET_TYPE")
+[[ -n "${COND_PATH:-}" ]] && EXTRA_ARGS+=(--cond_path="$COND_PATH")
+
+blender -b -P data_process/mesh_animation/animate_lbs.py -- \
+ --char_path="$CHAR_PATH" \
+ --anim_path="$ANIM_PATH" \
+ --output_dir="$OUTPUT_DIR" \
+ --save="$SAVE" \
+ "${EXTRA_ARGS[@]}" "$@"
diff --git a/data_process/scripts/run_preprocess_char.sh b/data_process/scripts/run_preprocess_char.sh
new file mode 100644
index 0000000..cea44c0
--- /dev/null
+++ b/data_process/scripts/run_preprocess_char.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+# Stage 5 — preprocess one rigged, animated asset through the real export +
+# feature pipeline. Leaves exactly three deliverables in OUTPUT_DIR:
+# <name>_canonical.{glb,fbx} canonical rest-pose asset
+# cond.npy model-side topology conditioning
+# motions/<clip>.npz motion features
+# Feature NPZs then drive the canonical asset cond-free via run_animate_lbs.sh.
+# (KEEP_INTERMEDIATE=1 keeps the export-stage NPZs and visuals.)
+#
+# Usage:
+# CHAR_PATH=asset.glb OUTPUT_DIR=outputs/asset \
+# FACE_R=R_Thigh FACE_L=L_Thigh FORMATS=glb,fbx \
+# bash data_process/scripts/run_preprocess_char.sh
+#
+# Env overrides:
+# CHAR_PATH (required — rigged, ANIMATED asset GLB/FBX)
+# OUTPUT_DIR (required — export/, motions/, cond.npy, <name>_canonical.*)
+# FACE_R/FACE_L raw face-joint names for facing canonicalization
+# BODY_AXIS=1 face pair is a head/tail body axis (serpentine rigs)
+# FORMATS comma-separated canonical formats (default: glb)
+# SAVE_VIS=1 also render per-clip preview MP4s
+# APPLY_CLIP=1 crop motions into training-length clips
+# KEEP_INTERMEDIATE=1 keep export-stage NPZs and T-pose/preview visuals
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+
+handle_help "$@"
+
+CHAR_PATH=${CHAR_PATH:?Set CHAR_PATH to a rigged, animated asset GLB/FBX}
+OUTPUT_DIR=${OUTPUT_DIR:?Set OUTPUT_DIR for the preprocessed outputs}
+
+EXTRA_ARGS=()
+[[ -n "${FACE_R:-}" ]] && EXTRA_ARGS+=(--face_r="$FACE_R")
+[[ -n "${FACE_L:-}" ]] && EXTRA_ARGS+=(--face_l="$FACE_L")
+[[ -n "${BODY_AXIS:-}" ]] && EXTRA_ARGS+=(--body_axis)
+[[ -n "${FORMATS:-}" ]] && EXTRA_ARGS+=(--formats="$FORMATS")
+[[ -n "${SAVE_VIS:-}" ]] && EXTRA_ARGS+=(--save_vis)
+[[ -n "${APPLY_CLIP:-}" ]] && EXTRA_ARGS+=(--apply_clip)
+[[ -n "${KEEP_INTERMEDIATE:-}" ]] && EXTRA_ARGS+=(--keep_intermediate)
+
+blender -b -P data_process/mesh_animation/preprocess_char.py -- \
+ --char_path="$CHAR_PATH" \
+ --output_dir="$OUTPUT_DIR" \
+ "${EXTRA_ARGS[@]}" "$@"
diff --git a/data_process/utils/blender_rig.py b/data_process/utils/blender_rig.py
index 8a3ff4a..79a3ecc 100644
--- a/data_process/utils/blender_rig.py
+++ b/data_process/utils/blender_rig.py
@@ -635,14 +635,20 @@ def export_animated_character(output_path_no_ext, formats=('glb',)):
export_selected_to_file(f"{output_path_no_ext}.{fmt}", fmt)
-def export_selected_to_file(filepath, char_anim_type='glb'):
- """Export currently-selected scene objects to GLB or FBX."""
+def export_selected_to_file(filepath, char_anim_type='glb', custom_props=False):
+ """Export currently-selected scene objects to GLB or FBX.
+
+ ``custom_props`` also exports object-level custom properties (glTF
+ extras / FBX user properties) — used by ``preprocess_char`` to carry the
+ canonical joint order inside the asset.
+ """
if char_anim_type == 'glb':
bpy.ops.export_scene.gltf(
filepath=filepath,
check_existing=False,
use_selection=True,
export_format='GLB',
+ export_extras=custom_props,
# Export the action's own F-curves rather than resampling every
# object: sampling also bakes the armature *object's* static
# transform into a stray second glTF animation.
@@ -665,6 +671,7 @@ def export_selected_to_file(filepath, char_anim_type='glb'):
bake_anim=True,
path_mode="COPY",
embed_textures=True,
+ use_custom_props=custom_props,
)
else:
raise RuntimeError(f"Invalid char_anim_type: {char_anim_type}")