Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: worker updates
nirholasd782dde6b145
diff --git a/workers/deploy/README.md b/workers/deploy/README.mdnew file mode 100644index 000000000..0b02b4344--- /dev/null+++ b/workers/deploy/README.md@@ -0,0 +1,118 @@+# Avatar pipeline — Google Cloud Run deploy runbook++Deploys the **Scan yourself to 3D** backend: selfie photos → textured 3D mesh →+auto-rigged GLB, served by Cloud Run GPU services and consumed by the site via+`api/_providers/gcp.js`.++```+/scan (browser)+ └─ POST /api/avatars/reconstruct (Vercel)+ └─ controller /reconstruct (Cloud Run, CPU) ← GCP_RECONSTRUCTION_URL+ ├─ mesh model /infer (Cloud Run, L4 GPU) Hunyuan3D / TRELLIS / TripoSR+ └─ UniRig /rig (Cloud Run, L4 GPU) skeleton + skinning + ARKit-52+ └─ rigged GLB → GCS → materialized as an avatar the user downloads+```++The site talks **only** to the controller. The controller fans out to the model++ rigging services and returns one rigged GLB.++---++## What you need before running++1. **A GCP project** with the credits / billing account linked.+2. **Cloud Run L4 GPU quota** in your region (default `us-central1`). This is the+ one thing that can block you and can take hours to approve — request it first:+ - Console → IAM & Admin → Quotas → filter “Cloud Run Admin API” →+ **`nvidia_l4_gpu_allocation_no_zonal_redundancy`** (and the zonal one) → request ≥ 1 per service you deploy concurrently.+3. **A Hugging Face token** (`HF_TOKEN`) — Hunyuan3D-2.1 is license-gated; accept the+ license on its HF page once, then the token can download it. TRELLIS/TripoSR/UniRig are open.+4. **~80 GB free disk** wherever you run `stage-weights.sh` (Cloud Shell has enough on a mounted scratch dir; use `STAGE_DIR=$HOME/weights` if `/tmp` is small).++---++## Fastest path — run it in Google Cloud Shell++Cloud Shell is pre-authenticated to your account, already has `gcloud`, `gsutil`,+`python3`, and `docker`. No credential sharing.++```bash+# in Cloud Shell, from a clone of this repo:+cd workers/deploy++# 1. stage model weights into gs://three-ws-model-weights (run once)+# In Cloud Shell, gcsfuse mode is REQUIRED: the full fleet is ~80 GB and+# Cloud Shell has only ~5 GB local disk, so weights stream straight into the+# bucket (gcsfuse is preinstalled). This is the default mode.+HF_TOKEN=hf_xxx SERVICES="hunyuan3d trellis triposr unirig" ./stage-weights.sh+# (on a big-disk GCE VM instead, you can use LOCAL_STAGE=1 for download+rsync.)++# 2. provision + build + deploy everything, in order+PROJECT_ID=your-project-id SERVICES="hunyuan3d trellis triposr unirig" ./deploy-all.sh+```++`SERVICES` must match between the two commands so the weights you staged line up+with the services you deploy.++`deploy-all.sh` is idempotent — safe to re-run. It will:+enable APIs · create the two GCS buckets · create Firestore (native) · create the+`avatar-reconstruction-key` secret · grant the runtime service account its roles ·+build + deploy each GPU service · deploy the controller and **wire it to the+service URLs** · print the exact Vercel env vars to set.++---++## Default vs full fleet++| `SERVICES` | what you get | cost/complexity |+| --- | --- | --- |+| `hunyuan3d unirig` *(default)* | Textured mesh **+ rig** — matches the “rigged model” promise | 2 GPU services |+| `triposr unirig` | Fastest mesh (~5–15s, untextured) + rig | 2 GPU services, cheapest |+| `hunyuan3d trellis triposr unirig` | All mesh backends (controller load-balances) + rig | 4 GPU services |++Start with the default. The controller routes 100 % to whatever mesh backends are+wired, so adding more later is just another `deploy-all.sh` run with a wider `SERVICES`.++---++## After deploy — wire the site++`deploy-all.sh` prints these. Set them in Vercel (Production) and redeploy:++```+AVATAR_REGEN_PROVIDER = gcp+GCP_RECONSTRUCTION_URL = https://avatar-pipeline-controller-….run.app+GCP_RECONSTRUCTION_KEY = <printed key>+```++`AVATAR_REGEN_PROVIDER=gcp` pins the provider so the resolver never falls back to+the flaky free Hugging Face Space path.++> Deploy-safety note: `api/config.js` imports `api/_lib/regen-provider.js`. If you+> redeploy the site from this working tree, make sure that file is committed —+> otherwise the Vercel build breaks on a missing import.++Verify: open `/scan`, capture a selfie, expect a downloadable **rigged** GLB in ~1–2 min.+Watch logs with `gcloud run services logs read avatar-pipeline-controller --region us-central1`.++---++## Cost (covered by credits)++GPU services scale to **zero** when idle (`min-instances=0`), so you pay L4 time+only while a scan runs (~1–2 min each). The controller runs `min-instances=1` (CPU,+cheap) so the first scan of the day isn’t blocked by a cold start. An L4 is ~\$0.71/hr+on-demand → a scan costs roughly **\$0.02–0.05** of GPU time. Weight storage is a few+GB-months. Well within the credits.++---++## Troubleshooting++| Symptom | Cause / fix |+| --- | --- |+| Build fails on `pip install hy3dgen/trellis/unirig` | The git-sourced CUDA package didn’t build. Check the Cloud Build log; TripoSR builds most reliably — deploy `SERVICES="triposr unirig"` first to prove the path, then add Hunyuan3D. |+| Service cold-starts then 503s on first request | Weights not staged for that model. Re-run `stage-weights.sh` for it. |+| `quota exceeded … nvidia_l4` at deploy | GPU quota not yet granted in the region — see step 2 above. |+| Controller `/health` shows empty `backends` | The controller’s `MODEL_*_URL` env wasn’t set — re-run `deploy-all.sh` (it re-wires), or set manually with `gcloud run services update`. |+| `/scan` still says “warming up” after env set | Vercel needs a redeploy for new env to take effect; confirm `/api/config` returns `avatarReconstruct:true`. |diff --git a/workers/deploy/deploy-all.sh b/workers/deploy/deploy-all.shnew file mode 100755index 000000000..2b71a75ce--- /dev/null+++ b/workers/deploy/deploy-all.sh@@ -0,0 +1,192 @@+#!/usr/bin/env bash+#+# deploy-all.sh — provision + deploy the three.ws avatar reconstruction pipeline+# to Google Cloud Run, in the correct order, idempotently.+#+# Pipeline shape:+# selfie photos → controller → mesh model (Hunyuan3D/TRELLIS/TripoSR, L4 GPU)+# → UniRig rigging (L4 GPU) → rigged GLB in GCS+#+# The Vercel function api/_providers/gcp.js talks ONLY to the controller, so the+# last thing this prints is the controller URL + API key to put in Vercel env.+#+# Prerequisites (see README.md):+# • gcloud authed to a project that has the $THREE GCP credits / billing linked+# • Cloud Run L4 GPU quota in $REGION (request early — approval can take hours)+# • Weights already staged: ./stage-weights.sh (services won't boot without them)+#+# Usage:+# PROJECT_ID=my-proj ./deploy-all.sh+# PROJECT_ID=my-proj SERVICES="hunyuan3d trellis triposr unirig" ./deploy-all.sh+#+# Env:+# PROJECT_ID required — target GCP project+# REGION default us-central1 (must offer Cloud Run nvidia-l4)+# SERVICES default "hunyuan3d unirig" (mesh model(s) + rigging)+# OUTPUT_BUCKET default three-ws-avatar-reconstructions+# WEIGHTS_BUCKET default three-ws-model-weights++set -euo pipefail++PROJECT_ID="${PROJECT_ID:?set PROJECT_ID to your GCP project}"+REGION="${REGION:-us-central1}"+SERVICES="${SERVICES:-hunyuan3d unirig}"+OUTPUT_BUCKET="${OUTPUT_BUCKET:-three-ws-avatar-reconstructions}"+WEIGHTS_BUCKET="${WEIGHTS_BUCKET:-three-ws-model-weights}"+SECRET_NAME="avatar-reconstruction-key"++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+cd "$REPO_ROOT"++log() { printf '\033[1;36m[deploy]\033[0m %s\n' "$*"; }+ok() { printf '\033[1;32m[deploy] ✓\033[0m %s\n' "$*"; }+warn() { printf '\033[1;33m[deploy] ! \033[0m %s\n' "$*"; }+die() { printf '\033[1;31m[deploy] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }++command -v gcloud >/dev/null 2>&1 || die "gcloud not found on PATH"+gcloud auth print-access-token >/dev/null 2>&1 || die "gcloud is not authenticated — run 'gcloud auth login'"++# service key -> "worker_dir|cloud_run_service|controller_env_var"+svc_dir() { case "$1" in hunyuan3d) echo model-hunyuan3d;; trellis) echo model-trellis;; triposr) echo model-triposr;; unirig) echo unirig;; *) echo "";; esac; }+svc_runname() { case "$1" in hunyuan3d) echo model-hunyuan3d;; trellis) echo model-trellis;; triposr) echo model-triposr;; unirig) echo unirig;; *) echo "";; esac; }+svc_ctrlenv() { case "$1" in hunyuan3d) echo MODEL_HUNYUAN3D_URL;; trellis) echo MODEL_TRELLIS_URL;; triposr) echo MODEL_TRIPOSR_URL;; unirig) echo UNIRIG_URL;; *) echo "";; esac; }++TAG="$(git rev-parse --short HEAD 2>/dev/null || echo manual)"++# ── 1. project + APIs ─────────────────────────────────────────────────────────+log "project: $PROJECT_ID region: $REGION services: $SERVICES"+gcloud config set project "$PROJECT_ID" >/dev/null+log "enabling required APIs (idempotent)…"+gcloud services enable \+ run.googleapis.com cloudbuild.googleapis.com artifactregistry.googleapis.com \+ storage.googleapis.com firestore.googleapis.com secretmanager.googleapis.com \+ --project "$PROJECT_ID" >/dev/null+ok "APIs enabled"++PROJECT_NUMBER="$(gcloud projects describe "$PROJECT_ID" --format='value(projectNumber)')"+COMPUTE_SA="${PROJECT_NUMBER}[email protected]"++# ── 2. buckets ────────────────────────────────────────────────────────────────+for b in "$OUTPUT_BUCKET" "$WEIGHTS_BUCKET"; do+ if gcloud storage buckets describe "gs://$b" >/dev/null 2>&1; then+ ok "bucket gs://$b exists"+ else+ log "creating bucket gs://$b…"+ gcloud storage buckets create "gs://$b" --location="$REGION" --uniform-bucket-level-access >/dev/null+ ok "created gs://$b"+ fi+done+# Output GLBs are served publicly (the avatar materializer fetches them by URL).+gcloud storage buckets add-iam-policy-binding "gs://$OUTPUT_BUCKET" \+ --member=allUsers --role=roles/storage.objectViewer >/dev/null 2>&1 || \+ warn "could not make $OUTPUT_BUCKET public-read (org policy may block allUsers) — check materializer fetch"++# ── 3. Firestore (controller job state) ───────────────────────────────────────+if gcloud firestore databases describe --database="(default)" >/dev/null 2>&1; then+ ok "Firestore (default) database exists"+else+ log "creating Firestore native database in $REGION…"+ gcloud firestore databases create --location="$REGION" --type=firestore-native >/dev/null \+ || warn "Firestore create failed — create a native-mode DB manually if the controller errors"+fi++# ── 4. shared API key secret ──────────────────────────────────────────────────+if gcloud secrets describe "$SECRET_NAME" >/dev/null 2>&1; then+ ok "secret $SECRET_NAME exists"+else+ log "creating secret $SECRET_NAME with a fresh random key…"+ openssl rand -hex 32 | gcloud secrets create "$SECRET_NAME" --data-file=- >/dev/null+ ok "created secret $SECRET_NAME"+fi++# ── 5. IAM for the Cloud Run runtime service account ──────────────────────────+log "granting runtime roles to $COMPUTE_SA…"+for role in roles/secretmanager.secretAccessor roles/datastore.user roles/storage.objectAdmin; do+ gcloud projects add-iam-policy-binding "$PROJECT_ID" \+ --member="serviceAccount:${COMPUTE_SA}" --role="$role" --condition=None >/dev/null 2>&1 \+ || warn "could not grant $role to $COMPUTE_SA (may already be bound or need an admin)"+done+ok "runtime IAM configured"++# ── 6. Artifact Registry repos + build/deploy each GPU service ────────────────+declare -A SERVICE_URL+build_and_deploy() {+ local key="$1" dir runname repo+ dir="workers/$(svc_dir "$key")"+ runname="$(svc_runname "$key")"+ repo="$runname"+ [ -d "$dir" ] || die "worker dir not found: $dir"++ if ! gcloud artifacts repositories describe "$repo" --location="$REGION" >/dev/null 2>&1; then+ log "creating Artifact Registry repo '$repo'…"+ gcloud artifacts repositories create "$repo" --repository-format=docker --location="$REGION" >/dev/null+ fi++ log "building + deploying '$runname' (this builds a CUDA GPU image — several minutes)…"+ gcloud builds submit \+ --config "$dir/cloudbuild.yaml" \+ --region "$REGION" \+ --substitutions="SHORT_SHA=${TAG},_REGION=${REGION},_GCS_BUCKET=${OUTPUT_BUCKET},_WEIGHTS_BUCKET=${WEIGHTS_BUCKET}" \+ . \+ || die "build/deploy failed for $runname — inspect the Cloud Build log above"++ local url+ url="$(gcloud run services describe "$runname" --region "$REGION" --format='value(status.url)')"+ [ -n "$url" ] || die "could not resolve URL for $runname after deploy"+ SERVICE_URL["$key"]="$url"+ ok "$runname → $url"+}++for svc in $SERVICES; do+ [ -n "$(svc_dir "$svc")" ] || die "unknown service '$svc' (valid: hunyuan3d trellis triposr unirig)"+ build_and_deploy "$svc"+done++# ── 7. controller — deploy, then wire to the backend URLs it must call ────────+log "building + deploying controller (avatar-pipeline-controller, CPU)…"+gcloud builds submit \+ --config "workers/avatar-pipeline-controller/cloudbuild.yaml" \+ --region "$REGION" \+ --substitutions="SHORT_SHA=${TAG},_REGION=${REGION},_GCS_BUCKET=${OUTPUT_BUCKET}" \+ . \+ || die "controller build/deploy failed"++# The controller's cloudbuild does NOT know the backend URLs (they don't exist+# until the services above are deployed). Wire them in now.+CTRL_ENV=""+for svc in $SERVICES; do+ envvar="$(svc_ctrlenv "$svc")"+ url="${SERVICE_URL[$svc]:-}"+ [ -n "$envvar" ] && [ -n "$url" ] && CTRL_ENV="${CTRL_ENV:+$CTRL_ENV,}${envvar}=${url}"+done+if [ -n "$CTRL_ENV" ]; then+ log "wiring controller → backends: $CTRL_ENV"+ gcloud run services update avatar-pipeline-controller --region "$REGION" \+ --update-env-vars "$CTRL_ENV" >/dev/null+fi+CONTROLLER_URL="$(gcloud run services describe avatar-pipeline-controller --region "$REGION" --format='value(status.url)')"+API_KEY_VALUE="$(gcloud secrets versions access latest --secret="$SECRET_NAME")"++ok "controller → $CONTROLLER_URL"++# ── 8. smoke test + handoff ───────────────────────────────────────────────────+log "controller health:"+curl -fsS -H "authorization: Bearer ${API_KEY_VALUE}" "${CONTROLLER_URL}/health" || warn "health check did not return 200 yet (cold start) — retry in a minute"+echo++cat <<EOF++────────────────────────────────────────────────────────────────────────+ DEPLOY COMPLETE. Set these in Vercel (Production), then redeploy the site:+────────────────────────────────────────────────────────────────────────+ AVATAR_REGEN_PROVIDER = gcp+ GCP_RECONSTRUCTION_URL = ${CONTROLLER_URL}+ GCP_RECONSTRUCTION_KEY = ${API_KEY_VALUE}++ vercel env add AVATAR_REGEN_PROVIDER production # paste: gcp+ vercel env add GCP_RECONSTRUCTION_URL production # paste the URL above+ vercel env add GCP_RECONSTRUCTION_KEY production # paste the key above++ Then verify: open /scan, capture a selfie, expect a rigged GLB in ~1–2 min.+────────────────────────────────────────────────────────────────────────+EOFdiff --git a/workers/deploy/stage-weights.sh b/workers/deploy/stage-weights.shnew file mode 100755index 000000000..505ef5f50--- /dev/null+++ b/workers/deploy/stage-weights.sh@@ -0,0 +1,118 @@+#!/usr/bin/env bash+#+# stage-weights.sh — download avatar-pipeline model weights from Hugging Face+# and stage them into the GCS weights bucket the Cloud Run services mount at+# /weights. Run this ONCE (and again only when a model is added/updated)+# before deploy-all.sh — the services load weights with from_pretrained() off+# the mounted bucket and will fail their cold-start health check if the weights+# are missing.+#+# Two modes:+# • gcsfuse (default, REQUIRED in Cloud Shell) — mounts the bucket and downloads+# HF repos straight into it. No large local disk needed; the full fleet is+# ~80 GB and Cloud Shell only has ~5 GB, so local staging would fail.+# • local (LOCAL_STAGE=1) — download to a local dir then rsync up. Only on a+# box with ~80 GB free disk (e.g. a GCE VM).+#+# Usage (Cloud Shell, full fleet):+# HF_TOKEN=hf_xxx SERVICES="hunyuan3d trellis triposr unirig" ./stage-weights.sh+#+# Env:+# WEIGHTS_BUCKET GCS bucket name (default: three-ws-model-weights)+# SERVICES space-separated subset (default: "hunyuan3d unirig")+# HF_TOKEN Hugging Face token (required for gated repos e.g. Hunyuan3D)+# LOCAL_STAGE "1" to use the local-dir+rsync path instead of gcsfuse+# MOUNT_DIR gcsfuse mountpoint (default: /tmp/three-ws-weights-mnt)+# STAGE_DIR local scratch (LOCAL_STAGE only, default: /tmp/three-ws-weights)+# FORCE "1" to re-download even if the bucket prefix already exists++set -euo pipefail++WEIGHTS_BUCKET="${WEIGHTS_BUCKET:-three-ws-model-weights}"+SERVICES="${SERVICES:-hunyuan3d unirig}"+LOCAL_STAGE="${LOCAL_STAGE:-0}"+MOUNT_DIR="${MOUNT_DIR:-/tmp/three-ws-weights-mnt}"+STAGE_DIR="${STAGE_DIR:-/tmp/three-ws-weights}"+FORCE="${FORCE:-0}"++# service -> "hf_repo|bucket_subdir" (sources documented in each worker's main.py)+weight_source() {+ case "$1" in+ hunyuan3d) echo "tencent/Hunyuan3D-2.1|hunyuan3d-2.1" ;;+ trellis) echo "microsoft/TRELLIS-image-large|trellis-large" ;;+ triposr) echo "stabilityai/TripoSR|triposr" ;;+ unirig) echo "VAST-AI/UniRig|unirig" ;;+ *) echo "" ;;+ esac+}++log() { printf '\033[1;36m[stage-weights]\033[0m %s\n' "$*"; }+ok() { printf '\033[1;32m[stage-weights] ✓\033[0m %s\n' "$*"; }+die() { printf '\033[1;31m[stage-weights] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }++command -v gcloud >/dev/null 2>&1 || die "gcloud not found on PATH"+command -v python3 >/dev/null 2>&1 || die "python3 not found on PATH"+gcloud auth print-access-token >/dev/null 2>&1 || die "gcloud not authenticated — run 'gcloud auth login'"++# A recent huggingface_hub downloads directly into --local-dir with no separate+# multi-GB global cache, which is what makes the gcsfuse path disk-free.+if ! python3 -c "import huggingface_hub, sys; v=tuple(map(int,huggingface_hub.__version__.split('.')[:2])); sys.exit(0 if v>=(0,23) else 1)" >/dev/null 2>&1; then+ log "installing/upgrading huggingface_hub…"+ pip install --quiet --upgrade "huggingface_hub[cli]>=0.23"+fi+HF_CLI="huggingface-cli"+command -v "$HF_CLI" >/dev/null 2>&1 || HF_CLI="python3 -m huggingface_hub.commands.huggingface_cli"+[ -n "${HF_TOKEN:-}" ] && export HF_TOKEN++# Ensure the weights bucket exists.+if ! gcloud storage buckets describe "gs://${WEIGHTS_BUCKET}" >/dev/null 2>&1; then+ log "creating weights bucket gs://${WEIGHTS_BUCKET}…"+ gcloud storage buckets create "gs://${WEIGHTS_BUCKET}" --uniform-bucket-level-access >/dev/null+fi++# ── gcsfuse mount lifecycle (default mode) ────────────────────────────────────+GCSFUSE_MOUNTED=0+cleanup() { [ "$GCSFUSE_MOUNTED" = "1" ] && fusermount -u "$MOUNT_DIR" 2>/dev/null || true; }+trap cleanup EXIT++if [ "$LOCAL_STAGE" != "1" ]; then+ command -v gcsfuse >/dev/null 2>&1 || die "gcsfuse not found — install it, or re-run with LOCAL_STAGE=1 on a big-disk host"+ mkdir -p "$MOUNT_DIR"+ log "mounting gs://${WEIGHTS_BUCKET} at ${MOUNT_DIR} via gcsfuse…"+ # implicit-dirs lets HF's nested paths appear; rename-dir-limit keeps temp renames working.+ gcsfuse --implicit-dirs --rename-dir-limit=200000 "$WEIGHTS_BUCKET" "$MOUNT_DIR" \+ || die "gcsfuse mount failed"+ GCSFUSE_MOUNTED=1+ ok "mounted"+fi++stage_one() {+ local svc="$1" src repo subdir dest target+ src="$(weight_source "$svc")"+ [ -n "$src" ] || die "unknown service '$svc' (valid: hunyuan3d trellis triposr unirig)"+ repo="${src%%|*}"; subdir="${src##*|}"+ dest="gs://${WEIGHTS_BUCKET}/${subdir}"++ if [ "$FORCE" != "1" ] && gcloud storage ls "${dest}/" >/dev/null 2>&1; then+ ok "${svc}: ${dest} already populated — skipping (FORCE=1 to re-stage)"+ return+ fi++ if [ "$LOCAL_STAGE" = "1" ]; then+ target="${STAGE_DIR}/${subdir}"+ log "${svc}: downloading ${repo} → ${target}"+ $HF_CLI download "$repo" --local-dir "$target" ${HF_TOKEN:+--token "$HF_TOKEN"}+ log "${svc}: uploading → ${dest}"+ gcloud storage rsync --recursive --delete-unmatched-destination-objects "$target" "$dest"+ else+ target="${MOUNT_DIR}/${subdir}"+ log "${svc}: downloading ${repo} straight into bucket (${dest}) — this is the slow step"+ $HF_CLI download "$repo" --local-dir "$target" ${HF_TOKEN:+--token "$HF_TOKEN"}+ fi+ ok "${svc}: staged at ${dest}"+}++for svc in $SERVICES; do stage_one "$svc"; done++log "all requested weights staged into gs://${WEIGHTS_BUCKET}"+log "next: PROJECT_ID=<your-project> SERVICES=\"${SERVICES}\" ./deploy-all.sh"diff --git a/workers/unirig/Dockerfile b/workers/unirig/Dockerfileindex 108bdc0ef..cbf455a39 100644--- a/workers/unirig/Dockerfile+++ b/workers/unirig/Dockerfile@@ -21,6 +21,7 @@ RUN pip install -r /app/requirements.txtWORKDIR /appCOPY worker_security.py /app/worker_security.py+COPY rig_glb.py /app/rig_glb.pyCOPY main.py /app/main.py# Wolf3D skeleton templates for blendshape transfer (added in Phase 2).diff --git a/workers/unirig/__pycache__/main.cpython-312.pyc b/workers/unirig/__pycache__/main.cpython-312.pycnew file mode 100644index 000000000..939c4e556Binary files /dev/null and b/workers/unirig/__pycache__/main.cpython-312.pyc differdiff --git a/workers/unirig/__pycache__/rig_glb.cpython-312.pyc b/workers/unirig/__pycache__/rig_glb.cpython-312.pycnew file mode 100644index 000000000..b5a9fb157Binary files /dev/null and b/workers/unirig/__pycache__/rig_glb.cpython-312.pyc differdiff --git a/workers/unirig/__pycache__/test_rig_glb.cpython-312.pyc b/workers/unirig/__pycache__/test_rig_glb.cpython-312.pycnew file mode 100644index 000000000..c26ed0da3Binary files /dev/null and b/workers/unirig/__pycache__/test_rig_glb.cpython-312.pyc differdiff --git a/workers/unirig/__pycache__/worker_security.cpython-312.pyc b/workers/unirig/__pycache__/worker_security.cpython-312.pycnew file mode 100644index 000000000..62088f518Binary files /dev/null and b/workers/unirig/__pycache__/worker_security.cpython-312.pyc differdiff --git a/workers/unirig/main.py b/workers/unirig/main.pyindex 7d6d73f71..8419adc3c 100644--- a/workers/unirig/main.py+++ b/workers/unirig/main.py@@ -39,13 +39,13 @@ import uuidfrom contextlib import asynccontextmanagerfrom typing import Optional-import numpy as npimport torchimport trimeshfrom fastapi import FastAPI, HTTPException, Header, BackgroundTasksfrom google.cloud import storagefrom pydantic import BaseModel, Field+from rig_glb import build_rigged_glbfrom worker_security import (UnsafeUrlError,fetch_remote_bytes_async,@@ -103,34 +103,6 @@ def _require_api_key(authorization: str) -> None:raise HTTPException(status_code=401, detail=str(exc)) from exc-# Wolf3D / ARKit-52 skeleton joint names. UniRig predicts joint placement; we-# remap its output to this hierarchy so the three.ws avatar runtime can drive it.-WOLF3D_JOINTS = [- "Hips", "Spine", "Spine1", "Spine2", "Neck", "Head",- "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand",- "RightShoulder", "RightArm", "RightForeArm", "RightHand",- "LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase",- "RightUpLeg", "RightLeg", "RightFoot", "RightToeBase",- "LeftEye", "RightEye", "Jaw",-]--ARKIT_52_BLENDSHAPES = [- "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft",- "browOuterUpRight", "cheekPuff", "cheekSquintLeft", "cheekSquintRight",- "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight",- "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight",- "eyeLookUpLeft", "eyeLookUpRight", "eyeSquintLeft", "eyeSquintRight",- "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",- "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight",- "mouthFrownLeft", "mouthFrownRight", "mouthFunnel", "mouthLeft",- "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft",- "mouthPressRight", "mouthPucker", "mouthRight", "mouthRollLower",- "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft",- "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight",- "mouthUpperUpLeft", "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight",- "tongueOut",-]-async def _run_rigging(task_id: str,@@ -169,16 +141,10 @@ async def _run_rigging(parents = skeleton["parents"].cpu().numpy()weights = skinning_weights.cpu().numpy()- import pygltflib- glb = pygltflib.GLTF2.load_from_bytes(mesh_bytes)- _inject_skeleton(glb, mesh, joints, parents, weights)-- if blendshapes and hasattr(result, "blendshapes"):- _inject_blendshapes(glb, mesh, result["blendshapes"])-- buf = io.BytesIO()- glb.save_to_bytes(buf)- return buf.getvalue()+ blendshape_data = result.get("blendshapes") if blendshapes else None+ return build_rigged_glb(+ mesh_bytes, mesh, joints, parents, weights, blendshape_data,+ )rigged_bytes = await loop.run_in_executor(None, _rig)@@ -206,43 +172,6 @@ async def _run_rigging(})-def _inject_skeleton(glb, mesh, joints, parents, weights):- """- Inject a skeleton (joints + inverse bind matrices) and skinning weights- into the GLB. This wires the mesh as a skinned mesh node with the Wolf3D- joint hierarchy so the three.ws avatar runtime can animate it.-- The actual implementation depends on UniRig's output format. This is a- scaffold — the joint remapping from UniRig's predicted skeleton to Wolf3D's- naming convention will need calibration during integration testing.- """- log.info("Injecting skeleton: %d joints, %d vertices", len(joints), len(mesh.vertices))- # TODO: Full pygltflib skeleton injection.- # This requires:- # 1. Creating skin.joints[] node array with Wolf3D names- # 2. Computing inverseBindMatrices accessor- # 3. Creating a JOINTS_0 + WEIGHTS_0 accessor pair on the mesh primitive- # 4. Remapping UniRig's joint ordering to WOLF3D_JOINTS- # Placeholder: the rigged GLB will be returned as-is from UniRig's output- # format. The three.ws glb-inspect.js will detect whether it's properly rigged.---def _inject_blendshapes(glb, mesh, blendshapes_data):- """- Inject ARKit-52 blendshape morph targets into the GLB.-- Blendshape transfer from a template head is the research-heavy part.- UniRig may or may not support this natively. Fallback approach:- 1. Register the generated head mesh to a Wolf3D template via ICP- 2. Transfer blendshape deltas using deformation transfer- 3. Name them per ARKIT_52_BLENDSHAPES-- This is scaffolded for now — the initial deployment will ship without- blendshapes (body animation only via skeleton). Blendshapes will be- added in a follow-up once we validate the mesh quality from each model.- """- log.info("Blendshape injection requested — not yet implemented, skipping")-class RigRequest(BaseModel):mesh_gcs_url: strdiff --git a/workers/unirig/rig_glb.py b/workers/unirig/rig_glb.pynew file mode 100644index 000000000..6a94d06e9--- /dev/null+++ b/workers/unirig/rig_glb.py@@ -0,0 +1,373 @@+"""+Pure glTF skin authoring — turns a raw mesh GLB + UniRig's predicted skeleton+and skinning weights into a spec-valid *rigged* GLB.++Kept dependency-light on purpose (numpy / scipy / pygltflib / trimesh only, no+torch / CUDA / GCP) so it can be unit-tested without a GPU — see test_rig_glb.py.++What `build_rigged_glb` produces, preserving all original geometry/materials:+ • a joint-node hierarchy (parent-relative translations, identity bind rotations)+ • an inverseBindMatrices accessor+ • a `skin` bound to every node that draws a mesh+ • JOINTS_0 / WEIGHTS_0 vertex attributes (top-4 normalized influences) on each+ primitive, aligned to that primitive's exact vertex order via a KD-tree+ (the model's GLB vertex set need not match UniRig's working vertices)+ • optional ARKit-named morph targets when UniRig supplies blendshape deltas++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.+"""++from __future__ import annotations++import logging++import numpy as np+import pygltflib+from scipy.spatial import cKDTree++log = logging.getLogger("unirig.rig_glb")++# Wolf3D / ARKit-52 skeleton joint names. UniRig predicts joint placement; when+# it returns exactly this many joints we name them in this canonical order so+# the three.ws avatar runtime can retarget; otherwise joints are named joint_i.+WOLF3D_JOINTS = [+ "Hips", "Spine", "Spine1", "Spine2", "Neck", "Head",+ "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand",+ "RightShoulder", "RightArm", "RightForeArm", "RightHand",+ "LeftUpLeg", "LeftLeg", "LeftFoot", "LeftToeBase",+ "RightUpLeg", "RightLeg", "RightFoot", "RightToeBase",+ "LeftEye", "RightEye", "Jaw",+]++ARKIT_52_BLENDSHAPES = [+ "browDownLeft", "browDownRight", "browInnerUp", "browOuterUpLeft",+ "browOuterUpRight", "cheekPuff", "cheekSquintLeft", "cheekSquintRight",+ "eyeBlinkLeft", "eyeBlinkRight", "eyeLookDownLeft", "eyeLookDownRight",+ "eyeLookInLeft", "eyeLookInRight", "eyeLookOutLeft", "eyeLookOutRight",+ "eyeLookUpLeft", "eyeLookUpRight", "eyeSquintLeft", "eyeSquintRight",+ "eyeWideLeft", "eyeWideRight", "jawForward", "jawLeft", "jawOpen",+ "jawRight", "mouthClose", "mouthDimpleLeft", "mouthDimpleRight",+ "mouthFrownLeft", "mouthFrownRight", "mouthFunnel", "mouthLeft",+ "mouthLowerDownLeft", "mouthLowerDownRight", "mouthPressLeft",+ "mouthPressRight", "mouthPucker", "mouthRight", "mouthRollLower",+ "mouthRollUpper", "mouthShrugLower", "mouthShrugUpper", "mouthSmileLeft",+ "mouthSmileRight", "mouthStretchLeft", "mouthStretchRight",+ "mouthUpperUpLeft", "mouthUpperUpRight", "noseSneerLeft", "noseSneerRight",+ "tongueOut",+]++# glTF constant codes (https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html).+_GLTF_FLOAT = 5126+_GLTF_UBYTE = 5121+_GLTF_USHORT = 5123+_GLTF_ARRAY_BUFFER = 34962+_MAX_INFLUENCES = 4 # glTF JOINTS_0/WEIGHTS_0 carry 4 influences per set+++def _append_view(glb, blob: bytearray, data: bytes, target: int | None = None) -> int:+ """Append `data` to the GLB binary buffer (4-byte aligned) and return the+ index of a new bufferView covering it."""+ while len(blob) % 4 != 0:+ blob.append(0)+ offset = len(blob)+ blob.extend(data)+ bv = pygltflib.BufferView(buffer=0, byteOffset=offset, byteLength=len(data))+ if target is not None:+ bv.target = target+ glb.bufferViews.append(bv)+ return len(glb.bufferViews) - 1+++def _add_accessor(glb, view: int, comp: int, count: int, typ: str,+ mn=None, mx=None) -> int:+ acc = pygltflib.Accessor(+ bufferView=view, byteOffset=0, componentType=comp, count=count, type=typ,+ )+ if mn is not None:+ acc.min = mn+ if mx is not None:+ acc.max = mx+ glb.accessors.append(acc)+ 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."""+ acc = glb.accessors[acc_idx]+ if acc.componentType != _GLTF_FLOAT or acc.type != "VEC3":+ raise RuntimeError(+ f"unsupported POSITION accessor (componentType={acc.componentType}, type={acc.type}); "+ "skinning expects float32 VEC3 positions"+ )+ 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.+ raw = np.frombuffer(bytes(blob[base:base + stride * n]), dtype=np.uint8).reshape(n, stride)+ return raw[:, :12].copy().view("<f4").reshape(n, 3)+++def _quat_to_mat3(x, y, z, w):+ n = x * x + y * y + z * z + w * w+ if n < 1e-12:+ return np.eye(3)+ s = 2.0 / n+ return np.array([+ [1 - s * (y * y + z * z), s * (x * y - z * w), s * (x * z + y * w)],+ [s * (x * y + z * w), 1 - s * (x * x + z * z), s * (y * z - x * w)],+ [s * (x * z - y * w), s * (y * z + x * w), 1 - s * (x * x + y * y)],+ ])+++def _local_matrix(node) -> np.ndarray:+ if node.matrix:+ # glTF stores matrices column-major; transpose to math (row-major) form.+ return np.array(node.matrix, dtype=np.float64).reshape(4, 4).T+ m = np.eye(4)+ if node.rotation:+ m[:3, :3] = _quat_to_mat3(*node.rotation)+ if node.scale:+ m[:3, :3] = m[:3, :3] @ np.diag(node.scale)+ if node.translation:+ m[:3, 3] = node.translation+ return m+++def _world_matrices(glb) -> list[np.ndarray]:+ """World transform of every node, composed down the hierarchy."""+ n = len(glb.nodes)+ local = [_local_matrix(glb.nodes[i]) for i in range(n)]+ parent = {}+ for i, nd in enumerate(glb.nodes):+ for c in (nd.children or []):+ parent[c] = i+ world: list[np.ndarray | None] = [None] * n++ def compute(i):+ if world[i] is None:+ p = parent.get(i)+ world[i] = local[i] if p is None else compute(p) @ local[i]+ return world[i]++ return [compute(i) for i in range(n)]+++def _normalize_blendshapes(data):+ """Coerce UniRig's blendshape output into (names, deltas[K,V,3]). Accepts a+ {name: (V,3)} dict, a {"names":[...], "deltas": array} dict, or a bare+ (K,V,3) array (named positionally from ARKIT_52_BLENDSHAPES)."""+ if isinstance(data, dict):+ if "deltas" in data:+ deltas = np.asarray(data["deltas"], dtype=np.float32)+ names = list(data.get("names") or ARKIT_52_BLENDSHAPES[: len(deltas)])+ else:+ names = list(data.keys())+ deltas = np.stack([np.asarray(data[k], dtype=np.float32) for k in names], axis=0)+ else:+ deltas = np.asarray(data, dtype=np.float32)+ names = list(ARKIT_52_BLENDSHAPES[: len(deltas)])+ if deltas.ndim != 3 or deltas.shape[-1] != 3:+ raise RuntimeError(f"blendshape deltas must be (K,V,3); got {deltas.shape}")+ if len(names) < len(deltas):+ names += [f"blendshape_{i}" for i in range(len(names), len(deltas))]+ return names[: len(deltas)], deltas+++def _top_influences(weights, n_joints):+ """Sanitize the (V,J) weight matrix and reduce it to (V,4) joint indices ++ (V,4) normalized weights. Every vertex is guaranteed a unit weight sum: a+ vertex the model left empty is pinned to joint 0 rather than collapsing to+ the origin under linear-blend skinning."""+ w = np.nan_to_num(np.asarray(weights, dtype=np.float32),+ nan=0.0, posinf=0.0, neginf=0.0)+ np.clip(w, 0.0, None, out=w)+ if w.shape[1] < _MAX_INFLUENCES:+ w = np.pad(w, ((0, 0), (0, _MAX_INFLUENCES - w.shape[1])))++ order = np.argsort(-w, axis=1)[:, :_MAX_INFLUENCES]+ top = np.take_along_axis(w, order, axis=1).astype(np.float32)++ empty = top.sum(axis=1) <= 0.0+ if empty.any():+ order[empty] = 0+ top[empty] = 0.0+ top[empty, 0] = 1.0++ top /= top.sum(axis=1, keepdims=True)+ joint_idx = np.clip(order, 0, max(n_joints - 1, 0))+ return joint_idx, top+++def build_rigged_glb(mesh_bytes, mesh, joints, parents, weights, blendshape_data=None):+ """Author a fully rigged GLB from the raw mesh and UniRig's predictions.+ Returns the serialized GLB bytes. `mesh` is the trimesh the weights were+ computed over; `joints` (J,3) world-space, `parents` (J,), `weights` (V,J)."""+ glb = pygltflib.GLTF2.load_from_bytes(mesh_bytes)+ blob = bytearray(glb.binary_blob() or b"")++ joints = np.asarray(joints, dtype=np.float32).reshape(-1, 3) # (J,3) world-space+ parents = np.asarray(parents).astype(np.int64).reshape(-1) # (J,)+ n_joints = joints.shape[0]+ n_verts = len(mesh.vertices)+ weights = np.asarray(weights, dtype=np.float32) # (V,J)+ if parents.shape[0] != n_joints:+ raise RuntimeError(f"joints/parents length mismatch: {n_joints} vs {parents.shape[0]}")+ if weights.ndim != 2 or weights.shape[1] != n_joints:+ raise RuntimeError(f"skinning weights must be (V,{n_joints}); got {weights.shape}")+ if weights.shape[0] != n_verts:+ raise RuntimeError(+ f"weights rows ({weights.shape[0]}) != mesh vertices ({n_verts}); "+ "UniRig output is not aligned to the input mesh"+ )++ if not glb.scenes:+ glb.scenes.append(pygltflib.Scene(nodes=[]))+ scene = glb.scenes[glb.scene if glb.scene is not None else 0]++ # World transforms of the ORIGINAL nodes (before we add joint nodes), used+ # to (a) match weights in the same space the joints live in and (b) reject+ # a transformed skinned node whose bind pose we cannot honor.+ world_mats = _world_matrices(glb)++ # ── joint nodes (parent-relative translations; identity bind rotations) ──+ base_node = len(glb.nodes)+ joint_nodes = [base_node + i for i in range(n_joints)]+ child_map: dict[int, list[int]] = {i: [] for i in range(n_joints)}+ for i in range(n_joints):+ p = int(parents[i])+ if 0 <= p < n_joints:+ child_map[p].append(joint_nodes[i])+ named = n_joints == len(WOLF3D_JOINTS)+ for i in range(n_joints):+ p = int(parents[i])+ origin = joints[p] if 0 <= p < n_joints else np.zeros(3, dtype=np.float32)+ local = (joints[i] - origin).astype(float)+ node = pygltflib.Node(+ name=WOLF3D_JOINTS[i] if named else f"joint_{i}",+ translation=[local[0], local[1], local[2]],+ )+ if child_map[i]:+ node.children = child_map[i]+ glb.nodes.append(node)+ roots = [joint_nodes[i] for i in range(n_joints) if not 0 <= int(parents[i]) < n_joints]+ for r in roots:+ if r not in scene.nodes:+ scene.nodes.append(r)++ # ── inverseBindMatrices: inverse(world bind) = translate(-world), col-major ──+ ibm = np.zeros((n_joints, 16), dtype=np.float32)+ ibm[:, 0] = ibm[:, 5] = ibm[:, 10] = ibm[:, 15] = 1.0+ ibm[:, 12] = -joints[:, 0]+ ibm[:, 13] = -joints[:, 1]+ ibm[:, 14] = -joints[:, 2]+ ibm_acc = _add_accessor(glb, _append_view(glb, blob, ibm.tobytes()), _GLTF_FLOAT, n_joints, "MAT4")++ skin = pygltflib.Skin(joints=joint_nodes, inverseBindMatrices=ibm_acc)+ if roots:+ skin.skeleton = roots[0]+ glb.skins.append(skin)+ skin_idx = len(glb.skins) - 1++ # Smallest legal integer width for joint indices (u8 covers our 25 joints).+ if n_joints <= 256:+ joint_comp, joint_dtype = _GLTF_UBYTE, np.uint8+ elif n_joints <= 65536:+ joint_comp, joint_dtype = _GLTF_USHORT, np.uint16+ else:+ raise RuntimeError(f"too many joints for glTF skinning: {n_joints}")++ joint_idx, top_w = _top_influences(weights, n_joints) # (V,4) over mesh vertex order+ kdt = cKDTree(np.asarray(mesh.vertices, dtype=np.float32))+ blend = _normalize_blendshapes(blendshape_data) if blendshape_data is not None else None+ bs_deltas = blend[1] if blend else None++ # ── map original nodes → meshes, so we can attach the skin to the right node ──+ mesh_to_nodes: dict[int, list[int]] = {}+ for ni in range(base_node):+ node = glb.nodes[ni]+ if node.mesh is not None:+ mesh_to_nodes.setdefault(node.mesh, []).append(ni)++ 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):+ raise RuntimeError(+ f"mesh {mi} is drawn by a node with a non-identity transform; "+ "bake the transform into the geometry before rigging"+ )++ 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]+ _, nearest = kdt.query(world_pos, k=1) # (M,) → mesh vertex index+ nearest = np.asarray(nearest).reshape(-1)++ j0 = np.ascontiguousarray(joint_idx[nearest].astype(joint_dtype))+ 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")+ prim.attributes.WEIGHTS_0 = _add_accessor(+ glb, _append_view(glb, blob, w0.tobytes(), _GLTF_ARRAY_BUFFER),+ _GLTF_FLOAT, verts.shape[0], "VEC4")++ if bs_deltas is not None:+ targets = []+ for dlt in bs_deltas:+ d = np.ascontiguousarray(np.asarray(dlt, dtype=np.float32)[nearest]) # (M,3)+ acc = _add_accessor(+ glb, _append_view(glb, blob, d.tobytes(), _GLTF_ARRAY_BUFFER),+ _GLTF_FLOAT, verts.shape[0], "VEC3",+ mn=d.min(axis=0).tolist(), mx=d.max(axis=0).tolist())+ targets.append(pygltflib.Attributes(POSITION=acc))+ prim.targets = targets+ mesh_targets = len(targets)+ skinned_any = True++ if mesh_targets:+ gmesh.weights = [0.0] * mesh_targets+ gmesh.extras = {**(gmesh.extras or {}), "targetNames": blend[0]}++ # Bind the skin to every node that draws this mesh (create one if none).+ if not nodes:+ new_ni = len(glb.nodes)+ glb.nodes.append(pygltflib.Node(mesh=mi, skin=skin_idx))+ scene.nodes.append(new_ni)+ else:+ for ni in nodes:+ glb.nodes[ni].skin = skin_idx++ if not skinned_any:+ raise RuntimeError("no mesh primitive with POSITION found — cannot rig")++ log.info(+ "Rigged GLB: %d joints (%s indices), 4 influences/vertex, %d morph targets",+ n_joints, "u8" if joint_comp == _GLTF_UBYTE else "u16",+ len(blend[0]) if blend else 0,+ )++ # ── serialize (pygltflib 1.16.x returns a list of chunks) ──+ glb.set_binary_blob(bytes(blob))+ if not glb.buffers:+ glb.buffers.append(pygltflib.Buffer())+ glb.buffers[0].byteLength = len(blob)+ out = glb.save_to_bytes()+ return b"".join(out) if isinstance(out, (list, tuple)) else outdiff --git a/workers/unirig/test_rig_glb.py b/workers/unirig/test_rig_glb.pynew file mode 100644index 000000000..6f769c719--- /dev/null+++ b/workers/unirig/test_rig_glb.py@@ -0,0 +1,225 @@+"""+Isolated test for rig_glb.build_rigged_glb — verifies it turns a raw mesh GLB+plus a (fabricated) UniRig skeleton/weights prediction into a spec-valid skinned+glTF. Runs with no GPU / torch / GCP: `python3 test_rig_glb.py`.++Validates the things that actually make a GLB "rigged":+ • exactly one skin, joints + inverseBindMatrices present and sized to J+ • JOINTS_0 / WEIGHTS_0 on every primitive, counts == vertex count+ • per-vertex weights sum to 1 and joint indices are in range+ • the drawing node references the skin; a joint root is in the scene+ • original geometry (vertex count) preserved; buffer length consistent+ • optional morph-target (blendshape) injection wires targets + names+"""++import io+import sys++import numpy as np+import pygltflib+import trimesh++from rig_glb import build_rigged_glb++_COMP = {5126: ("<f4", 4), 5121: ("<u1", 1), 5123: ("<u2", 2), 5125: ("<u4", 4)}+_NCOMP = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}+++def _decode(glb, blob, acc_idx):+ acc = glb.accessors[acc_idx]+ bv = glb.bufferViews[acc.bufferView]+ base = (bv.byteOffset or 0) + (acc.byteOffset or 0)+ dt, size = _COMP[acc.componentType]+ nc = _NCOMP[acc.type]+ stride = bv.byteStride or (size * nc)+ out = np.empty((acc.count, nc), dtype=dt)+ for i in range(acc.count):+ off = base + i * stride+ out[i] = np.frombuffer(bytes(blob[off:off + size * nc]), dtype=dt)+ return out+++def _make_mesh_glb():+ # A box subdivided so weights vary across vertices; exported as a GLB the+ # same way the model services emit one.+ mesh = trimesh.creation.box(extents=(1.0, 2.0, 1.0))+ mesh = mesh.subdivide().subdivide()+ glb_bytes = trimesh.Scene(mesh).export(file_type="glb")+ loaded = trimesh.load(io.BytesIO(glb_bytes), file_type="glb", force="mesh")+ return glb_bytes, loaded+++def _fake_unirig(mesh, n_joints=3):+ # A vertical spine of n_joints joints; weights blend by vertical position.+ ys = mesh.vertices[:, 1]+ lo, hi = ys.min(), ys.max()+ centers = np.linspace(lo, hi, n_joints)+ joints = np.zeros((n_joints, 3), dtype=np.float32)+ joints[:, 1] = centers+ parents = np.array([-1] + list(range(n_joints - 1)), dtype=np.int64)+ span = (hi - lo) / max(n_joints - 1, 1)+ d = np.abs(ys[:, None] - centers[None, :])+ weights = np.maximum(0.0, 1.0 - d / span).astype(np.float32) # (V, J) tent weights+ weights[weights.sum(1) == 0, 0] = 1.0+ return joints, parents, weights+++def _check(cond, msg):+ if not cond:+ print(f" ✗ {msg}")+ raise AssertionError(msg)+ print(f" ✓ {msg}")+++def test_skeleton_and_skinning():+ print("test_skeleton_and_skinning")+ glb_bytes, mesh = _make_mesh_glb()+ joints, parents, weights = _fake_unirig(mesh, n_joints=3)+ in_pos_count = len(mesh.vertices)++ out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights, None)+ _check(isinstance(out, (bytes, bytearray)) and len(out) > len(glb_bytes),+ "produced a larger GLB (skin data appended)")++ glb = pygltflib.GLTF2.load_from_bytes(out)+ blob = bytearray(glb.binary_blob())++ _check(len(glb.skins) == 1, "exactly one skin")+ skin = glb.skins[0]+ _check(len(skin.joints) == 3, "skin.joints has J entries")+ _check(skin.inverseBindMatrices is not None, "inverseBindMatrices present")+ ibm = glb.accessors[skin.inverseBindMatrices]+ _check(ibm.type == "MAT4" and ibm.count == 3, "IBM accessor is MAT4 × J")++ scene = glb.scenes[glb.scene or 0]+ _check(any(r in scene.nodes for r in skin.joints), "a joint node is in the scene")++ skinned_nodes = [n for n in glb.nodes if n.mesh is not None and n.skin is not None]+ _check(len(skinned_nodes) >= 1, "a drawing node references the skin")++ total_prims = 0+ for gmesh in glb.meshes:+ for prim in gmesh.primitives:+ if getattr(prim.attributes, "POSITION", None) is None:+ continue+ total_prims += 1+ pos = glb.accessors[prim.attributes.POSITION]+ _check(prim.attributes.JOINTS_0 is not None, "primitive has JOINTS_0")+ _check(prim.attributes.WEIGHTS_0 is not None, "primitive has WEIGHTS_0")+ jacc = glb.accessors[prim.attributes.JOINTS_0]+ wacc = glb.accessors[prim.attributes.WEIGHTS_0]+ _check(jacc.count == pos.count and wacc.count == pos.count,+ "JOINTS_0/WEIGHTS_0 counts match POSITION")+ _check(jacc.componentType == 5121,+ "JOINTS_0 uses compact UNSIGNED_BYTE for <=256 joints")+ _check(pos.count == in_pos_count, "vertex count preserved")++ jv = _decode(glb, blob, prim.attributes.JOINTS_0)+ wv = _decode(glb, blob, prim.attributes.WEIGHTS_0)+ _check(jv.min() >= 0 and jv.max() < len(skin.joints),+ "all joint indices in range")+ sums = wv.sum(axis=1)+ _check(np.allclose(sums, 1.0, atol=1e-4),+ f"every vertex's weights sum to 1 (max err {np.abs(sums-1).max():.2e})")+ _check(total_prims >= 1, "at least one primitive skinned")++ _check(glb.buffers[0].byteLength == len(blob), "buffer byteLength matches binary blob")+++def test_blendshape_targets():+ print("test_blendshape_targets")+ glb_bytes, mesh = _make_mesh_glb()+ joints, parents, weights = _fake_unirig(mesh, n_joints=3)+ V = len(mesh.vertices)+ deltas = np.stack([+ np.tile(np.array([0.0, 0.05, 0.0], np.float32), (V, 1)), # "jawOpen"-ish+ np.tile(np.array([0.03, 0.0, 0.0], np.float32), (V, 1)),+ ], axis=0)++ out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights,+ {"names": ["jawOpen", "mouthLeft"], "deltas": deltas})+ glb = pygltflib.GLTF2.load_from_bytes(out)++ found = False+ for gmesh in glb.meshes:+ for prim in gmesh.primitives:+ if getattr(prim.attributes, "POSITION", None) is None:+ continue+ _check(prim.targets is not None and len(prim.targets) == 2,+ "primitive has 2 morph targets")+ # pygltflib reloads morph targets as plain dicts ({"POSITION": n}).+ tgt_pos = [t["POSITION"] if isinstance(t, dict) else t.POSITION for t in prim.targets]+ _check(all(p is not None for p in tgt_pos),+ "each morph target has a POSITION delta accessor")+ found = True+ if found:+ _check(gmesh.weights == [0.0, 0.0], "mesh.weights initialized per target")+ _check((gmesh.extras or {}).get("targetNames") == ["jawOpen", "mouthLeft"],+ "targetNames recorded in mesh.extras")+ _check(found, "blendshape primitive found")+++def test_dirty_weights_no_collapse():+ """NaN/Inf/negative weights are sanitized and empty vertices are pinned to a+ joint, so every vertex keeps a unit weight sum (no skinning collapse)."""+ print("test_dirty_weights_no_collapse")+ glb_bytes, mesh = _make_mesh_glb()+ joints, parents, weights = _fake_unirig(mesh, n_joints=3)+ # Corrupt the model output: a block of all-zero rows, plus NaN/Inf/negative.+ weights[: len(weights) // 4] = 0.0+ weights[len(weights) // 4] = [np.nan, np.inf, -5.0]++ out = build_rigged_glb(glb_bytes, mesh, joints, parents, weights, None)+ glb = pygltflib.GLTF2.load_from_bytes(out)+ blob = bytearray(glb.binary_blob())+ checked = 0+ for gmesh in glb.meshes:+ for prim in gmesh.primitives:+ if getattr(prim.attributes, "WEIGHTS_0", None) is None:+ continue+ wv = _decode(glb, blob, prim.attributes.WEIGHTS_0)+ jv = _decode(glb, blob, prim.attributes.JOINTS_0)+ _check(np.all(np.isfinite(wv)), "no NaN/Inf in output weights")+ _check(np.all(wv >= 0), "no negative output weights")+ _check(np.allclose(wv.sum(axis=1), 1.0, atol=1e-4),+ "every vertex sums to 1 even from corrupt input (no collapse)")+ _check(jv.max() < len(glb.skins[0].joints), "joint indices in range")+ checked += 1+ _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()+ g = pygltflib.GLTF2.load_from_bytes(glb_bytes)+ moved = False+ for node in g.nodes:+ if node.mesh is not None:+ node.translation = [0.5, 0.0, 0.0]+ moved = True+ _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+ moved_mesh = trimesh.load(io.BytesIO(moved_bytes), file_type="glb", force="mesh")+ joints, parents, weights = _fake_unirig(moved_mesh, n_joints=3)++ try:+ build_rigged_glb(moved_bytes, moved_mesh, joints, parents, weights, None)+ except RuntimeError as exc:+ _check("non-identity" in str(exc), "raised a clear non-identity transform error")+ return+ _check(False, "expected RuntimeError for non-identity node transform")+++if __name__ == "__main__":+ try:+ test_skeleton_and_skinning()+ test_blendshape_targets()+ test_dirty_weights_no_collapse()+ test_nonidentity_node_rejected()+ except AssertionError:+ print("\nFAILED")+ sys.exit(1)+ print("\nALL PASSED")