valo-geometry 0.7.1

Pure 2D math for valo: points, rects, paths, 4x4 matrices, strokes, color
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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
use std::sync::Arc;

use crate::{Matrix, Point, Rect};

/// `FillRule` determines which regions of overlapping contours are filled.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FillRule {
    /// `NonZero` fills regions whose signed winding count is nonzero.
    #[default]
    NonZero,
    /// `EvenOdd` fills regions crossed an odd number of times.
    EvenOdd,
}

/// `Winding` selects the traversal direction of a closed contour.
///
/// Direction matters wherever traversal carries meaning: under the nonzero fill
/// rule two overlapping contours cancel when their windings oppose and add
/// when they agree, and dashing walks a contour in order.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Winding {
    /// `Clockwise` traverses in the clockwise direction on Valo's y-down plane.
    #[default]
    Clockwise,
    /// `CounterClockwise` traverses in the counterclockwise direction.
    CounterClockwise,
}

// Serialize ONLY (the serde feature is a debug dump): a deserializer would
// let malformed verb/point/weight counts reach flatten() and index out of
// bounds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
enum Verb {
    Move,
    Line,
    Quad,
    /// A rational quadratic: control point, end point, and a weight drawn
    /// from the side channel `weights`. Weights are strictly positive and
    /// finite — `conic_to` lowers everything else.
    Conic,
    Cubic,
    Close,
}

/// `Contour` is one path contour flattened into a polyline.
///
/// Closed contours repeat their first point at the end so measurement and
/// dashing include the closing edge. Closure remains explicit metadata rather
/// than being inferred from coincident endpoints.
#[derive(Clone, Debug, PartialEq)]
pub struct Contour {
    /// `points` contains the flattened polyline in traversal order.
    pub points: Vec<Point>,
    /// `closed` indicates whether the source contour ended with `close`.
    pub closed: bool,
    /// `has_segments` distinguishes drawn zero-length contours from a lone move.
    ///
    /// A close or explicit zero-length segment counts; a bare `move_to` does not.
    pub has_segments: bool,
}

/// `PathElement` is one step of a [`Path`], as [`Path::elements`] walks it.
///
/// Points are absolute. A `Conic` carries its weight; feed the elements to a
/// [`PathBuilder`] in order to rebuild an equal path.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PathElement {
    MoveTo(Point),
    LineTo(Point),
    QuadTo(Point, Point),
    ConicTo(Point, Point, f32),
    CubicTo(Point, Point, Point),
    Close,
}

/// `Path` is an immutable collection of line and Bézier contours.
///
/// Build paths with [`PathBuilder`]. Display lists retain shared [`Arc`] handles,
/// so recording and nesting do not copy path data.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Path {
    verbs: Vec<Verb>,
    points: Vec<Point>,
    /// One entry per `Verb::Conic`, consumed in verb order. Positive weights
    /// keep the curve inside its control hull, so `bounds` stays sound.
    weights: Vec<f32>,
    /// Control-point bounds: conservative (curves stay inside their hull),
    /// which is exactly what the record-time oracle wants.
    bounds: Rect,
}

impl Path {
    /// `elements` walks the path's verbs with their points, for a consumer that
    /// serializes or re-encodes it rather than flattens it.
    pub fn elements(&self) -> impl Iterator<Item = PathElement> + '_ {
        let mut point = 0;
        let mut weight = 0;
        self.verbs.iter().map(move |verb| {
            let element = match verb {
                Verb::Move => PathElement::MoveTo(self.points[point]),
                Verb::Line => PathElement::LineTo(self.points[point]),
                Verb::Quad => PathElement::QuadTo(self.points[point], self.points[point + 1]),
                Verb::Conic => {
                    let element = PathElement::ConicTo(
                        self.points[point],
                        self.points[point + 1],
                        self.weights[weight],
                    );
                    weight += 1;
                    element
                }
                Verb::Cubic => PathElement::CubicTo(
                    self.points[point],
                    self.points[point + 1],
                    self.points[point + 2],
                ),
                Verb::Close => PathElement::Close,
            };
            point += match verb {
                Verb::Move | Verb::Line => 1,
                Verb::Quad | Verb::Conic => 2,
                Verb::Cubic => 3,
                Verb::Close => 0,
            };
            element
        })
    }

    /// `bounds` returns conservative control-point bounds.
    pub fn bounds(&self) -> Rect {
        self.bounds
    }

    /// `tight_bounds` returns exact axis-aligned curve bounds.
    pub fn tight_bounds(&self) -> Rect {
        let mut bounds = TightBounds::default();
        let mut point_index = 0usize;
        let mut weight_index = 0usize;
        let mut cursor = Point::ZERO;
        let mut contour_start = Point::ZERO;
        for verb in &self.verbs {
            match verb {
                Verb::Move => {
                    cursor = self.points[point_index];
                    contour_start = cursor;
                    point_index += 1;
                    bounds.include(cursor);
                }
                Verb::Line => {
                    cursor = self.points[point_index];
                    point_index += 1;
                    bounds.include(cursor);
                }
                Verb::Quad => {
                    let control = self.points[point_index];
                    let end = self.points[point_index + 1];
                    point_index += 2;
                    include_quadratic_extrema(&mut bounds, cursor, control, end);
                    cursor = end;
                }
                Verb::Conic => {
                    let control = self.points[point_index];
                    let end = self.points[point_index + 1];
                    let weight = self.weights[weight_index];
                    point_index += 2;
                    weight_index += 1;
                    include_conic_extrema(&mut bounds, cursor, control, end, weight);
                    cursor = end;
                }
                Verb::Cubic => {
                    let first = self.points[point_index];
                    let second = self.points[point_index + 1];
                    let end = self.points[point_index + 2];
                    point_index += 3;
                    include_cubic_extrema(&mut bounds, cursor, first, second, end);
                    cursor = end;
                }
                Verb::Close => {
                    cursor = contour_start;
                    bounds.include(cursor);
                }
            }
        }
        bounds.rect()
    }

    /// `is_empty` reports whether the path contains no commands.
    pub fn is_empty(&self) -> bool {
        self.verbs.is_empty()
    }

    /// `heap_bytes` returns an estimate of owned path storage.
    pub fn heap_bytes(&self) -> usize {
        self.points.len() * std::mem::size_of::<Point>()
            + self.weights.len() * std::mem::size_of::<f32>()
            + self.verbs.len()
    }

    /// `contains` reports whether a point lies inside the filled path.
    ///
    /// The query evaluates the original curves, implicitly closes open contours,
    /// and treats points on the outline as inside.
    pub fn contains(&self, point: Point, fill_rule: FillRule) -> bool {
        if !self.bounds.contains_inclusive(point) {
            return false;
        }
        let crossings = self.walk_crossings(point);
        match fill_rule {
            FillRule::NonZero => crossings.is_inside_non_zero(),
            FillRule::EvenOdd => crossings.is_inside_even_odd(),
        }
    }

    /// Ray-cast the whole path, one segment at a time.
    fn walk_crossings(&self, point: Point) -> crate::winding::Crossings {
        let mut crossings = crate::winding::Crossings::default();
        let mut index = 0usize;
        let mut weight_index = 0usize;
        let mut cursor = Point::ZERO;
        let mut contour_start = Point::ZERO;
        let mut contour_open = false;
        for verb in &self.verbs {
            match verb {
                Verb::Move => {
                    // A new contour closes the previous one: fills always see
                    // that last→first edge, whether or not Close was recorded.
                    if contour_open {
                        crossings.line(cursor, contour_start, point);
                    }
                    contour_open = true;
                    contour_start = self.points[index];
                    cursor = contour_start;
                    index += 1;
                }
                Verb::Line => {
                    crossings.line(cursor, self.points[index], point);
                    cursor = self.points[index];
                    index += 1;
                }
                Verb::Quad => {
                    crossings.quad(cursor, self.points[index], self.points[index + 1], point);
                    cursor = self.points[index + 1];
                    index += 2;
                }
                Verb::Conic => {
                    crossings.conic(
                        cursor,
                        self.points[index],
                        self.points[index + 1],
                        self.weights[weight_index],
                        point,
                    );
                    cursor = self.points[index + 1];
                    index += 2;
                    weight_index += 1;
                }
                Verb::Cubic => {
                    crossings.cubic(
                        cursor,
                        self.points[index],
                        self.points[index + 1],
                        self.points[index + 2],
                        point,
                    );
                    cursor = self.points[index + 2];
                    index += 3;
                }
                Verb::Close => {
                    crossings.line(cursor, contour_start, point);
                    cursor = contour_start;
                    contour_open = false;
                }
            }
        }
        if contour_open {
            crossings.line(cursor, contour_start, point);
        }
        crossings
    }

    /// `measure` returns an arc-length measurement for each nonempty contour.
    ///
    /// `tolerance` is the maximum flattening deviation in path coordinates.
    pub fn measure(&self, tolerance: f32) -> Vec<crate::ContourMeasure> {
        self.flatten(tolerance)
            .iter()
            .filter_map(crate::ContourMeasure::of)
            .collect()
    }

    /// `flatten` approximates curves with polygonal contours.
    ///
    /// `tolerance` is the maximum deviation in path coordinates. Fill
    /// operations implicitly close every contour; stroke operations use
    /// [`Contour::closed`].
    pub fn flatten(&self, tolerance: f32) -> Vec<Contour> {
        let mut out = Flattener::new(tolerance.max(1e-4));
        let mut i = 0usize;
        let mut weight_index = 0usize;
        for verb in &self.verbs {
            match verb {
                Verb::Move => {
                    out.move_to(self.points[i]);
                    i += 1;
                }
                Verb::Line => {
                    out.line_to(self.points[i]);
                    i += 1;
                }
                Verb::Quad => {
                    out.quad_to(self.points[i], self.points[i + 1]);
                    i += 2;
                }
                Verb::Conic => {
                    out.conic_to(
                        self.points[i],
                        self.points[i + 1],
                        self.weights[weight_index],
                    );
                    i += 2;
                    weight_index += 1;
                }
                Verb::Cubic => {
                    out.cubic_to(self.points[i], self.points[i + 1], self.points[i + 2]);
                    i += 3;
                }
                Verb::Close => out.close(),
            }
        }
        out.finish()
    }
}

#[derive(Default)]
struct TightBounds(Option<(f32, f32, f32, f32)>);

impl TightBounds {
    fn include(&mut self, point: Point) {
        self.0 = Some(match self.0 {
            Some((left, top, right, bottom)) => (
                left.min(point.x),
                top.min(point.y),
                right.max(point.x),
                bottom.max(point.y),
            ),
            None => (point.x, point.y, point.x, point.y),
        });
    }

