main
John Lauer Family contract: pipeline 1.0.0 that built the three VL53Lx pages 8e4500f
#!/usr/bin/env python3
"""Build the annotated wiki-hero STEP: chip (already Z-up, side-etched) + nonphysical reference
artwork as separately named, coloured solids so the GLB can make them translucent:

  Adom.PadOutlines  teal dashed rectangles of every copper pad (footprint frame, z just under the seat)
  Adom.Silkscreen   the footprint's F.SilkS contours, white
  Adom.PadLabels    signal names per pad, light grey, outside the body, rotated to fit the pitch

usage: hero_step.py <chip.step> <footprint.kicad_mod> <create.json> <out-hero.step> [--report r.json]
The chip bytes are not touched; artwork is added as extra components. Board-use LODs must NOT
include these groups (see wiki-component-lod).
"""
import sys, re, json, math, os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from vendor_step import read_step, sha256
import cadquery as cq
from OCP.XCAFDoc import XCAFDoc_DocumentTool, XCAFDoc_ColorGen, XCAFDoc_ColorSurf
from OCP.TDF import TDF_LabelSequence
from OCP.TDataStd import TDataStd_Name
from OCP.TCollection import TCollection_ExtendedString
from OCP.Quantity import Quantity_Color, Quantity_TOC_RGB
from OCP.TopLoc import TopLoc_Location
from OCP.STEPCAFControl import STEPCAFControl_Writer
from OCP.STEPControl import STEPControl_AsIs
from OCP.IFSelect import IFSelect_RetDone
from OCP.TopExp import TopExp_Explorer
from OCP.TopAbs import TopAbs_FACE

TEAL = (0.0, 0.72, 0.69)
WHITE = (0.97, 0.97, 0.97)
GREY = (0.86, 0.86, 0.86)
Z_ART = -0.02      # just under the seating plane (board surface), so the chip never z-fights it
T_ART = 0.02
DASH, GAP, LINE = 0.14, 0.08, 0.045
TEXT_H = 0.30


def parse_mod(path):
    t = open(path).read()
    pads = []
    for m in re.finditer(r'\(pad\s+"?([^"\s]*)"?\s+smd\s+(\w+)\s*\(at ([-0-9.]+) ([-0-9.]+)(?: ([-0-9.]+))?\)\s*\(size ([-0-9.]+) ([-0-9.]+)\)', t):
        pads.append(dict(name=m.group(1), x=float(m.group(3)), y=-float(m.group(4)), w=float(m.group(6)), h=float(m.group(7))))
    silk = []
    for m in re.finditer(r'\(fp_line \(start ([-0-9.]+) ([-0-9.]+)\) \(end ([-0-9.]+) ([-0-9.]+)\) \(stroke \(width ([-0-9.]+)\)[^\n]*?\(layer "F.SilkS"\)', t):
        x1, y1, x2, y2, w = map(float, m.groups()); silk.append(("line", x1, -y1, x2, -y2, w))
    for m in re.finditer(r'\(fp_circle \(center ([-0-9.]+) ([-0-9.]+)\) \(end ([-0-9.]+) ([-0-9.]+)\) \(stroke \(width ([-0-9.]+)\)[^\n]*?\(layer "F.SilkS"\)', t):
        cx, cy, ex, ey, w = map(float, m.groups()); silk.append(("circle", cx, -cy, math.hypot(ex - cx, ey - cy), 0, w))
    return pads, silk


