axiolid-construct 0.3.22

Solid generation: profiles, lofts, sweeps, revolutions and half-space clipping
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Profile -> 2D polygon rings, then triangles.
//!
//! Curved boundaries are flattened to chords under an explicit
//! `TessellationOptions`-style budget; nothing here invents a default
//! tolerance.
//!
//! Triangulation of rings-with-holes is the crate's own certified ear clipper
//! (`ring_triangulation`, ADR 0083, replacing the `earcut` adoption of ADR
//! 0015 after it left T-junctions between holes in one band, #253).
//! `axiolid_reference::triangulate_simple` stays the differential oracle for
//! the hole-free case.

use axiolid_contracts::{GeomError, GeomResult};
use axiolid_core::{Point2, Scalar, Tolerance};
use axiolid_curve::Curve2;
use axiolid_profile::{CircleProfile, EllipseProfile, Profile, RectangleProfile};

/// Outer ring plus holes, all CCW/CW normalised by the caller's contract:
/// outer counter-clockwise, holes clockwise.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Rings {
    /// Outer boundary, counter-clockwise.
    pub outer: Vec<Point2>,
    /// Inner boundaries, clockwise.
    pub holes: Vec<Vec<Point2>>,
}

/// Flatten a profile into rings under an explicit chord budget.
///
/// Only the families a format adapter currently emits are handled. Everything
/// else returns `Unsupported` rather than a silently wrong approximation --
/// a wrong wall is far more expensive than a missing one.
pub fn profile_rings(
    profile: &Profile,
    chord_error: Scalar,
    tolerance: Tolerance,
) -> GeomResult<Rings> {
    match profile {
        // Rounded corners are exact arcs in the contour, chorded like any
        // other arc; a sharp rectangle keeps its four exact corners.
        Profile::Rectangle(r) if r.outer_radius.is_some() || r.inner_radius.is_some() => {
            let contour = crate::section_lower::rectangle_contour(r)?;
            contour_rings(&contour, chord_error, tolerance)
        }
        Profile::Rectangle(r) => rectangle_rings(r, chord_error, tolerance),
        // Structural sections (#193): the same exact contour the exact
        // extruder builds, fillets and toe radii as arcs, chorded here.
        Profile::Section(section) => {
            let contour = crate::section_lower::section_contour(section)?;
            contour_rings(&contour, chord_error, tolerance)
        }
        Profile::Circle(c) => circle_rings(c, chord_error),
        // Reachable only since curve evaluation moved into `axiolid-reference`:
        // an ellipse has no closed-form segment count, so the old fixed-count
        // flattener could not express it at all.
        Profile::Ellipse(e) => ellipse_rings(e, chord_error),
        Profile::Contour(c) => contour_rings(c, chord_error, tolerance),
        Profile::Derived { basis, transform } => {
            let mut rings = profile_rings(basis, chord_error, tolerance)?;
            apply2(&mut rings.outer, transform);
            for hole in &mut rings.holes {
                apply2(hole, transform);
            }
            // A mirroring placement reverses ring orientation; the extruder's
            // walls rely on outer CCW / holes CW, so restore it here
            // rather than letting a silently inside-out solid reach them.
            if transform.matrix2.determinant() < 0.0 {
                rings.outer.reverse();
                for hole in &mut rings.holes {
                    hole.reverse();
                }
            }
            Ok(rings)
        }
        Profile::CenterLine(cl) => {
            crate::center_line::center_line_rings(cl, chord_error, tolerance, contour_points)
        }
        other => Err(GeomError::Unsupported {
            backend: crate::BACKEND_ID,
            operation: axiolid_contracts::Operation::ProfileTriangulation,
        })
        .inspect_err(|_| {
            let _ = other;
        }),
    }
}

/// How far a profile's exact boundary may lie from the rings
/// [`profile_rings`] flattens it to (#232).
///
/// `Bounded(d)`: every point of the exact boundary is within `d` of an edge
/// of the rings, so every point of the exact region is within `d` of the
/// rings' region too (a point between an arc and its chord is in the
/// convex hull of the two, hence within the arc's distance of the chord).
/// `Unbounded` names the part that has no certified bound.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ProfileDeviation {
    /// A certified upper bound, in the profile's own units.
    Bounded(Scalar),
    /// No certified bound; the reason names the family.
    Unbounded(&'static str),
}