    fn rect(self) -> Rect {
        self.0
            .map_or_else(Rect::default, |(left, top, right, bottom)| {
                Rect::from_ltrb(left, top, right, bottom)
            })
    }
}

fn include_quadratic_extrema(bounds: &mut TightBounds, start: Point, control: Point, end: Point) {
    bounds.include(start);
    bounds.include(end);
    for (start_axis, control_axis, end_axis) in
        [(start.x, control.x, end.x), (start.y, control.y, end.y)]
    {
        let denominator = start_axis as f64 - 2.0 * control_axis as f64 + end_axis as f64;
        if denominator == 0.0 {
            continue;
        }
        let parameter = ((start_axis as f64 - control_axis as f64) / denominator) as f32;
        if parameter > 0.0 && parameter < 1.0 {
            bounds.include(eval_quad(start, control, end, parameter));
        }
    }
}

fn include_cubic_extrema(
    bounds: &mut TightBounds,
    start: Point,
    first: Point,
    second: Point,
    end: Point,
) {
    bounds.include(start);
    bounds.include(end);
    for (start_axis, first_axis, second_axis, end_axis) in [
        (start.x, first.x, second.x, end.x),
        (start.y, first.y, second.y, end.y),
    ] {
        for parameter in cubic_extrema(start_axis, first_axis, second_axis, end_axis)
            .into_iter()
            .flatten()
        {
            if parameter > 0.0 && parameter < 1.0 {
                bounds.include(eval_cubic(start, first, second, end, parameter));
            }
        }
    }
}

fn include_conic_extrema(
    bounds: &mut TightBounds,
    start: Point,
    control: Point,
    end: Point,
    weight: f32,
) {
    bounds.include(start);
    bounds.include(end);
    for (start_axis, control_axis, end_axis) in
        [(start.x, control.x, end.x), (start.y, control.y, end.y)]
    {
        for parameter in conic_derivative_roots(start_axis, control_axis, end_axis, weight) {
            let p = eval_conic(start, control, end, weight, parameter);
            // A positive-weight conic never leaves its control hull; a root
            // that lands a float ulp inside an endpoint must not let eval
            // noise widen the bounds past it.
            let clamp = |v: f32, a: f32, b: f32, c: f32| v.clamp(a.min(b).min(c), a.max(b).max(c));
            bounds.include(Point::new(
                clamp(p.x, start.x, control.x, end.x),
                clamp(p.y, start.y, control.y, end.y),
            ));
        }
    }
}

/// Parameters in (0, 1) where one coordinate of the conic turns around.
///
/// With numerator `N(t) = At² + Bt + C` and denominator `D(t) = at² − at + 1`
/// (`a = 2 − 2w`), the extremum condition `N′D − ND′ = 0` collapses — the
/// cubic terms cancel — to the quadratic `−a(A+B)t² + 2(A − aC)t + (B + aC)`.
pub(crate) fn conic_derivative_roots(
    start: f32,
    control: f32,
    end: f32,
    weight: f32,
) -> impl Iterator<Item = f32> {
    // In point DIFFERENCES, Skia's `conic_find_extrema` form: substituting
    // p10 = control − start and p20 = end − start collapses the quadratic
    // above (divided by 2) to the coefficients below. The absolute-coordinate
    // form subtracts near-equal products and loses every significant digit
    // for curves far from the origin; the difference form does not, and f64
    // covers what remains.
    let w = weight as f64;
    let p10 = control as f64 - start as f64;
    let p20 = end as f64 - start as f64;
    let quadratic = (w - 1.0) * p20;
    let linear = p20 - 2.0 * w * p10;
    let constant = w * p10;

    let mut roots = [None, None];
    if quadratic == 0.0 {
        roots[0] = unit_root(-constant, linear);
    } else {
        let discriminant = linear * linear - 4.0 * quadratic * constant;
        if discriminant >= 0.0 && discriminant.is_finite() {
            // The same stable pairing as `cubic_extrema`: never subtract two
            // near-equal numbers.
            let root = discriminant.sqrt();
            let q = -0.5 * (linear + root.copysign(linear));
            roots[0] = unit_root(q, quadratic);
            roots[1] = unit_root(constant, q).filter(|value| roots[0] != Some(*value));
        }
    }
    roots.into_iter().flatten()
}

/// The conic (rational quadratic) point at `t`.
pub(crate) fn eval_conic(start: Point, control: Point, end: Point, weight: f32, t: f32) -> Point {
    let u = 1.0 - t;
    let b0 = u * u;
    let b1 = 2.0 * weight * u * t;
    let b2 = t * t;
    let d = b0 + b1 + b2;
    Point::new(
        (b0 * start.x + b1 * control.x + b2 * end.x) / d,
        (b0 * start.y + b1 * control.y + b2 * end.y) / d,
    )
}

fn cubic_extrema(start: f32, first: f32, second: f32, end: f32) -> [Option<f32>; 2] {
    let start = start as f64;
    let first = first as f64;
    let second = second as f64;
    let end = end as f64;
    let quadratic = -start + 3.0 * first - 3.0 * second + end;
    let linear = 2.0 * (start - 2.0 * first + second);
    let constant = first - start;
    if quadratic == 0.0 {
        return [unit_root(-constant, linear), None];
    }
    let discriminant = linear * linear - 4.0 * quadratic * constant;
    if discriminant < 0.0 || !discriminant.is_finite() {
        return [None, None];
    }

    // Numerical Recipes / Skia: Q/A and C/Q avoid the cancellation in the
    // ordinary (-B ± sqrt(D)) / 2A formula when one root is much smaller.
    let root = discriminant.sqrt();
    let q = -0.5 * (linear + root.copysign(linear));
    let first_root = unit_root(q, quadratic);
    let second_root = unit_root(constant, q).filter(|value| Some(*value) != first_root);
    [first_root, second_root]
}

fn unit_root(numerator: f64, denominator: f64) -> Option<f32> {
    if denominator == 0.0 {
        return None;
    }
    let value = numerator / denominator;
    (value.is_finite() && value > 0.0 && value < 1.0).then_some(value as f32)
}

/// `PathBuilder` records commands used to create an immutable [`Path`].
#[derive(Clone, Default)]
pub struct PathBuilder {
    verbs: Vec<Verb>,
    points: Vec<Point>,
    weights: Vec<f32>,
    bounds: Option<Rect>,
    /// Where a segment recorded after a `close` resumes.
    ///
    /// It OUTLIVES the close — that is the whole point. Without it
    /// `M10,10 L30,10 Z L30,30` loses its diagonal, because the line would
    /// start at its own destination. Skia does the same in `ensureMove`
    /// (`moveTo(fPts[fLastMoveIndex])` when the last verb was a close), and
    /// Impeller inherits it by building on `SkPathBuilder`.
    ///
    /// NOT always the contour's origin, which is why it is not called that.
    /// For `close` it is. For `rect` and `roundRect` WHATWG names the point
    /// separately — "create a new subpath with the point (x, y)" — and for a
    /// rounded rectangle `(x, y)` is a bounding-box corner the outline never
    /// touches, since the walk begins at the top-left tangent. The two
    /// coincide only at radius zero.
    resume_point: Option<Point>,
    contour_open: bool,
}

impl PathBuilder {
    /// `new` creates an empty path builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// `move_to` starts a new contour at `p`.
    pub fn move_to(&mut self, p: impl Into<Point>) -> &mut Self {
        let p = p.into();
        self.verbs.push(Verb::Move);
        self.push_point(p);
        self.resume_point = Some(p);
        self.contour_open = true;
        self
    }

    /// `line_to` adds a straight segment to `p`.
    pub fn line_to(&mut self, p: impl Into<Point>) -> &mut Self {
        let p = p.into();
        self.ensure_contour(p);
        self.verbs.push(Verb::Line);
        self.push_point(p);
        self
    }

    /// `quad_to` adds a quadratic Bézier through control point `c` to `p`.
    pub fn quad_to(&mut self, c: impl Into<Point>, p: impl Into<Point>) -> &mut Self {
        let (c, p) = (c.into(), p.into());
        self.ensure_contour(c);
        self.verbs.push(Verb::Quad);
        self.push_point(c);
        self.push_point(p);
        self
    }

    /// `conic_to` adds a rational quadratic (a conic) through control point
    /// `c` to `p`.
    ///
    /// A weight of 1 is an ordinary quadratic; `cos(θ/2)` traces a circular
    /// arc of sweep `θ` exactly, which is what the arc and rounded-rect
    /// helpers rely on. Stored weights are restricted to positive finite
    /// values so every curve stays inside its control hull — the invariant
    /// the record-time bounds rely on. Everything else lowers: a nonpositive
    /// weight draws a line, a non-finite weight the control polygon (the
    /// curve's limit as the weight grows). Skia, by contrast, records
    /// negative weights as-is; nothing in valo's builders or Canvas2D
    /// produces one.
    pub fn conic_to(&mut self, c: impl Into<Point>, p: impl Into<Point>, weight: f32) -> &mut Self {
        let (c, p) = (c.into(), p.into());
        if !weight.is_finite() {
            return self.line_to(c).line_to(p);
        }
        if weight <= 0.0 {
            return self.line_to(p);
        }
        if weight == 1.0 {
            return self.quad_to(c, p);
        }
        self.ensure_contour(c);
        self.verbs.push(Verb::Conic);
        self.push_point(c);
        self.push_point(p);
        self.weights.push(weight);
        self
    }

    /// `cubic_to` adds a cubic Bézier through two control points to `p`.
    pub fn cubic_to(
        &mut self,
        c1: impl Into<Point>,
        c2: impl Into<Point>,
        p: impl Into<Point>,
    ) -> &mut Self {
        let (c1, c2, p) = (c1.into(), c2.into(), p.into());
        self.ensure_contour(c1);
        self.verbs.push(Verb::Cubic);
        self.push_point(c1);
        self.push_point(c2);
        self.push_point(p);
        self
    }

    /// `close` adds a segment back to the current contour's starting point.
    ///
    /// It has no effect when no contour is open.
    pub fn close(&mut self) -> &mut Self {
        if self.contour_open {
            self.verbs.push(Verb::Close);
            self.contour_open = false;
        }
        self
    }

    // ── shape helpers (the common vocabulary) ──────────────────────────────

    /// `rect` adds a closed rectangular contour.
    pub fn rect(&mut self, r: Rect) -> &mut Self {
        self.move_to((r.x, r.y))
            .line_to((r.right(), r.y))
            .line_to((r.right(), r.bottom()))
            .line_to((r.x, r.bottom()))
            .close();
        // WHATWG's separate closing step: "create a new subpath with the
        // point (x, y)". Stated here rather than inherited from the traversal
        // above, so reordering the walk cannot move it.
        self.resume_point = Some(Point::new(r.x, r.y));
        self
    }

