MustafaMulla29/usb-pd-motherboard

4-layer USB-C PD hub motherboard with 20 V USB-C input, Linux T113-S3 computer, CH338F USB hub, four individually controlled 5–20 V PD outputs, USB data/camera ports, regulated rails, and hardware watchdog/E-stop safety interlock.

Version
1.0.24
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone MustafaMulla29/usb-pd-motherboard  # download the package files into ./usb-pd-motherboard
tsci add MustafaMulla29/usb-pd-motherboard    # add it to your project as @tsci/MustafaMulla29.usb-pd-motherboard

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

tools/router/fastroute.cpp

// fastroute: one-pass grid router with rip-up for the whole board.
//
//   clang++ -O2 -std=c++17 -o tools/router/fastroute tools/router/fastroute.cpp
//   tools/router/fastroute routing/inputs/ALL.fr.txt routing/inputs/ALL.fr.out [--time 300] [--seed 1]
//   (normally run through tools/router/route.sh)
//
// Model
//   0.05 mm grid, 8 directions, through vias. Every piece of copper adds +1 to "blocked" counters
//   of all cells closer than (clearance + trace half width); while a net is routed its own copper
//   is subtracted, so a cell is free exactly when its counter is 0. Fixed copper (pads, holes,
//   board edge) and routed copper are counted separately, so a search may cross routed copper
//   at a price and then rips up whatever it crossed (those nets are queued again).
//   Separate counters with the via radius keep via checks exact.
//   Plane nets (GND, VIN_SYS, V5V0): each pad only has to reach a via inside its plane's outline.
//   Wide nets step down (0.5 -> 0.3 -> 0.2 -> 0.1 mm) only where the wider trace does not fit, e.g. at fine-pitch pins.
//   USB pairs: the second line of a pair pays 2.5x for every cell that is not right beside the first, so the
//   two run side by side at the closest pitch the clearance allows (0.35 mm for 0.22 mm lines); pair copper
//   costs 40x to rip, and pairs themselves rip ordinary copper cheaply. The first line of a pair pays 4x for
//   cells without room for its partner one pitch away, so it picks corridors wide enough for both. Pair lines are wider than 0.1 mm, so
//   a third set of counters with the pair line's own radius keeps their clearance check exact (the generic
//   wide-net check is deliberately pessimistic and would push the two lines too far apart).
//   Nets with a no-via / length rule (the hub crystal) are routed first and then fixed.
//   Pair jobs (PAIRJOB lines from prep.py): before the pair nets are routed, each pair's long run is laid as
//   ONE wide track on the top layer (A* with a heading, 45-degree turns only, a minimum straight run after
//   every turn) and split into two parallel lines 0.35 mm apart. Those two "mid" routes are fixed copper; the
//   ordinary router then only connects their ends to the pins. If no wide track fits, the pair falls back to
//   the side-by-side-by-cost method above.
//   Partial runs (tools/router/reroute.py): FIX / FIXV lines give existing copper of the other nets as fixed
//   obstacles and an ONLY line names the nets to route, so a few nets can be redone without touching the rest.
//   KT / kw / kv lines (same layout as the T / w / v lines of the output) give copper of a net that is routed in
//   this run but should keep what it has: those routes are loaded as fixed routes of the net, so only pins that
//   are not connected yet get new copper, joined onto the old where that is shortest. They are not written out.
//   Centre (thermal) pads of plane nets (TPAD lines from prep.py): up to four vias INSIDE the pad, 0.65 mm in
//   from its edges, before anything else is routed. A small QFN's centre pad is ringed by its pins and has no
//   other way out; the board allows vias in pads (isViaInPadAllowed). A pad that gets none is routed as usual.
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
typedef uint16_t u16; typedef uint32_t u32; typedef uint8_t u8;

// ---------------- rules ----------------
static double P = 0.05, X0, Y0, X1, Y1;
static int NX, NY, NC;                    // cells per layer
static double CLR = 0.1, VIA_D = 0.45, VIA_HOLE = 0.3, EDGE = 0.2, HOLECLR = 0.2;
static const double GUARD = 0.012;        // grid sampling guard
static double R0, RV, VIA_R;              // base radius, via radius add
static vector<string> layerNames; static vector<int> RLs; static int NL;   // routing layers (indices into layerNames)
static int rlOfLayer[8];

// ---------------- costs ----------------
static const int STEP = 10, DIAGC = 14;
static int VIA_COST = 500, RIP_COST = 220, NECK_MULT = 3, POUR_MULT = 6;

struct Shape { int type; u8 mask; double ax, ay, bx, by, hw, extra; };   // type 0 rect(center ax,ay half bx,by) 1 capsule
struct Pad { int net; u8 mask; double cx, cy, w, h; int kind; int circle; };
struct Pin { int net; double x, y; u8 mask; int pad; };
struct Pt { double x, y; int l; double w; bool via; };
struct Route {
  int net; int pinA, pinB;       // pin ids or -1
  int joinA, joinB;              // route ids joined onto, or -1
  bool plane;                    // ends in a plane via
  bool alive, frozen;
  bool mid = false;              // fixed middle run of a USB pair; other routes may only join its two ends
  bool pre = false;              // kept copper loaded from the input (partial runs): never ripped, never written out
  vector<Pt> pts; vector<u32> nodes; vector<Shape> shapes; vector<pair<double,double>> vias;
};
struct Net { string name; double w; bool plane; int planeLayer; int pair; vector<int> pins, pads; int rips = 0; bool failed = false, frozen = false; vector<int> routes; int novia = 0; double maxLen = 0; };

static vector<Net> nets; static vector<Pad> pads; static vector<Pin> pins; static vector<Route> routes;
static vector<vector<pair<double,double>>> planePoly; static vector<int> planeNet;
struct Pour { int net; vector<pair<double,double>> poly; };
static vector<Pour> pours; static vector<pair<double,double>> outline;

// grids (per routing layer)
static vector<vector<u16>> baseH, baseS, viaH, viaS, pwH, pwS;   // pw*: exact counters for the USB pair line width
static double PAIR_W = 0, RPW = 0;                              // pair line width, and its radius add (0 = no wide pairs)
static vector<u16> vvH, vvS; static vector<u8> padmask;
static vector<vector<u8>> mult;          // cost multiplier x10 (10 = normal)
static vector<vector<u8>> hist;
static vector<vector<u8>> planeOK;       // per plane net index: cell inside plane outline (shrunk)
static vector<vector<u8>> pairMark;      // cells blocked by USB pair copper (dear to rip)


static inline int ci(double x) { return (int)lround((x - X0) / P); }
static inline int cj(double y) { return (int)lround((y - Y0) / P); }
static inline double cx(int i) { return X0 + i * P; }
static inline double cy(int j) { return Y0 + j * P; }

