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
//! Certified zero-error fits for Bezier and rational-conic boundary data.
//!
//! This module keeps only the primitive cases needed by Bezier boolean and
//! offset work: a Bezier/conic image can be proven to be exactly one point or
//! exactly one endpoint line segment, and a certified flattened Bezier polyline
//! can be proven to have the same zero-error primitive image. These are proof
//! objects for exact branch decisions, not general fitting reports.

use hyperreal::{Real, RealSign};

use crate::classify::{classify_oriented_line, is_zero, real_sign};
use crate::{
    Aabb2, BezierFlatteningCertificate, CertifiedBezierPolyline2, Classification, CubicBezier2,
    CurveError, CurvePolicy, CurveResult, LineSeg2, LineSide, Point2, QuadraticBezier2,
    RationalQuadraticBezier2, UncertaintyReason,
};

/// Error metric used by a zero-error primitive fit.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BezierFitErrorMetric {
    /// Exact Euclidean point-to-primitive distance with a zero bound.
    ExactEuclideanDistance,
}

/// Proof status for a Bezier fitting error bound.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BezierFitBoundKind {
    /// The bound is proved exactly by symbolic predicates.
    ProvenExact,
}

/// Certificate attached to a zero-error Bezier primitive fit.
#[derive(Clone, Debug, PartialEq)]
pub struct BezierFitCertificate {
    source_start: usize,
    source_end: usize,
    fit_error_bound: Real,
    source_flattening_error: Option<Real>,
    source_flattening_max_depth: Option<usize>,
    construction_policy: CurvePolicy,
    metric: BezierFitErrorMetric,
    bound_kind: BezierFitBoundKind,
}

/// A Bezier or conic segment certified to be one exact affine point.
#[derive(Clone, Debug, PartialEq)]
pub struct CertifiedBezierPointImage2 {
    point: Point2,
    control_point_count: usize,
    fit_certificate: BezierFitCertificate,
}

/// A Bezier or conic segment certified to trace exactly one endpoint line segment.
#[derive(Clone, Debug, PartialEq)]
pub struct CertifiedBezierLineImage2 {
    line: LineSeg2,
    control_point_count: usize,
    fit_certificate: BezierFitCertificate,
}

/// Exact offset of a certified Bezier/conic line image.
#[derive(Clone, Debug, PartialEq)]
pub struct CertifiedBezierLineImageOffset2 {
    line: LineSeg2,
    control_point_count: usize,
    distance: Real,
    fit_certificate: BezierFitCertificate,
}

/// A zero-error line fit recovered from a certified flattened Bezier polyline.
#[derive(Clone, Debug, PartialEq)]
pub struct CertifiedBezierLineFit2 {
    line: LineSeg2,
    source_certificate: BezierFlatteningCertificate,
    fit_certificate: BezierFitCertificate,
}

/// A zero-error point fit recovered from a certified flattened Bezier polyline.
#[derive(Clone, Debug, PartialEq)]
pub struct CertifiedBezierPointFit2 {
    point: Point2,
    source_certificate: BezierFlatteningCertificate,
    fit_certificate: BezierFitCertificate,
}

/// Exact offset of a certified zero-error line fit.
#[derive(Clone, Debug, PartialEq)]
pub struct CertifiedBezierLineOffset2 {
    line: LineSeg2,
    source_certificate: BezierFlatteningCertificate,
    distance: Real,
    fit_certificate: BezierFitCertificate,
}

/// Result of attempting a zero-error line fit.
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum BezierLineFitRelation {
    /// Every retained source vertex is certified on the fitted line segment.
    Fit(CertifiedBezierLineFit2),
    /// At least one retained source vertex is certified off the fitted segment.
    NotLine,
}

/// Result of attempting a zero-error point fit.
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum BezierPointFitRelation {
    /// Every retained source vertex is certified equal to one point.
    Fit(CertifiedBezierPointFit2),
    /// At least one retained source vertex is certified different from the point.
    NotPoint,
}

/// Result of attempting to fit the Bezier/conic object itself to a line.
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum BezierLineImageFitRelation {
    /// Every control point is certified on the endpoint line segment.
    Fit(CertifiedBezierLineImage2),
    /// At least one control point is certified off the endpoint line segment.
    NotLine,
}

/// Result of attempting to fit the Bezier/conic object to one point.
#[derive(Clone, Debug, PartialEq)]
#[allow(clippy::large_enum_variant)]
pub enum BezierPointImageFitRelation {
    /// Every control point is certified equal to the endpoint point.
    Fit(CertifiedBezierPointImage2),
    /// At least one control point is certified different from the endpoint point.
    NotPoint,
}

