cadmpeg-ir 0.6.2

CAD data model, validation, diffing, and codec API for cadmpeg.
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
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
// SPDX-License-Identifier: Apache-2.0
//! Parameter-space curves, NURBS payloads, and source parameterization.

use super::nurbs::{
    admit_finite_weight, admit_weight, KnotVector, NurbsCurve, NurbsError, PoleValue,
};
use super::{FitTolerance, MAX_GEOMETRY_NESTING};
use crate::ids::PcurveId;
use crate::math::{Point2, Point3};
use crate::scalar::{FiniteReal, NonZeroReal, PositiveReal};
use crate::topology::ParameterInterval;
use crate::transform::Transform2;
use crate::units::{FinitePoint2, FiniteVector, NonzeroPoint2};
use cadmpeg_core::decode::{DecodeContext, ResourceLimit};
use cadmpeg_core::CodecError;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

mod construction;
pub mod evaluator;
mod scaling_admitted;

fn finite_axis_is_nonzero(axis: FinitePoint2) -> bool {
    let axis = axis.get();
    axis.u.hypot(axis.v) > 0.0
}

/// One rational pole in parameter space: its position and its weight.
// A source states a raw position; a `PcurveNurbs` holds the admitted row,
// whose position is a `FinitePoint2`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct WeightedPole2<P = Point2> {
    /// Pole position in parameter space.
    pub point: P,
    /// Rational weight at this pole.
    pub weight: NonZeroReal,
}

/// The poles of a parameter-space NURBS curve.
// A source states raw positions; a `PcurveNurbs` holds the admitted poles,
// whose positions are `FinitePoint2` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "form", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum PcurveNurbsPoles<P = Point2> {
    /// A polynomial pcurve: its poles carry no weight.
    Polynomial {
        /// Poles in parameter order.
        points: Vec<P>,
    },
    /// A rational pcurve: every pole carries its weight.
    Rational {
        /// Pole rows in parameter order.
        points: Vec<WeightedPole2<P>>,
    },
}

impl PcurveNurbsPoles {
    /// Edit every pole position, keeping the prior positions on a refusal.
    ///
    /// The closure states its own refusal, which discards the whole edit.
    pub fn edit_points(
        &mut self,
        edit: impl FnMut(&mut Point2) -> Result<(), NurbsError>,
    ) -> Result<(), NurbsError> {
        let mut candidate = self.clone();
        candidate.apply_points(edit)?;
        *self = candidate;
        Ok(())
    }

    /// Edit every pole position in place, keeping every accepted edit.
    ///
    /// A refusal leaves the lane partly edited, so the caller owns the copy
    /// that states the prior positions.
    fn apply_points(
        &mut self,
        mut edit: impl FnMut(&mut Point2) -> Result<(), NurbsError>,
    ) -> Result<(), NurbsError> {
        match self {
            Self::Polynomial { points } => {
                for point in points.iter_mut() {
                    edit(point)?;
                }
            }
            Self::Rational { points } => {
                for pole in points.iter_mut() {
                    edit(&mut pole.point)?;
                }
            }
        }
        Ok(())
    }
}

impl PcurveNurbsPoles<FinitePoint2> {
    /// The poles with raw positions, for a reader that edits or writes them.
    #[must_use]
    pub fn to_raw(&self) -> PcurveNurbsPoles {
        let Ok(raw) = self
            .clone()
            .try_map_points(|point| Ok::<_, std::convert::Infallible>(point.get()));
        raw
    }

    /// Raw pole positions in parameter order, for a reader that computes with
    /// or writes them.
    #[must_use]
    pub fn raw_points(&self) -> Vec<Point2> {
        self.points().into_iter().map(FinitePoint2::get).collect()
    }
}

impl<P> PcurveNurbsPoles<P> {
    /// Pair a source's pole lane with its weight lane. A store admits the
    /// positions it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, naming both counts,
    /// and a weight that is zero or non-finite, naming its index.
    pub fn from_lanes(points: Vec<P>, weights: Option<Vec<f64>>) -> Result<Self, NurbsError> {
        construction::pair_pcurve_lanes(points, weights, |index, weight| {
            admit_weight("pcurve poles", index, weight)
        })
    }

    /// Pair parameter poles with finite weights, checking lane length and nonzero weights.
    pub fn from_finite_lanes(
        points: Vec<P>,
        weights: Option<Vec<FiniteReal>>,
    ) -> Result<Self, NurbsError> {
        construction::pair_pcurve_lanes(points, weights, |index, weight| {
            admit_finite_weight("pcurve poles", index, weight)
        })
    }

    /// Pair a pole lane with an admitted weight lane. The weight type states
    /// the weight contract; a store admits the positions it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, naming both
    /// counts.
    pub fn from_checked_lanes(
        points: Vec<P>,
        weights: Option<Vec<NonZeroReal>>,
    ) -> Result<Self, NurbsError> {
        construction::pair_pcurve_lanes(points, weights, |_, weight| Ok(weight))
    }

    /// Count poles.
    #[must_use]
    pub fn count(&self) -> usize {
        match self {
            Self::Polynomial { points } => points.len(),
            Self::Rational { points } => points.len(),
        }
    }

    /// Rational weights in pole order, absent on a polynomial pcurve.
    #[must_use]
    pub fn weights(&self) -> Option<Vec<f64>> {
        match self {
            Self::Polynomial { .. } => None,
            Self::Rational { points } => {
                Some(points.iter().map(|pole| pole.weight.get()).collect())
            }
        }
    }

    /// Reverse the pole order.
    pub fn reverse(&mut self) {
        match self {
            Self::Polynomial { points } => points.reverse(),
            Self::Rational { points } => points.reverse(),
        }
    }

    /// Map every pole position in parameter order, keeping the weights.
    fn try_map_points<Q, E>(
        self,
        mut point: impl FnMut(P) -> Result<Q, E>,
    ) -> Result<PcurveNurbsPoles<Q>, E> {
        Ok(match self {
            Self::Polynomial { points } => PcurveNurbsPoles::Polynomial {
                points: points.into_iter().map(point).collect::<Result<_, E>>()?,
            },
            Self::Rational { points } => PcurveNurbsPoles::Rational {
                points: points
                    .into_iter()
                    .map(|pole| {
                        Ok(WeightedPole2 {
                            point: point(pole.point)?,
                            weight: pole.weight,
                        })
                    })
                    .collect::<Result<_, E>>()?,
            },
        })
    }
}

impl<P: Copy> PcurveNurbsPoles<P> {
    /// One admitted pole in parameter order.
    #[must_use]
    pub fn point_at(&self, index: usize) -> Option<P> {
        match self {
            Self::Polynomial { points } => points.get(index).copied(),
            Self::Rational { points } => points.get(index).map(|pole| pole.point),
        }
    }

    /// One rational weight, absent for a polynomial pcurve or invalid index.
    #[must_use]
    pub fn weight_at(&self, index: usize) -> Option<f64> {
        match self {
            Self::Polynomial { .. } => None,
            Self::Rational { points } => points.get(index).map(|pole| pole.weight.get()),
        }
    }

    /// Pole positions in parameter order.
    #[must_use]
    pub fn points(&self) -> Vec<P> {
        match self {
            Self::Polynomial { points } => points.clone(),
            Self::Rational { points } => points.iter().map(|pole| pole.point).collect(),
        }
    }
}

impl PoleValue<FinitePoint2> for Point2 {
    fn admit(self) -> Option<FinitePoint2> {
        FinitePoint2::new(self)
    }
}

impl PoleValue<FinitePoint2> for FinitePoint2 {
    fn admit(self) -> Option<FinitePoint2> {
        Some(self)
    }
    fn admit_pcurve_poles<E>(
        poles: PcurveNurbsPoles<Self>,
        _convert: impl FnOnce(PcurveNurbsPoles<Self>) -> Result<PcurveNurbsPoles<FinitePoint2>, E>,
    ) -> Result<PcurveNurbsPoles<FinitePoint2>, E> {
        Ok(poles)
    }
}

impl PoleValue<FiniteReal> for f64 {
    fn admit(self) -> Option<FiniteReal> {
        FiniteReal::new(self)
    }
}

impl PoleValue<FiniteReal> for FiniteReal {
    fn admit(self) -> Option<FiniteReal> {
        Some(self)
    }
}

/// Parameter-space line with a finite origin and nonzero direction.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "LinePcurveWire")]
pub struct LinePcurve {
    origin: FinitePoint2,
    direction: NonzeroPoint2,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct LinePcurveWire {
    /// Parameter-space line origin.
    origin: Point2,
    /// Parameter-space line direction.
    direction: Point2,
}

impl LinePcurve {
    /// Unit-u line through the parameter-space origin.
    pub const U_AXIS: Self = Self {
        origin: FinitePoint2::ZERO,
        direction: NonzeroPoint2::U_AXIS,
    };

    /// Build a line from admitted parts. The argument types state the whole
    /// invariant, so nothing is checked again.
    #[must_use]
    pub const fn new(origin: FinitePoint2, direction: NonzeroPoint2) -> Self {
        Self { origin, direction }
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(origin: Point2, direction: Point2) -> Result<Self, &'static str> {
        let origin = FinitePoint2::new(origin).ok_or("LinePcurve.origin must be finite")?;
        let direction = NonzeroPoint2::new(direction)
            .ok_or("LinePcurve.direction must be finite with squared norm greater than epsilon")?;
        Ok(Self { origin, direction })
    }

    /// Borrow the admitted origin. A caller that passes it on keeps the
    /// finiteness guarantee and performs no new admission.
    #[must_use]
    pub const fn origin(&self) -> &FinitePoint2 {
        &self.origin
    }

