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,1242 @@
|
|
|
1
|
+
"""Power and ground planes: assignment, pad-to-plane connection, fill and re-check.
|
|
2
|
+
|
|
3
|
+
What this module does for a board whose stackup has plane layers (``In1.Cu: GND`` ...):
|
|
4
|
+
|
|
5
|
+
* **Assignment.** The plane layers and their nets come from the project file the generator wrote
|
|
6
|
+
(``traceforge.stackup``). A layer may be *split*: several nets share it. The first net fills the
|
|
7
|
+
layer, every other net takes a region (a rectangle from the spec, or the hull of its pads and vias
|
|
8
|
+
grown by a margin) at a higher zone priority, so KiCad fills the base net around the regions.
|
|
9
|
+
* **Pad-to-plane connection.** Every pad of a plane net needs a way to the plane: a through-hole pad
|
|
10
|
+
whose layer holds that net's zone touches it directly, an SMD pad gets a via. The planner finds
|
|
11
|
+
pads that have none (geometrically, against all copper on the board) and gives each a via with a
|
|
12
|
+
short stub (dogbone), reuses a nearby via of the same net, or drops the via inside the pad. Large
|
|
13
|
+
exposed pads get a grid of vias. Every via and stub is checked for clearance against all copper,
|
|
14
|
+
holes and the board edge before it is written.
|
|
15
|
+
* **Thermal relief and islands.** Zones keep KiCad's thermal relief on through-hole pads. After the
|
|
16
|
+
fill, KiCad's own DRC is run: pads reported with a starved thermal join the plane solidly, pads
|
|
17
|
+
still unconnected get another via, and the fill is checked for copper islands.
|
|
18
|
+
* **Stitching.** Nets with several plane layers get vias on a grid and along the board edge, so the
|
|
19
|
+
planes act as one.
|
|
20
|
+
|
|
21
|
+
The entry point for the router is :func:`finish`; :func:`verify` re-checks a finished board.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
import math
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import shutil
|
|
31
|
+
import subprocess
|
|
32
|
+
import tempfile
|
|
33
|
+
import time
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
|
|
37
|
+
from traceforge.kicad import edit
|
|
38
|
+
from traceforge.kicad.pcb import Board, Pad, read_board
|
|
39
|
+
from traceforge.kicad.routegeom import Shape, SpatialIndex
|
|
40
|
+
from traceforge.sexpr import Sym, find, fmt
|
|
41
|
+
|
|
42
|
+
Point = tuple[float, float]
|
|
43
|
+
|
|
44
|
+
ISLAND_NOTE = "island check skipped: KiCad's Python module (pcbnew) could not read the fill"
|
|
45
|
+
_PAD_ITEM = re.compile(r"pad (\S+) \[(.+?)\] of (\S+)", re.IGNORECASE)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ----------------------------------------------------------------------------- project info
|
|
49
|
+
def _stackup_info(pcb: Path) -> dict:
|
|
50
|
+
project = Path(pcb).with_suffix(".kicad_pro")
|
|
51
|
+
try:
|
|
52
|
+
data = json.loads(project.read_text(encoding="utf-8"))
|
|
53
|
+
except (OSError, ValueError):
|
|
54
|
+
return {}
|
|
55
|
+
return (data.get("traceforge") or {}).get("stackup") or {}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def project_roles(pcb: Path) -> dict[str, str]:
|
|
59
|
+
"""Layer name -> ``signal`` or ``plane`` as the generator recorded it."""
|
|
60
|
+
return dict(_stackup_info(pcb).get("roles") or {})
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def project_layers(pcb: Path) -> dict[str, list[tuple[str, tuple | None]]]:
|
|
64
|
+
"""Plane layer -> ``[(net, region or None), ...]``; the first net fills the layer.
|
|
65
|
+
|
|
66
|
+
A region is ``(x0, y0, x1, y1)`` in mm from the board's top-left corner.
|
|
67
|
+
"""
|
|
68
|
+
info = _stackup_info(pcb)
|
|
69
|
+
layers: dict[str, list[tuple[str, tuple | None]]] = {}
|
|
70
|
+
for layer, net in (info.get("planes") or {}).items():
|
|
71
|
+
layers[str(layer)] = [(str(net), None)]
|
|
72
|
+
for layer, items in (info.get("splits") or {}).items():
|
|
73
|
+
layers[str(layer)] = [
|
|
74
|
+
(str(i["net"]), tuple(i["region"]) if i.get("region") else None) for i in items
|
|
75
|
+
]
|
|
76
|
+
return layers
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def project_assignment(pcb: Path) -> dict[str, list[str]]:
|
|
80
|
+
"""Net -> plane layers it is poured on (split planes included)."""
|
|
81
|
+
assign: dict[str, list[str]] = {}
|
|
82
|
+
for layer, nets in project_layers(pcb).items():
|
|
83
|
+
for net, _ in nets:
|
|
84
|
+
assign.setdefault(net, []).append(layer)
|
|
85
|
+
return assign
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ----------------------------------------------------------------------------- geometry
|
|
89
|
+
def _hull(points: list[Point]) -> list[Point]:
|
|
90
|
+
pts = sorted(set(points))
|
|
91
|
+
if len(pts) <= 2:
|
|
92
|
+
return pts
|
|
93
|
+
|
|
94
|
+
def cross(o: Point, a: Point, b: Point) -> float:
|
|
95
|
+
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
|
96
|
+
|
|
97
|
+
lower: list[Point] = []
|
|
98
|
+
for p in pts:
|
|
99
|
+
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
|
|
100
|
+
lower.pop()
|
|
101
|
+
lower.append(p)
|
|
102
|
+
upper: list[Point] = []
|
|
103
|
+
for p in reversed(pts):
|
|
104
|
+
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
|
|
105
|
+
upper.pop()
|
|
106
|
+
upper.append(p)
|
|
107
|
+
return lower[:-1] + upper[:-1]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _inside(poly: list[Point], x: float, y: float) -> bool:
|
|
111
|
+
hit = False
|
|
112
|
+
j = len(poly) - 1
|
|
113
|
+
for i, (xi, yi) in enumerate(poly):
|
|
114
|
+
xj, yj = poly[j]
|
|
115
|
+
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
|
|
116
|
+
hit = not hit
|
|
117
|
+
j = i
|
|
118
|
+
return hit
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _clip(points: list[Point], outline: tuple[float, float, float, float]) -> list[Point]:
|
|
122
|
+
x0, y0, x1, y1 = outline
|
|
123
|
+
return [(min(max(x, x0), x1), min(max(y, y0), y1)) for x, y in points]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@dataclass
|
|
127
|
+
class ZoneSpec:
|
|
128
|
+
net: str
|
|
129
|
+
layer: str
|
|
130
|
+
priority: int = 0
|
|
131
|
+
polygon: list[Point] | None = None # None: the whole board
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
@dataclass
|
|
135
|
+
class Layout:
|
|
136
|
+
"""The zones of a board's planes and where each net's copper is."""
|
|
137
|
+
|
|
138
|
+
zones: list[ZoneSpec] = field(default_factory=list)
|
|
139
|
+
notes: list[str] = field(default_factory=list)
|
|
140
|
+
|
|
141
|
+
def layers_of(self, net: str) -> list[str]:
|
|
142
|
+
return [z.layer for z in self.zones if z.net == net]
|
|
143
|
+
|
|
144
|
+
def nets(self) -> list[str]:
|
|
145
|
+
return list(dict.fromkeys(z.net for z in self.zones))
|
|
146
|
+
|
|
147
|
+
def zone(self, net: str, layer: str) -> ZoneSpec | None:
|
|
148
|
+
for z in self.zones:
|
|
149
|
+
if z.net == net and z.layer == layer:
|
|
150
|
+
return z
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
def covers(self, net: str, layer: str, x: float, y: float) -> bool:
|
|
154
|
+
"""Is the point inside the copper ``net`` pours on ``layer``?"""
|
|
155
|
+
zone = self.zone(net, layer)
|
|
156
|
+
if zone is None:
|
|
157
|
+
return False
|
|
158
|
+
if zone.polygon is not None:
|
|
159
|
+
return _inside(zone.polygon, x, y)
|
|
160
|
+
for other in self.zones:
|
|
161
|
+
if (
|
|
162
|
+
other.layer == layer
|
|
163
|
+
and other.priority > zone.priority
|
|
164
|
+
and other.polygon is not None
|
|
165
|
+
and _inside(other.polygon, x, y)
|
|
166
|
+
):
|
|
167
|
+
return False
|
|
168
|
+
return True
|
|
169
|
+
|
|
170
|
+
def reaches(self, net: str, layers: set[str], x: float, y: float) -> bool:
|
|
171
|
+
"""Does copper present on ``layers`` at the point touch a plane of ``net``?"""
|
|
172
|
+
return any(
|
|
173
|
+
self.covers(net, layer, x, y) for layer in self.layers_of(net) if layer in layers
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def build_layout(
|
|
178
|
+
pcb: Path,
|
|
179
|
+
board: Board,
|
|
180
|
+
pours: dict[str, list[str]],
|
|
181
|
+
margin: float = 1.2,
|
|
182
|
+
) -> Layout:
|
|
183
|
+
"""Zones for ``pours`` (net -> layers); splits and regions come from the project file."""
|
|
184
|
+
assert board.outline is not None
|
|
185
|
+
ox, oy, ex, ey = board.outline
|
|
186
|
+
project = project_layers(pcb)
|
|
187
|
+
per_layer: dict[str, list[tuple[str, tuple | None]]] = {}
|
|
188
|
+
for net, layers in pours.items():
|
|
189
|
+
for layer in layers:
|
|
190
|
+
entry = per_layer.setdefault(layer, [])
|
|
191
|
+
if not any(n == net for n, _ in entry):
|
|
192
|
+
entry.append((net, None))
|
|
193
|
+
for layer, nets in project.items():
|
|
194
|
+
if layer in per_layer and len(nets) > 1:
|
|
195
|
+
wanted = {n for n, _ in per_layer[layer]}
|
|
196
|
+
ordered = [(n, r) for n, r in nets if n in wanted]
|
|
197
|
+
ordered += [(n, None) for n, _ in per_layer[layer] if n not in {x for x, _ in ordered}]
|
|
198
|
+
per_layer[layer] = ordered
|
|
199
|
+
layout = Layout()
|
|
200
|
+
for layer in sorted(per_layer, key=lambda n: board.copper_layers.index(n)):
|
|
201
|
+
for priority, (net, region) in enumerate(per_layer[layer]):
|
|
202
|
+
polygon: list[Point] | None = None
|
|
203
|
+
if priority:
|
|
204
|
+
if region is not None:
|
|
205
|
+
x0, y0, x1, y1 = region
|
|
206
|
+
polygon = [
|
|
207
|
+
(ox + x0, oy + y0),
|
|
208
|
+
(ox + x1, oy + y0),
|
|
209
|
+
(ox + x1, oy + y1),
|
|
210
|
+
(ox + x0, oy + y1),
|
|
211
|
+
]
|
|
212
|
+
else:
|
|
213
|
+
polygon = _auto_region(board, net, margin)
|
|
214
|
+
if not polygon:
|
|
215
|
+
layout.notes.append(f"{net}: no pads for a region on {layer}")
|
|
216
|
+
continue
|
|
217
|
+
polygon = _clip(polygon, (ox, oy, ex, ey))
|
|
218
|
+
layout.zones.append(ZoneSpec(net, layer, priority, polygon))
|
|
219
|
+
_check_regions(layout, board)
|
|
220
|
+
return layout
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _auto_region(board: Board, net: str, margin: float) -> list[Point]:
|
|
224
|
+
points: list[Point] = []
|
|
225
|
+
for fp in board.footprints:
|
|
226
|
+
for pad in fp.pads:
|
|
227
|
+
if pad.net == net and pad.kind != "np_thru_hole":
|
|
228
|
+
reach = margin + max(pad.width, pad.height) / 2
|
|
229
|
+
points += [
|
|
230
|
+
(
|
|
231
|
+
pad.x + reach * math.cos(a * math.pi / 8),
|
|
232
|
+
pad.y + reach * math.sin(a * math.pi / 8),
|
|
233
|
+
)
|
|
234
|
+
for a in range(16)
|
|
235
|
+
]
|
|
236
|
+
for via in board.vias:
|
|
237
|
+
if via.net == net:
|
|
238
|
+
reach = margin + via.size / 2
|
|
239
|
+
points += [
|
|
240
|
+
(
|
|
241
|
+
via.x + reach * math.cos(a * math.pi / 8),
|
|
242
|
+
via.y + reach * math.sin(a * math.pi / 8),
|
|
243
|
+
)
|
|
244
|
+
for a in range(16)
|
|
245
|
+
]
|
|
246
|
+
return _hull(points)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _check_regions(layout: Layout, board: Board) -> None:
|
|
250
|
+
"""Note pads of one plane net that sit inside the region of another on the same layer."""
|
|
251
|
+
for zone in layout.zones:
|
|
252
|
+
if zone.polygon is None:
|
|
253
|
+
continue
|
|
254
|
+
for fp in board.footprints:
|
|
255
|
+
for pad in fp.pads:
|
|
256
|
+
if not pad.net or pad.net == zone.net or pad.kind == "np_thru_hole":
|
|
257
|
+
continue
|
|
258
|
+
other = layout.zone(pad.net, zone.layer)
|
|
259
|
+
if other is None or not layout.covers(pad.net, zone.layer, pad.x, pad.y):
|
|
260
|
+
if other is not None and _inside(zone.polygon, pad.x, pad.y):
|
|
261
|
+
layout.notes.append(
|
|
262
|
+
f"{fp.reference}.{pad.number} ({pad.net}) lies in the region of "
|
|
263
|
+
f"{zone.net} on {zone.layer}"
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# ----------------------------------------------------------------------------- zones
|
|
268
|
+
def _zone_net(root, zone, codes: dict[str, int]) -> str | None:
|
|
269
|
+
name = find(zone, "net_name")
|
|
270
|
+
if name is not None:
|
|
271
|
+
return str(name[1])
|
|
272
|
+
return edit._item_net(root, zone, codes)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def write_zones(
|
|
276
|
+
pcb: Path,
|
|
277
|
+
layout: Layout,
|
|
278
|
+
clearance: float = 0.3,
|
|
279
|
+
thermal_gap: float = 0.3,
|
|
280
|
+
thermal_bridge: float = 0.4,
|
|
281
|
+
min_thickness: float = 0.25,
|
|
282
|
+
) -> None:
|
|
283
|
+
"""Replace the copper zones of the layout's nets and layers by the layout's zones."""
|
|
284
|
+
board = read_board(pcb)
|
|
285
|
+
assert board.outline is not None
|
|
286
|
+
x0, y0, x1, y1 = board.outline
|
|
287
|
+
root = edit.load(pcb)
|
|
288
|
+
codes = edit.net_codes(root)
|
|
289
|
+
keys = {(z.net, z.layer) for z in layout.zones}
|
|
290
|
+
kept = []
|
|
291
|
+
for item in root:
|
|
292
|
+
if isinstance(item, list) and item and item[0] == "zone" and find(item, "keepout") is None:
|
|
293
|
+
layer = find(item, "layer")
|
|
294
|
+
if layer is not None and (_zone_net(root, item, codes), str(layer[1])) in keys:
|
|
295
|
+
continue
|
|
296
|
+
kept.append(item)
|
|
297
|
+
root[:] = kept
|
|
298
|
+
stamp = edit._stamp_key(root)
|
|
299
|
+
for z in layout.zones:
|
|
300
|
+
polygon = z.polygon or [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
|
|
301
|
+
net_node = edit._net_node(root, z.net)
|
|
302
|
+
node = [
|
|
303
|
+
Sym("zone"),
|
|
304
|
+
net_node,
|
|
305
|
+
*([[Sym("net_name"), z.net]] if isinstance(net_node[1], Sym) else []),
|
|
306
|
+
[Sym("layer"), z.layer],
|
|
307
|
+
[Sym(stamp), edit._new_uuid()],
|
|
308
|
+
[Sym("name"), f"plane {z.net} {z.layer}"],
|
|
309
|
+
[Sym("hatch"), Sym("edge"), Sym("0.5")],
|
|
310
|
+
*([[Sym("priority"), Sym(str(z.priority))]] if z.priority else []),
|
|
311
|
+
[Sym("connect_pads"), [Sym("clearance"), fmt(clearance)]],
|
|
312
|
+
[Sym("min_thickness"), fmt(min_thickness)],
|
|
313
|
+
[Sym("filled_areas_thickness"), Sym("no")],
|
|
314
|
+
[
|
|
315
|
+
Sym("fill"),
|
|
316
|
+
Sym("yes"),
|
|
317
|
+
[Sym("thermal_gap"), fmt(thermal_gap)],
|
|
318
|
+
[Sym("thermal_bridge_width"), fmt(thermal_bridge)],
|
|
319
|
+
],
|
|
320
|
+
[Sym("polygon"), [Sym("pts"), *[[Sym("xy"), fmt(px), fmt(py)] for px, py in polygon]]],
|
|
321
|
+
]
|
|
322
|
+
root.append(node)
|
|
323
|
+
edit.save(pcb, root)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# ----------------------------------------------------------------------------- copper field
|
|
327
|
+
@dataclass
|
|
328
|
+
class Params:
|
|
329
|
+
clearance: float = 0.2
|
|
330
|
+
via_size: float = 0.6
|
|
331
|
+
via_drill: float = 0.3
|
|
332
|
+
edge_clearance: float = 0.5
|
|
333
|
+
hole_clearance: float = 0.25
|
|
334
|
+
hole_to_hole: float = 0.25
|
|
335
|
+
track_width: float = 0.25
|
|
336
|
+
min_track: float = 0.15
|
|
337
|
+
via_in_pad: bool = False
|
|
338
|
+
reach: float = 3.0 # farthest a via may sit from its pad, mm
|
|
339
|
+
dogbone_reach: float = 1.5 # before routing, a fine-pitch pad's via sits this close or inside
|
|
340
|
+
stitch_pitch: float = 8.0
|
|
341
|
+
edge_pitch: float = 6.0
|
|
342
|
+
max_stitch: int = 400
|
|
343
|
+
net_width: dict[str, float] = field(default_factory=dict)
|
|
344
|
+
net_clear: dict[str, float] = field(default_factory=dict)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _project_rules(pcb: Path) -> tuple[dict[str, float], dict[str, float], float]:
|
|
348
|
+
"""Per-net track widths and clearances of the project's net classes, and the default clearance."""
|
|
349
|
+
try:
|
|
350
|
+
data = json.loads(Path(pcb).with_suffix(".kicad_pro").read_text(encoding="utf-8"))
|
|
351
|
+
except (OSError, ValueError):
|
|
352
|
+
return {}, {}, 0.0
|
|
353
|
+
settings = data.get("net_settings", {})
|
|
354
|
+
classes = {c.get("name"): c for c in settings.get("classes", [])}
|
|
355
|
+
widths: dict[str, float] = {}
|
|
356
|
+
clears: dict[str, float] = {}
|
|
357
|
+
for net, cls in (settings.get("netclass_assignments") or {}).items():
|
|
358
|
+
info = classes.get(cls) or {}
|
|
359
|
+
if info.get("track_width"):
|
|
360
|
+
widths[net] = float(info["track_width"])
|
|
361
|
+
if info.get("clearance"):
|
|
362
|
+
clears[net] = float(info["clearance"])
|
|
363
|
+
return widths, clears, float((classes.get("Default") or {}).get("clearance") or 0.0)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _pad_shape(pad: Pad, net: int, layers: int) -> Shape:
|
|
367
|
+
hw, hh = pad.width / 2, pad.height / 2
|
|
368
|
+
if pad.shape == "circle":
|
|
369
|
+
return Shape.capsule(pad.x, pad.y, pad.x, pad.y, min(hw, hh), net, layers, ("pad", pad))
|
|
370
|
+
if pad.shape == "oval":
|
|
371
|
+
if hw >= hh:
|
|
372
|
+
return Shape.capsule(
|
|
373
|
+
pad.x - hw + hh, pad.y, pad.x + hw - hh, pad.y, hh, net, layers, ("pad", pad)
|
|
374
|
+
)
|
|
375
|
+
return Shape.capsule(
|
|
376
|
+
pad.x, pad.y - hh + hw, pad.x, pad.y + hh - hw, hw, net, layers, ("pad", pad)
|
|
377
|
+
)
|
|
378
|
+
return Shape.rect(pad.x - hw, pad.y - hh, pad.x + hw, pad.y + hh, net, layers, ("pad", pad))
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
class Field:
|
|
382
|
+
"""All copper and holes of a board, for exact clearance checks of new vias and stubs."""
|
|
383
|
+
|
|
384
|
+
def __init__(self, board: Board, params: Params):
|
|
385
|
+
assert board.outline is not None
|
|
386
|
+
self.board = board
|
|
387
|
+
self.p = params
|
|
388
|
+
self.layers = list(board.copper_layers)
|
|
389
|
+
self.bit = {name: 1 << i for i, name in enumerate(self.layers)}
|
|
390
|
+
self.all = (1 << len(self.layers)) - 1
|
|
391
|
+
self.ids: dict[str, int] = {}
|
|
392
|
+
self.names: dict[int, str] = {}
|
|
393
|
+
self.index = SpatialIndex(1.0)
|
|
394
|
+
self.holes: list[tuple[float, float, float]] = []
|
|
395
|
+
self.outline = board.outline
|
|
396
|
+
self.geom = board.edge_geometry
|
|
397
|
+
for fp in board.footprints:
|
|
398
|
+
for pad in fp.pads:
|
|
399
|
+
if pad.kind == "np_thru_hole":
|
|
400
|
+
r = max(max(pad.width, pad.height), pad.drill) / 2
|
|
401
|
+
self.index.add(
|
|
402
|
+
Shape.capsule(pad.x, pad.y, pad.x, pad.y, r, 0, self.all, ("hole", pad))
|
|
403
|
+
)
|
|
404
|
+
self.holes.append((pad.x, pad.y, pad.drill))
|
|
405
|
+
continue
|
|
406
|
+
mask = self.mask(pad)
|
|
407
|
+
if not mask:
|
|
408
|
+
continue
|
|
409
|
+
self.index.add(_pad_shape(pad, self.net_id(pad.net), mask))
|
|
410
|
+
if pad.drill:
|
|
411
|
+
self.holes.append((pad.x, pad.y, pad.drill))
|
|
412
|
+
for t in board.tracks:
|
|
413
|
+
if t.layer in self.bit:
|
|
414
|
+
self.add_track(t.net, t.layer, (t.x1, t.y1), (t.x2, t.y2), t.width)
|
|
415
|
+
for v in board.vias:
|
|
416
|
+
self.add_via(v.net, v.x, v.y, v.size, v.drill)
|
|
417
|
+
|
|
418
|
+
def net_id(self, net: str) -> int:
|
|
419
|
+
if not net:
|
|
420
|
+
return 0
|
|
421
|
+
if net not in self.ids:
|
|
422
|
+
self.ids[net] = len(self.ids) + 1
|
|
423
|
+
self.names[self.ids[net]] = net
|
|
424
|
+
return self.ids[net]
|
|
425
|
+
|
|
426
|
+
def mask(self, pad: Pad) -> int:
|
|
427
|
+
return sum(bit for name, bit in self.bit.items() if pad.on_layer(name))
|
|
428
|
+
|
|
429
|
+
def clr(self, a: int, b: int) -> float:
|
|
430
|
+
c = self.p.clearance
|
|
431
|
+
for i in (a, b):
|
|
432
|
+
if i:
|
|
433
|
+
c = max(c, self.p.net_clear.get(self.names.get(i, ""), 0.0))
|
|
434
|
+
return c
|
|
435
|
+
|
|
436
|
+
def add_track(self, net: str, layer: str, a: Point, b: Point, width: float) -> None:
|
|
437
|
+
self.index.add(
|
|
438
|
+
Shape.capsule(
|
|
439
|
+
a[0],
|
|
440
|
+
a[1],
|
|
441
|
+
b[0],
|
|
442
|
+
b[1],
|
|
443
|
+
width / 2,
|
|
444
|
+
self.net_id(net),
|
|
445
|
+
self.bit[layer],
|
|
446
|
+
("track", None),
|
|
447
|
+
)
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
def add_via(self, net: str, x: float, y: float, size: float, drill: float) -> None:
|
|
451
|
+
self.index.add(
|
|
452
|
+
Shape.capsule(x, y, x, y, size / 2, self.net_id(net), self.all, ("via", (x, y)))
|
|
453
|
+
)
|
|
454
|
+
self.holes.append((x, y, drill))
|
|
455
|
+
|
|
456
|
+
def via_ok(self, x: float, y: float, net: str, size: float | None = None) -> bool:
|
|
457
|
+
p = self.p
|
|
458
|
+
size = size or p.via_size
|
|
459
|
+
r, nid = size / 2, self.net_id(net)
|
|
460
|
+
inset = p.edge_clearance + r
|
|
461
|
+
if self.geom.room(x, y) < inset:
|
|
462
|
+
return False
|
|
463
|
+
for s in self.index.near((x - r, y - r, x + r, y + r), 1.5):
|
|
464
|
+
if nid and s.net == nid:
|
|
465
|
+
continue
|
|
466
|
+
gap = s.dist_point(x, y) - r
|
|
467
|
+
need = self.clr(nid, s.net)
|
|
468
|
+
if s.tag[0] == "hole":
|
|
469
|
+
need = max(need, p.hole_clearance)
|
|
470
|
+
if gap < need - 1e-6:
|
|
471
|
+
return False
|
|
472
|
+
if (
|
|
473
|
+
s.tag[0] != "hole"
|
|
474
|
+
and s.dist_point(x, y) - p.via_drill / 2 < p.hole_clearance - 1e-6
|
|
475
|
+
):
|
|
476
|
+
return False
|
|
477
|
+
for hx, hy, hd in self.holes:
|
|
478
|
+
if abs(hx - x) < 1.5 and abs(hy - y) < 1.5:
|
|
479
|
+
if math.hypot(hx - x, hy - y) - hd / 2 - p.via_drill / 2 < p.hole_to_hole - 1e-6:
|
|
480
|
+
return False
|
|
481
|
+
return True
|
|
482
|
+
|
|
483
|
+
def stub_ok(self, layer: str, a: Point, b: Point, width: float, net: str) -> bool:
|
|
484
|
+
nid, bit = self.net_id(net), self.bit[layer]
|
|
485
|
+
pad = width / 2
|
|
486
|
+
bbox = (
|
|
487
|
+
min(a[0], b[0]) - pad,
|
|
488
|
+
min(a[1], b[1]) - pad,
|
|
489
|
+
max(a[0], b[0]) + pad,
|
|
490
|
+
max(a[1], b[1]) + pad,
|
|
491
|
+
)
|
|
492
|
+
for s in self.index.near(bbox, 1.0):
|
|
493
|
+
if not s.layers & bit or (nid and s.net == nid):
|
|
494
|
+
continue
|
|
495
|
+
need = self.clr(nid, s.net)
|
|
496
|
+
if s.tag[0] == "hole":
|
|
497
|
+
need = max(need, self.p.hole_clearance)
|
|
498
|
+
if s.dist_seg(a[0], a[1], b[0], b[1]) - pad < need - 1e-6:
|
|
499
|
+
return False
|
|
500
|
+
inset = self.p.edge_clearance + pad
|
|
501
|
+
return self.geom.segment_room(a[0], a[1], b[0], b[1]) >= inset
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
# ----------------------------------------------------------------------------- planner
|
|
505
|
+
@dataclass
|
|
506
|
+
class Plan:
|
|
507
|
+
tracks: list[tuple[str, str, float, list[Point]]] = field(default_factory=list)
|
|
508
|
+
vias: list[tuple[str, float, float]] = field(default_factory=list)
|
|
509
|
+
reused: int = 0
|
|
510
|
+
thermal: int = 0
|
|
511
|
+
stitch: int = 0
|
|
512
|
+
failed: list[str] = field(default_factory=list)
|
|
513
|
+
|
|
514
|
+
@property
|
|
515
|
+
def pad_vias(self) -> int:
|
|
516
|
+
return len(self.vias) - self.stitch - self.thermal
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
class _Union:
|
|
520
|
+
def __init__(self) -> None:
|
|
521
|
+
self.parent: dict[int, int] = {}
|
|
522
|
+
|
|
523
|
+
def find(self, a: int) -> int:
|
|
524
|
+
self.parent.setdefault(a, a)
|
|
525
|
+
while self.parent[a] != a:
|
|
526
|
+
self.parent[a] = self.parent[self.parent[a]]
|
|
527
|
+
a = self.parent[a]
|
|
528
|
+
return a
|
|
529
|
+
|
|
530
|
+
def union(self, a: int, b: int) -> None:
|
|
531
|
+
self.parent[self.find(a)] = self.find(b)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _item_layers(field_: Field, shape: Shape) -> set[str]:
|
|
535
|
+
return {name for name, bit in field_.bit.items() if shape.layers & bit}
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _accessible(field_: Field, layout: Layout, net: str) -> set[int]:
|
|
539
|
+
"""Ids of same-net shapes (by ``id``) whose connected copper touches a plane of the net."""
|
|
540
|
+
nid = field_.net_id(net)
|
|
541
|
+
shapes = [s for bucket in field_.index.buckets.values() for s in bucket if s.net == nid]
|
|
542
|
+
shapes = list({id(s): s for s in shapes}.values())
|
|
543
|
+
uf = _Union()
|
|
544
|
+
for s in shapes:
|
|
545
|
+
uf.find(id(s))
|
|
546
|
+
for o in field_.index.near(s.bbox, 0.01):
|
|
547
|
+
if o is s or o.net != nid or not o.layers & s.layers:
|
|
548
|
+
continue
|
|
549
|
+
if s.dist_shape(o) <= 0.002:
|
|
550
|
+
uf.union(id(s), id(o))
|
|
551
|
+
live: set[int] = set()
|
|
552
|
+
for s in shapes:
|
|
553
|
+
kind = s.tag[0]
|
|
554
|
+
if kind == "pad":
|
|
555
|
+
cx, cy = s.tag[1].x, s.tag[1].y
|
|
556
|
+
elif kind == "via":
|
|
557
|
+
cx, cy = s.tag[1]
|
|
558
|
+
else:
|
|
559
|
+
continue
|
|
560
|
+
if layout.reaches(net, _item_layers(field_, s), cx, cy):
|
|
561
|
+
live.add(uf.find(id(s)))
|
|
562
|
+
return {id(s) for s in shapes if uf.find(id(s)) in live}
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _grid(pad: Pad, reach: float, step: float = 0.1) -> list[tuple[float, float, float]]:
|
|
566
|
+
"""Via sites around a pad: ``(x, y, distance to the pad)`` sorted near to far."""
|
|
567
|
+
hw, hh = pad.width / 2, pad.height / 2
|
|
568
|
+
n = int((reach + max(hw, hh)) / step)
|
|
569
|
+
sites = []
|
|
570
|
+
for ix in range(-n, n + 1):
|
|
571
|
+
for iy in range(-n, n + 1):
|
|
572
|
+
dx, dy = ix * step, iy * step
|
|
573
|
+
ox, oy = max(abs(dx) - hw, 0.0), max(abs(dy) - hh, 0.0)
|
|
574
|
+
d = math.hypot(ox, oy)
|
|
575
|
+
if d < 1e-9:
|
|
576
|
+
d = 0.0
|
|
577
|
+
if d > reach:
|
|
578
|
+
continue
|
|
579
|
+
straight = dx == 0 or dy == 0 or abs(abs(dx) - abs(dy)) < 1e-9
|
|
580
|
+
sites.append((d + (0.0 if straight else 0.15), pad.x + dx, pad.y + dy, d))
|
|
581
|
+
sites.sort()
|
|
582
|
+
return [(x, y, d) for _, x, y, d in sites]
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _anchor(pad: Pad, x: float, y: float, width: float) -> Point:
|
|
586
|
+
"""Where a stub toward (x, y) leaves the pad: the point of the pad nearest to the via."""
|
|
587
|
+
hw = max(pad.width / 2 - width / 2, 0.0)
|
|
588
|
+
hh = max(pad.height / 2 - width / 2, 0.0)
|
|
589
|
+
return (min(max(x, pad.x - hw), pad.x + hw), min(max(y, pad.y - hh), pad.y + hh))
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _stub_layer(field_: Field, pad: Pad) -> str:
|
|
593
|
+
for name in field_.layers:
|
|
594
|
+
if pad.on_layer(name):
|
|
595
|
+
return name
|
|
596
|
+
return field_.layers[0]
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def plan_pad_vias(
|
|
600
|
+
field_: Field,
|
|
601
|
+
layout: Layout,
|
|
602
|
+
force: set[tuple[str, str]] | None = None,
|
|
603
|
+
avoid: dict[tuple[str, str], list[Point]] | None = None,
|
|
604
|
+
hard_only: bool = False,
|
|
605
|
+
) -> Plan:
|
|
606
|
+
"""Give each plane-net pad without a way to its plane a via (with a stub, or inside the pad).
|
|
607
|
+
|
|
608
|
+
``hard_only`` is for a board whose signals are not routed yet: it only serves the fine-pitch
|
|
609
|
+
pads (a dogbone on free copper close by, else a via inside the pad) and the large pads, so
|
|
610
|
+
that routing leaves those vias their place; the other pads are connected later.
|
|
611
|
+
"""
|
|
612
|
+
board, p = field_.board, field_.p
|
|
613
|
+
plan = Plan()
|
|
614
|
+
force = force or set()
|
|
615
|
+
avoid = avoid or {}
|
|
616
|
+
pads_by_net: dict[str, list[tuple[str, Pad]]] = {}
|
|
617
|
+
for fp in board.footprints:
|
|
618
|
+
for pad in fp.pads:
|
|
619
|
+
if pad.net in layout.nets() and pad.kind != "np_thru_hole":
|
|
620
|
+
pads_by_net.setdefault(pad.net, []).append((fp.reference, pad))
|
|
621
|
+
for net, pads in pads_by_net.items():
|
|
622
|
+
live = _accessible(field_, layout, net)
|
|
623
|
+
nid = field_.net_id(net)
|
|
624
|
+
pending = []
|
|
625
|
+
for ref, pad in pads:
|
|
626
|
+
shape = next(
|
|
627
|
+
(
|
|
628
|
+
s
|
|
629
|
+
for s in field_.index.near((pad.x, pad.y, pad.x, pad.y), 0.01)
|
|
630
|
+
if s.tag[0] == "pad" and s.tag[1] is pad
|
|
631
|
+
),
|
|
632
|
+
None,
|
|
633
|
+
)
|
|
634
|
+
if shape is None or ((ref, pad.number) not in force and id(shape) in live):
|
|
635
|
+
continue
|
|
636
|
+
pending.append((ref, pad))
|
|
637
|
+
# Fine-pitch and small pads first: they have the least room.
|
|
638
|
+
pending.sort(
|
|
639
|
+
key=lambda rp: (min(rp[1].width, rp[1].height) >= 1.5, min(rp[1].width, rp[1].height))
|
|
640
|
+
)
|
|
641
|
+
for ref, pad in pending:
|
|
642
|
+
label = f"{ref}.{pad.number}"
|
|
643
|
+
forced = (ref, pad.number) in force
|
|
644
|
+
if min(pad.width, pad.height) >= 1.5 and pad.width * pad.height >= 4.0:
|
|
645
|
+
if _pad_array(field_, layout, plan, pad, net):
|
|
646
|
+
continue
|
|
647
|
+
bad = avoid.get((ref, pad.number), [])
|
|
648
|
+
if hard_only:
|
|
649
|
+
if min(pad.width, pad.height) >= 0.5:
|
|
650
|
+
continue # room enough: the router places its via
|
|
651
|
+
# Fine pitch: a dogbone on free copper close by, else the via inside the pad.
|
|
652
|
+
kinds = ("reuse", "new")
|
|
653
|
+
if not _place_via(
|
|
654
|
+
field_,
|
|
655
|
+
layout,
|
|
656
|
+
plan,
|
|
657
|
+
pad,
|
|
658
|
+
net,
|
|
659
|
+
nid,
|
|
660
|
+
forced,
|
|
661
|
+
bad,
|
|
662
|
+
kinds,
|
|
663
|
+
True,
|
|
664
|
+
p.dogbone_reach,
|
|
665
|
+
True,
|
|
666
|
+
):
|
|
667
|
+
_place_via(field_, layout, plan, pad, net, nid, forced, bad, ("inside",))
|
|
668
|
+
continue
|
|
669
|
+
if not _place_via(field_, layout, plan, pad, net, nid, forced, bad):
|
|
670
|
+
plan.failed.append(label)
|
|
671
|
+
return plan
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def _pad_array(field_: Field, layout: Layout, plan: Plan, pad: Pad, net: str) -> bool:
|
|
675
|
+
"""Vias on a grid inside a large pad (exposed pad, thermal pad)."""
|
|
676
|
+
p = field_.p
|
|
677
|
+
inset = p.via_size / 2 + 0.25
|
|
678
|
+
pitch = p.via_size + 0.5
|
|
679
|
+
nx = max(1, int((pad.width - 2 * inset) / pitch) + 1)
|
|
680
|
+
ny = max(1, int((pad.height - 2 * inset) / pitch) + 1)
|
|
681
|
+
placed = 0
|
|
682
|
+
for ix in range(nx):
|
|
683
|
+
for iy in range(ny):
|
|
684
|
+
x = pad.x + (ix - (nx - 1) / 2) * pitch
|
|
685
|
+
y = pad.y + (iy - (ny - 1) / 2) * pitch
|
|
686
|
+
if (
|
|
687
|
+
abs(x - pad.x) > pad.width / 2 - inset + 1e-6
|
|
688
|
+
or abs(y - pad.y) > pad.height / 2 - inset + 1e-6
|
|
689
|
+
):
|
|
690
|
+
continue
|
|
691
|
+
if not layout.reaches(net, set(field_.layers), x, y):
|
|
692
|
+
continue
|
|
693
|
+
if field_.via_ok(x, y, net):
|
|
694
|
+
field_.add_via(net, x, y, p.via_size, p.via_drill)
|
|
695
|
+
plan.vias.append((net, round(x, 4), round(y, 4)))
|
|
696
|
+
placed += 1
|
|
697
|
+
if placed > 1:
|
|
698
|
+
plan.thermal += 1
|
|
699
|
+
return placed > 0
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _place_via(
|
|
703
|
+
field_: Field,
|
|
704
|
+
layout: Layout,
|
|
705
|
+
plan: Plan,
|
|
706
|
+
pad: Pad,
|
|
707
|
+
net: str,
|
|
708
|
+
nid: int,
|
|
709
|
+
forced: bool,
|
|
710
|
+
bad: list[Point],
|
|
711
|
+
kinds: tuple[str, ...] = ("reuse", "inside", "new"),
|
|
712
|
+
commit: bool = True,
|
|
713
|
+
limit: float | None = None,
|
|
714
|
+
off_pads: bool = False,
|
|
715
|
+
) -> bool:
|
|
716
|
+
p = field_.p
|
|
717
|
+
layer = _stub_layer(field_, pad)
|
|
718
|
+
widths = sorted(
|
|
719
|
+
{
|
|
720
|
+
round(min(p.net_width.get(net, p.track_width), p.track_width * 1.2), 4),
|
|
721
|
+
p.track_width,
|
|
722
|
+
0.2,
|
|
723
|
+
p.min_track,
|
|
724
|
+
},
|
|
725
|
+
reverse=True,
|
|
726
|
+
)
|
|
727
|
+
widths = [w for w in widths if w >= p.min_track - 1e-9] or [p.min_track]
|
|
728
|
+
penalty = 0.0 if p.via_in_pad else 1.5
|
|
729
|
+
candidates = []
|
|
730
|
+
# Existing vias of the net that reach a plane.
|
|
731
|
+
if not forced:
|
|
732
|
+
live = _accessible(field_, layout, net)
|
|
733
|
+
for s in field_.index.near((pad.x - 2.5, pad.y - 2.5, pad.x + 2.5, pad.y + 2.5), 0.0):
|
|
734
|
+
if s.tag[0] == "via" and s.net == nid and id(s) in live:
|
|
735
|
+
vx, vy = s.tag[1]
|
|
736
|
+
d = math.hypot(
|
|
737
|
+
max(abs(vx - pad.x) - pad.width / 2, 0.0),
|
|
738
|
+
max(abs(vy - pad.y) - pad.height / 2, 0.0),
|
|
739
|
+
)
|
|
740
|
+
if d <= 2.5:
|
|
741
|
+
candidates.append((d * 0.4, "reuse", vx, vy))
|
|
742
|
+
for x, y, d in _grid(pad, p.reach):
|
|
743
|
+
if any(math.hypot(x - bx, y - by) < 0.8 for bx, by in bad):
|
|
744
|
+
continue
|
|
745
|
+
inside = d == 0.0
|
|
746
|
+
if not inside and d < p.via_size / 2 + 0.1:
|
|
747
|
+
continue # a via straddling the pad's edge: either inside the pad or clear of it
|
|
748
|
+
cost = d + (penalty + 0.2 * math.hypot(x - pad.x, y - pad.y) if inside else 0.0)
|
|
749
|
+
candidates.append((cost, "inside" if inside else "new", x, y))
|
|
750
|
+
candidates.sort()
|
|
751
|
+
for cost, kind, x, y in candidates:
|
|
752
|
+
if kind not in kinds or (limit is not None and cost > limit):
|
|
753
|
+
continue
|
|
754
|
+
if kind != "reuse":
|
|
755
|
+
if not layout.reaches(net, set(field_.layers), x, y):
|
|
756
|
+
continue
|
|
757
|
+
if not field_.via_ok(x, y, net):
|
|
758
|
+
continue
|
|
759
|
+
if off_pads and any(
|
|
760
|
+
s.tag[0] == "pad" and s.dist_point(x, y) < p.via_size / 2 + 0.05
|
|
761
|
+
for s in field_.index.near((x, y, x, y), 0.5)
|
|
762
|
+
):
|
|
763
|
+
continue # on or touching a pad: not a free site
|
|
764
|
+
a = _anchor(pad, x, y, widths[-1])
|
|
765
|
+
if kind == "inside" or (abs(a[0] - x) < 1e-6 and abs(a[1] - y) < 1e-6):
|
|
766
|
+
stub = None
|
|
767
|
+
else:
|
|
768
|
+
stub = next((w for w in widths if field_.stub_ok(layer, a, (x, y), w, net)), None)
|
|
769
|
+
if stub is None:
|
|
770
|
+
continue
|
|
771
|
+
if not commit:
|
|
772
|
+
return True
|
|
773
|
+
if kind != "reuse":
|
|
774
|
+
field_.add_via(net, x, y, p.via_size, p.via_drill)
|
|
775
|
+
plan.vias.append((net, round(x, 4), round(y, 4)))
|
|
776
|
+
else:
|
|
777
|
+
plan.reused += 1
|
|
778
|
+
if stub is not None:
|
|
779
|
+
field_.add_track(net, layer, a, (x, y), stub)
|
|
780
|
+
plan.tracks.append((net, layer, stub, [a, (round(x, 4), round(y, 4))]))
|
|
781
|
+
return True
|
|
782
|
+
return False
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def plan_stitching(field_: Field, layout: Layout, nets: list[str] | None = None) -> Plan:
|
|
786
|
+
"""Vias that tie the plane layers of one net together: a grid and a ring along the edge."""
|
|
787
|
+
p = field_.p
|
|
788
|
+
plan = Plan()
|
|
789
|
+
x0, y0, x1, y1 = field_.outline
|
|
790
|
+
for net in nets if nets is not None else layout.nets():
|
|
791
|
+
layers = layout.layers_of(net)
|
|
792
|
+
if len(layers) < 2:
|
|
793
|
+
continue
|
|
794
|
+
existing = [
|
|
795
|
+
s.tag[1]
|
|
796
|
+
for bucket in field_.index.buckets.values()
|
|
797
|
+
for s in bucket
|
|
798
|
+
if s.tag[0] == "via" and s.net == field_.net_id(net)
|
|
799
|
+
]
|
|
800
|
+
existing = list(dict.fromkeys(existing))
|
|
801
|
+
sites: list[Point] = []
|
|
802
|
+
gx = x0 + p.stitch_pitch / 2
|
|
803
|
+
while gx < x1:
|
|
804
|
+
gy = y0 + p.stitch_pitch / 2
|
|
805
|
+
while gy < y1:
|
|
806
|
+
sites.append((gx, gy))
|
|
807
|
+
gy += p.stitch_pitch
|
|
808
|
+
gx += p.stitch_pitch
|
|
809
|
+
inset = p.edge_clearance + p.via_size / 2 + 0.7
|
|
810
|
+
corner = 3.0
|
|
811
|
+
t = x0 + corner
|
|
812
|
+
while t < x1 - corner:
|
|
813
|
+
sites += [(t, y0 + inset), (t, y1 - inset)]
|
|
814
|
+
t += p.edge_pitch
|
|
815
|
+
t = y0 + corner
|
|
816
|
+
while t < y1 - corner:
|
|
817
|
+
sites += [(x0 + inset, t), (x1 - inset, t)]
|
|
818
|
+
t += p.edge_pitch
|
|
819
|
+
for sx, sy in sites:
|
|
820
|
+
if plan.stitch >= p.max_stitch:
|
|
821
|
+
break
|
|
822
|
+
spacing = p.edge_pitch if field_.geom.room(sx, sy) < inset + 0.1 else p.stitch_pitch
|
|
823
|
+
if any(math.hypot(sx - ex, sy - ey) < spacing * 0.6 for ex, ey in existing):
|
|
824
|
+
continue
|
|
825
|
+
spot = _nearest_legal(field_, layout, net, layers, sx, sy, 1.5)
|
|
826
|
+
if spot is None:
|
|
827
|
+
continue
|
|
828
|
+
field_.add_via(net, spot[0], spot[1], p.via_size, p.via_drill)
|
|
829
|
+
plan.vias.append((net, round(spot[0], 4), round(spot[1], 4)))
|
|
830
|
+
existing.append(spot)
|
|
831
|
+
plan.stitch += 1
|
|
832
|
+
return plan
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def _nearest_legal(
|
|
836
|
+
field_: Field, layout: Layout, net: str, layers: list[str], x: float, y: float, radius: float
|
|
837
|
+
) -> Point | None:
|
|
838
|
+
step = 0.25
|
|
839
|
+
n = int(radius / step)
|
|
840
|
+
cells = sorted(
|
|
841
|
+
((ix * step) ** 2 + (iy * step) ** 2, ix, iy)
|
|
842
|
+
for ix in range(-n, n + 1)
|
|
843
|
+
for iy in range(-n, n + 1)
|
|
844
|
+
if (ix * step) ** 2 + (iy * step) ** 2 <= radius**2
|
|
845
|
+
)
|
|
846
|
+
for _, ix, iy in cells:
|
|
847
|
+
px, py = x + ix * step, y + iy * step
|
|
848
|
+
if all(layout.covers(net, layer, px, py) for layer in layers) and field_.via_ok(
|
|
849
|
+
px, py, net
|
|
850
|
+
):
|
|
851
|
+
return (px, py)
|
|
852
|
+
return None
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
# ----------------------------------------------------------------------------- KiCad checks
|
|
856
|
+
_ISLANDS = r"""
|
|
857
|
+
import sys, json, math, pcbnew
|
|
858
|
+
b = pcbnew.LoadBoard(sys.argv[1])
|
|
859
|
+
gap = float(sys.argv[2])
|
|
860
|
+
mm = pcbnew.ToMM
|
|
861
|
+
def psize(item, lid):
|
|
862
|
+
try:
|
|
863
|
+
return item.GetSize(lid) # KiCad 9 and later ask for the layer (and warn without it)
|
|
864
|
+
except TypeError:
|
|
865
|
+
return item.GetSize()
|
|
866
|
+
def vwidth(via, lid):
|
|
867
|
+
try:
|
|
868
|
+
return via.GetWidth(lid)
|
|
869
|
+
except TypeError:
|
|
870
|
+
return via.GetWidth()
|
|
871
|
+
pads = []
|
|
872
|
+
for fp in b.GetFootprints():
|
|
873
|
+
for pad in fp.Pads():
|
|
874
|
+
s = psize(pad, pcbnew.F_Cu)
|
|
875
|
+
pads.append((pad, "%s.%s" % (fp.GetReference(), pad.GetNumber()), max(mm(s.x), mm(s.y)) / 2))
|
|
876
|
+
vias = [t for t in b.GetTracks() if t.Type() == pcbnew.PCB_VIA_T]
|
|
877
|
+
out = []
|
|
878
|
+
for z in b.Zones():
|
|
879
|
+
try:
|
|
880
|
+
if z.GetIsRuleArea():
|
|
881
|
+
continue
|
|
882
|
+
except AttributeError:
|
|
883
|
+
if z.GetIsKeepout():
|
|
884
|
+
continue
|
|
885
|
+
for lid in z.GetLayerSet().Seq():
|
|
886
|
+
ps = z.GetFilledPolysList(lid)
|
|
887
|
+
chains = [ps.Outline(i) for i in range(ps.OutlineCount())]
|
|
888
|
+
items = [[] for _ in chains]
|
|
889
|
+
areas = [abs(c.Area()) for c in chains]
|
|
890
|
+
net = z.GetNetname()
|
|
891
|
+
cands = []
|
|
892
|
+
for pad, label, r in pads:
|
|
893
|
+
if pad.GetNetname() == net and pad.IsOnLayer(lid):
|
|
894
|
+
cands.append((label, pad.GetPosition(), r))
|
|
895
|
+
for v in vias:
|
|
896
|
+
if v.GetNetname() == net and v.IsOnLayer(lid):
|
|
897
|
+
p = v.GetPosition()
|
|
898
|
+
cands.append(("via@%.3f,%.3f" % (mm(p.x), mm(p.y)), p, mm(vwidth(v, lid)) / 2))
|
|
899
|
+
for label, pos, r in cands:
|
|
900
|
+
tol = int((r + gap + 0.05) * 1e6)
|
|
901
|
+
for i, c in enumerate(chains):
|
|
902
|
+
# Every outline that holds or touches the item counts: KiCad 9 and later cut a
|
|
903
|
+
# pad's thermal relief into extra small outlines beside the main fill.
|
|
904
|
+
if c.PointInside(pos) or math.sqrt(c.SquaredDistance(pos)) <= tol:
|
|
905
|
+
items[i].append(label)
|
|
906
|
+
out.append({"net": net, "layer": b.GetLayerName(lid), "outlines": [
|
|
907
|
+
{"area": mm(1) * mm(1) * areas[i], "items": items[i]} for i in range(len(chains))]})
|
|
908
|
+
print("ISLANDS" + json.dumps(out))
|
|
909
|
+
"""
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
@dataclass
|
|
913
|
+
class Analysis:
|
|
914
|
+
starved: set[tuple[str, str]] = field(default_factory=set)
|
|
915
|
+
unconnected: set[tuple[str, str]] = field(default_factory=set)
|
|
916
|
+
errors: dict[str, int] = field(default_factory=dict)
|
|
917
|
+
islands: int = 0 # fill outlines holding no pad or via of their net
|
|
918
|
+
detached: int = 0 # outlines with items, none of which the main outline holds
|
|
919
|
+
outlines: dict[str, int] = field(default_factory=dict) # "net layer" -> outline count
|
|
920
|
+
ran: bool = False
|
|
921
|
+
islands_ran: bool = False
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def _kicad_python() -> str | None:
|
|
925
|
+
from traceforge.kicad.cli import find_kicad_python
|
|
926
|
+
|
|
927
|
+
return find_kicad_python()
|
|
928
|
+
|
|
929
|
+
|
|
930
|
+
def analyse(pcb: Path, nets: list[str], thermal_gap: float = 0.3) -> Analysis:
|
|
931
|
+
"""KiCad's DRC on the (already filled) board, and the islands of every plane fill."""
|
|
932
|
+
from traceforge.kicad.cli import KicadCli, KicadCliError
|
|
933
|
+
|
|
934
|
+
result = Analysis()
|
|
935
|
+
try:
|
|
936
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
937
|
+
report = KicadCli().drc(Path(pcb), Path(tmp), schematic_parity=False)
|
|
938
|
+
except (KicadCliError, OSError, ValueError):
|
|
939
|
+
return result
|
|
940
|
+
result.ran = True
|
|
941
|
+
for violation in report.all():
|
|
942
|
+
if violation.excluded:
|
|
943
|
+
continue
|
|
944
|
+
if violation.kind in ("starved_thermal", "unconnected_items"):
|
|
945
|
+
for item in violation.items:
|
|
946
|
+
match = _PAD_ITEM.search(item)
|
|
947
|
+
if match and match.group(2) in nets:
|
|
948
|
+
key = (match.group(3), match.group(1))
|
|
949
|
+
(
|
|
950
|
+
result.starved
|
|
951
|
+
if violation.kind == "starved_thermal"
|
|
952
|
+
else result.unconnected
|
|
953
|
+
).add(key)
|
|
954
|
+
elif violation.severity == "error" and violation.kind not in (
|
|
955
|
+
"lib_footprint_issues",
|
|
956
|
+
"lib_footprint_mismatch",
|
|
957
|
+
):
|
|
958
|
+
result.errors[violation.kind] = result.errors.get(violation.kind, 0) + 1
|
|
959
|
+
python = _kicad_python()
|
|
960
|
+
if python is None:
|
|
961
|
+
return result
|
|
962
|
+
done = subprocess.run( # noqa: S603
|
|
963
|
+
[python, "-c", _ISLANDS, str(Path(pcb).resolve()), str(thermal_gap)],
|
|
964
|
+
capture_output=True,
|
|
965
|
+
text=True,
|
|
966
|
+
encoding="utf-8",
|
|
967
|
+
errors="replace",
|
|
968
|
+
timeout=300,
|
|
969
|
+
env={**os.environ, "QT_QPA_PLATFORM": "offscreen"},
|
|
970
|
+
check=False,
|
|
971
|
+
)
|
|
972
|
+
line = next((ln for ln in done.stdout.splitlines() if ln.startswith("ISLANDS")), None)
|
|
973
|
+
if line is None:
|
|
974
|
+
return result
|
|
975
|
+
result.islands_ran = True
|
|
976
|
+
for zone in json.loads(line[len("ISLANDS") :]):
|
|
977
|
+
outlines = zone["outlines"]
|
|
978
|
+
result.outlines[f"{zone['net']} {zone['layer']}"] = len(outlines)
|
|
979
|
+
if not outlines:
|
|
980
|
+
continue
|
|
981
|
+
main = max(range(len(outlines)), key=lambda i: outlines[i]["area"])
|
|
982
|
+
main_items = set(outlines[main]["items"])
|
|
983
|
+
for i, outline in enumerate(outlines):
|
|
984
|
+
if i == main:
|
|
985
|
+
continue
|
|
986
|
+
if not outline["items"]:
|
|
987
|
+
result.islands += 1
|
|
988
|
+
elif not main_items & set(outline["items"]):
|
|
989
|
+
result.detached += 1
|
|
990
|
+
return result
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
# ----------------------------------------------------------------------------- the entry points
|
|
994
|
+
@dataclass
|
|
995
|
+
class PlaneReport:
|
|
996
|
+
layers: dict[str, list[str]] = field(default_factory=dict)
|
|
997
|
+
pad_vias: int = 0
|
|
998
|
+
thermal_vias: int = 0
|
|
999
|
+
stitch_vias: int = 0
|
|
1000
|
+
reused_vias: int = 0
|
|
1001
|
+
solid_pads: int = 0
|
|
1002
|
+
filled: bool = False
|
|
1003
|
+
checked: bool = False
|
|
1004
|
+
starved_thermal: int = 0
|
|
1005
|
+
unconnected_pads: list[str] = field(default_factory=list)
|
|
1006
|
+
unplaced: list[str] = field(default_factory=list)
|
|
1007
|
+
islands: int = 0
|
|
1008
|
+
detached_islands: int = 0
|
|
1009
|
+
outlines: dict[str, int] = field(default_factory=dict)
|
|
1010
|
+
drc_errors: dict[str, int] = field(default_factory=dict)
|
|
1011
|
+
notes: list[str] = field(default_factory=list)
|
|
1012
|
+
rounds: int = 0
|
|
1013
|
+
seconds: float = 0.0
|
|
1014
|
+
|
|
1015
|
+
@property
|
|
1016
|
+
def clean(self) -> bool:
|
|
1017
|
+
return (
|
|
1018
|
+
self.filled
|
|
1019
|
+
and self.checked
|
|
1020
|
+
and not self.starved_thermal
|
|
1021
|
+
and not self.unconnected_pads
|
|
1022
|
+
and not self.unplaced
|
|
1023
|
+
and not self.islands
|
|
1024
|
+
and not self.detached_islands
|
|
1025
|
+
)
|
|
1026
|
+
|
|
1027
|
+
def to_dict(self) -> dict:
|
|
1028
|
+
data = {
|
|
1029
|
+
"layers": self.layers,
|
|
1030
|
+
"pad_vias": self.pad_vias,
|
|
1031
|
+
"thermal_vias": self.thermal_vias,
|
|
1032
|
+
"stitching_vias": self.stitch_vias,
|
|
1033
|
+
"reused_vias": self.reused_vias,
|
|
1034
|
+
"solid_pads": self.solid_pads,
|
|
1035
|
+
"filled": self.filled,
|
|
1036
|
+
"checked": self.checked,
|
|
1037
|
+
"starved_thermal": self.starved_thermal,
|
|
1038
|
+
"unconnected_plane_pads": self.unconnected_pads,
|
|
1039
|
+
"pads_without_via": self.unplaced,
|
|
1040
|
+
"isolated_islands": self.islands,
|
|
1041
|
+
"detached_islands": self.detached_islands,
|
|
1042
|
+
"fill_outlines": self.outlines,
|
|
1043
|
+
"clean": self.clean,
|
|
1044
|
+
"rounds": self.rounds,
|
|
1045
|
+
"seconds": round(self.seconds, 1),
|
|
1046
|
+
}
|
|
1047
|
+
if self.drc_errors:
|
|
1048
|
+
data["drc_errors_after_planes"] = self.drc_errors
|
|
1049
|
+
if self.notes:
|
|
1050
|
+
data["notes"] = self.notes
|
|
1051
|
+
return data
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def _write_plan(pcb: Path, plan: Plan, params: Params) -> None:
|
|
1055
|
+
if plan.tracks or plan.vias:
|
|
1056
|
+
edit.pcb_add_routing(pcb, plan.tracks, plan.vias, params.via_size, params.via_drill)
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
def finish(
|
|
1060
|
+
pcb: str | Path,
|
|
1061
|
+
pours: dict[str, list[str]],
|
|
1062
|
+
*,
|
|
1063
|
+
clearance: float = 0.2,
|
|
1064
|
+
via_size: float = 0.6,
|
|
1065
|
+
via_drill: float = 0.3,
|
|
1066
|
+
edge_clearance: float = 0.5,
|
|
1067
|
+
hole_clearance: float = 0.25,
|
|
1068
|
+
track_width: float = 0.25,
|
|
1069
|
+
via_in_pad: bool = False,
|
|
1070
|
+
solid_pads: list[tuple[str, str]] | None = None,
|
|
1071
|
+
stitch: bool = True,
|
|
1072
|
+
max_rounds: int = 4,
|
|
1073
|
+
pour_clearance: float | None = None,
|
|
1074
|
+
) -> PlaneReport:
|
|
1075
|
+
"""Pour, connect, fill and re-check the planes of a board whose signals are routed.
|
|
1076
|
+
|
|
1077
|
+
``pours`` maps each plane net to the layers it is poured on. Existing zones of those nets
|
|
1078
|
+
on those layers are replaced.
|
|
1079
|
+
"""
|
|
1080
|
+
started = time.monotonic()
|
|
1081
|
+
pcb = Path(pcb)
|
|
1082
|
+
board = read_board(pcb)
|
|
1083
|
+
widths, clears, default_clear = _project_rules(pcb)
|
|
1084
|
+
params = Params(
|
|
1085
|
+
clearance=max(clearance, default_clear),
|
|
1086
|
+
via_size=via_size,
|
|
1087
|
+
via_drill=via_drill,
|
|
1088
|
+
edge_clearance=edge_clearance,
|
|
1089
|
+
hole_clearance=hole_clearance,
|
|
1090
|
+
track_width=track_width,
|
|
1091
|
+
via_in_pad=via_in_pad,
|
|
1092
|
+
net_width=widths,
|
|
1093
|
+
net_clear=clears,
|
|
1094
|
+
)
|
|
1095
|
+
layout = build_layout(pcb, board, pours)
|
|
1096
|
+
report = PlaneReport(notes=list(layout.notes))
|
|
1097
|
+
for z in layout.zones:
|
|
1098
|
+
report.layers.setdefault(z.layer, []).append(z.net)
|
|
1099
|
+
write_zones(pcb, layout, clearance=pour_clearance or max(clearance, 0.3))
|
|
1100
|
+
poured = {
|
|
1101
|
+
(fp.reference, pad.number)
|
|
1102
|
+
for fp in board.footprints
|
|
1103
|
+
for pad in fp.pads
|
|
1104
|
+
if pad.net in pours
|
|
1105
|
+
and layout.reaches(
|
|
1106
|
+
pad.net, {n for n in board.copper_layers if pad.on_layer(n)}, pad.x, pad.y
|
|
1107
|
+
)
|
|
1108
|
+
}
|
|
1109
|
+
solid = {(str(r), str(n)) for r, n in solid_pads or [] if (str(r), str(n)) in poured}
|
|
1110
|
+
nets = layout.nets()
|
|
1111
|
+
|
|
1112
|
+
field_ = Field(board, params)
|
|
1113
|
+
plan = plan_pad_vias(field_, layout)
|
|
1114
|
+
if stitch and len(board.copper_layers) > 2:
|
|
1115
|
+
extra = plan_stitching(field_, layout)
|
|
1116
|
+
plan.vias += extra.vias
|
|
1117
|
+
plan.stitch = extra.stitch
|
|
1118
|
+
_write_plan(pcb, plan, params)
|
|
1119
|
+
report.pad_vias, report.thermal_vias = plan.pad_vias, plan.thermal
|
|
1120
|
+
report.stitch_vias, report.reused_vias = plan.stitch, plan.reused
|
|
1121
|
+
report.unplaced = list(plan.failed)
|
|
1122
|
+
if solid:
|
|
1123
|
+
edit.pcb_set_pad_zone_connect(pcb, sorted(solid))
|
|
1124
|
+
|
|
1125
|
+
report.filled = edit.fill_zones(pcb)
|
|
1126
|
+
if not report.filled:
|
|
1127
|
+
report.notes.append("zones not filled: KiCad's Python module (pcbnew) was not found")
|
|
1128
|
+
report.seconds = time.monotonic() - started
|
|
1129
|
+
return report
|
|
1130
|
+
tried: dict[tuple[str, str], list[Point]] = {}
|
|
1131
|
+
for round_ in range(max_rounds + 1):
|
|
1132
|
+
report.rounds = round_ + 1
|
|
1133
|
+
found = analyse(pcb, nets)
|
|
1134
|
+
report.checked = found.ran
|
|
1135
|
+
if found.ran and not found.islands_ran and ISLAND_NOTE not in report.notes:
|
|
1136
|
+
report.notes.append(ISLAND_NOTE)
|
|
1137
|
+
report.starved_thermal = len(found.starved)
|
|
1138
|
+
report.unconnected_pads = sorted(f"{r}.{n}" for r, n in found.unconnected)
|
|
1139
|
+
report.islands, report.detached_islands = found.islands, found.detached
|
|
1140
|
+
report.outlines = found.outlines
|
|
1141
|
+
report.drc_errors = found.errors
|
|
1142
|
+
if not found.ran or (not found.starved and not found.unconnected) or round_ == max_rounds:
|
|
1143
|
+
break
|
|
1144
|
+
changed = False
|
|
1145
|
+
fresh = found.starved - solid
|
|
1146
|
+
if fresh:
|
|
1147
|
+
solid |= fresh
|
|
1148
|
+
edit.pcb_set_pad_zone_connect(pcb, sorted(fresh))
|
|
1149
|
+
changed = True
|
|
1150
|
+
if found.unconnected:
|
|
1151
|
+
current = read_board(pcb)
|
|
1152
|
+
field_ = Field(current, params)
|
|
1153
|
+
for key in found.unconnected:
|
|
1154
|
+
for fp in current.footprints:
|
|
1155
|
+
if fp.reference == key[0]:
|
|
1156
|
+
for pad in fp.pads:
|
|
1157
|
+
if pad.number == key[1]:
|
|
1158
|
+
tried.setdefault(key, []).extend(
|
|
1159
|
+
(v.x, v.y)
|
|
1160
|
+
for v in current.vias
|
|
1161
|
+
if v.net == pad.net
|
|
1162
|
+
and math.hypot(v.x - pad.x, v.y - pad.y) < 3.0
|
|
1163
|
+
)
|
|
1164
|
+
again = plan_pad_vias(field_, layout, force=found.unconnected, avoid=tried)
|
|
1165
|
+
_write_plan(pcb, again, params)
|
|
1166
|
+
if again.vias or again.tracks:
|
|
1167
|
+
changed = True
|
|
1168
|
+
report.pad_vias += again.pad_vias
|
|
1169
|
+
report.thermal_vias += again.thermal
|
|
1170
|
+
report.unplaced = sorted(set(report.unplaced) | set(again.failed))
|
|
1171
|
+
if not changed:
|
|
1172
|
+
break
|
|
1173
|
+
edit.fill_zones(pcb)
|
|
1174
|
+
report.solid_pads = len(solid)
|
|
1175
|
+
report.seconds = time.monotonic() - started
|
|
1176
|
+
return report
|
|
1177
|
+
|
|
1178
|
+
|
|
1179
|
+
def reserve(
|
|
1180
|
+
pcb: str | Path,
|
|
1181
|
+
pours: dict[str, list[str]],
|
|
1182
|
+
*,
|
|
1183
|
+
clearance: float = 0.2,
|
|
1184
|
+
via_size: float = 0.6,
|
|
1185
|
+
via_drill: float = 0.3,
|
|
1186
|
+
edge_clearance: float = 0.5,
|
|
1187
|
+
hole_clearance: float = 0.25,
|
|
1188
|
+
track_width: float = 0.25,
|
|
1189
|
+
) -> int:
|
|
1190
|
+
"""Before routing: vias for the fine-pitch plane pads, and via arrays in exposed pads.
|
|
1191
|
+
|
|
1192
|
+
The router then sees them as copper and routes signals around them."""
|
|
1193
|
+
pcb = Path(pcb)
|
|
1194
|
+
board = read_board(pcb)
|
|
1195
|
+
widths, clears, default_clear = _project_rules(pcb)
|
|
1196
|
+
params = Params(
|
|
1197
|
+
clearance=max(clearance, default_clear),
|
|
1198
|
+
via_size=via_size,
|
|
1199
|
+
via_drill=via_drill,
|
|
1200
|
+
edge_clearance=edge_clearance,
|
|
1201
|
+
hole_clearance=hole_clearance,
|
|
1202
|
+
track_width=track_width,
|
|
1203
|
+
net_width=widths,
|
|
1204
|
+
net_clear=clears,
|
|
1205
|
+
)
|
|
1206
|
+
layout = build_layout(pcb, board, pours)
|
|
1207
|
+
plan = plan_pad_vias(Field(board, params), layout, hard_only=True)
|
|
1208
|
+
_write_plan(pcb, plan, params)
|
|
1209
|
+
return len(plan.vias)
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
def verify(pcb: str | Path, work_dir: str | Path | None = None) -> PlaneReport:
|
|
1213
|
+
"""Refill the zones of a copy of the board and report the state of its planes.
|
|
1214
|
+
|
|
1215
|
+
The copy keeps the original untouched. ``nets`` are the plane nets of the project file.
|
|
1216
|
+
"""
|
|
1217
|
+
pcb = Path(pcb)
|
|
1218
|
+
layers = project_layers(pcb)
|
|
1219
|
+
report = PlaneReport()
|
|
1220
|
+
for layer, nets in layers.items():
|
|
1221
|
+
report.layers[layer] = [n for n, _ in nets]
|
|
1222
|
+
plane_nets = sorted({n for nets in layers.values() for n, _ in nets})
|
|
1223
|
+
board = read_board(pcb)
|
|
1224
|
+
for zone in board.zones:
|
|
1225
|
+
if zone["net"] and zone["net"] not in plane_nets and zone["filled"]:
|
|
1226
|
+
plane_nets.append(zone["net"])
|
|
1227
|
+
with tempfile.TemporaryDirectory(dir=work_dir) as tmp:
|
|
1228
|
+
copy = Path(tmp) / pcb.name
|
|
1229
|
+
for suffix in (".kicad_pcb", ".kicad_pro", ".kicad_dru", ".kicad_prl"):
|
|
1230
|
+
if pcb.with_suffix(suffix).exists():
|
|
1231
|
+
shutil.copy2(pcb.with_suffix(suffix), Path(tmp) / (pcb.stem + suffix))
|
|
1232
|
+
report.filled = edit.fill_zones(copy)
|
|
1233
|
+
found = analyse(copy, plane_nets)
|
|
1234
|
+
report.checked = found.ran
|
|
1235
|
+
if found.ran and not found.islands_ran:
|
|
1236
|
+
report.notes.append(ISLAND_NOTE)
|
|
1237
|
+
report.starved_thermal = len(found.starved)
|
|
1238
|
+
report.unconnected_pads = sorted(f"{r}.{n}" for r, n in found.unconnected)
|
|
1239
|
+
report.islands, report.detached_islands = found.islands, found.detached
|
|
1240
|
+
report.outlines = found.outlines
|
|
1241
|
+
report.drc_errors = found.errors
|
|
1242
|
+
return report
|