impl BezierFitCertificate {
    fn proven_exact(
        source_start: usize,
        source_end: usize,
        source_flattening_error: Option<Real>,
        source_flattening_max_depth: Option<usize>,
        construction_policy: &CurvePolicy,
    ) -> Self {
        Self {
            source_start,
            source_end,
            fit_error_bound: Real::zero(),
            source_flattening_error,
            source_flattening_max_depth,
            construction_policy: construction_policy.clone(),
            metric: BezierFitErrorMetric::ExactEuclideanDistance,
            bound_kind: BezierFitBoundKind::ProvenExact,
        }
    }

    /// Returns the half-open start index of the fitted source range.
    pub const fn source_start(&self) -> usize {
        self.source_start
    }

    /// Returns the half-open end index of the fitted source range.
    pub const fn source_end(&self) -> usize {
        self.source_end
    }

    /// Returns the proven fit-error bound.
    pub const fn fit_error_bound(&self) -> &Real {
        &self.fit_error_bound
    }

    /// Returns the source curve-to-polyline flattening error, when applicable.
    pub const fn source_flattening_error(&self) -> Option<&Real> {
        self.source_flattening_error.as_ref()
    }

    /// Returns the source flattening recursion budget, when applicable.
    pub const fn source_flattening_max_depth(&self) -> Option<usize> {
        self.source_flattening_max_depth
    }

    /// Returns the policy used to prove this fit.
    pub const fn construction_policy(&self) -> &CurvePolicy {
        &self.construction_policy
    }

    /// Returns the error metric certified by this fit.
    pub const fn metric(&self) -> BezierFitErrorMetric {
        self.metric
    }

    /// Returns whether the fit bound is proven exactly.
    pub const fn bound_kind(&self) -> BezierFitBoundKind {
        self.bound_kind
    }
}

impl CertifiedBezierPointImage2 {
    /// Returns the exact point image traced by the Bezier/conic.
    pub const fn point(&self) -> &Point2 {
        &self.point
    }

    /// Returns the number of source control points covered by the fit.
    pub const fn control_point_count(&self) -> usize {
        self.control_point_count
    }

    /// Returns the certificate proving this exact point-image fit.
    pub const fn fit_certificate(&self) -> &BezierFitCertificate {
        &self.fit_certificate
    }
}

impl CertifiedBezierLineImage2 {
    /// Returns the exact endpoint line segment traced by the Bezier/conic.
    pub const fn line(&self) -> &LineSeg2 {
        &self.line
    }

    /// Returns the number of source control points covered by the fit.
    pub const fn control_point_count(&self) -> usize {
        self.control_point_count
    }

    /// Returns the certificate proving this exact line-image fit.
    pub const fn fit_certificate(&self) -> &BezierFitCertificate {
        &self.fit_certificate
    }

    /// Offsets the certified line image exactly as a line primitive.
    pub fn offset_left_exact(
        &self,
        distance: Real,
    ) -> CurveResult<CertifiedBezierLineImageOffset2> {
        Ok(CertifiedBezierLineImageOffset2 {
            line: self.line.offset_left(distance.clone())?,
            control_point_count: self.control_point_count,
            distance,
            fit_certificate: self.fit_certificate.clone(),
        })
    }

    /// Offsets the certified line image exactly to the curve's right side.
    pub fn offset_right_exact(
        &self,
        distance: Real,
    ) -> CurveResult<CertifiedBezierLineImageOffset2> {
        self.offset_left_exact(-distance)
    }
}

impl CertifiedBezierLineImageOffset2 {
    /// Returns the exact offset line segment.
    pub const fn line(&self) -> &LineSeg2 {
        &self.line
    }

    /// Returns the number of source control points covered by the fit.
    pub const fn control_point_count(&self) -> usize {
        self.control_point_count
    }

    /// Returns the exact offset distance.
    pub const fn distance(&self) -> &Real {
        &self.distance
    }

    /// Returns the fit certificate inherited by this exact primitive offset.
    pub const fn fit_certificate(&self) -> &BezierFitCertificate {
        &self.fit_certificate
    }
}

impl CertifiedBezierLineFit2 {
    /// Returns the fitted exact line segment.
    pub const fn line(&self) -> &LineSeg2 {
        &self.line
    }

    /// Returns the source flattening certificate.
    pub const fn source_certificate(&self) -> &BezierFlatteningCertificate {
        &self.source_certificate
    }

    /// Returns the certificate proving this zero-error fit.
    pub const fn fit_certificate(&self) -> &BezierFitCertificate {
        &self.fit_certificate
    }

    /// Offsets the certified zero-error line fit exactly.
    pub fn offset_left_exact(&self, distance: Real) -> CurveResult<CertifiedBezierLineOffset2> {
        Ok(CertifiedBezierLineOffset2 {
            line: self.line.offset_left(distance.clone())?,
            source_certificate: self.source_certificate.clone(),
            distance,
            fit_certificate: self.fit_certificate.clone(),
        })
    }

