main
Drew Owens Fix contralateral leg-frame and torso-shell CAD bug, regenerate single-solid STLs/GLB/Bambu/MJCF/USD/clearance, and ali… 9a64946
#!/usr/bin/env python3
"""Pack Microgoose printable STL parts onto 3 logical Bambu build plates (Z=0 seated,
optimal flat build orientation), slice headlessly with Bambu Studio (bambu_slice),
and write mechanical/bambu_slice_report.json.

Run with:
    python3 mechanical/slice_bambu_plates.py
"""

from __future__ import annotations

import json
import math
import os
import subprocess
import time
from pathlib import Path
from typing import Any, Dict, List

import numpy as np
import trimesh


ROOT_DIR = Path(__file__).resolve().parents[1]
MECH_DIR = ROOT_DIR / "mechanical"
STL_DIR = MECH_DIR / "stl"
PLATES_DIR = STL_DIR / "plates"


PLATE_CONFIGS = [
    {
        "plateIndex": 1,
        "plateId": "plate1_structural_petgcf",
        "title": "Plate 1: Structural Torso, Mezzanine & Leg Frames (PETG-CF)",
        "printer": "Bambu Lab H2D 0.4 nozzle",
        "process": "0.20mm Balanced Strength @BBL H2D",
        "filament": "Bambu PETG-CF @BBL H2D 0.4 nozzle",
        "colorLabel": "Carbon Slate (#1e293b)",
        "parts": [
            "torso_core_cradle",
            "radxa_mezzanine_carrier",
            "battery_sled",
            "left_hip_yoke",
            "right_hip_yoke",
            "left_hip_roll_clevis",
            "right_hip_roll_clevis",
            "left_thigh_frame",
            "right_thigh_frame",
            "left_shank_frame",
            "right_shank_frame",
        ],
    },
    {
        "plateIndex": 2,
        "plateId": "plate2_white_shells_pla_matte",
        "title": "Plate 2: Goose Plumage Shells, S-Neck & Sensor Cranium (PLA Matte White)",
        "printer": "Bambu Lab H2D 0.4 nozzle",
        "process": "0.20mm Standard @BBL H2D",
        "filament": "Bambu PLA Matte @BBL H2D",
        "colorLabel": "Matte Snow White (#f1f5f9)",
        "parts": [
            "torso_shell_left",
            "torso_shell_right",
            "torso_dorsal_hatch",
            "neck_s_curve_lower",
            "neck_yaw_collar",
            "head_shell",
        ],
    },
    {
        "plateIndex": 3,
        "plateId": "plate3_orange_feet_beak_bam_pla_matte",
        "title": "Plate 3: Webbed Goose Feet, Articulated Beak & BAM Pendulum Rig (PLA Matte Orange)",
        "printer": "Bambu Lab H2D 0.4 nozzle",
        "process": "0.20mm Standard @BBL H2D",
        "filament": "Bambu PLA Matte @BBL H2D",
        "colorLabel": "Goose-Bill Orange (#f97316)",
        "parts": [
            "left_foot_sole",
            "right_foot_sole",
            "beak_upper",
            "beak_lower",
            "bam_pendulum_base",
            "bam_pendulum_arm",
        ],
    },
]


def orient_for_print(name: str, mesh: trimesh.Trimesh) -> trimesh.Trimesh:
    """Orient part cleanly for minimal-support FDM printing and seat flat on Z = 0.0 mm."""
    m = mesh.copy()
    # Lay side-extruded plates/shells/arms flat on XY bed
    if name in ("left_thigh_frame", "right_thigh_frame", "left_shank_frame", "right_shank_frame"):
        rot = trimesh.transformations.rotation_matrix(math.pi / 2.0, [1, 0, 0])
        m.apply_transform(rot)
    elif name == "torso_shell_left":
        rot = trimesh.transformations.rotation_matrix(math.pi / 2.0, [1, 0, 0])
        m.apply_transform(rot)
    elif name == "torso_shell_right":
        rot = trimesh.transformations.rotation_matrix(-math.pi / 2.0, [1, 0, 0])
        m.apply_transform(rot)
    elif name == "bam_pendulum_arm":
        rot = trimesh.transformations.rotation_matrix(-math.pi / 2.0, [0, 1, 0])
        m.apply_transform(rot)
    elif name == "torso_dorsal_hatch":
        # Flip upside down so flat roof sits on build plate
        rot = trimesh.transformations.rotation_matrix(math.pi, [1, 0, 0])
        m.apply_transform(rot)

    bounds = m.bounds
    cx = 0.5 * (bounds[0][0] + bounds[1][0])
    cy = 0.5 * (bounds[0][1] + bounds[1][1])
    zmin = bounds[0][2]
    m.apply_translation([-cx, -cy, -zmin])
    return m


