i_curve 0.1.2

Boolean operations on closed paths of lines, Bezier curves, and rational elliptic arcs
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
use crate::float::curve::converter::{CurveConversionReport, convert_resource, convert_shapes_to_float};
use crate::float::curve::path::CurvePath;
use crate::float::curve::shape::CurveShape;
use crate::float::resource::{CurveResource, resource_bounds};
use crate::int::CURVE_COORDINATE_SAFETY_BITS;
use crate::int::{CurveInt, CurveOverlayOptions, CurveOverlayOptionsError, IntCurveOverlay};
use crate::{CurveConversionError, FillRule, OverlayRule, Solver};
use i_overlay::i_float::adapter::FloatPointAdapter;
use i_overlay::i_float::float::compatible::FloatPointCompatible;
use i_overlay::i_float::float::number::FloatNumber;
use i_overlay::i_float::float::rect::FloatRect;
use i_overlay::i_float::int::number::int::IntNumber;

/// Curve approximation options expressed in float input coordinates.
///
/// Construct this non-exhaustive configuration from [`Default`] and override
/// only the values your application needs.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct FloatCurveOverlayOptions<F: FloatNumber> {
    /// Absolute chord length below which a curve segment is accepted without
    /// further subdivision.
    ///
    /// `None` preserves the scale-relative default used by the integer engine.
    pub min_chord_length: Option<F>,
    /// Maximum dimensionless sine deviation used to classify a curve segment
    /// as nearly linear. The value must be finite and in the range `(0, 1]`.
    pub angle_tolerance: F,
    /// Hard safety limit for local approximation subdivision. The value must
    /// not exceed [`CurveOverlayOptions::MAX_APPROXIMATION_DEPTH`].
    pub max_approximation_depth: u32,
    /// Power-of-two subdivision used when another chord endpoint lies inside
    /// a curve piece's convex hull. The default produces eight pieces.
    pub refinement_subdivision_power: u32,
    /// Negative power-of-two sine tolerance below which a curve piece is too
    /// flat to containment-refine.
    pub refinement_angle_tolerance_power: u32,
    /// Maximum number of containment-refinement passes.
    pub max_refinement_iterations: u32,
}

impl<F: FloatNumber> Default for FloatCurveOverlayOptions<F> {
    fn default() -> Self {
        Self {
            min_chord_length: None,
            angle_tolerance: F::from_float(0.125_f64),
            max_approximation_depth: CurveOverlayOptions::default().max_approximation_depth,
            refinement_subdivision_power: CurveOverlayOptions::default().refinement_subdivision_power,
            refinement_angle_tolerance_power: CurveOverlayOptions::default().refinement_angle_tolerance_power,
            max_refinement_iterations: CurveOverlayOptions::default().max_refinement_iterations,
        }
    }
}

/// Invalid [`FloatCurveOverlayOptions`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FloatCurveOverlayOptionsError {
    /// The requested minimum chord length is zero or negative.
    MinChordLengthNonPositive,
    /// The requested minimum chord length is NaN or infinite.
    MinChordLengthNotFinite,
    /// The requested angle tolerance is NaN or infinite.
    AngleToleranceNotFinite,
    /// The requested angle tolerance is outside `(0, 1]`.
    AngleToleranceOutOfRange,
    /// Integer approximation limits rejected the converted configuration.
    Approximation(CurveOverlayOptionsError),
}

impl From<CurveOverlayOptionsError> for FloatCurveOverlayOptionsError {
    fn from(error: CurveOverlayOptionsError) -> Self {
        Self::Approximation(error)
    }
}

impl core::fmt::Display for FloatCurveOverlayOptionsError {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::MinChordLengthNonPositive => formatter.write_str("minimum chord length must be positive"),
            Self::MinChordLengthNotFinite => formatter.write_str("minimum chord length must be finite"),
            Self::AngleToleranceNotFinite => formatter.write_str("angle tolerance must be finite"),
            Self::AngleToleranceOutOfRange => {
                formatter.write_str("angle tolerance must be in the range (0, 1]")
            }
            Self::Approximation(_) => formatter.write_str("invalid curve approximation options"),
        }
    }
}