impl ProfileDeviation {
    /// The worse of two deviations: unbounded wins, else the larger bound.
    #[must_use]
    pub fn max(self, other: Self) -> Self {
        match (self, other) {
            (Self::Unbounded(reason), _) | (_, Self::Unbounded(reason)) => Self::Unbounded(reason),
            (Self::Bounded(a), Self::Bounded(b)) => Self::Bounded(a.max(b)),
        }
    }

    fn scaled(self, factor: Scalar) -> Self {
        match self {
            Self::Bounded(d) => Self::Bounded(d * factor),
            unbounded => unbounded,
        }
    }

    fn plus(self, extra: Scalar) -> Self {
        match self {
            Self::Bounded(d) => Self::Bounded(d + extra),
            unbounded => unbounded,
        }
    }
}

/// The deviation of [`profile_rings`]`(profile, chord_error, tolerance)`
/// from the exact profile (#232).
///
/// The rings are rebuilt here, deterministically, and three things are
/// read off them:
///
/// - each curved segment's family: one [`axiolid_reference::curve::flatten2`]
///   certifies ([`axiolid_reference::bound::certifies_flattening2`]) is
///   within `chord_error` of its chords; any other is `Unbounded`;
/// - the points merged as coincident (within the linear tolerance of the
///   point kept): a merged point moves the ring by at most its distance to
///   the kept one, which is added;
/// - a derived profile's transform, whose largest stretch scales the
///   basis's bound.
///
/// # Errors
///
/// As [`profile_rings`] for the same arguments.
pub fn profile_deviation(
    profile: &Profile,
    chord_error: Scalar,
    tolerance: Tolerance,
) -> GeomResult<ProfileDeviation> {
    Ok(match profile {
        Profile::Rectangle(r) if r.outer_radius.is_some() || r.inner_radius.is_some() => {
            contour_deviation(
                &crate::section_lower::rectangle_contour(r)?,
                chord_error,
                tolerance,
            )?
        }
        Profile::Rectangle(r) => {
            rectangle_rings(r, chord_error, tolerance)?;
            match r.thickness {
                // The hole is dropped when one of its extents vanishes
                // within the tolerance; its slit walls then lie inside the
                // solid, far from every ring.
                Some(t) if tolerance.eq(r.x / 2.0 - t, 0.0) || tolerance.eq(r.y / 2.0 - t, 0.0) => {
                    ProfileDeviation::Unbounded("hollow rectangle whose hole collapses")
                }
                _ => ProfileDeviation::Bounded(0.0),
            }
        }
        Profile::Section(section) => contour_deviation(
            &crate::section_lower::section_contour(section)?,
            chord_error,
            tolerance,
        )?,
        Profile::Circle(c) => {
            circle_rings(c, chord_error)?;
            ProfileDeviation::Bounded(chord_error)
        }
        Profile::Ellipse(e) => {
            ellipse_rings(e, chord_error)?;
            ProfileDeviation::Bounded(chord_error)
        }
        Profile::Contour(c) => contour_deviation(c, chord_error, tolerance)?,
        Profile::Derived { basis, transform } => {
            profile_deviation(basis, chord_error, tolerance)?.scaled(stretch2(transform))
        }
        Profile::CenterLine(cl) => {
            profile_rings(profile, chord_error, tolerance)?;
            let mut merged: Scalar = 0.0;
            contour_points_measured(&cl.path, chord_error, tolerance, &mut merged)?;
            let straight = cl
                .path
                .segments
                .iter()
                .all(|segment| matches!(segment.curve, Curve2::Line(_) | Curve2::Polyline(_)));
            if straight && merged == 0.0 {
                ProfileDeviation::Bounded(0.0)
            } else {
                ProfileDeviation::Unbounded("centre-line profile along a curved or merged path")
            }
        }
        _ => {
            profile_rings(profile, chord_error, tolerance)?;
            ProfileDeviation::Unbounded("profile family")
        }
    })
}

