main
Drew Owens Fix contralateral leg-frame and torso-shell CAD bug, regenerate single-solid STLs/GLB/Bambu/MJCF/USD/clearance, and ali… 9a64946
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
#!/usr/bin/env python3
"""Build Microgoose multi-layer annotated 3D Hero GLB (docs/3d/microgoose-hero.glb)
and render the 4 high-resolution (1920x1200) dark-themed (#0d1317) studio PNGs in screenshots/.

Run with:
    MUJOCO_GL=egl python3 mechanical/build_hero_glb.py
"""

from __future__ import annotations

import json
import math
import os
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

os.environ.setdefault("MUJOCO_GL", "egl")

import mujoco
import numpy as np
import pygltflib
import trimesh
from PIL import Image, ImageDraw, ImageFont


ROOT_DIR = Path(__file__).resolve().parents[1]
MECH_DIR = ROOT_DIR / "mechanical"
STL_DIR = MECH_DIR / "stl"
PLATES_DIR = STL_DIR / "plates"
HERO_MESH_DIR = MECH_DIR / "parts" / "hero_meshes"
MANIFEST_PATH = HERO_MESH_DIR / "manifest.json"
MASS_PROPS_PATH = MECH_DIR / "kinematics_mass_props.json"
INTERF_PATH = MECH_DIR / "interference-report.json"
SLICE_REPORT_PATH = MECH_DIR / "bambu_slice_report.json"
GLB_OUT_PATH = ROOT_DIR / "docs" / "3d" / "microgoose-hero.glb"
SPINE_GLB_PATH = ROOT_DIR / "docs" / "3d" / "microgoose-spine.glb"
REAL_SPINE_MESH_DIR = HERO_MESH_DIR / "real_spine"
SCREENSHOTS_DIR = ROOT_DIR / "screenshots"

# Brand dark palette (#0d1317 background, crisp slate cards, teal/orange accents)
BG_HEX = "#0d1317"
BG_RGB = (13, 19, 23)
CARD_BG = (20, 29, 36, 232)
CARD_BORDER = (51, 72, 88, 255)
TEXT_MAIN = (241, 245, 249, 255)
TEXT_MUTED = (148, 163, 184, 255)
ACCENT_TEAL = (0, 230, 220, 255)
ACCENT_ORANGE = (249, 115, 22, 255)
ACCENT_GREEN = (34, 197, 94, 255)
ACCENT_BLUE = (59, 130, 246, 255)


