hypercurve 0.3.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
//! Native Bezier split materialization over exact and algebraic parameters.
//!
//! This module is the first consumer of [`BezierParameter2`]. It materializes
//! polynomial and rational Bezier subcurves when both range boundaries are
//! represented [`Real`](hyperreal::Real) values. For algebraic boundaries it
//! now consumes the boundary into exact endpoint point/tangent images when
//! that construction is certified, otherwise it carries the interval forward
//! as an unresolved fragment. That is intentional: Yap's exact
//! geometric-computation model requires exact objects to survive until the
//! kernel has a certified operation for them, rather than converting algebraic
//! roots to finite approximations; see Yap, "Towards Exact Geometric
//! Computation," *Computational Geometry* 7(1-2), 3-23 (1997).
//!
//! Exact materialization uses de Casteljau subdivision. The construction is
//! affine for polynomial Beziers and homogeneous for rational Beziers, matching
//! de Casteljau, "Outillage methodes calcul," Andre Citroen Automobiles SA
//! (1959), and the rational Bezier treatment in Farin, *Curves and Surfaces
//! for Computer-Aided Geometric Design* (5th ed., 2002). Algebraic parameters
//! whose defining equation is certified linear are first promoted to their
//! represented [`Real`] root, so the same exact subdivision path handles that
//! materializable algebraic subset without approximating nonlinear roots.

use std::cmp::Ordering;

use hyperreal::Real;

use crate::classify::{compare_reals, in_closed_unit_interval, is_zero};
use crate::{
    BezierAlgebraicEndpointImage2, BezierAlgebraicParameter2, BezierParameter2, Classification,
    CubicBezier2, CurveError, CurvePolicy, CurveResult, Point2, QuadraticBezier2,
    RationalQuadraticBezier2,
};

/// A native Bezier subcurve produced by exact split materialization.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum BezierSubcurve2 {
    /// Polynomial quadratic Bezier subcurve.
    Quadratic(QuadraticBezier2),
    /// Polynomial cubic Bezier subcurve.
    Cubic(CubicBezier2),
    /// Rational quadratic Bezier/conic subcurve.
    RationalQuadratic(RationalQuadraticBezier2),
}

/// One fragment between adjacent split boundaries.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq)]
pub enum BezierSplitFragment2 {
    /// Both boundaries were represented exactly and the native subcurve exists.
    Materialized {
        /// Start split boundary in the original parameter space.
        start: BezierParameter2,
        /// End split boundary in the original parameter space.
        end: BezierParameter2,
        /// Native subcurve over this range.
        curve: BezierSubcurve2,
    },
    /// At least one boundary is algebraic, and its exact endpoint images were
    /// constructed without making a native subcurve.
    AlgebraicEndpointImages {
        /// Start split boundary in the original parameter space.
        start: BezierParameter2,
        /// End split boundary in the original parameter space.
        end: BezierParameter2,
        /// Source curve that generated this algebraic-boundary fragment.
        ///
        /// This is not a native subcurve over the algebraic parameter range.
        /// It is retained construction evidence for conservative exact
        /// measurements, such as source-curve envelopes, that can safely
        /// overbound the algebraic subrange without evaluating an algebraic
        /// split point as a floating coordinate.
        source_curve: Option<BezierSubcurve2>,
        /// Exact point/tangent image when the start boundary is algebraic.
        start_image: Option<BezierAlgebraicEndpointImage2>,
        /// Exact point/tangent image when the end boundary is algebraic.
        end_image: Option<BezierAlgebraicEndpointImage2>,
    },
    /// At least one boundary is algebraic and must be carried forward.
    Unresolved {
        /// Start split boundary in the original parameter space.
        start: BezierParameter2,
        /// End split boundary in the original parameter space.
        end: BezierParameter2,
    },
}

/// Ordered split result for one Bezier segment.
#[derive(Clone, Debug, PartialEq)]
pub struct BezierSplitMaterialization2 {
    fragments: Vec<BezierSplitFragment2>,
}