impl core::error::Error for FloatCurveOverlayOptionsError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Approximation(error) => Some(error),
            _ => None,
        }
    }
}

impl<F: FloatNumber> FloatCurveOverlayOptions<F> {
    /// Sets the absolute minimum accepted chord length.
    #[must_use]
    pub fn with_min_chord_length(mut self, length: F) -> Self {
        self.min_chord_length = Some(length);
        self
    }

    /// Sets the maximum sine deviation used for near-linear classification.
    #[must_use]
    pub fn with_angle_tolerance(mut self, tolerance: F) -> Self {
        self.angle_tolerance = tolerance;
        self
    }

    /// Sets the local approximation subdivision limit.
    #[must_use]
    pub fn with_max_approximation_depth(mut self, depth: u32) -> Self {
        self.max_approximation_depth = depth;
        self
    }

    /// Sets the power-of-two subdivision used by containment refinement.
    #[must_use]
    pub fn with_refinement_subdivision_power(mut self, power: u32) -> Self {
        self.refinement_subdivision_power = power;
        self
    }

    /// Sets the near-linear angle threshold used by containment refinement.
    #[must_use]
    pub fn with_refinement_angle_tolerance_power(mut self, power: u32) -> Self {
        self.refinement_angle_tolerance_power = power;
        self
    }

    /// Sets the maximum number of containment-refinement passes.
    #[must_use]
    pub fn with_max_refinement_iterations(mut self, iterations: u32) -> Self {
        self.max_refinement_iterations = iterations;
        self
    }

    fn to_int<P, I>(
        self,
        adapter: &FloatPointAdapter<P, I>,
    ) -> Result<CurveOverlayOptions, FloatCurveOverlayOptionsError>
    where
        P: FloatPointCompatible<Scalar = F>,
        I: IntNumber,
    {
        let min_chord_length_power = match self.min_chord_length {
            Some(length) => {
                if !length.to_f64().is_finite() {
                    return Err(FloatCurveOverlayOptionsError::MinChordLengthNotFinite);
                }
                if length <= F::ZERO {
                    return Err(FloatCurveOverlayOptionsError::MinChordLengthNonPositive);
                }

                let grid_log2 = length.log2() + adapter.dir_scale().log2();
                if grid_log2 <= F::ZERO {
                    0
                } else {
                    grid_log2.to_i32() as u32
                }
            }
            None => CurveOverlayOptions::default().min_chord_length_power,
        };

        if !self.angle_tolerance.to_f64().is_finite() {
            return Err(FloatCurveOverlayOptionsError::AngleToleranceNotFinite);
        }
        if self.angle_tolerance <= F::ZERO || self.angle_tolerance > F::ONE {
            return Err(FloatCurveOverlayOptionsError::AngleToleranceOutOfRange);
        }

        let angle_power = -self.angle_tolerance.log2();
        let truncated_power = angle_power.to_i32();
        let angle_tolerance_power = if F::from_int(truncated_power) < angle_power {
            truncated_power + 1
        } else {
            truncated_power
        } as u32;

        Ok(CurveOverlayOptions {
            min_chord_length_power,
            angle_tolerance_power,
            max_approximation_depth: self.max_approximation_depth,
            refinement_subdivision_power: self.refinement_subdivision_power,
            refinement_angle_tolerance_power: self.refinement_angle_tolerance_power,
            max_refinement_iterations: self.max_refinement_iterations,
        })
    }
}

