main
John Lauer Schematic symbols U1/L1/D1: chip outlines drawn in the standard iso pose (pin 1 toward the viewer) so part numbers read… 11be571
#!/usr/bin/env python3
"""Build L1 / C1 / D1 as the standard KiCad schematic symbols (Device:L coil, Device:C_Polarized with
its +, Device:LED triangle / bar / emission arrows) with the part's 3D outline as a small graphic
OFFSET beside the symbol, into ../../lib/buck12v5v.kicad_sym (U1 TPS54202DDCR is kept as it is).

John, 2026-10-02: EEs must still see the standard symbol; the outline only shows what the part looks
like on the board (that D1 is a small SMD LED, not a through-hole one), so it sits off to the side and
never overlaps the symbol, its pins, its text or a wire.

1. `adom-symbol create --file <MPN>-create.json --outline-svg <outline> --outline-name none` gives the
   Adom fields (MPN / Manufacturer / Mouser / DigiKey / Adom Wiki / Adom_Chip_Outline) and the outline
   as symbol polylines. The outlines come from service-step2glb's /outline (OCCT HLR), see outlines/:
   Every outline shows the part in the standard iso pose, pin 1 / pad 1 toward the camera, so the part
   number reads upright and left to right like a real part's marking (John, 2026-10-03). The service's
   camera looks at a KiCad-frame part from the pad-2 side, so L1 and D1 are turned 180 deg about their
   vertical first (rotate_step_xcaf.py); C1's footprint binding already carries that turn (-90 0 180).
     L1 AMPLH5030S-150MT  Abracon STEP turned 180; its raised AMPLH5030S print (upright in this pose)
                          replaced by the service's flat name at rot=270 (same line and reading
                          direction as the print), l1_compose.py
     C1 EEE-FK1V470P      bare Panasonic STEP (upAxis=y) + flat name at rot=270: along the polarity
                          stripe on the silver field, reading from the + side, as on the etched STEP
     D1 IN-S63BTG         plain outline of the side-etched STEP turned 180: the mark on the -Y side wall
                          faces the camera and reads upright; the top and lens window stay clear
2. The graphics and pins are KiCad's Device symbol, turned in the library to the way the sheet draws
   the part (L1 horizontal, pin 1 left; D1 vertical, A on top), so the sheet places them unrotated and
   the outline stays upright. Pin numbers, names and types are Device's, so the netlist differs from
   v1/v2 only in libsource.
3. The outline polylines are scaled to fit the outline box (about the symbol's own height, much
   smaller than U1's) and drawn as thin grey lines; keywords and footprint filters are Device's.
"""
import json, os, subprocess, sys, tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
KI = os.path.normpath(os.path.join(HERE, "..", ".."))
sys.path.insert(0, KI)
import sexp
from sexp import Sym as S

O = os.path.join(HERE, "outlines")
PARTS = [
    # mpn, Device symbol, CCW turn (deg), outline svg, outline box (x0, y0, x1, y1) mm y-up,
    # Reference (x, y, justify), Value (x, y, justify): centred above / below the pins so they clear the
    # outline and the arrows in any renderer (the sheet places its own field text)
    ("AMPLH5030S-150MT", "L", 90, "AMPLH5030S-150MT-3d-outline-dark-named270.svg", (-2.8, 1.5, 2.8, 6.3),
     (0, -1.9, None), (0, -3.6, None)),
    ("EEE-FK1V470P", "C_Polarized", 0, "EEE-FK1V470P-3d-outline-dark-named270.svg", (-8.4, -2.7, -3.2, 2.7),
     (0, 5.08, None), (0, -6.35, None)),
    ("IN-S63BTG", "LED", 90, "IN-S63BTG-3d-outline-dark.svg", (-8.4, -2.4, -2.6, 2.4),
     (0, 5.08, None), (0, -6.35, None)),
]
GREY = [S("color"), 110, 110, 110, 1]


def num(v):
    v = round(float(v), 4)
    return S(f"{v:.4f}".rstrip("0").rstrip(".") if abs(v) > 1e-9 else "0")


