hypercurve 0.2.0

Hyperreal-backed planar curves, contours, and regions for CAD topology
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! Primitive parallel offsets for line and circular-arc segments.
//!
//! Offsetting is split into primitive parallel curves, joins/caps, and later
//! trimming/rebuild work. The staged construction follows Tiller and Hanson,
//! "Offsets of Two-Dimensional Profiles" (*IEEE Computer Graphics and
//! Applications* 4(9), 36-46, 1984). The reason checked offsets reject raw
//! self-intersections instead of accepting them is the offset-curve topology
//! described by Farouki and Neff, "Analytic Properties of Plane Offset Curves"
//! (*Computer Aided Geometric Design* 7(1-4), 83-99, 1990), where offsets may
//! form cusps and extraneous loops that require trimming.

use hyperreal::{Real, RealSign};

use crate::classify::{is_zero, real_sign};
use crate::contour::Contour2;
use crate::curve_string::CurveString2;
use crate::segment::{CircularArc2, LineSeg2, Segment2};
use crate::{Classification, CurveError, CurvePolicy, CurveResult, Point2, UncertaintyReason};

/// Endpoint cap style for checked open curve-string outlines.
///
/// The cap is applied after the source curve string has been offset on both
/// sides. This enum describes only the endpoint construction; joins along the
/// left and right traces still use the primitive offset and line/round-join
/// machinery documented on [`CurveString2::offset_left_with_line_joins`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OffsetCap {
    /// Connect left and right traces with circular arcs centered on endpoints.
    Round,
    /// Connect left and right traces directly at each endpoint.
    Butt,
    /// Extend each trace by one half-width along endpoint tangents before
    /// adding straight endpoint connectors.
    Square,
}

impl LineSeg2 {
    /// Returns the constant-distance segment on this segment's left side.
    ///
    /// The offset direction is the normalized left normal `(-dy, dx) / length`.
    /// This is the primitive line-profile case used by profile offset
    /// algorithms; higher-level curve-string offsetting must still add joins,
    /// trim self-intersections, and rebuild topology. See Tiller and Hanson,
    /// "Offsets of Two-Dimensional Profiles" (1984), for the line/arc
    /// primitive plus trim-and-join framing used by many CAD offset pipelines.
    pub fn offset_left(&self, distance: Real) -> CurveResult<Self> {
        let length = self.length_squared().sqrt()?;
        let (dx, dy) = self.delta();
        let normal_x = ((-dy) / &length)?;
        let normal_y = (dx / &length)?;
        let offset_x = &normal_x * &distance;
        let offset_y = &normal_y * &distance;

        Self::try_new(
            self.start().translated(offset_x.clone(), offset_y.clone()),
            self.end().translated(offset_x, offset_y),
        )
    }
}

