1use 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
69pub const DEFAULT_THERMAL_GAP: i32 = 500;
71pub const DEFAULT_SPOKE_WIDTH: i32 = 500;
73pub const DEFAULT_MIN_WIDTH: i32 = 250;
75pub const PITCH: i32 = 50;
77pub const SIMPLIFY: f64 = 2.;
79const 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct Zone {
96 pub id: Uuid,
97 pub net: String,
99 pub layer: u8,
100 pub outline: Vec<Point>,
102 #[serde(default = "default_thermal_gap")]
104 pub thermal_gap: i32,
105 #[serde(default = "default_spoke_width")]
106 pub spoke_width: i32,
107 #[serde(default = "default_min_width")]
109 pub min_width: i32,
110 #[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 pub fn fill_area(&self) -> f64 {
129 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#[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 pub fn contains(&self, p: Point) -> bool {
167 polygon_contains(&self.outer, p) && !self.holes.iter().any(|h| polygon_contains(h, p))
168 }
169 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 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 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 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 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
228pub 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#[derive(Clone, Debug, PartialEq)]
241pub struct Thermal {
242 pub owner: CopperRef,
243 pub at: Point,
244 pub spokes: u8,
246}
247
248#[derive(Clone, Debug, PartialEq)]
250pub struct ZoneReport {
251 pub zone: Uuid,
252 pub pieces: usize,
253 pub area: f64,
255 pub islands_removed: usize,
257 pub thermals: Vec<Thermal>,
258 pub pitch: i32,
260 pub empty_because: Option<String>,
262 pub unstitched: Vec<(Point, Vec<String>)>,
265}
266
267#[derive(Clone, Debug, PartialEq)]
270pub struct ContestedVia {
271 pub via: usize,
273 pub at: Point,
274 pub nets: Vec<String>,
276 pub zones: Vec<usize>,
278}
279
280struct Stitching {
285 net: HashMap<usize, String>,
287 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 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 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 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 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 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 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
400enum Obstacle {
403 Keep(Shape, f64),
405 Zone(Vec<Point>, f64),
407}
408
409fn 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
418struct 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 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
449struct 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
484fn item_net<'a>(conn: &'a Connectivity, i: usize) -> Option<&'a str> {
486 conn.island_net(conn.islands[i])
487}
488
489fn 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 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 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 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 let radius = f64::from(own.max(h));
540 let margin = (2. * f64::from(h * h) / (8. * radius) + SIMPLIFY + 1. + 1.) as f32;
541
542 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 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 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 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 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 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 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 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 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 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 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
774fn 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 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 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
852fn 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
894pub 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 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 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 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
1019pub 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 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 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 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
1080pub fn describe(zone: &Zone, layer_count: u8) -> String {
1082 format!("{} zone on {}", zone.net, super::layer_name(zone.layer, layer_count))
1083}