def turn(x, y, deg):
    x, y = float(x), float(y)
    for _ in range((deg // 90) % 4):          # CCW, y up: (x, y) -> (-y, x)
        x, y = -y, x
    return x, y


def turn_node(node, deg):
    """Turn every coordinate of a library graphic / pin by deg (CCW)."""
    if not isinstance(node, list) or not node:
        return
    if node[0] in ("xy", "start", "end", "mid", "center") and len(node) >= 3:
        node[1], node[2] = map(num, turn(node[1], node[2], deg))
        return
    if node[0] == "at" and len(node) >= 3:
        node[1], node[2] = map(num, turn(node[1], node[2], deg))
        if len(node) >= 4:
            node[3] = S(str((int(float(node[3])) + deg) % 360))
        return
    for e in node[1:]:
        turn_node(e, deg)


def fprop(name, value, x, y, hide=False, justify=None):
    eff = [S("effects"), [S("font"), [S("size"), S("1.27"), S("1.27")]]]
    if justify:
        eff.append([S("justify"), S(justify)])
    if hide:
        eff.append([S("hide"), S("yes")])
    return [S("property"), name, value, [S("at"), num(x), num(y), S("0")], eff]


dev = sexp.lib_symbols(os.path.join(KI, "lib", "Device.kicad_sym"))


def build(mpn, devname, deg, outline, box, refat, valat):
    spec = json.load(open(os.path.join(HERE, f"{mpn}-create.json")))
    out = tempfile.mkdtemp()
    subprocess.run(["adom-symbol", "create", "--file", os.path.join(HERE, f"{mpn}-create.json"), "--out", out,
                    "--outline-svg", os.path.join(O, outline), "--outline-name", "none"],
                   check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    adom = sexp.first(sexp.parse(open(os.path.join(out, f"{mpn}.kicad_sym"), encoding="utf-8").read()), "symbol")
    aprops = {p[1]: p[2] for p in sexp.find(adom, "property")}
    polys = [pl for u in sexp.find(adom, "symbol") for pl in sexp.find(u, "polyline")]
    assert polys, f"{mpn}: no outline polylines"

    sym = sexp.flatten(devname, dev, "Device")
    dprops = {p[1]: p[2] for p in sexp.find(sym, "property")}
    body = [e for e in sym[2:] if not (isinstance(e, list) and e and e[0] == "property")]
    for u in sexp.find(body, "symbol"):
        u[1] = mpn + u[1][len(devname):]
        turn_node(u, deg)
    # outline: adom-symbol's polylines, scaled into the box beside the symbol, thin grey
    xs = [float(p[1]) for pl in polys for p in sexp.first(pl, "pts")[1:]]
    ys = [float(p[2]) for pl in polys for p in sexp.first(pl, "pts")[1:]]
    x0, y0, x1, y1 = box
    sc = min((x1 - x0) / (max(xs) - min(xs)), (y1 - y0) / (max(ys) - min(ys)))
    cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
    art = []
    for pl in polys:
        pts = [S("pts")] + [[S("xy"), num((x0 + x1) / 2 + (float(p[1]) - cx) * sc), num((y0 + y1) / 2 + (float(p[2]) - cy) * sc)]
                            for p in sexp.first(pl, "pts")[1:]]
        art.append([S("polyline"), pts, [S("stroke"), [S("width"), S("0.1")], [S("type"), S("default")], GREY],
                    [S("fill"), [S("type"), S("none")]]])
    unit0 = [u for u in sexp.find(body, "symbol") if u[1].endswith("_0_1")][0]
    unit0.extend(art)
    for u in sexp.find(body, "symbol"):
        for p in sexp.find(u, "pin"):
            at = sexp.first(p, "at")
            x, y = float(at[1]), float(at[2])
            assert abs(x / 1.27 - round(x / 1.27)) < 1e-6 and abs(y / 1.27 - round(y / 1.27)) < 1e-6, (mpn, x, y)

    hy = y0 - 6
    props = [fprop("Reference", spec["referencePrefix"], refat[0], refat[1], justify=refat[2]),
             fprop("Value", mpn, valat[0], valat[1], justify=valat[2]),
             fprop("Footprint", spec["footprint"], 0, hy, hide=True),
             fprop("Datasheet", spec["datasheetUrl"], 0, hy - 2.54, hide=True),
             fprop("Description", spec["description"], 0, hy - 5.08, hide=True)]
    extra = [k for k in ("Manufacturer", "MPN", "Adom Wiki", "DigiKey", "Mouser", "Adom_Chip_Outline") if aprops.get(k)]
    for i, k in enumerate(extra):
        props.append(fprop(k, aprops[k], 0, hy - 7.62 - 2.54 * i, hide=True))
    props.append(fprop("ki_keywords", dprops.get("ki_keywords", ""), 0, 0, hide=True))
    props.append(fprop("ki_fp_filters", dprops.get("ki_fp_filters", ""), 0, 0, hide=True))
    lead = [e for e in body if isinstance(e, list) and e and e[0] in ("pin_numbers", "pin_names", "exclude_from_sim", "in_bom", "on_board")]
    tail = [e for e in body if not any(e is x for x in lead)]
    return [S("symbol"), mpn] + lead + props + tail


dst = os.path.join(KI, "lib", "buck12v5v.kicad_sym")
lib = sexp.parse(open(dst, encoding="utf-8").read())
names = {p[0] for p in PARTS}
lib[:] = [e for e in lib if not (isinstance(e, list) and e and e[0] == "symbol" and e[1] in names)]
for part in PARTS:
    lib.append(build(*part))
open(dst, "w", encoding="utf-8").write(sexp.dump(lib) + "\n")
print("wrote", dst, [e[1] for e in lib if isinstance(e, list) and e and e[0] == "symbol"])