    /// Offsets the certified zero-error line fit exactly to the right side.
    pub fn offset_right_exact(&self, distance: Real) -> CurveResult<CertifiedBezierLineOffset2> {
        self.offset_left_exact(-distance)
    }
}

impl CertifiedBezierPointFit2 {
    /// Returns the fitted exact point.
    pub const fn point(&self) -> &Point2 {
        &self.point
    }

    /// Returns the source flattening certificate.
    pub const fn source_certificate(&self) -> &BezierFlatteningCertificate {
        &self.source_certificate
    }

    /// Returns the certificate proving this zero-error fit.
    pub const fn fit_certificate(&self) -> &BezierFitCertificate {
        &self.fit_certificate
    }
}

impl CertifiedBezierLineOffset2 {
    /// Returns the exact offset line segment.
    pub const fn line(&self) -> &LineSeg2 {
        &self.line
    }

    /// Returns the source flattening certificate.
    pub const fn source_certificate(&self) -> &BezierFlatteningCertificate {
        &self.source_certificate
    }

    /// Returns the exact offset distance.
    pub const fn distance(&self) -> &Real {
        &self.distance
    }

    /// Returns the fit certificate inherited by this exact primitive offset.
    pub const fn fit_certificate(&self) -> &BezierFitCertificate {
        &self.fit_certificate
    }
}