impl CircularArc2 {
    /// Returns the constant-distance arc on this arc's left side.
    ///
    /// Counter-clockwise arcs have their left normal on the circle interior, so
    /// a positive offset decreases radius. Clockwise arcs have their left normal
    /// on the exterior, so a positive offset increases radius. Radius collapse
    /// and radius sign reversal are returned as explicit uncertainty because
    /// the primitive arc no longer has a valid circular-arc image at that
    /// distance. Tiller and Hanson, "Offsets of Two-Dimensional Profiles"
    /// (1984), describe this concentric-arc primitive as one step in a complete
    /// profile offset pipeline.
    pub fn offset_left(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Self>> {
        let radius = self.radius_squared().sqrt()?;
        let offset_radius = if self.is_clockwise() {
            &radius + &distance
        } else {
            &radius - &distance
        };

        match real_sign(&offset_radius, policy) {
            Some(RealSign::Positive) => {}
            Some(RealSign::Zero | RealSign::Negative) => {
                return Ok(Classification::Uncertain(UncertaintyReason::Unsupported));
            }
            None => return Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
        }

        let radius_scale = (offset_radius / &radius)?;
        let offset = Self::try_from_center_with_bulge(
            scale_from_center(self.start(), self.center(), &radius_scale),
            scale_from_center(self.end(), self.center(), &radius_scale),
            self.center().clone(),
            self.is_clockwise(),
            self.bulge().cloned(),
        )?;
        Ok(Classification::Decided(offset))
    }
}

impl Segment2 {
    /// Returns this segment's left-side primitive offset.
    ///
    /// Lines always produce a translated line. Arcs produce a concentric arc
    /// when the requested distance leaves a positive radius; radius collapse or
    /// reversal is reported as uncertainty instead of fabricating degenerate
    /// topology.
    pub fn offset_left(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Self>> {
        match self {
            Self::Line(line) => line
                .offset_left(distance)
                .map(Self::Line)
                .map(Classification::Decided),
            Self::Arc(arc) => arc
                .offset_left(distance, policy)
                .map(|arc| arc.map(Segment2::Arc)),
        }
    }
}

impl CurveString2 {
    /// Returns a left offset of this open curve string with straight-line joins.
    ///
    /// This is a raw offset-construction layer, not a full offset engine. Each
    /// source segment is first replaced by its primitive parallel offset. Adjacent
    /// offset lines are mitered by intersecting their supporting lines; joins
    /// that cannot be mitered are connected by a circular arc centered at the
    /// original shared vertex. A complete profile offset pipeline still has to
    /// classify join style, trim self-intersections, and cap open endpoints.
    /// Tiller and Hanson, "Offsets of Two-Dimensional Profiles" (1984),
    /// describe this staged primitive, join, and trim structure for
    /// two-dimensional profile offsets.
    pub fn offset_left_with_line_joins(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Self>> {
        if is_zero(&distance, policy) == Some(true) {
            return Ok(Classification::Decided(self.clone()));
        }

        let offsets = match offset_segments_left(self.segments(), &distance, policy)? {
            Classification::Decided(offsets) => offsets,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        let joined = match joined_offset_segments(self.segments(), &offsets, false, policy)? {
            Classification::Decided(joined) => joined,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        Ok(Classification::Decided(CurveString2::new_unchecked(joined)))
    }

    /// Returns a raw joined left offset, rejecting self-contacting output.
    ///
    /// This method does not trim self-intersections or cap open endpoints. It
    /// runs the joined open offset construction and then classifies the result
    /// with [`CurveString2::has_self_contacts`]. A detected self contact is
    /// reported as explicit uncertainty so callers can choose a future trimming
    /// path instead of consuming invalid raw linework. Farouki and Neff,
    /// "Analytic Properties of Plane Offset Curves" (1990), describe exactly
    /// these self-intersections and extraneous loops as offset topology that
    /// must be trimmed before the curve can represent the intended profile.
    pub fn offset_left_checked(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Self>> {
        let offset = match self.offset_left_with_line_joins(distance, policy)? {
            Classification::Decided(offset) => offset,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };

        match offset.has_self_contacts(policy)? {
            Classification::Decided(false) => Ok(Classification::Decided(offset)),
            Classification::Decided(true) => {
                Ok(Classification::Uncertain(UncertaintyReason::Unsupported))
            }
            Classification::Uncertain(reason) => Ok(Classification::Uncertain(reason)),
        }
    }

    /// Builds a checked closed outline around this open curve string.
    ///
    /// The outline follows the left joined offset, applies the selected
    /// [`OffsetCap`] at the end point, returns along the reversed right joined
    /// offset, and applies the matching cap at the start point. The `distance`
    /// is the half-width of the outline and must be strictly positive under
    /// the active policy. As with [`CurveString2::offset_left_checked`], this
    /// is still the raw offset-construction stage described by Tiller and
    /// Hanson, "Offsets of Two-Dimensional Profiles" (1984): self-contacting
    /// input or output is rejected as explicit uncertainty until the
    /// trim/rebuild stage exists.
    pub fn offset_outline(
        &self,
        distance: Real,
        cap: OffsetCap,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Contour2>> {
        match cap {
            OffsetCap::Round => self.offset_outline_round_caps(distance, policy),
            OffsetCap::Butt => self.offset_outline_butt_caps(distance, policy),
            OffsetCap::Square => self.offset_outline_square_caps(distance, policy),
        }
    }

    /// Builds a checked closed outline around this open curve string.
    ///
    /// The outline follows the left joined offset, adds a round cap at the end
    /// point, returns along the reversed right joined offset, and adds a round
    /// cap at the start point. The `distance` is the half-width of the outline
    /// and must be strictly positive under the active policy. As with
    /// [`CurveString2::offset_left_checked`], this is still a raw offset
    /// construction: if the input or resulting closed outline self-contacts,
    /// the method returns explicit uncertainty instead of trimming. Tiller and
    /// Hanson, "Offsets of Two-Dimensional Profiles" (1984), describe this
    /// primitive offset, cap, and trim decomposition for open profile offsets.
    pub fn offset_outline_round_caps(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Contour2>> {
        let offsets = match checked_outline_offsets(self, distance, policy)? {
            Classification::Decided(offsets) => offsets,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        let OutlineOffsets {
            left,
            right,
            start_center,
            end_center,
            left_start,
            left_end,
            right_start,
            right_end,
        } = offsets;

        let mut segments = Vec::with_capacity(left.len() + right.len() + 2);
        segments.extend(left.into_segments());
        match round_cap_arc(&left_end, &right_end, &end_center, policy)? {
            Classification::Decided(cap) => segments.push(Segment2::Arc(cap)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }
        segments.extend(reversed_segments(right.into_segments()));
        match round_cap_arc(&right_start, &left_start, &start_center, policy)? {
            Classification::Decided(cap) => segments.push(Segment2::Arc(cap)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }

        checked_outline_contour(segments, policy)
    }

    /// Builds a checked closed outline around this open curve string.
    ///
    /// This variant connects the left and right offset traces with straight
    /// endpoint caps. Those cap lines are the radial/perpendicular endpoint
    /// connectors in the same primitive-offset, cap, and trim decomposition
    /// used for open profiles by Tiller and Hanson, "Offsets of
    /// Two-Dimensional Profiles" (1984). The distance is the half-width and
    /// must be strictly positive. As with round caps, this constructor rejects
    /// self-contacting input or output instead of trimming the raw outline.
    pub fn offset_outline_butt_caps(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Contour2>> {
        let offsets = match checked_outline_offsets(self, distance, policy)? {
            Classification::Decided(offsets) => offsets,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        let OutlineOffsets {
            left,
            right,
            left_start,
            left_end,
            right_start,
            right_end,
            ..
        } = offsets;

        let mut segments = Vec::with_capacity(left.len() + right.len() + 2);
        segments.extend(left.into_segments());
        match cap_line(&left_end, &right_end)? {
            Classification::Decided(cap) => segments.push(Segment2::Line(cap)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }
        segments.extend(reversed_segments(right.into_segments()));
        match cap_line(&right_start, &left_start)? {
            Classification::Decided(cap) => segments.push(Segment2::Line(cap)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }

        checked_outline_contour(segments, policy)
    }

    /// Builds a checked closed outline with square endpoint caps.
    ///
    /// Square caps extend both offset traces by one half-width along the source
    /// endpoint tangent before connecting them with a straight cap line. For
    /// line endpoints this can be folded into the endpoint offset segment; for
    /// arc endpoints it becomes an explicit tangent extension line so the
    /// circular offset arc remains exact. This is still the primitive
    /// offset/cap construction stage described by Tiller and Hanson, "Offsets
    /// of Two-Dimensional Profiles" (1984): self-contacting input or output is
    /// rejected as uncertainty until the trim/rebuild stage exists.
    pub fn offset_outline_square_caps(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Contour2>> {
        let offsets = match checked_outline_offsets(self, distance.clone(), policy)? {
            Classification::Decided(offsets) => offsets,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        let OutlineOffsets {
            left,
            right,
            left_start,
            left_end,
            right_start,
            right_end,
            ..
        } = offsets;

        let start_tangent = unit_tangent_at_segment_start(
            self.segments()
                .first()
                .ok_or(CurveError::EmptyCurveString)?,
        )?;
        let end_tangent = unit_tangent_at_segment_end(
            self.segments().last().ok_or(CurveError::EmptyCurveString)?,
        )?;
        let start_dx = &start_tangent.0 * &distance;
        let start_dy = &start_tangent.1 * &distance;
        let end_dx = &end_tangent.0 * &distance;
        let end_dy = &end_tangent.1 * &distance;

        let left_start_square = left_start.translated(-start_dx.clone(), -start_dy.clone());
        let right_start_square = right_start.translated(-start_dx, -start_dy);
        let left_end_square = left_end.translated(end_dx.clone(), end_dy.clone());
        let right_end_square = right_end.translated(end_dx, end_dy);

        let left = match extend_square_cap_trace(
            left.into_segments(),
            left_start_square.clone(),
            left_end_square.clone(),
        )? {
            Classification::Decided(left) => left,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        let right = match extend_square_cap_trace(
            right.into_segments(),
            right_start_square.clone(),
            right_end_square.clone(),
        )? {
            Classification::Decided(right) => right,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };

        let mut segments = Vec::with_capacity(left.len() + right.len() + 2);
        segments.extend(left);
        match cap_line(&left_end_square, &right_end_square)? {
            Classification::Decided(cap) => segments.push(Segment2::Line(cap)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }
        segments.extend(reversed_segments(right));
        match cap_line(&right_start_square, &left_start_square)? {
            Classification::Decided(cap) => segments.push(Segment2::Line(cap)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }

        checked_outline_contour(segments, policy)
    }
}

impl Contour2 {
    /// Returns a left offset of this closed contour with straight-line joins.
    ///
    /// Line-line corners are mitered at the exact supporting-line intersection
    /// whenever that relation can be classified. Joins that cannot be mitered
    /// are connected by a circular arc centered at the original shared vertex.
    /// The returned contour is checked for closure, but this method deliberately
    /// does not trim self-intersections or resolve collapsed regions; those
    /// operations belong to the later full offset pipeline described by Tiller
    /// and Hanson, "Offsets of Two-Dimensional Profiles" (1984).
    pub fn offset_left_with_line_joins(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Self>> {
        if is_zero(&distance, policy) == Some(true) {
            return Ok(Classification::Decided(self.clone()));
        }

        let offsets = match offset_segments_left(self.segments(), &distance, policy)? {
            Classification::Decided(offsets) => offsets,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        let joined = match joined_offset_segments(self.segments(), &offsets, true, policy)? {
            Classification::Decided(joined) => joined,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        Ok(Classification::Decided(Contour2::new_unchecked(
            CurveString2::new_unchecked(joined),
            self.fill_rule(),
        )))
    }

    /// Returns a raw joined left offset, rejecting self-contacting output.
    ///
    /// This method does not trim self-intersections. It runs the joined offset
    /// construction and then classifies the result with
    /// [`Contour2::has_self_contacts`]. A detected self contact is reported as
    /// explicit uncertainty so callers do not mistake an untrimmed raw offset
    /// for a regularized contour. This matches Farouki and Neff's offset-curve
    /// treatment of self-intersections and extraneous loops as a separate
    /// trimming stage, not a property of the primitive parallel curve itself.
    pub fn offset_left_checked(
        &self,
        distance: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<Self>> {
        let offset = match self.offset_left_with_line_joins(distance, policy)? {
            Classification::Decided(offset) => offset,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };

        match offset.has_self_contacts(policy)? {
            Classification::Decided(false) => Ok(Classification::Decided(offset)),
            Classification::Decided(true) => {
                Ok(Classification::Uncertain(UncertaintyReason::Unsupported))
            }
            Classification::Uncertain(reason) => Ok(Classification::Uncertain(reason)),
        }
    }
}

fn scale_from_center(point: &Point2, center: &Point2, scale: &Real) -> Point2 {
    let radius = point.delta_from(center);
    Point2::new(
        center.x() + (&radius.0 * scale),
        center.y() + (&radius.1 * scale),
    )
}

struct OutlineOffsets {
    left: CurveString2,
    right: CurveString2,
    start_center: Point2,
    end_center: Point2,
    left_start: Point2,
    left_end: Point2,
    right_start: Point2,
    right_end: Point2,
}

// Shared setup for open-profile outlines. The public cap variants differ only
// in how they connect the two offset traces; both must enforce the same
// positive-distance and no-self-contact preconditions before exposing a closed
// contour to callers.
fn checked_outline_offsets(
    source: &CurveString2,
    distance: Real,
    policy: &CurvePolicy,
) -> CurveResult<Classification<OutlineOffsets>> {
    match real_sign(&distance, policy) {
        Some(RealSign::Positive) => {}
        Some(RealSign::Zero | RealSign::Negative) => {
            return Ok(Classification::Uncertain(UncertaintyReason::Unsupported));
        }
        None => return Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
    }

    match source.has_self_contacts(policy)? {
        Classification::Decided(false) => {}
        Classification::Decided(true) => {
            return Ok(Classification::Uncertain(UncertaintyReason::Unsupported));
        }
        Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
    }

    let left = match source.offset_left_with_line_joins(distance.clone(), policy)? {
        Classification::Decided(left) => left,
        Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
    };
    let right = match source.offset_left_with_line_joins(-distance, policy)? {
        Classification::Decided(right) => right,
        Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
    };

    Ok(Classification::Decided(OutlineOffsets {
        start_center: source.start().ok_or(CurveError::EmptyCurveString)?.clone(),
        end_center: source.end().ok_or(CurveError::EmptyCurveString)?.clone(),
        left_start: left.start().ok_or(CurveError::EmptyCurveString)?.clone(),
        left_end: left.end().ok_or(CurveError::EmptyCurveString)?.clone(),
        right_start: right.start().ok_or(CurveError::EmptyCurveString)?.clone(),
        right_end: right.end().ok_or(CurveError::EmptyCurveString)?.clone(),
        left,
        right,
    }))
}

// Contour closure and self-contact checks are deliberately centralized so every
// open-outline cap style preserves the same "raw construction, no trimming"
// contract described by Tiller and Hanson (1984).
fn checked_outline_contour(
    segments: Vec<Segment2>,
    policy: &CurvePolicy,
) -> CurveResult<Classification<Contour2>> {
    let outline = match Contour2::try_new(segments) {
        Ok(outline) => outline,
        Err(CurveError::DisconnectedCurveString) => {
            return Ok(Classification::Uncertain(UncertaintyReason::Unsupported));
        }
        Err(CurveError::AmbiguousCurveStringConnection) => {
            return Ok(Classification::Uncertain(UncertaintyReason::RealSign));
        }
        Err(error) => return Err(error),
    };
    match outline.has_self_contacts(policy)? {
        Classification::Decided(false) => Ok(Classification::Decided(outline)),
        Classification::Decided(true) => {
            Ok(Classification::Uncertain(UncertaintyReason::Unsupported))
        }
        Classification::Uncertain(reason) => Ok(Classification::Uncertain(reason)),
    }
}

fn extend_square_cap_trace(
    mut segments: Vec<Segment2>,
    extended_start: Point2,
    extended_end: Point2,
) -> CurveResult<Classification<Vec<Segment2>>> {
    if segments.is_empty() {
        return Err(CurveError::EmptyCurveString);
    }

    let original_start = segments[0].start().clone();
    match &segments[0] {
        Segment2::Line(line) => {
            segments[0] = match cap_line(&extended_start, line.end())? {
                Classification::Decided(line) => Segment2::Line(line),
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            };
        }
        Segment2::Arc(_) => match cap_line(&extended_start, &original_start)? {
            Classification::Decided(line) => segments.insert(0, Segment2::Line(line)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        },
    }

    let last_index = segments.len() - 1;
    let original_end = segments[last_index].end().clone();
    match &segments[last_index] {
        Segment2::Line(line) => {
            segments[last_index] = match cap_line(line.start(), &extended_end)? {
                Classification::Decided(line) => Segment2::Line(line),
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            };
        }
        Segment2::Arc(_) => match cap_line(&original_end, &extended_end)? {
            Classification::Decided(line) => segments.push(Segment2::Line(line)),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        },
    }

    Ok(Classification::Decided(segments))
}

fn unit_tangent_at_segment_start(segment: &Segment2) -> CurveResult<(Real, Real)> {
    match segment {
        Segment2::Line(line) => unit_tangent_for_line(line),
        Segment2::Arc(arc) => unit_tangent_for_arc_at_point(arc, arc.start()),
    }
}

fn unit_tangent_at_segment_end(segment: &Segment2) -> CurveResult<(Real, Real)> {
    match segment {
        Segment2::Line(line) => unit_tangent_for_line(line),
        Segment2::Arc(arc) => unit_tangent_for_arc_at_point(arc, arc.end()),
    }
}

fn unit_tangent_for_line(line: &LineSeg2) -> CurveResult<(Real, Real)> {
    let length = line.length_squared().sqrt()?;
    let (dx, dy) = line.delta();
    Ok(((dx / &length)?, (dy / &length)?))
}

fn unit_tangent_for_arc_at_point(arc: &CircularArc2, point: &Point2) -> CurveResult<(Real, Real)> {
    let radius = arc.radius_squared().sqrt()?;
    let (rx, ry) = point.delta_from(arc.center());
    if arc.is_clockwise() {
        Ok(((ry / &radius)?, ((-rx) / &radius)?))
    } else {
        Ok(((-ry / &radius)?, (rx / &radius)?))
    }
}

fn offset_segments_left(
    segments: &[Segment2],
    distance: &Real,
    policy: &CurvePolicy,
) -> CurveResult<Classification<Vec<Segment2>>> {
    let mut offsets = Vec::with_capacity(segments.len());
    for segment in segments {
        match segment.offset_left(distance.clone(), policy)? {
            Classification::Decided(offset) => offsets.push(offset),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }
    }
    Ok(Classification::Decided(offsets))
}

#[derive(Clone, Debug, PartialEq)]
enum OffsetJoin {
    Miter(Point2),
    Round { center: Point2 },
}

fn joined_offset_segments(
    source: &[Segment2],
    offsets: &[Segment2],
    closed: bool,
    policy: &CurvePolicy,
) -> CurveResult<Classification<Vec<Segment2>>> {
    if offsets.is_empty() {
        return Err(CurveError::EmptyCurveString);
    }
    if source.len() != offsets.len() {
        return Err(CurveError::Topology(
            "source and offset segment counts differ".into(),
        ));
    }

    let join_count = if closed {
        offsets.len()
    } else {
        offsets.len().saturating_sub(1)
    };
    let mut joins = Vec::with_capacity(join_count);
    for index in 0..join_count {
        let next_index = (index + 1) % offsets.len();
        match classify_offset_join(
            &source[index],
            &source[next_index],
            &offsets[index],
            &offsets[next_index],
            policy,
        )? {
            Classification::Decided(join) => joins.push(join),
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }
    }

    let mut joined = Vec::with_capacity(offsets.len() + join_count);
    for index in 0..offsets.len() {
        let start_override = start_miter_for_segment(index, offsets.len(), closed, &joins);
        let end_override = end_miter_for_segment(index, &joins);
        let adjusted = match adjust_offset_segment(
            &offsets[index],
            start_override.as_ref(),
            end_override.as_ref(),
        )? {
            Classification::Decided(segment) => segment,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        joined.push(adjusted);

        if let Some(OffsetJoin::Round { center }) = joins.get(index) {
            let from = joined
                .last()
                .expect("current adjusted offset segment was just pushed")
                .end()
                .clone();
            let to = offsets[(index + 1) % offsets.len()].start().clone();
            match append_round_join_if_needed(&mut joined, &from, &to, center, policy)? {
                Classification::Decided(()) => {}
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            }
        }
    }

    Ok(Classification::Decided(joined))
}

fn classify_offset_join(
    source_previous: &Segment2,
    source_next: &Segment2,
    offset_previous: &Segment2,
    offset_next: &Segment2,
    policy: &CurvePolicy,
) -> CurveResult<Classification<OffsetJoin>> {
    match (offset_previous, offset_next) {
        (Segment2::Line(previous), Segment2::Line(next)) => {
            match line_support_intersection(previous, next, policy)? {
                Classification::Decided(Some(point)) => {
                    Ok(Classification::Decided(OffsetJoin::Miter(point)))
                }
                Classification::Decided(None) => Ok(Classification::Decided(round_join(
                    source_previous,
                    source_next,
                ))),
                Classification::Uncertain(reason) => Ok(Classification::Uncertain(reason)),
            }
        }
        _ => Ok(Classification::Decided(round_join(
            source_previous,
            source_next,
        ))),
    }
}

fn round_join(previous: &Segment2, next: &Segment2) -> OffsetJoin {
    let _ = next;
    OffsetJoin::Round {
        center: previous.end().clone(),
    }
}

fn line_support_intersection(
    previous: &LineSeg2,
    next: &LineSeg2,
    policy: &CurvePolicy,
) -> CurveResult<Classification<Option<Point2>>> {
    let (rx, ry) = previous.delta();
    let (sx, sy) = next.delta();
    let denominator = cross(&rx, &ry, &sx, &sy);

    match real_sign(&denominator, policy) {
        Some(RealSign::Zero) => Ok(Classification::Decided(None)),
        Some(RealSign::Positive | RealSign::Negative) => {
            let qmp = next.start().delta_from(previous.start());
            let numerator = cross(&qmp.0, &qmp.1, &sx, &sy);
            let t = (numerator / &denominator)?;
            Ok(Classification::Decided(Some(previous.point_at(t))))
        }
        None => Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
    }
}

fn start_miter_for_segment(
    index: usize,
    segment_count: usize,
    closed: bool,
    joins: &[OffsetJoin],
) -> Option<Point2> {
    if !closed && index == 0 {
        return None;
    }
    let join_index = if index == 0 {
        segment_count - 1
    } else {
        index - 1
    };
    match joins.get(join_index) {
        Some(OffsetJoin::Miter(point)) => Some(point.clone()),
        _ => None,
    }
}

fn end_miter_for_segment(index: usize, joins: &[OffsetJoin]) -> Option<Point2> {
    match joins.get(index) {
        Some(OffsetJoin::Miter(point)) => Some(point.clone()),
        _ => None,
    }
}

fn adjust_offset_segment(
    segment: &Segment2,
    start_override: Option<&Point2>,
    end_override: Option<&Point2>,
) -> CurveResult<Classification<Segment2>> {
    match segment {
        Segment2::Line(line) => {
            let start = start_override
                .cloned()
                .unwrap_or_else(|| line.start().clone());
            let end = end_override.cloned().unwrap_or_else(|| line.end().clone());
            match LineSeg2::try_new(start, end) {
                Ok(line) => Ok(Classification::Decided(Segment2::Line(line))),
                Err(CurveError::ZeroLengthLine) => {
                    Ok(Classification::Uncertain(UncertaintyReason::Unsupported))
                }
                Err(error) => Err(error),
            }
        }
        Segment2::Arc(_) if start_override.is_some() || end_override.is_some() => {
            Ok(Classification::Uncertain(UncertaintyReason::Unsupported))
        }
        Segment2::Arc(arc) => Ok(Classification::Decided(Segment2::Arc(arc.clone()))),
    }
}

fn append_round_join_if_needed(
    joined: &mut Vec<Segment2>,
    from: &Point2,
    to: &Point2,
    center: &Point2,
    policy: &CurvePolicy,
) -> CurveResult<Classification<()>> {
    let distance = from.distance_squared(to);
    match is_zero(&distance, policy) {
        Some(true) => Ok(Classification::Decided(())),
        Some(false) => {
            let clockwise = match round_join_clockwise(center, from, to, policy) {
                Classification::Decided(clockwise) => clockwise,
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            };
            match round_join_arc(from, to, center, clockwise) {
                Classification::Decided(arc) => {
                    joined.push(Segment2::Arc(arc));
                    Ok(Classification::Decided(()))
                }
                Classification::Uncertain(reason) => Ok(Classification::Uncertain(reason)),
            }
        }
        None => Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
    }
}

fn round_cap_arc(
    from: &Point2,
    to: &Point2,
    center: &Point2,
    policy: &CurvePolicy,
) -> CurveResult<Classification<CircularArc2>> {
    match is_zero(&from.distance_squared(to), policy) {
        Some(true) => Ok(Classification::Uncertain(UncertaintyReason::Unsupported)),
        Some(false) => {
            let clockwise = match round_join_clockwise(center, from, to, policy) {
                Classification::Decided(clockwise) => clockwise,
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            };
            Ok(round_join_arc(from, to, center, clockwise))
        }
        None => Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
    }
}

fn round_join_arc(
    from: &Point2,
    to: &Point2,
    center: &Point2,
    clockwise: bool,
) -> Classification<CircularArc2> {
    match CircularArc2::try_from_center(from.clone(), to.clone(), center.clone(), clockwise) {
        Ok(arc) => Classification::Decided(arc),
        // A round join is only valid when both offset endpoints are certified
        // to lie on the circle around the source vertex. If exact radii differ,
        // the primitive join stage has reached the unsupported trim/rebuild
        // boundary described by Tiller-Hanson and Farouki-Neff above.
        Err(CurveError::ZeroRadiusArc | CurveError::RadiusMismatch) => {
            Classification::Uncertain(UncertaintyReason::Unsupported)
        }
        Err(error) => {
            unreachable!("round join arc construction returned unexpected error: {error}")
        }
    }
}

fn cap_line(from: &Point2, to: &Point2) -> CurveResult<Classification<LineSeg2>> {
    match LineSeg2::try_new(from.clone(), to.clone()) {
        Ok(line) => Ok(Classification::Decided(line)),
        Err(CurveError::ZeroLengthLine) => {
            Ok(Classification::Uncertain(UncertaintyReason::Unsupported))
        }
        Err(error) => Err(error),
    }
}

fn reversed_segments(segments: Vec<Segment2>) -> impl Iterator<Item = Segment2> {
    segments.into_iter().rev().map(|segment| segment.reversed())
}

fn round_join_clockwise(
    center: &Point2,
    from: &Point2,
    to: &Point2,
    policy: &CurvePolicy,
) -> Classification<bool> {
    let from_radius = from.delta_from(center);
    let to_radius = to.delta_from(center);
    let turn = cross(&from_radius.0, &from_radius.1, &to_radius.0, &to_radius.1);

    match real_sign(&turn, policy) {
        Some(RealSign::Positive) => Classification::Decided(false),
        Some(RealSign::Negative) => Classification::Decided(true),
        Some(RealSign::Zero) => Classification::Decided(true),
        None => Classification::Uncertain(UncertaintyReason::RealSign),
    }
}

fn cross(ax: &Real, ay: &Real, bx: &Real, by: &Real) -> Real {
    (ax * by) - (ay * bx)
}