    /// Borrow the admitted direction. A caller that passes it on keeps the
    /// finite nonzero guarantee and performs no new admission.
    #[must_use]
    pub const fn direction(&self) -> &NonzeroPoint2 {
        &self.direction
    }
}

impl TryFrom<LinePcurveWire> for LinePcurve {
    type Error = &'static str;
    fn try_from(wire: LinePcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.origin, wire.direction)
    }
}

/// Polar harmonic curve with finite coefficients and nonzero radial variation.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "PolarHarmonicPcurveWire")]
pub struct PolarHarmonicPcurve {
    radial_center: FinitePoint2,
    radial_cos: FinitePoint2,
    radial_sin: FinitePoint2,
    axial_origin: FiniteReal,
    axial_cos: FiniteReal,
    axial_sin: FiniteReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PolarHarmonicPcurveWire {
    /// Constant radial coefficient.
    radial_center: Point2,
    /// Cosine radial coefficient.
    radial_cos: Point2,
    /// Sine radial coefficient.
    radial_sin: Point2,
    /// Constant axial coefficient.
    axial_origin: f64,
    /// Cosine axial coefficient.
    axial_cos: f64,
    /// Sine axial coefficient.
    axial_sin: f64,
}

impl PolarHarmonicPcurve {
    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        radial_center: Point2,
        radial_cos: Point2,
        radial_sin: Point2,
        axial_origin: f64,
        axial_cos: f64,
        axial_sin: f64,
    ) -> Result<Self, &'static str> {
        if !(radial_cos.u.hypot(radial_cos.v) > 0.0 || radial_sin.u.hypot(radial_sin.v) > 0.0) {
            return Err("PolarHarmonicPcurve.radial_cos/radial_sin must not both be zero");
        }
        let radial_center = FinitePoint2::new(radial_center)
            .ok_or("PolarHarmonicPcurve.radial_center must be finite")?;
        let radial_cos =
            FinitePoint2::new(radial_cos).ok_or("PolarHarmonicPcurve.radial_cos must be finite")?;
        let radial_sin =
            FinitePoint2::new(radial_sin).ok_or("PolarHarmonicPcurve.radial_sin must be finite")?;
        let axial_origin = FiniteReal::new(axial_origin)
            .ok_or("PolarHarmonicPcurve.axial_origin must be finite")?;
        let axial_cos =
            FiniteReal::new(axial_cos).ok_or("PolarHarmonicPcurve.axial_cos must be finite")?;
        let axial_sin =
            FiniteReal::new(axial_sin).ok_or("PolarHarmonicPcurve.axial_sin must be finite")?;
        Ok(Self {
            radial_center,
            radial_cos,
            radial_sin,
            axial_origin,
            axial_cos,
            axial_sin,
        })
    }

    /// Return the radial center.
    #[must_use]
    pub const fn radial_center(&self) -> &FinitePoint2 {
        &self.radial_center
    }

    /// Return the radial cos.
    #[must_use]
    pub const fn radial_cos(&self) -> &FinitePoint2 {
        &self.radial_cos
    }

    /// Return the radial sin.
    #[must_use]
    pub const fn radial_sin(&self) -> &FinitePoint2 {
        &self.radial_sin
    }

    /// Return the axial origin.
    #[must_use]
    pub const fn axial_origin(&self) -> FiniteReal {
        self.axial_origin
    }

    /// Return the axial cos.
    #[must_use]
    pub const fn axial_cos(&self) -> FiniteReal {
        self.axial_cos
    }

    /// Return the axial sin.
    #[must_use]
    pub const fn axial_sin(&self) -> FiniteReal {
        self.axial_sin
    }
}

impl TryFrom<PolarHarmonicPcurveWire> for PolarHarmonicPcurve {
    type Error = &'static str;
    fn try_from(wire: PolarHarmonicPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.radial_center,
            wire.radial_cos,
            wire.radial_sin,
            wire.axial_origin,
            wire.axial_cos,
            wire.axial_sin,
        )
    }
}

/// Spherical great-circle chart with finite coefficients and nonzero azimuth rate.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SphericalGreatCirclePcurveWire")]
pub struct SphericalGreatCirclePcurve {
    azimuth_origin: FiniteReal,
    azimuth_rate: FiniteReal,
    plane_phase: FiniteReal,
    plane_slope: FiniteReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SphericalGreatCirclePcurveWire {
    /// Azimuth at the parameter origin.
    azimuth_origin: f64,
    /// Azimuth change for one unit of parameter.
    azimuth_rate: f64,
    /// Phase of the great-circle plane.
    plane_phase: f64,
    /// Slope of the great-circle plane.
    plane_slope: f64,
}

impl SphericalGreatCirclePcurve {
    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        azimuth_origin: f64,
        azimuth_rate: f64,
        plane_phase: f64,
        plane_slope: f64,
    ) -> Result<Self, &'static str> {
        if azimuth_rate == 0.0 {
            return Err("SphericalGreatCirclePcurve.azimuth_rate must be nonzero");
        }
        let azimuth_origin = FiniteReal::new(azimuth_origin)
            .ok_or("SphericalGreatCirclePcurve.azimuth_origin must be finite")?;
        let azimuth_rate = FiniteReal::new(azimuth_rate)
            .ok_or("SphericalGreatCirclePcurve.azimuth_rate must be finite")?;
        let plane_phase = FiniteReal::new(plane_phase)
            .ok_or("SphericalGreatCirclePcurve.plane_phase must be finite")?;
        let plane_slope = FiniteReal::new(plane_slope)
            .ok_or("SphericalGreatCirclePcurve.plane_slope must be finite")?;
        Ok(Self {
            azimuth_origin,
            azimuth_rate,
            plane_phase,
            plane_slope,
        })
    }

    /// Return the azimuth origin.
    #[must_use]
    pub const fn azimuth_origin(&self) -> FiniteReal {
        self.azimuth_origin
    }

    /// Return the azimuth rate.
    #[must_use]
    pub const fn azimuth_rate(&self) -> FiniteReal {
        self.azimuth_rate
    }

    /// Return the plane phase.
    #[must_use]
    pub const fn plane_phase(&self) -> FiniteReal {
        self.plane_phase
    }

    /// Return the plane slope.
    #[must_use]
    pub const fn plane_slope(&self) -> FiniteReal {
        self.plane_slope
    }

    /// The same great circle traversed as `reflection - t`. The azimuth
    /// origin moves to `azimuth_origin + azimuth_rate * reflection` and the
    /// rate changes sign. The negated rate stays finite and nonzero and the
    /// plane is kept, so only the moved origin is checked. The result is
    /// absent when the moved origin is not finite.
    #[must_use]
    pub fn reflected(&self, reflection: f64) -> Option<Self> {
        let azimuth_origin =
            FiniteReal::new(self.azimuth_origin.get() + self.azimuth_rate.get() * reflection)?;
        Some(Self {
            azimuth_origin,
            azimuth_rate: self.azimuth_rate.negated(),
            plane_phase: self.plane_phase,
            plane_slope: self.plane_slope,
        })
    }
}

impl TryFrom<SphericalGreatCirclePcurveWire> for SphericalGreatCirclePcurve {
    type Error = &'static str;
    fn try_from(wire: SphericalGreatCirclePcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.azimuth_origin,
            wire.azimuth_rate,
            wire.plane_phase,
            wire.plane_slope,
        )
    }
}

/// Parameter-space circle with a positive radius and finite nonzero axes.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "CirclePcurveWire")]
pub struct CirclePcurve {
    center: FinitePoint2,
    x_axis: FinitePoint2,
    y_axis: FinitePoint2,
    radius: PositiveReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct CirclePcurveWire {
    /// Parameter-space circle center.
    center: Point2,
    /// First parameter-space axis.
    x_axis: Point2,
    /// Second parameter-space axis.
    y_axis: Point2,
    /// Circle radius in parameter space.
    radius: f64,
}

impl CirclePcurve {
    /// Build from admitted finite axes and a positive radius. Only the two
    /// nonzero axis conditions remain to check.
    pub fn from_parts(
        center: FinitePoint2,
        x_axis: FinitePoint2,
        y_axis: FinitePoint2,
        radius: PositiveReal,
    ) -> Option<Self> {
        (finite_axis_is_nonzero(x_axis) && finite_axis_is_nonzero(y_axis)).then_some(Self {
            center,
            x_axis,
            y_axis,
            radius,
        })
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point2,
        x_axis: Point2,
        y_axis: Point2,
        radius: f64,
    ) -> Result<Self, &'static str> {
        if x_axis.u.hypot(x_axis.v) <= 0.0 {
            return Err("CirclePcurve.x_axis must be nonzero");
        }
        if y_axis.u.hypot(y_axis.v) <= 0.0 {
            return Err("CirclePcurve.y_axis must be nonzero");
        }
        let center = FinitePoint2::new(center).ok_or("CirclePcurve.center must be finite")?;
        let x_axis = FinitePoint2::new(x_axis).ok_or("CirclePcurve.x_axis must be finite")?;
        let y_axis = FinitePoint2::new(y_axis).ok_or("CirclePcurve.y_axis must be finite")?;
        let radius =
            PositiveReal::new(radius).ok_or("CirclePcurve.radius must be positive and finite")?;
        Ok(Self {
            center,
            x_axis,
            y_axis,
            radius,
        })
    }

    fn scaled_isotropic(self, scale: f64) -> Result<Self, &'static str> {
        let center = self.center.get();
        let center = FinitePoint2::new(Point2::new(center.u * scale, center.v * scale))
            .ok_or("CirclePcurve.center must be finite")?;
        let radius = PositiveReal::new(self.radius.get() * scale)
            .ok_or("CirclePcurve.radius must be positive and finite")?;
        Ok(Self {
            center,
            radius,
            ..self
        })
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> &FinitePoint2 {
        &self.center
    }