impl BezierSplitMaterialization2 {
    /// Constructs a materialization result from ordered fragments.
    pub fn new(fragments: Vec<BezierSplitFragment2>) -> CurveResult<Self> {
        validate_bezier_split_fragments(&fragments)?;
        Ok(Self { fragments })
    }

    /// Returns fragments in increasing source-parameter order.
    pub fn fragments(&self) -> &[BezierSplitFragment2] {
        &self.fragments
    }

    /// Returns true when every fragment was materialized as a native curve.
    pub fn is_fully_materialized(&self) -> bool {
        self.fragments
            .iter()
            .all(|fragment| matches!(fragment, BezierSplitFragment2::Materialized { .. }))
    }

    /// Returns true when at least one algebraic-boundary fragment remains.
    pub fn has_unresolved_fragments(&self) -> bool {
        self.fragments
            .iter()
            .any(|fragment| matches!(fragment, BezierSplitFragment2::Unresolved { .. }))
    }

    /// Returns true when at least one algebraic-boundary fragment carries
    /// exact endpoint point/tangent images.
    pub fn has_algebraic_endpoint_images(&self) -> bool {
        self.fragments.iter().any(|fragment| {
            matches!(
                fragment,
                BezierSplitFragment2::AlgebraicEndpointImages { .. }
            )
        })
    }
}

fn validate_bezier_split_fragments(fragments: &[BezierSplitFragment2]) -> CurveResult<()> {
    if fragments.is_empty() {
        return Err(CurveError::Topology(
            "Bezier split materialization must carry at least one source fragment".into(),
        ));
    }

    let policy = CurvePolicy::certified();
    validate_bezier_split_coverage(fragments, &policy)?;
    for (left_index, left) in fragments.iter().enumerate() {
        validate_bezier_split_fragment(left, &policy)?;
        if let Some(right) = fragments.get(left_index + 1) {
            validate_adjacent_bezier_split_fragments(left, right)?;
        }
        if fragments[left_index + 1..]
            .iter()
            .any(|right| right == left)
        {
            return Err(CurveError::Topology(
                "Bezier split materialization must not contain duplicate fragments".into(),
            ));
        }
    }
    Ok(())
}

fn validate_bezier_split_coverage(
    fragments: &[BezierSplitFragment2],
    policy: &CurvePolicy,
) -> CurveResult<()> {
    let (first_start, _) = bezier_split_fragment_range(&fragments[0]);
    let (_, last_end) = bezier_split_fragment_range(&fragments[fragments.len() - 1]);
    validate_bezier_boundary_equals(first_start, &BezierParameter2::Exact(Real::zero()), policy)?;
    validate_bezier_boundary_equals(last_end, &BezierParameter2::Exact(Real::one()), policy)?;
    Ok(())
}

fn validate_bezier_boundary_equals(
    actual: &BezierParameter2,
    expected: &BezierParameter2,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    match actual.cmp_by_interval(expected, policy)? {
        Classification::Decided(Ordering::Equal) => Ok(()),
        Classification::Decided(_) => Err(CurveError::Topology(
            "Bezier split materialization must cover the full source parameter interval".into(),
        )),
        Classification::Uncertain(reason) => Err(CurveError::Topology(format!(
            "Bezier split materialization source coverage is uncertain: {reason:?}"
        ))),
    }
}