    /// `rrect` adds a closed rounded rectangle with one corner radius.
    pub fn rrect(&mut self, r: Rect, radius: f32) -> &mut Self {
        self.rrect_radii(r, [radius; 4])
    }

    /// `rrect_radii` adds a rounded rectangle with circular corner radii.
    ///
    /// `radii` is ordered clockwise from the top-left.
    pub fn rrect_radii(&mut self, r: Rect, radii: [f32; 4]) -> &mut Self {
        self.rrect_radii_elliptical(r, radii.map(|radius| [radius; 2]))
    }

    /// `rrect_radii_elliptical` adds per-corner elliptical radii.
    ///
    /// Each corner is `[x_radius, y_radius]`, starting at the top-left. Radii
    /// are proportionally reduced when adjacent corners would overlap.
    pub fn rrect_radii_elliptical(
        &mut self,
        r: impl Into<Rect>,
        radii: [[f32; 2]; 4],
    ) -> &mut Self {
        self.rrect_radii_elliptical_wound(r, radii, Winding::Clockwise)
    }

    /// `rrect_radii_elliptical_wound` adds a rounded rectangle with explicit winding.
    ///
    /// Opposing contours cancel under [`FillRule::NonZero`], and dashing follows
    /// this traversal order.
    pub fn rrect_radii_elliptical_wound(
        &mut self,
        r: impl Into<Rect>,
        radii: [[f32; 2]; 4],
        winding: Winding,
    ) -> &mut Self {
        let r = r.into();
        let [tl, tr, br, bl] = constrain_radii_elliptical(&r, radii);
        let (l, t, rr, b) = (r.x, r.y, r.right(), r.bottom());
        if [tl, tr, br, bl].iter().all(|[x, y]| *x == 0.0 && *y == 0.0) {
            match winding {
                Winding::Clockwise => self.rect(r),
                Winding::CounterClockwise => self
                    .move_to((l, t))
                    .line_to((l, b))
                    .line_to((rr, b))
                    .line_to((rr, t))
                    .close(),
            };
            self.resume_point = Some(Point::new(l, t));
            return self;
        }
        // Each corner is one conic: a quarter ELLIPSE, exactly — the control
        // point is the box corner and the weight is cos(45°). Impeller's
        // rounded rect uses the identical construction (`round_rect.cc`).
        let w = std::f32::consts::FRAC_1_SQRT_2;
        match winding {
            Winding::Clockwise => self
                .move_to((l + tl[0], t))
                .line_to((rr - tr[0], t))
                .conic_to((rr, t), (rr, t + tr[1]), w)
                .line_to((rr, b - br[1]))
                .conic_to((rr, b), (rr - br[0], b), w)
                .line_to((l + bl[0], b))
                .conic_to((l, b), (l, b - bl[1]), w)
                .line_to((l, t + tl[1]))
                .conic_to((l, t), (l + tl[0], t), w)
                .close(),
            // The same anchors in reverse around the same control points —
            // so the two directions are the identical outline and differ
            // only in traversal.
            Winding::CounterClockwise => self
                .move_to((l + tl[0], t))
                .conic_to((l, t), (l, t + tl[1]), w)
                .line_to((l, b - bl[1]))
                .conic_to((l, b), (l + bl[0], b), w)
                .line_to((rr - br[0], b))
                .conic_to((rr, b), (rr, b - br[1]), w)
                .line_to((rr, t + tr[1]))
                .conic_to((rr, t), (rr - tr[0], t), w)
                .line_to((l + tl[0], t))
                .close(),
        };
        // WHATWG step 14, SEPARATE from the outline that step 12 walks:
        // "create a new subpath with the point (x, y)". For a rounded
        // rectangle that corner is not on the outline at all — the walk
        // begins at the top-left tangent — so this cannot be inherited from
        // the traversal the way `close`'s resumption point is. Blink does the
        // same explicitly, chaining `.MoveTo(x, y)` after its rounded-rect
        // builder (`canvas_path.cc`).
        //
        // Verified against the spec text and current Blink source rather than
        // by probing a browser. This corner of Canvas2D has already produced
        // two places where the prose and every implementation disagree, so
        // that distinction is worth keeping in view.
        self.resume_point = Some(Point::new(l, t));
        self
    }

    /// `rsuperellipse` adds a rounded superellipse with one corner radius.
    ///
    /// The corner profile is the iOS "squircle": circular near the diagonal,
    /// blending into the straight edges along a superellipse instead of
    /// meeting them abruptly the way a circular [`Self::rrect`] corner does.
    pub fn rsuperellipse(&mut self, r: Rect, radius: f32) -> &mut Self {
        self.rsuperellipse_radii(r, [[radius; 2]; 4])
    }

    /// `rsuperellipse_radii` adds a rounded superellipse with per-corner
    /// elliptical radii.
    ///
    /// Each corner is `[x_radius, y_radius]`, clockwise from the top-left.
    /// Radii are proportionally reduced when adjacent corners would overlap.
    pub fn rsuperellipse_radii(&mut self, r: Rect, radii: [[f32; 2]; 4]) -> &mut Self {
        crate::superellipse::RoundSuperellipse::new(r, radii).emit(self);
        self.resume_point = Some(Point::new(r.x, r.y));
        self
    }

    /// `arc` adds a circular arc.
    ///
    /// Angles are radians clockwise from +x in Valo's y-down coordinates.
    /// Sweeps are limited to one full turn.
    pub fn arc(
        &mut self,
        center: impl Into<Point>,
        radius: f32,
        start_angle: f32,
        sweep_angle: f32,
    ) -> &mut Self {
        self.ellipse(center, [radius; 2], 0.0, start_angle, sweep_angle)
    }

    /// `ellipse` adds an elliptical arc.
    ///
    /// `radii` are the x and y half-extents, `x_axis_rotation` turns the
    /// ellipse, and angles are radians clockwise from +x. An active contour is
    /// connected to the arc's first point. Sweeps are limited to one full turn.
    ///
    /// Non-finite input is ignored. Negative radii trigger a debug assertion
    /// and are ignored in release builds.
    pub fn ellipse(
        &mut self,
        center: impl Into<Point>,
        radii: [f32; 2],
        x_axis_rotation: f32,
        start_angle: f32,
        sweep_angle: f32,
    ) -> &mut Self {
        let center = center.into();
        let [radius_x, radius_y] = radii;
        // Every input, not just the radii: a NaN centre flows into NaN points,
        // and `f32::min`/`max` drop those from the bounds accumulator without
        // complaint — an under-reported box silently breaks culling and
        // hit-testing later.
        let finite = center.x.is_finite()
            && center.y.is_finite()
            && radius_x.is_finite()
            && radius_y.is_finite()
            && x_axis_rotation.is_finite()
            && start_angle.is_finite()
            && sweep_angle.is_finite();
        debug_assert!(
            radius_x >= 0.0 && radius_y >= 0.0,
            "negative radii draw nothing; Canvas2D throws here"
        );
        if !finite || radius_x < 0.0 || radius_y < 0.0 {
            return self;
        }

        // Canvas2D stops at one full turn, and Skia routes full sweeps to an
        // oval. Without this, `sweep = 1e20` passes the finite check above and
        // asks for ~1e19 cubic pieces — an allocation the process does not
        // survive, reachable by any embedder forwarding user input.
        let full_turn = std::f32::consts::TAU;
        let sweep_angle = sweep_angle.clamp(-full_turn, full_turn);

        let unit_circle_to_ellipse = unit_circle_map(center, radii, x_axis_rotation);
        let first = unit_circle_to_ellipse.map_point(unit_circle_point(start_angle));
        // Canvas2D runs a straight line in to the arc's start when a contour
        // is live. A CLOSED contour still counts as live for this: it resumes
        // at its origin and then runs the line, so an arc after `closePath`
        // stays connected to the seam. Only a path with no contour at all
        // starts at the arc.
        if self.contour_open || self.resume_point.is_some() {
            self.ensure_contour(first);
            self.line_to(first);
        } else {
            self.move_to(first);
        }
        if sweep_angle != 0.0 {
            self.push_arc_conics(&unit_circle_to_ellipse, start_angle, sweep_angle);
        }
        // A whole turn ends where it began: close it, so the stroker joins the
        // seam instead of capping it (Skia's full sweeps produce a closed oval).
        if sweep_angle.abs() >= full_turn {
            self.close();
        }
        self
    }

    /// `arc_to` rounds the corner between the current point, `corner`, and `next`.
    ///
    /// Zero or negative radius, coincident points, and straight-through corners
    /// fall back to a line ending at `corner`.
    pub fn arc_to(
        &mut self,
        corner: impl Into<Point>,
        next: impl Into<Point>,
        radius: f32,
    ) -> &mut Self {
        let (corner, next) = (corner.into(), next.into());
        self.ensure_contour(corner);
        let start = *self.points.last().expect("ensure_contour opened a contour");

        // Skia's construction, in f64: the tangent length follows from the
        // half-angle at the corner, and the centre sits one radius along the
        // inward normal of the incoming edge.
        let incoming = normalize(
            corner.x as f64 - start.x as f64,
            corner.y as f64 - start.y as f64,
        );
        let outgoing = normalize(
            next.x as f64 - corner.x as f64,
            next.y as f64 - corner.y as f64,
        );
        let (Some(incoming), Some(outgoing)) = (incoming, outgoing) else {
            return self.line_to(corner);
        };
        let cosine = incoming.0 * outgoing.0 + incoming.1 * outgoing.1;
        let sine = incoming.0 * outgoing.1 - incoming.1 * outgoing.0;
        if radius <= 0.0 || !radius.is_finite() || sine.abs() < 1.0 / (1 << 12) as f64 {
            return self.line_to(corner);
        }

        let tangent_length = (radius as f64 * (1.0 - cosine) / sine).abs();
        let entry = Point::new(
            corner.x - (tangent_length * incoming.0) as f32,
            corner.y - (tangent_length * incoming.1) as f32,
        );
        // The turn's sign puts the centre on the side the arc bends toward.
        let turn = sine.signum() as f32;
        let center = Point::new(
            entry.x + radius * turn * -(incoming.1 as f32),
            entry.y + radius * turn * incoming.0 as f32,
        );
        let exit = Point::new(
            corner.x + (tangent_length * outgoing.0) as f32,
            corner.y + (tangent_length * outgoing.1) as f32,
        );

        let start_angle = (entry.y - center.y).atan2(entry.x - center.x);
        let end_angle = (exit.y - center.y).atan2(exit.x - center.x);
        let sweep = shortest_sweep(start_angle, end_angle, turn);

        self.line_to(entry);
        let map = unit_circle_map(center, [radius; 2], 0.0);
        self.push_arc_conics(&map, start_angle, sweep);
        self
    }

