skia-rs-path 0.2.7

Path geometry and operations for skia-rs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
//! Path data structure and iteration.

use skia_rs_core::{Point, Rect, Scalar};
use smallvec::SmallVec;
use std::sync::atomic::{AtomicU8, Ordering};

/// Path fill type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum FillType {
    /// Non-zero winding rule.
    #[default]
    Winding = 0,
    /// Even-odd rule.
    EvenOdd,
    /// Inverse non-zero winding.
    InverseWinding,
    /// Inverse even-odd.
    InverseEvenOdd,
}

impl FillType {
    /// Check if this is an inverse fill type.
    #[inline]
    pub const fn is_inverse(&self) -> bool {
        matches!(self, FillType::InverseWinding | FillType::InverseEvenOdd)
    }

    /// Convert to the inverse fill type.
    #[inline]
    pub const fn inverse(&self) -> Self {
        match self {
            FillType::Winding => FillType::InverseWinding,
            FillType::EvenOdd => FillType::InverseEvenOdd,
            FillType::InverseWinding => FillType::Winding,
            FillType::InverseEvenOdd => FillType::EvenOdd,
        }
    }
}

/// Path verb (command type).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Verb {
    /// Move to a point.
    Move = 0,
    /// Line to a point.
    Line,
    /// Quadratic bezier.
    Quad,
    /// Conic (weighted quadratic).
    Conic,
    /// Cubic bezier.
    Cubic,
    /// Close the current contour.
    Close,
}

impl Verb {
    /// Number of points consumed by this verb.
    #[inline]
    pub const fn point_count(&self) -> usize {
        match self {
            Verb::Move | Verb::Line => 1,
            Verb::Quad | Verb::Conic => 2,
            Verb::Cubic => 3,
            Verb::Close => 0,
        }
    }
}

/// Path direction (clockwise or counter-clockwise).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum PathDirection {
    /// Clockwise direction.
    #[default]
    CW = 0,
    /// Counter-clockwise direction.
    CCW,
}

/// Path convexity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(u8)]
pub enum PathConvexity {
    /// Unknown convexity.
    #[default]
    Unknown = 0,
    /// Path is convex.
    Convex = 1,
    /// Path is concave.
    Concave = 2,
}

impl PathConvexity {
    fn from_u8(v: u8) -> Self {
        match v {
            1 => PathConvexity::Convex,
            2 => PathConvexity::Concave,
            _ => PathConvexity::Unknown,
        }
    }
}

/// A 2D geometric path.
#[derive(Debug)]
pub struct Path {
    /// Path verbs.
    pub(crate) verbs: SmallVec<[Verb; 16]>,
    /// Path points.
    pub(crate) points: SmallVec<[Point; 32]>,
    /// Conic weights.
    pub(crate) conic_weights: SmallVec<[Scalar; 4]>,
    /// Fill type.
    pub(crate) fill_type: FillType,
    /// Cached bounds (lazily computed).
    pub(crate) bounds: Option<Rect>,
    /// Cached convexity (stored as u8 for Send+Sync via AtomicU8).
    pub(crate) convexity: AtomicU8,
}

impl Default for Path {
    fn default() -> Self {
        Self {
            verbs: SmallVec::new(),
            points: SmallVec::new(),
            conic_weights: SmallVec::new(),
            fill_type: FillType::default(),
            bounds: None,
            convexity: AtomicU8::new(PathConvexity::Unknown as u8),
        }
    }
}

impl Clone for Path {
    fn clone(&self) -> Self {
        Self {
            verbs: self.verbs.clone(),
            points: self.points.clone(),
            conic_weights: self.conic_weights.clone(),
            fill_type: self.fill_type,
            bounds: self.bounds,
            convexity: AtomicU8::new(self.convexity.load(Ordering::Relaxed)),
        }
    }
}

impl PartialEq for Path {
    fn eq(&self, other: &Self) -> bool {
        self.verbs == other.verbs
            && self.points == other.points
            && self.conic_weights == other.conic_weights
            && self.fill_type == other.fill_type
    }
}

