diff options
| author | Louis <louis@dnge.de> | 2026-11-11 10:08:41 +0100 |
|---|---|---|
| committer | Louis <louis@dnge.de> | 2026-11-11 10:08:41 +0100 |
| commit | 2e433fcd0d1afadd8ab786dd30d7d4546bdee43d (patch) | |
| tree | f2a5603703d56b08c1eaa672eaf529ec4b2cc3fa /tools/router-rs/src/board.rs | |
| download | hw-toolchain-2e433fcd0d1afadd8ab786dd30d7d4546bdee43d.tar.gz | |
hw-toolchain: placer, routers and KiCad helpers for agent-driven hardware work
Rust placer (simulated annealing) and negotiated-congestion router for
2-layer KiCad boards, pnr.sh to place, route, DRC-check and install
candidates, Python KiCad helpers, repo conventions (AGENTS.md) and the
tool documentation under knowledge/. Konnect (KiCad MCP, AGPL) as a
submodule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/router-rs/src/board.rs')
| -rw-r--r-- | tools/router-rs/src/board.rs | 847 |
1 files changed, 847 insertions, 0 deletions
diff --git a/tools/router-rs/src/board.rs b/tools/router-rs/src/board.rs new file mode 100644 index 0000000..137b4fa --- /dev/null +++ b/tools/router-rs/src/board.rs @@ -0,0 +1,847 @@ +//! Board model and clearance fields (port of tools/router/pcbroute.py). +//! +//! The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu), with its origin on a +//! multiple of 0.05 mm, so that parts placed on the placer's 0.05 mm grid have their pads on +//! cell centres (an outline at 99.975 put 0.5 mm-pitch pins between two cell rows, where no +//! 0.25 mm neck fits). For every cell, d1/n1 +//! hold the distance to and the net of the nearest copper, d2 the distance to the nearest +//! copper of another net. A track of width w fits where the foreign distance is +//! >= w/2 + CLR. Board edge, NPTH holes and keep-outs are net -1 copper in the static +//! `base` field. Items are kept in insertion order; removal re-inserts the neighbours of the +//! cleared region, as the Python router does, so ties resolve the same way. +//! +//! Footprint copper that is not a pad (`fpcopper`, e.g. a net tie's bridge) is static copper: +//! of its net when it touches pads of one net, else of no net (foreign to every net) with the +//! pads it joins cut out, so that the tie's nets still reach their pads from outside. +//! +//! Negotiated routing (router::negotiate) commits `soft` items: they go into a second field +//! (`soft`), which the search may violate at a cost (`pres` per conflicting step plus the +//! `hist` cost of the cell); everything else is hard. + +use crate::astar::{Search, SearchArgs}; +use crate::geom::{poly_poly, Poly, Pt}; +use crate::io::{BoardJson, FpCopperJson}; +use std::collections::HashMap; + +pub const RES: f64 = 0.05; +pub const CAP: f32 = 1.5; +pub const CLR: f64 = 0.2; +pub const M: f64 = 0.015; // numeric margin on clearance checks +pub const RDIAG: f64 = 0.02; // extra margin on diagonal steps +pub const EDGE_CLR: f64 = 0.5; +pub const HOLE_CLR: f64 = 0.3; +pub const HOLE_HOLE: f64 = 0.25; // drill edge to drill edge, any nets +/// A track may neck down within this distance (mm) of the pad bboxes it joins (default of the +/// `neck_zone` option). +pub const NECK_ZONE: f64 = 1.0; +/// Sample spacing (mm) of footprint copper. +pub const CU_STEP: f64 = 0.025; + +/// Drill of a via of diameter d (as written to the board). +pub fn via_drill(d: f64) -> f64 { + if d >= 0.8 { + 0.4 + } else { + 0.3 + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Shape { + Pad(usize), + Seg(Pt, Pt), + Via(Pt), + /// footprint copper (index into Board::cu) + Cu(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Owner { + Pad, + Existing, + Routed, + /// routed by negotiation (or its cleanup): the cleanup may reroute it + Negotiated, + Waypoint, +} + +#[derive(Clone, Debug)] +pub struct Item { + pub shape: Shape, + pub net: i32, + pub layers: u8, // bit 0 F.Cu, bit 1 B.Cu + pub w: f64, + pub bbox: [f64; 4], + pub owner: Owner, + pub soft: bool, +} + +impl Item { + pub fn on(&self, layer: usize) -> bool { + self.layers >> layer & 1 == 1 + } +} + +pub struct Pad { + pub refdes: String, + pub num: String, + pub net: i32, + pub layers: u8, + pub poly: Poly, + pub x: f64, + pub y: f64, + pub tht: bool, + pub drill: f64, + pub item: usize, +} + +/// Search settings of one connection (pcbroute.Board.route keyword arguments). +#[derive(Clone, Copy, Debug)] +pub struct SearchOpts { + pub via_cost: f64, + pub via_cmult: f64, + pub bmult: f64, + pub turn: f64, + pub allow_via: bool, + pub layer_mask: u8, + pub max_expand: i64, + pub hweight: f64, + /// search only within this margin (mm) around the connection's copper; 0: whole board + pub margin: f64, + /// extra cost per step that does not run alongside other copper (bundles parallel lines) + pub hug: f64, + /// a necked step costs 0.3 plus this much per mm of width given up (the cleanup uses 4: + /// 1.0 -> 0.2 mm costs 3.5 per step, so a net necks only where its width does not fit) + pub neck: f64, + /// a track may neck down within this distance (mm) of the pad bboxes it joins + pub neck_zone: f64, +} + +impl Default for SearchOpts { + fn default() -> Self { + SearchOpts { via_cost: 40.0, via_cmult: 0.0, bmult: 3.0, turn: 4.0, allow_via: true, layer_mask: 3, max_expand: 4_000_000, hweight: 1.0, margin: 0.0, hug: 0.0, neck: 0.0, neck_zone: NECK_ZONE } + } +} + +pub type Seg = (usize, Pt, Pt, f64); // layer, a, b, width + +/// Clearance field of one state: distance to and net of the nearest copper (d1, n1) and +/// distance to the nearest copper of another net (d2). +#[derive(Clone, Copy, Debug)] +pub struct Field { + pub d1: f32, + pub n1: i32, + pub d2: f32, +} + +impl Field { + pub const EMPTY: Field = Field { d1: CAP, n1: 0, d2: CAP }; + + /// Distance to copper of a net other than `net`. + #[inline] + pub fn fdist(&self, net: i32) -> f32 { + if self.n1 == net { + self.d2 + } else { + self.d1 + } + } + + #[inline] + fn add(&mut self, dd: f32, net: i32) { + if self.n1 == net { + self.d1 = self.d1.min(dd); + } else if dd < self.d1 { + self.d2 = self.d1; + self.d1 = dd; + self.n1 = net; + } else { + self.d2 = self.d2.min(dd); + } + } +} + +pub struct Board { + /// grid extent (origin snapped to the grid) + pub x0: f64, + pub y0: f64, + pub x1: f64, + pub y1: f64, + /// the board outline's bounds, for the edge clearance + edge: [f64; 4], + pub nx: usize, + pub ny: usize, + pub n: usize, + pub f: Vec<Field>, + pub padd: Vec<f32>, + pub soft: Vec<Field>, + pub hist: Vec<f32>, + /// commit soft items and price soft conflicts (`pres` = INFINITY: soft copper is hard) + pub soft_mode: bool, + pub pres: f32, + pub costs: HashMap<String, Vec<f32>>, + pub cost: String, + /// owner of committed routes + pub commit_owner: Owner, + base: Vec<f32>, // one layer; both layers share it + pub pads: Vec<Pad>, + pub items: Vec<Item>, + pub alive: Vec<bool>, + pub netid: HashMap<String, i32>, + pub netnames: Vec<String>, // by net id; id 0 is unused, -1 is "" + npth: Vec<(f64, f64, f64)>, + /// per cell: distance to the nearest drill edge (pads, NPTH, vias of any net) + pub hole: Vec<f32>, + hole_base: Vec<f32>, + keepouts: Vec<Poly>, + /// bundle attraction (cleanup): per state distance to the partners' copper, and its cost + attract: Vec<f32>, + attract_cost: f32, + /// routing area (route.toml `area`): copper stays `area_margin` inside the union + area: Vec<Poly>, + area_margin: f64, + /// footprint copper as sample points (spacing CU_STEP) inside its outline + pub cu: Vec<Vec<Pt>>, + tgt: Vec<u8>, + search: Search, +} + +impl Board { + pub fn new(d: &BoardJson, plane_nets: &[String], area: Vec<Poly>, area_margin: f64) -> Board { + let [bx0, by0, x1, y1] = d.bounds; + // the grid's origin on a multiple of RES (exact multiples stay) + let snap = |v: f64| if ((v / RES).round() * RES - v).abs() < 1e-9 { v } else { (v / RES).floor() * RES }; + let (x0, y0) = (snap(bx0), snap(by0)); + let nx = ((x1 - x0) / RES - 1e-6).ceil() as usize + 1; + let ny = ((y1 - y0) / RES - 1e-6).ceil() as usize + 1; + let n = nx * ny; + let mut b = Board { + x0, + y0, + x1, + y1, + edge: d.bounds, + nx, + ny, + n, + f: vec![Field::EMPTY; 2 * n], + padd: vec![CAP; 2 * n], + soft: vec![Field::EMPTY; 2 * n], + hist: vec![0.0; 2 * n], + soft_mode: false, + pres: 0.0, + costs: HashMap::from([("none".to_string(), vec![0.0; 2 * n])]), + cost: "none".into(), + commit_owner: Owner::Routed, + base: vec![CAP; n], + pads: Vec::new(), + items: Vec::new(), + alive: Vec::new(), + netid: HashMap::new(), + netnames: vec![String::new()], + npth: Vec::new(), + keepouts: d.keepouts.iter().map(|k| Poly::new(k.iter().map(|p| (p[0], p[1])).collect())).collect(), + area, + area_margin, + attract: Vec::new(), + attract_cost: 0.0, + cu: Vec::new(), + tgt: vec![0; 2 * n], + hole: vec![CAP; n], + hole_base: vec![CAP; n], + search: Search::new(2 * n), + }; + for p in &d.pads { + let layers = (p.f.is_some() as u8) | (p.b.is_some() as u8) << 1; + if layers == 0 { + continue; + } + let net = if p.net.is_empty() || p.net.starts_with("unconnected") { + -1 + } else { + match b.netid.get(&p.net) { + Some(&k) => k, + None => { + let k = b.netnames.len() as i32; + b.netid.insert(p.net.clone(), k); + b.netnames.push(p.net.clone()); + k + } + } + }; + let pts = p.f.as_ref().or(p.b.as_ref()).unwrap(); + b.pads.push(Pad { + refdes: p.refdes.clone(), + num: p.num.clone(), + net, + layers, + poly: Poly::new(pts.iter().map(|q| (q[0], q[1])).collect()), + x: p.x, + y: p.y, + tht: layers == 3, + drill: p.drill, + item: usize::MAX, + }); + } + b.npth = d.pads.iter().filter(|p| p.npth).map(|p| (p.x, p.y, p.drill)).collect(); + b.build_static(plane_nets); + for c in &d.fpcopper { + b.add_fpcopper(c); + } + let holes: Vec<(f64, f64, f64)> = b.pads.iter().filter(|p| p.tht && p.drill > 0.0).map(|p| (p.x, p.y, p.drill / 2.0)).chain(b.npth.iter().map(|h| (h.0, h.1, h.2 / 2.0))).collect(); + for (x, y, r) in holes { + b.hole_min(x, y, r, true); + } + b.hole.clone_from(&b.hole_base); + b + } + + /// Footprint copper as a static item: the net of the pads it touches if they share one, + /// else no net with those pads cut out (a net tie's bridge). + fn add_fpcopper(&mut self, c: &FpCopperJson) { + let l = if c.layer == "B" { 1 } else { 0 }; + let poly = Poly::new(c.poly.iter().map(|p| (p[0], p[1])).collect()); + let touch: Vec<usize> = (0..self.pads.len()) + .filter(|&k| self.pads[k].refdes == c.refdes && self.pads[k].layers >> l & 1 == 1 && poly_poly(&self.pads[k].poly, &poly) <= 1e-6) + .collect(); + let mut nets: Vec<i32> = touch.iter().map(|&k| self.pads[k].net).collect(); + nets.sort(); + nets.dedup(); + let (net, cut) = if nets.len() == 1 { (nets[0], vec![]) } else { (-1, touch) }; + let bb = poly.bbox; + let mut pts = Vec::new(); + let mut y = bb[1] + CU_STEP / 2.0; + while y < bb[3] { + let mut x = bb[0] + CU_STEP / 2.0; + while x < bb[2] { + if poly.contains((x, y)) && cut.iter().all(|&k| self.pads[k].poly.dist((x, y)) > CU_STEP / 2.0) { + pts.push((x, y)); + } + x += CU_STEP; + } + y += CU_STEP; + } + if pts.is_empty() { + return; + } + let h = CU_STEP / 2.0; + let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for &(x, y) in &pts { + b = [b[0].min(x - h), b[1].min(y - h), b[2].max(x + h), b[3].max(y + h)]; + } + self.cu.push(pts); + let k = self.cu.len() - 1; + self.add(Item { shape: Shape::Cu(k), net, layers: 1 << l, w: 0.0, bbox: b, owner: Owner::Pad, soft: false }); + } + + pub fn netname(&self, net: i32) -> &str { + if net < 0 { + "" + } else { + &self.netnames[net as usize] + } + } + + pub fn cell_xy(&self, i: usize, j: usize) -> Pt { + (self.x0 + i as f64 * RES, self.y0 + j as f64 * RES) + } + + pub fn xy_cell(&self, x: f64, y: f64) -> (i64, i64) { + (((x - self.x0) / RES).round_ties_even() as i64, ((y - self.y0) / RES).round_ties_even() as i64) + } + + fn gx(&self, i: usize) -> f64 { + self.x0 + i as f64 * RES + } + + fn gy(&self, j: usize) -> f64 { + self.y0 + j as f64 * RES + } + + /// Cell window (inclusive) covering bbox b grown by `pad`, clipped to the grid. + pub fn window(&self, b: &[f64; 4], pad: f64) -> (usize, usize, usize, usize) { + let i0 = ((b[0] - pad - self.x0) / RES).floor().max(0.0) as usize; + let j0 = ((b[1] - pad - self.y0) / RES).floor().max(0.0) as usize; + let i1 = (((b[2] + pad - self.x0) / RES).ceil() as i64).min(self.nx as i64 - 1); + let j1 = (((b[3] + pad - self.y0) / RES).ceil() as i64).min(self.ny as i64 - 1); + (i0, j0, i1.max(-1) as usize, j1.max(-1) as usize) + } + + fn build_static(&mut self, plane_nets: &[String]) { + let (nx, ny) = (self.nx, self.ny); + let mut base = vec![0.0f64; self.n]; + for j in 0..ny { + for i in 0..nx { + let (x, y) = (self.gx(i), self.gy(j)); + let e = self.edge; + base[j * nx + i] = (x - e[0]).min(e[2] - x).min(y - e[1]).min(e[3] - y) - (EDGE_CLR - CLR); + } + } + // routing area: outside it is no-net copper, like the board edge (signed distance to + // the union, approximated by the deepest containing polygon) + if !self.area.is_empty() { + for j in 0..ny { + for i in 0..nx { + let p = (self.gx(i), self.gy(j)); + let inside = self.area.iter().filter(|a| a.contains(p)).map(|a| a.boundary_dist(p)).fold(f64::NEG_INFINITY, f64::max); + let d = if inside.is_finite() { inside } else { -self.area.iter().map(|a| a.dist(p)).fold(f64::INFINITY, f64::min) }; + let c = &mut base[j * nx + i]; + *c = c.min(d - (self.area_margin - CLR)); + } + } + } + // values >= CAP do not matter (the fields are capped), so holes and keep-outs only + // need a window around them + for &(x, y, dr) in &self.npth.clone() { + let r = dr / 2.0 + HOLE_CLR; + let (i0, j0, i1, j1) = self.window(&[x, y, x, y], r + 2.0); + for j in j0..=j1 { + for i in i0..=i1 { + let v = (self.gx(i) - x).hypot(self.gy(j) - y) - r + CLR; + let c = &mut base[j * nx + i]; + *c = c.min(v); + } + } + } + for k in 0..self.keepouts.len() { + let bb = self.keepouts[k].bbox; + let (i0, j0, i1, j1) = self.window(&bb, 2.0); + for j in j0..=j1 { + for i in i0..=i1 { + let v = self.keepouts[k].dist((self.gx(i), self.gy(j))) + CLR; + let c = &mut base[j * nx + i]; + *c = c.min(v); + } + } + } + for (k, v) in base.iter().enumerate() { + self.base[k] = *v as f32; + } + self.reset_region(None); + // pad distance field for via-in-pad avoidance (SMD pads, not exposed plane pads) + for k in 0..self.pads.len() { + let p = &self.pads[k]; + if p.tht { + continue; + } + let b = p.poly.bbox; + if b[2] - b[0] > 2.5 && b[3] - b[1] > 2.5 && p.net >= 0 && plane_nets.iter().any(|n| n == self.netname(p.net)) { + continue; + } + let (i0, j0, i1, j1) = self.window(&b, 1.0); + for j in j0..=j1 { + for i in i0..=i1 { + let dd = p.poly.dist((self.gx(i), self.gy(j))) as f32; + for l in 0..2 { + if p.layers >> l & 1 == 1 { + let c = &mut self.padd[(j * nx + i) * 2 + l]; + *c = c.min(dd); + } + } + } + } + } + for k in 0..self.pads.len() { + let p = &self.pads[k]; + let it = Item { shape: Shape::Pad(k), net: p.net, layers: p.layers, w: 0.0, bbox: p.poly.bbox, owner: Owner::Pad, soft: false }; + let id = self.add(it); + self.pads[k].item = id; + } + } + + /// Append an item and insert it into the fields; returns its id. + pub fn add(&mut self, it: Item) -> usize { + self.items.push(it); + self.alive.push(true); + let id = self.items.len() - 1; + self.insert(id, None); + if let Shape::Via(p) = self.items[id].shape { + self.hole_min(p.0, p.1, via_drill(self.items[id].w) / 2.0, false); + } + id + } + + /// Lower the hole field (or its static base) around a drill of radius r at (x, y). + fn hole_min(&mut self, x: f64, y: f64, r: f64, base: bool) { + let (i0, j0, i1, j1) = self.window(&[x, y, x, y], r + 1.0); + for j in j0..=j1 { + for i in i0..=i1 { + let d = ((self.gx(i) - x).hypot(self.gy(j) - y) - r) as f32; + let c = if base { &mut self.hole_base[j * self.nx + i] } else { &mut self.hole[j * self.nx + i] }; + *c = c.min(d); + } + } + } + + /// Rebuild the hole field around (x, y) after a via there was removed. + fn hole_reset(&mut self, x: f64, y: f64) { + let (i0, j0, i1, j1) = self.window(&[x, y, x, y], 2.5); + for j in j0..=j1 { + for i in i0..=i1 { + self.hole[j * self.nx + i] = self.hole_base[j * self.nx + i]; + } + } + for o in 0..self.items.len() { + if let (true, Shape::Via(p)) = (self.alive[o], self.items[o].shape) { + if (p.0 - x).abs() < 4.0 && (p.1 - y).abs() < 4.0 { + let r = via_drill(self.items[o].w) / 2.0; + let (k0, l0, k1, l1) = self.window(&[p.0, p.1, p.0, p.1], r + 1.0); + for j in l0.max(j0)..=l1.min(j1) { + for i in k0.max(i0)..=k1.min(i1) { + let d = ((self.gx(i) - p.0).hypot(self.gy(j) - p.1) - r) as f32; + let c = &mut self.hole[j * self.nx + i]; + *c = c.min(d); + } + } + } + } + } + } + + /// Attract the following searches to the copper of `items` (a net's bundle partners): + /// a step farther than the hug band from it costs `cost` more. Distances are exact within + /// ATTRACT_R of the items, CAP beyond. `cost` 0 switches it off. + pub fn set_attract(&mut self, items: &[usize], cost: f64) { + const ATTRACT_R: f64 = 1.5; + self.attract_cost = cost as f32; + if cost <= 0.0 { + return; + } + self.attract.clear(); + self.attract.resize(2 * self.n, CAP); + for &id in items { + let it = &self.items[id]; + let (i0, j0, i1, j1) = self.window(&it.bbox, ATTRACT_R); + for j in j0..=j1 { + for i in i0..=i1 { + let d = self.item_dist(it, self.gx(i), self.gy(j)); + for l in 0..2 { + if it.on(l) { + let a = &mut self.attract[(j * self.nx + i) * 2 + l]; + *a = a.min(d); + } + } + } + } + } + } + + pub fn reset_region(&mut self, b: Option<&[f64; 4]>) { + self.reset(b, false) + } + + fn reset(&mut self, b: Option<&[f64; 4]>, soft: bool) { + let (i0, j0, i1, j1) = match b { + None => (0, 0, self.nx - 1, self.ny - 1), + Some(b) => self.window(b, 0.0), + }; + for l in 0..2 { + for j in j0..=j1 { + for i in i0..=i1 { + let c = j * self.nx + i; + if soft { + self.soft[c * 2 + l] = Field::EMPTY; + } else { + let bd = self.base[c]; + self.f[c * 2 + l] = Field { d1: bd.min(CAP), n1: if bd < CAP { -1 } else { 0 }, d2: CAP }; + } + } + } + } + } + + /// Move all soft items into the hard field (after negotiation). + pub fn harden(&mut self) { + let ids: Vec<usize> = (0..self.items.len()).filter(|&i| self.alive[i] && self.items[i].soft).collect(); + for &id in &ids { + self.items[id].soft = false; + self.insert(id, None); + } + self.reset(None, true); + } + + /// Distance from (x, y) to an item's copper (f64 as in numpy, then f32). + pub fn item_dist(&self, it: &Item, x: f64, y: f64) -> f32 { + match it.shape { + Shape::Pad(k) => self.pads[k].poly.dist((x, y)) as f32, + Shape::Seg((x1, y1), (x2, y2)) => { + let (dx, dy) = (x2 - x1, y2 - y1); + let l2 = dx * dx + dy * dy; + let t = if l2 == 0.0 { 0.0 } else { (((x - x1) * dx + (y - y1) * dy) / l2).clamp(0.0, 1.0) }; + ((x - (x1 + t * dx)).hypot(y - (y1 + t * dy)) - it.w / 2.0) as f32 + } + Shape::Via((vx, vy)) => ((x - vx).hypot(y - vy) - it.w / 2.0) as f32, + Shape::Cu(k) => (self.cu[k].iter().map(|p| (x - p.0).hypot(y - p.1)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0) as f32, + } + } + + fn insert(&mut self, id: usize, clip: Option<&[f64; 4]>) { + let it = self.items[id].clone(); + let b = it.bbox; + let (i0, j0, i1, j1) = match clip { + Some(c) => { + let b2 = [(b[0] - CAP as f64).max(c[0]), (b[1] - CAP as f64).max(c[1]), (b[2] + CAP as f64).min(c[2]), (b[3] + CAP as f64).min(c[3])]; + if b2[0] > b2[2] || b2[1] > b2[3] { + return; + } + self.window(&b2, 0.0) + } + None => self.window(&b, CAP as f64), + }; + let net = it.net; + let field = if it.soft { &mut self.soft } else { &mut self.f }; + for j in j0..=j1 { + for i in i0..=i1 { + let (x, y) = (self.x0 + i as f64 * RES, self.y0 + j as f64 * RES); + let dd = match it.shape { + Shape::Pad(k) => self.pads[k].poly.dist((x, y)) as f32, + Shape::Seg((x1, y1), (x2, y2)) => { + let (dx, dy) = (x2 - x1, y2 - y1); + let l2 = dx * dx + dy * dy; + let t = if l2 == 0.0 { 0.0 } else { (((x - x1) * dx + (y - y1) * dy) / l2).clamp(0.0, 1.0) }; + ((x - (x1 + t * dx)).hypot(y - (y1 + t * dy)) - it.w / 2.0) as f32 + } + Shape::Via((vx, vy)) => ((x - vx).hypot(y - vy) - it.w / 2.0) as f32, + Shape::Cu(k) => (self.cu[k].iter().map(|p| (x - p.0).hypot(y - p.1)).fold(f64::INFINITY, f64::min) - CU_STEP / 2.0) as f32, + }; + for l in 0..2 { + if !it.on(l) { + continue; + } + field[(j * self.nx + i) * 2 + l].add(dd, net); + } + } + } + } + + pub fn remove_items(&mut self, ids: &[usize]) { + for &id in ids { + self.alive[id] = false; + } + let c = CAP as f64; + for &id in ids { + let ib = self.items[id].bbox; + let soft = self.items[id].soft; + let b = [ib[0] - c, ib[1] - c, ib[2] + c, ib[3] + c]; + self.reset(Some(&b), soft); + for o in 0..self.items.len() { + if !self.alive[o] || self.items[o].soft != soft { + continue; + } + let ob = self.items[o].bbox; + if ob[0] - c > b[2] || ob[2] + c < b[0] || ob[1] - c > b[3] || ob[3] + c < b[1] { + continue; + } + self.insert(o, Some(&b)); + } + if let Shape::Via(p) = self.items[id].shape { + self.hole_reset(p.0, p.1); + } + } + } + + /// Distance to foreign copper for `net` at state index s. + pub fn fdist(&self, s: usize, net: i32) -> f32 { + self.f[s].fdist(net) + } + + /// Grid states (cell * 2 + layer, sorted) covered by the copper of `ids` on `layers`. + pub fn cells_of(&self, ids: &[usize], layers: u8) -> Vec<i32> { + let mut out = Vec::new(); + for &id in ids { + let it = &self.items[id]; + let (i0, j0, i1, j1) = self.window(&it.bbox, 0.05); + for j in j0..=j1 { + for i in i0..=i1 { + if self.item_dist(it, self.gx(i), self.gy(j)) <= 0.0 { + for l in 0..2 { + if it.on(l) && layers >> l & 1 == 1 { + out.push(((j * self.nx + i) * 2 + l) as i32); + } + } + } + } + } + } + out.sort_unstable(); + out.dedup(); + out + } + + /// A* from the copper of `src` to the copper of `tgt` (and `extra_tgt` cells, or any + /// B.Cu cell with `goal_layer1`). Returns the cell path (source first) and neck flags. + #[allow(clippy::too_many_arguments)] + pub fn route( + &mut self, + net: i32, + src: &[usize], + tgt: &[usize], + goal_layer1: bool, + w: f64, + wneck: f64, + via_d: f64, + neck_items: &[usize], + hxy: Option<Pt>, + extra_tgt: Option<&[i32]>, + o: &SearchOpts, + ) -> Option<(Vec<i32>, Vec<u8>)> { + let src_cells = self.cells_of(src, 3); + if src_cells.is_empty() { + return None; + } + let mut tc = if tgt.is_empty() { Vec::new() } else { self.cells_of(tgt, 3) }; + if let Some(e) = extra_tgt { + tc.extend_from_slice(e); + } + for &c in &tc { + self.tgt[c as usize] = 1; + } + let hxy = hxy.unwrap_or_else(|| match tgt.first() { + Some(&g) => match self.items[g].shape { + Shape::Pad(k) => self.pads[k].poly.centroid(), + Shape::Via(p) => p, + Shape::Seg(a, _) => a, + Shape::Cu(k) => self.cu[k][0], + }, + None => (self.x0, self.y0), + }); + let (hx, hy) = self.xy_cell(hxy.0, hxy.1); + let mut boxes = Vec::new(); + for &id in neck_items { + let b = self.items[id].bbox; + let (i0, j0) = self.xy_cell(b[0] - o.neck_zone, b[1] - o.neck_zone); + let (i1, j1) = self.xy_cell(b[2] + o.neck_zone, b[3] + o.neck_zone); + boxes.push([i0 as i32, j0 as i32, i1 as i32, j1 as i32]); + } + let mut window = [0, 0, self.nx as i32 - 1, self.ny as i32 - 1]; + if o.margin > 0.0 && !tgt.is_empty() { + let mut bb = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for &id in src.iter().chain(tgt) { + let b = self.items[id].bbox; + bb = [bb[0].min(b[0]), bb[1].min(b[1]), bb[2].max(b[2]), bb[3].max(b[3])]; + } + let (i0, j0, i1, j1) = self.window(&bb, o.margin); + window = [i0 as i32, j0 as i32, i1 as i32, j1 as i32]; + } + let args = SearchArgs { + window, + nx: self.nx, + n: self.n, + f: &self.f, + padd: &self.padd, + hole: &self.hole, + r_hole: (via_drill(via_d) / 2.0 + HOLE_HOLE + M) as f32, + via_gap: ((via_drill(via_d) + HOLE_HOLE) / RES).ceil() as u16 + 1, + cost: &self.costs[&self.cost], + soft: if self.soft_mode { Some(&self.soft) } else { None }, + hist: &self.hist, + pres: self.pres, + net, + src: &src_cells, + tgt: &self.tgt, + goal_layer1, + hx: hx as i32, + hy: hy as i32, + r_nom: (w / 2.0 + CLR + M) as f32, + r_neck: if wneck != 0.0 { (wneck / 2.0 + CLR + M) as f32 } else { 0.0 }, + r_via: (via_d / 2.0 + CLR + M) as f32, + r_vpad: (via_d / 2.0 + 0.05) as f32, + r_diag: RDIAG as f32, + neckbox: &boxes, + via_cost: o.via_cost as f32, + via_cmult: o.via_cmult as f32, + bmult: o.bmult as f32, + turn_cost: o.turn as f32, + allow_via: o.allow_via, + max_expand: o.max_expand, + layer_mask: o.layer_mask, + hweight: o.hweight as f32, + hug: o.hug as f32, + attract: if self.attract_cost > 0.0 { Some(&self.attract) } else { None }, + attract_cost: self.attract_cost, + neck: o.neck as f32, + }; + let t = std::time::Instant::now(); + let r = self.search.route(&args); + if std::env::var("ROUTER_TRACE").is_ok() { + eprintln!("ASTAR {:.6}", t.elapsed().as_secs_f64()); + } + if std::env::var("ROUTER_TRACE").is_ok() { + eprintln!("TRACE net={} src={} tgt={} first={:?} last={:?} hx={} hy={} len={:?}", net, src_cells.len(), tc.len(), src_cells.first(), src_cells.last(), hx, hy, r.as_ref().map(|(p, _)| (p.len(), p[p.len() - 1], p[0]))); + } + for &c in &tc { + self.tgt[c as usize] = 0; + } + r.map(|(mut p, mut nk)| { + p.reverse(); + nk.reverse(); + (p, nk) + }) + } + + /// Cell path to segments (collinear steps of equal width merged) and vias. + pub fn path_to_geom(&self, path: &[i32], neck: &[u8], w: f64, wneck: f64) -> (Vec<Seg>, Vec<Pt>) { + let pts: Vec<(usize, usize, usize, bool)> = path + .iter() + .zip(neck) + .map(|(&s, &nk)| { + let (l, c) = (s as usize & 1, s as usize >> 1); + (l, c % self.nx, c / self.nx, nk != 0) + }) + .collect(); + let width = |a: &(usize, usize, usize, bool), b: &(usize, usize, usize, bool)| if wneck != 0.0 && (a.3 || b.3) { wneck } else { w }; + let mut segs = Vec::new(); + let mut vias = Vec::new(); + let flush = |run: &[(usize, usize, usize, bool)], segs: &mut Vec<Seg>| { + if run.len() < 2 { + return; + } + let mut k = 0; + while k < run.len() - 1 { + let (l, i, j, _) = run[k]; + let wd = width(&run[k], &run[k + 1]); + let d = (run[k + 1].1 as i64 - i as i64, run[k + 1].2 as i64 - j as i64); + let mut m = k + 1; + while m < run.len() - 1 { + let w2 = width(&run[m], &run[m + 1]); + if (run[m + 1].1 as i64 - run[m].1 as i64, run[m + 1].2 as i64 - run[m].2 as i64) != d || w2 != wd { + break; + } + m += 1; + } + segs.push((l, self.cell_xy(i, j), self.cell_xy(run[m].1, run[m].2), wd)); + k = m; + } + }; + let mut run = vec![pts[0]]; + for &p in &pts[1..] { + if p.0 != run[run.len() - 1].0 { + flush(&run, &mut segs); + vias.push(self.cell_xy(p.1, p.2)); + run = vec![p]; + } else { + run.push(p); + } + } + flush(&run, &mut segs); + (segs, vias) + } + + pub fn seg_item(net: i32, l: usize, a: Pt, b: Pt, w: f64, owner: Owner) -> Item { + let bbox = [a.0.min(b.0) - w / 2.0, a.1.min(b.1) - w / 2.0, a.0.max(b.0) + w / 2.0, a.1.max(b.1) + w / 2.0]; + Item { shape: Shape::Seg(a, b), net, layers: 1 << l, w, bbox, owner, soft: false } + } + + pub fn via_item(net: i32, p: Pt, d: f64, layers: u8, owner: Owner) -> Item { + let r = d / 2.0; + Item { shape: Shape::Via(p), net, layers, w: d, bbox: [p.0 - r, p.1 - r, p.0 + r, p.1 + r], owner, soft: false } + } + + pub fn commit(&mut self, net: i32, segs: &[Seg], vias: &[Pt], via_d: f64) -> Vec<usize> { + let o = self.commit_owner; + let mut items: Vec<Item> = segs.iter().map(|&(l, a, b, w)| Board::seg_item(net, l, a, b, w, o)).collect(); + items.extend(vias.iter().map(|&v| Board::via_item(net, v, via_d, 3, o))); + let soft = self.soft_mode; + items.into_iter().map(|it| self.add(Item { soft, ..it })).collect() + } +} |
