Restack to four signal layers and route the board

The Ti375 fanout could not be resolved with three routing layers, so L5
stops being a dedicated 1.8-V plane and becomes a signal layer.  No rail
owns a whole layer any more: the supplies are split into zone islands on
L4 and L6, L2 and L7 stay solid and completely unrouted, and F.Cu, L3, L5
and B.Cu are all available for signals.

Routing is staged rather than handed to the autorouter wholesale.  The
BGA escape, the buck high-current loops, plane stitching and the local
power completion all run first and are locked; Freerouting then sees only
the ordinary digital classes, with everything else present as fixed
copper.  finalize_routing.py installs the audited RF and USB geometry and
closes whatever the autorouter left.

Four bugs behind the routing failures, all of them the same shape - a
layer list written down instead of read from the board, which was correct
while L5 was a plane and silently wrong afterwards:

- export_routing_stage.py emitted via keepouts for three layers only, so
  every existing via was invisible to the router on L5.  It drove traces
  straight through them: 102 shorting_items in DRC.
- route_local_power.py never used L5 at all, and picked up escape vias on
  two layers instead of all four.
- add_rf_ground() judged fence positions against vias and pads but not
  tracks.  It runs after the session import, when that region already has
  routed copper, and dropped a ground via on top of a signal trace.

route_local_power.py also grew a via cloud on every rail: reaching a
plane counted as progress even when it merged nothing, so the same pad
collected a via per pass, 0.4 mm further out each time.  Progress is now
measured by the group count actually falling, and groups already sitting
on their plane are skipped.  That removed 404 redundant vias.

The MAX2771 PLL loop filter was spread across three corners of the
package, which forced the charge-pump node onto an inner layer under the
GPS front end.  All three parts now sit in the pocket at U21's north-west
corner and the net stays on F.Cu.  A permanent RF_NO_DIGITAL area plus a
scoped rule keeps that region free of non-power copper on L3/L5/L6/B.Cu,
and the local router enforces the same restriction, since it is the one
stage that runs after the temporary keepout is deleted.

Also enables the solder-mask bridge check that was switched off
board-wide; the board passes it with no violations.