    /// Return the x axis.
    #[must_use]
    pub const fn x_axis(&self) -> &FinitePoint2 {
        &self.x_axis
    }

    /// Return the y axis.
    #[must_use]
    pub const fn y_axis(&self) -> &FinitePoint2 {
        &self.y_axis
    }

    /// Return the radius.
    #[must_use]
    pub const fn radius(&self) -> PositiveReal {
        self.radius
    }
}

impl TryFrom<CirclePcurveWire> for CirclePcurve {
    type Error = &'static str;
    fn try_from(wire: CirclePcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.center, wire.x_axis, wire.y_axis, wire.radius)
    }
}

/// Parameter-space ellipse with positive radii and finite nonzero axes.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "EllipsePcurveWire")]
pub struct EllipsePcurve {
    center: FinitePoint2,
    x_axis: FinitePoint2,
    y_axis: FinitePoint2,
    major_radius: PositiveReal,
    minor_radius: PositiveReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct EllipsePcurveWire {
    /// Parameter-space ellipse center.
    center: Point2,
    /// First parameter-space axis.
    x_axis: Point2,
    /// Second parameter-space axis.
    y_axis: Point2,
    /// Major semiaxis radius in parameter space.
    major_radius: f64,
    /// Minor semiaxis radius in parameter space.
    minor_radius: f64,
}

impl EllipsePcurve {
    /// Build from admitted finite axes and positive radii. Only the two
    /// nonzero axis conditions remain to check.
    pub fn from_parts(
        center: FinitePoint2,
        x_axis: FinitePoint2,
        y_axis: FinitePoint2,
        major_radius: PositiveReal,
        minor_radius: PositiveReal,
    ) -> Option<Self> {
        (finite_axis_is_nonzero(x_axis) && finite_axis_is_nonzero(y_axis)).then_some(Self {
            center,
            x_axis,
            y_axis,
            major_radius,
            minor_radius,
        })
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point2,
        x_axis: Point2,
        y_axis: Point2,
        major_radius: f64,
        minor_radius: f64,
    ) -> Result<Self, &'static str> {
        if x_axis.u.hypot(x_axis.v) <= 0.0 {
            return Err("EllipsePcurve.x_axis must be nonzero");
        }
        if y_axis.u.hypot(y_axis.v) <= 0.0 {
            return Err("EllipsePcurve.y_axis must be nonzero");
        }
        let center = FinitePoint2::new(center).ok_or("EllipsePcurve.center must be finite")?;
        let x_axis = FinitePoint2::new(x_axis).ok_or("EllipsePcurve.x_axis must be finite")?;
        let y_axis = FinitePoint2::new(y_axis).ok_or("EllipsePcurve.y_axis must be finite")?;
        let major_radius = PositiveReal::new(major_radius)
            .ok_or("EllipsePcurve.major_radius must be positive and finite")?;
        let minor_radius = PositiveReal::new(minor_radius)
            .ok_or("EllipsePcurve.minor_radius must be positive and finite")?;
        Ok(Self {
            center,
            x_axis,
            y_axis,
            major_radius,
            minor_radius,
        })
    }

    fn scaled_isotropic(self, scale: f64) -> Result<Self, &'static str> {
        let center = self.center.get();
        let center = FinitePoint2::new(Point2::new(center.u * scale, center.v * scale))
            .ok_or("EllipsePcurve.center must be finite")?;
        let major_radius = PositiveReal::new(self.major_radius.get() * scale)
            .ok_or("EllipsePcurve.major_radius must be positive and finite")?;
        let minor_radius = PositiveReal::new(self.minor_radius.get() * scale)
            .ok_or("EllipsePcurve.minor_radius must be positive and finite")?;
        Ok(Self {
            center,
            major_radius,
            minor_radius,
            ..self
        })
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> &FinitePoint2 {
        &self.center
    }

    /// Return the x axis.
    #[must_use]
    pub const fn x_axis(&self) -> &FinitePoint2 {
        &self.x_axis
    }

    /// Return the y axis.
    #[must_use]
    pub const fn y_axis(&self) -> &FinitePoint2 {
        &self.y_axis
    }

    /// Return the major radius.
    #[must_use]
    pub const fn major_radius(&self) -> PositiveReal {
        self.major_radius
    }

    /// Return the minor radius.
    #[must_use]
    pub const fn minor_radius(&self) -> PositiveReal {
        self.minor_radius
    }

    /// The same ellipse traversed as `-t`: the second axis changes sign.
    /// Negation keeps the axis finite and nonzero and every other field is
    /// kept, so nothing is checked.
    #[must_use]
    pub fn reversed_about_zero(&self) -> Self {
        Self {
            y_axis: self.y_axis.negated(),
            ..*self
        }
    }
}

impl TryFrom<EllipsePcurveWire> for EllipsePcurve {
    type Error = &'static str;
    fn try_from(wire: EllipsePcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.center,
            wire.x_axis,
            wire.y_axis,
            wire.major_radius,
            wire.minor_radius,
        )
    }
}

/// Harmonic parameter-space curve with finite coefficients and nonzero variation.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HarmonicPcurveWire")]
pub struct HarmonicPcurve {
    center: FinitePoint2,
    cosine: FinitePoint2,
    sine: FinitePoint2,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HarmonicPcurveWire {
    /// Constant parameter-space coefficient.
    center: Point2,
    /// Cosine parameter-space coefficient.
    cosine: Point2,
    /// Sine parameter-space coefficient.
    sine: Point2,
}

impl HarmonicPcurve {
    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(center: Point2, cosine: Point2, sine: Point2) -> Result<Self, &'static str> {
        if !(cosine.u.hypot(cosine.v) > 0.0 || sine.u.hypot(sine.v) > 0.0) {
            return Err("HarmonicPcurve.cosine/sine must not both be zero");
        }
        let center = FinitePoint2::new(center).ok_or("HarmonicPcurve.center must be finite")?;
        let cosine = FinitePoint2::new(cosine).ok_or("HarmonicPcurve.cosine must be finite")?;
        let sine = FinitePoint2::new(sine).ok_or("HarmonicPcurve.sine must be finite")?;
        Ok(Self {
            center,
            cosine,
            sine,
        })
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> &FinitePoint2 {
        &self.center
    }

    /// Return the cosine.
    #[must_use]
    pub const fn cosine(&self) -> &FinitePoint2 {
        &self.cosine
    }

    /// Return the sine.
    #[must_use]
    pub const fn sine(&self) -> &FinitePoint2 {
        &self.sine
    }
}

impl TryFrom<HarmonicPcurveWire> for HarmonicPcurve {
    type Error = &'static str;
    fn try_from(wire: HarmonicPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.center, wire.cosine, wire.sine)
    }
}

/// Parameter-space parabola with a positive focal distance and finite nonzero axes.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "ParabolaPcurveWire")]
pub struct ParabolaPcurve {
    vertex: FinitePoint2,
    x_axis: FinitePoint2,
    y_axis: FinitePoint2,
    focal_distance: PositiveReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct ParabolaPcurveWire {
    /// Parameter-space parabola vertex.
    vertex: Point2,
    /// First parameter-space axis.
    x_axis: Point2,
    /// Second parameter-space axis.
    y_axis: Point2,
    /// Distance from the vertex to the focus, in parameter space.
    focal_distance: f64,
}

impl ParabolaPcurve {
    /// Build from admitted finite axes and a positive focal distance. Only
    /// the two nonzero axis conditions remain to check.
    pub fn from_parts(
        vertex: FinitePoint2,
        x_axis: FinitePoint2,
        y_axis: FinitePoint2,
        focal_distance: PositiveReal,
    ) -> Option<Self> {
        (finite_axis_is_nonzero(x_axis) && finite_axis_is_nonzero(y_axis)).then_some(Self {
            vertex,
            x_axis,
            y_axis,
            focal_distance,
        })
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        vertex: Point2,
        x_axis: Point2,
        y_axis: Point2,
        focal_distance: f64,
    ) -> Result<Self, &'static str> {
        if x_axis.u.hypot(x_axis.v) <= 0.0 {
            return Err("ParabolaPcurve.x_axis must be nonzero");
        }
        if y_axis.u.hypot(y_axis.v) <= 0.0 {
            return Err("ParabolaPcurve.y_axis must be nonzero");
        }
        let vertex = FinitePoint2::new(vertex).ok_or("ParabolaPcurve.vertex must be finite")?;
        let x_axis = FinitePoint2::new(x_axis).ok_or("ParabolaPcurve.x_axis must be finite")?;
        let y_axis = FinitePoint2::new(y_axis).ok_or("ParabolaPcurve.y_axis must be finite")?;
        let focal_distance = PositiveReal::new(focal_distance)
            .ok_or("ParabolaPcurve.focal_distance must be positive and finite")?;
        Ok(Self {
            vertex,
            x_axis,
            y_axis,
            focal_distance,
        })
    }

    /// Return the vertex.
    #[must_use]
    pub const fn vertex(&self) -> &FinitePoint2 {
        &self.vertex
    }

    /// Return the x axis.
    #[must_use]
    pub const fn x_axis(&self) -> &FinitePoint2 {
        &self.x_axis
    }

    /// Return the y axis.
    #[must_use]
    pub const fn y_axis(&self) -> &FinitePoint2 {
        &self.y_axis
    }

    /// Return the focal distance.
    #[must_use]
    pub const fn focal_distance(&self) -> PositiveReal {
        self.focal_distance
    }

