# /// script # requires-python = ">=3.10" # dependencies = ["usd-core"] # /// """Make the 3D previews the Space's viewer loads: previews/.glb + previews/.json. For each package in projectsim/simready-assets (read-only; nothing is written to the dataset) this downloads simready_usd/ (without thumbnails) to a temporary folder, converts the USD to a small Draco GLB with Blender (tools/blender_glb.py), and writes the rig: one entry per hinge or slider joint with its parent and child part, pivot, axis and range, in the GLB's Y-up metres. Parts are matched to GLB nodes by USD prim name. Previews are cached in tools/preview_cache.json by package id, so a rerun only converts new or changed packages. Run from the Space folder: HF_TOKEN=$(hf auth token) uv run tools/make_previews.py [asset ...] (the token only raises Hugging Face's download rate limit; nothing is uploaded) """ import argparse import json import os import re import struct import subprocess import sys import tempfile import time import urllib.error import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor from pxr import Gf, Usd, UsdGeom, UsdPhysics sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from build_catalog import HF, get_json, hidden_assets, list_files # noqa: E402 BLENDER = "/Applications/Blender.app/Contents/MacOS/Blender" AXES = {"X": Gf.Vec3d(1, 0, 0), "Y": Gf.Vec3d(0, 1, 0), "Z": Gf.Vec3d(0, 0, 1)} def rig(usd_path): """Hinge and slider joints with pivot and axis in GLB space (Y-up metres).""" stage = Usd.Stage.Open(usd_path) mpu = UsdGeom.GetStageMetersPerUnit(stage) or 1.0 zup = UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z to_gltf = (lambda v: [v[0], v[2], -v[1]]) if zup else (lambda v: [v[0], v[1], v[2]]) cache = UsdGeom.XformCache() joints = [] for prim in stage.Traverse(Usd.TraverseInstanceProxies()): if prim.IsA(UsdPhysics.RevoluteJoint): kind, typed = "hinge", UsdPhysics.RevoluteJoint(prim) elif prim.IsA(UsdPhysics.PrismaticJoint): kind, typed = "slider", UsdPhysics.PrismaticJoint(prim) else: continue j = UsdPhysics.Joint(prim) b0 = j.GetBody0Rel().GetTargets() b1 = j.GetBody1Rel().GetTargets() if not b1: continue world0 = cache.GetLocalToWorldTransform(stage.GetPrimAtPath(b0[0])) if b0 else Gf.Matrix4d(1) pos = Gf.Vec3d(j.GetLocalPos0Attr().Get() or Gf.Vec3f(0)) rot = j.GetLocalRot0Attr().Get() or Gf.Quatf(1) axis_local = Gf.Rotation(Gf.Quatd(rot)).TransformDir(AXES.get(typed.GetAxisAttr().Get(), AXES["X"])) pivot = world0.Transform(pos) * mpu axis = world0.TransformDir(axis_local).GetNormalized() lo, hi = typed.GetLowerLimitAttr().Get(), typed.GetUpperLimitAttr().Get() limited = lo is not None and hi is not None and abs(hi - lo) < 1e6 scale = 1.0 if kind == "hinge" else mpu joints.append({ "name": prim.GetName(), "type": kind, "parent": b0[0].name if b0 else None, "child": b1[0].name, "pivot": [round(x, 6) for x in to_gltf(pivot)], "axis": [round(x, 6) for x in to_gltf(axis)], "lower": round(lo * scale, 6) if limited else None, "upper": round(hi * scale, 6) if limited else None, }) # parents before children, so the viewer can chain joints in one pass order, placed = [], set() while len(order) < len(joints): before = len(order) for jt in joints: if jt["name"] not in placed and (jt["parent"] is None or jt["parent"] not in {k["child"] for k in joints if k["name"] not in placed}): order.append(jt); placed.add(jt["name"]) if len(order) == before: # a loop: keep the rest as they are order += [jt for jt in joints if jt["name"] not in placed] break return order def download(url, dest, tries=6): """GET with an optional HF_TOKEN (higher rate limits) and backoff on 429/5xx.""" headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"} if os.environ.get("HF_TOKEN") else {} for attempt in range(tries): try: with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=300) as r, open(dest, "wb") as f: while chunk := r.read(1 << 20): f.write(chunk) return except urllib.error.HTTPError as e: if e.code not in (429, 500, 502, 503, 504) or attempt == tries - 1: raise wait = int(e.headers.get("Retry-After") or 0) or 15 * (attempt + 1) time.sleep(min(wait, 300)) def glb_node_names(path): data = open(path, "rb").read() n = struct.unpack_from("