/// The largest stretch of a 2D affine map's linear part: its largest
/// singular value, `sqrt((F + sqrt(F^2 - 4 D^2)) / 2)` with `F` the squared
/// Frobenius norm and `D` the determinant, inflated against rounding.
fn stretch2(transform: &axiolid_core::Transform2) -> Scalar {
    let m = transform.matrix2;
    let f = m.x_axis.length_squared() + m.y_axis.length_squared();
    let d = m.determinant();
    let disc = (f * f - 4.0 * d * d).max(0.0).sqrt();
    (0.5 * (f + disc)).sqrt() * (1.0 + 1e-12)
}

/// [`ProfileDeviation`] of one contour with holes.
fn contour_deviation(
    c: &axiolid_profile::ContourProfile,
    chord_error: Scalar,
    tolerance: Tolerance,
) -> GeomResult<ProfileDeviation> {
    let mut deviation = ProfileDeviation::Bounded(0.0);
    for contour in core::iter::once(&c.outer).chain(&c.holes) {
        let mut merged: Scalar = 0.0;
        contour_points_measured(contour, chord_error, tolerance, &mut merged)?;
        let mut chords = ProfileDeviation::Bounded(0.0);
        for segment in &contour.segments {
            chords = chords.max(segment_deviation(&segment.curve, chord_error));
        }
        deviation = deviation.max(chords.plus(merged));
    }
    Ok(deviation)
}

/// A segment's chord deviation: none for a straight one, the budget for a
/// family the flattener certifies, else unbounded by family.
fn segment_deviation(curve: &Curve2, chord_error: Scalar) -> ProfileDeviation {
    match curve {
        Curve2::Line(_) | Curve2::Polyline(_) => ProfileDeviation::Bounded(0.0),
        other if axiolid_reference::bound::certifies_flattening2(other) => {
            ProfileDeviation::Bounded(chord_error)
        }
        Curve2::Intrinsic(_) => ProfileDeviation::Unbounded("intrinsic (clothoid) profile segment"),
        Curve2::Chain(_) => {
            ProfileDeviation::Unbounded("arc-length chain profile segment with an unbounded piece")
        }
        Curve2::BSpline(_) => {
            ProfileDeviation::Unbounded("B-spline profile segment with a non-positive weight")
        }
        _ => ProfileDeviation::Unbounded("profile segment family"),
    }
}

/// An exact contour with holes, flattened under the chord budget.
fn contour_rings(
    c: &axiolid_profile::ContourProfile,
    chord_error: Scalar,
    tolerance: Tolerance,
) -> GeomResult<Rings> {
    let outer = contour_points(&c.outer, chord_error, tolerance)?;
    let mut holes = Vec::with_capacity(c.holes.len());
    for hole in &c.holes {
        holes.push(contour_points(hole, chord_error, tolerance)?);
    }
    Ok(orient_rings(outer, holes))
}

/// Rectangle, optionally hollow, with sharp corners (rounded ones go
/// through the exact contour).
fn rectangle_rings(
    r: &RectangleProfile,
    _chord_error: Scalar,
    tolerance: Tolerance,
) -> GeomResult<Rings> {
    if !(r.x.is_finite() && r.y.is_finite()) || r.x <= 0.0 || r.y <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "rectangle profile must have positive finite extents, got {} x {}",
            r.x, r.y
        )));
    }
    let (hx, hy) = (r.x / 2.0, r.y / 2.0);
    let outer = vec![
        Point2::new(-hx, -hy),
        Point2::new(hx, -hy),
        Point2::new(hx, hy),
        Point2::new(-hx, hy),
    ];
    let mut holes = Vec::new();
    if let Some(t) = r.thickness {
        if t <= 0.0 || 2.0 * t >= r.x || 2.0 * t >= r.y {
            return Err(GeomError::InvalidInput(format!(
                "hollow rectangle wall thickness {t} does not fit inside {} x {}",
                r.x, r.y
            )));
        }
        let (ix, iy) = (hx - t, hy - t);
        if !tolerance.eq(ix, 0.0) && !tolerance.eq(iy, 0.0) {
            // Clockwise: opposite winding to the outer ring marks it a hole.
            holes.push(vec![
                Point2::new(-ix, -iy),
                Point2::new(-ix, iy),
                Point2::new(ix, iy),
                Point2::new(ix, -iy),
            ]);
        }
    }
    Ok(Rings { outer, holes })
}