fn validate_bezier_split_fragment(
    fragment: &BezierSplitFragment2,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    let (start, end) = bezier_split_fragment_range(fragment);
    validate_parameter(start, policy)?;
    validate_parameter(end, policy)?;
    validate_bezier_parameter_order(start, end, policy)?;

    match fragment {
        BezierSplitFragment2::Materialized { start, end, .. } => {
            if !start.is_exact() || !end.is_exact() {
                return Err(CurveError::Topology(
                    "materialized Bezier split fragment must have exact range boundaries".into(),
                ));
            }
        }
        BezierSplitFragment2::AlgebraicEndpointImages {
            start,
            end,
            source_curve,
            start_image,
            end_image,
        } => {
            let Some(source_curve) = source_curve else {
                return Err(CurveError::Topology(
                    "algebraic Bezier split endpoint images must retain source curve provenance"
                        .into(),
                ));
            };
            validate_algebraic_endpoint_image_boundary(
                "start",
                start,
                start_image.as_ref(),
                source_curve,
                policy,
            )?;
            validate_algebraic_endpoint_image_boundary(
                "end",
                end,
                end_image.as_ref(),
                source_curve,
                policy,
            )?;
        }
        BezierSplitFragment2::Unresolved { start, end } => {
            if start.is_exact() && end.is_exact() {
                return Err(CurveError::Topology(
                    "unresolved Bezier split fragment must have an algebraic range boundary".into(),
                ));
            }
        }
    }

    Ok(())
}

fn validate_adjacent_bezier_split_fragments(
    left: &BezierSplitFragment2,
    right: &BezierSplitFragment2,
) -> CurveResult<()> {
    let (_, left_end) = bezier_split_fragment_range(left);
    let (right_start, _) = bezier_split_fragment_range(right);
    if left_end != right_start {
        return Err(CurveError::Topology(
            "Bezier split materialization fragments must be contiguous and ordered".into(),
        ));
    }
    if let (
        BezierSplitFragment2::Materialized {
            curve: left_curve, ..
        },
        BezierSplitFragment2::Materialized {
            curve: right_curve, ..
        },
    ) = (left, right)
    {
        let left_endpoint = left_curve.end_point();
        let right_endpoint = right_curve.start_point();
        if !certified_split_points_equal(&left_endpoint, &right_endpoint, &CurvePolicy::certified())
        {
            return Err(CurveError::Topology(
                "adjacent materialized Bezier split fragments must be endpoint-connected".into(),
            ));
        }
    }
    Ok(())
}

fn certified_split_points_equal(left: &Point2, right: &Point2, policy: &CurvePolicy) -> bool {
    is_zero(&left.distance_squared(right), policy) == Some(true)
}

fn bezier_split_fragment_range(
    fragment: &BezierSplitFragment2,
) -> (&BezierParameter2, &BezierParameter2) {
    match fragment {
        BezierSplitFragment2::Materialized { start, end, .. }
        | BezierSplitFragment2::AlgebraicEndpointImages { start, end, .. }
        | BezierSplitFragment2::Unresolved { start, end } => (start, end),
    }
}

fn validate_bezier_parameter_order(
    start: &BezierParameter2,
    end: &BezierParameter2,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    match start.cmp_by_interval(end, policy)? {
        Classification::Decided(Ordering::Less) => Ok(()),
        Classification::Decided(Ordering::Equal | Ordering::Greater) => Err(CurveError::Topology(
            "Bezier split fragment range must be strictly increasing".into(),
        )),
        Classification::Uncertain(reason) => Err(CurveError::Topology(format!(
            "Bezier split fragment range ordering is uncertain: {reason:?}"
        ))),
    }
}

fn validate_algebraic_endpoint_image_boundary(
    name: &str,
    boundary: &BezierParameter2,
    image: Option<&BezierAlgebraicEndpointImage2>,
    source_curve: &BezierSubcurve2,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    match (boundary, image) {
        (BezierParameter2::Exact(_), None) => Ok(()),
        (BezierParameter2::Exact(_), Some(_)) => Err(CurveError::Topology(format!(
            "exact {name} Bezier split boundary must not carry algebraic endpoint image evidence"
        ))),
        (BezierParameter2::Algebraic(parameter), Some(image)) => {
            if image.parameter() != parameter {
                return Err(CurveError::Topology(format!(
                    "algebraic {name} Bezier split endpoint image parameter does not match boundary"
                )));
            }
            if !image.is_transformed() {
                return Err(CurveError::Topology(format!(
                    "algebraic {name} Bezier split endpoint image must be exact transformed evidence"
                )));
            }
            let expected =
                BezierAlgebraicEndpointImage2::from_source_curve(source_curve, parameter, policy)?;
            if &expected != image {
                return Err(CurveError::Topology(format!(
                    "algebraic {name} Bezier split endpoint image does not match retained source curve"
                )));
            }
            Ok(())
        }
        (BezierParameter2::Algebraic(_), None) => Err(CurveError::Topology(format!(
            "algebraic {name} Bezier split boundary must carry endpoint image evidence"
        ))),
    }
}