impl QuadraticBezier2 {
    /// Fits this quadratic Bezier to one exact point when possible.
    pub fn fit_exact_point_image(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierPointImageFitRelation>> {
        fit_control_polygon_point_image(&self.control_points(), policy)
    }

    /// Fits this quadratic Bezier to its exact endpoint line image when possible.
    pub fn fit_exact_line_image(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierLineImageFitRelation>> {
        fit_control_polygon_line_image(&self.control_points(), policy)
    }
}

impl CubicBezier2 {
    /// Fits this cubic Bezier to one exact point when possible.
    pub fn fit_exact_point_image(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierPointImageFitRelation>> {
        fit_control_polygon_point_image(&self.control_points(), policy)
    }

    /// Fits this cubic Bezier to its exact endpoint line image when possible.
    pub fn fit_exact_line_image(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierLineImageFitRelation>> {
        fit_control_polygon_line_image(&self.control_points(), policy)
    }
}

impl RationalQuadraticBezier2 {
    /// Fits this rational quadratic conic to one exact affine point when possible.
    pub fn fit_exact_point_image(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierPointImageFitRelation>> {
        match weights_known_same_nonzero_sign(self.weights().as_slice(), policy) {
            Some(true) => fit_control_polygon_point_image(&self.control_points(), policy),
            Some(false) => Ok(Classification::Uncertain(UncertaintyReason::Unsupported)),
            None => Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
        }
    }

    /// Fits this rational quadratic conic to its exact endpoint line image when possible.
    pub fn fit_exact_line_image(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierLineImageFitRelation>> {
        match weights_known_same_nonzero_sign(self.weights().as_slice(), policy) {
            Some(true) => fit_control_polygon_line_image(&self.control_points(), policy),
            Some(false) => Ok(Classification::Uncertain(UncertaintyReason::Unsupported)),
            None => Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
        }
    }
}

impl CertifiedBezierPolyline2 {
    /// Fits this certified polyline to one exact point when the fit has zero error.
    pub fn fit_exact_point(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierPointFitRelation>> {
        let Some(point) = self.points().first() else {
            return Err(CurveError::InsufficientVertices);
        };
        for vertex in self.points().iter().skip(1) {
            match is_zero(&point.distance_squared(vertex), policy) {
                Some(true) => {}
                Some(false) => {
                    return Ok(Classification::Decided(BezierPointFitRelation::NotPoint));
                }
                None => return Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
            }
        }

        Ok(Classification::Decided(BezierPointFitRelation::Fit(
            CertifiedBezierPointFit2 {
                point: point.clone(),
                source_certificate: self.certificate().clone(),
                fit_certificate: BezierFitCertificate::proven_exact(
                    0,
                    self.points().len(),
                    Some(self.certificate().max_error().clone()),
                    Some(self.certificate().max_depth()),
                    policy,
                ),
            },
        )))
    }

    /// Fits this certified polyline to one exact line when the fit has zero error.
    pub fn fit_exact_line(
        &self,
        policy: &CurvePolicy,
    ) -> CurveResult<Classification<BezierLineFitRelation>> {
        let Some(start) = self.points().first() else {
            return Err(CurveError::InsufficientVertices);
        };
        let Some(end) = self.points().last() else {
            return Err(CurveError::InsufficientVertices);
        };
        if is_zero(&start.distance_squared(end), policy) == Some(true) {
            return Err(CurveError::ZeroLengthLine);
        }
        let line = LineSeg2::try_new(start.clone(), end.clone())?;
        let envelope = match Aabb2::from_points([start, end], policy) {
            Classification::Decided(envelope) => envelope,
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        };

        for point in self
            .points()
            .iter()
            .skip(1)
            .take(self.points().len().saturating_sub(2))
        {
            match point_on_line_interval(start, end, &envelope, point, policy) {
                Classification::Decided(true) => {}
                Classification::Decided(false) => {
                    return Ok(Classification::Decided(BezierLineFitRelation::NotLine));
                }
                Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
            }
        }

        Ok(Classification::Decided(BezierLineFitRelation::Fit(
            CertifiedBezierLineFit2 {
                line,
                source_certificate: self.certificate().clone(),
                fit_certificate: BezierFitCertificate::proven_exact(
                    0,
                    self.points().len(),
                    Some(self.certificate().max_error().clone()),
                    Some(self.certificate().max_depth()),
                    policy,
                ),
            },
        )))
    }
}

fn weights_known_same_nonzero_sign(weights: &[&Real], policy: &CurvePolicy) -> Option<bool> {
    let mut expected = None;
    for weight in weights {
        let sign = real_sign(weight, policy)?;
        match sign {
            RealSign::Positive | RealSign::Negative => {
                if let Some(expected) = expected {
                    if sign != expected {
                        return Some(false);
                    }
                } else {
                    expected = Some(sign);
                }
            }
            RealSign::Zero => return Some(false),
        }
    }
    Some(expected.is_some())
}

fn fit_control_polygon_point_image(
    controls: &[&Point2],
    policy: &CurvePolicy,
) -> CurveResult<Classification<BezierPointImageFitRelation>> {
    let Some(point) = controls.first().copied() else {
        return Err(CurveError::InsufficientVertices);
    };
    for control in controls.iter().skip(1) {
        match is_zero(&point.distance_squared(control), policy) {
            Some(true) => {}
            Some(false) => {
                return Ok(Classification::Decided(
                    BezierPointImageFitRelation::NotPoint,
                ));
            }
            None => return Ok(Classification::Uncertain(UncertaintyReason::RealSign)),
        }
    }

    Ok(Classification::Decided(BezierPointImageFitRelation::Fit(
        CertifiedBezierPointImage2 {
            point: point.clone(),
            control_point_count: controls.len(),
            fit_certificate: BezierFitCertificate::proven_exact(
                0,
                controls.len(),
                None,
                None,
                policy,
            ),
        },
    )))
}

fn fit_control_polygon_line_image(
    controls: &[&Point2],
    policy: &CurvePolicy,
) -> CurveResult<Classification<BezierLineImageFitRelation>> {
    let Some(start) = controls.first().copied() else {
        return Err(CurveError::InsufficientVertices);
    };
    let Some(end) = controls.last().copied() else {
        return Err(CurveError::InsufficientVertices);
    };
    if is_zero(&start.distance_squared(end), policy) == Some(true) {
        return Err(CurveError::ZeroLengthLine);
    }
    let line = LineSeg2::try_new(start.clone(), end.clone())?;
    let envelope = match Aabb2::from_points([start, end], policy) {
        Classification::Decided(envelope) => envelope,
        Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
    };

    for point in controls
        .iter()
        .skip(1)
        .take(controls.len().saturating_sub(2))
    {
        match point_on_line_interval(start, end, &envelope, point, policy) {
            Classification::Decided(true) => {}
            Classification::Decided(false) => {
                return Ok(Classification::Decided(BezierLineImageFitRelation::NotLine));
            }
            Classification::Uncertain(reason) => return Ok(Classification::Uncertain(reason)),
        }
    }

    Ok(Classification::Decided(BezierLineImageFitRelation::Fit(
        CertifiedBezierLineImage2 {
            line,
            control_point_count: controls.len(),
            fit_certificate: BezierFitCertificate::proven_exact(
                0,
                controls.len(),
                None,
                None,
                policy,
            ),
        },
    )))
}

fn point_on_line_interval(
    start: &Point2,
    end: &Point2,
    envelope: &Aabb2,
    point: &Point2,
    policy: &CurvePolicy,
) -> Classification<bool> {
    match classify_oriented_line(start, end, point, policy) {
        Classification::Decided(LineSide::On) => {}
        Classification::Decided(_) => return Classification::Decided(false),
        Classification::Uncertain(reason) => return Classification::Uncertain(reason),
    }
    envelope.contains_point(point, policy)
}