/// Circle, optionally annular.
fn circle_rings(c: &CircleProfile, chord_error: Scalar) -> GeomResult<Rings> {
    if !c.radius.is_finite() || c.radius <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "circle profile radius must be positive and finite, got {}",
            c.radius
        )));
    }
    // Flattened by the scalar evaluator so a parameterized circle and a
    // contour-declared circular arc obey exactly the same chord budget.
    let outer = flatten_circle(c.radius, chord_error)?;
    let mut holes = Vec::new();
    if let Some(t) = c.thickness {
        if t <= 0.0 || t >= c.radius {
            return Err(GeomError::InvalidInput(format!(
                "annulus wall thickness {t} does not fit inside radius {}",
                c.radius
            )));
        }
        let inner = c.radius - t;
        let mut ring = flatten_circle(inner, chord_error)?;
        ring.reverse(); // clockwise
        holes.push(ring);
    }
    Ok(Rings { outer, holes })
}

/// Ellipse profile, flattened under the chord budget.
fn ellipse_rings(e: &EllipseProfile, chord_error: Scalar) -> GeomResult<Rings> {
    if !e.semi_axis_x.is_finite() || e.semi_axis_x <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "ellipse semi-axis x must be positive and finite, got {}",
            e.semi_axis_x
        )));
    }
    if !e.semi_axis_y.is_finite() || e.semi_axis_y <= 0.0 {
        return Err(GeomError::InvalidInput(format!(
            "ellipse semi-axis y must be positive and finite, got {}",
            e.semi_axis_y
        )));
    }
    use axiolid_core::{Frame2, Interval, Vec2};
    use axiolid_curve::{Curve2, Ellipse2};

    let curve = Curve2::Ellipse(Ellipse2 {
        frame: Frame2 {
            origin: Point2::new(0.0, 0.0),
            x: Vec2::new(1.0, 0.0),
            y: Vec2::new(0.0, 1.0),
        },
        semi_axis_x: e.semi_axis_x,
        semi_axis_y: e.semi_axis_y,
    });
    let mut ring = axiolid_reference::curve::flatten2(
        &curve,
        Interval {
            start: 0.0,
            end: core::f64::consts::TAU,
        },
        chord_error,
        MAX_SUBDIVISION_DEPTH,
    )?;
    // Drop the duplicate closing vertex; a ring is implicitly closed.
    ring.pop();
    Ok(Rings {
        outer: ring,
        holes: Vec::new(),
    })
}

/// Flatten a full circle of `radius` under the chord budget.
///
/// The closing duplicate of the start point is dropped: a ring is implicitly
/// closed, and a repeated vertex would create a zero-length edge that the
/// extruder would turn into a degenerate side quad.
fn flatten_circle(radius: Scalar, chord_error: Scalar) -> GeomResult<Vec<Point2>> {
    use axiolid_core::{Frame2, Interval, Vec2};
    use axiolid_curve::{Circle2, Curve2};

    let curve = Curve2::Circle(Circle2 {
        frame: Frame2 {
            origin: Point2::new(0.0, 0.0),
            x: Vec2::new(1.0, 0.0),
            y: Vec2::new(0.0, 1.0),
        },
        radius,
    });
    let flatten = |start: Scalar| {
        axiolid_reference::curve::flatten2(
            &curve,
            Interval {
                start,
                end: start + core::f64::consts::TAU,
            },
            chord_error,
            MAX_SUBDIVISION_DEPTH,
        )
    };
    // Bisection puts a point at every quarter turn. Started half a step
    // later, the same chords put a chord's middle there instead, strictly
    // inside the circle: a void tangent to a face along an axis direction,
    // as openings are, then leaves a sliver of material rather than a
    // chord point on the face, which would pinch the solid there (#194).
    let steps = flatten(0.0)?.len().saturating_sub(1).max(1);
    let mut ring = flatten(core::f64::consts::PI / steps as Scalar)?;
    ring.pop();
    Ok(ring)
}