    /// The same parabola traversed as `-t`: the second axis changes sign.
    /// Negation keeps the axis finite and nonzero and every other field is
    /// kept, so nothing is checked.
    #[must_use]
    pub fn reversed_about_zero(&self) -> Self {
        Self {
            y_axis: self.y_axis.negated(),
            ..*self
        }
    }
}

impl TryFrom<ParabolaPcurveWire> for ParabolaPcurve {
    type Error = &'static str;
    fn try_from(wire: ParabolaPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.vertex, wire.x_axis, wire.y_axis, wire.focal_distance)
    }
}

/// Parameter-space hyperbola with positive radii and finite nonzero axes.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HyperbolaPcurveWire")]
pub struct HyperbolaPcurve {
    center: FinitePoint2,
    x_axis: FinitePoint2,
    y_axis: FinitePoint2,
    major_radius: PositiveReal,
    minor_radius: PositiveReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HyperbolaPcurveWire {
    /// Parameter-space hyperbola center.
    center: Point2,
    /// First parameter-space axis.
    x_axis: Point2,
    /// Second parameter-space axis.
    y_axis: Point2,
    /// Transverse semiaxis radius in parameter space.
    major_radius: f64,
    /// Conjugate semiaxis radius in parameter space.
    minor_radius: f64,
}

impl HyperbolaPcurve {
    /// Build from admitted finite axes and positive radii. Only the two
    /// nonzero axis conditions remain to check.
    pub fn from_parts(
        center: FinitePoint2,
        x_axis: FinitePoint2,
        y_axis: FinitePoint2,
        major_radius: PositiveReal,
        minor_radius: PositiveReal,
    ) -> Option<Self> {
        (finite_axis_is_nonzero(x_axis) && finite_axis_is_nonzero(y_axis)).then_some(Self {
            center,
            x_axis,
            y_axis,
            major_radius,
            minor_radius,
        })
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        center: Point2,
        x_axis: Point2,
        y_axis: Point2,
        major_radius: f64,
        minor_radius: f64,
    ) -> Result<Self, &'static str> {
        if x_axis.u.hypot(x_axis.v) <= 0.0 {
            return Err("HyperbolaPcurve.x_axis must be nonzero");
        }
        if y_axis.u.hypot(y_axis.v) <= 0.0 {
            return Err("HyperbolaPcurve.y_axis must be nonzero");
        }
        let center = FinitePoint2::new(center).ok_or("HyperbolaPcurve.center must be finite")?;
        let x_axis = FinitePoint2::new(x_axis).ok_or("HyperbolaPcurve.x_axis must be finite")?;
        let y_axis = FinitePoint2::new(y_axis).ok_or("HyperbolaPcurve.y_axis must be finite")?;
        let major_radius = PositiveReal::new(major_radius)
            .ok_or("HyperbolaPcurve.major_radius must be positive and finite")?;
        let minor_radius = PositiveReal::new(minor_radius)
            .ok_or("HyperbolaPcurve.minor_radius must be positive and finite")?;
        Ok(Self {
            center,
            x_axis,
            y_axis,
            major_radius,
            minor_radius,
        })
    }

    fn scaled_isotropic(self, scale: f64) -> Result<Self, &'static str> {
        let center = self.center.get();
        let center = FinitePoint2::new(Point2::new(center.u * scale, center.v * scale))
            .ok_or("HyperbolaPcurve.center must be finite")?;
        let major_radius = PositiveReal::new(self.major_radius.get() * scale)
            .ok_or("HyperbolaPcurve.major_radius must be positive and finite")?;
        let minor_radius = PositiveReal::new(self.minor_radius.get() * scale)
            .ok_or("HyperbolaPcurve.minor_radius must be positive and finite")?;
        Ok(Self {
            center,
            major_radius,
            minor_radius,
            ..self
        })
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> &FinitePoint2 {
        &self.center
    }

    /// Return the x axis.
    #[must_use]
    pub const fn x_axis(&self) -> &FinitePoint2 {
        &self.x_axis
    }

    /// Return the y axis.
    #[must_use]
    pub const fn y_axis(&self) -> &FinitePoint2 {
        &self.y_axis
    }

    /// Return the major radius.
    #[must_use]
    pub const fn major_radius(&self) -> PositiveReal {
        self.major_radius
    }

    /// Return the minor radius.
    #[must_use]
    pub const fn minor_radius(&self) -> PositiveReal {
        self.minor_radius
    }

    /// The same hyperbola traversed as `-t`: the second axis changes sign.
    /// Negation keeps the axis finite and nonzero and every other field is
    /// kept, so nothing is checked.
    #[must_use]
    pub fn reversed_about_zero(&self) -> Self {
        Self {
            y_axis: self.y_axis.negated(),
            ..*self
        }
    }
}

impl TryFrom<HyperbolaPcurveWire> for HyperbolaPcurve {
    type Error = &'static str;
    fn try_from(wire: HyperbolaPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.center,
            wire.x_axis,
            wire.y_axis,
            wire.major_radius,
            wire.minor_radius,
        )
    }
}

/// Hyperbolic parameter-space curve with finite coefficients and nonzero variation.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HyperbolicPcurveWire")]
pub struct HyperbolicPcurve {
    center: FinitePoint2,
    cosine: FinitePoint2,
    sine: FinitePoint2,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HyperbolicPcurveWire {
    /// Constant parameter-space coefficient.
    center: Point2,
    /// Hyperbolic-cosine parameter-space coefficient.
    cosine: Point2,
    /// Hyperbolic-sine parameter-space coefficient.
    sine: Point2,
}

impl HyperbolicPcurve {
    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(center: Point2, cosine: Point2, sine: Point2) -> Result<Self, &'static str> {
        if !(cosine.u.hypot(cosine.v) > 0.0 || sine.u.hypot(sine.v) > 0.0) {
            return Err("HyperbolicPcurve.cosine/sine must not both be zero");
        }
        let center = FinitePoint2::new(center).ok_or("HyperbolicPcurve.center must be finite")?;
        let cosine = FinitePoint2::new(cosine).ok_or("HyperbolicPcurve.cosine must be finite")?;
        let sine = FinitePoint2::new(sine).ok_or("HyperbolicPcurve.sine must be finite")?;
        Ok(Self {
            center,
            cosine,
            sine,
        })
    }

    /// Return the center.
    #[must_use]
    pub const fn center(&self) -> &FinitePoint2 {
        &self.center
    }

    /// Return the cosine.
    #[must_use]
    pub const fn cosine(&self) -> &FinitePoint2 {
        &self.cosine
    }

    /// Return the sine.
    #[must_use]
    pub const fn sine(&self) -> &FinitePoint2 {
        &self.sine
    }
}

impl TryFrom<HyperbolicPcurveWire> for HyperbolicPcurve {
    type Error = &'static str;
    fn try_from(wire: HyperbolicPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.center, wire.cosine, wire.sine)
    }
}

/// Parameter-space trim with a finite ordered interval.
///
/// `parameter_range` is stated in the basis's own parameter space and is the
/// carrier's declared domain: the trimmed pcurve exists on that interval and a
/// coedge use range over it is checked against it. Equal endpoints state no
/// interval, and the basis's parameterization governs instead.
///
/// The trim reparameterizes nothing, so
/// [`pcurve_uv`](crate::eval::pcurve_uv) hands `t` to the basis unchanged. It
/// does so at every `t`, inside the interval and outside it, because pcurve
/// evaluation is total: it extrapolates past any declared domain, a NURBS
/// carrier's knot interval included. A declared domain and an evaluable
/// parameter are two different questions, and this carrier answers only the
/// first.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "TrimmedPcurveWire")]
pub struct TrimmedPcurve {
    #[cfg_attr(feature = "schema", schemars(with = "[f64; 2]"))]
    parameter_range: ParameterInterval,
    #[serde(default = "crate::default_true")]
    same_sense: bool,
    basis: Box<PcurveGeometry>,
    #[serde(skip)]
    depth: usize,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct TrimmedPcurveWire {
    /// Native parameter interval retained from the basis.
    parameter_range: [f64; 2],
    /// Whether the trim follows increasing basis parameters.
    #[serde(default = "crate::default_true")]
    same_sense: bool,
    /// Curve this curve trims.
    basis: Box<PcurveGeometry>,
}

impl TrimmedPcurve {
    /// Build from finite endpoints, checking their order and the basis depth.
    pub fn from_finite_parts(
        parameter_range: [FiniteReal; 2],
        same_sense: bool,
        basis: Box<PcurveGeometry>,
    ) -> Result<Self, &'static str> {
        let parameter_range = ParameterInterval::from_finite_endpoints(parameter_range.into())
            .map_err(|_| "TrimmedPcurve.parameter_range must be finite and ordered")?;
        let depth = nesting_depth_over(&basis)
            .ok_or("TrimmedPcurve.basis nests past the admitted inline basis depth")?;
        Ok(Self {
            parameter_range,
            same_sense,
            basis,
            depth,
        })
    }

    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(
        parameter_range: [f64; 2],
        same_sense: bool,
        basis: Box<PcurveGeometry>,
    ) -> Result<Self, &'static str> {
        let first = FiniteReal::new(parameter_range[0])
            .ok_or("TrimmedPcurve.parameter_range must be finite and ordered")?;
        let last = FiniteReal::new(parameter_range[1])
            .ok_or("TrimmedPcurve.parameter_range must be finite and ordered")?;
        Self::from_finite_parts([first, last], same_sense, basis)
    }

    /// Return the parameter range.
    #[must_use]
    pub const fn parameter_range(&self) -> ParameterInterval {
        self.parameter_range
    }

    /// Return the same sense.
    #[must_use]
    pub const fn same_sense(&self) -> bool {
        self.same_sense
    }

    /// Return the basis.
    #[must_use]
    pub const fn basis(&self) -> &PcurveGeometry {
        &self.basis
    }
}