Final board: DRC clean - no shorts, clearance, disallowed-item or
dangling-copper violations - with 26 unconnected endpoints left.  Routing
is spread 37% L3, 27% F.Cu, 26% L5, 10% B.Cu over 6548 mm and 971 vias.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-16 01:41:43 +03:00
parent b706197667
commit af7c43b2a8
19 changed files with 62060 additions and 58295 deletions
+164 -47
View File
@@ -5,6 +5,10 @@ This deliberately does not replace power-stage routing. It only installs
short pad-to-via connections where a filled, same-net plane is physically
present below the candidate via. High-current converter loops and plane
bridges are handled separately.
It runs *after* route_power_stage.py: a candidate via is only checked against
copper that already exists, so any stage that lays down wide trunks has to go
first or its copper is invisible here.
"""
from __future__ import annotations
@@ -18,7 +22,7 @@ import pcbnew
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_INPUT = ROOT / "hardware" / "board_prerouted.kicad_pcb"
DEFAULT_INPUT = ROOT / "hardware" / "board_power_routed.kicad_pcb"
DEFAULT_OUTPUT = ROOT / "hardware" / "board_plane_stitched.kicad_pcb"
PLANE_NETS = {
"GND", "SYS5", "VCC0V95", "VCC1V8", "VCC3V3", "VCC3V3_AUX",
@@ -38,7 +42,7 @@ def distance_mm(a: pcbnew.VECTOR2I, b: pcbnew.VECTOR2I) -> float:
def add_track(board: pcbnew.BOARD, pad: pcbnew.PAD,
end: pcbnew.VECTOR2I, width: float) -> None:
end: pcbnew.VECTOR2I, width: float) -> pcbnew.PCB_TRACK:
track = pcbnew.PCB_TRACK(board)
track.SetStart(pad.GetPosition())
track.SetEnd(end)
@@ -47,6 +51,23 @@ def add_track(board: pcbnew.BOARD, pad: pcbnew.PAD,
track.SetNet(pad.GetNet())
track.SetLocked(True)
board.Add(track)
return track
def already_connected(pad: pcbnew.PAD, tracks: list[pcbnew.PCB_TRACK],
vias: list[pcbnew.PCB_VIA]) -> bool:
"""Report whether an earlier stage already attached copper to this pad."""
net = pad.GetNetname()
box = pad.GetBoundingBox()
def inside(position: pcbnew.VECTOR2I) -> bool:
return (box.GetX() <= position.x <= box.GetRight() and
box.GetY() <= position.y <= box.GetBottom())
for track in tracks:
if track.GetNetname() == net and (inside(track.GetStart()) or inside(track.GetEnd())):
return True
return any(via.GetNetname() == net and inside(via.GetPosition()) for via in vias)
def add_via(board: pcbnew.BOARD, pad: pcbnew.PAD,
@@ -68,6 +89,66 @@ def plane_at(zones_by_net: dict[str, list[pcbnew.ZONE]], net: str,
for zone in zones_by_net.get(net, ()))
def inside_temporary_keepout(position: pcbnew.VECTOR2I,
keepouts: list[pcbnew.ZONE]) -> bool:
"""Reject a through-via whose copper can touch an RF/USB rule area."""
radius = VIA_DIAMETER / 2 + CLEARANCE
probes = [(0.0, 0.0)]
for index in range(8):
angle = index * math.pi / 4
probes.append((radius * math.cos(angle), radius * math.sin(angle)))
for dx, dy in probes:
probe = pcbnew.VECTOR2I(position.x + mm(dx), position.y + mm(dy))
if any(zone.Outline().Contains(probe) for zone in keepouts):
return True
return False
def segment_distance_mm(point: pcbnew.VECTOR2I, start: pcbnew.VECTOR2I,
end: pcbnew.VECTOR2I) -> float:
px, py = pcbnew.ToMM(point.x), pcbnew.ToMM(point.y)
ax, ay = pcbnew.ToMM(start.x), pcbnew.ToMM(start.y)
bx, by = pcbnew.ToMM(end.x), pcbnew.ToMM(end.y)
dx, dy = bx - ax, by - ay
length = dx * dx + dy * dy
if length == 0.0:
return math.hypot(px - ax, py - ay)
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / length))
return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
def clear_of_tracks(position: pcbnew.VECTOR2I, net: str,
tracks: list[pcbnew.PCB_TRACK], extra: float = 0.0) -> bool:
"""Keep a via barrel clear of copper installed by the routing stages."""
for track in tracks:
if track.GetNetname() == net or isinstance(track, pcbnew.PCB_VIA):
continue
limit = (VIA_DIAMETER / 2 + extra + pcbnew.ToMM(track.GetWidth()) / 2
+ CLEARANCE + 0.03)
if segment_distance_mm(position, track.GetStart(), track.GetEnd()) < limit:
return False
return True
def clear_track_of_tracks(start: pcbnew.VECTOR2I, end: pcbnew.VECTOR2I, net: str,
tracks: list[pcbnew.PCB_TRACK], layer: int,
width: float) -> bool:
for track in tracks:
if track.GetNetname() == net or isinstance(track, pcbnew.PCB_VIA):
continue
if track.GetLayer() != layer:
continue
limit = width / 2 + pcbnew.ToMM(track.GetWidth()) / 2 + CLEARANCE + 0.03
for step in range(0, 13):
sample = pcbnew.VECTOR2I(
round(start.x + (end.x - start.x) * step / 12),
round(start.y + (end.y - start.y) * step / 12),
)
if segment_distance_mm(sample, track.GetStart(), track.GetEnd()) < limit:
return False
return True
def clear_of_other_copper(position: pcbnew.VECTOR2I, net: str,
pads: list[pcbnew.PAD], vias: list[pcbnew.PCB_VIA]) -> bool:
x, y = pcbnew.ToMM(position.x), pcbnew.ToMM(position.y)
@@ -116,19 +197,93 @@ def candidates(pad: pcbnew.PAD, footprint: pcbnew.FOOTPRINT) -> list[pcbnew.VECT
away = 0.0
radius = max(pcbnew.ToMM(pad.GetSizeX()), pcbnew.ToMM(pad.GetSizeY())) / 2
radius += VIA_DIAMETER / 2 + CLEARANCE + 0.08
angles = [away]
for delta_deg in (30, -30, 60, -60, 90, -90, 120, -120, 150, -150, 180):
angles.append(away + math.radians(delta_deg))
# Freerouting treats fixed non-45-degree traces as invalid geometry. Use
# only global orthogonal/45-degree directions, ordered by how closely they
# point away from the footprint centre.
directions = [(math.cos(math.radians(angle)), math.sin(math.radians(angle)))
for angle in range(0, 360, 45)]
directions.sort(key=lambda direction: -(
direction[0] * math.cos(away) + direction[1] * math.sin(away)
))
result = []
for scale in (1.0, 1.35, 1.75):
for angle in angles:
for dx, dy in directions:
result.append(pcbnew.VECTOR2I(
pad_pos.x + mm(radius * scale * math.cos(angle)),
pad_pos.y + mm(radius * scale * math.sin(angle)),
pad_pos.x + mm(radius * scale * dx),
pad_pos.y + mm(radius * scale * dy),
))
return result
def stitch(board: pcbnew.BOARD) -> tuple[dict[str, int], dict[str, int]]:
"""Connect every reachable SMD power pad to its plane on the given board.
Callable twice: once before signal routing, so the planes already have
real connection points, and again from finalize_routing.py once the RF and
USB corridors are no longer reserved by temporary rule areas. Pads that
are already stitched are skipped because the candidate location is then
occupied by the earlier via.
"""
zones_by_net: dict[str, list[pcbnew.ZONE]] = {}
for zone in board.Zones():
if not zone.GetIsRuleArea() and zone.GetNetname() in PLANE_NETS:
zones_by_net.setdefault(zone.GetNetname(), []).append(zone)
temporary_keepouts = [zone for zone in board.Zones()
if zone.GetIsRuleArea() and zone.GetZoneName().startswith("TEMP_")]
all_pads = [pad for fp in board.GetFootprints() for pad in fp.Pads()]
all_vias = [item for item in board.GetTracks() if isinstance(item, pcbnew.PCB_VIA)]
all_tracks = [item for item in board.GetTracks() if not isinstance(item, pcbnew.PCB_VIA)]
connected: dict[str, int] = {}
skipped: dict[str, int] = {}
for fp in board.GetFootprints():
# U1 already has deterministic dogbones. J2 is an edge-launch part;
# its ground lands are completed by finalize_routing.py's RF ground
# zone/fence, not by ordinary tracks that would run along Edge.Cuts.
# U13 ground/thermal vias are part of the deterministic high-current
# converter geometry in route_power_stage.py. Generic radial dogbones
# here can intrude into its SW and VIN paths.
if fp.GetReference() in {"U1", "U13", "J2"}:
continue
for pad in fp.Pads():
net = pad.GetNetname()
if net not in PLANE_NETS or pad.GetAttribute() != pcbnew.PAD_ATTRIB_SMD:
continue
if already_connected(pad, all_tracks, all_vias):
continue
chosen = None
pad_min = min(pcbnew.ToMM(pad.GetSizeX()), pcbnew.ToMM(pad.GetSizeY()))
width = max(0.15, min(0.30, pad_min * 0.65))
for candidate in candidates(pad, fp):
x, y = pcbnew.ToMM(candidate.x), pcbnew.ToMM(candidate.y)
if not (20.5 < x < 174.5 and 20.5 < y < 109.5):
continue
if not plane_at(zones_by_net, net, candidate):
continue
if inside_temporary_keepout(candidate, temporary_keepouts):
continue
if not clear_of_other_copper(candidate, net, all_pads, all_vias):
continue
if not clear_track_path(pad.GetPosition(), candidate, net, pad, all_pads, width):
continue
if not clear_of_tracks(candidate, net, all_tracks):
continue
if not clear_track_of_tracks(pad.GetPosition(), candidate, net,
all_tracks, pad.GetLayer(), width):
continue
chosen = candidate
break
if chosen is None:
skipped[net] = skipped.get(net, 0) + 1
continue
all_tracks.append(add_track(board, pad, chosen, width))
all_vias.append(add_via(board, pad, chosen))
connected[net] = connected.get(net, 0) + 1
return connected, skipped
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("input", nargs="?", type=Path, default=DEFAULT_INPUT)
@@ -138,45 +293,7 @@ def main() -> None:
board = pcbnew.LoadBoard(str(args.input))
if not pcbnew.ZONE_FILLER(board).Fill(board.Zones()):
raise RuntimeError("Could not fill planes before stitching")
zones_by_net: dict[str, list[pcbnew.ZONE]] = {}
for zone in board.Zones():
if not zone.GetIsRuleArea() and zone.GetNetname() in PLANE_NETS:
zones_by_net.setdefault(zone.GetNetname(), []).append(zone)
all_pads = [pad for fp in board.GetFootprints() for pad in fp.Pads()]
all_vias = [item for item in board.GetTracks() if isinstance(item, pcbnew.PCB_VIA)]
connected: dict[str, int] = {}
skipped: dict[str, int] = {}
for fp in board.GetFootprints():
if fp.GetReference() == "U1":
continue
for pad in fp.Pads():
net = pad.GetNetname()
if net not in PLANE_NETS or pad.GetAttribute() != pcbnew.PAD_ATTRIB_SMD:
continue
chosen = None
pad_min = min(pcbnew.ToMM(pad.GetSizeX()), pcbnew.ToMM(pad.GetSizeY()))
width = max(0.15, min(0.30, pad_min * 0.65))
for candidate in candidates(pad, fp):
x, y = pcbnew.ToMM(candidate.x), pcbnew.ToMM(candidate.y)
if not (20.5 < x < 174.5 and 20.5 < y < 109.5):
continue
if not plane_at(zones_by_net, net, candidate):
continue
if not clear_of_other_copper(candidate, net, all_pads, all_vias):
continue
if not clear_track_path(pad.GetPosition(), candidate, net, pad, all_pads, width):
continue
chosen = candidate
break
if chosen is None:
skipped[net] = skipped.get(net, 0) + 1
continue
add_track(board, pad, chosen, width)
all_vias.append(add_via(board, pad, chosen))
connected[net] = connected.get(net, 0) + 1
connected, skipped = stitch(board)
if not pcbnew.ZONE_FILLER(board).Fill(board.Zones()):
raise RuntimeError("Could not refill planes after stitching")