main
John Lauer Family contract: pipeline 1.0.0 that built the three VL53Lx pages 8e4500f
#!/usr/bin/env python3
"""Derive Z-up, colour-preserving STEP variants from a manufacturer (SamacSys/CSE) STEP.

  vendor_step.py <in.step> <out.step> [--keep-fov] [--etch MPN] [--etch-wall -y|+y|-x|+x]
                 [--rot-z DEG] [--report out.json]

- Reads with XCAF so per-face colours survive.
- Rotates the source Y-up frame to Adom's Z-up (R_x(+90 deg)), then re-seats the body so the
  package underside sits on z = 0 and the XY bbox is centred on the origin (the footprint frame).
- Solids whose volume is < 1 % of the largest solid are the manufacturer's field-of-view cones
  (nonphysical helpers); they are dropped unless --keep-fov, in which case they are kept as a
  separately named product 'FOV' so a viewer can toggle them.
- --etch MPN adds the part number as a thin light-grey inlay body on the requested side wall
  (a colour change, not a groove, same idea as adom-chip-laser) so it survives STEP -> GLB.
Every transform is written to the --report JSON (source hash, units, up axis, rotation,
translation, dropped solids, etch placement) for the component page's provenance.
"""
import sys, json, math, hashlib, os
import cadquery as cq
from OCP.STEPCAFControl import STEPCAFControl_Reader, STEPCAFControl_Writer
from OCP.TDocStd import TDocStd_Document
from OCP.TCollection import TCollection_ExtendedString
from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorSurf, XCAFDoc_ColorGen
from OCP.XCAFApp import XCAFApp_Application
from OCP.TDF import TDF_LabelSequence, TDF_Label
from OCP.TopoDS import TopoDS_Shape, TopoDS
from OCP.TopExp import TopExp_Explorer
from OCP.TopAbs import TopAbs_FACE, TopAbs_SOLID, TopAbs_SHELL
from OCP.Quantity import Quantity_Color, Quantity_TOC_RGB
from OCP.gp import gp_Trsf, gp_Ax1, gp_Pnt, gp_Dir, gp_Vec
from OCP.BRepBuilderAPI import BRepBuilderAPI_Transform
from OCP.Bnd import Bnd_Box
from OCP.BRepBndLib import BRepBndLib
from OCP.GProp import GProp_GProps
from OCP.BRepGProp import BRepGProp
from OCP.IFSelect import IFSelect_RetDone
from OCP.STEPControl import STEPControl_AsIs
from OCP.TDataStd import TDataStd_Name
from OCP.TopTools import TopTools_ListOfShape