    /// `circle` adds a closed circular contour.
    ///
    /// Four conic quarters trace the circle exactly; the control points are
    /// the bounding box's corners.
    pub fn circle(&mut self, center: impl Into<Point>, radius: f32) -> &mut Self {
        let c = center.into();
        let r = radius;
        let w = std::f32::consts::FRAC_1_SQRT_2;
        self.move_to((c.x + r, c.y))
            .conic_to((c.x + r, c.y + r), (c.x, c.y + r), w)
            .conic_to((c.x - r, c.y + r), (c.x - r, c.y), w)
            .conic_to((c.x - r, c.y - r), (c.x, c.y - r), w)
            .conic_to((c.x + r, c.y - r), (c.x + r, c.y), w)
            .close()
    }

    /// `append` adds a transformed copy of another path.
    ///
    /// The appended path's final contour becomes the current contour for
    /// subsequent commands.
    pub fn append(&mut self, path: &Path, transform: &Matrix) -> &mut Self {
        if path.verbs.is_empty() {
            // Appending nothing must change nothing — in particular it must
            // not close this builder's open contour.
            return self;
        }
        let mut point = path.points.iter();
        let mut weight = path.weights.iter();
        let mut cursor = Point::ZERO;
        let mut contour_start = Point::ZERO;
        for verb in &path.verbs {
            let count = match verb {
                Verb::Move | Verb::Line => 1,
                Verb::Quad | Verb::Conic => 2,
                Verb::Cubic => 3,
                Verb::Close => 0,
            };
            self.verbs.push(*verb);
            for _ in 0..count {
                let Some(&p) = point.next() else {
                    return self;
                };
                cursor = transform.map_point(p);
                self.push_point(cursor);
            }
            if matches!(verb, Verb::Conic) {
                // Weights survive affine transforms unchanged. (A projective
                // transform would need to reweigh them — but it would also
                // need more than control-point mapping for quads and cubics,
                // so every verb shares that limitation.)
                let Some(&w) = weight.next() else {
                    return self;
                };
                self.weights.push(w);
            }
            match verb {
                Verb::Move => contour_start = cursor,
                Verb::Close => cursor = contour_start,
                _ => {}
            }
        }
        // WHATWG's `Path2D.addPath` ends by "creating a new subpath with the
        // last point in path", which is what lets a following `line_to`
        // continue from where the source stopped. A source ending mid-contour
        // already leaves this builder there; one ending in `close` does not,
        // and without the reopen the next segment would start at its own
        // endpoint and the connecting edge would vanish.
        //
        // The reopen leaves a lone-point contour when nothing follows. That
        // costs no pixels here: it sits exactly on the closed contour's seam,
        // which the fill and the stroke's join already cover.
        if matches!(path.verbs.last(), Some(Verb::Close)) {
            self.move_to(cursor);
        } else {
            // The appended contour is this builder's contour now, origin and
            // all — leaving the receiver's own origin in place would send a
            // later `close` + segment back to the wrong seam.
            self.resume_point = Some(contour_start);
            self.contour_open = true;
        }
        self
    }

    /// `build` consumes the builder and returns a shared immutable path.
    pub fn build(self) -> Arc<Path> {
        Arc::new(Path {
            verbs: self.verbs,
            points: self.points,
            weights: self.weights,
            bounds: self.bounds.unwrap_or_default(),
        })
    }

    // ── internals ──────────────────────────────────────────────────────────

    /// `push_arc_conics` traces an arc with conic pieces of at most 90°.
    ///
    /// Each piece is exact: a conic of weight `cos(θ/2)` whose control point
    /// sits where the endpoint tangents meet IS the circular arc of sweep
    /// `θ`. The current point must already be at the arc's start.
    fn push_arc_conics(&mut self, map: &Matrix, start_angle: f32, sweep_angle: f32) {
        let piece_count = (sweep_angle.abs() / std::f32::consts::FRAC_PI_2)
            .ceil()
            .max(1.0);
        let step = sweep_angle / piece_count;
        let weight = (step / 2.0).cos();

        let mut angle = start_angle;
        for _ in 0..piece_count as u32 {
            let mid = unit_circle_point(angle + step / 2.0);
            let control = Point::new(mid.x / weight, mid.y / weight);
            let to = unit_circle_point(angle + step);
            self.conic_to(map.map_point(control), map.map_point(to), weight);
            angle += step;
        }
    }

    /// `ensure_contour` guarantees an open contour before recording a segment.
    ///
    /// After a `close` the path resumes at the CLOSED contour's origin — the
    /// spec's "new subpath with the last point", and Skia's `ensureMove`.
    /// Resuming at the incoming point instead silently deletes the segment
    /// from the seam, which is the whole bug this exists to prevent.
    ///
    /// A path that never had a contour starts at the incoming point: Skia's
    /// implicit `moveTo(0, 0)` there is a footgun valo does not copy.
    fn ensure_contour(&mut self, p: Point) {
        if self.contour_open {
            return;
        }
        self.move_to(self.resume_point.unwrap_or(p));
    }

    fn push_point(&mut self, p: Point) {
        self.points.push(p);
        // Plain min/max accumulation — a zero-size seed rect is a valid
        // bound, wherever it sits (a rect-union "empty = identity" rule
        // would drop a first point at the origin).
        self.bounds = Some(match self.bounds {
            Some(b) => Rect::from_ltrb(
                b.x.min(p.x),
                b.y.min(p.y),
                b.right().max(p.x),
                b.bottom().max(p.y),
            ),
            None => Rect::new(p.x, p.y, 0.0, 0.0),
        });
    }
}

/// `unit_circle_point` returns the point at `angle` on the unit circle.
fn unit_circle_point(angle: f32) -> Point {
    let (sine, cosine) = angle.sin_cos();
    Point::new(cosine, sine)
}

/// `unit_circle_map` creates the transform from a unit circle to an ellipse.
fn unit_circle_map(center: Point, radii: [f32; 2], rotation: f32) -> Matrix {
    let [radius_x, radius_y] = radii;
    let (sine, cosine) = rotation.sin_cos();
    Matrix::from_affine(
        radius_x * cosine,
        radius_x * sine,
        -radius_y * sine,
        radius_y * cosine,
        center.x,
        center.y,
    )
}

/// `shortest_sweep` returns the sub-turn sweep matching `direction`.
fn shortest_sweep(start: f32, end: f32, direction: f32) -> f32 {
    let mut sweep = end - start;
    let turn = std::f32::consts::TAU;
    while sweep > 0.0 && direction < 0.0 {
        sweep -= turn;
    }
    while sweep < 0.0 && direction > 0.0 {
        sweep += turn;
    }
    sweep
}

/// `normalize` returns a unit vector or `None` when no finite direction exists.
fn normalize(x: f64, y: f64) -> Option<(f64, f64)> {
    let length = (x * x + y * y).sqrt();
    (length.is_finite() && length > 0.0).then(|| (x / length, y / length))
}

/// `constrain_radii` proportionally reduces circular radii to fit a rectangle.
///
/// Radii are ordered clockwise from the top-left. Negative values become zero.
pub fn constrain_radii(r: &Rect, radii: [f32; 4]) -> [f32; 4] {
    constrain_radii_elliptical(r, radii.map(|v| [v; 2])).map(|[x, _]| x)
}

/// `constrain_radii_elliptical` proportionally reduces elliptical radii to fit.
///
/// Corners are ordered clockwise from the top-left as `[x_radius, y_radius]`.
/// Negative components become zero.
pub fn constrain_radii_elliptical(r: &Rect, radii: [[f32; 2]; 4]) -> [[f32; 2]; 4] {
    let [tl, tr, br, bl] = radii.map(|[x, y]| [x.max(0.0), y.max(0.0)]);
    let fit = |side: f32, a: f32, b: f32| if a + b <= side { 1.0 } else { side / (a + b) };
    let f = fit(r.width, tl[0], tr[0])
        .min(fit(r.width, bl[0], br[0]))
        .min(fit(r.height, tl[1], bl[1]))
        .min(fit(r.height, tr[1], br[1]));
    [tl, tr, br, bl].map(|[x, y]| [x * f, y * f])
}

/// `Flattener` approximates curves with uniformly parameterized line segments.
struct Flattener {
    tolerance: f32,
    contours: Vec<Contour>,
    current: Vec<Point>,
    /// Whether a segment verb has landed since the last `move_to`.
    has_segments: bool,
}

impl Flattener {
    fn new(tolerance: f32) -> Self {
        Self {
            tolerance,
            contours: Vec::new(),
            current: Vec::new(),
            has_segments: false,
        }
    }

    fn move_to(&mut self, p: Point) {
        self.flush(false);
        self.current.push(p);
        self.has_segments = false;
    }

    fn line_to(&mut self, p: Point) {
        self.current.push(p);
        self.has_segments = true;
    }

    fn quad_to(&mut self, c: Point, p: Point) {
        let Some(&start) = self.current.last() else {
            return;
        };
        self.has_segments = true;
        let dev = second_difference(start, c, p);
        let n = segment_count((dev / (8.0 * self.tolerance)).sqrt());
        for i in 1..=n {
            let t = i as f32 / n as f32;
            self.current.push(eval_quad(start, c, p, t));
        }
    }

    fn conic_to(&mut self, c: Point, p: Point, w: f32) {
        let Some(&start) = self.current.last() else {
            return;
        };
        self.has_segments = true;
        let n = segment_count(conic_segment_estimate(start, c, p, w, self.tolerance));
        for i in 1..=n {
            let t = i as f32 / n as f32;
            self.current.push(eval_conic(start, c, p, w, t));
        }
    }

    fn cubic_to(&mut self, c1: Point, c2: Point, p: Point) {
        let Some(&start) = self.current.last() else {
            return;
        };
        self.has_segments = true;
        let dev = second_difference(start, c1, c2).max(second_difference(c1, c2, p));
        let n = segment_count((3.0 * dev / (4.0 * self.tolerance)).sqrt());
        for i in 1..=n {
            let t = i as f32 / n as f32;
            self.current.push(eval_cubic(start, c1, c2, p, t));
        }
    }

