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

cad_text_realization/
text_topology.rs

1//! Bounded KiCad-compatible contour normalization and hole fracture.
2
3use crate::{TextContour, TextContourError, TextContourErrorKind, TextPoint};
4use std::cmp::Ordering;
5
6/// Fractured exterior-only contours and observable topology work.
7#[derive(Clone, Debug, PartialEq)]
8pub struct TextTopologyOutput {
9    pub contours: Vec<TextContour>,
10    pub input_points: usize,
11    pub edge_slots: usize,
12    pub output_points: usize,
13    pub containment_edge_checks: usize,
14    pub bridge_edge_checks: usize,
15    pub link_steps: usize,
16}
17
18/// One normalized filled text region before optional hole fracture.
19#[derive(Clone, Debug, PartialEq)]
20pub struct TextContourRegion {
21    pub outer: TextContour,
22    pub holes: Vec<TextContour>,
23}
24
25/// Normalize and group one glyph's contours into explicit outer/hole regions.
26///
27/// This shares the containment authority used by [`fracture_text_contours_a0`]
28/// for consumers whose geometry carrier can preserve holes directly.
29pub fn group_text_contours_a0(
30    contours: &[TextContour],
31) -> Result<Vec<TextContourRegion>, TextContourError> {
32    let mut work = Work::default();
33    let normalized = normalize_contours(contours, &mut work)?;
34    let polygons = classify_contours(&normalized, &mut work)?;
35    let mut regions = Vec::with_capacity(polygons.len());
36    for polygon in polygons {
37        let outer = normalized[polygon.exterior].clone();
38        if outer.points.len() < 3 {
39            continue;
40        }
41        let holes = polygon
42            .holes
43            .into_iter()
44            .filter_map(|index| {
45                let contour = normalized[index].clone();
46                (contour.points.len() >= 3).then_some(contour)
47            })
48            .collect();
49        regions.push(TextContourRegion { outer, holes });
50    }
51    Ok(regions)
52}
53
54#[derive(Clone, Debug)]
55struct Polygon {
56    exterior: usize,
57    holes: Vec<usize>,
58}
59
60#[derive(Clone, Copy, Debug)]
61struct PathInfo {
62    contour: usize,
63    start: usize,
64    leftmost: usize,
65    x_min: f64,
66    y_min: f64,
67    provoking: usize,
68    bridge: Option<usize>,
69}
70
71#[derive(Clone, Copy, Debug)]
72struct Edge {
73    p1: TextPoint,
74    p2: TextPoint,
75    next: usize,
76}
77
78#[derive(Default)]
79struct Work {
80    input_points: usize,
81    edge_slots: usize,
82    output_points: usize,
83    containment_edge_checks: usize,
84    bridge_edge_checks: usize,
85    link_steps: usize,
86}
87
88/// Normalize duplicate closure points and fracture holes into exterior paths.
89///
90/// This mirrors the cache-oriented ordering used by the Python KiCad reference.
91/// Contours are classified by containment-depth parity (even depth = exterior,
92/// odd depth = hole), so holes may arrive before or after their exterior (Noto
93/// faces store holes first). One call must cover exactly one glyph's polygon
94/// set: KiCad only runs
95/// `Fracture()` (and its Clipper2 `Simplify()` seam rewrite plus outer
96/// reordering) when the glyph set has holes, so a hole-free input keeps font
97/// order and ring starts untouched.
98/// Degenerate (<3 point) contours are standalone exteriors published at their
99/// stored position in hole-free inputs and dropped from holed inputs, matching
100/// Clipper2 `Simplify()` eating degenerate rings during `Fracture()`.
101pub fn fracture_text_contours_a0(
102    contours: &[TextContour],
103) -> Result<TextTopologyOutput, TextContourError> {
104    let mut work = Work::default();
105    let mut normalized = normalize_contours(contours, &mut work)?;
106    let polygons = classify_contours(&normalized, &mut work)?;
107    let has_holes = polygons.iter().any(|polygon| !polygon.holes.is_empty());
108    if has_holes {
109        normalize_fracture_orientation(&mut normalized, &polygons)?;
110    }
111    let mut output = Vec::with_capacity(polygons.len());
112    for polygon in &polygons {
113        // `Fracture()`'s Clipper2 `Simplify()` drops degenerate rings, so
114        // they only survive in hole-free groups that skip `Fracture()`.
115        if has_holes && normalized[polygon.exterior].points.len() < 3 {
116            continue;
117        }
118        let points = fracture_polygon(&normalized, polygon, has_holes, &mut work)?;
119        output.push(TextContour { points });
120    }
121    if has_holes {
122        sort_contours_by_simplify_order(&mut output);
123    }
124    Ok(TextTopologyOutput {
125        contours: output,
126        input_points: work.input_points,
127        edge_slots: work.edge_slots,
128        output_points: work.output_points,
129        containment_edge_checks: work.containment_edge_checks,
130        bridge_edge_checks: work.bridge_edge_checks,
131        link_steps: work.link_steps,
132    })
133}
134
135fn normalize_contours(
136    contours: &[TextContour],
137    work: &mut Work,
138) -> Result<Vec<TextContour>, TextContourError> {
139    let mut normalized = Vec::with_capacity(contours.len());
140    for (contour_index, contour) in contours.iter().enumerate() {
141        charge(
142            &mut work.input_points,
143            contour.points.len(),
144            "$.contours[*].points",
145            "input point limit exceeded",
146        )?;
147        if contour
148            .points
149            .iter()
150            .any(|point| !point.x.is_finite() || !point.y.is_finite())
151        {
152            return Err(invalid(
153                format!("$.contours[{contour_index}].points"),
154                "contour coordinates must be finite",
155            ));
156        }
157        let retained =
158            if contour.points.len() > 1 && contour.points.first() == contour.points.last() {
159                &contour.points[..contour.points.len() - 1]
160            } else {
161                &contour.points
162            };
163        // Degenerate (<3 point) rings are kept: KiCad publishes contours
164        // collapsed by cache-frame quantization in the saved render cache.
165        if !retained.is_empty() {
166            normalized.push(TextContour {
167                points: retained.to_vec(),
168            });
169        }
170    }
171    Ok(normalized)
172}
173
174fn classify_contours(
175    contours: &[TextContour],
176    work: &mut Work,
177) -> Result<Vec<Polygon>, TextContourError> {
178    // Containment-depth parity: even depth = exterior, odd depth = hole, and
179    // a hole's parent is its first stored containing exterior one level up.
180    // This is order-independent: Noto faces store holes before exteriors.
181    // Degenerate (<3 point) rings are standalone: they never contain, never
182    // count as holes, and stay at their stored position among the exteriors.
183    let containers = containment_containers(contours, work)?;
184    let mut polygons: Vec<Polygon> = Vec::new();
185    let mut polygon_of = vec![usize::MAX; contours.len()];
186    for contour_index in 0..contours.len() {
187        if contours[contour_index].points.len() < 3
188            || containers[contour_index].len().is_multiple_of(2)
189        {
190            polygon_of[contour_index] = polygons.len();
191            push_polygon(&mut polygons, contour_index)?;
192        }
193    }
194    for contour_index in 0..contours.len() {
195        let depth = containers[contour_index].len();
196        if contours[contour_index].points.len() < 3 || depth.is_multiple_of(2) {
197            continue;
198        }
199        let parent = containers[contour_index]
200            .iter()
201            .copied()
202            .find(|&other_index| containers[other_index].len() + 1 == depth)
203            .map(|other_index| polygon_of[other_index]);
204        match parent {
205            Some(polygon_index) => polygons[polygon_index].holes.push(contour_index),
206            None => push_polygon(&mut polygons, contour_index)?,
207        }
208    }
209    Ok(polygons)
210}
211
212/// For each contour, the stored-order indices of contours containing its
213/// first point; the list length is the contour's containment depth.
214fn containment_containers(
215    contours: &[TextContour],
216    work: &mut Work,
217) -> Result<Vec<Vec<usize>>, TextContourError> {
218    let mut containers = Vec::with_capacity(contours.len());
219    for (contour_index, contour) in contours.iter().enumerate() {
220        let mut containing = Vec::new();
221        for (other_index, other) in contours.iter().enumerate() {
222            if other_index != contour_index
223                && other.points.len() >= 3
224                && point_in_polygon(contour.points[0], &other.points, work)?
225            {
226                containing.push(other_index);
227            }
228        }
229        containers.push(containing);
230    }
231    Ok(containers)
232}
233
234fn push_polygon(polygons: &mut Vec<Polygon>, exterior: usize) -> Result<(), TextContourError> {
235    polygons.push(Polygon {
236        exterior,
237        holes: Vec::new(),
238    });
239    Ok(())
240}
241
242fn point_in_polygon(
243    point: TextPoint,
244    polygon: &[TextPoint],
245    work: &mut Work,
246) -> Result<bool, TextContourError> {
247    let mut inside = false;
248    for index in 0..polygon.len() {
249        charge(
250            &mut work.containment_edge_checks,
251            1,
252            "$.work.containment_edge_checks",
253            "containment edge-check limit exceeded",
254        )?;
255        let p1 = polygon[index];
256        let p2 = polygon[(index + 1) % polygon.len()];
257        if (p1.y > point.y) != (p2.y > point.y) {
258            let delta_x = checked_derived(p2.x - p1.x)?;
259            let delta_y = checked_derived(p2.y - p1.y)?;
260            let query_delta_y = checked_derived(point.y - p1.y)?;
261            let intersect =
262                checked_derived(checked_derived(delta_x * query_delta_y)? / delta_y + p1.x)?;
263            if point.x < intersect {
264                inside = !inside;
265            }
266        }
267    }
268    Ok(inside)
269}
270
271fn fracture_polygon(
272    contours: &[TextContour],
273    polygon: &Polygon,
274    group_has_holes: bool,
275    work: &mut Work,
276) -> Result<Vec<TextPoint>, TextContourError> {
277    if polygon.holes.is_empty() {
278        let exterior = &contours[polygon.exterior].points;
279        charge_output(exterior.len(), work)?;
280        if !group_has_holes {
281            return Ok(exterior.clone());
282        }
283        // A holed glyph's `Simplify()` rewrites every ring seam, including
284        // hole-free outers sharing the glyph's polygon set.
285        let start = seam_index(exterior);
286        let mut rotated = exterior[start..].to_vec();
287        rotated.extend_from_slice(&exterior[..start]);
288        return Ok(rotated);
289    }
290
291    let exterior = &contours[polygon.exterior].points;
292    let mut infos = Vec::with_capacity(polygon.holes.len() + 1);
293    infos.push(path_info(contours, polygon.exterior, seam_index(exterior)));
294    for &hole in &polygon.holes {
295        infos.push(path_info(contours, hole, 0));
296    }
297    infos[1..].sort_by(|left, right| {
298        finite_cmp(left.x_min, right.x_min).then_with(|| finite_cmp(left.y_min, right.y_min))
299    });
300
301    let required_slots = infos.iter().try_fold(0usize, |total, info| {
302        total
303            .checked_add(contours[info.contour].points.len())
304            .and_then(|value| value.checked_add(usize::from(info.contour != polygon.exterior) * 3))
305    });
306    let required_slots =
307        required_slots.ok_or_else(|| limit("$.edges", "edge slot count overflow"))?;
308    charge(
309        &mut work.edge_slots,
310        required_slots,
311        "$.edges",
312        "edge slot limit exceeded",
313    )?;
314    let mut edges: Vec<Option<Edge>> = Vec::with_capacity(required_slots);
315    for info in &mut infos {
316        let points = &contours[info.contour].points;
317        let provoking = edges.len();
318        info.provoking = provoking;
319        for index in 0..points.len() {
320            edges.push(Some(Edge {
321                p1: path_point(points, info.start, index),
322                p2: path_point(points, info.start, (index + 1) % points.len()),
323                next: if index + 1 < points.len() {
324                    provoking + index + 1
325                } else {
326                    provoking
327                },
328            }));
329        }
330        if info.contour != polygon.exterior {
331            info.bridge = Some(edges.len());
332            edges.extend([None, None, None]);
333        }
334    }
335
336    for info in infos.iter().skip(1) {
337        bridge_hole(&mut edges, *info, work)?;
338    }
339    collect_fractured(&edges, work)
340}
341
342/// `Fracture()`'s Clipper2 `Simplify()` emits rings in a fixed orientation
343/// (exteriors positive shoelace area in the cache frame, holes negative)
344/// regardless of input winding. Mirrored text flips every ring's winding, so
345/// holed groups normalize orientation before the seam/bridge rules; hole-free
346/// groups skip `Simplify()` and keep their stored winding.
347fn normalize_fracture_orientation(
348    contours: &mut [TextContour],
349    polygons: &[Polygon],
350) -> Result<(), TextContourError> {
351    for polygon in polygons {
352        if signed_area(&contours[polygon.exterior].points)? < 0.0 {
353            contours[polygon.exterior].points.reverse();
354        }
355        for &hole in &polygon.holes {
356            if signed_area(&contours[hole].points)? > 0.0 {
357                contours[hole].points.reverse();
358            }
359        }
360    }
361    Ok(())
362}
363
364/// Shoelace signed area; nonfinite accumulation fails closed.
365fn signed_area(points: &[TextPoint]) -> Result<f64, TextContourError> {
366    let mut total = 0.0;
367    for index in 0..points.len() {
368        let p1 = points[index];
369        let p2 = points[(index + 1) % points.len()];
370        total += p1.x * p2.y - p2.x * p1.y;
371    }
372    checked_derived(total / 2.0)
373}
374
375/// Ring seam stored by `Fracture()`'s Clipper2 `Simplify()` rewrite: one past
376/// the exit of the min-y run whose top closes the ring last in the sweep.
377///
378/// A "run" is a maximal stretch of consecutive stored points at the ring's
379/// minimum y. Clipper2's `DoTopOfScanbeam` handles single-point maxima
380/// left-to-right but defers horizontal maxima onto a LIFO stack processed
381/// right-to-left afterwards, so a multi-point (horizontal) run always closes
382/// after every single-point run, the leftmost horizontal run closes last,
383/// and with only single-point runs the rightmost closes last.
384fn seam_index(points: &[TextPoint]) -> usize {
385    let min_y = points
386        .iter()
387        .map(|point| point.y)
388        .min_by(|left, right| finite_cmp(*left, *right))
389        .expect("normalized contours are nonempty");
390    let runs = min_y_runs(points, min_y);
391    let Some(first) = runs.first() else {
392        // Every stored point sits at min y; keep the smallest-x anchor.
393        return points
394            .iter()
395            .enumerate()
396            .min_by(|(_, left), (_, right)| finite_cmp(left.x, right.x))
397            .map(|(index, _)| index)
398            .expect("normalized contours are nonempty");
399    };
400    let chosen = runs
401        .iter()
402        .filter(|(start, end)| start != end)
403        .min_by(|left, right| finite_cmp(run_min_x(points, **left), run_min_x(points, **right)))
404        .or_else(|| {
405            runs.iter()
406                .max_by(|(left, _), (right, _)| finite_cmp(points[*left].x, points[*right].x))
407        })
408        .unwrap_or(first);
409    (chosen.1 + 1) % points.len()
410}
411
412/// Maximal cyclic `(start, end)` stretches of consecutive min-y points.
413fn min_y_runs(points: &[TextPoint], min_y: f64) -> Vec<(usize, usize)> {
414    let count = points.len();
415    let mut runs = Vec::new();
416    for index in 0..count {
417        if points[index].y != min_y || points[(index + count - 1) % count].y == min_y {
418            continue;
419        }
420        let mut end = index;
421        while points[(end + 1) % count].y == min_y {
422            end = (end + 1) % count;
423        }
424        runs.push((index, end));
425    }
426    runs
427}
428
429/// Smallest x among a cyclic min-y run's stored points.
430fn run_min_x(points: &[TextPoint], run: (usize, usize)) -> f64 {
431    let mut index = run.0;
432    let mut x = points[run.0].x;
433    while index != run.1 {
434        index = (index + 1) % points.len();
435        if points[index].x < x {
436            x = points[index].x;
437        }
438    }
439    x
440}
441
442/// Approximate Clipper2's `LocMinSorter` outer output order within one glyph.
443///
444/// KiCad's `Fracture()` runs `Simplify()` per glyph `SHAPE_POLY_SET`, and
445/// Clipper2's sweep emits each disjoint outer at its bottom-most local
446/// minimum: bottom-most first (largest y in the y-down cache frame), ties by
447/// smallest x, otherwise stable in input order.
448fn sort_contours_by_simplify_order(contours: &mut [TextContour]) {
449    contours.sort_by(|left, right| {
450        let (left_y, left_x) = bottom_vertex_key(&left.points);
451        let (right_y, right_x) = bottom_vertex_key(&right.points);
452        finite_cmp(right_y, left_y).then_with(|| finite_cmp(left_x, right_x))
453    });
454}
455
456/// Bottom-most vertex key: the largest y and the smallest x at that y.
457fn bottom_vertex_key(points: &[TextPoint]) -> (f64, f64) {
458    let mut max_y = f64::NEG_INFINITY;
459    let mut min_x = f64::INFINITY;
460    for point in points {
461        if point.y > max_y {
462            max_y = point.y;
463            min_x = point.x;
464        } else if point.y == max_y && point.x < min_x {
465            min_x = point.x;
466        }
467    }
468    (max_y, min_x)
469}
470
471fn path_info(contours: &[TextContour], contour: usize, start: usize) -> PathInfo {
472    let points = &contours[contour].points;
473    let count = points.len();
474    let x_min = points
475        .iter()
476        .map(|point| point.x)
477        .min_by(|left, right| finite_cmp(*left, *right))
478        .expect("normalized contours are nonempty");
479    // KiCad's `fractureSingleCacheFriendly()` bridges each hole at the first
480    // stored point whose x equals the hole's minimum (strict `<` scan, no
481    // tie-break).  The stored order comes from `Fracture()`'s Clipper2
482    // `Simplify()`, so the scan starts at the ring's Simplify seam and takes
483    // the first min-x point reached in stored traversal order.
484    let seam = seam_index(points);
485    let leftmost_raw = (0..count)
486        .map(|offset| (seam + offset) % count)
487        .find(|&index| points[index].x == x_min)
488        .expect("normalized contours are nonempty");
489    // Edge slots view the ring rotated by `start`; express the bridge vertex
490    // in that view.
491    let leftmost = (leftmost_raw + count - start) % count;
492    let y_min = points
493        .iter()
494        .map(|point| point.y)
495        .min_by(|left, right| finite_cmp(*left, *right))
496        .expect("normalized contours are nonempty");
497    PathInfo {
498        contour,
499        start,
500        leftmost,
501        x_min,
502        y_min,
503        provoking: 0,
504        bridge: None,
505    }
506}
507
508fn bridge_hole(
509    edges: &mut [Option<Edge>],
510    info: PathInfo,
511    work: &mut Work,
512) -> Result<(), TextContourError> {
513    let hole_edge_index = info.provoking + info.leftmost;
514    let hole_edge = edges[hole_edge_index].expect("hole edge is populated");
515    let mut nearest: Option<(usize, f64)> = None;
516    let mut min_distance = f64::INFINITY;
517    for (candidate_index, candidate) in edges.iter().copied().enumerate().take(info.provoking) {
518        charge(
519            &mut work.bridge_edge_checks,
520            1,
521            "$.work.bridge_edge_checks",
522            "bridge edge-check limit exceeded",
523        )?;
524        let Some(candidate) = candidate else {
525            continue;
526        };
527        if !edge_matches_y(candidate.p1, candidate.p2, hole_edge.p1.y) {
528            continue;
529        }
530        let intersect = edge_x_intersect(candidate.p1, candidate.p2, hole_edge.p1.y)?;
531        let distance = checked_derived(hole_edge.p1.x - intersect)?;
532        if distance >= 0.0 && distance < min_distance {
533            min_distance = distance;
534            nearest = Some((candidate_index, intersect));
535        }
536    }
537    let Some((nearest_index, nearest_x)) = nearest else {
538        return Ok(());
539    };
540    let bridge = info.bridge.expect("holes reserve bridge slots");
541    let nearest_edge = edges[nearest_index].expect("nearest edge is populated");
542    let split = TextPoint {
543        x: nearest_x,
544        y: hole_edge.p1.y,
545    };
546    edges[bridge] = Some(Edge {
547        p1: split,
548        p2: hole_edge.p1,
549        next: hole_edge_index,
550    });
551    edges[bridge + 1] = Some(Edge {
552        p1: hole_edge.p1,
553        p2: split,
554        next: bridge + 2,
555    });
556    edges[bridge + 2] = Some(Edge {
557        p1: split,
558        p2: nearest_edge.p2,
559        next: nearest_edge.next,
560    });
561    edges[nearest_index] = Some(Edge {
562        p2: split,
563        next: bridge,
564        ..nearest_edge
565    });
566
567    let mut last = hole_edge_index;
568    loop {
569        charge_link(work)?;
570        let next = edges[last].expect("hole ring edge is populated").next;
571        if next == hole_edge_index {
572            break;
573        }
574        last = next;
575    }
576    edges[last]
577        .as_mut()
578        .expect("hole ring edge is populated")
579        .next = bridge + 1;
580    Ok(())
581}
582
583fn collect_fractured(
584    edges: &[Option<Edge>],
585    work: &mut Work,
586) -> Result<Vec<TextPoint>, TextContourError> {
587    let mut points: Vec<TextPoint> = Vec::new();
588    let mut current = 0;
589    loop {
590        charge_link(work)?;
591        let edge = edges[current].expect("fractured exterior edge is populated");
592        // KiCad assembles the fractured ring through SHAPE_LINE_CHAIN::Append,
593        // which drops points equal to the last one; a bridge split point can
594        // coincide with the hole's bridge vertex at small glyph sizes.
595        if points.last() != Some(&edge.p1) {
596            charge_output(1, work)?;
597            points.push(edge.p1);
598        }
599        if edge.next == 0 {
600            break;
601        }
602        current = edge.next;
603    }
604    Ok(points)
605}
606
607fn path_point(points: &[TextPoint], start: usize, offset: usize) -> TextPoint {
608    points[(start + offset) % points.len()]
609}
610
611fn edge_matches_y(p1: TextPoint, p2: TextPoint, y: f64) -> bool {
612    (y >= p1.y || y >= p2.y) && (y <= p1.y || y <= p2.y)
613}
614
615fn edge_x_intersect(p1: TextPoint, p2: TextPoint, y: f64) -> Result<f64, TextContourError> {
616    if p1.y == p2.y {
617        Ok(if p1.x < p2.x { p2.x } else { p1.x })
618    } else {
619        let delta_x = checked_derived(p2.x - p1.x)?;
620        let delta_y = checked_derived(p2.y - p1.y)?;
621        let query_delta_y = checked_derived(y - p1.y)?;
622        checked_derived(p1.x + checked_derived(delta_x * query_delta_y)? / delta_y)
623    }
624}
625
626fn finite_cmp(left: f64, right: f64) -> Ordering {
627    left.partial_cmp(&right)
628        .expect("validated coordinates are finite")
629}
630
631fn checked_derived(value: f64) -> Result<f64, TextContourError> {
632    if value.is_finite() {
633        Ok(value)
634    } else {
635        Err(invalid(
636            "$.work.derived_coordinate".to_owned(),
637            "contour topology produced a nonfinite derived coordinate",
638        ))
639    }
640}
641
642fn charge_output(amount: usize, work: &mut Work) -> Result<(), TextContourError> {
643    charge(
644        &mut work.output_points,
645        amount,
646        "$.output.points",
647        "output point limit exceeded",
648    )
649}
650
651fn charge_link(work: &mut Work) -> Result<(), TextContourError> {
652    charge(
653        &mut work.link_steps,
654        1,
655        "$.work.link_steps",
656        "edge-link traversal limit exceeded",
657    )
658}
659
660fn charge(
661    value: &mut usize,
662    amount: usize,
663    path: &'static str,
664    message: &'static str,
665) -> Result<(), TextContourError> {
666    let next = value
667        .checked_add(amount)
668        .ok_or_else(|| limit(path, message))?;
669    *value = next;
670    Ok(())
671}
672
673fn limit(path: &'static str, message: &'static str) -> TextContourError {
674    TextContourError {
675        kind: TextContourErrorKind::ResourceLimit,
676        path: path.to_owned(),
677        message,
678    }
679}
680
681fn invalid(path: String, message: &'static str) -> TextContourError {
682    TextContourError {
683        kind: TextContourErrorKind::InvalidInput,
684        path,
685        message,
686    }
687}