tools/epro2/kicad: Phase-1 .kicad_pcb exporter — 6/6 boards open in KiCad 8

Phase-1 scope: produce a .kicad_pcb that kicad-cli loads cleanly and
that has the right geometry (nets, footprints, tracks, vias, board
outline) — not a 1:1 EDA round-trip. Skipped on purpose for Phase 2:
copper pours (POUR/POURED), manual FILL, teardrops, board-level
strings/images, ARC circle-center recovery.

What lands:
  - pcb_writer.write_pcb(): header/general, data-driven layer table
    (F.Cu = ord 0; B.Cu = ord 31; SIGNAL inner ids 15+ allocated to
    In1.Cu/In2.Cu/... in EPRO2-id sorted order so used inner layers
    stay contiguous), net-name → integer id map (id 0 reserved for the
    empty net per KiCad convention), LINE→segment / LINE→gr_line on
    Edge.Cuts, layer-11 POLY paths walked into Edge.Cuts gr_line chains
    (the actual board outline lives on POLY here, not LINE — without
    this stats showed edge=0), VIA→via.
  - footprint_writer.write_footprint_placement(): inline (footprint ...)
    blocks per PCB COMPONENT. EPRO2 RECT/ELLIPSE/OVAL/POLYGON pad
    shapes mapped to KiCad rect/circle/oval/custom; SMD vs THT detected
    by PAD.hole presence; SLOT holes use (drill oval w h). Pad nets
    resolved cross-doc via the existing PCB.PAD_NET → footprint.pad
    chain in ProjectRelations. layerId=2 component → (layer B.Cu) +
    text on B.SilkS so bottom-side parts render correctly.

Smoke test on ESP-VoCat (6 PCBs): all 6 pass `kicad-cli pcb export svg`
and render. DRC on smallest (MicBoard) reports 145 violations + 75
unconnected — most of the unconnected are GND nets that the EPRO2
source resolves through POUR copper, which Phase 2 will export.

CLI: `python -m tools.epro2.kicad <project> --all-pcb --out <dir>`
emits one .kicad_pcb per PCB doc.

52 → 65 unit tests pass. Float comparisons in tests use math.isclose
because the s-expr 6-decimal trim doesn't preserve strict equality
through `value * MIL_TO_MM` round-trips.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-29 00:18:32 +08:00
parent fc2a45f658
commit e61404478e
6 changed files with 1211 additions and 1 deletions

View File

@@ -22,6 +22,7 @@ from pathlib import Path
from ..project_relations import ProjectRelations
from ..replay import Document, Project, replay_project
from .pcb_writer import write_pcb
from .root_sch_writer import ChildSheet, new_sheet_uuid, write_root_sheet
from .sch_writer import write_sch_page
@@ -153,12 +154,44 @@ def _convert_hierarchical(
return root_count
def _convert_all_pcb(proj: Project, out_dir: Path, pr: ProjectRelations) -> int:
"""Emit one .kicad_pcb per PCB doc. Each is named after its META.title
and dropped into a sibling directory of the matching SCH for parity
with the schematic export layout."""
pcb_uuids = [u for u, d in proj.documents.items() if d.doc_type == "PCB"]
if not pcb_uuids:
print("no PCB docs in this project", file=sys.stderr)
return 0
print(f"Converting {len(pcb_uuids)} PCB doc(s) → {out_dir}")
n = 0
for u in pcb_uuids:
doc = proj.documents[u]
title = (doc.objects.get("META") or {}).get("title") or u[:12]
try:
text = write_pcb(doc, project_relations=pr)
except Exception as e: # noqa: BLE001
print(f" FAIL {u[:12]}: {e}", file=sys.stderr)
continue
out_path = out_dir / f"{_safe_filename(title)}.kicad_pcb"
out_path.write_text(text, encoding="utf-8")
stats = getattr(write_pcb, "last_stats", None)
if stats:
print(
f" {out_path.name}: nets={stats.nets} fps={stats.footprints} "
f"fps_unresolved={stats.footprints_unresolved} "
f"segments={stats.segments} vias={stats.vias} edge={stats.edge_cuts}"
)
n += 1
return n
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description="EPRO2 → KiCad schematic exporter (Phase 3 hierarchical)")
ap = argparse.ArgumentParser(description="EPRO2 → KiCad schematic + PCB exporter")
ap.add_argument("project_dir", type=Path)
g = ap.add_mutually_exclusive_group(required=True)
g.add_argument("--doc", help="SCH_PAGE doc uuid (or unique prefix) to convert")
g.add_argument("--all-sch", action="store_true", help="convert every SCH_PAGE")
g.add_argument("--all-pcb", action="store_true", help="convert every PCB doc to .kicad_pcb")
ap.add_argument("--out", type=Path, default=Path("data/processed/kicad_sch"))
ap.add_argument(
"--no-lib-symbols",
@@ -176,6 +209,12 @@ def main(argv: list[str] | None = None) -> int:
args.out.mkdir(parents=True, exist_ok=True)
pr = None if args.no_lib_symbols else ProjectRelations.build(proj)
if args.all_pcb:
if pr is None:
pr = ProjectRelations.build(proj)
_convert_all_pcb(proj, args.out, pr=pr)
return 0
if args.doc:
_convert_one_flat(proj, args.doc, args.out, pr=pr)
return 0