Skip to main content

brep_ecad_core/
board.rs

1//! Printed circuit board layout: footprints, copper, connectivity, and design checks.
2//!
3//! Board coordinates use the schematic's integer micrometres with positive Y down.
4//! Copper connectivity is derived purely from geometry and net identity comes from
5//! the schematic netlist, so the schematic remains the single source of truth.
6use crate::{Document, Netlist, Point, Uuid, footprint};
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, BTreeSet};
9
10/// Courtyard clearance added around footprint bounds.
11pub const COURTYARD_MARGIN: i32 = 250;
12/// Gap between parts and from the board edge during automatic placement.
13const PLACEMENT_SPACING: i32 = 2000;
14/// Gap a part added to a board already laid out keeps from other courtyards and
15/// from the outline ([`Document::seat_in_free_room`]).
16const SEAT_GAP: i32 = 1000;
17
18pub mod net_classes;
19pub mod zones;
20pub use net_classes::{ClassReason, DEFAULT_CLASS, NetClass};
21pub use zones::{FillPiece, Zone};
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
24pub enum PadShape {
25    #[default]
26    Rect,
27    Circle,
28    Oval,
29}
30
31#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
32pub struct Pad {
33    /// Matches a symbol pin number. Empty for mechanical pads.
34    pub number: String,
35    pub at: Point,
36    /// Width (x) and height (y) in footprint coordinates.
37    pub size: Point,
38    #[serde(default)]
39    pub shape: PadShape,
40    /// Through-hole drill diameter; `None` for surface-mount pads.
41    #[serde(default)]
42    pub drill: Option<i32>,
43    /// Whether a drilled hole is plated. Unplated holes go to the NPTH drill file.
44    #[serde(default = "plated_by_default")]
45    pub plated: bool,
46}
47fn plated_by_default() -> bool {
48    true
49}
50
51/// The 3D model a footprint names, as KiCad's `(model …)` entry gives it: the file and
52/// its placement on the pads. The numbers are carried through as the file authored them,
53/// millimetres for the offset and degrees for the rotation, for a host to interpret.
54#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
55pub struct Model {
56    /// The file the footprint names, often with a variable such as
57    /// `${KICAD9_3DMODEL_DIR}` that the host resolves.
58    pub path: String,
59    #[serde(default)]
60    pub offset: [f64; 3],
61    #[serde(default = "unit_scale")]
62    pub scale: [f64; 3],
63    #[serde(default)]
64    pub rotation: [f64; 3],
65}
66fn unit_scale() -> [f64; 3] {
67    [1., 1., 1.]
68}
69impl Model {
70    /// The same model as a STEP file. KiCad's libraries name a `.wrl` mesh for rendering
71    /// and keep a `.step` of the same name beside it, which carries the solid geometry;
72    /// any other path is returned unchanged.
73    pub fn step_path(&self) -> String {
74        match self.path.strip_suffix(".wrl") {
75            Some(stem) => format!("{stem}.step"),
76            None => self.path.clone(),
77        }
78    }
79}
80#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
81pub struct Footprint {
82    pub name: String,
83    pub pads: Vec<Pad>,
84    /// Silkscreen polylines in footprint coordinates.
85    #[serde(default)]
86    pub silk: Vec<Vec<Point>>,
87    /// The 3D model this footprint names, if it has one.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub model: Option<Model>,
90}
91impl Footprint {
92    /// Check a footprint on its own, with messages that name the offending pad: the
93    /// AUTHORING rule, [`Footprint::validate_placeable`] plus a name.
94    pub fn validate(&self) -> Result<(), String> {
95        if self.name.trim().is_empty() {
96            return Err("Enter a footprint name.".into());
97        }
98        self.validate_placeable()
99    }
100    /// Whether a footprint can sit on a board: every check of [`Footprint::validate`]
101    /// except the name. A name is a label, and a copy of a part's pads that has none
102    /// is still copper a board can carry; refusing it there refused the whole document,
103    /// so one unnamed part in an assembly stopped every edit to the sheet and the board
104    /// from being stored (the eCAD workflow audit, issue 3).
105    pub fn validate_placeable(&self) -> Result<(), String> {
106        for pad in &self.pads {
107            let name = if pad.number.is_empty() {
108                "An unnumbered pad".to_owned()
109            } else {
110                format!("Pad {}", pad.number)
111            };
112            if pad.size.x <= 0 || pad.size.y <= 0 {
113                return Err(format!("{name} needs a positive width and height."));
114            }
115            if pad
116                .drill
117                .is_some_and(|d| d <= 0 || d > pad.size.x.max(pad.size.y))
118            {
119                return Err(format!("{name} has a drill larger than the pad."));
120            }
121        }
122        if self.silk.iter().any(|line| line.len() < 2) {
123            return Err("Silkscreen lines need at least two points.".into());
124        }
125        if let Some(model) = &self.model {
126            let numbers = model
127                .offset
128                .iter()
129                .chain(&model.scale)
130                .chain(&model.rotation);
131            if model.path.trim().is_empty() || numbers.into_iter().any(|v| !v.is_finite()) {
132                return Err("The 3D model needs a file and finite placement numbers.".into());
133            }
134        }
135        let id = Uuid::nil();
136        let board = Board {
137            placements: vec![Placement {
138                component: id,
139                footprint: self.clone(),
140                at: Point::new(0, 0),
141                rotation: 0,
142                bottom: false,
143            }],
144            ..Board::default()
145        };
146        board.validate(&BTreeSet::from([id]))
147    }
148    /// Bounds of pads and silkscreen in footprint coordinates.
149    pub fn bounds(&self) -> (Point, Point) {
150        let mut points: Vec<Point> = self
151            .pads
152            .iter()
153            .flat_map(|p| {
154                let (min, max) = Shape::pad(p.at, p.size, PadShape::Rect).bounds();
155                [min, max]
156            })
157            .collect();
158        points.extend(self.silk.iter().flatten().copied());
159        bounds_of(&points).unwrap_or_default()
160    }
161}
162
163/// One footprint instance, bound to a schematic component by ID.
164#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
165pub struct Placement {
166    pub component: Uuid,
167    pub footprint: Footprint,
168    pub at: Point,
169    #[serde(default)]
170    pub rotation: u8,
171    /// Mounted on the bottom side: mirrored in X, and SMD pads use the last layer.
172    #[serde(default)]
173    pub bottom: bool,
174}
175impl Placement {
176    pub fn transform(&self, p: Point) -> Point {
177        let p = if self.bottom {
178            Point::new(-p.x, p.y)
179        } else {
180            p
181        };
182        p.rotate(self.rotation).offset(self.at)
183    }
184    pub fn pad_shape(&self, pad: &Pad) -> Shape {
185        let size = if self.rotation % 2 == 1 {
186            Point::new(pad.size.y, pad.size.x)
187        } else {
188            pad.size
189        };
190        Shape::pad(self.transform(pad.at), size, pad.shape)
191    }
192    /// Inclusive copper layer range of a pad.
193    pub fn pad_layers(&self, pad: &Pad, layer_count: u8) -> (u8, u8) {
194        let last = layer_count.saturating_sub(1);
195        match (pad.drill, self.bottom) {
196            (Some(_), _) => (0, last),
197            (None, false) => (0, 0),
198            (None, true) => (last, last),
199        }
200    }
201    /// World-space courtyard rectangle.
202    pub fn courtyard(&self) -> (Point, Point) {
203        let (min, max) = self.footprint.bounds();
204        let corners = [min, max, Point::new(min.x, max.y), Point::new(max.x, min.y)]
205            .map(|p| self.transform(p));
206        let (min, max) = bounds_of(&corners).unwrap_or_default();
207        (
208            Point::new(min.x - COURTYARD_MARGIN, min.y - COURTYARD_MARGIN),
209            Point::new(max.x + COURTYARD_MARGIN, max.y + COURTYARD_MARGIN),
210        )
211    }
212}
213
214#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
215pub struct Track {
216    pub id: Uuid,
217    pub layer: u8,
218    pub width: i32,
219    /// The width was set on this track itself, so the net's width rule leaves it alone.
220    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
221    pub fixed_width: bool,
222    pub points: Vec<Point>,
223}
224impl Track {
225    /// Build a track, dropping repeated and collinear interior points.
226    pub fn new(layer: u8, width: i32, points: Vec<Point>) -> Self {
227        Self {
228            id: Uuid::new_v4(),
229            layer,
230            width,
231            fixed_width: false,
232            points: simplify_path(points),
233        }
234    }
235    pub fn segments(&self) -> impl Iterator<Item = Shape> + '_ {
236        self.points
237            .windows(2)
238            .map(|s| Shape::segment(s[0], s[1], self.width))
239    }
240}
241
242#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
243pub struct Via {
244    pub id: Uuid,
245    pub at: Point,
246    pub diameter: i32,
247    pub drill: i32,
248}
249
250#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
251pub struct DesignRules {
252    /// The Default net class's track width, clearance and via ([`net_classes`]).
253    pub track_width: i32,
254    pub clearance: i32,
255    pub via_diameter: i32,
256    pub via_drill: i32,
257    /// Minimum distance from copper to the board outline.
258    pub edge_clearance: i32,
259    /// Autorouter grid pitch.
260    pub routing_grid: i32,
261    /// Track width overrides by exact net name, e.g. wider supply nets.
262    #[serde(default)]
263    pub net_widths: BTreeMap<String, i32>,
264    /// Solder mask openings extend this far beyond each pad.
265    #[serde(default = "default_mask_expansion")]
266    pub mask_expansion: i32,
267    /// How the autorouter uses vias. Boards saved before this existed get the default.
268    #[serde(default)]
269    pub autoroute_vias: ViaPolicy,
270    /// The net classes besides Default, in pattern order ([`net_classes`]). Written
271    /// only when there are some, so a board with none saves as it did before.
272    #[serde(default, skip_serializing_if = "Vec::is_empty")]
273    pub net_classes: Vec<NetClass>,
274    /// Explicit net → class assignments, which beat every pattern.
275    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
276    pub net_class_of: BTreeMap<String, String>,
277}
278fn default_mask_expansion() -> i32 {
279    50
280}
281
282/// How the autorouter trades vias against track length.
283#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
284#[serde(rename_all = "snake_case")]
285pub enum ViaPolicy {
286    /// A via is an ordinary cost, taken whenever it shortens the route enough.
287    Allow,
288    /// Route as `Allow` does, then reroute every net that has vias against the
289    /// finished board, looking first for a route with none, and keep whichever
290    /// copper has fewer. Connects the same nets as `Allow`, more slowly.
291    #[default]
292    Avoid,
293    /// Never place a via. Connections that cannot be made on one layer stay unrouted.
294    Never,
295}
296impl Default for DesignRules {
297    fn default() -> Self {
298        Self {
299            track_width: 250,
300            clearance: 200,
301            via_diameter: 600,
302            via_drill: 300,
303            edge_clearance: 300,
304            routing_grid: 100,
305            net_widths: BTreeMap::new(),
306            mask_expansion: default_mask_expansion(),
307            autoroute_vias: ViaPolicy::default(),
308            net_classes: vec![],
309            net_class_of: BTreeMap::new(),
310        }
311    }
312}
313
314#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
315pub struct Board {
316    /// Closed board outline polygon.
317    pub outline: Vec<Point>,
318    /// Copper layers; layer 0 is the top (F.Cu), the last is the bottom (B.Cu).
319    pub layer_count: u8,
320    #[serde(default)]
321    pub placements: Vec<Placement>,
322    #[serde(default)]
323    pub tracks: Vec<Track>,
324    #[serde(default)]
325    pub vias: Vec<Via>,
326    #[serde(default)]
327    pub rules: DesignRules,
328    /// Copper zones, in drawing order, which is also their fill priority. Written
329    /// only when there are some, so a board with none serializes exactly as it did
330    /// before zones existed (the host compares the block byte for byte).
331    #[serde(default, skip_serializing_if = "Vec::is_empty")]
332    pub zones: Vec<Zone>,
333}
334impl Default for Board {
335    fn default() -> Self {
336        Self {
337            outline: rectangle(Point::new(0, 0), Point::new(60_000, 40_000)),
338            layer_count: 2,
339            placements: vec![],
340            tracks: vec![],
341            vias: vec![],
342            rules: DesignRules::default(),
343            zones: vec![],
344        }
345    }
346}
347
348/// The substrate's thickness in board micrometres — 1.6 mm, the board every
349/// fabricator quotes by default.
350///
351/// A CONSTANT rather than a [`Board`] field on purpose. A field would serialize
352/// into the `pcb` block, and the eCAD host compares the block it holds against
353/// the stored one byte for byte to decide whether the editor is in step — a new
354/// always-serialized field puts every block written before it out of step (the
355/// `Pin::unit` lesson, 2026-09-20). Until a board needs its own stack-up, one
356/// number the app and the 3D build share is honest and costs nothing.
357pub const SUBSTRATE_THICKNESS: i32 = 1_600;
358
359/// Copper foil thickness in board micrometres — 35 µm, "1 oz" copper. Also the
360/// wall thickness of a plated via barrel.
361pub const COPPER_THICKNESS: i32 = 35;
362
363/// The z of copper layer `layer`'s own plane, in board micrometres, with the
364/// TOP copper plane at 0 and +z out of the board's top face — the frame
365/// [`Placement`] poses are already written in.
366///
367/// Layer 0 (`F.Cu`) is 0 and the last (`B.Cu`) is `-SUBSTRATE_THICKNESS`; the
368/// inner layers are spread evenly between them, so the LAYER COUNT decides the
369/// stack exactly as it decides the names ([`layer_name`]). A one-layer board
370/// has only layer 0, at 0.
371pub fn layer_z(layer: u8, layer_count: u8) -> i32 {
372    let last = layer_count.saturating_sub(1);
373    if layer == 0 || last == 0 {
374        return 0;
375    }
376    let layer = layer.min(last);
377    -(SUBSTRATE_THICKNESS as i64 * i64::from(layer) / i64::from(last)) as i32
378}
379
380/// KiCad-style copper layer name.
381pub fn layer_name(layer: u8, layer_count: u8) -> String {
382    if layer == 0 {
383        "F.Cu".into()
384    } else if layer + 1 >= layer_count {
385        "B.Cu".into()
386    } else {
387        format!("In{layer}.Cu")
388    }
389}
390
391pub fn rectangle(min: Point, max: Point) -> Vec<Point> {
392    vec![min, Point::new(max.x, min.y), max, Point::new(min.x, max.y)]
393}
394
395/// A copper primitive for clearance and connectivity calculations.
396#[derive(Clone, Copy, Debug, PartialEq)]
397pub enum Shape {
398    Rect {
399        min: Point,
400        max: Point,
401    },
402    /// A segment swept by a disc. A circle has `a == b`.
403    Capsule {
404        a: Point,
405        b: Point,
406        radius: i32,
407    },
408}
409impl Shape {
410    pub fn pad(center: Point, size: Point, shape: PadShape) -> Self {
411        let half = Point::new(size.x / 2, size.y / 2);
412        match shape {
413            PadShape::Rect => {
414                let min = Point::new(center.x - half.x, center.y - half.y);
415                Self::Rect {
416                    min,
417                    max: Point::new(min.x + size.x, min.y + size.y),
418                }
419            }
420            PadShape::Circle => Self::circle(center, size.x.min(size.y) / 2),
421            PadShape::Oval => {
422                let radius = size.x.min(size.y) / 2;
423                let reach = Point::new((half.x - radius).max(0), (half.y - radius).max(0));
424                Self::Capsule {
425                    a: Point::new(center.x - reach.x, center.y - reach.y),
426                    b: Point::new(center.x + reach.x, center.y + reach.y),
427                    radius,
428                }
429            }
430        }
431    }
432    pub fn circle(center: Point, radius: i32) -> Self {
433        Self::Capsule {
434            a: center,
435            b: center,
436            radius,
437        }
438    }
439    pub fn segment(a: Point, b: Point, width: i32) -> Self {
440        Self::Capsule {
441            a,
442            b,
443            radius: width / 2,
444        }
445    }
446    pub fn bounds(&self) -> (Point, Point) {
447        match *self {
448            Self::Rect { min, max } => (min, max),
449            Self::Capsule { a, b, radius } => (
450                Point::new(a.x.min(b.x) - radius, a.y.min(b.y) - radius),
451                Point::new(a.x.max(b.x) + radius, a.y.max(b.y) + radius),
452            ),
453        }
454    }
455    pub fn center(&self) -> Point {
456        let (min, max) = self.bounds();
457        Point::new(
458            ((i64::from(min.x) + i64::from(max.x)) / 2) as i32,
459            ((i64::from(min.y) + i64::from(max.y)) / 2) as i32,
460        )
461    }
462    /// Distance from a point to the shape; zero inside.
463    pub fn distance_to_point(&self, p: Point) -> f64 {
464        match *self {
465            Self::Rect { min, max } => point_rect_distance(p, min, max),
466            Self::Capsule { a, b, radius } => {
467                (point_segment_distance(p, a, b) - f64::from(radius)).max(0.)
468            }
469        }
470    }
471    pub fn contains(&self, p: Point) -> bool {
472        self.distance_to_point(p) <= 0.
473    }
474    /// Gap between two shapes; zero when they touch or overlap.
475    pub fn distance(&self, other: &Self) -> f64 {
476        match (*self, *other) {
477            (Self::Rect { min: a0, max: a1 }, Self::Rect { min: b0, max: b1 }) => {
478                let dx = (i64::from(a0.x) - i64::from(b1.x))
479                    .max(i64::from(b0.x) - i64::from(a1.x))
480                    .max(0) as f64;
481                let dy = (i64::from(a0.y) - i64::from(b1.y))
482                    .max(i64::from(b0.y) - i64::from(a1.y))
483                    .max(0) as f64;
484                dx.hypot(dy)
485            }
486            (Self::Rect { min, max }, Self::Capsule { a, b, radius })
487            | (Self::Capsule { a, b, radius }, Self::Rect { min, max }) => {
488                (segment_rect_distance(a, b, min, max) - f64::from(radius)).max(0.)
489            }
490            (
491                Self::Capsule {
492                    a: a0,
493                    b: a1,
494                    radius: ra,
495                },
496                Self::Capsule {
497                    a: b0,
498                    b: b1,
499                    radius: rb,
500                },
501            ) => (segment_distance(a0, a1, b0, b1) - f64::from(ra) - f64::from(rb)).max(0.),
502        }
503    }
504}
505
506fn cross(o: Point, a: Point, b: Point) -> i64 {
507    (i64::from(a.x) - i64::from(o.x)) * (i64::from(b.y) - i64::from(o.y))
508        - (i64::from(a.y) - i64::from(o.y)) * (i64::from(b.x) - i64::from(o.x))
509}
510fn within_box(a: Point, b: Point, p: Point) -> bool {
511    p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y)
512}
513pub fn segments_intersect(a: Point, b: Point, c: Point, d: Point) -> bool {
514    let d1 = cross(c, d, a);
515    let d2 = cross(c, d, b);
516    let d3 = cross(a, b, c);
517    let d4 = cross(a, b, d);
518    if d1.signum() * d2.signum() < 0 && d3.signum() * d4.signum() < 0 {
519        return true;
520    }
521    (d1 == 0 && within_box(c, d, a))
522        || (d2 == 0 && within_box(c, d, b))
523        || (d3 == 0 && within_box(a, b, c))
524        || (d4 == 0 && within_box(a, b, d))
525}
526pub fn point_segment_distance(p: Point, a: Point, b: Point) -> f64 {
527    let (px, py) = (f64::from(p.x), f64::from(p.y));
528    let (ax, ay) = (f64::from(a.x), f64::from(a.y));
529    let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay);
530    let len2 = dx * dx + dy * dy;
531    let t = if len2 == 0. {
532        0.
533    } else {
534        (((px - ax) * dx + (py - ay) * dy) / len2).clamp(0., 1.)
535    };
536    (px - ax - t * dx).hypot(py - ay - t * dy)
537}
538fn segment_distance(a: Point, b: Point, c: Point, d: Point) -> f64 {
539    if segments_intersect(a, b, c, d) {
540        return 0.;
541    }
542    point_segment_distance(a, c, d)
543        .min(point_segment_distance(b, c, d))
544        .min(point_segment_distance(c, a, b))
545        .min(point_segment_distance(d, a, b))
546}
547fn point_rect_distance(p: Point, min: Point, max: Point) -> f64 {
548    let dx = (i64::from(min.x) - i64::from(p.x))
549        .max(i64::from(p.x) - i64::from(max.x))
550        .max(0) as f64;
551    let dy = (i64::from(min.y) - i64::from(p.y))
552        .max(i64::from(p.y) - i64::from(max.y))
553        .max(0) as f64;
554    dx.hypot(dy)
555}
556fn segment_rect_distance(a: Point, b: Point, min: Point, max: Point) -> f64 {
557    let corners = rectangle(min, max);
558    if within_box(min, max, a)
559        || within_box(min, max, b)
560        || (0..4).any(|i| segments_intersect(a, b, corners[i], corners[(i + 1) % 4]))
561    {
562        return 0.;
563    }
564    corners
565        .iter()
566        .map(|c| point_segment_distance(*c, a, b))
567        .fold(
568            point_rect_distance(a, min, max).min(point_rect_distance(b, min, max)),
569            f64::min,
570        )
571}
572/// Even-odd point-in-polygon test.
573pub fn polygon_contains(polygon: &[Point], p: Point) -> bool {
574    let (px, py) = (f64::from(p.x), f64::from(p.y));
575    let mut inside = false;
576    for (i, a) in polygon.iter().enumerate() {
577        let b = polygon[(i + 1) % polygon.len()];
578        let (ax, ay, bx, by) = (
579            f64::from(a.x),
580            f64::from(a.y),
581            f64::from(b.x),
582            f64::from(b.y),
583        );
584        if (ay > py) != (by > py) && px < ax + (py - ay) * (bx - ax) / (by - ay) {
585            inside = !inside;
586        }
587    }
588    inside
589}
590fn bounds_of(points: &[Point]) -> Option<(Point, Point)> {
591    let first = *points.first()?;
592    Some(points.iter().fold((first, first), |(min, max), p| {
593        (
594            Point::new(min.x.min(p.x), min.y.min(p.y)),
595            Point::new(max.x.max(p.x), max.y.max(p.y)),
596        )
597    }))
598}
599/// Remove repeated points and interior points that continue in the same direction.
600pub fn simplify_path(points: Vec<Point>) -> Vec<Point> {
601    let mut clean: Vec<Point> = vec![];
602    for p in points {
603        if clean.last() == Some(&p) {
604            continue;
605        }
606        if clean.len() >= 2 {
607            let a = clean[clean.len() - 2];
608            let b = clean[clean.len() - 1];
609            let forward = (i64::from(b.x) - i64::from(a.x)) * (i64::from(p.x) - i64::from(b.x))
610                + (i64::from(b.y) - i64::from(a.y)) * (i64::from(p.y) - i64::from(b.y));
611            if cross(a, b, p) == 0 && forward > 0 {
612                clean.pop();
613            }
614        }
615        clean.push(p);
616    }
617    clean
618}
619
620/// What a copper primitive belongs to.
621#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
622pub enum CopperRef {
623    Pad { placement: usize, pad: usize },
624    Track { track: usize, segment: usize },
625    Via(usize),
626}
627#[derive(Clone, Debug)]
628pub struct CopperItem {
629    pub owner: CopperRef,
630    pub shape: Shape,
631    /// Inclusive layer range.
632    pub layers: (u8, u8),
633}
634impl CopperItem {
635    fn shares_layer(&self, other: &Self) -> bool {
636        self.layers.0 <= other.layers.1 && other.layers.0 <= self.layers.1
637    }
638}
639
640/// Copper islands and the schematic nets each island carries.
641#[derive(Clone, Debug, Default)]
642pub struct Connectivity {
643    pub items: Vec<CopperItem>,
644    /// Island index for each item.
645    pub islands: Vec<usize>,
646    pub island_count: usize,
647    /// Schematic net of each pad item.
648    pub item_nets: Vec<Option<String>>,
649    pub island_nets: Vec<BTreeSet<String>>,
650    /// Island index of each piece of each zone's fill, by zone then piece: a fill
651    /// is copper, and joins every item it touches.
652    pub zone_islands: Vec<Vec<usize>>,
653}
654impl Connectivity {
655    /// The single net carried by an island, if it carries exactly one.
656    pub fn island_net(&self, island: usize) -> Option<&str> {
657        let nets = &self.island_nets[island];
658        (nets.len() == 1).then(|| nets.iter().next().unwrap().as_str())
659    }
660}
661
662/// An unrouted connection between two copper islands of one net.
663#[derive(Clone, Debug, PartialEq)]
664pub struct Airwire {
665    pub net: String,
666    pub a: Point,
667    pub b: Point,
668}
669
670#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
671pub enum ViolationKind {
672    Short,
673    Clearance,
674    /// A track narrower than its net's width: its own width rule, else its class's.
675    TrackWidth,
676    BoardEdge,
677    MissingPad,
678    Courtyard,
679    /// A via with no net that zones of two nets claim, and which is stitched to
680    /// neither ([`Board::contested_vias`]).
681    Stitching,
682    Unrouted,
683}
684#[derive(Clone, Debug, PartialEq)]
685pub struct Violation {
686    pub kind: ViolationKind,
687    pub message: String,
688    pub at: Point,
689}
690
691struct Dsu(Vec<usize>);
692impl Dsu {
693    fn new(n: usize) -> Self {
694        Self((0..n).collect())
695    }
696    fn root(&mut self, mut i: usize) -> usize {
697        while self.0[i] != i {
698            self.0[i] = self.0[self.0[i]];
699            i = self.0[i];
700        }
701        i
702    }
703    fn join(&mut self, a: usize, b: usize) -> bool {
704        let (a, b) = (self.root(a), self.root(b));
705        if a != b {
706            self.0[a.max(b)] = a.min(b);
707        }
708        a != b
709    }
710}
711
712/// Visit item pairs whose bounds, expanded by `slack`, overlap on a shared layer.
713fn near_pairs(items: &[CopperItem], slack: i32, mut visit: impl FnMut(usize, usize)) {
714    let bounds: Vec<_> = items.iter().map(|i| i.shape.bounds()).collect();
715    let mut order: Vec<usize> = (0..items.len()).collect();
716    order.sort_by_key(|&i| (bounds[i].0.x, i));
717    for (k, &i) in order.iter().enumerate() {
718        let (min, max) = bounds[i];
719        for &j in &order[k + 1..] {
720            let (other_min, other_max) = bounds[j];
721            if other_min.x > max.x.saturating_add(slack) {
722                break;
723            }
724            if other_min.y > max.y.saturating_add(slack)
725                || min.y > other_max.y.saturating_add(slack)
726                || !items[i].shares_layer(&items[j])
727            {
728                continue;
729            }
730            visit(i.min(j), i.max(j));
731        }
732    }
733}
734
735/// Schematic net name for each (component, pin number).
736pub fn pin_nets(netlist: &Netlist) -> BTreeMap<(Uuid, String), String> {
737    netlist
738        .nets
739        .iter()
740        .flat_map(|n| {
741            n.pins
742                .iter()
743                .map(|p| ((p.component_id, p.number.clone()), n.name.clone()))
744        })
745        .collect()
746}
747
748impl Board {
749    pub fn outline_bounds(&self) -> (Point, Point) {
750        bounds_of(&self.outline).unwrap_or_default()
751    }
752    /// True when the outline is an axis-aligned rectangle.
753    pub fn outline_is_rectangle(&self) -> bool {
754        let (min, max) = self.outline_bounds();
755        self.outline.len() == 4
756            && self
757                .outline
758                .iter()
759                .all(|p| (p.x == min.x || p.x == max.x) && (p.y == min.y || p.y == max.y))
760            && min.x < max.x
761            && min.y < max.y
762    }
763    /// Even-odd point-in-polygon test for the outline.
764    pub fn outline_contains(&self, p: Point) -> bool {
765        polygon_contains(&self.outline, p)
766    }
767    pub fn outline_edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
768        let n = self.outline.len();
769        (0..n).map(move |i| (self.outline[i], self.outline[(i + 1) % n]))
770    }
771    /// Change the number of copper layers. Bottom-layer copper stays on the bottom;
772    /// changes that would strand inner-layer tracks, or leave a single-layer board
773    /// with vias or bottom-side copper, are refused.
774    pub fn set_layer_count(&mut self, count: u8) -> Result<(), String> {
775        if !(1..=32).contains(&count) {
776            return Err("Boards need between 1 and 32 copper layers".into());
777        }
778        let old_last = self.layer_count.saturating_sub(1);
779        let new_last = count - 1;
780        if self
781            .tracks
782            .iter()
783            .any(|t| t.layer != 0 && t.layer != old_last && t.layer >= new_last)
784        {
785            return Err("Move or delete the tracks on removed inner layers first".into());
786        }
787        if self
788            .zones
789            .iter()
790            .any(|z| z.layer != 0 && z.layer != old_last && z.layer >= new_last)
791        {
792            return Err("Move or delete the zones on removed inner layers first".into());
793        }
794        if count == 1 && self.zones.iter().any(|z| z.layer != 0) {
795            return Err("A single-layer board cannot keep bottom zones".into());
796        }
797        if count == 1
798            && (!self.vias.is_empty()
799                || self.placements.iter().any(|p| p.bottom)
800                || self.tracks.iter().any(|t| t.layer != 0))
801        {
802            return Err(
803                "A single-layer board cannot keep vias, bottom tracks, or bottom-side parts".into(),
804            );
805        }
806        for track in &mut self.tracks {
807            if track.layer == old_last && old_last != 0 {
808                track.layer = new_last;
809            }
810        }
811        for zone in &mut self.zones {
812            if zone.layer == old_last && old_last != 0 {
813                zone.layer = new_last;
814            }
815        }
816        self.layer_count = count;
817        Ok(())
818    }
819    pub fn placement(&self, component: Uuid) -> Option<&Placement> {
820        self.placements.iter().find(|p| p.component == component)
821    }
822    /// Every copper primitive on the board.
823    pub fn copper(&self) -> Vec<CopperItem> {
824        let last = self.layer_count.saturating_sub(1);
825        let mut items = vec![];
826        for (pi, placement) in self.placements.iter().enumerate() {
827            for (pad_index, pad) in placement.footprint.pads.iter().enumerate() {
828                items.push(CopperItem {
829                    owner: CopperRef::Pad {
830                        placement: pi,
831                        pad: pad_index,
832                    },
833                    shape: placement.pad_shape(pad),
834                    layers: placement.pad_layers(pad, self.layer_count),
835                });
836            }
837        }
838        for (ti, track) in self.tracks.iter().enumerate() {
839            for (segment, shape) in track.segments().enumerate() {
840                items.push(CopperItem {
841                    owner: CopperRef::Track { track: ti, segment },
842                    shape,
843                    layers: (track.layer, track.layer),
844                });
845            }
846        }
847        for (vi, via) in self.vias.iter().enumerate() {
848            items.push(CopperItem {
849                owner: CopperRef::Via(vi),
850                shape: Shape::circle(via.at, via.diameter / 2),
851                layers: (0, last),
852            });
853        }
854        items
855    }
856    /// Copper islands and their nets, a zone's fill joining whatever it touches.
857    pub fn connectivity(&self, netlist: &Netlist) -> Connectivity {
858        self.connectivity_of(netlist, true)
859    }
860    /// [`Self::connectivity`], with or without the zones' fills: a fill is made
861    /// against the copper WITHOUT any fill, so a stale one never decides the net
862    /// of a track.
863    pub fn connectivity_of(&self, netlist: &Netlist, with_zones: bool) -> Connectivity {
864        let items = self.copper();
865        let pins = pin_nets(netlist);
866        let pieces: Vec<(usize, &FillPiece)> = if with_zones {
867            self.zones
868                .iter()
869                .enumerate()
870                .flat_map(|(z, zone)| zone.fill.iter().map(move |p| (z, p)))
871                .collect()
872        } else {
873            vec![]
874        };
875        let mut dsu = Dsu::new(items.len() + pieces.len());
876        near_pairs(&items, 0, |i, j| {
877            if items[i].shape.distance(&items[j].shape) <= 0.5 {
878                dsu.join(i, j);
879            }
880        });
881        for (k, (z, piece)) in pieces.iter().enumerate() {
882            let layer = self.zones[*z].layer;
883            let (min, max) = piece.bounds();
884            for (i, item) in items.iter().enumerate() {
885                let (lo, hi) = item.shape.bounds();
886                if item.layers.0 <= layer
887                    && layer <= item.layers.1
888                    && lo.x <= max.x
889                    && hi.x >= min.x
890                    && lo.y <= max.y
891                    && hi.y >= min.y
892                    && piece.touches(&item.shape)
893                {
894                    dsu.join(i, items.len() + k);
895                }
896            }
897        }
898        let mut numbering = BTreeMap::new();
899        let mut all: Vec<usize> = (0..items.len() + pieces.len())
900            .map(|i| {
901                let next = numbering.len();
902                *numbering.entry(dsu.root(i)).or_insert(next)
903            })
904            .collect();
905        let piece_islands = all.split_off(items.len());
906        let islands = all;
907        let mut zone_islands: Vec<Vec<usize>> = if with_zones {
908            self.zones.iter().map(|z| Vec::with_capacity(z.fill.len())).collect()
909        } else {
910            vec![]
911        };
912        for ((z, _), island) in pieces.iter().zip(piece_islands) {
913            zone_islands[*z].push(island);
914        }
915        let item_nets: Vec<Option<String>> = items
916            .iter()
917            .map(|item| match item.owner {
918                CopperRef::Pad { placement, pad } => {
919                    let placement = &self.placements[placement];
920                    let number = &placement.footprint.pads[pad].number;
921                    pins.get(&(placement.component, number.clone())).cloned()
922                }
923                _ => None,
924            })
925            .collect();
926        let mut island_nets = vec![BTreeSet::new(); numbering.len()];
927        for (island, net) in islands.iter().zip(&item_nets) {
928            if let Some(net) = net {
929                island_nets[*island].insert(net.clone());
930            }
931        }
932        Connectivity {
933            island_count: numbering.len(),
934            items,
935            islands,
936            item_nets,
937            island_nets,
938            zone_islands,
939        }
940    }
941    /// Minimum spanning connections between the unjoined copper islands of each net.
942    pub fn ratsnest(&self, conn: &Connectivity) -> Vec<Airwire> {
943        let mut net_pads: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
944        for (i, net) in conn.item_nets.iter().enumerate() {
945            if let Some(net) = net {
946                net_pads.entry(net).or_default().push(i);
947            }
948        }
949        let mut island_anchors: BTreeMap<usize, Vec<Point>> = BTreeMap::new();
950        for (i, item) in conn.items.iter().enumerate() {
951            let anchors = island_anchors.entry(conn.islands[i]).or_default();
952            match item.owner {
953                CopperRef::Track { .. } => {
954                    if let Shape::Capsule { a, b, .. } = item.shape {
955                        anchors.extend([a, b]);
956                    }
957                }
958                CopperRef::Via(_) => anchors.push(item.shape.center()),
959                CopperRef::Pad { .. } => {}
960            }
961        }
962        let mut airwires = vec![];
963        for (net, pads) in net_pads {
964            let islands: BTreeSet<usize> = pads.iter().map(|&i| conn.islands[i]).collect();
965            if islands.len() < 2 {
966                continue;
967            }
968            let mut anchors: Vec<(usize, Point)> = pads
969                .iter()
970                .map(|&i| (conn.islands[i], conn.items[i].shape.center()))
971                .collect();
972            let extra: Vec<(usize, Point)> = islands
973                .iter()
974                .flat_map(|&island| {
975                    island_anchors
976                        .get(&island)
977                        .into_iter()
978                        .flatten()
979                        .map(move |p| (island, *p))
980                })
981                .collect();
982            if anchors.len() + extra.len() <= 400 {
983                anchors.extend(extra);
984            }
985            anchors.sort();
986            anchors.dedup();
987            let mut pairs = vec![];
988            for i in 0..anchors.len() {
989                for j in i + 1..anchors.len() {
990                    if anchors[i].0 != anchors[j].0 {
991                        let dx = i64::from(anchors[i].1.x) - i64::from(anchors[j].1.x);
992                        let dy = i64::from(anchors[i].1.y) - i64::from(anchors[j].1.y);
993                        pairs.push((dx * dx + dy * dy, i, j));
994                    }
995                }
996            }
997            pairs.sort_unstable();
998            let index: BTreeMap<usize, usize> =
999                islands.iter().enumerate().map(|(i, &s)| (s, i)).collect();
1000            let mut dsu = Dsu::new(islands.len());
1001            let mut joined = 1;
1002            for (_, i, j) in pairs {
1003                if dsu.join(index[&anchors[i].0], index[&anchors[j].0]) {
1004                    airwires.push(Airwire {
1005                        net: net.to_owned(),
1006                        a: anchors[i].1,
1007                        b: anchors[j].1,
1008                    });
1009                    joined += 1;
1010                    if joined == islands.len() {
1011                        break;
1012                    }
1013                }
1014            }
1015        }
1016        airwires
1017    }
1018    fn describe(&self, owner: CopperRef, references: &BTreeMap<Uuid, String>) -> String {
1019        match owner {
1020            CopperRef::Pad { placement, pad } => {
1021                let placement = &self.placements[placement];
1022                format!(
1023                    "{} pad {}",
1024                    references
1025                        .get(&placement.component)
1026                        .map_or("?", String::as_str),
1027                    placement.footprint.pads[pad].number
1028                )
1029            }
1030            CopperRef::Track { track, .. } => format!(
1031                "track on {}",
1032                layer_name(self.tracks[track].layer, self.layer_count)
1033            ),
1034            CopperRef::Via(_) => "via".into(),
1035        }
1036    }
1037    /// [`Self::describe`] with the nets the copper carries: "track on F.Cu (SIG)".
1038    fn describe_on(&self, owner: CopperRef, nets: &BTreeSet<String>, references: &BTreeMap<Uuid, String>) -> String {
1039        let what = self.describe(owner, references);
1040        if nets.is_empty() {
1041            what
1042        } else {
1043            format!("{what} ({})", nets.iter().cloned().collect::<Vec<_>>().join(", "))
1044        }
1045    }
1046    /// Design rule check against exact copper geometry.
1047    pub fn drc(&self, netlist: &Netlist) -> Vec<Violation> {
1048        let conn = self.connectivity(netlist);
1049        let references: BTreeMap<Uuid, String> = netlist
1050            .nets
1051            .iter()
1052            .flat_map(|n| &n.pins)
1053            .map(|p| (p.component_id, p.reference.clone()))
1054            .collect();
1055        let object = |owner: CopperRef| match owner {
1056            CopperRef::Pad { placement, pad } => (0, placement, pad),
1057            CopperRef::Track { track, .. } => (1, track, 0),
1058            CopperRef::Via(v) => (2, v, 0),
1059        };
1060        let mut violations = vec![];
1061        for (island, nets) in conn.island_nets.iter().enumerate() {
1062            if nets.len() > 1 {
1063                let at = conn
1064                    .islands
1065                    .iter()
1066                    .position(|&i| i == island)
1067                    .map_or_else(Point::default, |i| conn.items[i].shape.center());
1068                violations.push(Violation {
1069                    kind: ViolationKind::Short,
1070                    message: format!(
1071                        "Short circuit between {}",
1072                        nets.iter().cloned().collect::<Vec<_>>().join(", ")
1073                    ),
1074                    at,
1075                });
1076            }
1077        }
1078        // Each pair keeps the larger of its two nets' class clearances, so the
1079        // prefilter must reach as far as the largest any class asks for.
1080        let nets_of = |island: usize| conn.island_nets[island].iter().map(String::as_str);
1081        let mut reported = BTreeSet::new();
1082        near_pairs(&conn.items, self.rules.max_clearance(), |i, j| {
1083            let (island_i, island_j) = (conn.islands[i], conn.islands[j]);
1084            if island_i == island_j {
1085                return;
1086            }
1087            if let (Some(a), Some(b)) = (conn.island_net(island_i), conn.island_net(island_j))
1088                && a == b
1089            {
1090                return;
1091            }
1092            let (a, b) = (&conn.items[i], &conn.items[j]);
1093            let (required, class) = self.rules.clearance_between_nets(nets_of(island_i), nets_of(island_j));
1094            let clearance = f64::from(required);
1095            let gap = a.shape.distance(&b.shape);
1096            let key = (object(a.owner), object(b.owner));
1097            if gap + 0.5 < clearance && reported.insert(key) {
1098                let (ca, cb) = (a.shape.center(), b.shape.center());
1099                violations.push(Violation {
1100                    kind: ViolationKind::Clearance,
1101                    message: format!(
1102                        "{} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
1103                        self.describe_on(a.owner, &conn.island_nets[island_i], &references),
1104                        self.describe_on(b.owner, &conn.island_nets[island_j], &references),
1105                        gap / 1000.,
1106                        class.name,
1107                        clearance / 1000.
1108                    ),
1109                    at: Point::new(
1110                        ((i64::from(ca.x) + i64::from(cb.x)) / 2) as i32,
1111                        ((i64::from(ca.y) + i64::from(cb.y)) / 2) as i32,
1112                    ),
1113                });
1114            }
1115        });
1116        // A zone's fill is copper like any other: it keeps the clearance from every
1117        // island it is not part of that does not carry its own net, and from the
1118        // fill of any other zone of another net on its layer.
1119        let edge_clearance = f64::from(self.rules.edge_clearance);
1120        for (z, zone) in self.zones.iter().enumerate() {
1121            let label = zones::describe(zone, self.layer_count);
1122            let mut reported = BTreeSet::new();
1123            for (k, piece) in zone.fill.iter().enumerate() {
1124                let island = conn.zone_islands[z][k];
1125                let (min, max) = piece.bounds();
1126                for (i, item) in conn.items.iter().enumerate() {
1127                    if !(item.layers.0 <= zone.layer && zone.layer <= item.layers.1)
1128                        || conn.islands[i] == island
1129                    {
1130                        continue;
1131                    }
1132                    if conn.island_net(conn.islands[i]) == Some(zone.net.as_str())
1133                        && conn.island_net(island) == Some(zone.net.as_str())
1134                    {
1135                        continue;
1136                    }
1137                    let (lo, hi) = item.shape.bounds();
1138                    let slack = self.rules.max_clearance();
1139                    if lo.x > max.x + slack
1140                        || hi.x < min.x - slack
1141                        || lo.y > max.y + slack
1142                        || hi.y < min.y - slack
1143                    {
1144                        continue;
1145                    }
1146                    let (required, class) =
1147                        self.rules.clearance_between_nets([zone.net.as_str()], nets_of(conn.islands[i]));
1148                    let clearance = f64::from(required);
1149                    let gap = piece.distance(&item.shape);
1150                    if gap + 0.5 < clearance && reported.insert(object(item.owner)) {
1151                        violations.push(Violation {
1152                            kind: ViolationKind::Clearance,
1153                            message: format!(
1154                                "{label} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
1155                                self.describe_on(item.owner, &conn.island_nets[conn.islands[i]], &references),
1156                                gap / 1000.,
1157                                class.name,
1158                                clearance / 1000.
1159                            ),
1160                            at: item.shape.center(),
1161                        });
1162                    }
1163                }
1164                for (other_z, other) in self.zones.iter().enumerate().skip(z + 1) {
1165                    if other.layer != zone.layer || other.net == zone.net {
1166                        continue;
1167                    }
1168                    for (m, other_piece) in other.fill.iter().enumerate() {
1169                        if conn.zone_islands[other_z][m] == island {
1170                            continue;
1171                        }
1172                        let (required, class) =
1173                            self.rules.clearance_between(Some(zone.net.as_str()), Some(other.net.as_str()));
1174                        let clearance = f64::from(required);
1175                        let gap = piece.distance_to_piece(other_piece);
1176                        if gap + 0.5 < clearance {
1177                            violations.push(Violation {
1178                                kind: ViolationKind::Clearance,
1179                                message: format!(
1180                                    "{label} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
1181                                    zones::describe(other, self.layer_count),
1182                                    gap / 1000.,
1183                                    class.name,
1184                                    clearance / 1000.
1185                                ),
1186                                at: other_piece.outer[0],
1187                            });
1188                        }
1189                    }
1190                }
1191                let edge_gap = piece
1192                    .edges()
1193                    .flat_map(|(a, b)| {
1194                        let edge = Shape::segment(a, b, 0);
1195                        self.outline_edges()
1196                            .map(move |(c, d)| edge.distance(&Shape::segment(c, d, 0)))
1197                    })
1198                    .fold(f64::INFINITY, f64::min);
1199                if !self.outline_contains(piece.outer[0]) || edge_gap + 0.5 < edge_clearance {
1200                    violations.push(Violation {
1201                        kind: ViolationKind::BoardEdge,
1202                        message: format!(
1203                            "{label} is outside the board or within {:.3} mm of its edge",
1204                            edge_clearance / 1000.
1205                        ),
1206                        at: piece.outer[0],
1207                    });
1208                }
1209            }
1210        }
1211        let mut reported = BTreeSet::new();
1212        for item in &conn.items {
1213            let center = item.shape.center();
1214            let gap = self
1215                .outline_edges()
1216                .map(|(a, b)| item.shape.distance(&Shape::segment(a, b, 0)))
1217                .fold(f64::INFINITY, f64::min);
1218            if (!self.outline_contains(center) || gap + 0.5 < edge_clearance)
1219                && reported.insert(object(item.owner))
1220            {
1221                violations.push(Violation {
1222                    kind: ViolationKind::BoardEdge,
1223                    message: format!(
1224                        "{} is outside the board or within {:.3} mm of its edge",
1225                        self.describe(item.owner, &references),
1226                        edge_clearance / 1000.
1227                    ),
1228                    at: center,
1229                });
1230            }
1231        }
1232        // Every track at least as wide as its net asks for; an island shorting two
1233        // nets is already a finding, and asks for its widest.
1234        let mut reported = BTreeSet::new();
1235        for (i, item) in conn.items.iter().enumerate() {
1236            let CopperRef::Track { track, .. } = item.owner else { continue };
1237            let t = &self.tracks[track];
1238            let nets = &conn.island_nets[conn.islands[i]];
1239            let (required, rule) = match conn.island_net(conn.islands[i]) {
1240                Some(net) if self.rules.net_widths.contains_key(net) => {
1241                    (self.rules.width_for(net), format!("{net}'s width"))
1242                }
1243                _ => {
1244                    let class = self.rules.class_of_nets(nets.iter().map(String::as_str));
1245                    let widest = nets
1246                        .iter()
1247                        .map(|n| self.rules.width_for(n))
1248                        .max()
1249                        .unwrap_or(class.track_width);
1250                    (widest, format!("{} width", class.name))
1251                }
1252            };
1253            if t.width < required && reported.insert(track) {
1254                violations.push(Violation {
1255                    kind: ViolationKind::TrackWidth,
1256                    message: format!(
1257                        "track on {}{}: {:.3} mm wide, {rule} {:.3} mm required",
1258                        layer_name(t.layer, self.layer_count),
1259                        if nets.is_empty() {
1260                            String::new()
1261                        } else {
1262                            format!(" ({})", nets.iter().cloned().collect::<Vec<_>>().join(", "))
1263                        },
1264                        f64::from(t.width) / 1000.,
1265                        f64::from(required) / 1000.
1266                    ),
1267                    at: t.points.first().copied().unwrap_or_default(),
1268                });
1269            }
1270        }
1271        for (i, a) in self.placements.iter().enumerate() {
1272            let (a0, a1) = a.courtyard();
1273            for b in &self.placements[i + 1..] {
1274                let (b0, b1) = b.courtyard();
1275                if a.bottom == b.bottom && a0.x < b1.x && b0.x < a1.x && a0.y < b1.y && b0.y < a1.y
1276                {
1277                    violations.push(Violation {
1278                        kind: ViolationKind::Courtyard,
1279                        message: format!(
1280                            "Courtyards of {} and {} overlap",
1281                            references.get(&a.component).map_or("?", String::as_str),
1282                            references.get(&b.component).map_or("?", String::as_str)
1283                        ),
1284                        at: Point::new((a.at.x + b.at.x) / 2, (a.at.y + b.at.y) / 2),
1285                    });
1286                }
1287            }
1288        }
1289        for net in netlist.nets.iter().filter(|n| n.pins.len() > 1) {
1290            for pin in &net.pins {
1291                if let Some(placement) = self.placement(pin.component_id)
1292                    && !placement
1293                        .footprint
1294                        .pads
1295                        .iter()
1296                        .any(|p| p.number == pin.number)
1297                {
1298                    violations.push(Violation {
1299                        kind: ViolationKind::MissingPad,
1300                        message: format!(
1301                            "{} pin {} (net {}) has no pad in footprint {}",
1302                            pin.reference, pin.number, net.name, placement.footprint.name
1303                        ),
1304                        at: placement.at,
1305                    });
1306                }
1307            }
1308        }
1309        violations.extend(self.stitching_findings(netlist));
1310        for wire in self.ratsnest(&conn) {
1311            violations.push(Violation {
1312                kind: ViolationKind::Unrouted,
1313                message: format!("Unrouted connection in net {}", wire.net),
1314                at: Point::new((wire.a.x + wire.b.x) / 2, (wire.a.y + wire.b.y) / 2),
1315            });
1316        }
1317        violations.sort_by(|a, b| (a.kind, &a.message, a.at).cmp(&(b.kind, &b.message, b.at)));
1318        violations
1319    }
1320    pub fn validate(&self, components: &BTreeSet<Uuid>) -> Result<(), String> {
1321        let valid = |p: Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
1322        let size = |v: i32| (1..=100_000_000).contains(&v);
1323        if !(1..=32).contains(&self.layer_count) {
1324            return Err("Boards need between 1 and 32 copper layers".into());
1325        }
1326        if self.outline.len() < 3 || self.outline.iter().any(|p| !valid(*p)) {
1327            return Err("Board outline needs at least three valid points".into());
1328        }
1329        let r = &self.rules;
1330        if !size(r.track_width)
1331            || !(0..=100_000_000).contains(&r.clearance)
1332            || !(0..=100_000_000).contains(&r.edge_clearance)
1333            || !size(r.via_drill)
1334            || r.via_diameter <= r.via_drill
1335            || !size(r.via_diameter)
1336            || !(10..=100_000).contains(&r.routing_grid)
1337            || r.net_widths.values().any(|w| !size(*w))
1338            || !(0..=10_000).contains(&r.mask_expansion)
1339        {
1340            return Err("Invalid design rules".into());
1341        }
1342        r.check_net_classes()?;
1343        let mut placed = BTreeSet::new();
1344        for p in &self.placements {
1345            if !components.contains(&p.component) {
1346                return Err("Footprint refers to a missing component".into());
1347            }
1348            if !placed.insert(p.component) {
1349                return Err("Component has more than one footprint".into());
1350            }
1351            if !valid(p.at) || p.rotation > 3 {
1352                return Err("Invalid footprint placement".into());
1353            }
1354            for pad in &p.footprint.pads {
1355                if !valid(pad.at)
1356                    || !size(pad.size.x)
1357                    || !size(pad.size.y)
1358                    || pad
1359                        .drill
1360                        .is_some_and(|d| !size(d) || d > pad.size.x.max(pad.size.y))
1361                {
1362                    return Err(format!("Invalid pad in footprint {}", p.footprint.name));
1363                }
1364            }
1365            if p.footprint.silk.iter().flatten().any(|q| !valid(*q)) {
1366                return Err("Invalid footprint silkscreen".into());
1367            }
1368        }
1369        for t in &self.tracks {
1370            if t.layer >= self.layer_count
1371                || !size(t.width)
1372                || t.points.len() < 2
1373                || t.points.iter().any(|q| !valid(*q))
1374                || t.points.windows(2).any(|s| s[0] == s[1])
1375            {
1376                return Err("Tracks need a valid layer, width, and nonzero segments".into());
1377            }
1378        }
1379        for v in &self.vias {
1380            if !valid(v.at) || !size(v.drill) || v.diameter <= v.drill {
1381                return Err("Invalid via".into());
1382            }
1383        }
1384        for zone in &self.zones {
1385            zone.validate(self.layer_count)?;
1386        }
1387        Ok(())
1388    }
1389}
1390
1391/// Result of bringing the board in line with the schematic.
1392#[derive(Clone, Debug, Default, PartialEq, Eq)]
1393pub struct BoardSync {
1394    pub added: usize,
1395    pub removed: usize,
1396    /// The references of components that need a footprint but have no pads, in
1397    /// natural order. Their part carries none, so they are not on the board.
1398    pub without_pads: Vec<String>,
1399    /// The outline's size, width and height in micrometres, before and after the
1400    /// pass, when the pass grew it: parts added to a board with no free room left
1401    /// for them are packed below it and the outline follows them down.
1402    pub outline_grew: Option<(Point, Point)>,
1403}
1404
1405/// Explicit native pads always belong on the board. Pin-bearing symbols without
1406/// pads are reported as missing pads; standalone power symbols and flags are not.
1407pub fn needs_footprint(component: &crate::Component) -> bool {
1408    component.pads.is_some() || (component.symbol.power_net.is_none()
1409        && !component.reference.starts_with('#')
1410        && !component.symbol.pins.is_empty())
1411}
1412
1413impl Document {
1414    /// Place each new component with its part's pads and drop the placements of
1415    /// removed components. Existing placements are kept. A component with no pads is
1416    /// left off the board and listed in [`BoardSync::without_pads`]: pads come with
1417    /// the part, from a KiCad import or the pads editor, never from a generator.
1418    pub fn sync_board(&mut self) -> BoardSync {
1419        let wanted: BTreeSet<Uuid> = self
1420            .components
1421            .iter()
1422            .filter(|c| needs_footprint(c))
1423            .map(|c| c.id)
1424            .collect();
1425        let before = self.board.placements.len();
1426        self.board
1427            .placements
1428            .retain(|p| wanted.contains(&p.component));
1429        let removed = before - self.board.placements.len();
1430        let was_empty = self.board.placements.is_empty();
1431        let mut added = vec![];
1432        let mut without_pads = vec![];
1433        for c in self.components.iter().filter(|c| wanted.contains(&c.id)) {
1434            if self.board.placement(c.id).is_some() {
1435                continue;
1436            }
1437            let Some(pads) = &c.pads else {
1438                without_pads.push(c.reference.clone());
1439                continue;
1440            };
1441            self.board.placements.push(Placement {
1442                component: c.id,
1443                footprint: pads.clone(),
1444                at: Point::default(),
1445                rotation: 0,
1446                bottom: false,
1447            });
1448            added.push(c.id);
1449        }
1450        without_pads.sort_by(|a, b| footprint::natural_cmp(a, b));
1451        let size = |(min, max): (Point, Point)| Point::new(max.x - min.x, max.y - min.y);
1452        let before = size(self.board.outline_bounds());
1453        if was_empty {
1454            self.auto_place();
1455        } else if !added.is_empty() {
1456            // Into the room the board already has first, beside the parts each shares
1457            // a net with. Packing every addition as a new row under the lowest part
1458            // grew the board by a row per part: six parts added one at a time took a
1459            // stock 60 × 40 mm board to 60 × 54 before it was ever looked at, and one
1460            // capacitor grew a fitted 40 × 19 mm board to 40 × 21 (the eCAD re-audit's
1461            // B10 and item 16).
1462            let homeless = self.seat_in_free_room(&added);
1463            if !homeless.is_empty() {
1464                let (min, _) = self.board.outline_bounds();
1465                let top = self
1466                    .board
1467                    .placements
1468                    .iter()
1469                    .filter(|p| !homeless.contains(&p.component))
1470                    .map(|p| p.courtyard().1.y + PLACEMENT_SPACING)
1471                    .max()
1472                    .unwrap_or(min.y + PLACEMENT_SPACING);
1473                self.pack(&homeless, top);
1474            }
1475        }
1476        let after = size(self.board.outline_bounds());
1477        BoardSync {
1478            added: added.len(),
1479            removed,
1480            without_pads,
1481            outline_grew: (!was_empty && after != before).then_some((before, after)),
1482        }
1483    }
1484    /// Lay every part out afresh by its nets: the part with the most pins in the
1485    /// middle of the board, then each part, in `Self::placement_order`, in the free
1486    /// room nearest the parts already laid out that it shares a small net with. Each
1487    /// keeps its side and its rotation. Where the room runs out the rest are packed
1488    /// in rows below, as [`Self::auto_place`] packs them, and the outline grows.
1489    ///
1490    /// [`Self::auto_place`] packs the same order into rows, so a part's neighbours
1491    /// were the ones beside it in the row and the next row began at the left edge
1492    /// however far that was from them (the eCAD re-audit's B10).
1493    pub fn place_by_nets(&mut self) {
1494        let order = self.placement_order();
1495        let homeless = self.seat_in_free_room(&order);
1496        if !homeless.is_empty() {
1497            let (min, _) = self.board.outline_bounds();
1498            let top = self
1499                .board
1500                .placements
1501                .iter()
1502                .filter(|p| !homeless.contains(&p.component))
1503                .map(|p| p.courtyard().1.y + PLACEMENT_SPACING)
1504                .max()
1505                .unwrap_or(min.y + PLACEMENT_SPACING);
1506            self.pack(&homeless, top);
1507        }
1508    }
1509    /// Seat each of `ids`, in turn, in the free room inside the outline nearest the
1510    /// placed parts it shares a small net with (a rail of more than eight parts is
1511    /// everyone's neighbour and so no one's), or nearest the placed parts' middle
1512    /// when it shares none. Free room is a spot where its courtyard keeps
1513    /// [`SEAT_GAP`] from the outline and from every other courtyard on its side, and
1514    /// the design rules' clearance from every piece of copper already on the board,
1515    /// so a part added to a routed board does not land on a track. Each keeps its
1516    /// side and its rotation. Returns the ones with no room anywhere, left where
1517    /// they were.
1518    fn seat_in_free_room(&mut self, ids: &[Uuid]) -> Vec<Uuid> {
1519        let mut pending: BTreeSet<Uuid> = ids.iter().copied().collect();
1520        let mut nets_of: BTreeMap<Uuid, Vec<usize>> = BTreeMap::new();
1521        for (n, net) in self.netlist().nets.iter().enumerate() {
1522            let members: BTreeSet<Uuid> = net.pins.iter().map(|p| p.component_id).collect();
1523            if members.len() <= 8 {
1524                for m in members {
1525                    nets_of.entry(m).or_default().push(n);
1526                }
1527            }
1528        }
1529        let (min, max) = self.board.outline_bounds();
1530        let clearance = f64::from(self.board.rules.max_clearance());
1531        let gap = f64::from(SEAT_GAP);
1532        let mut homeless = vec![];
1533        for &id in ids {
1534            let Some(index) = self.board.placements.iter().position(|p| p.component == id) else {
1535                continue;
1536            };
1537            let seated: Vec<&Placement> = self
1538                .board
1539                .placements
1540                .iter()
1541                .filter(|p| !pending.contains(&p.component))
1542                .collect();
1543            let mine = nets_of.get(&id).cloned().unwrap_or_default();
1544            let near: Vec<Point> = seated
1545                .iter()
1546                .filter(|p| {
1547                    nets_of
1548                        .get(&p.component)
1549                        .is_some_and(|theirs| theirs.iter().any(|n| mine.contains(n)))
1550                })
1551                .map(|p| p.at)
1552                .collect();
1553            let centre = |points: &[Point]| {
1554                let n = points.len().max(1) as i64;
1555                let (x, y) = points
1556                    .iter()
1557                    .fold((0i64, 0i64), |(x, y), p| (x + i64::from(p.x), y + i64::from(p.y)));
1558                Point::new((x / n) as i32, (y / n) as i32)
1559            };
1560            let target = if !near.is_empty() {
1561                centre(&near)
1562            } else if !seated.is_empty() {
1563                centre(&seated.iter().map(|p| p.at).collect::<Vec<_>>())
1564            } else {
1565                Point::new((min.x + max.x) / 2, (min.y + max.y) / 2)
1566            };
1567            let mut placement = self.board.placements[index].clone();
1568            placement.at = Point::default();
1569            let courtyards: Vec<Shape> = seated
1570                .iter()
1571                .filter(|p| p.bottom == placement.bottom)
1572                .map(|p| {
1573                    let (min, max) = p.courtyard();
1574                    Shape::Rect { min, max }
1575                })
1576                .collect();
1577            let copper: Vec<Shape> = self
1578                .board
1579                .copper()
1580                .into_iter()
1581                .filter(|item| match item.owner {
1582                    CopperRef::Pad { placement, .. } => {
1583                        !pending.contains(&self.board.placements[placement].component)
1584                    }
1585                    _ => true,
1586                })
1587                .map(|item| item.shape)
1588                .collect();
1589            let (c0, c1) = placement.courtyard();
1590            let step = 500;
1591            let span = |lo: i32, hi: i32, c_lo: i32, c_hi: i32| {
1592                let first = snap_up(lo + SEAT_GAP - c_lo, step);
1593                let last = snap_down(hi - SEAT_GAP - c_hi, step);
1594                (first..=last).step_by(step as usize)
1595            };
1596            let mut spots: Vec<Point> = span(min.x, max.x, c0.x, c1.x)
1597                .flat_map(|x| span(min.y, max.y, c0.y, c1.y).map(move |y| Point::new(x, y)))
1598                .collect();
1599            let middle = Point::new((c0.x + c1.x) / 2, (c0.y + c1.y) / 2);
1600            let far = |at: &Point| {
1601                let (dx, dy) = (
1602                    i64::from(at.x + middle.x - target.x),
1603                    i64::from(at.y + middle.y - target.y),
1604                );
1605                (dx * dx + dy * dy, at.y, at.x)
1606            };
1607            spots.sort_by_key(far);
1608            let free = spots.into_iter().find(|&at| {
1609                let body = Shape::Rect { min: c0.offset(at), max: c1.offset(at) };
1610                let corners = [
1611                    c0.offset(at),
1612                    c1.offset(at),
1613                    Point::new(c0.x, c1.y).offset(at),
1614                    Point::new(c1.x, c0.y).offset(at),
1615                ];
1616                corners.iter().all(|&p| self.board.outline_contains(p))
1617                    && self
1618                        .board
1619                        .outline_edges()
1620                        .all(|(a, b)| body.distance(&Shape::segment(a, b, 0)) >= gap)
1621                    && courtyards.iter().all(|c| body.distance(c) >= gap)
1622                    && copper.iter().all(|c| body.distance(c) >= clearance)
1623            });
1624            match free {
1625                Some(at) => {
1626                    placement.at = at;
1627                    self.board.placements[index] = placement;
1628                    pending.remove(&id);
1629                }
1630                None => homeless.push(id),
1631            }
1632        }
1633        homeless
1634    }
1635    /// Pack all placements in rows inside the outline, keeping connected parts together.
1636    pub fn auto_place(&mut self) {
1637        let order = self.placement_order();
1638        let (min, _) = self.board.outline_bounds();
1639        self.pack(&order, min.y + PLACEMENT_SPACING);
1640        let (min, max) = self.board.outline_bounds();
1641        let corners: Vec<Point> = self
1642            .board
1643            .placements
1644            .iter()
1645            .flat_map(|p| {
1646                let (a, b) = p.courtyard();
1647                [a, b]
1648            })
1649            .collect();
1650        if let Some((a, b)) = bounds_of(&corners) {
1651            let centre = |lo: i32, hi: i32, a: i32, b: i32| {
1652                let shift = (lo + hi) / 2 - (a + b) / 2;
1653                shift.div_euclid(100) * 100
1654            };
1655            let shift = Point::new(
1656                centre(min.x, max.x, a.x, b.x),
1657                centre(min.y, max.y, a.y, b.y),
1658            );
1659            for p in &mut self.board.placements {
1660                p.at = p.at.offset(shift);
1661            }
1662        }
1663    }
1664    /// Components ordered by breadth-first traversal of small shared nets.
1665    fn placement_order(&self) -> Vec<Uuid> {
1666        let placed: BTreeSet<Uuid> = self.board.placements.iter().map(|p| p.component).collect();
1667        let mut neighbours: BTreeMap<Uuid, BTreeSet<Uuid>> = BTreeMap::new();
1668        for net in self.netlist().nets {
1669            let members: BTreeSet<Uuid> = net
1670                .pins
1671                .iter()
1672                .map(|p| p.component_id)
1673                .filter(|c| placed.contains(c))
1674                .collect();
1675            if members.len() > 8 {
1676                continue;
1677            }
1678            for a in &members {
1679                neighbours
1680                    .entry(*a)
1681                    .or_default()
1682                    .extend(members.iter().filter(|b| *b != a));
1683            }
1684        }
1685        let mut seeds: Vec<&crate::Component> = self
1686            .components
1687            .iter()
1688            .filter(|c| placed.contains(&c.id))
1689            .collect();
1690        seeds.sort_by(|a, b| {
1691            b.symbol
1692                .pins
1693                .len()
1694                .cmp(&a.symbol.pins.len())
1695                .then_with(|| footprint::natural_cmp(&a.reference, &b.reference))
1696        });
1697        let reference: BTreeMap<Uuid, &str> = self
1698            .components
1699            .iter()
1700            .map(|c| (c.id, c.reference.as_str()))
1701            .collect();
1702        let mut order = vec![];
1703        let mut seen = BTreeSet::new();
1704        for seed in seeds {
1705            if !seen.insert(seed.id) {
1706                continue;
1707            }
1708            let mut queue = std::collections::VecDeque::from([seed.id]);
1709            while let Some(id) = queue.pop_front() {
1710                order.push(id);
1711                let mut next: Vec<Uuid> = neighbours
1712                    .get(&id)
1713                    .into_iter()
1714                    .flatten()
1715                    .filter(|n| !seen.contains(*n))
1716                    .copied()
1717                    .collect();
1718                next.sort_by(|a, b| footprint::natural_cmp(reference[a], reference[b]));
1719                for n in next {
1720                    seen.insert(n);
1721                    queue.push_back(n);
1722                }
1723            }
1724        }
1725        order
1726    }
1727    /// Row-pack the given placements starting at `top`, growing a rectangular outline
1728    /// downward if they do not fit.
1729    fn pack(&mut self, ids: &[Uuid], top: i32) {
1730        let (min, max) = self.board.outline_bounds();
1731        let left = min.x + PLACEMENT_SPACING;
1732        let right = max.x - PLACEMENT_SPACING;
1733        let mut cursor = Point::new(left, top);
1734        let mut row_height = 0;
1735        for id in ids {
1736            let Some(p) = self
1737                .board
1738                .placements
1739                .iter_mut()
1740                .find(|p| p.component == *id)
1741            else {
1742                continue;
1743            };
1744            p.at = Point::default();
1745            let (c0, c1) = p.courtyard();
1746            let (w, h) = (c1.x - c0.x, c1.y - c0.y);
1747            if cursor.x + w > right && cursor.x > left {
1748                cursor = Point::new(left, cursor.y + row_height + PLACEMENT_SPACING);
1749                row_height = 0;
1750            }
1751            p.at = Point::new(snap_up(cursor.x - c0.x, 100), snap_up(cursor.y - c0.y, 100));
1752            cursor.x += w + PLACEMENT_SPACING;
1753            row_height = row_height.max(h);
1754        }
1755        let bottom = cursor.y + row_height + PLACEMENT_SPACING;
1756        if bottom > max.y && self.board.outline_is_rectangle() {
1757            self.board.outline = rectangle(min, Point::new(max.x, snap_up(bottom, 1000)));
1758        }
1759    }
1760    /// Resize a rectangular outline around all courtyards with a margin.
1761    pub fn fit_board_outline(&mut self, margin: i32) {
1762        let corners: Vec<Point> = self
1763            .board
1764            .placements
1765            .iter()
1766            .flat_map(|p| {
1767                let (a, b) = p.courtyard();
1768                [a, b]
1769            })
1770            .chain(self.board.tracks.iter().flat_map(|t| t.points.clone()))
1771            .chain(self.board.vias.iter().map(|v| v.at))
1772            .collect();
1773        if let Some((min, max)) = bounds_of(&corners) {
1774            self.board.outline = rectangle(
1775                Point::new(
1776                    snap_down(min.x - margin, 1000),
1777                    snap_down(min.y - margin, 1000),
1778                ),
1779                Point::new(snap_up(max.x + margin, 1000), snap_up(max.y + margin, 1000)),
1780            );
1781        }
1782    }
1783    /// The schematic net each drawn track carries, for the tracks whose copper island
1784    /// carries exactly one. A track joined to nothing, or bridging two nets, has none.
1785    pub fn track_nets(&self) -> BTreeMap<Uuid, String> {
1786        let connectivity = self.board.connectivity(&self.netlist());
1787        let mut nets = BTreeMap::new();
1788        for (i, item) in connectivity.items.iter().enumerate() {
1789            if let CopperRef::Track { track, .. } = item.owner
1790                && let Some(net) = connectivity.island_net(connectivity.islands[i])
1791            {
1792                nets.insert(self.board.tracks[track].id, net.to_owned());
1793            }
1794        }
1795        nets
1796    }
1797    /// Give every drawn track the width its net asks for, or the default width where its
1798    /// net has no rule of its own. Tracks whose width was set by hand keep it. Returns
1799    /// how many tracks changed. Widening copper can break clearances, so run the design
1800    /// rule check afterwards.
1801    pub fn apply_net_widths(&mut self) -> usize {
1802        let nets = self.track_nets();
1803        let rules = self.board.rules.clone();
1804        let mut changed = 0;
1805        for track in self.board.tracks.iter_mut().filter(|t| !t.fixed_width) {
1806            let width = nets
1807                .get(&track.id)
1808                .map_or(rules.track_width, |net| rules.width_for(net));
1809            if track.width != width {
1810                track.width = width;
1811                changed += 1;
1812            }
1813        }
1814        changed
1815    }
1816    /// Set one track's width, whatever its net asks for. [`Document::apply_net_widths`]
1817    /// then leaves this track alone until [`Document::follow_net_width`] gives it back.
1818    pub fn set_track_width(&mut self, id: Uuid, width: i32) -> Result<(), String> {
1819        if !(1..=100_000_000).contains(&width) {
1820            return Err("A track needs a positive width".into());
1821        }
1822        let track = self
1823            .board
1824            .tracks
1825            .iter_mut()
1826            .find(|t| t.id == id)
1827            .ok_or("Track no longer exists")?;
1828        track.width = width;
1829        track.fixed_width = true;
1830        Ok(())
1831    }
1832    /// Hand one track back to its net's width rule.
1833    pub fn follow_net_width(&mut self, id: Uuid) {
1834        let width = self
1835            .track_nets()
1836            .get(&id)
1837            .map_or(self.board.rules.track_width, |net| {
1838                self.board.rules.width_for(net)
1839            });
1840        if let Some(track) = self.board.tracks.iter_mut().find(|t| t.id == id) {
1841            track.width = width;
1842            track.fixed_width = false;
1843        }
1844    }
1845    pub fn board_drc(&self) -> Vec<Violation> {
1846        self.board.drc(&self.netlist())
1847    }
1848}
1849fn snap_up(v: i32, step: i32) -> i32 {
1850    v.div_euclid(step) * step + if v.rem_euclid(step) == 0 { 0 } else { step }
1851}
1852fn snap_down(v: i32, step: i32) -> i32 {
1853    v.div_euclid(step) * step
1854}