impl TryFrom<TrimmedPcurveWire> for TrimmedPcurve {
    type Error = &'static str;
    fn try_from(wire: TrimmedPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.parameter_range, wire.same_sense, wire.basis)
    }
}

/// Parameter-space offset with a finite signed distance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "OffsetPcurveWire")]
pub struct OffsetPcurve {
    distance: FiniteReal,
    basis: Box<PcurveGeometry>,
    #[serde(skip)]
    depth: usize,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct OffsetPcurveWire {
    /// Signed parameter-space offset distance.
    distance: f64,
    /// Curve this curve is offset from.
    basis: Box<PcurveGeometry>,
}

impl OffsetPcurve {
    /// Admit finite parameters that satisfy the carrier's numeric contract.
    pub fn try_new(distance: f64, basis: Box<PcurveGeometry>) -> Result<Self, &'static str> {
        let distance = FiniteReal::new(distance).ok_or("OffsetPcurve.distance must be finite")?;
        Self::from_finite_parts(distance, basis)
    }

    /// Build from a finite distance, checking only the basis depth.
    pub fn from_finite_parts(
        distance: FiniteReal,
        basis: Box<PcurveGeometry>,
    ) -> Result<Self, &'static str> {
        let depth = nesting_depth_over(&basis)
            .ok_or("OffsetPcurve.basis nests past the admitted inline basis depth")?;
        Ok(Self {
            distance,
            basis,
            depth,
        })
    }

    /// Return the distance.
    #[must_use]
    pub const fn distance(&self) -> FiniteReal {
        self.distance
    }

    /// Return the basis.
    #[must_use]
    pub const fn basis(&self) -> &PcurveGeometry {
        &self.basis
    }
}

impl TryFrom<OffsetPcurveWire> for OffsetPcurve {
    type Error = &'static str;
    fn try_from(wire: OffsetPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.distance, wire.basis)
    }
}

/// The shape of a parameter-space (u, v) curve on a surface.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum PcurveGeometry {
    /// A straight line in parameter space.
    Line(LinePcurve),
    /// Polar angle and axial coordinate of a first-order harmonic spatial curve.
    PolarHarmonic(PolarHarmonicPcurve),
    /// Polar angle and axial coordinate obtained from a rational NURBS vector.
    PolarNurbs {
        /// Checked polar NURBS payload.
        #[serde(flatten)]
        #[cfg_attr(feature = "schema", schemars(flatten, with = "PolarPcurveNurbsWire"))]
        nurbs: PolarPcurveNurbs,
    },
    /// Great-circle locus in a sphere's azimuth/latitude parameter chart.
    SphericalGreatCircle(SphericalGreatCirclePcurve),
    /// Full circle in parameter space.
    Circle(CirclePcurve),
    /// Full ellipse in parameter space.
    Ellipse(EllipsePcurve),
    /// General first-order harmonic curve in parameter space.
    Harmonic(HarmonicPcurve),
    /// Parabola in parameter space.
    Parabola(ParabolaPcurve),
    /// Hyperbola in parameter space.
    Hyperbola(HyperbolaPcurve),
    /// General first-order hyperbolic curve in parameter space.
    Hyperbolic(HyperbolicPcurve),
    /// A free-form NURBS curve in parameter space (control points are (u, v)).
    Nurbs {
        /// Checked parameter-space NURBS payload.
        #[serde(flatten)]
        #[cfg_attr(feature = "schema", schemars(flatten))]
        nurbs: PcurveNurbs,
    },
    /// Affine replica of a parent pcurve in the same parameter space.
    Transformed(PlacedPcurve),
    /// Parameter restriction of an exact basis pcurve.
    Trimmed(TrimmedPcurve),
    /// Signed planar offset of an exact basis pcurve.
    Offset(OffsetPcurve),
}

/// One paired radial and axial pole of a polar parameter-space NURBS.
// A source states raw values; a `PolarPcurveNurbs` holds the admitted row,
// whose radial pole is a `FinitePoint2` and whose axial pole is a
// `FiniteReal`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PolarNurbsPole<P = Point2, S = f64> {
    /// Euclidean radial-plane pole.
    pub radial: P,
    /// Axial pole value.
    pub axial: S,
}

/// Checked polar parameter-space NURBS payload.
#[derive(Debug, Clone, PartialEq)]
pub struct PolarPcurveNurbs {
    degree: u32,
    knots: KnotVector,
    poles: PolarNurbsPoles<FinitePoint2, FiniteReal>,
    periodic: bool,
}

/// One rational polar pole: its radial and axial halves and its weight.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct WeightedPolarNurbsPole<P = Point2, S = f64> {
    /// Euclidean radial-plane pole.
    pub radial: P,
    /// Axial pole value.
    pub axial: S,
    /// Rational weight at this pole.
    pub weight: NonZeroReal,
}

/// The poles of a polar parameter-space NURBS curve.
// A source states raw values; a `PolarPcurveNurbs` holds the admitted poles.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "form", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum PolarNurbsPoles<P = Point2, S = f64> {
    /// A polynomial polar curve: its poles carry no weight.
    Polynomial {
        /// Poles in parameter order.
        poles: Vec<PolarNurbsPole<P, S>>,
    },
    /// A rational polar curve: every pole carries its weight.
    Rational {
        /// Pole rows in parameter order.
        poles: Vec<WeightedPolarNurbsPole<P, S>>,
    },
}

impl PolarNurbsPoles<FinitePoint2, FiniteReal> {
    /// The poles with raw radial and axial values, for a reader that writes
    /// them.
    #[must_use]
    pub fn to_raw(&self) -> PolarNurbsPoles {
        let Ok(raw) = self.clone().try_map_poles(|radial, axial| {
            Ok::<_, std::convert::Infallible>((radial.get(), axial.get()))
        });
        raw
    }
}

impl<P, S> PolarNurbsPoles<P, S> {
    /// Pair a source's pole lane with its weight lane. A store admits the
    /// poles it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, naming both counts,
    /// and a weight that is zero or non-finite, naming its index.
    pub fn from_lanes(
        poles: Vec<PolarNurbsPole<P, S>>,
        weights: Option<Vec<f64>>,
    ) -> Result<Self, NurbsError> {
        construction::pair_polar_lanes(poles, weights, |index, weight| {
            admit_weight("polar poles", index, weight)
        })
    }

    /// Pair a pole lane with an admitted weight lane. The weight type states
    /// the weight contract; a store admits the poles it is handed.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, naming both
    /// counts.
    pub fn from_checked_lanes(
        poles: Vec<PolarNurbsPole<P, S>>,
        weights: Option<Vec<NonZeroReal>>,
    ) -> Result<Self, NurbsError> {
        construction::pair_polar_lanes(poles, weights, |_, weight| Ok(weight))
    }

    /// Count poles.
    #[must_use]
    pub fn count(&self) -> usize {
        match self {
            Self::Polynomial { poles } => poles.len(),
            Self::Rational { poles } => poles.len(),
        }
    }

    /// Rational weights in pole order, absent on a polynomial curve.
    #[must_use]
    pub fn weights(&self) -> Option<Vec<f64>> {
        match self {
            Self::Polynomial { .. } => None,
            Self::Rational { poles } => Some(poles.iter().map(|pole| pole.weight.get()).collect()),
        }
    }

    /// Reverse the pole order.
    pub fn reverse(&mut self) {
        match self {
            Self::Polynomial { poles } => poles.reverse(),
            Self::Rational { poles } => poles.reverse(),
        }
    }

    /// Map the radial and axial halves of every pole in parameter order,
    /// keeping the weights.
    fn try_map_poles<Q, T, E>(
        self,
        mut pole: impl FnMut(P, S) -> Result<(Q, T), E>,
    ) -> Result<PolarNurbsPoles<Q, T>, E> {
        Ok(match self {
            Self::Polynomial { poles } => PolarNurbsPoles::Polynomial {
                poles: poles
                    .into_iter()
                    .map(|row| {
                        let (radial, axial) = pole(row.radial, row.axial)?;
                        Ok(PolarNurbsPole { radial, axial })
                    })
                    .collect::<Result<_, E>>()?,
            },
            Self::Rational { poles } => PolarNurbsPoles::Rational {
                poles: poles
                    .into_iter()
                    .map(|row| {
                        let (radial, axial) = pole(row.radial, row.axial)?;
                        Ok(WeightedPolarNurbsPole {
                            radial,
                            axial,
                            weight: row.weight,
                        })
                    })
                    .collect::<Result<_, E>>()?,
            },
        })
    }
}

impl<P: Copy, S: Copy> PolarNurbsPoles<P, S> {
    /// Paired radial and axial poles in parameter order.
    #[must_use]
    pub fn poles(&self) -> Vec<PolarNurbsPole<P, S>> {
        match self {
            Self::Polynomial { poles } => poles.clone(),
            Self::Rational { poles } => poles
                .iter()
                .map(|pole| PolarNurbsPole {
                    radial: pole.radial,
                    axial: pole.axial,
                })
                .collect(),
        }
    }
}