def pack_plate_meshes(part_names: List[str], spacing_mm: float = 10.0, max_row_width_mm: float = 240.0) -> tuple[trimesh.Trimesh, List[Dict[str, Any]]]:
    """Shelf-pack oriented meshes onto a centered XY build plate within 260x260 mm."""
    oriented = []
    for pname in part_names:
        stl_p = STL_DIR / f"{pname}.stl"
        raw = trimesh.load_mesh(str(stl_p), force="mesh")
        om = orient_for_print(pname, raw)
        ext = om.extents
        oriented.append((pname, om, float(ext[0]), float(ext[1]), float(ext[2])))

    # Sort tallest XY footprint first for tidy shelf packing
    oriented.sort(key=lambda t: t[3], reverse=True)

    placed_meshes = []
    placements_meta = []
    cur_x = 0.0
    cur_y = 0.0
    row_h = 0.0

    for pname, om, sx, sy, sz in oriented:
        if cur_x > 0.0 and (cur_x + sx) > max_row_width_mm:
            cur_x = 0.0
            cur_y += row_h + spacing_mm
            row_h = 0.0
        px = cur_x + 0.5 * sx
        py = cur_y + 0.5 * sy
        m_placed = om.copy()
        m_placed.apply_translation([px, py, 0.0])
        placed_meshes.append(m_placed)
        placements_meta.append({
            "part": pname,
            "orientedSizeMm": [round(sx, 2), round(sy, 2), round(sz, 2)],
            "plateXYMm": [round(px, 2), round(py, 2)],
        })
        cur_x += sx + spacing_mm
        row_h = max(row_h, sy)

    combined = trimesh.util.concatenate(placed_meshes)
    b = combined.bounds
    shift_x = -0.5 * (b[0][0] + b[1][0])
    shift_y = -0.5 * (b[0][1] + b[1][1])
    combined.apply_translation([shift_x, shift_y, -b[0][2]])
    for pm in placements_meta:
        pm["plateXYMm"] = [round(pm["plateXYMm"][0] + shift_x, 2), round(pm["plateXYMm"][1] + shift_y, 2)]
    return combined, placements_meta


def run_ab(verb: str, payload: Dict[str, Any], timeout_s: int = 120) -> Dict[str, Any]:
    cmd = ["adom-bridge", "--ai-thread", "microgoose"]
    bridge_target = os.environ.get("ADOM_BRIDGE_TARGET", "").strip()
    if bridge_target:
        cmd.extend(["--target", bridge_target])
    cmd.extend([verb, json.dumps(payload)])
    proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s, check=False)
    if proc.returncode != 0 and not proc.stdout.strip():
        raise RuntimeError(f"adom-bridge {verb} failed ({proc.returncode}): {proc.stderr}")
    outer = json.loads(proc.stdout)
    if isinstance(outer.get("output"), str) and outer["output"].strip().startswith("{"):
        try:
            inner = json.loads(outer["output"])
            inner["_outerRoute"] = outer.get("route")
            return inner
        except Exception:
            pass
    return outer


def parse_duration_seconds(text: str) -> int:
    """Parse Bambu printTime strings like '1h 24m 12s' or '48m 10s' into seconds."""
    if not text:
        return 0
    import re

    total = 0
    d = re.search(r"(\d+)\s*d", text)
    h = re.search(r"(\d+)\s*h", text)
    m = re.search(r"(\d+)\s*m", text)
    s = re.search(r"(\d+)\s*s", text)
    if d:
        total += int(d.group(1)) * 86400
    if h:
        total += int(h.group(1)) * 3600
    if m:
        total += int(m.group(1)) * 60
    if s:
        total += int(s.group(1))
    return total