/// Triangulate rings into a flat index buffer over a single vertex list.
///
/// The returned vertices are the concatenation `outer ++ holes`, unchanged,
/// and every one of them is a corner of some triangle. Rings may be given
/// either way round; the triangles are counter-clockwise. The result is
/// certified before it is returned (#253): every ring edge is a triangle
/// edge, every other edge is shared by exactly two triangles, so no
/// triangle edge runs past a vertex and an extrusion of the caps closes.
///
/// # Errors
///
/// `InvalidInput`, naming the ring, for rings that do not bound a polygon
/// with holes: fewer than three or non-finite vertices, a repeated vertex,
/// a ring that folds back on or crosses itself or runs along a seam both
/// ways (a keyhole, #270), holes that overlap or touch
/// each other or the outer ring, a hole outside the outer ring or inside
/// another hole. `Degenerate` if the triangulation cannot be certified.
///
/// Touching rings are refused because this is the cap of a solid
/// ([`PinchPolicy::Refuse`]); a 2D region or a planar surface patch uses
/// [`triangulate_with`] and [`PinchPolicy::Accept`].
pub fn triangulate(rings: &Rings) -> GeomResult<(Vec<Point2>, Vec<[u32; 3]>)> {
    triangulate_with(rings, PinchPolicy::Refuse)
}

/// How a triangulation treats rings that touch at a single point (#262):
/// a hole touching the outer ring or another hole at a vertex, an outer
/// ring pinched at a vertex, or a vertex lying on another ring's edge.
///
/// The region such rings bound is valid, but the surface an extrusion
/// builds over it is not a two-manifold: the walls of the two rings meet
/// along one edge, which four faces then share. So solids refuse it and
/// regions and surface patches accept it. The same holds for a ring that
/// joins a hole by a seam it runs along both ways (#270): its region is
/// the outer polygon less the hole, but an extrusion puts two coincident
/// wall faces on the seam.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PinchPolicy {
    /// Refuse touching rings and seams with `InvalidInput` naming them. For
    /// anything that must close into a two-manifold: extrusion and loft
    /// caps.
    Refuse,
    /// Triangulate the region the touching rings bound. For 2D regions and
    /// planar surface patches: a plan footprint that is a union of shadows
    /// touching at a corner, a space-boundary surface, a planar face of a
    /// B-rep (whose edges are the ring edges either way, once a vertex
    /// inside an edge, which [`ring_touches`] lists, is inserted into the
    /// neighbouring face's copy of that edge too). A ring joining a hole by
    /// a seam run both ways (a keyhole, #270) is accepted too.
    Accept,
}