/// Boolean overlay for float curve shapes.
///
/// Inputs are mapped to one automatically selected fixed-point grid. The
/// integer topology engine and the reverse conversion are implementation
/// details; [`overlay`](Self::overlay) returns float curve shapes directly.
///
/// ```
/// use i_curve::{CurveBuilder, FillRule, FloatCurveOverlay, OverlayRule};
///
/// let subject = CurveBuilder::new()
///     .move_to([0.0_f64, 0.0])?
///     .line_to([10.0, 0.0])?
///     .line_to([10.0, 10.0])?
///     .close_contour()?
///     .build()?;
/// let clip = CurveBuilder::new()
///     .move_to([5.0_f64, -1.0])?
///     .line_to([12.0, -1.0])?
///     .line_to([12.0, 6.0])?
///     .close_contour()?
///     .build()?;
///
/// let result = FloatCurveOverlay::<_, i32>::new(&subject, &clip)
///     .overlay(OverlayRule::Intersect, FillRule::NonZero);
/// assert!(!result.is_empty());
/// # Ok::<(), i_curve::CurveBuildError>(())
/// ```
///
/// Inspect [`conversion_report`](Self::conversion_report) before consuming the
/// overlay when grid-induced geometry loss must be diagnosed.
pub struct FloatCurveOverlay<P: FloatPointCompatible, I: CurveInt> {
    adapter: FloatPointAdapter<P, I>,
    overlay: IntCurveOverlay<I>,
    options: FloatCurveOverlayOptions<P::Scalar>,
    conversion_report: FloatCurveOverlayConversionReport,
}

/// Per-operand float-to-integer conversion diagnostics for an overlay.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct FloatCurveOverlayConversionReport {
    /// Conversion diagnostics for the subject operand.
    pub subject: CurveConversionReport,
    /// Conversion diagnostics for the clip operand, or `None` for an overlay
    /// created with [`FloatCurveOverlay::from_subject`].
    pub clip: Option<CurveConversionReport>,
}

impl FloatCurveOverlayConversionReport {
    /// Returns whether either operand lost geometry or linearized an arc.
    #[inline]
    pub fn has_degeneracies(&self) -> bool {
        self.subject.has_degeneracies() || self.clip.is_some_and(|report| report.has_degeneracies())
    }
}

