traceforge-pcb 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- traceforge/__init__.py +3 -0
- traceforge/__main__.py +3 -0
- traceforge/acp_server.py +570 -0
- traceforge/agent.py +680 -0
- traceforge/altium/__init__.py +6 -0
- traceforge/altium/cfb.py +70 -0
- traceforge/altium/cli.py +60 -0
- traceforge/altium/model.py +163 -0
- traceforge/altium/outputs.py +24 -0
- traceforge/altium/pcb.py +301 -0
- traceforge/altium/project.py +328 -0
- traceforge/altium/schematic.py +400 -0
- traceforge/altium/tools.py +166 -0
- traceforge/approval.py +219 -0
- traceforge/attachments.py +346 -0
- traceforge/background.py +253 -0
- traceforge/bench/__init__.py +5 -0
- traceforge/bench/adapters.py +337 -0
- traceforge/bench/checks.py +410 -0
- traceforge/bench/cli.py +121 -0
- traceforge/bench/design.py +439 -0
- traceforge/bench/kicad.py +99 -0
- traceforge/bench/partscheck.py +159 -0
- traceforge/bench/review.py +100 -0
- traceforge/bench/runner.py +226 -0
- traceforge/bench/score.py +204 -0
- traceforge/bench/tasks.py +102 -0
- traceforge/chat.py +1185 -0
- traceforge/checks.py +328 -0
- traceforge/checks_sides.py +118 -0
- traceforge/cli.py +2224 -0
- traceforge/clipboard.py +107 -0
- traceforge/config.py +299 -0
- traceforge/context.py +276 -0
- traceforge/design/__init__.py +1 -0
- traceforge/design/constraints.py +397 -0
- traceforge/design/generate.py +1789 -0
- traceforge/design/outline.py +905 -0
- traceforge/design/schematic_layout.py +932 -0
- traceforge/design/schematic_lint.py +329 -0
- traceforge/design/schematic_route.py +207 -0
- traceforge/design/sheets.py +854 -0
- traceforge/design/sides.py +328 -0
- traceforge/design/spec.py +462 -0
- traceforge/design/specsheet.py +2351 -0
- traceforge/design/specsheet_render.py +183 -0
- traceforge/desktop/__init__.py +109 -0
- traceforge/desktop/keys.py +90 -0
- traceforge/desktop/project.py +443 -0
- traceforge/desktop/review.py +20 -0
- traceforge/desktop/server.py +1277 -0
- traceforge/desktop/static/app.css +223 -0
- traceforge/desktop/static/app.js +683 -0
- traceforge/desktop/static/highlight.js +77 -0
- traceforge/desktop/static/index.html +89 -0
- traceforge/desktop/static/md.js +90 -0
- traceforge/desktop/static/viewer.js +213 -0
- traceforge/desktop/symbols.py +212 -0
- traceforge/desktop/update.py +65 -0
- traceforge/diagnostics.py +67 -0
- traceforge/errata.py +219 -0
- traceforge/fab.py +108 -0
- traceforge/fab_layers.py +44 -0
- traceforge/features/__init__.py +6 -0
- traceforge/features/candidates.py +117 -0
- traceforge/features/cli.py +200 -0
- traceforge/features/package.py +433 -0
- traceforge/features/revdiff.py +224 -0
- traceforge/features/sarif.py +145 -0
- traceforge/features/viewer.py +265 -0
- traceforge/firmware/__init__.py +3 -0
- traceforge/firmware/cli.py +174 -0
- traceforge/firmware/drivers.py +372 -0
- traceforge/firmware/drivers_data.py +256 -0
- traceforge/firmware/mcus.py +177 -0
- traceforge/firmware/netlist.py +55 -0
- traceforge/firmware/pinmap.py +296 -0
- traceforge/firmware/scaffold.py +466 -0
- traceforge/firmware/toolchain.py +262 -0
- traceforge/hooks.py +237 -0
- traceforge/kicad/__init__.py +0 -0
- traceforge/kicad/cli.py +519 -0
- traceforge/kicad/diffpair.py +174 -0
- traceforge/kicad/edgegeom.py +191 -0
- traceforge/kicad/edit.py +405 -0
- traceforge/kicad/escape.py +1410 -0
- traceforge/kicad/formats.py +1073 -0
- traceforge/kicad/impedance.py +320 -0
- traceforge/kicad/install.py +75 -0
- traceforge/kicad/libraries.py +490 -0
- traceforge/kicad/models3d.py +942 -0
- traceforge/kicad/outputs.py +81 -0
- traceforge/kicad/pcb.py +787 -0
- traceforge/kicad/planes.py +1242 -0
- traceforge/kicad/project.py +136 -0
- traceforge/kicad/route.py +2698 -0
- traceforge/kicad/routegeom.py +164 -0
- traceforge/kicad/schematic.py +268 -0
- traceforge/kicad/sides.py +34 -0
- traceforge/kicad/stackup.py +424 -0
- traceforge/kicad_plugin/__init__.py +12 -0
- traceforge/kicad_plugin/actions.py +92 -0
- traceforge/kicad_plugin/cli.py +66 -0
- traceforge/kicad_plugin/client.py +86 -0
- traceforge/kicad_plugin/context.py +257 -0
- traceforge/kicad_plugin/discovery.py +81 -0
- traceforge/kicad_plugin/install.py +203 -0
- traceforge/kicad_plugin/overlay.py +60 -0
- traceforge/kicad_plugin/payload/action_plugin.py +65 -0
- traceforge/kicad_plugin/payload/ipc_main.py +42 -0
- traceforge/kicad_plugin/payload/plugin.json +90 -0
- traceforge/kicad_plugin/payload/requirements.txt +1 -0
- traceforge/kicad_plugin/views.py +202 -0
- traceforge/langchain.py +57 -0
- traceforge/local.py +580 -0
- traceforge/mcp_server.py +304 -0
- traceforge/models.py +310 -0
- traceforge/next_steps.py +110 -0
- traceforge/parts/__init__.py +52 -0
- traceforge/parts/alternates.py +488 -0
- traceforge/parts/bom.py +423 -0
- traceforge/parts/brief.py +705 -0
- traceforge/parts/catalog.py +297 -0
- traceforge/parts/cli_sourcing.py +156 -0
- traceforge/parts/data/duty_rates.yaml +37 -0
- traceforge/parts/data/hs_codes.yaml +103 -0
- traceforge/parts/datasheet.py +278 -0
- traceforge/parts/fx.py +100 -0
- traceforge/parts/model.py +185 -0
- traceforge/parts/net.py +187 -0
- traceforge/parts/offers.py +46 -0
- traceforge/parts/packages.py +397 -0
- traceforge/parts/pinout.py +714 -0
- traceforge/parts/providers/__init__.py +17 -0
- traceforge/parts/providers/base.py +100 -0
- traceforge/parts/providers/jlc.py +364 -0
- traceforge/parts/providers/keyed.py +661 -0
- traceforge/parts/report.py +508 -0
- traceforge/parts/supply.py +330 -0
- traceforge/parts/verify.py +455 -0
- traceforge/parts/web.py +575 -0
- traceforge/plans.py +70 -0
- traceforge/preferences.py +127 -0
- traceforge/prices.py +130 -0
- traceforge/prices.yaml +28 -0
- traceforge/prompts/__init__.py +54 -0
- traceforge/prompts/system.md +103 -0
- traceforge/providers.py +764 -0
- traceforge/remote/__init__.py +33 -0
- traceforge/remote/client.py +422 -0
- traceforge/remote/oidc.py +240 -0
- traceforge/remote/orgs.py +510 -0
- traceforge/remote/server.py +690 -0
- traceforge/remote/store.py +100 -0
- traceforge/review_changes.py +187 -0
- traceforge/routing.py +99 -0
- traceforge/runtime.py +435 -0
- traceforge/sessions.py +324 -0
- traceforge/sexpr.py +279 -0
- traceforge/sim/__init__.py +17 -0
- traceforge/sim/acmath.py +234 -0
- traceforge/sim/circuit.py +499 -0
- traceforge/sim/cli.py +162 -0
- traceforge/sim/engine.py +172 -0
- traceforge/sim/ltspice.py +175 -0
- traceforge/sim/measure.py +123 -0
- traceforge/sim/models.py +76 -0
- traceforge/sim/project.py +218 -0
- traceforge/sim/rawfile.py +123 -0
- traceforge/sim/results.py +298 -0
- traceforge/sim/tune.py +172 -0
- traceforge/skill_commands.py +165 -0
- traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
- traceforge/skill_library/compliance-review/SKILL.md +51 -0
- traceforge/skill_library/design-review/SKILL.md +47 -0
- traceforge/skill_library/errata-hunt/SKILL.md +30 -0
- traceforge/skill_library/firmware/SKILL.md +26 -0
- traceforge/skill_library/power-budget/SKILL.md +27 -0
- traceforge/skill_library/release-package/SKILL.md +29 -0
- traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
- traceforge/skill_library/thermal-review/SKILL.md +15 -0
- traceforge/skills.py +131 -0
- traceforge/thermal.py +557 -0
- traceforge/tools/__init__.py +48 -0
- traceforge/tools/agent_tools.py +213 -0
- traceforge/tools/base.py +303 -0
- traceforge/tools/batch.py +155 -0
- traceforge/tools/connections.py +245 -0
- traceforge/tools/files.py +777 -0
- traceforge/tools/firmware_tools.py +218 -0
- traceforge/tools/kicad_tools.py +1072 -0
- traceforge/tools/models3d_tools.py +141 -0
- traceforge/tools/parts_tools.py +473 -0
- traceforge/tools/processes.py +246 -0
- traceforge/tools/review_tools.py +178 -0
- traceforge/tools/sim_tools.py +230 -0
- traceforge/tui.py +620 -0
- traceforge/updates.py +124 -0
- traceforge/validate/__init__.py +77 -0
- traceforge/validate/builtins.py +1091 -0
- traceforge/validate/circuits.py +1240 -0
- traceforge/validate/config.py +410 -0
- traceforge/validate/default.yaml +113 -0
- traceforge/validate/design.py +191 -0
- traceforge/validate/explain.py +112 -0
- traceforge/validate/grounding.py +169 -0
- traceforge/validate/ipc2221.py +350 -0
- traceforge/validate/multilayer.py +805 -0
- traceforge/validate/netmodel.py +261 -0
- traceforge/validate/partcheck.py +472 -0
- traceforge/validate/report.py +280 -0
- traceforge/validate/review.py +322 -0
- traceforge/validate/runner.py +662 -0
- traceforge/workspace.py +171 -0
- traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
- traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
- traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
- traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
- traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1789 @@
|
|
|
1
|
+
"""Compile a :class:`DesignSpec` into a KiCad project (schematic + board).
|
|
2
|
+
|
|
3
|
+
The output is written in the file format of the installed KiCad by default
|
|
4
|
+
(``kicad_version="auto"``), or of KiCad 7, 8, 9 or 10 when asked: the tree is built
|
|
5
|
+
once and :mod:`traceforge.kicad.formats` rewrites it for the target release, so
|
|
6
|
+
library parts from a newer KiCad can be written for an older one and vice versa.
|
|
7
|
+
KiCad 10 opens the KiCad 9 format. Symbols and footprints are copied from the
|
|
8
|
+
installed KiCad libraries, so the generated design is exactly what KiCad's own
|
|
9
|
+
editors would produce from the same library parts.
|
|
10
|
+
|
|
11
|
+
Schematic connectivity uses net labels placed on every pin end; there are no
|
|
12
|
+
wires to route by hand. The board gets every footprint with its pad nets
|
|
13
|
+
assigned, a board outline and fab-ready design rules. Tracks are left to the
|
|
14
|
+
router (``traceforge route``) or to the agent.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import copy
|
|
20
|
+
import json
|
|
21
|
+
import math
|
|
22
|
+
import os
|
|
23
|
+
import re
|
|
24
|
+
import uuid as uuidlib
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from traceforge import sexpr
|
|
29
|
+
from traceforge.design import constraints
|
|
30
|
+
from traceforge.design import outline as outlinemod
|
|
31
|
+
from traceforge.design import sides as sidemod
|
|
32
|
+
from traceforge.design.spec import DesignSpec, PartSpec
|
|
33
|
+
from traceforge.fab import FabProfile, get_fab
|
|
34
|
+
from traceforge.kicad import diffpair, formats, impedance, stackup
|
|
35
|
+
from traceforge.kicad.libraries import (
|
|
36
|
+
LibPin,
|
|
37
|
+
Libraries,
|
|
38
|
+
LibraryError,
|
|
39
|
+
LibSymbol,
|
|
40
|
+
footprint_extent,
|
|
41
|
+
footprint_pad_numbers,
|
|
42
|
+
)
|
|
43
|
+
from traceforge.kicad.pcb import _rotate, edge_marker
|
|
44
|
+
from traceforge.sexpr import Node, Sym, find, find_all, fmt
|
|
45
|
+
|
|
46
|
+
SCH_VERSION = "20230121"
|
|
47
|
+
PCB_VERSION = "20221018"
|
|
48
|
+
GRID = 2.54
|
|
49
|
+
_NAMESPACE = uuidlib.UUID("7f1d3c2a-5b4e-4f60-9a8b-1c2d3e4f5a6b")
|
|
50
|
+
|
|
51
|
+
_MOUNTING_HOLES = {
|
|
52
|
+
2.2: "MountingHole_2.2mm_M2",
|
|
53
|
+
2.7: "MountingHole_2.7mm_M2.5",
|
|
54
|
+
3.2: "MountingHole_3.2mm_M3",
|
|
55
|
+
4.3: "MountingHole_4.3mm_M4",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class DesignError(ValueError):
|
|
60
|
+
"""The spec cannot be compiled (unknown symbol, pin, footprint...)."""
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass
|
|
64
|
+
class Issue:
|
|
65
|
+
severity: str # error | warning | info
|
|
66
|
+
message: str
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> dict:
|
|
69
|
+
return {"severity": self.severity, "message": self.message}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class GenerationResult:
|
|
74
|
+
project: Path
|
|
75
|
+
schematic: Path
|
|
76
|
+
pcb: Path
|
|
77
|
+
issues: list[Issue] = field(default_factory=list)
|
|
78
|
+
stats: dict = field(default_factory=dict)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def ok(self) -> bool:
|
|
82
|
+
return not any(i.severity == "error" for i in self.issues)
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict:
|
|
85
|
+
return {
|
|
86
|
+
"ok": self.ok,
|
|
87
|
+
"project": str(self.project),
|
|
88
|
+
"schematic": str(self.schematic),
|
|
89
|
+
"pcb": str(self.pcb),
|
|
90
|
+
"stats": self.stats,
|
|
91
|
+
"issues": [i.to_dict() for i in self.issues],
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _uuid(*parts: str) -> str:
|
|
96
|
+
return str(uuidlib.uuid5(_NAMESPACE, "/".join(parts)))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _snap(value: float, grid: float = GRID) -> float:
|
|
100
|
+
return round(value / grid) * grid
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _effects(size: float = 1.27, *, hide: bool = False, justify: list[str] | None = None) -> Node:
|
|
104
|
+
node: Node = [Sym("effects"), [Sym("font"), [Sym("size"), fmt(size), fmt(size)]]]
|
|
105
|
+
if justify:
|
|
106
|
+
node.append([Sym("justify"), *[Sym(j) for j in justify]])
|
|
107
|
+
if hide:
|
|
108
|
+
node.append(Sym("hide"))
|
|
109
|
+
return node
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@dataclass
|
|
113
|
+
class _ResolvedPart:
|
|
114
|
+
spec: PartSpec
|
|
115
|
+
symbol: LibSymbol
|
|
116
|
+
pin_nets: dict[str, str] # pin number -> net
|
|
117
|
+
nc_pins: set[str]
|
|
118
|
+
footprint: Node | None
|
|
119
|
+
uuids: dict[int, str] # unit -> symbol uuid
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Generator:
|
|
123
|
+
def __init__(
|
|
124
|
+
self,
|
|
125
|
+
spec: DesignSpec,
|
|
126
|
+
libraries: Libraries | None = None,
|
|
127
|
+
kicad_version: int | str | None = None,
|
|
128
|
+
):
|
|
129
|
+
self.spec = spec
|
|
130
|
+
self.libs = libraries or Libraries()
|
|
131
|
+
self.issues: list[Issue] = []
|
|
132
|
+
self.sheet_files: dict[str, Node] = {}
|
|
133
|
+
self.sheet_stats: dict = {}
|
|
134
|
+
self._sides: dict[str, str] = {}
|
|
135
|
+
self.fab: FabProfile = get_fab(spec.fab)
|
|
136
|
+
self.root_uuid = _uuid(spec.name, "root")
|
|
137
|
+
requested = (
|
|
138
|
+
kicad_version or spec.kicad_version or os.environ.get("TRACEFORGE_KICAD_VERSION")
|
|
139
|
+
)
|
|
140
|
+
try:
|
|
141
|
+
self.kicad_version = formats.resolve_target(requested)
|
|
142
|
+
except ValueError as exc:
|
|
143
|
+
raise DesignError(str(exc)) from exc
|
|
144
|
+
|
|
145
|
+
# ---------------------------------------------------------------- resolve
|
|
146
|
+
def _with_mounting_holes(self) -> list[PartSpec]:
|
|
147
|
+
parts = list(self.spec.parts)
|
|
148
|
+
drill = self.spec.board.mounting_holes
|
|
149
|
+
if drill:
|
|
150
|
+
size = min(_MOUNTING_HOLES, key=lambda d: abs(d - drill))
|
|
151
|
+
existing = {p.ref for p in parts}
|
|
152
|
+
index = 1
|
|
153
|
+
for _ in range(4):
|
|
154
|
+
while f"H{index}" in existing:
|
|
155
|
+
index += 1
|
|
156
|
+
parts.append(
|
|
157
|
+
PartSpec(
|
|
158
|
+
ref=f"H{index}",
|
|
159
|
+
symbol="Mechanical:MountingHole",
|
|
160
|
+
value=f"M{size:g}",
|
|
161
|
+
footprint=f"MountingHole:{_MOUNTING_HOLES[size]}",
|
|
162
|
+
group="__holes__",
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
existing.add(f"H{index}")
|
|
166
|
+
return parts
|
|
167
|
+
|
|
168
|
+
def resolve(self) -> list[_ResolvedPart]:
|
|
169
|
+
resolved: list[_ResolvedPart] = []
|
|
170
|
+
for part in self._with_mounting_holes():
|
|
171
|
+
try:
|
|
172
|
+
symbol = self.libs.symbol(part.symbol)
|
|
173
|
+
except LibraryError as exc:
|
|
174
|
+
raise DesignError(f"{part.ref}: {exc}") from exc
|
|
175
|
+
pin_nets: dict[str, str] = {}
|
|
176
|
+
for key, net in part.pins.items():
|
|
177
|
+
pins = symbol.resolve_pin(key)
|
|
178
|
+
if not pins:
|
|
179
|
+
available = ", ".join(sorted({f"{p.number}({p.name})" for p in symbol.pins}))
|
|
180
|
+
raise DesignError(
|
|
181
|
+
f"{part.ref}: symbol {part.symbol} has no pin {key!r}. Pins: {available}"
|
|
182
|
+
)
|
|
183
|
+
for pin in pins:
|
|
184
|
+
previous = pin_nets.get(pin.number)
|
|
185
|
+
if previous and previous != net:
|
|
186
|
+
raise DesignError(
|
|
187
|
+
f"{part.ref}.{pin.number} assigned to both {previous} and {net}"
|
|
188
|
+
)
|
|
189
|
+
pin_nets[pin.number] = net
|
|
190
|
+
nc_pins: set[str] = set()
|
|
191
|
+
for key in part.nc:
|
|
192
|
+
pins = symbol.resolve_pin(key)
|
|
193
|
+
if not pins:
|
|
194
|
+
raise DesignError(f"{part.ref}: nc pin {key!r} does not exist on {part.symbol}")
|
|
195
|
+
nc_pins.update(p.number for p in pins)
|
|
196
|
+
overlap = nc_pins & set(pin_nets)
|
|
197
|
+
if overlap:
|
|
198
|
+
raise DesignError(
|
|
199
|
+
f"{part.ref}: pins {sorted(overlap)} are both connected and marked nc"
|
|
200
|
+
)
|
|
201
|
+
unassigned = sorted(
|
|
202
|
+
{p.number for p in symbol.pins if p.electrical != "no_connect"}
|
|
203
|
+
- set(pin_nets)
|
|
204
|
+
- nc_pins,
|
|
205
|
+
key=_pin_key,
|
|
206
|
+
)
|
|
207
|
+
if unassigned and not symbol.is_power and symbol.pins:
|
|
208
|
+
names = {p.number: p.name for p in symbol.pins}
|
|
209
|
+
pretty = ", ".join(f"{n}({names.get(n, '')})" for n in unassigned)
|
|
210
|
+
self.issues.append(
|
|
211
|
+
Issue(
|
|
212
|
+
"warning",
|
|
213
|
+
f"{part.ref} ({part.symbol}): unconnected pins {pretty}. "
|
|
214
|
+
"Connect them or list them under nc.",
|
|
215
|
+
)
|
|
216
|
+
)
|
|
217
|
+
footprint_id = part.footprint or symbol.properties.get("Footprint") or None
|
|
218
|
+
footprint = None
|
|
219
|
+
if footprint_id:
|
|
220
|
+
try:
|
|
221
|
+
actual_id = self.libs.resolve_footprint_id(footprint_id)
|
|
222
|
+
if actual_id != footprint_id:
|
|
223
|
+
self.issues.append(
|
|
224
|
+
Issue(
|
|
225
|
+
"warning",
|
|
226
|
+
f"{part.ref}: footprint {footprint_id} is named {actual_id} in "
|
|
227
|
+
"the installed KiCad libraries; using that.",
|
|
228
|
+
)
|
|
229
|
+
)
|
|
230
|
+
part.footprint = footprint_id = actual_id
|
|
231
|
+
footprint = self.libs.footprint(footprint_id)
|
|
232
|
+
except LibraryError as exc:
|
|
233
|
+
raise DesignError(f"{part.ref}: {exc}") from exc
|
|
234
|
+
pads = set(footprint_pad_numbers(footprint))
|
|
235
|
+
missing = sorted(set(pin_nets) - pads, key=_pin_key)
|
|
236
|
+
if missing:
|
|
237
|
+
self.issues.append(
|
|
238
|
+
Issue(
|
|
239
|
+
"error",
|
|
240
|
+
f"{part.ref}: footprint {footprint_id} has no pads {missing} "
|
|
241
|
+
f"for connected symbol pins (pads: {sorted(pads, key=_pin_key)})",
|
|
242
|
+
)
|
|
243
|
+
)
|
|
244
|
+
part = part.model_copy(update={"footprint": footprint_id})
|
|
245
|
+
elif not symbol.is_power:
|
|
246
|
+
self.issues.append(
|
|
247
|
+
Issue("warning", f"{part.ref}: no footprint; it will not appear on the board")
|
|
248
|
+
)
|
|
249
|
+
units = sorted({p.unit for p in symbol.pins if p.unit > 0}) or [1]
|
|
250
|
+
uuids = {unit: _uuid(self.spec.name, part.ref, str(unit)) for unit in units}
|
|
251
|
+
resolved.append(_ResolvedPart(part, symbol, pin_nets, nc_pins, footprint, uuids))
|
|
252
|
+
self._check_nets(resolved)
|
|
253
|
+
return resolved
|
|
254
|
+
|
|
255
|
+
def _check_nets(self, parts: list[_ResolvedPart]) -> None:
|
|
256
|
+
members: dict[str, list[str]] = {}
|
|
257
|
+
for part in parts:
|
|
258
|
+
for pin, net in part.pin_nets.items():
|
|
259
|
+
members.setdefault(net, []).append(f"{part.spec.ref}.{pin}")
|
|
260
|
+
for net, pins in sorted(members.items()):
|
|
261
|
+
if len(pins) == 1 and net not in self.spec.power_nets:
|
|
262
|
+
self.issues.append(Issue("warning", f"net {net} has a single pin ({pins[0]})"))
|
|
263
|
+
for net in self.spec.power_nets:
|
|
264
|
+
if net not in members:
|
|
265
|
+
self.issues.append(Issue("warning", f"power net {net} is not connected to any pin"))
|
|
266
|
+
drivers = {"power_out"}
|
|
267
|
+
for net in sorted(members):
|
|
268
|
+
kinds = set()
|
|
269
|
+
for part in parts:
|
|
270
|
+
for pin in part.symbol.pins:
|
|
271
|
+
if part.pin_nets.get(pin.number) == net:
|
|
272
|
+
kinds.add(pin.electrical)
|
|
273
|
+
if "power_in" in kinds and not (kinds & drivers) and net not in self.spec.power_nets:
|
|
274
|
+
self.issues.append(
|
|
275
|
+
Issue(
|
|
276
|
+
"warning",
|
|
277
|
+
f"net {net} feeds power_in pins but has no power_out driver; "
|
|
278
|
+
"add it to power_nets so it gets a PWR_FLAG",
|
|
279
|
+
)
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
# -------------------------------------------------------------- schematic
|
|
283
|
+
def schematic(self, parts: list[_ResolvedPart]) -> Node:
|
|
284
|
+
"""The root schematic; child sheets (if any) are left in ``self.sheet_files``."""
|
|
285
|
+
from traceforge.design.sheets import build_schematic
|
|
286
|
+
|
|
287
|
+
root, children, stats = build_schematic(self, parts)
|
|
288
|
+
self.sheet_files = children
|
|
289
|
+
self.sheet_stats = stats
|
|
290
|
+
return root
|
|
291
|
+
|
|
292
|
+
def _symbol_instance(
|
|
293
|
+
self,
|
|
294
|
+
part: _ResolvedPart,
|
|
295
|
+
unit: int,
|
|
296
|
+
unit_uuid: str,
|
|
297
|
+
x: float,
|
|
298
|
+
y: float,
|
|
299
|
+
angle: int = 0,
|
|
300
|
+
path: str | None = None,
|
|
301
|
+
texts: dict | None = None,
|
|
302
|
+
) -> Node:
|
|
303
|
+
spec = part.spec
|
|
304
|
+
node: Node = [
|
|
305
|
+
Sym("symbol"),
|
|
306
|
+
[Sym("lib_id"), part.symbol.lib_id],
|
|
307
|
+
[Sym("at"), fmt(x), fmt(y), Sym(str(angle))],
|
|
308
|
+
[Sym("unit"), Sym(str(unit))],
|
|
309
|
+
[
|
|
310
|
+
Sym("in_bom"),
|
|
311
|
+
Sym("no" if part.symbol.is_power or _excluded_from_bom(part) else "yes"),
|
|
312
|
+
],
|
|
313
|
+
[Sym("on_board"), Sym("yes")],
|
|
314
|
+
[Sym("dnp"), Sym("yes" if spec.dnp else "no")],
|
|
315
|
+
[Sym("uuid"), unit_uuid],
|
|
316
|
+
]
|
|
317
|
+
lib_props = {str(p[1]): p for p in find_all(part.symbol.node, "property") if len(p) > 2}
|
|
318
|
+
values = {
|
|
319
|
+
"Reference": spec.ref,
|
|
320
|
+
"Value": spec.value
|
|
321
|
+
or part.symbol.properties.get("Value", part.symbol.lib_id.split(":")[1]),
|
|
322
|
+
"Footprint": spec.footprint or "",
|
|
323
|
+
"Datasheet": part.symbol.properties.get("Datasheet", "~"),
|
|
324
|
+
}
|
|
325
|
+
for key, val in [*values.items(), *spec.fields.items()]:
|
|
326
|
+
template = lib_props.get(key)
|
|
327
|
+
if template is not None:
|
|
328
|
+
at = find(template, "at") or [Sym("at"), Sym("0"), Sym("0"), Sym("0")]
|
|
329
|
+
prop_at = [
|
|
330
|
+
Sym("at"),
|
|
331
|
+
fmt(x + sexpr.num(at[1])),
|
|
332
|
+
fmt(y - sexpr.num(at[2])),
|
|
333
|
+
at[3] if len(at) > 3 else Sym("0"),
|
|
334
|
+
]
|
|
335
|
+
effects = copy.deepcopy(find(template, "effects")) or _effects()
|
|
336
|
+
else:
|
|
337
|
+
prop_at = [Sym("at"), fmt(x), fmt(y), Sym("0")]
|
|
338
|
+
effects = _effects(hide=True)
|
|
339
|
+
if texts and key in texts:
|
|
340
|
+
tx, ty, just = texts[key]
|
|
341
|
+
prop_at = [Sym("at"), fmt(tx), fmt(ty), Sym(str((-angle) % 180))]
|
|
342
|
+
effects = _effects(justify=[just] if just != "center" else None)
|
|
343
|
+
if key in {"Footprint", "Datasheet"} or key in spec.fields:
|
|
344
|
+
if not any(isinstance(e, sexpr.Sym) and e == "hide" for e in effects):
|
|
345
|
+
effects.append(Sym("hide"))
|
|
346
|
+
node.append([Sym("property"), key, str(val), prop_at, effects])
|
|
347
|
+
for pin in part.symbol.pins_for_unit(unit):
|
|
348
|
+
node.append(
|
|
349
|
+
[Sym("pin"), pin.number, [Sym("uuid"), _uuid(unit_uuid, "pin", pin.number)]]
|
|
350
|
+
)
|
|
351
|
+
node.append(
|
|
352
|
+
[
|
|
353
|
+
Sym("instances"),
|
|
354
|
+
[
|
|
355
|
+
Sym("project"),
|
|
356
|
+
self.spec.name,
|
|
357
|
+
[
|
|
358
|
+
Sym("path"),
|
|
359
|
+
path or f"/{self.root_uuid}",
|
|
360
|
+
[Sym("reference"), spec.ref],
|
|
361
|
+
[Sym("unit"), Sym(str(unit))],
|
|
362
|
+
],
|
|
363
|
+
],
|
|
364
|
+
]
|
|
365
|
+
)
|
|
366
|
+
return node
|
|
367
|
+
|
|
368
|
+
# ------------------------------------------------------------------- board
|
|
369
|
+
def board(self, parts: list[_ResolvedPart]) -> tuple[Node, dict]:
|
|
370
|
+
spec_board = self.spec.board
|
|
371
|
+
named = {n for p in parts for n in p.pin_nets.values()}
|
|
372
|
+
# KiCad gives every unconnected pin its own net, "unconnected-(J1-SBU1-PadA8)";
|
|
373
|
+
# the board must use the same names or schematic parity reports each pad.
|
|
374
|
+
unconnected = {
|
|
375
|
+
name
|
|
376
|
+
for p in parts
|
|
377
|
+
if p.footprint is not None
|
|
378
|
+
for name in _unconnected_nets(p, self.kicad_version).values()
|
|
379
|
+
}
|
|
380
|
+
nets = ["", *sorted(named), *sorted(unconnected - named)]
|
|
381
|
+
net_index = {name: i for i, name in enumerate(nets)}
|
|
382
|
+
ox, oy = spec_board.origin
|
|
383
|
+
placements = self._place(parts)
|
|
384
|
+
footprints: list[Node] = []
|
|
385
|
+
for part in parts:
|
|
386
|
+
if part.footprint is None:
|
|
387
|
+
continue
|
|
388
|
+
px, py = placements[part.spec.ref]
|
|
389
|
+
footprints.append(self._board_footprint(part, ox + px, oy + py, net_index))
|
|
390
|
+
sidemod.declutter_reference_texts(footprints)
|
|
391
|
+
width, height = self._board_size(parts, placements)
|
|
392
|
+
footprints_before = len(footprints)
|
|
393
|
+
footprints.extend(self._mechanical(width, height, ox, oy, net_index))
|
|
394
|
+
stack = self.spec.stackup_model()
|
|
395
|
+
root: Node = [
|
|
396
|
+
Sym("kicad_pcb"),
|
|
397
|
+
[Sym("version"), Sym(PCB_VERSION)],
|
|
398
|
+
[Sym("generator"), Sym("traceforge")],
|
|
399
|
+
[
|
|
400
|
+
Sym("general"),
|
|
401
|
+
[Sym("thickness"), fmt(stack.thickness if stack else spec_board.thickness)],
|
|
402
|
+
],
|
|
403
|
+
[Sym("paper"), "A4"],
|
|
404
|
+
[Sym("title_block"), [Sym("title"), self.spec.name]],
|
|
405
|
+
_layers(spec_board.layers),
|
|
406
|
+
[
|
|
407
|
+
Sym("setup"),
|
|
408
|
+
*([stack.to_node()] if stack else []),
|
|
409
|
+
[Sym("pad_to_mask_clearance"), Sym("0")],
|
|
410
|
+
[
|
|
411
|
+
Sym("pcbplotparams"),
|
|
412
|
+
[Sym("layerselection"), Sym("0x00010fc_ffffffff")],
|
|
413
|
+
[Sym("plot_on_all_layers_selection"), Sym("0x0000000_00000000")],
|
|
414
|
+
[Sym("usegerberextensions"), Sym("true")],
|
|
415
|
+
[Sym("usegerberattributes"), Sym("false")],
|
|
416
|
+
[Sym("usegerberadvancedattributes"), Sym("false")],
|
|
417
|
+
[Sym("creategerberjobfile"), Sym("false")],
|
|
418
|
+
[Sym("excludeedgelayer"), Sym("true")],
|
|
419
|
+
[Sym("plotframeref"), Sym("false")],
|
|
420
|
+
[Sym("viasonmask"), Sym("false")],
|
|
421
|
+
[Sym("mode"), Sym("1")],
|
|
422
|
+
[Sym("useauxorigin"), Sym("false")],
|
|
423
|
+
[Sym("outputformat"), Sym("1")],
|
|
424
|
+
[Sym("mirror"), Sym("false")],
|
|
425
|
+
[Sym("drillshape"), Sym("0")],
|
|
426
|
+
[Sym("scaleselection"), Sym("1")],
|
|
427
|
+
[Sym("outputdirectory"), "gerbers/"],
|
|
428
|
+
],
|
|
429
|
+
],
|
|
430
|
+
]
|
|
431
|
+
for name, index in net_index.items():
|
|
432
|
+
root.append([Sym("net"), Sym(str(index)), name])
|
|
433
|
+
root.extend(footprints)
|
|
434
|
+
root.extend(
|
|
435
|
+
constraints.rule_area_nodes(
|
|
436
|
+
self.spec, (ox, oy), lambda name: _uuid(self.spec.name, "rule_area", name)
|
|
437
|
+
)
|
|
438
|
+
)
|
|
439
|
+
if spec_board.outline is not None:
|
|
440
|
+
prims = outlinemod.outline_prims(
|
|
441
|
+
width, height, spec_board.outline, spec_board.corner_radius
|
|
442
|
+
)
|
|
443
|
+
root.extend(outlinemod.edge_nodes(ox, oy, prims, self.spec.name))
|
|
444
|
+
else:
|
|
445
|
+
root.extend(_outline(ox, oy, width, height, spec_board.corner_radius, self.spec.name))
|
|
446
|
+
del footprints_before
|
|
447
|
+
stats = {
|
|
448
|
+
"board_mm": [round(width, 2), round(height, 2)],
|
|
449
|
+
"nets": len(nets) - 1,
|
|
450
|
+
"footprints": len(footprints),
|
|
451
|
+
}
|
|
452
|
+
return root, stats
|
|
453
|
+
|
|
454
|
+
@staticmethod
|
|
455
|
+
def _plain_geometry(width: float, height: float):
|
|
456
|
+
from traceforge.kicad.edgegeom import EdgeGeometry
|
|
457
|
+
|
|
458
|
+
return EdgeGeometry(
|
|
459
|
+
[
|
|
460
|
+
(0, 0, width, 0),
|
|
461
|
+
(width, 0, width, height),
|
|
462
|
+
(width, height, 0, height),
|
|
463
|
+
(0, height, 0, 0),
|
|
464
|
+
]
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
def _edge_geometry(self, width: float, height: float):
|
|
468
|
+
board = self.spec.board
|
|
469
|
+
if board.outline is None:
|
|
470
|
+
return None
|
|
471
|
+
return outlinemod.check_outline(width, height, board.outline, board.corner_radius)
|
|
472
|
+
|
|
473
|
+
def _mech_spots(self, width: float, height: float, geom) -> dict[str, list]:
|
|
474
|
+
board = self.spec.board
|
|
475
|
+
spots: dict[str, list] = {"mounting": [], "tooling": [], "fiducials": []}
|
|
476
|
+
try:
|
|
477
|
+
if board.mounting:
|
|
478
|
+
spots["mounting"] = outlinemod.mounting_positions(
|
|
479
|
+
board.mounting, width, height, geom
|
|
480
|
+
)
|
|
481
|
+
if board.tooling_holes:
|
|
482
|
+
t = board.tooling_holes
|
|
483
|
+
spots["tooling"] = t.positions or outlinemod.corner_positions(
|
|
484
|
+
t.inset, width, height, geom, t.count, t.drill / 2 + 0.5
|
|
485
|
+
)
|
|
486
|
+
if board.fiducials:
|
|
487
|
+
f = board.fiducials
|
|
488
|
+
spots["fiducials"] = f.positions or outlinemod.corner_positions(
|
|
489
|
+
f.inset, width, height, geom, f.count, f.diameter / 2 + f.mask_margin + 0.5
|
|
490
|
+
)
|
|
491
|
+
except ValueError as exc:
|
|
492
|
+
raise DesignError(str(exc)) from exc
|
|
493
|
+
return spots
|
|
494
|
+
|
|
495
|
+
def _mechanical(
|
|
496
|
+
self, width: float, height: float, ox: float, oy: float, net_index: dict[str, int]
|
|
497
|
+
) -> list[Node]:
|
|
498
|
+
"""Board-only footprints: mounting holes, fiducials, tooling holes, castellated pads."""
|
|
499
|
+
board = self.spec.board
|
|
500
|
+
geom = self._edge_geometry(width, height)
|
|
501
|
+
if geom is None:
|
|
502
|
+
from traceforge.kicad.edgegeom import EdgeGeometry
|
|
503
|
+
|
|
504
|
+
geom = EdgeGeometry(
|
|
505
|
+
[
|
|
506
|
+
(0, 0, width, 0),
|
|
507
|
+
(width, 0, width, height),
|
|
508
|
+
(width, height, 0, height),
|
|
509
|
+
(0, height, 0, 0),
|
|
510
|
+
]
|
|
511
|
+
)
|
|
512
|
+
seed = self.spec.name
|
|
513
|
+
out: list[Node] = []
|
|
514
|
+
spots = self._mech_spots(width, height, geom)
|
|
515
|
+
for i, (x, y) in enumerate(spots["mounting"], 1):
|
|
516
|
+
drill = board.mounting.drill # type: ignore[union-attr]
|
|
517
|
+
out.append(
|
|
518
|
+
outlinemod.hole_footprint(f"MH{i}", ox + x, oy + y, drill, seed, "MountingHole")
|
|
519
|
+
)
|
|
520
|
+
for i, (x, y) in enumerate(spots["tooling"], 1):
|
|
521
|
+
drill = board.tooling_holes.drill # type: ignore[union-attr]
|
|
522
|
+
out.append(
|
|
523
|
+
outlinemod.hole_footprint(f"TH{i}", ox + x, oy + y, drill, seed, "ToolingHole")
|
|
524
|
+
)
|
|
525
|
+
n = 0
|
|
526
|
+
for x, y in spots["fiducials"]:
|
|
527
|
+
f = board.fiducials # type: ignore[assignment]
|
|
528
|
+
for bottom in [False, True] if f.side == "both" else [f.side == "bottom"]:
|
|
529
|
+
n += 1
|
|
530
|
+
out.append(
|
|
531
|
+
outlinemod.fiducial_footprint(f"FID{n}", ox + x, oy + y, f, seed, bottom)
|
|
532
|
+
)
|
|
533
|
+
index = 0
|
|
534
|
+
for c in board.castellated:
|
|
535
|
+
for pos, net in zip(outlinemod.castellated_positions(c, width, height), c.nets):
|
|
536
|
+
index += 1
|
|
537
|
+
if net and net not in net_index:
|
|
538
|
+
raise DesignError(f"castellated hole on unknown net {net!r}")
|
|
539
|
+
if geom.distance(*pos) > 0.01:
|
|
540
|
+
raise DesignError(
|
|
541
|
+
f"castellated hole at ({pos[0]:.2f}, {pos[1]:.2f}) is not on the board edge"
|
|
542
|
+
)
|
|
543
|
+
node = [Sym("net"), Sym(str(net_index[net])), net] if net else None
|
|
544
|
+
out.append(
|
|
545
|
+
outlinemod.castellated_footprint(
|
|
546
|
+
f"CH{index}", ox + pos[0], oy + pos[1], c, node, seed
|
|
547
|
+
)
|
|
548
|
+
)
|
|
549
|
+
return out
|
|
550
|
+
|
|
551
|
+
def _footprint_size(self, part: _ResolvedPart) -> tuple[float, float, float, float]:
|
|
552
|
+
assert part.footprint is not None
|
|
553
|
+
extent = footprint_extent(part.footprint)
|
|
554
|
+
if self._sides.get(part.spec.ref) == sidemod.BOTTOM:
|
|
555
|
+
extent = sidemod.mirror_extent(extent)
|
|
556
|
+
return _rotated_extent(extent, part.spec.rotation)
|
|
557
|
+
|
|
558
|
+
def _place(self, parts: list[_ResolvedPart]) -> dict[str, tuple[float, float]]:
|
|
559
|
+
"""Greedy, connectivity-driven placement inside the board.
|
|
560
|
+
|
|
561
|
+
Connectors go to the board edge; every other part goes to the free spot
|
|
562
|
+
closest to the parts it shares nets with (nets with many pins, such as
|
|
563
|
+
ground, count less). Footprints keep a gap between courtyards and stay
|
|
564
|
+
clear of the mounting-hole corners. Positions are relative to the board
|
|
565
|
+
origin. ``at`` in the spec pins a part in place.
|
|
566
|
+
"""
|
|
567
|
+
board = self.spec.board
|
|
568
|
+
margin = board.margin
|
|
569
|
+
gap = 1.6
|
|
570
|
+
placements: dict[str, tuple[float, float]] = {}
|
|
571
|
+
self._sides = sidemod.requested_sides(parts)
|
|
572
|
+
for p in parts: # edge-mount connectors point out of the board: they stay on top
|
|
573
|
+
if (
|
|
574
|
+
self._sides.get(p.spec.ref) == sidemod.BOTTOM
|
|
575
|
+
and edge_marker(p.footprint, p.spec.footprint) is not None
|
|
576
|
+
):
|
|
577
|
+
self._sides[p.spec.ref] = sidemod.TOP
|
|
578
|
+
self.issues.append(
|
|
579
|
+
Issue(
|
|
580
|
+
"warning", f"{p.spec.ref} is an edge-mount connector; kept on the top side"
|
|
581
|
+
)
|
|
582
|
+
)
|
|
583
|
+
movable = [
|
|
584
|
+
p
|
|
585
|
+
for p in parts
|
|
586
|
+
if p.footprint is not None and p.spec.at is None and p.spec.group != "__holes__"
|
|
587
|
+
]
|
|
588
|
+
sizes = {p.spec.ref: self._footprint_size(p) for p in parts if p.footprint is not None}
|
|
589
|
+
area = sum(
|
|
590
|
+
(sizes[p.spec.ref][2] - sizes[p.spec.ref][0] + gap)
|
|
591
|
+
* (sizes[p.spec.ref][3] - sizes[p.spec.ref][1] + gap)
|
|
592
|
+
for p in movable
|
|
593
|
+
)
|
|
594
|
+
hole_keepout = 7.5 if board.mounting_holes else 0.0
|
|
595
|
+
if board.width and board.height:
|
|
596
|
+
width, height = board.width, board.height
|
|
597
|
+
else:
|
|
598
|
+
needed = max(area * 2.4, 100.0)
|
|
599
|
+
width = board.width or max(math.sqrt(needed * 1.4), 20.0)
|
|
600
|
+
height = board.height or max(needed / width, 15.0)
|
|
601
|
+
biggest_w = max([s[2] - s[0] for s in sizes.values()] + [0.0])
|
|
602
|
+
biggest_h = max([s[3] - s[1] for s in sizes.values()] + [0.0])
|
|
603
|
+
width = max(width, biggest_w + 2 * margin + 2 * hole_keepout)
|
|
604
|
+
height = max(height, biggest_h + 2 * margin)
|
|
605
|
+
width, height = math.ceil(width), math.ceil(height)
|
|
606
|
+
|
|
607
|
+
# A roomy board gets wider gaps between parts: more routing channels.
|
|
608
|
+
density = area / max(1.0, width * height)
|
|
609
|
+
gap += min(1.0, max(0.0, 0.45 - density) * 5.0)
|
|
610
|
+
rects = sidemod.SidedRects()
|
|
611
|
+
through = {
|
|
612
|
+
p.spec.ref: sidemod.is_through_hole(p.footprint)
|
|
613
|
+
for p in parts
|
|
614
|
+
if p.footprint is not None
|
|
615
|
+
}
|
|
616
|
+
if hole_keepout:
|
|
617
|
+
k = hole_keepout
|
|
618
|
+
rects += [
|
|
619
|
+
(0, 0, k, k),
|
|
620
|
+
(width - k, 0, width, k),
|
|
621
|
+
(0, height - k, k, height),
|
|
622
|
+
(width - k, height - k, width, height),
|
|
623
|
+
]
|
|
624
|
+
geom = self._edge_geometry(width, height)
|
|
625
|
+
if geom is not None:
|
|
626
|
+
rects += outlinemod.keepout_rects(geom, width, height, margin)
|
|
627
|
+
spots = self._mech_spots(width, height, geom or self._plain_geometry(width, height))
|
|
628
|
+
for kind, size in (
|
|
629
|
+
("mounting", board.mounting.drill if board.mounting else 0.0),
|
|
630
|
+
("tooling", board.tooling_holes.drill if board.tooling_holes else 0.0),
|
|
631
|
+
(
|
|
632
|
+
"fiducials",
|
|
633
|
+
2 * (board.fiducials.diameter + board.fiducials.mask_margin)
|
|
634
|
+
if board.fiducials
|
|
635
|
+
else 0.0,
|
|
636
|
+
),
|
|
637
|
+
):
|
|
638
|
+
k = size / 2 + 1.5
|
|
639
|
+
rects += [(hx - k, hy - k, hx + k, hy + k) for hx, hy in spots[kind]]
|
|
640
|
+
for part in parts:
|
|
641
|
+
if part.footprint is not None and part.spec.at is not None:
|
|
642
|
+
x, y = part.spec.at
|
|
643
|
+
placements[part.spec.ref] = (x, y)
|
|
644
|
+
minx, miny, maxx, maxy = sizes[part.spec.ref]
|
|
645
|
+
rects.add(
|
|
646
|
+
(x + minx, y + miny, x + maxx, y + maxy),
|
|
647
|
+
self._sides[part.spec.ref],
|
|
648
|
+
through[part.spec.ref],
|
|
649
|
+
)
|
|
650
|
+
|
|
651
|
+
nets_of = {p.spec.ref: set(p.pin_nets.values()) for p in parts}
|
|
652
|
+
net_size: dict[str, int] = {}
|
|
653
|
+
for p in parts:
|
|
654
|
+
for net in nets_of[p.spec.ref]:
|
|
655
|
+
net_size[net] = net_size.get(net, 0) + 1
|
|
656
|
+
|
|
657
|
+
def is_connector(part: _ResolvedPart) -> bool:
|
|
658
|
+
return part.spec.ref.rstrip("0123456789") in {"J", "P", "CN", "USB", "X"}
|
|
659
|
+
|
|
660
|
+
# Order: edge-mount connectors first, then breadth-first from the most connected
|
|
661
|
+
# part (other connectors still prefer the board edge, see below).
|
|
662
|
+
def on_edge(part: _ResolvedPart) -> bool:
|
|
663
|
+
return edge_marker(part.footprint, part.spec.footprint) is not None
|
|
664
|
+
|
|
665
|
+
order: list[_ResolvedPart] = sorted(
|
|
666
|
+
[p for p in movable if on_edge(p)], key=lambda p: _ref_sort(p.spec.ref)
|
|
667
|
+
)
|
|
668
|
+
rest = [p for p in movable if not on_edge(p)]
|
|
669
|
+
while rest:
|
|
670
|
+
placed_nets = set().union(*(nets_of[p.spec.ref] for p in order)) if order else set()
|
|
671
|
+
|
|
672
|
+
def score(part: _ResolvedPart, placed_nets: set = placed_nets) -> tuple[float, float]:
|
|
673
|
+
shared = sum(
|
|
674
|
+
1.0 / max(1, net_size[n] - 1) for n in nets_of[part.spec.ref] & placed_nets
|
|
675
|
+
)
|
|
676
|
+
return (-shared, -len(part.pin_nets))
|
|
677
|
+
|
|
678
|
+
rest.sort(key=lambda p: (score(p), _ref_sort(p.spec.ref)))
|
|
679
|
+
order.append(rest.pop(0))
|
|
680
|
+
|
|
681
|
+
# Satellites (decoupling caps, crystals and their load caps, series parts) are
|
|
682
|
+
# placed right after the part they serve, next to the pin they serve.
|
|
683
|
+
satellites = self._satellites(parts, is_connector)
|
|
684
|
+
self._sides = sidemod.derive_decoupling_sides(parts, satellites, self._sides)
|
|
685
|
+
for p in movable:
|
|
686
|
+
sizes[p.spec.ref] = self._footprint_size(p)
|
|
687
|
+
hosted = {sub: host for host, subs in satellites.items() for sub, _ in subs}
|
|
688
|
+
by_ref = {p.spec.ref: p for p in parts}
|
|
689
|
+
sequence: list[_ResolvedPart] = [p for p in order if on_edge(p)]
|
|
690
|
+
|
|
691
|
+
def visit(ref: str) -> None:
|
|
692
|
+
for sub, _ in satellites.get(ref, []):
|
|
693
|
+
if by_ref[sub] in movable and by_ref[sub] not in sequence:
|
|
694
|
+
sequence.append(by_ref[sub])
|
|
695
|
+
visit(sub)
|
|
696
|
+
|
|
697
|
+
hosts = [*sequence, *(p for p in parts if p.footprint and p not in movable)]
|
|
698
|
+
pair_nets = {n for pair in self.diff_pairs() for n in pair["nets"]}
|
|
699
|
+
saved = dict(satellites)
|
|
700
|
+
satellites = { # differential-pair parts claim their spots first
|
|
701
|
+
h: [s for s in subs if nets_of[s[0]] & pair_nets] for h, subs in saved.items()
|
|
702
|
+
}
|
|
703
|
+
for part in hosts:
|
|
704
|
+
visit(part.spec.ref)
|
|
705
|
+
satellites = saved
|
|
706
|
+
for part in hosts:
|
|
707
|
+
visit(part.spec.ref)
|
|
708
|
+
for part in order:
|
|
709
|
+
host = hosted.get(part.spec.ref)
|
|
710
|
+
if part in sequence or (host is not None and by_ref[host] in movable):
|
|
711
|
+
continue # placed right after its host
|
|
712
|
+
sequence.append(part)
|
|
713
|
+
visit(part.spec.ref)
|
|
714
|
+
sequence += [p for p in order if p not in sequence]
|
|
715
|
+
special = {sub: (host, pins) for host, subs in satellites.items() for sub, pins in subs}
|
|
716
|
+
|
|
717
|
+
ground = {n for n in net_size if "GND" in n.upper()}
|
|
718
|
+
if board.ground_plane:
|
|
719
|
+
ground.add(board.ground_plane)
|
|
720
|
+
local_pads = {
|
|
721
|
+
p.spec.ref: sidemod.mirror_pads(_pad_offsets(p.footprint))
|
|
722
|
+
if self._sides[p.spec.ref] == sidemod.BOTTOM
|
|
723
|
+
else _pad_offsets(p.footprint)
|
|
724
|
+
for p in parts
|
|
725
|
+
if p.footprint is not None
|
|
726
|
+
}
|
|
727
|
+
fixed_rotation = {p.spec.ref for p in parts if "rotation" in p.spec.model_fields_set}
|
|
728
|
+
|
|
729
|
+
def pads_at(ref: str) -> list[tuple[str, float, float]]:
|
|
730
|
+
"""Absolute pads of a placed part: (number, x, y)."""
|
|
731
|
+
px, py = placements[ref]
|
|
732
|
+
angle = by_ref[ref].spec.rotation
|
|
733
|
+
out = []
|
|
734
|
+
for number, lx, ly in local_pads.get(ref, []):
|
|
735
|
+
dx, dy = _rotate(lx, ly, angle)
|
|
736
|
+
out.append((number, px + dx, py + dy))
|
|
737
|
+
return out
|
|
738
|
+
|
|
739
|
+
step = 0.5
|
|
740
|
+
edge_parts = {
|
|
741
|
+
p.spec.ref: m
|
|
742
|
+
for p in order
|
|
743
|
+
if (m := edge_marker(p.footprint, p.spec.footprint)) is not None
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
def targets_for(part: _ResolvedPart) -> list[tuple[str, float, list]]:
|
|
747
|
+
"""Where this part's pads want to be: placed pads on the same nets."""
|
|
748
|
+
ref = part.spec.ref
|
|
749
|
+
targets: list[tuple[str, float, list]] = []
|
|
750
|
+
for net in nets_of[ref]:
|
|
751
|
+
weight = 1.0 / max(1, net_size[net] - 1)
|
|
752
|
+
if net in ground:
|
|
753
|
+
weight *= 0.2
|
|
754
|
+
spots = [
|
|
755
|
+
(x, y)
|
|
756
|
+
for other in placements
|
|
757
|
+
if other != ref and net in nets_of.get(other, set())
|
|
758
|
+
for number, x, y in pads_at(other)
|
|
759
|
+
if by_ref[other].pin_nets.get(number) == net
|
|
760
|
+
]
|
|
761
|
+
if spots:
|
|
762
|
+
targets.append((net, weight, spots))
|
|
763
|
+
if ref in special and special[ref][0] in placements:
|
|
764
|
+
host, pins = special[ref]
|
|
765
|
+
host_pads = {n: (x, y) for n, x, y in pads_at(host)}
|
|
766
|
+
for own_net, host_pin in pins:
|
|
767
|
+
if host_pin in host_pads:
|
|
768
|
+
targets.append((own_net, 4.0, [host_pads[host_pin]]))
|
|
769
|
+
return targets
|
|
770
|
+
|
|
771
|
+
def shape(part: _ResolvedPart, angle: float):
|
|
772
|
+
local = footprint_extent(part.footprint)
|
|
773
|
+
if self._sides[part.spec.ref] == sidemod.BOTTOM:
|
|
774
|
+
local = sidemod.mirror_extent(local)
|
|
775
|
+
extent = _rotated_extent(local, angle)
|
|
776
|
+
pads = [
|
|
777
|
+
(part.pin_nets.get(n), *_rotate(lx, ly, angle))
|
|
778
|
+
for n, lx, ly in local_pads.get(part.spec.ref, [])
|
|
779
|
+
if part.pin_nets.get(n)
|
|
780
|
+
]
|
|
781
|
+
return extent, pads
|
|
782
|
+
|
|
783
|
+
def pad_cost(pads, targets, x: float, y: float) -> float:
|
|
784
|
+
cost = 0.0
|
|
785
|
+
for net, wt, spots in targets:
|
|
786
|
+
cost += wt * min(
|
|
787
|
+
abs(x + px - sx) + abs(y + py - sy)
|
|
788
|
+
for pn, px, py in pads
|
|
789
|
+
if pn == net
|
|
790
|
+
for sx, sy in spots
|
|
791
|
+
)
|
|
792
|
+
return cost
|
|
793
|
+
|
|
794
|
+
def free(extent, x: float, y: float) -> bool:
|
|
795
|
+
minx, miny, maxx, maxy = extent
|
|
796
|
+
if x + minx < margin - 1e-9 or y + miny < margin - 1e-9:
|
|
797
|
+
return False
|
|
798
|
+
if x + maxx > width - margin + 1e-9 or y + maxy > height - margin + 1e-9:
|
|
799
|
+
return False
|
|
800
|
+
box = (x + minx - gap / 2, y + miny - gap / 2, x + maxx + gap / 2, y + maxy + gap / 2)
|
|
801
|
+
return not any(
|
|
802
|
+
box[0] < r[2] and r[0] < box[2] and box[1] < r[3] and r[1] < box[3] for r in rects
|
|
803
|
+
)
|
|
804
|
+
|
|
805
|
+
def commit(part: _ResolvedPart, x: float, y: float, angle: float, extent) -> None:
|
|
806
|
+
ref = part.spec.ref
|
|
807
|
+
x, y = _snap(x, 0.05), _snap(y, 0.05)
|
|
808
|
+
if angle % 360 != part.spec.rotation % 360:
|
|
809
|
+
part.spec.rotation = angle % 360
|
|
810
|
+
sizes[ref] = extent
|
|
811
|
+
placements[ref] = (x, y)
|
|
812
|
+
room = fanout_room if len(local_pads.get(ref, [])) > 8 else 0.0
|
|
813
|
+
minx, miny, maxx, maxy = extent
|
|
814
|
+
rects.append((x + minx - room, y + miny - room, x + maxx + room, y + maxy + room))
|
|
815
|
+
|
|
816
|
+
# Many-pin parts keep a routing channel around their pads.
|
|
817
|
+
fanout_room = 0.6
|
|
818
|
+
# A differential pair's two series parts are placed together, side by side.
|
|
819
|
+
twins: dict[str, str] = {}
|
|
820
|
+
for pos, neg in (pair["nets"] for pair in self.diff_pairs()):
|
|
821
|
+
ps = [p for p in movable if pos in nets_of[p.spec.ref] and len(p.pin_nets) <= 4]
|
|
822
|
+
ns = [p for p in movable if neg in nets_of[p.spec.ref] and len(p.pin_nets) <= 4]
|
|
823
|
+
for a in ps:
|
|
824
|
+
for b in ns:
|
|
825
|
+
if a.spec.footprint == b.spec.footprint and a.spec.ref not in twins:
|
|
826
|
+
if b.spec.ref not in twins:
|
|
827
|
+
twins[a.spec.ref], twins[b.spec.ref] = b.spec.ref, a.spec.ref
|
|
828
|
+
|
|
829
|
+
step = 0.5
|
|
830
|
+
edge_parts = {
|
|
831
|
+
p.spec.ref: m
|
|
832
|
+
for p in order
|
|
833
|
+
if (m := edge_marker(p.footprint, p.spec.footprint)) is not None
|
|
834
|
+
}
|
|
835
|
+
corridors: set[tuple[str, str]] = set()
|
|
836
|
+
|
|
837
|
+
def keep_pair_corridors() -> None:
|
|
838
|
+
"""Once both ends of a pair are placed, keep other parts off the straight
|
|
839
|
+
run between them."""
|
|
840
|
+
for pair in self.diff_pairs():
|
|
841
|
+
key = tuple(pair["nets"])
|
|
842
|
+
refs = [r for r in nets_of if set(pair["nets"]) & nets_of[r]]
|
|
843
|
+
if key in corridors or any(r not in placements for r in refs):
|
|
844
|
+
continue
|
|
845
|
+
corridors.add(key)
|
|
846
|
+
ends: list[list[tuple[float, float]]] = []
|
|
847
|
+
for r in refs:
|
|
848
|
+
pts = [(x, y) for n, x, y in pads_at(r) if by_ref[r].pin_nets.get(n) in key]
|
|
849
|
+
cx = sum(x for x, _ in pts) / len(pts)
|
|
850
|
+
cy = sum(y for _, y in pts) / len(pts)
|
|
851
|
+
for end in ends:
|
|
852
|
+
if math.dist(end[0], (cx, cy)) < 5.0:
|
|
853
|
+
end.append((cx, cy))
|
|
854
|
+
break
|
|
855
|
+
else:
|
|
856
|
+
ends.append([(cx, cy)])
|
|
857
|
+
if len(ends) != 2:
|
|
858
|
+
continue
|
|
859
|
+
(ax, ay), (bx, by) = (
|
|
860
|
+
(sum(x for x, _ in e) / len(e), sum(y for _, y in e) / len(e)) for e in ends
|
|
861
|
+
)
|
|
862
|
+
if min(abs(ax - bx), abs(ay - by)) > 3.0:
|
|
863
|
+
continue # diagonal: a bounding box would block too much
|
|
864
|
+
half = pair["width"] + pair["gap"] / 2 + 0.3
|
|
865
|
+
rects.append(
|
|
866
|
+
(
|
|
867
|
+
min(ax, bx) - half,
|
|
868
|
+
min(ay, by) - half,
|
|
869
|
+
max(ax, bx) + half,
|
|
870
|
+
max(ay, by) + half,
|
|
871
|
+
),
|
|
872
|
+
both=True,
|
|
873
|
+
)
|
|
874
|
+
|
|
875
|
+
for part in sequence:
|
|
876
|
+
ref = part.spec.ref
|
|
877
|
+
keep_pair_corridors()
|
|
878
|
+
if ref in placements:
|
|
879
|
+
continue
|
|
880
|
+
rects.use(self._sides[ref], through[ref])
|
|
881
|
+
if ref in edge_parts:
|
|
882
|
+
spot = self._place_on_edge(part, edge_parts[ref], width, height, margin, gap, rects)
|
|
883
|
+
if spot is not None:
|
|
884
|
+
x, y, extent = spot
|
|
885
|
+
placements[ref] = (x, y)
|
|
886
|
+
sizes[ref] = extent
|
|
887
|
+
rects.append((x + extent[0], y + extent[1], x + extent[2], y + extent[3]))
|
|
888
|
+
continue
|
|
889
|
+
self.issues.append(
|
|
890
|
+
Issue(
|
|
891
|
+
"warning",
|
|
892
|
+
f"{ref} is an edge-mount connector but no free spot on the "
|
|
893
|
+
"board edge fits it; placed inside the board. Enlarge the board or "
|
|
894
|
+
"place it with 'at'.",
|
|
895
|
+
)
|
|
896
|
+
)
|
|
897
|
+
twin = by_ref.get(twins.get(ref, ""))
|
|
898
|
+
if twin is not None and (
|
|
899
|
+
twin.spec.ref in placements
|
|
900
|
+
or twin not in movable
|
|
901
|
+
or self._sides[twin.spec.ref] != self._sides[ref]
|
|
902
|
+
):
|
|
903
|
+
twin = None
|
|
904
|
+
targets = targets_for(part)
|
|
905
|
+
twin_targets = targets_for(twin) if twin is not None else []
|
|
906
|
+
angles = [part.spec.rotation]
|
|
907
|
+
if ref not in fixed_rotation and len(local_pads.get(ref, [])) <= 4:
|
|
908
|
+
if not is_connector(part):
|
|
909
|
+
angles = [part.spec.rotation + a for a in (0.0, 90.0, 180.0, 270.0)]
|
|
910
|
+
if targets or twin_targets:
|
|
911
|
+
spots = [s for _, _, ss in targets + twin_targets for s in ss]
|
|
912
|
+
reach = 12.0 if ref in special else 25.0
|
|
913
|
+
window = (
|
|
914
|
+
min(x for x, _ in spots) - reach,
|
|
915
|
+
min(y for _, y in spots) - reach,
|
|
916
|
+
max(x for x, _ in spots) + reach,
|
|
917
|
+
max(y for _, y in spots) + reach,
|
|
918
|
+
)
|
|
919
|
+
else:
|
|
920
|
+
window = (-1e9, -1e9, 1e9, 1e9)
|
|
921
|
+
best = None
|
|
922
|
+
for _pass in range(2):
|
|
923
|
+
for angle in angles:
|
|
924
|
+
extent, pads = shape(part, angle)
|
|
925
|
+
minx, miny, maxx, maxy = extent
|
|
926
|
+
offsets = [(0.0, 0.0)]
|
|
927
|
+
if twin is not None:
|
|
928
|
+
# Beside each other across the pad axis, pads in line.
|
|
929
|
+
tw, th = maxx - minx + gap / 2 + 0.05, maxy - miny + gap / 2 + 0.05
|
|
930
|
+
xs_ = [px for _, px, _ in pads]
|
|
931
|
+
ys_ = [py for _, _, py in pads]
|
|
932
|
+
if max(xs_) - min(xs_) >= max(ys_) - min(ys_):
|
|
933
|
+
offsets = [(0.0, th), (0.0, -th)]
|
|
934
|
+
else:
|
|
935
|
+
offsets = [(tw, 0.0), (-tw, 0.0)]
|
|
936
|
+
twin_extent, twin_pads = shape(twin, angle)
|
|
937
|
+
x = max(margin - minx, _snap(window[0], step))
|
|
938
|
+
while x + maxx <= min(width - margin, window[2] + maxx) + 1e-9:
|
|
939
|
+
y = max(margin - miny, _snap(window[1], step))
|
|
940
|
+
while y + maxy <= min(height - margin, window[3] + maxy) + 1e-9:
|
|
941
|
+
if not free(extent, x, y):
|
|
942
|
+
y += step
|
|
943
|
+
continue
|
|
944
|
+
if targets:
|
|
945
|
+
cost = pad_cost(pads, targets, x, y)
|
|
946
|
+
else:
|
|
947
|
+
cost = 0.05 * (abs(x - width / 2) + abs(y - height / 2))
|
|
948
|
+
if is_connector(part):
|
|
949
|
+
edge = min(
|
|
950
|
+
x + minx - margin,
|
|
951
|
+
width - margin - (x + maxx),
|
|
952
|
+
y + miny - margin,
|
|
953
|
+
height - margin - (y + maxy),
|
|
954
|
+
)
|
|
955
|
+
cost += 20.0 * edge
|
|
956
|
+
cost += 0.01 * (angle - part.spec.rotation) / 90.0
|
|
957
|
+
for ox, oy in offsets:
|
|
958
|
+
total = cost
|
|
959
|
+
if twin is not None:
|
|
960
|
+
if not free(twin_extent, x + ox, y + oy):
|
|
961
|
+
continue
|
|
962
|
+
total += pad_cost(twin_pads, twin_targets, x + ox, y + oy)
|
|
963
|
+
if best is None or total < best[0] - 1e-9:
|
|
964
|
+
best = (total, x, y, angle, extent, ox, oy)
|
|
965
|
+
y += step
|
|
966
|
+
x += step
|
|
967
|
+
if best is not None:
|
|
968
|
+
break
|
|
969
|
+
window = (-1e9, -1e9, 1e9, 1e9)
|
|
970
|
+
if best is None and twin is not None:
|
|
971
|
+
twin = None # no room side by side: place them one at a time
|
|
972
|
+
sequence.append(by_ref[twins[ref]])
|
|
973
|
+
del twins[twins[ref]], twins[ref]
|
|
974
|
+
sequence.append(part)
|
|
975
|
+
continue
|
|
976
|
+
if best is None:
|
|
977
|
+
minx, miny, maxx, maxy = sizes[ref]
|
|
978
|
+
self.issues.append(
|
|
979
|
+
Issue(
|
|
980
|
+
"warning",
|
|
981
|
+
f"no room for {ref} ({maxx - minx:.1f} x {maxy - miny:.1f} mm); "
|
|
982
|
+
"placed outside the board. Enlarge the board or place it with 'at'.",
|
|
983
|
+
)
|
|
984
|
+
)
|
|
985
|
+
best = (0.0, width + 5 - minx, margin - miny, part.spec.rotation, sizes[ref], 0, 0)
|
|
986
|
+
_, bx, by, angle, extent, ox, oy = best
|
|
987
|
+
commit(part, bx, by, angle, extent)
|
|
988
|
+
if twin is not None:
|
|
989
|
+
commit(twin, bx + ox, by + oy, angle, shape(twin, angle)[0])
|
|
990
|
+
|
|
991
|
+
self._auto_size = (float(width), float(height))
|
|
992
|
+
holes = [p for p in parts if p.spec.group == "__holes__"]
|
|
993
|
+
inset = 3.5
|
|
994
|
+
corners = [
|
|
995
|
+
(inset, inset),
|
|
996
|
+
(width - inset, inset),
|
|
997
|
+
(inset, height - inset),
|
|
998
|
+
(width - inset, height - inset),
|
|
999
|
+
]
|
|
1000
|
+
for part, corner in zip(holes, corners):
|
|
1001
|
+
placements[part.spec.ref] = corner
|
|
1002
|
+
return placements
|
|
1003
|
+
|
|
1004
|
+
def _satellites(self, parts: list[_ResolvedPart], is_connector) -> dict[str, list]:
|
|
1005
|
+
"""Small parts that belong next to one pin of another part.
|
|
1006
|
+
|
|
1007
|
+
Returns ``{host: [(part, [(net, host pin), ...]), ...]}``: decoupling caps (a
|
|
1008
|
+
cap from an IC supply-pin net to ground; small caps go to the IC with the most
|
|
1009
|
+
pins, bulk caps to the smallest, e.g. the regulator, one cap per supply pin
|
|
1010
|
+
first), crystals on an IC's XTAL/OSC pins and their load caps, and two-pin parts
|
|
1011
|
+
on a net shared only with the host (series and pull resistors, LEDs, UCAP).
|
|
1012
|
+
"""
|
|
1013
|
+
placed = [p for p in parts if p.footprint is not None and p.spec.group != "__holes__"]
|
|
1014
|
+
pad_count = {p.spec.ref: len(footprint_pad_numbers(p.footprint)) for p in placed}
|
|
1015
|
+
ground = {n for p in placed for n in p.pin_nets.values() if "GND" in n.upper()}
|
|
1016
|
+
if self.spec.board.ground_plane:
|
|
1017
|
+
ground.add(self.spec.board.ground_plane)
|
|
1018
|
+
members: dict[str, set[str]] = {}
|
|
1019
|
+
for p in placed:
|
|
1020
|
+
for net in p.pin_nets.values():
|
|
1021
|
+
members.setdefault(net, set()).add(p.spec.ref)
|
|
1022
|
+
|
|
1023
|
+
def prefix(p: _ResolvedPart) -> str:
|
|
1024
|
+
return p.spec.ref.rstrip("0123456789").upper()
|
|
1025
|
+
|
|
1026
|
+
ics = [
|
|
1027
|
+
p
|
|
1028
|
+
for p in placed
|
|
1029
|
+
if not is_connector(p)
|
|
1030
|
+
and (prefix(p) in {"U", "IC"} or pad_count[p.spec.ref] > 4)
|
|
1031
|
+
and edge_marker(p.footprint, p.spec.footprint) is None
|
|
1032
|
+
]
|
|
1033
|
+
ics.sort(key=lambda p: (-len(p.pin_nets), _ref_sort(p.spec.ref)))
|
|
1034
|
+
small = [
|
|
1035
|
+
p for p in placed if p not in ics and not is_connector(p) and pad_count[p.spec.ref] <= 4
|
|
1036
|
+
]
|
|
1037
|
+
crystals = [
|
|
1038
|
+
p
|
|
1039
|
+
for p in small
|
|
1040
|
+
if prefix(p) == "Y" or any(k in p.spec.symbol.lower() for k in ("crystal", "resonat"))
|
|
1041
|
+
]
|
|
1042
|
+
result: dict[str, list] = {}
|
|
1043
|
+
host_of: dict[str, str] = {}
|
|
1044
|
+
|
|
1045
|
+
def add(host: str, sub: str, links: list[tuple[str, str]]) -> None:
|
|
1046
|
+
result.setdefault(host, []).append((sub, links))
|
|
1047
|
+
host_of[sub] = host
|
|
1048
|
+
|
|
1049
|
+
def cap_to_ground(p: _ResolvedPart) -> str | None:
|
|
1050
|
+
nets = set(p.pin_nets.values())
|
|
1051
|
+
if prefix(p) != "C" or len(nets) != 2 or len(nets & ground) != 1:
|
|
1052
|
+
return None
|
|
1053
|
+
return next(iter(nets - ground))
|
|
1054
|
+
|
|
1055
|
+
caps = [p for p in small if cap_to_ground(p)]
|
|
1056
|
+
caps.sort(key=lambda p: (_farads(p.spec.value), _ref_sort(p.spec.ref)))
|
|
1057
|
+
taken: dict[tuple[str, str], int] = {}
|
|
1058
|
+
for cap in caps:
|
|
1059
|
+
net = cap_to_ground(cap)
|
|
1060
|
+
bulk = _farads(cap.spec.value) >= 1e-6
|
|
1061
|
+
options = [
|
|
1062
|
+
(ic, pin)
|
|
1063
|
+
for ic in ics
|
|
1064
|
+
for pin in ic.symbol.pins
|
|
1065
|
+
if ic.pin_nets.get(pin.number) == net and _is_supply(pin)
|
|
1066
|
+
]
|
|
1067
|
+
if not options:
|
|
1068
|
+
continue
|
|
1069
|
+
ic, pin = min(
|
|
1070
|
+
options,
|
|
1071
|
+
key=lambda o: (
|
|
1072
|
+
taken.get((o[0].spec.ref, o[1].number), 0),
|
|
1073
|
+
len(o[0].pin_nets) if bulk else -len(o[0].pin_nets),
|
|
1074
|
+
o[1].electrical not in ("power_in", "power_out"),
|
|
1075
|
+
_pin_key(o[1].number),
|
|
1076
|
+
),
|
|
1077
|
+
)
|
|
1078
|
+
taken[(ic.spec.ref, pin.number)] = taken.get((ic.spec.ref, pin.number), 0) + 1
|
|
1079
|
+
add(ic.spec.ref, cap.spec.ref, [(net, pin.number)])
|
|
1080
|
+
for xtal in crystals:
|
|
1081
|
+
nets = set(xtal.pin_nets.values()) - ground
|
|
1082
|
+
for ic in ics:
|
|
1083
|
+
links = [
|
|
1084
|
+
(ic.pin_nets[pin.number], pin.number)
|
|
1085
|
+
for pin in ic.symbol.pins
|
|
1086
|
+
if ic.pin_nets.get(pin.number) in nets and _XTAL_NAME.search(pin.name)
|
|
1087
|
+
]
|
|
1088
|
+
if links:
|
|
1089
|
+
add(ic.spec.ref, xtal.spec.ref, links)
|
|
1090
|
+
for cap in caps:
|
|
1091
|
+
net = cap_to_ground(cap)
|
|
1092
|
+
if cap.spec.ref not in host_of and net in nets:
|
|
1093
|
+
pins = [n for n, v in xtal.pin_nets.items() if v == net]
|
|
1094
|
+
add(xtal.spec.ref, cap.spec.ref, [(net, pins[0])])
|
|
1095
|
+
break
|
|
1096
|
+
# Parts on a net shared with one other part only (series resistors, LEDs, UCAP).
|
|
1097
|
+
queue = [p.spec.ref for p in ics] + [p.spec.ref for p in placed if is_connector(p)]
|
|
1098
|
+
queue += [ref for ref in host_of if ref not in queue]
|
|
1099
|
+
by_ref = {p.spec.ref: p for p in placed}
|
|
1100
|
+
small_refs = {p.spec.ref for p in small}
|
|
1101
|
+
i = 0
|
|
1102
|
+
while i < len(queue):
|
|
1103
|
+
host = by_ref[queue[i]]
|
|
1104
|
+
i += 1
|
|
1105
|
+
for pin, net in sorted(host.pin_nets.items()):
|
|
1106
|
+
others = members.get(net, set()) - {host.spec.ref}
|
|
1107
|
+
if net in ground or len(others) != 1:
|
|
1108
|
+
continue
|
|
1109
|
+
sub = next(iter(others))
|
|
1110
|
+
if sub in small_refs and sub not in host_of and sub not in queue[:i]:
|
|
1111
|
+
add(host.spec.ref, sub, [(net, pin)])
|
|
1112
|
+
queue.append(sub)
|
|
1113
|
+
# Per host: pair parts first, then crystals, decoupling, the rest.
|
|
1114
|
+
pair_nets = {n for pair in self.diff_pairs() for n in pair["nets"]}
|
|
1115
|
+
rank = {p.spec.ref: 1 for p in crystals}
|
|
1116
|
+
rank.update({p.spec.ref: 2 for p in caps})
|
|
1117
|
+
for subs in result.values():
|
|
1118
|
+
subs.sort(
|
|
1119
|
+
key=lambda s: (
|
|
1120
|
+
0 if set(by_ref[s[0]].pin_nets.values()) & pair_nets else rank.get(s[0], 3)
|
|
1121
|
+
)
|
|
1122
|
+
)
|
|
1123
|
+
return result
|
|
1124
|
+
|
|
1125
|
+
def _place_on_edge(
|
|
1126
|
+
self,
|
|
1127
|
+
part: _ResolvedPart,
|
|
1128
|
+
marker: tuple[tuple[float, float], float],
|
|
1129
|
+
width: float,
|
|
1130
|
+
height: float,
|
|
1131
|
+
margin: float,
|
|
1132
|
+
gap: float,
|
|
1133
|
+
rects: list[tuple[float, float, float, float]],
|
|
1134
|
+
) -> tuple[float, float, tuple[float, float, float, float]] | None:
|
|
1135
|
+
"""Seat an edge-mount connector with its opening on the board edge.
|
|
1136
|
+
|
|
1137
|
+
Tries each rotation (only the given one if the spec sets ``rotation``),
|
|
1138
|
+
puts the footprint's edge line exactly on the matching board edge and
|
|
1139
|
+
slides it along that edge to the free spot nearest the edge's middle.
|
|
1140
|
+
Sets ``part.spec.rotation`` to the rotation used.
|
|
1141
|
+
"""
|
|
1142
|
+
assert part.footprint is not None
|
|
1143
|
+
(ux, uy), offset = marker
|
|
1144
|
+
local = footprint_extent(part.footprint)
|
|
1145
|
+
if "rotation" in part.spec.model_fields_set:
|
|
1146
|
+
angles = [part.spec.rotation % 360]
|
|
1147
|
+
else:
|
|
1148
|
+
angles = [0.0, 90.0, 180.0, 270.0]
|
|
1149
|
+
best: tuple[float, float, float, float, tuple] | None = None # cost, x, y, angle, ext
|
|
1150
|
+
step = 0.25
|
|
1151
|
+
for angle in angles:
|
|
1152
|
+
dx, dy = (round(v) for v in _rotate(ux, uy, angle))
|
|
1153
|
+
px, py = _rotate(ux * offset, uy * offset, angle)
|
|
1154
|
+
extent = _rotated_extent(local, angle)
|
|
1155
|
+
minx, miny, maxx, maxy = extent
|
|
1156
|
+
if dx: # opening faces left or right: x is fixed, slide along y
|
|
1157
|
+
x = (width - px) if dx > 0 else -px
|
|
1158
|
+
positions = []
|
|
1159
|
+
y = margin - miny
|
|
1160
|
+
while y + maxy <= height - margin + 1e-9:
|
|
1161
|
+
positions.append((x, y, abs(y - height / 2)))
|
|
1162
|
+
y += step
|
|
1163
|
+
else: # faces up or down: y is fixed, slide along x
|
|
1164
|
+
y = (height - py) if dy > 0 else -py
|
|
1165
|
+
positions = []
|
|
1166
|
+
x = margin - minx
|
|
1167
|
+
while x + maxx <= width - margin + 1e-9:
|
|
1168
|
+
positions.append((x, y, abs(x - width / 2)))
|
|
1169
|
+
x += step
|
|
1170
|
+
for x, y, cost in positions:
|
|
1171
|
+
box = (
|
|
1172
|
+
x + minx - gap / 2,
|
|
1173
|
+
y + miny - gap / 2,
|
|
1174
|
+
x + maxx + gap / 2,
|
|
1175
|
+
y + maxy + gap / 2,
|
|
1176
|
+
)
|
|
1177
|
+
if any(
|
|
1178
|
+
box[0] < r[2] and r[0] < box[2] and box[1] < r[3] and r[1] < box[3]
|
|
1179
|
+
for r in rects
|
|
1180
|
+
):
|
|
1181
|
+
continue
|
|
1182
|
+
# Prefer the left edge, then bottom, top, right: power and USB usually
|
|
1183
|
+
# come in from the side, and ties should be deterministic.
|
|
1184
|
+
side = {(-1, 0): 0.0, (0, 1): 0.1, (0, -1): 0.2, (1, 0): 0.3}[(dx, dy)]
|
|
1185
|
+
total = cost + side
|
|
1186
|
+
if best is None or total < best[0]:
|
|
1187
|
+
best = (total, x, y, angle, extent)
|
|
1188
|
+
if best is None:
|
|
1189
|
+
return None
|
|
1190
|
+
_, x, y, angle, extent = best
|
|
1191
|
+
part.spec.rotation = angle
|
|
1192
|
+
return _snap(x, 0.01), _snap(y, 0.01), extent
|
|
1193
|
+
|
|
1194
|
+
def _board_size(self, parts: list[_ResolvedPart], placements: dict) -> tuple[float, float]:
|
|
1195
|
+
return getattr(
|
|
1196
|
+
self, "_auto_size", (self.spec.board.width or 50.0, self.spec.board.height or 50.0)
|
|
1197
|
+
)
|
|
1198
|
+
|
|
1199
|
+
def _board_footprint(
|
|
1200
|
+
self, part: _ResolvedPart, x: float, y: float, net_index: dict[str, int]
|
|
1201
|
+
) -> Node:
|
|
1202
|
+
assert part.footprint is not None
|
|
1203
|
+
source = copy.deepcopy(part.footprint)
|
|
1204
|
+
spec = part.spec
|
|
1205
|
+
angle = spec.rotation % 360
|
|
1206
|
+
bottom = self._sides.get(spec.ref) == sidemod.BOTTOM
|
|
1207
|
+
if bottom:
|
|
1208
|
+
sidemod.flip_footprint(source)
|
|
1209
|
+
node: Node = [Sym("footprint"), spec.footprint]
|
|
1210
|
+
node.append([Sym("layer"), "B.Cu" if bottom else "F.Cu"])
|
|
1211
|
+
node.append([Sym("tstamp"), _uuid(self.spec.name, spec.ref, "footprint")])
|
|
1212
|
+
at: Node = [Sym("at"), fmt(x), fmt(y)]
|
|
1213
|
+
if angle:
|
|
1214
|
+
at.append(fmt(angle))
|
|
1215
|
+
node.append(at)
|
|
1216
|
+
first_uuid = next(iter(part.uuids.values()))
|
|
1217
|
+
skip = {
|
|
1218
|
+
"version",
|
|
1219
|
+
"generator",
|
|
1220
|
+
"generator_version",
|
|
1221
|
+
"tedit",
|
|
1222
|
+
"layer",
|
|
1223
|
+
"at",
|
|
1224
|
+
"tstamp",
|
|
1225
|
+
"uuid",
|
|
1226
|
+
}
|
|
1227
|
+
inserted_meta = False
|
|
1228
|
+
for item in source[2:]:
|
|
1229
|
+
if isinstance(item, list) and item and str(item[0]) in skip:
|
|
1230
|
+
continue
|
|
1231
|
+
if (
|
|
1232
|
+
not inserted_meta
|
|
1233
|
+
and isinstance(item, list)
|
|
1234
|
+
and item
|
|
1235
|
+
and item[0] in {"attr", "fp_text", "property", "pad", "fp_line"}
|
|
1236
|
+
):
|
|
1237
|
+
node.append([Sym("property"), "Sheetfile", f"{self.spec.name}.kicad_sch"])
|
|
1238
|
+
node.append([Sym("property"), "Sheetname", ""])
|
|
1239
|
+
datasheet = part.symbol.properties.get("Datasheet", "")
|
|
1240
|
+
if datasheet and datasheet != "~":
|
|
1241
|
+
node.append([Sym("property"), "Datasheet", datasheet])
|
|
1242
|
+
node.append([Sym("path"), f"/{first_uuid}"])
|
|
1243
|
+
inserted_meta = True
|
|
1244
|
+
if isinstance(item, list) and item:
|
|
1245
|
+
head = item[0]
|
|
1246
|
+
if head == "fp_text" and len(item) > 2:
|
|
1247
|
+
if item[1] == "reference":
|
|
1248
|
+
item[2] = spec.ref
|
|
1249
|
+
elif item[1] == "value":
|
|
1250
|
+
item[2] = spec.value or item[2]
|
|
1251
|
+
_rotate_text(item, angle)
|
|
1252
|
+
elif head == "property" and len(item) > 2 and item[1] == "Datasheet":
|
|
1253
|
+
continue # the symbol's Datasheet was added above
|
|
1254
|
+
elif head == "property" and len(item) > 2:
|
|
1255
|
+
if item[1] == "Reference":
|
|
1256
|
+
item[2] = spec.ref
|
|
1257
|
+
elif item[1] == "Value":
|
|
1258
|
+
item[2] = spec.value or item[2]
|
|
1259
|
+
_rotate_text(item, angle)
|
|
1260
|
+
elif head == "pad":
|
|
1261
|
+
net = part.pin_nets.get(str(item[1])) or _unconnected_nets(
|
|
1262
|
+
part, self.kicad_version
|
|
1263
|
+
).get(str(item[1]))
|
|
1264
|
+
for existing in find_all(item, "net"):
|
|
1265
|
+
item.remove(existing)
|
|
1266
|
+
if net:
|
|
1267
|
+
item.append([Sym("net"), Sym(str(net_index[net])), net])
|
|
1268
|
+
pad_at = find(item, "at")
|
|
1269
|
+
if pad_at is not None and angle:
|
|
1270
|
+
base = sexpr.num(pad_at[3]) if len(pad_at) > 3 else 0.0
|
|
1271
|
+
del pad_at[3:]
|
|
1272
|
+
pad_at.append(fmt((base + angle) % 360))
|
|
1273
|
+
node.append(item)
|
|
1274
|
+
else:
|
|
1275
|
+
node.append(item)
|
|
1276
|
+
if not inserted_meta:
|
|
1277
|
+
node.append([Sym("path"), f"/{first_uuid}"])
|
|
1278
|
+
if spec.dnp and self.kicad_version >= 8:
|
|
1279
|
+
attr = find(node, "attr")
|
|
1280
|
+
if attr is None:
|
|
1281
|
+
attr = [Sym("attr")]
|
|
1282
|
+
node.append(attr)
|
|
1283
|
+
if "dnp" not in [str(a) for a in attr[1:]]:
|
|
1284
|
+
attr.append(Sym("dnp"))
|
|
1285
|
+
for key, value in spec.fields.items():
|
|
1286
|
+
node.append([Sym("property"), key, value])
|
|
1287
|
+
# Library footprints carry fixed UUIDs on pads and graphics; every placed
|
|
1288
|
+
# copy needs its own, or two R_0603 parts would share pad identities.
|
|
1289
|
+
counter = [0]
|
|
1290
|
+
|
|
1291
|
+
def renumber(item: Node) -> None:
|
|
1292
|
+
for child in item:
|
|
1293
|
+
if not isinstance(child, list) or not child:
|
|
1294
|
+
continue
|
|
1295
|
+
if str(child[0]) in {"tstamp", "uuid"} and len(child) > 1:
|
|
1296
|
+
counter[0] += 1
|
|
1297
|
+
child[1] = _uuid(self.spec.name, spec.ref, "item", str(counter[0]))
|
|
1298
|
+
else:
|
|
1299
|
+
renumber(child)
|
|
1300
|
+
|
|
1301
|
+
for child in node[2:]:
|
|
1302
|
+
if isinstance(child, list) and child and str(child[0]) not in {"tstamp", "uuid"}:
|
|
1303
|
+
renumber(child)
|
|
1304
|
+
return node
|
|
1305
|
+
|
|
1306
|
+
# --------------------------------------------------------------- project
|
|
1307
|
+
def project_file(self) -> dict:
|
|
1308
|
+
fab = self.fab
|
|
1309
|
+
classes = [
|
|
1310
|
+
{
|
|
1311
|
+
"name": "Default",
|
|
1312
|
+
"clearance": self.default_clearance(),
|
|
1313
|
+
"track_width": self.default_track(),
|
|
1314
|
+
"via_diameter": fab.default_via_diameter,
|
|
1315
|
+
"via_drill": fab.default_via_drill,
|
|
1316
|
+
"diff_pair_gap": 0.25,
|
|
1317
|
+
"diff_pair_via_gap": 0.25,
|
|
1318
|
+
"diff_pair_width": 0.2,
|
|
1319
|
+
"line_style": 0,
|
|
1320
|
+
"microvia_diameter": 0.3,
|
|
1321
|
+
"microvia_drill": 0.1,
|
|
1322
|
+
"pcb_color": "rgba(0, 0, 0, 0.000)",
|
|
1323
|
+
"schematic_color": "rgba(0, 0, 0, 0.000)",
|
|
1324
|
+
"wire_width": 6,
|
|
1325
|
+
"bus_width": 12,
|
|
1326
|
+
}
|
|
1327
|
+
]
|
|
1328
|
+
assignments: dict[str, str] = {}
|
|
1329
|
+
pairs = self.diff_pairs()
|
|
1330
|
+
for pair in pairs:
|
|
1331
|
+
p, n = pair["nets"]
|
|
1332
|
+
if p in assignments or n in assignments:
|
|
1333
|
+
continue
|
|
1334
|
+
name = f"DiffPair_{p}_{n}"
|
|
1335
|
+
classes.append(
|
|
1336
|
+
{
|
|
1337
|
+
**classes[0],
|
|
1338
|
+
"name": name,
|
|
1339
|
+
"diff_pair_width": pair["width"],
|
|
1340
|
+
"diff_pair_gap": pair["gap"],
|
|
1341
|
+
}
|
|
1342
|
+
)
|
|
1343
|
+
assignments[p] = assignments[n] = name
|
|
1344
|
+
for name, settings in self.spec.net_classes.items():
|
|
1345
|
+
classes.append(
|
|
1346
|
+
{
|
|
1347
|
+
**classes[0],
|
|
1348
|
+
"name": name,
|
|
1349
|
+
"clearance": float(settings.get("clearance", self.default_clearance())),
|
|
1350
|
+
"track_width": float(settings.get("track_width", self.default_track())),
|
|
1351
|
+
"via_diameter": float(settings.get("via_diameter", fab.default_via_diameter)),
|
|
1352
|
+
"via_drill": float(settings.get("via_drill", fab.default_via_drill)),
|
|
1353
|
+
}
|
|
1354
|
+
)
|
|
1355
|
+
for net in settings.get("nets", []):
|
|
1356
|
+
assignments[str(net)] = name
|
|
1357
|
+
return {
|
|
1358
|
+
"board": {
|
|
1359
|
+
"design_settings": {
|
|
1360
|
+
"defaults": {
|
|
1361
|
+
"board_outline_line_width": 0.1,
|
|
1362
|
+
"copper_line_width": 0.2,
|
|
1363
|
+
"silk_line_width": 0.15,
|
|
1364
|
+
"silk_text_size_h": 1.0,
|
|
1365
|
+
"silk_text_size_v": 1.0,
|
|
1366
|
+
"silk_text_thickness": 0.15,
|
|
1367
|
+
},
|
|
1368
|
+
"rules": {
|
|
1369
|
+
"min_clearance": fab.min_clearance,
|
|
1370
|
+
"min_track_width": fab.min_track,
|
|
1371
|
+
"min_via_diameter": fab.min_via_diameter,
|
|
1372
|
+
"min_through_hole_diameter": fab.min_drill,
|
|
1373
|
+
"min_copper_edge_clearance": fab.min_copper_edge,
|
|
1374
|
+
"min_hole_to_hole": 0.25,
|
|
1375
|
+
"min_via_annular_width": fab.min_annular_ring,
|
|
1376
|
+
"min_silk_clearance": 0.0,
|
|
1377
|
+
"min_text_height": fab.min_silk_text_height,
|
|
1378
|
+
"min_text_thickness": 0.08,
|
|
1379
|
+
},
|
|
1380
|
+
"track_widths": [0.0, fab.default_track, 0.4, 0.5, 0.8, 1.0],
|
|
1381
|
+
"via_dimensions": [
|
|
1382
|
+
{"diameter": 0.0, "drill": 0.0},
|
|
1383
|
+
{"diameter": fab.default_via_diameter, "drill": fab.default_via_drill},
|
|
1384
|
+
],
|
|
1385
|
+
},
|
|
1386
|
+
},
|
|
1387
|
+
"meta": {"filename": f"{self.spec.name}.kicad_pro", "version": 1},
|
|
1388
|
+
"net_settings": {
|
|
1389
|
+
"classes": classes,
|
|
1390
|
+
"meta": {"version": 3},
|
|
1391
|
+
"net_colors": None,
|
|
1392
|
+
"netclass_assignments": assignments or None,
|
|
1393
|
+
"netclass_patterns": [],
|
|
1394
|
+
},
|
|
1395
|
+
"schematic": {"meta": {"version": 1}},
|
|
1396
|
+
"sheets": [[self.root_uuid, ""]],
|
|
1397
|
+
"text_variables": {},
|
|
1398
|
+
# Read by the router (KiCad ignores unknown keys): pairs and length tolerance.
|
|
1399
|
+
"traceforge": {
|
|
1400
|
+
"diff_pairs": pairs,
|
|
1401
|
+
"length_groups": [g.model_dump() for g in self.spec.length_groups],
|
|
1402
|
+
**self._stackup_info(),
|
|
1403
|
+
**constraints.router_info(self.spec, self.spec.board.origin),
|
|
1404
|
+
},
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
def default_clearance(self) -> float:
|
|
1408
|
+
"""The spec's board-wide clearance, kept at or above the fab's minimum."""
|
|
1409
|
+
rules = self.spec.rules
|
|
1410
|
+
if rules and rules.clearance:
|
|
1411
|
+
return max(rules.clearance, self.fab.min_clearance)
|
|
1412
|
+
return self.fab.default_clearance
|
|
1413
|
+
|
|
1414
|
+
def default_track(self) -> float:
|
|
1415
|
+
rules = self.spec.rules
|
|
1416
|
+
if rules and rules.track_width:
|
|
1417
|
+
return max(rules.track_width, self.fab.min_track)
|
|
1418
|
+
return self.fab.default_track
|
|
1419
|
+
|
|
1420
|
+
def _skew_pairs(self) -> list[dict]:
|
|
1421
|
+
"""Pairs whose spec asks for a KiCad skew rule."""
|
|
1422
|
+
wanted = {tuple(p.nets) for p in self.spec.diff_pairs if p.drc_skew}
|
|
1423
|
+
return [p for p in self.diff_pairs() if tuple(p["nets"]) in wanted]
|
|
1424
|
+
|
|
1425
|
+
def _stackup_info(self) -> dict:
|
|
1426
|
+
"""Layer roles and plane nets for the router (KiCad has no place for them)."""
|
|
1427
|
+
stack = self.spec.stackup_model()
|
|
1428
|
+
if stack is None:
|
|
1429
|
+
return {}
|
|
1430
|
+
info = {
|
|
1431
|
+
"preset": stack.name,
|
|
1432
|
+
"roles": {c.name: c.role for c in stack.copper},
|
|
1433
|
+
"planes": stack.plane_nets(),
|
|
1434
|
+
}
|
|
1435
|
+
# Split planes: every net of the layer, region relative to the board's top-left corner.
|
|
1436
|
+
splits = {
|
|
1437
|
+
c.name: [{"net": n, "region": list(r) if r else None} for n, r in c.splits]
|
|
1438
|
+
for c in stack.copper
|
|
1439
|
+
if c.splits
|
|
1440
|
+
}
|
|
1441
|
+
if splits:
|
|
1442
|
+
info["splits"] = splits
|
|
1443
|
+
return {"stackup": info}
|
|
1444
|
+
|
|
1445
|
+
def diff_pairs(self) -> list[dict]:
|
|
1446
|
+
"""Differential pairs (from ``diff_pairs`` and by net name) with width and gap
|
|
1447
|
+
worked out for the target impedance on this board's stackup."""
|
|
1448
|
+
if hasattr(self, "_pairs_cache"):
|
|
1449
|
+
return self._pairs_cache
|
|
1450
|
+
spec = self.spec
|
|
1451
|
+
nets = spec.all_nets()
|
|
1452
|
+
wide = {
|
|
1453
|
+
str(n)
|
|
1454
|
+
for settings in spec.net_classes.values()
|
|
1455
|
+
if float(settings.get("track_width", 0) or 0) > self.fab.default_track
|
|
1456
|
+
for n in settings.get("nets", [])
|
|
1457
|
+
}
|
|
1458
|
+
chosen = {tuple(p.nets): p for p in spec.diff_pairs}
|
|
1459
|
+
taken = {n for pair in chosen for n in pair}
|
|
1460
|
+
for pos, neg in diffpair.pair_names(nets):
|
|
1461
|
+
if {pos, neg} & (taken | wide | set(spec.power_nets)):
|
|
1462
|
+
continue
|
|
1463
|
+
chosen[(pos, neg)] = None
|
|
1464
|
+
taken |= {pos, neg}
|
|
1465
|
+
stack = spec.stackup_model() or stackup.default_for(2)
|
|
1466
|
+
layer = stack.signal_layers()[0]
|
|
1467
|
+
ref = stack.reference_below(layer)
|
|
1468
|
+
height = ref[1] if ref else diffpair.dielectric_height(spec.board.thickness, 2)
|
|
1469
|
+
result: list[dict] = []
|
|
1470
|
+
for (pos, neg), given in chosen.items():
|
|
1471
|
+
missing = [n for n in (pos, neg) if n not in nets]
|
|
1472
|
+
if missing:
|
|
1473
|
+
self.issues.append(
|
|
1474
|
+
Issue("warning", f"diff pair {pos}/{neg}: no pins on {', '.join(missing)}")
|
|
1475
|
+
)
|
|
1476
|
+
continue
|
|
1477
|
+
target = (given.impedance if given else None) or diffpair.USB_IMPEDANCE
|
|
1478
|
+
gap = (given.gap if given else None) or self.fab.default_clearance
|
|
1479
|
+
if given and given.width:
|
|
1480
|
+
width = given.width
|
|
1481
|
+
achieved = round(impedance.differential(stack, layer, width, gap), 1)
|
|
1482
|
+
else:
|
|
1483
|
+
try:
|
|
1484
|
+
width, _ = impedance.solve_pair(
|
|
1485
|
+
target,
|
|
1486
|
+
layer,
|
|
1487
|
+
stack,
|
|
1488
|
+
gap=gap,
|
|
1489
|
+
min_width=self.fab.default_track,
|
|
1490
|
+
max_width=2.0,
|
|
1491
|
+
)
|
|
1492
|
+
width = round(width, 2)
|
|
1493
|
+
except impedance.ImpedanceError: # out of reach: the nearest bound
|
|
1494
|
+
narrow = impedance.differential(stack, layer, self.fab.default_track, gap)
|
|
1495
|
+
width = self.fab.default_track if narrow < target else 2.0
|
|
1496
|
+
achieved = round(impedance.differential(stack, layer, width, gap), 1)
|
|
1497
|
+
if abs(achieved - target) > 0.1 * target:
|
|
1498
|
+
self.issues.append(
|
|
1499
|
+
Issue(
|
|
1500
|
+
"warning",
|
|
1501
|
+
f"diff pair {pos}/{neg}: {width} mm / {gap} mm gives {achieved} ohm, "
|
|
1502
|
+
f"not {target}; adjust width/gap or the stackup",
|
|
1503
|
+
)
|
|
1504
|
+
)
|
|
1505
|
+
result.append(
|
|
1506
|
+
{
|
|
1507
|
+
"nets": [pos, neg],
|
|
1508
|
+
"width": width,
|
|
1509
|
+
"gap": gap,
|
|
1510
|
+
"impedance": target,
|
|
1511
|
+
"estimated_impedance": achieved,
|
|
1512
|
+
"tolerance": given.tolerance if given else 0.1,
|
|
1513
|
+
"height": round(height, 3),
|
|
1514
|
+
"width_given": bool(given and given.width),
|
|
1515
|
+
}
|
|
1516
|
+
)
|
|
1517
|
+
self._pairs_cache = result
|
|
1518
|
+
return result
|
|
1519
|
+
|
|
1520
|
+
# ------------------------------------------------------------------ write
|
|
1521
|
+
def generate(self, out_dir: str | Path, *, overwrite: bool = False) -> GenerationResult:
|
|
1522
|
+
out = Path(out_dir)
|
|
1523
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
1524
|
+
project = out / f"{self.spec.name}.kicad_pro"
|
|
1525
|
+
schematic = out / f"{self.spec.name}.kicad_sch"
|
|
1526
|
+
pcb = out / f"{self.spec.name}.kicad_pcb"
|
|
1527
|
+
if not overwrite:
|
|
1528
|
+
existing = [p.name for p in (schematic, pcb) if p.exists()]
|
|
1529
|
+
if existing:
|
|
1530
|
+
raise DesignError(
|
|
1531
|
+
f"{', '.join(existing)} already exist in {out}; pass overwrite to replace"
|
|
1532
|
+
)
|
|
1533
|
+
parts = self.resolve()
|
|
1534
|
+
sch_root = formats.convert_schematic(self.schematic(parts), self.kicad_version)
|
|
1535
|
+
pcb_root, board_stats = self.board(parts)
|
|
1536
|
+
formats.convert_board(pcb_root, self.kicad_version)
|
|
1537
|
+
schematic.write_text(sexpr.dumps(sch_root), encoding="utf-8")
|
|
1538
|
+
for filename, child in self.sheet_files.items():
|
|
1539
|
+
formats.convert_schematic(child, self.kicad_version)
|
|
1540
|
+
(out / filename).write_text(sexpr.dumps(child), encoding="utf-8")
|
|
1541
|
+
pcb.write_text(sexpr.dumps(pcb_root), encoding="utf-8")
|
|
1542
|
+
project.write_text(json.dumps(self.project_file(), indent=2) + "\n", encoding="utf-8")
|
|
1543
|
+
rules = project.with_suffix(".kicad_dru")
|
|
1544
|
+
rules_text = constraints.dru_text(self.spec, self._skew_pairs())
|
|
1545
|
+
if rules_text:
|
|
1546
|
+
rules.write_text(rules_text, encoding="utf-8")
|
|
1547
|
+
else:
|
|
1548
|
+
rules.unlink(missing_ok=True)
|
|
1549
|
+
panel_stats: dict = {}
|
|
1550
|
+
if self.spec.board.panel is not None:
|
|
1551
|
+
summary = outlinemod.panelize(
|
|
1552
|
+
pcb, self.spec.board.panel, out / f"{self.spec.name}_panel.kicad_pcb"
|
|
1553
|
+
)
|
|
1554
|
+
self.sheet_stats["panel"] = summary
|
|
1555
|
+
panel_stats = {"panel": summary}
|
|
1556
|
+
stats = {
|
|
1557
|
+
"parts": len(parts),
|
|
1558
|
+
"symbols": sum(len(p.uuids) for p in parts),
|
|
1559
|
+
"connections": sum(len(p.pin_nets) for p in parts),
|
|
1560
|
+
"kicad_version": self.kicad_version,
|
|
1561
|
+
"sheets": self.sheet_stats.get("sheets", 1),
|
|
1562
|
+
"paper": self.sheet_stats.get("papers", {}),
|
|
1563
|
+
**board_stats,
|
|
1564
|
+
**panel_stats,
|
|
1565
|
+
}
|
|
1566
|
+
return GenerationResult(project, schematic, pcb, list(self.issues), stats)
|
|
1567
|
+
|
|
1568
|
+
|
|
1569
|
+
# ------------------------------------------------------------------------ helpers
|
|
1570
|
+
|
|
1571
|
+
|
|
1572
|
+
def _rotated_extent(
|
|
1573
|
+
extent: tuple[float, float, float, float], angle: float
|
|
1574
|
+
) -> tuple[float, float, float, float]:
|
|
1575
|
+
"""Bounding box of a footprint-local box after KiCad's rotation by ``angle``."""
|
|
1576
|
+
minx, miny, maxx, maxy = extent
|
|
1577
|
+
corners = [_rotate(x, y, angle) for x in (minx, maxx) for y in (miny, maxy)]
|
|
1578
|
+
xs = [round(c[0], 6) for c in corners]
|
|
1579
|
+
ys = [round(c[1], 6) for c in corners]
|
|
1580
|
+
return min(xs), min(ys), max(xs), max(ys)
|
|
1581
|
+
|
|
1582
|
+
|
|
1583
|
+
def _pad_offsets(footprint: Node) -> list[tuple[str, float, float]]:
|
|
1584
|
+
"""Footprint-local pad centres: (number, x, y)."""
|
|
1585
|
+
found = []
|
|
1586
|
+
for pad in find_all(footprint, "pad"):
|
|
1587
|
+
at = find(pad, "at")
|
|
1588
|
+
if len(pad) > 1 and str(pad[1]) and at is not None:
|
|
1589
|
+
found.append((str(pad[1]), sexpr.num(at[1]), sexpr.num(at[2])))
|
|
1590
|
+
return found
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
_SUPPLY_NAME = re.compile(r"^(A|U|D|P)?V(CC|DD|IN|OUT|I|O|BAT)\d*$", re.IGNORECASE)
|
|
1594
|
+
_XTAL_NAME = re.compile(r"(^|/)(XTAL|XIN|XOUT|OSC|XI|XO)", re.IGNORECASE)
|
|
1595
|
+
_FARADS = re.compile(r"^\s*([0-9.]+)\s*([pnuµm]?)", re.IGNORECASE)
|
|
1596
|
+
|
|
1597
|
+
|
|
1598
|
+
def _is_supply(pin: LibPin) -> bool:
|
|
1599
|
+
return pin.electrical in ("power_in", "power_out") or bool(_SUPPLY_NAME.match(pin.name))
|
|
1600
|
+
|
|
1601
|
+
|
|
1602
|
+
def _farads(value: str | None) -> float:
|
|
1603
|
+
"""Capacitance from a value like 100n, 4.7uF or 22p (0 when unknown)."""
|
|
1604
|
+
match = _FARADS.match(value or "")
|
|
1605
|
+
if not match:
|
|
1606
|
+
return 0.0
|
|
1607
|
+
try:
|
|
1608
|
+
number = float(match.group(1))
|
|
1609
|
+
except ValueError:
|
|
1610
|
+
return 0.0
|
|
1611
|
+
scale = {"p": 1e-12, "n": 1e-9, "u": 1e-6, "µ": 1e-6, "m": 1e-3, "": 1.0}
|
|
1612
|
+
return number * scale[match.group(2).lower()]
|
|
1613
|
+
|
|
1614
|
+
|
|
1615
|
+
def _pin_key(number: str) -> tuple[int, str]:
|
|
1616
|
+
digits = "".join(c for c in number if c.isdigit())
|
|
1617
|
+
return (int(digits) if digits and number.isdigit() else 10**6, number)
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
def _ref_sort(reference: str) -> tuple[str, int]:
|
|
1621
|
+
prefix = reference.rstrip("0123456789")
|
|
1622
|
+
digits = reference[len(prefix) :]
|
|
1623
|
+
return (prefix, int(digits) if digits else 0)
|
|
1624
|
+
|
|
1625
|
+
|
|
1626
|
+
def _label(
|
|
1627
|
+
net: str, x: float, y: float, pin: LibPin | None, label_uuid: str, angle: int | None = None
|
|
1628
|
+
) -> Node:
|
|
1629
|
+
# Text runs away from the body: opposite to the pin's direction.
|
|
1630
|
+
outward = angle if pin is None else (pin.angle + 180) % 360
|
|
1631
|
+
# Global labels: a local label on the root sheet names its net "/NAME", while the
|
|
1632
|
+
# board uses "NAME"; KiCad 8+ schematic parity reports every such net as a conflict.
|
|
1633
|
+
angle = int(outward) % 360
|
|
1634
|
+
justify = ["left"] if angle in (0, 90) else ["right"]
|
|
1635
|
+
return [
|
|
1636
|
+
Sym("global_label"),
|
|
1637
|
+
net,
|
|
1638
|
+
[Sym("shape"), Sym("passive")],
|
|
1639
|
+
[Sym("at"), fmt(x), fmt(y), Sym(str(angle))],
|
|
1640
|
+
[Sym("fields_autoplaced")],
|
|
1641
|
+
_effects(justify=justify),
|
|
1642
|
+
[Sym("uuid"), label_uuid],
|
|
1643
|
+
[
|
|
1644
|
+
Sym("property"),
|
|
1645
|
+
"Intersheetrefs",
|
|
1646
|
+
"${INTERSHEET_REFS}",
|
|
1647
|
+
[Sym("at"), fmt(x), fmt(y), Sym("0")],
|
|
1648
|
+
_effects(hide=True),
|
|
1649
|
+
],
|
|
1650
|
+
]
|
|
1651
|
+
|
|
1652
|
+
|
|
1653
|
+
def _unconnected_nets(part: _ResolvedPart, major: int = 7) -> dict[str, str]:
|
|
1654
|
+
"""Pad number -> KiCad's net name for symbol pins that are not connected."""
|
|
1655
|
+
out: dict[str, str] = {}
|
|
1656
|
+
for pin in part.symbol.pins:
|
|
1657
|
+
if pin.number in part.pin_nets or pin.number in out:
|
|
1658
|
+
continue
|
|
1659
|
+
name = pin.name if pin.name and pin.name not in {"~", pin.number} else ""
|
|
1660
|
+
label = (
|
|
1661
|
+
f"{part.spec.ref}-{name}-Pad{pin.number}"
|
|
1662
|
+
if name
|
|
1663
|
+
else f"{part.spec.ref}-Pad{pin.number}"
|
|
1664
|
+
)
|
|
1665
|
+
if major >= 8: # KiCad 8+ writes '/' in a generated net name as {slash}
|
|
1666
|
+
label = label.replace("/", "{slash}")
|
|
1667
|
+
out[pin.number] = f"unconnected-({label})"
|
|
1668
|
+
return out
|
|
1669
|
+
|
|
1670
|
+
|
|
1671
|
+
def _excluded_from_bom(part: _ResolvedPart) -> bool:
|
|
1672
|
+
if part.footprint is None:
|
|
1673
|
+
return False
|
|
1674
|
+
attr = find(part.footprint, "attr")
|
|
1675
|
+
return attr is not None and any(str(a) == "exclude_from_bom" for a in attr[1:])
|
|
1676
|
+
|
|
1677
|
+
|
|
1678
|
+
def _rotate_text(item: Node, angle: float) -> None:
|
|
1679
|
+
if not angle:
|
|
1680
|
+
return
|
|
1681
|
+
at = find(item, "at")
|
|
1682
|
+
if at is None:
|
|
1683
|
+
return
|
|
1684
|
+
base = sexpr.num(at[3]) if len(at) > 3 else 0.0
|
|
1685
|
+
del at[3:]
|
|
1686
|
+
at.append(fmt((base + angle) % 360))
|
|
1687
|
+
|
|
1688
|
+
|
|
1689
|
+
def _layers(count: int) -> Node:
|
|
1690
|
+
copper: list[tuple[int, str]] = [(0, "F.Cu")]
|
|
1691
|
+
copper += [(i, f"In{i}.Cu") for i in range(1, count - 1)]
|
|
1692
|
+
copper.append((31, "B.Cu"))
|
|
1693
|
+
node: Node = [Sym("layers")]
|
|
1694
|
+
for index, name in copper:
|
|
1695
|
+
node.append([Sym(str(index)), name, Sym("signal")])
|
|
1696
|
+
for index, name, kind, user in [
|
|
1697
|
+
(32, "B.Adhes", "user", "B.Adhesive"),
|
|
1698
|
+
(33, "F.Adhes", "user", "F.Adhesive"),
|
|
1699
|
+
(34, "B.Paste", "user", None),
|
|
1700
|
+
(35, "F.Paste", "user", None),
|
|
1701
|
+
(36, "B.SilkS", "user", "B.Silkscreen"),
|
|
1702
|
+
(37, "F.SilkS", "user", "F.Silkscreen"),
|
|
1703
|
+
(38, "B.Mask", "user", None),
|
|
1704
|
+
(39, "F.Mask", "user", None),
|
|
1705
|
+
(40, "Dwgs.User", "user", "User.Drawings"),
|
|
1706
|
+
(41, "Cmts.User", "user", "User.Comments"),
|
|
1707
|
+
(42, "Eco1.User", "user", "User.Eco1"),
|
|
1708
|
+
(43, "Eco2.User", "user", "User.Eco2"),
|
|
1709
|
+
(44, "Edge.Cuts", "user", None),
|
|
1710
|
+
(45, "Margin", "user", None),
|
|
1711
|
+
(46, "B.CrtYd", "user", "B.Courtyard"),
|
|
1712
|
+
(47, "F.CrtYd", "user", "F.Courtyard"),
|
|
1713
|
+
(48, "B.Fab", "user", None),
|
|
1714
|
+
(49, "F.Fab", "user", None),
|
|
1715
|
+
]:
|
|
1716
|
+
entry: Node = [Sym(str(index)), name, Sym(kind)]
|
|
1717
|
+
if user:
|
|
1718
|
+
entry.append(user)
|
|
1719
|
+
node.append(entry)
|
|
1720
|
+
return node
|
|
1721
|
+
|
|
1722
|
+
|
|
1723
|
+
def _outline(
|
|
1724
|
+
ox: float, oy: float, width: float, height: float, radius: float, seed: str
|
|
1725
|
+
) -> list[Node]:
|
|
1726
|
+
stroke = [Sym("stroke"), [Sym("width"), Sym("0.1")], [Sym("type"), Sym("default")]]
|
|
1727
|
+
if radius <= 0:
|
|
1728
|
+
return [
|
|
1729
|
+
[
|
|
1730
|
+
Sym("gr_rect"),
|
|
1731
|
+
[Sym("start"), fmt(ox), fmt(oy)],
|
|
1732
|
+
[Sym("end"), fmt(ox + width), fmt(oy + height)],
|
|
1733
|
+
copy.deepcopy(stroke),
|
|
1734
|
+
[Sym("fill"), Sym("none")],
|
|
1735
|
+
[Sym("layer"), "Edge.Cuts"],
|
|
1736
|
+
[Sym("tstamp"), _uuid(seed, "outline")],
|
|
1737
|
+
]
|
|
1738
|
+
]
|
|
1739
|
+
r = min(radius, width / 2, height / 2)
|
|
1740
|
+
x0, y0, x1, y1 = ox, oy, ox + width, oy + height
|
|
1741
|
+
items: list[Node] = []
|
|
1742
|
+
lines = [
|
|
1743
|
+
((x0 + r, y0), (x1 - r, y0)),
|
|
1744
|
+
((x1, y0 + r), (x1, y1 - r)),
|
|
1745
|
+
((x1 - r, y1), (x0 + r, y1)),
|
|
1746
|
+
((x0, y1 - r), (x0, y0 + r)),
|
|
1747
|
+
]
|
|
1748
|
+
for i, ((sx, sy), (ex, ey)) in enumerate(lines):
|
|
1749
|
+
items.append(
|
|
1750
|
+
[
|
|
1751
|
+
Sym("gr_line"),
|
|
1752
|
+
[Sym("start"), fmt(sx), fmt(sy)],
|
|
1753
|
+
[Sym("end"), fmt(ex), fmt(ey)],
|
|
1754
|
+
copy.deepcopy(stroke),
|
|
1755
|
+
[Sym("layer"), "Edge.Cuts"],
|
|
1756
|
+
[Sym("tstamp"), _uuid(seed, "edge", str(i))],
|
|
1757
|
+
]
|
|
1758
|
+
)
|
|
1759
|
+
k = r * (1 - math.sqrt(0.5))
|
|
1760
|
+
arcs = [
|
|
1761
|
+
((x0, y0 + r), (x0 + k, y0 + k), (x0 + r, y0)),
|
|
1762
|
+
((x1 - r, y0), (x1 - k, y0 + k), (x1, y0 + r)),
|
|
1763
|
+
((x1, y1 - r), (x1 - k, y1 - k), (x1 - r, y1)),
|
|
1764
|
+
((x0 + r, y1), (x0 + k, y1 - k), (x0, y1 - r)),
|
|
1765
|
+
]
|
|
1766
|
+
for i, (start, mid, end) in enumerate(arcs):
|
|
1767
|
+
items.append(
|
|
1768
|
+
[
|
|
1769
|
+
Sym("gr_arc"),
|
|
1770
|
+
[Sym("start"), fmt(start[0]), fmt(start[1])],
|
|
1771
|
+
[Sym("mid"), fmt(mid[0]), fmt(mid[1])],
|
|
1772
|
+
[Sym("end"), fmt(end[0]), fmt(end[1])],
|
|
1773
|
+
copy.deepcopy(stroke),
|
|
1774
|
+
[Sym("layer"), "Edge.Cuts"],
|
|
1775
|
+
[Sym("tstamp"), _uuid(seed, "arc", str(i))],
|
|
1776
|
+
]
|
|
1777
|
+
)
|
|
1778
|
+
return items
|
|
1779
|
+
|
|
1780
|
+
|
|
1781
|
+
def generate(
|
|
1782
|
+
spec: DesignSpec,
|
|
1783
|
+
out_dir: str | Path,
|
|
1784
|
+
*,
|
|
1785
|
+
overwrite: bool = False,
|
|
1786
|
+
libraries: Libraries | None = None,
|
|
1787
|
+
kicad_version: int | str | None = None,
|
|
1788
|
+
) -> GenerationResult:
|
|
1789
|
+
return Generator(spec, libraries, kicad_version).generate(out_dir, overwrite=overwrite)
|