/// [`triangulate`] under an explicit [`PinchPolicy`].
///
/// Under [`PinchPolicy::Refuse`] this is [`triangulate`]. Under
/// [`PinchPolicy::Accept`] rings may also touch at single points: where two
/// edges meet at a point that is a vertex of at least one of them. The
/// region is then the points inside the outer ring and outside every hole
/// (for a ring pinched into loops, inside an odd number of its loops),
/// split into its connected parts at the pinches; each part is triangulated
/// and the whole is certified as [`triangulate`] is, with each visit of a
/// pinch point counted as its own vertex. A point several vertices share is
/// referenced by its first index in `outer ++ holes`, and a vertex on
/// another ring's edge splits that edge, so the ring edges of the result
/// are the rings' edges cut at every touching vertex. Rings touching
/// nowhere triangulate exactly as under [`PinchPolicy::Refuse`].
///
/// Under [`PinchPolicy::Accept`] a ring may also join a hole by a seam
/// (#270): an edge and a later edge of the same ring between the same two
/// points in opposite directions, which no other edge has, and which no
/// other edge meets except at its ends -- a keyhole, the outer boundary,
/// the seam, the hole and the seam back. The two copies cancel: the ring
/// bounds what its other edges bound, and is split at its seams into the
/// loops they join, triangulated as above (a hole loop drawn either way
/// round is a hole; a seam between two loops side by side leaves two
/// parts). A seam may be a triangle edge, once each way, or none at all;
/// a planar face of a closed shell uses [`triangulate_shell_face`], which
/// never makes it one (#283).
///
/// # Errors
///
/// As [`triangulate`], except that touching at single points and seams
/// are accepted under [`PinchPolicy::Accept`]. Rings that cross, at a
/// shared vertex included, or overlap along an edge are refused by name
/// under both, and so are, under [`PinchPolicy::Accept`], an edge running
/// back along only part of another, the same edge in one direction twice
/// or more than twice in all, seams interleaving along their ring instead
/// of nesting, seams in a row, an edge crossing, touching or running along
/// a seam away from its ends, and a loop folding back where a seam left
/// it. [`PinchPolicy::Refuse`] refuses any seam by name.
pub fn triangulate_with(
    rings: &Rings,
    pinches: PinchPolicy,
) -> GeomResult<(Vec<Point2>, Vec<[u32; 3]>)> {
    check_ring_sizes(rings)?;
    crate::ring_triangulation::triangulate_rings(&rings.outer, &rings.holes, pinches)
}

/// Refuse an outer ring or a hole of fewer than three vertices.
fn check_ring_sizes(rings: &Rings) -> GeomResult<()> {
    if rings.outer.len() < 3 {
        return Err(GeomError::InvalidInput(format!(
            "profile outer ring needs at least 3 vertices, got {}",
            rings.outer.len()
        )));
    }
    for hole in &rings.holes {
        if hole.len() < 3 {
            return Err(GeomError::InvalidInput(format!(
                "profile hole needs at least 3 vertices, got {}",
                hole.len()
            )));
        }
    }
    Ok(())
}

/// A vertex lying inside an edge of a ring, away from both its ends, as
/// [`triangulate_with`] finds it under [`PinchPolicy::Accept`] (#265).
///
/// Indices follow [`triangulate_with`]: ring `0` is the outer ring and ring
/// `h + 1` hole `h`; edge `k` of a ring runs from its vertex `k` to its
/// vertex `k + 1` (the last back to the first); `vertex` indexes
/// `outer ++ holes`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RingTouch {
    /// The ring whose edge the vertex lies in.
    pub ring: usize,
    /// The edge of that ring.
    pub edge: usize,
    /// The vertex, by its index in `outer ++ holes`.
    pub vertex: usize,
}

/// Every vertex lying inside another edge of `rings`, decided by the same
/// exact `orient2d` tests with which [`triangulate_with`] under
/// [`PinchPolicy::Accept`] inserts it into that edge (#265).
///
/// The triangulation then splits that edge at the vertex, so its ring edges
/// are no longer the rings' edges. A caller whose rings share their edges
/// with neighbouring patches (the faces of a closed shell) splits the
/// neighbour's copy of each such edge at the same vertex, or the patches
/// meet at a T-junction. Validation runs as in [`triangulate_with`] and in
/// the same order, so the touches come in a deterministic order, each
/// vertex and edge pair once; nothing is triangulated.
///
/// A ring with a seam run both ways (a keyhole, #270) is validated as
/// [`triangulate_with`] validates it, without its seams: the touches are
/// those of the loops the seams join, on their edges, which are the ring's
/// other edges. No vertex lies inside a seam, and a seam's ends, where the
/// ring meets itself, are shared vertices, not touches.
///
/// # Errors
///
/// As [`triangulate_with`] under [`PinchPolicy::Accept`] for rings that do
/// not bound a region: too few, non-finite or repeated vertices, a ring
/// folding back, rings that cross or overlap along an edge, a seam that is
/// not one.
pub fn ring_touches(rings: &Rings) -> GeomResult<Vec<RingTouch>> {
    crate::ring_triangulation::ring_touches(&rings.outer, &rings.holes).map(|touches| {
        touches
            .into_iter()
            .map(|(ring, edge, vertex)| RingTouch { ring, edge, vertex })
            .collect()
    })
}