PBR_MATERIALS: Dict[str, Dict[str, Any]] = {
    "goose_white": {"rgba": [0.945, 0.961, 0.976, 1.0], "metallic": 0.04, "roughness": 0.58},
    "goose_orange": {"rgba": [0.976, 0.451, 0.086, 1.0], "metallic": 0.06, "roughness": 0.46},
    "carbon_petg": {"rgba": [0.118, 0.161, 0.231, 1.0], "metallic": 0.18, "roughness": 0.52},
    "xl330_charcoal": {"rgba": [0.082, 0.106, 0.153, 1.0], "metallic": 0.28, "roughness": 0.38},
    "pcb_fr4": {"rgba": [0.020, 0.588, 0.412, 1.0], "metallic": 0.14, "roughness": 0.36},
    "spine_pcb_emerald": {"rgba": [0.020, 0.588, 0.412, 1.0], "metallic": 0.14, "roughness": 0.36},
    "gold_pin": {"rgba": [0.918, 0.702, 0.031, 1.0], "metallic": 0.88, "roughness": 0.22},
    "gold_pins": {"rgba": [0.918, 0.702, 0.031, 1.0], "metallic": 0.88, "roughness": 0.22},
    "jst_ivory": {"rgba": [0.886, 0.910, 0.941, 1.0], "metallic": 0.05, "roughness": 0.45},
    "ic_dark": {"rgba": [0.110, 0.115, 0.130, 1.0], "metallic": 0.22, "roughness": 0.36},
    "ic_charcoal": {"rgba": [0.110, 0.115, 0.130, 1.0], "metallic": 0.22, "roughness": 0.36},
    "passive_tan": {"rgba": [0.765, 0.612, 0.404, 1.0], "metallic": 0.15, "roughness": 0.42},
    "led_green": {"rgba": [0.133, 0.900, 0.420, 1.0], "metallic": 0.05, "roughness": 0.25},
    "radxa_blue": {"rgba": [0.114, 0.306, 0.847, 1.0], "metallic": 0.20, "roughness": 0.38},
    "battery_pack": {"rgba": [0.160, 0.168, 0.185, 1.0], "metallic": 0.16, "roughness": 0.48},
    "steel_silver": {"rgba": [0.796, 0.835, 0.882, 1.0], "metallic": 0.85, "roughness": 0.25},
    "fov_cone": {
        "rgba": [0.0, 0.902, 0.863, 0.26],
        "metallic": 0.0,
        "roughness": 0.35,
        "alphaMode": "BLEND",
        "doubleSided": True,
    },
    "wire_red": {"rgba": [0.937, 0.267, 0.267, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_black": {"rgba": [0.145, 0.180, 0.235, 1.0], "metallic": 0.08, "roughness": 0.36},
    "wire_yellow": {"rgba": [0.918, 0.702, 0.031, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_orange": {"rgba": [0.976, 0.451, 0.086, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_green": {"rgba": [0.133, 0.773, 0.369, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_blue": {"rgba": [0.231, 0.510, 0.965, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_purple": {"rgba": [0.659, 0.333, 0.969, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_cyan": {"rgba": [0.024, 0.714, 0.831, 1.0], "metallic": 0.08, "roughness": 0.34},
    "wire_white": {"rgba": [0.886, 0.910, 0.941, 1.0], "metallic": 0.08, "roughness": 0.34},
}


def load_font(size: int, bold: bool = False, mono: bool = False) -> ImageFont.FreeTypeFont:
    candidates = []
    if mono:
        candidates = [
            "/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
            "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
        ]
    else:
        candidates = [
            "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
            "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf" if bold else "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
        ]
    for p in candidates:
        if Path(p).exists():
            return ImageFont.truetype(p, size=size)
    return ImageFont.load_default()


def prepare_crease_normals_metres(stl_path: Path, crease_deg: float = 36.0) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Load an STL in mm, scale by 0.001 to metres (Z-up), and compute crisp crease-angle
    vertex normals so curved fillets and wire tubes shade smoothly while sharp edges stay crisp.
    """
    raw = trimesh.load_mesh(str(stl_path), force="mesh", process=False)
    # Build triangle soup scaled to metres
    tris_v = np.asarray(raw.vertices, dtype=np.float64)[np.asarray(raw.faces, dtype=np.int64)] * 0.001
    v0 = tris_v[:, 0, :]
    v1 = tris_v[:, 1, :]
    v2 = tris_v[:, 2, :]
    fn = np.cross(v1 - v0, v2 - v0)
    fl = np.linalg.norm(fn, axis=1, keepdims=True)
    valid = fl[:, 0] > 1e-16
    tris_v = tris_v[valid]
    fn = fn[valid] / fl[valid]

    n_tri = len(tris_v)
    flat_v = tris_v.reshape(-1, 3)
    flat_n = np.repeat(fn, 3, axis=0)

    # Quantize position (0.1 um) + coarse normal bucket so only nearly co-directional normals merge,
    # OR average normals within crease_deg per position cluster:
    pos_key = np.round(flat_v * 1e7).astype(np.int64)
    # Group identical positions using lexsort
    order = np.lexsort((pos_key[:, 2], pos_key[:, 1], pos_key[:, 0]))
    sorted_pos = pos_key[order]
    diff = np.any(sorted_pos[1:] != sorted_pos[:-1], axis=1)
    starts = np.concatenate(([0], np.nonzero(diff)[0] + 1, [len(order)]))

    cos_thresh = math.cos(math.radians(crease_deg))
    smoothed_n = flat_n.copy()

    # Vectorized fast pass for most small groups; loop only over multi-corner groups
    counts = starts[1:] - starts[:-1]
    for g_idx in np.nonzero(counts > 1)[0]:
        s = starts[g_idx]
        e = starts[g_idx + 1]
        idxs = order[s:e]
        gn = flat_n[idxs]
        dots = gn @ gn.T
        adj = dots >= cos_thresh
        summed = adj @ gn
        norms = np.linalg.norm(summed, axis=1, keepdims=True)
        norms = np.maximum(norms, 1e-12)
        smoothed_n[idxs] = summed / norms

    # Deduplicate (position, smoothed_normal) pairs to compact indexed mesh
    pn_key = np.hstack([pos_key, np.round(smoothed_n * 1e4).astype(np.int64)])
    _, unique_first, inverse_idx = np.unique(pn_key, axis=0, return_index=True, return_inverse=True)

    verts_out = flat_v[unique_first].astype(np.float32)
    norms_out = smoothed_n[unique_first].astype(np.float32)
    n_len = np.linalg.norm(norms_out, axis=1, keepdims=True)
    norms_out = norms_out / np.maximum(n_len, 1e-8)
    faces_out = inverse_idx.reshape(n_tri, 3).astype(np.uint32)
    return verts_out, norms_out, faces_out


def make_tof_fov_frustum_metres() -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Build a translucent 45x45 deg VL53L5CX ToF optical frustum starting at the forehead window
    (X=0.0495 m, Y=0.0 m, Z=0.2715 m) projecting +0.135 m forward along +X.
    """
    apex = np.array([0.0495, 0.0, 0.2715], dtype=np.float64)
    dist = 0.135
    half_w = dist * math.tan(math.radians(22.5))
    c0 = apex + np.array([dist, -half_w, -half_w])
    c1 = apex + np.array([dist, +half_w, -half_w])
    c2 = apex + np.array([dist, +half_w, +half_w])
    c3 = apex + np.array([dist, -half_w, +half_w])

    tris = np.array(
        [
            [apex, c0, c1],
            [apex, c1, c2],
            [apex, c2, c3],
            [apex, c3, c0],
        ],
        dtype=np.float64,
    )
    verts = tris.reshape(-1, 3).astype(np.float32)
    norms = np.zeros_like(verts)
    for i in range(4):
        a, b, c = tris[i]
        n = np.cross(b - a, c - a)
        n = n / max(np.linalg.norm(n), 1e-9)
        norms[3 * i : 3 * i + 3] = n.astype(np.float32)
    faces = np.arange(12, dtype=np.uint32).reshape(4, 3)
    return verts, norms, faces


def _quat_to_mat3(q: List[float]) -> np.ndarray:
    x, y, z, w = float(q[0]), float(q[1]), float(q[2]), float(q[3])
    xx, yy, zz = x * x, y * y, z * z
    xy, xz, yz = x * y, x * z, y * z
    wx, wy, wz = w * x, w * y, w * z
    return np.array(
        [
            [1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy)],
            [2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx)],
            [2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy)],
        ],
        dtype=np.float64,
    )


def _node_local_matrix(node: pygltflib.Node) -> np.ndarray:
    if node.matrix is not None and len(node.matrix) == 16:
        return np.array(node.matrix, dtype=np.float64).reshape((4, 4), order="F")
    m = np.eye(4, dtype=np.float64)
    r = _quat_to_mat3(node.rotation) if node.rotation is not None else np.eye(3, dtype=np.float64)
    s = np.array(node.scale if node.scale is not None else [1.0, 1.0, 1.0], dtype=np.float64)
    m[:3, :3] = r * s[None, :]
    if node.translation is not None:
        m[:3, 3] = np.array(node.translation, dtype=np.float64)
    return m


def _decode_gltf_accessor(gltf: pygltflib.GLTF2, blob_mv: memoryview, acc_idx: int) -> np.ndarray:
    acc = gltf.accessors[acc_idx]
    bv = gltf.bufferViews[acc.bufferView]
    base_off = (bv.byteOffset or 0) + (acc.byteOffset or 0)
    num_comp = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4}[acc.type]
    dtype_map = {
        5120: (np.int8, 1, 127.0),
        5121: (np.uint8, 1, 255.0),
        5122: (np.int16, 2, 32767.0),
        5123: (np.uint16, 2, 65535.0),
        5125: (np.uint32, 4, 1.0),
        5126: (np.float32, 4, 1.0),
    }
    np_dt, elem_bytes, norm_div = dtype_map[acc.componentType]
    row_stride = bv.byteStride if bv.byteStride else (num_comp * elem_bytes)
    arr = np.ndarray(
        shape=(acc.count, num_comp),
        dtype=np_dt,
        buffer=blob_mv,
        offset=base_off,
        strides=(row_stride, elem_bytes),
    ).copy()
    if acc.normalized and acc.componentType != 5126:
        arr = np.maximum(arr.astype(np.float64) / norm_div, -1.0)
    return arr


def _write_binary_stl_mm(stl_path: Path, tris_v: np.ndarray) -> int:
    """Write (N, 3, 3) float64/float32 triangle array in mm to binary STL."""
    v0 = tris_v[:, 0, :]
    v1 = tris_v[:, 1, :]
    v2 = tris_v[:, 2, :]
    fn = np.cross(v1 - v0, v2 - v0)
    fl = np.linalg.norm(fn, axis=1, keepdims=True)
    valid = fl[:, 0] > 1e-12
    tris_v = tris_v[valid]
    fn = fn[valid] / fl[valid]
    n_tri = int(len(tris_v))
    if n_tri == 0:
        return 0

    stl_dtype = np.dtype(
        [
            ("normal", "<f4", (3,)),
            ("v0", "<f4", (3,)),
            ("v1", "<f4", (3,)),
            ("v2", "<f4", (3,)),
            ("attr", "<u2"),
        ]
    )
    recs = np.zeros(n_tri, dtype=stl_dtype)
    recs["normal"] = fn.astype("<f4")
    recs["v0"] = tris_v[:, 0, :].astype("<f4")
    recs["v1"] = tris_v[:, 1, :].astype("<f4")
    recs["v2"] = tris_v[:, 2, :].astype("<f4")

    stl_path.parent.mkdir(parents=True, exist_ok=True)
    with stl_path.open("wb") as fh:
        fh.write(b"microgoose copper-accurate spine glb mesh".ljust(80, b"\x00"))
        fh.write(np.uint32(n_tri).tobytes())
        fh.write(recs.tobytes())
    return n_tri


def extract_real_board_meshes_for_mujoco() -> Tuple[List[Dict[str, Any]], Dict[str, Dict[str, Any]]]:
    """Decompose docs/3d/microgoose-spine.glb in exact robot-frame mm into per-material STL files
    and PBR material entries so MuJoCo studio renders show actual copper traces, silkscreen, and 87 parts.
    """
    REAL_SPINE_MESH_DIR.mkdir(parents=True, exist_ok=True)
    for old_f in REAL_SPINE_MESH_DIR.glob("*.stl"):
        old_f.unlink()

    gltf = pygltflib.GLTF2().load(str(SPINE_GLB_PATH))
    blob_bytes = gltf.binary_blob()
    blob_mv = memoryview(blob_bytes)

    # Root transform from KiCad GLB (metres) -> Robot world (mm):
    # p_robot_m = R_z(-90 deg) * p_glb_m + [0.118, 0.132, 0.148], then * 1000.0 to mm
    root_mm = np.array(
        [
            [0.0, 1000.0, 0.0, 118.0],
            [-1000.0, 0.0, 0.0, 132.0],
            [0.0, 0.0, 1000.0, 148.0],
            [0.0, 0.0, 0.0, 1.0],
        ],
        dtype=np.float64,
    )

    mat_tris: Dict[int, List[np.ndarray]] = {}

    def walk_node(n_idx: int, parent_mat: np.ndarray) -> None:
        nd = gltf.nodes[n_idx]
        world_mat = parent_mat @ _node_local_matrix(nd)
        if nd.mesh is not None:
            lin = world_mat[:3, :3]
            trans = world_mat[:3, 3]
            flip_winding = np.linalg.det(lin) < 0.0
            for prim in gltf.meshes[nd.mesh].primitives:
                if prim.mode not in (None, pygltflib.TRIANGLES):
                    continue
                pos_acc = prim.attributes.POSITION
                if pos_acc is None:
                    continue
                pos_local = _decode_gltf_accessor(gltf, blob_mv, pos_acc).astype(np.float64)
                pos_mm = pos_local @ lin.T + trans[None, :]
                if prim.indices is not None:
                    idx_arr = _decode_gltf_accessor(gltf, blob_mv, prim.indices).reshape(-1).astype(np.int64)
                else:
                    idx_arr = np.arange(len(pos_mm), dtype=np.int64)
                n_f = len(idx_arr) // 3
                if n_f == 0:
                    continue
                faces = idx_arr[: 3 * n_f].reshape(n_f, 3)
                if flip_winding:
                    faces = faces[:, [0, 2, 1]]
                tris = pos_mm[faces]
                m_i = prim.material if prim.material is not None else -1
                mat_tris.setdefault(m_i, []).append(tris)
        for ch in nd.children or []:
            walk_node(ch, world_mat)

    orig_roots = list(gltf.scenes[gltf.scene or 0].nodes)
    for r_i in orig_roots:
        walk_node(r_i, root_mm)

    extra_mats: Dict[str, Dict[str, Any]] = {}
    mj_items: List[Dict[str, Any]] = []
    max_tris_per_stl = 140000

    for m_i, tri_chunks in sorted(mat_tris.items()):
        merged = np.concatenate(tri_chunks, axis=0)
        mat_key = f"real_spine_mat_{m_i if m_i >= 0 else 'default'}"
        if 0 <= m_i < len(gltf.materials):
            gm = gltf.materials[m_i]
            pbr = gm.pbrMetallicRoughness
            rgba = list(pbr.baseColorFactor) if (pbr and pbr.baseColorFactor) else [0.75, 0.78, 0.80, 1.0]
            met = float(pbr.metallicFactor) if (pbr and pbr.metallicFactor is not None) else 0.2
            rough = float(pbr.roughnessFactor) if (pbr and pbr.roughnessFactor is not None) else 0.45
        else:
            rgba = [0.75, 0.78, 0.80, 1.0]
            met = 0.2
            rough = 0.45
        extra_mats[mat_key] = {"rgba": rgba, "metallic": met, "roughness": rough}

        for part_idx, start in enumerate(range(0, len(merged), max_tris_per_stl)):
            sub = merged[start : start + max_tris_per_stl]
            stl_p = REAL_SPINE_MESH_DIR / f"{mat_key}_{part_idx}.stl"
            written = _write_binary_stl_mm(stl_p, sub)
            if written > 0:
                mj_items.append(
                    {
                        "nodeName": f"{mat_key}_{part_idx}",
                        "stlPath": str(stl_p),
                        "layer": "electronics_battery",
                        "material": mat_key,
                    }
                )
    return mj_items, extra_mats


def build_hero_glb(manifest: Dict[str, Any]) -> Dict[str, Any]:
    """Assemble docs/3d/microgoose-hero.glb by embedding the real copper-accurate
    docs/3d/microgoose-spine.glb under Layer_Electronics_Battery -> Spine_Board_Root,
    alongside declared adomLayer toggles, PBR materials, hover tooltips, ToF FoV intro cone,
    and all 22 physicalConductorId root wire nodes (0 child primitives).
    """
    gltf = pygltflib.GLTF2().load(str(SPINE_GLB_PATH))
    gltf.asset = pygltflib.Asset(
        version="2.0",
        generator="microgoose-build-hero-glb/2.0-copper-spine",
    )
    orig_board_roots = list(gltf.scenes[gltf.scene or 0].nodes)
    blob = bytearray(gltf.binary_blob())

    # Count existing triangles in real copper-accurate Spine GLB
    board_tris = 0
    for nd in gltf.nodes:
        if nd.mesh is not None:
            for prim in gltf.meshes[nd.mesh].primitives:
                if prim.indices is not None:
                    board_tris += int(gltf.accessors[prim.indices].count) // 3
                elif prim.attributes.POSITION is not None:
                    board_tris += int(gltf.accessors[prim.attributes.POSITION].count) // 3

    mat_index: Dict[str, int] = {}
    for m_name, spec in PBR_MATERIALS.items():
        mat_index[m_name] = len(gltf.materials)
        gltf.materials.append(
            pygltflib.Material(
                name=m_name,
                pbrMetallicRoughness=pygltflib.PbrMetallicRoughness(
                    baseColorFactor=spec["rgba"],
                    metallicFactor=spec["metallic"],
                    roughnessFactor=spec["roughness"],
                ),
                alphaMode=spec.get("alphaMode", pygltflib.OPAQUE),
                doubleSided=bool(spec.get("doubleSided", False)),
            )
        )

    # Create the 4 subsystem root layer group nodes
    layer_defs = [
        (
            "chassis_shells",
            "Layer_Chassis_Shells",
            {"adomLayer": {"key": "chassis_shells", "label": "Chassis Shells", "group": "Structure"}},
        ),
        (
            "actuators_legs",
            "Layer_Actuators_Legs",
            {"adomLayer": {"key": "actuators_legs", "label": "Actuators & Legs", "group": "Motion"}},
        ),
        (
            "electronics_battery",
            "Layer_Electronics_Battery",
            {"adomLayer": {"key": "electronics_battery", "label": "Electronics & Battery", "group": "Avionics"}},
        ),
        (
            "wiring_loom",
            "Layer_Wiring_Loom",
            {"adomLayer": {"key": "wiring_loom", "label": "Wiring Loom", "group": "Avionics"}},
        ),
    ]
    layer_node_idx: Dict[str, int] = {}
    for l_key, n_name, ext in layer_defs:
        idx = len(gltf.nodes)
        layer_node_idx[l_key] = idx
        gltf.nodes.append(pygltflib.Node(name=n_name, children=[], extras=ext))

    # Mount the real copper-accurate Spine GLB scene graph into robot frame (Z = 148.0 mm, R_z(-90 deg))
    spine_root_idx = len(gltf.nodes)
    gltf.nodes.append(
        pygltflib.Node(
            name="Spine_Board_Root",
            translation=[0.118, 0.132, 0.148],
            rotation=[0.0, 0.0, -0.7071067811865475, 0.7071067811865476],
            children=orig_board_roots,
            extras={
                "tooltip": (
                    "Microgoose Spine Rev A Molecule PCB (70x70x1.6 mm)\n"
                    "87 Z-up parts, copper traces & silkscreen\n"
                    "STM32G431 + LMR33640 5V/4A + INA226 + BMI270"
                )
            },
        )
    )
    gltf.nodes[layer_node_idx["electronics_battery"]].children.append(spine_root_idx)

    def append_bytes_aligned(raw_bytes: bytes) -> Tuple[int, int]:
        while len(blob) % 4 != 0:
            blob.append(0)
        offset = len(blob)
        blob.extend(raw_bytes)
        return offset, len(raw_bytes)

    def add_mesh_primitive(mesh_name: str, verts: np.ndarray, norms: np.ndarray, faces: np.ndarray, mat_key: str) -> int:
        v_bytes = verts.astype("<f4").tobytes()
        n_bytes = norms.astype("<f4").tobytes()
        use_u16 = len(verts) <= 65535
        idx_flat = faces.reshape(-1).astype("<u2" if use_u16 else "<u4")
        i_comp_type = pygltflib.UNSIGNED_SHORT if use_u16 else pygltflib.UNSIGNED_INT
        i_bytes = idx_flat.tobytes()

        v_off, v_len = append_bytes_aligned(v_bytes)
        n_off, n_len = append_bytes_aligned(n_bytes)
        i_off, i_len = append_bytes_aligned(i_bytes)

        bv_v = len(gltf.bufferViews)
        gltf.bufferViews.append(pygltflib.BufferView(buffer=0, byteOffset=v_off, byteLength=v_len, target=pygltflib.ARRAY_BUFFER))
        bv_n = len(gltf.bufferViews)
        gltf.bufferViews.append(pygltflib.BufferView(buffer=0, byteOffset=n_off, byteLength=n_len, target=pygltflib.ARRAY_BUFFER))
        bv_i = len(gltf.bufferViews)
        gltf.bufferViews.append(pygltflib.BufferView(buffer=0, byteOffset=i_off, byteLength=i_len, target=pygltflib.ELEMENT_ARRAY_BUFFER))

        acc_v = len(gltf.accessors)
        gltf.accessors.append(
            pygltflib.Accessor(
                bufferView=bv_v,
                byteOffset=0,
                componentType=pygltflib.FLOAT,
                count=int(len(verts)),
                type=pygltflib.VEC3,
                min=[float(x) for x in verts.min(axis=0)],
                max=[float(x) for x in verts.max(axis=0)],
            )
        )
        acc_n = len(gltf.accessors)
        gltf.accessors.append(
            pygltflib.Accessor(
                bufferView=bv_n,
                byteOffset=0,
                componentType=pygltflib.FLOAT,
                count=int(len(norms)),
                type=pygltflib.VEC3,
            )
        )
        acc_i = len(gltf.accessors)
        gltf.accessors.append(
            pygltflib.Accessor(
                bufferView=bv_i,
                byteOffset=0,
                componentType=i_comp_type,
                count=int(len(idx_flat)),
                type=pygltflib.SCALAR,
                min=[int(idx_flat.min())],
                max=[int(idx_flat.max())],
            )
        )

        m_idx = len(gltf.meshes)
        prim = pygltflib.Primitive(
            attributes=pygltflib.Attributes(POSITION=acc_v, NORMAL=acc_n),
            indices=acc_i,
            material=mat_index.get(mat_key, mat_index["carbon_petg"]),
            mode=pygltflib.TRIANGLES,
        )
        gltf.meshes.append(pygltflib.Mesh(name=mesh_name, primitives=[prim]))
        return m_idx

    total_tris = board_tris
    wire_count = 0
    for item in manifest["heroItems"]:
        # Skip STEP-categorized spine_* duplicates because Spine_Board_Root embeds real microgoose-spine.glb
        if item["nodeName"].startswith("spine_"):
            continue
        stl_p = Path(item["stlPath"])
        if not stl_p.is_absolute():
            stl_p = ROOT_DIR / stl_p
        verts, norms, faces = prepare_crease_normals_metres(stl_p)
        total_tris += int(len(faces))
        m_idx = add_mesh_primitive(item["nodeName"], verts, norms, faces, item["material"])

        node_extras: Dict[str, Any] = {"tooltip": item["tooltip"]}
        if "physicalConductorId" in item:
            node_extras["physicalConductorId"] = item["physicalConductorId"]
            wire_count += 1

        n_idx = len(gltf.nodes)
        gltf.nodes.append(
            pygltflib.Node(
                name=item["nodeName"],
                mesh=m_idx,
                children=[],
                extras=node_extras,
            )
        )
        parent_idx = layer_node_idx[item["layer"]]
        gltf.nodes[parent_idx].children.append(n_idx)

    # Add VL53L5CX 8x8 ToF optical cone as hidden layer with Load Intro
    fv, fn, ff = make_tof_fov_frustum_metres()
    fov_mesh_idx = add_mesh_primitive("Adom.FOV.Mesh", fv, fn, ff, "fov_cone")
    fov_node_idx = len(gltf.nodes)
    gltf.nodes.append(
        pygltflib.Node(
            name="Adom.FOV",
            mesh=fov_mesh_idx,
            children=[],
            extras={
                "adomLayer": {
                    "key": "fov",
                    "label": "VL53L5CX 8x8 ToF FoV",
                    "group": "Sensors",
                    "hidden": True,
                    "intro": {
                        "fadeInAt": 1.2,
                        "fadeOutAt": 5.5,
                        "highlightButton": True,
                        "fadeMs": 650,
                    },
                },
                "tooltip": "VL53L5CX 8x8 Multizone ToF Rangefinder FoV\n45x45 deg optical frustum, up to 4.0 m",
            },
        )
    )

    root_nodes = list(layer_node_idx.values()) + [fov_node_idx]
    gltf.scenes = [pygltflib.Scene(name="MicrogooseHeroScene", nodes=root_nodes)]
    gltf.scene = 0
    if gltf.buffers:
        gltf.buffers[0].byteLength = len(blob)
    else:
        gltf.buffers = [pygltflib.Buffer(byteLength=len(blob))]
    gltf.set_binary_blob(bytes(blob))

    GLB_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
    gltf.save_binary(str(GLB_OUT_PATH))
    size_mb = GLB_OUT_PATH.stat().st_size / (1024.0 * 1024.0)
    return {
        "glbPath": str(GLB_OUT_PATH),
        "spineGlbEmbedded": str(SPINE_GLB_PATH),
        "sizeMb": round(size_mb, 3),
        "nodeCount": len(gltf.nodes),
        "meshCount": len(gltf.meshes),
        "materialCount": len(gltf.materials),
        "wireRootNodeCount": wire_count,
        "boardTriangleCount": board_tris,
        "triangleCount": total_tris,
    }


# ---------------- MUJOCO STUDIO RENDERING & PROJECTION HELPERS ----------------

def build_mj_scene_xml(
    items: List[Dict[str, Any]],
    cameras: List[Dict[str, Any]],
    with_pedestal: bool = True,
    scale_str: str = "0.001 0.001 0.001",
    extra_materials: Optional[Dict[str, Dict[str, Any]]] = None,
) -> str:
    """Create a MuJoCo XML scene with #0d1317 dark background, 4096 shadows, and 3-point studio lighting."""
    mj = ET.Element("mujoco", model="microgoose_studio")
    ET.SubElement(mj, "compiler", angle="degree")

    vis = ET.SubElement(mj, "visual")
    ET.SubElement(vis, "global", offwidth="2560", offheight="1600")
    ET.SubElement(vis, "quality", shadowsize="4096", offsamples="4")
    ET.SubElement(vis, "headlight", ambient="0.26 0.28 0.31", diffuse="0.28 0.30 0.34", specular="0.18 0.20 0.22")
    ET.SubElement(vis, "rgba", fog="0.051 0.0745 0.0902 1")

    asset = ET.SubElement(mj, "asset")
    ET.SubElement(
        asset,
        "texture",
        name="sky_dark",
        type="skybox",
        builtin="flat",
        rgb1="0.051 0.0745 0.0902",
        rgb2="0.051 0.0745 0.0902",
        width="64",
        height="64",
    )
    ET.SubElement(
        asset,
        "material",
        name="mat_pedestal",
        rgba="0.082 0.114 0.141 1",
        specular="0.25",
        shininess="0.35",
        reflectance="0.08",
    )
    all_materials: Dict[str, Dict[str, Any]] = dict(PBR_MATERIALS)
    if extra_materials:
        all_materials.update(extra_materials)
    for m_key, mat_spec in all_materials.items():
        rgba = mat_spec["rgba"]
        rgba_s = f"{rgba[0]:.4f} {rgba[1]:.4f} {rgba[2]:.4f} {rgba[3]:.4f}"
        spec_val = 0.15 + 0.55 * mat_spec["metallic"]
        shine_val = max(0.1, 1.0 - mat_spec["roughness"])
        ET.SubElement(
            asset,
            "material",
            name=f"mat_{m_key}",
            rgba=rgba_s,
            specular=f"{spec_val:.3f}",
            shininess=f"{shine_val:.3f}",
        )
    for idx, it in enumerate(items):
        m_name = f"m_{idx}_{it['nodeName']}"
        it["_mjMeshName"] = m_name
        raw_p = Path(it["stlPath"])
        abs_p = raw_p if raw_p.is_absolute() else (ROOT_DIR / raw_p)
        ET.SubElement(asset, "mesh", name=m_name, file=str(abs_p), scale=scale_str, inertia="shell")

    wb = ET.SubElement(mj, "worldbody")
    # 3-point studio lighting (warm-white key, cool-blue rim, soft front fill)
    ET.SubElement(
        wb,
        "light",
        name="key_light",
        pos="0.48 -0.45 0.68",
        dir="-0.52 0.48 -0.70",
        diffuse="0.82 0.83 0.86",
        specular="0.42 0.44 0.48",
        castshadow="true",
    )
    ET.SubElement(
        wb,
        "light",
        name="fill_light",
        pos="0.45 0.52 0.38",
        dir="-0.55 -0.60 -0.58",
        diffuse="0.44 0.48 0.54",
        specular="0.16 0.18 0.22",
        castshadow="false",
    )
    ET.SubElement(
        wb,
        "light",
        name="rim_light",
        pos="-0.50 0.15 0.55",
        dir="0.68 -0.18 -0.70",
        diffuse="0.34 0.44 0.56",
        specular="0.30 0.38 0.48",
        castshadow="false",
    )

    if with_pedestal:
        ET.SubElement(
            wb,
            "geom",
            name="studio_pedestal",
            type="cylinder",
            pos="0.012 0 -0.0022",
            size="0.125 0.002",
            material="mat_pedestal",
            contype="0",
            conaffinity="0",
        )
        ET.SubElement(
            wb,
            "geom",
            name="studio_pedestal_ring",
            type="cylinder",
            pos="0.012 0 -0.0028",
            size="0.128 0.0012",
            rgba="0.0 0.55 0.54 0.65",
            contype="0",
            conaffinity="0",
        )

    for cam in cameras:
        attrs = {
            "name": cam["name"],
            "pos": cam["pos"],
            "xyaxes": cam["xyaxes"],
            "fovy": str(cam["fovy"]),
        }
        if cam.get("orthographic"):
            attrs["orthographic"] = "true"
        ET.SubElement(wb, "camera", **attrs)

    for it in items:
        mat_key = it["material"] if it["material"] in all_materials else "carbon_petg"
        pos_s = it.get("pos", "0 0 0")
        g_attrs = {
            "name": f"g_{it['_mjMeshName']}",
            "type": "mesh",
            "mesh": it["_mjMeshName"],
            "pos": pos_s,
            "material": f"mat_{mat_key}",
            "contype": "0",
            "conaffinity": "0",
        }
        if "overrideRgba" in it:
            rgba = it["overrideRgba"]
            g_attrs["rgba"] = f"{rgba[0]:.4f} {rgba[1]:.4f} {rgba[2]:.4f} {rgba[3]:.4f}"
        ET.SubElement(wb, "geom", **g_attrs)

    return ET.tostring(mj, encoding="unicode")


def make_lookat_camera(
    name: str,
    eye_m: Tuple[float, float, float],
    target_m: Tuple[float, float, float],
    fovy: float = 30.0,
    orthographic: bool = False,
    up_vec: Tuple[float, float, float] = (0.0, 0.0, 1.0),
) -> Dict[str, Any]:
    """Build exact MuJoCo camera dict (pos, xyaxes, fovy) looking from eye_m toward target_m."""
    eye = np.array(eye_m, dtype=np.float64)
    tgt = np.array(target_m, dtype=np.float64)
    up = np.array(up_vec, dtype=np.float64)

    fwd = tgt - eye
    fwd = fwd / np.linalg.norm(fwd)
    right = np.cross(fwd, up)
    if np.linalg.norm(right) < 1e-6:
        right = np.array([1.0, 0.0, 0.0], dtype=np.float64)
    else:
        right = right / np.linalg.norm(right)
    cam_up = np.cross(right, fwd)
    cam_up = cam_up / np.linalg.norm(cam_up)

    return {
        "name": name,
        "pos": f"{eye[0]:.5f} {eye[1]:.5f} {eye[2]:.5f}",
        "xyaxes": f"{right[0]:.6f} {right[1]:.6f} {right[2]:.6f} {cam_up[0]:.6f} {cam_up[1]:.6f} {cam_up[2]:.6f}",
        "fovy": fovy,
        "orthographic": orthographic,
        "_eye": eye,
        "_right": right,
        "_up": cam_up,
        "_fwd": fwd,
    }


def project_point_3d(
    pt_mm: Tuple[float, float, float],
    cam: Dict[str, Any],
    width: int,
    height: int,
) -> Tuple[float, float]:
    """Project 3D point (in mm) into 2D image pixel coordinates (px, py) matching MuJoCo camera."""
    p = np.array(pt_mm, dtype=np.float64) * 0.001
    rel = p - cam["_eye"]
    x_c = float(np.dot(rel, cam["_right"]))
    y_c = float(np.dot(rel, cam["_up"]))
    z_c = float(np.dot(rel, cam["_fwd"]))  # positive depth in front of camera

    aspect = width / float(height)
    if cam.get("orthographic"):
        # In MuJoCo orthographic camera, fovy is the full vertical view extent in metres
        half_h = 0.5 * float(cam["fovy"])
        half_w = half_h * aspect
        u = 0.5 + 0.5 * (x_c / half_w)
        v = 0.5 - 0.5 * (y_c / half_h)
    else:
        z_safe = max(z_c, 1e-4)
        tan_half = math.tan(math.radians(0.5 * float(cam["fovy"])))
        u = 0.5 + 0.5 * (x_c / (z_safe * tan_half * aspect))
        v = 0.5 - 0.5 * (y_c / (z_safe * tan_half))
    return u * width, v * height


def render_mj_camera(xml_str: str, cam_name: str, width: int, height: int) -> Image.Image:
    model = mujoco.MjModel.from_xml_string(xml_str)
    data = mujoco.MjData(model)
    mujoco.mj_forward(model, data)
    renderer = mujoco.Renderer(model, height=height, width=width)
    try:
        renderer.update_scene(data, camera=cam_name)
        rgb = renderer.render()
        return Image.fromarray(rgb)
    finally:
        renderer.close()


# ---------------- CLEAN ENGINEERING CALLOUT & UI HELPERS ----------------

def draw_header_bar(
    draw: ImageDraw.ImageDraw,
    title: str,
    subtitle: str,
    badge_right: str,
    width: int = 1920,
) -> None:
    f_title = load_font(28, bold=True)
    f_sub = load_font(16, bold=False)
    f_badge = load_font(15, bold=True, mono=True)

    draw.rectangle([0, 0, width, 78], fill=(13, 19, 23, 240))
    draw.line([(36, 76), (width - 36, 76)], fill=(42, 62, 78, 255), width=1)
    draw.rounded_rectangle([36, 20, 44, 58], radius=3, fill=ACCENT_TEAL)
    draw.text((58, 15), title, font=f_title, fill=TEXT_MAIN)
    draw.text((58, 49), subtitle, font=f_sub, fill=TEXT_MUTED)

    bbox = draw.textbbox((0, 0), badge_right, font=f_badge)
    bw = (bbox[2] - bbox[0]) + 28
    bx0 = width - 36 - bw
    draw.rounded_rectangle([bx0, 22, width - 36, 56], radius=8, fill=(22, 35, 46, 255), outline=ACCENT_TEAL, width=1)
    draw.text((bx0 + 14, 30), badge_right, font=f_badge, fill=ACCENT_TEAL)


def draw_callout_box(
    draw: ImageDraw.ImageDraw,
    anchor_xy: Tuple[float, float],
    box_xy: Tuple[int, int],
    title: str,
    detail: str,
    accent: Tuple[int, int, int, int] = ACCENT_TEAL,
    box_w: int = 330,
) -> None:
    f_t = load_font(16, bold=True)
    f_d = load_font(13, bold=False)
    bx, by = box_xy
    lines = detail.split("\n")
    box_h = 34 + 19 * len(lines)

    # Leader elbow from anchor_xy to nearest horizontal side of box
    ax, ay = anchor_xy
    if ax < bx:
        attach_x = bx
    elif ax > bx + box_w:
        attach_x = bx + box_w
    else:
        attach_x = bx + box_w // 2
    attach_y = by + box_h // 2
    elbow_x = attach_x - 24 if attach_x == bx else (attach_x + 24 if attach_x == bx + box_w else attach_x)

    draw.line([(ax, ay), (elbow_x, attach_y), (attach_x, attach_y)], fill=accent, width=2)
    draw.ellipse([ax - 5, ay - 5, ax + 5, ay + 5], fill=accent, outline=(13, 19, 23, 255), width=2)

    draw.rounded_rectangle([bx, by, bx + box_w, by + box_h], radius=8, fill=CARD_BG, outline=CARD_BORDER, width=1)
    draw.rounded_rectangle([bx, by, bx + 5, by + box_h], radius=3, fill=accent)
    draw.text((bx + 14, by + 8), title, font=f_t, fill=TEXT_MAIN)
    for i, ln in enumerate(lines):
        draw.text((bx + 14, by + 30 + i * 18), ln, font=f_d, fill=TEXT_MUTED)


def draw_dimension_line(
    draw: ImageDraw.ImageDraw,
    p1: Tuple[float, float],
    p2: Tuple[float, float],
    label: str,
    offset_px: Tuple[float, float] = (0.0, 0.0),
    color: Tuple[int, int, int, int] = ACCENT_TEAL,
) -> None:
    f_dim = load_font(14, bold=True, mono=True)
    x1, y1 = p1[0] + offset_px[0], p1[1] + offset_px[1]
    x2, y2 = p2[0] + offset_px[0], p2[1] + offset_px[1]

    # Extension ticks from p1->(x1,y1) and p2->(x2,y2)
    if abs(offset_px[0]) > 2 or abs(offset_px[1]) > 2:
        draw.line([p1, (x1, y1)], fill=(90, 115, 135, 180), width=1)
        draw.line([p2, (x2, y2)], fill=(90, 115, 135, 180), width=1)

    draw.line([(x1, y1), (x2, y2)], fill=color, width=2)
    # End ticks
    dx, dy = x2 - x1, y2 - y1
    L = max(math.hypot(dx, dy), 1.0)
    nx, ny = -dy / L, dx / L
    for px, py in ((x1, y1), (x2, y2)):
        draw.line([(px - nx * 6, py - ny * 6), (px + nx * 6, py + ny * 6)], fill=color, width=2)

    mx, my = 0.5 * (x1 + x2), 0.5 * (y1 + y2)
    tb = draw.textbbox((0, 0), label, font=f_dim)
    tw, th = tb[2] - tb[0], tb[3] - tb[1]
    draw.rounded_rectangle(
        [mx - tw // 2 - 7, my - th // 2 - 4, mx + tw // 2 + 7, my + th // 2 + 4],
        radius=5,
        fill=(13, 19, 23, 235),
        outline=color,
        width=1,
    )
    draw.text((mx - tw // 2, my - th // 2 - 1), label, font=f_dim, fill=color)


# ---------------- 4 STUDIO SCREENSHOT GENERATORS ----------------

def render_hero_perspective(
    manifest: Dict[str, Any],
    mass_props: Dict[str, Any],
    interf: Dict[str, Any],
    spine_mj_items: List[Dict[str, Any]],
    spine_extra_mats: Dict[str, Dict[str, Any]],
) -> Path:
    W, H = 1920, 1200
    items = [dict(it) for it in manifest["heroItems"] if not it["nodeName"].startswith("spine_")] + [
        dict(it) for it in spine_mj_items
    ]
    cam = make_lookat_camera(
        name="hero_persp",
        eye_m=(0.505, -0.465, 0.270),
        target_m=(0.012, 0.0, 0.132),
        fovy=31.0,
    )
    xml_s = build_mj_scene_xml(items, [cam], with_pedestal=True, extra_materials=spine_extra_mats)
    img = render_mj_camera(xml_s, "hero_persp", W, H).convert("RGBA")
    overlay = Image.new("RGBA", (W, H), (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)

    total_g = mass_props["totalMassKg"] * 1000.0
    h_mm = interf["robotEnvelopeMm"]["standingHeightMm"]
    draw_header_bar(
        draw,
        "MICROGOOSE 15-DOF BIPEDAL ROBOTIC GOOSE",
        "Full Parametric CAD Assembly  |  Populated 70x70 mm Spine Rev A PCB + Radxa Zero 3W + 15x Dynamixel XL330-M288-T",
        f"HEIGHT {h_mm:.1f} MM  |  MASS {total_g:.0f} G  |  0 COLLISIONS",
        W,
    )

    # Left-side callouts
    draw_callout_box(
        draw,
        project_point_3d((-44.0, 0.0, 174.0), cam, W, H),
        (52, 190),
        "Quick-Access Dorsal Hatch",
        "6.8 mm hex-driver ports + SWD window\nCovers Radxa Zero 3W & Spine Molecule",
        ACCENT_TEAL,
        345,
    )
    draw_callout_box(
        draw,
        project_point_3d((-36.0, -18.0, 126.0), cam, W, H),
        (52, 340),
        "Underslung NP-F550 Battery Sled",
        "7.4 V 2S 2600 mAh Li-ion (104 g)\nLowers standing CoM to Z = 135 mm",
        ACCENT_BLUE,
        345,
    )
    draw_callout_box(
        draw,
        project_point_3d((0.0, -34.0, 94.0), cam, W, H),
        (52, 510),
        "5-DoF Biped Leg Kinematics (x2)",
        "Left IDs 1..5, Right IDs 6..10\nPETG-CF brackets, >= 0.8 mm clearances",
        ACCENT_TEAL,
        345,
    )
    draw_callout_box(
        draw,
        project_point_3d((-10.0, -34.0, 4.0), cam, W, H),
        (52, 680),
        "Curved Webbed Goose Foot",
        "84 x 50 mm flat Z = 0.0 mm stance sole\n3 webbed toes + ventral traction grooves",
        ACCENT_ORANGE,
        345,
    )

    # Right-side callouts
    draw_callout_box(
        draw,
        project_point_3d((48.5, 0.0, 272.0), cam, W, H),
        (1495, 165),
        "Sensor Cranium (Z_top = 284.0 mm)",
        "Forward VL53L5CX 8x8 ToF aperture\n+ Head BMI270 6-axis IMU pocket",
        ACCENT_TEAL,
        375,
    )
    draw_callout_box(
        draw,
        project_point_3d((82.0, -8.0, 241.0), cam, W, H),
        (1495, 315),
        "15th-DoF Articulated Honking Beak",
        "Dedicated XL330-M288-T (dxlId = 15)\n0 to 38 deg expressive lower mandible",
        ACCENT_ORANGE,
        375,
    )
    draw_callout_box(
        draw,
        project_point_3d((34.0, -18.0, 205.0), cam, W, H),
        (1495, 475),
        "4-DoF Sculpted Goose S-Neck",
        "IDs 11..14 Neck & Head Pitch/Yaw/Roll\nInternal DXL & I2C cable channels",
        ACCENT_BLUE,
        375,
    )

    # Bottom engineering summary strip
    n_b_solids = interf.get("boardSubsolidsEvaluated", 802)
    cards = [
        ("ACTUATION", "15x XL330-M288-T", "IDs 1..5 L, 6..10 R, 11..15 Neck/Beak"),
        ("AVIONICS STACK", "70x70 mm Spine + Radxa", "87 Z-up parts, MP1..MP4 @ Z=148 mm"),
        ("WIRING BUNDLES", "6 Bundles / 22 Wires", "Min bend >= 4.3x OD, ROM slack"),
        ("OCCT INTERFERENCE", "0 Solid Collisions", f"{n_b_solids} PCB solids + {interf['totalPairsEvaluated']} pairs"),
    ]
    cw = 435
    gap = 22
    start_x = (W - (4 * cw + 3 * gap)) // 2
    f_k = load_font(12, bold=True, mono=True)
    f_v = load_font(18, bold=True)
    f_s = load_font(13, bold=False)
    for idx, (k, v, s) in enumerate(cards):
        x0 = start_x + idx * (cw + gap)
        y0 = H - 108
        draw.rounded_rectangle([x0, y0, x0 + cw, H - 24], radius=9, fill=CARD_BG, outline=CARD_BORDER, width=1)
        draw.text((x0 + 16, y0 + 10), k, font=f_k, fill=ACCENT_TEAL)
        draw.text((x0 + 16, y0 + 30), v, font=f_v, fill=TEXT_MAIN)
        draw.text((x0 + 16, y0 + 56), s, font=f_s, fill=TEXT_MUTED)

    out = Image.alpha_composite(img, overlay).convert("RGB")
    out_path = SCREENSHOTS_DIR / "mech_hero_perspective.png"
    out.save(out_path)
    return out_path


def render_cutaway_torso(
    manifest: Dict[str, Any],
    spine_mj_items: List[Dict[str, Any]],
    spine_extra_mats: Dict[str, Dict[str, Any]],
) -> Path:
    """Cutaway view hiding dorsal hatch, left shell, and head shell to expose real populated Spine PCB,
    Radxa Zero 3W mezzanine, NP-F550 battery sled, and all 6 routed 3D cable bundles.
    """
    W, H = 1920, 1200
    hidden_cutaway = {"torso_dorsal_hatch", "torso_shell_left", "head_shell"}
    items = []
    for it in manifest["heroItems"]:
        if it["nodeName"] in hidden_cutaway or it["nodeName"].startswith("spine_"):
            continue
        c = dict(it)
        if c["nodeName"] in ("torso_shell_right", "neck_s_curve_lower"):
            # Subtle translucent ghost shell on far side for anatomical context
            c["overrideRgba"] = [0.92, 0.95, 0.98, 0.25]
        items.append(c)
    for it in spine_mj_items:
        items.append(dict(it))

    # View from front-left-above looking right into the open torso bay!
    cam = make_lookat_camera(
        name="cutaway_cam",
        eye_m=(0.175, 0.225, 0.235),
        target_m=(0.000, 0.005, 0.156),
        fovy=29.0,
    )
    xml_s = build_mj_scene_xml(items, [cam], with_pedestal=False, extra_materials=spine_extra_mats)
    img = render_mj_camera(xml_s, "cutaway_cam", W, H).convert("RGBA")
    overlay = Image.new("RGBA", (W, H), (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)

    draw_header_bar(
        draw,
        "TORSO & AVIONICS CUTAWAY: SPINE REV A PCB, RADXA & WIRING",
        "Populated 87-Part Spine PCB + Copper Artwork  |  20+ mm Clearance Above Z = 148.0 mm Datum",
        "6 BUNDLES  |  22 CONDUCTORS  |  LINT EXIT 0",
        W,
    )

    # Left callouts (monotonically ordered top-to-bottom to eliminate any leader crossings)
    draw_callout_box(
        draw,
        project_point_3d((26.5, -24.8, 192.0), cam, W, H),
        (48, 150),
        "J5 -> Head Sensor I2C + INT (5-Pin)",
        "3V3, GND, SCL, SDA, INT to cranium\nFeeds VL53L5CX ToF + Head BMI270",
        ACCENT_GREEN,
        380,
    )
    draw_callout_box(
        draw,
        project_point_3d((31.5, 4.0, 174.0), cam, W, H),
        (48, 308),
        "J3 -> Neck / Head / Beak DXL Bus",
        "Daisy-chains IDs 11..14 + Beak 15\n65 mm full 4-axis S-neck ROM slack",
        ACCENT_ORANGE,
        380,
    )
    draw_callout_box(
        draw,
        project_point_3d((22.0, 16.0, 153.5), cam, W, H),
        (48, 466),
        "J4 -> Radxa Host Link (5-Pin)",
        "Dual 5V_BUS + GND + 1 Mbps UART TX/RX\n20 mm mezzanine service foldback loop",
        ACCENT_GREEN,
        380,
    )
    draw_callout_box(
        draw,
        project_point_3d((30.0, 30.0, 149.6), cam, W, H),
        (48, 624),
        "70 x 70 x 1.6 mm Spine Molecule PCB",
        "87 Z-up parts, MP1..MP4 (64x64 mm)\nSTM32G431 + LMR33640 5V/4A + INA226",
        ACCENT_TEAL,
        380,
    )

    # Right callouts (monotonically ordered top-to-bottom)
    draw_callout_box(
        draw,
        project_point_3d((-22.0, 0.0, 163.0), cam, W, H),
        (1472, 165),
        "Radxa Zero 3W Mezzanine (Z=160.2 mm)",
        "RK3566 quad-core host running goosectl\n4x M2.5 brass inserts on PETG-CF arch",
        ACCENT_BLUE,
        400,
    )
    draw_callout_box(
        draw,
        project_point_3d((-35.5, 22.0, 151.5), cam, W, H),
        (1472, 330),
        "J1 & J2 -> Left/Right Leg DXL Buses",
        "J1 Left IDs 1..5, J2 Right IDs 6..10\n52 mm hip yaw/roll/pitch service loop",
        ACCENT_ORANGE,
        400,
    )
    draw_callout_box(
        draw,
        project_point_3d((-16.0, 32.0, 149.6), cam, W, H),
        (1472, 495),
        "MC1..MC3 -> VBAT & GND Feed",
        "22 AWG silicone from NP-F550 leaf contacts\nDual MachineContactMedium VBAT pins",
        ACCENT_TEAL,
        400,
    )
    draw_callout_box(
        draw,
        project_point_3d((-12.0, 19.0, 131.0), cam, W, H),
        (1472, 660),
        "NP-F550 Quick-Swap Battery Bay",
        "Underslung Z = 122.3..142.8 mm envelope\nRear compliant latch clears hip yaw servos",
        ACCENT_BLUE,
        400,
    )

    # Legend bar at bottom
    draw.rounded_rectangle([48, H - 94, W - 48, H - 24], radius=9, fill=CARD_BG, outline=CARD_BORDER, width=1)
    f_leg_h = load_font(14, bold=True, mono=True)
    f_leg = load_font(14, bold=False)
    draw.text((70, H - 80), "CONDUCTOR COLOR CODE & SERVICE ACCESS:", font=f_leg_h, fill=ACCENT_TEAL)
    swatches = [
        ((239, 68, 68, 255), "Red: 5V / 3V3 / VBAT"),
        ((55, 65, 81, 255), "Black: GND"),
        ((234, 179, 8, 255), "Yellow: DXL_DATA"),
        ((34, 197, 94, 255), "Green/Blue: UART TX/RX"),
        ((168, 85, 247, 255), "Purple/Cyan: I2C SCL/SDA"),
        ((226, 232, 240, 255), "2.0 mm & 1.5 mm Straight Hex Access"),
    ]
    sx = 70
    for col, txt in swatches:
        draw.rounded_rectangle([sx, H - 52, sx + 16, H - 36], radius=4, fill=col, outline=(200, 210, 220, 160), width=1)
        draw.text((sx + 24, H - 53), txt, font=f_leg, fill=TEXT_MAIN)
        sx += 292

    out = Image.alpha_composite(img, overlay).convert("RGB")
    out_path = SCREENSHOTS_DIR / "mech_cutaway_torso.png"
    out.save(out_path)
    return out_path


def render_kinematic_orthos(
    manifest: Dict[str, Any],
    mass_props: Dict[str, Any],
    spine_mj_items: List[Dict[str, Any]],
    spine_extra_mats: Dict[str, Dict[str, Any]],
) -> Path:
    """4-panel engineering sheet:
      - Panel 1 (Left): Front Orthographic (+X looking -X) with Z datums & track width
      - Panel 2 (Center): Right Sagittal Orthographic (-Y looking +Y) with link lengths & CoM
      - Panel 3 (Top-Right): Articulated 15th-DoF Honking Beak & Forehead ToF close-up
      - Panel 4 (Bottom-Right): Curved Orange Webbed Goose Foot & Ankle Clevis close-up
    """
    W, H = 1920, 1200
    canvas = Image.new("RGBA", (W, H), (*BG_RGB, 255))
    draw = ImageDraw.Draw(canvas)

    draw_header_bar(
        draw,
        "ORTHOGRAPHIC KINEMATICS, DATUMS & END-EFFECTOR DETAILS",
        "Standing Reference Pose (Knee +0.70 rad / Hip & Ankle -0.35 rad)  |  Z = 0.0 mm Webbed Foot Contact Plane",
        "15 DOF  |  Z_TOP = 284.0 MM  |  TRACK = 68.0 MM",
        W,
    )

    items = [dict(it) for it in manifest["heroItems"] if not it["nodeName"].startswith("spine_")] + [
        dict(it) for it in spine_mj_items
    ]
    pw, ph = 560, 1050
    dw, dh = 660, 512

    cam_front = make_lookat_camera("front_ortho", (3.50, 0.0, 0.144), (0.0, 0.0, 0.144), fovy=5.55)
    cam_side = make_lookat_camera("side_ortho", (0.012, -3.50, 0.144), (0.012, 0.0, 0.144), fovy=5.55)
    cam_beak = make_lookat_camera("beak_detail", (0.185, -0.140, 0.270), (0.050, 0.0, 0.252), fovy=27.0)
    cam_foot = make_lookat_camera("foot_detail", (0.150, -0.155, 0.092), (0.018, -0.034, 0.006), fovy=28.0)

    xml_s = build_mj_scene_xml(
        items,
        [cam_front, cam_side, cam_beak, cam_foot],
        with_pedestal=False,
        extra_materials=spine_extra_mats,
    )
    model = mujoco.MjModel.from_xml_string(xml_s)
    data = mujoco.MjData(model)
    mujoco.mj_forward(model, data)

    r_tall = mujoco.Renderer(model, height=ph, width=pw)
    r_tall.update_scene(data, camera="front_ortho")
    im_front = Image.fromarray(r_tall.render()).convert("RGBA")
    r_tall.update_scene(data, camera="side_ortho")
    im_side = Image.fromarray(r_tall.render()).convert("RGBA")
    r_tall.close()

    r_det = mujoco.Renderer(model, height=dh, width=dw)
    r_det.update_scene(data, camera="beak_detail")
    im_beak = Image.fromarray(r_det.render()).convert("RGBA")
    r_det.update_scene(data, camera="foot_detail")
    im_foot = Image.fromarray(r_det.render()).convert("RGBA")
    r_det.close()

    # Paste 4 framed viewport panels
    panels = [
        (36, 98, pw, ph, im_front, "A. FRONT ORTHOGRAPHIC (+X -> -X)"),
        (620, 98, pw, ph, im_side, "B. SAGITTAL ORTHOGRAPHIC (-Y -> +Y)"),
        (1204, 98, dw, dh, im_beak, "C. 15TH-DOF HONKING BEAK & VL53L5CX TOF"),
        (1204, 636, dw, dh, im_foot, "D. 84 x 50 MM CURVED WEBBED GOOSE FOOT"),
    ]
    f_pan = load_font(15, bold=True, mono=True)
    for x0, y0, w0, h0, sub_im, ptitle in panels:
        canvas.paste(sub_im, (x0, y0))
        draw.rounded_rectangle([x0, y0, x0 + w0, y0 + h0], radius=10, outline=CARD_BORDER, width=2)
        draw.rounded_rectangle([x0 + 14, y0 + 12, x0 + 14 + 390, y0 + 42], radius=6, fill=(13, 19, 23, 220), outline=CARD_BORDER, width=1)
        draw.text((x0 + 24, y0 + 18), ptitle, font=f_pan, fill=ACCENT_TEAL)

    # Panel A (Front Ortho) dimensions
    fx0, fy0 = 36, 98
    p_sole = project_point_3d((0.0, 34.0, 0.0), cam_front, pw, ph)
    p_crown = project_point_3d((0.0, 0.0, 284.0), cam_front, pw, ph)
    draw_dimension_line(
        draw,
        (fx0 + p_sole[0], fy0 + p_sole[1]),
        (fx0 + p_sole[0], fy0 + p_crown[1]),
        "284.0 mm",
        offset_px=(95.0, 0.0),
        color=ACCENT_TEAL,
    )
    p_hl = project_point_3d((0.0, 34.0, 14.0), cam_front, pw, ph)
    p_hr = project_point_3d((0.0, -34.0, 14.0), cam_front, pw, ph)
    draw_dimension_line(
        draw,
        (fx0 + p_hr[0], fy0 + p_hr[1]),
        (fx0 + p_hl[0], fy0 + p_hl[1]),
        "68.0 mm track",
        offset_px=(0.0, 48.0),
        color=ACCENT_ORANGE,
    )
    p_pcb = project_point_3d((0.0, -35.0, 148.0), cam_front, pw, ph)
    draw.line([(fx0 + 40, fy0 + p_pcb[1]), (fx0 + pw - 90, fy0 + p_pcb[1])], fill=(34, 197, 94, 150), width=1)
    draw.text((fx0 + 46, fy0 + p_pcb[1] - 20), "Z=148.0 Spine PCB", font=load_font(13, bold=True, mono=True), fill=ACCENT_GREEN)

    # Panel B (Side Ortho) dimensions & CoM marker
    sx0, sy0 = 620, 98
    com_mm = mass_props["standingWorldComMm"]
    p_com = project_point_3d(tuple(com_mm), cam_side, pw, ph)
    cx_p, cy_p = sx0 + p_com[0], sy0 + p_com[1]
    draw.ellipse([cx_p - 9, cy_p - 9, cx_p + 9, cy_p + 9], fill=ACCENT_ORANGE, outline=(13, 19, 23, 255), width=2)
    draw.text((cx_p + 14, cy_p - 9), f"CoM Z={com_mm[2]:.1f} mm", font=load_font(13, bold=True, mono=True), fill=ACCENT_ORANGE)

    p_hip = project_point_3d((0.0, -34.0, 76.0), cam_side, pw, ph)
    p_knee = project_point_3d((11.3, -34.0, 45.0), cam_side, pw, ph)
    p_ank = project_point_3d((0.0, -34.0, 14.0), cam_side, pw, ph)
    draw_dimension_line(
        draw,
        (sx0 + p_hip[0], sy0 + p_hip[1]),
        (sx0 + p_knee[0], sy0 + p_knee[1]),
        "33.0 mm",
        offset_px=(82.0, 0.0),
        color=ACCENT_BLUE,
    )
    draw_dimension_line(
        draw,
        (sx0 + p_knee[0], sy0 + p_knee[1]),
        (sx0 + p_ank[0], sy0 + p_ank[1]),
        "33.0 mm",
        offset_px=(82.0, 0.0),
        color=ACCENT_BLUE,
    )
    p_tail = project_point_3d((-66.0, 0.0, 156.0), cam_side, pw, ph)
    p_btip = project_point_3d((90.0, 0.0, 260.0), cam_side, pw, ph)
    draw_dimension_line(
        draw,
        (sx0 + p_tail[0], sy0 + ph - 58),
        (sx0 + p_btip[0], sy0 + ph - 58),
        "156.0 mm nose-to-tail",
        offset_px=(0.0, 0.0),
        color=ACCENT_TEAL,
    )

    # Panel C & D concise annotations (2 wrapped lines inside 624 px card)
    f_note = load_font(13, bold=False)
    f_nh = load_font(15, bold=True)
    draw.rounded_rectangle([1222, 506, 1846, 596], radius=8, fill=(13, 19, 23, 232), outline=CARD_BORDER, width=1)
    draw.text((1238, 514), "dxl_15_beak_pitch (XL330-M288-T) + Forehead Optical Window", font=f_nh, fill=ACCENT_ORANGE)
    draw.text((1238, 538), "Upper orange bill & knob house dxlId=15; lower mandible pivots 0 to 38 deg.", font=f_note, fill=TEXT_MUTED)
    draw.text((1238, 558), "Forehead VL53L5CX ToF window behind basal bill knob (see Sec 4.5 FoV audit).", font=f_note, fill=TEXT_MUTED)

    draw.rounded_rectangle([1222, 1044, 1846, 1134], radius=8, fill=(13, 19, 23, 232), outline=CARD_BORDER, width=1)
    draw.text((1238, 1052), "Wide 3-Toed Support Polygon (84.0 mm AP x 50.0 mm ML)", font=f_nh, fill=ACCENT_ORANGE)
    draw.text((1238, 1076), "0.9 mm sole clearance beneath ankle XL330; flat Z = 0.0 mm stance plane.", font=f_note, fill=TEXT_MUTED)
    draw.text((1238, 1096), "Lateral clevis ears mount outside PETG-CF shank plates with traction grooves.", font=f_note, fill=TEXT_MUTED)

    out_path = SCREENSHOTS_DIR / "mech_kinematic_orthos.png"
    canvas.convert("RGB").save(out_path)
    return out_path


def render_bam_and_bambu_plates(slice_report: Dict[str, Any]) -> Path:
    """Left half: Standalone Rhoban/BAM XL330 Pendulum Identification Rig 3/4 studio view.
    Right half: 3 Rendered Bambu Build Plates + Headless Bambu Studio Slice Metrics table.
    """
    W, H = 1920, 1200
    canvas = Image.new("RGBA", (W, H), (*BG_RGB, 255))
    draw = ImageDraw.Draw(canvas)

    tot = slice_report["totals"]
    draw_header_bar(
        draw,
        "STAGE 1 BAM ACTUATOR-ID RIG & HEADLESS BAMBU STUDIO PRINT PLATES",
        f"Bench XL330 Friction/Inertia Pendulum Rig  +  3 Sliced Build Plates ({slice_report['printerPreset']})",
        f"PRINT TOTAL: {tot['filamentWeightG']:.1f} G  |  {tot['printTimeFormatted'].upper()}",
        W,
    )

    # Left panel: BAM Pendulum Rig (840 x 1050)
    lw, lh = 840, 1050
    bam_items = [
        {"nodeName": "bam_base", "stlPath": STL_DIR / "bam_pendulum_base.stl", "material": "goose_orange"},
        {"nodeName": "bam_arm", "stlPath": STL_DIR / "bam_pendulum_arm.stl", "material": "goose_orange"},
        {"nodeName": "bam_servo", "stlPath": HERO_MESH_DIR / "bam_servo.stl", "material": "xl330_charcoal"},
        {"nodeName": "bam_mass", "stlPath": HERO_MESH_DIR / "bam_proof_mass.stl", "material": "steel_silver"},
    ]
    cam_bam = make_lookat_camera(
        name="bam_cam",
        eye_m=(0.285, -0.250, 0.195),
        target_m=(0.005, 0.0, 0.080),
        fovy=31.0,
    )
    xml_bam = build_mj_scene_xml(bam_items, [cam_bam], with_pedestal=True)
    im_bam = render_mj_camera(xml_bam, "bam_cam", lw, lh).convert("RGBA")
    canvas.paste(im_bam, (36, 98))
    draw.rounded_rectangle([36, 98, 36 + lw, 98 + lh], radius=10, outline=CARD_BORDER, width=2)

    f_pan = load_font(15, bold=True, mono=True)
    draw.rounded_rectangle([54, 114, 545, 146], radius=6, fill=(13, 19, 23, 225), outline=CARD_BORDER, width=1)
    draw.text((66, 121), "RHOBAN/BAM XL330 PENDULUM IDENTIFICATION RIG", font=f_pan, fill=ACCENT_TEAL)

    # BAM dimension & callouts
    bx0, by0 = 36, 98
    p_piv = project_point_3d((27.0, 0.0, 145.0), cam_bam, lw, lh)
    p_tip = project_point_3d((27.0, 0.0, 35.0), cam_bam, lw, lh)
    draw_dimension_line(
        draw,
        (bx0 + p_piv[0], by0 + p_piv[1]),
        (bx0 + p_tip[0], by0 + p_tip[1]),
        "L = 110.0 mm",
        offset_px=(84.0, 0.0),
        color=ACCENT_TEAL,
    )

    draw_callout_box(
        draw,
        (bx0 + p_piv[0] - 18, by0 + p_piv[1]),
        (54, 185),
        "Single XL330-M288-T Under Test",
        "Shaft Z = 145.0 mm (35 mm swing clearance)\nIdentifies armature, viscous & Coulomb params",
        ACCENT_TEAL,
        335,
    )
    draw_callout_box(
        draw,
        (bx0 + p_tip[0] + 10, by0 + p_tip[1] + 6),
        (54, 835),
        "Calibrated M4 Proof-Mass Mount",
        "Matches Stage 1 BAM sweeps: 50 / 100 / 180 g\nRigid gusseted A-frame with 4x M5 bench holes",
        ACCENT_ORANGE,
        345,
    )

    # Right column: 3 Packed Bambu Plate Previews + Verified Slice Table (984 px wide!)
    rx0 = 900
    rw = W - 36 - rx0  # 984 px
    plate_mats = ["carbon_petg", "goose_white", "goose_orange"]
    plate_accents = [ACCENT_BLUE, ACCENT_TEAL, ACCENT_ORANGE]
    short_titles = [
        "Plate 1: Structural Torso, Mezzanine & Leg Frames (PETG-CF)",
        "Plate 2: Goose Plumage Shells, S-Neck & Cranium (PLA White)",
        "Plate 3: Webbed Feet, Articulated Beak & BAM Rig (PLA Orange)",
    ]

    f_ph = load_font(16, bold=True)
    f_pm = load_font(14, bold=True, mono=True)
    f_ps = load_font(13, bold=False)

    for idx, p_entry in enumerate(slice_report["plates"]):
        card_y = 98 + idx * 252
        card_h = 236
        draw.rounded_rectangle([rx0, card_y, rx0 + rw, card_y + card_h], radius=10, fill=CARD_BG, outline=CARD_BORDER, width=1)

        tw, th = 276, 208
        plate_stl = PLATES_DIR / f"{p_entry['plateId']}.stl"
        p_items = [{"nodeName": p_entry["plateId"], "stlPath": plate_stl, "material": plate_mats[idx]}]
        cam_p = make_lookat_camera("plate_cam", (0.0, -0.21, 0.28), (0.0, 0.0, 0.015), fovy=44.0)
        xml_p = build_mj_scene_xml(p_items, [cam_p], with_pedestal=False)
        im_p = render_mj_camera(xml_p, "plate_cam", tw, th).convert("RGBA")
        canvas.paste(im_p, (rx0 + 14, card_y + 14))
        draw.rounded_rectangle([rx0 + 14, card_y + 14, rx0 + 14 + tw, card_y + 14 + th], radius=7, outline=plate_accents[idx], width=2)

        tx = rx0 + 308
        draw.text((tx, card_y + 16), short_titles[idx], font=f_ph, fill=TEXT_MAIN)
        draw.text((tx, card_y + 44), f"Filament: {p_entry['filament']}  ({p_entry['colorLabel']})", font=f_ps, fill=TEXT_MUTED)
        draw.text((tx, card_y + 66), f"Process:  {p_entry['process']}  |  Tree(Auto) Support", font=f_ps, fill=TEXT_MUTED)

        fp = p_entry["plateFootprintMm"]
        draw.text(
            (tx, card_y + 94),
            f"Parts: {p_entry['partCount']}   |   Footprint: {fp[0]:.0f} x {fp[1]:.0f} x {fp[2]:.0f} mm",
            font=f_ps,
            fill=TEXT_MAIN,
        )

        metrics_line = (
            f"{p_entry['filamentWeightG']:.1f} g   |   {p_entry['printTime']}   |   "
            f"{p_entry['layerCount']} layers   |   {p_entry['filamentLengthM']:.2f} m"
        )
        draw.rounded_rectangle([tx, card_y + 126, rx0 + rw - 18, card_y + 164], radius=7, fill=(13, 19, 23, 230), outline=plate_accents[idx], width=1)
        draw.text((tx + 14, card_y + 136), metrics_line, font=f_pm, fill=plate_accents[idx])

        part_names_short = ", ".join(pp["part"] for pp in p_entry["packedParts"][:3])
        if len(p_entry["packedParts"]) > 3:
            part_names_short += f" (+{len(p_entry['packedParts']) - 3} more)"
        draw.text((tx, card_y + 178), f"Parts: {part_names_short}", font=f_ps, fill=TEXT_MUTED)

    # Bottom-right grand total summary card (fits 984 px cleanly)
    gy = 98 + 3 * 252
    draw.rounded_rectangle([rx0, gy, rx0 + rw, 1148], radius=10, fill=(18, 31, 40, 245), outline=ACCENT_TEAL, width=2)
    draw.text((rx0 + 24, gy + 16), "VERIFIED HEADLESS BAMBU STUDIO SLICE TOTALS (BAMBU LAB H2D 0.4 MM)", font=f_pan, fill=ACCENT_TEAL)

    f_col_k = load_font(12, bold=True, mono=True)
    f_col_v = load_font(22, bold=True)
    summary_cols = [
        ("PRINTABLE PARTS", f"{slice_report['totalPrintableParts']} STLs / 3 Plates"),
        ("TOTAL FILAMENT", f"{tot['filamentWeightG']:.1f} g  ({tot['filamentLengthM']:.1f} m)"),
        ("TOTAL PRINT TIME", f"{tot['printTimeFormatted']}  ({tot['totalLayersAcrossPlates']} layers)"),
    ]
    for c_i, (ck, cv) in enumerate(summary_cols):
        cx = rx0 + 24 + c_i * 316
        draw.text((cx, gy + 54), ck, font=f_col_k, fill=TEXT_MUTED)
        draw.text((cx, gy + 74), cv, font=f_col_v, fill=TEXT_MAIN)

    draw.text(
        (rx0 + 24, gy + 124),
        f"Slicer: {slice_report['slicerEngine']}  |  Preset: {slice_report['printerPreset']}",
        font=f_ps,
        fill=TEXT_MUTED,
    )
    draw.text(
        (rx0 + 24, gy + 148),
        "All 3 plates shelf-packed flat on Z = 0.0 mm within single H2D build volume (<240 x 185 mm).",
        font=f_ps,
        fill=TEXT_MUTED,
    )

    out_path = SCREENSHOTS_DIR / "mech_bam_pendulum_rig.png"
    canvas.convert("RGB").save(out_path)
    return out_path


def main() -> None:
    SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)
    manifest = json.loads(MANIFEST_PATH.read_text())
    mass_props = json.loads(MASS_PROPS_PATH.read_text())
    interf = json.loads(INTERF_PATH.read_text())
    slice_report = json.loads(SLICE_REPORT_PATH.read_text())

    print("[1/3] Building annotated multi-layer Hero GLB -> docs/3d/microgoose-hero.glb ...")
    glb_stats = build_hero_glb(manifest)
    print("  GLB stats:", json.dumps(glb_stats))

    print("[2/3] Extracting real copper-accurate Spine GLB meshes for MuJoCo studio renderer ...")
    spine_mj_items, spine_extra_mats = extract_real_board_meshes_for_mujoco()
    print(f"  Extracted {len(spine_mj_items)} per-material STL meshes ({len(spine_extra_mats)} PBR materials)")

    print("[3/3] Rendering 4 studio 1920x1200 PNGs on #0d1317 dark background ...")
    p1 = render_hero_perspective(manifest, mass_props, interf, spine_mj_items, spine_extra_mats)
    print(f"  Wrote {p1}")
    p2 = render_cutaway_torso(manifest, spine_mj_items, spine_extra_mats)
    print(f"  Wrote {p2}")
    p3 = render_kinematic_orthos(manifest, mass_props, spine_mj_items, spine_extra_mats)
    print(f"  Wrote {p3}")
    p4 = render_bam_and_bambu_plates(slice_report)
    print(f"  Wrote {p4}")


if __name__ == "__main__":
    main()