impl<P, I> FloatCurveOverlay<P, I>
where
    P: FloatPointCompatible,
    I: CurveInt,
{
    const COORDINATE_BITS: u32 = I::BITS - CURVE_COORDINATE_SAFETY_BITS;

    /// Creates an overlay containing subject and clip curve resources.
    ///
    /// The adapter is selected from the combined bounds so both inputs use
    /// exactly the same internal grid.
    pub fn new<R0, R1>(subject: &R0, clip: &R1) -> Self
    where
        R0: CurveResource<P> + ?Sized,
        R1: CurveResource<P> + ?Sized,
    {
        let bounds = combined_bounds(subject, clip);
        let adapter = FloatPointAdapter::with_coordinate_bits(bounds, Self::COORDINATE_BITS);
        Self::with_adapter(subject, Some(clip), adapter)
    }

    /// Creates an overlay containing only a subject curve resource.
    pub fn from_subject<R>(subject: &R) -> Self
    where
        R: CurveResource<P> + ?Sized,
    {
        let bounds = resource_bounds(subject).unwrap_or_else(FloatRect::zero);
        let adapter = FloatPointAdapter::with_coordinate_bits(bounds, Self::COORDINATE_BITS);
        Self::with_adapter::<R, R>(subject, None, adapter)
    }

    /// Creates a subject-only overlay with an explicit float-to-grid scale.
    ///
    /// This is the deterministic-scale counterpart of [`from_subject`](Self::from_subject),
    /// useful for resolving one operand with [`OverlayRule::Subject`]. Larger
    /// values retain smaller features but reduce the safe coordinate range.
    /// The scale is rejected when it cannot represent the subject bounds safely.
    pub fn try_from_subject_with_scale<R>(subject: &R, scale: P::Scalar) -> Result<Self, CurveConversionError>
    where
        R: CurveResource<P> + ?Sized,
    {
        let bounds = resource_bounds(subject).unwrap_or_else(FloatRect::zero);
        let adapter =
            FloatPointAdapter::try_with_scale_and_coordinate_bits(bounds, scale, Self::COORDINATE_BITS)?;
        Ok(Self::with_adapter::<R, R>(subject, None, adapter))
    }

    /// Creates an overlay with an explicit float-to-grid scale.
    ///
    /// Larger values retain smaller features but reduce the safe coordinate
    /// range. The scale is rejected when it cannot represent the combined
    /// input bounds safely.
    pub fn try_with_scale<R0, R1>(
        subject: &R0,
        clip: &R1,
        scale: P::Scalar,
    ) -> Result<Self, CurveConversionError>
    where
        R0: CurveResource<P> + ?Sized,
        R1: CurveResource<P> + ?Sized,
    {
        let bounds = combined_bounds(subject, clip);
        let adapter =
            FloatPointAdapter::try_with_scale_and_coordinate_bits(bounds, scale, Self::COORDINATE_BITS)?;
        Ok(Self::with_adapter(subject, Some(clip), adapter))
    }

    fn with_adapter<R0, R1>(subject: &R0, clip: Option<&R1>, adapter: FloatPointAdapter<P, I>) -> Self
    where
        R0: CurveResource<P> + ?Sized,
        R1: CurveResource<P> + ?Sized,
    {
        let capacity = resource_segment_count(subject) + clip.map_or(0, resource_segment_count);
        let mut overlay = IntCurveOverlay::with_capacity(capacity);
        let subject_report = add_converted_resource(&mut overlay, subject, &adapter, true);
        let clip_report = clip.map(|clip| add_converted_resource(&mut overlay, clip, &adapter, false));
        let conversion_report = FloatCurveOverlayConversionReport {
            subject: subject_report,
            clip: clip_report,
        };
        Self {
            adapter,
            overlay,
            options: FloatCurveOverlayOptions::default(),
            conversion_report,
        }
    }

    /// Sets the topology solver configuration.
    #[must_use]
    pub fn with_solver(mut self, solver: Solver) -> Self {
        self.overlay = self.overlay.with_solver(solver);
        self
    }

    /// Sets curve approximation options expressed in float input coordinates.
    pub fn try_with_options(
        mut self,
        options: FloatCurveOverlayOptions<P::Scalar>,
    ) -> Result<Self, FloatCurveOverlayOptionsError> {
        self.overlay = self.overlay.try_with_options(options.to_int(&self.adapter)?)?;
        self.options = options;
        Ok(self)
    }

    /// Returns the topology solver configuration.
    #[inline]
    pub fn solver(&self) -> Solver {
        self.overlay.solver()
    }

    /// Returns the curve approximation options in float input coordinates.
    #[inline]
    pub fn options(&self) -> FloatCurveOverlayOptions<P::Scalar> {
        self.options
    }

    /// Returns the effective float-to-integer conversion scale.
    #[inline]
    pub fn scale(&self) -> P::Scalar {
        self.adapter.dir_scale()
    }

    /// Returns topology changes observed while converting each operand.
    #[inline]
    pub fn conversion_report(&self) -> FloatCurveOverlayConversionReport {
        self.conversion_report
    }

    /// Resolves the subject operand using the selected fill rule.
    ///
    /// This is the direct completion method for overlays created with
    /// [`from_subject`](Self::from_subject) or
    /// [`try_from_subject_with_scale`](Self::try_from_subject_with_scale).
    /// If a clip operand is present, it is ignored.
    pub fn resolve_subject(self, fill_rule: FillRule) -> alloc::vec::Vec<CurveShape<P>> {
        self.overlay(OverlayRule::Subject, fill_rule)
    }

    /// Performs the Boolean operation and returns float curve shapes.
    pub fn overlay(self, overlay_rule: OverlayRule, fill_rule: FillRule) -> alloc::vec::Vec<CurveShape<P>> {
        let shapes = self.overlay.overlay(overlay_rule, fill_rule);
        convert_shapes_to_float(shapes, &self.adapter)
    }
}