/// A triangulation of a planar face of a closed shell, from
/// [`triangulate_shell_face`] (#283).
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct ShellFaceTriangulation {
    /// `outer ++ holes`, then each of [`Self::steiner`] at the position
    /// its chain of midpoints gives in the plane.
    pub points: Vec<Point2>,
    /// Counter-clockwise triangles over [`Self::points`].
    pub triangles: Vec<[u32; 3]>,
    /// The points added inside the face, in order: point `k` of these is
    /// `points[outer.len() + holes' lengths + k]`.
    pub steiner: Vec<SteinerPoint>,
}

/// A point [`triangulate_shell_face`] adds inside a face, as a chain of
/// midpoints of the face's own points (#283): the midpoint `m` of the
/// seam from `seam[0]` to `seam[1]`, then `halvings` times the midpoint
/// of `m` and the point so far, starting from `toward`.
///
/// A caller that lifts the face back into space places the point with the
/// same chain over its own points ([`Self::place`]). On a face lying in an
/// axis plane, the midpoint of two points with that coordinate in common
/// keeps it exactly, so the point lies exactly in the plane; elsewhere it
/// lies within the rounding of the chain.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SteinerPoint {
    /// The seam's two ends, by index into
    /// [`ShellFaceTriangulation::points`].
    pub seam: [u32; 2],
    /// The point the seam's midpoint is moved towards: a corner of one of
    /// the seam's two triangles, possibly an earlier Steiner point.
    pub toward: u32,
    /// How often the point is moved half way, at least once.
    pub halvings: u32,
}

impl SteinerPoint {
    /// The point by its chain of midpoints, over any point type: `at`
    /// gives a point by its index (earlier Steiner points included), and
    /// `midpoint` the midpoint of two points.
    pub fn place<T: Copy>(&self, at: impl Fn(u32) -> T, midpoint: impl Fn(T, T) -> T) -> T {
        crate::ring_triangulation::Steiner {
            seam: self.seam,
            toward: self.toward,
            halvings: self.halvings,
        }
        .place(at, midpoint)
    }
}

/// Triangulate a planar face of a closed shell (#283): as
/// [`triangulate_with`] under [`PinchPolicy::Accept`], and no triangle
/// edge lies on a seam.
///
/// A seam (a keyhole's segment run both ways, #270) may be a triangle edge
/// there. Inside one face that is only a diagonal, but other faces of a
/// shell can run along the same segment (a rim's two end faces at its
/// cut), and with the seam a triangle edge too that segment has four
/// triangle uses. So where a seam would be a triangle edge, the two
/// triangles on it are replaced: by the other diagonal of their
/// quadrilateral where it is strictly convex, otherwise by four triangles
/// around a [`SteinerPoint`] strictly inside it and off the seam's line
/// (a thin rim seamed at its corner has no triangulation on its own
/// vertices without the seam). A Steiner point adds no area and moves no
/// boundary: the result is certified against the cover it replaces, the
/// same boundary edges with every triangle strictly counter-clockwise.
///
/// Rings without a seam triangulate exactly as under
/// [`PinchPolicy::Accept`], with no Steiner point.
///
/// # Errors
///
/// As [`triangulate_with`] under [`PinchPolicy::Accept`]; `Degenerate`
/// naming the seam when no Steiner point can be placed off it, and when
/// the result fails its certificate.
pub fn triangulate_shell_face(rings: &Rings) -> GeomResult<ShellFaceTriangulation> {
    check_ring_sizes(rings)?;
    let (points, triangles, steiner) =
        crate::ring_triangulation::triangulate_sealed(&rings.outer, &rings.holes)?;
    Ok(ShellFaceTriangulation {
        points,
        triangles,
        steiner: steiner
            .into_iter()
            .map(|s| SteinerPoint {
                seam: s.seam,
                toward: s.toward,
                halvings: s.halvings,
            })
            .collect(),
    })
}