impl PolarPcurveNurbs {
    /// Build a polar NURBS from its pole rows.
    ///
    /// A pole is one row carrying its radial and axial halves together, so
    /// there are no two lists to pair up and no length to compare. Raw pole
    /// values are admitted through the caller policy. Each radial and axial
    /// value is converted together.
    ///
    /// # Errors
    ///
    /// Refuses a pole or knot count that does not follow from the degree, a
    /// zero degree, a non-finite raw pole value and then a non-finite or
    /// decreasing knot.
    pub fn new<P: PoleValue<FinitePoint2>, S: PoleValue<FiniteReal>, K: super::nurbs::KnotValue>(
        degree: u32,
        knots: K,
        poles: PolarNurbsPoles<P, S>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        construction::build_polar(degree, knots, poles, periodic)
    }

    /// Polynomial degree shared by every component.
    pub const fn degree(&self) -> u32 {
        self.degree
    }

    /// Expanded knot vector.
    pub fn knots(&self) -> &KnotVector {
        &self.knots
    }

    /// Build a polar NURBS from a source's pole and weight lanes.
    pub fn from_lanes<
        P: PoleValue<FinitePoint2>,
        S: PoleValue<FiniteReal>,
        K: super::nurbs::KnotValue,
    >(
        degree: u32,
        knots: K,
        poles: Vec<PolarNurbsPole<P, S>>,
        weights: Option<Vec<f64>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles = construction::pair_polar_lanes(poles, weights, |index, weight| {
            admit_weight("polar poles", index, weight)
        })?;
        construction::build_polar(degree, knots, poles, periodic)
    }

    /// Build a polar NURBS from admitted knots, a pole lane and an admitted weight lane.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, invalid
    /// cardinalities, or a non-finite raw pole value.
    pub fn from_checked_lanes<
        P: PoleValue<FinitePoint2>,
        S: PoleValue<FiniteReal>,
        K: super::nurbs::KnotValue,
    >(
        degree: u32,
        knots: K,
        poles: Vec<PolarNurbsPole<P, S>>,
        weights: Option<Vec<NonZeroReal>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles = construction::pair_polar_lanes(poles, weights, |_, weight| Ok(weight))?;
        construction::build_polar(degree, knots, poles, periodic)
    }

    /// Paired radial and axial poles.
    pub fn poles(&self) -> Vec<PolarNurbsPole<FinitePoint2, FiniteReal>> {
        self.poles.poles()
    }

    /// Radial-plane poles in parameter order.
    #[must_use]
    pub fn radial_control_points(&self) -> Vec<FinitePoint2> {
        self.poles().into_iter().map(|pole| pole.radial).collect()
    }

    /// Axial pole values in parameter order.
    #[must_use]
    pub fn axial_control_values(&self) -> Vec<FiniteReal> {
        self.poles().into_iter().map(|pole| pole.axial).collect()
    }

    /// Pole rows, with the curve's rational form and admitted values.
    pub const fn pole_rows(&self) -> &PolarNurbsPoles<FinitePoint2, FiniteReal> {
        &self.poles
    }

    /// Rational weights in pole order.
    pub fn weights(&self) -> Option<Vec<NonZeroReal>> {
        match &self.poles {
            PolarNurbsPoles::Polynomial { .. } => None,
            PolarNurbsPoles::Rational { poles } => {
                Some(poles.iter().map(|pole| pole.weight).collect())
            }
        }
    }

    /// Whether the NURBS parameterization is periodic.
    pub const fn periodic(&self) -> bool {
        self.periodic
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PolarPcurveNurbsWire {
    degree: u32,
    knots: Vec<f64>,
    poles: PolarNurbsPoles,
    #[serde(default)]
    periodic: bool,
}

impl Serialize for PolarPcurveNurbs {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        PolarPcurveNurbsWire {
            degree: self.degree,
            knots: self.knots.to_vec(),
            poles: self.poles.to_raw(),
            periodic: self.periodic,
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for PolarPcurveNurbs {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = PolarPcurveNurbsWire::deserialize(deserializer)?;
        construction::build_polar(wire.degree, wire.knots, wire.poles, wire.periodic)
            .map_err(serde::de::Error::custom)
    }
}

/// Checked two-dimensional NURBS payload for pcurves and sketch curves.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct PcurveNurbs {
    degree: u32,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<f64>"))]
    knots: KnotVector,
    #[cfg_attr(feature = "schema", schemars(with = "PcurveNurbsPoles"))]
    poles: PcurveNurbsPoles<FinitePoint2>,
    #[serde(default)]
    periodic: bool,
}

impl PcurveNurbs {
    /// Map admitted pole positions in place without allocating storage.
    ///
    /// # Errors
    ///
    /// Returns the first mapper refusal. Earlier positions keep their edits.
    pub fn try_map_control_points_in_place<E>(
        &mut self,
        mut map: impl FnMut(FinitePoint2) -> Result<FinitePoint2, E>,
    ) -> Result<(), E> {
        match &mut self.poles {
            PcurveNurbsPoles::Polynomial { points } => {
                for point in points {
                    *point = map(*point)?;
                }
            }
            PcurveNurbsPoles::Rational { points } => {
                for pole in points {
                    pole.point = map(pole.point)?;
                }
            }
        }
        Ok(())
    }

    /// Scale every pole position in place.
    ///
    /// A non-finite result refuses with the poles scaled so far left in place,
    /// so the caller discards the curve on refusal.
    pub(crate) fn scale_points(&mut self, scale: PositiveReal) -> Result<(), NurbsError> {
        fn scale_point(point: &mut FinitePoint2, scale: PositiveReal) -> Result<(), NurbsError> {
            let raw = point.get();
            *point = FinitePoint2::new(Point2::new(raw.u * scale.get(), raw.v * scale.get()))
                .ok_or_else(|| {
                    NurbsError::Structure("control_points contains a non-finite point".to_owned())
                })?;
            Ok(())
        }
        match &mut self.poles {
            PcurveNurbsPoles::Polynomial { points } => {
                for point in points {
                    scale_point(point, scale)?;
                }
            }
            PcurveNurbsPoles::Rational { points } => {
                for pole in points {
                    scale_point(&mut pole.point, scale)?;
                }
            }
        }
        Ok(())
    }

    /// Build a parameter-space NURBS with consistent cardinalities.
    ///
    /// Raw pole positions are admitted; admitted positions are kept, so a
    /// producer that holds them tests only the degree, the cardinalities and
    /// the knots.
    ///
    /// # Errors
    ///
    /// Refuses a pole or knot count that does not follow from the degree, a
    /// zero degree, a non-finite raw pole coordinate and then a non-finite or
    /// decreasing knot.
    pub fn new<P: PoleValue<FinitePoint2>, K: super::nurbs::KnotValue>(
        degree: u32,
        knots: K,
        poles: PcurveNurbsPoles<P>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        construction::build_pcurve(degree, knots, poles, periodic)
    }

    /// Lift each two-dimensional pole into model space, keeping its weight.
    ///
    /// # Errors
    ///
    /// Refuses a lifted pole with a non-finite coordinate.
    pub fn lift(&self, mut lift: impl FnMut(Point2) -> Point3) -> Result<NurbsCurve, NurbsError> {
        let points: Vec<Point3> = self
            .poles
            .points()
            .into_iter()
            .map(|point| lift(point.get()))
            .collect();
        let poles = super::nurbs::pair_curve_lanes(points, self.weights(), |_, weight| Ok(weight))?;
        NurbsCurve::new(self.degree, self.knots.clone(), poles, self.periodic)
    }

    /// Curve degree.
    pub const fn degree(&self) -> u32 {
        self.degree
    }

    /// Full knot vector.
    pub fn knots(&self) -> &KnotVector {
        &self.knots
    }

    /// Build a parameter-space NURBS from a source's pole and weight lanes.
    pub fn from_lanes<P: PoleValue<FinitePoint2>, K: super::nurbs::KnotValue>(
        degree: u32,
        knots: K,
        control_points: Vec<P>,
        weights: Option<Vec<f64>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles = construction::pair_pcurve_lanes(control_points, weights, |index, weight| {
            admit_weight("pcurve poles", index, weight)
        })?;
        construction::build_pcurve(degree, knots, poles, periodic)
    }

    /// Build from finite knot, pole, and weight lanes. Only relationships and
    /// the nonzero weight condition are checked.
    pub fn from_finite_lanes(
        degree: u32,
        knots: Vec<FiniteReal>,
        control_points: Vec<FinitePoint2>,
        weights: Option<Vec<FiniteReal>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles = construction::pair_pcurve_lanes(control_points, weights, |index, weight| {
            admit_finite_weight("pcurve poles", index, weight)
        })?;
        construction::build_pcurve(degree, knots, poles, periodic)
    }

    /// Build a parameter-space NURBS from admitted knots, a pole lane and an
    /// admitted weight lane.
    ///
    /// # Errors
    ///
    /// Refuses a weight lane that does not cover the poles, invalid
    /// cardinalities, or a non-finite raw pole coordinate.
    pub fn from_checked_lanes<P: PoleValue<FinitePoint2>, K: super::nurbs::KnotValue>(
        degree: u32,
        knots: K,
        control_points: Vec<P>,
        weights: Option<Vec<NonZeroReal>>,
        periodic: bool,
    ) -> Result<Self, NurbsError> {
        let poles =
            construction::pair_pcurve_lanes(control_points, weights, |_, weight| Ok(weight))?;
        construction::build_pcurve(degree, knots, poles, periodic)
    }

    /// Poles in parameter order, with the pcurve's rational form and admitted
    /// positions.
    pub const fn pole_rows(&self) -> &PcurveNurbsPoles<FinitePoint2> {
        &self.poles
    }

    /// Control points in parameter order.
    #[must_use]
    pub fn control_points(&self) -> Vec<FinitePoint2> {
        self.poles.points()
    }

    /// Replace every admitted pole position when the supplied lane has the same cardinality.
    ///
    /// The check precedes mutation. Pole weights and knots stay in place.
    pub fn replace_admitted_control_points(&mut self, positions: &[FinitePoint2]) -> bool {
        let count = match &self.poles {
            PcurveNurbsPoles::Polynomial { points } => points.len(),
            PcurveNurbsPoles::Rational { points } => points.len(),
        };
        if positions.len() != count {
            return false;
        }

        match &mut self.poles {
            PcurveNurbsPoles::Polynomial { points } => {
                for (point, position) in points.iter_mut().zip(positions) {
                    *point = *position;
                }
            }
            PcurveNurbsPoles::Rational { points } => {
                for (pole, position) in points.iter_mut().zip(positions) {
                    pole.point = *position;
                }
            }
        }
        true
    }

    /// Map pole positions in order after every result passes admission.
    /// The map must return the same result for the same index and position.
    /// Pole weights and knots stay in place.
    pub fn try_map_control_points<E>(
        &mut self,
        map: impl Fn(usize, FinitePoint2) -> Result<FinitePoint2, E>,
    ) -> Result<(), E> {
        match &self.poles {
            PcurveNurbsPoles::Polynomial { points } => {
                for (index, point) in points.iter().copied().enumerate() {
                    map(index, point)?;
                }
            }
            PcurveNurbsPoles::Rational { points } => {
                for (index, pole) in points.iter().enumerate() {
                    map(index, pole.point)?;
                }
            }
        }
        match &mut self.poles {
            PcurveNurbsPoles::Polynomial { points } => {
                for (index, point) in points.iter_mut().enumerate() {
                    *point = map(index, *point)?;
                }
            }
            PcurveNurbsPoles::Rational { points } => {
                for (index, pole) in points.iter_mut().enumerate() {
                    pole.point = map(index, pole.point)?;
                }
            }
        }
        Ok(())
    }

    /// Rational weights in pole order.
    pub fn weights(&self) -> Option<Vec<NonZeroReal>> {
        match &self.poles {
            PcurveNurbsPoles::Polynomial { .. } => None,
            PcurveNurbsPoles::Rational { points } => {
                Some(points.iter().map(|pole| pole.weight).collect())
            }
        }
    }

    /// Whether the parameter-space curve is periodic.
    pub const fn periodic(&self) -> bool {
        self.periodic
    }

    /// Reverse poles, weights, and the signed knot parameterization together.
    pub fn reverse_parameterization(&mut self) {
        self.knots.reverse_negated();
        self.poles.reverse();
    }
}

impl<'de> Deserialize<'de> for PcurveNurbs {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            degree: u32,
            knots: Vec<f64>,
            poles: PcurveNurbsPoles,
            #[serde(default)]
            periodic: bool,
        }

        let wire = Wire::deserialize(deserializer)?;
        construction::build_pcurve(wire.degree, wire.knots, wire.poles, wire.periodic)
            .map_err(serde::de::Error::custom)
    }
}