    fn close(&mut self) {
        // Emit the closing edge back to the contour's start (unless the
        // last curve already landed there exactly).
        if let (Some(&first), Some(&last)) = (self.current.first(), self.current.last()) {
            if self.current.len() >= 2 && (first.x, first.y) != (last.x, last.y) {
                self.current.push(first);
            }
        }
        // Closing is itself a drawing command: `move_to(p)` then `close()` is
        // an explicit zero-length SUBPATH, which strokes exactly like an
        // explicit zero-length segment. Impeller says so directly — its
        // `Close()` calls `SegmentEncountered()` — and Skia turns move+close
        // into a zero-length line for every non-butt cap.
        if !self.current.is_empty() {
            self.has_segments = true;
        }
        self.flush(true);
    }

    fn finish(mut self) -> Vec<Contour> {
        self.flush(false);
        self.contours
    }

    /// `flush` keeps every contour, even lone points.
    ///
    /// Fills fan nothing from <3 points,
    /// but the stroker draws 2-point lines and caps EXPLICIT zero-length
    /// subpaths. A move-only contour is kept too, carrying `has_segments:
    /// false` so the stroker can tell the two apart.
    fn flush(&mut self, closed: bool) {
        if !self.current.is_empty() {
            self.contours.push(Contour {
                points: std::mem::take(&mut self.current),
                closed,
                has_segments: self.has_segments,
            });
        }
        self.has_segments = false;
    }
}

/// Wang's formula extended to conics — the same estimate Impeller and Skia's
/// GPU tessellators use ("Wang's formula for rational quadratics", Skia
/// `wangs_formula::conic`), with `precision = 1 / tolerance`.
fn conic_segment_estimate(start: Point, control: Point, end: Point, w: f32, tolerance: f32) -> f32 {
    let precision = 1.0 / tolerance;
    // Recentring on the bounding box improves translation invariance.
    let cx = 0.5 * (start.x.min(control.x).min(end.x) + start.x.max(control.x).max(end.x));
    let cy = 0.5 * (start.y.min(control.y).min(end.y) + start.y.max(control.y).max(end.y));
    let (p0x, p0y) = (start.x - cx, start.y - cy);
    let (p1x, p1y) = (control.x - cx, control.y - cy);
    let (p2x, p2y) = (end.x - cx, end.y - cy);
    let max_len_sq = (p0x * p0x + p0y * p0y)
        .max(p1x * p1x + p1y * p1y)
        .max(p2x * p2x + p2y * p2y);
    let (dpx, dpy) = (p0x - 2.0 * w * p1x + p2x, p0y - 2.0 * w * p1y + p2y);
    let dw = (2.0 - 2.0 * w).abs();
    let rp_minus_1 = (max_len_sq.sqrt() * precision - 1.0).max(0.0);
    let numer = (dpx * dpx + dpy * dpy).sqrt() * precision + rp_minus_1 * dw;
    let denom = 4.0 * w.min(1.0);
    (numer / denom).sqrt()
}

fn second_difference(a: Point, b: Point, c: Point) -> f32 {
    let dx = a.x - 2.0 * b.x + c.x;
    let dy = a.y - 2.0 * b.y + c.y;
    (dx * dx + dy * dy).sqrt()
}

fn segment_count(estimate: f32) -> u32 {
    (estimate.ceil() as u32).clamp(1, 64)
}

fn eval_quad(p0: Point, c: Point, p1: Point, t: f32) -> Point {
    let u = 1.0 - t;
    Point::new(
        u * u * p0.x + 2.0 * u * t * c.x + t * t * p1.x,
        u * u * p0.y + 2.0 * u * t * c.y + t * t * p1.y,
    )
}

fn eval_cubic(p0: Point, c1: Point, c2: Point, p1: Point, t: f32) -> Point {
    let u = 1.0 - t;
    let (uu, tt) = (u * u, t * t);
    Point::new(
        u * uu * p0.x + 3.0 * uu * t * c1.x + 3.0 * u * tt * c2.x + t * tt * p1.x,
        u * uu * p0.y + 3.0 * uu * t * c1.y + 3.0 * u * tt * c2.y + t * tt * p1.y,
    )
}