def sha256(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def new_doc():
    app = XCAFApp_Application.GetApplication_s()
    doc = TDocStd_Document(TCollection_ExtendedString("MDTV-XCAF"))
    app.NewDocument(TCollection_ExtendedString("MDTV-XCAF"), doc)
    return doc


def read_step(path):
    doc = new_doc()
    rdr = STEPCAFControl_Reader()
    rdr.SetColorMode(True); rdr.SetNameMode(True)
    if rdr.ReadFile(path) != IFSelect_RetDone:
        raise SystemExit(f"cannot read {path}")
    rdr.Transfer(doc)
    return doc


def bbox(shape):
    b = Bnd_Box(); BRepBndLib.Add_s(shape, b, True)
    return b.Get()  # xmin ymin zmin xmax ymax zmax


def volume(shape):
    g = GProp_GProps(); BRepGProp.VolumeProperties_s(shape, g); return abs(g.Mass())


def face_colours(ctool, shape):
    """(face -> (r,g,b)) for every face of shape that has a surface or generic colour."""
    out = []
    ex = TopExp_Explorer(shape, TopAbs_FACE)
    while ex.More():
        f = ex.Current(); col = Quantity_Color(); c = None
        if ctool.GetColor(f, XCAFDoc_ColorSurf, col) or ctool.GetColor(f, XCAFDoc_ColorGen, col):
            c = (col.Red(), col.Green(), col.Blue())
        out.append(c); ex.Next()
    return out


def shape_colour(ctool, shape):
    col = Quantity_Color()
    if ctool.GetColor(shape, XCAFDoc_ColorSurf, col) or ctool.GetColor(shape, XCAFDoc_ColorGen, col):
        return (col.Red(), col.Green(), col.Blue())
    return None


def main(argv):
    src, dst = argv[1], argv[2]
    keep_fov = "--keep-fov" in argv
    etch = argv[argv.index("--etch") + 1] if "--etch" in argv else None
    wall = argv[argv.index("--etch-wall") + 1] if "--etch-wall" in argv else "-y"
    rot_z = float(argv[argv.index("--rot-z") + 1]) if "--rot-z" in argv else 0.0
    report_path = argv[argv.index("--report") + 1] if "--report" in argv else None
    etch_size = float(argv[argv.index("--etch-size") + 1]) if "--etch-size" in argv else 0.0

    doc = read_step(src)
    stool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main())
    ctool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())
    labels = TDF_LabelSequence(); stool.GetFreeShapes(labels)
    # Walk assembly components: colours live on the PROTOTYPE (referred) labels, instances only
    # carry a location. Explore the prototype, read its face colours, then move the piece by the
    # instance location so the geometry matches what the file displays.
    pieces = []  # (located shape, kind, [face colours], shape colour)

    def explore_pieces(proto_shape, loc, ctool):
        found = False
        for kind in (TopAbs_SOLID, TopAbs_SHELL):
            ex = TopExp_Explorer(proto_shape, kind)
            while ex.More():
                s = ex.Current(); found = True
                fc = face_colours(ctool, s); sc = shape_colour(ctool, s)
                pieces.append((s.Moved(loc), kind, fc, sc))
                ex.Next()
            if found:
                break
        if not found:
            pieces.append((proto_shape.Moved(loc), None, face_colours(ctool, proto_shape), shape_colour(ctool, proto_shape)))

    def walk(lab, loc):
        if stool.IsAssembly_s(lab):
            comps = TDF_LabelSequence(); stool.GetComponents_s(lab, comps)
            for j in range(1, comps.Length() + 1):
                c = comps.Value(j)
                cloc = stool.GetLocation_s(c)
                ref = TDF_Label()
                if stool.GetReferredShape_s(c, ref):
                    walk(ref, loc.Multiplied(cloc))
                else:
                    explore_pieces(stool.GetShape_s(c), loc.Multiplied(cloc), ctool)
        else:
            ref = TDF_Label()
            if stool.IsReference_s(lab) and stool.GetReferredShape_s(lab, ref):
                walk(ref, loc.Multiplied(stool.GetLocation_s(lab)))
            else:
                explore_pieces(stool.GetShape_s(lab), loc, ctool)

    from OCP.TopLoc import TopLoc_Location
    for i in range(1, labels.Length() + 1):
        walk(labels.Value(i), TopLoc_Location())
    vols = [volume(p[0]) if p[1] == TopAbs_SOLID else 0.0 for p in pieces]
    vmax = max(vols) if vols else 0.0
    fov_idx = [i for i, v in enumerate(vols) if pieces[i][1] == TopAbs_SOLID and vmax > 0 and v < 0.01 * vmax]
    body_idx = [i for i in range(len(pieces)) if i not in fov_idx]

    # ---- transform: Y-up -> Z-up, optional yaw, then seat on z=0 centred in XY
    t1 = gp_Trsf(); t1.SetRotation(gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(1, 0, 0)), math.radians(90))
    t2 = gp_Trsf(); t2.SetRotation(gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), math.radians(rot_z))
    T = gp_Trsf(); T.Multiply(t2); T.Multiply(t1)  # T = t2 * t1  (t1 first)
    moved = [BRepBuilderAPI_Transform(p[0], T, True).Shape() for p in pieces]
    # seat using the BODY pieces only (the FoV cones must not shift the seating plane)
    bb = Bnd_Box()
    for i in body_idx:
        BRepBndLib.Add_s(moved[i], bb, True)
    xmin, ymin, zmin, xmax, ymax, zmax = bb.Get()
    t3 = gp_Trsf(); t3.SetTranslation(gp_Vec(-(xmin + xmax) / 2, -(ymin + ymax) / 2, -zmin))
    moved = [BRepBuilderAPI_Transform(m, t3, True).Shape() for m in moved]
    body_bb = (round(xmax - xmin, 3), round(ymax - ymin, 3), round(zmax - zmin, 3))

    # ---- optional side-wall etch as a light-grey inlay body
    etch_info = None
    if etch:
        L, W, H = body_bb
        along_x = wall in ("-y", "+y")
        wall_len = L if along_x else W
        size = etch_size or min(H * 0.55, wall_len * 0.8 / (len(etch) * 0.62))
        depth = 0.03
        # text on a workplane whose normal points OUT of the wall, glyph baseline along the wall
        if wall == "-y":
            wp = cq.Workplane("XZ", origin=(0, -W / 2 + depth * 0.5, H / 2))            # XZ normal = -Y (outward)
            txt = wp.text(etch, size, depth, combine=False, halign="center", valign="center")
        elif wall == "+y":
            wp = cq.Workplane("XZ", origin=(0, W / 2 - depth * 0.5, H / 2)).transformed(rotate=(0, 180, 0))
            txt = wp.text(etch, size, depth, combine=False, halign="center", valign="center")
        elif wall == "+x":
            wp = cq.Workplane("YZ", origin=(L / 2 - depth * 0.5, 0, H / 2))
            txt = wp.text(etch, size, depth, combine=False, halign="center", valign="center")
        else:  # -x
            wp = cq.Workplane("YZ", origin=(-L / 2 + depth * 0.5, 0, H / 2)).transformed(rotate=(0, 180, 0))
            txt = wp.text(etch, size, depth, combine=False, halign="center", valign="center")
        tshape = txt.val().wrapped
        tb = bbox(tshape)
        etch_info = {"text": etch, "wall": wall, "size_mm": round(size, 3), "inlay_depth_mm": depth,
                     "bbox": [round(v, 3) for v in tb], "colour": [0.82, 0.82, 0.80],
                     "note": "virtual identification aid, NOT a manufacturer marking"}

    # ---- write IN PLACE: keep the original document (prototypes + their colours untouched),
    # wrap the original free shapes under a new root assembly with the pose as a location,
    # remove the FoV cone instances, and add the etch as one more coloured component.
    from OCP.TopLoc import TopLoc_Location
    Tall = gp_Trsf(); Tall.Multiply(t3); Tall.Multiply(T)   # Tall = t3 * T
    pose = TopLoc_Location(Tall)
    root = stool.NewShape()
    TDataStd_Name.Set_s(root, TCollection_ExtendedString("ADOM_ZUP"))
    for i in range(1, labels.Length() + 1):
        stool.AddComponent(root, labels.Value(i), pose)
    # drop the helper-cone instances (components whose solid is a FoV helper)
    removed = 0
    if not keep_fov and fov_idx:
        thresh = 0.01 * vmax
        def prune(lab):
            nonlocal removed
            if not stool.IsAssembly_s(lab):
                return
            comps = TDF_LabelSequence(); stool.GetComponents_s(lab, comps)
            victims = []
            for j in range(1, comps.Length() + 1):
                c = comps.Value(j); ref = TDF_Label()
                if stool.GetReferredShape_s(c, ref):
                    if stool.IsAssembly_s(ref):
                        prune(ref); continue
                    sh = stool.GetShape_s(ref)
                    ex = TopExp_Explorer(sh, TopAbs_SOLID); v = 0.0; n = 0
                    while ex.More():
                        v += volume(ex.Current()); n += 1; ex.Next()
                    if n and v < thresh:
                        victims.append((c, ref))
            for c, ref in victims:
                stool.RemoveComponent(c); stool.RemoveShape(ref, True); removed += 1
        for i in range(1, labels.Length() + 1):
            prune(labels.Value(i))
    else:
        # name the cone instances so a viewer can toggle them
        pass
    if etch:
        elab = stool.AddShape(tshape, False, False)
        TDataStd_Name.Set_s(elab, TCollection_ExtendedString("MPN_ETCH_VIRTUAL"))
        ctool.SetColor(elab, Quantity_Color(0.82, 0.82, 0.80, Quantity_TOC_RGB), XCAFDoc_ColorGen)
        ctool.SetColor(elab, Quantity_Color(0.82, 0.82, 0.80, Quantity_TOC_RGB), XCAFDoc_ColorSurf)
        stool.AddComponent(root, elab, TopLoc_Location())
    stool.UpdateAssemblies()
    w = STEPCAFControl_Writer(); w.SetColorMode(True); w.SetNameMode(True)
    w.Transfer(doc, STEPControl_AsIs)
    if w.Write(dst) != IFSelect_RetDone:
        raise SystemExit("write failed")
    kept = len(pieces) - removed

    rep = {"source": os.path.basename(src), "source_sha256": sha256(src), "output": os.path.basename(dst),
           "output_sha256": sha256(dst), "source_units": "mm", "source_up_axis": "Y",
           "transform": {"rotate_x_deg": 90, "rotate_z_deg": rot_z,
                         "translate_mm": [round(-(xmin + xmax) / 2, 4), round(-(ymin + ymax) / 2, 4), round(-zmin, 4)],
                         "result": "Adom Z-up, underside on z=0, XY centred (footprint frame)"},
           "body_bbox_mm": {"x": body_bb[0], "y": body_bb[1], "z": body_bb[2]},
           "pieces_total": len(pieces), "solids_kept": kept,
           "fov_helper_solids": [{"index": i, "volume_mm3": round(vols[i], 4)} for i in fov_idx],
           "fov_kept": keep_fov, "etch": etch_info}
    if report_path:
        json.dump(rep, open(report_path, "w"), indent=1)
    print(json.dumps({k: rep[k] for k in ("output", "body_bbox_mm", "solids_kept", "fov_helper_solids", "fov_kept", "etch")}))


if __name__ == "__main__":
    main(sys.argv)