/// The depth a new nesting carrier over `basis` would hold, or `None` when
/// that is past [`MAX_GEOMETRY_NESTING`].
///
/// A pcurve nests through three wrappers rather than one: [`PlacedPcurve`],
/// [`TrimmedPcurve`] and [`OffsetPcurve`] each hold one inline basis, and the
/// admitted depth counts all three together. Each stores its own depth, so
/// this reads one field.
fn nesting_depth_over(basis: &PcurveGeometry) -> Option<usize> {
    basis
        .nesting_depth()
        .checked_add(1)
        .filter(|depth| *depth <= MAX_GEOMETRY_NESTING)
}

/// Affine replica of a parent pcurve in the same parameter space.
///
/// `try_new` is the only constructor and refuses a chain deeper than
/// [`MAX_GEOMETRY_NESTING`], so no [`PcurveGeometry`] value nests past the
/// bound however it was built or read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "PlacedPcurveWire")]
pub struct PlacedPcurve {
    basis: Box<PcurveGeometry>,
    transform: Transform2,
    #[serde(skip)]
    depth: usize,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PlacedPcurveWire {
    /// Exact parent pcurve and its parameterization.
    basis: Box<PcurveGeometry>,
    /// Two-dimensional affine map from parent coordinates to replica coordinates.
    transform: Transform2,
}

impl PlacedPcurve {
    /// Place a basis pcurve, refusing a chain past [`MAX_GEOMETRY_NESTING`].
    ///
    /// # Errors
    ///
    /// Refuses a basis already at the bound, whose placement would produce a
    /// carrier one deeper than the IR admits.
    pub fn try_new(
        basis: Box<PcurveGeometry>,
        transform: Transform2,
    ) -> Result<Self, &'static str> {
        let depth = nesting_depth_over(&basis)
            .ok_or("PlacedPcurve.basis nests past the admitted inline basis depth")?;
        Ok(Self {
            basis,
            transform,
            depth,
        })
    }

    /// Return the basis.
    #[must_use]
    pub const fn basis(&self) -> &PcurveGeometry {
        &self.basis
    }

    /// Return the transform.
    #[must_use]
    pub const fn transform(&self) -> &Transform2 {
        &self.transform
    }
}

impl TryFrom<PlacedPcurveWire> for PlacedPcurve {
    type Error = &'static str;
    fn try_from(wire: PlacedPcurveWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.basis, wire.transform)
    }
}

/// Refusal while staging or scaling chart coordinates.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PcurveCoordinateScaleError {
    /// A changed coordinate failed the carrier invariant.
    #[error("{0}")]
    Invalid(String),
    /// Storage or work exceeded the operation limit.
    #[error("resource refusal: {0:?}")]
    Resource(cadmpeg_core::decode::ResourceLimit),
}
impl From<CodecError> for PcurveCoordinateScaleError {
    fn from(error: CodecError) -> Self {
        match error {
            CodecError::ResourceLimit(limit) => Self::Resource(limit),
            CodecError::Malformed(message) => Self::Invalid(message),
            error => Self::Invalid(error.to_string()),
        }
    }
}

impl PcurveGeometry {
    /// Nesting carriers enclosing the leaf of this carrier's inline chain.
    #[must_use]
    pub(crate) const fn nesting_depth(&self) -> usize {
        match self {
            Self::Transformed(placed) => placed.depth,
            Self::Trimmed(trimmed) => trimmed.depth,
            Self::Offset(offset) => offset.depth,
            Self::Line(_)
            | Self::PolarHarmonic(_)
            | Self::PolarNurbs { .. }
            | Self::SphericalGreatCircle(_)
            | Self::Circle(_)
            | Self::Ellipse(_)
            | Self::Harmonic(_)
            | Self::Parabola(_)
            | Self::Hyperbola(_)
            | Self::Hyperbolic(_)
            | Self::Nurbs { .. } => 0,
        }
    }

    /// Scale chart coordinates atomically without changing the curve parameterization.
    pub fn try_scale_coordinates(
        &mut self,
        scales: [f64; 2],
    ) -> Result<(), PcurveCoordinateScaleError> {
        let arena = cadmpeg_core::decode::DecodeArena::new();
        let policy = cadmpeg_core::decode::DecodePolicy::default();
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy)
            .map_err(PcurveCoordinateScaleError::from)?;
        let candidate = match self
            .clone()
            .scaled_coordinates_owned(&ctx, scales)
            .map_err(PcurveCoordinateScaleError::from)?
        {
            Ok(candidate) => candidate,
            Err(message) => return Err(PcurveCoordinateScaleError::Invalid(message.to_owned())),
        };
        *self = candidate;
        Ok(())
    }

    /// Returns the origin and direction of a line-valued pcurve.
    ///
    /// Trimming and affine replicas preserve a line's parameterization. An
    /// offset does not preserve it because the offset is evaluated from the
    /// basis tangent, so it is deliberately excluded.
    pub fn line_parameters(
        &self,
        ctx: &DecodeContext<'_>,
    ) -> Result<Option<(Point2, Point2)>, ResourceLimit> {
        let _depth = ctx.enter_nested_limit("pcurve line parameter nesting")?;

        Ok(match self {
            Self::Line(line_pcurve) => {
                let origin = line_pcurve.origin().as_raw();
                let direction = line_pcurve.direction().as_raw();
                Some((*origin, *direction))
            }
            Self::Transformed(placed) => {
                let Some((origin, direction)) = placed.basis().line_parameters(ctx)? else {
                    return Ok(None);
                };
                let transform = placed.transform();
                Some((
                    transform.apply_point(origin),
                    transform.apply_vector(direction),
                ))
            }
            Self::Trimmed(trimmed_pcurve) => {
                let basis = trimmed_pcurve.basis();
                basis.line_parameters(ctx)?
            }
            Self::PolarHarmonic(_) => None,
            Self::PolarNurbs { .. } => None,
            Self::SphericalGreatCircle(_) => None,
            Self::Circle(_) => None,
            Self::Ellipse(_) => None,
            Self::Harmonic(_) => None,
            Self::Parabola(_) => None,
            Self::Hyperbola(_) => None,
            Self::Hyperbolic(_) => None,
            Self::Nurbs { .. } => None,
            Self::Offset(_) => None,
        })
    }
}

/// A pcurve carrier: the 2D image of a coedge in its face's surface parameter
/// space. Referenced by a coedge; the owning surface establishes whether a
/// parameter dimension is a length (relevant to unit scaling, see [F3D spec §5](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/asm.md#5-topology-records)).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Pcurve {
    /// Arena id.
    pub id: PcurveId,
    /// Parameter-space shape.
    pub geometry: PcurveGeometry,
    /// Source parameterization metadata.
    #[serde(default)]
    pub metadata: PcurveMetadata,
}