fn add_converted_resource<P, I, R>(
    overlay: &mut IntCurveOverlay<I>,
    source: &R,
    adapter: &FloatPointAdapter<P, I>,
    is_subject: bool,
) -> CurveConversionReport
where
    P: FloatPointCompatible,
    I: CurveInt,
    R: CurveResource<P> + ?Sized,
{
    let (shape, report) = convert_resource(source, adapter);
    if shape.contours.is_empty() {
        return report;
    }

    let result = if is_subject {
        overlay.add_subject(shape)
    } else {
        overlay.add_clip(shape)
    };
    assert!(result.is_ok(), "float conversion produced invalid curve topology");
    report
}

impl<P: FloatPointCompatible> CurveShape<P> {
    /// Performs a Boolean operation using the standard `i32` engine.
    pub fn overlay(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<Self> {
        FloatCurveOverlay::<P, i32>::new(self, clip).overlay(overlay_rule, fill_rule)
    }

    /// Performs a Boolean operation using an explicitly selected integer engine.
    pub fn overlay_as<I>(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<Self>
    where
        I: CurveInt,
    {
        FloatCurveOverlay::<P, I>::new(self, clip).overlay(overlay_rule, fill_rule)
    }
}

impl<P: FloatPointCompatible> CurvePath<P> {
    /// Performs a Boolean operation using the standard `i32` engine.
    pub fn overlay(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<CurveShape<P>> {
        FloatCurveOverlay::<P, i32>::new(self, clip).overlay(overlay_rule, fill_rule)
    }

    /// Performs a Boolean operation using an explicitly selected integer engine.
    pub fn overlay_as<I>(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<CurveShape<P>>
    where
        I: CurveInt,
    {
        FloatCurveOverlay::<P, I>::new(self, clip).overlay(overlay_rule, fill_rule)
    }
}

/// Convenience Boolean operations for arbitrary float curve resources.
///
/// [`CurveShape`] and [`CurvePath`] provide the same methods directly. Import
/// this trait when the subject is a slice, array, `Vec`, or another resource.
pub trait CurveResourceOverlayExt<P: FloatPointCompatible>: CurveResource<P> {
    /// Uses the standard `i32` engine and returns float curves.
    fn overlay(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<CurveShape<P>>;

    /// Uses the selected integer engine and returns float curves.
    fn overlay_as<I>(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<CurveShape<P>>
    where
        I: CurveInt;
}

impl<P, R> CurveResourceOverlayExt<P> for R
where
    P: FloatPointCompatible,
    R: CurveResource<P> + ?Sized,
{
    #[inline]
    fn overlay(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<CurveShape<P>> {
        FloatCurveOverlay::<P, i32>::new(self, clip).overlay(overlay_rule, fill_rule)
    }

    #[inline]
    fn overlay_as<I>(
        &self,
        clip: &(impl CurveResource<P> + ?Sized),
        overlay_rule: OverlayRule,
        fill_rule: FillRule,
    ) -> alloc::vec::Vec<CurveShape<P>>
    where
        I: CurveInt,
    {
        FloatCurveOverlay::<P, I>::new(self, clip).overlay(overlay_rule, fill_rule)
    }
}

fn combined_bounds<P, R0, R1>(subject: &R0, clip: &R1) -> FloatRect<P::Scalar>
where
    P: FloatPointCompatible,
    R0: CurveResource<P> + ?Sized,
    R1: CurveResource<P> + ?Sized,
{
    match (resource_bounds(subject), resource_bounds(clip)) {
        (Some(subject), Some(clip)) => FloatRect::with_rects(subject, clip),
        (Some(bounds), None) | (None, Some(bounds)) => bounds,
        (None, None) => FloatRect::zero(),
    }
}

fn resource_segment_count<P, R>(resource: &R) -> usize
where
    P: FloatPointCompatible,
    R: CurveResource<P> + ?Sized,
{
    resource.iter_paths().map(|path| path.segments().len()).sum()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::float::arc::{Ellipse, EllipticArc};
    use crate::{CurveBuilder, FloatCurveSegment};

    fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> CurveShape<[f64; 2]> {
        CurveBuilder::new()
            .move_to([x0, y0])
            .unwrap()
            .line_to([x1, y0])
            .unwrap()
            .line_to([x1, y1])
            .unwrap()
            .line_to([x0, y1])
            .unwrap()
            .close_contour()
            .unwrap()
            .build()
            .unwrap()
    }

    #[test]
    fn convenience_overlay_returns_closed_float_paths() {
        let subject = rectangle(0.0, 0.0, 10.0, 10.0);
        let clip = rectangle(5.0, 2.0, 12.0, 8.0);

        let result = subject.overlay(&clip, OverlayRule::Intersect, FillRule::NonZero);

        assert_eq!(result.len(), 1);
        let start = result[0].contours()[0].start();
        assert!((start[0] - 5.0).abs() < 1.0e-6 || (start[0] - 10.0).abs() < 1.0e-6);
    }

    #[test]
    fn rational_arcs_are_returned_in_float_coordinates() {
        let circle = EllipticArc {
            ellipse: Ellipse {
                center: [2.0_f64, 3.0],
                radius_x: 5.0,
                radius_y: 5.0,
                rotation: 0.0,
            },
            start_angle: 0.0,
            sweep_angle: core::f64::consts::TAU,
        };
        let subject = CurveBuilder::new()
            .move_to(circle.start_point())
            .unwrap()
            .arc_to(circle)
            .unwrap()
            .close_contour()
            .unwrap()
            .build()
            .unwrap();

        let result = FloatCurveOverlay::<_, i32>::from_subject(&subject).resolve_subject(FillRule::NonZero);

        assert_eq!(result.len(), 1);
        assert!(
            result[0].contours()[0]
                .segments()
                .iter()
                .any(|segment| matches!(segment, FloatCurveSegment::Arc { arc } if arc.sweep_angle > 0.0))
        );
        let rebuilt = CurveShape::try_new(result[0].clone().into_contours()).unwrap();
        assert_eq!(rebuilt, result[0]);
    }

    #[test]
    fn explicit_scale_is_float_and_validated() {
        let subject = rectangle(0.0, 0.0, 10.0, 10.0);
        let clip = rectangle(5.0, 2.0, 12.0, 8.0);

        let result = FloatCurveOverlay::<_, i32>::try_with_scale(&subject, &clip, 1_000.0)
            .unwrap()
            .overlay(OverlayRule::Union, FillRule::NonZero);

        assert_eq!(result.len(), 1);
    }

    #[test]
    fn subject_only_explicit_scale_is_used_and_reported() {
        let subject = rectangle(0.0, 0.0, 10.0, 10.0);

        let overlay = FloatCurveOverlay::<_, i32>::try_from_subject_with_scale(&subject, 1_024.0).unwrap();

        assert_eq!(overlay.scale(), 1_024.0);
        let report = overlay.conversion_report();
        assert_eq!(report.subject.contour_count, 1);
        assert!(report.clip.is_none());
        assert!(!report.has_degeneracies());

        let result = overlay.resolve_subject(FillRule::NonZero);
        assert_eq!(result.len(), 1);

        let error = FloatCurveOverlay::<_, i32>::try_from_subject_with_scale(&subject, 0.0)
            .err()
            .unwrap();
        assert_eq!(error, CurveConversionError::ScaleNonPositive);
    }

    #[test]
    fn float_options_are_converted_with_the_effective_scale() {
        let subject = rectangle(0.0, 0.0, 10.0, 10.0);
        let clip = rectangle(5.0, 2.0, 12.0, 8.0);
        let options = FloatCurveOverlayOptions {
            min_chord_length: Some(0.25),
            angle_tolerance: 0.2,
            max_approximation_depth: 12,
            refinement_subdivision_power: 2,
            refinement_angle_tolerance_power: 6,
            max_refinement_iterations: 1,
        };

        let overlay = FloatCurveOverlay::<_, i32>::try_with_scale(&subject, &clip, 1_024.0)
            .unwrap()
            .try_with_options(options)
            .unwrap();

        assert_eq!(overlay.scale(), 1_024.0);
        assert_eq!(overlay.options(), options);
        assert_eq!(
            overlay.overlay.options(),
            CurveOverlayOptions {
                min_chord_length_power: 8,
                angle_tolerance_power: 3,
                max_approximation_depth: 12,
                refinement_subdivision_power: 2,
                refinement_angle_tolerance_power: 6,
                max_refinement_iterations: 1,
            }
        );
    }

    #[test]
    fn float_options_reject_invalid_tolerances() {
        let subject = rectangle(0.0, 0.0, 10.0, 10.0);
        let clip = rectangle(5.0, 2.0, 12.0, 8.0);

        let error = FloatCurveOverlay::<_, i32>::new(&subject, &clip)
            .try_with_options(FloatCurveOverlayOptions {
                min_chord_length: Some(0.0),
                ..Default::default()
            })
            .err();
        assert_eq!(
            error,
            Some(FloatCurveOverlayOptionsError::MinChordLengthNonPositive)
        );

        let error = FloatCurveOverlay::<_, i32>::new(&subject, &clip)
            .try_with_options(FloatCurveOverlayOptions {
                angle_tolerance: f64::NAN,
                ..Default::default()
            })
            .err();
        assert_eq!(
            error,
            Some(FloatCurveOverlayOptionsError::AngleToleranceNotFinite)
        );

        let error = FloatCurveOverlay::<_, i32>::new(&subject, &clip)
            .try_with_options(FloatCurveOverlayOptions {
                angle_tolerance: 1.1,
                ..Default::default()
            })
            .err();
        assert_eq!(
            error,
            Some(FloatCurveOverlayOptionsError::AngleToleranceOutOfRange)
        );

        let error = FloatCurveOverlay::<_, i32>::new(&subject, &clip)
            .try_with_options(
                FloatCurveOverlayOptions::default()
                    .with_max_approximation_depth(CurveOverlayOptions::MAX_APPROXIMATION_DEPTH + 1),
            )
            .err()
            .unwrap();
        assert_eq!(
            error,
            FloatCurveOverlayOptionsError::Approximation(
                CurveOverlayOptionsError::MaxApproximationDepthTooLarge {
                    requested: CurveOverlayOptions::MAX_APPROXIMATION_DEPTH + 1,
                    maximum: CurveOverlayOptions::MAX_APPROXIMATION_DEPTH,
                }
            )
        );
        assert_eq!(alloc::format!("{error}"), "invalid curve approximation options");
        let source = core::error::Error::source(&error).unwrap();
        assert!(source.is::<CurveOverlayOptionsError>());
        assert_eq!(
            alloc::format!("{source}"),
            alloc::format!(
                "maximum approximation depth {} exceeds the safety limit {}",
                CurveOverlayOptions::MAX_APPROXIMATION_DEPTH + 1,
                CurveOverlayOptions::MAX_APPROXIMATION_DEPTH
            )
        );
        assert!(source.source().is_none());
    }

    #[test]
    fn operand_collapsed_by_shared_grid_behaves_as_empty() {
        let subject = rectangle(0.0, 0.0, 10.0, 10.0);
        let clip = rectangle(5.0, 5.0, 5.0 + 1.0e-12, 5.0 + 1.0e-12);

        let overlay = FloatCurveOverlay::<_, i32>::new(&subject, &clip);
        let report = overlay.conversion_report();
        assert!(!report.subject.has_degeneracies());
        let clip_report = report.clip.expect("clip report");
        assert_eq!(clip_report.contour_count, 1);
        assert_eq!(clip_report.collapsed_contour_count, 1);
        assert_eq!(clip_report.collapsed_segment_count, 4);
        assert!(report.has_degeneracies());

        let intersection = overlay.overlay(OverlayRule::Intersect, FillRule::NonZero);
        let union = subject.overlay(&clip, OverlayRule::Union, FillRule::NonZero);

        assert!(intersection.is_empty());
        assert_eq!(union.len(), 1);
    }
}