/// `local_tolerance` returns local curve tolerance for quarter-pixel device error.
pub fn local_tolerance(transform: &Matrix) -> f32 {
    0.25 / transform.max_scale().max(1e-3)
}

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

    /// The observable meaning of winding: under the NON-ZERO rule two
    /// overlapping contours cancel when their directions oppose and reinforce
    /// when they agree. This is the property Chrome exhibits for a
    /// `roundRect` given with a negative width, and the reason normalizing
    /// the box without carrying the direction is wrong — the second rectangle
    /// would add instead of subtract.
    #[test]
    fn opposed_windings_cancel_under_the_non_zero_rule() {
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        let radii = [[12.0, 12.0]; 4];
        let inside = Point::new(50.0, 50.0);

        let mut opposed = PathBuilder::new();
        opposed.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
        opposed.rrect_radii_elliptical_wound(rect, radii, Winding::CounterClockwise);
        assert!(
            !opposed.build().contains(inside, FillRule::NonZero),
            "opposed windings must cancel"
        );

        let mut agreeing = PathBuilder::new();
        agreeing.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
        agreeing.rrect_radii_elliptical_wound(rect, radii, Winding::Clockwise);
        assert!(
            agreeing.build().contains(inside, FillRule::NonZero),
            "agreeing windings must reinforce"
        );
    }

    /// Direction must not move the OUTLINE, only the traversal. A reversed
    /// corner whose control points were not swapped with it would bulge the
    /// wrong way and show up here.
    #[test]
    fn winding_reverses_the_walk_without_moving_the_outline() {
        let rect = Rect::new(10.0, 20.0, 80.0, 60.0);
        let radii = [[8.0, 14.0], [4.0, 4.0], [20.0, 6.0], [0.0, 0.0]];
        let wound = |winding| {
            let mut path = PathBuilder::new();
            path.rrect_radii_elliptical_wound(rect, radii, winding);
            path.build()
        };
        let clockwise = wound(Winding::Clockwise);
        let counter = wound(Winding::CounterClockwise);
        assert_eq!(clockwise.tight_bounds(), counter.tight_bounds());
        // Sample across the shape, including just inside and outside each
        // rounded corner.
        for point in [
            Point::new(50.0, 50.0),
            Point::new(14.0, 30.0),
            Point::new(86.0, 24.0),
            Point::new(74.0, 76.0),
            Point::new(12.0, 78.0),
            Point::new(5.0, 15.0),
            Point::new(95.0, 85.0),
        ] {
            assert_eq!(
                clockwise.contains(point, FillRule::NonZero),
                counter.contains(point, FillRule::NonZero),
                "the two directions disagree about {point:?}"
            );
        }
    }

    /// WHATWG leaves a one-point subpath at the closed contour's origin, so a
    /// segment recorded after `closePath` starts from the SEAM.
    ///
    /// The bug this pins is invisible to any test that paints immediately
    /// after the close — the closed shape looks right and the missing
    /// diagonal is a segment that was never recorded at all. That is exactly
    /// why the conformance fuzzer never caught it.
    #[test]
    fn a_segment_after_close_resumes_at_the_contour_origin() {
        let mut path = PathBuilder::new();
        path.move_to((10.0, 10.0));
        path.line_to((30.0, 10.0));
        path.close();
        path.line_to((30.0, 30.0));
        let path = path.build();

        // The diagonal runs (10,10) → (30,30); its midpoint is (20,20).
        let contours = path.flatten(0.05);
        let resumed = contours.last().expect("the path continues after the close");
        assert_eq!(
            resumed.points.first().copied(),
            Some(Point::new(10.0, 10.0)),
            "the segment after close must start at the contour origin, not its own end"
        );
        assert!(crate::stroke_contains(
            &contours,
            &crate::Stroke::new(6.0),
            0.05,
            Point::new(20.0, 20.0)
        ));
    }

    /// `rect` and `roundRect` resume at `(x, y)` — the bounding box's corner,
    /// which is a SEPARATE spec step from the outline they walk.
    ///
    /// For a rounded rectangle that corner is not on the outline at all: the
    /// walk starts at the top-left tangent, `(18, 10)` here. The two points
    /// coincide only at radius zero, which is exactly why a rect-only test
    /// would miss this.
    #[test]
    fn a_segment_after_a_shape_helper_resumes_at_the_box_corner() {
        let box_corner = Point::new(10.0, 10.0);
        for corner in [0.0f32, 8.0] {
            let mut path = PathBuilder::new();
            if corner == 0.0 {
                path.rect(Rect::new(10.0, 10.0, 40.0, 40.0));
            } else {
                path.rrect_radii_elliptical(Rect::new(10.0, 10.0, 40.0, 40.0), [[corner; 2]; 4]);
            }
            path.line_to((90.0, 90.0));

            let contours = path.build().flatten(0.05);
            let resumed = contours.last().expect("the path continues after the shape");
            assert_eq!(
                resumed.points.first().copied(),
                Some(box_corner),
                "corner radius {corner}: the trailing segment starts at (x, y)"
            );
        }

        // The same thing said in ink, which is how the divergence was found:
        // the diagonal from (10,10) is stroked and the one from the tangent
        // (18,10) is not.
        let mut path = PathBuilder::new();
        path.rrect_radii_elliptical(Rect::new(10.0, 10.0, 40.0, 40.0), [[8.0; 2]; 4]);
        path.line_to((90.0, 90.0));
        let contours = path.build().flatten(0.05);
        let stroke = crate::Stroke::new(4.0);
        assert!(
            crate::stroke_contains(&contours, &stroke, 0.05, Point::new(50.0, 50.0)),
            "the diagonal from (10,10) must be stroked"
        );
        assert!(
            !crate::stroke_contains(&contours, &stroke, 0.05, Point::new(54.0, 50.0)),
            "the diagonal from the tangent (18,10) must not be"
        );
    }

    /// `closePath` keeps the contour-origin rule — the shape helpers' `(x, y)`
    /// override must not have leaked into it.
    #[test]
    fn close_still_resumes_at_the_contour_origin() {
        let mut path = PathBuilder::new();
        path.move_to((10.0, 10.0));
        path.line_to((30.0, 10.0));
        path.line_to((30.0, 30.0));
        path.close();
        path.line_to((90.0, 90.0));
        let contours = path.build().flatten(0.05);
        assert_eq!(
            contours
                .last()
                .and_then(|contour| contour.points.first())
                .copied(),
            Some(Point::new(10.0, 10.0)),
            "close resumes where the contour began, not at any box corner"
        );
    }

    /// A path that never opened a contour still starts where it is told —
    /// Skia's implicit `moveTo(0, 0)` is deliberately not copied.
    #[test]
    fn a_first_segment_with_no_contour_starts_at_its_own_point() {
        let mut path = PathBuilder::new();
        path.line_to((30.0, 30.0));
        assert_eq!(
            path.build().bounds(),
            Rect::from_ltrb(30.0, 30.0, 30.0, 30.0)
        );
    }

    #[test]
    fn append_carries_verbs_through_the_transform() {
        let mut source = PathBuilder::new();
        source.rect(Rect::new(0.0, 0.0, 10.0, 10.0));
        let source = source.build();

        let mut target = PathBuilder::new();
        target.rect(Rect::new(0.0, 0.0, 4.0, 4.0));
        target.append(&source, &Matrix::translation(100.0, 50.0));
        let target = target.build();

        assert_eq!(target.bounds(), Rect::from_ltrb(0.0, 0.0, 110.0, 60.0));
        assert!(target.contains(Point::new(105.0, 55.0), FillRule::NonZero));
        assert!(!target.contains(Point::new(5.0, 5.0), FillRule::NonZero));
    }

    /// The reopen after a closed source is what keeps the next segment
    /// connected. Without it the `line_to` below starts a fresh contour at
    /// its own endpoint and the edge from the seam disappears.
    #[test]
    fn appending_a_closed_contour_reopens_at_its_seam() {
        let mut source = PathBuilder::new();
        source.move_to((10.0, 10.0));
        source.line_to((20.0, 10.0));
        source.close();
        let source = source.build();

        let mut target = PathBuilder::new();
        target.append(&source, &Matrix::IDENTITY);
        target.line_to((10.0, 40.0));
        let built = target.build();

        // The seam is (10, 10); the new edge runs from there to (10, 40).
        assert_eq!(built.bounds(), Rect::from_ltrb(10.0, 10.0, 20.0, 40.0));
        assert!(built.contains(Point::new(10.0, 25.0), FillRule::NonZero));
    }

    /// An appended OPEN contour becomes the receiver's contour, origin
    /// included. Keeping the receiver's own origin would send a later
    /// `close` + segment back to the wrong seam.
    #[test]
    fn appending_an_open_contour_hands_over_its_origin() {
        let mut source = PathBuilder::new();
        source.move_to((50.0, 50.0));
        source.line_to((60.0, 50.0));
        let source = source.build();

        let mut target = PathBuilder::new();
        target.move_to((0.0, 0.0));
        target.line_to((10.0, 0.0));
        target.append(&source, &Matrix::IDENTITY);
        target.close();
        target.line_to((90.0, 90.0));

        let contours = target.build().flatten(0.05);
        let resumed = contours.last().expect("the path continues after the close");
        assert_eq!(
            resumed.points.first().copied(),
            Some(Point::new(50.0, 50.0)),
            "the resumed segment must start at the APPENDED contour's origin"
        );
    }

    #[test]
    fn appending_nothing_leaves_an_open_contour_open() {
        let empty = PathBuilder::new().build();
        let mut target = PathBuilder::new();
        target.move_to((0.0, 0.0));
        target.line_to((10.0, 0.0));
        target.append(&empty, &Matrix::IDENTITY);
        target.line_to((10.0, 10.0));
        assert_eq!(
            target.build().bounds(),
            Rect::from_ltrb(0.0, 0.0, 10.0, 10.0)
        );
    }

    #[test]
    fn appending_an_open_contour_leaves_it_open() {
        let mut source = PathBuilder::new();
        source.move_to((0.0, 0.0));
        source.line_to((10.0, 0.0));
        let source = source.build();

        let mut target = PathBuilder::new();
        target.append(&source, &Matrix::IDENTITY);
        // Without the contour-open handoff this would restart at the origin
        // and the bounds would be unchanged by the new point.
        target.line_to((10.0, 10.0));
        assert_eq!(
            target.build().bounds(),
            Rect::from_ltrb(0.0, 0.0, 10.0, 10.0)
        );
    }

    #[test]
    fn tight_bounds_use_curve_extrema_not_control_points() {
        let mut path = PathBuilder::new();
        path.move_to((0.0, 0.0));
        path.quad_to((100.0, 100.0), (200.0, 0.0));
        let path = path.build();
        assert_eq!(path.bounds(), Rect::new(0.0, 0.0, 200.0, 100.0));
        assert_eq!(path.tight_bounds(), Rect::new(0.0, 0.0, 200.0, 50.0));
    }

    #[test]
    fn tight_bounds_keep_extrema_below_f32_epsilon() {
        let mut path = PathBuilder::new();
        path.move_to((0.0, 0.0));
        path.quad_to((0.0, 1.0e-8), (0.0, 0.0));
        let bounds = path.build().tight_bounds();
        assert!((bounds.height - 5.0e-9).abs() < 1.0e-12);
    }

    #[test]
    fn cubic_extrema_preserve_the_small_root() {
        let roots = cubic_extrema(0.0, 1.0e-8, -0.5, -0.5);
        assert!(roots
            .into_iter()
            .flatten()
            .any(|root| (root - 1.0e-8).abs() < 1.0e-10));
    }

    #[test]
    fn radii_constrain_together() {
        let r = Rect::new(0.0, 0.0, 100.0, 40.0);
        // tl+bl = 80 > height 40 → everything scales by 0.5.
        let out = constrain_radii(&r, [40.0, 10.0, 10.0, 40.0]);
        assert_eq!(out, [20.0, 5.0, 5.0, 20.0]);
        // Already fitting radii pass through untouched.
        assert_eq!(constrain_radii(&r, [8.0, 8.0, 8.0, 8.0]), [8.0; 4]);
    }

    #[test]
    fn per_corner_rrect_stays_in_rect() {
        let r = Rect::new(10.0, 10.0, 100.0, 60.0);
        let mut b = PathBuilder::new();
        b.rrect_radii(r, [30.0, 0.0, 16.0, 8.0]);
        assert_eq!(b.build().bounds(), r);
    }

    #[test]
    fn bounds_cover_control_points() {
        let mut b = PathBuilder::new();
        b.move_to((10.0, 10.0)).quad_to((50.0, -20.0), (90.0, 10.0));
        let p = b.build();
        assert_eq!(p.bounds(), Rect::from_ltrb(10.0, -20.0, 90.0, 10.0));
    }

    #[test]
    fn circle_flattens_to_radius() {
        let mut b = PathBuilder::new();
        b.circle((0.0, 0.0), 100.0);
        let contours = b.build().flatten(0.1);
        assert_eq!(contours.len(), 1);
        assert!(contours[0].closed, "circle closes its contour");
        for p in &contours[0].points {
            let r = (p.x * p.x + p.y * p.y).sqrt();
            assert!((r - 100.0).abs() < 0.5, "point off circle: r={r}");
        }
    }

    #[test]
    fn finer_tolerance_means_more_segments() {
        let path = {
            let mut b = PathBuilder::new();
            b.circle((0.0, 0.0), 100.0);
            b.build()
        };
        let coarse = path.flatten(2.0)[0].points.len();
        let fine = path.flatten(0.05)[0].points.len();
        assert!(fine > coarse, "fine {fine} vs coarse {coarse}");
    }

    #[test]
    fn small_contours_survive_for_the_stroker() {
        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0)).line_to((10.0, 0.0)); // a stroked line segment
        b.move_to((50.0, 50.0)); // a lone point (caps render it)
        let contours = b.build().flatten(0.1);
        assert_eq!(contours.len(), 2);
        assert_eq!(contours[0].points.len(), 2);
        assert!(!contours[0].closed);
        assert_eq!(contours[1].points.len(), 1);
    }

    #[test]
    fn close_emits_the_closing_edge_and_marks_the_contour() {
        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0))
            .line_to((10.0, 0.0))
            .line_to((10.0, 10.0))
            .close();
        let contours = b.build().flatten(0.1);
        assert!(contours[0].closed);
        assert_eq!(contours[0].points.len(), 4, "closing edge in the polyline");
        assert_eq!(contours[0].points[3], Point::new(0.0, 0.0));
    }

    #[test]
    fn bounds_keep_a_first_point_at_the_origin() {
        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0)).line_to((50.0, 80.0));
        assert_eq!(b.build().bounds(), Rect::from_ltrb(0.0, 0.0, 50.0, 80.0));

        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0)).line_to((100.0, 0.0)); // zero-height line
        assert_eq!(b.build().bounds(), Rect::from_ltrb(0.0, 0.0, 100.0, 0.0));
    }

    #[test]
    fn curve_without_move_starts_contour() {
        let mut b = PathBuilder::new();
        b.line_to((10.0, 0.0))
            .line_to((10.0, 10.0))
            .line_to((0.0, 10.0));
        let contours = b.build().flatten(0.1);
        assert_eq!(contours.len(), 1);
        assert_eq!(contours[0].points.len(), 4);
    }

    /// The circular constructor must be EXACTLY the rx == ry case of the
    /// elliptical one — same constraint order, same cubics — so every
    /// existing rrect golden also pins the elliptical code path.
    #[test]
    fn circular_rrect_is_the_equal_axes_elliptical_case() {
        let r = Rect::new(10.0, 20.0, 120.0, 80.0);
        let radii = [24.0, 8.0, 30.0, 0.0];
        let mut circular = PathBuilder::new();
        circular.rrect_radii(r, radii);
        let mut elliptical = PathBuilder::new();
        elliptical.rrect_radii_elliptical(r, radii.map(|v| [v; 2]));
        assert_eq!(
            circular.build().flatten(0.1)[0].points,
            elliptical.build().flatten(0.1)[0].points,
        );
    }

    #[test]
    fn elliptical_radii_constrain_per_axis() {
        // A 100×40 rect with tall corner ellipses: the HEIGHT edges force
        // the scale (20 + 30 > 40 → f = 0.8); x components ride along.
        let r = Rect::new(0.0, 0.0, 100.0, 40.0);
        let out = constrain_radii_elliptical(
            &r,
            [[10.0, 20.0], [10.0, 20.0], [10.0, 30.0], [10.0, 30.0]],
        );
        assert_eq!(out[0], [8.0, 16.0]);
        assert_eq!(out[2], [8.0, 24.0]);
        // Negative radii clamp to zero before constraining.
        let out = constrain_radii_elliptical(&r, [[-5.0, 10.0], [0.0; 2], [0.0; 2], [0.0; 2]]);
        assert_eq!(out[0], [0.0, 10.0]);
    }

    #[test]
    fn elliptical_corner_lands_on_axis_extremes() {
        // One elliptical corner (rx 40, ry 10): the arc must start 40 in
        // from the corner on x and end 10 down on y.
        let r = Rect::new(0.0, 0.0, 200.0, 100.0);
        let mut b = PathBuilder::new();
        b.rrect_radii_elliptical(r, [[0.0; 2], [40.0, 10.0], [0.0; 2], [0.0; 2]]);
        let points = &b.build().flatten(0.05)[0].points;
        // The top edge stops at x = 160 (200 - rx) and the right edge
        // starts at y = 10 (ry) — both points must be on the outline.
        assert!(points
            .iter()
            .any(|p| (p.x - 160.0).abs() < 0.5 && p.y.abs() < 0.5));
        assert!(points
            .iter()
            .any(|p| (p.x - 200.0).abs() < 0.5 && (p.y - 10.0).abs() < 0.5));
    }

    // ── arcs ────────────────────────────────────────────────────────────────

    /// Every point of a swept circle sits on the circle, to well under a
    /// tenth of a pixel — the cubic approximation's whole claim.
    #[test]
    fn swept_arc_stays_on_its_circle() {
        let (center, radius) = (Point::new(50.0, 60.0), 40.0);
        let mut b = PathBuilder::new();
        b.arc(center, radius, 0.0, std::f32::consts::TAU);
        for point in &b.build().flatten(0.01)[0].points {
            let offset = (point.x - center.x).hypot(point.y - center.y);
            assert!(
                (offset - radius).abs() < 0.05,
                "point {point:?} is {offset} from the centre, not {radius}"
            );
        }
    }

    /// A quarter turn ends exactly where trigonometry says it does.
    #[test]
    fn quarter_arc_ends_where_it_should() {
        let mut b = PathBuilder::new();
        b.arc((0.0, 0.0), 100.0, 0.0, std::f32::consts::FRAC_PI_2);
        let points = &b.build().flatten(0.01)[0].points;
        let (first, last) = (points[0], *points.last().unwrap());
        assert!(
            (first.x - 100.0).abs() < 0.01 && first.y.abs() < 0.01,
            "{first:?}"
        );
        assert!(
            last.x.abs() < 0.05 && (last.y - 100.0).abs() < 0.05,
            "{last:?}"
        );
    }

    /// An ellipse reaches its own half-extents on each axis.
    #[test]
    fn ellipse_reaches_both_radii() {
        let mut b = PathBuilder::new();
        b.ellipse((0.0, 0.0), [80.0, 20.0], 0.0, 0.0, std::f32::consts::TAU);
        let points = &b.build().flatten(0.01)[0].points;
        let widest = points.iter().fold(0.0f32, |m, p| m.max(p.x.abs()));
        let tallest = points.iter().fold(0.0f32, |m, p| m.max(p.y.abs()));
        assert!((widest - 80.0).abs() < 0.1, "widest {widest}");
        assert!((tallest - 20.0).abs() < 0.1, "tallest {tallest}");
    }

    /// The rotation turns the ellipse: a 90° turn swaps which axis is long.
    #[test]
    fn ellipse_rotation_swaps_the_axes() {
        let mut b = PathBuilder::new();
        b.ellipse(
            (0.0, 0.0),
            [80.0, 20.0],
            std::f32::consts::FRAC_PI_2,
            0.0,
            std::f32::consts::TAU,
        );
        let points = &b.build().flatten(0.01)[0].points;
        let widest = points.iter().fold(0.0f32, |m, p| m.max(p.x.abs()));
        let tallest = points.iter().fold(0.0f32, |m, p| m.max(p.y.abs()));
        assert!((widest - 20.0).abs() < 0.1, "widest {widest}");
        assert!((tallest - 80.0).abs() < 0.1, "tallest {tallest}");
    }

    /// A right-angle `arc_to` with radius r touches down r before the corner
    /// and leaves r after it, and every point between is r from the centre
    /// the two tangents share.
    #[test]
    fn arc_to_rounds_a_right_angle() {
        let radius = 20.0f32;
        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0))
            .arc_to((100.0, 0.0), (100.0, 100.0), radius);
        let points = &b.build().flatten(0.01)[0].points;

        let entry = Point::new(100.0 - radius, 0.0);
        let exit = Point::new(100.0, radius);
        assert!(points
            .iter()
            .any(|p| (p.x - entry.x).abs() < 0.1 && (p.y - entry.y).abs() < 0.1));
        assert!(points
            .iter()
            .any(|p| (p.x - exit.x).abs() < 0.1 && (p.y - exit.y).abs() < 0.1));

        let center = Point::new(100.0 - radius, radius);
        for point in points.iter().filter(|p| p.x > entry.x - 0.01) {
            let offset = (point.x - center.x).hypot(point.y - center.y);
            assert!(
                (offset - radius).abs() < 0.1,
                "{point:?} is {offset} from the centre"
            );
        }
    }

    /// Collinear points and a zero radius both degenerate to a plain line,
    /// which is what the Canvas2D algorithm prescribes.
    #[test]
    fn degenerate_arc_to_falls_back_to_a_line() {
        for (corner, next, radius) in [
            ((50.0, 0.0), (100.0, 0.0), 20.0), // straight through
            ((50.0, 0.0), (50.0, 50.0), 0.0),  // no radius
        ] {
            let mut b = PathBuilder::new();
            b.move_to((0.0, 0.0)).arc_to(corner, next, radius);
            let points = &b.build().flatten(0.01)[0].points;
            assert_eq!(points.len(), 2, "expected a bare line, got {points:?}");
            assert!((points[1].x - corner.0).abs() < 0.01 && (points[1].y - corner.1).abs() < 0.01);
        }
    }

    // ── containment ─────────────────────────────────────────────────────────

    #[test]
    fn rect_contains_what_it_covers() {
        let mut b = PathBuilder::new();
        b.rect(Rect::new(10.0, 10.0, 80.0, 60.0));
        let path = b.build();
        assert!(path.contains(Point::new(50.0, 40.0), FillRule::NonZero));
        assert!(!path.contains(Point::new(5.0, 40.0), FillRule::NonZero));
        assert!(!path.contains(Point::new(50.0, 80.0), FillRule::NonZero));
        // Exactly on the outline counts as inside — on EVERY edge. The far
        // two are the ones a half-open bounds check silently loses.
        for on_outline in [
            Point::new(10.0, 40.0), // left
            Point::new(50.0, 10.0), // top
            Point::new(90.0, 40.0), // right
            Point::new(50.0, 70.0), // bottom
            Point::new(90.0, 70.0), // the far corner
        ] {
            assert!(
                path.contains(on_outline, FillRule::NonZero),
                "{on_outline:?} is on the outline and must count as inside"
            );
        }
    }

    /// Canvas2D caps an arc at one turn. Without the clamp a huge sweep asks
    /// for billions of cubic pieces, which is an allocation the process does
    /// not survive — so this test is a crash guard, not a geometry check.
    #[test]
    fn an_enormous_sweep_stays_one_turn() {
        let mut b = PathBuilder::new();
        b.arc((0.0, 0.0), 50.0, 0.0, 1e20);
        let path = b.build();
        let contours = path.flatten(0.1);
        assert_eq!(contours.len(), 1);
        // One turn at this tolerance is a few hundred points, never millions.
        assert!(
            contours[0].points.len() < 1_000,
            "a clamped turn should stay small, got {}",
            contours[0].points.len()
        );
        assert!(contours[0].closed, "a full turn closes its contour");
    }

    #[test]
    fn a_negative_sweep_turns_the_other_way() {
        let quarter = std::f32::consts::FRAC_PI_2;
        let mut clockwise = PathBuilder::new();
        clockwise.arc((0.0, 0.0), 50.0, 0.0, quarter);
        let mut anticlockwise = PathBuilder::new();
        anticlockwise.arc((0.0, 0.0), 50.0, 0.0, -quarter);

        // y-down: a positive sweep from +x heads towards +y, a negative one
        // towards -y. Both start at the same point.
        let forward = clockwise.build().bounds();
        let backward = anticlockwise.build().bounds();
        assert!(forward.bottom() > 40.0, "positive sweep reaches +y");
        assert!(backward.y < -40.0, "negative sweep reaches -y");
    }

    /// Containment runs on the CURVE, so it agrees with the true circle at
    /// every angle — a flattened test would drift inside the chords.
    #[test]
    fn circle_containment_is_exact_all_the_way_round() {
        let (center, radius) = (Point::new(0.0, 0.0), 100.0f32);
        let mut b = PathBuilder::new();
        b.circle(center, radius);
        let path = b.build();
        for step in 0..64 {
            let angle = step as f32 / 64.0 * std::f32::consts::TAU;
            let (sine, cosine) = angle.sin_cos();
            let inside = Point::new(cosine * radius * 0.99, sine * radius * 0.99);
            let outside = Point::new(cosine * radius * 1.01, sine * radius * 1.01);
            assert!(
                path.contains(inside, FillRule::NonZero),
                "{inside:?} should be in"
            );
            assert!(
                !path.contains(outside, FillRule::NonZero),
                "{outside:?} should be out"
            );
        }
    }

    /// The two fill rules disagree exactly where they should: a hole wound
    /// the same way as its parent is solid under non-zero, empty under
    /// even-odd.
    #[test]
    fn fill_rules_disagree_about_a_same_wound_hole() {
        let mut b = PathBuilder::new();
        b.rect(Rect::new(0.0, 0.0, 100.0, 100.0));
        b.rect(Rect::new(25.0, 25.0, 50.0, 50.0));
        let path = b.build();
        let middle = Point::new(50.0, 50.0);
        assert!(path.contains(middle, FillRule::NonZero));
        assert!(!path.contains(middle, FillRule::EvenOdd));
        // Between the rings both rules agree it is filled.
        let ring = Point::new(10.0, 50.0);
        assert!(path.contains(ring, FillRule::NonZero));
        assert!(path.contains(ring, FillRule::EvenOdd));
    }

    /// An unclosed contour still fills, so it must still contain.
    #[test]
    fn open_contour_closes_implicitly() {
        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0))
            .line_to((100.0, 0.0))
            .line_to((100.0, 100.0));
        let path = b.build();
        assert!(path.contains(Point::new(80.0, 40.0), FillRule::NonZero));
        assert!(!path.contains(Point::new(20.0, 60.0), FillRule::NonZero));
    }

    /// Curved segments contribute their real crossings, not a chord's.
    #[test]
    fn containment_handles_curves_that_double_back() {
        let mut b = PathBuilder::new();
        b.move_to((0.0, 0.0))
            .cubic_to((120.0, 120.0), (-20.0, 120.0), (100.0, 0.0))
            .close();
        let path = b.build();
        assert!(path.contains(Point::new(50.0, 40.0), FillRule::NonZero));
        assert!(!path.contains(Point::new(50.0, -10.0), FillRule::NonZero));
        assert!(!path.contains(Point::new(-30.0, 40.0), FillRule::NonZero));
    }

    // ── conic segments ─────────────────────────────────────────────────────

    /// A conic quarter with weight cos(45°) IS the circle: every flattened
    /// point sits on it exactly, not within the old cubic approximation's
    /// 0.027%-of-radius bulge. Ignoring the weight (treating the segment as
    /// a plain quad) would miss by ~6% of the radius.
    #[test]
    fn circle_flattens_onto_the_exact_circle() {
        let mut b = PathBuilder::new();
        b.circle((10.0, -20.0), 100.0);
        let contours = b.build().flatten(0.1);
        let points: Vec<Point> = contours.iter().flat_map(|c| c.points.clone()).collect();
        assert!(points.len() > 20);
        for p in &points {
            let distance = (p.x - 10.0).hypot(p.y + 20.0);
            assert!(
                (distance - 100.0).abs() < 2e-3,
                "{p:?} is off the circle by {}",
                (distance - 100.0).abs()
            );
        }
    }

    /// `ellipse` runs on conics too: sampled points must satisfy the ellipse
    /// equation, including through a rotation.
    #[test]
    fn ellipse_arc_flattens_onto_the_exact_ellipse() {
        let mut b = PathBuilder::new();
        let rotation = 0.5f32;
        b.ellipse((5.0, 7.0), [80.0, 30.0], rotation, 0.3, 4.0);
        let contours = b.build().flatten(0.05);
        let (sin_r, cos_r) = rotation.sin_cos();
        for p in contours.iter().flat_map(|c| &c.points) {
            let (dx, dy) = (p.x - 5.0, p.y - 7.0);
            // Undo the rotation, then normalize by the radii.
            let (ux, uy) = (dx * cos_r + dy * sin_r, -dx * sin_r + dy * cos_r);
            let value = (ux / 80.0).powi(2) + (uy / 30.0).powi(2);
            assert!((value - 1.0).abs() < 1e-3, "{p:?} deviates: {value}");
        }
    }

    /// The conic's rational midpoint reaches the true circle edge, so the
    /// tight bounds of a circle are its exact box — no cubic overshoot, and
    /// no undershoot from treating control points as reachable.
    #[test]
    fn conic_circle_tight_bounds_are_exact() {
        let mut b = PathBuilder::new();
        b.circle((0.0, 0.0), 50.0);
        let tight = b.build().tight_bounds();
        for (got, want) in [
            (tight.x, -50.0),
            (tight.y, -50.0),
            (tight.right(), 50.0),
            (tight.bottom(), 50.0),
        ] {
            assert!((got - want).abs() < 1e-3, "bound {got} should be {want}");
        }
        // The arc helper's extremum lies between piece endpoints: an arc
        // through the top must still reach exactly -50 in y.
        let mut arc = PathBuilder::new();
        arc.arc((0.0, 0.0), 50.0, -3.0, 2.5);
        let tight = arc.build().tight_bounds();
        assert!((tight.y + 50.0).abs() < 1e-3, "arc top: {}", tight.y);
    }

    /// Analytic containment solves the conic itself: probes 0.05 units off a
    /// 100-unit circle land on the right side at every angle.
    #[test]
    fn conic_containment_is_exact_on_the_curve() {
        let mut b = PathBuilder::new();
        b.circle((0.0, 0.0), 100.0);
        let path = b.build();
        for i in 0..64 {
            let angle = i as f32 / 64.0 * std::f32::consts::TAU;
            let (s, c) = angle.sin_cos();
            let inside = Point::new(c * 99.95, s * 99.95);
            let outside = Point::new(c * 100.05, s * 100.05);
            assert!(
                path.contains(inside, FillRule::NonZero),
                "{inside:?} at angle {i} should be inside"
            );
            assert!(
                !path.contains(outside, FillRule::NonZero),
                "{outside:?} at angle {i} should be outside"
            );
        }
    }

    /// Conic circles wind like any other contour: an opposing inner circle
    /// carves a hole under the non-zero rule.
    #[test]
    fn conic_windings_cancel_under_the_non_zero_rule() {
        let mut b = PathBuilder::new();
        b.circle((0.0, 0.0), 100.0);
        // The same circle traversed the other way: swap the conic sweep
        // direction by walking the quarters in reverse.
        let w = std::f32::consts::FRAC_1_SQRT_2;
        b.move_to((60.0, 0.0))
            .conic_to((60.0, -60.0), (0.0, -60.0), w)
            .conic_to((-60.0, -60.0), (-60.0, 0.0), w)
            .conic_to((-60.0, 60.0), (0.0, 60.0), w)
            .conic_to((60.0, 60.0), (60.0, 0.0), w)
            .close();
        let path = b.build();
        assert!(!path.contains(Point::new(0.0, 0.0), FillRule::NonZero));
        assert!(path.contains(Point::new(80.0, 0.0), FillRule::NonZero));
    }

    /// `append` carries conic weights through its transform: a rotated
    /// circle is still a circle.
    #[test]
    fn append_preserves_conic_weights() {
        let mut source = PathBuilder::new();
        source.circle((0.0, 0.0), 40.0);
        let source = source.build();
        let mut b = PathBuilder::new();
        b.append(&source, &Matrix::rotation(0.7));
        for p in b.build().flatten(0.05).iter().flat_map(|c| &c.points) {
            let distance = p.x.hypot(p.y);
            assert!((distance - 40.0).abs() < 1e-3, "{p:?} off by {distance}");
        }
    }

    /// Degenerate weights lower instead of recording: nonpositive to a line,
    /// exactly 1 to a quad, non-finite to the control polygon.
    #[test]
    fn degenerate_conic_weights_lower_to_simpler_verbs() {
        let mut zero = PathBuilder::new();
        zero.move_to((0.0, 0.0))
            .conic_to((50.0, 50.0), (100.0, 0.0), 0.0);
        let contour = &zero.build().flatten(0.1)[0];
        assert_eq!(contour.points.len(), 2, "weight 0 must be a straight line");

        let mut quad = PathBuilder::new();
        quad.move_to((0.0, 0.0))
            .conic_to((50.0, 50.0), (100.0, 0.0), 1.0);
        let mut plain = PathBuilder::new();
        plain
            .move_to((0.0, 0.0))
            .quad_to((50.0, 50.0), (100.0, 0.0));
        assert_eq!(
            quad.build().flatten(0.1),
            plain.build().flatten(0.1),
            "weight 1 must match the plain quadratic"
        );

        let mut infinite = PathBuilder::new();
        infinite
            .move_to((0.0, 0.0))
            .conic_to((50.0, 50.0), (100.0, 0.0), f32::INFINITY);
        let contour = &infinite.build().flatten(0.1)[0];
        assert_eq!(
            contour.points,
            vec![
                Point::new(0.0, 0.0),
                Point::new(50.0, 50.0),
                Point::new(100.0, 0.0)
            ],
            "an unbounded weight collapses onto the control polygon"
        );
    }

    /// Extremum-finding must survive coordinates far from the origin: the
    /// quadratic's coefficients are built from point DIFFERENCES (Skia's
    /// `conic_find_extrema` form) in f64, because the absolute-coordinate
    /// form cancels catastrophically in f32. Audit repro: this curve near
    /// y=442028 has a real interior maximum that the naive form misses.
    #[test]
    fn conic_extrema_survive_large_coordinates() {
        let p0 = Point::new(0.0, 442_027.38);
        let c = Point::new(50.0, 442_028.47);
        let p2 = Point::new(100.0, 442_027.03);
        let w = 20.189_045;
        let mut b = PathBuilder::new();
        b.move_to(p0).conic_to(c, p2, w).close();
        let path = b.build();
        let bottom = path.tight_bounds().bottom();
        assert!(
            (bottom - 442_028.4).abs() < 0.05,
            "tight bottom {bottom} should reach the true maximum ~442028.41"
        );
        assert!(
            path.contains(Point::new(49.660_536, 442_028.0), FillRule::NonZero),
            "an interior point above the chord must be inside"
        );
    }

    /// Flattening error stays within the requested tolerance for a strongly
    /// hyperbolic weight (the superellipse emits weights past 8): the chord
    /// midpoints of consecutive flattened points may deviate from the curve
    /// by at most the tolerance.
    #[test]
    fn conic_flattening_respects_tolerance_for_large_weights() {
        let (p0, c, p2, w) = (
            Point::new(0.0, 100.0),
            Point::new(35.0, 100.0),
            Point::new(40.0, 90.0),
            8.3f32,
        );
        let tolerance = 0.05f32;
        let mut b = PathBuilder::new();
        b.move_to(p0).conic_to(c, p2, w);
        let contour = &b.build().flatten(tolerance)[0];
        // Dense reference polyline on the true curve.
        let reference: Vec<Point> = (0..=4096)
            .map(|i| eval_conic(p0, c, p2, w, i as f32 / 4096.0))
            .collect();
        for pair in contour.points.windows(2) {
            let mid = Point::new((pair[0].x + pair[1].x) / 2.0, (pair[0].y + pair[1].y) / 2.0);
            let distance = reference
                .iter()
                .map(|r| (r.x - mid.x).hypot(r.y - mid.y))
                .fold(f32::MAX, f32::min);
            assert!(
                distance <= tolerance * 1.1,
                "chord midpoint {mid:?} is {distance} off the curve"
            );
        }
    }
}

