Skip to main content

brep_ecad_core/
autoroute.rs

1//! Grid-based autorouter.
2//!
3//! Each net is routed island to island (a Prim-style tree) with A* over a uniform
4//! grid on every copper layer, using 45° moves and through vias.
5//!
6//! Clearance is exact, not approximated by the grid. Every copper obstacle is convex
7//! (rectangles, capsules, discs, outline edges). If both ends of a move of length `L`
8//! lie at least `T` from a convex shape, every point of the move lies at least
9//! `√(T² − L²/4)` from it: a chord that dips closer would be shorter than `L`. Nodes
10//! are therefore legal only at `T = √(Q² + pitch²/2)`, with `Q = clearance + width/2`,
11//! which guarantees `Q` along every straight or diagonal move, so routed copper passes
12//! the exact-geometry DRC while the extra margin stays a few micrometres.
13//!
14//! Net classes. Each net is routed at its class's track width and via
15//! ([`crate::board::DesignRules::width_for`], [`crate::board::DesignRules::via_for`]),
16//! and the `clearance` above is PER PAIR: between the net being routed and each
17//! obstacle it is [`crate::board::DesignRules::clearance_between_classes`] of their
18//! two classes, the larger of the two, which is the rule DRC checks. The grid keeps
19//! one set of maps per `Profile` (a track width or via diameter, and the class of
20//! the net using it), and grows each obstacle on a map by the pair's clearance; a
21//! board with no classes has exactly the maps, and routes exactly as, before
22//! classes existed. A net that is blocked by earlier routes is retried with those routes allowed
23//! at a high cost; the nets it crosses are ripped up and queued again, with bounded
24//! attempts. Work is split into [`RouteJob::step`] calls, measured in node
25//! expansions rather than wall time, so interactive and WebAssembly hosts stay
26//! responsive.
27//!
28//! Vias follow the board's [`ViaPolicy`]. `Avoid` routes exactly as `Allow` does, so
29//! it connects every net `Allow` would, and then removes vias: each net that has any
30//! is rerouted against the finished board, first searching for a route with no via
31//! at all, and keeps the new copper only if it connects everything with fewer vias.
32//! Routing with vias priced out from the start was tried and rejected: long
33//! single-layer detours fill the board early and later nets fail to route.
34use crate::board::{
35    Board, Connectivity, CopperItem, CopperRef, DesignRules, NetClass, Shape, Track, Via, ViaPolicy,
36};
37use crate::{Document, Netlist, Point, Uuid};
38use std::cmp::Reverse;
39use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
40
41/// Pad entry points for one net.
42#[derive(Default)]
43struct Stubs {
44    /// Per seed node, the stub from the pad centre up to (not including) the node.
45    paths: HashMap<u32, Vec<Point>>,
46    /// Seed nodes inside large pads, such as exposed thermal pads, where a via fits.
47    vias: HashSet<u32>,
48}
49
50/// Claim owner for copper that no routed net may touch.
51const BLOCKED: u32 = u32::MAX;
52/// Upper bound on grid cells per layer; the pitch is coarsened to stay below it.
53const MAX_CELLS: usize = 1_500_000;
54const DIRECTIONS: [(i64, i64); 8] = [
55    (1, 0),
56    (1, 1),
57    (0, 1),
58    (-1, 1),
59    (-1, 0),
60    (-1, -1),
61    (0, -1),
62    (1, -1),
63];
64const NO_DIRECTION: u8 = 8;
65const NO_PARENT: u32 = u32::MAX;
66/// Width of the band around routed pads that other nets are discouraged from using.
67const APPROACH: i32 = 800;
68/// Rip-up retries a single net may initiate.
69const MAX_ATTEMPTS: u32 = 4;
70/// Rerouting passes over nets with vias; another pass runs only if one improved.
71const MAX_CLEANUP_PASSES: u32 = 3;
72
73#[derive(Clone, Copy, Debug)]
74struct Grid {
75    origin: Point,
76    pitch: i32,
77    width: usize,
78    height: usize,
79    layers: usize,
80}
81impl Grid {
82    fn cells(&self) -> usize {
83        self.width * self.height
84    }
85    fn centre(&self, cell: usize) -> Point {
86        Point::new(
87            self.origin.x + (cell % self.width) as i32 * self.pitch,
88            self.origin.y + (cell / self.width) as i32 * self.pitch,
89        )
90    }
91    /// Inclusive cell rectangle whose centres lie within the world bounds.
92    fn span(&self, min: Point, max: Point) -> Option<(usize, usize, usize, usize)> {
93        let pitch = i64::from(self.pitch);
94        let low = |v: i32, o: i32| (i64::from(v) - i64::from(o)).div_euclid(pitch) + 1;
95        let high = |v: i32, o: i32| (i64::from(v) - i64::from(o)).div_euclid(pitch);
96        let x0 = (low(min.x - 1, self.origin.x)).max(0);
97        let y0 = (low(min.y - 1, self.origin.y)).max(0);
98        let x1 = high(max.x, self.origin.x).min(self.width as i64 - 1);
99        let y1 = high(max.y, self.origin.y).min(self.height as i64 - 1);
100        (x0 <= x1 && y0 <= y1).then_some((x0 as usize, x1 as usize, y0 as usize, y1 as usize))
101    }
102}
103
104/// Whether a disc lies entirely within a shape.
105fn disc_inside(shape: &Shape, at: Point, radius: i32) -> bool {
106    match *shape {
107        Shape::Rect { min, max } => {
108            at.x - radius >= min.x
109                && at.x + radius <= max.x
110                && at.y - radius >= min.y
111                && at.y + radius <= max.y
112        }
113        Shape::Capsule { a, b, radius: r } => {
114            crate::board::point_segment_distance(at, a, b) + f64::from(radius) <= f64::from(r)
115        }
116    }
117}
118
119/// Visit cells whose centres are closer than `radius` to the shape.
120fn for_cells_near(grid: &Grid, shape: &Shape, radius: f64, mut visit: impl FnMut(usize)) {
121    let (min, max) = shape.bounds();
122    let reach = radius.ceil() as i32 + 1;
123    let Some((x0, x1, y0, y1)) = grid.span(
124        Point::new(min.x.saturating_sub(reach), min.y.saturating_sub(reach)),
125        Point::new(max.x.saturating_add(reach), max.y.saturating_add(reach)),
126    ) else {
127        return;
128    };
129    for y in y0..=y1 {
130        for x in x0..=x1 {
131            let cell = y * grid.width + x;
132            if shape.distance_to_point(grid.centre(cell)) < radius {
133                visit(cell);
134            }
135        }
136    }
137}
138
139/// Per-cell claims by copper owners. Each owner claims a cell at most once, so a
140/// cell is usable by net `n` when unclaimed or claimed only by `n`.
141#[derive(Clone)]
142struct Claims {
143    count: Vec<u16>,
144    sum: Vec<u32>,
145}
146impl Claims {
147    fn new(cells: usize) -> Self {
148        Self {
149            count: vec![0; cells],
150            sum: vec![0; cells],
151        }
152    }
153    fn free(&self, cell: usize, net: u32) -> bool {
154        let count = self.count[cell];
155        count == 0 || (count == 1 && self.sum[cell] == net)
156    }
157    fn add(&mut self, cell: usize, owner: u32) {
158        self.count[cell] = self.count[cell].saturating_add(1);
159        self.sum[cell] = self.sum[cell].wrapping_add(owner);
160    }
161    fn remove(&mut self, cell: usize, owner: u32) {
162        self.count[cell] -= 1;
163        self.sum[cell] = self.sum[cell].wrapping_sub(owner);
164    }
165}
166
167/// What one set of grid maps is inflated for: copper `size` across (a track width
168/// or a via diameter) of a net in class `class`, an index into
169/// [`RouteJob::gaps`]. Obstacle `o` is kept `gaps[class][o's class]` from it.
170#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
171struct Profile {
172    size: i32,
173    class: usize,
174}
175
176struct RouteNet {
177    name: String,
178    width: i32,
179    /// The net's class, an index into [`RouteJob::gaps`].
180    class: usize,
181    /// Its via diameter and drill, its class's.
182    via: (i32, i32),
183    /// The [`Profile`]s its tracks and its vias are searched on.
184    profile: usize,
185    via_profile: usize,
186    /// Copper item indices of each island carrying the net.
187    islands: Vec<Vec<usize>>,
188    span: i64,
189}
190
191#[derive(Default)]
192struct NetState {
193    tracks: Vec<Track>,
194    vias: Vec<Via>,
195    /// Route claims as `map * cells + cell`.
196    claimed: HashSet<u64>,
197    /// Island connections that could not be made in the last attempt.
198    missing: usize,
199    routed: bool,
200}
201
202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
203pub struct Progress {
204    pub total_nets: usize,
205    pub completed_nets: usize,
206    pub failed_nets: usize,
207    pub rip_ups: usize,
208    /// Every net is routed and nets with vias are being rerouted to drop them.
209    pub removing_vias: bool,
210    pub done: bool,
211}
212
213#[derive(Clone, Debug, Default, PartialEq)]
214pub struct RouteOutcome {
215    pub tracks: Vec<Track>,
216    pub vias: Vec<Via>,
217    /// Nets left with unrouted connections.
218    pub unrouted: Vec<String>,
219    /// Grid pitch actually used, after any coarsening for large boards.
220    pub pitch: i32,
221}
222impl RouteOutcome {
223    /// Add the routed copper to the board. Existing copper is kept.
224    pub fn apply(self, board: &mut Board) {
225        board.tracks.extend(self.tracks);
226        board.vias.extend(self.vias);
227    }
228}
229
230/// A resumable routing run over a snapshot of the board.
231pub struct RouteJob {
232    grid: Grid,
233    /// The track profiles of routed nets, then their via profiles; one set of
234    /// maps each.
235    profiles: Vec<Profile>,
236    /// The clearance between copper of two classes, by class index: filled once
237    /// from [`crate::board::DesignRules::clearance_between_classes`], the one
238    /// lookup DRC and the zone fill use, and the only clearance this router reads.
239    /// Class 0 is the class of copper on no net, Default.
240    gaps: Vec<Vec<i32>>,
241    /// The largest entry of `gaps`, for bounding-box prefilters.
242    max_gap: i32,
243    items: Vec<CopperItem>,
244    /// The class of each static item: that of the nets its island carries.
245    item_class: Vec<usize>,
246    /// Claim owner of each static item: a routed net index or `BLOCKED`.
247    owners: Vec<u32>,
248    outline: Vec<Point>,
249    edge_clearance: i32,
250    static_claims: Vec<Claims>,
251    route_claims: Vec<Claims>,
252    /// Per layer, the approaches to routed nets' pads. Other nets pay to pass
253    /// through them, which leaves room for fan-out from fine-pitch parts.
254    approaches: Vec<Claims>,
255    nets: Vec<RouteNet>,
256    states: Vec<NetState>,
257    queue: VecDeque<usize>,
258    attempts: Vec<u32>,
259    rip_ups: usize,
260    rip_up_limit: usize,
261    expansions: u64,
262    cost: Vec<u32>,
263    parent: Vec<u32>,
264    direction: Vec<u8>,
265    stamp: Vec<u32>,
266    generation: u32,
267    /// How often each node has been contested; raises its cost for every net.
268    history: Vec<u16>,
269    /// Cells where a via would touch a pad; through vias span every layer.
270    no_via: Vec<bool>,
271    vias: ViaPolicy,
272    /// Nets still to reroute in the current via clean-up pass; `None` until routing
273    /// has finished and the first pass begins.
274    cleanup: Option<VecDeque<usize>>,
275    cleanup_passes: u32,
276    /// Where copper given up by nets that lost vias this pass sat, grown by the
277    /// search margin. Only nets near it can gain from another pass.
278    cleanup_freed: Vec<(Point, Point)>,
279}
280
281impl RouteJob {
282    /// Prepare to connect every unrouted connection. Existing copper is kept and
283    /// treated as part of its net, or as an obstacle.
284    pub fn new(board: &Board, netlist: &Netlist) -> Self {
285        let conn = board.connectivity(netlist);
286        let rules = &board.rules;
287        // Every class in play, Default first, so netless copper is class 0.
288        let mut classes: Vec<NetClass> = vec![rules.default_class()];
289        let mut class_index = |class: NetClass| {
290            classes
291                .iter()
292                .position(|c| c.name == class.name)
293                .unwrap_or_else(|| {
294                    classes.push(class);
295                    classes.len() - 1
296                })
297        };
298        let island_class: Vec<usize> = conn
299            .island_nets
300            .iter()
301            .map(|nets| class_index(rules.class_of_nets(nets.iter().map(String::as_str))))
302            .collect();
303        let item_class: Vec<usize> = conn.islands.iter().map(|&i| island_class[i]).collect();
304        let mut island_items = vec![vec![]; conn.island_count];
305        for (i, island) in conn.islands.iter().enumerate() {
306            island_items[*island].push(i);
307        }
308        let mut net_islands: BTreeMap<&str, BTreeSet<usize>> = BTreeMap::new();
309        for (i, net) in conn.item_nets.iter().enumerate() {
310            if let Some(net) = net {
311                net_islands.entry(net).or_default().insert(conn.islands[i]);
312            }
313        }
314        let mut nets: Vec<RouteNet> = net_islands
315            .into_iter()
316            .filter(|(_, islands)| islands.len() > 1)
317            .map(|(name, islands)| {
318                let centres: Vec<Point> = islands
319                    .iter()
320                    .flat_map(|&s| island_items[s].iter())
321                    .map(|&i| conn.items[i].shape.center())
322                    .collect();
323                let (x0, x1) = centres
324                    .iter()
325                    .fold((i32::MAX, i32::MIN), |(a, b), p| (a.min(p.x), b.max(p.x)));
326                let (y0, y1) = centres
327                    .iter()
328                    .fold((i32::MAX, i32::MIN), |(a, b), p| (a.min(p.y), b.max(p.y)));
329                let class = rules.class_of(Some(name));
330                RouteNet {
331                    name: name.to_owned(),
332                    width: rules.width_for(name),
333                    via: (class.via_diameter, class.via_drill),
334                    class: class_index(class),
335                    profile: 0,
336                    via_profile: 0,
337                    islands: islands.iter().map(|&s| island_items[s].clone()).collect(),
338                    span: i64::from(x1) - i64::from(x0) + i64::from(y1) - i64::from(y0),
339                }
340            })
341            .collect();
342        nets.sort_by(|a, b| a.span.cmp(&b.span).then_with(|| a.name.cmp(&b.name)));
343        let gaps: Vec<Vec<i32>> = classes
344            .iter()
345            .map(|a| {
346                classes
347                    .iter()
348                    .map(|b| DesignRules::clearance_between_classes(a, b).0)
349                    .collect()
350            })
351            .collect();
352        let max_gap = gaps.iter().flatten().copied().max().unwrap_or(0);
353        let tracks: Vec<Profile> = nets
354            .iter()
355            .map(|n| Profile {
356                size: n.width,
357                class: n.class,
358            })
359            .collect::<BTreeSet<_>>()
360            .into_iter()
361            .collect();
362        let vias: Vec<Profile> = nets
363            .iter()
364            .map(|n| Profile {
365                size: n.via.0,
366                class: n.class,
367            })
368            .collect::<BTreeSet<_>>()
369            .into_iter()
370            .collect();
371        for net in &mut nets {
372            let (track, via) = (
373                Profile {
374                    size: net.width,
375                    class: net.class,
376                },
377                Profile {
378                    size: net.via.0,
379                    class: net.class,
380                },
381            );
382            net.profile = tracks.binary_search(&track).unwrap_or(0);
383            net.via_profile = tracks.len() + vias.binary_search(&via).unwrap_or(0);
384        }
385        let thinnest = tracks
386            .iter()
387            .map(|p| &p.size)
388            .chain(board.tracks.iter().map(|t| &t.width))
389            .min()
390            .copied()
391            .unwrap_or(rules.track_width);
392        let profiles: Vec<Profile> = tracks.into_iter().chain(vias).collect();
393        let (min, max) = board.outline_bounds();
394        let dims = |pitch: i32| {
395            (
396                ((i64::from(max.x) - i64::from(min.x)) / i64::from(pitch) + 1) as usize,
397                ((i64::from(max.y) - i64::from(min.y)) / i64::from(pitch) + 1) as usize,
398            )
399        };
400        let mut pitch = rules.routing_grid.min(thinnest * 7 / 10).max(10);
401        while {
402            let (w, h) = dims(pitch);
403            w * h > MAX_CELLS
404        } {
405            pitch += pitch / 4 + 1;
406        }
407        let (width, height) = dims(pitch);
408        let grid = Grid {
409            origin: min,
410            pitch,
411            width,
412            height,
413            layers: usize::from(board.layer_count.max(1)),
414        };
415        let cells = grid.cells();
416        let nodes = cells * grid.layers;
417        let maps = profiles.len() * grid.layers;
418        let count = nets.len();
419        let mut job = Self {
420            grid,
421            gaps,
422            max_gap,
423            items: vec![],
424            item_class,
425            owners: vec![],
426            outline: board.outline.clone(),
427            edge_clearance: rules.edge_clearance,
428            static_claims: vec![Claims::new(cells); maps],
429            route_claims: vec![Claims::new(cells); maps],
430            approaches: vec![Claims::new(cells); grid.layers],
431            states: (0..count).map(|_| NetState::default()).collect(),
432            queue: (0..count).collect(),
433            attempts: vec![0; count],
434            rip_ups: 0,
435            rip_up_limit: count * MAX_ATTEMPTS as usize + 16,
436            expansions: 0,
437            cost: vec![0; nodes],
438            parent: vec![NO_PARENT; nodes],
439            direction: vec![NO_DIRECTION; nodes],
440            stamp: vec![0; nodes],
441            generation: 0,
442            history: vec![0; nodes],
443            no_via: vec![false; cells],
444            vias: rules.autoroute_vias,
445            cleanup: None,
446            cleanup_passes: 0,
447            cleanup_freed: vec![],
448            profiles,
449            nets,
450        };
451        job.paint_static(board, &conn);
452        job.items = conn.items;
453        job
454    }
455
456    /// Distance from a node to an obstacle below which the node is unusable for a
457    /// profile, so that moves between usable nodes keep `gap` (see the module docs).
458    fn keep_out(&self, gap: i32, profile: usize) -> f64 {
459        let q = f64::from(gap) + f64::from(self.profiles[profile].size) / 2.;
460        let pitch = f64::from(self.grid.pitch);
461        (q * q + pitch * pitch / 2.).sqrt() + 1.
462    }
463
464    fn next_generation(&mut self) -> u32 {
465        if self.generation == u32::MAX {
466            self.stamp.fill(0);
467            self.generation = 0;
468        }
469        self.generation += 1;
470        self.generation
471    }
472
473    fn paint_static(&mut self, board: &Board, conn: &Connectivity) {
474        let index: BTreeMap<&str, u32> = self
475            .nets
476            .iter()
477            .enumerate()
478            .map(|(i, n)| (n.name.as_str(), i as u32))
479            .collect();
480        self.owners = conn
481            .islands
482            .iter()
483            .map(|island| {
484                conn.island_net(*island)
485                    .and_then(|net| index.get(net))
486                    .copied()
487                    .unwrap_or(BLOCKED)
488            })
489            .collect();
490        let mut owners: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
491        for (i, owner) in self.owners.iter().enumerate() {
492            owners.entry(*owner).or_default().push(i);
493        }
494        let grid = self.grid;
495        let cells = grid.cells();
496        // Vias stay off pads, including pads of their own net: a via in a solder
497        // land wicks solder. Large thermal pads opt back in through `Stubs::vias`.
498        // One map serves every net, so it is sized for the largest via and its
499        // class's own clearance; other nets' pads also keep their pair clearance
500        // through the static claims.
501        let via_reach = self
502            .profiles
503            .iter()
504            .filter(|p| {
505                self.nets
506                    .iter()
507                    .any(|n| self.profiles[n.via_profile] == **p)
508            })
509            .map(|p| f64::from(p.size / 2 + self.gaps[p.class][p.class] / 2))
510            .fold(0., f64::max);
511        for item in conn
512            .items
513            .iter()
514            .filter(|i| matches!(i.owner, CopperRef::Pad { .. }))
515        {
516            let no_via = &mut self.no_via;
517            for_cells_near(&grid, &item.shape, via_reach, |cell| no_via[cell] = true);
518        }
519        let outside: Vec<bool> = (0..cells)
520            .map(|cell| !board.outline_contains(grid.centre(cell)))
521            .collect();
522        // The approach band around routed pads: as wide as the widest track keeps
523        // from copper of its own class, plus `APPROACH`.
524        let approach = (0..self.profiles.len())
525            .filter(|&p| self.nets.iter().any(|n| n.profile == p))
526            .map(|p| self.keep_out(self.gaps[self.profiles[p].class][self.profiles[p].class], p))
527            .fold(0., f64::max)
528            + f64::from(APPROACH);
529        for class in 0..self.profiles.len() {
530            let routing = self.profiles[class].class;
531            for (&owner, members) in &owners {
532                let generation = self.next_generation();
533                for &i in members {
534                    let item = &conn.items[i];
535                    let radius = self.keep_out(self.gaps[routing][self.item_class[i]], class);
536                    for layer in item.layers.0..=item.layers.1 {
537                        let layer = usize::from(layer);
538                        let claims = &mut self.static_claims[class * grid.layers + layer];
539                        let stamp = &mut self.stamp;
540                        for_cells_near(&grid, &item.shape, radius, |cell| {
541                            let node = layer * cells + cell;
542                            if stamp[node] != generation {
543                                stamp[node] = generation;
544                                claims.add(cell, owner);
545                            }
546                        });
547                    }
548                }
549            }
550            if class == 0 {
551                let radius = approach;
552                for (&owner, members) in owners.iter().filter(|(o, _)| **o != BLOCKED) {
553                    let generation = self.next_generation();
554                    for &i in members {
555                        let item = &conn.items[i];
556                        if !matches!(item.owner, CopperRef::Pad { .. }) {
557                            continue;
558                        }
559                        for layer in item.layers.0..=item.layers.1 {
560                            let layer = usize::from(layer);
561                            let claims = &mut self.approaches[layer];
562                            let stamp = &mut self.stamp;
563                            for_cells_near(&grid, &item.shape, radius, |cell| {
564                                let node = layer * cells + cell;
565                                if stamp[node] != generation {
566                                    stamp[node] = generation;
567                                    claims.add(cell, owner);
568                                }
569                            });
570                        }
571                    }
572                }
573            }
574            let edge_radius = self.keep_out(board.rules.edge_clearance, class);
575            for layer in 0..grid.layers {
576                let claims = &mut self.static_claims[class * grid.layers + layer];
577                for (cell, out) in outside.iter().enumerate() {
578                    if *out {
579                        claims.add(cell, BLOCKED);
580                    }
581                }
582                for (a, b) in board.outline_edges() {
583                    for_cells_near(&grid, &Shape::segment(a, b, 0), edge_radius, |cell| {
584                        claims.add(cell, BLOCKED)
585                    });
586                }
587            }
588        }
589    }
590
591    fn map(&self, class: usize, node: usize) -> (usize, usize) {
592        let cells = self.grid.cells();
593        (class * self.grid.layers + node / cells, node % cells)
594    }
595    /// Whether a node may carry the net's track, and whether that uses another
596    /// net's route (only permitted in soft mode).
597    fn legal(&self, net: usize, node: usize, soft: bool) -> Option<bool> {
598        let (map, cell) = self.map(self.nets[net].profile, node);
599        if !self.static_claims[map].free(cell, net as u32) {
600            return None;
601        }
602        let conflict = !self.route_claims[map].free(cell, net as u32);
603        (!conflict || soft).then_some(conflict)
604    }
605    fn via_legal(&self, net: usize, cell: usize, soft: bool) -> Option<bool> {
606        let class = self.nets[net].via_profile;
607        let mut conflict = false;
608        for layer in 0..self.grid.layers {
609            let map = class * self.grid.layers + layer;
610            if !self.static_claims[map].free(cell, net as u32) {
611                return None;
612            }
613            conflict |= !self.route_claims[map].free(cell, net as u32);
614        }
615        (!conflict || soft).then_some(conflict)
616    }
617
618    /// Statically legal nodes inside an island's copper. Pads record the stub back to
619    /// their centre; a pad with no usable interior node escapes to nearby grid nodes.
620    fn seeds(&self, net: usize, island: usize, stubs: &mut Stubs) -> Vec<u32> {
621        let cells = self.grid.cells();
622        let class = self.nets[net].profile;
623        let usable = |node: u32| {
624            let (map, cell) = self.map(class, node as usize);
625            self.static_claims[map].free(cell, net as u32)
626        };
627        let mut seeds = vec![];
628        for &i in &self.nets[net].islands[island] {
629            let item = &self.items[i];
630            let is_pad = matches!(item.owner, CopperRef::Pad { .. });
631            for layer in item.layers.0..=item.layers.1 {
632                let base = usize::from(layer) * cells;
633                let mut inside = vec![];
634                for_cells_near(&self.grid, &item.shape, 0.5, |cell| {
635                    let node = (base + cell) as u32;
636                    if usable(node) {
637                        inside.push(node);
638                    }
639                });
640                if is_pad {
641                    if inside.is_empty() {
642                        for (node, stub) in self.escapes(net, item, layer) {
643                            stubs.paths.entry(node).or_insert(stub);
644                            inside.push(node);
645                        }
646                    } else {
647                        let (min, max) = item.shape.bounds();
648                        let diameter = self.nets[net].via.0;
649                        let radius = diameter / 2;
650                        let large = (max.x - min.x).min(max.y - min.y) >= 3 * diameter;
651                        for node in &inside {
652                            stubs
653                                .paths
654                                .entry(*node)
655                                .or_insert_with(|| vec![item.shape.center()]);
656                            let at = self.grid.centre(*node as usize % cells);
657                            if large && disc_inside(&item.shape, at, radius) {
658                                stubs.vias.insert(*node);
659                            }
660                        }
661                    }
662                }
663                seeds.extend(inside);
664            }
665        }
666        seeds.sort_unstable();
667        seeds.dedup();
668        seeds
669    }
670
671    /// Fan-out from a pad whose interior is too tight for the grid: leave the pad
672    /// centre along each axis to a grid line past the pad, then jog onto the nearest
673    /// grid node. Each stub is checked against exact copper geometry.
674    fn escapes(&self, net: usize, pad: &CopperItem, layer: u8) -> Vec<(u32, Vec<Point>)> {
675        let grid = self.grid;
676        let pitch = i64::from(grid.pitch);
677        let width = self.nets[net].width;
678        let centre = pad.shape.center();
679        let (min, max) = pad.shape.bounds();
680        let column = |v: i32, o: i32| (i64::from(v) - i64::from(o)) as f64 / pitch as f64;
681        let mut escapes = vec![];
682        for (dx, dy) in [(1i64, 0i64), (-1, 0), (0, 1), (0, -1)] {
683            for k in 0..6 {
684                let (gx, gy) = if dx != 0 {
685                    let edge = column(if dx > 0 { max.x } else { min.x }, grid.origin.x);
686                    let gx = if dx > 0 {
687                        edge.floor() as i64 + 1 + k
688                    } else {
689                        edge.ceil() as i64 - 1 - k
690                    };
691                    (gx, column(centre.y, grid.origin.y).round() as i64)
692                } else {
693                    let edge = column(if dy > 0 { max.y } else { min.y }, grid.origin.y);
694                    let gy = if dy > 0 {
695                        edge.floor() as i64 + 1 + k
696                    } else {
697                        edge.ceil() as i64 - 1 - k
698                    };
699                    (column(centre.x, grid.origin.x).round() as i64, gy)
700                };
701                if gx < 0 || gy < 0 || gx >= grid.width as i64 || gy >= grid.height as i64 {
702                    break;
703                }
704                let cell = gy as usize * grid.width + gx as usize;
705                let node = (usize::from(layer) * grid.cells() + cell) as u32;
706                let target = grid.centre(cell);
707                let jog = if dx != 0 {
708                    Point::new(target.x, centre.y)
709                } else {
710                    Point::new(centre.x, target.y)
711                };
712                let (map, _) = self.map(self.nets[net].profile, node as usize);
713                if !self.static_claims[map].free(cell, net as u32) {
714                    continue;
715                }
716                let path = crate::board::simplify_path(vec![centre, jog, target]);
717                if path
718                    .windows(2)
719                    .all(|s| self.clear(net, &Shape::segment(s[0], s[1], width), layer))
720                {
721                    let mut stub = path;
722                    stub.pop();
723                    escapes.push((node, stub));
724                    break;
725                }
726            }
727        }
728        escapes
729    }
730
731    /// Exact clearance of new copper against the board edge, other owners' static
732    /// copper, and other nets' routes.
733    fn clear(&self, net: usize, shape: &Shape, layer: u8) -> bool {
734        let gaps = &self.gaps[self.nets[net].class];
735        let (min, max) = shape.bounds();
736        let near = |other: &Shape| {
737            let (a, b) = other.bounds();
738            a.x <= max.x.saturating_add(self.max_gap)
739                && b.x >= min.x.saturating_sub(self.max_gap)
740                && a.y <= max.y.saturating_add(self.max_gap)
741                && b.y >= min.y.saturating_sub(self.max_gap)
742        };
743        let statics = self
744            .items
745            .iter()
746            .zip(&self.owners)
747            .zip(&self.item_class)
748            .all(|((item, owner), class)| {
749                *owner == net as u32
750                    || layer < item.layers.0
751                    || layer > item.layers.1
752                    || !near(&item.shape)
753                    || shape.distance(&item.shape) >= f64::from(gaps[*class])
754            });
755        let inside = crate::board::polygon_contains(&self.outline, shape.center())
756            && self.outline_edges().all(|(a, b)| {
757                shape.distance(&Shape::segment(a, b, 0)) >= f64::from(self.edge_clearance)
758            });
759        let routes = self.states.iter().enumerate().all(|(j, state)| {
760            let clearance = f64::from(gaps[self.nets[j].class]);
761            j == net
762                || (state
763                    .tracks
764                    .iter()
765                    .filter(|t| t.layer == layer)
766                    .flat_map(|t| t.segments())
767                    .all(|other| !near(&other) || shape.distance(&other) >= clearance)
768                    && state.vias.iter().all(|v| {
769                        let other = Shape::circle(v.at, v.diameter / 2);
770                        !near(&other) || shape.distance(&other) >= clearance
771                    }))
772        });
773        statics && inside && routes
774    }
775    fn outline_edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
776        let n = self.outline.len();
777        (0..n).map(move |i| (self.outline[i], self.outline[(i + 1) % n]))
778    }
779
780    fn cell_box(&self, nodes: impl Iterator<Item = u32>) -> Option<(i64, i64, i64, i64)> {
781        let cells = self.grid.cells();
782        nodes.fold(None, |b, node| {
783            let cell = node as usize % cells;
784            let (x, y) = (
785                (cell % self.grid.width) as i64,
786                (cell / self.grid.width) as i64,
787            );
788            Some(match b {
789                None => (x, x, y, y),
790                Some((x0, x1, y0, y1)) => (x0.min(x), x1.max(x), y0.min(y), y1.max(y)),
791            })
792        })
793    }
794
795    #[allow(clippy::too_many_arguments)]
796    fn search(
797        &mut self,
798        net: usize,
799        sources: &[u32],
800        targets: &HashMap<u32, usize>,
801        boxes: &[(i64, i64, i64, i64)],
802        window: Option<(i64, i64, i64, i64)>,
803        soft: bool,
804        stubs: &Stubs,
805        via_cost: Option<u32>,
806    ) -> Option<Vec<u32>> {
807        let generation = self.next_generation();
808        let grid = self.grid;
809        let cells = grid.cells();
810        let pitch = u32::try_from(grid.pitch).unwrap_or(1);
811        let straight = pitch;
812        let diagonal = (f64::from(pitch) * std::f64::consts::SQRT_2 * 1.15).round() as u32;
813        let diagonal_floor = (f64::from(pitch) * std::f64::consts::SQRT_2).floor() as u32;
814        let cross_grain = pitch / 2;
815        let bends = [0, pitch, 3 * pitch];
816        // Sharing is cheap on the first retry, so a blocked net takes its natural path
817        // and displaces the other net; repeated retries make sharing progressively
818        // dearer so contested nets settle instead of trading places.
819        let conflict_cost = pitch * (1 + 2 * self.attempts[net]);
820        let history_cost = pitch.div_ceil(2);
821        let approach_cost = 3 * pitch;
822        // Paths start and end near pad centres, so stubs stay short and square.
823        let stub = |node: usize| {
824            stubs.paths.get(&(node as u32)).map_or(0, |points| {
825                let mut length = 0.;
826                let mut last = grid.centre(node % cells);
827                for p in points.iter().rev() {
828                    length += f64::from(last.x - p.x).hypot(f64::from(last.y - p.y));
829                    last = *p;
830                }
831                length.round() as u32
832            })
833        };
834        let (x0, x1, y0, y1) =
835            window.unwrap_or((0, grid.width as i64 - 1, 0, grid.height as i64 - 1));
836        let heuristic = |node: usize| -> u32 {
837            let cell = node % cells;
838            let (x, y) = ((cell % grid.width) as i64, (cell / grid.width) as i64);
839            boxes
840                .iter()
841                .map(|&(bx0, bx1, by0, by1)| {
842                    let dx = (bx0 - x).max(x - bx1).max(0) as u32;
843                    let dy = (by0 - y).max(y - by1).max(0) as u32;
844                    straight
845                        .saturating_mul(dx.max(dy) - dx.min(dy))
846                        .saturating_add(diagonal_floor.saturating_mul(dx.min(dy)))
847                })
848                .min()
849                .unwrap_or(0)
850        };
851        let mut heap = BinaryHeap::new();
852        for &source in sources {
853            let node = source as usize;
854            if self.legal(net, node, soft).is_none() {
855                continue;
856            }
857            let start = stub(node);
858            self.stamp[node] = generation;
859            self.cost[node] = start;
860            self.parent[node] = NO_PARENT;
861            self.direction[node] = NO_DIRECTION;
862            heap.push(Reverse((start + heuristic(node), start, source)));
863        }
864        while let Some(Reverse((_, g, node))) = heap.pop() {
865            let node = node as usize;
866            if g != self.cost[node] {
867                continue;
868            }
869            self.expansions += 1;
870            if targets.contains_key(&(node as u32)) {
871                let mut path = vec![node as u32];
872                while let Some(&last) = path.last() {
873                    let parent = self.parent[last as usize];
874                    if parent == NO_PARENT {
875                        break;
876                    }
877                    path.push(parent);
878                }
879                path.reverse();
880                return Some(path);
881            }
882            let (layer, cell) = (node / cells, node % cells);
883            let (x, y) = ((cell % grid.width) as i64, (cell / grid.width) as i64);
884            let came = self.direction[node];
885            let mut relax = |job: &mut Self, next: usize, cost: u32, direction: u8| {
886                if job.stamp[next] != generation || cost < job.cost[next] {
887                    job.stamp[next] = generation;
888                    job.cost[next] = cost;
889                    job.parent[next] = node as u32;
890                    job.direction[next] = direction;
891                    heap.push(Reverse((
892                        cost.saturating_add(heuristic(next)),
893                        cost,
894                        next as u32,
895                    )));
896                }
897            };
898            for (d, (dx, dy)) in DIRECTIONS.iter().enumerate() {
899                let (nx, ny) = (x + dx, y + dy);
900                if nx < x0 || nx > x1 || ny < y0 || ny > y1 {
901                    continue;
902                }
903                let turn = if came == NO_DIRECTION {
904                    0
905                } else {
906                    let t = (d as i64 - i64::from(came)).rem_euclid(8);
907                    t.min(8 - t) as usize
908                };
909                if turn > 2 {
910                    continue;
911                }
912                let next = layer * cells + ny as usize * grid.width + nx as usize;
913                let Some(conflict) = self.legal(net, next, soft) else {
914                    continue;
915                };
916                let mut step = if d % 2 == 1 {
917                    diagonal
918                } else if grid.layers > 1 && (d % 4 == 0) != (layer % 2 == 0) {
919                    straight + cross_grain
920                } else {
921                    straight
922                };
923                step += bends[turn] + u32::from(self.history[next]) * history_cost;
924                if !self.approaches[layer].free(next % cells, net as u32) {
925                    step += approach_cost;
926                }
927                if conflict {
928                    step += conflict_cost;
929                }
930                if targets.contains_key(&(next as u32)) {
931                    step += stub(next);
932                }
933                relax(self, next, g.saturating_add(step), d as u8);
934            }
935            if grid.layers > 1
936                && let Some(via_cost) = via_cost
937                && (stubs.vias.contains(&(node as u32))
938                    || (!stubs.paths.contains_key(&(node as u32)) && !self.no_via[cell]))
939                && let Some(via_conflict) = self.via_legal(net, cell, soft)
940            {
941                for other in (0..grid.layers).filter(|l| *l != layer) {
942                    let next = other * cells + cell;
943                    let Some(conflict) = self.legal(net, next, soft) else {
944                        continue;
945                    };
946                    let mut step =
947                        via_cost.saturating_add(u32::from(self.history[next]) * history_cost);
948                    if conflict || via_conflict {
949                        step = step.saturating_add(conflict_cost);
950                    }
951                    relax(self, next, g.saturating_add(step), NO_DIRECTION);
952                }
953            }
954        }
955        None
956    }
957
958    /// Nets whose route claims a soft path overlaps.
959    fn blockers(&self, net: usize, path: &[u32]) -> BTreeSet<usize> {
960        let cells = self.grid.cells();
961        let via_class = self.nets[net].via_profile;
962        let mut keys = vec![];
963        for (i, &node) in path.iter().enumerate() {
964            let (map, cell) = self.map(self.nets[net].profile, node as usize);
965            keys.push((map * cells + cell) as u64);
966            if i > 0 && path[i - 1] as usize % cells == cell {
967                for layer in 0..self.grid.layers {
968                    keys.push(((via_class * self.grid.layers + layer) * cells + cell) as u64);
969                }
970            }
971        }
972        self.states
973            .iter()
974            .enumerate()
975            .filter(|(j, state)| *j != net && keys.iter().any(|k| state.claimed.contains(k)))
976            .map(|(j, _)| j)
977            .collect()
978    }
979
980    fn rip_up(&mut self, net: usize) {
981        let cells = self.grid.cells();
982        let state = std::mem::take(&mut self.states[net]);
983        for key in state.claimed {
984            let key = key as usize;
985            self.route_claims[key / cells].remove(key % cells, net as u32);
986        }
987        self.rip_ups += 1;
988        self.queue.push_back(net);
989    }
990
991    fn claim(&mut self, net: usize, shape: &Shape, layers: (usize, usize)) {
992        let grid = self.grid;
993        let cells = grid.cells();
994        for class in 0..self.profiles.len() {
995            let gap = self.gaps[self.profiles[class].class][self.nets[net].class];
996            let radius = self.keep_out(gap, class);
997            for layer in layers.0..=layers.1 {
998                let map = class * grid.layers + layer;
999                let claims = &mut self.route_claims[map];
1000                let claimed = &mut self.states[net].claimed;
1001                for_cells_near(&grid, shape, radius, |cell| {
1002                    if claimed.insert((map * cells + cell) as u64) {
1003                        claims.add(cell, net as u32);
1004                    }
1005                });
1006            }
1007        }
1008    }
1009
1010    /// Turn a grid path into tracks and vias and claim their clearance zones.
1011    fn commit(&mut self, net: usize, path: &[u32], stubs: &Stubs) {
1012        let cells = self.grid.cells();
1013        let width = self.nets[net].width;
1014        let mut runs = vec![];
1015        let mut vias = vec![];
1016        let mut points = vec![];
1017        points.extend(stubs.paths.get(&path[0]).into_iter().flatten().copied());
1018        for (i, &node) in path.iter().enumerate() {
1019            let (layer, cell) = (node as usize / cells, node as usize % cells);
1020            if i > 0 && path[i - 1] as usize % cells == cell {
1021                runs.push((path[i - 1] as usize / cells, std::mem::take(&mut points)));
1022                vias.push(self.grid.centre(cell));
1023            }
1024            points.push(self.grid.centre(cell));
1025            if i + 1 == path.len() {
1026                points.extend(stubs.paths.get(&node).into_iter().flatten().rev().copied());
1027                runs.push((layer, std::mem::take(&mut points)));
1028            }
1029        }
1030        let last_layer = self.grid.layers - 1;
1031        for (layer, points) in runs {
1032            let track = Track::new(layer as u8, width, points);
1033            if track.points.len() < 2 {
1034                continue;
1035            }
1036            let segments: Vec<Shape> = track.segments().collect();
1037            for segment in &segments {
1038                self.claim(net, segment, (layer, layer));
1039            }
1040            self.states[net].tracks.push(track);
1041        }
1042        let (diameter, drill) = self.nets[net].via;
1043        for at in vias {
1044            self.claim(net, &Shape::circle(at, diameter / 2), (0, last_layer));
1045            self.states[net].vias.push(Via {
1046                id: Uuid::new_v4(),
1047                at,
1048                diameter,
1049                drill,
1050            });
1051        }
1052    }
1053
1054    /// What a via costs when one may be placed.
1055    fn via_cost(&self) -> u32 {
1056        (20 * u32::try_from(self.grid.pitch).unwrap_or(1)).max(2000)
1057    }
1058
1059    /// Route one net. `cleanup` reroutes a finished net for fewer vias; it never rips
1060    /// up another net.
1061    fn route_net(&mut self, net: usize, cleanup: bool) {
1062        self.states[net].missing = 0;
1063        self.states[net].routed = true;
1064        let islands = self.nets[net].islands.len();
1065        let mut stubs = Stubs::default();
1066        let seeds: Vec<Vec<u32>> = (0..islands)
1067            .map(|i| self.seeds(net, i, &mut stubs))
1068            .collect();
1069        let mut connected = vec![false; islands];
1070        connected[0] = true;
1071        let mut tree = seeds[0].clone();
1072        for remaining in (1..islands).rev() {
1073            let mut targets = HashMap::new();
1074            let mut boxes = vec![];
1075            for (island, nodes) in seeds.iter().enumerate().filter(|(i, _)| !connected[*i]) {
1076                boxes.extend(self.cell_box(nodes.iter().copied()));
1077                for &node in nodes {
1078                    targets.insert(node, island);
1079                }
1080            }
1081            if boxes.len() > 16
1082                && let Some(all) = self.cell_box(targets.keys().copied())
1083            {
1084                boxes = vec![all];
1085            }
1086            let window = self
1087                .cell_box(tree.iter().chain(targets.keys()).copied())
1088                .map(|(x0, x1, y0, y1)| {
1089                    let pad = 40.max((x1 - x0).max(y1 - y0) / 3);
1090                    (x0 - pad, x1 + pad, y0 - pad, y1 + pad)
1091                });
1092            // Via costs to try in order; `None` searches without vias. A clean-up
1093            // reroute looks for a route with no via before accepting one.
1094            let allow = Some(self.via_cost());
1095            let stages = match self.vias {
1096                ViaPolicy::Never => vec![None],
1097                ViaPolicy::Avoid if cleanup => vec![None, allow],
1098                ViaPolicy::Allow | ViaPolicy::Avoid => vec![allow],
1099            };
1100            let mut path = None;
1101            for &vias in &stages {
1102                path = self.search(net, &tree, &targets, &boxes, window, false, &stubs, vias);
1103                if path.is_none() {
1104                    path = self.search(net, &tree, &targets, &boxes, None, false, &stubs, vias);
1105                }
1106                if path.is_some() {
1107                    break;
1108                }
1109            }
1110            let soft_vias = *stages.last().unwrap();
1111            if path.is_none()
1112                && !cleanup
1113                && self.attempts[net] < MAX_ATTEMPTS
1114                && self.rip_ups < self.rip_up_limit
1115                && let Some(soft) =
1116                    self.search(net, &tree, &targets, &boxes, None, true, &stubs, soft_vias)
1117            {
1118                self.attempts[net] += 1;
1119                for &node in &soft {
1120                    if self.legal(net, node as usize, false).is_none() {
1121                        let h = &mut self.history[node as usize];
1122                        *h = h.saturating_add(1);
1123                    }
1124                }
1125                for blocker in self.blockers(net, &soft) {
1126                    self.rip_up(blocker);
1127                }
1128                path = Some(soft);
1129            }
1130            let Some(path) = path else {
1131                self.states[net].missing = remaining;
1132                return;
1133            };
1134            let reached = targets[path.last().unwrap()];
1135            self.commit(net, &path, &stubs);
1136            connected[reached] = true;
1137            tree.extend(path);
1138            tree.extend(seeds[reached].iter().copied());
1139        }
1140    }
1141
1142    /// Reroute a finished net against the board as it now stands. The new copper is
1143    /// kept only if it still connects every island with fewer vias; otherwise the
1144    /// old copper and its claims are put back exactly.
1145    fn reduce_vias(&mut self, net: usize) {
1146        let before = self.states[net].vias.len();
1147        if before == 0 || self.states[net].missing > 0 {
1148            return;
1149        }
1150        let cells = self.grid.cells();
1151        let old = std::mem::take(&mut self.states[net]);
1152        for &key in &old.claimed {
1153            let key = key as usize;
1154            self.route_claims[key / cells].remove(key % cells, net as u32);
1155        }
1156        self.route_net(net, true);
1157        let new = &self.states[net];
1158        if new.missing == 0 && new.vias.len() < before {
1159            if let Some(region) = self.copper_region(&old) {
1160                self.cleanup_freed.push(region);
1161            }
1162            return;
1163        }
1164        let new = std::mem::replace(&mut self.states[net], old);
1165        for key in new.claimed {
1166            let key = key as usize;
1167            self.route_claims[key / cells].remove(key % cells, net as u32);
1168        }
1169        for &key in &self.states[net].claimed {
1170            let key = key as usize;
1171            self.route_claims[key / cells].add(key % cells, net as u32);
1172        }
1173    }
1174
1175    /// Bounds of a net's routed copper, grown by the margin a search window adds.
1176    fn copper_region(&self, state: &NetState) -> Option<(Point, Point)> {
1177        let points = state
1178            .tracks
1179            .iter()
1180            .flat_map(|t| t.points.iter().copied())
1181            .chain(state.vias.iter().map(|v| v.at));
1182        let (min, max) = points.fold(None, |b: Option<(Point, Point)>, p| {
1183            Some(b.map_or((p, p), |(a, b)| {
1184                (
1185                    Point::new(a.x.min(p.x), a.y.min(p.y)),
1186                    Point::new(b.x.max(p.x), b.y.max(p.y)),
1187                )
1188            }))
1189        })?;
1190        let margin = 40 * self.grid.pitch + (max.x - min.x).max(max.y - min.y) / 3;
1191        Some((
1192            Point::new(min.x - margin, min.y - margin),
1193            Point::new(max.x + margin, max.y + margin),
1194        ))
1195    }
1196
1197    /// Whether the via clean-up that follows routing under Avoid has more to do.
1198    fn cleanup_pending(&self) -> bool {
1199        self.vias == ViaPolicy::Avoid
1200            && match &self.cleanup {
1201                None => true,
1202                Some(queue) => {
1203                    !queue.is_empty()
1204                        || (!self.cleanup_freed.is_empty()
1205                            && self.cleanup_passes < MAX_CLEANUP_PASSES)
1206                }
1207            }
1208    }
1209
1210    /// The next net to reroute for fewer vias, starting a pass when one is due.
1211    fn next_cleanup(&mut self) -> Option<usize> {
1212        if !self.cleanup_pending() {
1213            return None;
1214        }
1215        if self.cleanup.as_ref().is_none_or(VecDeque::is_empty) {
1216            self.cleanup_passes += 1;
1217            let freed = std::mem::take(&mut self.cleanup_freed);
1218            let first = self.cleanup.is_none();
1219            let near = |region: Option<(Point, Point)>| {
1220                region.is_some_and(|(a, b)| {
1221                    freed
1222                        .iter()
1223                        .any(|(c, d)| a.x <= d.x && c.x <= b.x && a.y <= d.y && c.y <= b.y)
1224                })
1225            };
1226            self.cleanup = Some(
1227                (0..self.nets.len())
1228                    .filter(|&i| !self.states[i].vias.is_empty() && self.states[i].missing == 0)
1229                    .filter(|&i| first || near(self.copper_region(&self.states[i])))
1230                    .collect(),
1231            );
1232        }
1233        self.cleanup.as_mut()?.pop_front()
1234    }
1235
1236    /// Route queued nets until roughly `budget` grid nodes have been expanded.
1237    pub fn step(&mut self, budget: u64) -> Progress {
1238        let stop = self.expansions.saturating_add(budget);
1239        while self.expansions < stop {
1240            if let Some(net) = self.queue.pop_front() {
1241                self.route_net(net, false);
1242            } else if let Some(net) = self.next_cleanup() {
1243                self.reduce_vias(net);
1244            } else {
1245                break;
1246            }
1247        }
1248        self.progress()
1249    }
1250    pub fn progress(&self) -> Progress {
1251        let queued: BTreeSet<usize> = self.queue.iter().copied().collect();
1252        let settled = |i: &usize| !queued.contains(i) && self.states[*i].routed;
1253        Progress {
1254            total_nets: self.nets.len(),
1255            completed_nets: (0..self.nets.len())
1256                .filter(|i| settled(i) && self.states[*i].missing == 0)
1257                .count(),
1258            failed_nets: (0..self.nets.len())
1259                .filter(|i| settled(i) && self.states[*i].missing > 0)
1260                .count(),
1261            rip_ups: self.rip_ups,
1262            removing_vias: self.queue.is_empty()
1263                && self.cleanup.is_some()
1264                && self.cleanup_pending(),
1265            done: self.queue.is_empty() && !self.cleanup_pending(),
1266        }
1267    }
1268    /// Copper routed so far, for previews.
1269    pub fn routed(&self) -> impl Iterator<Item = (&[Track], &[Via])> {
1270        self.states
1271            .iter()
1272            .map(|s| (s.tracks.as_slice(), s.vias.as_slice()))
1273    }
1274    pub fn pitch(&self) -> i32 {
1275        self.grid.pitch
1276    }
1277    pub fn run(mut self) -> RouteOutcome {
1278        while !self.step(u64::MAX).done {}
1279        self.outcome()
1280    }
1281    pub fn outcome(&self) -> RouteOutcome {
1282        let queued: BTreeSet<usize> = self.queue.iter().copied().collect();
1283        RouteOutcome {
1284            tracks: self.states.iter().flat_map(|s| s.tracks.clone()).collect(),
1285            vias: self.states.iter().flat_map(|s| s.vias.clone()).collect(),
1286            unrouted: self
1287                .nets
1288                .iter()
1289                .enumerate()
1290                .filter(|(i, _)| queued.contains(i) || self.states[*i].missing > 0)
1291                .map(|(_, n)| n.name.clone())
1292                .collect(),
1293            pitch: self.grid.pitch,
1294        }
1295    }
1296}
1297
1298impl Document {
1299    /// Route every unrouted connection and add the copper to the board.
1300    pub fn autoroute(&mut self) -> RouteOutcome {
1301        let outcome = RouteJob::new(&self.board, &self.netlist()).run();
1302        outcome.clone().apply(&mut self.board);
1303        outcome
1304    }
1305}
1306