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
//! Split markers extracted from normalized contour events.
//!
//! This is the intersection-insertion stage used by later boolean selection:
//! every event becomes an ordered marker on each affected source segment before
//! fragments are rebuilt. Greiner and Hormann's clipping pipeline uses the same
//! "insert intersections, then traverse classified pieces" shape in "Efficient
//! Clipping of Arbitrary Polygons" (*ACM Transactions on Graphics* 17(2),
//! 71-83, 1998). Finite display output can disturb marker order, so the
//! preview-only comparator is intentionally isolated here; see Hobby,
//! "Practical Segment Intersection with Finite Precision Output"
//! (*Computational Geometry* 13(4), 199-214, 1999).

use std::cmp::Ordering;

use hyperreal::Real;

use crate::classify::{
    compare_reals, compare_reals_for_split_ordering, in_closed_unit_interval, is_zero,
};
use crate::{
    Classification, Contour2, ContourIntersection, ContourIntersectionSet, ContourOperand,
    CurveError, CurvePolicy, CurveResult, Point2, UncertaintyReason,
};

/// A local split parameter on one contour segment.
#[derive(Clone, Debug, PartialEq)]
pub struct SegmentSplitPoint {
    /// Segment index in the source contour.
    pub segment_index: usize,
    /// Local segment parameter.
    pub param: Real,
}

/// A local split marker with both ordering parameter and geometric point.
#[derive(Clone, Debug, PartialEq)]
pub struct SegmentSplitMarker {
    /// Segment index in the source contour.
    pub segment_index: usize,
    /// Local segment ordering parameter.
    pub param: Real,
    /// Exact split point on the source segment.
    pub point: Point2,
}

/// Point-bearing split markers grouped by source contour segment.
#[derive(Clone, Debug, PartialEq)]
pub struct ContourSplitMarkers {
    segment_markers: Vec<Vec<SegmentSplitMarker>>,
}

impl ContourSplitMarkers {
    /// Constructs split markers from already-normalized per-segment markers.
    pub fn new(segment_markers: Vec<Vec<SegmentSplitMarker>>) -> CurveResult<Self> {
        validate_split_markers(&segment_markers)?;
        Ok(Self { segment_markers })
    }

    /// Constructs a marker set containing only each segment's endpoints.
    pub fn with_contour_endpoints(contour: &Contour2) -> Self {
        let mut segment_markers = Vec::with_capacity(contour.len());
        for (segment_index, segment) in contour.segments().iter().enumerate() {
            segment_markers.push(vec![
                SegmentSplitMarker {
                    segment_index,
                    param: Real::zero(),
                    point: segment.start().clone(),
                },
                SegmentSplitMarker {
                    segment_index,
                    param: Real::one(),
                    point: segment.end().clone(),
                },
            ]);
        }

        Self { segment_markers }
    }