def dashed_rect(wp, x, y, w, h):
    solids = []
    corners = [(x - w / 2, y - h / 2), (x + w / 2, y - h / 2), (x + w / 2, y + h / 2), (x - w / 2, y + h / 2)]
    for i in range(4):
        (x1, y1), (x2, y2) = corners[i], corners[(i + 1) % 4]
        L = math.hypot(x2 - x1, y2 - y1); ang = math.degrees(math.atan2(y2 - y1, x2 - x1))
        n = max(1, int(L // (DASH + GAP)))
        step = L / n
        for k in range(n):
            s = k * step; d = min(DASH, step * 0.65)
            cx = x1 + (x2 - x1) * (s + d / 2) / L; cy = y1 + (y2 - y1) * (s + d / 2) / L
            solids.append(wp.center(cx, cy).transformed(rotate=(0, 0, ang)).rect(d, LINE).extrude(T_ART).val())
    return solids


def main(argv):
    chip, mod, cjson, dst = argv[1:5]
    report_path = argv[argv.index("--report") + 1] if "--report" in argv else None
    pads, silk = parse_mod(mod)
    names = {p["number"]: p["name"] for p in json.load(open(cjson))["pins"]}
    wp = lambda: cq.Workplane("XY").workplane(offset=Z_ART)
    # pad outlines
    pad_solids = []
    for p in pads:
        pad_solids += dashed_rect(wp(), p["x"], p["y"], p["w"], p["h"])
    # silkscreen
    silk_solids = []
    for kind, a, b, c, d, w in silk:
        if kind == "line":
            L = math.hypot(c - a, d - b); ang = math.degrees(math.atan2(d - b, c - a))
            silk_solids.append(wp().center((a + c) / 2, (b + d) / 2).transformed(rotate=(0, 0, ang)).rect(L + w, w).extrude(T_ART).val())
        else:
            silk_solids.append(wp().center(a, b).circle(c + w / 2).circle(max(c - w / 2, 0.01)).extrude(T_ART).val())
    # labels: outside the silk box, vertical for the two pad rows, horizontal for the side pads
    xs = [p["x"] for p in pads]; ys = [p["y"] for p in pads]
    ymax_s = max([abs(s[2]) for s in silk] + [abs(s[4]) for s in silk if s[0] == "line"] + [1.7])
    xmax_s = max([abs(s[1]) for s in silk] + [abs(s[3]) for s in silk if s[0] == "line"] + [3.4])
    label_solids = []; placed = []
    def text(txt, x, y, rot, halign):
        w = wp().center(x, y).transformed(rotate=(0, 0, rot))
        s = w.text(txt, TEXT_H, T_ART, combine=False, halign=halign, valign="center", kind="regular")
        label_solids.append(s.val()); placed.append(dict(pad=txt, x=x, y=y, rot=rot))
    for p in pads:
        nm = names.get(p["name"], p["name"])
        if abs(p["y"]) > 0.6 and abs(p["x"]) < 2.5:          # the two rows
            if p["y"] < 0:
                text(nm, p["x"], -ymax_s - 0.25, 90, "right")   # reads upward, ends at the silk
            else:
                text(nm, p["x"], ymax_s + 0.25, 90, "left")
        elif abs(p["x"]) > 2.5:                                 # side pads
            if p["x"] > 0:
                text(nm, xmax_s + 0.25, p["y"], 0, "left")
            else:
                text(nm, -xmax_s - 0.25, p["y"], 0, "right")
        else:                                                   # thermal pad
            text(f"{nm} ({p['name']})", 0, -ymax_s - 0.25 - 3.4, 0, "center")
    # ---- add to the chip doc as coloured, named components
    doc = read_step(chip)
    stool = XCAFDoc_DocumentTool.ShapeTool_s(doc.Main()); ctool = XCAFDoc_DocumentTool.ColorTool_s(doc.Main())
    labels = TDF_LabelSequence(); stool.GetFreeShapes(labels)
    root = stool.NewShape(); TDataStd_Name.Set_s(root, TCollection_ExtendedString("ADOM_HERO"))
    chip_root = stool.NewShape(); TDataStd_Name.Set_s(chip_root, TCollection_ExtendedString("Adom.Chip"))
    for i in range(1, labels.Length() + 1):
        stool.AddComponent(chip_root, labels.Value(i), TopLoc_Location())
    stool.AddComponent(root, chip_root, TopLoc_Location())

    def add_group(name, solids, colour):
        if not solids:
            return
        comp = cq.Compound.makeCompound(solids).wrapped
        lab = stool.AddShape(comp, False, False)
        TDataStd_Name.Set_s(lab, TCollection_ExtendedString(name))
        col = Quantity_Color(*colour, Quantity_TOC_RGB)
        ctool.SetColor(lab, col, XCAFDoc_ColorGen); ctool.SetColor(lab, col, XCAFDoc_ColorSurf)
        ex = TopExp_Explorer(comp, TopAbs_FACE)
        while ex.More():
            fl = stool.AddSubShape(lab, ex.Current())
            if not fl.IsNull():
                ctool.SetColor(fl, col, XCAFDoc_ColorSurf)
            ex.Next()
        stool.AddComponent(root, lab, TopLoc_Location())
    add_group("Adom.PadOutlines", pad_solids, TEAL)
    add_group("Adom.Silkscreen", silk_solids, WHITE)
    add_group("Adom.PadLabels", label_solids, GREY)
    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")
    rep = {"chip": os.path.basename(chip), "chip_sha256": sha256(chip), "footprint": os.path.basename(mod),
           "output": os.path.basename(dst), "output_sha256": sha256(dst),
           "groups": {"Adom.PadOutlines": {"colour": TEAL, "alpha": 0.5, "count": len(pad_solids)},
                      "Adom.Silkscreen": {"colour": WHITE, "alpha": 0.3, "count": len(silk_solids)},
                      "Adom.PadLabels": {"colour": GREY, "alpha": 0.5, "count": len(label_solids)}},
           "z_art_mm": Z_ART, "labels": placed,
           "note": "nonphysical hero-only artwork; board LODs must exclude these groups"}
    if report_path:
        json.dump(rep, open(report_path, "w"), indent=1)
    print(json.dumps({k: rep[k] for k in ("output", "groups")}))


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