#[cfg(test)]
mod element_tests {
    use super::*;

    #[test]
    fn elements_rebuild_an_equal_path() {
        let mut builder = PathBuilder::new();
        builder
            .move_to((0.0, 0.0))
            .line_to((10.0, 0.0))
            .quad_to((10.0, 5.0), (10.0, 10.0))
            .conic_to((5.0, 10.0), (0.0, 10.0), 0.7)
            .cubic_to((0.0, 7.0), (0.0, 3.0), (0.0, 0.0))
            .close();
        let path = builder.build();
        let mut rebuilt = PathBuilder::new();
        for element in path.elements() {
            match element {
                PathElement::MoveTo(p) => rebuilt.move_to(p),
                PathElement::LineTo(p) => rebuilt.line_to(p),
                PathElement::QuadTo(c, p) => rebuilt.quad_to(c, p),
                PathElement::ConicTo(c, p, w) => rebuilt.conic_to(c, p, w),
                PathElement::CubicTo(a, b, p) => rebuilt.cubic_to(a, b, p),
                PathElement::Close => rebuilt.close(),
            };
        }
        let rebuilt = rebuilt.build();
        assert_eq!(path.elements().count(), 6);
        assert_eq!(rebuilt.bounds(), path.bounds());
        assert!(path.elements().eq(rebuilt.elements()));
    }
}