aboutsummaryrefslogtreecommitdiff
path: root/tools/router/src/astar.rs
diff options
context:
space:
mode:
authorLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
committerLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
commita59e8e99243a895197a30d6cd6dd8d744dd606de (patch)
tree8910cc7476ff1317932257dfc8497a0f9ffc29f7 /tools/router/src/astar.rs
parent6f2bbe1f94e4321c329f92ec3420f6d32fd7b26d (diff)
downloadhw-toolchain-main.tar.gz
Keep only the current router: drop the Python router, router-rs -> routerHEADmain
The sequential Python/C router (pcbroute.py, pipeline.py, astar.c) is gone. The Rust crate takes its place at tools/router/, next to the KiCad I/O scripts it uses (dump_board.py, write_board.py, plot_routes.py). knowledge/tooling/router.md is now the Rust router's reference; the small Python venv for plots and 3D checks moves to tools/.venv (tools/requirements.txt). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/router/src/astar.rs')
-rw-r--r--tools/router/src/astar.rs320
1 files changed, 320 insertions, 0 deletions
diff --git a/tools/router/src/astar.rs b/tools/router/src/astar.rs
new file mode 100644
index 0000000..0a91f7a
--- /dev/null
+++ b/tools/router/src/astar.rs
@@ -0,0 +1,320 @@
+//! Grid A* core, 2 layers (port of an earlier C core with the same arithmetic in f32;
+//! a radix heap replaces the binary heap, so ties break differently).
+//!
+//! States are cell * 2 + layer, so both layers of a cell share a cache line. Foreign distance for net X: n1 == X ? d2 : d1.
+
+use crate::board::Field;
+
+/// A step "runs alongside" copper within this distance (mm) beyond its clearance.
+const HUG_BAND: f32 = 0.15;
+
+/// A via's conflicts and history weigh like this many track steps.
+const VIA_SOFT: f32 = 8.0;
+
+const DX: [i32; 8] = [1, 1, 0, -1, -1, -1, 0, 1];
+const DY: [i32; 8] = [0, 1, 1, 1, 0, -1, -1, -1];
+
+pub struct SearchArgs<'a> {
+ pub nx: usize,
+ pub n: usize,
+ pub f: &'a [Field],
+ pub padd: &'a [f32],
+ /// per cell distance to the nearest drill edge; a via needs r_hole
+ pub hole: &'a [f32],
+ pub r_hole: f32,
+ /// steps a path needs between two of its own vias
+ pub via_gap: u16,
+ pub cost: &'a [f32],
+ /// negotiation: a step onto other nets' soft copper costs (base + hist) * (1 + pres)
+ /// (INFINITY: not allowed); elsewhere base + hist
+ pub soft: Option<&'a [Field]>,
+ pub hist: &'a [f32],
+ pub pres: f32,
+ pub net: i32,
+ pub src: &'a [i32],
+ pub tgt: &'a [u8],
+ pub goal_layer1: bool,
+ pub hx: i32,
+ pub hy: i32,
+ pub r_nom: f32,
+ pub r_neck: f32,
+ pub r_via: f32,
+ pub r_vpad: f32,
+ pub r_diag: f32,
+ pub neckbox: &'a [[i32; 4]],
+ pub via_cost: f32,
+ pub via_cmult: f32,
+ pub bmult: f32,
+ pub turn_cost: f32,
+ pub allow_via: bool,
+ pub max_expand: i64,
+ pub layer_mask: u8,
+ /// heuristic weight: 1 is exact A*, more trades path cost for fewer expansions
+ pub hweight: f32,
+ /// extra cost per step farther than HUG_BAND from other copper
+ pub hug: f32,
+ /// per state distance to the copper of the net's bundle partners (pair, bus), and the
+ /// extra cost per step farther than HUG_BAND from it
+ pub attract: Option<&'a [f32]>,
+ pub attract_cost: f32,
+ /// a necked step costs 0.3 plus this much per mm of width given up
+ pub neck: f32,
+ /// cell window [x0, y0, x1, y1] (inclusive) the search stays in
+ pub window: [i32; 4],
+}
+
+/// Per-state search data, packed so that one state is one cache access.
+#[derive(Clone, Copy, Default)]
+struct Node {
+ g: f32,
+ par: i32,
+ stamp: u32,
+ dir: u8,
+ closed: bool,
+ /// steps since the path's last via (its own vias are not in the hole field yet)
+ since: u16,
+}
+
+/// Radix heap on the f32 bit patterns of non-negative keys. A* pops keys in non-decreasing
+/// order (the octile heuristic is consistent: every step costs at least its length), which
+/// is all a radix heap needs; push and pop are O(1) amortised instead of a binary heap's
+/// cache-missing O(log n).
+struct RadixHeap {
+ last: u32,
+ len: usize,
+ buckets: Vec<Vec<(u32, i32)>>,
+}
+
+impl RadixHeap {
+ fn new() -> RadixHeap {
+ RadixHeap { last: 0, len: 0, buckets: (0..33).map(|_| Vec::new()).collect() }
+ }
+
+ fn clear(&mut self) {
+ self.buckets.iter_mut().for_each(Vec::clear);
+ self.last = 0;
+ self.len = 0;
+ }
+
+ fn bucket(&self, k: u32) -> usize {
+ (32 - (k ^ self.last).leading_zeros()) as usize
+ }
+
+ fn push(&mut self, f: f32, i: i32) {
+ let k = f.max(0.0).to_bits().max(self.last); // a key below the last pop would break the order
+ let b = self.bucket(k);
+ self.buckets[b].push((k, i));
+ self.len += 1;
+ }
+
+ fn pop(&mut self) -> i32 {
+ if self.buckets[0].is_empty() {
+ let b = (1..33).find(|&b| !self.buckets[b].is_empty()).unwrap();
+ let items = std::mem::take(&mut self.buckets[b]);
+ self.last = items.iter().map(|e| e.0).min().unwrap();
+ for &(k, i) in &items {
+ let nb = self.bucket(k);
+ self.buckets[nb].push((k, i));
+ }
+ let mut v = items;
+ v.clear();
+ self.buckets[b] = v;
+ }
+ self.len -= 1;
+ self.buckets[0].pop().unwrap().1
+ }
+
+ fn is_empty(&self) -> bool {
+ self.len == 0
+ }
+}
+
+pub struct Search {
+ node: Vec<Node>,
+ call: u32,
+ heap: RadixHeap,
+}
+
+#[inline]
+fn heur(x: i32, y: i32, hx: i32, hy: i32) -> f32 {
+ let (ax, ay) = ((x - hx).abs(), (y - hy).abs());
+ ax.max(ay) as f32 + 0.414_213_56f32 * ax.min(ay) as f32
+}
+
+impl Search {
+ pub fn new(states: usize) -> Search {
+ Search { node: vec![Node::default(); states], call: 0, heap: RadixHeap::new() }
+ }
+
+ fn push(&mut self, f: f32, i: i32) {
+ self.heap.push(f, i);
+ }
+
+ fn pop(&mut self) -> i32 {
+ self.heap.pop()
+ }
+
+ /// Path (target back to source) with neck flags, or None.
+ pub fn route(&mut self, a: &SearchArgs) -> Option<(Vec<i32>, Vec<u8>)> {
+ let nx = a.nx as i32;
+ let fdist = |s: usize| a.f[s].fdist(a.net);
+ self.call = self.call.wrapping_add(1);
+ if self.call == 0 {
+ self.node.iter_mut().for_each(|v| v.stamp = 0);
+ self.call = 1;
+ }
+ let call = self.call;
+ self.heap.clear();
+ let neck_cost = 0.3 + a.neck * 2.0 * (a.r_nom - a.r_neck).max(0.0);
+ for &s in a.src {
+ let s = s as usize;
+ let l = s & 1;
+ if (a.layer_mask >> l) & 1 == 0 {
+ continue;
+ }
+ if fdist(s) < if a.r_neck > 0.0 { a.r_neck } else { a.r_nom } {
+ continue; // a track must fit at its start cell
+ }
+ self.node[s] = Node { g: 0.0, par: -1, stamp: call, dir: 255, closed: false, since: u16::MAX };
+ let c = (s >> 1) as i32;
+ self.push(if a.goal_layer1 { 0.0 } else { a.hweight * heur(c % nx, c / nx, a.hx, a.hy) }, s as i32);
+ }
+ let mut expanded: i64 = 0;
+ let mut found: i64 = -1;
+ while !self.heap.is_empty() {
+ let s = self.pop() as usize;
+ if self.node[s].closed {
+ continue;
+ }
+ self.node[s].closed = true;
+ let l = s & 1;
+ let c = s >> 1;
+ let (x, y) = ((c % a.nx) as i32, (c / a.nx) as i32);
+ if a.tgt[s] != 0 || (a.goal_layer1 && l == 1) {
+ found = s as i64;
+ break;
+ }
+ expanded += 1;
+ if expanded > a.max_expand {
+ break;
+ }
+ let gcur = self.node[s].g;
+ let pd = self.node[s].dir;
+ let since = self.node[s].since;
+ for d in 0..8usize {
+ // cheap rejections first: reversals and sharp turns, closed states
+ let mut turn = 0.0f32;
+ if pd != 255 && pd as usize != d {
+ let mut t = (pd as i32 - d as i32).abs();
+ if t > 4 {
+ t = 8 - t;
+ }
+ if t >= 3 {
+ continue;
+ }
+ turn = a.turn_cost * t as f32;
+ }
+ let (qx, qy) = (x + DX[d], y + DY[d]);
+ if qx < a.window[0] || qy < a.window[1] || qx > a.window[2] || qy > a.window[3] {
+ continue;
+ }
+ let nc = (qy * nx + qx) as usize;
+ let ns = nc * 2 + l;
+ let q = self.node[ns];
+ if q.stamp == call && q.closed {
+ continue;
+ }
+ let fd = fdist(ns);
+ let odd = d & 1 == 1;
+ let need = a.r_nom + if odd { a.r_diag } else { 0.0 };
+ let mut neck = false;
+ let mut r = need;
+ if fd < need {
+ if a.r_neck <= 0.0 {
+ continue;
+ }
+ let needn = a.r_neck + if odd { a.r_diag } else { 0.0 };
+ if fd < needn {
+ continue;
+ }
+ if !a.neckbox.iter().any(|b| qx >= b[0] && qx <= b[2] && qy >= b[1] && qy <= b[3]) {
+ continue;
+ }
+ neck = true;
+ r = needn;
+ }
+ let step = if odd { 1.414_213_56f32 } else { 1.0f32 };
+ let mut cst = step * if l == 1 { a.bmult } else { 1.0 } + a.cost[ns] * step;
+ if neck {
+ cst += neck_cost * step;
+ }
+ if a.hug > 0.0 && fd > r + HUG_BAND {
+ cst += a.hug * step;
+ }
+ if let Some(at) = a.attract {
+ if at[ns] > r + HUG_BAND {
+ cst += a.attract_cost * step;
+ }
+ }
+ if let Some(sf) = a.soft {
+ // PathFinder: (base + history) * (1 + present factor on conflict)
+ cst += a.hist[ns] * step;
+ if sf[ns].fdist(a.net) < r {
+ if a.pres == f32::INFINITY {
+ continue;
+ }
+ cst *= 1.0 + a.pres;
+ }
+ }
+ cst += turn;
+ let ng = gcur + cst;
+ if q.stamp == call && q.g <= ng {
+ continue;
+ }
+ self.node[ns] = Node { g: ng, par: s as i32, stamp: call, dir: d as u8, closed: false, since: since.saturating_add(1) };
+ self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(qx, qy, a.hx, a.hy) }, ns as i32);
+ }
+ if a.allow_via && a.layer_mask & 3 == 3 {
+ let (s0, s1) = (c * 2, c * 2 + 1);
+ let mut soft_ok = true;
+ let mut vc = a.via_cost + a.via_cmult * (a.cost[s0] + a.cost[s1]);
+ if let Some(sf) = a.soft {
+ let n = (sf[s0].fdist(a.net) < a.r_via) as u32 + (sf[s1].fdist(a.net) < a.r_via) as u32;
+ soft_ok = n == 0 || a.pres != f32::INFINITY;
+ vc += VIA_SOFT * (a.hist[s0] + a.hist[s1]);
+ if n > 0 {
+ vc *= 1.0 + a.pres * n as f32;
+ }
+ }
+ if soft_ok && since >= a.via_gap && a.hole[c] >= a.r_hole && fdist(s0) >= a.r_via && fdist(s1) >= a.r_via && a.padd[s0] >= a.r_vpad && a.padd[s1] >= a.r_vpad {
+ let ns = c * 2 + 1 - l;
+ let ng = gcur + vc;
+ let q = &mut self.node[ns];
+ if !(q.stamp == call && (q.closed || q.g <= ng)) {
+ *q = Node { g: ng, par: s as i32, stamp: call, dir: 255, closed: false, since: 0 };
+ self.push(ng + if a.goal_layer1 { 0.0 } else { a.hweight * heur(x, y, a.hx, a.hy) }, ns as i32);
+ }
+ }
+ }
+ }
+ if std::env::var("ROUTER_TRACE").is_ok() {
+ eprintln!("EXP {} {}", expanded, found >= 0);
+ }
+ if found < 0 {
+ return None;
+ }
+ let (mut out, mut neck) = (Vec::new(), Vec::new());
+ let mut s = found as i32;
+ while s >= 0 && out.len() < 400_000 {
+ let su = s as usize;
+ // the same test the search used to enter the cell: a full-width track that
+ // barely fits must not be drawn necked all along its run
+ let dd = self.node[su].dir;
+ let odd = dd != 255 && dd & 1 == 1;
+ neck.push((fdist(su) < a.r_nom + if odd { a.r_diag } else { 0.0 }) as u8);
+ out.push(s);
+ s = self.node[su].par;
+ }
+ Some((out, neck))
+ }
+}