impl QuadraticBezier2 {
    /// Splits this quadratic at exact/algebraic Bezier parameters.
    pub fn split_at_parameters(
        &self,
        parameters: &[BezierParameter2],
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierSplitMaterialization2>> {
        split_curve_at_parameters(
            parameters,
            policy,
            |start, end| {
                Ok(BezierSubcurve2::Quadratic(
                    self.subcurve_between_exact(start, end, policy)?,
                ))
            },
            |parameter| BezierAlgebraicEndpointImage2::quadratic(self, parameter, policy),
            BezierSubcurve2::Quadratic(self.clone()),
        )
    }

    /// Materializes the exact subcurve over `[start, end]`.
    pub fn subcurve_between_exact(
        &self,
        start: &Real,
        end: &Real,
        policy: &CurvePolicy,
    ) -> CurveResult<QuadraticBezier2> {
        validate_exact_range(start, end, policy)?;
        if compare_reals(start, end, policy) == Some(Ordering::Equal) {
            let point = self.point_at(start.clone());
            return Ok(QuadraticBezier2::new(point.clone(), point.clone(), point));
        }
        if compare_reals(start, &Real::zero(), policy) == Some(Ordering::Equal)
            && compare_reals(end, &Real::one(), policy) == Some(Ordering::Equal)
        {
            return Ok(self.clone());
        }
        if compare_reals(start, &Real::zero(), policy) == Some(Ordering::Equal) {
            let (left, _) = self.split_at_exact(end.clone());
            return Ok(left);
        }
        if compare_reals(end, &Real::one(), policy) == Some(Ordering::Equal) {
            let (_, right) = self.split_at_exact(start.clone());
            return Ok(right);
        }

        let (left, _) = self.split_at_exact(end.clone());
        let local_start = (start.clone() / end.clone())?;
        let (_, middle) = left.split_at_exact(local_start);
        Ok(middle)
    }

    /// Splits this quadratic at one represented parameter.
    pub fn split_at_exact(&self, t: Real) -> (QuadraticBezier2, QuadraticBezier2) {
        let p01 = self.start().lerp(self.control(), t.clone());
        let p12 = self.control().lerp(self.end(), t.clone());
        let p012 = p01.lerp(&p12, t);
        (
            QuadraticBezier2::new(self.start().clone(), p01, p012.clone()),
            QuadraticBezier2::new(p012, p12, self.end().clone()),
        )
    }
}

impl CubicBezier2 {
    /// Splits this cubic at exact/algebraic Bezier parameters.
    pub fn split_at_parameters(
        &self,
        parameters: &[BezierParameter2],
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierSplitMaterialization2>> {
        split_curve_at_parameters(
            parameters,
            policy,
            |start, end| {
                Ok(BezierSubcurve2::Cubic(
                    self.subcurve_between_exact(start, end, policy)?,
                ))
            },
            |parameter| BezierAlgebraicEndpointImage2::cubic(self, parameter, policy),
            BezierSubcurve2::Cubic(self.clone()),
        )
    }

    /// Materializes the exact subcurve over `[start, end]`.
    pub fn subcurve_between_exact(
        &self,
        start: &Real,
        end: &Real,
        policy: &CurvePolicy,
    ) -> CurveResult<CubicBezier2> {
        validate_exact_range(start, end, policy)?;
        if compare_reals(start, end, policy) == Some(Ordering::Equal) {
            let point = self.point_at(start.clone());
            return Ok(CubicBezier2::new(
                point.clone(),
                point.clone(),
                point.clone(),
                point,
            ));
        }
        if compare_reals(start, &Real::zero(), policy) == Some(Ordering::Equal)
            && compare_reals(end, &Real::one(), policy) == Some(Ordering::Equal)
        {
            return Ok(self.clone());
        }
        if compare_reals(start, &Real::zero(), policy) == Some(Ordering::Equal) {
            let (left, _) = self.split_at_exact(end.clone());
            return Ok(left);
        }
        if compare_reals(end, &Real::one(), policy) == Some(Ordering::Equal) {
            let (_, right) = self.split_at_exact(start.clone());
            return Ok(right);
        }

        let (left, _) = self.split_at_exact(end.clone());
        let local_start = (start.clone() / end.clone())?;
        let (_, middle) = left.split_at_exact(local_start);
        Ok(middle)
    }

    /// Splits this cubic at one represented parameter.
    pub fn split_at_exact(&self, t: Real) -> (CubicBezier2, CubicBezier2) {
        let p01 = self.start().lerp(self.control1(), t.clone());
        let p12 = self.control1().lerp(self.control2(), t.clone());
        let p23 = self.control2().lerp(self.end(), t.clone());
        let p012 = p01.lerp(&p12, t.clone());
        let p123 = p12.lerp(&p23, t.clone());
        let p0123 = p012.lerp(&p123, t);
        (
            CubicBezier2::new(self.start().clone(), p01, p012, p0123.clone()),
            CubicBezier2::new(p0123, p123, p23, self.end().clone()),
        )
    }
}

impl RationalQuadraticBezier2 {
    /// Splits this conic at exact/algebraic Bezier parameters.
    pub fn split_at_parameters(
        &self,
        parameters: &[BezierParameter2],
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierSplitMaterialization2>> {
        split_curve_at_parameters(
            parameters,
            policy,
            |start, end| {
                Ok(BezierSubcurve2::RationalQuadratic(
                    self.subcurve_between_exact(start, end, policy)?,
                ))
            },
            |parameter| BezierAlgebraicEndpointImage2::rational_quadratic(self, parameter, policy),
            BezierSubcurve2::RationalQuadratic(self.clone()),
        )
    }

    /// Materializes the exact conic subcurve over `[start, end]`.
    pub fn subcurve_between_exact(
        &self,
        start: &Real,
        end: &Real,
        policy: &CurvePolicy,
    ) -> CurveResult<RationalQuadraticBezier2> {
        validate_exact_range(start, end, policy)?;
        if compare_reals(start, end, policy) == Some(Ordering::Equal) {
            let point = match self.point_at(start.clone(), policy) {
                Classification::Decided(point) => point,
                Classification::Uncertain(reason) => {
                    return Err(CurveError::Topology(format!(
                        "rational Bezier endpoint evaluation uncertain: {reason:?}"
                    )));
                }
            };
            return RationalQuadraticBezier2::try_new(
                point.clone(),
                point.clone(),
                point,
                Real::one(),
                Real::one(),
                Real::one(),
            );
        }
        if compare_reals(start, &Real::zero(), policy) == Some(Ordering::Equal)
            && compare_reals(end, &Real::one(), policy) == Some(Ordering::Equal)
        {
            return Ok(self.clone());
        }
        if compare_reals(start, &Real::zero(), policy) == Some(Ordering::Equal) {
            let (left, _) = self.split_at_exact(end.clone(), policy)?;
            return Ok(left);
        }
        if compare_reals(end, &Real::one(), policy) == Some(Ordering::Equal) {
            let (_, right) = self.split_at_exact(start.clone(), policy)?;
            return Ok(right);
        }

        let (left, _) = self.split_at_exact(end.clone(), policy)?;
        let local_start = (start.clone() / end.clone())?;
        let (_, middle) = left.split_at_exact(local_start, policy)?;
        Ok(middle)
    }

    /// Splits this rational quadratic at one represented parameter.
    pub fn split_at_exact(
        &self,
        t: Real,
        policy: &CurvePolicy,
    ) -> CurveResult<(RationalQuadraticBezier2, RationalQuadraticBezier2)> {
        let controls = self.control_points();
        let weights = self.weights();
        let levels = homogeneous_de_casteljau_levels(&controls, &weights, t);
        let left = levels
            .iter()
            .map(|level| level[0].clone())
            .collect::<Vec<_>>();
        let right = levels
            .iter()
            .rev()
            .map(|level| level[level.len() - 1].clone())
            .collect::<Vec<_>>();
        Ok((
            rational_from_homogeneous(&left, policy)?,
            rational_from_homogeneous(&right, policy)?,
        ))
    }
}

fn split_curve_at_parameters<F, G>(
    parameters: &[BezierParameter2],
    policy: &CurvePolicy,
    mut materialize: F,
    mut endpoint_image: G,
    source_curve: BezierSubcurve2,
) -> CurveResult<Classification<BezierSplitMaterialization2>>
where
    F: FnMut(&Real, &Real) -> CurveResult<BezierSubcurve2>,
    G: FnMut(&BezierAlgebraicParameter2) -> CurveResult<BezierAlgebraicEndpointImage2>,
{
    let mut boundaries = vec![
        BezierParameter2::Exact(Real::zero()),
        BezierParameter2::Exact(Real::one()),
    ];
    for parameter in parameters {
        validate_parameter(parameter, policy)?;
        let parameter = match parameter.clone().promote_represented_linear_root(policy)? {
            Classification::Decided(parameter) => parameter,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };
        push_boundary(&mut boundaries, parameter, policy)?;
    }
    match sort_boundaries(&mut boundaries, policy)? {
        Classification::Decided(()) => {}
        Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
    }

    let mut fragments = Vec::with_capacity(boundaries.len().saturating_sub(1));
    for pair in boundaries.windows(2) {
        let start = pair[0].clone();
        let end = pair[1].clone();
        match (start.as_exact(), end.as_exact()) {
            (Some(start_exact), Some(end_exact)) => {
                let curve = materialize(start_exact, end_exact)?;
                fragments.push(BezierSplitFragment2::Materialized { start, end, curve });
            }
            _ => {
                let start_image = endpoint_image_for(&start, &mut endpoint_image)?;
                let end_image = endpoint_image_for(&end, &mut endpoint_image)?;
                if start_image
                    .as_ref()
                    .is_none_or(BezierAlgebraicEndpointImage2::is_transformed)
                    && end_image
                        .as_ref()
                        .is_none_or(BezierAlgebraicEndpointImage2::is_transformed)
                {
                    fragments.push(BezierSplitFragment2::AlgebraicEndpointImages {
                        start,
                        end,
                        source_curve: Some(source_curve.clone()),
                        start_image,
                        end_image,
                    });
                } else {
                    fragments.push(BezierSplitFragment2::Unresolved { start, end });
                }
            }
        }
    }

    Ok(Classification::Decided(BezierSplitMaterialization2::new(
        fragments,
    )?))
}

fn endpoint_image_for<G>(
    parameter: &BezierParameter2,
    endpoint_image: &mut G,
) -> CurveResult<Option<BezierAlgebraicEndpointImage2>>
where
    G: FnMut(&BezierAlgebraicParameter2) -> CurveResult<BezierAlgebraicEndpointImage2>,
{
    match parameter {
        BezierParameter2::Exact(_) => Ok(None),
        BezierParameter2::Algebraic(parameter) => Ok(Some(endpoint_image(parameter)?)),
    }
}

fn validate_parameter(parameter: &BezierParameter2, policy: &CurvePolicy) -> CurveResult<()> {
    match parameter.known_interval(policy)? {
        Classification::Decided(_) => Ok(()),
        Classification::Uncertain(reason) => Err(CurveError::Topology(format!(
            "Bezier split parameter interval uncertain: {reason:?}"
        ))),
    }
}

fn push_boundary(
    boundaries: &mut Vec<BezierParameter2>,
    candidate: BezierParameter2,
    policy: &CurvePolicy,
) -> CurveResult<()> {
    for existing in boundaries.iter() {
        if let Classification::Decided(Ordering::Equal) =
            candidate.cmp_by_interval(existing, policy)?
        {
            return Ok(());
        }
    }
    boundaries.push(candidate);
    Ok(())
}

fn sort_boundaries(
    boundaries: &mut [BezierParameter2],
    policy: &CurvePolicy,
) -> CurveResult<Classification<()>> {
    for index in 1..boundaries.len() {
        let mut cursor = index;
        while cursor > 0 {
            match boundaries[cursor].cmp_by_interval(&boundaries[cursor - 1], policy)? {
                Classification::Decided(Ordering::Less) => {
                    boundaries.swap(cursor, cursor - 1);
                    cursor -= 1;
                }
                Classification::Decided(Ordering::Equal | Ordering::Greater) => break,
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            }
        }
    }
    Ok(Classification::Decided(()))
}

fn validate_exact_range(start: &Real, end: &Real, policy: &CurvePolicy) -> CurveResult<()> {
    match (
        in_closed_unit_interval(start, policy),
        in_closed_unit_interval(end, policy),
    ) {
        (Some(true), Some(true)) => {}
        (Some(false), _) | (_, Some(false)) => return Err(CurveError::InvalidBezierParameter),
        _ => {
            return Err(CurveError::Topology(
                "Bezier exact split range endpoint ordering is uncertain".to_string(),
            ));
        }
    }
    match compare_reals(start, end, policy) {
        Some(Ordering::Greater) => Err(CurveError::InvalidBezierRange),
        Some(_) => Ok(()),
        None => Err(CurveError::Topology(
            "Bezier exact split range order is uncertain".to_string(),
        )),
    }
}

#[derive(Clone, Debug)]
struct HomogeneousControl {
    x: Real,
    y: Real,
    weight: Real,
}

fn homogeneous_de_casteljau_levels(
    controls: &[&Point2; 3],
    weights: &[&Real; 3],
    t: Real,
) -> Vec<Vec<HomogeneousControl>> {
    let mut levels = vec![
        controls
            .iter()
            .zip(weights.iter())
            .map(|(point, weight)| HomogeneousControl {
                x: point.x() * *weight,
                y: point.y() * *weight,
                weight: (*weight).clone(),
            })
            .collect::<Vec<_>>(),
    ];

    while levels.last().map(|level| level.len()).unwrap_or(0) > 1 {
        let previous = levels.last().expect("level exists");
        let next = previous
            .windows(2)
            .map(|pair| lerp_homogeneous(&pair[0], &pair[1], t.clone()))
            .collect::<Vec<_>>();
        levels.push(next);
    }

    levels
}

fn lerp_homogeneous(
    first: &HomogeneousControl,
    second: &HomogeneousControl,
    t: Real,
) -> HomogeneousControl {
    let one_minus_t = Real::one() - &t;
    HomogeneousControl {
        x: (&first.x * &one_minus_t) + (&second.x * &t),
        y: (&first.y * &one_minus_t) + (&second.y * &t),
        weight: (&first.weight * &one_minus_t) + (&second.weight * &t),
    }
}

fn rational_from_homogeneous(
    controls: &[HomogeneousControl],
    policy: &CurvePolicy,
) -> CurveResult<RationalQuadraticBezier2> {
    let mut points = Vec::with_capacity(controls.len());
    let mut weights = Vec::with_capacity(controls.len());
    for control in controls {
        match is_zero(&control.weight, policy) {
            Some(true) => return Err(CurveError::ZeroRationalBezierWeight),
            Some(false) => {}
            None => {
                return Err(CurveError::Real(
                    "rational split weight sign uncertain".into(),
                ));
            }
        }
        let x = (&control.x / &control.weight)?;
        let y = (&control.y / &control.weight)?;
        points.push(Point2::new(x, y));
        weights.push(control.weight.clone());
    }

    RationalQuadraticBezier2::try_new(
        points[0].clone(),
        points[1].clone(),
        points[2].clone(),
        weights[0].clone(),
        weights[1].clone(),
        weights[2].clone(),
    )
}