def main() -> None:
    PLATES_DIR.mkdir(parents=True, exist_ok=True)
    plate_files: List[str] = []
    plate_pack_info: Dict[str, Any] = {}

    for cfg in PLATE_CONFIGS:
        pid = cfg["plateId"]
        combined, pmeta = pack_plate_meshes(cfg["parts"])
        out_stl = PLATES_DIR / f"{pid}.stl"
        combined.export(str(out_stl))
        ext = combined.extents
        plate_files.append(str(out_stl))
        plate_pack_info[pid] = {
            "localStl": out_stl.relative_to(ROOT_DIR).as_posix(),
            "plateFootprintMm": [round(float(ext[0]), 2), round(float(ext[1]), 2), round(float(ext[2]), 2)],
            "partCount": len(cfg["parts"]),
            "packedParts": pmeta,
        }
        print(f"Packed {pid}: {len(cfg['parts'])} parts, footprint {ext[0]:.1f} x {ext[1]:.1f} x {ext[2]:.1f} mm")

    print("Sending 3 packed build plate STLs to slicer host via adom-bridge send_files...")
    send_res = run_ab("send_files", {"filePaths": plate_files})
    print("send_files reply keys:", list(send_res.keys()))

    # Extract remote paths returned by send_files
    remote_map: Dict[str, str] = {}
    files_arr = (
        send_res.get("destinationPaths")
        or send_res.get("receipts")
        or send_res.get("files")
        or send_res.get("savedFiles")
        or send_res.get("paths")
        or []
    )
    if isinstance(files_arr, list):
        for idx, item in enumerate(files_arr):
            if isinstance(item, dict):
                rpath = item.get("savedPath") or item.get("destPath") or item.get("path") or item.get("remotePath")
                src = item.get("sourcePath") or item.get("name") or plate_files[idx]
                if rpath:
                    remote_map[Path(src).stem] = rpath
            elif isinstance(item, str):
                remote_map[Path(item).stem] = item
    if not remote_map and isinstance(send_res.get("destDir"), str):
        ddir = send_res["destDir"].rstrip("\\/")
        for pf in plate_files:
            remote_map[Path(pf).stem] = f"{ddir}\\{Path(pf).name}"
    if not remote_map:
        print("Raw send_files response:", json.dumps(send_res, indent=2))
        raise RuntimeError("Could not resolve remote paths on slicer host from send_files")

    slice_results = []
    total_weight_g = 0.0
    total_length_m = 0.0
    total_seconds = 0
    total_layers = 0

    for cfg in PLATE_CONFIGS:
        pid = cfg["plateId"]
        rpath = remote_map[pid]
        print(f"Slicing {pid} on slicer host...")
        slice_args = {
            "file": rpath,
            "printer": cfg["printer"],
            "process": cfg["process"],
            "filament": cfg["filament"],
            "settings": {
                "enable_support": "1",
                "support_type": "tree(auto)",
                "sparse_infill_density": "35%" if cfg["plateIndex"] == 1 else "20%",
                "wall_loops": "3",
            },
        }
        res = run_ab("bambu_slice", slice_args, timeout_s=120)
        while res.get("stillRunning") and res.get("jobId"):
            time.sleep(3.0)
            res = run_ab("bambu_progress", {"jobId": res["jobId"]}, timeout_s=60)

        if not res.get("success", False):
            print("Failed slice reply:", json.dumps(res, indent=2))
            raise RuntimeError(f"bambu_slice failed on {pid}")

        totals = res.get("totals", {})
        plates_arr = res.get("plates", [{}])
        p0 = plates_arr[0] if plates_arr else {}
        w_g = float(totals.get("weightG") or p0.get("weightG") or p0.get("grams") or 0.0)
        l_m = float(totals.get("lengthM") or p0.get("lengthM") or 0.0)
        ptime = str(totals.get("printTime") or p0.get("printTime") or p0.get("time") or "")
        psec = int(totals.get("printTimeSec") or p0.get("timeSec") or parse_duration_seconds(ptime))
        layers = int(p0.get("layers") or p0.get("layerCount") or 0)

        total_weight_g += w_g
        total_length_m += l_m
        total_seconds += psec
        total_layers += layers

        raw_3mf = str((res.get("outputs") or {}).get("threeMf", ""))
        clean_3mf = Path(raw_3mf.replace("\\", "/")).name if raw_3mf else f"{pid}.3mf"
        entry = {
            "plateIndex": cfg["plateIndex"],
            "plateId": pid,
            "title": cfg["title"],
            "printer": cfg["printer"],
            "process": cfg["process"],
            "filament": cfg["filament"],
            "colorLabel": cfg["colorLabel"],
            "plateStl": f"mechanical/stl/plates/{pid}.stl",
            "partCount": plate_pack_info[pid]["partCount"],
            "plateFootprintMm": plate_pack_info[pid]["plateFootprintMm"],
            "packedParts": plate_pack_info[pid]["packedParts"],
            "summary": res.get("summary", ""),
            "printTime": ptime,
            "printTimeSeconds": psec,
            "printTimeHours": round(psec / 3600.0, 2),
            "filamentWeightG": round(w_g, 2),
            "filamentLengthM": round(l_m, 2),
            "layerCount": layers,
            "supportEnabled": True,
            "supportType": "tree(auto)",
            "warnings": res.get("warnings", []),
            "threeMfOutput": f"mechanical/stl/plates/{clean_3mf}",
        }
        slice_results.append(entry)
        print(f"  -> {pid}: {w_g:.1f} g, {ptime} ({layers} layers) | {res.get('summary', '')}")

    hrs = total_seconds // 3600
    mins = (total_seconds % 3600) // 60
    report = {
        "schema": "microgoose-bambu-slice-report/v1",
        "pass": len(slice_results) == len(PLATE_CONFIGS) and total_weight_g > 0.0,
        "slicerHost": "a Windows laptop with an RTX 4090 Laptop GPU",
        "slicerEngine": "Bambu Studio 02.09.01.70 (headless bambu_slice)",
        "printerPreset": "Bambu Lab H2D 0.4 nozzle",
        "totalPlates": len(slice_results),
        "totalPrintableParts": sum(p["partCount"] for p in slice_results),
        "totals": {
            "filamentWeightG": round(total_weight_g, 2),
            "filamentLengthM": round(total_length_m, 2),
            "printTimeSeconds": total_seconds,
            "printTimeHours": round(total_seconds / 3600.0, 2),
            "printTimeFormatted": f"{hrs}h {mins:02d}m",
            "totalLayersAcrossPlates": total_layers,
        },
        "plates": slice_results,
    }
    out_json = MECH_DIR / "bambu_slice_report.json"
    out_json.write_text(json.dumps(report, indent=2) + "\n")
    print(f"Wrote {out_json}: Total {total_weight_g:.1f} g across 3 plates, {hrs}h {mins:02d}m total print time.")


if __name__ == "__main__":
    main()