impl Pcurve {
    /// Native wrapper reversal, when the source stores one.
    pub fn wrapper_reversed(&self) -> Option<bool> {
        self.metadata.wrapper_reversed()
    }

    /// Four ASM booleans following an inline subtype scope.
    pub fn native_tail_flags(&self) -> Option<[bool; 4]> {
        self.metadata.native_tail_flags()
    }

    /// Directed native parameter interval on which this pcurve is evaluated.
    pub fn parameter_range(&self) -> Option<FiniteVector<2>> {
        self.metadata.parameter_range()
    }

    /// Parameter-space fit tolerance following a solved UV cache.
    pub fn fit_tolerance(&self) -> Option<FitTolerance> {
        self.metadata.fit_tolerance()
    }
}

/// Source-specific pcurve parameterization metadata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "source", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum PcurveMetadata {
    /// An ASM inline `exp_par_cur` record and its complete native tail.
    AsmInline {
        /// Complete inline record fields.
        form: PcurveInlineForm,
    },
    /// Metadata that does not assert the ASM inline-record contract.
    General {
        /// Optional fields carried without an inline-record claim.
        #[serde(default)]
        form: PcurveGeneralForm,
    },
}

impl Default for PcurveMetadata {
    fn default() -> Self {
        Self::General {
            form: PcurveGeneralForm::default(),
        }
    }
}

impl PcurveMetadata {
    /// The refusal of a parameter range with a non-finite endpoint.
    pub const NON_FINITE_PARAMETER_RANGE: &'static str =
        "pcurve parameter_range endpoints must be finite";
    /// The refusal of a fit tolerance that is not finite and non-negative.
    pub const INVALID_FIT_TOLERANCE: &'static str =
        "pcurve fit_tolerance must be finite and non-negative";

    /// Construct metadata without an ASM inline-record claim from admitted
    /// fields.
    #[must_use]
    pub const fn general(
        wrapper_reversed: Option<bool>,
        parameter_range: Option<FiniteVector<2>>,
        fit_tolerance: Option<FitTolerance>,
    ) -> Self {
        Self::General {
            form: PcurveGeneralForm::new(wrapper_reversed, parameter_range, fit_tolerance),
        }
    }

    /// Native wrapper reversal, when the source stores one.
    pub fn wrapper_reversed(&self) -> Option<bool> {
        match self {
            Self::AsmInline { form: inline } => Some(inline.wrapper_reversed),
            Self::General { form: general } => general.wrapper_reversed,
        }
    }

    /// Four ASM booleans following an inline subtype scope.
    pub fn native_tail_flags(&self) -> Option<[bool; 4]> {
        match self {
            Self::AsmInline { form: inline } => Some(inline.native_tail_flags),
            Self::General { .. } => None,
        }
    }

    /// Directed native parameter interval on which this pcurve is evaluated.
    pub fn parameter_range(&self) -> Option<FiniteVector<2>> {
        match self {
            Self::AsmInline { form: inline } => Some(inline.parameter_range),
            Self::General { form: general } => general.parameter_range,
        }
    }

    /// Parameter-space fit tolerance following a solved UV cache.
    pub fn fit_tolerance(&self) -> Option<FitTolerance> {
        match self {
            Self::AsmInline { form: inline } => Some(inline.fit_tolerance()),
            Self::General { form: general } => general.fit_tolerance(),
        }
    }
}

fn admit_pcurve_parameter_range(range: [f64; 2]) -> Result<FiniteVector<2>, &'static str> {
    FiniteVector::new(range).ok_or(PcurveMetadata::NON_FINITE_PARAMETER_RANGE)
}

fn admit_pcurve_fit_tolerance(value: f64) -> Result<FitTolerance, &'static str> {
    FitTolerance::try_new(value).map_err(|_| PcurveMetadata::INVALID_FIT_TOLERANCE)
}

/// The fields carried together by an ASM inline `exp_par_cur` record.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "PcurveInlineFormWire")]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct PcurveInlineForm {
    /// Parameterization wrapper reversal.
    pub wrapper_reversed: bool,
    /// Four native booleans following the inline subtype scope.
    pub native_tail_flags: [bool; 4],
    #[cfg_attr(feature = "schema", schemars(with = "[f64; 2]"))]
    parameter_range: FiniteVector<2>,
    fit_tolerance: FitTolerance,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
struct PcurveInlineFormWire {
    /// Parameterization wrapper reversal.
    wrapper_reversed: bool,
    /// Four native booleans following the inline subtype scope.
    native_tail_flags: [bool; 4],
    /// Directed native parameter interval.
    parameter_range: [f64; 2],
    /// Parameter-space fit tolerance.
    fit_tolerance: f64,
}

impl TryFrom<PcurveInlineFormWire> for PcurveInlineForm {
    type Error = &'static str;
    fn try_from(wire: PcurveInlineFormWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.wrapper_reversed,
            wire.native_tail_flags,
            wire.parameter_range,
            wire.fit_tolerance,
        )
    }
}

impl PcurveInlineForm {
    /// Construct inline metadata from admitted fields.
    #[must_use]
    pub const fn new(
        wrapper_reversed: bool,
        native_tail_flags: [bool; 4],
        parameter_range: FiniteVector<2>,
        fit_tolerance: FitTolerance,
    ) -> Self {
        Self {
            wrapper_reversed,
            native_tail_flags,
            parameter_range,
            fit_tolerance,
        }
    }

    /// Admit inline metadata read from the wire, refusing a non-finite
    /// endpoint and then a tolerance that is not finite and non-negative.
    pub(crate) fn try_new(
        wrapper_reversed: bool,
        native_tail_flags: [bool; 4],
        parameter_range: [f64; 2],
        fit_tolerance: f64,
    ) -> Result<Self, &'static str> {
        Ok(Self::new(
            wrapper_reversed,
            native_tail_flags,
            admit_pcurve_parameter_range(parameter_range)?,
            admit_pcurve_fit_tolerance(fit_tolerance)?,
        ))
    }

    /// Parameter-space fit tolerance.
    #[must_use]
    pub const fn fit_tolerance(&self) -> FitTolerance {
        self.fit_tolerance
    }

    /// Replace the fit tolerance.
    pub fn set_fit_tolerance(&mut self, value: FitTolerance) {
        self.fit_tolerance = value;
    }

    /// Directed native parameter interval.
    #[must_use]
    pub const fn parameter_range(&self) -> FiniteVector<2> {
        self.parameter_range
    }
}

/// Pcurve metadata with no ASM inline-record contract.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "PcurveGeneralFormWire")]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct PcurveGeneralForm {
    /// Source wrapper reversal, when stored independently of an ASM tail.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_wrapper_reversed"
    )]
    pub wrapper_reversed: Option<bool>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_parameter_range"
    )]
    #[cfg_attr(feature = "schema", schemars(with = "Option<[f64; 2]>"))]
    parameter_range: Option<FiniteVector<2>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    fit_tolerance: Option<FitTolerance>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
struct PcurveGeneralFormWire {
    /// Source wrapper reversal, when stored independently of an ASM tail.
    #[serde(default, deserialize_with = "deserialize_wrapper_reversed")]
    wrapper_reversed: Option<bool>,
    /// Directed native parameter interval.
    #[serde(default, deserialize_with = "deserialize_parameter_range")]
    parameter_range: Option<[f64; 2]>,
    /// Parameter-space fit tolerance.
    #[serde(
        default,
        deserialize_with = "deserialize_pcurve_general_form_wire_fit_tolerance"
    )]
    fit_tolerance: Option<f64>,
}

impl TryFrom<PcurveGeneralFormWire> for PcurveGeneralForm {
    type Error = &'static str;
    fn try_from(wire: PcurveGeneralFormWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.wrapper_reversed,
            wire.parameter_range,
            wire.fit_tolerance,
        )
    }
}

impl PcurveGeneralForm {
    /// Construct general metadata from admitted fields.
    #[must_use]
    pub const fn new(
        wrapper_reversed: Option<bool>,
        parameter_range: Option<FiniteVector<2>>,
        fit_tolerance: Option<FitTolerance>,
    ) -> Self {
        Self {
            wrapper_reversed,
            parameter_range,
            fit_tolerance,
        }
    }

    /// Admit general metadata read from the wire, refusing a non-finite
    /// endpoint and then a tolerance that is not finite and non-negative.
    pub(crate) fn try_new(
        wrapper_reversed: Option<bool>,
        parameter_range: Option<[f64; 2]>,
        fit_tolerance: Option<f64>,
    ) -> Result<Self, &'static str> {
        Ok(Self::new(
            wrapper_reversed,
            parameter_range
                .map(admit_pcurve_parameter_range)
                .transpose()?,
            fit_tolerance.map(admit_pcurve_fit_tolerance).transpose()?,
        ))
    }

    /// Parameter-space fit tolerance.
    #[must_use]
    pub fn fit_tolerance(&self) -> Option<FitTolerance> {
        self.fit_tolerance
    }

    /// Replace or clear the fit tolerance.
    pub fn set_fit_tolerance(&mut self, value: Option<FitTolerance>) {
        self.fit_tolerance = value;
    }

    /// Directed native parameter interval.
    #[must_use]
    pub const fn parameter_range(&self) -> Option<FiniteVector<2>> {
        self.parameter_range
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(deserialize_wrapper_reversed, bool, "wrapper_reversed");
cadmpeg_core::named_optional_field!(deserialize_parameter_range, [f64; 2], "parameter_range");
cadmpeg_core::named_optional_field!(
    deserialize_pcurve_general_form_wire_fit_tolerance,
    f64,
    "fit_tolerance"
);

#[cfg(test)]
mod tests;

mod identity_rewrite;