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::graphic::{GraphicLayer, LayerGraphic};
7use crate::{Document, Netlist, Point, Uuid, footprint};
8use serde::{Deserialize, Serialize};
9use std::collections::{BTreeMap, BTreeSet};
10
11/// Courtyard clearance added around footprint bounds.
12pub const COURTYARD_MARGIN: i32 = 250;
13/// Gap between parts and from the board edge during automatic placement.
14const PLACEMENT_SPACING: i32 = 2000;
15/// Gap a part added to a board already laid out keeps from other courtyards and
16/// from the outline ([`Document::seat_in_free_room`]).
17const SEAT_GAP: i32 = 1000;
18
19pub mod net_classes;
20pub mod zones;
21pub use net_classes::{ClassReason, DEFAULT_CLASS, NetClass};
22pub use zones::{FillPiece, Zone};
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
25pub enum PadShape {
26    #[default]
27    Rect,
28    Circle,
29    Oval,
30    /// A rectangle with rounded corners, of [`Pad::corner_radius`].
31    RoundRect,
32    /// A rectangle tapered by [`Pad::trapezoid_delta`] (KiCad's `rect_delta`):
33    /// one pair of opposite sides lengthened and the other shortened.
34    Trapezoid,
35    /// Any simple polygon, [`Pad::polygon`], around the pad's position, its
36    /// outline rounded by [`Pad::corner_radius`].
37    Custom,
38}
39/// The most corners a custom pad's polygon may have.
40pub const MAX_PAD_CORNERS: usize = 1000;
41
42/// What a pad's PRESET (its kind, side and shape) would put on the solder mask and
43/// paste layers, overridden where the user says otherwise. The default is "as the
44/// preset says", and serializes as nothing, so a pad with no overrides is stored
45/// exactly as it was before overrides existed.
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
47pub struct PadLayers {
48    /// Solder mask stays OVER the pad on the footprint's front (tented): no opening.
49    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
50    pub cover_front: bool,
51    /// Solder mask stays over the pad on the footprint's back.
52    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
53    pub cover_back: bool,
54    /// No solder paste aperture for this surface-mount pad.
55    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
56    pub no_paste: bool,
57    /// The mask opening's growth beyond the copper, replacing the board's
58    /// [`DesignRules::mask_expansion`] for this pad.
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub mask_margin: Option<i32>,
61    /// The paste aperture's growth beyond the copper (negative shrinks it), in
62    /// place of the default 0: the aperture matches the copper.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub paste_margin: Option<i32>,
65    /// The paste split into a grid of smaller windows (a windowpane), as a large
66    /// thermal pad's is so the part does not float on one big deposit.
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub paste_windows: Option<PasteWindows>,
69}
70impl PadLayers {
71    pub fn is_auto(&self) -> bool {
72        *self == Self::default()
73    }
74}
75/// A windowpane paste stencil: the aperture's bounding box cut into `columns`
76/// by `rows` equal windows `gap` apart, each kept only where it lies wholly on
77/// the aperture.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
79pub struct PasteWindows {
80    pub columns: u8,
81    pub rows: u8,
82    /// The web of stencil left between windows.
83    pub gap: i32,
84}
85impl PasteWindows {
86    /// Why these windows cannot be cut, if they cannot.
87    pub fn problem(&self) -> Option<&'static str> {
88        if !(1..=20).contains(&self.columns) || !(1..=20).contains(&self.rows) {
89            Some("needs between 1 and 20 paste windows each way")
90        } else if !(0..=10_000).contains(&self.gap) {
91            Some("needs a paste window gap between 0 and 10 mm")
92        } else {
93            None
94        }
95    }
96    /// The windows cut from `aperture`.
97    pub fn cut(&self, aperture: &Shape) -> Vec<Shape> {
98        let (min, max) = aperture.bounds();
99        let (columns, rows) = (i64::from(self.columns.max(1)), i64::from(self.rows.max(1)));
100        let gap = i64::from(self.gap.max(0));
101        let span = |lo: i32, hi: i32, n: i64, k: i64| {
102            let (lo, hi) = (i64::from(lo), i64::from(hi));
103            let cell = (hi - lo - gap * (n - 1)) as f64 / n as f64;
104            let start = lo as f64 + k as f64 * (cell + gap as f64);
105            (start.round() as i32, (start + cell).round() as i32)
106        };
107        let mut out = vec![];
108        for row in 0..rows {
109            let (y0, y1) = span(min.y, max.y, rows, row);
110            for column in 0..columns {
111                let (x0, x1) = span(min.x, max.x, columns, column);
112                if x1 > x0 && y1 > y0 {
113                    let (lo, hi) = (Point::new(x0, y0), Point::new(x1, y1));
114                    if aperture.covers_box(lo, hi) {
115                        out.push(Shape::Rect { min: lo, max: hi });
116                    }
117                }
118            }
119        }
120        out
121    }
122}
123
124#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
125pub struct Pad {
126    /// Matches a symbol pin number. Empty for mechanical pads.
127    pub number: String,
128    pub at: Point,
129    /// Width (x) and height (y) in footprint coordinates.
130    pub size: Point,
131    #[serde(default)]
132    pub shape: PadShape,
133    /// Through-hole drill diameter; `None` for surface-mount pads. For an OVAL
134    /// (slotted) hole, its width along the pad's x ([`Pad::drill_height`]).
135    #[serde(default)]
136    pub drill: Option<i32>,
137    /// An oval (slotted) hole's height along the pad's y, KiCad's
138    /// `(drill oval <width> <height>)`; `None` for a round hole of [`Pad::drill`].
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub drill_height: Option<i32>,
141    /// Whether a drilled hole is plated. Unplated holes go to the NPTH drill file.
142    #[serde(default = "plated_by_default")]
143    pub plated: bool,
144    /// Corner radius of a [`PadShape::RoundRect`] pad, at most half its smaller side.
145    #[serde(default, skip_serializing_if = "is_zero")]
146    pub corner_radius: i32,
147    /// A surface-mount pad on the footprint's BACK copper (B.Cu) rather than its
148    /// front. A part mounted on the bottom flips this with the rest of the part.
149    /// Ignored for a drilled pad, which spans every copper layer.
150    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
151    pub back: bool,
152    /// Mask and paste overrides of what the pad's preset generates.
153    #[serde(default, skip_serializing_if = "PadLayers::is_auto")]
154    pub layers: PadLayers,
155    /// A [`PadShape::Trapezoid`] pad's taper, KiCad's `rect_delta`: `x`
156    /// lengthens the left side and shortens the right by as much, `y`
157    /// lengthens the bottom and shortens the top.
158    #[serde(default, skip_serializing_if = "is_origin")]
159    pub trapezoid_delta: Point,
160    /// A [`PadShape::Custom`] pad's copper: a closed polygon of corners relative
161    /// to [`Pad::at`], which it covers.
162    #[serde(default, skip_serializing_if = "Vec::is_empty")]
163    pub polygon: Vec<Point>,
164    /// A grid of through vias in a surface-mount pad (a thermal pad's), owned
165    /// by the footprint: on a board each is a via on every layer, joined to the
166    /// pad's copper.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub vias: Option<PadVias>,
169}
170/// A pad's grid of through vias: `columns` by `rows` about the pad's position,
171/// `pitch` apart, each of `diameter` copper round a `drill` hole.
172#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
173pub struct PadVias {
174    pub columns: u8,
175    pub rows: u8,
176    pub pitch: Point,
177    pub drill: i32,
178    pub diameter: i32,
179    /// The solder mask stays over the vias on the side away from the pad
180    /// (tented), so solder cannot wick through and out. On the pad's own side
181    /// the pad's mask opening exposes them either way.
182    #[serde(default = "plated_by_default")]
183    pub tented: bool,
184}
185/// The most vias one pad's grid may have each way.
186pub const MAX_PAD_VIAS_EACH_WAY: u8 = 20;
187fn plated_by_default() -> bool {
188    true
189}
190fn is_zero(v: &i32) -> bool {
191    *v == 0
192}
193fn is_origin(p: &Point) -> bool {
194    *p == Point::default()
195}
196impl Pad {
197    /// A pad of the given number, place, size and shape with every other property
198    /// at its default: surface mount, front, no overrides.
199    pub fn smd(number: impl Into<String>, at: Point, size: Point, shape: PadShape) -> Self {
200        Self {
201            number: number.into(),
202            at,
203            size,
204            shape,
205            drill: None,
206            drill_height: None,
207            plated: true,
208            corner_radius: 0,
209            back: false,
210            layers: PadLayers::default(),
211            trapezoid_delta: Point::default(),
212            polygon: vec![],
213            vias: None,
214        }
215    }
216    /// The centres of the pad's vias in footprint coordinates, row by row from
217    /// the top left; none without a grid.
218    pub fn via_points(&self) -> Vec<Point> {
219        let Some(v) = self.vias else { return vec![] };
220        let at = |k: i64, n: u8, pitch: i32, centre: i32| {
221            let offset = (2 * k - (i64::from(n) - 1)) * i64::from(pitch) / 2;
222            (i64::from(centre) + offset).clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32
223        };
224        let mut out = vec![];
225        for row in 0..i64::from(v.rows) {
226            for column in 0..i64::from(v.columns) {
227                out.push(Point::new(
228                    at(column, v.columns, v.pitch.x, self.at.x),
229                    at(row, v.rows, v.pitch.y, self.at.y),
230                ));
231            }
232        }
233        out
234    }
235    /// Why the pad's via grid cannot be built, if it cannot.
236    pub fn vias_problem(&self) -> Option<String> {
237        let v = self.vias?;
238        if self.drill.is_some() {
239            return Some("carries a via grid only as a surface-mount pad".into());
240        }
241        if !(1..=MAX_PAD_VIAS_EACH_WAY).contains(&v.columns) || !(1..=MAX_PAD_VIAS_EACH_WAY).contains(&v.rows) {
242            return Some(format!("needs between 1 and {MAX_PAD_VIAS_EACH_WAY} vias each way"));
243        }
244        if !(1..=10_000).contains(&v.drill) || v.diameter <= v.drill || v.diameter > 20_000 {
245            return Some("needs a via drill up to 10 mm and a via diameter larger than its drill".into());
246        }
247        if (v.columns > 1 && v.pitch.x < v.diameter) || (v.rows > 1 && v.pitch.y < v.diameter) || v.pitch.x > 100_000 || v.pitch.y > 100_000 {
248            return Some("needs a via pitch at least the via diameter".into());
249        }
250        let copper = self.local_shape();
251        if self.via_points().iter().any(|p| copper.depth(*p) < f64::from(v.diameter) / 2.) {
252            return Some("has a via that leaves its copper".into());
253        }
254        None
255    }
256    /// The corner radius actually drawn: the stored one for a rounded rectangle,
257    /// clamped to half the smaller side, a custom pad's rounding, else 0.
258    pub fn effective_corner_radius(&self) -> i32 {
259        match self.shape {
260            PadShape::RoundRect => self.corner_radius.clamp(0, self.size.x.min(self.size.y) / 2),
261            PadShape::Custom => self.corner_radius.clamp(0, 100_000),
262            _ => 0,
263        }
264    }
265    /// A trapezoid or custom pad's corners in footprint coordinates, else `None`.
266    pub fn corners(&self) -> Option<Vec<Point>> {
267        let at = |x: i64, y: i64| {
268            let c = |v: i64| v.clamp(i64::from(i32::MIN), i64::from(i32::MAX)) as i32;
269            Point::new(c(i64::from(self.at.x) + x), c(i64::from(self.at.y) + y))
270        };
271        match self.shape {
272            PadShape::Trapezoid => {
273                let (hx, hy) = (i64::from(self.size.x) / 2, i64::from(self.size.y) / 2);
274                let (dx, dy) = (i64::from(self.trapezoid_delta.x) / 2, i64::from(self.trapezoid_delta.y) / 2);
275                Some(vec![
276                    at(-hx - dy, hy + dx),
277                    at(hx + dy, hy - dx),
278                    at(hx - dy, -hy + dx),
279                    at(-hx + dy, -hy - dx),
280                ])
281            }
282            PadShape::Custom => Some(self.polygon.iter().map(|p| at(i64::from(p.x), i64::from(p.y))).collect()),
283            _ => None,
284        }
285    }
286    /// The pad's copper in footprint coordinates.
287    pub fn local_shape(&self) -> Shape {
288        match self.corners() {
289            Some(corners) => Shape::polygon(corners, self.effective_corner_radius()),
290            None => Shape::rounded_pad(self.at, self.size, self.shape, self.effective_corner_radius()),
291        }
292    }
293    /// Why a trapezoid's taper or a custom pad's polygon is not copper, if it is
294    /// not.
295    pub fn outline_problem(&self) -> Option<String> {
296        let far = |v: i32| !(-100_000_000..=100_000_000).contains(&v);
297        match self.shape {
298            PadShape::Trapezoid => {
299                let d = self.trapezoid_delta;
300                if d.x.unsigned_abs() >= self.size.y.unsigned_abs() || d.y.unsigned_abs() >= self.size.x.unsigned_abs() {
301                    return Some("needs a taper shorter than the side it narrows".into());
302                }
303                if d.x != 0 && d.y != 0 {
304                    return Some("tapers one pair of sides only".into());
305                }
306                None
307            }
308            PadShape::Custom => {
309                let n = self.polygon.len();
310                if n < 3 {
311                    return Some("needs at least three corners".into());
312                }
313                if n > MAX_PAD_CORNERS {
314                    return Some(format!("has more than {MAX_PAD_CORNERS} corners"));
315                }
316                if self.polygon.iter().any(|p| far(p.x) || far(p.y)) || far(self.at.x) || far(self.at.y) {
317                    return Some("lies outside the drawing area".into());
318                }
319                if ring_area2(&self.polygon) == 0 {
320                    return Some("encloses no area".into());
321                }
322                if ring_crosses_itself(&self.polygon) {
323                    return Some("crosses itself".into());
324                }
325                if polygon_depth(&self.polygon, Point::default()) + f64::from(self.effective_corner_radius()) < 0. {
326                    return Some("does not cover its own position".into());
327                }
328                None
329            }
330            _ => None,
331        }
332    }
333    /// Which sides of the FOOTPRINT the pad's copper reaches: (front, back).
334    pub fn copper_sides(&self) -> (bool, bool) {
335        match self.drill {
336            Some(_) => (true, true),
337            None => (!self.back, self.back),
338        }
339    }
340    /// Whether the pad gets a solder mask opening on the footprint's front (or back).
341    pub fn mask_open(&self, front: bool) -> bool {
342        let (f, b) = self.copper_sides();
343        if front {
344            f && !self.layers.cover_front
345        } else {
346            b && !self.layers.cover_back
347        }
348    }
349    /// Whether the pad gets a paste aperture on the footprint's front (or back).
350    pub fn paste_open(&self, front: bool) -> bool {
351        self.drill.is_none() && !self.layers.no_paste && self.back != front
352    }
353    /// The hole's extent, width (x) and height (y) in footprint coordinates: a
354    /// round hole's diameter both ways, a slot's own two. `None` with no drill.
355    pub fn hole_size(&self) -> Option<Point> {
356        let width = self.drill?;
357        Some(Point::new(width, self.drill_height.unwrap_or(width)))
358    }
359    /// The hole in footprint coordinates: a circle, or a slot's stadium.
360    pub fn local_hole(&self) -> Option<Shape> {
361        Some(Shape::pad(self.at, self.hole_size()?, PadShape::Oval))
362    }
363    /// The plated copper ring left round the drill, at its narrowest. `None` for
364    /// a pad with no drill or an unplated hole; negative where the hole breaks
365    /// out of the copper.
366    pub fn annular_ring(&self) -> Option<i32> {
367        let drill = self.drill.filter(|_| self.plated)?;
368        if self.drill_height.is_none() && self.corners().is_none() {
369            // A round hole: half the pad's smaller side less the drill's radius,
370            // as it has always been measured.
371            return Some((self.size.x.min(self.size.y) - drill) / 2);
372        }
373        Some(self.hole_clearance()?.floor() as i32)
374    }
375    /// How far the hole stays inside the pad's copper at its nearest: the hole is
376    /// a disc swept along a segment. The preset shapes are convex, so the depth
377    /// of the copper over the segment is least at one of its ends. A polygon may
378    /// turn inward. A hole within the polygon's own corners, crossing none of its
379    /// edges, has the nearest edge's distance and the rounding as its ring; any
380    /// other (in the rounding, or across a notch) is measured along its length.
381    fn hole_clearance(&self) -> Option<f64> {
382        let Shape::Capsule { a, b, radius } = self.local_hole()? else {
383            return None;
384        };
385        let copper = self.local_shape();
386        if let Shape::Polygon { points, radius: round } = &copper {
387            let within = polygon_contains(points, a)
388                && polygon_contains(points, b)
389                && ring_edges(points).all(|(p, q)| !segments_intersect(p, q, a, b));
390            if !within {
391                // Through the rounding, or across a notch: the copper's own depth,
392                // sampled along the hole's segment at most a micrometre apart and
393                // taken half a step shallower, as depth changes no faster than
394                // the point moves.
395                let len = f64::from(b.x - a.x).hypot(f64::from(b.y - a.y));
396                let steps = (len.ceil() as usize).clamp(1, 4096);
397                let step = len / steps as f64;
398                let depth = (0..=steps)
399                    .map(|k| {
400                        let t = k as f64 / steps as f64;
401                        let p = Point::new(
402                            (f64::from(a.x) + t * f64::from(b.x - a.x)).round() as i32,
403                            (f64::from(a.y) + t * f64::from(b.y - a.y)).round() as i32,
404                        );
405                        copper.depth(p)
406                    })
407                    .fold(f64::INFINITY, f64::min);
408                return Some(depth - step / 2. - f64::from(radius));
409            }
410            let edges = ring_edges(points).map(|(p, q)| segment_distance(p, q, a, b)).fold(f64::INFINITY, f64::min);
411            return Some(edges + f64::from(*round) - f64::from(radius));
412        }
413        Some(copper.depth(a).min(copper.depth(b)) - f64::from(radius))
414    }
415    /// Why the hole does not fit the pad, if it does not: a drill must be
416    /// positive and no wider or taller than the pad.
417    fn hole_problem(&self) -> Option<&'static str> {
418        let hole = self.hole_size()?;
419        let far = |v: i32| !(-100_000_000..=100_000_000).contains(&v);
420        if [self.at.x, self.at.y, self.size.x, self.size.y, hole.x, hole.y].into_iter().any(far) {
421            // Measured nowhere: the geometry would overflow before it could say why.
422            return Some("lies outside the drawing area");
423        }
424        if hole.x <= 0 || hole.y <= 0 {
425            Some("needs a positive drill")
426        } else if self.drill_height.is_some() && self.hole_clearance().is_some_and(|c| c < 0.) {
427            Some("has a slot larger than the pad")
428        } else if self.drill_height.is_none() && self.corners().is_some() && self.hole_clearance().is_some_and(|c| c < 0.) {
429            Some("has a drill larger than the pad")
430        } else if self.drill_height.is_none() && hole.x > self.size.x.max(self.size.y) {
431            Some("has a drill larger than the pad")
432        } else {
433            None
434        }
435    }
436}
437
438/// The 3D model a footprint names, as KiCad's `(model …)` entry gives it: the file and
439/// its placement on the pads. The numbers are carried through as the file authored them,
440/// millimetres for the offset and degrees for the rotation, for a host to interpret.
441#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
442pub struct Model {
443    /// The file the footprint names, often with a variable such as
444    /// `${KICAD9_3DMODEL_DIR}` that the host resolves.
445    pub path: String,
446    #[serde(default)]
447    pub offset: [f64; 3],
448    #[serde(default = "unit_scale")]
449    pub scale: [f64; 3],
450    #[serde(default)]
451    pub rotation: [f64; 3],
452}
453fn unit_scale() -> [f64; 3] {
454    [1., 1., 1.]
455}
456impl Model {
457    /// The same model as a STEP file. KiCad's libraries name a `.wrl` mesh for rendering
458    /// and keep a `.step` of the same name beside it, which carries the solid geometry;
459    /// any other path is returned unchanged.
460    pub fn step_path(&self) -> String {
461        match self.path.strip_suffix(".wrl") {
462            Some(stem) => format!("{stem}.step"),
463            None => self.path.clone(),
464        }
465    }
466}
467#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
468pub struct Footprint {
469    pub name: String,
470    pub pads: Vec<Pad>,
471    /// Silkscreen polylines in footprint coordinates.
472    #[serde(default)]
473    pub silk: Vec<Vec<Point>>,
474    /// The 3D model this footprint names, if it has one.
475    #[serde(default, skip_serializing_if = "Option::is_none")]
476    pub model: Option<Model>,
477    /// Courtyard clearance round the pads and silkscreen, in place of
478    /// [`COURTYARD_MARGIN`].
479    #[serde(default, skip_serializing_if = "Option::is_none")]
480    pub courtyard_margin: Option<i32>,
481    /// Drawn items on the silkscreen, fabrication and courtyard layers of either
482    /// side, beside the front silkscreen polylines in `silk`.
483    #[serde(default, skip_serializing_if = "Vec::is_empty")]
484    pub graphics: Vec<LayerGraphic>,
485}
486impl Footprint {
487    /// Check a footprint on its own, with messages that name the offending pad: the
488    /// AUTHORING rule, [`Footprint::validate_placeable`] plus a name.
489    pub fn validate(&self) -> Result<(), String> {
490        if self.name.trim().is_empty() {
491            return Err("Enter a footprint name.".into());
492        }
493        self.validate_placeable()
494    }
495    /// Whether a footprint can sit on a board: every check of [`Footprint::validate`]
496    /// except the name. A name is a label, and a copy of a part's pads that has none
497    /// is still copper a board can carry; refusing it there refused the whole document,
498    /// so one unnamed part in an assembly stopped every edit to the sheet and the board
499    /// from being stored (the eCAD workflow audit, issue 3).
500    pub fn validate_placeable(&self) -> Result<(), String> {
501        for pad in &self.pads {
502            let name = if pad.number.is_empty() {
503                "An unnumbered pad".to_owned()
504            } else {
505                format!("Pad {}", pad.number)
506            };
507            if pad.size.x <= 0 || pad.size.y <= 0 {
508                return Err(format!("{name} needs a positive width and height."));
509            }
510            if let Some(problem) = pad.outline_problem() {
511                return Err(format!("{name} {problem}."));
512            }
513            if let Some(problem) = pad.hole_problem() {
514                return Err(format!("{name} {problem}."));
515            }
516            if !(0..=100_000).contains(&pad.corner_radius) {
517                return Err(format!("{name} needs a corner radius between 0 and 100 mm."));
518            }
519            let margins = [pad.layers.mask_margin, pad.layers.paste_margin];
520            if margins.into_iter().flatten().any(|m| !(-10_000..=10_000).contains(&m)) {
521                return Err(format!("{name} has a mask or paste margin beyond 10 mm."));
522            }
523            if let Some(problem) = pad.layers.paste_windows.and_then(|w| w.problem()) {
524                return Err(format!("{name} {problem}."));
525            }
526            if let Some(problem) = pad.vias_problem() {
527                return Err(format!("{name} {problem}."));
528            }
529        }
530        if self.courtyard_margin.is_some_and(|m| !(0..=100_000).contains(&m)) {
531            return Err("The courtyard clearance must be between 0 and 100 mm.".into());
532        }
533        if self.silk.iter().any(|line| line.len() < 2) {
534            return Err("Silkscreen lines need at least two points.".into());
535        }
536        if self.graphics.len() > 100_000 {
537            return Err("A footprint can carry at most 100000 drawn items.".into());
538        }
539        for (i, graphic) in self.graphics.iter().enumerate() {
540            if let Some(problem) = graphic.problem() {
541                return Err(format!("Drawing {} on {} {problem}.", i + 1, graphic.layer.name()));
542            }
543        }
544        if let Some(model) = &self.model {
545            let numbers = model
546                .offset
547                .iter()
548                .chain(&model.scale)
549                .chain(&model.rotation);
550            if model.path.trim().is_empty() || numbers.into_iter().any(|v| !v.is_finite()) {
551                return Err("The 3D model needs a file and finite placement numbers.".into());
552            }
553        }
554        let id = Uuid::nil();
555        let board = Board {
556            placements: vec![Placement {
557                component: id,
558                footprint: self.clone(),
559                at: Point::new(0, 0),
560                rotation: 0,
561                bottom: false,
562            }],
563            ..Board::default()
564        };
565        board.validate(&BTreeSet::from([id]))
566    }
567    /// Every drawn item as (layer, pen width, filled, centre lines) in footprint
568    /// coordinates: the `silk` polylines as front silkscreen at
569    /// [`crate::fabrication::SILK_WIDTH`], then the graphics. Text on a back layer
570    /// is written mirrored, so it reads from the back.
571    pub fn drawing(&self) -> impl Iterator<Item = Drawn> + '_ {
572        let silk = self.silk.iter().map(|line| Drawn {
573            layer: GraphicLayer::FrontSilk,
574            width: crate::fabrication::SILK_WIDTH,
575            filled: false,
576            strokes: vec![line.clone()],
577        });
578        silk.chain(self.graphics.iter().map(|g| Drawn {
579            layer: g.layer,
580            width: g.width(),
581            filled: g.filled,
582            strokes: g.strokes(!g.layer.front()),
583        }))
584    }
585    /// The bounds of the courtyard drawn on the footprint's front (F.CrtYd,
586    /// `front`) or back (B.CrtYd), if it has one. The front one replaces the
587    /// rectangle generated round pads and legend.
588    pub fn drawn_courtyard(&self, front: bool) -> Option<(Point, Point)> {
589        let layer = if front { GraphicLayer::FrontCourtyard } else { GraphicLayer::BackCourtyard };
590        let points: Vec<Point> = self
591            .graphics
592            .iter()
593            .filter(|g| g.layer == layer)
594            .flat_map(LayerGraphic::points)
595            .collect();
596        bounds_of(&points)
597    }
598    /// Bounds of pads and silkscreen (on either side) in footprint coordinates.
599    pub fn bounds(&self) -> (Point, Point) {
600        let mut points: Vec<Point> = self
601            .pads
602            .iter()
603            .flat_map(|p| {
604                let (min, max) = match p.corners() {
605                    Some(_) => p.local_shape().bounds(),
606                    None => Shape::pad(p.at, p.size, PadShape::Rect).bounds(),
607                };
608                [min, max]
609            })
610            .collect();
611        points.extend(self.silk.iter().flatten().copied());
612        points.extend(
613            self.graphics
614                .iter()
615                .filter(|g| g.layer.is_silk())
616                .flat_map(LayerGraphic::points),
617        );
618        bounds_of(&points).unwrap_or_default()
619    }
620}
621
622/// One drawn item of a footprint, read by [`Footprint::drawing`].
623#[derive(Clone, Debug, PartialEq, Eq)]
624pub struct Drawn {
625    pub layer: GraphicLayer,
626    pub width: i32,
627    pub filled: bool,
628    /// Centre lines in footprint coordinates.
629    pub strokes: Vec<Vec<Point>>,
630}
631
632/// One footprint instance, bound to a schematic component by ID.
633#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
634pub struct Placement {
635    pub component: Uuid,
636    pub footprint: Footprint,
637    pub at: Point,
638    #[serde(default)]
639    pub rotation: u8,
640    /// Mounted on the bottom side: mirrored in X, and SMD pads use the last layer.
641    #[serde(default)]
642    pub bottom: bool,
643}
644impl Placement {
645    pub fn transform(&self, p: Point) -> Point {
646        let p = if self.bottom {
647            Point::new(-p.x, p.y)
648        } else {
649            p
650        };
651        p.rotate(self.rotation).offset(self.at)
652    }
653    pub fn pad_shape(&self, pad: &Pad) -> Shape {
654        let size = if self.rotation % 2 == 1 {
655            Point::new(pad.size.y, pad.size.x)
656        } else {
657            pad.size
658        };
659        match pad.corners() {
660            Some(corners) => Shape::polygon(
661                corners.into_iter().map(|p| self.transform(p)).collect(),
662                pad.effective_corner_radius(),
663            ),
664            None => Shape::rounded_pad(self.transform(pad.at), size, pad.shape, pad.effective_corner_radius()),
665        }
666    }
667    /// A pad's grid of vias on the board, each a through via with an identity
668    /// fixed by the part, the pad and its place in the grid.
669    pub fn pad_vias(&self, pad_index: usize) -> Vec<Via> {
670        let Some(pad) = self.footprint.pads.get(pad_index) else { return vec![] };
671        let Some(grid) = pad.vias else { return vec![] };
672        pad.via_points()
673            .into_iter()
674            .enumerate()
675            .map(|(k, p)| Via {
676                id: Uuid::from_u128(
677                    self.component.as_u128() ^ (0x7061_6476_6961_u128 << 80) ^ ((pad_index as u128) << 32) ^ (k as u128 + 1),
678                ),
679                at: self.transform(p),
680                diameter: grid.diameter,
681                drill: grid.drill,
682                span: None,
683            })
684            .collect()
685    }
686    /// A surface-mount pad's paste on the board: its copper grown by its paste
687    /// margin, cut into windows when it has a windowpane. The windows are cut in
688    /// the footprint's own frame, so columns and rows turn with the part.
689    pub fn pad_paste(&self, pad: &Pad) -> Vec<Shape> {
690        let margin = pad.layers.paste_margin.unwrap_or(0);
691        let Some(windows) = pad.layers.paste_windows else {
692            return self.pad_shape(pad).grown_parts(margin);
693        };
694        // A window over a via's hole would print paste into it: not cut.
695        let holes: Vec<Shape> = match pad.vias {
696            Some(grid) => pad.via_points().into_iter().map(|p| Shape::circle(p, grid.drill / 2)).collect(),
697            None => vec![],
698        };
699        pad.local_shape()
700            .grown_parts(margin)
701            .iter()
702            .flat_map(|aperture| windows.cut(aperture))
703            .filter(|window| holes.iter().all(|hole| hole.distance(window) > 0.))
704            .filter_map(|window| {
705                let Shape::Rect { min, max } = window else { return None };
706                let (a, b) = (self.transform(min), self.transform(max));
707                Some(Shape::Rect {
708                    min: Point::new(a.x.min(b.x), a.y.min(b.y)),
709                    max: Point::new(a.x.max(b.x), a.y.max(b.y)),
710                })
711            })
712            .collect()
713    }
714    /// A drilled pad's hole on the board: a circle, or a slot turned with the part.
715    pub fn pad_hole(&self, pad: &Pad) -> Option<Shape> {
716        let hole = pad.hole_size()?;
717        let hole = if self.rotation % 2 == 1 { Point::new(hole.y, hole.x) } else { hole };
718        Some(Shape::pad(self.transform(pad.at), hole, PadShape::Oval))
719    }
720    /// Inclusive copper layer range of a pad: a drilled pad spans every layer, a
721    /// surface-mount pad sits on the board side its footprint side faces.
722    pub fn pad_layers(&self, pad: &Pad, layer_count: u8) -> (u8, u8) {
723        let last = layer_count.saturating_sub(1);
724        match (pad.drill, self.bottom != pad.back) {
725            (Some(_), _) => (0, last),
726            (None, false) => (0, 0),
727            (None, true) => (last, last),
728        }
729    }
730    /// Whether a surface-mount pad of this placement sits on the board's BOTTOM
731    /// copper: a back pad of a top part, or a front pad of a bottom part.
732    pub fn has_back_copper_pad(&self) -> bool {
733        self.footprint.pads.iter().any(|pad| pad.drill.is_none() && pad.back != self.bottom)
734    }
735    /// The footprint side that faces the board's top (true) or bottom (false):
736    /// true means the footprint's front.
737    pub fn front_faces(&self, board_top: bool) -> bool {
738        board_top != self.bottom
739    }
740    /// Every drawn item of the footprint that lands on `layer` of the BOARD, as
741    /// (pen width, filled, centre lines) in board coordinates: a part on the
742    /// bottom puts its front layers on the board's back.
743    pub fn drawing_on(&self, layer: GraphicLayer) -> Vec<(i32, bool, Vec<Vec<Point>>)> {
744        self.footprint
745            .drawing()
746            .filter(|d| if self.bottom { d.layer.flipped() } else { d.layer } == layer)
747            .map(|d| {
748                let strokes = d
749                    .strokes
750                    .into_iter()
751                    .map(|line| line.into_iter().map(|p| self.transform(p)).collect())
752                    .collect();
753                (d.width, d.filled, strokes)
754            })
755            .collect()
756    }
757    /// The board layer one of the footprint's graphics lands on, and its centre
758    /// lines in board coordinates.
759    pub fn place_graphic(&self, graphic: &LayerGraphic) -> (GraphicLayer, Vec<Vec<Point>>) {
760        let layer = if self.bottom { graphic.layer.flipped() } else { graphic.layer };
761        let strokes = graphic
762            .strokes(!graphic.layer.front())
763            .into_iter()
764            .map(|line| line.into_iter().map(|p| self.transform(p)).collect())
765            .collect();
766        (layer, strokes)
767    }
768    /// The world-space rectangle round a courtyard drawn on the footprint's
769    /// BACK (B.CrtYd), which is on the board side opposite the one the part is
770    /// mounted on.
771    pub fn back_courtyard(&self) -> Option<(Point, Point)> {
772        let (min, max) = self.footprint.drawn_courtyard(false)?;
773        let corners = [min, max, Point::new(min.x, max.y), Point::new(max.x, min.y)]
774            .map(|p| self.transform(p));
775        bounds_of(&corners)
776    }
777    /// The courtyard rectangles this part occupies on the board's top (`true`)
778    /// or bottom side: its own on the side it is mounted on, and a drawn back
779    /// courtyard on the other.
780    pub fn courtyard_on(&self, top: bool) -> Option<(Point, Point)> {
781        if self.bottom != top { Some(self.courtyard()) } else { self.back_courtyard() }
782    }
783    /// World-space courtyard rectangle: round the drawn courtyard when the
784    /// footprint has one, otherwise round the pads and legend plus the clearance.
785    pub fn courtyard(&self) -> (Point, Point) {
786        let drawn = self.footprint.drawn_courtyard(true);
787        let (min, max) = drawn.unwrap_or_else(|| self.footprint.bounds());
788        let corners = [min, max, Point::new(min.x, max.y), Point::new(max.x, min.y)]
789            .map(|p| self.transform(p));
790        let (min, max) = bounds_of(&corners).unwrap_or_default();
791        let margin = match drawn {
792            Some(_) => 0,
793            None => self.footprint.courtyard_margin.unwrap_or(COURTYARD_MARGIN),
794        };
795        (
796            Point::new(min.x - margin, min.y - margin),
797            Point::new(max.x + margin, max.y + margin),
798        )
799    }
800}
801
802#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
803pub struct Track {
804    pub id: Uuid,
805    pub layer: u8,
806    pub width: i32,
807    /// The width was set on this track itself, so the net's width rule leaves it alone.
808    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
809    pub fixed_width: bool,
810    pub points: Vec<Point>,
811}
812impl Track {
813    /// Build a track, dropping repeated and collinear interior points.
814    pub fn new(layer: u8, width: i32, points: Vec<Point>) -> Self {
815        Self {
816            id: Uuid::new_v4(),
817            layer,
818            width,
819            fixed_width: false,
820            points: simplify_path(points),
821        }
822    }
823    pub fn segments(&self) -> impl Iterator<Item = Shape> + '_ {
824        self.points
825            .windows(2)
826            .map(|s| Shape::segment(s[0], s[1], self.width))
827    }
828}
829
830#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
831pub struct Via {
832    pub id: Uuid,
833    pub at: Point,
834    pub diameter: i32,
835    pub drill: i32,
836    /// The copper layers a BLIND or BURIED via joins, inclusive and top first
837    /// (`from < to`). `None` is a through via, joining every layer, and is how
838    /// every via was stored before spans existed.
839    #[serde(default, skip_serializing_if = "Option::is_none")]
840    pub span: Option<(u8, u8)>,
841}
842/// What a via joins: every layer, an outer layer to an inner one, or inner
843/// layers only.
844#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
845pub enum ViaKind {
846    Through,
847    /// From the top or bottom copper to an inner layer.
848    Blind,
849    /// Between inner layers only.
850    Buried,
851}
852impl Via {
853    /// A through via.
854    pub fn through(at: Point, diameter: i32, drill: i32) -> Self {
855        Self { id: Uuid::new_v4(), at, diameter, drill, span: None }
856    }
857    /// The inclusive copper layer range the via joins on a board of
858    /// `layer_count` layers.
859    pub fn layers(&self, layer_count: u8) -> (u8, u8) {
860        let last = layer_count.saturating_sub(1);
861        match self.span {
862            Some((from, to)) => (from.min(last), to.min(last)),
863            None => (0, last),
864        }
865    }
866    pub fn kind(&self, layer_count: u8) -> ViaKind {
867        let last = layer_count.saturating_sub(1);
868        match self.layers(layer_count) {
869            (0, to) if to == last => ViaKind::Through,
870            (from, to) if from == 0 || to == last => ViaKind::Blind,
871            _ => ViaKind::Buried,
872        }
873    }
874}
875
876#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
877pub struct DesignRules {
878    /// The Default net class's track width, clearance and via ([`net_classes`]).
879    pub track_width: i32,
880    pub clearance: i32,
881    pub via_diameter: i32,
882    pub via_drill: i32,
883    /// Minimum distance from copper to the board outline.
884    pub edge_clearance: i32,
885    /// Autorouter grid pitch.
886    pub routing_grid: i32,
887    /// Track width overrides by exact net name, e.g. wider supply nets.
888    #[serde(default)]
889    pub net_widths: BTreeMap<String, i32>,
890    /// Solder mask openings extend this far beyond each pad.
891    #[serde(default = "default_mask_expansion")]
892    pub mask_expansion: i32,
893    /// How the autorouter uses vias. Boards saved before this existed get the default.
894    #[serde(default)]
895    pub autoroute_vias: ViaPolicy,
896    /// The net classes besides Default, in pattern order ([`net_classes`]). Written
897    /// only when there are some, so a board with none saves as it did before.
898    #[serde(default, skip_serializing_if = "Vec::is_empty")]
899    pub net_classes: Vec<NetClass>,
900    /// Explicit net → class assignments, which beat every pattern.
901    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
902    pub net_class_of: BTreeMap<String, String>,
903    /// The narrowest plated copper ring a drilled pad or via may keep round its
904    /// hole. Written only when it differs from the default, so a board that never
905    /// changed it is stored as before.
906    #[serde(
907        default = "default_min_annular_ring",
908        skip_serializing_if = "is_default_min_annular_ring"
909    )]
910    pub min_annular_ring: i32,
911    /// Whether the solder mask covers every via (tented, the default) or opens
912    /// over each via's ring on both sides. Written only when off.
913    #[serde(default = "tented_by_default", skip_serializing_if = "Clone::clone")]
914    pub tent_vias: bool,
915    /// The narrowest web of board left between two drilled holes, edge to edge
916    /// (KiCad's hole to hole). 0 turns the check off, though holes that touch
917    /// are always a finding. Written only when it differs from the default.
918    #[serde(
919        default = "default_min_hole_spacing",
920        skip_serializing_if = "is_default_min_hole_spacing"
921    )]
922    pub min_hole_spacing: i32,
923}
924fn tented_by_default() -> bool {
925    true
926}
927fn default_mask_expansion() -> i32 {
928    50
929}
930/// The default minimum annular ring, 0.13 mm: the ring most board houses quote
931/// for their standard process (KiCad's own default is 0.1 mm).
932pub const DEFAULT_MIN_ANNULAR_RING: i32 = 130;
933fn default_min_annular_ring() -> i32 {
934    DEFAULT_MIN_ANNULAR_RING
935}
936fn is_default_min_annular_ring(v: &i32) -> bool {
937    *v == DEFAULT_MIN_ANNULAR_RING
938}
939/// The default minimum hole spacing, 0.25 mm: KiCad's own default, and the web
940/// board houses quote between drills for their standard process.
941pub const DEFAULT_MIN_HOLE_SPACING: i32 = 250;
942fn default_min_hole_spacing() -> i32 {
943    DEFAULT_MIN_HOLE_SPACING
944}
945fn is_default_min_hole_spacing(v: &i32) -> bool {
946    *v == DEFAULT_MIN_HOLE_SPACING
947}
948
949/// How the autorouter trades vias against track length.
950#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
951#[serde(rename_all = "snake_case")]
952pub enum ViaPolicy {
953    /// A via is an ordinary cost, taken whenever it shortens the route enough.
954    Allow,
955    /// Route as `Allow` does, then reroute every net that has vias against the
956    /// finished board, looking first for a route with none, and keep whichever
957    /// copper has fewer. Connects the same nets as `Allow`, more slowly.
958    #[default]
959    Avoid,
960    /// Never place a via. Connections that cannot be made on one layer stay unrouted.
961    Never,
962}
963impl Default for DesignRules {
964    fn default() -> Self {
965        Self {
966            track_width: 250,
967            clearance: 200,
968            via_diameter: 600,
969            via_drill: 300,
970            edge_clearance: 300,
971            routing_grid: 100,
972            net_widths: BTreeMap::new(),
973            mask_expansion: default_mask_expansion(),
974            autoroute_vias: ViaPolicy::default(),
975            net_classes: vec![],
976            net_class_of: BTreeMap::new(),
977            min_annular_ring: DEFAULT_MIN_ANNULAR_RING,
978            tent_vias: true,
979            min_hole_spacing: DEFAULT_MIN_HOLE_SPACING,
980        }
981    }
982}
983
984#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
985pub struct Board {
986    /// Closed board outline polygon.
987    pub outline: Vec<Point>,
988    /// Copper layers; layer 0 is the top (F.Cu), the last is the bottom (B.Cu).
989    pub layer_count: u8,
990    #[serde(default)]
991    pub placements: Vec<Placement>,
992    #[serde(default)]
993    pub tracks: Vec<Track>,
994    #[serde(default)]
995    pub vias: Vec<Via>,
996    #[serde(default)]
997    pub rules: DesignRules,
998    /// Copper zones, in drawing order, which is also their fill priority. Written
999    /// only when there are some, so a board with none serializes exactly as it did
1000    /// before zones existed (the host compares the block byte for byte).
1001    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1002    pub zones: Vec<Zone>,
1003    /// Lines, shapes and text drawn on the board itself, on a silkscreen or
1004    /// fabrication layer, belonging to no part: a board's name and revision, a
1005    /// connector's legend, an outline on its assembly drawing. Written only when
1006    /// there are some, as zones are.
1007    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1008    pub graphics: Vec<BoardGraphic>,
1009    /// Holes milled through the board inside its outline (KiCad's inner
1010    /// Edge.Cuts loops): closed polygons, each wholly inside the outline and
1011    /// apart from every other. Copper keeps the edge clearance from them as it
1012    /// does from the outline. Written only when there are some, as zones are.
1013    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1014    pub cutouts: Vec<BoardCutout>,
1015}
1016/// The most corners one cutout may have.
1017pub const MAX_CUTOUT_CORNERS: usize = 1000;
1018/// The most cutouts one board may have.
1019pub const MAX_CUTOUTS: usize = 1000;
1020/// A hole milled through the board: a closed polygon (its last corner joins
1021/// its first), with the identity a selection and an undo step hold it by.
1022#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1023pub struct BoardCutout {
1024    pub id: Uuid,
1025    pub points: Vec<Point>,
1026}
1027impl BoardCutout {
1028    pub fn new(points: Vec<Point>) -> Self {
1029        Self { id: Uuid::new_v4(), points }
1030    }
1031}
1032/// The edges of a closed ring, edge `i` running from corner `i` to the next.
1033fn ring_edges(ring: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
1034    let n = ring.len();
1035    (0..n).map(move |i| (ring[i], ring[(i + 1) % n]))
1036}
1037/// True when two edges of `ring` that do not share a corner touch.
1038fn ring_crosses_itself(ring: &[Point]) -> bool {
1039    let n = ring.len();
1040    (0..n).any(|i| {
1041        (i + 2..n).any(|j| {
1042            (i, j) != (0, n - 1)
1043                && segments_intersect(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n])
1044        })
1045    })
1046}
1047/// True when an edge of `a` touches an edge of `b`.
1048fn rings_touch(a: &[Point], b: &[Point]) -> bool {
1049    ring_edges(a).any(|(p, q)| ring_edges(b).any(|(r, s)| segments_intersect(p, q, r, s)))
1050}
1051/// A drawn item on the board itself: a [`LayerGraphic`] with the identity a
1052/// selection and an undo step hold it by.
1053#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1054pub struct BoardGraphic {
1055    pub id: Uuid,
1056    #[serde(flatten)]
1057    pub graphic: LayerGraphic,
1058}
1059impl BoardGraphic {
1060    pub fn new(graphic: LayerGraphic) -> Self {
1061        Self { id: Uuid::new_v4(), graphic }
1062    }
1063    /// Why this item cannot be on a board, if it cannot: what any drawn item
1064    /// is refused for ([`LayerGraphic::problem`]), and a courtyard, which is the
1065    /// room a PART needs and means nothing on the board by itself.
1066    pub fn problem(&self) -> Option<String> {
1067        if self.graphic.layer.is_courtyard() {
1068            return Some(format!(
1069                "is on {}: a courtyard belongs to a part's footprint, not to the board",
1070                self.graphic.layer.name()
1071            ));
1072        }
1073        self.graphic.problem().map(str::to_owned)
1074    }
1075}
1076impl Board {
1077    /// Every item drawn on the board ITSELF on `layer`, as (pen width, filled,
1078    /// centre lines) in board coordinates — the board-level counterpart of
1079    /// [`Placement::drawing_on`]. Back-layer text is written mirrored, so it reads
1080    /// from the board's back.
1081    pub fn drawing_on(&self, layer: GraphicLayer) -> Vec<(i32, bool, Vec<Vec<Point>>)> {
1082        self.graphics
1083            .iter()
1084            .filter(|g| g.graphic.layer == layer)
1085            .map(|g| (g.graphic.width(), g.graphic.filled, g.graphic.strokes(!layer.front())))
1086            .collect()
1087    }
1088}
1089impl Default for Board {
1090    fn default() -> Self {
1091        Self {
1092            outline: rectangle(Point::new(0, 0), Point::new(60_000, 40_000)),
1093            layer_count: 2,
1094            placements: vec![],
1095            tracks: vec![],
1096            vias: vec![],
1097            rules: DesignRules::default(),
1098            zones: vec![],
1099            graphics: vec![],
1100            cutouts: vec![],
1101        }
1102    }
1103}
1104
1105/// The substrate's thickness in board micrometres — 1.6 mm, the board every
1106/// fabricator quotes by default.
1107///
1108/// A CONSTANT rather than a [`Board`] field on purpose. A field would serialize
1109/// into the `pcb` block, and the eCAD host compares the block it holds against
1110/// the stored one byte for byte to decide whether the editor is in step — a new
1111/// always-serialized field puts every block written before it out of step (the
1112/// `Pin::unit` lesson, 2026-09-20). Until a board needs its own stack-up, one
1113/// number the app and the 3D build share is honest and costs nothing.
1114pub const SUBSTRATE_THICKNESS: i32 = 1_600;
1115
1116/// Copper foil thickness in board micrometres — 35 µm, "1 oz" copper. Also the
1117/// wall thickness of a plated via barrel.
1118pub const COPPER_THICKNESS: i32 = 35;
1119
1120/// The z of copper layer `layer`'s own plane, in board micrometres, with the
1121/// TOP copper plane at 0 and +z out of the board's top face — the frame
1122/// [`Placement`] poses are already written in.
1123///
1124/// Layer 0 (`F.Cu`) is 0 and the last (`B.Cu`) is `-SUBSTRATE_THICKNESS`; the
1125/// inner layers are spread evenly between them, so the LAYER COUNT decides the
1126/// stack exactly as it decides the names ([`layer_name`]). A one-layer board
1127/// has only layer 0, at 0.
1128pub fn layer_z(layer: u8, layer_count: u8) -> i32 {
1129    let last = layer_count.saturating_sub(1);
1130    if layer == 0 || last == 0 {
1131        return 0;
1132    }
1133    let layer = layer.min(last);
1134    -(SUBSTRATE_THICKNESS as i64 * i64::from(layer) / i64::from(last)) as i32
1135}
1136
1137/// KiCad-style copper layer name.
1138pub fn layer_name(layer: u8, layer_count: u8) -> String {
1139    if layer == 0 {
1140        "F.Cu".into()
1141    } else if layer + 1 >= layer_count {
1142        "B.Cu".into()
1143    } else {
1144        format!("In{layer}.Cu")
1145    }
1146}
1147
1148/// The box grown by `grow` on every side; a shrink stops at a 1-unit box about
1149/// the middle and never turns the box inside out. Growing by 0 is the identity.
1150fn grow_box(min: Point, max: Point, grow: i32) -> (Point, Point) {
1151    if grow >= 0 {
1152        return (
1153            Point::new(min.x - grow, min.y - grow),
1154            Point::new(max.x + grow, max.y + grow),
1155        );
1156    }
1157    let shrink = |lo: i32, hi: i32| {
1158        let (a, b) = (lo - grow, hi + grow);
1159        if a < b {
1160            (a, b)
1161        } else {
1162            let mid = (i64::from(lo) + i64::from(hi)).div_euclid(2) as i32;
1163            (mid, mid + 1)
1164        }
1165    };
1166    let (x0, x1) = shrink(min.x, max.x);
1167    let (y0, y1) = shrink(min.y, max.y);
1168    (Point::new(x0, y0), Point::new(x1, y1))
1169}
1170pub fn rectangle(min: Point, max: Point) -> Vec<Point> {
1171    vec![min, Point::new(max.x, min.y), max, Point::new(min.x, max.y)]
1172}
1173
1174/// A copper primitive for clearance and connectivity calculations.
1175#[derive(Clone, Debug, PartialEq)]
1176pub enum Shape {
1177    Rect {
1178        min: Point,
1179        max: Point,
1180    },
1181    /// A segment swept by a disc. A circle has `a == b`.
1182    Capsule {
1183        a: Point,
1184        b: Point,
1185        radius: i32,
1186    },
1187    /// A rectangle with corners rounded by `radius`: the rectangle `min..max`
1188    /// shrunk by `radius` on every side, swept by a disc of `radius`.
1189    RoundRect {
1190        min: Point,
1191        max: Point,
1192        radius: i32,
1193    },
1194    /// A simple polygon swept by a disc of `radius`: a trapezoid or custom
1195    /// pad's copper (rounded by its corner radius), and its mask opening grown
1196    /// from it. `points` run counter-clockwise in a y-up frame, as
1197    /// [`Shape::polygon`] puts them.
1198    Polygon {
1199        points: Vec<Point>,
1200        radius: i32,
1201    },
1202}
1203impl Shape {
1204    /// A polygon swept by a disc of `radius`, its corners turned to run
1205    /// counter-clockwise in a y-up frame (a positive signed area in board
1206    /// coordinates) whichever way they were given, so a mirrored part's pad
1207    /// has the same winding as any other.
1208    pub fn polygon(mut points: Vec<Point>, radius: i32) -> Self {
1209        if ring_area2(&points) < 0 {
1210            points.reverse();
1211        }
1212        Self::Polygon { points, radius: radius.max(0) }
1213    }
1214    /// A point the shape surely covers, or touches: for a containment test.
1215    fn anchor(&self) -> Point {
1216        match self {
1217            Self::Rect { min, .. } => *min,
1218            Self::RoundRect { min, max, radius } => Self::core(*min, *max, *radius).0,
1219            Self::Capsule { a, .. } => *a,
1220            Self::Polygon { points, .. } => points.first().copied().unwrap_or_default(),
1221        }
1222    }
1223    /// Whether the shape covers the whole box `min..max`.
1224    pub fn covers_box(&self, min: Point, max: Point) -> bool {
1225        let corners = rectangle(min, max);
1226        if !corners.iter().all(|c| self.depth(*c) >= 0.) {
1227            return false;
1228        }
1229        // The preset shapes are convex: covering the corners covers the box. A
1230        // polygon may turn inward between them, so none of its outline's edges
1231        // may enter the box.
1232        let Self::Polygon { .. } = self else {
1233            return true;
1234        };
1235        let ring = self.outline(8);
1236        let (lo, hi) = (Point::new(min.x + 1, min.y + 1), Point::new(max.x - 1, max.y - 1));
1237        lo.x > hi.x || lo.y > hi.y || ring_edges(&ring).all(|(p, q)| segment_rect_distance(p, q, lo, hi) > 0.)
1238    }
1239    /// A pad's copper, a rounded rectangle taken square-cornered
1240    /// ([`Shape::rounded_pad`] gives it its corners).
1241    pub fn pad(center: Point, size: Point, shape: PadShape) -> Self {
1242        Self::rounded_pad(center, size, shape, 0)
1243    }
1244    /// A pad's copper. `corner` is the corner radius of a rounded rectangle (0
1245    /// makes it an ordinary rectangle); other shapes ignore it.
1246    pub fn rounded_pad(center: Point, size: Point, shape: PadShape, corner: i32) -> Self {
1247        let half = Point::new(size.x / 2, size.y / 2);
1248        match shape {
1249            PadShape::RoundRect if corner > 0 => {
1250                let min = Point::new(center.x - half.x, center.y - half.y);
1251                Self::RoundRect {
1252                    min,
1253                    max: Point::new(min.x + size.x, min.y + size.y),
1254                    radius: corner.min(size.x.min(size.y) / 2),
1255                }
1256            }
1257            // A trapezoid or custom pad given only its size: its bounding box
1258            // ([`Pad::local_shape`] gives it its corners).
1259            PadShape::Rect | PadShape::RoundRect | PadShape::Trapezoid | PadShape::Custom => {
1260                let min = Point::new(center.x - half.x, center.y - half.y);
1261                Self::Rect {
1262                    min,
1263                    max: Point::new(min.x + size.x, min.y + size.y),
1264                }
1265            }
1266            PadShape::Circle => Self::circle(center, size.x.min(size.y) / 2),
1267            PadShape::Oval => {
1268                let radius = size.x.min(size.y) / 2;
1269                let reach = Point::new((half.x - radius).max(0), (half.y - radius).max(0));
1270                Self::Capsule {
1271                    a: Point::new(center.x - reach.x, center.y - reach.y),
1272                    b: Point::new(center.x + reach.x, center.y + reach.y),
1273                    radius,
1274                }
1275            }
1276        }
1277    }
1278    pub fn circle(center: Point, radius: i32) -> Self {
1279        Self::Capsule {
1280            a: center,
1281            b: center,
1282            radius,
1283        }
1284    }
1285    pub fn segment(a: Point, b: Point, width: i32) -> Self {
1286        Self::Capsule {
1287            a,
1288            b,
1289            radius: width / 2,
1290        }
1291    }
1292    /// The shape grown by `grow` on every side (shrunk when negative): a pad's
1293    /// solder mask opening or paste aperture. A shrink never inverts the shape.
1294    pub fn grown(&self, grow: i32) -> Self {
1295        if grow == 0 {
1296            return self.clone();
1297        }
1298        if let Self::Polygon { points, radius } = self {
1299            let radius = radius + grow;
1300            if radius >= 0 {
1301                return Self::Polygon { points: points.clone(), radius };
1302            }
1303            // Shrunk past its rounding: the polygon itself moves in.
1304            return match shrink_ring(points, -radius) {
1305                Some(points) => Self::Polygon { points, radius: 0 },
1306                None => Self::circle(polygon_inner_point(points), 1),
1307            };
1308        }
1309        match *self {
1310            Self::Rect { min, max } => {
1311                let (min, max) = grow_box(min, max, grow);
1312                Self::Rect { min, max }
1313            }
1314            Self::RoundRect { min, max, radius } => {
1315                let (min, max) = grow_box(min, max, grow);
1316                let radius = (radius + grow).clamp(0, (max.x - min.x).min(max.y - min.y) / 2);
1317                // Shrunk past its corners, it is a plain rectangle.
1318                if radius == 0 { Self::Rect { min, max } } else { Self::RoundRect { min, max, radius } }
1319            }
1320            Self::Capsule { a, b, radius } => Self::Capsule {
1321                a,
1322                b,
1323                radius: (radius + grow).max(1),
1324            },
1325            Self::Polygon { .. } => unreachable!(),
1326        }
1327    }
1328    /// A rounded polygon's outline as exact arcs and the straights between
1329    /// them, for a host that draws curves (the STEP export). `None` for any
1330    /// other shape, an unrounded polygon (its corners are its outline), or one
1331    /// whose rounding fills a notch, where only [`Shape::outline`] is exact.
1332    pub fn swept_corners(&self) -> Option<Vec<SweptCorner>> {
1333        let Self::Polygon { points, radius } = self else { return None };
1334        if *radius == 0 {
1335            return None;
1336        }
1337        let (raw, concave) = swept_outline(points, *radius, 8);
1338        if concave && ring_crosses_itself(&raw) {
1339            return None;
1340        }
1341        Some(swept_corners_of(points, *radius))
1342    }
1343    /// The shape grown by `grow`, as [`Shape::grown`], but a polygon that a
1344    /// shrink cuts in two keeps every piece (two lands joined by a thin bridge
1345    /// each keep their paste); a shrink that leaves nothing gives none.
1346    pub fn grown_parts(&self, grow: i32) -> Vec<Self> {
1347        match self {
1348            Self::Polygon { points, radius } if radius + grow < 0 => shrink_parts(points, -(radius + grow))
1349                .into_iter()
1350                .map(|points| Self::Polygon { points, radius: 0 })
1351                .collect(),
1352            _ => vec![self.grown(grow)],
1353        }
1354    }
1355    /// The rectangle a rounded rectangle's disc sweeps: `min..max` less `radius`.
1356    fn core(min: Point, max: Point, radius: i32) -> (Point, Point) {
1357        (
1358            Point::new(min.x + radius, min.y + radius),
1359            Point::new(max.x - radius, max.y - radius),
1360        )
1361    }
1362    /// The outline as a closed polygon, counter-clockwise in a y-up frame, arcs
1363    /// faceted `facets` to the quarter turn, each vertex ON the true outline.
1364    pub fn outline(&self, facets: usize) -> Vec<Point> {
1365        let arc = |out: &mut Vec<Point>, c: Point, r: i32, from: f64, steps: usize, sweep: f64| {
1366            for i in 0..=steps {
1367                let t = from + sweep * i as f64 / steps.max(1) as f64;
1368                out.push(Point::new(
1369                    c.x + (f64::from(r) * t.cos()).round() as i32,
1370                    c.y + (f64::from(r) * t.sin()).round() as i32,
1371                ));
1372            }
1373        };
1374        let quarter = std::f64::consts::FRAC_PI_2;
1375        let facets = facets.max(1);
1376        if let Self::Polygon { points, radius } = self {
1377            if *radius == 0 {
1378                return points.clone();
1379            }
1380            let (out, concave) = swept_outline(points, *radius, facets);
1381            // Where the rounding fills a notch, the swept edges of the notch
1382            // cross: the loop they make lies inside the copper and is cut out.
1383            return if concave { remove_loops(out) } else { out };
1384        }
1385        match *self {
1386            Self::Rect { min, max } => rectangle(min, max),
1387            Self::RoundRect { min, max, radius } => {
1388                let (lo, hi) = Self::core(min, max, radius);
1389                let mut out = vec![];
1390                for (k, c) in [Point::new(hi.x, lo.y), hi, Point::new(lo.x, hi.y), lo]
1391                    .into_iter()
1392                    .enumerate()
1393                {
1394                    arc(&mut out, c, radius, quarter * (k as f64 - 1.), facets, quarter);
1395                }
1396                out.dedup();
1397                if out.len() > 1 && out.first() == out.last() {
1398                    out.pop();
1399                }
1400                out
1401            }
1402            Self::Capsule { a, b, radius } => {
1403                let (dx, dy) = (f64::from(b.x - a.x), f64::from(b.y - a.y));
1404                let base = if dx == 0. && dy == 0. { 0. } else { dy.atan2(dx) } - quarter;
1405                let mut out = vec![];
1406                arc(&mut out, b, radius, base, 2 * facets, 2. * quarter);
1407                if a == b {
1408                    out.pop();
1409                    arc(&mut out, a, radius, base + 2. * quarter, 2 * facets, 2. * quarter);
1410                    out.pop();
1411                } else {
1412                    arc(&mut out, a, radius, base + 2. * quarter, 2 * facets, 2. * quarter);
1413                }
1414                out.dedup();
1415                if out.len() > 1 && out.first() == out.last() {
1416                    out.pop();
1417                }
1418                out
1419            }
1420            Self::Polygon { .. } => unreachable!(),
1421        }
1422    }
1423    pub fn bounds(&self) -> (Point, Point) {
1424        if let Self::Polygon { points, radius } = self {
1425            let (min, max) = bounds_of(points).unwrap_or_default();
1426            return (
1427                Point::new(min.x.saturating_sub(*radius), min.y.saturating_sub(*radius)),
1428                Point::new(max.x.saturating_add(*radius), max.y.saturating_add(*radius)),
1429            );
1430        }
1431        match *self {
1432            Self::Rect { min, max } | Self::RoundRect { min, max, .. } => (min, max),
1433            Self::Capsule { a, b, radius } => (
1434                Point::new(a.x.min(b.x) - radius, a.y.min(b.y) - radius),
1435                Point::new(a.x.max(b.x) + radius, a.y.max(b.y) + radius),
1436            ),
1437            Self::Polygon { .. } => unreachable!(),
1438        }
1439    }
1440    pub fn center(&self) -> Point {
1441        let (min, max) = self.bounds();
1442        Point::new(
1443            ((i64::from(min.x) + i64::from(max.x)) / 2) as i32,
1444            ((i64::from(min.y) + i64::from(max.y)) / 2) as i32,
1445        )
1446    }
1447    /// Distance from a point to the shape; zero inside.
1448    pub fn distance_to_point(&self, p: Point) -> f64 {
1449        if let Self::Polygon { points, radius } = self {
1450            return (-polygon_depth(points, p) - f64::from(*radius)).max(0.);
1451        }
1452        match *self {
1453            Self::Rect { min, max } => point_rect_distance(p, min, max),
1454            Self::RoundRect { min, max, radius } => {
1455                let (lo, hi) = Self::core(min, max, radius);
1456                (point_rect_distance(p, lo, hi) - f64::from(radius)).max(0.)
1457            }
1458            Self::Capsule { a, b, radius } => {
1459                (point_segment_distance(p, a, b) - f64::from(radius)).max(0.)
1460            }
1461            Self::Polygon { .. } => unreachable!(),
1462        }
1463    }
1464    /// How deep `p` lies inside the shape: its distance to the boundary,
1465    /// positive inside and negative outside.
1466    pub fn depth(&self, p: Point) -> f64 {
1467        let inside_box = |min: Point, max: Point| {
1468            let d = [p.x - min.x, max.x - p.x, p.y - min.y, max.y - p.y];
1469            f64::from(d.into_iter().min().unwrap_or(0))
1470        };
1471        if let Self::Polygon { points, radius } = self {
1472            return polygon_depth(points, p) + f64::from(*radius);
1473        }
1474        match *self {
1475            Self::Rect { min, max } => {
1476                let inner = inside_box(min, max);
1477                if inner >= 0. { inner } else { -point_rect_distance(p, min, max) }
1478            }
1479            Self::RoundRect { min, max, radius } => {
1480                let (lo, hi) = Self::core(min, max, radius);
1481                let inner = inside_box(lo, hi);
1482                f64::from(radius) + if inner >= 0. { inner } else { -point_rect_distance(p, lo, hi) }
1483            }
1484            Self::Capsule { a, b, radius } => f64::from(radius) - point_segment_distance(p, a, b),
1485            Self::Polygon { .. } => unreachable!(),
1486        }
1487    }
1488    pub fn contains(&self, p: Point) -> bool {
1489        self.distance_to_point(p) <= 0.
1490    }
1491    /// Gap between two shapes; zero when they touch or overlap.
1492    pub fn distance(&self, other: &Self) -> f64 {
1493        // A polygon is its edges swept by its disc, unless one shape lies
1494        // wholly inside the other.
1495        if let Self::Polygon { points, radius } = self {
1496            if points.is_empty() {
1497                return f64::INFINITY;
1498            }
1499            if polygon_contains(points, other.anchor()) || other.contains(points[0]) {
1500                return 0.;
1501            }
1502            let edges = ring_edges(points)
1503                .map(|(a, b)| Self::Capsule { a, b, radius: 0 }.distance(other))
1504                .fold(f64::INFINITY, f64::min);
1505            return (edges - f64::from(*radius)).max(0.);
1506        }
1507        if let Self::Polygon { .. } = other {
1508            return other.distance(self);
1509        }
1510        // A rounded rectangle is its core rectangle swept by a disc: measure from
1511        // the core and take the radius off.
1512        if let Self::RoundRect { min, max, radius } = *self {
1513            let (lo, hi) = Self::core(min, max, radius);
1514            return (Self::Rect { min: lo, max: hi }.distance(other) - f64::from(radius)).max(0.);
1515        }
1516        if let Self::RoundRect { .. } = *other {
1517            return other.distance(self);
1518        }
1519        match (self.clone(), other.clone()) {
1520            (Self::Rect { min: a0, max: a1 }, Self::Rect { min: b0, max: b1 }) => {
1521                let dx = (i64::from(a0.x) - i64::from(b1.x))
1522                    .max(i64::from(b0.x) - i64::from(a1.x))
1523                    .max(0) as f64;
1524                let dy = (i64::from(a0.y) - i64::from(b1.y))
1525                    .max(i64::from(b0.y) - i64::from(a1.y))
1526                    .max(0) as f64;
1527                dx.hypot(dy)
1528            }
1529            (Self::Rect { min, max }, Self::Capsule { a, b, radius })
1530            | (Self::Capsule { a, b, radius }, Self::Rect { min, max }) => {
1531                (segment_rect_distance(a, b, min, max) - f64::from(radius)).max(0.)
1532            }
1533            (
1534                Self::Capsule {
1535                    a: a0,
1536                    b: a1,
1537                    radius: ra,
1538                },
1539                Self::Capsule {
1540                    a: b0,
1541                    b: b1,
1542                    radius: rb,
1543                },
1544            ) => (segment_distance(a0, a1, b0, b1) - f64::from(ra) - f64::from(rb)).max(0.),
1545            (Self::RoundRect { .. } | Self::Polygon { .. }, _) | (_, Self::RoundRect { .. } | Self::Polygon { .. }) => {
1546                unreachable!()
1547            }
1548        }
1549    }
1550}
1551
1552fn cross(o: Point, a: Point, b: Point) -> i64 {
1553    (i64::from(a.x) - i64::from(o.x)) * (i64::from(b.y) - i64::from(o.y))
1554        - (i64::from(a.y) - i64::from(o.y)) * (i64::from(b.x) - i64::from(o.x))
1555}
1556fn within_box(a: Point, b: Point, p: Point) -> bool {
1557    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)
1558}
1559pub fn segments_intersect(a: Point, b: Point, c: Point, d: Point) -> bool {
1560    let d1 = cross(c, d, a);
1561    let d2 = cross(c, d, b);
1562    let d3 = cross(a, b, c);
1563    let d4 = cross(a, b, d);
1564    if d1.signum() * d2.signum() < 0 && d3.signum() * d4.signum() < 0 {
1565        return true;
1566    }
1567    (d1 == 0 && within_box(c, d, a))
1568        || (d2 == 0 && within_box(c, d, b))
1569        || (d3 == 0 && within_box(a, b, c))
1570        || (d4 == 0 && within_box(a, b, d))
1571}
1572pub fn point_segment_distance(p: Point, a: Point, b: Point) -> f64 {
1573    let (px, py) = (f64::from(p.x), f64::from(p.y));
1574    let (ax, ay) = (f64::from(a.x), f64::from(a.y));
1575    let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay);
1576    let len2 = dx * dx + dy * dy;
1577    let t = if len2 == 0. {
1578        0.
1579    } else {
1580        (((px - ax) * dx + (py - ay) * dy) / len2).clamp(0., 1.)
1581    };
1582    (px - ax - t * dx).hypot(py - ay - t * dy)
1583}
1584fn segment_distance(a: Point, b: Point, c: Point, d: Point) -> f64 {
1585    if segments_intersect(a, b, c, d) {
1586        return 0.;
1587    }
1588    point_segment_distance(a, c, d)
1589        .min(point_segment_distance(b, c, d))
1590        .min(point_segment_distance(c, a, b))
1591        .min(point_segment_distance(d, a, b))
1592}
1593fn point_rect_distance(p: Point, min: Point, max: Point) -> f64 {
1594    let dx = (i64::from(min.x) - i64::from(p.x))
1595        .max(i64::from(p.x) - i64::from(max.x))
1596        .max(0) as f64;
1597    let dy = (i64::from(min.y) - i64::from(p.y))
1598        .max(i64::from(p.y) - i64::from(max.y))
1599        .max(0) as f64;
1600    dx.hypot(dy)
1601}
1602fn segment_rect_distance(a: Point, b: Point, min: Point, max: Point) -> f64 {
1603    let corners = rectangle(min, max);
1604    if within_box(min, max, a)
1605        || within_box(min, max, b)
1606        || (0..4).any(|i| segments_intersect(a, b, corners[i], corners[(i + 1) % 4]))
1607    {
1608        return 0.;
1609    }
1610    corners
1611        .iter()
1612        .map(|c| point_segment_distance(*c, a, b))
1613        .fold(
1614            point_rect_distance(a, min, max).min(point_rect_distance(b, min, max)),
1615            f64::min,
1616        )
1617}
1618/// Even-odd point-in-polygon test.
1619pub fn polygon_contains(polygon: &[Point], p: Point) -> bool {
1620    let (px, py) = (f64::from(p.x), f64::from(p.y));
1621    let mut inside = false;
1622    for (i, a) in polygon.iter().enumerate() {
1623        let b = polygon[(i + 1) % polygon.len()];
1624        let (ax, ay, bx, by) = (
1625            f64::from(a.x),
1626            f64::from(a.y),
1627            f64::from(b.x),
1628            f64::from(b.y),
1629        );
1630        if (ay > py) != (by > py) && px < ax + (py - ay) * (bx - ax) / (by - ay) {
1631            inside = !inside;
1632        }
1633    }
1634    inside
1635}
1636/// One corner of a rounded polygon's outline ([`Shape::swept_corners`]): an arc
1637/// of the disc about a corner that turns outward, from angle `from` (radians,
1638/// board coordinates) through `sweep`, or the point where the two swept edges
1639/// of a corner that turns inward meet. Straight edges join consecutive corners.
1640#[derive(Clone, Copy, Debug, PartialEq)]
1641pub enum SweptCorner {
1642    Arc { centre: Point, radius: i32, from: f64, sweep: f64 },
1643    Meet(f64, f64),
1644}
1645impl SweptCorner {
1646    /// Where the corner's piece of outline starts and ends.
1647    pub fn ends(&self) -> ((f64, f64), (f64, f64)) {
1648        match *self {
1649            Self::Arc { centre, radius, from, sweep } => {
1650                let at = |t: f64| (f64::from(centre.x) + f64::from(radius) * t.cos(), f64::from(centre.y) + f64::from(radius) * t.sin());
1651                (at(from), at(from + sweep))
1652            }
1653            Self::Meet(x, y) => ((x, y), (x, y)),
1654        }
1655    }
1656}
1657/// A counter-clockwise polygon's corners swept by a disc of `radius`.
1658fn swept_corners_of(points: &[Point], radius: i32) -> Vec<SweptCorner> {
1659    let n = points.len();
1660    let r = f64::from(radius);
1661    (0..n)
1662        .map(|i| {
1663            let (prev, here, next) = (points[(i + n - 1) % n], points[i], points[(i + 1) % n]);
1664            let (d0, d1) = (unit(prev, here), unit(here, next));
1665            // Outward normal of a counter-clockwise (y-up) edge.
1666            let (n0, n1) = ((d0.1, -d0.0), (d1.1, -d1.0));
1667            if d0.0 * d1.1 - d0.1 * d1.0 > 1e-12 {
1668                let from = n0.1.atan2(n0.0);
1669                let mut sweep = n1.1.atan2(n1.0) - from;
1670                while sweep <= 0. {
1671                    sweep += 2. * std::f64::consts::PI;
1672                }
1673                SweptCorner::Arc { centre: here, radius, from, sweep }
1674            } else {
1675                let (mx, my) = miter(n0, n1);
1676                SweptCorner::Meet(f64::from(here.x) + mx * r, f64::from(here.y) + my * r)
1677            }
1678        })
1679        .collect()
1680}
1681/// A rounded polygon's outline before any loop is cut, arcs faceted `facets`
1682/// to the quarter turn, and whether the polygon turns inward anywhere.
1683fn swept_outline(points: &[Point], radius: i32, facets: usize) -> (Vec<Point>, bool) {
1684    let quarter = std::f64::consts::FRAC_PI_2;
1685    let mut out = vec![];
1686    let round = |(x, y): (f64, f64)| Point::new(x.round() as i32, y.round() as i32);
1687    for corner in swept_corners_of(points, radius) {
1688        match corner {
1689            SweptCorner::Arc { centre, radius, from, sweep } => {
1690                let steps = ((sweep / quarter) * facets.max(1) as f64).ceil().max(1.) as usize;
1691                for k in 0..=steps {
1692                    let t = from + sweep * k as f64 / steps as f64;
1693                    out.push(round((
1694                        f64::from(centre.x) + f64::from(radius) * t.cos(),
1695                        f64::from(centre.y) + f64::from(radius) * t.sin(),
1696                    )));
1697                }
1698            }
1699            SweptCorner::Meet(x, y) => out.push(round((x, y))),
1700        }
1701    }
1702    out.dedup();
1703    if out.len() > 1 && out.first() == out.last() {
1704        out.pop();
1705    }
1706    let n = points.len();
1707    let concave = (0..n).any(|i| cross(points[(i + n - 1) % n], points[i], points[(i + 1) % n]) < 0);
1708    (out, concave)
1709}
1710/// Signed distance from `p` to a closed polygon's boundary: positive inside.
1711pub(crate) fn polygon_depth(polygon: &[Point], p: Point) -> f64 {
1712    let d = ring_edges(polygon)
1713        .map(|(a, b)| point_segment_distance(p, a, b))
1714        .fold(f64::INFINITY, f64::min);
1715    if polygon_contains(polygon, p) { d } else { -d }
1716}
1717/// Twice a ring's signed area: positive when it runs counter-clockwise in a
1718/// y-up frame.
1719fn ring_area2(ring: &[Point]) -> i128 {
1720    ring_edges(ring)
1721        .map(|(a, b)| i128::from(a.x) * i128::from(b.y) - i128::from(b.x) * i128::from(a.y))
1722        .sum()
1723}
1724/// The unit direction from `a` to `b`, or zero where they coincide.
1725fn unit(a: Point, b: Point) -> (f64, f64) {
1726    let (dx, dy) = (f64::from(b.x) - f64::from(a.x), f64::from(b.y) - f64::from(a.y));
1727    let len = dx.hypot(dy);
1728    if len == 0. { (0., 0.) } else { (dx / len, dy / len) }
1729}
1730/// Where two lines offset one unit along normals `n0` and `n1` meet, from the
1731/// corner they share; the normal itself when the lines are parallel.
1732fn miter(n0: (f64, f64), n1: (f64, f64)) -> (f64, f64) {
1733    let (sx, sy) = (n0.0 + n1.0, n0.1 + n1.1);
1734    let dot = 1. + n0.0 * n1.0 + n0.1 * n1.1;
1735    if dot < 1e-9 { n1 } else { (sx / dot, sy / dot) }
1736}
1737/// A counter-clockwise ring moved `by` inward along every edge, each corner
1738/// where two moved edges meet. An edge that the move turns round (a short
1739/// chamfer, say) is dropped and its neighbours meet instead, and a loop the
1740/// move leaves where the ring turns inward is cut out; there the corner stays
1741/// sharp, a little more than an exact inset. `None` when nothing is left or the
1742/// result would leave the ring's own inset.
1743fn shrink_parts(ring: &[Point], by: i32) -> Vec<Vec<Point>> {
1744    type Line = ((f64, f64), (f64, f64));
1745    let d = f64::from(by);
1746    // Where two moved edges meet: the second's start when they are one line.
1747    let meet = |((px, py), (ux, uy)): Line, ((qx, qy), (vx, vy)): Line| -> Option<(f64, f64)> {
1748        let turn = ux * vy - uy * vx;
1749        if turn.abs() < 1e-9 {
1750            return (ux * vx + uy * vy > 0.).then_some((qx, qy));
1751        }
1752        let t = ((qx - px) * vy - (qy - py) * vx) / turn;
1753        Some((px + t * ux, py + t * uy))
1754    };
1755    // Each edge as a line moved inward: a point on it and its direction.
1756    let mut lines: Vec<Line> = ring_edges(ring)
1757        .filter(|(a, b)| a != b)
1758        .map(|(a, b)| {
1759            let u = unit(a, b);
1760            ((f64::from(a.x) - u.1 * d, f64::from(a.y) + u.0 * d), u)
1761        })
1762        .collect();
1763    for _ in 0..=ring.len() {
1764        let n = lines.len();
1765        if n < 3 {
1766            return vec![];
1767        }
1768        let Some(corners) = (0..n).map(|i| meet(lines[(i + n - 1) % n], lines[i])).collect::<Option<Vec<(f64, f64)>>>() else {
1769            return vec![];
1770        };
1771        // How far each moved edge still runs along its own direction.
1772        let run = |i: usize| {
1773            let (s, e) = (corners[i], corners[(i + 1) % n]);
1774            (e.0 - s.0) * lines[i].1.0 + (e.1 - s.1) * lines[i].1.1
1775        };
1776        match (0..n).filter(|&i| run(i) <= 0.5).min_by(|&i, &j| run(i).total_cmp(&run(j))) {
1777            Some(worst) => {
1778                lines.remove(worst);
1779            }
1780            None => {
1781                let out: Vec<Point> = corners.iter().map(|c| Point::new(c.0.round() as i32, c.1.round() as i32)).collect();
1782                let mut parts = vec![];
1783                split_loops(out, &mut parts, &mut ring.len().max(8));
1784                parts.retain(|part| {
1785                    part.iter().all(|p| polygon_depth(ring, *p) >= d - 2.) && !ring_crosses_itself(part)
1786                });
1787                return parts;
1788            }
1789        }
1790    }
1791    vec![]
1792}
1793/// The largest piece [`shrink_parts`] leaves.
1794fn shrink_ring(ring: &[Point], by: i32) -> Option<Vec<Point>> {
1795    shrink_parts(ring, by).into_iter().max_by_key(|part| ring_area2(part))
1796}
1797/// A ring cut at each place it crosses itself into the loops it makes,
1798/// keeping each loop that runs counter-clockwise (a reversed loop is where an
1799/// inset overran itself and holds nothing); at most `budget` cuts.
1800fn split_loops(ring: Vec<Point>, out: &mut Vec<Vec<Point>>, budget: &mut usize) {
1801    let n = ring.len();
1802    let crossing = (0..n).find_map(|i| {
1803        let (a, b) = (ring[i], ring[(i + 1) % n]);
1804        (i + 2..n).find_map(|j| {
1805            let (c, d) = (ring[j], ring[(j + 1) % n]);
1806            ((i, j) != (0, n - 1) && segments_intersect(a, b, c, d)).then_some((i, j))
1807        })
1808    });
1809    match crossing {
1810        Some((i, j)) if *budget > 0 && n >= 4 => {
1811            *budget -= 1;
1812            let x = crossing_point(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n]);
1813            let mut outer: Vec<Point> = ring[..=i].to_vec();
1814            outer.push(x);
1815            outer.extend_from_slice(&ring[j + 1..]);
1816            let mut inner = vec![x];
1817            inner.extend_from_slice(&ring[i + 1..=j]);
1818            for mut part in [outer, inner] {
1819                part.dedup();
1820                if part.len() > 1 && part.first() == part.last() {
1821                    part.pop();
1822                }
1823                if part.len() >= 3 {
1824                    split_loops(part, out, budget);
1825                }
1826            }
1827        }
1828        _ => {
1829            if n >= 3 && ring_area2(&ring) > 0 {
1830                out.push(ring);
1831            }
1832        }
1833    }
1834}
1835/// Where segments `a..b` and `c..d`, known to touch, meet.
1836fn crossing_point(a: Point, b: Point, c: Point, d: Point) -> Point {
1837    let (u, v) = ((f64::from(b.x - a.x), f64::from(b.y - a.y)), (f64::from(d.x - c.x), f64::from(d.y - c.y)));
1838    let turn = u.0 * v.1 - u.1 * v.0;
1839    if turn.abs() < 1e-9 {
1840        return if within_box(a, b, c) { c } else { a };
1841    }
1842    let t = (f64::from(c.x - a.x) * v.1 - f64::from(c.y - a.y) * v.0) / turn;
1843    Point::new((f64::from(a.x) + t * u.0).round() as i32, (f64::from(a.y) + t * u.1).round() as i32)
1844}
1845/// A ring with the loops it makes where it crosses itself cut out, keeping at
1846/// each crossing the side of larger counter-clockwise area: the outline of an
1847/// offset whose edges overran one another.
1848fn remove_loops(mut ring: Vec<Point>) -> Vec<Point> {
1849    'cut: for _ in 0..ring.len() {
1850        let n = ring.len();
1851        if n < 4 {
1852            break;
1853        }
1854        for i in 0..n {
1855            let (a, b) = (ring[i], ring[(i + 1) % n]);
1856            for j in i + 2..n {
1857                if (i, j) == (0, n - 1) {
1858                    continue;
1859                }
1860                let (c, d) = (ring[j], ring[(j + 1) % n]);
1861                if a.x.max(b.x) < c.x.min(d.x)
1862                    || c.x.max(d.x) < a.x.min(b.x)
1863                    || a.y.max(b.y) < c.y.min(d.y)
1864                    || c.y.max(d.y) < a.y.min(b.y)
1865                    || !segments_intersect(a, b, c, d)
1866                {
1867                    continue;
1868                }
1869                let x = crossing_point(a, b, c, d);
1870                let mut outer: Vec<Point> = ring[..=i].to_vec();
1871                outer.push(x);
1872                outer.extend_from_slice(&ring[j + 1..]);
1873                let mut inner = vec![x];
1874                inner.extend_from_slice(&ring[i + 1..=j]);
1875                outer.dedup();
1876                inner.dedup();
1877                ring = if ring_area2(&inner) > ring_area2(&outer) { inner } else { outer };
1878                continue 'cut;
1879            }
1880        }
1881        break;
1882    }
1883    ring
1884}
1885/// A point inside a simple polygon: the middle of its widest span across the
1886/// middle of its height.
1887pub fn polygon_inner_point(ring: &[Point]) -> Point {
1888    let Some((min, max)) = bounds_of(ring) else {
1889        return Point::default();
1890    };
1891    let y = (i64::from(min.y) + i64::from(max.y)) / 2;
1892    let mut xs: Vec<f64> = ring_edges(ring)
1893        .filter(|(a, b)| (i64::from(a.y) > y) != (i64::from(b.y) > y))
1894        .map(|(a, b)| {
1895            let t = (y as f64 - f64::from(a.y)) / (f64::from(b.y) - f64::from(a.y));
1896            f64::from(a.x) + t * (f64::from(b.x) - f64::from(a.x))
1897        })
1898        .collect();
1899    xs.sort_by(f64::total_cmp);
1900    let widest = xs.chunks(2).filter(|c| c.len() == 2).max_by(|a, b| (a[1] - a[0]).total_cmp(&(b[1] - b[0])));
1901    match widest {
1902        Some(c) => Point::new(((c[0] + c[1]) / 2.).round() as i32, y as i32),
1903        None => ring[0],
1904    }
1905}
1906fn bounds_of(points: &[Point]) -> Option<(Point, Point)> {
1907    let first = *points.first()?;
1908    Some(points.iter().fold((first, first), |(min, max), p| {
1909        (
1910            Point::new(min.x.min(p.x), min.y.min(p.y)),
1911            Point::new(max.x.max(p.x), max.y.max(p.y)),
1912        )
1913    }))
1914}
1915/// Remove repeated points and interior points that continue in the same direction.
1916pub fn simplify_path(points: Vec<Point>) -> Vec<Point> {
1917    let mut clean: Vec<Point> = vec![];
1918    for p in points {
1919        if clean.last() == Some(&p) {
1920            continue;
1921        }
1922        if clean.len() >= 2 {
1923            let a = clean[clean.len() - 2];
1924            let b = clean[clean.len() - 1];
1925            let forward = (i64::from(b.x) - i64::from(a.x)) * (i64::from(p.x) - i64::from(b.x))
1926                + (i64::from(b.y) - i64::from(a.y)) * (i64::from(p.y) - i64::from(b.y));
1927            if cross(a, b, p) == 0 && forward > 0 {
1928                clean.pop();
1929            }
1930        }
1931        clean.push(p);
1932    }
1933    clean
1934}
1935
1936/// What a copper primitive belongs to.
1937#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1938pub enum CopperRef {
1939    Pad { placement: usize, pad: usize },
1940    Track { track: usize, segment: usize },
1941    Via(usize),
1942}
1943#[derive(Clone, Debug)]
1944pub struct CopperItem {
1945    pub owner: CopperRef,
1946    pub shape: Shape,
1947    /// Inclusive layer range.
1948    pub layers: (u8, u8),
1949}
1950impl CopperItem {
1951    fn shares_layer(&self, other: &Self) -> bool {
1952        self.layers.0 <= other.layers.1 && other.layers.0 <= self.layers.1
1953    }
1954}
1955
1956/// Copper islands and the schematic nets each island carries.
1957#[derive(Clone, Debug, Default)]
1958pub struct Connectivity {
1959    pub items: Vec<CopperItem>,
1960    /// Island index for each item.
1961    pub islands: Vec<usize>,
1962    pub island_count: usize,
1963    /// Schematic net of each pad item.
1964    pub item_nets: Vec<Option<String>>,
1965    pub island_nets: Vec<BTreeSet<String>>,
1966    /// Island index of each piece of each zone's fill, by zone then piece: a fill
1967    /// is copper, and joins every item it touches.
1968    pub zone_islands: Vec<Vec<usize>>,
1969}
1970impl Connectivity {
1971    /// The single net carried by an island, if it carries exactly one.
1972    pub fn island_net(&self, island: usize) -> Option<&str> {
1973        let nets = &self.island_nets[island];
1974        (nets.len() == 1).then(|| nets.iter().next().unwrap().as_str())
1975    }
1976}
1977
1978/// An unrouted connection between two copper islands of one net.
1979#[derive(Clone, Debug, PartialEq)]
1980pub struct Airwire {
1981    pub net: String,
1982    pub a: Point,
1983    pub b: Point,
1984}
1985
1986#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1987pub enum ViolationKind {
1988    Short,
1989    Clearance,
1990    /// A track narrower than its net's width: its own width rule, else its class's.
1991    TrackWidth,
1992    BoardEdge,
1993    MissingPad,
1994    Courtyard,
1995    /// A plated hole whose copper ring is narrower than
1996    /// [`DesignRules::min_annular_ring`].
1997    AnnularRing,
1998    /// Two drilled holes nearer than [`DesignRules::min_hole_spacing`], or an
1999    /// unplated hole cutting copper of its own net.
2000    Hole,
2001    /// A via with no net that zones of two nets claim, and which is stitched to
2002    /// neither ([`Board::contested_vias`]).
2003    Stitching,
2004    Unrouted,
2005    /// A placed part's pin whose 3D seat misses the pad of its number
2006    /// ([`crate::seat_check`]). The host measures it from the part's solids and
2007    /// adds it to the check's findings; [`Board::drc`] never reports it, so the
2008    /// board's own check and fabrication do not depend on 3D models.
2009    PinSeat,
2010}
2011#[derive(Clone, Debug, PartialEq)]
2012pub struct Violation {
2013    pub kind: ViolationKind,
2014    pub message: String,
2015    pub at: Point,
2016}
2017
2018struct Dsu(Vec<usize>);
2019impl Dsu {
2020    fn new(n: usize) -> Self {
2021        Self((0..n).collect())
2022    }
2023    fn root(&mut self, mut i: usize) -> usize {
2024        while self.0[i] != i {
2025            self.0[i] = self.0[self.0[i]];
2026            i = self.0[i];
2027        }
2028        i
2029    }
2030    fn join(&mut self, a: usize, b: usize) -> bool {
2031        let (a, b) = (self.root(a), self.root(b));
2032        if a != b {
2033            self.0[a.max(b)] = a.min(b);
2034        }
2035        a != b
2036    }
2037}
2038
2039/// Visit item pairs whose bounds, expanded by `slack`, overlap on a shared layer.
2040/// One key per object a finding names: a pad, a whole track (whichever of its
2041/// segments), a via.
2042fn object_key(owner: CopperRef) -> (u8, usize, usize) {
2043    match owner {
2044        CopperRef::Pad { placement, pad } => (0, placement, pad),
2045        CopperRef::Track { track, .. } => (1, track, 0),
2046        CopperRef::Via(v) => (2, v, 0),
2047    }
2048}
2049fn near_pairs(items: &[CopperItem], slack: i32, mut visit: impl FnMut(usize, usize)) {
2050    let bounds: Vec<_> = items.iter().map(|i| i.shape.bounds()).collect();
2051    let mut order: Vec<usize> = (0..items.len()).collect();
2052    order.sort_by_key(|&i| (bounds[i].0.x, i));
2053    for (k, &i) in order.iter().enumerate() {
2054        let (min, max) = bounds[i];
2055        for &j in &order[k + 1..] {
2056            let (other_min, other_max) = bounds[j];
2057            if other_min.x > max.x.saturating_add(slack) {
2058                break;
2059            }
2060            if other_min.y > max.y.saturating_add(slack)
2061                || min.y > other_max.y.saturating_add(slack)
2062                || !items[i].shares_layer(&items[j])
2063            {
2064                continue;
2065            }
2066            visit(i.min(j), i.max(j));
2067        }
2068    }
2069}
2070
2071/// Schematic net name for each (component, pin number).
2072pub fn pin_nets(netlist: &Netlist) -> BTreeMap<(Uuid, String), String> {
2073    netlist
2074        .nets
2075        .iter()
2076        .flat_map(|n| {
2077            n.pins
2078                .iter()
2079                .map(|p| ((p.component_id, p.number.clone()), n.name.clone()))
2080        })
2081        .collect()
2082}
2083
2084impl Board {
2085    pub fn outline_bounds(&self) -> (Point, Point) {
2086        bounds_of(&self.outline).unwrap_or_default()
2087    }
2088    /// True when the outline is an axis-aligned rectangle.
2089    pub fn outline_is_rectangle(&self) -> bool {
2090        let (min, max) = self.outline_bounds();
2091        self.outline.len() == 4
2092            && self
2093                .outline
2094                .iter()
2095                .all(|p| (p.x == min.x || p.x == max.x) && (p.y == min.y || p.y == max.y))
2096            && min.x < max.x
2097            && min.y < max.y
2098    }
2099    /// True when `p` is on the board: inside the outline (even-odd) and in no
2100    /// cutout.
2101    pub fn outline_contains(&self, p: Point) -> bool {
2102        polygon_contains(&self.outline, p) && !self.cutouts.iter().any(|c| polygon_contains(&c.points, p))
2103    }
2104    /// Every edge of the board: the outline's, then each cutout's. Copper keeps
2105    /// the edge clearance from all of them.
2106    pub fn outline_edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
2107        std::iter::once(self.outline.as_slice())
2108            .chain(self.cutouts.iter().map(|c| c.points.as_slice()))
2109            .flat_map(ring_edges)
2110    }
2111    /// Why `points` cannot be a cutout of this board, if it cannot: fewer than
2112    /// three corners, no area, edges that cross, a corner off the board or on
2113    /// its outline, or touching another cutout. `except` is the index of the
2114    /// cutout being replaced, which is not checked against itself.
2115    pub fn cutout_problem(&self, points: &[Point], except: Option<usize>) -> Option<String> {
2116        self.cutout_problem_among(points, &self.cutouts, except)
2117    }
2118    /// [`Board::cutout_problem`] against `others` only.
2119    fn cutout_problem_among(&self, points: &[Point], others: &[BoardCutout], except: Option<usize>) -> Option<String> {
2120        if points.len() < 3 {
2121            return Some("needs at least three corners".into());
2122        }
2123        // The checks below compare every edge with every other: a cutout is a
2124        // milled shape, and a thousand corners is far more than one needs.
2125        if points.len() > MAX_CUTOUT_CORNERS {
2126            return Some(format!("has more than {MAX_CUTOUT_CORNERS} corners"));
2127        }
2128        if zones::ring_area(points) == 0. {
2129            return Some("encloses no area".into());
2130        }
2131        if ring_crosses_itself(points) {
2132            return Some("crosses itself".into());
2133        }
2134        if points.iter().any(|&p| !polygon_contains(&self.outline, p)) || rings_touch(points, &self.outline) {
2135            return Some("is not wholly inside the board outline".into());
2136        }
2137        let bounds = bounds_of(points);
2138        for (k, other) in others.iter().enumerate() {
2139            // Two cutouts whose boxes are apart can neither touch nor hold one
2140            // another: the edge-by-edge checks are only for the near ones.
2141            let apart = match (bounds, bounds_of(&other.points)) {
2142                (Some((a0, a1)), Some((b0, b1))) => a1.x < b0.x || b1.x < a0.x || a1.y < b0.y || b1.y < a0.y,
2143                _ => true,
2144            };
2145            if Some(k) == except || apart {
2146                continue;
2147            }
2148            if rings_touch(points, &other.points)
2149                || polygon_contains(&other.points, points[0])
2150                || polygon_contains(points, other.points[0])
2151            {
2152                return Some(format!("overlaps cutout {}", k + 1));
2153            }
2154        }
2155        None
2156    }
2157    /// Change the number of copper layers. Bottom-layer copper stays on the bottom;
2158    /// changes that would strand inner-layer tracks, or leave a single-layer board
2159    /// with vias or bottom-side copper, are refused.
2160    pub fn set_layer_count(&mut self, count: u8) -> Result<(), String> {
2161        if !(1..=32).contains(&count) {
2162            return Err("Boards need between 1 and 32 copper layers".into());
2163        }
2164        let old_last = self.layer_count.saturating_sub(1);
2165        let new_last = count - 1;
2166        if self
2167            .tracks
2168            .iter()
2169            .any(|t| t.layer != 0 && t.layer != old_last && t.layer >= new_last)
2170        {
2171            return Err("Move or delete the tracks on removed inner layers first".into());
2172        }
2173        if self
2174            .zones
2175            .iter()
2176            .any(|z| z.layer != 0 && z.layer != old_last && z.layer >= new_last)
2177        {
2178            return Err("Move or delete the zones on removed inner layers first".into());
2179        }
2180        if count == 1 && self.zones.iter().any(|z| z.layer != 0) {
2181            return Err("A single-layer board cannot keep bottom zones".into());
2182        }
2183        if count == 1
2184            && (!self.vias.is_empty()
2185                || !self.pad_vias().is_empty()
2186                || self.placements.iter().any(|p| p.bottom || p.has_back_copper_pad())
2187                || self.tracks.iter().any(|t| t.layer != 0))
2188        {
2189            return Err(
2190                "A single-layer board cannot keep vias (a pad's own included), bottom tracks, bottom-side parts, or back-side pads".into(),
2191            );
2192        }
2193        // A via's span keeps its ends: an end on the bottom stays on the bottom,
2194        // an end on a removed inner layer refuses the change.
2195        let remap = |layer: u8| -> Option<u8> {
2196            if layer == 0 {
2197                Some(0)
2198            } else if layer == old_last {
2199                Some(new_last)
2200            } else if layer < new_last {
2201                Some(layer)
2202            } else {
2203                None
2204            }
2205        };
2206        let mut spans = vec![];
2207        for via in &self.vias {
2208            spans.push(match via.span {
2209                None => None,
2210                Some((from, to)) => match (remap(from), remap(to)) {
2211                    (Some(from), Some(to)) if from < to => Some((from, to)),
2212                    _ => return Err("Move or delete the blind and buried vias on removed inner layers first".into()),
2213                },
2214            });
2215        }
2216        // Both ends kept means it still stops short of one outer layer (or both):
2217        // a blind or buried via stays one.
2218        for (via, span) in self.vias.iter_mut().zip(spans) {
2219            via.span = span;
2220        }
2221        for track in &mut self.tracks {
2222            if track.layer == old_last && old_last != 0 {
2223                track.layer = new_last;
2224            }
2225        }
2226        for zone in &mut self.zones {
2227            if zone.layer == old_last && old_last != 0 {
2228                zone.layer = new_last;
2229            }
2230        }
2231        self.layer_count = count;
2232        Ok(())
2233    }
2234    pub fn placement(&self, component: Uuid) -> Option<&Placement> {
2235        self.placements.iter().find(|p| p.component == component)
2236    }
2237    /// Every copper primitive on the board.
2238    /// Every via its parts' pads carry ([`Pad::vias`]), with whether each is
2239    /// tented on the side away from its pad, and that side (true: the board's
2240    /// bottom).
2241    pub fn pad_vias(&self) -> Vec<(Via, bool, bool)> {
2242        let mut out = vec![];
2243        for placement in &self.placements {
2244            for (index, pad) in placement.footprint.pads.iter().enumerate() {
2245                let Some(grid) = pad.vias else { continue };
2246                let (layer, _) = placement.pad_layers(pad, self.layer_count);
2247                let far_is_bottom = layer == 0;
2248                out.extend(placement.pad_vias(index).into_iter().map(|via| (via, grid.tented, far_is_bottom)));
2249            }
2250        }
2251        out
2252    }
2253    /// The board's own vias, then every via its pads carry: what the copper,
2254    /// the checks, the drill file and the 3D board see. An index below
2255    /// `vias.len()` is the board's own via of that index.
2256    pub fn all_vias(&self) -> Vec<Via> {
2257        let mut out = self.vias.clone();
2258        out.extend(self.pad_vias().into_iter().map(|(via, _, _)| via));
2259        out
2260    }
2261    pub fn copper(&self) -> Vec<CopperItem> {
2262        let mut items = vec![];
2263        for (pi, placement) in self.placements.iter().enumerate() {
2264            for (pad_index, pad) in placement.footprint.pads.iter().enumerate() {
2265                items.push(CopperItem {
2266                    owner: CopperRef::Pad {
2267                        placement: pi,
2268                        pad: pad_index,
2269                    },
2270                    shape: placement.pad_shape(pad),
2271                    layers: placement.pad_layers(pad, self.layer_count),
2272                });
2273            }
2274        }
2275        for (ti, track) in self.tracks.iter().enumerate() {
2276            for (segment, shape) in track.segments().enumerate() {
2277                items.push(CopperItem {
2278                    owner: CopperRef::Track { track: ti, segment },
2279                    shape,
2280                    layers: (track.layer, track.layer),
2281                });
2282            }
2283        }
2284        for (vi, via) in self.all_vias().iter().enumerate() {
2285            items.push(CopperItem {
2286                owner: CopperRef::Via(vi),
2287                shape: Shape::circle(via.at, via.diameter / 2),
2288                layers: via.layers(self.layer_count),
2289            });
2290        }
2291        items
2292    }
2293    /// Copper islands and their nets, a zone's fill joining whatever it touches.
2294    pub fn connectivity(&self, netlist: &Netlist) -> Connectivity {
2295        self.connectivity_of(netlist, true)
2296    }
2297    /// [`Self::connectivity`], with or without the zones' fills: a fill is made
2298    /// against the copper WITHOUT any fill, so a stale one never decides the net
2299    /// of a track.
2300    pub fn connectivity_of(&self, netlist: &Netlist, with_zones: bool) -> Connectivity {
2301        let items = self.copper();
2302        let pins = pin_nets(netlist);
2303        let pieces: Vec<(usize, &FillPiece)> = if with_zones {
2304            self.zones
2305                .iter()
2306                .enumerate()
2307                .flat_map(|(z, zone)| zone.fill.iter().map(move |p| (z, p)))
2308                .collect()
2309        } else {
2310            vec![]
2311        };
2312        let mut dsu = Dsu::new(items.len() + pieces.len());
2313        near_pairs(&items, 0, |i, j| {
2314            if items[i].shape.distance(&items[j].shape) <= 0.5 {
2315                dsu.join(i, j);
2316            }
2317        });
2318        for (k, (z, piece)) in pieces.iter().enumerate() {
2319            let layer = self.zones[*z].layer;
2320            let (min, max) = piece.bounds();
2321            for (i, item) in items.iter().enumerate() {
2322                let (lo, hi) = item.shape.bounds();
2323                if item.layers.0 <= layer
2324                    && layer <= item.layers.1
2325                    && lo.x <= max.x
2326                    && hi.x >= min.x
2327                    && lo.y <= max.y
2328                    && hi.y >= min.y
2329                    && piece.touches(&item.shape)
2330                {
2331                    dsu.join(i, items.len() + k);
2332                }
2333            }
2334        }
2335        let mut numbering = BTreeMap::new();
2336        let mut all: Vec<usize> = (0..items.len() + pieces.len())
2337            .map(|i| {
2338                let next = numbering.len();
2339                *numbering.entry(dsu.root(i)).or_insert(next)
2340            })
2341            .collect();
2342        let piece_islands = all.split_off(items.len());
2343        let islands = all;
2344        let mut zone_islands: Vec<Vec<usize>> = if with_zones {
2345            self.zones.iter().map(|z| Vec::with_capacity(z.fill.len())).collect()
2346        } else {
2347            vec![]
2348        };
2349        for ((z, _), island) in pieces.iter().zip(piece_islands) {
2350            zone_islands[*z].push(island);
2351        }
2352        let item_nets: Vec<Option<String>> = items
2353            .iter()
2354            .map(|item| match item.owner {
2355                CopperRef::Pad { placement, pad } => {
2356                    let placement = &self.placements[placement];
2357                    let number = &placement.footprint.pads[pad].number;
2358                    pins.get(&(placement.component, number.clone())).cloned()
2359                }
2360                _ => None,
2361            })
2362            .collect();
2363        let mut island_nets = vec![BTreeSet::new(); numbering.len()];
2364        for (island, net) in islands.iter().zip(&item_nets) {
2365            if let Some(net) = net {
2366                island_nets[*island].insert(net.clone());
2367            }
2368        }
2369        Connectivity {
2370            island_count: numbering.len(),
2371            items,
2372            islands,
2373            item_nets,
2374            island_nets,
2375            zone_islands,
2376        }
2377    }
2378    /// Minimum spanning connections between the unjoined copper islands of each net.
2379    pub fn ratsnest(&self, conn: &Connectivity) -> Vec<Airwire> {
2380        let mut net_pads: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
2381        for (i, net) in conn.item_nets.iter().enumerate() {
2382            if let Some(net) = net {
2383                net_pads.entry(net).or_default().push(i);
2384            }
2385        }
2386        let mut island_anchors: BTreeMap<usize, Vec<Point>> = BTreeMap::new();
2387        for (i, item) in conn.items.iter().enumerate() {
2388            let anchors = island_anchors.entry(conn.islands[i]).or_default();
2389            match item.owner {
2390                CopperRef::Track { .. } => {
2391                    if let Shape::Capsule { a, b, .. } = item.shape {
2392                        anchors.extend([a, b]);
2393                    }
2394                }
2395                CopperRef::Via(_) => anchors.push(item.shape.center()),
2396                CopperRef::Pad { .. } => {}
2397            }
2398        }
2399        let mut airwires = vec![];
2400        for (net, pads) in net_pads {
2401            let islands: BTreeSet<usize> = pads.iter().map(|&i| conn.islands[i]).collect();
2402            if islands.len() < 2 {
2403                continue;
2404            }
2405            let mut anchors: Vec<(usize, Point)> = pads
2406                .iter()
2407                .map(|&i| (conn.islands[i], conn.items[i].shape.center()))
2408                .collect();
2409            let extra: Vec<(usize, Point)> = islands
2410                .iter()
2411                .flat_map(|&island| {
2412                    island_anchors
2413                        .get(&island)
2414                        .into_iter()
2415                        .flatten()
2416                        .map(move |p| (island, *p))
2417                })
2418                .collect();
2419            if anchors.len() + extra.len() <= 400 {
2420                anchors.extend(extra);
2421            }
2422            anchors.sort();
2423            anchors.dedup();
2424            let mut pairs = vec![];
2425            for i in 0..anchors.len() {
2426                for j in i + 1..anchors.len() {
2427                    if anchors[i].0 != anchors[j].0 {
2428                        let dx = i64::from(anchors[i].1.x) - i64::from(anchors[j].1.x);
2429                        let dy = i64::from(anchors[i].1.y) - i64::from(anchors[j].1.y);
2430                        pairs.push((dx * dx + dy * dy, i, j));
2431                    }
2432                }
2433            }
2434            pairs.sort_unstable();
2435            let index: BTreeMap<usize, usize> =
2436                islands.iter().enumerate().map(|(i, &s)| (s, i)).collect();
2437            let mut dsu = Dsu::new(islands.len());
2438            let mut joined = 1;
2439            for (_, i, j) in pairs {
2440                if dsu.join(index[&anchors[i].0], index[&anchors[j].0]) {
2441                    airwires.push(Airwire {
2442                        net: net.to_owned(),
2443                        a: anchors[i].1,
2444                        b: anchors[j].1,
2445                    });
2446                    joined += 1;
2447                    if joined == islands.len() {
2448                        break;
2449                    }
2450                }
2451            }
2452        }
2453        airwires
2454    }
2455    fn describe(&self, owner: CopperRef, references: &BTreeMap<Uuid, String>) -> String {
2456        match owner {
2457            CopperRef::Pad { placement, pad } => {
2458                let placement = &self.placements[placement];
2459                format!(
2460                    "{} pad {}",
2461                    references
2462                        .get(&placement.component)
2463                        .map_or("?", String::as_str),
2464                    placement.footprint.pads[pad].number
2465                )
2466            }
2467            CopperRef::Track { track, .. } => format!(
2468                "track on {}",
2469                layer_name(self.tracks[track].layer, self.layer_count)
2470            ),
2471            CopperRef::Via(_) => "via".into(),
2472        }
2473    }
2474    /// [`Self::describe`] with the nets the copper carries: "track on F.Cu (SIG)".
2475    fn describe_on(&self, owner: CopperRef, nets: &BTreeSet<String>, references: &BTreeMap<Uuid, String>) -> String {
2476        let what = self.describe(owner, references);
2477        if nets.is_empty() {
2478            what
2479        } else {
2480            format!("{what} ({})", nets.iter().cloned().collect::<Vec<_>>().join(", "))
2481        }
2482    }
2483    /// Every drilled hole on the board, as a [`CopperItem`] whose shape is the
2484    /// hole and whose layers are the DIELECTRIC gaps the drill passes through
2485    /// (gap `k` lies between copper layers `k` and `k + 1`), so a blind via from
2486    /// layer 0 to 1 and a buried one from 1 to 2 share no drilling. Pad holes
2487    /// first, then [`Board::all_vias`] in its order, with whether each is plated.
2488    fn drilled_holes(&self) -> Vec<(CopperItem, bool)> {
2489        let gaps = |(from, to): (u8, u8)| (from, to.saturating_sub(1).max(from));
2490        let mut holes = vec![];
2491        for (pi, placement) in self.placements.iter().enumerate() {
2492            for (pad_index, pad) in placement.footprint.pads.iter().enumerate() {
2493                let Some(shape) = placement.pad_hole(pad) else { continue };
2494                let item = CopperItem {
2495                    owner: CopperRef::Pad { placement: pi, pad: pad_index },
2496                    shape,
2497                    layers: gaps(placement.pad_layers(pad, self.layer_count)),
2498                };
2499                holes.push((item, pad.plated));
2500            }
2501        }
2502        for (vi, via) in self.all_vias().iter().enumerate() {
2503            let item = CopperItem {
2504                owner: CopperRef::Via(vi),
2505                shape: Shape::circle(via.at, via.drill / 2),
2506                layers: gaps(via.layers(self.layer_count)),
2507            };
2508            holes.push((item, true));
2509        }
2510        holes
2511    }
2512    /// The drilling checks: two holes whose drilling meets nearer than
2513    /// [`DesignRules::min_hole_spacing`] edge to edge, or touching whatever the
2514    /// rule, and an UNPLATED hole that copper comes within the clearance of, or
2515    /// touches whatever the clearance, a zone's fill included. Copper the copper
2516    /// check already reports against the unplated pad's own copper is left to
2517    /// that finding; a hole larger than its pad is measured itself, and held to
2518    /// the edge clearance from the outline and the cutouts as its pad is. The vias of
2519    /// one pad's grid too close together are one finding for the pad.
2520    fn hole_findings(&self, conn: &Connectivity, references: &BTreeMap<Uuid, String>) -> Vec<Violation> {
2521        let holes = self.drilled_holes();
2522        let own_vias = self.vias.len();
2523        // The pad each of a pad's grid vias belongs to, by its index in all_vias.
2524        let grid_owner: Vec<CopperRef> = self
2525            .placements
2526            .iter()
2527            .enumerate()
2528            .flat_map(|(pi, placement)| {
2529                (0..placement.footprint.pads.len()).flat_map(move |pad_index| {
2530                    let count = placement.pad_vias(pad_index).len();
2531                    std::iter::repeat_n(CopperRef::Pad { placement: pi, pad: pad_index }, count)
2532                })
2533            })
2534            .collect();
2535        let pad_of_via = |owner: CopperRef| match owner {
2536            CopperRef::Via(v) if v >= own_vias => grid_owner.get(v - own_vias).copied(),
2537            _ => None,
2538        };
2539        let label = |owner: CopperRef| match (owner, pad_of_via(owner)) {
2540            (_, Some(pad)) => format!("a via in {}", self.describe(pad, references)),
2541            (CopperRef::Via(_), None) => "via".to_owned(),
2542            (owner, None) => format!("{} hole", self.describe(owner, references)),
2543        };
2544        let spacing = f64::from(self.rules.min_hole_spacing);
2545        let mm = |v: f64| v / 1000.;
2546        let mut violations = vec![];
2547        let items: Vec<CopperItem> = holes.iter().map(|(item, _)| item.clone()).collect();
2548        let mut grids_reported = BTreeSet::new();
2549        near_pairs(&items, self.rules.min_hole_spacing.max(1), |i, j| {
2550            let (a, b) = (&items[i], &items[j]);
2551            let gap = a.shape.distance(&b.shape);
2552            if !(gap + 0.5 < spacing || gap == 0.) {
2553                return;
2554            }
2555            let (ca, cb) = (a.shape.center(), b.shape.center());
2556            let at = Point::new(
2557                ((i64::from(ca.x) + i64::from(cb.x)) / 2) as i32,
2558                ((i64::from(ca.y) + i64::from(cb.y)) / 2) as i32,
2559            );
2560            let message = match (pad_of_via(a.owner), pad_of_via(b.owner)) {
2561                (Some(pa), Some(pb)) if pa == pb => {
2562                    if !grids_reported.insert(pa) {
2563                        return;
2564                    }
2565                    format!(
2566                        "{}'s vias: {:.3} mm between holes, minimum hole spacing {:.3} mm",
2567                        self.describe(pa, references),
2568                        mm(gap),
2569                        mm(spacing)
2570                    )
2571                }
2572                _ => format!(
2573                    "{} to {}: {:.3} mm between holes, minimum hole spacing {:.3} mm",
2574                    label(a.owner),
2575                    label(b.owner),
2576                    mm(gap),
2577                    mm(spacing)
2578                ),
2579            };
2580            violations.push(Violation { kind: ViolationKind::Hole, message, at });
2581        });
2582        let nets_of = |island: usize| conn.island_nets[island].iter().map(String::as_str);
2583        let mut pad_items = BTreeMap::new();
2584        for (i, item) in conn.items.iter().enumerate() {
2585            if let CopperRef::Pad { .. } = item.owner {
2586                pad_items.insert(object_key(item.owner), i);
2587            }
2588        }
2589        for (hole, _) in holes.iter().filter(|(_, plated)| !plated) {
2590            let Some(&own) = pad_items.get(&object_key(hole.owner)) else { continue };
2591            let own_island = conn.islands[own];
2592            let own_net = conn.island_net(own_island);
2593            let unplated = format!("{}'s unplated hole", self.describe(hole.owner, references));
2594            let pad_copper = &conn.items[own].shape;
2595            // Copper the copper check already holds to the clearance from the
2596            // pad: of another island and not of the pad's one net, and near the
2597            // pad's copper. A hole larger than its pad reaches past that copper,
2598            // so everything else is measured against the hole itself.
2599            let reported_by_copper = |related: bool, gap_to_pad: f64, required: i32| {
2600                !related && gap_to_pad + 0.5 < f64::from(required)
2601            };
2602            // Copper the drill touches is always cut, whatever the clearance.
2603            let too_near = |gap: f64, required: i32| gap + 0.5 < f64::from(required) || gap == 0.;
2604            let mut reported = BTreeSet::new();
2605            for (i, item) in conn.items.iter().enumerate() {
2606                let island = conn.islands[i];
2607                if i == own || !(item.layers.0 <= hole.layers.1 + 1 && hole.layers.0 <= item.layers.1) {
2608                    continue;
2609                }
2610                let related = island == own_island || own_net.is_some() && conn.island_net(island) == own_net;
2611                let (required, class) = self.rules.clearance_between_nets(nets_of(own_island), nets_of(island));
2612                if reported_by_copper(related, pad_copper.distance(&item.shape), required) {
2613                    continue;
2614                }
2615                let gap = hole.shape.distance(&item.shape);
2616                if too_near(gap, required) && reported.insert(object_key(item.owner)) {
2617                    violations.push(Violation {
2618                        kind: ViolationKind::Hole,
2619                        message: format!(
2620                            "{unplated} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
2621                            self.describe_on(item.owner, &conn.island_nets[island], references),
2622                            mm(gap),
2623                            class.name,
2624                            mm(f64::from(required))
2625                        ),
2626                        at: hole.shape.center(),
2627                    });
2628                }
2629            }
2630            // The edge clearance, from the outline and every cutout: the
2631            // copper check holds the pad to it, so only a hole reaching past
2632            // its pad is this check's.
2633            let edge_clearance = f64::from(self.rules.edge_clearance);
2634            let off_edge = |shape: &Shape| {
2635                let gap = self
2636                    .outline_edges()
2637                    .map(|(a, b)| shape.distance(&Shape::segment(a, b, 0)))
2638                    .fold(f64::INFINITY, f64::min);
2639                !self.outline_contains(shape.center()) || gap + 0.5 < edge_clearance || gap == 0.
2640            };
2641            if off_edge(&hole.shape) && !off_edge(pad_copper) {
2642                violations.push(Violation {
2643                    kind: ViolationKind::Hole,
2644                    message: format!(
2645                        "{unplated} is outside the board or within {:.3} mm of its edge",
2646                        mm(edge_clearance)
2647                    ),
2648                    at: hole.shape.center(),
2649                });
2650            }
2651            for (z, zone) in self.zones.iter().enumerate() {
2652                for (k, piece) in zone.fill.iter().enumerate() {
2653                    let island = conn.zone_islands[z][k];
2654                    let related = island == own_island || own_net == Some(zone.net.as_str());
2655                    let (required, class) = self.rules.clearance_between_nets(nets_of(own_island), [zone.net.as_str()]);
2656                    if reported_by_copper(related, piece.distance(pad_copper), required) {
2657                        continue;
2658                    }
2659                    let gap = piece.distance(&hole.shape);
2660                    if too_near(gap, required) {
2661                        violations.push(Violation {
2662                            kind: ViolationKind::Hole,
2663                            message: format!(
2664                                "{unplated} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
2665                                zones::describe(zone, self.layer_count),
2666                                mm(gap),
2667                                class.name,
2668                                mm(f64::from(required))
2669                            ),
2670                            at: hole.shape.center(),
2671                        });
2672                        break;
2673                    }
2674                }
2675            }
2676        }
2677        violations
2678    }
2679    /// Design rule check against exact copper geometry.
2680    pub fn drc(&self, netlist: &Netlist) -> Vec<Violation> {
2681        let conn = self.connectivity(netlist);
2682        let references: BTreeMap<Uuid, String> = netlist
2683            .nets
2684            .iter()
2685            .flat_map(|n| &n.pins)
2686            .map(|p| (p.component_id, p.reference.clone()))
2687            .collect();
2688        let object = |owner: CopperRef| match owner {
2689            CopperRef::Pad { placement, pad } => (0, placement, pad),
2690            CopperRef::Track { track, .. } => (1, track, 0),
2691            CopperRef::Via(v) => (2, v, 0),
2692        };
2693        let mut violations = vec![];
2694        for (island, nets) in conn.island_nets.iter().enumerate() {
2695            if nets.len() > 1 {
2696                let at = conn
2697                    .islands
2698                    .iter()
2699                    .position(|&i| i == island)
2700                    .map_or_else(Point::default, |i| conn.items[i].shape.center());
2701                violations.push(Violation {
2702                    kind: ViolationKind::Short,
2703                    message: format!(
2704                        "Short circuit between {}",
2705                        nets.iter().cloned().collect::<Vec<_>>().join(", ")
2706                    ),
2707                    at,
2708                });
2709            }
2710        }
2711        // Each pair keeps the larger of its two nets' class clearances, so the
2712        // prefilter must reach as far as the largest any class asks for.
2713        let nets_of = |island: usize| conn.island_nets[island].iter().map(String::as_str);
2714        let mut reported = BTreeSet::new();
2715        near_pairs(&conn.items, self.rules.max_clearance(), |i, j| {
2716            let (island_i, island_j) = (conn.islands[i], conn.islands[j]);
2717            if island_i == island_j {
2718                return;
2719            }
2720            if let (Some(a), Some(b)) = (conn.island_net(island_i), conn.island_net(island_j))
2721                && a == b
2722            {
2723                return;
2724            }
2725            let (a, b) = (&conn.items[i], &conn.items[j]);
2726            let (required, class) = self.rules.clearance_between_nets(nets_of(island_i), nets_of(island_j));
2727            let clearance = f64::from(required);
2728            let gap = a.shape.distance(&b.shape);
2729            let key = (object(a.owner), object(b.owner));
2730            if gap + 0.5 < clearance && reported.insert(key) {
2731                let (ca, cb) = (a.shape.center(), b.shape.center());
2732                violations.push(Violation {
2733                    kind: ViolationKind::Clearance,
2734                    message: format!(
2735                        "{} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
2736                        self.describe_on(a.owner, &conn.island_nets[island_i], &references),
2737                        self.describe_on(b.owner, &conn.island_nets[island_j], &references),
2738                        gap / 1000.,
2739                        class.name,
2740                        clearance / 1000.
2741                    ),
2742                    at: Point::new(
2743                        ((i64::from(ca.x) + i64::from(cb.x)) / 2) as i32,
2744                        ((i64::from(ca.y) + i64::from(cb.y)) / 2) as i32,
2745                    ),
2746                });
2747            }
2748        });
2749        // A zone's fill is copper like any other: it keeps the clearance from every
2750        // island it is not part of that does not carry its own net, and from the
2751        // fill of any other zone of another net on its layer.
2752        let edge_clearance = f64::from(self.rules.edge_clearance);
2753        for (z, zone) in self.zones.iter().enumerate() {
2754            let label = zones::describe(zone, self.layer_count);
2755            let mut reported = BTreeSet::new();
2756            for (k, piece) in zone.fill.iter().enumerate() {
2757                let island = conn.zone_islands[z][k];
2758                let (min, max) = piece.bounds();
2759                for (i, item) in conn.items.iter().enumerate() {
2760                    if !(item.layers.0 <= zone.layer && zone.layer <= item.layers.1)
2761                        || conn.islands[i] == island
2762                    {
2763                        continue;
2764                    }
2765                    if conn.island_net(conn.islands[i]) == Some(zone.net.as_str())
2766                        && conn.island_net(island) == Some(zone.net.as_str())
2767                    {
2768                        continue;
2769                    }
2770                    let (lo, hi) = item.shape.bounds();
2771                    let slack = self.rules.max_clearance();
2772                    if lo.x > max.x + slack
2773                        || hi.x < min.x - slack
2774                        || lo.y > max.y + slack
2775                        || hi.y < min.y - slack
2776                    {
2777                        continue;
2778                    }
2779                    let (required, class) =
2780                        self.rules.clearance_between_nets([zone.net.as_str()], nets_of(conn.islands[i]));
2781                    let clearance = f64::from(required);
2782                    let gap = piece.distance(&item.shape);
2783                    if gap + 0.5 < clearance && reported.insert(object(item.owner)) {
2784                        violations.push(Violation {
2785                            kind: ViolationKind::Clearance,
2786                            message: format!(
2787                                "{label} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
2788                                self.describe_on(item.owner, &conn.island_nets[conn.islands[i]], &references),
2789                                gap / 1000.,
2790                                class.name,
2791                                clearance / 1000.
2792                            ),
2793                            at: item.shape.center(),
2794                        });
2795                    }
2796                }
2797                for (other_z, other) in self.zones.iter().enumerate().skip(z + 1) {
2798                    if other.layer != zone.layer || other.net == zone.net {
2799                        continue;
2800                    }
2801                    for (m, other_piece) in other.fill.iter().enumerate() {
2802                        if conn.zone_islands[other_z][m] == island {
2803                            continue;
2804                        }
2805                        let (required, class) =
2806                            self.rules.clearance_between(Some(zone.net.as_str()), Some(other.net.as_str()));
2807                        let clearance = f64::from(required);
2808                        let gap = piece.distance_to_piece(other_piece);
2809                        if gap + 0.5 < clearance {
2810                            violations.push(Violation {
2811                                kind: ViolationKind::Clearance,
2812                                message: format!(
2813                                    "{label} to {}: {:.3} mm gap, {} clearance {:.3} mm required",
2814                                    zones::describe(other, self.layer_count),
2815                                    gap / 1000.,
2816                                    class.name,
2817                                    clearance / 1000.
2818                                ),
2819                                at: other_piece.outer[0],
2820                            });
2821                        }
2822                    }
2823                }
2824                let edge_gap = piece
2825                    .edges()
2826                    .flat_map(|(a, b)| {
2827                        let edge = Shape::segment(a, b, 0);
2828                        self.outline_edges()
2829                            .map(move |(c, d)| edge.distance(&Shape::segment(c, d, 0)))
2830                    })
2831                    .fold(f64::INFINITY, f64::min);
2832                // Copper ON an edge (crossing the outline or a cutout) is a
2833                // finding even when the edge clearance is nil: the mill cuts it.
2834                // A cutout the fill wholly covers touches none of its edges: a
2835                // stale fill poured before the cutout was made.
2836                let covers_cutout = self.cutouts.iter().any(|c| piece.contains(c.points[0]));
2837                if !self.outline_contains(piece.outer[0])
2838                    || edge_gap + 0.5 < edge_clearance
2839                    || edge_gap == 0.
2840                    || covers_cutout
2841                {
2842                    violations.push(Violation {
2843                        kind: ViolationKind::BoardEdge,
2844                        message: format!(
2845                            "{label} is outside the board or within {:.3} mm of its edge",
2846                            edge_clearance / 1000.
2847                        ),
2848                        at: piece.outer[0],
2849                    });
2850                }
2851            }
2852        }
2853        let mut reported = BTreeSet::new();
2854        for item in &conn.items {
2855            let center = item.shape.center();
2856            let gap = self
2857                .outline_edges()
2858                .map(|(a, b)| item.shape.distance(&Shape::segment(a, b, 0)))
2859                .fold(f64::INFINITY, f64::min);
2860            if (!self.outline_contains(center) || gap + 0.5 < edge_clearance || gap == 0.)
2861                && reported.insert(object(item.owner))
2862            {
2863                violations.push(Violation {
2864                    kind: ViolationKind::BoardEdge,
2865                    message: format!(
2866                        "{} is outside the board or within {:.3} mm of its edge",
2867                        self.describe(item.owner, &references),
2868                        edge_clearance / 1000.
2869                    ),
2870                    at: center,
2871                });
2872            }
2873        }
2874        // Every track at least as wide as its net asks for; an island shorting two
2875        // nets is already a finding, and asks for its widest.
2876        let mut reported = BTreeSet::new();
2877        for (i, item) in conn.items.iter().enumerate() {
2878            let CopperRef::Track { track, .. } = item.owner else { continue };
2879            let t = &self.tracks[track];
2880            let nets = &conn.island_nets[conn.islands[i]];
2881            let (required, rule) = match conn.island_net(conn.islands[i]) {
2882                Some(net) if self.rules.net_widths.contains_key(net) => {
2883                    (self.rules.width_for(net), format!("{net}'s width"))
2884                }
2885                _ => {
2886                    let class = self.rules.class_of_nets(nets.iter().map(String::as_str));
2887                    let widest = nets
2888                        .iter()
2889                        .map(|n| self.rules.width_for(n))
2890                        .max()
2891                        .unwrap_or(class.track_width);
2892                    (widest, format!("{} width", class.name))
2893                }
2894            };
2895            if t.width < required && reported.insert(track) {
2896                violations.push(Violation {
2897                    kind: ViolationKind::TrackWidth,
2898                    message: format!(
2899                        "track on {}{}: {:.3} mm wide, {rule} {:.3} mm required",
2900                        layer_name(t.layer, self.layer_count),
2901                        if nets.is_empty() {
2902                            String::new()
2903                        } else {
2904                            format!(" ({})", nets.iter().cloned().collect::<Vec<_>>().join(", "))
2905                        },
2906                        f64::from(t.width) / 1000.,
2907                        f64::from(required) / 1000.
2908                    ),
2909                    at: t.points.first().copied().unwrap_or_default(),
2910                });
2911            }
2912        }
2913        // Courtyards side by side: a part's own on the side it is mounted on,
2914        // and a drawn back courtyard on the other.
2915        let overlap = |a: Option<(Point, Point)>, b: Option<(Point, Point)>| match (a, b) {
2916            (Some((a0, a1)), Some((b0, b1))) => a0.x < b1.x && b0.x < a1.x && a0.y < b1.y && b0.y < a1.y,
2917            _ => false,
2918        };
2919        for (i, a) in self.placements.iter().enumerate() {
2920            for b in &self.placements[i + 1..] {
2921                if [true, false].into_iter().any(|top| overlap(a.courtyard_on(top), b.courtyard_on(top))) {
2922                    violations.push(Violation {
2923                        kind: ViolationKind::Courtyard,
2924                        message: format!(
2925                            "Courtyards of {} and {} overlap",
2926                            references.get(&a.component).map_or("?", String::as_str),
2927                            references.get(&b.component).map_or("?", String::as_str)
2928                        ),
2929                        at: Point::new((a.at.x + b.at.x) / 2, (a.at.y + b.at.y) / 2),
2930                    });
2931                }
2932            }
2933        }
2934        // A one-layer board has no bottom copper: a surface-mount pad that would
2935        // face the bottom (a back pad of a top part) has nowhere to go.
2936        if self.layer_count == 1 {
2937            for placement in self.placements.iter().filter(|p| p.has_back_copper_pad()) {
2938                violations.push(Violation {
2939                    kind: ViolationKind::MissingPad,
2940                    message: format!(
2941                        "{} has pads on the back copper, which a one-layer board does not have",
2942                        references.get(&placement.component).map_or("?", String::as_str)
2943                    ),
2944                    at: placement.at,
2945                });
2946            }
2947            // Nor can a pad's vias go through to a layer that is not there.
2948            for placement in self.placements.iter().filter(|p| p.footprint.pads.iter().any(|pad| pad.vias.is_some())) {
2949                violations.push(Violation {
2950                    kind: ViolationKind::MissingPad,
2951                    message: format!(
2952                        "{} has vias in its pads, which a one-layer board cannot carry",
2953                        references.get(&placement.component).map_or("?", String::as_str)
2954                    ),
2955                    at: placement.at,
2956                });
2957            }
2958        }
2959        let ring = self.rules.min_annular_ring;
2960        for placement in &self.placements {
2961            for pad in &placement.footprint.pads {
2962                if let Some(have) = pad.annular_ring().filter(|r| *r < ring) {
2963                    let reference = references.get(&placement.component).map_or("?", String::as_str);
2964                    let name = if pad.number.is_empty() { "unnumbered pad".to_owned() } else { format!("pad {}", pad.number) };
2965                    violations.push(Violation {
2966                        kind: ViolationKind::AnnularRing,
2967                        message: format!(
2968                            "{reference} {name}: annular ring {:.3} mm, {:.3} mm required",
2969                            f64::from(have) / 1000.,
2970                            f64::from(ring) / 1000.
2971                        ),
2972                        at: placement.transform(pad.at),
2973                    });
2974                }
2975            }
2976        }
2977        for via in &self.all_vias() {
2978            let have = (via.diameter - via.drill) / 2;
2979            if have < ring {
2980                violations.push(Violation {
2981                    kind: ViolationKind::AnnularRing,
2982                    message: format!(
2983                        "Via: annular ring {:.3} mm, {:.3} mm required",
2984                        f64::from(have) / 1000.,
2985                        f64::from(ring) / 1000.
2986                    ),
2987                    at: via.at,
2988                });
2989            }
2990        }
2991        violations.extend(self.hole_findings(&conn, &references));
2992        for net in netlist.nets.iter().filter(|n| n.pins.len() > 1) {
2993            for pin in &net.pins {
2994                if let Some(placement) = self.placement(pin.component_id)
2995                    && !placement
2996                        .footprint
2997                        .pads
2998                        .iter()
2999                        .any(|p| p.number == pin.number)
3000                {
3001                    violations.push(Violation {
3002                        kind: ViolationKind::MissingPad,
3003                        message: format!(
3004                            "{} pin {} (net {}) has no pad in footprint {}",
3005                            pin.reference, pin.number, net.name, placement.footprint.name
3006                        ),
3007                        at: placement.at,
3008                    });
3009                }
3010            }
3011        }
3012        violations.extend(self.stitching_findings(netlist));
3013        for wire in self.ratsnest(&conn) {
3014            violations.push(Violation {
3015                kind: ViolationKind::Unrouted,
3016                message: format!("Unrouted connection in net {}", wire.net),
3017                at: Point::new((wire.a.x + wire.b.x) / 2, (wire.a.y + wire.b.y) / 2),
3018            });
3019        }
3020        violations.sort_by(|a, b| (a.kind, &a.message, a.at).cmp(&(b.kind, &b.message, b.at)));
3021        violations
3022    }
3023    pub fn validate(&self, components: &BTreeSet<Uuid>) -> Result<(), String> {
3024        let valid = |p: Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
3025        let size = |v: i32| (1..=100_000_000).contains(&v);
3026        if !(1..=32).contains(&self.layer_count) {
3027            return Err("Boards need between 1 and 32 copper layers".into());
3028        }
3029        if self.outline.len() < 3 || self.outline.iter().any(|p| !valid(*p)) {
3030            return Err("Board outline needs at least three valid points".into());
3031        }
3032        let r = &self.rules;
3033        if !size(r.track_width)
3034            || !(0..=100_000_000).contains(&r.clearance)
3035            || !(0..=100_000_000).contains(&r.edge_clearance)
3036            || !size(r.via_drill)
3037            || r.via_diameter <= r.via_drill
3038            || !size(r.via_diameter)
3039            || !(10..=100_000).contains(&r.routing_grid)
3040            || r.net_widths.values().any(|w| !size(*w))
3041            || !(0..=10_000).contains(&r.mask_expansion)
3042            || !(0..=10_000).contains(&r.min_annular_ring)
3043            || !(0..=10_000).contains(&r.min_hole_spacing)
3044        {
3045            return Err("Invalid design rules".into());
3046        }
3047        r.check_net_classes()?;
3048        let mut placed = BTreeSet::new();
3049        for p in &self.placements {
3050            if !components.contains(&p.component) {
3051                return Err("Footprint refers to a missing component".into());
3052            }
3053            if !placed.insert(p.component) {
3054                return Err("Component has more than one footprint".into());
3055            }
3056            if !valid(p.at) || p.rotation > 3 {
3057                return Err("Invalid footprint placement".into());
3058            }
3059            for pad in &p.footprint.pads {
3060                if !valid(pad.at)
3061                    || !size(pad.size.x)
3062                    || !size(pad.size.y)
3063                    || pad.outline_problem().is_some()
3064                    || pad.layers.paste_windows.is_some_and(|w| w.problem().is_some())
3065                    || pad.vias_problem().is_some()
3066                    || pad.hole_problem().is_some()
3067                    || pad.hole_size().is_some_and(|h| !size(h.x) || !size(h.y))
3068                    || !(0..=100_000).contains(&pad.corner_radius)
3069                    || [pad.layers.mask_margin, pad.layers.paste_margin]
3070                        .into_iter()
3071                        .flatten()
3072                        .any(|m| !(-10_000..=10_000).contains(&m))
3073                {
3074                    return Err(format!("Invalid pad in footprint {}", p.footprint.name));
3075                }
3076            }
3077            if p.footprint.courtyard_margin.is_some_and(|m| !(0..=100_000).contains(&m)) {
3078                return Err(format!("Invalid courtyard clearance in footprint {}", p.footprint.name));
3079            }
3080            if p.footprint.silk.iter().flatten().any(|q| !valid(*q)) {
3081                return Err("Invalid footprint silkscreen".into());
3082            }
3083            if p.footprint.graphics.len() > 100_000
3084                || p.footprint.graphics.iter().any(|g| g.problem().is_some())
3085            {
3086                return Err(format!("Invalid drawing in footprint {}", p.footprint.name));
3087            }
3088        }
3089        if self.graphics.len() > 100_000 {
3090            return Err("A board holds at most 100000 drawn items".into());
3091        }
3092        // A drawn item is selected, edited and deleted by its id: two sharing
3093        // one would be edited as one and deleted together.
3094        let mut ids = BTreeSet::new();
3095        if !self.graphics.iter().all(|g| ids.insert(g.id)) {
3096            return Err("Two board drawings share an id".into());
3097        }
3098        if let Some((n, problem)) = self
3099            .graphics
3100            .iter()
3101            .enumerate()
3102            .find_map(|(n, g)| g.problem().map(|p| (n, p)))
3103        {
3104            return Err(format!("Board drawing {} {problem}", n + 1));
3105        }
3106        if self.cutouts.len() > MAX_CUTOUTS {
3107            return Err(format!("A board holds at most {MAX_CUTOUTS} cutouts"));
3108        }
3109        // A cutout is selected, moved and deleted by its id, as a drawing is.
3110        let mut ids = BTreeSet::new();
3111        if !self.cutouts.iter().all(|c| ids.insert(c.id)) {
3112            return Err("Two board cutouts share an id".into());
3113        }
3114        for (n, c) in self.cutouts.iter().enumerate() {
3115            if c.points.iter().any(|q| !valid(*q)) {
3116                return Err(format!("Cutout {} has a corner off the drawing area", n + 1));
3117            }
3118            // Each against the ones before it, so of two that overlap the later
3119            // one, the one just drawn, is named.
3120            if let Some(problem) = self.cutout_problem_among(&c.points, &self.cutouts[..n], None) {
3121                return Err(format!("Cutout {} {problem}", n + 1));
3122            }
3123        }
3124        for t in &self.tracks {
3125            if t.layer >= self.layer_count
3126                || !size(t.width)
3127                || t.points.len() < 2
3128                || t.points.iter().any(|q| !valid(*q))
3129                || t.points.windows(2).any(|s| s[0] == s[1])
3130            {
3131                return Err("Tracks need a valid layer, width, and nonzero segments".into());
3132            }
3133        }
3134        for v in &self.vias {
3135            if !valid(v.at) || !size(v.drill) || v.diameter <= v.drill {
3136                return Err("Invalid via".into());
3137            }
3138            if v.span.is_some_and(|(from, to)| from >= to || to >= self.layer_count) {
3139                return Err("A blind or buried via needs two different layers of the board".into());
3140            }
3141        }
3142        for zone in &self.zones {
3143            zone.validate(self.layer_count)?;
3144        }
3145        Ok(())
3146    }
3147}
3148
3149/// Result of bringing the board in line with the schematic.
3150#[derive(Clone, Debug, Default, PartialEq, Eq)]
3151pub struct BoardSync {
3152    pub added: usize,
3153    pub removed: usize,
3154    /// The references of components that need a footprint but have no pads, in
3155    /// natural order. Their part carries none, so they are not on the board.
3156    pub without_pads: Vec<String>,
3157    /// The outline's size, width and height in micrometres, before and after the
3158    /// pass, when the pass grew it: parts added to a board with no free room left
3159    /// for them are packed below it and the outline follows them down.
3160    pub outline_grew: Option<(Point, Point)>,
3161}
3162
3163/// Explicit native pads always belong on the board. Pin-bearing symbols without
3164/// pads are reported as missing pads; standalone power symbols and flags are not.
3165pub fn needs_footprint(component: &crate::Component) -> bool {
3166    // A part off the board (a sheet's fan or switch) is not seated, pads or not.
3167    !component.off_board && (component.pads.is_some() || (component.symbol.power_net.is_none()
3168        && !component.reference.starts_with('#')
3169        && !component.symbol.pins.is_empty()))
3170}
3171
3172impl Document {
3173    /// Place each new component with its part's pads and drop the placements of
3174    /// removed components. Existing placements are kept. A component with no pads is
3175    /// left off the board and listed in [`BoardSync::without_pads`]: pads come with
3176    /// the part, from a KiCad import or the pads editor, never from a generator.
3177    pub fn sync_board(&mut self) -> BoardSync {
3178        let wanted: BTreeSet<Uuid> = self
3179            .components
3180            .iter()
3181            .filter(|c| needs_footprint(c))
3182            .map(|c| c.id)
3183            .collect();
3184        let before = self.board.placements.len();
3185        self.board
3186            .placements
3187            .retain(|p| wanted.contains(&p.component));
3188        let removed = before - self.board.placements.len();
3189        let was_empty = self.board.placements.is_empty();
3190        let mut added = vec![];
3191        let mut without_pads = vec![];
3192        for c in self.components.iter().filter(|c| wanted.contains(&c.id)) {
3193            if self.board.placement(c.id).is_some() {
3194                continue;
3195            }
3196            let Some(pads) = &c.pads else {
3197                without_pads.push(c.reference.clone());
3198                continue;
3199            };
3200            self.board.placements.push(Placement {
3201                component: c.id,
3202                footprint: pads.clone(),
3203                at: Point::default(),
3204                rotation: 0,
3205                bottom: false,
3206            });
3207            added.push(c.id);
3208        }
3209        without_pads.sort_by(|a, b| footprint::natural_cmp(a, b));
3210        let size = |(min, max): (Point, Point)| Point::new(max.x - min.x, max.y - min.y);
3211        let before = size(self.board.outline_bounds());
3212        if was_empty {
3213            self.auto_place();
3214        } else if !added.is_empty() {
3215            // Into the room the board already has first, beside the parts each shares
3216            // a net with. Packing every addition as a new row under the lowest part
3217            // grew the board by a row per part: six parts added one at a time took a
3218            // stock 60 × 40 mm board to 60 × 54 before it was ever looked at, and one
3219            // capacitor grew a fitted 40 × 19 mm board to 40 × 21 (the eCAD re-audit's
3220            // B10 and item 16).
3221            let homeless = self.seat_in_free_room(&added);
3222            if !homeless.is_empty() {
3223                let (min, _) = self.board.outline_bounds();
3224                let top = self
3225                    .board
3226                    .placements
3227                    .iter()
3228                    .filter(|p| !homeless.contains(&p.component))
3229                    .map(|p| p.courtyard().1.y + PLACEMENT_SPACING)
3230                    .max()
3231                    .unwrap_or(min.y + PLACEMENT_SPACING);
3232                self.pack(&homeless, top);
3233            }
3234        }
3235        let after = size(self.board.outline_bounds());
3236        BoardSync {
3237            added: added.len(),
3238            removed,
3239            without_pads,
3240            outline_grew: (!was_empty && after != before).then_some((before, after)),
3241        }
3242    }
3243    /// Lay every part out afresh by its nets: the part with the most pins in the
3244    /// middle of the board, then each part, in `Self::placement_order`, in the free
3245    /// room nearest the parts already laid out that it shares a small net with. Each
3246    /// keeps its side and its rotation. Where the room runs out the rest are packed
3247    /// in rows below, as [`Self::auto_place`] packs them, and the outline grows.
3248    ///
3249    /// [`Self::auto_place`] packs the same order into rows, so a part's neighbours
3250    /// were the ones beside it in the row and the next row began at the left edge
3251    /// however far that was from them (the eCAD re-audit's B10).
3252    pub fn place_by_nets(&mut self) {
3253        let order = self.placement_order();
3254        let homeless = self.seat_in_free_room(&order);
3255        if !homeless.is_empty() {
3256            let (min, _) = self.board.outline_bounds();
3257            let top = self
3258                .board
3259                .placements
3260                .iter()
3261                .filter(|p| !homeless.contains(&p.component))
3262                .map(|p| p.courtyard().1.y + PLACEMENT_SPACING)
3263                .max()
3264                .unwrap_or(min.y + PLACEMENT_SPACING);
3265            self.pack(&homeless, top);
3266        }
3267    }
3268    /// Seat each of `ids`, in turn, in the free room inside the outline nearest the
3269    /// placed parts it shares a small net with (a rail of more than eight parts is
3270    /// everyone's neighbour and so no one's), or nearest the placed parts' middle
3271    /// when it shares none. Free room is a spot where its courtyard keeps
3272    /// [`SEAT_GAP`] from the outline and from every other courtyard on its side, and
3273    /// the design rules' clearance from every piece of copper already on the board,
3274    /// so a part added to a routed board does not land on a track. Each keeps its
3275    /// side and its rotation. Returns the ones with no room anywhere, left where
3276    /// they were.
3277    fn seat_in_free_room(&mut self, ids: &[Uuid]) -> Vec<Uuid> {
3278        let mut pending: BTreeSet<Uuid> = ids.iter().copied().collect();
3279        let mut nets_of: BTreeMap<Uuid, Vec<usize>> = BTreeMap::new();
3280        for (n, net) in self.netlist().nets.iter().enumerate() {
3281            let members: BTreeSet<Uuid> = net.pins.iter().map(|p| p.component_id).collect();
3282            if members.len() <= 8 {
3283                for m in members {
3284                    nets_of.entry(m).or_default().push(n);
3285                }
3286            }
3287        }
3288        let (min, max) = self.board.outline_bounds();
3289        let clearance = f64::from(self.board.rules.max_clearance());
3290        let gap = f64::from(SEAT_GAP);
3291        let mut homeless = vec![];
3292        for &id in ids {
3293            let Some(index) = self.board.placements.iter().position(|p| p.component == id) else {
3294                continue;
3295            };
3296            let seated: Vec<&Placement> = self
3297                .board
3298                .placements
3299                .iter()
3300                .filter(|p| !pending.contains(&p.component))
3301                .collect();
3302            let mine = nets_of.get(&id).cloned().unwrap_or_default();
3303            let near: Vec<Point> = seated
3304                .iter()
3305                .filter(|p| {
3306                    nets_of
3307                        .get(&p.component)
3308                        .is_some_and(|theirs| theirs.iter().any(|n| mine.contains(n)))
3309                })
3310                .map(|p| p.at)
3311                .collect();
3312            let centre = |points: &[Point]| {
3313                let n = points.len().max(1) as i64;
3314                let (x, y) = points
3315                    .iter()
3316                    .fold((0i64, 0i64), |(x, y), p| (x + i64::from(p.x), y + i64::from(p.y)));
3317                Point::new((x / n) as i32, (y / n) as i32)
3318            };
3319            let target = if !near.is_empty() {
3320                centre(&near)
3321            } else if !seated.is_empty() {
3322                centre(&seated.iter().map(|p| p.at).collect::<Vec<_>>())
3323            } else {
3324                Point::new((min.x + max.x) / 2, (min.y + max.y) / 2)
3325            };
3326            let mut placement = self.board.placements[index].clone();
3327            placement.at = Point::default();
3328            // The seated parts' courtyards on the side this part is mounted on,
3329            // and on the other side, which a back courtyard of its own occupies.
3330            let mounted_top = !placement.bottom;
3331            let on_side = |top: bool| -> Vec<Shape> {
3332                seated
3333                    .iter()
3334                    .filter_map(|p| p.courtyard_on(top))
3335                    .map(|(min, max)| Shape::Rect { min, max })
3336                    .collect()
3337            };
3338            let (courtyards, other_side) = (on_side(mounted_top), on_side(!mounted_top));
3339            let back = placement.back_courtyard();
3340            let copper: Vec<Shape> = self
3341                .board
3342                .copper()
3343                .into_iter()
3344                .filter(|item| match item.owner {
3345                    CopperRef::Pad { placement, .. } => {
3346                        !pending.contains(&self.board.placements[placement].component)
3347                    }
3348                    _ => true,
3349                })
3350                .map(|item| item.shape)
3351                .collect();
3352            let (c0, c1) = placement.courtyard();
3353            let step = 500;
3354            let span = |lo: i32, hi: i32, c_lo: i32, c_hi: i32| {
3355                let first = snap_up(lo + SEAT_GAP - c_lo, step);
3356                let last = snap_down(hi - SEAT_GAP - c_hi, step);
3357                (first..=last).step_by(step as usize)
3358            };
3359            let mut spots: Vec<Point> = span(min.x, max.x, c0.x, c1.x)
3360                .flat_map(|x| span(min.y, max.y, c0.y, c1.y).map(move |y| Point::new(x, y)))
3361                .collect();
3362            let middle = Point::new((c0.x + c1.x) / 2, (c0.y + c1.y) / 2);
3363            let far = |at: &Point| {
3364                let (dx, dy) = (
3365                    i64::from(at.x + middle.x - target.x),
3366                    i64::from(at.y + middle.y - target.y),
3367                );
3368                (dx * dx + dy * dy, at.y, at.x)
3369            };
3370            spots.sort_by_key(far);
3371            let free = spots.into_iter().find(|&at| {
3372                let body = Shape::Rect { min: c0.offset(at), max: c1.offset(at) };
3373                let corners = [
3374                    c0.offset(at),
3375                    c1.offset(at),
3376                    Point::new(c0.x, c1.y).offset(at),
3377                    Point::new(c1.x, c0.y).offset(at),
3378                ];
3379                corners.iter().all(|&p| self.board.outline_contains(p))
3380                    && self
3381                        .board
3382                        .outline_edges()
3383                        .all(|(a, b)| body.distance(&Shape::segment(a, b, 0)) >= gap)
3384                    && courtyards.iter().all(|c| body.distance(c) >= gap)
3385                    && back.is_none_or(|(b0, b1)| {
3386                        let back = Shape::Rect { min: b0.offset(at), max: b1.offset(at) };
3387                        other_side.iter().all(|c| back.distance(c) >= gap)
3388                    })
3389                    && copper.iter().all(|c| body.distance(c) >= clearance)
3390            });
3391            match free {
3392                Some(at) => {
3393                    placement.at = at;
3394                    self.board.placements[index] = placement;
3395                    pending.remove(&id);
3396                }
3397                None => homeless.push(id),
3398            }
3399        }
3400        homeless
3401    }
3402    /// Pack all placements in rows inside the outline, keeping connected parts together.
3403    pub fn auto_place(&mut self) {
3404        let order = self.placement_order();
3405        let (min, _) = self.board.outline_bounds();
3406        self.pack(&order, min.y + PLACEMENT_SPACING);
3407        let (min, max) = self.board.outline_bounds();
3408        let corners: Vec<Point> = self
3409            .board
3410            .placements
3411            .iter()
3412            .flat_map(|p| {
3413                let (a, b) = p.courtyard();
3414                [a, b]
3415            })
3416            .collect();
3417        if let Some((a, b)) = bounds_of(&corners) {
3418            let centre = |lo: i32, hi: i32, a: i32, b: i32| {
3419                let shift = (lo + hi) / 2 - (a + b) / 2;
3420                shift.div_euclid(100) * 100
3421            };
3422            let shift = Point::new(
3423                centre(min.x, max.x, a.x, b.x),
3424                centre(min.y, max.y, a.y, b.y),
3425            );
3426            for p in &mut self.board.placements {
3427                p.at = p.at.offset(shift);
3428            }
3429        }
3430    }
3431    /// Components ordered by breadth-first traversal of small shared nets.
3432    fn placement_order(&self) -> Vec<Uuid> {
3433        let placed: BTreeSet<Uuid> = self.board.placements.iter().map(|p| p.component).collect();
3434        let mut neighbours: BTreeMap<Uuid, BTreeSet<Uuid>> = BTreeMap::new();
3435        for net in self.netlist().nets {
3436            let members: BTreeSet<Uuid> = net
3437                .pins
3438                .iter()
3439                .map(|p| p.component_id)
3440                .filter(|c| placed.contains(c))
3441                .collect();
3442            if members.len() > 8 {
3443                continue;
3444            }
3445            for a in &members {
3446                neighbours
3447                    .entry(*a)
3448                    .or_default()
3449                    .extend(members.iter().filter(|b| *b != a));
3450            }
3451        }
3452        let mut seeds: Vec<&crate::Component> = self
3453            .components
3454            .iter()
3455            .filter(|c| placed.contains(&c.id))
3456            .collect();
3457        seeds.sort_by(|a, b| {
3458            b.symbol
3459                .pins
3460                .len()
3461                .cmp(&a.symbol.pins.len())
3462                .then_with(|| footprint::natural_cmp(&a.reference, &b.reference))
3463        });
3464        let reference: BTreeMap<Uuid, &str> = self
3465            .components
3466            .iter()
3467            .map(|c| (c.id, c.reference.as_str()))
3468            .collect();
3469        let mut order = vec![];
3470        let mut seen = BTreeSet::new();
3471        for seed in seeds {
3472            if !seen.insert(seed.id) {
3473                continue;
3474            }
3475            let mut queue = std::collections::VecDeque::from([seed.id]);
3476            while let Some(id) = queue.pop_front() {
3477                order.push(id);
3478                let mut next: Vec<Uuid> = neighbours
3479                    .get(&id)
3480                    .into_iter()
3481                    .flatten()
3482                    .filter(|n| !seen.contains(*n))
3483                    .copied()
3484                    .collect();
3485                next.sort_by(|a, b| footprint::natural_cmp(reference[a], reference[b]));
3486                for n in next {
3487                    seen.insert(n);
3488                    queue.push_back(n);
3489                }
3490            }
3491        }
3492        order
3493    }
3494    /// Row-pack the given placements starting at `top`, growing a rectangular outline
3495    /// downward if they do not fit.
3496    fn pack(&mut self, ids: &[Uuid], top: i32) {
3497        let (min, max) = self.board.outline_bounds();
3498        let left = min.x + PLACEMENT_SPACING;
3499        let right = max.x - PLACEMENT_SPACING;
3500        let mut cursor = Point::new(left, top);
3501        let mut row_height = 0;
3502        for id in ids {
3503            let Some(p) = self
3504                .board
3505                .placements
3506                .iter_mut()
3507                .find(|p| p.component == *id)
3508            else {
3509                continue;
3510            };
3511            p.at = Point::default();
3512            let (c0, c1) = p.courtyard();
3513            let (w, h) = (c1.x - c0.x, c1.y - c0.y);
3514            if cursor.x + w > right && cursor.x > left {
3515                cursor = Point::new(left, cursor.y + row_height + PLACEMENT_SPACING);
3516                row_height = 0;
3517            }
3518            p.at = Point::new(snap_up(cursor.x - c0.x, 100), snap_up(cursor.y - c0.y, 100));
3519            cursor.x += w + PLACEMENT_SPACING;
3520            row_height = row_height.max(h);
3521        }
3522        let bottom = cursor.y + row_height + PLACEMENT_SPACING;
3523        if bottom > max.y && self.board.outline_is_rectangle() {
3524            self.board.outline = rectangle(min, Point::new(max.x, snap_up(bottom, 1000)));
3525        }
3526    }
3527    /// Resize a rectangular outline around all courtyards with a margin.
3528    pub fn fit_board_outline(&mut self, margin: i32) {
3529        let corners: Vec<Point> = self
3530            .board
3531            .placements
3532            .iter()
3533            .flat_map(|p| {
3534                let (a, b) = p.courtyard();
3535                [a, b]
3536            })
3537            .chain(self.board.tracks.iter().flat_map(|t| t.points.clone()))
3538            .chain(self.board.vias.iter().map(|v| v.at))
3539            .chain(self.board.cutouts.iter().flat_map(|c| c.points.clone()))
3540            .collect();
3541        if let Some((min, max)) = bounds_of(&corners) {
3542            self.board.outline = rectangle(
3543                Point::new(
3544                    snap_down(min.x - margin, 1000),
3545                    snap_down(min.y - margin, 1000),
3546                ),
3547                Point::new(snap_up(max.x + margin, 1000), snap_up(max.y + margin, 1000)),
3548            );
3549        }
3550    }
3551    /// The schematic net each drawn track carries, for the tracks whose copper island
3552    /// carries exactly one. A track joined to nothing, or bridging two nets, has none.
3553    pub fn track_nets(&self) -> BTreeMap<Uuid, String> {
3554        let connectivity = self.board.connectivity(&self.netlist());
3555        let mut nets = BTreeMap::new();
3556        for (i, item) in connectivity.items.iter().enumerate() {
3557            if let CopperRef::Track { track, .. } = item.owner
3558                && let Some(net) = connectivity.island_net(connectivity.islands[i])
3559            {
3560                nets.insert(self.board.tracks[track].id, net.to_owned());
3561            }
3562        }
3563        nets
3564    }
3565    /// Give every drawn track the width its net asks for, or the default width where its
3566    /// net has no rule of its own. Tracks whose width was set by hand keep it. Returns
3567    /// how many tracks changed. Widening copper can break clearances, so run the design
3568    /// rule check afterwards.
3569    pub fn apply_net_widths(&mut self) -> usize {
3570        let nets = self.track_nets();
3571        let rules = self.board.rules.clone();
3572        let mut changed = 0;
3573        for track in self.board.tracks.iter_mut().filter(|t| !t.fixed_width) {
3574            let width = nets
3575                .get(&track.id)
3576                .map_or(rules.track_width, |net| rules.width_for(net));
3577            if track.width != width {
3578                track.width = width;
3579                changed += 1;
3580            }
3581        }
3582        changed
3583    }
3584    /// Set one track's width, whatever its net asks for. [`Document::apply_net_widths`]
3585    /// then leaves this track alone until [`Document::follow_net_width`] gives it back.
3586    pub fn set_track_width(&mut self, id: Uuid, width: i32) -> Result<(), String> {
3587        if !(1..=100_000_000).contains(&width) {
3588            return Err("A track needs a positive width".into());
3589        }
3590        let track = self
3591            .board
3592            .tracks
3593            .iter_mut()
3594            .find(|t| t.id == id)
3595            .ok_or("Track no longer exists")?;
3596        track.width = width;
3597        track.fixed_width = true;
3598        Ok(())
3599    }
3600    /// Hand one track back to its net's width rule.
3601    pub fn follow_net_width(&mut self, id: Uuid) {
3602        let width = self
3603            .track_nets()
3604            .get(&id)
3605            .map_or(self.board.rules.track_width, |net| {
3606                self.board.rules.width_for(net)
3607            });
3608        if let Some(track) = self.board.tracks.iter_mut().find(|t| t.id == id) {
3609            track.width = width;
3610            track.fixed_width = false;
3611        }
3612    }
3613    pub fn board_drc(&self) -> Vec<Violation> {
3614        self.board.drc(&self.netlist())
3615    }
3616}
3617fn snap_up(v: i32, step: i32) -> i32 {
3618    v.div_euclid(step) * step + if v.rem_euclid(step) == 0 { 0 } else { step }
3619}
3620fn snap_down(v: i32, step: i32) -> i32 {
3621    v.div_euclid(step) * step
3622}