    /// Builds split markers from one contour-pair event set.
    pub fn from_intersections(
        contour: &Contour2,
        intersections: &ContourIntersectionSet,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Classification<Self> {
        let mut markers = Self::with_contour_endpoints(contour);
        match markers.merge_intersections(intersections, operand, policy) {
            Classification::Decided(()) => Classification::Decided(markers),
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }

    /// Builds split markers from self-intersection events on one contour.
    ///
    /// Each retained event contributes markers for both participating source
    /// segments. Ordinary adjacent connectivity points should already have
    /// been filtered by the self-intersection collector.
    pub fn from_self_intersections(
        contour: &Contour2,
        intersections: &ContourIntersectionSet,
        policy: &CurvePolicy,
    ) -> Classification<Self> {
        let mut markers = Self::with_contour_endpoints(contour);
        match markers.merge_self_intersections(intersections, policy) {
            Classification::Decided(()) => Classification::Decided(markers),
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }

    /// Returns all segment marker bins.
    pub fn segments(&self) -> &[Vec<SegmentSplitMarker>] {
        &self.segment_markers
    }

    /// Returns markers for one segment.
    pub fn markers_for_segment(&self, segment_index: usize) -> Option<&[SegmentSplitMarker]> {
        self.segment_markers
            .get(segment_index)
            .map(std::vec::Vec::as_slice)
    }

    /// Returns the segment count represented by this marker set.
    pub fn segment_count(&self) -> usize {
        self.segment_markers.len()
    }

    /// Returns true when the marker set contains no segments.
    pub fn is_empty(&self) -> bool {
        self.segment_markers.is_empty()
    }

    /// Merges another contour-pair event set into this marker set.
    pub fn merge_intersections(
        &mut self,
        intersections: &ContourIntersectionSet,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Classification<()> {
        for event in intersections.events() {
            match self.merge_event(event, operand, policy) {
                Ok(()) => {}
                Err(reason) => return Classification::Uncertain(reason),
            }
        }

        Classification::Decided(())
    }

    /// Merges self-intersection events into this marker set.
    pub fn merge_self_intersections(
        &mut self,
        intersections: &ContourIntersectionSet,
        policy: &CurvePolicy,
    ) -> Classification<()> {
        for event in intersections.events() {
            match self.merge_event(event, ContourOperand::First, policy) {
                Ok(()) => {}
                Err(reason) => return Classification::Uncertain(reason),
            }
            match self.merge_event(event, ContourOperand::Second, policy) {
                Ok(()) => {}
                Err(reason) => return Classification::Uncertain(reason),
            }
        }

        Classification::Decided(())
    }

    /// Returns all markers flattened in segment order.
    pub fn split_markers(&self) -> Vec<SegmentSplitMarker> {
        let mut split_markers = Vec::new();
        for markers in &self.segment_markers {
            for marker in markers {
                split_markers.push(marker.clone());
            }
        }
        split_markers
    }

    fn merge_event(
        &mut self,
        event: &ContourIntersection,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Result<(), UncertaintyReason> {
        match event {
            ContourIntersection::Point(point) => {
                let (segment_index, param) = match operand {
                    ContourOperand::First => (point.a_segment_index, point.a_param.clone()),
                    ContourOperand::Second => (point.b_segment_index, point.b_param.clone()),
                };
                self.insert_marker(
                    SegmentSplitMarker {
                        segment_index,
                        param,
                        point: point.point.clone(),
                    },
                    policy,
                )
            }
            ContourIntersection::Overlap(overlap) => {
                let (segment_index, start_param, end_param) = match operand {
                    ContourOperand::First => (
                        overlap.a_segment_index,
                        overlap.a_range.start().clone(),
                        overlap.a_range.end().clone(),
                    ),
                    ContourOperand::Second => (
                        overlap.b_segment_index,
                        overlap.b_range.start().clone(),
                        overlap.b_range.end().clone(),
                    ),
                };
                self.insert_marker(
                    SegmentSplitMarker {
                        segment_index,
                        param: start_param,
                        point: overlap.segment.start().clone(),
                    },
                    policy,
                )?;
                self.insert_marker(
                    SegmentSplitMarker {
                        segment_index,
                        param: end_param,
                        point: overlap.segment.end().clone(),
                    },
                    policy,
                )
            }
            ContourIntersection::Uncertain(uncertain) => Err(uncertain.reason),
        }
    }

    fn insert_marker(
        &mut self,
        marker: SegmentSplitMarker,
        policy: &CurvePolicy,
    ) -> Result<(), UncertaintyReason> {
        let Some(markers) = self.segment_markers.get_mut(marker.segment_index) else {
            return Err(UncertaintyReason::Unsupported);
        };

        insert_unique_sorted_marker(markers, marker, policy)
    }
}

/// Per-segment split parameters for a contour.
///
/// Every segment starts with `0` and `1` so downstream fragment assembly can
/// build intervals directly after event parameters are merged in.
#[derive(Clone, Debug, PartialEq)]
pub struct ContourSplitMap {
    segment_splits: Vec<Vec<Real>>,
}

impl ContourSplitMap {
    /// Constructs a split map from already-normalized per-segment parameters.
    pub fn new(segment_splits: Vec<Vec<Real>>) -> CurveResult<Self> {
        validate_split_params(&segment_splits)?;
        Ok(Self { segment_splits })
    }

    /// Constructs a split map containing only segment endpoints.
    pub fn with_segment_count(segment_count: usize) -> Self {
        let mut segment_splits = Vec::with_capacity(segment_count);
        for _ in 0..segment_count {
            segment_splits.push(vec![Real::zero(), Real::one()]);
        }
        Self { segment_splits }
    }

    /// Builds a split map from one contour-pair event set.
    pub fn from_intersections(
        segment_count: usize,
        intersections: &ContourIntersectionSet,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Classification<Self> {
        let mut map = Self::with_segment_count(segment_count);
        match map.merge_intersections(intersections, operand, policy) {
            Classification::Decided(()) => Classification::Decided(map),
            Classification::Uncertain(reason) => Classification::Uncertain(reason),
        }
    }

    /// Returns the split parameters for all segments.
    pub fn segments(&self) -> &[Vec<Real>] {
        &self.segment_splits
    }

    /// Returns the split parameters for one segment.
    pub fn params_for_segment(&self, segment_index: usize) -> Option<&[Real]> {
        self.segment_splits
            .get(segment_index)
            .map(std::vec::Vec::as_slice)
    }

    /// Returns the segment count represented by this map.
    pub fn segment_count(&self) -> usize {
        self.segment_splits.len()
    }

    /// Returns true when the map contains no segments.
    pub fn is_empty(&self) -> bool {
        self.segment_splits.is_empty()
    }

    /// Merges another contour-pair event set into this split map.
    pub fn merge_intersections(
        &mut self,
        intersections: &ContourIntersectionSet,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Classification<()> {
        for event in intersections.events() {
            match self.merge_event(event, operand, policy) {
                Ok(()) => {}
                Err(reason) => return Classification::Uncertain(reason),
            }
        }

        Classification::Decided(())
    }

    /// Returns all split points flattened in segment order.
    pub fn split_points(&self) -> Vec<SegmentSplitPoint> {
        let mut split_points = Vec::new();
        for (segment_index, params) in self.segment_splits.iter().enumerate() {
            for param in params {
                split_points.push(SegmentSplitPoint {
                    segment_index,
                    param: param.clone(),
                });
            }
        }
        split_points
    }

    fn merge_event(
        &mut self,
        event: &ContourIntersection,
        operand: ContourOperand,
        policy: &CurvePolicy,
    ) -> Result<(), UncertaintyReason> {
        match event {
            ContourIntersection::Point(point) => {
                let (segment_index, param) = match operand {
                    ContourOperand::First => (point.a_segment_index, point.a_param.clone()),
                    ContourOperand::Second => (point.b_segment_index, point.b_param.clone()),
                };
                self.insert_param(segment_index, param, policy)
            }
            ContourIntersection::Overlap(overlap) => {
                let (segment_index, start, end) = match operand {
                    ContourOperand::First => (
                        overlap.a_segment_index,
                        overlap.a_range.start().clone(),
                        overlap.a_range.end().clone(),
                    ),
                    ContourOperand::Second => (
                        overlap.b_segment_index,
                        overlap.b_range.start().clone(),
                        overlap.b_range.end().clone(),
                    ),
                };
                self.insert_param(segment_index, start, policy)?;
                self.insert_param(segment_index, end, policy)
            }
            ContourIntersection::Uncertain(uncertain) => Err(uncertain.reason),
        }
    }

    fn insert_param(
        &mut self,
        segment_index: usize,
        param: Real,
        policy: &CurvePolicy,
    ) -> Result<(), UncertaintyReason> {
        let Some(params) = self.segment_splits.get_mut(segment_index) else {
            return Err(UncertaintyReason::Unsupported);
        };

        insert_unique_sorted(params, param, policy)
    }
}

fn insert_unique_sorted(
    params: &mut Vec<Real>,
    param: Real,
    policy: &CurvePolicy,
) -> Result<(), UncertaintyReason> {
    for index in 0..params.len() {
        match compare_reals_for_split_ordering(&param, &params[index], policy) {
            Some(Ordering::Equal) => return Ok(()),
            Some(Ordering::Less) => {
                params.insert(index, param);
                return Ok(());
            }
            Some(Ordering::Greater) => {}
            None => return Err(UncertaintyReason::Ordering),
        }
    }

    params.push(param);
    Ok(())
}

fn insert_unique_sorted_marker(
    markers: &mut Vec<SegmentSplitMarker>,
    marker: SegmentSplitMarker,
    policy: &CurvePolicy,
) -> Result<(), UncertaintyReason> {
    for index in 0..markers.len() {
        match compare_reals_for_split_ordering(&marker.param, &markers[index].param, policy) {
            Some(Ordering::Equal) => {
                let distance = marker.point.distance_squared(&markers[index].point);
                // Equal parameters must also be the same geometric marker. Two
                // different points at one parameter would represent a broken
                // split graph, the kind of degeneracy Greiner-Hormann style
                // traversal cannot resolve by local ordering alone.
                return match is_zero(&distance, policy) {
                    Some(true) => Ok(()),
                    Some(false) => Err(UncertaintyReason::Unsupported),
                    None => Err(UncertaintyReason::RealSign),
                };
            }
            Some(Ordering::Less) => {
                markers.insert(index, marker);
                return Ok(());
            }
            Some(Ordering::Greater) => {}
            None => return Err(UncertaintyReason::Ordering),
        }
    }

    markers.push(marker);
    Ok(())
}

fn validate_split_params(segment_splits: &[Vec<Real>]) -> CurveResult<()> {
    if segment_splits.is_empty() {
        return Err(CurveError::Topology(
            "contour split evidence must carry at least one source segment".to_owned(),
        ));
    }
    for params in segment_splits {
        validate_split_param_sequence(params)?;
    }
    Ok(())
}

fn validate_split_markers(segment_markers: &[Vec<SegmentSplitMarker>]) -> CurveResult<()> {
    if segment_markers.is_empty() {
        return Err(CurveError::Topology(
            "contour split marker evidence must carry at least one source segment".to_owned(),
        ));
    }
    for (segment_index, markers) in segment_markers.iter().enumerate() {
        validate_split_marker_sequence(segment_index, markers)?;
    }
    Ok(())
}

fn validate_split_marker_sequence(
    segment_index: usize,
    markers: &[SegmentSplitMarker],
) -> CurveResult<()> {
    if markers
        .iter()
        .any(|marker| marker.segment_index != segment_index)
    {
        return Err(CurveError::Topology(
            "contour split marker bin carries mismatched segment index evidence".to_owned(),
        ));
    }
    validate_split_param_sequence(markers.iter().map(|marker| &marker.param))
}

fn validate_split_param_sequence<'a>(
    params: impl IntoIterator<Item = &'a Real>,
) -> CurveResult<()> {
    let params = params.into_iter().collect::<Vec<_>>();
    if params.len() < 2 {
        return Err(CurveError::Topology(
            "contour split evidence must include both segment endpoints".to_owned(),
        ));
    }

    let policy = CurvePolicy::certified();
    if compare_reals(params[0], &Real::zero(), &policy) != Some(Ordering::Equal)
        || compare_reals(params[params.len() - 1], &Real::one(), &policy) != Some(Ordering::Equal)
    {
        return Err(CurveError::Topology(
            "contour split evidence must start at 0 and end at 1".to_owned(),
        ));
    }

    for param in &params {
        if in_closed_unit_interval(param, &policy) != Some(true) {
            return Err(CurveError::Topology(
                "contour split parameter evidence must lie inside the unit interval".to_owned(),
            ));
        }
    }

    for window in params.windows(2) {
        match compare_reals(window[0], window[1], &policy) {
            Some(Ordering::Less) => {}
            Some(Ordering::Equal | Ordering::Greater) => {
                return Err(CurveError::Topology(
                    "contour split parameter evidence must be strictly increasing".to_owned(),
                ));
            }
            None => {
                return Err(CurveError::Topology(
                    "contour split parameter ordering must be certified".to_owned(),
                ));
            }
        }
    }

    Ok(())
}