Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_fab/
designator_fit.rs

1//! Canonical source-neutral assembly-designator fitting shared by `FabView`
2//! virtual layers (`ASSEMBLY_DESIGNATORS_*`) and `kcr pcb-svg` / `toon`.
3//!
4//! Matches `pcbe`'s primary `assembly.rs` fitter: hole-preserving `MultiPolygon`
5//! containment, deterministic multi-center candidate search (centroid, interior
6//! point, bbox center, per-part centers, 3x3 interior grid), 12-step binary
7//! search, and an explicit horizontal (`0 deg`) tie-breaker on equal/square fits.
8
9use std::collections::HashMap;
10
11use geo::{
12    Area, BooleanOps, BoundingRect, Centroid, ConvexHull, Coord, Covers, InteriorPoint, LineString,
13    MultiPolygon, Point, Polygon, Rect, Translate, algorithm::bool_ops::unary_union,
14};
15
16const TEXT_ADVANCE_PER_CHARACTER: f64 = 0.62;
17const CENTER_GRID_DIVISIONS: usize = 4;
18const BINARY_SEARCH_STEPS: usize = 12;
19/// Minimum component aspect ratio (`long / short`) required before an oblique
20/// component (e.g. `45 deg`) rotates its designator off horizontal/orthogonal.
21pub const DEFAULT_OBLIQUE_MIN_ASPECT_RATIO: f64 = 1.2;
22
23/// One fitted component designator placement in millimetres (`+Y` up or canvas space).
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct DesignatorFit {
26    pub center_mm: [f64; 2],
27    pub font_size_mm: f64,
28    pub rotation_degrees: f64,
29}
30
31#[derive(Clone, Debug, Eq, Hash, PartialEq)]
32struct FitKey {
33    geometry: Vec<i64>,
34    text_aspect: i64,
35    rotations: Vec<i64>,
36    fill_ratio: i64,
37    maximum_font_size_mm: i64,
38}
39
40/// Relative-fit memoization session for fitting designators across a board.
41#[derive(Default)]
42pub struct DesignatorFitSession {
43    fits: HashMap<FitKey, Option<DesignatorFit>>,
44    pub requests: usize,
45    pub hits: usize,
46    pub misses: usize,
47}
48
49impl DesignatorFitSession {
50    /// Fit `designator` inside `region` (preserving voids/holes) using
51    /// [`DEFAULT_OBLIQUE_MIN_ASPECT_RATIO`].
52    pub fn fit(
53        &mut self,
54        designator: &str,
55        region: &MultiPolygon<f64>,
56        fill_ratio: f64,
57        maximum_font_size_mm: f64,
58        auto_base_rotation_degrees: f64,
59        manual_rotation_degrees: Option<f64>,
60    ) -> Option<DesignatorFit> {
61        self.fit_with_oblique_min_aspect_ratio(
62            designator,
63            region,
64            fill_ratio,
65            maximum_font_size_mm,
66            auto_base_rotation_degrees,
67            manual_rotation_degrees,
68            DEFAULT_OBLIQUE_MIN_ASPECT_RATIO,
69        )
70    }
71
72    /// Fit `designator` inside `region` (preserving voids/holes) with an
73    /// explicit `oblique_min_aspect_ratio` threshold (`<= 1.0` always aligns
74    /// oblique parts with the component axes).
75    #[allow(
76        clippy::too_many_arguments,
77        reason = "mirrors fit() with the optional oblique_min_aspect_ratio threshold"
78    )]
79    pub fn fit_with_oblique_min_aspect_ratio(
80        &mut self,
81        designator: &str,
82        region: &MultiPolygon<f64>,
83        fill_ratio: f64,
84        maximum_font_size_mm: f64,
85        auto_base_rotation_degrees: f64,
86        manual_rotation_degrees: Option<f64>,
87        oblique_min_aspect_ratio: f64,
88    ) -> Option<DesignatorFit> {
89        self.requests += 1;
90        if !fill_ratio.is_finite()
91            || !maximum_font_size_mm.is_finite()
92            || !auto_base_rotation_degrees.is_finite()
93            || !oblique_min_aspect_ratio.is_finite()
94            || manual_rotation_degrees.is_some_and(|r| !r.is_finite())
95        {
96            return None;
97        }
98        let bounds = region.bounding_rect()?;
99        if !bounds.min().x.is_finite()
100            || !bounds.min().y.is_finite()
101            || !bounds.max().x.is_finite()
102            || !bounds.max().y.is_finite()
103        {
104            return None;
105        }
106        let anchor = [bounds.min().x, bounds.min().y];
107        let relative = region.translate(-anchor[0], -anchor[1]);
108        let min_oblique_ar = oblique_min_aspect_ratio.max(1.0);
109        let rotations = match manual_rotation_degrees {
110            Some(rotation) => vec![normalize_designator_axis(rotation)],
111            None => {
112                let primary = normalize_designator_axis(auto_base_rotation_degrees);
113                let secondary = normalize_designator_axis(primary + 90.0);
114                let is_oblique = primary.abs() > 1.0e-3 && (primary.abs() - 90.0).abs() > 1.0e-3;
115                if is_oblique
116                    && min_oblique_ar > 1.0
117                    && region_axis_aspect_ratio(&relative, primary) < min_oblique_ar
118                {
119                    vec![0.0, -90.0]
120                } else if (primary - secondary).abs() <= 1.0e-9 {
121                    vec![primary]
122                } else {
123                    vec![primary, secondary]
124                }
125            }
126        };
127        let text_aspect = (designator.chars().count() as f64 * TEXT_ADVANCE_PER_CHARACTER).max(1.0);
128        let key = FitKey {
129            geometry: geometry_key(&relative),
130            text_aspect: quantize(text_aspect),
131            rotations: rotations.iter().copied().map(quantize).collect(),
132            fill_ratio: quantize(fill_ratio.clamp(0.05, 1.0)),
133            maximum_font_size_mm: quantize(maximum_font_size_mm.max(0.0)),
134        };
135        let relative_fit = if let Some(cached) = self.fits.get(&key) {
136            self.hits += 1;
137            *cached
138        } else {
139            self.misses += 1;
140            let fitted = fit_uncached(
141                &relative,
142                text_aspect,
143                fill_ratio.clamp(0.05, 1.0),
144                maximum_font_size_mm.max(0.0),
145                &rotations,
146            );
147            self.fits.insert(key, fitted);
148            fitted
149        }?;
150        Some(DesignatorFit {
151            center_mm: [
152                relative_fit.center_mm[0] + anchor[0],
153                relative_fit.center_mm[1] + anchor[1],
154            ],
155            ..relative_fit
156        })
157    }
158}
159
160/// Normalize an orientation angle into `[-90, 90)` degrees.
161#[must_use]
162pub fn normalize_designator_axis(angle_degrees: f64) -> f64 {
163    let normalized = (angle_degrees + 90.0).rem_euclid(180.0) - 90.0;
164    if normalized.abs() <= 1.0e-12 {
165        0.0
166    } else {
167        normalized
168    }
169}
170
171/// Combine already-closed projected rings with SVG's even-odd rule per layer,
172/// then union the visible layers into one annotation region.
173#[must_use]
174pub fn region_from_evenodd_layers(
175    layers: impl IntoIterator<Item = Vec<Vec<[f64; 2]>>>,
176) -> Option<MultiPolygon<f64>> {
177    let mut visible_layers = Vec::new();
178    for rings in layers {
179        let mut layer = MultiPolygon::new(Vec::new());
180        for ring in rings {
181            let Some(polygon) = ring_polygon(&ring) else {
182                continue;
183            };
184            layer = if layer.0.is_empty() {
185                MultiPolygon::new(vec![polygon])
186            } else {
187                layer.xor(&polygon)
188            };
189        }
190        if !layer.0.is_empty() {
191            visible_layers.push(layer);
192        }
193    }
194    if visible_layers.is_empty() {
195        None
196    } else {
197        Some(unary_union(&visible_layers))
198    }
199}
200
201/// Convex hull envelope over a component's pad polygons.
202#[must_use]
203pub fn pad_envelope(polygons: &[Polygon<f64>]) -> Option<MultiPolygon<f64>> {
204    if polygons.is_empty() {
205        return None;
206    }
207    Some(MultiPolygon::new(polygons.to_vec()).convex_hull().into())
208}
209
210/// Build a valid positive-area polygon from a ring of 2D mm coordinates.
211#[must_use]
212pub fn ring_polygon(points: &[[f64; 2]]) -> Option<Polygon<f64>> {
213    if points.len() < 3
214        || points
215            .iter()
216            .any(|p| !p[0].is_finite() || !p[1].is_finite())
217    {
218        return None;
219    }
220    let mut coordinates = points
221        .iter()
222        .map(|point| Coord {
223            x: point[0],
224            y: point[1],
225        })
226        .collect::<Vec<_>>();
227    if coordinates.first() != coordinates.last() {
228        coordinates.push(coordinates[0]);
229    }
230    let polygon = Polygon::new(LineString::new(coordinates), Vec::new());
231    (polygon.unsigned_area() > 1.0e-12).then_some(polygon)
232}
233
234/// Subtract board cutouts from an annotation region so labels never sit over empty air.
235#[must_use]
236pub fn subtract_cutouts(
237    region: &MultiPolygon<f64>,
238    cutouts: &MultiPolygon<f64>,
239) -> Option<MultiPolygon<f64>> {
240    if cutouts.0.is_empty() {
241        return Some(region.clone());
242    }
243    let clipped = region.difference(cutouts);
244    (!clipped.0.is_empty()).then_some(clipped)
245}
246
247fn region_axis_aspect_ratio(region: &MultiPolygon<f64>, axis_degrees: f64) -> f64 {
248    let (sin, cos) = (-axis_degrees).to_radians().sin_cos();
249    let mut min_x = f64::INFINITY;
250    let mut max_x = f64::NEG_INFINITY;
251    let mut min_y = f64::INFINITY;
252    let mut max_y = f64::NEG_INFINITY;
253    for poly in &region.0 {
254        for coord in poly.exterior().coords() {
255            let lx = coord.x * cos - coord.y * sin;
256            let ly = coord.x * sin + coord.y * cos;
257            min_x = min_x.min(lx);
258            max_x = max_x.max(lx);
259            min_y = min_y.min(ly);
260            max_y = max_y.max(ly);
261        }
262    }
263    if !min_x.is_finite() {
264        return 1.0;
265    }
266    let w = max_x - min_x;
267    let h = max_y - min_y;
268    let short_side = w.min(h);
269    if short_side <= 1.0e-9 {
270        return f64::INFINITY;
271    }
272    w.max(h) / short_side
273}
274
275fn fit_uncached(
276    region: &MultiPolygon<f64>,
277    text_aspect: f64,
278    fill_ratio: f64,
279    maximum_font_size_mm: f64,
280    rotations: &[f64],
281) -> Option<DesignatorFit> {
282    let centers = candidate_centers(region);
283    let mut best = None;
284    for &rotation in rotations {
285        let (raw_font, center) =
286            largest_font_at_candidates(region, &centers, text_aspect, rotation)?;
287        let candidate = DesignatorFit {
288            center_mm: center,
289            font_size_mm: maximum_font_size_mm.min(raw_font * fill_ratio),
290            rotation_degrees: rotation,
291        };
292        if candidate.font_size_mm <= 0.0 {
293            continue;
294        }
295        if best.is_none_or(|current: DesignatorFit| {
296            candidate.font_size_mm > current.font_size_mm + 1.0e-6
297                || ((candidate.font_size_mm - current.font_size_mm).abs() <= 1.0e-6
298                    && candidate.rotation_degrees.abs() < current.rotation_degrees.abs())
299        }) {
300            best = Some(candidate);
301        }
302    }
303    best
304}
305
306fn candidate_centers(region: &MultiPolygon<f64>) -> Vec<[f64; 2]> {
307    let Some(bounds) = region.bounding_rect() else {
308        return Vec::new();
309    };
310    let mut candidates = Vec::new();
311    if let Some(point) = region.centroid() {
312        add_candidate(region, &mut candidates, point);
313    }
314    if let Some(point) = region.interior_point() {
315        add_candidate(region, &mut candidates, point);
316    }
317    add_candidate(region, &mut candidates, rect_center(bounds));
318    let mut parts = region.0.iter().collect::<Vec<_>>();
319    parts.sort_by(|left, right| {
320        polygon_bounds_key(left)
321            .partial_cmp(&polygon_bounds_key(right))
322            .unwrap_or(std::cmp::Ordering::Equal)
323    });
324    for part in parts {
325        if let Some(point) = part.centroid() {
326            add_candidate(region, &mut candidates, point);
327        }
328        if let Some(point) = part.interior_point() {
329            add_candidate(region, &mut candidates, point);
330        }
331        if let Some(bounds) = part.bounding_rect() {
332            add_candidate(region, &mut candidates, rect_center(bounds));
333        }
334    }
335    for x_index in 1..CENTER_GRID_DIVISIONS {
336        let x = bounds.min().x + bounds.width() * x_index as f64 / CENTER_GRID_DIVISIONS as f64;
337        for y_index in 1..CENTER_GRID_DIVISIONS {
338            let y =
339                bounds.min().y + bounds.height() * y_index as f64 / CENTER_GRID_DIVISIONS as f64;
340            add_candidate(region, &mut candidates, Point::new(x, y));
341        }
342    }
343    candidates
344}
345
346fn add_candidate(region: &MultiPolygon<f64>, candidates: &mut Vec<[f64; 2]>, point: Point<f64>) {
347    let candidate = [point.x(), point.y()];
348    if region.covers(&point)
349        && !candidates.iter().any(|existing| {
350            (existing[0] - candidate[0]).abs() <= 1.0e-12
351                && (existing[1] - candidate[1]).abs() <= 1.0e-12
352        })
353    {
354        candidates.push(candidate);
355    }
356}
357
358fn largest_font_at_candidates(
359    region: &MultiPolygon<f64>,
360    centers: &[[f64; 2]],
361    text_aspect: f64,
362    rotation_degrees: f64,
363) -> Option<(f64, [f64; 2])> {
364    let bounds = region.bounding_rect()?;
365    let upper_bound = bounds.width().max(bounds.height());
366    let mut best_font = 0.0;
367    let mut best_center = *centers.first()?;
368    for &center in centers {
369        let mut low = 0.0;
370        let mut high = upper_bound;
371        for _ in 0..BINARY_SEARCH_STEPS {
372            let font_size = (low + high) / 2.0;
373            if text_box_fits(region, center, font_size, text_aspect, rotation_degrees) {
374                low = font_size;
375            } else {
376                high = font_size;
377            }
378        }
379        if low > best_font + 1.0e-9 {
380            best_font = low;
381            best_center = center;
382        }
383    }
384    Some((best_font, best_center))
385}
386
387fn text_box_fits(
388    region: &MultiPolygon<f64>,
389    center: [f64; 2],
390    font_size: f64,
391    text_aspect: f64,
392    rotation_degrees: f64,
393) -> bool {
394    let half_width = text_aspect * font_size / 2.0;
395    let half_height = font_size / 2.0;
396    let angle = rotation_degrees.to_radians();
397    let (sin, cos) = angle.sin_cos();
398    let corners = [
399        [-half_width, -half_height],
400        [half_width, -half_height],
401        [half_width, half_height],
402        [-half_width, half_height],
403    ]
404    .map(|point| {
405        [
406            center[0] + point[0] * cos - point[1] * sin,
407            center[1] + point[0] * sin + point[1] * cos,
408        ]
409    });
410    let Some(rectangle) = ring_polygon(&corners) else {
411        return false;
412    };
413    region.covers(&rectangle)
414}
415
416fn rect_center(bounds: Rect<f64>) -> Point<f64> {
417    Point::new(
418        (bounds.min().x + bounds.max().x) / 2.0,
419        (bounds.min().y + bounds.max().y) / 2.0,
420    )
421}
422
423fn polygon_bounds_key(polygon: &Polygon<f64>) -> [f64; 5] {
424    let Some(bounds) = polygon.bounding_rect() else {
425        return [
426            f64::INFINITY,
427            f64::INFINITY,
428            f64::INFINITY,
429            f64::INFINITY,
430            0.0,
431        ];
432    };
433    [
434        bounds.min().x,
435        bounds.min().y,
436        bounds.max().x,
437        bounds.max().y,
438        polygon.unsigned_area(),
439    ]
440}
441
442fn geometry_key(region: &MultiPolygon<f64>) -> Vec<i64> {
443    let mut result = Vec::new();
444    for polygon in &region.0 {
445        append_ring_key(&mut result, polygon.exterior());
446        result.push(i64::MIN);
447        for interior in polygon.interiors() {
448            append_ring_key(&mut result, interior);
449            result.push(i64::MIN + 1);
450        }
451        result.push(i64::MAX);
452    }
453    result
454}
455
456fn append_ring_key(result: &mut Vec<i64>, ring: &LineString<f64>) {
457    for coordinate in ring.coords() {
458        result.push(quantize(coordinate.x));
459        result.push(quantize(coordinate.y));
460    }
461}
462
463fn quantize(value: f64) -> i64 {
464    let scaled = (value * 1_000_000_000.0).round();
465    if scaled == 0.0 { 0 } else { scaled as i64 }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471
472    fn rectangle(x: f64, y: f64, width: f64, height: f64) -> Vec<[f64; 2]> {
473        vec![
474            [x, y],
475            [x + width, y],
476            [x + width, y + height],
477            [x, y + height],
478        ]
479    }
480
481    #[test]
482    fn square_rotated_part_prefers_horizontal_tie_break() {
483        // Mirrors U9 (7x7 mm QFN rotated -90 deg): horizontal 0 deg wins tie over -90 deg.
484        let region = MultiPolygon::new(vec![ring_polygon(&rectangle(0.0, 0.0, 7.0, 7.0)).unwrap()]);
485        let mut session = DesignatorFitSession::default();
486        let fit = session.fit("U9", &region, 0.8, 2.5, -90.0, None).unwrap();
487        assert_eq!(fit.rotation_degrees, 0.0);
488        assert!((fit.center_mm[0] - 3.5).abs() < 1e-6);
489        assert!((fit.center_mm[1] - 3.5).abs() < 1e-6);
490    }
491
492    #[test]
493    fn tall_narrow_rotated_part_keeps_vertical_orientation() {
494        let region = MultiPolygon::new(vec![ring_polygon(&rectangle(0.0, 0.0, 2.7, 3.2)).unwrap()]);
495        let mut session = DesignatorFitSession::default();
496        let fit = session.fit("L11", &region, 0.8, 2.5, 90.0, None).unwrap();
497        assert_eq!(fit.rotation_degrees, -90.0);
498    }
499
500    fn rotated_rect(cx: f64, cy: f64, width: f64, height: f64, angle_deg: f64) -> Vec<[f64; 2]> {
501        let (sin, cos) = angle_deg.to_radians().sin_cos();
502        let hw = width / 2.0;
503        let hh = height / 2.0;
504        [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]]
505            .into_iter()
506            .map(|[x, y]| [cx + x * cos - y * sin, cy + x * sin + y * cos])
507            .collect()
508    }
509
510    #[test]
511    fn square_part_at_45_deg_stays_horizontal() {
512        // Mirrors U17 (TQFP128 at 135 deg), smaller QFNs, and near-square parts (AR < 1.2):
513        // stays at normal horizontal 0 deg rather than rotating diagonally.
514        for (w, h) in [(4.0, 4.0), (14.0, 14.0), (2.2, 2.0)] {
515            let region = MultiPolygon::new(vec![
516                ring_polygon(&rotated_rect(10.0, 10.0, w, h, 135.0)).unwrap(),
517            ]);
518            let mut session = DesignatorFitSession::default();
519            let fit = session.fit("U17", &region, 0.78, 2.4, 135.0, None).unwrap();
520            assert_eq!(fit.rotation_degrees, 0.0, "w={w} h={h}");
521        }
522        // Threshold override <= 1.0 restores oblique rotation on squarish parts.
523        let near_sq = MultiPolygon::new(vec![
524            ring_polygon(&rotated_rect(10.0, 10.0, 2.2, 2.0, 45.0)).unwrap(),
525        ]);
526        let mut session = DesignatorFitSession::default();
527        let forced = session
528            .fit_with_oblique_min_aspect_ratio("U19", &near_sq, 0.78, 2.4, 45.0, None, 1.0)
529            .unwrap();
530        assert!((forced.rotation_degrees - 45.0).abs() < 1e-6);
531    }
532
533    #[test]
534    fn elongated_part_at_45_deg_rotates_along_long_axis() {
535        // Mirrors Y2 (2520 xtal, AR=1.25) and 0805 / 0603 passives at 45 deg (AR >= 1.2).
536        for (designator, w, h) in [("Y2", 2.5, 2.0), ("R138", 2.0, 1.0)] {
537            let region = MultiPolygon::new(vec![
538                ring_polygon(&rotated_rect(10.0, 10.0, w, h, 45.0)).unwrap(),
539            ]);
540            let mut session = DesignatorFitSession::default();
541            let fit = session
542                .fit(designator, &region, 0.78, 2.4, 45.0, None)
543                .unwrap();
544            assert!((fit.rotation_degrees - 45.0).abs() < 1e-6, "{designator}");
545        }
546        // Raising oblique_min_aspect_ratio above 2.0 keeps even 2:1 parts horizontal.
547        let region = MultiPolygon::new(vec![
548            ring_polygon(&rotated_rect(10.0, 10.0, 2.0, 1.0, 45.0)).unwrap(),
549        ]);
550        let mut session = DesignatorFitSession::default();
551        let strict = session
552            .fit_with_oblique_min_aspect_ratio("R138", &region, 0.78, 2.4, 45.0, None, 2.5)
553            .unwrap();
554        assert_eq!(strict.rotation_degrees, 0.0);
555    }
556}