/// Apply a 2D affine transform to a ring in place.
fn apply2(ring: &mut [Point2], t: &axiolid_core::Transform2) {
    for p in ring.iter_mut() {
        *p = t.transform_point2(*p);
    }
}

/// Flatten one closed contour into a point ring.
///
/// Consecutive duplicate points are dropped: adjoining segments share an
/// endpoint by construction, and the triangulation refuses a repeated
/// vertex as a zero-length edge.
fn contour_points(
    contour: &axiolid_profile::Contour,
    chord_error: Scalar,
    tolerance: Tolerance,
) -> GeomResult<Vec<Point2>> {
    let mut merged = 0.0;
    contour_points_measured(contour, chord_error, tolerance, &mut merged)
}

/// [`contour_points`], also raising `merged` to the largest distance
/// between a dropped near-duplicate point and the point it merged into
/// (#232): dropping it moves the ring by no more than that.
fn contour_points_measured(
    contour: &axiolid_profile::Contour,
    chord_error: Scalar,
    tolerance: Tolerance,
    merged: &mut Scalar,
) -> GeomResult<Vec<Point2>> {
    let mut out: Vec<Point2> = Vec::new();
    for segment in &contour.segments {
        let mut pts = segment_points(segment, chord_error)?;
        if !segment.same_sense {
            pts.reverse();
        }
        for p in pts {
            match out.last() {
                Some(last) if near2(*last, p, tolerance.linear()) => {
                    *merged = merged.max((*last - p).length());
                }
                _ => out.push(p),
            }
        }
    }
    // A closed ring must not repeat its first point as its last.
    while out.len() > 1 && near2(out[0], *out.last().expect("non-empty"), tolerance.linear()) {
        let dropped = out.pop().expect("non-empty");
        *merged = merged.max((out[0] - dropped).length());
    }
    if out.len() < 3 {
        return Err(GeomError::Degenerate(format!(
            "contour flattened to {} points, need at least 3",
            out.len()
        )));
    }
    Ok(out)
}

/// Whether two points coincide within a linear tolerance.
fn near2(a: Point2, b: Point2, linear: Scalar) -> bool {
    (a.x - b.x).abs() <= linear && (a.y - b.y).abs() <= linear
}

/// Sample one bounded segment, flattening curves under the chord budget.
///
/// Delegates to `axiolid-reference`'s curve evaluator (ADR 0012). This crate used
/// to carry a private circle flattener with a closed-form segment count, and
/// refused ellipses and B-splines outright. Both limits are gone: the scalar
/// evaluator subdivides adaptively on measured sagitta, so every declared
/// `Curve2` family flattens under the same tolerance contract.
///
/// `MAX_SUBDIVISION_DEPTH` bounds the work. 24 levels is 16M potential
/// segments -- far beyond any real tolerance -- so it is a runaway guard, not
/// a quality knob.
const MAX_SUBDIVISION_DEPTH: u32 = 24;

fn segment_points(
    segment: &axiolid_profile::ProfileSegment,
    chord_error: Scalar,
) -> GeomResult<Vec<Point2>> {
    axiolid_reference::curve::flatten2(
        &segment.curve,
        segment.domain,
        chord_error,
        MAX_SUBDIVISION_DEPTH,
    )
}

/// Force the ring-orientation convention the extruder expects:
/// outer counter-clockwise, holes clockwise.
///
/// Source contours carry whatever orientation the authoring tool wrote, so
/// normalising here is cheaper than rejecting otherwise-valid geometry.
use axiolid_reference::signed_area2;

fn orient_rings(mut outer: Vec<Point2>, mut holes: Vec<Vec<Point2>>) -> Rings {
    if signed_area2(&outer) < 0.0 {
        outer.reverse();
    }
    for hole in &mut holes {
        if signed_area2(hole) > 0.0 {
            hole.reverse();
        }
    }
    Rings { outer, holes }
}