Skip to main content

brep_ecad_core/board/
zones.rs

1//! Copper zones: a polygon on one copper layer, given to one net, and FILLED with
2//! copper wherever the board's rules allow it — a ground pour.
3//!
4//! # The fill rule
5//!
6//! The fill of a zone on layer `L` for net `N` is the zone's polygon
7//!
8//! * inside the board outline by at least [`DesignRules::edge_clearance`](crate::board::DesignRules::edge_clearance);
9//! * minus a clearance round every piece of copper on `L` that is NOT on `N` —
10//!   pads, tracks and vias of other nets, and copper that carries no net at all
11//!   (an unrouted stub, a mechanical pad). The clearance is the larger of `N`'s net
12//!   class's and that copper's ([`DesignRules::clearance_between`](crate::board::DesignRules::clearance_between); netless copper
13//!   is Default);
14//! * minus the whole outline of every EARLIER zone on `L` of another net, grown by
15//!   the larger of the two nets' class clearances: zones are filled in the order they were drawn and the first
16//!   one keeps the ground they share (KiCad's priority, fixed to drawing order);
17//! * with same-net copper joined as follows — a surface-mount pad, a track and a
18//!   via of `N` are SOLID: the fill runs over them. A through-hole pad of `N` gets
19//!   a THERMAL RELIEF: a gap of [`Zone::thermal_gap`] (at least `N`'s class clearance) all
20//!   round it, bridged by up to four straight spokes, [`Zone::spoke_width`] wide,
21//!   left, right, up and down. A spoke is laid only where the fill is there to
22//!   meet it, so [`Thermal::spokes`] counts spokes that connect;
23//! * opened by [`Zone::min_width`]: every part of the fill narrower than that is
24//!   dropped (erode by half the width, grow back by half), before the spokes go
25//!   in so a spoke is never eroded away;
26//! * with its ISLANDS removed: a separate piece of fill that touches no copper of
27//!   `N` is dropped.
28//!
29//! A via with no net of its own whose centre is inside the zone's polygon is taken
30//! as a STITCHING via of the zone's net rather than as copper to keep clear of —
31//! a via dropped into a ground pour is there to join it to the other side.
32//! Which net a netless via stitches is decided ONCE for the board, per copper
33//! island, before any zone is filled: the nets of every zone that holds one of
34//! the island's vias. One net, and the island is that net's. Two or more — a
35//! via where a GND pour on one side and a VCC pour on the other overlap — and it
36//! is stitched to NONE: each fill keeps clear of it, as of any other copper, and
37//! the fill report and the design rule check both name it
38//! ([`Board::contested_vias`]). Stitched to both, the plated barrel would join
39//! the two fills and the Gerbers would carry the short.
40//!
41//! # How it is computed
42//!
43//! On a square grid of [`PITCH`] (finer when the clearance is small), each sample
44//! holds how far it is INSIDE the fill region: the least of its distance inside
45//! the zone, inside the outline less the edge clearance, and its distance from
46//! each piece of other-net copper less the clearance. The fill's boundary is that
47//! function's zero contour, traced by marching squares with the crossing on each
48//! grid edge interpolated — so an edge round a pad is a smooth curve and not a
49//! staircase — and every ring is simplified to within [`SIMPLIFY`]. The contour is
50//! taken at [`Self`]'s margin rather than at zero, so what interpolation and
51//! simplification can cost is paid out of the fill and never out of the
52//! clearance: a fill measured from its Gerber is never nearer other copper than
53//! the rule.
54//!
55//! # When it is filled
56//!
57//! On demand ([`Board::fill_zones`], the board's Fill zones action) and by the
58//! board view's design rule check, which refills before it checks. NOT on every
59//! edit: the fill is the costliest thing on a board after the autorouter, and a
60//! drag is sixty edits a second. What was filled is STORED in the zone, so the
61//! Gerbers, the 3D view and the STEP export all draw the copper the user saw; the
62//! fabrication export refills a copy first, so a stale fill is never what is
63//! sent to be made.
64use super::{Board, CopperItem, CopperRef, Connectivity, Shape, polygon_contains, point_segment_distance};
65use crate::{Document, Netlist, Point, Uuid};
66use serde::{Deserialize, Serialize};
67use std::collections::{BTreeMap, BTreeSet, HashMap};
68
69/// A thermal relief's default gap round a through-hole pad: KiCad's 0.5 mm.
70pub const DEFAULT_THERMAL_GAP: i32 = 500;
71/// A thermal spoke's default width: KiCad's 0.5 mm.
72pub const DEFAULT_SPOKE_WIDTH: i32 = 500;
73/// The narrowest fill kept by default: KiCad's 0.25 mm.
74pub const DEFAULT_MIN_WIDTH: i32 = 250;
75/// The fill grid's pitch in micrometres, unless the clearance asks for a finer one.
76pub const PITCH: i32 = 50;
77/// How far, in micrometres, a simplified fill edge may stray from the traced one.
78pub const SIMPLIFY: f64 = 2.;
79/// The most grid samples one zone's fill takes; a bigger zone gets a coarser grid.
80const MAX_SAMPLES: usize = 12_000_000;
81
82fn default_thermal_gap() -> i32 {
83    DEFAULT_THERMAL_GAP
84}
85fn default_spoke_width() -> i32 {
86    DEFAULT_SPOKE_WIDTH
87}
88fn default_min_width() -> i32 {
89    DEFAULT_MIN_WIDTH
90}
91
92/// A copper zone: an outline on one copper layer, the net it pours, and the copper
93/// its last fill made.
94#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct Zone {
96    pub id: Uuid,
97    /// The net the zone pours, by name.
98    pub net: String,
99    pub layer: u8,
100    /// Closed outline polygon, in board micrometres.
101    pub outline: Vec<Point>,
102    /// Gap round a through-hole pad of the zone's net, bridged by spokes.
103    #[serde(default = "default_thermal_gap")]
104    pub thermal_gap: i32,
105    #[serde(default = "default_spoke_width")]
106    pub spoke_width: i32,
107    /// Fill narrower than this is dropped.
108    #[serde(default = "default_min_width")]
109    pub min_width: i32,
110    /// The copper the last fill made. Empty until the zone is filled.
111    #[serde(default, skip_serializing_if = "Vec::is_empty")]
112    pub fill: Vec<FillPiece>,
113}
114impl Zone {
115    pub fn new(net: &str, layer: u8, outline: Vec<Point>) -> Self {
116        Self {
117            id: Uuid::new_v4(),
118            net: net.to_owned(),
119            layer,
120            outline,
121            thermal_gap: DEFAULT_THERMAL_GAP,
122            spoke_width: DEFAULT_SPOKE_WIDTH,
123            min_width: DEFAULT_MIN_WIDTH,
124            fill: vec![],
125        }
126    }
127    /// Filled copper area in square micrometres.
128    pub fn fill_area(&self) -> f64 {
129        // `+ 0.`: an empty float sum is -0.0, which read "-0.0 mm²".
130        self.fill.iter().map(FillPiece::area).sum::<f64>() + 0.
131    }
132    pub(super) fn validate(&self, layer_count: u8) -> Result<(), String> {
133        let valid = |p: &Point| p.x.abs_diff(0) <= 100_000_000 && p.y.abs_diff(0) <= 100_000_000;
134        if self.layer >= layer_count {
135            return Err("A zone is on a copper layer the board does not have".into());
136        }
137        if self.net.trim().is_empty() {
138            return Err("A zone needs a net".into());
139        }
140        if self.outline.len() < 3 || !self.outline.iter().all(valid) || ring_area(&self.outline) == 0. {
141            return Err("A zone's outline needs at least three points enclosing an area".into());
142        }
143        let size = |v: i32| (1..=100_000_000).contains(&v);
144        if !size(self.thermal_gap) || !size(self.spoke_width) || !size(self.min_width) {
145            return Err("A zone's thermal gap, spoke width and minimum width must be positive".into());
146        }
147        let rings = self.fill.iter().flat_map(|p| std::iter::once(&p.outer).chain(&p.holes));
148        for ring in rings {
149            if ring.len() < 3 || !ring.iter().all(valid) {
150                return Err("A zone's fill has a ring of fewer than three valid points".into());
151            }
152        }
153        Ok(())
154    }
155}
156
157/// One connected piece of a zone's fill: its outer ring and the holes in it.
158#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
159pub struct FillPiece {
160    pub outer: Vec<Point>,
161    #[serde(default, skip_serializing_if = "Vec::is_empty")]
162    pub holes: Vec<Vec<Point>>,
163}
164impl FillPiece {
165    /// Whether `p` is copper of this piece: inside the outer ring and in no hole.
166    pub fn contains(&self, p: Point) -> bool {
167        polygon_contains(&self.outer, p) && !self.holes.iter().any(|h| polygon_contains(h, p))
168    }
169    /// Every edge of every ring.
170    pub fn edges(&self) -> impl Iterator<Item = (Point, Point)> + '_ {
171        std::iter::once(&self.outer)
172            .chain(&self.holes)
173            .flat_map(|ring| (0..ring.len()).map(move |i| (ring[i], ring[(i + 1) % ring.len()])))
174    }
175    /// Area in square micrometres.
176    pub fn area(&self) -> f64 {
177        ring_area(&self.outer).abs() - self.holes.iter().map(|h| ring_area(h).abs()).sum::<f64>()
178    }
179    pub fn bounds(&self) -> (Point, Point) {
180        super::bounds_of(&self.outer).unwrap_or_default()
181    }
182    /// The gap between this piece and a copper shape; zero when they touch or overlap.
183    pub fn distance(&self, shape: &Shape) -> f64 {
184        if self.contains(shape.center()) {
185            return 0.;
186        }
187        self.edges()
188            .map(|(a, b)| Shape::segment(a, b, 0).distance(shape))
189            .fold(f64::INFINITY, f64::min)
190    }
191    /// Whether a copper shape touches or overlaps this piece, to within 0.5 µm:
192    /// [`Self::distance`] `<= 0.5`, without measuring the edges that are nowhere
193    /// near it. The board view asks this for every item on the zone's layer on
194    /// every frame, so it pays for the edges beside the shape and no others.
195    pub fn touches(&self, shape: &Shape) -> bool {
196        let (lo, hi) = shape.bounds();
197        let near = |a: Point, b: Point| {
198            a.x.min(b.x) <= hi.x + 1 && a.x.max(b.x) >= lo.x - 1 && a.y.min(b.y) <= hi.y + 1 && a.y.max(b.y) >= lo.y - 1
199        };
200        self.edges()
201            .any(|(a, b)| near(a, b) && Shape::segment(a, b, 0).distance(shape) <= 0.5)
202            || self.contains(shape.center())
203    }
204    /// The gap between two pieces; zero when they touch or overlap.
205    pub fn distance_to_piece(&self, other: &FillPiece) -> f64 {
206        if other.outer.first().is_some_and(|p| self.contains(*p))
207            || self.outer.first().is_some_and(|p| other.contains(*p))
208        {
209            return 0.;
210        }
211        let (min, max) = other.bounds();
212        let mut best = f64::INFINITY;
213        for (a, b) in self.edges() {
214            let edge = Shape::segment(a, b, 0);
215            let (e0, e1) = edge.bounds();
216            let far = f64::from((min.x - e1.x).max(e0.x - max.x).max(min.y - e1.y).max(e0.y - max.y));
217            if far >= best {
218                continue;
219            }
220            for (c, d) in other.edges() {
221                best = best.min(edge.distance(&Shape::segment(c, d, 0)));
222            }
223        }
224        best
225    }
226}
227
228/// The signed area of a ring in square micrometres, positive when it
229/// turns from +x towards +y.
230pub fn ring_area(ring: &[Point]) -> f64 {
231    let mut sum = 0i128;
232    for i in 0..ring.len() {
233        let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
234        sum += i128::from(a.x) * i128::from(b.y) - i128::from(b.x) * i128::from(a.y);
235    }
236    sum as f64 / 2.
237}
238
239/// A through-hole pad of a zone's net and the spokes that join it to the fill.
240#[derive(Clone, Debug, PartialEq)]
241pub struct Thermal {
242    pub owner: CopperRef,
243    pub at: Point,
244    /// Spokes laid, 0 to 4. Zero means the zone does not reach the pad.
245    pub spokes: u8,
246}
247
248/// What one zone's fill did.
249#[derive(Clone, Debug, PartialEq)]
250pub struct ZoneReport {
251    pub zone: Uuid,
252    pub pieces: usize,
253    /// Filled area in square micrometres.
254    pub area: f64,
255    /// Pieces dropped because they touched no copper of the zone's net.
256    pub islands_removed: usize,
257    pub thermals: Vec<Thermal>,
258    /// The grid pitch the fill was computed on, in micrometres.
259    pub pitch: i32,
260    /// Why the zone has no fill at all, when it has none.
261    pub empty_because: Option<String>,
262    /// Netless vias inside this zone that it did NOT stitch, because a zone of
263    /// another net holds them too: each via's centre and the other nets.
264    pub unstitched: Vec<(Point, Vec<String>)>,
265}
266
267/// A via with no net that zones of more than one net hold, and which is therefore
268/// stitched to none of them.
269#[derive(Clone, Debug, PartialEq)]
270pub struct ContestedVia {
271    /// Index into [`Board::vias`].
272    pub via: usize,
273    pub at: Point,
274    /// Every net whose zones hold a via of this via's copper island, in order.
275    pub nets: Vec<String>,
276    /// The zones that hold THIS via, by index into [`Board::zones`].
277    pub zones: Vec<usize>,
278}
279
280/// Which net each netless copper island is stitched to, decided once for the
281/// board: the island's vias, the zones whose polygon holds one of them on a
282/// layer the via reaches, and those zones' nets. `conn` is the connectivity
283/// WITHOUT any fill.
284struct Stitching {
285    /// The island's net, where exactly one net's zones hold its vias.
286    net: HashMap<usize, String>,
287    /// Every net claiming each island that more than one net claims.
288    contested: BTreeMap<usize, BTreeSet<String>>,
289}
290fn holds(zone: &Zone, item: &CopperItem) -> bool {
291    item.layers.0 <= zone.layer && zone.layer <= item.layers.1 && polygon_contains(&zone.outline, item.shape.center())
292}
293fn stitching(board: &Board, conn: &Connectivity) -> Stitching {
294    let mut claims: BTreeMap<usize, BTreeSet<String>> = BTreeMap::new();
295    for (i, item) in conn.items.iter().enumerate() {
296        let island = conn.islands[i];
297        if !matches!(item.owner, CopperRef::Via(_)) || !conn.island_nets[island].is_empty() {
298            continue;
299        }
300        for zone in board.zones.iter().filter(|z| holds(z, item)) {
301            claims.entry(island).or_default().insert(zone.net.clone());
302        }
303    }
304    let mut out = Stitching { net: HashMap::new(), contested: BTreeMap::new() };
305    for (island, nets) in claims {
306        if nets.len() == 1 {
307            out.net.insert(island, nets.into_iter().next().unwrap());
308        } else {
309            out.contested.insert(island, nets);
310        }
311    }
312    out
313}
314
315impl Document {
316    /// Fill every zone of the board against the schematic's nets.
317    pub fn fill_zones(&mut self) -> Vec<ZoneReport> {
318        let netlist = self.netlist();
319        self.board.fill_zones(&netlist)
320    }
321}
322
323impl Board {
324    /// Refill every zone, in the order they were drawn, and say what each fill did.
325    pub fn fill_zones(&mut self, netlist: &Netlist) -> Vec<ZoneReport> {
326        let conn = self.connectivity_of(netlist, false);
327        let stitch = stitching(self, &conn);
328        let mut reports = Vec::with_capacity(self.zones.len());
329        for index in 0..self.zones.len() {
330            let (fill, report) = fill_zone(self, &conn, &stitch, index);
331            self.zones[index].fill = fill;
332            reports.push(report);
333        }
334        reports
335    }
336    /// Whether any zone's fill differs from what a fill now would make.
337    pub fn zones_stale(&self, netlist: &Netlist) -> bool {
338        if self.zones.is_empty() {
339            return false;
340        }
341        let mut fresh = self.clone();
342        fresh.fill_zones(netlist);
343        fresh.zones != self.zones
344    }
345    /// The vias with no net that zones of two or more nets hold, which the fill
346    /// therefore stitches to none of them, in the order of [`Board::vias`].
347    pub fn contested_vias(&self, netlist: &Netlist) -> Vec<ContestedVia> {
348        if self.zones.is_empty() {
349            return vec![];
350        }
351        let conn = self.connectivity_of(netlist, false);
352        let stitch = stitching(self, &conn);
353        let mut out = vec![];
354        for (i, item) in conn.items.iter().enumerate() {
355            let CopperRef::Via(via) = item.owner else { continue };
356            let Some(nets) = stitch.contested.get(&conn.islands[i]) else { continue };
357            let zones: Vec<usize> = (0..self.zones.len()).filter(|&z| holds(&self.zones[z], item)).collect();
358            if !zones.is_empty() {
359                out.push(ContestedVia { via, at: item.shape.center(), nets: nets.iter().cloned().collect(), zones });
360            }
361        }
362        out
363    }
364    /// A design rule finding for each contested via ([`Self::contested_vias`]),
365    /// naming it by where it is and the zones that hold it.
366    pub(super) fn stitching_findings(&self, netlist: &Netlist) -> Vec<super::Violation> {
367        self.contested_vias(netlist)
368            .into_iter()
369            .map(|c| {
370                let zones: Vec<String> = c.zones.iter().map(|&z| describe(&self.zones[z], self.layer_count)).collect();
371                let own: BTreeSet<&str> = c.zones.iter().map(|&z| self.zones[z].net.as_str()).collect();
372                let others: Vec<&str> = c.nets.iter().map(String::as_str).filter(|n| !own.contains(n)).collect();
373                // Held by zones of both nets itself, or by one net's zone and
374                // joined by copper to a via another net's zone holds.
375                let place = if others.is_empty() {
376                    format!("is in both the {}", zones.join(" and the "))
377                } else {
378                    format!(
379                        "is in the {}, and copper joins it to a via in a {} zone",
380                        zones.join(" and the "),
381                        others.join(" and ")
382                    )
383                };
384                super::Violation {
385                    kind: super::ViolationKind::Stitching,
386                    message: format!(
387                        "Via at {:.2}, {:.2} mm has no net and {place}: it is stitched to none of them, \
388                         because that would short {}. Give it a net, or keep it in one net's zones",
389                        f64::from(c.at.x) / 1000.,
390                        f64::from(c.at.y) / 1000.,
391                        c.nets.join(" to ")
392                    ),
393                    at: c.at,
394                }
395            })
396            .collect()
397    }
398}
399
400/// What the field at a sample is made of: the copper to keep clear of, and the
401/// pads to relieve.
402enum Obstacle {
403    /// Other-net copper: keep `clearance` from the shape.
404    Keep(Shape, f64),
405    /// Another zone's outline, taken whole: keep `clearance` from it.
406    Zone(Vec<Point>, f64),
407}
408
409/// Signed distance from `p` to a closed polygon: positive inside.
410fn polygon_depth(polygon: &[Point], p: Point) -> f64 {
411    let n = polygon.len();
412    let d = (0..n)
413        .map(|i| point_segment_distance(p, polygon[i], polygon[(i + 1) % n]))
414        .fold(f64::INFINITY, f64::min);
415    if polygon_contains(polygon, p) { d } else { -d }
416}
417
418/// A sampled scalar field over a rectangle of the board.
419struct Grid {
420    x0: i32,
421    y0: i32,
422    h: i32,
423    nx: usize,
424    ny: usize,
425    v: Vec<f32>,
426}
427impl Grid {
428    fn at(&self, i: usize, j: usize) -> Point {
429        Point::new(self.x0 + i as i32 * self.h, self.y0 + j as i32 * self.h)
430    }
431    fn get(&self, i: usize, j: usize) -> f32 {
432        self.v[j * self.nx + i]
433    }
434    /// The field at any point, bilinear between samples; `-inf` off the grid.
435    fn sample(&self, p: Point) -> f32 {
436        let fx = f64::from(p.x - self.x0) / f64::from(self.h);
437        let fy = f64::from(p.y - self.y0) / f64::from(self.h);
438        if fx < 0. || fy < 0. || fx >= (self.nx - 1) as f64 || fy >= (self.ny - 1) as f64 {
439            return f32::NEG_INFINITY;
440        }
441        let (i, j) = (fx as usize, fy as usize);
442        let (tx, ty) = ((fx - i as f64) as f32, (fy - j as f64) as f32);
443        let top = self.get(i, j) * (1. - tx) + self.get(i + 1, j) * tx;
444        let bottom = self.get(i, j + 1) * (1. - tx) + self.get(i + 1, j + 1) * tx;
445        top * (1. - ty) + bottom * ty
446    }
447}
448
449/// Buckets of obstacles by square cell, so a sample asks only those near it.
450struct Buckets {
451    x0: i32,
452    y0: i32,
453    size: i32,
454    nx: usize,
455    ny: usize,
456    cells: Vec<Vec<u32>>,
457}
458impl Buckets {
459    fn new(min: Point, max: Point, size: i32) -> Self {
460        let nx = ((max.x - min.x) / size + 1).max(1) as usize;
461        let ny = ((max.y - min.y) / size + 1).max(1) as usize;
462        Self { x0: min.x, y0: min.y, size, nx, ny, cells: vec![vec![]; nx * ny] }
463    }
464    fn cell(&self, x: i32, y: i32) -> (usize, usize) {
465        let i = ((x - self.x0).div_euclid(self.size)).clamp(0, self.nx as i32 - 1) as usize;
466        let j = ((y - self.y0).div_euclid(self.size)).clamp(0, self.ny as i32 - 1) as usize;
467        (i, j)
468    }
469    fn insert(&mut self, index: u32, min: Point, max: Point) {
470        let (i0, j0) = self.cell(min.x, min.y);
471        let (i1, j1) = self.cell(max.x, max.y);
472        for j in j0..=j1 {
473            for i in i0..=i1 {
474                self.cells[j * self.nx + i].push(index);
475            }
476        }
477    }
478    fn near(&self, p: Point) -> &[u32] {
479        let (i, j) = self.cell(p.x, p.y);
480        &self.cells[j * self.nx + i]
481    }
482}
483
484/// The net each item's copper island carries, and which vias count as the zone's.
485fn item_net<'a>(conn: &'a Connectivity, i: usize) -> Option<&'a str> {
486    conn.island_net(conn.islands[i])
487}
488
489/// Fill zone `index` of `board`. `conn` is the board's connectivity WITHOUT any
490/// zone's fill, so a stale fill never decides which net a track is on.
491fn fill_zone(board: &Board, conn: &Connectivity, stitch: &Stitching, index: usize) -> (Vec<FillPiece>, ZoneReport) {
492    let zone = &board.zones[index];
493    let mut report = ZoneReport {
494        zone: zone.id,
495        pieces: 0,
496        area: 0.,
497        islands_removed: 0,
498        thermals: vec![],
499        pitch: PITCH,
500        empty_because: None,
501        unstitched: vec![],
502    };
503    let rules = &board.rules;
504    // Each piece of copper is kept clear by the larger of its net's class
505    // clearance and the zone's ([`DesignRules::clearance_between`]); the zone's own
506    // class clearance is the least any obstacle is kept clear by.
507    let own = rules.class_of(Some(zone.net.as_str())).clearance.max(0);
508    let clearance_to = |nets: &BTreeSet<String>| {
509        f64::from(rules.clearance_between_nets([zone.net.as_str()], nets.iter().map(String::as_str)).0)
510    };
511    let gap = f64::from(zone.thermal_gap.max(own));
512    let half_width = f64::from(zone.min_width) / 2.;
513    let spoke_half = f64::from(zone.spoke_width) / 2.;
514    let layer = zone.layer;
515    let on_layer = |item: &CopperItem| item.layers.0 <= layer && layer <= item.layers.1;
516
517    // The rectangle to sample: the zone's bounds within the outline's.
518    let (Some((zmin, zmax)), (omin, omax)) = (super::bounds_of(&zone.outline), board.outline_bounds()) else {
519        report.empty_because = Some("the zone has no outline".into());
520        return (vec![], report);
521    };
522    let min = Point::new(zmin.x.max(omin.x), zmin.y.max(omin.y));
523    let max = Point::new(zmax.x.min(omax.x), zmax.y.min(omax.y));
524    if min.x >= max.x || min.y >= max.y {
525        report.empty_because = Some("the zone is outside the board".into());
526        return (vec![], report);
527    }
528    // A pitch fine enough that a clearance spans two samples, coarse enough that
529    // the grid stays within MAX_SAMPLES.
530    let mut h = PITCH.min((own / 2).max(10));
531    let area = |h: i32| (((max.x - min.x) / h + 3) as usize) * (((max.y - min.y) / h + 3) as usize);
532    while area(h) > MAX_SAMPLES {
533        h *= 2;
534    }
535    report.pitch = h;
536    // What interpolation, the simplification and rounding to whole micrometres can
537    // cost at worst, taken out of the fill: the chord across a cell of a curve of
538    // radius the clearance sags by (√2 h)² / 8r, and the rest is fixed.
539    let radius = f64::from(own.max(h));
540    let margin = (2. * f64::from(h * h) / (8. * radius) + SIMPLIFY + 1. + 1.) as f32;
541
542    // One ring of samples beyond the rectangle on every side, all outside, so every
543    // contour closes.
544    let x0 = min.x - h;
545    let y0 = min.y - h;
546    let nx = ((max.x - min.x) / h + 3) as usize;
547    let ny = ((max.y - min.y) / h + 3) as usize;
548
549    // The copper: what to keep clear of, what to relieve, what is solid.
550    let mut obstacles: Vec<Obstacle> = vec![];
551    let mut thermal_pads: Vec<(CopperRef, Shape)> = vec![];
552    let mut same_net: Vec<usize> = vec![];
553    for (i, item) in conn.items.iter().enumerate() {
554        if !on_layer(item) {
555            continue;
556        }
557        let net = item_net(conn, i);
558        // A netless via in the zone joins it only when its island was given the
559        // zone's net for the whole board ([`stitching`]); one another net's zone
560        // also holds is kept clear of, and said.
561        let island = conn.islands[i];
562        let held = matches!(item.owner, CopperRef::Via(_)) && holds(zone, item);
563        let stitched = held && stitch.net.get(&island) == Some(&zone.net);
564        if held && let Some(nets) = stitch.contested.get(&island) {
565            let others = nets.iter().filter(|n| **n != zone.net).cloned().collect();
566            report.unstitched.push((item.shape.center(), others));
567        }
568        if net == Some(zone.net.as_str()) || stitched {
569            same_net.push(i);
570            if let CopperRef::Pad { placement, pad } = item.owner
571                && board.placements[placement].footprint.pads[pad].drill.is_some()
572            {
573                thermal_pads.push((item.owner, item.shape));
574            }
575        } else {
576            obstacles.push(Obstacle::Keep(item.shape, clearance_to(&conn.island_nets[island])));
577        }
578    }
579    for earlier in &board.zones[..index] {
580        if earlier.layer == layer && earlier.net != zone.net && earlier.outline.len() >= 3 {
581            let clearance = f64::from(rules.clearance_between(Some(zone.net.as_str()), Some(earlier.net.as_str())).0);
582            obstacles.push(Obstacle::Zone(earlier.outline.clone(), clearance));
583        }
584    }
585    let clearance = obstacles
586        .iter()
587        .map(|o| match o {
588            Obstacle::Keep(_, c) | Obstacle::Zone(_, c) => *c,
589        })
590        .fold(f64::from(own), f64::max);
591    // Far from every obstacle the field only needs to be known up to a cap: past
592    // it, nothing the fill decides changes.
593    let cap = (half_width + 4. * f64::from(h)) as f32;
594    let reach = (clearance.max(gap) + f64::from(cap)) as i32 + h;
595    let mut buckets = Buckets::new(Point::new(x0, y0), Point::new(x0 + nx as i32 * h, y0 + ny as i32 * h), 1000);
596    for (k, obstacle) in obstacles.iter().enumerate() {
597        let (lo, hi) = match obstacle {
598            Obstacle::Keep(shape, _) => shape.bounds(),
599            Obstacle::Zone(outline, _) => super::bounds_of(outline).unwrap_or_default(),
600        };
601        buckets.insert(k as u32, Point::new(lo.x - reach, lo.y - reach), Point::new(hi.x + reach, hi.y + reach));
602    }
603    let mut relief = Buckets::new(Point::new(x0, y0), Point::new(x0 + nx as i32 * h, y0 + ny as i32 * h), 1000);
604    for (k, (_, shape)) in thermal_pads.iter().enumerate() {
605        let (lo, hi) = shape.bounds();
606        relief.insert(k as u32, Point::new(lo.x - reach, lo.y - reach), Point::new(hi.x + reach, hi.y + reach));
607    }
608
609    // The base field: how far inside the fill region each sample is, before the
610    // thermal gaps, and the thermal gaps.
611    let edge_clearance = f64::from(rules.edge_clearance);
612    let keep = |p: Point| -> f32 {
613        let mut v = polygon_depth(&zone.outline, p).min(polygon_depth(&board.outline, p) - edge_clearance) as f32;
614        for &k in buckets.near(p) {
615            let d = match &obstacles[k as usize] {
616                Obstacle::Keep(shape, c) => shape.distance_to_point(p) - c,
617                Obstacle::Zone(outline, c) => -polygon_depth(outline, p) - c,
618            };
619            v = v.min(d as f32);
620        }
621        v.min(cap)
622    };
623    let mut base = Grid { x0, y0, h, nx, ny, v: vec![f32::NEG_INFINITY; nx * ny] };
624    let mut clear = vec![f32::NEG_INFINITY; nx * ny];
625    for j in 1..ny - 1 {
626        for i in 1..nx - 1 {
627            let p = base.at(i, j);
628            let k = keep(p);
629            let mut v = k;
630            for &t in relief.near(p) {
631                v = v.min((thermal_pads[t as usize].1.distance_to_point(p) - gap) as f32);
632            }
633            clear[j * nx + i] = k - margin;
634            base.v[j * nx + i] = v - margin;
635        }
636    }
637
638    // Open by the minimum width: a sample stays where some sample at least half the
639    // width deep is within half the width of it, measured to the edge of that deep
640    // sample's own disc (the field is a distance, so a sample `d` deep has a disc of
641    // radius `d - w/2` that is all deep).
642    let window = ((half_width + 2. * f64::from(h)) / f64::from(h)).ceil() as isize;
643    let mut opened = base.v.clone();
644    let deep = |v: f32| f64::from(v) >= half_width;
645    for j in 1..ny - 1 {
646        for i in 1..nx - 1 {
647            let v = base.v[j * nx + i];
648            if v < 0. || deep(v) {
649                continue;
650            }
651            let mut best = f64::INFINITY;
652            for dj in -window..=window {
653                for di in -window..=window {
654                    let (a, b) = (i as isize + di, j as isize + dj);
655                    if a < 0 || b < 0 || a >= nx as isize || b >= ny as isize {
656                        continue;
657                    }
658                    let q = base.v[b as usize * nx + a as usize];
659                    if !deep(q) {
660                        continue;
661                    }
662                    let dist = f64::from(h) * ((di * di + dj * dj) as f64).sqrt();
663                    best = best.min(dist - (f64::from(q) - half_width));
664                }
665            }
666            // Slack of a micrometre so a wide region's own edge is not nibbled.
667            let reach = (half_width - best + 1.) as f32;
668            opened[j * nx + i] = v.min(reach);
669        }
670    }
671    let mut field = Grid { v: opened, ..base };
672
673    // Spokes: from each relieved pad's centre out along ±x and ±y, through the gap
674    // and a spoke's width into the fill, laid only where the fill is there to meet.
675    for (owner, shape) in &thermal_pads {
676        let (lo, hi) = shape.bounds();
677        let centre = shape.center();
678        let half = [(hi.x - lo.x) / 2, (hi.y - lo.y) / 2];
679        let mut spokes = 0u8;
680        for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
681            let extent = f64::from(if dx != 0 { half[0] } else { half[1] });
682            let meet = extent + gap + spoke_half.max(f64::from(h));
683            let probe = Point::new(centre.x + (dx as f64 * meet) as i32, centre.y + (dy as f64 * meet) as i32);
684            if field.sample(probe) <= 0. {
685                continue;
686            }
687            let length = extent + gap + 2. * spoke_half;
688            let end = Point::new(centre.x + (dx as f64 * length) as i32, centre.y + (dy as f64 * length) as i32);
689            let spoke = Shape::segment(centre, end, zone.spoke_width);
690            let (s0, s1) = spoke.bounds();
691            let i0 = ((s0.x - x0) / h - 1).max(1) as usize;
692            let j0 = ((s0.y - y0) / h - 1).max(1) as usize;
693            let i1 = (((s1.x - x0) / h + 2) as usize).min(nx - 2);
694            let j1 = (((s1.y - y0) / h + 2) as usize).min(ny - 2);
695            for j in j0..=j1 {
696                for i in i0..=i1 {
697                    let p = field.at(i, j);
698                    let s = (spoke_half - point_segment_distance(p, centre, end)) as f32;
699                    let v = s.min(clear[j * nx + i] + margin) - margin;
700                    let cell = &mut field.v[j * nx + i];
701                    *cell = cell.max(v);
702                }
703            }
704            spokes += 1;
705        }
706        report.thermals.push(Thermal { owner: *owner, at: centre, spokes });
707    }
708
709    // Trace, sort into pieces, drop the islands.
710    let rings = contour(&field);
711    let mut outers: Vec<Vec<Point>> = vec![];
712    let mut holes: Vec<Vec<Point>> = vec![];
713    for ring in rings {
714        let ring = simplify_ring(&ring, SIMPLIFY);
715        if ring.len() < 3 {
716            continue;
717        }
718        let ring: Vec<Point> = ring
719            .iter()
720            .map(|&(x, y)| Point::new(x.round() as i32, y.round() as i32))
721            .collect();
722        let ring = super::simplify_path(ring);
723        let area = ring_area(&ring);
724        if area > 0. {
725            outers.push(ring);
726        } else if area < 0. {
727            holes.push(ring);
728        }
729    }
730    let mut pieces: Vec<FillPiece> = outers
731        .into_iter()
732        .map(|outer| FillPiece { outer, holes: vec![] })
733        .collect();
734    // Each hole goes to the smallest outer ring that holds it.
735    for hole in holes {
736        let probe = hole[0];
737        let owner = pieces
738            .iter()
739            .enumerate()
740            .filter(|(_, p)| polygon_contains(&p.outer, probe))
741            .min_by(|a, b| ring_area(&a.1.outer).total_cmp(&ring_area(&b.1.outer)))
742            .map(|(k, _)| k);
743        if let Some(k) = owner {
744            pieces[k].holes.push(hole);
745        }
746    }
747    let before = pieces.len();
748    pieces.retain(|piece| {
749        let (pmin, pmax) = piece.bounds();
750        same_net.iter().any(|&i| {
751            let (lo, hi) = conn.items[i].shape.bounds();
752            lo.x <= pmax.x && hi.x >= pmin.x && lo.y <= pmax.y && hi.y >= pmin.y
753                && piece.touches(&conn.items[i].shape)
754        })
755    });
756    report.islands_removed = before - pieces.len();
757    // Largest first: the order a painter draws them in, and the one they are read in.
758    pieces.sort_by(|a, b| b.area().total_cmp(&a.area()));
759    report.pieces = pieces.len();
760    report.area = pieces.iter().map(FillPiece::area).sum::<f64>() + 0.;
761    if pieces.is_empty() {
762        report.empty_because = Some(if before > 0 {
763            format!(
764                "no piece of it reaches any {0} copper (a pad, track or via of {0}), and a piece that joins nothing is an island, which is removed",
765                zone.net
766            )
767        } else {
768            "nothing is left of it once the clearances to other copper and to the board edge are kept".into()
769        });
770    }
771    (pieces, report)
772}
773
774/// The zero contour of a field, as closed rings in board micrometres, the fill
775/// (the positive side) on the left of each: outer rings turn positively, holes
776/// negatively. Marching squares, with each crossing interpolated along its grid
777/// edge and a saddle resolved by the cell's mean.
778fn contour(grid: &Grid) -> Vec<Vec<(f64, f64)>> {
779    let (nx, ny) = (grid.nx, grid.ny);
780    let value = |i: usize, j: usize| {
781        let v = grid.get(i, j);
782        if v == 0. { -1e-6 } else { v }
783    };
784    // Edge ids: 2·(j·nx + i) is the edge from sample (i, j) to (i+1, j); one more is
785    // the edge from (i, j) to (i, j+1).
786    let horizontal = |i: usize, j: usize| 2 * (j * nx + i);
787    let vertical = |i: usize, j: usize| 2 * (j * nx + i) + 1;
788    let point = |edge: usize| -> (f64, f64) {
789        let cell = edge / 2;
790        let (i, j) = (cell % nx, cell / nx);
791        let (i2, j2) = if edge % 2 == 0 { (i + 1, j) } else { (i, j + 1) };
792        let (va, vb) = (f64::from(value(i, j)), f64::from(value(i2, j2)));
793        let t = va / (va - vb);
794        let (a, b) = (grid.at(i, j), grid.at(i2, j2));
795        (
796            f64::from(a.x) + t * f64::from(b.x - a.x),
797            f64::from(a.y) + t * f64::from(b.y - a.y),
798        )
799    };
800    let mut next: HashMap<usize, usize> = HashMap::new();
801    for j in 0..ny - 1 {
802        for i in 0..nx - 1 {
803            let c = [value(i, j), value(i + 1, j), value(i + 1, j + 1), value(i, j + 1)];
804            let inside = c.map(|v| v > 0.);
805            let case = inside.iter().enumerate().fold(0, |acc, (k, &b)| acc | (usize::from(b) << k));
806            if case == 0 || case == 15 {
807                continue;
808            }
809            let edges = [horizontal(i, j), vertical(i + 1, j), horizontal(i, j + 1), vertical(i, j)];
810            // Edge k runs from corner k to corner k+1: an exit where the fill ends
811            // along it, an entry where it starts.
812            let exits: Vec<usize> = (0..4).filter(|&k| inside[k] && !inside[(k + 1) % 4]).collect();
813            if exits.len() == 1 {
814                let entry = (0..4).find(|&k| !inside[k] && inside[(k + 1) % 4]).unwrap();
815                next.insert(edges[exits[0]], edges[entry]);
816            } else {
817                let joined = c.iter().map(|&v| f64::from(v)).sum::<f64>() > 0.;
818                for &k in &exits {
819                    let entry = if joined { (k + 1) % 4 } else { (k + 3) % 4 };
820                    next.insert(edges[k], edges[entry]);
821                }
822            }
823        }
824    }
825    let mut starts: Vec<usize> = next.keys().copied().collect();
826    starts.sort_unstable();
827    let mut seen = std::collections::HashSet::new();
828    let mut rings = vec![];
829    for start in starts {
830        if seen.contains(&start) {
831            continue;
832        }
833        let mut ring = vec![];
834        let mut edge = start;
835        loop {
836            if !seen.insert(edge) {
837                break;
838            }
839            ring.push(point(edge));
840            match next.get(&edge) {
841                Some(&n) => edge = n,
842                None => break,
843            }
844        }
845        if ring.len() >= 3 {
846            rings.push(ring);
847        }
848    }
849    rings
850}
851
852/// A closed ring simplified to within `tolerance`: Douglas–Peucker on the two
853/// halves between the first point and the point farthest from it.
854fn simplify_ring(ring: &[(f64, f64)], tolerance: f64) -> Vec<(f64, f64)> {
855    if ring.len() < 4 {
856        return ring.to_vec();
857    }
858    let d2 = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).powi(2) + (a.1 - b.1).powi(2);
859    let far = (1..ring.len())
860        .max_by(|&a, &b| d2(ring[0], ring[a]).total_cmp(&d2(ring[0], ring[b])))
861        .unwrap();
862    let mut keep = vec![false; ring.len()];
863    keep[0] = true;
864    keep[far] = true;
865    let closed: Vec<(f64, f64)> = ring.iter().copied().chain(std::iter::once(ring[0])).collect();
866    let mut stack = vec![(0, far), (far, ring.len())];
867    while let Some((a, b)) = stack.pop() {
868        if b <= a + 1 {
869            continue;
870        }
871        let (pa, pb) = (closed[a], closed[b]);
872        let (dx, dy) = (pb.0 - pa.0, pb.1 - pa.1);
873        let len = dx.hypot(dy);
874        let mut worst = (0., a);
875        for (k, &p) in closed.iter().enumerate().take(b).skip(a + 1) {
876            let d = if len < 1e-9 {
877                (p.0 - pa.0).hypot(p.1 - pa.1)
878            } else {
879                ((p.0 - pa.0) * dy - (p.1 - pa.1) * dx).abs() / len
880            };
881            if d > worst.0 {
882                worst = (d, k);
883            }
884        }
885        if worst.0 > tolerance {
886            keep[worst.1] = true;
887            stack.push((a, worst.1));
888            stack.push((worst.1, b));
889        }
890    }
891    ring.iter().zip(keep).filter(|(_, k)| *k).map(|(p, _)| *p).collect()
892}
893
894/// Trapezoids covering a set of rings by the even-odd rule, as triangles: each
895/// strip between two consecutive vertex heights is cut where the rings' edges
896/// cross it and filled between alternate crossings. Robust for any rings that do
897/// not cross one another, holes included, which is what a fill is — and what
898/// neither a fan nor ear clipping without hole bridging can draw.
899///
900/// The triangles are WATERTIGHT: where a strip meets the next, each side's edge
901/// is split at every point the other side has on that line, and every point is
902/// computed once, so two neighbouring triangles share their corners exactly and
903/// no edge inside the fill is used by one triangle alone (the 3D view outlines a
904/// hovered face by exactly those edges). A trapezoid with points on its top or
905/// bottom edge is fanned from its centre.
906pub fn fill_triangles(rings: &[&[Point]]) -> Vec<[(f64, f64); 3]> {
907    type Edge = ((f64, f64), (f64, f64));
908    let mut edges: Vec<Edge> = vec![];
909    let mut ys: Vec<i32> = vec![];
910    for ring in rings {
911        for i in 0..ring.len() {
912            let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
913            ys.push(a.y);
914            if a.y != b.y {
915                let (a, b) = if a.y < b.y { (a, b) } else { (b, a) };
916                edges.push(((f64::from(a.x), f64::from(a.y)), (f64::from(b.x), f64::from(b.y))));
917            }
918        }
919    }
920    ys.sort_unstable();
921    ys.dedup();
922    edges.sort_by(|a, b| a.0.1.total_cmp(&b.0.1));
923    // An edge's x at `y`, EXACT at both of its ends, so the edge that ends at a
924    // vertex and the one that starts there agree on it to the bit.
925    let x_at = |e: &Edge, y: f64| {
926        if y == e.0.1 {
927            e.0.0
928        } else if y == e.1.1 {
929            e.1.0
930        } else {
931            e.0.0 + (e.1.0 - e.0.0) * (y - e.0.1) / (e.1.1 - e.0.1)
932        }
933    };
934    // Each strip's filled spans: (x left, x right) at its top and at its bottom.
935    let mut strips: Vec<Vec<[f64; 4]>> = Vec::with_capacity(ys.len());
936    let mut active: Vec<usize> = vec![];
937    let mut next_edge = 0;
938    for w in ys.windows(2) {
939        let (top, bottom) = (f64::from(w[0]), f64::from(w[1]));
940        while next_edge < edges.len() && edges[next_edge].0.1 <= top {
941            active.push(next_edge);
942            next_edge += 1;
943        }
944        active.retain(|&e| edges[e].1.1 > top);
945        let mid = (top + bottom) / 2.;
946        let mut crossing: Vec<(f64, usize)> = active
947            .iter()
948            .filter(|&&e| edges[e].0.1 <= top && edges[e].1.1 >= bottom)
949            .map(|&e| (x_at(&edges[e], mid), e))
950            .collect();
951        crossing.sort_by(|a, b| a.0.total_cmp(&b.0));
952        strips.push(
953            crossing
954                .chunks_exact(2)
955                .map(|pair| {
956                    let (l, r) = (&edges[pair[0].1], &edges[pair[1].1]);
957                    [x_at(l, top), x_at(r, top), x_at(l, bottom), x_at(r, bottom)]
958                })
959                .collect(),
960        );
961    }
962    // Every point on each horizontal line, from the strips on both sides of it.
963    let mut lines: Vec<Vec<f64>> = vec![vec![]; ys.len()];
964    for (k, spans) in strips.iter().enumerate() {
965        for span in spans {
966            lines[k].extend([span[0], span[1]]);
967            lines[k + 1].extend([span[2], span[3]]);
968        }
969    }
970    for line in &mut lines {
971        line.sort_by(f64::total_cmp);
972        line.dedup();
973    }
974    let mut out = vec![];
975    for (k, spans) in strips.iter().enumerate() {
976        let (top, bottom) = (f64::from(ys[k]), f64::from(ys[k + 1]));
977        for &[lt, rt, lb, rb] in spans {
978            let mut polygon: Vec<(f64, f64)> = vec![(lt, top)];
979            polygon.extend(lines[k].iter().filter(|&&x| x > lt && x < rt).map(|&x| (x, top)));
980            polygon.push((rt, top));
981            polygon.push((rb, bottom));
982            polygon.extend(lines[k + 1].iter().rev().filter(|&&x| x > lb && x < rb).map(|&x| (x, bottom)));
983            polygon.push((lb, bottom));
984            polygon.dedup();
985            if polygon.len() > 1 && polygon.first() == polygon.last() {
986                polygon.pop();
987            }
988            let area2 = |a: (f64, f64), b: (f64, f64), c: (f64, f64)| {
989                ((b.0 - a.0) * (c.1 - a.1) - (b.1 - a.1) * (c.0 - a.0)).abs()
990            };
991            if polygon.len() == 3 {
992                if area2(polygon[0], polygon[1], polygon[2]) > 0. {
993                    out.push([polygon[0], polygon[1], polygon[2]]);
994                }
995            } else if polygon.len() == 4 {
996                for tri in [[polygon[0], polygon[1], polygon[2]], [polygon[0], polygon[2], polygon[3]]] {
997                    if area2(tri[0], tri[1], tri[2]) > 0. {
998                        out.push(tri);
999                    }
1000                }
1001            } else if polygon.len() > 4 {
1002                let n = polygon.len() as f64;
1003                let centre = (
1004                    polygon.iter().map(|p| p.0).sum::<f64>() / n,
1005                    polygon.iter().map(|p| p.1).sum::<f64>() / n,
1006                );
1007                for i in 0..polygon.len() {
1008                    let tri = [centre, polygon[i], polygon[(i + 1) % polygon.len()]];
1009                    if area2(tri[0], tri[1], tri[2]) > 0. {
1010                        out.push(tri);
1011                    }
1012                }
1013            }
1014        }
1015    }
1016    out
1017}
1018
1019/// A piece's rings as ONE ring, each hole joined to the outside by a cut-in: a
1020/// zero-width slit from the hole's leftmost vertex straight left to the nearest
1021/// edge, walked in and back out. The way a Gerber region carries a hole without a
1022/// clear-polarity step (which would also clear any copper drawn before it).
1023/// The outer ring comes out turning positively and each hole negatively.
1024pub fn fractured(piece: &FillPiece) -> Vec<Point> {
1025    let mut outer = piece.outer.clone();
1026    if ring_area(&outer) < 0. {
1027        outer.reverse();
1028    }
1029    let mut holes: Vec<Vec<Point>> = piece
1030        .holes
1031        .iter()
1032        .map(|h| {
1033            let mut h = h.clone();
1034            if ring_area(&h) > 0. {
1035                h.reverse();
1036            }
1037            // Start each hole at its leftmost vertex.
1038            let k = (0..h.len()).min_by_key(|&k| (h[k].x, h[k].y)).unwrap_or(0);
1039            h.rotate_left(k);
1040            h
1041        })
1042        .collect();
1043    holes.sort_by_key(|h| (h[0].x, h[0].y));
1044    for hole in holes {
1045        let v = hole[0];
1046        // The nearest edge of the ring so far that the ray from `v` leftwards meets.
1047        let mut best: Option<(f64, usize, Point)> = None;
1048        let n = outer.len();
1049        for i in 0..n {
1050            let (a, b) = (outer[i], outer[(i + 1) % n]);
1051            // Half-open, so a ring vertex level with `v` is met once.
1052            if (a.y <= v.y) == (b.y <= v.y) {
1053                continue;
1054            }
1055            let t = f64::from(v.y - a.y) / f64::from(b.y - a.y);
1056            let x = f64::from(a.x) + t * f64::from(b.x - a.x);
1057            if x > f64::from(v.x) {
1058                continue;
1059            }
1060            let d = f64::from(v.x) - x;
1061            if best.is_none_or(|(bd, ..)| d < bd) {
1062                best = Some((d, i, Point::new(x.round() as i32, v.y)));
1063            }
1064        }
1065        let Some((_, i, at)) = best else { continue };
1066        let mut spliced = Vec::with_capacity(n + hole.len() + 3);
1067        spliced.extend_from_slice(&outer[..=i]);
1068        if outer[i] != at {
1069            spliced.push(at);
1070        }
1071        spliced.extend(hole.iter().copied());
1072        spliced.push(v);
1073        spliced.push(at);
1074        spliced.extend_from_slice(&outer[i + 1..]);
1075        outer = spliced;
1076    }
1077    outer
1078}
1079
1080/// A zone's settings as a line: "GND on B.Cu".
1081pub fn describe(zone: &Zone, layer_count: u8) -> String {
1082    format!("{} zone on {}", zone.net, super::layer_name(zone.layer, layer_count))
1083}