Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(env): add GCS_RESULT_BUCKETS for GPU worker uploads and enhance provider URL validation feat(avatar): refine avatar prompt for clearer face detection in reconstruction fix(rig): ensure world transforms are baked into geometry for skinned meshes chore(rig): update staging script to include demo data and improve asset handling test(rig): add tests for non-identity node transforms and divergent instances

nirholasb53b7205c3b0
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 3c53e451d..89bbf2aef 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -284,6 +284,19 @@ export const env = {
return trimSlash(req('S3_PUBLIC_DOMAIN'));
},
+ // GCS buckets our own GPU workers (avatar-reconstruction, unirig, remesh,
+ // stylize, model-*) upload result GLBs to. Consumed by the provider-result
+ // URL allowlist: a storage.googleapis.com result URL is only accepted when
+ // its bucket is in this set, so a forged provider payload cannot point the
+ // server at an arbitrary third-party bucket. Comma-separated; defaults to
+ // the production fleet's shared output bucket.
+ get GCS_RESULT_BUCKETS() {
+ return opt('GCS_RESULT_BUCKETS', 'three-ws-avatar-reconstructions')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean);
+ },
+
// Resolved as an atomic pair (see pickPair) so URL and token always come from
// the SAME Upstash store — never a store-A URL with a store-B token (WRONGPASS).
get UPSTASH_REDIS_REST_URL() {
diff --git a/api/_lib/provider-result-url.js b/api/_lib/provider-result-url.js
index ef6c32a9b..0430d000b 100644
--- a/api/_lib/provider-result-url.js
+++ b/api/_lib/provider-result-url.js
@@ -68,6 +68,34 @@ function ownPublicHost() {
}
}
+// Our own GPU workers (the `gcp` provider: avatar-reconstruction, unirig,
+// remesh, stylize, model-*) upload their result GLBs to Cloud Storage and
+// report plain `https://storage.googleapis.com/<bucket>/<object>` URLs. The
+// host alone is NOT a safe allowlist entry: anyone can create a GCS bucket, so
+// accepting the whole host would let a forged payload aim the fetch at an
+// attacker-controlled object. Pin acceptance to OUR buckets (env
+// GCS_RESULT_BUCKETS), matching both URL styles GCS serves:
+// path style: https://storage.googleapis.com/<bucket>/<object>
+// virtual-hosted style: https://<bucket>.storage.googleapis.com/<object>
+function isOwnGcsResultUrl(u) {
+ let buckets;
+ try {
+ buckets = env.GCS_RESULT_BUCKETS;
+ } catch {
+ return false;
+ }
+ if (!buckets?.length) return false;
+ const host = u.hostname.toLowerCase();
+ if (host === 'storage.googleapis.com') {
+ const bucket = u.pathname.split('/').filter(Boolean)[0] ?? '';
+ return buckets.includes(bucket);
+ }
+ if (host.endsWith('.storage.googleapis.com')) {
+ return buckets.includes(host.slice(0, -'.storage.googleapis.com'.length));
+ }
+ return false;
+}
+
// Narrow positive gate — exactly the webhook's original semantics: parse, require
// https, lowercase the host, and accept an exact or `.`-suffix match against the
// allowed hosts (the provider delivery hosts ∪ our own CDN host). Never throws;
@@ -81,6 +109,7 @@ export function isAllowedProviderResultUrl(raw) {
return false;
}
if (u.protocol !== 'https:') return false;
+ if (isOwnGcsResultUrl(u)) return true;
const host = u.hostname.toLowerCase();
const own = ownPublicHost();
const allowed = own ? [...PROVIDER_RESULT_HOSTS, own] : PROVIDER_RESULT_HOSTS;
diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.js
index bbd3f5155..409dea8da 100644
--- a/api/_lib/solana-signers.js
+++ b/api/_lib/solana-signers.js
@@ -56,20 +56,23 @@ export const SOLANA_SIGNERS = [
name: 'pump-x402-launcher',
env: 'PUMP_X402_LAUNCHER_SECRET_KEY_B64',
minSol: 0.1,
- // CRITICAL: this env resolves to the SAME physical wallet as the x402 ring
- // TREASURY / receiver (X402_PAY_TO_SOLANA / X402_TREASURY_SECRET_BASE58 →
- // secret `wallet-x402-treasury-b64`, pubkey wwwww…ccrU). That wallet holds
- // the ring's live USDC float and platform x402 revenue. Without holdsTokens,
- // the excess-mode treasury-sweepback consolidated its USDC up to the master
- // AND closed its USDC ATA every run — so every following ring settle had to
- // recreate the ATA at ~2,039,280 lamports of rent, which is what dragged the
- // per-settle fee to ~570k lamports (114× the 5k self-pay floor) and quietly
- // drained the closed loop's float into the master. holdsTokens keeps the
- // ring float where the ring's own rebalancer (treasury→payer) can
- // recirculate it; only an explicit drain may still consolidate it.
+ // CRITICAL — do NOT remove holdsTokens. This env resolves to the SAME physical
+ // wallet as the x402 ring TREASURY / receiver (X402_PAY_TO_SOLANA /
+ // X402_TREASURY_SECRET_BASE58 → secret `wallet-x402-treasury-b64`, pubkey
+ // wwwww…ccrU). Its LIVE, load-bearing role is the treasury: it holds the ring's
+ // USDC float + platform x402 revenue and signs the rebalancer's treasury→payer
+ // sweeps (so it keeps a SOL floor). The pump.fun x402 launch role that named
+ // this entry is not in active use. Without holdsTokens, the excess-mode
+ // treasury-sweepback consolidated its USDC up to the master AND closed its USDC
+ // ATA every run — so every following ring settle recreated the ATA at ~2,039,280
+ // lamports of rent, dragging the per-settle fee to ~570k lamports (114× the 5k
+ // self-pay floor) and draining the closed loop's float into the master. It reads
+ // like "just a launcher fee wallet" that wouldn't need holdsTokens — it is not.
+ // holdsTokens keeps the ring float where the rebalancer can recirculate it; only
+ // an explicit drain may still consolidate it.
holdsTokens: true,
purpose:
- 'fronts the ~0.022 SOL deploy cost for x402 pay-per-call pump.fun launches; ALSO the x402 ring treasury/receiver (holds USDC revenue + ring float) — holdsTokens protects it from excess-mode sweepback',
+ 'x402 ring treasury/receiver (pubkey wwwww…ccrU): holds USDC revenue + the ring float and signs treasury→payer sweeps; keeps a SOL floor for those fees. holdsTokens protects its USDC from excess-mode sweepback. (Legacy name: also the pump.fun x402 launch fee wallet, a role not in active use.)',
network: 'mainnet',
},
{
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 7a74e7bdc..122f54af2 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -1028,8 +1028,11 @@ const reconstructSchema = z
// Steer Flux toward a single, evenly-lit, full-figure humanoid on a plain
// background — that composition reconstructs and auto-rigs far more reliably
// than a busy scene — without overriding the user's own subject description.
+// "clear detailed face" matters: the gcp reconstruct lane is a face pipeline
+// (it warps the render's face onto a template body), so a render whose face is
+// obscured or featureless fails detection outright.
const AVATAR_PROMPT_SUFFIX =
- ', full body character, standing in a relaxed A-pose, facing forward, centered in frame, entire figure visible from head to feet, plain neutral studio background, soft even lighting, single subject, high detail, game-ready character render';
+ ', full body character, standing in a relaxed A-pose, facing forward with a clear detailed face, centered in frame, entire figure visible from head to feet, plain neutral studio background, soft even lighting, single subject, high detail, game-ready character render';
const handleReconstruct = wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
diff --git a/tests/provider-result-url.test.js b/tests/provider-result-url.test.js
index 5f4cfe84e..d0cf0a332 100644
--- a/tests/provider-result-url.test.js
+++ b/tests/provider-result-url.test.js
@@ -116,6 +116,60 @@ describe('isAllowedProviderResultUrl — host allowlist (webhook semantics)', ()
});
});
+describe('isAllowedProviderResultUrl — own GCS result buckets (gcp workers)', () => {
+ // The env getter reads process.env at call time, so each test can set the
+ // bucket list and restore it after.
+ let savedBuckets;
+ beforeEach(() => {
+ savedBuckets = process.env.GCS_RESULT_BUCKETS;
+ return () => {
+ if (savedBuckets === undefined) delete process.env.GCS_RESULT_BUCKETS;
+ else process.env.GCS_RESULT_BUCKETS = savedBuckets;
+ };
+ });
+
+ it('accepts a path-style URL for the default production bucket', () => {
+ delete process.env.GCS_RESULT_BUCKETS;
+ expect(
+ isAllowedProviderResultUrl(
+ 'https://storage.googleapis.com/three-ws-avatar-reconstructions/reconstruct/x.glb',
+ ),
+ ).toBe(true);
+ });
+
+ it('accepts virtual-hosted-style URLs for an allowed bucket', () => {
+ process.env.GCS_RESULT_BUCKETS = 'bucket-a, bucket-b';
+ expect(
+ isAllowedProviderResultUrl('https://bucket-a.storage.googleapis.com/out/x.glb'),
+ ).toBe(true);
+ expect(
+ isAllowedProviderResultUrl('https://storage.googleapis.com/bucket-b/out/x.glb'),
+ ).toBe(true);
+ });
+
+ it('rejects any bucket not in the allowlist (host alone is never enough)', () => {
+ process.env.GCS_RESULT_BUCKETS = 'bucket-a';
+ expect(
+ isAllowedProviderResultUrl('https://storage.googleapis.com/attacker-bucket/x.glb'),
+ ).toBe(false);
+ expect(
+ isAllowedProviderResultUrl('https://attacker-bucket.storage.googleapis.com/x.glb'),
+ ).toBe(false);
+ // No object path at all: no bucket to match.
+ expect(isAllowedProviderResultUrl('https://storage.googleapis.com/')).toBe(false);
+ });
+
+ it('rejects look-alike hosts and http downgrades', () => {
+ process.env.GCS_RESULT_BUCKETS = 'bucket-a';
+ expect(
+ isAllowedProviderResultUrl('https://storage.googleapis.com.evil.com/bucket-a/x.glb'),
+ ).toBe(false);
+ expect(
+ isAllowedProviderResultUrl('http://storage.googleapis.com/bucket-a/x.glb'),
+ ).toBe(false);
+ });
+});
+
describe('assertProviderResultUrl', () => {
it('returns the url on an allowed host', () => {
const u = 'https://pbxt.replicate.delivery/x.glb';
diff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.py
index 0bef527c5..f29e7e387 100644
--- a/workers/avatar-reconstruction/face_pipeline.py
+++ b/workers/avatar-reconstruction/face_pipeline.py
@@ -147,6 +147,70 @@ def _get_landmarks(img: Image.Image) -> Optional[list]:
return None
+class _Landmark:
+ """Minimal stand-in for a MediaPipe NormalizedLandmark (x, y, z attributes)."""
+
+ __slots__ = ("x", "y", "z")
+
+ def __init__(self, x: float, y: float, z: float):
+ self.x, self.y, self.z = x, y, z
+
+
+def _get_landmarks_small_face(img: Image.Image) -> Optional[list]:
+ """
+ Rescue pass for images whose face is too small for FaceMesh's built-in
+ detector: full-body renders (the text-to-avatar lane generates head-to-feet
+ reference images) and selfies taken at a distance. BlazeFace's full-range
+ model still finds those small faces; crop around its box with generous
+ margin, upscale the crop to a size FaceMesh is reliable at, run FaceMesh on
+ the crop, then map the landmarks back to full-image normalised coordinates
+ so every downstream consumer (UV warp, skin/hair/eye sampling) is untouched.
+ """
+ arr = np.array(img)
+ with mp.solutions.face_detection.FaceDetection(
+ model_selection=1, # full-range model: small faces in wide shots
+ min_detection_confidence=0.3,
+ ) as fd:
+ det = fd.process(arr)
+ if not det.detections:
+ return None
+ box = max(det.detections, key=lambda d: d.score[0]).location_data.relative_bounding_box
+
+ img_w, img_h = img.size
+ # FaceMesh needs forehead / chin / ear context around the raw face box.
+ margin = 0.75
+ left = int(max(0.0, box.xmin - box.width * margin) * img_w)
+ top = int(max(0.0, box.ymin - box.height * margin) * img_h)
+ right = int(min(1.0, box.xmin + box.width * (1 + margin)) * img_w)
+ bottom = int(min(1.0, box.ymin + box.height * (1 + margin)) * img_h)
+ crop_w, crop_h = right - left, bottom - top
+ if crop_w < 8 or crop_h < 8:
+ return None
+
+ crop = img.crop((left, top, right, bottom))
+ scale = 512 / min(crop_w, crop_h)
+ if scale > 1.0:
+ crop = crop.resize(
+ (max(1, round(crop_w * scale)), max(1, round(crop_h * scale))),
+ Image.LANCZOS,
+ )
+
+ crop_landmarks = _get_landmarks(crop)
+ if crop_landmarks is None:
+ return None
+ # Landmark coords are normalised to the crop; renormalise to the full image.
+ # z is normalised by image width like x, so rescale it proportionally (it is
+ # only used for the frontality heuristic, never for geometry).
+ return [
+ _Landmark(
+ (left + lm.x * crop_w) / img_w,
+ (top + lm.y * crop_h) / img_h,
+ lm.z * (crop_w / img_w),
+ )
+ for lm in crop_landmarks
+ ]
+
+
# ── background removal ─────────────────────────────────────────────────────────
def _remove_background(img: Image.Image) -> Image.Image:
@@ -402,6 +466,16 @@ def process(
if landmarks is None:
# No face detected in any image — try harder on the first image.
landmarks = _get_landmarks(images[0])
+ if landmarks is None:
+ # Small-face rescue: full-body renders and distant selfies defeat
+ # FaceMesh's detector but not BlazeFace's full-range model. Crop, zoom,
+ # and retry on each image until one yields landmarks.
+ for idx, img in enumerate(images):
+ landmarks = _get_landmarks_small_face(img)
+ if landmarks is not None:
+ best_img = img
+ log.info("[%s] small-face rescue succeeded on image %d", job_id, idx)
+ break
if landmarks is None:
raise ValueError("no face detected in any of the provided photos")
log.info("[%s] face selected (%.1fs)", job_id, time.time() - t0)
diff --git a/workers/rig/Dockerfile b/workers/rig/Dockerfile
index 08e7bb702..b30b947a8 100644
--- a/workers/rig/Dockerfile
+++ b/workers/rig/Dockerfile
@@ -8,7 +8,10 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
DEBIAN_FRONTEND=noninteractive \
- MPLBACKEND=Agg
+ MPLBACKEND=Agg \
+ GRADIO_ANALYTICS_ENABLED=False \
+ HF_HUB_DISABLE_TELEMETRY=1 \
+ DO_NOT_TRACK=1
RUN apt-get update && apt-get install -y --no-install-recommends \
python3.11 python3.11-dev python3.11-venv python3-pip \
diff --git a/workers/rig/cloudbuild.yaml b/workers/rig/cloudbuild.yaml
index e43b1dcdc..6f1f5a2b2 100644
--- a/workers/rig/cloudbuild.yaml
+++ b/workers/rig/cloudbuild.yaml
@@ -56,6 +56,10 @@ steps:
- --min-instances=${_MIN_INSTANCES}
- --max-instances=${_MAX_INSTANCES}
- --timeout=900
+ # Model init (bpy kinematic trees + ~2.4 GB of checkpoints) takes a few
+ # minutes; the default 4-minute startup window killed healthy instances.
+ - --startup-probe=tcpSocket.port=8080,initialDelaySeconds=0,periodSeconds=60,timeoutSeconds=60,failureThreshold=15
+ - --cpu-boost
- --allow-unauthenticated
- --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}
- --add-volume-mount=volume=weights,mount-path=/weights
diff --git a/workers/rig/engine_mia.py b/workers/rig/engine_mia.py
index 1e3500277..29fd20e4d 100644
--- a/workers/rig/engine_mia.py
+++ b/workers/rig/engine_mia.py
@@ -53,6 +53,23 @@ def init() -> None:
import app as mia_app # noqa: PLC0415 (heavy import by design, once)
+ # MIA replaces gradio.helpers.log_message with a version that reads
+ # LocalContext.blocks.get(); on current gradio that ContextVar has no
+ # default, so every Timing(print_fn=gr.Info) raises LookupError outside a
+ # live Gradio request. Re-replace it with a print-only logger: this
+ # service has no UI to toast to.
+ import warnings # noqa: PLC0415
+
+ import gradio.helpers # noqa: PLC0415
+
+ def _headless_log(message, level="info", *args, **kwargs):
+ if level == "warning":
+ warnings.warn(message)
+ else:
+ print(message)
+
+ gradio.helpers.log_message = _headless_log
+
mia_app.init_models()
# The stage functions return Gradio component-update dicts keyed by UI
# globals that only exist after init_blocks(); build the (unlaunched)
diff --git a/workers/rig/entrypoint.sh b/workers/rig/entrypoint.sh
index 6cad9a208..8fddf789e 100755
--- a/workers/rig/entrypoint.sh
+++ b/workers/rig/entrypoint.sh
@@ -1,13 +1,20 @@
#!/bin/sh
-# Wire the GCS-FUSE weights mount into the Make-It-Animatable checkout, then
-# serve. The mount (see cloudbuild.yaml) exposes the bucket at /weights; MIA
-# resolves its checkpoints and Mixamo templates relative to its own tree.
+# Wire staged assets into the Make-It-Animatable checkout, then serve.
+#
+# The weights bucket is FUSE-mounted at /weights (see cloudbuild.yaml), but the
+# checkpoints are COPIED to local disk rather than symlinked: torch.load over
+# gcsfuse does slow random reads and blew past the startup probe (the same
+# lesson the hunyuan3d worker learned). A sequential cp of ~2.4 GB takes
+# seconds; loading from local disk is then fast and deterministic.
set -eu
WEIGHTS_ROOT="${WEIGHTS_ROOT:-/weights/make-it-animatable}"
MIA_DIR="${MIA_DIR:-/app/mia}"
-for rel in output/best/new data/Mixamo; do
+# data/ carries the Mixamo bone templates plus the demo files (Standard
+# Run.fbx, examples/) that MIA's init_blocks() resolves at import; missing
+# demo files abort startup, so the whole staged data tree comes along.
+for rel in output/best/new data; do
src="$WEIGHTS_ROOT/$rel"
dst="$MIA_DIR/$rel"
if [ ! -e "$src" ]; then
@@ -16,13 +23,13 @@ for rel in output/best/new data/Mixamo; do
fi
mkdir -p "$(dirname "$dst")"
rm -rf "$dst"
- ln -s "$src" "$dst"
+ echo "staging $src -> $dst"
+ cp -r "$src" "$dst"
done
if [ ! -f "${ARKIT_TEMPLATE:-/app/assets/arkit_template.npz}" ]; then
- # The template also lives in the weights bucket; link it into place.
mkdir -p /app/assets
- ln -sf "$WEIGHTS_ROOT/arkit_template.npz" /app/assets/arkit_template.npz
+ cp "$WEIGHTS_ROOT/arkit_template.npz" /app/assets/arkit_template.npz
fi
exec uvicorn main:app --host 0.0.0.0 --port 8080 --workers 1 --timeout-keep-alive 300
diff --git a/workers/rig/rig_glb.py b/workers/rig/rig_glb.py
index 9d7cf5944..b55150b82 100644
--- a/workers/rig/rig_glb.py
+++ b/workers/rig/rig_glb.py
@@ -18,8 +18,10 @@ What `build_rigged_glb` produces, preserving all original geometry/materials:
Robustness: model output is sanitized (NaN/Inf/negative weights dropped), every
vertex is guaranteed a unit weight sum (no skinning collapse), JOINTS_0 uses the
-smallest legal integer width, and a non-identity skinned-node transform (which
-would silently misplace the skeleton) fails loudly instead of corrupting output.
+smallest legal integer width, a non-identity drawing-node transform is BAKED
+into world-space geometry (glTF ignores a skinned node's own transform, so
+local-space vertices would render misplaced), and a mesh instanced under
+divergent transforms fails loudly instead of corrupting output.
This file began as workers/unirig/rig_glb.py and generalizes it: the caller
supplies explicit `joint_names` (the rig worker passes Mixamo names, which the
@@ -88,24 +90,77 @@ def _add_accessor(glb, view: int, comp: int, count: int, typ: str,
return len(glb.accessors) - 1
-def _read_positions(glb, blob: bytearray, acc_idx: int) -> np.ndarray:
- """Decode a VEC3/FLOAT POSITION accessor from the binary buffer. Handles
- both tightly packed and interleaved (byteStride) layouts, vectorized."""
+def _read_float_attr(glb, blob: bytearray, acc_idx: int, what: str) -> np.ndarray:
+ """Decode a float VEC3/VEC4 accessor from the binary buffer. Handles both
+ tightly packed and interleaved (byteStride) layouts, vectorized."""
acc = glb.accessors[acc_idx]
- if acc.componentType != _GLTF_FLOAT or acc.type != "VEC3":
+ ncomp = {"VEC3": 3, "VEC4": 4}.get(acc.type)
+ if acc.componentType != _GLTF_FLOAT or ncomp is None:
raise RuntimeError(
- f"unsupported POSITION accessor (componentType={acc.componentType}, type={acc.type}); "
- "skinning expects float32 VEC3 positions"
+ f"unsupported {what} accessor (componentType={acc.componentType}, type={acc.type}); "
+ "expected float32 VEC3/VEC4"
)
+ width = 4 * ncomp
bv = glb.bufferViews[acc.bufferView]
base = (bv.byteOffset or 0) + (acc.byteOffset or 0)
n = acc.count
- stride = bv.byteStride or 12
- if stride == 12:
- return np.frombuffer(bytes(blob[base:base + 12 * n]), dtype="<f4").reshape(n, 3).copy()
- # Interleaved: lift the first 12 bytes (the VEC3) out of each stride slot.
+ stride = bv.byteStride or width
+ if stride == width:
+ return np.frombuffer(bytes(blob[base:base + width * n]), dtype="<f4").reshape(n, ncomp).copy()
+ # Interleaved: lift the attribute's bytes out of each stride slot.
raw = np.frombuffer(bytes(blob[base:base + stride * n]), dtype=np.uint8).reshape(n, stride)
- return raw[:, :12].copy().view("<f4").reshape(n, 3)
+ return raw[:, :width].copy().view("<f4").reshape(n, ncomp)
+
+
+def _read_positions(glb, blob: bytearray, acc_idx: int) -> np.ndarray:
+ return _read_float_attr(glb, blob, acc_idx, "POSITION")
+
+
+def _write_vec_accessor(glb, blob: bytearray, data: np.ndarray) -> int:
+ """Append a float VEC3/VEC4 accessor holding `data` and return its index."""
+ data = np.ascontiguousarray(data.astype(np.float32))
+ typ = "VEC3" if data.shape[1] == 3 else "VEC4"
+ return _add_accessor(
+ glb, _append_view(glb, blob, data.tobytes(), _GLTF_ARRAY_BUFFER),
+ _GLTF_FLOAT, data.shape[0], typ,
+ mn=data.min(axis=0).tolist(), mx=data.max(axis=0).tolist())
+
+
+def _bake_world_transform(glb, blob: bytearray, prim, wm: np.ndarray) -> np.ndarray:
+ """Bake the drawing node's world transform into a primitive's geometry.
+
+ glTF ignores a skinned node's own transform: vertices must live in the
+ same space as the skeleton (world). Positions, normals, and tangents are
+ rewritten into NEW accessors (never in place, so accessors shared with
+ other meshes stay untouched). Returns the world-space positions."""
+ rot = wm[:3, :3]
+ # Normals transform by the inverse-transpose of the linear part.
+ try:
+ nrm_mat = np.linalg.inv(rot).T
+ except np.linalg.LinAlgError as exc:
+ raise RuntimeError("mesh node transform is singular; cannot bake") from exc
+
+ pos = _read_positions(glb, blob, prim.attributes.POSITION)
+ world_pos = pos @ rot.T + wm[:3, 3]
+ prim.attributes.POSITION = _write_vec_accessor(glb, blob, world_pos)
+
+ nrm_acc = getattr(prim.attributes, "NORMAL", None)
+ if nrm_acc is not None:
+ nrm = _read_float_attr(glb, blob, nrm_acc, "NORMAL") @ nrm_mat.T
+ norms = np.linalg.norm(nrm, axis=1, keepdims=True)
+ nrm = np.divide(nrm, norms, out=np.zeros_like(nrm), where=norms > 1e-12)
+ prim.attributes.NORMAL = _write_vec_accessor(glb, blob, nrm)
+
+ tan_acc = getattr(prim.attributes, "TANGENT", None)
+ if tan_acc is not None:
+ tan = _read_float_attr(glb, blob, tan_acc, "TANGENT")
+ txyz = tan[:, :3] @ rot.T
+ norms = np.linalg.norm(txyz, axis=1, keepdims=True)
+ txyz = np.divide(txyz, norms, out=np.zeros_like(txyz), where=norms > 1e-12)
+ prim.attributes.TANGENT = _write_vec_accessor(
+ glb, blob, np.concatenate([txyz, tan[:, 3:4]], axis=1))
+
+ return world_pos
def _quat_to_mat3(x, y, z, w):
@@ -299,25 +354,29 @@ def build_rigged_glb(mesh_bytes, mesh, joints, parents, weights,
skinned_any = False
for mi, gmesh in enumerate(glb.meshes):
nodes = mesh_to_nodes.get(mi, [])
- # Joints are world-space; if the drawing node carries a transform, the
- # primitive's local positions live in a different frame. Honor that for
- # weight matching, and refuse a non-identity transform we can't bake
- # into the bind pose (our generators export identity, so this is a
- # loud guard, not a silent corruption).
- wm = world_mats[nodes[0]] if nodes else np.eye(4)
- if not np.allclose(wm, np.eye(4), atol=1e-4):
+ # Joints are world-space, and glTF ignores a skinned node's own
+ # transform, so a mesh drawn under a non-identity transform gets that
+ # transform BAKED into fresh geometry accessors. A mesh instanced by
+ # several nodes with DIFFERENT world transforms cannot be skinned to
+ # one world-space skeleton: that stays a loud error.
+ node_mats = [world_mats[ni] for ni in nodes] or [np.eye(4)]
+ wm = node_mats[0]
+ if any(not np.allclose(m, wm, atol=1e-4) for m in node_mats[1:]):
raise RuntimeError(
- f"mesh {mi} is drawn by a node with a non-identity transform; "
- "bake the transform into the geometry before rigging"
+ f"mesh {mi} is instanced by nodes with different transforms; "
+ "cannot rig one skeleton across divergent instances"
)
+ bake = not np.allclose(wm, np.eye(4), atol=1e-4)
mesh_targets = 0
for prim in gmesh.primitives:
pos_acc = getattr(prim.attributes, "POSITION", None)
if pos_acc is None:
continue
- verts = _read_positions(glb, blob, pos_acc) # (M,3) primitive order
- world_pos = verts @ wm[:3, :3].T + wm[:3, 3]
+ if bake:
+ world_pos = _bake_world_transform(glb, blob, prim, wm)
+ else:
+ world_pos = _read_positions(glb, blob, pos_acc) # (M,3) primitive order
_, nearest = kdt.query(world_pos, k=1) # (M,) -> mesh vertex index
nearest = np.asarray(nearest).reshape(-1)
@@ -325,10 +384,10 @@ def build_rigged_glb(mesh_bytes, mesh, joints, parents, weights,
w0 = np.ascontiguousarray(top_w[nearest].astype(np.float32))
prim.attributes.JOINTS_0 = _add_accessor(
glb, _append_view(glb, blob, j0.tobytes(), _GLTF_ARRAY_BUFFER),
- joint_comp, verts.shape[0], "VEC4")
+ joint_comp, world_pos.shape[0], "VEC4")
prim.attributes.WEIGHTS_0 = _add_accessor(
glb, _append_view(glb, blob, w0.tobytes(), _GLTF_ARRAY_BUFFER),
- _GLTF_FLOAT, verts.shape[0], "VEC4")
+ _GLTF_FLOAT, world_pos.shape[0], "VEC4")
if bs_deltas is not None:
prim_deltas = bs_deltas[:, nearest, :] # (K,M,3)
@@ -341,7 +400,7 @@ def build_rigged_glb(mesh_bytes, mesh, joints, parents, weights,
d = np.ascontiguousarray(np.asarray(d, dtype=np.float32))
acc = _add_accessor(
glb, _append_view(glb, blob, d.tobytes(), _GLTF_ARRAY_BUFFER),
- _GLTF_FLOAT, verts.shape[0], "VEC3",
+ _GLTF_FLOAT, world_pos.shape[0], "VEC3",
mn=d.min(axis=0).tolist(), mx=d.max(axis=0).tolist())
targets.append(pygltflib.Attributes(POSITION=acc))
prim.targets = targets
@@ -359,7 +418,17 @@ def build_rigged_glb(mesh_bytes, mesh, joints, parents, weights,
scene.nodes.append(new_ni)
else:
for ni in nodes:
- glb.nodes[ni].skin = skin_idx
+ node = glb.nodes[ni]
+ node.skin = skin_idx
+ # The transform is baked into the geometry now. Clear it on
+ # childless nodes so non-spec-strict viewers agree with the
+ # baked positions; keep it when children depend on it (spec
+ # viewers ignore a skinned node's transform either way).
+ if bake and not node.children:
+ node.matrix = None
+ node.translation = None
+ node.rotation = None
+ node.scale = None
if not skinned_any:
raise RuntimeError("no mesh primitive with POSITION found; cannot rig")
diff --git a/workers/rig/stage-assets.sh b/workers/rig/stage-assets.sh
index 62539a80d..f05477d22 100755
--- a/workers/rig/stage-assets.sh
+++ b/workers/rig/stage-assets.sh
@@ -17,10 +17,12 @@ WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
HERE="$(cd "$(dirname "$0")" && pwd)"
-echo "==> Make-It-Animatable checkpoints (HF: jasongzy/Make-It-Animatable)"
+echo "==> Make-It-Animatable checkpoints + demo data (HF: jasongzy/Make-It-Animatable)"
GIT_LFS_SKIP_SMUDGE=1 git clone --depth 1 \
https://huggingface.co/jasongzy/Make-It-Animatable "$WORK/hf-mia"
-git -C "$WORK/hf-mia" lfs pull -I output/best/new
+# data/ (Standard Run.fbx + examples/) is required too: MIA's init_blocks()
+# resolves those demo files at import and aborts startup when they're absent.
+git -C "$WORK/hf-mia" lfs pull -I output/best/new,data
echo "==> Mixamo bone templates (HF dataset: jasongzy/Mixamo, gated: auto)"
# The dataset is gated (auto-approve). Needs an HF token; the platform one
@@ -49,6 +51,8 @@ python3 "$HERE/build_arkit_template.py" \
echo "==> Upload to $BUCKET"
gcloud storage cp -r "$WORK/hf-mia/output/best/new" "$BUCKET/output/best/new"
+gcloud storage cp "$WORK/hf-mia/data/Standard Run.fbx" "$BUCKET/data/"
+gcloud storage cp -r "$WORK/hf-mia/data/examples" "$BUCKET/data/examples"
gcloud storage cp "$WORK/hf-mixamo/bones.fbx" "$WORK/hf-mixamo/bones_vroid.fbx" \
"$BUCKET/data/Mixamo/"
gcloud storage cp "$WORK/arkit_template.npz" "$BUCKET/arkit_template.npz"
diff --git a/workers/rig/test_rig_glb.py b/workers/rig/test_rig_glb.py
index 100dabec0..7fa6a790a 100644
--- a/workers/rig/test_rig_glb.py
+++ b/workers/rig/test_rig_glb.py
@@ -262,11 +262,12 @@ def test_dirty_weights_no_collapse():
_check(checked >= 1, "weights validated")
-def test_nonidentity_node_rejected():
- """A skinned mesh node with a non-identity transform must fail loudly rather
- than silently misplacing the skeleton."""
- print("test_nonidentity_node_rejected")
- glb_bytes, mesh = _make_mesh_glb()
+def test_nonidentity_node_baked():
+ """A mesh drawn under a non-identity node transform gets that transform
+ baked into world-space geometry (glTF ignores a skinned node's own
+ transform, so local-space vertices would render misplaced)."""
+ print("test_nonidentity_node_baked")
+ glb_bytes, _ = _make_mesh_glb()
g = pygltflib.GLTF2.load_from_bytes(glb_bytes)
moved = False
for node in g.nodes:
@@ -276,15 +277,54 @@ def test_nonidentity_node_rejected():
_check(moved, "test set a transform on the mesh node")
chunks = g.save_to_bytes()
moved_bytes = b"".join(chunks) if isinstance(chunks, (list, tuple)) else chunks
+ # trimesh applies node transforms on load, so this mesh is in WORLD space:
+ # exactly the frame the predictor sees and the skeleton lives in.
moved_mesh = trimesh.load(io.BytesIO(moved_bytes), file_type="glb", force="mesh")
joints, parents, weights = _fake_prediction(moved_mesh, n_joints=3)
+ out = build_rigged_glb(moved_bytes, moved_mesh, joints, parents, weights, None)
+ glb = pygltflib.GLTF2.load_from_bytes(out)
+ blob = bytearray(glb.binary_blob())
+
+ checked = False
+ for gmesh in glb.meshes:
+ for prim in gmesh.primitives:
+ if getattr(prim.attributes, "POSITION", None) is None:
+ continue
+ pos = _decode(glb, blob, prim.attributes.POSITION)[:, :3].astype(np.float32)
+ # Baked positions must match trimesh's world-space vertices.
+ got = np.sort(pos.round(4).view([('x','<f4'),('y','<f4'),('z','<f4')]), axis=0)
+ want = np.sort(np.asarray(moved_mesh.vertices, np.float32).round(4)
+ .view([('x','<f4'),('y','<f4'),('z','<f4')]), axis=0)
+ _check(np.array_equal(got, want), "positions baked to world space")
+ checked = True
+ _check(checked, "baked primitive validated")
+
+ for node in glb.nodes:
+ if node.mesh is not None and node.skin is not None and not node.children:
+ _check(not node.translation, "baked node transform cleared")
+
+
+def test_divergent_instances_rejected():
+ """One mesh instanced by nodes with DIFFERENT world transforms cannot be
+ skinned to a single world-space skeleton; that must fail loudly."""
+ print("test_divergent_instances_rejected")
+ glb_bytes, mesh = _make_mesh_glb()
+ g = pygltflib.GLTF2.load_from_bytes(glb_bytes)
+ scene = g.scenes[g.scene or 0]
+ src_ni = next(i for i, n in enumerate(g.nodes) if n.mesh is not None)
+ g.nodes.append(pygltflib.Node(mesh=g.nodes[src_ni].mesh, translation=[3.0, 0.0, 0.0]))
+ scene.nodes.append(len(g.nodes) - 1)
+ chunks = g.save_to_bytes()
+ twin_bytes = b"".join(chunks) if isinstance(chunks, (list, tuple)) else chunks
+ joints, parents, weights = _fake_prediction(mesh, n_joints=3)
+
try:
- build_rigged_glb(moved_bytes, moved_mesh, joints, parents, weights, None)
+ build_rigged_glb(twin_bytes, mesh, joints, parents, weights, None)
except RuntimeError as exc:
- _check("non-identity" in str(exc), "raised a clear non-identity transform error")
+ _check("instanced" in str(exc), "raised a clear divergent-instances error")
return
- _check(False, "expected RuntimeError for non-identity node transform")
+ _check(False, "expected RuntimeError for divergent instances")
if __name__ == "__main__":
@@ -294,7 +334,8 @@ if __name__ == "__main__":
test_blendshape_targets()
test_zero_delta_primitives_skipped()
test_dirty_weights_no_collapse()
- test_nonidentity_node_rejected()
+ test_nonidentity_node_baked()
+ test_divergent_instances_rejected()
except AssertionError:
print("\nFAILED")
sys.exit(1)