#[inline]
fn axis_of(p: Point, axis: usize) -> Scalar {
    if axis == 0 { p.x } else { p.y }
}

#[inline]
fn record_axis_bound(
    axis: usize,
    val: Scalar,
    min_x: &mut Scalar,
    max_x: &mut Scalar,
    min_y: &mut Scalar,
    max_y: &mut Scalar,
) {
    if axis == 0 {
        if val < *min_x { *min_x = val; }
        if val > *max_x { *max_x = val; }
    } else {
        if val < *min_y { *min_y = val; }
        if val > *max_y { *max_y = val; }
    }
}

impl Path {
    /// Create a new empty path.
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Get the fill type.
    #[inline]
    pub fn fill_type(&self) -> FillType {
        self.fill_type
    }

    /// Set the fill type.
    #[inline]
    pub fn set_fill_type(&mut self, fill_type: FillType) {
        self.fill_type = fill_type;
    }

    /// Check if the path is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.verbs.is_empty()
    }

    /// Get the number of verbs.
    #[inline]
    pub fn verb_count(&self) -> usize {
        self.verbs.len()
    }

    /// Get the number of points.
    #[inline]
    pub fn point_count(&self) -> usize {
        self.points.len()
    }

    /// Get the bounds of the path.
    pub fn bounds(&self) -> Rect {
        if let Some(bounds) = self.bounds {
            return bounds;
        }

        if self.points.is_empty() {
            return Rect::EMPTY;
        }

        let mut min_x = self.points[0].x;
        let mut min_y = self.points[0].y;
        let mut max_x = min_x;
        let mut max_y = min_y;

        for p in &self.points[1..] {
            min_x = min_x.min(p.x);
            min_y = min_y.min(p.y);
            max_x = max_x.max(p.x);
            max_y = max_y.max(p.y);
        }

        Rect::new(min_x, min_y, max_x, max_y)
    }

    /// Clear the path.
    #[inline]
    pub fn reset(&mut self) {
        self.verbs.clear();
        self.points.clear();
        self.conic_weights.clear();
        self.bounds = None;
    }

    /// Iterate over the path elements.
    pub fn iter(&self) -> PathIter<'_> {
        PathIter {
            path: self,
            verb_index: 0,
            point_index: 0,
            weight_index: 0,
        }
    }

    /// Get the verbs slice.
    #[inline]
    pub fn verbs(&self) -> &[Verb] {
        &self.verbs
    }

    /// Get the points slice.
    #[inline]
    pub fn points(&self) -> &[Point] {
        &self.points
    }

    /// Get the last point in the path.
    #[inline]
    pub fn last_point(&self) -> Option<Point> {
        self.points.last().copied()
    }

    /// Get the number of contours in the path.
    pub fn contour_count(&self) -> usize {
        self.verbs.iter().filter(|v| **v == Verb::Move).count()
    }

    /// Check if the path is closed.
    pub fn is_closed(&self) -> bool {
        self.verbs.last() == Some(&Verb::Close)
    }

    /// Check if the path represents a line.
    pub fn is_line(&self) -> bool {
        self.verbs.len() == 2 && self.verbs[0] == Verb::Move && self.verbs[1] == Verb::Line
    }

    /// Check if the path represents a rectangle.
    pub fn is_rect(&self) -> Option<Rect> {
        // A rectangle has: Move, Line, Line, Line, Line, Close (or just 4 lines)
        if self.verbs.len() < 5 {
            return None;
        }

        let mut line_count = 0;
        let mut has_close = false;

        for verb in &self.verbs {
            match verb {
                Verb::Move => {}
                Verb::Line => line_count += 1,
                Verb::Close => has_close = true,
                _ => return None,
            }
        }

        if line_count != 4 || !has_close {
            return None;
        }

        // Check if points form a rectangle
        if self.points.len() < 5 {
            return None;
        }

        let p0 = self.points[0];
        let p1 = self.points[1];
        let p2 = self.points[2];
        let p3 = self.points[3];
        let p4 = self.points[4];

        // Check for axis-aligned rectangle
        let is_horizontal_1 = (p0.y - p1.y).abs() < 0.001;
        let is_vertical_2 = (p1.x - p2.x).abs() < 0.001;
        let is_horizontal_3 = (p2.y - p3.y).abs() < 0.001;
        let is_vertical_4 = (p3.x - p4.x).abs() < 0.001;

        if is_horizontal_1 && is_vertical_2 && is_horizontal_3 && is_vertical_4 {
            let left = p0.x.min(p1.x).min(p2.x).min(p3.x);
            let top = p0.y.min(p1.y).min(p2.y).min(p3.y);
            let right = p0.x.max(p1.x).max(p2.x).max(p3.x);
            let bottom = p0.y.max(p1.y).max(p2.y).max(p3.y);
            return Some(Rect::new(left, top, right, bottom));
        }

        None
    }

    /// Returns true if this path is a simple oval (ellipse).
    ///
    /// Verifies both verb structure (Move, 4 curves, Close) AND that the
    /// curve endpoints lie on the cardinal points of the bounding ellipse
    /// (left, right, top, bottom). This rejects 4-cubic paths that share
    /// the verb pattern but have arbitrary geometry.
    pub fn is_oval(&self) -> bool {
        let elements: Vec<_> = self.iter().collect();
        if elements.len() != 6 {
            return false;
        }

        let start = match elements[0] {
            PathElement::Move(p) => p,
            _ => return false,
        };
        if !matches!(elements[5], PathElement::Close) {
            return false;
        }

        let all_cubic = elements[1..5]
            .iter()
            .all(|e| matches!(e, PathElement::Cubic(_, _, _)));
        let all_conic = elements[1..5]
            .iter()
            .all(|e| matches!(e, PathElement::Conic(_, _, _)));
        if !all_cubic && !all_conic {
            return false;
        }

        let bounds = self.bounds();
        let cx = (bounds.left + bounds.right) * 0.5;
        let cy = (bounds.top + bounds.bottom) * 0.5;
        if bounds.right - bounds.left <= 0.0 || bounds.bottom - bounds.top <= 0.0 {
            return false;
        }

        let tolerance = ((bounds.right - bounds.left) + (bounds.bottom - bounds.top)) * 1e-4;
        let on_cardinal = |p: Point| -> bool {
            let on_h = (p.y - cy).abs() < tolerance
                && ((p.x - bounds.left).abs() < tolerance
                    || (p.x - bounds.right).abs() < tolerance);
            let on_v = (p.x - cx).abs() < tolerance
                && ((p.y - bounds.top).abs() < tolerance
                    || (p.y - bounds.bottom).abs() < tolerance);
            on_h || on_v
        };

        if !on_cardinal(start) {
            return false;
        }

        for elem in &elements[1..5] {
            let end = match *elem {
                PathElement::Cubic(_, _, p) => p,
                PathElement::Conic(_, p, _) => p,
                _ => return false,
            };
            if !on_cardinal(end) {
                return false;
            }
        }

        true
    }

    /// Get the convexity of the path.
    pub fn convexity(&self) -> PathConvexity {
        let cached = PathConvexity::from_u8(self.convexity.load(Ordering::Relaxed));
        if cached != PathConvexity::Unknown {
            return cached;
        }

        // Simple convexity check based on cross product signs
        if self.points.len() < 3 {
            let result = PathConvexity::Convex;
            self.convexity.store(result as u8, Ordering::Relaxed);
            return result;
        }

        let mut sign = 0i32;
        let n = self.points.len();

        for i in 0..n {
            let p0 = self.points[i];
            let p1 = self.points[(i + 1) % n];
            let p2 = self.points[(i + 2) % n];

            let cross = (p1.x - p0.x) * (p2.y - p1.y) - (p1.y - p0.y) * (p2.x - p1.x);

            if cross.abs() > 0.001 {
                let current_sign = if cross > 0.0 { 1 } else { -1 };
                if sign == 0 {
                    sign = current_sign;
                } else if sign != current_sign {
                    let result = PathConvexity::Concave;
                    self.convexity.store(result as u8, Ordering::Relaxed);
                    return result;
                }
            }
        }

        let result = PathConvexity::Convex;
        self.convexity.store(result as u8, Ordering::Relaxed);
        result
    }

    /// Check if the path is convex.
    #[inline]
    pub fn is_convex(&self) -> bool {
        self.convexity() == PathConvexity::Convex
    }

    /// Get the direction of the first contour.
    pub fn direction(&self) -> Option<PathDirection> {
        if self.points.len() < 3 {
            return None;
        }

        // Calculate signed area using shoelace formula
        let mut signed_area = 0.0;
        let n = self.points.len();

        for i in 0..n {
            let p0 = self.points[i];
            let p1 = self.points[(i + 1) % n];
            signed_area += (p1.x - p0.x) * (p1.y + p0.y);
        }

        if signed_area.abs() < 0.001 {
            return None;
        }

        Some(if signed_area > 0.0 {
            PathDirection::CW
        } else {
            PathDirection::CCW
        })
    }

    /// Reverse the path direction.
    pub fn reverse(&mut self) {
        if self.verbs.is_empty() {
            return;
        }

        // Reverse points
        self.points.reverse();

        // Reverse conic weights
        self.conic_weights.reverse();

        // Reverse verbs (keeping structure)
        // This is a simplified implementation
        let mut new_verbs = SmallVec::new();
        let mut i = self.verbs.len();

        while i > 0 {
            i -= 1;
            match self.verbs[i] {
                Verb::Move => {
                    if !new_verbs.is_empty() {
                        new_verbs.push(Verb::Close);
                    }
                    new_verbs.push(Verb::Move);
                }
                Verb::Close => {
                    // Skip, will be added before next Move
                }
                v => new_verbs.push(v),
            }
        }

        if !new_verbs.is_empty() && self.is_closed() {
            new_verbs.push(Verb::Close);
        }

        self.verbs = new_verbs;
        self.bounds = None;
        self.convexity.store(PathConvexity::Unknown as u8, Ordering::Relaxed);
    }

    /// Transform the path by a matrix.
    pub fn transform(&mut self, matrix: &skia_rs_core::Matrix) {
        for point in &mut self.points {
            *point = matrix.map_point(*point);
        }
        self.bounds = None;
        self.convexity.store(PathConvexity::Unknown as u8, Ordering::Relaxed);
    }

    /// Create a transformed copy of the path.
    pub fn transformed(&self, matrix: &skia_rs_core::Matrix) -> Self {
        let mut result = self.clone();
        result.transform(matrix);
        result
    }

    /// Offset the path by (dx, dy).
    pub fn offset(&mut self, dx: Scalar, dy: Scalar) {
        for point in &mut self.points {
            point.x += dx;
            point.y += dy;
        }
        if let Some(ref mut bounds) = self.bounds {
            bounds.left += dx;
            bounds.right += dx;
            bounds.top += dy;
            bounds.bottom += dy;
        }
    }

    /// Check if a point is inside the path (using fill rule).
    pub fn contains(&self, point: Point) -> bool {
        use crate::flatten::{flatten_cubic_adaptive, flatten_conic_adaptive, flatten_quad_adaptive};

        // Ray casting algorithm
        if !self.bounds().contains(point) {
            return false;
        }

        let mut crossings = 0;
        let mut current = Point::zero();
        let mut contour_start = Point::zero();
        const TOL: Scalar = 0.1;
        let mut pts: Vec<Point> = Vec::with_capacity(32);

        for element in self.iter() {
            match element {
                PathElement::Move(p) => {
                    current = p;
                    contour_start = p;
                }
                PathElement::Line(end) => {
                    if ray_crosses_segment(point, current, end) {
                        crossings += 1;
                    }
                    current = end;
                }
                PathElement::Quad(ctrl, end) => {
                    pts.clear();
                    flatten_quad_adaptive(&mut pts, current, ctrl, end, TOL);
                    let mut prev = current;
                    for pt in &pts {
                        if ray_crosses_segment(point, prev, *pt) {
                            crossings += 1;
                        }
                        prev = *pt;
                    }
                    current = end;
                }
                PathElement::Conic(ctrl, end, w) => {
                    pts.clear();
                    flatten_conic_adaptive(&mut pts, current, ctrl, end, w, TOL);
                    let mut prev = current;
                    for pt in &pts {
                        if ray_crosses_segment(point, prev, *pt) {
                            crossings += 1;
                        }
                        prev = *pt;
                    }
                    current = end;
                }
                PathElement::Cubic(c1, c2, end) => {
                    pts.clear();
                    flatten_cubic_adaptive(&mut pts, current, c1, c2, end, TOL);
                    let mut prev = current;
                    for pt in &pts {
                        if ray_crosses_segment(point, prev, *pt) {
                            crossings += 1;
                        }
                        prev = *pt;
                    }
                    current = end;
                }
                PathElement::Close => {
                    if ray_crosses_segment(point, current, contour_start) {
                        crossings += 1;
                    }
                    current = contour_start;
                }
            }
        }

        match self.fill_type {
            FillType::Winding => crossings != 0,
            FillType::EvenOdd => crossings % 2 != 0,
            FillType::InverseWinding => crossings == 0,
            FillType::InverseEvenOdd => crossings % 2 == 0,
        }
    }

    /// Returns the tight bounding rectangle of this path.
    ///
    /// Unlike `bounds()`, this computes the bounds from the actual curve
    /// extents, not the control-point bounding box. For cubic and quadratic
    /// Bezier curves with control points outside the actual curve range,
    /// tight_bounds() may be significantly smaller than bounds().
    ///
    /// Conics fall back to control-polygon bounds (exact extrema for rational
    /// curves would require solving a quartic).
    pub fn tight_bounds(&self) -> Rect {
        if self.verbs.is_empty() {
            return Rect::EMPTY;
        }

        let mut min_x = Scalar::INFINITY;
        let mut min_y = Scalar::INFINITY;
        let mut max_x = Scalar::NEG_INFINITY;
        let mut max_y = Scalar::NEG_INFINITY;

        let include = |p: Point, min_x: &mut Scalar, min_y: &mut Scalar, max_x: &mut Scalar, max_y: &mut Scalar| {
            if p.x < *min_x { *min_x = p.x; }
            if p.y < *min_y { *min_y = p.y; }
            if p.x > *max_x { *max_x = p.x; }
            if p.y > *max_y { *max_y = p.y; }
        };

        let mut current = Point::new(0.0, 0.0);

        for elem in self.iter() {
            match elem {
                PathElement::Move(p) | PathElement::Line(p) => {
                    include(p, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    current = p;
                }
                PathElement::Quad(c, p) => {
                    include(current, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    include(p, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    // Quadratic extremum per axis: t = (start - ctrl) / (start - 2*ctrl + end)
                    for axis in 0..2 {
                        let s = axis_of(current, axis);
                        let cv = axis_of(c, axis);
                        let e = axis_of(p, axis);
                        let denom = s - 2.0 * cv + e;
                        if denom.abs() > 1e-9 {
                            let t = (s - cv) / denom;
                            if t > 0.0 && t < 1.0 {
                                let mt = 1.0 - t;
                                let val = mt * mt * s + 2.0 * mt * t * cv + t * t * e;
                                record_axis_bound(axis, val, &mut min_x, &mut max_x, &mut min_y, &mut max_y);
                            }
                        }
                    }
                    current = p;
                }
                PathElement::Cubic(c1, c2, p) => {
                    include(current, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    include(p, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    // Cubic extrema per axis: solve 3*a*t^2 + 2*b*t + c = 0 where
                    // B'(t) = 3*(1-t)^2*(c1-s) + 6*(1-t)*t*(c2-c1) + 3*t^2*(e-c2)
                    // Expanding into quadratic: a*t^2 + b*t + cc
                    for axis in 0..2 {
                        let s = axis_of(current, axis);
                        let c1v = axis_of(c1, axis);
                        let c2v = axis_of(c2, axis);
                        let e = axis_of(p, axis);
                        let a = 3.0 * (e - 3.0 * c2v + 3.0 * c1v - s);
                        let b = 6.0 * (c2v - 2.0 * c1v + s);
                        let cc = 3.0 * (c1v - s);

                        let mut roots: [Scalar; 2] = [Scalar::NAN, Scalar::NAN];
                        let mut n_roots = 0;

                        if a.abs() < 1e-9 {
                            // Linear: b*t + cc = 0
                            if b.abs() > 1e-9 {
                                let t = -cc / b;
                                roots[0] = t;
                                n_roots = 1;
                            }
                        } else {
                            let disc = b * b - 4.0 * a * cc;
                            if disc >= 0.0 {
                                let sqrt_disc = disc.sqrt();
                                roots[0] = (-b + sqrt_disc) / (2.0 * a);
                                roots[1] = (-b - sqrt_disc) / (2.0 * a);
                                n_roots = 2;
                            }
                        }

                        for i in 0..n_roots {
                            let t = roots[i];
                            if t.is_finite() && t > 0.0 && t < 1.0 {
                                let mt = 1.0 - t;
                                let val = mt * mt * mt * s
                                    + 3.0 * mt * mt * t * c1v
                                    + 3.0 * mt * t * t * c2v
                                    + t * t * t * e;
                                record_axis_bound(axis, val, &mut min_x, &mut max_x, &mut min_y, &mut max_y);
                            }
                        }
                    }
                    current = p;
                }
                PathElement::Conic(c, p, _w) => {
                    // Rational extrema require quartic solve; use control polygon
                    // as a correct (if looser) upper bound.
                    include(current, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    include(c, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    include(p, &mut min_x, &mut min_y, &mut max_x, &mut max_y);
                    current = p;
                }
                PathElement::Close => {}
            }
        }

        if min_x == Scalar::INFINITY {
            return Rect::EMPTY;
        }
        Rect::new(min_x, min_y, max_x, max_y)
    }

    /// Get the total length of the path.
    pub fn length(&self) -> Scalar {
        use crate::flatten::{flatten_cubic_adaptive, flatten_conic_adaptive, flatten_quad_adaptive};

        let mut total = 0.0;
        let mut current = Point::zero();
        let mut contour_start = Point::zero();
        const TOL: Scalar = 0.25;
        let mut pts: Vec<Point> = Vec::with_capacity(32);

        for element in self.iter() {
            match element {
                PathElement::Move(p) => {
                    current = p;
                    contour_start = p;
                }
                PathElement::Line(end) => {
                    total += current.distance(&end);
                    current = end;
                }
                PathElement::Quad(ctrl, end) => {
                    pts.clear();
                    flatten_quad_adaptive(&mut pts, current, ctrl, end, TOL);
                    let mut prev = current;
                    for pt in &pts {
                        total += prev.distance(pt);
                        prev = *pt;
                    }
                    current = end;
                }
                PathElement::Conic(ctrl, end, w) => {
                    pts.clear();
                    flatten_conic_adaptive(&mut pts, current, ctrl, end, w, TOL);
                    let mut prev = current;
                    for pt in &pts {
                        total += prev.distance(pt);
                        prev = *pt;
                    }
                    current = end;
                }
                PathElement::Cubic(c1, c2, end) => {
                    pts.clear();
                    flatten_cubic_adaptive(&mut pts, current, c1, c2, end, TOL);
                    let mut prev = current;
                    for pt in &pts {
                        total += prev.distance(pt);
                        prev = *pt;
                    }
                    current = end;
                }
                PathElement::Close => {
                    total += current.distance(&contour_start);
                    current = contour_start;
                }
            }
        }

        total
    }
}

/// Check if a horizontal ray from point crosses the segment.
fn ray_crosses_segment(point: Point, p0: Point, p1: Point) -> bool {
    // Ensure p0 is below p1
    let (p0, p1) = if p0.y <= p1.y { (p0, p1) } else { (p1, p0) };

    // Check if point is in y-range of segment
    if point.y < p0.y || point.y >= p1.y {
        return false;
    }

    // Calculate x-coordinate of intersection
    let t = (point.y - p0.y) / (p1.y - p0.y);
    let x_intersect = p0.x + t * (p1.x - p0.x);

    x_intersect > point.x
}

/// A path element from iteration.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PathElement {
    /// Move to point.
    Move(Point),
    /// Line to point.
    Line(Point),
    /// Quadratic bezier (control, end).
    Quad(Point, Point),
    /// Conic (control, end, weight).
    Conic(Point, Point, Scalar),
    /// Cubic bezier (control1, control2, end).
    Cubic(Point, Point, Point),
    /// Close the path.
    Close,
}

/// Iterator over path elements.
pub struct PathIter<'a> {
    path: &'a Path,
    verb_index: usize,
    point_index: usize,
    weight_index: usize,
}

impl<'a> Iterator for PathIter<'a> {
    type Item = PathElement;

    fn next(&mut self) -> Option<Self::Item> {
        if self.verb_index >= self.path.verbs.len() {
            return None;
        }

        let verb = self.path.verbs[self.verb_index];
        self.verb_index += 1;

        let element = match verb {
            Verb::Move => {
                let p = self.path.points[self.point_index];
                self.point_index += 1;
                PathElement::Move(p)
            }
            Verb::Line => {
                let p = self.path.points[self.point_index];
                self.point_index += 1;
                PathElement::Line(p)
            }
            Verb::Quad => {
                let p1 = self.path.points[self.point_index];
                let p2 = self.path.points[self.point_index + 1];
                self.point_index += 2;
                PathElement::Quad(p1, p2)
            }
            Verb::Conic => {
                let p1 = self.path.points[self.point_index];
                let p2 = self.path.points[self.point_index + 1];
                let w = self.path.conic_weights[self.weight_index];
                self.point_index += 2;
                self.weight_index += 1;
                PathElement::Conic(p1, p2, w)
            }
            Verb::Cubic => {
                let p1 = self.path.points[self.point_index];
                let p2 = self.path.points[self.point_index + 1];
                let p3 = self.path.points[self.point_index + 2];
                self.point_index += 3;
                PathElement::Cubic(p1, p2, p3)
            }
            Verb::Close => PathElement::Close,
        };

        Some(element)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::PathBuilder;

    #[test]
    fn test_is_oval_true_for_actual_oval() {
        let mut builder = PathBuilder::new();
        builder.add_oval(&Rect::new(0.0, 0.0, 100.0, 50.0));
        let path = builder.build();
        assert!(path.is_oval(), "add_oval result should report is_oval=true");
    }

    #[test]
    fn test_is_oval_false_for_random_cubics() {
        // 4 cubics with arbitrary control points — should NOT be detected.
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.cubic_to(10.0, 0.0, 20.0, 5.0, 30.0, 10.0);
        builder.cubic_to(40.0, 15.0, 50.0, 20.0, 60.0, 25.0);
        builder.cubic_to(70.0, 30.0, 80.0, 35.0, 90.0, 40.0);
        builder.cubic_to(95.0, 45.0, 100.0, 47.0, 0.0, 0.0);
        builder.close();
        let path = builder.build();
        assert!(!path.is_oval(), "Random 4-cubic path should not be detected as oval");
    }

    #[test]
    fn test_path_convexity_returns_consistent_result() {
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.line_to(10.0, 0.0);
        builder.line_to(10.0, 10.0);
        builder.line_to(0.0, 10.0);
        builder.close();
        let path = builder.build();

        let c1 = path.convexity();
        let c2 = path.convexity();
        assert_eq!(c1, c2);
    }

    #[test]
    fn test_tight_bounds_smaller_than_bounds_for_curves() {
        // A cubic Bezier where control points extend far beyond the actual curve.
        // The "loose" bounds (bounds()) include control points; tight should be tighter.
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.cubic_to(50.0, 100.0, 50.0, -100.0, 100.0, 0.0);
        let path = builder.build();

        let loose = path.bounds();
        let tight = path.tight_bounds();

        // Loose bounds include y=±100 control points
        assert!(
            loose.top <= -99.0 || loose.bottom >= 99.0,
            "Loose bounds should include control points (top={}, bottom={})",
            loose.top, loose.bottom
        );

        // Tight bounds should be strictly tighter on at least one of top/bottom
        assert!(
            tight.top > loose.top || tight.bottom < loose.bottom,
            "Tight bounds should be tighter than loose for this off-axis cubic"
        );

        // For this symmetric S-cubic, actual extrema are approximately ±19.245
        assert!(
            tight.bottom < 30.0 && tight.top > -30.0,
            "Tight bounds should reflect actual curve range (got top={}, bottom={})",
            tight.top, tight.bottom
        );
    }

    #[test]
    fn test_tight_bounds_same_as_bounds_for_lines() {
        // For line-only paths, tight_bounds should equal bounds
        let mut builder = PathBuilder::new();
        builder.move_to(10.0, 20.0);
        builder.line_to(30.0, 40.0);
        let path = builder.build();

        let loose = path.bounds();
        let tight = path.tight_bounds();
        assert!((loose.left - tight.left).abs() < 1e-4);
        assert!((loose.right - tight.right).abs() < 1e-4);
        assert!((loose.top - tight.top).abs() < 1e-4);
        assert!((loose.bottom - tight.bottom).abs() < 1e-4);
    }

    #[test]
    fn test_length_quarter_circle_close_to_pi_over_2() {
        // Quarter-circle arc as a conic with weight sqrt(2)/2.
        // Radius 1, circumference of full circle = 2π, quarter = π/2 ≈ 1.5708.
        let mut builder = PathBuilder::new();
        builder.move_to(1.0, 0.0);
        builder.conic_to(1.0, 1.0, 0.0, 1.0, std::f32::consts::FRAC_1_SQRT_2);
        let path = builder.build();
        let len = path.length();
        let expected = std::f32::consts::FRAC_PI_2;
        assert!(
            (len - expected).abs() < 0.05,
            "expected ~π/2 = {}, got {}",
            expected,
            len
        );
    }

    #[test]
    fn test_length_tight_cubic_less_than_control_polygon() {
        // Straight-line cubic: all 4 control points collinear. Length = chord length.
        // Control polygon length = 3x chord length. Old impl would return 3x.
        let mut builder = PathBuilder::new();
        builder.move_to(0.0, 0.0);
        builder.cubic_to(1.0, 0.0, 2.0, 0.0, 3.0, 0.0);
        let path = builder.build();
        let len = path.length();
        assert!(
            (len - 3.0).abs() < 0.1,
            "expected 3.0, got {}",
            len
        );
    }

    #[test]
    fn test_contains_conic_honors_weight() {
        // A quarter-circle conic + closing lines forms a filled quarter-disk.
        // A point inside the arc but outside the control triangle should still be contained.
        let mut builder = PathBuilder::new();
        builder.move_to(1.0, 0.0);
        builder.conic_to(1.0, 1.0, 0.0, 1.0, std::f32::consts::FRAC_1_SQRT_2);
        builder.line_to(0.0, 0.0);
        builder.close();
        let path = builder.build();

        // Point at (0.7, 0.3) is inside the quarter-circle (r = sqrt(0.49 + 0.09) ≈ 0.76 < 1)
        assert!(
            path.contains(Point::new(0.7, 0.3)),
            "point inside quarter-disk should be contained"
        );

        // Point at (0.9, 0.9) is outside the arc (r = sqrt(0.81 + 0.81) ≈ 1.27 > 1)
        assert!(
            !path.contains(Point::new(0.9, 0.9)),
            "point outside quarter-disk should not be contained"
        );
    }
}