template <class F> static void forRect(double x, double y, double hw, double hh, double r, F f) {
  int ia = max(0, ci(x - hw - r) - 1), ib = min(NX - 1, ci(x + hw + r) + 1), ja = max(0, cj(y - hh - r) - 1), jb = min(NY - 1, cj(y + hh + r) + 1);
  double r2 = r * r;
  for (int j = ja; j <= jb; j++) { double dy = max(fabs(cy(j) - y) - hh, 0.0); if (dy >= r) continue;
    for (int i = ia; i <= ib; i++) { double dx = max(fabs(cx(i) - x) - hw, 0.0); if (dx * dx + dy * dy < r2) f(j * NX + i); } }
}
template <class F> static void forSeg(double ax, double ay, double bx, double by, double r, F f) {
  int ia = max(0, ci(min(ax, bx) - r) - 1), ib = min(NX - 1, ci(max(ax, bx) + r) + 1), ja = max(0, cj(min(ay, by) - r) - 1), jb = min(NY - 1, cj(max(ay, by) + r) + 1);
  double vx = bx - ax, vy = by - ay, L2 = vx * vx + vy * vy, r2 = r * r;
  for (int j = ja; j <= jb; j++) { double y = cy(j);
    for (int i = ia; i <= ib; i++) { double x = cx(i); double t = L2 > 0 ? ((x - ax) * vx + (y - ay) * vy) / L2 : 0; t = t < 0 ? 0 : t > 1 ? 1 : t;
      double dx = x - (ax + t * vx), dy = y - (ay + t * vy); if (dx * dx + dy * dy < r2) f(j * NX + i); } }
}
template <class F> static void forShape(const Shape& s, double r, F f) {
  if (s.type == 0) forRect(s.ax, s.ay, s.bx, s.by, r, f); else forSeg(s.ax, s.ay, s.bx, s.by, r, f);
}
static void markShape(const Shape& s, int d, bool soft) {
  for (int l = 0; l < NL; l++) if (s.mask & (1 << RLs[l])) {
    u16* b = (soft ? baseS : baseH)[l].data(); u16* v = (soft ? viaS : viaH)[l].data();
    forShape(s, s.hw + s.extra + R0, [&](int c) { b[c] += d; });
    forShape(s, s.hw + s.extra + RV, [&](int c) { v[c] += d; });
    if (RPW > 0) { u16* w = (soft ? pwS : pwH)[l].data(); forShape(s, s.hw + s.extra + RPW, [&](int c) { w[c] += d; }); }
  }
}
static const double VV_R = 0.4 + GUARD;
static void markVia(double x, double y, int d, bool soft) { u16* g = (soft ? vvS : vvH).data(); forSeg(x, y, x, y, VV_R, [&](int c) { g[c] += d; }); }
static void markPair(Route& r, int d);
static void markRoute(Route& r, int d) {
  bool soft = !r.frozen; markPair(r, d);
  for (auto& s : r.shapes) markShape(s, d, soft);
  for (auto& v : r.vias) markVia(v.first, v.second, d, soft);
}
static vector<vector<Shape>> fixedShapes;   // per net (index nets.size() = no net)
static void markPair(Route& r, int d) {
  if (nets[r.net].pair < 0) return;
  for (auto& sh : r.shapes) for (int l = 0; l < NL; l++) if (sh.mask & (1 << RLs[l])) forShape(sh, sh.hw + RV, [&](int c) { pairMark[l][c] += d; });
}
static bool inPoly(const vector<pair<double,double>>& poly, double x, double y) {
  bool in = false; size_t n = poly.size();
  for (size_t i = 0, j = n - 1; i < n; j = i++) { auto [xi, yi] = poly[i]; auto [xj, yj] = poly[j];
    if ((yi > y) != (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) in = !in; }
  return in;
}
static double distPoly(const vector<pair<double,double>>& poly, double x, double y) {
  double best = 1e18; size_t n = poly.size();
  for (size_t i = 0, j = n - 1; i < n; j = i++) { auto [ax, ay] = poly[j]; auto [bx, by] = poly[i];
    double vx = bx - ax, vy = by - ay, L2 = vx * vx + vy * vy; double t = L2 > 0 ? ((x - ax) * vx + (y - ay) * vy) / L2 : 0; t = t < 0 ? 0 : t > 1 ? 1 : t;
    double dx = x - (ax + t * vx), dy = y - (ay + t * vy); best = min(best, dx * dx + dy * dy); }
  return sqrt(best);
}

// ---------------- search state ----------------
static vector<u32> gsc, gstamp; static vector<u8> par; static u32 gen = 1;
static vector<u32> infoStamp; static vector<int> info;     // source/target marks: >=0 pin id, <= -2 route id (-2 - id)
static vector<u8> infoKind;                                 // 1 source 2 target
static vector<vector<u32>> ownStamp; static u32 ownGen = 1; // cells inside the routed net's own pads
static const int DX[8] = {1, 1, 0, -1, -1, -1, 0, 1}, DY[8] = {0, 1, 1, 1, 0, -1, -1, -1};

struct HeapItem { u32 f, g, node; bool operator<(const HeapItem& o) const { return f != o.f ? f > o.f : g < o.g; } };

static vector<pair<int,int>> makeStencil(double e) {
  vector<pair<int,int>> s; int n = (int)ceil((e + 2 * P) / P);
  for (int dj = -n; dj <= n; dj++) for (int di = -n; di <= n; di++) if (hypot(di * P, dj * P) <= e + P * 1.5 && (di || dj)) s.push_back({di, dj});   // +1.5 P keeps the full clearance between grid points too
  return s;
}
// status of a cell for a trace of the routing net: 0 blocked, 1 free, 2 free only by ripping
static inline int cellStatus(int l, int c, bool strict) {
  if (baseH[l][c]) return ownStamp[l][c] == ownGen ? 1 : 0;
  if (baseS[l][c]) return strict ? 0 : 2;
  return 1;
}
static inline int wideStatus(int l, int i, int j, const vector<pair<int,int>>& st, bool strict) {
  int res = 1;
  for (auto& d : st) { int a = i + d.first, b = j + d.second; if (a < 0 || b < 0 || a >= NX || b >= NY) return 0; int c = b * NX + a;
    if (baseH[l][c] && ownStamp[l][c] != ownGen) return 0; if (baseS[l][c]) { if (strict) return 0; res = 2; } }
  return res;
}
static inline int viaStatus(int c, bool strict) {
  if (padmask[c] || vvH[c]) return 0; int res = 1;
  if (vvS[c]) { if (strict) return 0; res = 2; }
  for (int l = 0; l < NL; l++) { if (viaH[l][c]) return 0; if (viaS[l][c]) { if (strict) return 0; res = 2; } }
  return res;
}

struct SearchResult { bool ok = false; vector<u32> path; vector<u8> neck; bool planeGoal = false; long expanded = 0; };   // neck[k] = width level at node k (0 = full width)

// Width levels of a wide net: full width first, then narrower fall-backs down to 0.1 mm. The search uses the
// widest level that fits at each cell (narrower costs more), so a power trace only necks as far as it must.
static vector<vector<double>> levelW;                     // per net
static vector<vector<vector<pair<int,int>>>> levelSt;     // per net, per level: cells to test (empty for 0.1 mm)
static const int LEVEL_MULT[4] = {10, 13, 18, 30};
static int NECK_SCALE = 1;                                    // --neck N: how much dearer a narrower level is (partial runs use more)
static vector<vector<u8>> band; static bool bandOn = false;
static bool roomOn = false; static vector<pair<int,int>> roomSt;   // first line of a pair: is there room for its partner at one pitch?
static vector<vector<u8>> halo;                               // cells within 0.6 mm of a pad   // follower of a USB pair: cells beside the leader

// A* from marked sources to marked targets (or, for plane nets, to any cell where a via reaches the plane).
// par[] byte: low 4 bits = move (0-7 direction, 8+l via from layer l, 15 source), bits 4-6 = width level.
static SearchResult astar(const vector<u32>& sources, int netId, bool strict, double tx, double ty, bool haveTarget, long budget, int planeIdx) {
  SearchResult R; Net& net = nets[netId];
  const auto& LS = levelSt[netId]; int nlev = LS.size(); bool wide = nlev > 1;
  int bottomMult = net.pair >= 0 ? 20 : 10;                  // pairs prefer the top layer (solid GND plane right below)
  int viaCost = net.pair >= 0 ? VIA_COST * 3 : VIA_COST;
  int ripBase = net.pair >= 0 ? RIP_COST / 5 : RIP_COST;      // pairs have right of way: ordinary copper in their path is ripped and goes round or under
  gen++; if (gen == 0) { fill(gstamp.begin(), gstamp.end(), 0); gen = 1; }
  priority_queue<HeapItem> pq;
  int ti = haveTarget ? ci(tx) : 0, tj = haveTarget ? cj(ty) : 0;
  auto h = [&](int i, int j) -> u32 { if (!haveTarget) return 0; int dx = abs(i - ti), dy = abs(j - tj); int mn = min(dx, dy), mx = max(dx, dy); return (u32)(DIAGC * mn + STEP * (mx - mn)); };
  // widest level that fits at (l, i, j); returns nlev-1 (0.1 mm) when nothing wider does
  bool exactTop = wide && net.pair >= 0 && RPW > 0;   // pair line: exact counters for the full width
  auto levelAt = [&](int l, int i, int j, int stt) -> int {
    // full width fits; or (pairs have right of way) only ordinary routed copper is in the way and gets ripped.
    // Next to other pair copper, the partner included, the full clearance always holds.
    if (exactTop) { int c = j * NX + i; if (!pwH[l][c] && (!pwS[l][c] || (!strict && (stt == 2 || !pairMark[l][c])))) return 0; }
    for (int k = exactTop ? 1 : 0; k + 1 < nlev; k++) { int ws = wideStatus(l, i, j, LS[k], strict); if (ws == 1 || (ws == 2 && stt == 2)) return k; }
    return nlev - 1; };
  auto roomAt = [&](int l, int i, int j) -> bool {
    for (auto& d : roomSt) { int a = i + d.first, b = j + d.second; if (a < 0 || b < 0 || a >= NX || b >= NY) return false; int c = b * NX + a;
      if ((pwH[l][c] && ownStamp[l][c] != ownGen) || pwS[l][c]) return false; }
    return true; };
  for (u32 s : sources) { if (gstamp[s] == gen) continue; gstamp[s] = gen; gsc[s] = 0; par[s] = 15; int c = s % NC; pq.push({h(c % NX, c / NX), 0, s}); }
  const u32 GOAL = (u32)NL * NC;       // virtual plane node
  u32 goalNode = UINT32_MAX, goalFrom = 0; u32 bestGoalG = UINT32_MAX;
  while (!pq.empty()) {
    HeapItem it = pq.top(); pq.pop();
    if (it.node == GOAL) { goalNode = goalFrom; R.planeGoal = true; break; }
    if (it.g != gsc[it.node]) continue;
    u32 node = it.node; int l = node / NC, c = node % NC, i = c % NX, j = c / NX;
    if (infoKind[node] == 2) { goalNode = node; break; }
    if (++R.expanded > budget) break;
    u32 g = it.g;
    if (planeIdx >= 0 && planeOK[planeIdx][c]) {      // plane net: drop a via here
      int vs = viaStatus(c, strict);
      if (vs) { u32 ng = g + viaCost + (vs == 2 ? RIP_COST * 4 : 0); if (ng < bestGoalG) { bestGoalG = ng; goalFrom = node; pq.push({ng, ng, GOAL}); } }
    }
    int lm = (RLs[l] == (int)layerNames.size() - 1) ? bottomMult : 10;
    for (int d = 0; d < 8; d++) {
      int a = i + DX[d], b = j + DY[d]; if (a < 0 || b < 0 || a >= NX || b >= NY) continue;
      int c2 = b * NX + a; u32 n2 = (u32)l * NC + c2;
      int stt = cellStatus(l, c2, strict); if (!stt) continue;
      int m = mult[l][c2]; int lev = 0;
      if (wide) { lev = levelAt(l, a, b, stt); if (lev && ownStamp[l][c2] != ownGen) m = m * (10 + (LEVEL_MULT[min(lev + (4 - nlev), 3)] - 10) * NECK_SCALE) / 10; }
      if (bandOn && !band[l][c2]) m *= 8;            // dearer than ripping ordinary copper out of the band
      if (roomOn && lev == 0 && ownStamp[l][c2] != ownGen && !roomAt(l, a, b)) m *= 4;   // first line of a pair: keep room beside it for the second
      u32 cost = (u32)((d & 1 ? DIAGC : STEP) * m * lm / 100);
      if (stt == 2) cost += (pairMark[l][c2] ? (bandOn && band[l][c2] ? RIP_COST * 6 : RIP_COST * 40) : ripBase) + 30 * hist[l][c2];   // partner 6x, any other pair 40x   // pair copper: last resort; even its partner should via under it first
      u32 ng = g + cost;
      if (gstamp[n2] == gen && gsc[n2] <= ng) continue;
      gstamp[n2] = gen; gsc[n2] = ng; par[n2] = (u8)d | (lev << 4); pq.push({ng + h(a, b), ng, n2});
    }
    if (NL > 1 && !net.novia) {                       // via to the other routing layers
      int vs = -1;
      for (int l2 = 0; l2 < NL; l2++) if (l2 != l) {
        u32 n2 = (u32)l2 * NC + c; if (gstamp[n2] == gen && gsc[n2] <= g + viaCost) continue;
        if (vs < 0) vs = viaStatus(c, strict); if (!vs) break;
        u32 ng = g + viaCost + (vs == 2 ? (pairMark[l][c] ? (bandOn && band[l][c] ? RIP_COST * 12 : RIP_COST * 60) : ripBase * 4) : 0);
        if (gstamp[n2] == gen && gsc[n2] <= ng) continue;
        int lev = wide ? levelAt(l2, i, j, cellStatus(l2, c, strict)) : 0;   // widest trace that fits where the via lands
        gstamp[n2] = gen; gsc[n2] = ng; par[n2] = (u8)(8 + l) | (lev << 4); pq.push({ng + h(i, j), ng, n2});
      }
    }
  }
  if (goalNode == UINT32_MAX) return R;
  R.ok = true; u32 n = goalNode;
  while (true) { R.path.push_back(n); u8 p = par[n]; if (p == 15) { R.neck.push_back(nlev - 1); break; } R.neck.push_back(p >> 4); int code = p & 15;
    if (code >= 8) { n = (u32)(code - 8) * NC + n % NC; } else { int c = n % NC, l = n / NC; n = (u32)l * NC + (c - DX[code] - DY[code] * NX); } }
  reverse(R.path.begin(), R.path.end()); reverse(R.neck.begin(), R.neck.end());
  return R;
}

// ---------------- net bookkeeping ----------------
static void exempt(int n, int d) {   // d=-1 remove own copper from the grids, +1 put it back
  for (auto& s : fixedShapes[n]) markShape(s, d, false);
  for (int r : nets[n].routes) if (routes[r].alive) { for (auto& s : routes[r].shapes) markShape(s, d, !routes[r].frozen); }
}
static void stampOwn(int n) {
  ownGen++;
  for (int p : nets[n].pads) { Pad& pd = pads[p]; if (pd.kind == 1) continue;
    for (int l = 0; l < NL; l++) if (pd.mask & (1 << RLs[l])) forRect(pd.cx, pd.cy, pd.w / 2, pd.h / 2, 1e-6 + 0.0001, [&](int c) { ownStamp[l][c] = ownGen; }); }
}
static void killRoute(int r) {
  Route& R = routes[r]; if (!R.alive) return;
  markRoute(R, -1); R.alive = false;
  for (int q : nets[R.net].routes) if (routes[q].alive && (routes[q].joinA == r || routes[q].joinB == r)) killRoute(q);
}
static vector<int> ufp;
static int uff(int x) { while (ufp[x] != x) x = ufp[x] = ufp[ufp[x]]; return x; }

static long totalExpanded = 0; static int ripEvents = 0;
static deque<int> *queuePtr = nullptr; static vector<char> inQueue;
static chrono::steady_clock::time_point T0; static double TIME_LIMIT = 600;
static double elapsed() { return chrono::duration<double>(chrono::steady_clock::now() - T0).count(); }
static int MAXRIP = 6;


static Shape capsule(double ax, double ay, double bx, double by, double hw, u8 mask) { return Shape{1, mask, ax, ay, bx, by, hw, 0}; }

// Build a Route from a node path. Returns route id.
static int commitRoute(int netId, const SearchResult& S, int pinA, int joinA, int pinB, int joinB, bool plane) {
  Net& net = nets[netId]; Route R; R.net = netId; R.pinA = pinA; R.pinB = pinB; R.joinA = joinA; R.joinB = joinB; R.plane = plane; R.alive = true; R.frozen = net.frozen;
  u8 allMask = 0; for (int l = 0; l < NL; l++) allMask |= 1 << RLs[l];
  struct Raw { double x, y; int l; double w; };
  vector<Raw> raw;                                    // w = widest trace that fits at this point
  if (pinA >= 0) raw.push_back({pins[pinA].x, pins[pinA].y, (int)(S.path[0] / NC), 0.1});
  for (size_t k = 0; k < S.path.size(); k++) { u32 n = S.path[k]; int l = n / NC, c = n % NC;
    raw.push_back({cx(c % NX), cy(c / NX), l, levelW[netId][S.neck[k]]}); R.nodes.push_back(n); }
  if (pinB >= 0) raw.push_back({pins[pinB].x, pins[pinB].y, raw.back().l, 0.1});
  // polyline: Pt.w is the width of the segment ENDING at the point (a segment is wide only if both ends fit wide);
  // collinear segments of equal width are merged.
  auto addVia = [&](double x, double y, int l) { R.pts.push_back({x, y, l, VIA_D, true}); R.vias.push_back({x, y}); R.shapes.push_back(capsule(x, y, x, y, VIA_R, allMask)); };
  for (size_t k = 0; k < raw.size(); k++) { Raw& q = raw[k];
    if (k == 0) { R.pts.push_back({q.x, q.y, q.l, q.w, false}); continue; }
    Raw& p = raw[k - 1];
    if (p.l != q.l) { addVia(q.x, q.y, q.l); R.pts.push_back({q.x, q.y, q.l, q.w, false}); continue; }
    if (fabs(p.x - q.x) < 1e-9 && fabs(p.y - q.y) < 1e-9) continue;
    double sw = min(p.w, q.w); size_t n = R.pts.size();
    if (n >= 2 && !R.pts[n - 1].via && !R.pts[n - 2].via && R.pts[n - 2].l == q.l && fabs(R.pts[n - 1].w - sw) < 1e-9) {
      Pt& a = R.pts[n - 2]; Pt& m = R.pts[n - 1]; double cr = (m.x - a.x) * (q.y - m.y) - (m.y - a.y) * (q.x - m.x), dt = (m.x - a.x) * (q.x - m.x) + (m.y - a.y) * (q.y - m.y);
      if (fabs(cr) < 1e-9 && dt > 0) { m.x = q.x; m.y = q.y; continue; } }
    R.pts.push_back({q.x, q.y, q.l, sw, false});
  }
  for (size_t k = 1; k < R.pts.size(); k++) { Pt& a = R.pts[k - 1]; Pt& b = R.pts[k]; if (!a.via && !b.via && a.l == b.l) R.shapes.push_back(capsule(a.x, a.y, b.x, b.y, b.w / 2, 1 << RLs[a.l])); }
  if (plane && S.planeGoal) { u32 last = S.path.back(); int lc = last % NC; addVia(cx(lc % NX), cy(lc / NX), -1); }
  for (auto& v : R.vias) { int c = cj(v.second) * NX + ci(v.first); for (int l = 0; l < NL; l++) R.nodes.push_back((u32)l * NC + c); }   // via cells join the tree on every layer
  // Copper clearance marks are added when the net's routing call ends (exempt +1). The via-spacing and
  // pair marks are not part of that exemption, so they go in now (markRoute removes all three on rip-up).
  for (auto& v : R.vias) markVia(v.first, v.second, +1, !R.frozen);
  markPair(R, +1);
  int id = routes.size(); routes.push_back(R); net.routes.push_back(id);
  return id;
}

static double ptSegDist(double px, double py, const Shape& s) {
  if (s.type == 0) { double dx = max(fabs(px - s.ax) - s.bx, 0.0), dy = max(fabs(py - s.ay) - s.by, 0.0); return hypot(dx, dy); }
  double vx = s.bx - s.ax, vy = s.by - s.ay, L2 = vx * vx + vy * vy; double t = L2 > 0 ? ((px - s.ax) * vx + (py - s.ay) * vy) / L2 : 0; t = t < 0 ? 0 : t > 1 ? 1 : t;
  return hypot(px - (s.ax + t * vx), py - (s.ay + t * vy));
}
static double segSegDist(const Shape& a, const Shape& b) {   // capsule centre lines (sampled; segments are short)
  auto d1 = [&](double t) { return ptSegDist(a.ax + (a.bx - a.ax) * t, a.ay + (a.by - a.ay) * t, b); };
  auto d2 = [&](double t) { return ptSegDist(b.ax + (b.bx - b.ax) * t, b.ay + (b.by - b.ay) * t, a); };
  double La = hypot(a.bx - a.ax, a.by - a.ay), Lb = hypot(b.bx - b.ax, b.by - b.ay); int na = max(1, (int)(La / 0.04)), nb = max(1, (int)(Lb / 0.04)); double best = 1e9;
  for (int k = 0; k <= na; k++) best = min(best, d1((double)k / na)); for (int k = 0; k <= nb; k++) best = min(best, d2((double)k / nb)); return best;
}
// routes of other nets whose copper is closer than the rule to the new route's copper
static void findConflicts(const Route& R, vector<int>& out) {
  double xa = 1e9, ya = 1e9, xb = -1e9, yb = -1e9;
  for (auto& s : R.shapes) { xa = min({xa, s.ax, s.bx}); xb = max({xb, s.ax, s.bx}); ya = min({ya, s.ay, s.by}); yb = max({yb, s.ay, s.by}); }
  for (size_t q = 0; q < routes.size(); q++) { Route& Q = routes[q]; if (!Q.alive || Q.net == R.net || Q.frozen) continue;
    bool hit = false;
    for (auto& t : Q.shapes) { if (min(t.ax, t.bx) > xb + 1 || max(t.ax, t.bx) < xa - 1 || min(t.ay, t.by) > yb + 1 || max(t.ay, t.by) < ya - 1) continue;
      for (auto& s : R.shapes) { if (!(s.mask & t.mask)) continue; double lim = s.hw + t.hw + CLR + GUARD * 0.5;
        if (min(t.ax, t.bx) > max(s.ax, s.bx) + lim || max(t.ax, t.bx) < min(s.ax, s.bx) - lim || min(t.ay, t.by) > max(s.ay, s.by) + lim || max(t.ay, t.by) < min(s.ay, s.by) - lim) continue;
        if (segSegDist(s, t) < lim) { hit = true; break; } }
      if (hit) break; }
    if (!hit) for (auto& v : R.vias) { for (auto& u : Q.vias) if (hypot(v.first - u.first, v.second - u.second) < VV_R) { hit = true; break; } if (hit) break; }
    if (hit) out.push_back(q);
  }
}

static void markInfo(u32 node, u8 kind, int val) { infoKind[node] = kind; info[node] = val; }
static void clearInfo(const vector<u32>& nodes) { for (u32 n : nodes) infoKind[n] = 0; }

static bool routeNet(int netId, bool allowRip) {
  Net& net = nets[netId]; if (net.pins.size() < (net.plane ? 1u : 2u)) return true;
  exempt(netId, -1); stampOwn(netId);
  // USB pair: every cell that is not right beside the partner's copper costs 8x, so the two lines run side by side
  vector<pair<int,int>> bandCells;
  // band = cells no farther from the partner's centre line than the closest legal pitch (+0.04 mm), so the
  // only cheap place for this line is exactly one pitch away from its partner
  double bandR = ceil((net.w + CLR + GUARD) / P - 1e-9) * P + 0.04;
  if (net.pair >= 0) for (int m = 0; m < (int)nets.size(); m++) if (m != netId && nets[m].pair == net.pair)
    for (int r : nets[m].routes) if (routes[r].alive) for (auto& sh : routes[r].shapes) for (int l = 0; l < NL; l++) if (sh.mask & (1 << RLs[l]))
      forShape(sh, sh.type == 1 && sh.ax == sh.bx && sh.ay == sh.by ? 0.9 : bandR, [&](int c) { if (!band[l][c]) { band[l][c] = 1; bandCells.push_back({l, c}); } });
  bandOn = !bandCells.empty();
  roomOn = net.pair >= 0 && !bandOn && RPW > 0;      // no partner copper yet: this is the first line of the pair
  int planeIdx = -1; if (net.plane) for (size_t k = 0; k < planeNet.size(); k++) if (planeNet[k] == netId) planeIdx = k;
  bool allOk = true; int np = net.pins.size(); vector<int> skip;   // pins whose component could not be connected in this call
  auto padNodes = [&](int pinId, vector<u32>& out) {
    Pin& pn = pins[pinId]; bool any = false;
    if (pn.pad >= 0) { Pad& pd = pads[pn.pad];
      for (int l = 0; l < NL; l++) if (pd.mask & (1 << RLs[l])) forRect(pd.cx, pd.cy, max(pd.w / 2 - 0.06, 0.0), max(pd.h / 2 - 0.06, 0.0), 0.0005, [&](int c) { out.push_back((u32)l * NC + c); any = true; }); }
    if (!any) for (int l = 0; l < NL; l++) if (pn.mask & (1 << RLs[l])) out.push_back((u32)l * NC + cj(pn.y) * NX + ci(pn.x));
    // always include the cell nearest the pin itself
    for (int l = 0; l < NL; l++) if (pn.mask & (1 << RLs[l]) || (pn.pad >= 0 && (pads[pn.pad].mask & (1 << RLs[l])))) out.push_back((u32)l * NC + cj(pn.y) * NX + ci(pn.x));
  };
  for (int guard = 0; guard < np * 4 + 4; guard++) {
    if (elapsed() > TIME_LIMIT) { allOk = false; break; }
    // components
    int PL = np;                       // plane node
    ufp.assign(np + 1 + net.routes.size(), 0); for (size_t k = 0; k < ufp.size(); k++) ufp[k] = k;
    map<int,int> pinLocal; for (int k = 0; k < np; k++) pinLocal[net.pins[k]] = k;
    map<int,int> routeLocal; for (size_t k = 0; k < net.routes.size(); k++) routeLocal[net.routes[k]] = np + 1 + k;
    auto uni = [&](int a, int b) { a = uff(a); b = uff(b); if (a != b) ufp[a] = b; };
    for (size_t k = 0; k < net.routes.size(); k++) { Route& R = routes[net.routes[k]]; if (!R.alive) continue; int me = np + 1 + k;
      if (R.pinA >= 0) uni(me, pinLocal[R.pinA]); if (R.pinB >= 0) uni(me, pinLocal[R.pinB]); if (R.joinA >= 0) uni(me, routeLocal[R.joinA]); if (R.joinB >= 0) uni(me, routeLocal[R.joinB]); if (R.plane) uni(me, PL); }
    if (net.plane) for (int k = 0; k < np; k++) { Pin& pn = pins[net.pins[k]]; if (pn.pad >= 0 && (pads[pn.pad].mask & (1 << net.planeLayer))) uni(k, PL); }
    // pick a source component
    int src = -1;
    if (net.plane) { for (int k = 0; k < np; k++) if (uff(k) != uff(PL) && find(skip.begin(), skip.end(), k) == skip.end()) { src = uff(k); break; } }
    else if (net.pair >= 0) { bool sk = false; for (int k : skip) if (uff(k) == uff(0)) sk = true;      // pair: grow from the host pin (first pin)
      for (int k = 1; k < np && !sk; k++) if (uff(k) != uff(0)) { src = uff(0); break; }
      if (src < 0 && !sk) for (size_t k = 0; k < net.routes.size(); k++) if (routes[net.routes[k]].alive && routes[net.routes[k]].mid && uff(np + 1 + k) != uff(0)) { src = uff(0); break; } }
    else { map<int,int> cnt; for (int k = 0; k < np; k++) cnt[uff(k)]++;
      if (cnt.size() > 1) { int best = 1 << 30; for (auto& kv : cnt) { bool sk = false; for (int k : skip) if (uff(k) == kv.first) sk = true; if (!sk && kv.second < best) { best = kv.second; src = kv.first; } } } }
    if (src < 0) break;
    vector<u32> sources, marked; double sx = 0, sy = 0; int sn = 0;
    // targets first, sources second: copper of this net may already cross a source pad, and a source must stay a source
    for (int k = 0; k < np; k++) if (uff(k) != src && !net.plane) { vector<u32> tmp; padNodes(net.pins[k], tmp); for (u32 n : tmp) { markInfo(n, 2, net.pins[k]); marked.push_back(n); } }
    for (size_t k = 0; k < net.routes.size(); k++) { Route& R = routes[net.routes[k]]; if (!R.alive) continue; int comp = uff(np + 1 + k);
      if (comp != src && (!net.plane || comp == uff(PL))) for (u32 n : R.nodes) { markInfo(n, 2, -2 - net.routes[k]); marked.push_back(n); } }
    if (net.plane) for (int p : net.pads) if (pads[p].kind == 2) { int c = cj(pads[p].cy) * NX + ci(pads[p].cx); for (int l = 0; l < NL; l++) { u32 n = (u32)l * NC + c; markInfo(n, 2, -1); marked.push_back(n); } }
    for (int k = 0; k < np; k++) if (uff(k) == src) { vector<u32> tmp; padNodes(net.pins[k], tmp); for (u32 n : tmp) { sources.push_back(n); markInfo(n, 1, net.pins[k]); marked.push_back(n); } sx += pins[net.pins[k]].x; sy += pins[net.pins[k]].y; sn++; }
    for (size_t k = 0; k < net.routes.size(); k++) { Route& R = routes[net.routes[k]]; if (!R.alive) continue;
      if (uff(np + 1 + k) == src) for (u32 n : R.nodes) { sources.push_back(n); markInfo(n, 1, -2 - net.routes[k]); marked.push_back(n); } }
    // heuristic target: nearest pin of another component
    double tx = 0, ty = 0; bool haveT = false;
    if (!net.plane) { sx /= sn; sy /= sn; double best = 1e18; for (int k = 0; k < np; k++) if (uff(k) != src) { double d = hypot(pins[net.pins[k]].x - sx, pins[net.pins[k]].y - sy); if (d < best) { best = d; tx = pins[net.pins[k]].x; ty = pins[net.pins[k]].y; haveT = true; } } }
    SearchResult S; bool ripped = false;
    if (net.pair < 0 || !allowRip) { S = astar(sources, netId, true, tx, ty, haveT, 3000000, planeIdx); totalExpanded += S.expanded; }
    if (!S.ok && allowRip) { S = astar(sources, netId, false, tx, ty, haveT, 6000000, planeIdx); totalExpanded += S.expanded; ripped = true; }
    if (!S.ok) { clearInfo(marked); allOk = false; for (int k = 0; k < np; k++) if (uff(k) == src) skip.push_back(k); continue; }
    u32 a = S.path.front(), b = S.path.back(); int pinA = -1, joinA = -1, pinB = -1, joinB = -1; bool plane = false;
    if (info[a] >= 0) pinA = info[a]; else joinA = -2 - info[a];
    if (S.planeGoal) plane = true; else if (infoKind[b] == 2) { if (info[b] >= 0) pinB = info[b]; else if (info[b] == -1) plane = true; else { joinB = -2 - info[b]; } }
    if (net.plane && !S.planeGoal && infoKind[b] == 2 && info[b] <= -2) { /* joined a plane-connected stub */ }
    clearInfo(marked);
    int rid = commitRoute(netId, S, pinA, joinA, pinB, joinB, plane);
    vector<int> conf; if (ripped) findConflicts(routes[rid], conf);
    if (!conf.empty()) {
      ripEvents++;
      for (u32 n : S.path) { int l = n / NC, c = n % NC; if (baseS[l][c] && hist[l][c] < 240) hist[l][c] += 6; }
      for (int q : conf) { int m = routes[q].net; if (nets[m].pair >= 0 && getenv("FR_DEBUG")) fprintf(stderr, "    pair net %s ripped by %s\n", nets[m].name.c_str(), net.name.c_str()); killRoute(q); nets[m].rips++; if (!inQueue[m]) { inQueue[m] = 1; queuePtr->push_back(m); } }
    }
  }
  // put own copper back (routes created above are not marked yet: exempt() re-adds every alive route)
  bandOn = false; roomOn = false; for (auto& lc : bandCells) band[lc.first][lc.second] = 0;
  exempt(netId, +1);
  // newly created routes were never marked before; exempt(+1) marked all alive routes once, which is right
  // because exempt(-1) at the start only removed the ones alive then, and killed ones were unmarked by killRoute.
  net.failed = !allOk;
  return allOk;
}

int main(int argc, char** argv) {
  if (argc < 3) { fprintf(stderr, "usage: fastroute in.txt out.txt [--time s] [--order file]\n"); return 2; }
  int seed = 1; for (int a = 3; a + 1 < argc; a += 2) { string k = argv[a]; if (k == "--time") TIME_LIMIT = atof(argv[a + 1]); else if (k == "--seed") seed = atoi(argv[a + 1]); else if (k == "--via") VIA_COST = atoi(argv[a + 1]); else if (k == "--rip") RIP_COST = atoi(argv[a + 1]); else if (k == "--maxrip") MAXRIP = atoi(argv[a + 1]); else if (k == "--neck") NECK_SCALE = atoi(argv[a + 1]); }
  T0 = chrono::steady_clock::now();
  ifstream in(argv[1]); string line; memset(rlOfLayer, -1, sizeof rlOfLayer);
  struct PairJob { int k, nP, nN; double sx, sy; int ux, uy; double tx, ty; int ax, ay, pLeft, ok, grp = 0; };
  vector<PairJob> pairJobs;
  struct FixSeg { int net, layer; double x1, y1, x2, y2, w; }; struct FixVia { int net; double x, y; };
  vector<FixSeg> fixSegs; vector<FixVia> fixVias; vector<int> only;
  struct PrePt { double x, y; int layer; double w; bool via; }; struct PreRoute { int net, pinA, pinB, plane; vector<PrePt> pts; };
  vector<PreRoute> preRoutes; vector<int> thermalPads;
  while (getline(in, line)) { istringstream ss(line); string t; ss >> t;
    if (t == "G") { ss >> X0 >> Y0 >> X1 >> Y1 >> P; }
    else if (t == "RULE") { ss >> CLR >> VIA_D >> VIA_HOLE >> EDGE >> HOLECLR; }
    else if (t == "L") { string s; while (ss >> s) layerNames.push_back(s); }
    else if (t == "RL") { int k; while (ss >> k) { rlOfLayer[k] = RLs.size(); RLs.push_back(k); } }
    else if (t == "N") { Net n; int id, pl; ss >> id >> n.name >> n.w >> pl >> n.planeLayer >> n.pair >> n.novia >> n.maxLen; n.plane = pl; nets.push_back(n); }
    else if (t == "PAD") { Pad p; int m; ss >> p.net >> m >> p.cx >> p.cy >> p.w >> p.h >> p.kind >> p.circle; p.mask = m; if (p.net >= 0) nets[p.net].pads.push_back(pads.size()); pads.push_back(p); }
    else if (t == "PIN") { Pin p; int m; ss >> p.net >> p.x >> p.y >> m >> p.pad; p.mask = m; nets[p.net].pins.push_back(pins.size()); pins.push_back(p); }
    else if (t == "POUR") { Pour p; int l, n; ss >> p.net >> l >> n; for (int k = 0; k < n; k++) { double x, y; ss >> x >> y; p.poly.push_back({x, y}); } pours.push_back(p); }
    else if (t == "PLANE") { int net, n; ss >> net >> n; vector<pair<double,double>> poly; for (int k = 0; k < n; k++) { double x, y; ss >> x >> y; poly.push_back({x, y}); } planeNet.push_back(net); planePoly.push_back(poly); }
    else if (t == "PAIRJOB") { PairJob j; ss >> j.k >> j.nP >> j.nN >> j.sx >> j.sy >> j.ux >> j.uy >> j.tx >> j.ty >> j.ax >> j.ay >> j.pLeft >> j.ok >> j.grp; pairJobs.push_back(j); }
    else if (t == "FIX") { FixSeg f; ss >> f.net >> f.layer >> f.x1 >> f.y1 >> f.x2 >> f.y2 >> f.w; fixSegs.push_back(f); }
    else if (t == "FIXV") { FixVia f; ss >> f.net >> f.x >> f.y; fixVias.push_back(f); }
    else if (t == "ONLY") { int k; while (ss >> k) only.push_back(k); }
    else if (t == "TPAD") { int k; ss >> k; thermalPads.push_back(k); }
    else if (t == "KT") { PreRoute r; ss >> r.net >> r.pinA >> r.pinB >> r.plane; preRoutes.push_back(r); }
    else if (t == "kw") { PrePt q; ss >> q.x >> q.y >> q.layer >> q.w; q.via = false; preRoutes.back().pts.push_back(q); }
    else if (t == "kv") { PrePt q; ss >> q.x >> q.y >> q.layer; q.w = 0; q.via = true; preRoutes.back().pts.push_back(q); }
    else if (t == "OUT") { int n; ss >> n; for (int k = 0; k < n; k++) { double x, y; ss >> x >> y; outline.push_back({x, y}); } }
  }
  NL = RLs.size(); NX = (int)lround((X1 - X0) / P) + 1; NY = (int)lround((Y1 - Y0) / P) + 1; NC = NX * NY;
  VIA_R = VIA_D / 2; R0 = CLR + GUARD + 0.05; RV = CLR + GUARD + VIA_R;
  for (auto& n : nets) if (n.pair >= 0 && n.w > 0.1001) PAIR_W = max(PAIR_W, n.w);
  if (PAIR_W > 0) RPW = CLR + GUARD + PAIR_W / 2;
  baseH.assign(NL, vector<u16>(NC, 0)); baseS = baseH; viaH = baseH; viaS = baseH; if (RPW > 0) { pwH = baseH; pwS = baseH; } vvH.assign(NC, 0); vvS.assign(NC, 0); padmask.assign(NC, 0);
  mult.assign(NL, vector<u8>(NC, 10)); hist.assign(NL, vector<u8>(NC, 0)); ownStamp.assign(NL, vector<u32>(NC, 0));
  gsc.assign((size_t)NL * NC + 1, 0); gstamp.assign((size_t)NL * NC + 1, 0); par.assign((size_t)NL * NC + 1, 0); infoStamp.assign((size_t)NL * NC, 0); info.assign((size_t)NL * NC, 0); infoKind.assign((size_t)NL * NC, 0);
  int NN = nets.size(); fixedShapes.assign(NN + 1, {}); u8 allMask = 0; for (int l = 0; l < NL; l++) allMask |= 1 << RLs[l];
  // fixed copper
  for (auto& p : pads) { Shape s; s.mask = p.mask; s.extra = 0;
    if (p.circle || p.kind == 2) { s.type = 1; s.ax = s.bx = p.cx; s.ay = s.by = p.cy; s.hw = p.w / 2; } else { s.type = 0; s.ax = p.cx; s.ay = p.cy; s.bx = p.w / 2; s.by = p.h / 2; s.hw = 0; }
    if (p.kind == 1) s.extra = HOLECLR - CLR;
    fixedShapes[p.net >= 0 ? p.net : NN].push_back(s);
    if (p.kind == 0 && !(p.mask == allMask && false)) { if (p.circle) forSeg(p.cx, p.cy, p.cx, p.cy, p.w / 2 + VIA_R + 0.01, [&](int c) { padmask[c] = 1; }); else forRect(p.cx, p.cy, p.w / 2, p.h / 2, VIA_R + 0.01, [&](int c) { padmask[c] = 1; }); }
    if (p.kind == 2) markVia(p.cx, p.cy, +1, false);
    if (p.kind == 1) forSeg(p.cx, p.cy, p.cx, p.cy, p.w / 2 + 0.15 + VIA_HOLE / 2 + GUARD, [&](int c) { vvH[c]++; });
  }
  // existing copper of nets that are not being routed in this run (partial runs)
  for (auto& f : fixSegs) if (rlOfLayer[f.layer] >= 0) fixedShapes[f.net].push_back(capsule(f.x1, f.y1, f.x2, f.y2, f.w / 2, 1 << f.layer));
  for (auto& f : fixVias) { fixedShapes[f.net].push_back(capsule(f.x, f.y, f.x, f.y, VIA_R, allMask)); markVia(f.x, f.y, +1, false); }
  // board edge: cells outside the outline or closer than the edge clearance
  for (size_t k = 0; k < outline.size(); k++) { auto a = outline[k], b = outline[(k + 1) % outline.size()]; Shape s = capsule(a.first, a.second, b.first, b.second, 0, allMask); s.extra = EDGE - CLR; fixedShapes[NN].push_back(s); }
  for (int j = 0; j < NY; j++) for (int i = 0; i < NX; i++) { double x = cx(i), y = cy(j); if ((x < X0 + 2.5 || x > X1 - 2.5) && (y < Y0 + 2.5 || y > Y1 - 2.5) && !inPoly(outline, x, y)) { for (int l = 0; l < NL; l++) { baseH[l][j * NX + i] += 1000; viaH[l][j * NX + i] += 1000; if (RPW > 0) pwH[l][j * NX + i] += 1000; } } }
  for (int n = 0; n <= NN; n++) for (auto& s : fixedShapes[n]) markShape(s, +1, false);
  // top power pours: expensive for other nets
  // (not blocked: pads of other nets inside a pour still have to get out)
  static vector<vector<int>> pourOwner; pourOwner.assign(1, vector<int>(NC, -1));
  for (auto& p : pours) { double xa = 1e9, xb = -1e9, ya = 1e9, yb = -1e9; for (auto& q : p.poly) { xa = min(xa, q.first); xb = max(xb, q.first); ya = min(ya, q.second); yb = max(yb, q.second); }
    int l = rlOfLayer[0]; if (l < 0) continue;
    for (int j = max(0, cj(ya)); j <= min(NY - 1, cj(yb)); j++) for (int i = max(0, ci(xa)); i <= min(NX - 1, ci(xb)); i++) if (inPoly(p.poly, cx(i), cy(j))) pourOwner[0][j * NX + i] = p.net; }
  // plane regions (via centre at least 0.5 mm inside the outline)
  for (size_t k = 0; k < planePoly.size(); k++) { vector<u8> ok(NC, 0); auto& poly = planePoly[k];
    for (int j = 0; j < NY; j++) for (int i = 0; i < NX; i++) { double x = cx(i), y = cy(j); if (inPoly(poly, x, y) && distPoly(poly, x, y) > 0.5) ok[j * NX + i] = 1; }
    planeOK.push_back(ok); }
  for (int n = 0; n < NN; n++) { vector<double> ws; double w = nets[n].w;
    if (w > 0.1001) { ws.push_back(w); if (w > 0.3001) ws.push_back(0.3); if (w > 0.2001) ws.push_back(0.2); } ws.push_back(0.1);
    vector<vector<pair<int,int>>> st; for (double x : ws) st.push_back(x > 0.1001 ? makeStencil(x / 2 - 0.05) : vector<pair<int,int>>());
    levelW.push_back(ws); levelSt.push_back(st); }
  if (RPW > 0) { double pitch = ceil((PAIR_W + CLR + GUARD) / P - 1e-9) * P; int n = (int)ceil((pitch + P) / P);
    for (int dj = -n; dj <= n; dj++) for (int di = -n; di <= n; di++) if (hypot(di * P, dj * P) <= pitch + 0.012) roomSt.push_back({di, dj}); }
  band.assign(NL, vector<u8>(NC, 0)); halo.assign(NL, vector<u8>(NC, 0)); pairMark.assign(NL, vector<u8>(NC, 0));
  for (auto& p : pads) if (p.kind == 0) for (int l = 0; l < NL; l++) if (p.mask & (1 << RLs[l])) forRect(p.cx, p.cy, p.w / 2, p.h / 2, 0.6, [&](int c) { halo[l][c] = 1; });
  // kept copper of nets routed in this run (partial runs): fixed routes with their pins and joins
  { map<pair<int,u32>, int> nodeOwner;       // (net, node) -> first kept route that has copper there
    int first = routes.size();
    for (auto& pr : preRoutes) { Route R; R.net = pr.net; R.pinA = pr.pinA; R.pinB = pr.pinB; R.joinA = R.joinB = -1; R.plane = pr.plane; R.alive = true; R.frozen = true; R.pre = true;
      int curL = -1;
      for (auto& q : pr.pts) {
        if (q.via) { R.pts.push_back({q.x, q.y, q.layer < 0 ? -1 : rlOfLayer[q.layer], VIA_D, true}); R.vias.push_back({q.x, q.y}); R.shapes.push_back(capsule(q.x, q.y, q.x, q.y, VIA_R, allMask));
          int c = cj(q.y) * NX + ci(q.x); for (int l = 0; l < NL; l++) R.nodes.push_back((u32)l * NC + c); curL = -1; continue; }
        int l = rlOfLayer[q.layer]; if (l < 0) continue;
        if (curL == l && !R.pts.empty() && !R.pts.back().via) { Pt& a = R.pts.back(); R.shapes.push_back(capsule(a.x, a.y, q.x, q.y, max(q.w, 0.1) / 2, 1 << RLs[l]));
          double L = hypot(q.x - a.x, q.y - a.y); int n = max(1, (int)ceil(L / (P / 2)));
          for (int k = 0; k <= n; k++) { double x = a.x + (q.x - a.x) * k / n, y = a.y + (q.y - a.y) * k / n; int i = ci(x), j = cj(y);
            if (i < 0 || j < 0 || i >= NX || j >= NY || hypot(cx(i) - x, cy(j) - y) > 0.021) continue;      // only cells that sit on the centre line
            u32 node = (u32)l * NC + j * NX + i; if (R.nodes.empty() || R.nodes.back() != node) R.nodes.push_back(node); } }
        R.pts.push_back({q.x, q.y, l, q.w, false}); curL = l; }
      if (R.pts.empty()) continue;
      int id = routes.size(); routes.push_back(R); nets[R.net].routes.push_back(id); markRoute(routes[id], +1);
      for (u32 nd : routes[id].nodes) nodeOwner.insert({{R.net, nd}, id}); }
    // an end that is not on a pin and not in a plane sits on other kept copper of its net: find which
    auto owner = [&](int net, const Pt& q, int self) -> int { int lA = q.l < 0 || q.via ? 0 : q.l, lB = q.l < 0 || q.via ? NL - 1 : q.l; int i0 = ci(q.x), j0 = cj(q.y);
      for (int rad = 0; rad <= 2; rad++) for (int dj = -rad; dj <= rad; dj++) for (int di = -rad; di <= rad; di++) { int i = i0 + di, j = j0 + dj; if (i < 0 || j < 0 || i >= NX || j >= NY) continue;
        for (int l = lA; l <= lB; l++) { auto it = nodeOwner.find({net, (u32)l * NC + j * NX + i}); if (it != nodeOwner.end() && it->second != self) return it->second;
          for (int r : nets[net].routes) if (r != self && routes[r].pre) for (u32 nd : routes[r].nodes) if (nd == (u32)l * NC + j * NX + i) return r; } }
      return -1; };
    int loose = 0;
    for (int id = first; id < (int)routes.size(); id++) { Route& R = routes[id];
      if (R.pinA < 0) { R.joinA = owner(R.net, R.pts.front(), id); if (R.joinA < 0 && R.pts.size() > 1) R.joinA = owner(R.net, R.pts[1], id); if (R.joinA < 0) loose++; }
      if (R.pinB < 0 && !R.plane) { R.joinB = owner(R.net, R.pts.back(), id); if (R.joinB < 0 && R.pts.size() > 1) R.joinB = owner(R.net, R.pts[R.pts.size() - 2], id); if (R.joinB < 0) loose++; } }
    if (!preRoutes.empty()) fprintf(stderr, "kept copper: %zu routes loaded, %d loose end(s)\n", routes.size() - first, loose); }
  fprintf(stderr, "grid %dx%d x%d layers, %d nets, %zu pads, %zu pins, setup %.1fs\n", NX, NY, NL, NN, pads.size(), pins.size(), elapsed());

  // order: pairs, then plane stubs and short nets first
  vector<int> order; for (int n = 0; n < NN; n++) order.push_back(n);
  auto span = [&](int n) { double xa = 1e9, xb = -1e9, ya = 1e9, yb = -1e9; for (int p : nets[n].pins) { xa = min(xa, pins[p].x); xb = max(xb, pins[p].x); ya = min(ya, pins[p].y); yb = max(yb, pins[p].y); } return (xb - xa) + (yb - ya); };
  // 1 nets that may not use vias (crystal), 2 USB pairs, 3 very short local nets, 4 plane stubs, 5 the rest, short first
  vector<double> key(NN); for (int n = 0; n < NN; n++) { double sp = span(n); size_t np = nets[n].pins.size();
    key[n] = nets[n].novia ? -4e6 + sp : nets[n].pair >= 0 ? -3e6 + nets[n].pair * 10 + n * 0.001 : nets[n].plane ? -1e6 + n
           : (sp <= 2.5 && np <= 3) ? -2e6 + sp : sp / max<size_t>(1, np - 1) + (seed > 1 ? (rand() % 100) * 0.01 * seed : 0); }
  sort(order.begin(), order.end(), [&](int a, int b) { return key[a] < key[b]; });
  vector<char> selected(NN, only.empty() ? 1 : 0); for (int n : only) selected[n] = 1;
  // thermal pads: vias inside the pad (see the notes at the top)
  { int made = 0, padsDone = 0;
    for (int pi : thermalPads) { if (pi < 0 || pi >= (int)pads.size()) continue; Pad& pd = pads[pi]; int n = pd.net; if (n < 0 || !nets[n].plane || !selected[n]) continue;
      int pin = -1; for (int q : nets[n].pins) if (pins[q].pad == pi) pin = q; if (pin < 0) continue;
      bool has = false; for (int r : nets[n].routes) if (routes[r].alive && (routes[r].pinA == pin || routes[r].pinB == pin)) has = true; if (has) continue;
      int planeIdx = -1; for (size_t k = 0; k < planeNet.size(); k++) if (planeNet[k] == n) planeIdx = k; if (planeIdx < 0) continue;
      int l0 = -1; for (int l = 0; l < NL; l++) if (pd.mask & (1 << RLs[l])) l0 = l; if (l0 < 0) continue;
      double q = min(pd.w, pd.h) / 2 - 0.65; vector<pair<double,double>> cand; if (q >= 0.3) for (int sx : {-1, 1}) for (int sy : {-1, 1}) cand.push_back({pd.cx + sx * q, pd.cy + sy * q}); else continue;
      exempt(n, -1); bool was = nets[n].frozen; nets[n].frozen = true; int got = 0;
      for (auto& cnd : cand) { int c = cj(cnd.second) * NX + ci(cnd.first); bool ok = planeOK[planeIdx][c] && !vvH[c] && !vvS[c];
        for (int l = 0; l < NL && ok; l++) if (viaH[l][c] || viaS[l][c]) ok = false;
        if (!ok) continue;
        SearchResult S; S.ok = true; S.planeGoal = true; S.path.push_back((u32)l0 * NC + c); S.neck.push_back((u8)(levelW[n].size() - 1));
        commitRoute(n, S, pin, -1, -1, -1, true); got++; }
      nets[n].frozen = was; exempt(n, +1); made += got; padsDone += got > 0; }
    if (!thermalPads.empty()) fprintf(stderr, "thermal pads: %d via(s) placed inside %d pad(s)\n", made, padsDone); }
  { vector<int> o2; for (int n : order) if (selected[n]) o2.push_back(n); order.swap(o2); }
  deque<int> Q(order.begin(), order.end()); queuePtr = &Q; inQueue.assign(NN, 0); for (int n : order) inQueue[n] = 1;
  // Nets with a length limit or a no-via rule (the hub crystal) go first and are then fixed: nothing may rip them.
  for (int n = 0; n < NN; n++) if (nets[n].novia || nets[n].maxLen > 0) nets[n].frozen = true;
  vector<int> pourCells; for (int c = 0; c < NC; c++) if (pourOwner[0][c] >= 0) pourCells.push_back(c);
  auto setPourMult = [&](int n) { int l = rlOfLayer[0]; if (l < 0) return; for (int c : pourCells) mult[l][c] = pourOwner[0][c] != n ? 10 * POUR_MULT : 10; };
  // pour multipliers depend on the net; recompute only when it matters (few pours): keep a per-net bbox test cheap
  // ---------------- USB pair runs as one wide track ----------------
  vector<u32> gF, stF; vector<u8> parF; u32 genF = 0;
  vector<int> midIds;               // mid routes created by the current attempt
  auto fatRoute = [&](const PairJob& job) -> bool {
    int l = rlOfLayer[0]; if (l < 0 || RPW <= 0) return false;
    if (gF.empty()) { gF.assign((size_t)8 * NC, 0); stF.assign((size_t)8 * NC, 0); parF.assign((size_t)8 * NC, 0); }
    exempt(job.nP, -1); exempt(job.nN, -1); setPourMult(job.nP);
    genF++;
    // The two lines sit 4 / 3 cells (axis) or 3 / 2 diagonal steps (diagonal) to the left / right of the track
    // centre, so both line centres are grid cells and the pair-width counters give an exact answer.
    auto pwFree = [&](int i, int j) { if (i < 0 || j < 0 || i >= NX || j >= NY) return false; int cc = j * NX + i; return !pwH[l][cc] && !pwS[l][cc]; };
    auto lineOK = [&](int c, int d) { int i = c % NX, j = c / NX, nx = -DY[d], ny = DX[d]; int a = (d & 1) ? 3 : 4, b = (d & 1) ? 2 : 3;
      return pwFree(i + a * nx, j + a * ny) && pwFree(i - b * nx, j - b * ny); };
    // at a turn the two lines meet at mitre points that are not grid cells: the cells around each must be free
    auto mitreOK = [&](int c, int d1, int d2) { double vx = cx(c % NX), vy = cy(c / NX);
      for (int side = 0; side < 2; side++) {
        auto ex = [&](int d) { double L = hypot(DX[d], DY[d]); return make_pair(DX[d] / L, DY[d] / L); };
        auto off = [&](int d) { double a = side == 0 ? ((d & 1) ? 3 * P * sqrt(2.0) : 4 * P) : -((d & 1) ? 2 * P * sqrt(2.0) : 3 * P); auto e = ex(d); return make_pair(-e.second * a, e.first * a); };
        auto e1 = ex(d1), e2 = ex(d2); auto o1 = off(d1), o2 = off(d2);
        double den = e1.first * e2.second - e1.second * e2.first, t = fabs(den) < 1e-12 ? 0 : ((o2.first - o1.first) * e2.second - (o2.second - o1.second) * e2.first) / den;
        double qx = vx + o1.first + t * e1.first, qy = vy + o1.second + t * e1.second; int qi = ci(qx), qj = cj(qy);
        for (int dj = -1; dj <= 1; dj++) for (int di = -1; di <= 1; di++) if (hypot(cx(qi + di) - qx, cy(qj + dj) - qy) <= 0.045 && !pwFree(qi + di, qj + dj)) return false; }
      return true; };
    auto dirOf = [&](int dx, int dy) { for (int d = 0; d < 8; d++) if (DX[d] == dx && DY[d] == dy) return d; return 0; };
    int d0 = dirOf(job.ux, job.uy), dT = dirOf(job.ax, job.ay);
    int sc = cj(job.sy) * NX + ci(job.sx), tc = cj(job.ty) * NX + ci(job.tx);
    int ti = 0, tj = 0;
    auto stepc = [&](int c, int d, int k) { return c + k * (DX[d] + DY[d] * NX); };
    auto inb = [&](int c, int d, int k) { int i = c % NX + k * DX[d], j = c / NX + k * DY[d]; return i >= 0 && j >= 0 && i < NX && j < NY; };
    auto hF = [&](int c) -> u32 { int dx = abs(c % NX - ti), dy = abs(c / NX - tj); int mn = min(dx, dy), mx = max(dx, dy); return (u32)(DIAGC * mn + STEP * (mx - mn)); };
    auto runOK = [&](int c, int d, int k) { if (!inb(c, d, k)) return false; for (int q = 1; q <= k; q++) if (!lineOK(stepc(c, d, q), d)) return false; return true; };
    // stay away from where the OTHER pairs start and end (6x within 5 mm), so this track does not seal them in
    vector<pair<double,double>> keep; for (auto& o : pairJobs) if (o.k != job.k) { keep.push_back({o.sx, o.sy}); keep.push_back({o.tx, o.ty}); }
    auto nearOther = [&](int cc) { double x = cx(cc % NX), y = cy(cc / NX); for (auto& q : keep) if (fabs(x - q.first) < 5 && fabs(y - q.second) < 5 && hypot(x - q.first, y - q.second) < 5) return true; return false; };
    auto runCost = [&](int c, int d, int k) { u32 t = 0; for (int q = 1; q <= k; q++) { int cc = stepc(c, d, q); t += (u32)((d & 1 ? DIAGC : STEP) * mult[l][cc] * (halo[l][cc] ? 2 : 1) * (nearOther(cc) ? 6 : 1) / 10); } return t; };
    const int K0 = 4; bool found = false; long expanded = 0;
    // other copper may sit right in front of the pins (the hub's crystal traces do): move each end outward,
    // up to 4 mm, to the first spot where the track fits. The ordinary router bridges the gap.
    for (int q = 0; q < 80 && !lineOK(tc, dT) && inb(tc, dT, -1); q++) tc = stepc(tc, dT, -1);
    ti = tc % NX; tj = tc / NX;
    // Start candidates: at the pins, then the first free spot beyond each blocked stretch (the hub has a row of
    // decoupling capacitors right in front of its USB pins). The first candidate that reaches the end wins.
    vector<int> starts; { int c = sc; bool wasOK = false;
      for (int q = 0; q < 80 && inb(c, d0, K0 + 1); q++, c = stepc(c, d0, 1)) { bool ok = lineOK(c, d0) && runOK(c, d0, K0); if (ok && !wasOK) starts.push_back(c); wasOK = ok; } }
    priority_queue<HeapItem> pq;
    u32 goal = (u32)dT * NC + tc;
    for (int startCell : starts) {
    if (found) break;
    sc = startCell; genF++; while (!pq.empty()) pq.pop(); long budget = expanded + 30000000;
    if (lineOK(tc, dT)) { int c = stepc(sc, d0, K0); u32 s = (u32)d0 * NC + c; stF[s] = genF; gF[s] = runCost(sc, d0, K0); parF[s] = 200; pq.push({gF[s] + hF(c), gF[s], s}); }
    while (!pq.empty()) {
      HeapItem it = pq.top(); pq.pop(); u32 s = it.node; if (it.g != gF[s]) continue;
      if (s == goal) { found = true; break; }
      if (++expanded > budget) break;
      int d = s / NC, c = s % NC;
      auto relax = [&](int c2, int d2, u32 ng, u8 code) { u32 s2 = (u32)d2 * NC + c2; if (stF[s2] == genF && gF[s2] <= ng) return; stF[s2] = genF; gF[s2] = ng; parF[s2] = code; pq.push({ng + hF(c2), ng, s2}); };
      if (runOK(c, d, 1)) relax(stepc(c, d, 1), d, it.g + runCost(c, d, 1), 1);
      for (int turn = 0; turn < 2; turn++) { int d2 = turn ? (d + 7) & 7 : (d + 1) & 7; int k = (d2 & 1) ? 3 : 4;   // minimum straight run after a turn: 0.2 mm
        if (lineOK(c, d2) && mitreOK(c, d, d2) && runOK(c, d2, k)) relax(stepc(c, d2, k), d2, it.g + runCost(c, d2, k) + 60, turn ? 3 : 2); }
    }
    }
    bool done = false;
    if (found) {
      // centre-line vertices, from the end back to the start
      vector<pair<int,int>> verts; vector<int> dirs;     // dirs[i] = heading of the segment that ENDS at verts[i] (walking backwards)
      u32 s = goal; verts.push_back({tc % NX, tc / NX}); int curDir = dT;
      while (true) { int d = s / NC, c = s % NC; u8 code = parF[s];
        if (code == 200) { dirs.push_back(curDir); verts.push_back({sc % NX, sc / NX}); break; }
        if (code == 1) { s = (u32)d * NC + stepc(c, d, -1); continue; }
        int k = (d & 1) ? 3 : 4; int pc = stepc(c, d, -k); int pd = code == 2 ? (d + 7) & 7 : (d + 1) & 7;
        dirs.push_back(curDir); verts.push_back({pc % NX, pc / NX}); curDir = pd; s = (u32)pd * NC + pc; }
      reverse(verts.begin(), verts.end()); reverse(dirs.begin(), dirs.end());     // now dirs[i] = heading of segment verts[i] -> verts[i+1]
      int nseg = dirs.size();
      auto offsetLine = [&](bool left) { vector<pair<double,double>> out;
        auto ex = [&](int d) { double L = hypot(DX[d], DY[d]); return make_pair(DX[d] / L, DY[d] / L); };
        auto off = [&](int d) { double a = left ? ((d & 1) ? 3 * P * sqrt(2.0) : 4 * P) : -((d & 1) ? 2 * P * sqrt(2.0) : 3 * P); auto e = ex(d); return make_pair(-e.second * a, e.first * a); };   // a x left normal
        for (int i = 0; i <= nseg; i++) { double vx = cx(verts[i].first), vy = cy(verts[i].second);
          if (i == 0) { auto o = off(dirs[0]); out.push_back({vx + o.first, vy + o.second}); }
          else if (i == nseg) { auto o = off(dirs[nseg - 1]); out.push_back({vx + o.first, vy + o.second}); }
          else { auto e1 = ex(dirs[i - 1]), e2 = ex(dirs[i]); auto o1 = off(dirs[i - 1]), o2 = off(dirs[i]);
            double rx = o2.first - o1.first, ry = o2.second - o1.second, den = e1.first * e2.second - e1.second * e2.first;
            double t = fabs(den) < 1e-12 ? 0 : (rx * e2.second - ry * e2.first) / den;
            out.push_back({vx + o1.first + t * e1.first, vy + o1.second + t * e1.second}); } }
        return out; };
      auto makeMid = [&](int netId, const vector<pair<double,double>>& poly) {
        Route R; R.net = netId; R.pinA = R.pinB = R.joinA = R.joinB = -1; R.plane = false; R.alive = true; R.frozen = true; R.mid = true; double w = nets[netId].w;
        for (auto& q : poly) R.pts.push_back({q.first, q.second, l, w, false});
        for (size_t i = 1; i < poly.size(); i++) R.shapes.push_back(capsule(poly[i - 1].first, poly[i - 1].second, poly[i].first, poly[i].second, w / 2, 1 << RLs[l]));
        R.nodes.push_back((u32)l * NC + cj(poly.front().second) * NX + ci(poly.front().first)); R.nodes.push_back((u32)l * NC + cj(poly.back().second) * NX + ci(poly.back().first));
        markPair(R, +1); int id = routes.size(); routes.push_back(R); nets[netId].routes.push_back(id); midIds.push_back(id); };
      // every offset segment must keep its heading (a too-tight turn would flip the inner line)
      auto L = offsetLine(true), Rr = offsetLine(false); bool sane = true;
      for (auto* poly : {&L, &Rr}) for (int i = 0; i < nseg; i++) { double ex_ = DX[dirs[i]], ey_ = DY[dirs[i]]; if (((*poly)[i + 1].first - (*poly)[i].first) * ex_ + ((*poly)[i + 1].second - (*poly)[i].second) * ey_ <= 1e-6) sane = false; }
      if (sane) { makeMid(job.pLeft ? job.nP : job.nN, L); makeMid(job.pLeft ? job.nN : job.nP, Rr); done = true; }
    }
    exempt(job.nP, +1); exempt(job.nN, +1);
    double len = 0; if (done) { auto& R = routes.back(); for (auto& sh : R.shapes) len += hypot(sh.bx - sh.ax, sh.by - sh.ay); }
    fprintf(stderr, "  pair run %s/%s: %s (%ldk states)%s\n", nets[job.nP].name.c_str(), nets[job.nN].name.c_str(), done ? "wide track laid" : (found ? "turn too tight, falling back" : "no wide track fits, falling back"), expanded / 1000, done ? (", " + to_string((int)lround(len)) + " mm").c_str() : "");
    return done;
  };

  long iter = 0; int lastReport = 0;
  auto drain = [&](double limit) {
    while (!Q.empty() && elapsed() < limit) {
      int n = Q.front(); Q.pop_front(); inQueue[n] = 0; iter++;
      if (nets[n].rips > MAXRIP && !nets[n].frozen) { nets[n].frozen = true; for (int r : nets[n].routes) if (routes[r].alive && !routes[r].frozen) { markRoute(routes[r], -1); routes[r].frozen = true; markRoute(routes[r], +1); } }
      setPourMult(n);
      routeNet(n, true);
      if ((int)elapsed() >= lastReport + 10) { lastReport = (int)elapsed(); int fail = 0; for (auto& x : nets) fail += x.failed; fprintf(stderr, "  t=%ds iter=%ld queue=%zu rips=%d failed=%d expanded=%ldM\n", lastReport, iter, Q.size(), ripEvents, fail, totalExpanded / 1000000); }
    }
  };
  while (!Q.empty() && nets[Q.front()].novia) { int n = Q.front(); Q.pop_front(); inQueue[n] = 0; setPourMult(n); routeNet(n, true); }   // crystal nets first
  // Pair runs are walls for one another, so the order matters: pairs that leave one side of a chip have to
  // nest. Try the hub's pairs in pin order and in reverse pin order and keep whichever lays more wide tracks.
  { auto attempt = [&](bool reverseHub) { vector<PairJob> order; for (auto& j : pairJobs) if (j.grp == 0) order.push_back(j);
      vector<PairJob> hub; for (auto& j : pairJobs) if (j.grp != 0) hub.push_back(j); if (reverseHub) reverse(hub.begin(), hub.end()); order.insert(order.end(), hub.begin(), hub.end());
      int ok = 0; for (auto& job : order) if (selected[job.nP] && selected[job.nN]) ok += fatRoute(job) ? 1 : 0; return ok; };
    auto undo = [&]() { for (int id : midIds) if (routes[id].alive) { markRoute(routes[id], -1); routes[id].alive = false; } midIds.clear(); };
    if (!pairJobs.empty()) { fprintf(stderr, " pair runs, hub pairs in pin order:\n"); int a = attempt(false); undo();
      fprintf(stderr, " pair runs, hub pairs in reverse pin order:\n"); int b = attempt(true);
      if (a > b) { undo(); fprintf(stderr, " keeping pin order (%d wide tracks against %d):\n", a, b); attempt(false); } else fprintf(stderr, " keeping reverse pin order (%d wide tracks against %d)\n", b, a); } }
  drain(TIME_LIMIT);
  // Nets that failed were boxed in by nets that had been ripped too often and were frozen. Thaw everything,
  // give the failed nets first go, and let the neighbourhood re-settle. Repeat a few times.
  for (int round = 0; round < 6 && elapsed() < TIME_LIMIT * 1.5; round++) {
    vector<int> failed; for (int n = 0; n < NN; n++) if (nets[n].failed) failed.push_back(n);
    if (failed.empty()) break;
    for (auto& R : routes) if (R.alive && R.frozen && !R.mid && !R.pre && !nets[R.net].novia && nets[R.net].maxLen == 0) { markRoute(R, -1); R.frozen = false; markRoute(R, +1); }
    for (auto& n : nets) if (!n.novia && n.maxLen == 0) { n.frozen = false; n.rips = 0; }
    fprintf(stderr, "  retry round %d: %zu failed net(s)\n", round + 1, failed.size());
    for (int n : failed) if (!inQueue[n]) { inQueue[n] = 1; Q.push_back(n); }
    drain(TIME_LIMIT * 1.5);
  }

  // ---------------- output ----------------
  FILE* f = fopen(argv[2], "w"); int alive = 0, nvias = 0; vector<double> len(NL, 0);
  for (auto& R : routes) { if (!R.alive || R.pre) continue; alive++;
    fprintf(f, "T %d %d %d %d %zu\n", R.net, R.pinA, R.pinB, R.plane ? 1 : 0, R.pts.size());
    for (size_t k = 0; k < R.pts.size(); k++) { auto& p = R.pts[k]; if (p.via) { fprintf(f, "v %.4f %.4f %d\n", p.x, p.y, p.l < 0 ? -1 : RLs[p.l]); nvias++; } else { fprintf(f, "w %.6f %.6f %d %.3f\n", p.x, p.y, RLs[p.l], p.w); if (k && !R.pts[k - 1].via && R.pts[k - 1].l == p.l) len[p.l] += hypot(p.x - R.pts[k - 1].x, p.y - R.pts[k - 1].y); } } }
  int unrouted = 0;
  for (int n = 0; n < NN; n++) { Net& net = nets[n]; int np = net.pins.size(); if (np < (net.plane ? 1 : 2) || !selected[n]) continue;
    ufp.assign(np + 1 + net.routes.size(), 0); for (size_t k = 0; k < ufp.size(); k++) ufp[k] = k;
    map<int,int> pinLocal; for (int k = 0; k < np; k++) pinLocal[net.pins[k]] = k; map<int,int> routeLocal; for (size_t k = 0; k < net.routes.size(); k++) routeLocal[net.routes[k]] = np + 1 + k;
    auto uni = [&](int a, int b) { a = uff(a); b = uff(b); if (a != b) ufp[a] = b; };
    for (size_t k = 0; k < net.routes.size(); k++) { Route& R = routes[net.routes[k]]; if (!R.alive) continue; int me = np + 1 + k; if (R.pinA >= 0) uni(me, pinLocal[R.pinA]); if (R.pinB >= 0) uni(me, pinLocal[R.pinB]); if (R.joinA >= 0) uni(me, routeLocal[R.joinA]); if (R.joinB >= 0) uni(me, routeLocal[R.joinB]); if (R.plane) uni(me, np); }
    if (net.plane) { for (int k = 0; k < np; k++) { Pin& pn = pins[net.pins[k]]; if (pn.pad >= 0 && (pads[pn.pad].mask & (1 << net.planeLayer))) uni(k, np); } for (int k = 0; k < np; k++) if (uff(k) != uff(np)) { fprintf(f, "U %d %d %s %.3f %.3f\n", n, net.pins[k], net.name.c_str(), pins[net.pins[k]].x, pins[net.pins[k]].y); unrouted++; } }
    else { map<int,int> cnt; for (int k = 0; k < np; k++) cnt[uff(k)]++; int big = -1, bn = 0; for (auto& kv : cnt) if (kv.second > bn) { bn = kv.second; big = kv.first; } for (int k = 0; k < np; k++) if (uff(k) != big) { fprintf(f, "U %d %d %s %.3f %.3f\n", n, net.pins[k], net.name.c_str(), pins[net.pins[k]].x, pins[net.pins[k]].y); unrouted++; } }
  }
  fclose(f);
  fprintf(stderr, "done in %.1fs: %d routes, %d vias, %d unconnected pins, %d rip events, %ldM expansions;", elapsed(), alive, nvias, unrouted, ripEvents, totalExpanded / 1000000);
  for (int l = 0; l < NL; l++) fprintf(stderr, " %s %.0f mm", layerNames[RLs[l]].c_str(), len[l]); fprintf(stderr, "\n");
  return 0;
}