cadmpeg-ir 0.6.5

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
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
// SPDX-License-Identifier: Apache-2.0
//! Geometry carriers: analytic surfaces, analytic curves, NURBS, and pcurves.
//!
//! Carriers are stored in their own arenas and referenced by id from the
//! topology graph (a face references a [`Surface`], an edge a [`Curve`], a
//! coedge a [`pcurve::Pcurve`]). One carrier may therefore support several topological
//! entities.

use crate::features::{FinitePoint3, FiniteVector3};
use crate::ids::{CurveId, PcurveId, ProceduralCurveId, ProceduralSurfaceId, SurfaceId, UnknownId};
use crate::math::{
    sum::{fast_dot, ExactSignedSum},
    Point3, Vector3,
};
use crate::provenance::SourceObjectAssociation;
use crate::scalar::{FiniteReal, NonNegativeReal, PositiveI64};
use crate::transform::Transform;
use crate::units::FiniteVector;
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::num::NonZeroI64;

pub mod analytic;
pub mod nurbs;
pub mod pcurve;
pub mod sampled;
pub mod scaling;
use analytic::{
    CircleCurve, ConeSurface, CylinderSurface, DegenerateCurve, EllipseCurve, HyperbolaCurve,
    LineCurve, ParabolaCurve, PlaneSurface, SphereSurface, TorusSurface,
};
use nurbs::{NurbsCurve, NurbsSurface};
use pcurve::PcurveGeometry;
use sampled::{PolygonalSurface, PolylineCurve};

/// Checked procedural curve payloads.
pub mod curve_payloads;
mod lanes;
/// Checked procedural surface payloads.
pub mod surface_payloads;

/// Greatest number of nesting carriers the IR admits over one geometry leaf.
///
/// A nesting carrier holds its basis inline in a `Box` rather than by arena id:
/// [`PlacedSurface`], [`PlacedCurve`], and a pcurve's
/// [`PlacedPcurve`](pcurve::PlacedPcurve),
/// [`TrimmedPcurve`](pcurve::TrimmedPcurve) and
/// [`OffsetPcurve`](pcurve::OffsetPcurve). Each one's `try_new` refuses a
/// result past this depth and stores the depth it holds, so no value of the
/// three carriers nests deeper however it was built or deserialized, and every
/// consumer that reads through a basis is bounded without a check of its own.
pub const MAX_GEOMETRY_NESTING: usize = 256;

/// Admitted conditional flag shapes in the pre-revision offset-surface layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
pub enum LegacyExtensionFlags {
    /// The compact `offsur` layout has no extension flag.
    Absent {},
    /// The extension gate is false, so no dependent flags follow it.
    Disabled {},
    /// The extension gate is true and carries its required flag and optional
    /// later-revision flag.
    Enabled {
        /// Required flag following the true extension gate.
        secondary: bool,
        /// Optional flag admitted by the later legacy layout.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_tertiary"
        )]
        tertiary: Option<bool>,
    },
}

/// Mutually exclusive pre-revision and revision-gated offset layouts.
// A source states raw scalars; an `OffsetSurfaceConstruction` holds the
// admitted extension, whose scalars are `FiniteReal` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "layout", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub enum OffsetExtension<R = f64> {
    /// Pre-revision conditional flag sequence.
    Legacy {
        /// Conditional flag sequence in its positional wire form.
        flags: LegacyExtensionFlags,
        /// Solved-cache fit contract this layout states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    /// Revision-gated fields with the required four-boolean carrier run.
    Revision {
        /// Revision-gated form whose carrier run is exactly four booleans.
        form: Box<RevisionSurfaceForm<[bool; 4], R>>,
    },
}

/// Analytic, NURBS, or opaque surface geometry established without a
/// construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SolvedSurfaceGeometry {
    /// Infinite plane through `origin` with the given `normal`.
    Plane(PlaneSurface),
    /// Right circular cylinder of the given `radius` about the axis line.
    Cylinder(CylinderSurface),
    /// Right elliptical cone. `radius` is the major radius at `origin`;
    /// `ratio` is the minor-to-major radius ratio; `half_angle` is the major
    /// half-angle between the axis and the cone surface, in radians.
    Cone(ConeSurface),
    /// Sphere.
    Sphere(SphereSurface),
    /// Torus. `major_radius` is the distance from `center` to the tube center;
    /// `minor_radius` is the tube radius.
    Torus(TorusSurface),
    /// Free-form NURBS surface.
    Nurbs(NurbsSurface),
    /// Source-native polygonal surface with an explicit chordal error bound.
    Polygonal(PolygonalSurface),
    /// Exact affine placement of an inline basis surface.
    Transformed(PlacedSurface),
    /// Surface geometry that has no typed neutral representation.
    ///
    /// `record` links to retained source bytes when available.
    ///
    /// A [`Surface`] carrying this variant should have entity exactness
    /// [`Exactness::Unknown`](crate::provenance::Exactness::Unknown) in the
    /// document's [`Annotations`](crate::annotations::Annotations): the shape was
    /// not established, so nothing about it is byte-exact or derived.
    Unknown {
        /// Link to the preserved raw record, when the decoder kept the bytes.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_record"
        )]
        record: Option<UnknownId>,
    },
}

impl SolvedSurfaceGeometry {
    /// Placements enclosing the leaf of this carrier's inline basis chain.
    ///
    /// [`PlacedSurface`] stores its own depth, so this reads one field and
    /// building a chain costs one addition per placement.
    #[must_use]
    pub(crate) const fn nesting_depth(&self) -> usize {
        match self {
            Self::Transformed(placed) => placed.depth,
            Self::Plane(_)
            | Self::Cylinder(_)
            | Self::Cone(_)
            | Self::Sphere(_)
            | Self::Torus(_)
            | Self::Nurbs(_)
            | Self::Polygonal(_)
            | Self::Unknown { .. } => 0,
        }
    }
}

/// Exact affine placement of an inline basis surface.
///
/// `try_new` is the only constructor and refuses a chain deeper than
/// [`MAX_GEOMETRY_NESTING`], so no [`SolvedSurfaceGeometry`] 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 = "PlacedSurfaceWire")]
pub struct PlacedSurface {
    basis: Box<SolvedSurfaceGeometry>,
    transform: Transform,
    #[serde(skip)]
    depth: usize,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PlacedSurfaceWire {
    /// Unplaced basis geometry with unchanged parameterization.
    basis: Box<SolvedSurfaceGeometry>,
    /// Affine map from basis coordinates to model coordinates.
    transform: Transform,
}

impl PlacedSurface {
    /// Place a basis surface, 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<SolvedSurfaceGeometry>,
        transform: Transform,
    ) -> Result<Self, &'static str> {
        let Some(depth) = basis
            .nesting_depth()
            .checked_add(1)
            .filter(|depth| *depth <= MAX_GEOMETRY_NESTING)
        else {
            return Err("PlacedSurface.basis nests past the admitted inline basis depth");
        };
        Ok(Self {
            basis,
            transform,
            depth,
        })
    }

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

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

    /// Replace the transform. The basis chain, and so the depth, is unchanged.
    pub const fn set_transform(&mut self, transform: Transform) {
        self.transform = transform;
    }
}

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

/// Analytic, NURBS, procedural, or opaque surface geometry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SurfaceGeometry {
    /// Exact surface defined by a procedural construction in the same model.
    Procedural {
        /// Construction that produces this carrier.
        construction: ProceduralSurfaceId,
        /// Solved carrier geometry retained from the source cache.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_surface_geometry_cache"
        )]
        #[cfg_attr(feature = "schema", schemars(skip))]
        cache: Option<SolvedSurfaceGeometry>,
    },
    /// A carrier whose shape is established without a construction.
    #[serde(untagged)]
    Solved(SolvedSurfaceGeometry),
}

impl SurfaceGeometry {
    /// Construction that owns this carrier, when it is procedural.
    #[must_use]
    pub const fn procedural_construction(&self) -> Option<&ProceduralSurfaceId> {
        match self {
            Self::Procedural { construction, .. } => Some(construction),
            Self::Solved(_) => None,
        }
    }

    /// Solved carrier retained from the source cache, when this carrier is
    /// procedural.
    #[must_use]
    pub const fn solved_cache(&self) -> Option<&SolvedSurfaceGeometry> {
        match self {
            Self::Procedural { cache, .. } => cache.as_ref(),
            Self::Solved(_) => None,
        }
    }

    /// Geometry that evaluates this carrier without following a construction.
    #[must_use]
    pub const fn solved(&self) -> Option<&SolvedSurfaceGeometry> {
        match self {
            Self::Procedural { cache, .. } => cache.as_ref(),
            Self::Solved(geometry) => Some(geometry),
        }
    }
}

/// An identified surface carrier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Surface {
    /// Arena id.
    pub id: SurfaceId,
    /// Surface shape.
    pub geometry: SurfaceGeometry,
    /// Native source-object identity and effective display metadata.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_object"
    )]
    pub source_object: Option<SourceObjectAssociation>,
}

/// The analytic or free-form shape of a 3D curve carrier established without a
/// construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SolvedCurveGeometry {
    /// Infinite line.
    Line(LineCurve),
    /// Full circle.
    Circle(CircleCurve),
    /// Ellipse.
    Ellipse(EllipseCurve),
    /// Parabola in STEP conic form.
    Parabola(ParabolaCurve),
    /// Hyperbola in STEP conic form.
    Hyperbola(HyperbolaCurve),
    /// A curve collapsed to one model-space point at a topological singularity.
    Degenerate(DegenerateCurve),
    /// Ordered child curves joined into one bounded carrier.
    Composite {
        /// Ordered curve uses and their continuity contracts.
        segments: CompositeCurveSegments,
        /// Whether the source classifies the complete curve as self-intersecting.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        self_intersect: Option<bool>,
    },
    /// Free-form NURBS curve.
    Nurbs(NurbsCurve),
    /// Source-native polyline with an explicit chordal error bound.
    Polyline(PolylineCurve),
    /// Exact affine placement of an inline basis curve.
    Transformed(PlacedCurve),
    /// Native curve carrier whose shape is not decoded.
    Unknown {
        /// Retained native record containing the curve carrier.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_record"
        )]
        record: Option<UnknownId>,
    },
}

impl SolvedCurveGeometry {
    /// Placements enclosing the leaf of this carrier's inline basis chain.
    ///
    /// [`PlacedCurve`] stores its own depth, so this reads one field and
    /// building a chain costs one addition per placement.
    #[must_use]
    pub(crate) const fn nesting_depth(&self) -> usize {
        match self {
            Self::Transformed(placed) => placed.depth,
            Self::Line(_)
            | Self::Circle(_)
            | Self::Ellipse(_)
            | Self::Parabola(_)
            | Self::Hyperbola(_)
            | Self::Degenerate(_)
            | Self::Composite { .. }
            | Self::Nurbs(_)
            | Self::Polyline(_)
            | Self::Unknown { .. } => 0,
        }
    }
}

/// Exact affine placement of an inline basis curve.
///
/// `try_new` is the only constructor and refuses a chain deeper than
/// [`MAX_GEOMETRY_NESTING`], so no [`SolvedCurveGeometry`] 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 = "PlacedCurveWire")]
pub struct PlacedCurve {
    basis: Box<SolvedCurveGeometry>,
    transform: Transform,
    #[serde(skip)]
    depth: usize,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PlacedCurveWire {
    /// Unplaced basis geometry with unchanged parameterization.
    basis: Box<SolvedCurveGeometry>,
    /// Affine map from basis coordinates to model coordinates.
    transform: Transform,
}

impl PlacedCurve {
    /// Place a basis curve, 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<SolvedCurveGeometry>,
        transform: Transform,
    ) -> Result<Self, &'static str> {
        let Some(depth) = basis
            .nesting_depth()
            .checked_add(1)
            .filter(|depth| *depth <= MAX_GEOMETRY_NESTING)
        else {
            return Err("PlacedCurve.basis nests past the admitted inline basis depth");
        };
        Ok(Self {
            basis,
            transform,
            depth,
        })
    }

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

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

    /// Replace the transform. The basis chain, and so the depth, is unchanged.
    pub const fn set_transform(&mut self, transform: Transform) {
        self.transform = transform;
    }
}

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

/// The analytic, free-form, procedural, or opaque shape of a 3D curve carrier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum CurveGeometry {
    /// Exact curve defined by a procedural construction in the same model.
    Procedural {
        /// Construction that produces this carrier.
        construction: ProceduralCurveId,
        /// Solved carrier geometry retained from the source cache.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_curve_geometry_cache"
        )]
        #[cfg_attr(feature = "schema", schemars(skip))]
        cache: Option<SolvedCurveGeometry>,
    },
    /// A carrier whose shape is established without a construction.
    #[serde(untagged)]
    Solved(SolvedCurveGeometry),
}

impl CurveGeometry {
    /// Construction that owns this carrier, when it is procedural.
    #[must_use]
    pub const fn procedural_construction(&self) -> Option<&ProceduralCurveId> {
        match self {
            Self::Procedural { construction, .. } => Some(construction),
            Self::Solved(_) => None,
        }
    }

    /// Solved carrier retained from the source cache, when this carrier is
    /// procedural.
    #[must_use]
    pub const fn solved_cache(&self) -> Option<&SolvedCurveGeometry> {
        match self {
            Self::Procedural { cache, .. } => cache.as_ref(),
            Self::Solved(_) => None,
        }
    }

    #[cfg(test)]
    pub(crate) const fn solved_cache_mut(&mut self) -> Option<&mut SolvedCurveGeometry> {
        match self {
            Self::Procedural { cache, .. } => cache.as_mut(),
            Self::Solved(_) => None,
        }
    }

    /// Geometry that evaluates this carrier without following a construction.
    #[must_use]
    pub const fn solved(&self) -> Option<&SolvedCurveGeometry> {
        match self {
            Self::Procedural { cache, .. } => cache.as_ref(),
            Self::Solved(geometry) => Some(geometry),
        }
    }
}

/// Non-empty ordered child uses of a composite curve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "Vec<CompositeCurveSegment>")]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct CompositeCurveSegments(Vec<CompositeCurveSegment>);

impl TryFrom<Vec<CompositeCurveSegment>> for CompositeCurveSegments {
    type Error = &'static str;

    fn try_from(segments: Vec<CompositeCurveSegment>) -> Result<Self, Self::Error> {
        if segments.is_empty() {
            return Err("composite curve segments must not be empty");
        }
        Ok(Self(segments))
    }
}

impl std::ops::Deref for CompositeCurveSegments {
    type Target = [CompositeCurveSegment];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for CompositeCurveSegments {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a> IntoIterator for &'a CompositeCurveSegments {
    type Item = &'a CompositeCurveSegment;
    type IntoIter = std::slice::Iter<'a, CompositeCurveSegment>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

/// One directed child use in a composite curve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CompositeCurveSegment {
    /// Referenced child curve carrier.
    pub curve: CurveId,
    /// Whether the child parameter direction is retained.
    pub same_sense: bool,
    /// Required continuity from the preceding segment to this segment.
    pub transition: CompositeCurveTransition,
}

/// STEP composite-curve transition continuity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum CompositeCurveTransition {
    /// No positional continuity is asserted.
    Discontinuous,
    /// Positional continuity.
    Continuous,
    /// Positional and tangent continuity.
    ContSameGradient,
    /// Positional, tangent, and curvature continuity.
    ContSameGradientSameCurvature,
}

/// Derive a stable in-plane reference direction from an axis.
///
/// The least-aligned global basis axis is projected onto the plane normal to
/// `axis`, then normalized. Degenerate axes fall back to global x.
pub fn derive_reference_direction(axis: Vector3) -> Vector3 {
    let norm = axis.norm();
    let axis = if norm.is_finite() && norm != 0.0 {
        Vector3::new(axis.x / norm, axis.y / norm, axis.z / norm)
    } else if let Some(unit) = crate::features::FiniteVector3::new(axis)
        .and_then(crate::features::FiniteVector3::unit_nonzero)
    {
        unit
    } else {
        return Vector3::new(1.0, 0.0, 0.0);
    };
    let basis = if axis.x.abs() <= axis.y.abs() && axis.x.abs() <= axis.z.abs() {
        Vector3::new(1.0, 0.0, 0.0)
    } else if axis.y.abs() <= axis.z.abs() {
        Vector3::new(0.0, 1.0, 0.0)
    } else {
        Vector3::new(0.0, 0.0, 1.0)
    };
    let dot = axis.x * basis.x + axis.y * basis.y + axis.z * basis.z;
    let projected = Vector3::new(
        basis.x - dot * axis.x,
        basis.y - dot * axis.y,
        basis.z - dot * axis.z,
    );
    let projected_norm = projected.norm();
    Vector3::new(
        projected.x / projected_norm,
        projected.y / projected_norm,
        projected.z / projected_norm,
    )
}

/// A 3D curve carrier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Curve {
    /// Arena id.
    pub id: CurveId,
    /// Curve shape.
    pub geometry: CurveGeometry,
    /// Finite source interval of the carrier, independent of topology trims.
    /// The underlying mathematical curve can still be used outside this interval.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_carrier_parameter_range"
    )]
    pub parameter_range: Option<crate::topology::IncreasingParameterInterval>,
    /// Native source-object identity and effective display metadata.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_source_object"
    )]
    pub source_object: Option<SourceObjectAssociation>,
}

/// Four optional finite parameter bounds retained from one native surface
/// record.
///
/// The positions are the native record's fields. Their meaning is supplied
/// by the owning subtype, so a partial quartet remains valid. `None` in one
/// position means that field was absent in the source record.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "[Option<f64>; 4]", into = "[Option<f64>; 4]")]
pub struct RecordBounds([Option<f64>; 4]);

/// A record-bound quartet contained a non-finite value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("record bounds must contain only finite values")]
pub struct RecordBoundsError;

impl RecordBounds {
    /// Admit a native quartet after checking every present value.
    pub fn try_new(raw: [Option<f64>; 4]) -> Result<Self, RecordBoundsError> {
        if raw.iter().flatten().all(|value| value.is_finite()) {
            Ok(Self(raw))
        } else {
            Err(RecordBoundsError)
        }
    }

    /// Build the quartet `[u_lower, v_lower, u_upper, v_upper]` of a
    /// parameter box: its lower corner, then its upper corner. Every endpoint
    /// of an admitted interval is finite, so nothing is checked.
    #[must_use]
    pub const fn from_corners(
        u: crate::topology::IncreasingParameterInterval,
        v: crate::topology::IncreasingParameterInterval,
    ) -> Self {
        Self([
            Some(u.lower()),
            Some(v.lower()),
            Some(u.upper()),
            Some(v.upper()),
        ])
    }

    /// Build the quartet of four present finite values in the native
    /// record's field order. Every value is finite, so nothing is checked.
    #[must_use]
    pub const fn from_finite([first, second, third, fourth]: [FiniteReal; 4]) -> Self {
        Self([
            Some(first.get()),
            Some(second.get()),
            Some(third.get()),
            Some(fourth.get()),
        ])
    }

    /// Return the admitted quartet. Every present position is finite.
    #[must_use]
    pub const fn get(self) -> [Option<f64>; 4] {
        self.0
    }
}

impl TryFrom<[Option<f64>; 4]> for RecordBounds {
    type Error = RecordBoundsError;

    fn try_from(raw: [Option<f64>; 4]) -> Result<Self, Self::Error> {
        Self::try_new(raw)
    }
}

impl From<RecordBounds> for [Option<f64>; 4] {
    fn from(bounds: RecordBounds) -> Self {
        bounds.get()
    }
}

/// A neutral surface construction linked to the carrier it produces.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ProceduralSurface {
    /// Stable construction identity.
    pub id: ProceduralSurfaceId,
    /// Neutral construction definition, which states its own cache contract.
    definition: ProceduralSurfaceDefinition,
    /// Four optional U/V parameter bounds following the record's subtype
    /// scope. For a procedural extrusion or revolution, the first pair is
    /// the neutral surface-carrier interval; its definition retains the
    /// source directrix interval separately. `None` when the record stores no
    /// bound fields.
    #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
    record_bounds: Option<RecordBounds>,
}

/// Parameter fields carried by exact and loft spline-surface constructions.
// A source states raw scalars; a `LoftSurfacePayload` holds the admitted
// fields, whose scalars are `FiniteReal` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SplineSurfaceParameters<R = f64> {
    /// Ordered semantic U and V intervals in the legacy layout.
    OrderedRanges {
        /// Ordered U and V intervals.
        ranges: [[R; 2]; 2],
    },
    /// Two parameter intervals in a revision-gated layout, each stored as an
    /// ordered `[lo, hi]` pair of optional bounds. For exact and t-spline
    /// surfaces these are the surface's unextended (pre-extension) parameter
    /// ranges; for loft surfaces they are wrap ranges, where a reversed pair
    /// (`lo > hi`) encodes an empty interval (no wrap). `None` is a false
    /// bound-presence flag.
    RevisionRanges {
        /// Two parameter intervals in serialized field order.
        intervals: [[Option<R>; 2]; 2],
    },
}

/// Mutually exclusive legacy and revision-gated exact-spline layouts.
// A source states raw scalars; an `ExactSurfacePayload` holds the admitted
// spline, whose scalars are `FiniteReal` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "layout", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub enum ExactSpline<R = f64> {
    /// Legacy solved-cache layout with ordered U/V ranges.
    Legacy {
        /// Ordered U and V parameter ranges.
        ranges: [[R; 2]; 2],
        /// Native ASM extension integer following the ranges.
        extension: i64,
        /// Solved-cache fit contract this layout states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    /// Revision-gated layout with optional interval bounds and shared form.
    Revision {
        /// Two optional-bound parameter intervals in wire order.
        intervals: [[Option<R>; 2]; 2],
        /// Native ASM extension enum following the intervals.
        extension: i64,
        /// Required revision-gated form.
        form: Box<RevisionSurfaceForm<Vec<bool>, R>>,
    },
}

/// One component and its native construction scalar.
// A source states a raw scalar; a compound construction holds the admitted
// component, whose scalar is a `FiniteReal`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct CompoundComponent<T, R = f64> {
    /// Scalar paired with this component.
    pub parameter: R,
    /// Component geometry or its resolved identity.
    pub component: T,
}

/// A non-empty compound curve with finite construction parameters.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "CompoundCurveConstructionWire")]
pub struct CompoundCurveConstruction {
    parameters: Vec<FiniteReal>,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<CompoundComponent<CurveId>>"))]
    components: Vec<CompoundComponent<CurveId, FiniteReal>>,
    /// Solved-cache fit contract this construction states itself.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_cache"
    )]
    cache: Option<LegacyCache>,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct CompoundCurveConstructionWire {
    /// Finite leading and per-component construction parameters.
    parameters: Vec<f64>,
    /// Component curves in construction order.
    components: Vec<CompoundComponent<CurveId>>,
    /// Solved-cache fit contract this construction states itself.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_cache"
    )]
    cache: Option<LegacyCache>,
}

impl TryFrom<CompoundCurveConstructionWire> for CompoundCurveConstruction {
    type Error = &'static str;
    fn try_from(wire: CompoundCurveConstructionWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.parameters, wire.components, wire.cache)
    }
}

impl CompoundCurveConstruction {
    /// Admit at least one component and finite leading and component parameters.
    pub fn try_new(
        parameters: Vec<f64>,
        components: Vec<CompoundComponent<CurveId>>,
        cache: Option<LegacyCache>,
    ) -> Result<Self, &'static str> {
        const INVALID: &str = "compound curve parameters must be finite";
        if components.is_empty() {
            return Err("compound curve components must not be empty");
        }
        let [parameters] = FiniteReal::lanes([parameters]).ok_or(INVALID)?;
        let components = components
            .into_iter()
            .map(CompoundComponent::admit)
            .collect::<Option<Vec<_>>>()
            .ok_or(INVALID)?;
        Ok(Self {
            parameters,
            components,
            cache,
        })
    }

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

    /// Return the components.
    #[must_use]
    pub fn components(&self) -> &[CompoundComponent<CurveId, FiniteReal>] {
        &self.components
    }
}

/// Neutral semantics for a procedural surface.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ProceduralSurfaceDefinition {
    /// Exact native NURBS surface with retained parameter fields.
    Exact(surface_payloads::ExactSurfacePayload),
    /// Ordered native compound of a solved surface and component surfaces.
    Compound(surface_payloads::CompoundSurfacePayload),
    /// Exact rectangular restriction of an embedded support surface.
    SubSurface(surface_payloads::SubSurfaceConstruction),
    /// Taper of a support surface around a reference curve.
    Taper(surface_payloads::TaperSurfaceConstruction),
    /// Native loft defined by two section graphs and closure contracts.
    Loft(surface_payloads::LoftSurfacePayload),
    /// Native compound-loft construction.
    CompoundLoft(surface_payloads::CompoundLoftSurfacePayload),
    /// Revision-gated compound-loft construction.
    RevisionCompoundLoft {
        /// Complete native revision-gated compound-loft graph.
        construction: Box<RevisionCompoundLoftConstruction>,
    },
    /// Native scaled compound-loft construction.
    ScaledCompoundLoft(surface_payloads::ScaledCompoundLoftSurfacePayload),
    /// Native skinned spline surface.
    Skin(surface_payloads::SkinSurfacePayload),
    /// Native surface defined by recursive law formulas.
    Law(surface_payloads::LawSurfacePayload),
    /// Native curve-network spline surface.
    Net(surface_payloads::NetSurfacePayload),
    /// Native curvature-continuous two-sided blend.
    G2Blend(surface_payloads::G2BlendSurfacePayload),
    /// Revision-gated curvature-continuous blend in the variable-blend side
    /// layout.
    RevisionG2Blend {
        /// Complete native revision-gated G2 construction graph.
        construction: Box<RevisionG2BlendConstruction>,
    },
    /// Native variable-radius two-sided blend.
    VariableBlend(surface_payloads::VariableBlendSurfacePayload),
    /// Native vertex-blend patch.
    VertexBlend(surface_payloads::VertexBlendSurfacePayload),
    /// Translation of a directrix along a direction.
    Extrusion(surface_payloads::ExtrusionSurfaceConstruction),
    /// Unbounded linear sweep of a directrix.
    LinearSweep(surface_payloads::LinearSweepSurfaceConstruction),
    /// Revolution of a directrix about an axis.
    Revolution(surface_payloads::RevolutionSurfaceConstruction),
    /// Full revolution of a directrix about an axis.
    AxisRevolution(surface_payloads::AxisRevolutionSurfaceConstruction),
    /// Sum of two ordered curves from a base point.
    Sum(surface_payloads::SumSurfaceConstruction),
    /// Sweep of a profile along a spine.
    Sweep(surface_payloads::SweepSurfacePayload),
    /// T-spline face with its shared subtransform program.
    TSpline {
        /// Complete native T-spline wrapper construction.
        construction: Box<TSplineSurfaceConstruction>,
    },
    /// Surface generated along an inline circular or linear helix path.
    Helix {
        /// Complete native helix-surface construction.
        construction: Box<HelixSurfaceConstruction>,
    },
    /// Native deformable spline surface.
    Deformable(surface_payloads::DeformableSurfacePayload),
    /// Offset from a support surface.
    Offset(surface_payloads::OffsetSurfaceConstruction),
    /// Rectangular parameter sub-range of a support surface.
    Subset(surface_payloads::SubsetSurfaceConstruction),
    /// Affine replica of a surface carrier, retaining the parent surface
    /// construction and its parameter domain.
    Replica {
        /// Surface being replicated.
        source: SurfaceId,
        /// Affine map from the parent surface coordinates to this surface.
        transform: Transform,
    },
    /// Parallel offset from a support surface.
    ParallelOffset(surface_payloads::ParallelOffsetSurfaceConstruction),
    /// Self-intersecting torus with an explicitly selected outer or inner sheet.
    DegenerateTorus {
        /// Whether the outer sheet is selected at the self-intersection.
        select_outer: bool,
    },
    /// Surface domain bounded by ordered curves on a supporting surface.
    CurveBounded {
        /// Supporting surface whose parameterization defines the domain.
        support: SurfaceId,
        /// Boundary curves on the support.
        boundaries: Vec<CurveId>,
        /// Parameter-space carriers used by surface-curve boundary segments.
        ///
        /// These are separate from `boundaries`: one STEP surface curve can
        /// carry both a model-space curve and pcurves on the support surface.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        boundary_pcurves: Vec<PcurveId>,
        /// Whether the support's natural outer boundary is implicit.
        implicit_outer: bool,
    },
    /// Ruled surface joining two directrices.
    Ruled {
        /// First bounding curve of the ruled surface.
        first: CurveId,
        /// Second bounding curve of the ruled surface.
        second: CurveId,
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
    /// Rolling-ball or law-driven blend between two support surfaces.
    Blend(surface_payloads::BlendSurfacePayload),
    /// Rolling-ball surface defined by aligned quintic value/derivative jets.
    RollingBallJet(RollingBallJetStations),
    /// Preserved construction without a neutral interpretation.
    Unknown {
        /// Reference to the preserved raw source record, when retained.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        record: Option<UnknownId>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
}

#[derive(Deserialize)]
#[serde(
    remote = "ProceduralSurfaceDefinition",
    tag = "kind",
    rename_all = "snake_case",
    deny_unknown_fields
)]
enum ProceduralSurfaceDefinitionWire {
    Exact(surface_payloads::ExactSurfacePayload),
    Compound(surface_payloads::CompoundSurfacePayload),
    SubSurface(surface_payloads::SubSurfaceConstruction),
    Taper(surface_payloads::TaperSurfaceConstruction),
    Loft(surface_payloads::LoftSurfacePayload),
    CompoundLoft(surface_payloads::CompoundLoftSurfacePayload),
    RevisionCompoundLoft {
        construction: Box<RevisionCompoundLoftConstruction>,
    },
    ScaledCompoundLoft(surface_payloads::ScaledCompoundLoftSurfacePayload),
    Skin(surface_payloads::SkinSurfacePayload),
    Law(surface_payloads::LawSurfacePayload),
    Net(surface_payloads::NetSurfacePayload),
    G2Blend(surface_payloads::G2BlendSurfacePayload),
    RevisionG2Blend {
        construction: Box<RevisionG2BlendConstruction>,
    },
    VariableBlend(surface_payloads::VariableBlendSurfacePayload),
    VertexBlend(surface_payloads::VertexBlendSurfacePayload),
    Extrusion(surface_payloads::ExtrusionSurfaceConstruction),
    LinearSweep(surface_payloads::LinearSweepSurfaceConstruction),
    Revolution(surface_payloads::RevolutionSurfaceConstruction),
    AxisRevolution(surface_payloads::AxisRevolutionSurfaceConstruction),
    Sum(surface_payloads::SumSurfaceConstruction),
    Sweep(surface_payloads::SweepSurfacePayload),
    TSpline {
        construction: Box<TSplineSurfaceConstruction>,
    },
    Helix {
        construction: Box<HelixSurfaceConstruction>,
    },
    Deformable(surface_payloads::DeformableSurfacePayload),
    Offset(surface_payloads::OffsetSurfaceConstruction),
    Subset(surface_payloads::SubsetSurfaceConstruction),
    Replica {
        source: SurfaceId,
        transform: Transform,
    },
    ParallelOffset(surface_payloads::ParallelOffsetSurfaceConstruction),
    DegenerateTorus {
        select_outer: bool,
    },
    CurveBounded {
        support: SurfaceId,
        boundaries: Vec<CurveId>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        boundary_pcurves: Vec<PcurveId>,
        implicit_outer: bool,
    },
    Ruled {
        first: CurveId,
        second: CurveId,
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    Blend(surface_payloads::BlendSurfacePayload),
    RollingBallJet(RollingBallJetStations),
    Unknown {
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_record"
        )]
        record: Option<UnknownId>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
}

impl<'de> Deserialize<'de> for ProceduralSurfaceDefinition {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        ProceduralSurfaceDefinitionWire::deserialize(deserializer)
    }
}

impl ProceduralSurfaceDefinition {
    fn revision_cache(
        &self,
    ) -> Option<&RevisionCacheForm<RevisionSurfaceParameterization<FiniteReal>>> {
        match self {
            Self::Exact(payload) => payload.revision_cache(),
            Self::Taper(definition_payload) => {
                let revision_form = definition_payload.revision_form();
                revision_form.as_ref().map(|form| &form.cache)
            }
            Self::Extrusion(definition_payload) => {
                let revision_form = definition_payload.revision_form();
                revision_form.as_ref().map(|form| &form.cache)
            }
            Self::Revolution(definition_payload) => {
                let revision_form = definition_payload.revision_form();
                revision_form.as_ref().map(|form| &form.cache)
            }
            Self::Sum(payload) => payload.revision_form().map(|form| &form.cache),
            Self::Offset(payload) => match payload.extension() {
                OffsetExtension::Revision { form } => Some(&form.cache),
                OffsetExtension::Legacy { .. } => None,
            },
            Self::Loft(payload) => payload.revision_cache(),
            Self::RevisionCompoundLoft { construction } => Some(&construction.cache),
            Self::RevisionG2Blend { construction } => Some(&construction.cache),
            Self::Sweep(payload) => payload.revision_cache(),
            Self::TSpline { construction } => construction.cache.form().map(|form| &form.cache),
            Self::Deformable(payload) => payload.revision_cache(),
            Self::Blend(payload) => payload.revision_cache(),
            Self::Compound(_)
            | Self::SubSurface(_)
            | Self::CompoundLoft(_)
            | Self::ScaledCompoundLoft(_)
            | Self::Skin(_)
            | Self::Law(_)
            | Self::Net(_)
            | Self::G2Blend(_)
            | Self::VariableBlend(_)
            | Self::VertexBlend(_)
            | Self::LinearSweep(_)
            | Self::AxisRevolution(_)
            | Self::Helix { .. }
            | Self::Subset(_)
            | Self::Replica { .. }
            | Self::ParallelOffset(_)
            | Self::DegenerateTorus { .. }
            | Self::CurveBounded { .. }
            | Self::Ruled { .. }
            | Self::RollingBallJet(_)
            | Self::Unknown { .. } => None,
        }
    }

    /// Write the fit tolerance of the revision-gated solved cache.
    ///
    /// The narrow write route: the borrow of the cache form stays inside this
    /// method, so no construction lends its admitted interior for writing.
    fn write_revision_fit_tolerance(&mut self, write: ToleranceWrite) -> RevisionCacheWrite {
        match self {
            Self::Exact(payload) => payload.write_revision_fit_tolerance(write),
            Self::Taper(payload) => payload.write_revision_fit_tolerance(write),
            Self::Extrusion(payload) => payload.write_revision_fit_tolerance(write),
            Self::Revolution(payload) => payload.write_revision_fit_tolerance(write),
            Self::Sum(payload) => payload.write_revision_fit_tolerance(write),
            Self::Offset(payload) => payload.write_revision_fit_tolerance(write),
            Self::Loft(payload) => payload.write_revision_fit_tolerance(write),
            Self::RevisionCompoundLoft { construction } => {
                construction.cache.write_fit_tolerance(write)
            }
            Self::RevisionG2Blend { construction } => construction.cache.write_fit_tolerance(write),
            Self::Sweep(payload) => payload.write_revision_fit_tolerance(write),
            Self::TSpline { construction } => write_revision_form_tolerance(
                construction.cache.form_mut().map(|form| &mut form.cache),
                write,
            ),
            Self::Deformable(payload) => payload.write_revision_fit_tolerance(write),
            Self::Blend(payload) => payload.write_revision_fit_tolerance(write),
            Self::Compound(_)
            | Self::SubSurface(_)
            | Self::CompoundLoft(_)
            | Self::ScaledCompoundLoft(_)
            | Self::Skin(_)
            | Self::Law(_)
            | Self::Net(_)
            | Self::G2Blend(_)
            | Self::VariableBlend(_)
            | Self::VertexBlend(_)
            | Self::LinearSweep(_)
            | Self::AxisRevolution(_)
            | Self::Helix { .. }
            | Self::Subset(_)
            | Self::Replica { .. }
            | Self::ParallelOffset(_)
            | Self::DegenerateTorus { .. }
            | Self::CurveBounded { .. }
            | Self::Ruled { .. }
            | Self::RollingBallJet(_)
            | Self::Unknown { .. } => RevisionCacheWrite::NoForm,
        }
    }

    /// Whether the construction owns a revision-gated cache form, which then
    /// states its solved-cache fit tolerance.
    #[must_use]
    pub fn owns_revision_cache(&self) -> bool {
        self.revision_cache().is_some() || matches!(self, Self::VariableBlend(..))
    }
}

/// What a write to a revision-gated cache form found.
enum RevisionCacheWrite {
    /// The form states a solved cache, whose tolerance the write states.
    Written,
    /// The form states a parameterization, which has no solved cache.
    Parameterized,
    /// The construction owns no revision-gated cache form.
    NoForm,
    /// Scaling the held tolerance overflowed.
    InvalidValue(f64),
}

impl RevisionCacheWrite {
    /// The outcome the fit-tolerance setter states for this write.
    const fn into_set_result(self) -> Result<(), CacheContractError> {
        match self {
            Self::Written => Ok(()),
            Self::Parameterized => Err(CacheContractError::Parameterized),
            Self::NoForm => Err(CacheContractError::Layout(NO_LEGACY_SLOT)),
            Self::InvalidValue(value) => Err(CacheContractError::InvalidValue { value }),
        }
    }
}

/// Whether a tolerance write states the value or only raises to it.
#[derive(Clone, Copy)]
enum ToleranceWrite {
    /// State the value in place of the tolerance the form carries.
    State(FitTolerance),
    /// Keep the tolerance the form carries unless the value exceeds it.
    Raise(FitTolerance),
    /// Scale the tolerance already carried by a solved cache.
    Scale(crate::scalar::PositiveReal),
}

/// State the fit tolerance of an optional solved cache form.
fn write_revision_form_tolerance<P>(
    form: Option<&mut RevisionCacheForm<P>>,
    write: ToleranceWrite,
) -> RevisionCacheWrite {
    form.map_or(RevisionCacheWrite::NoForm, |form| {
        form.write_fit_tolerance(write)
    })
}

/// The outcome of clearing the fit tolerance of a revision-gated cache form: a
/// solved cache cannot lose the tolerance it states, and a parameterized form
/// states none to lose.
const fn clear_revision_form_tolerance<P>(
    form: Option<&RevisionCacheForm<P>>,
) -> Result<(), CacheContractError> {
    match form {
        Some(RevisionCacheForm::SolvedCache { .. }) => Err(CacheContractError::MissingSolved),
        Some(RevisionCacheForm::Parameterization(_)) | None => Ok(()),
    }
}

/// A finite, non-negative fit tolerance.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "f64", into = "f64")]
pub struct FitTolerance(f64);

impl FitTolerance {
    /// A zero fit tolerance.
    pub const ZERO: Self = Self(0.0);

    /// Admit a finite, non-negative fit tolerance.
    pub fn try_new(value: f64) -> Result<Self, CacheContractError> {
        if value.is_finite() && value >= 0.0 {
            Ok(Self(value))
        } else {
            Err(CacheContractError::InvalidValue { value })
        }
    }

    /// The fit tolerance in carrier units.
    #[must_use]
    pub const fn get(self) -> f64 {
        self.0
    }

    /// The tolerance times `scale`.
    ///
    /// A positive scale keeps the sign of a non-negative tolerance: zero
    /// stays zero, and rounding does not change a sign. The product is
    /// refused only when it overflows.
    #[must_use]
    pub fn scaled(self, scale: crate::scalar::PositiveReal) -> Option<Self> {
        let value = self.0 * scale.get();
        value.is_finite().then_some(Self(value))
    }
}

impl TryFrom<f64> for FitTolerance {
    type Error = CacheContractError;

    fn try_from(value: f64) -> Result<Self, Self::Error> {
        Self::try_new(value)
    }
}

impl From<FitTolerance> for f64 {
    fn from(value: FitTolerance) -> Self {
        value.get()
    }
}

/// A fit tolerance admits exactly the finite, non-negative values.
impl From<NonNegativeReal> for FitTolerance {
    fn from(value: NonNegativeReal) -> Self {
        Self(value.get())
    }
}

/// Fit contract of a solved cache that the construction states itself, used by
/// constructions with no revision-gated [`RevisionCacheForm`].
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LegacyCache {
    /// Fit tolerance of the solved cache.
    pub fit_tolerance: FitTolerance,
}

impl LegacyCache {
    /// A legacy cache with this fit tolerance.
    #[must_use]
    pub const fn new(fit_tolerance: FitTolerance) -> Self {
        Self { fit_tolerance }
    }

    /// A legacy cache stating an admissible fit tolerance.
    pub fn try_new(fit_tolerance: f64) -> Result<Self, CacheContractError> {
        FitTolerance::try_new(fit_tolerance).map(Self::new)
    }
}

/// The cache contract of a construction that has both a legacy and a
/// revision-gated layout: the tolerance is stated in exactly one of them.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "layout", rename_all = "snake_case", deny_unknown_fields)]
pub enum CacheContract<F> {
    /// Legacy layout, which states its own solved-cache tolerance.
    Legacy {
        /// Solved-cache fit contract, absent when the record stated none.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    /// Revision-gated layout, which states the tolerance in its cache form.
    Revision {
        /// Revision-gated form.
        form: F,
    },
}

impl<F> CacheContract<F> {
    /// A legacy layout with no solved-cache tolerance.
    #[must_use]
    pub const fn legacy() -> Self {
        Self::Legacy { cache: None }
    }

    /// The contract an optional revision-gated form states.
    #[must_use]
    pub fn from_form(form: Option<F>) -> Self {
        match form {
            Some(form) => Self::Revision { form },
            None => Self::legacy(),
        }
    }

    /// The revision-gated form, absent in the legacy layout.
    #[must_use]
    pub const fn form(&self) -> Option<&F> {
        match self {
            Self::Revision { form } => Some(form),
            Self::Legacy { .. } => None,
        }
    }

    /// Mutable revision-gated form, absent in the legacy layout.
    pub const fn form_mut(&mut self) -> Option<&mut F> {
        match self {
            Self::Revision { form } => Some(form),
            Self::Legacy { .. } => None,
        }
    }

    /// The legacy solved-cache tolerance, absent in the revision layout.
    #[must_use]
    pub const fn legacy_fit_tolerance(&self) -> Option<FitTolerance> {
        match self {
            Self::Legacy { cache: Some(cache) } => Some(cache.fit_tolerance),
            Self::Legacy { cache: None } | Self::Revision { .. } => None,
        }
    }

    /// Mutable legacy solved-cache slot, absent in the revision layout.
    const fn legacy_cache_mut(&mut self) -> Option<&mut Option<LegacyCache>> {
        match self {
            Self::Legacy { cache } => Some(cache),
            Self::Revision { .. } => None,
        }
    }
}

impl<F> CacheContract<F> {
    /// Whether this is the legacy layout with no stated tolerance, which is
    /// what a record that states neither carries.
    #[must_use]
    pub const fn is_bare_legacy(&self) -> bool {
        matches!(self, Self::Legacy { cache: None })
    }
}

impl<F> Default for CacheContract<F> {
    fn default() -> Self {
        Self::legacy()
    }
}

/// A fit tolerance, or the cache contract that states it, is not admissible.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum CacheContractError {
    /// A fit tolerance is negative or non-finite.
    #[error("fit_tolerance must be finite and non-negative, got {value}")]
    InvalidValue {
        /// Rejected tolerance.
        value: f64,
    },
    /// A parameterized cache form states no solved-cache tolerance.
    #[error("a parameterized cache form states no fit tolerance")]
    Parameterized,
    /// A solved cache form cannot lose its required tolerance.
    #[error("a solved cache form states a fit tolerance")]
    MissingSolved,
    /// The construction's layout states no solved-cache tolerance.
    #[error("{0}")]
    Layout(&'static str),
}

impl From<CacheContractError> for cadmpeg_core::CodecError {
    fn from(error: CacheContractError) -> Self {
        Self::Malformed(error.to_string())
    }
}

/// A rejected procedural definition or cache contract.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum ProceduralGeometryError {
    /// A local construction field violates its numeric contract.
    #[error("{0}")]
    Payload(&'static str),
    /// The cache contract is invalid for the definition.
    #[error(transparent)]
    Cache(#[from] CacheContractError),
    /// A member list violates its member contract.
    #[error(transparent)]
    Members(#[from] crate::features::BodySelectionError),
}

/// A construction whose layout states no solved-cache fit tolerance.
const NO_LEGACY_SLOT: &str = "this construction states no solved-cache fit tolerance";

const PARAMETERIZED_NO_SOLVED_CACHE: &str =
    "a parameterized cache form takes no solved-cache fit tolerance";

/// A construction whose layout always states one.
const REQUIRED_LEGACY_SLOT: &str = "this construction states a solved-cache fit tolerance";

/// The legacy solved-cache slot of one surface construction, borrowed for
/// writing.
///
/// A layout that may omit the cache lends `Optional`; a layout that always
/// states one lends `Required`, which is why losing the cache is the one
/// refusal a slot makes. Surface-only: `ProceduralCurveDefinition` has no
/// `Required` slot, so a curve lends its slot as a plain
/// `&mut Option<LegacyCache>`.
enum LegacyCacheSlot<'a> {
    /// Slot of a layout whose record may state no cache.
    Optional(&'a mut Option<LegacyCache>),
    /// Slot of a layout that always states a cache.
    Required(&'a mut LegacyCache),
}

impl LegacyCacheSlot<'_> {
    /// Replace the cache the slot holds.
    const fn set(&mut self, cache: Option<LegacyCache>) -> Result<(), CacheContractError> {
        match (self, cache) {
            (Self::Optional(slot), cache) => {
                **slot = cache;
                Ok(())
            }
            (Self::Required(slot), Some(cache)) => {
                **slot = cache;
                Ok(())
            }
            (Self::Required(_), None) => Err(CacheContractError::Layout(REQUIRED_LEGACY_SLOT)),
        }
    }

    /// Scale the tolerance held by this slot, if the optional cache is present.
    fn scale_fit_tolerance(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), CacheContractError> {
        let cache = match self {
            Self::Optional(slot) => slot.as_mut(),
            Self::Required(cache) => Some(&mut **cache),
        };
        if let Some(cache) = cache {
            let value = cache.fit_tolerance;
            cache.fit_tolerance =
                value
                    .scaled(scale)
                    .ok_or_else(|| CacheContractError::InvalidValue {
                        value: value.get() * scale.get(),
                    })?;
        }
        Ok(())
    }
}

impl ProceduralSurfaceDefinition {
    /// Solved-cache fit contract this construction states outside a
    /// revision-gated cache form.
    #[must_use]
    pub fn legacy_cache(&self) -> Option<LegacyCache> {
        match self {
            Self::Exact(payload) => payload.legacy_cache(),
            Self::Compound(payload) => payload.legacy_cache(),
            Self::Taper(payload) => payload.legacy_cache(),
            Self::Loft(payload) => payload.legacy_cache(),
            Self::CompoundLoft(payload) => payload.legacy_cache(),
            Self::ScaledCompoundLoft(payload) => payload.legacy_cache(),
            Self::Skin(payload) => payload.legacy_cache(),
            Self::Law(payload) => payload.legacy_cache(),
            Self::Net(payload) => payload.legacy_cache(),
            Self::G2Blend(payload) => payload.legacy_cache(),
            Self::Extrusion(payload) => payload.legacy_cache(),
            Self::Revolution(payload) => payload.legacy_cache(),
            Self::Sum(payload) => payload.legacy_cache(),
            Self::Sweep(payload) => payload.legacy_cache(),
            Self::TSpline { construction } => construction.legacy_cache(),
            Self::Deformable(payload) => payload.legacy_cache(),
            Self::Offset(payload) => payload.legacy_cache(),
            Self::Subset(payload) => payload.legacy_cache(),
            Self::Blend(payload) => payload.legacy_cache(),
            Self::Ruled { cache, .. } | Self::Unknown { cache, .. } => *cache,
            Self::SubSurface(_)
            | Self::RevisionCompoundLoft { .. }
            | Self::RevisionG2Blend { .. }
            | Self::VariableBlend(_)
            | Self::VertexBlend(_)
            | Self::LinearSweep(_)
            | Self::AxisRevolution(_)
            | Self::Helix { .. }
            | Self::Replica { .. }
            | Self::ParallelOffset(_)
            | Self::DegenerateTorus { .. }
            | Self::CurveBounded { .. }
            | Self::RollingBallJet(_) => None,
        }
    }

    /// Mutable legacy solved-cache slot of this construction, absent when the
    /// layout states none.
    ///
    /// The one write route to the legacy cache: both the setter and the raise
    /// go through it, so a construction cannot answer them differently.
    fn legacy_cache_slot_mut(&mut self) -> Option<LegacyCacheSlot<'_>> {
        match self {
            Self::Exact(payload) => payload.legacy_cache_slot_mut(),
            Self::Compound(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::Taper(payload) => payload.legacy_cache_slot_mut(),
            Self::Loft(payload) => payload.legacy_cache_slot_mut(),
            Self::CompoundLoft(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::ScaledCompoundLoft(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::Skin(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::Law(payload) => payload.legacy_cache_slot_mut(),
            Self::Net(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::G2Blend(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::Extrusion(payload) => payload.legacy_cache_slot_mut(),
            Self::Revolution(payload) => payload.legacy_cache_slot_mut(),
            Self::Sum(payload) => payload.legacy_cache_slot_mut(),
            Self::Sweep(payload) => payload.legacy_cache_slot_mut(),
            Self::TSpline { construction } => construction.legacy_cache_slot_mut(),
            Self::Deformable(payload) => payload.legacy_cache_slot_mut(),
            Self::Offset(payload) => payload.legacy_cache_slot_mut(),
            Self::Subset(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::Blend(payload) => payload.legacy_cache_slot_mut(),
            Self::Ruled { cache, .. } | Self::Unknown { cache, .. } => {
                Some(LegacyCacheSlot::Optional(cache))
            }
            Self::SubSurface(_)
            | Self::RevisionCompoundLoft { .. }
            | Self::RevisionG2Blend { .. }
            | Self::VariableBlend(_)
            | Self::VertexBlend(_)
            | Self::LinearSweep(_)
            | Self::AxisRevolution(_)
            | Self::Helix { .. }
            | Self::Replica { .. }
            | Self::ParallelOffset(_)
            | Self::DegenerateTorus { .. }
            | Self::CurveBounded { .. }
            | Self::RollingBallJet(_) => None,
        }
    }

    /// State or clear the legacy solved-cache fit contract.
    ///
    /// Fallible in both directions, because a surface construction can hold a
    /// cache it cannot lose. A layout that states none refuses `Some`, and a
    /// `LawSurfaceTail::Full` tail, whose `Required` slot always states a
    /// tolerance, refuses `None`.
    pub fn set_legacy_cache(
        &mut self,
        cache: Option<LegacyCache>,
    ) -> Result<(), CacheContractError> {
        match self.legacy_cache_slot_mut() {
            Some(mut slot) => slot.set(cache),
            None => cache.map_or(Ok(()), |_| Err(CacheContractError::Layout(NO_LEGACY_SLOT))),
        }
    }

    /// Effective fit tolerance of the solved cache: a revision-gated form
    /// states it in its cache form, a legacy layout in the cache it holds.
    #[must_use]
    pub fn cache_fit_tolerance(&self) -> Option<FitTolerance> {
        if let Self::VariableBlend(payload) = self {
            return payload.construction().cache.fit_tolerance();
        }
        match self.revision_cache() {
            Some(RevisionCacheForm::SolvedCache { fit_tolerance }) => Some(*fit_tolerance),
            Some(RevisionCacheForm::Parameterization(_)) => None,
            None => self.legacy_cache().map(|cache| cache.fit_tolerance),
        }
    }

    /// Change the effective fit tolerance without permitting a parameterized
    /// cache to acquire one or a solved cache to lose it.
    pub fn set_cache_fit_tolerance(
        &mut self,
        value: Option<FitTolerance>,
    ) -> Result<(), CacheContractError> {
        if let Self::VariableBlend(payload) = self {
            return payload.write_cache_fit_tolerance(value);
        }
        if self.owns_revision_cache() {
            return match value {
                Some(value) => self
                    .write_revision_fit_tolerance(ToleranceWrite::State(value))
                    .into_set_result(),
                None => clear_revision_form_tolerance(self.revision_cache()),
            };
        }
        self.set_legacy_cache(value.map(LegacyCache::new))
    }

    /// Scale only the fit tolerance already carried by this construction.
    fn scale_cache_fit_tolerance(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), CacheContractError> {
        if let Self::VariableBlend(payload) = self {
            return payload.scale_cache_fit_tolerance(scale);
        }
        match self.write_revision_fit_tolerance(ToleranceWrite::Scale(scale)) {
            RevisionCacheWrite::Written | RevisionCacheWrite::Parameterized => Ok(()),
            RevisionCacheWrite::NoForm => self
                .legacy_cache_slot_mut()
                .map_or(Ok(()), |mut slot| slot.scale_fit_tolerance(scale)),
            RevisionCacheWrite::InvalidValue(value) => {
                Err(CacheContractError::InvalidValue { value })
            }
        }
    }
}

impl ProceduralCurveDefinition {
    /// Solved-cache fit contract this construction states outside a
    /// revision-gated cache form.
    #[must_use]
    pub fn legacy_cache(&self) -> Option<LegacyCache> {
        match self {
            Self::Compound(construction) => construction.legacy_cache(),
            Self::Helix(construction) => construction.legacy_cache(),
            Self::Subset(payload) => payload.legacy_cache(),
            Self::VectorOffset(payload) => payload.legacy_cache(),
            Self::TwoSidedOffset(payload) => payload.legacy_cache(),
            Self::Spring(payload) => payload.legacy_cache(),
            Self::SurfaceOffset(payload) => payload.legacy_cache(),
            Self::Exact { cache }
            | Self::Law { cache, .. }
            | Self::Intersection { cache, .. }
            | Self::TolerantIntersection { cache, .. }
            | Self::Unknown { cache, .. } => *cache,
            Self::ThreeSurfaceIntersection(_)
            | Self::SurfaceCurve { .. }
            | Self::Silhouette(_)
            | Self::Deformable(_)
            | Self::Projection(_)
            | Self::Offset(_)
            | Self::SpatialOffset(_)
            | Self::Replica { .. }
            | Self::BlendSpine { .. } => None,
        }
    }

    /// Mutable legacy solved-cache slot of this construction, absent when the
    /// layout states none.
    ///
    /// The one write route to the legacy cache: the setter, the clear and the
    /// raise go through it, so a construction cannot answer them differently.
    /// No curve construction holds a cache it cannot lose, so the slot is a
    /// plain `&mut Option<LegacyCache>` and `LegacyCacheSlot` is surface-only.
    fn legacy_cache_slot_mut(&mut self) -> Option<&mut Option<LegacyCache>> {
        match self {
            Self::Compound(construction) => Some(construction.legacy_cache_slot_mut()),
            Self::Helix(construction) => Some(construction.legacy_cache_slot_mut()),
            Self::Subset(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::VectorOffset(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::TwoSidedOffset(payload) => Some(payload.legacy_cache_slot_mut()),
            Self::Spring(payload) => payload.legacy_cache_slot_mut(),
            Self::SurfaceOffset(payload) => payload.legacy_cache_slot_mut(),
            Self::Exact { cache }
            | Self::Law { cache, .. }
            | Self::Intersection { cache, .. }
            | Self::TolerantIntersection { cache, .. }
            | Self::Unknown { cache, .. } => Some(cache),
            Self::ThreeSurfaceIntersection(_)
            | Self::SurfaceCurve { .. }
            | Self::Silhouette(_)
            | Self::Deformable(_)
            | Self::Projection(_)
            | Self::Offset(_)
            | Self::SpatialOffset(_)
            | Self::Replica { .. }
            | Self::BlendSpine { .. } => None,
        }
    }

    /// State the legacy solved-cache fit contract. A construction whose
    /// layout states none refuses a contract.
    pub fn set_legacy_cache(&mut self, cache: LegacyCache) -> Result<(), CacheContractError> {
        match self.legacy_cache_slot_mut() {
            Some(slot) => {
                *slot = Some(cache);
                Ok(())
            }
            None => Err(CacheContractError::Layout(NO_LEGACY_SLOT)),
        }
    }

    /// Clear the legacy solved-cache fit contract.
    ///
    /// Total: a construction with a slot loses the contract it states, and a
    /// construction with no slot has none to lose. No curve construction holds
    /// a cache it cannot lose, so this refuses nothing.
    pub fn clear_legacy_cache(&mut self) {
        if let Some(slot) = self.legacy_cache_slot_mut() {
            *slot = None;
        }
    }

    /// Effective fit tolerance of the solved cache.
    #[must_use]
    pub fn cache_fit_tolerance(&self) -> Option<FitTolerance> {
        match self.revision_cache() {
            Some(RevisionCacheForm::SolvedCache { fit_tolerance }) => Some(*fit_tolerance),
            Some(RevisionCacheForm::Parameterization(_)) => None,
            None => self.legacy_cache().map(|cache| cache.fit_tolerance),
        }
    }

    /// Change the effective fit tolerance without permitting a parameterized
    /// cache to acquire one or a solved cache to lose it.
    pub fn set_cache_fit_tolerance(
        &mut self,
        value: Option<FitTolerance>,
    ) -> Result<(), CacheContractError> {
        if self.owns_revision_cache() {
            return match value {
                Some(value) => self
                    .write_revision_fit_tolerance(ToleranceWrite::State(value))
                    .into_set_result(),
                None => clear_revision_form_tolerance(self.revision_cache()),
            };
        }
        match value {
            Some(value) => self.set_legacy_cache(LegacyCache::new(value)),
            None => {
                self.clear_legacy_cache();
                Ok(())
            }
        }
    }

    /// Scale only the fit tolerance already carried by this construction.
    fn scale_cache_fit_tolerance(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), CacheContractError> {
        match self.write_revision_fit_tolerance(ToleranceWrite::Scale(scale)) {
            RevisionCacheWrite::Written | RevisionCacheWrite::Parameterized => Ok(()),
            RevisionCacheWrite::NoForm => {
                if let Some(Some(cache)) = self.legacy_cache_slot_mut() {
                    let value = cache.fit_tolerance;
                    cache.fit_tolerance =
                        value
                            .scaled(scale)
                            .ok_or_else(|| CacheContractError::InvalidValue {
                                value: value.get() * scale.get(),
                            })?;
                }
                Ok(())
            }
            RevisionCacheWrite::InvalidValue(value) => {
                Err(CacheContractError::InvalidValue { value })
            }
        }
    }

    /// State that a solved carrier of this construction was fitted to `value`,
    /// raising an existing contract rather than lowering it.
    ///
    /// Answers every layout. A construction whose legacy slot is empty takes
    /// the contract; one that already carries a cache raises it; a solved
    /// revision cache raises its own tolerance. A parameterized form and a
    /// layout that states no slot have no solved cache to state, so they
    /// refuse: a caller that asked for a solved cache never gets a silent
    /// nothing. The write goes through `legacy_cache_slot_mut`, the one write
    /// route to the slot, so a construction cannot answer it differently from
    /// the setter and the clear.
    pub fn require_cache_fit_tolerance(
        &mut self,
        value: FitTolerance,
    ) -> Result<(), CacheContractError> {
        match self.write_revision_fit_tolerance(ToleranceWrite::Raise(value)) {
            RevisionCacheWrite::Written => Ok(()),
            RevisionCacheWrite::Parameterized => {
                Err(CacheContractError::Layout(PARAMETERIZED_NO_SOLVED_CACHE))
            }
            RevisionCacheWrite::NoForm => match self.legacy_cache_slot_mut() {
                Some(slot @ None) => {
                    *slot = Some(LegacyCache::new(value));
                    Ok(())
                }
                Some(Some(cache)) => {
                    if value.get() > cache.fit_tolerance.get() {
                        cache.fit_tolerance = value;
                    }
                    Ok(())
                }
                None => Err(CacheContractError::Layout(NO_LEGACY_SLOT)),
            },
            RevisionCacheWrite::InvalidValue(value) => {
                Err(CacheContractError::InvalidValue { value })
            }
        }
    }
}

fn set_variable_blend_cache(
    cache: &mut VariableBlendCache<FiniteReal>,
    value: Option<FitTolerance>,
) -> Result<(), CacheContractError> {
    match (cache, value) {
        (VariableBlendCache::Parameterization { .. }, Some(_)) => {
            Err(CacheContractError::Parameterized)
        }
        (VariableBlendCache::Parameterization { .. } | VariableBlendCache::Stale {}, None) => {
            Ok(())
        }
        (VariableBlendCache::Current { fit_tolerance, .. }, Some(value)) => {
            *fit_tolerance = value;
            Ok(())
        }
        (VariableBlendCache::Current { .. }, None) => Err(CacheContractError::MissingSolved),
        (VariableBlendCache::Stale {}, Some(_)) => Err(CacheContractError::Layout(
            "a stale variable-blend cache states no fit tolerance",
        )),
    }
}

impl ProceduralSurface {
    /// Build a procedural surface from its construction definition.
    pub fn new(
        id: ProceduralSurfaceId,
        definition: ProceduralSurfaceDefinition,
        record_bounds: Option<RecordBounds>,
    ) -> Self {
        Self {
            id,
            definition,
            record_bounds,
        }
    }

    /// Return the retained native record bounds, when present. The aggregate
    /// moves whole, so a reader that keeps it holds the finiteness the
    /// constructor established; `RecordBounds::get` opens it for computation.
    #[must_use]
    pub const fn record_bounds(&self) -> Option<RecordBounds> {
        self.record_bounds
    }

    /// Borrow the neutral construction definition.
    #[must_use]
    pub fn definition(&self) -> &ProceduralSurfaceDefinition {
        &self.definition
    }

    /// Edit the definition in place.
    pub fn edit_definition<R>(
        &mut self,
        edit: impl FnOnce(&mut ProceduralSurfaceDefinition) -> R,
    ) -> R {
        edit(&mut self.definition)
    }

    /// Effective fit tolerance of the solved cache.
    #[must_use]
    pub fn cache_fit_tolerance(&self) -> Option<FitTolerance> {
        self.definition.cache_fit_tolerance()
    }

    /// Change the effective fit tolerance without permitting a parameterized
    /// cache to acquire one or a solved cache to lose it.
    pub fn set_cache_fit_tolerance(
        &mut self,
        value: Option<f64>,
    ) -> Result<(), CacheContractError> {
        let value = value.map(FitTolerance::try_new).transpose()?;
        self.definition.set_cache_fit_tolerance(value)
    }

    /// Scale the effective cache-fit tolerance in place.
    ///
    /// A positive scale keeps the tolerance non-negative, so the scaled
    /// tolerance is refused only when it overflows, with the admission's own
    /// error.
    pub fn scale_cache_fit_tolerance(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), CacheContractError> {
        self.definition.scale_cache_fit_tolerance(scale)
    }
}

/// Structurally selected deformable-surface payload.
// A source states raw values; a `DeformableSurfacePayload` holds the admitted
// payload, whose scalars, vectors and points are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum DeformableSurfaceData<R = f64, V = Vector3, P = Point3> {
    /// Mode-6 full embedded deformation payload.
    Full {
        /// Four leading deformation vectors.
        leading_vectors: [V; 4],
        /// Leading deformation scalar.
        leading_parameter: R,
        /// Three leading flags.
        leading_flags: [bool; 3],
        /// Native selector before the secondary support.
        selector: i64,
        /// Secondary embedded support surface.
        surface: SurfaceId,
        /// Native long after the support.
        native_id: i64,
        /// Native support-side flag.
        flag: bool,
        /// First scalar after the flag.
        first_parameter: R,
        /// Version-gated ASM long when present.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        version_value: Option<i64>,
        /// Second scalar after the optional long.
        second_parameter: R,
        /// Embedded deformation curve.
        curve: CurveId,
        /// Two ordered full vector frames.
        frames: Box<[DeformableVectorFrame<R, V>; 2]>,
        /// Native trailing long.
        trailing_value: i64,
    },
    /// Mode-5 surface-and-curve deformation payload.
    SurfaceCurve {
        /// Secondary embedded support surface.
        surface: SurfaceId,
        /// Native long identifier.
        native_id: i64,
        /// Native leading flag.
        flag: bool,
        /// First native scalar.
        first_parameter: R,
        /// Native selector integer.
        selector: i64,
        /// Second native scalar.
        second_parameter: R,
        /// Embedded deformation curve.
        curve: CurveId,
        /// Four ordered deformation vectors.
        vectors: [V; 4],
        /// Frame scalar after the vectors.
        frame_parameter: R,
        /// Three frame flags.
        flags: [bool; 3],
        /// Counted ordered scalar triples.
        parameter_triples: Vec<[R; 3]>,
    },
    /// Mode-1 deformation frame with counted parameter triples.
    Plain {
        /// Shared full deformation frame.
        frame: Box<DeformableSurfaceFrame<R, V, P>>,
        /// Ordered native scalar triples.
        parameter_triples: Vec<[R; 3]>,
    },
    /// Mode-3 deformation frame with a guide scalar.
    Guided {
        /// Shared full deformation frame.
        frame: Box<DeformableSurfaceFrame<R, V, P>>,
        /// Native guide selector.
        selector: i64,
        /// Native guide scalar.
        guide_parameter: R,
    },
    /// Mode-8 minimal four-vector scaffold.
    Minimal {
        /// Four ordered deformation vectors.
        vectors: [V; 4],
        /// Native trailing selector.
        selector: i64,
    },
    /// Revision-gated mode-3 deformation payload.
    RevisionMode3 {
        /// Four leading deformation vectors.
        leading_vectors: [V; 4],
        /// Scalar following the leading vectors.
        leading_parameter: R,
        /// Three flags following the leading scalar.
        leading_flags: [bool; 3],
        /// Position anchoring the trailing frame.
        trailing_point: P,
        /// Two vectors following the trailing point.
        trailing_vectors: [V; 2],
        /// Scalar following the trailing vectors.
        frame_parameter: R,
        /// Two flags following the trailing frame scalar.
        frame_flags: [bool; 2],
        /// Three ordered scalar parameters following the trailing frame.
        parameters: [R; 3],
        /// Five flags following the ordered scalar parameters.
        trailing_flags: [bool; 5],
        /// Scalar preceding the payload's final integer.
        trailing_parameter: R,
        /// Integer closing the revision mode-3 payload.
        trailing_value: i64,
    },
}

/// Four-vector frame used by full deformable surfaces.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DeformableVectorFrame<R = f64, V = Vector3> {
    /// Four ordered vectors.
    pub vectors: [V; 4],
    /// Frame scalar.
    pub parameter: R,
    /// Three ordered flags.
    pub flags: [bool; 3],
}

/// Shared frame payload of deformable-surface modes 1 and 3.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DeformableSurfaceFrame<R = f64, V = Vector3, P = Point3> {
    /// Four leading deformation vectors.
    pub leading_vectors: [V; 4],
    /// Leading frame scalar.
    pub leading_parameter: R,
    /// Three leading frame flags.
    pub leading_flags: [bool; 3],
    /// Three secondary deformation vectors.
    pub secondary_vectors: [V; 3],
    /// Secondary frame scalar.
    pub secondary_parameter: R,
    /// Two secondary frame flags.
    pub secondary_flags: [bool; 2],
    /// Native model-space frame point.
    pub point: P,
    /// Five trailing frame flags.
    pub trailing_flags: [bool; 5],
}

/// Complete native deformable-surface construction.
// A source states raw values; a `DeformableSurfacePayload` holds the admitted
// construction, whose scalars, vectors and points are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct DeformableSurfaceConstruction<R = f64, V = Vector3, P = Point3> {
    /// Surface being deformed.
    pub support: SurfaceId,
    /// Discriminator-selected deformation data.
    pub data: DeformableSurfaceData<R, V, P>,
    /// Cache contract: the revision-gated fields surrounding the support and
    /// shared surface tail, or the legacy solved-cache tolerance this
    /// construction states instead.
    #[serde(default, skip_serializing_if = "CacheContract::is_bare_legacy")]
    pub cache: CacheContract<RevisionSurfaceForm<Vec<bool>, R>>,
    /// Six ordered solved-surface discontinuity arrays.
    pub discontinuities: [Vec<R>; 6],
    /// Native discontinuity tail flag.
    pub discontinuity_flag: bool,
}

const EPS_HELIX_SURFACE_RADIUS_RELATIVE: f64 = 1.0e-9;
const EPS_HELIX_CURVE_RADIUS: f64 = 1.0e-9;

/// Finite circular path of a helix surface.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HelixPathConstructionWire")]
pub struct HelixPathConstruction {
    angle_range: FiniteVector<2>,
    center: FinitePoint3,
    major: FiniteVector3,
    minor: FiniteVector3,
    pitch: FiniteVector3,
    apex_factor: FiniteReal,
    axis: FiniteVector3,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HelixPathConstructionWire {
    /// Native helix angle interval.
    angle_range: [f64; 2],
    /// Helix center in model space.
    center: Point3,
    /// Major radial axis vector.
    major: Vector3,
    /// Minor radial axis vector.
    minor: Vector3,
    /// Axial advance of one turn, as a vector.
    pitch: Vector3,
    /// Native apex taper factor.
    apex_factor: f64,
    /// Helix axis direction.
    axis: Vector3,
}

/// The positioned frame a helix construction states.
///
/// The two helix constructions state the same five values, so they take them
/// as one argument and each admits them against its own contract.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HelixFrame<Axis = Vector3> {
    /// Helix centre in model space.
    pub center: Point3,
    /// Major radial vector.
    pub major: Vector3,
    /// Minor radial vector.
    pub minor: Vector3,
    /// Pitch vector along the axis.
    pub pitch: Vector3,
    /// Helix axis direction.
    pub axis: Axis,
}

impl HelixPathConstruction {
    /// Admit parameters that satisfy the helix payload contract.
    pub fn try_new(
        angle_range: [f64; 2],
        frame: HelixFrame,
        apex_factor: f64,
    ) -> Result<Self, &'static str> {
        Self::try_from_axis(angle_range, frame, apex_factor, FiniteVector3::new)
    }

    /// Build a helix path from an already admitted unit axis.
    pub fn try_with_unit_axis(
        angle_range: [f64; 2],
        frame: HelixFrame<crate::units::UnitVector3>,
        apex_factor: f64,
    ) -> Result<Self, &'static str> {
        Self::try_from_axis(angle_range, frame, apex_factor, |axis| Some(axis.into()))
    }

    fn try_from_axis<Axis>(
        angle_range: [f64; 2],
        frame: HelixFrame<Axis>,
        apex_factor: f64,
        admit_axis: impl FnOnce(Axis) -> Option<FiniteVector3>,
    ) -> Result<Self, &'static str> {
        let HelixFrame {
            center,
            major,
            minor,
            pitch,
            axis,
        } = frame;
        let major_length = major.norm();
        let minor_length = minor.norm();
        if !(major_length.is_finite()
            && minor_length.is_finite()
            && major_length > 0.0
            && minor_length > 0.0
            && (major_length - minor_length).abs()
                <= EPS_HELIX_SURFACE_RADIUS_RELATIVE * major_length.max(minor_length))
        {
            return Err("helix surface path major and minor must define a circular path");
        }

        let angle_range = FiniteVector::new(angle_range)
            .ok_or("HelixPathConstruction.angle_range must be finite")?;
        let center =
            FinitePoint3::new(center).ok_or("HelixPathConstruction.center must be finite")?;
        let major =
            FiniteVector3::new(major).ok_or("HelixPathConstruction.major must be finite")?;
        let minor =
            FiniteVector3::new(minor).ok_or("HelixPathConstruction.minor must be finite")?;
        let pitch =
            FiniteVector3::new(pitch).ok_or("HelixPathConstruction.pitch must be finite")?;
        let apex_factor = FiniteReal::new(apex_factor)
            .ok_or("HelixPathConstruction.apex_factor must be finite")?;
        let axis = admit_axis(axis).ok_or("HelixPathConstruction.axis must be finite")?;
        Ok(Self {
            angle_range,
            center,
            major,
            minor,
            pitch,
            apex_factor,
            axis,
        })
    }
    /// Return the angle range.
    #[must_use]
    pub const fn angle_range(&self) -> &FiniteVector<2> {
        &self.angle_range
    }

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

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

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

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

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

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

impl TryFrom<HelixPathConstructionWire> for HelixPathConstruction {
    type Error = &'static str;
    fn try_from(wire: HelixPathConstructionWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.angle_range,
            HelixFrame {
                center: wire.center,
                major: wire.major,
                minor: wire.minor,
                pitch: wire.pitch,
                axis: wire.axis,
            },
            wire.apex_factor,
        )
    }
}

/// Finite ordered helix curve with a non-degenerate radial frame.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HelixCurveConstructionWire")]
pub struct HelixCurveConstruction {
    angle_range: FiniteVector<2>,
    center: FinitePoint3,
    major: FiniteVector3,
    minor: FiniteVector3,
    pitch: FiniteVector3,
    apex_factor: FiniteReal,
    axis: FiniteVector3,
    /// Solved-cache fit contract this construction states itself.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_cache"
    )]
    cache: Option<LegacyCache>,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HelixCurveConstructionWire {
    /// Native helix angle interval.
    angle_range: [f64; 2],
    /// Helix center in model space.
    center: Point3,
    /// Major radial axis vector.
    major: Vector3,
    /// Minor radial axis vector.
    minor: Vector3,
    /// Axial advance of one turn, as a vector.
    pitch: Vector3,
    /// Native apex taper factor.
    apex_factor: f64,
    /// Helix axis direction.
    axis: Vector3,
    /// Solved-cache fit contract this construction states itself.
    #[serde(default, deserialize_with = "deserialize_cache")]
    cache: Option<LegacyCache>,
}

impl HelixCurveConstruction {
    /// Admit parameters that satisfy the helix payload contract.
    pub fn try_new(
        angle_range: [f64; 2],
        frame: HelixFrame,
        apex_factor: f64,
        cache: Option<LegacyCache>,
    ) -> Result<Self, &'static str> {
        let HelixFrame {
            center,
            major,
            minor,
            pitch,
            axis,
        } = frame;
        if angle_range[0] > angle_range[1] {
            return Err("helix curve angle_range must be ordered");
        }
        let major_radius = major.norm();
        let minor_radius = minor.norm();
        if major_radius <= f64::EPSILON
            || minor_radius <= f64::EPSILON
            || axis.norm() <= f64::EPSILON
        {
            return Err("helix curve major, minor, and axis must be non-degenerate");
        }
        if major.is_finite()
            && minor.is_finite()
            && (!major_radius.is_finite()
                || !minor_radius.is_finite()
                || (major_radius - minor_radius).abs() > EPS_HELIX_CURVE_RADIUS)
        {
            return Err("helix curve major and minor radii must agree");
        }

        let angle_range = FiniteVector::new(angle_range)
            .ok_or("HelixCurveConstruction.angle_range must be finite")?;
        let center =
            FinitePoint3::new(center).ok_or("HelixCurveConstruction.center must be finite")?;
        let major =
            FiniteVector3::new(major).ok_or("HelixCurveConstruction.major must be finite")?;
        let minor =
            FiniteVector3::new(minor).ok_or("HelixCurveConstruction.minor must be finite")?;
        let pitch =
            FiniteVector3::new(pitch).ok_or("HelixCurveConstruction.pitch must be finite")?;
        let apex_factor = FiniteReal::new(apex_factor)
            .ok_or("HelixCurveConstruction.apex_factor must be finite")?;
        let axis = FiniteVector3::new(axis).ok_or("HelixCurveConstruction.axis must be finite")?;
        Ok(Self {
            angle_range,
            center,
            major,
            minor,
            pitch,
            apex_factor,
            axis,
            cache,
        })
    }
    /// Return the angle range.
    #[must_use]
    pub const fn angle_range(&self) -> &FiniteVector<2> {
        &self.angle_range
    }

    /// Borrow the admitted center.
    #[must_use]
    pub const fn center(&self) -> &FinitePoint3 {
        &self.center
    }

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

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

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

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

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

impl TryFrom<HelixCurveConstructionWire> for HelixCurveConstruction {
    type Error = &'static str;
    fn try_from(wire: HelixCurveConstructionWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.angle_range,
            HelixFrame {
                center: wire.center,
                major: wire.major,
                minor: wire.minor,
                pitch: wire.pitch,
                axis: wire.axis,
            },
            wire.apex_factor,
            wire.cache,
        )
    }
}

impl HelixCurveConstruction {
    /// Reverse the parameter while preserving points and derivatives.
    /// A zero radius at the new interval start has no admitted helix frame.
    pub fn try_reverse_parameterization(&mut self) -> Result<(), &'static str> {
        let [start, end] = self.angle_range.finite_components();
        let turns = end.turns_from(start).get();
        let radial_end = self.apex_factor.get().mul_add(turns, 1.0);
        if !turns.is_finite() || !radial_end.is_finite() || radial_end == 0.0 {
            return Err("helix curve reversal has no finite nonzero starting radius");
        }
        let scale = |vector: Vector3| {
            Vector3::new(
                vector.x * radial_end,
                vector.y * radial_end,
                vector.z * radial_end,
            )
        };
        let candidate = Self::try_new(
            self.angle_range.reversed_negated().get(),
            HelixFrame {
                center: self.center.get().translated(self.pitch.get(), turns),
                major: scale(self.major.get()),
                minor: scale(self.minor.negated().get()),
                pitch: self.pitch.negated().get(),
                axis: self.axis.get(),
            },
            -self.apex_factor.get() / radial_end,
            self.cache,
        )?;
        *self = candidate;
        Ok(())
    }

    /// Scale lengths atomically and retain the old path when admission fails.
    pub fn try_scale_lengths(&mut self, scale: f64) -> Result<(), &'static str> {
        let vector =
            |value: Vector3| Vector3::new(value.x * scale, value.y * scale, value.z * scale);
        let center = Point3::new(
            self.center.x * scale,
            self.center.y * scale,
            self.center.z * scale,
        );
        let major = vector(self.major.get());
        let minor = vector(self.minor.get());
        let pitch = vector(self.pitch.get());
        let major_radius = major.norm();
        let minor_radius = minor.norm();
        if major_radius <= f64::EPSILON || minor_radius <= f64::EPSILON {
            return Err("helix curve major, minor, and axis must be non-degenerate");
        }
        if major.is_finite()
            && minor.is_finite()
            && (!major_radius.is_finite()
                || !minor_radius.is_finite()
                || (major_radius - minor_radius).abs() > EPS_HELIX_CURVE_RADIUS)
        {
            return Err("helix curve major and minor radii must agree");
        }
        let center =
            FinitePoint3::new(center).ok_or("HelixCurveConstruction.center must be finite")?;
        let major =
            FiniteVector3::new(major).ok_or("HelixCurveConstruction.major must be finite")?;
        let minor =
            FiniteVector3::new(minor).ok_or("HelixCurveConstruction.minor must be finite")?;
        let pitch =
            FiniteVector3::new(pitch).ok_or("HelixCurveConstruction.pitch must be finite")?;
        self.center = center;
        self.major = major;
        self.minor = minor;
        self.pitch = pitch;
        Ok(())
    }
}

/// Finite circular helix profile with a nonzero signed radius.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HelixCircleProfileWire")]
pub struct HelixCircleProfile {
    length: FiniteReal,
    radius: FiniteReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HelixCircleProfileWire {
    /// Native profile length.
    length: f64,
    /// Signed circular profile radius.
    radius: f64,
}

impl HelixCircleProfile {
    /// Admit parameters that satisfy the helix payload contract.
    pub fn try_new(length: f64, radius: f64) -> Result<Self, &'static str> {
        if radius == 0.0 {
            return Err("helix circle profile radius must be finite and nonzero");
        }
        let length = FiniteReal::new(length).ok_or("helix circle profile length must be finite")?;
        let radius = FiniteReal::new(radius).ok_or("helix circle profile radius must be finite")?;
        Ok(Self { length, radius })
    }
    /// Native profile length.
    #[must_use]
    pub const fn length(&self) -> FiniteReal {
        self.length
    }

    /// Signed circular profile radius.
    #[must_use]
    pub const fn radius(&self) -> FiniteReal {
        self.radius
    }
}

impl TryFrom<HelixCircleProfileWire> for HelixCircleProfile {
    type Error = &'static str;
    fn try_from(wire: HelixCircleProfileWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.length, wire.radius)
    }
}

/// Finite non-degenerate linear helix profile.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HelixLineProfileWire")]
pub struct HelixLineProfile {
    direction: FiniteVector3,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HelixLineProfileWire {
    /// Finite non-degenerate profile direction.
    direction: Vector3,
}

impl HelixLineProfile {
    /// Admit parameters that satisfy the helix payload contract.
    pub fn try_new(direction: Vector3) -> Result<Self, &'static str> {
        const INVALID: &str = "helix line profile direction must be finite and non-degenerate";
        let direction = FiniteVector3::new(direction).ok_or(INVALID)?;
        if direction.x == 0.0 && direction.y == 0.0 && direction.z == 0.0 {
            return Err(INVALID);
        }
        Ok(Self { direction })
    }
    /// Finite non-degenerate profile direction.
    #[must_use]
    pub const fn direction(&self) -> FiniteVector3 {
        self.direction
    }
}

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

/// Profile-specific tail of a helix surface.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum HelixSurfaceProfile {
    /// Circular profile swept along the helix.
    Circle(HelixCircleProfile),
    /// Linear profile swept along a direction.
    Line(HelixLineProfile),
}

/// Complete helix-surface construction with finite native intervals.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "HelixSurfaceConstructionWire")]
pub struct HelixSurfaceConstruction {
    angle_range: FiniteVector<2>,
    dimension_range: FiniteVector<2>,
    path: HelixPathConstruction,
    profile: HelixSurfaceProfile,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct HelixSurfaceConstructionWire {
    /// Native helix angle interval.
    angle_range: [f64; 2],
    /// Native profile dimension interval.
    dimension_range: [f64; 2],
    /// Circular path of the helix surface.
    path: HelixPathConstruction,
    /// Profile swept along the path.
    profile: HelixSurfaceProfile,
}

impl HelixSurfaceConstruction {
    /// Admit parameters that satisfy the helix payload contract.
    pub fn try_new(
        angle_range: [f64; 2],
        dimension_range: [f64; 2],
        path: HelixPathConstruction,
        profile: HelixSurfaceProfile,
    ) -> Result<Self, &'static str> {
        let angle_range =
            FiniteVector::new(angle_range).ok_or("helix surface angle_range must be finite")?;
        let dimension_range = FiniteVector::new(dimension_range)
            .ok_or("helix surface dimension_range must be finite")?;
        Ok(Self {
            angle_range,
            dimension_range,
            path,
            profile,
        })
    }
    /// Return the angle range.
    #[must_use]
    pub const fn angle_range(&self) -> &FiniteVector<2> {
        &self.angle_range
    }

    /// Return the dimension range.
    #[must_use]
    pub const fn dimension_range(&self) -> &FiniteVector<2> {
        &self.dimension_range
    }

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

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

impl TryFrom<HelixSurfaceConstructionWire> for HelixSurfaceConstruction {
    type Error = &'static str;
    fn try_from(wire: HelixSurfaceConstructionWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.angle_range,
            wire.dimension_range,
            wire.path,
            wire.profile,
        )
    }
}

/// A non-negative native subtype-table index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "i64", into = "i64")]
pub struct SubtypeTableIndex(i64);

impl SubtypeTableIndex {
    /// Admit a non-negative native subtype-table index.
    pub fn try_new(index: i64) -> Result<Self, &'static str> {
        if index >= 0 {
            Ok(Self(index))
        } else {
            Err("subtype table index must be non-negative")
        }
    }

    /// Native subtype-table index.
    #[must_use]
    pub const fn get(self) -> i64 {
        self.0
    }
}

impl TryFrom<i64> for SubtypeTableIndex {
    type Error = &'static str;
    fn try_from(index: i64) -> Result<Self, Self::Error> {
        Self::try_new(index)
    }
}

impl From<SubtypeTableIndex> for i64 {
    fn from(index: SubtypeTableIndex) -> Self {
        index.get()
    }
}

/// An inline T-spline program and its non-empty companion values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    tag = "kind",
    rename = "inline",
    try_from = "InlineTSplineSubtransformWire"
)]
pub struct InlineTSplineSubtransform {
    /// Line-oriented topology and geometry program.
    pub program: cadmpeg_core::text::NonBlankString,
    /// Optional native separator boolean.
    pub separator: Option<bool>,
    /// Companion values program.
    pub values: cadmpeg_core::text::NonBlankString,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
enum InlineTSplineSubtransformWire {
    /// Inline line-oriented T-spline program and companion values.
    Inline {
        /// Line-oriented topology and geometry program.
        program: String,
        /// Optional native separator boolean.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        separator: Option<bool>,
        /// Companion values program.
        values: String,
    },
}

impl TryFrom<InlineTSplineSubtransformWire> for InlineTSplineSubtransform {
    type Error = &'static str;
    fn try_from(wire: InlineTSplineSubtransformWire) -> Result<Self, Self::Error> {
        let InlineTSplineSubtransformWire::Inline {
            program,
            separator,
            values,
        } = wire;
        Self::try_new(program, separator, values)
    }
}

impl InlineTSplineSubtransform {
    /// Admit a non-empty T-spline program and companion values.
    pub fn try_new(
        program: impl Into<String>,
        separator: Option<bool>,
        values: impl Into<String>,
    ) -> Result<Self, &'static str> {
        Ok(Self {
            program: cadmpeg_core::text::NonBlankString::new(program)
                .ok_or("T-spline program must not be empty")?,
            separator,
            values: cadmpeg_core::text::NonBlankString::new(values)
                .ok_or("T-spline values must not be empty")?,
        })
    }
}

/// Native T-spline subtransform storage form.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "TSplineSubtransformWire")]
pub enum TSplineSubtransform {
    /// Inline line-oriented T-spline program and companion values.
    Inline(InlineTSplineSubtransform),
    /// Resolved reference to an earlier subtype-table entry.
    Resolved {
        /// Native subtype-table index.
        index: SubtypeTableIndex,
        /// Resolved shared program.
        transform: Box<InlineTSplineSubtransform>,
    },
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
enum TSplineSubtransformWire {
    /// Inline line-oriented T-spline program and companion values.
    Inline {
        /// Line-oriented topology and geometry program.
        program: String,
        /// Optional native separator boolean.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        separator: Option<bool>,
        /// Companion values program.
        values: String,
    },
    /// Resolved reference to an earlier subtype-table entry.
    Reference {
        /// Native subtype-table index.
        index: SubtypeTableIndex,
        /// Resolved shared program.
        resolved: Box<InlineTSplineSubtransform>,
    },
}

impl TryFrom<TSplineSubtransformWire> for TSplineSubtransform {
    type Error = &'static str;
    fn try_from(wire: TSplineSubtransformWire) -> Result<Self, Self::Error> {
        match wire {
            TSplineSubtransformWire::Inline {
                program,
                separator,
                values,
            } => InlineTSplineSubtransform::try_new(program, separator, values).map(Self::Inline),
            TSplineSubtransformWire::Reference { index, resolved } => Ok(Self::Resolved {
                index,
                transform: resolved,
            }),
        }
    }
}

impl Serialize for TSplineSubtransform {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        #[serde(tag = "kind", rename_all = "snake_case")]
        enum Wire<'a> {
            Reference {
                index: SubtypeTableIndex,
                resolved: &'a InlineTSplineSubtransform,
            },
        }
        match self {
            Self::Inline(inline) => inline.serialize(serializer),
            Self::Resolved { index, transform } => Wire::Reference {
                index: *index,
                resolved: transform,
            }
            .serialize(serializer),
        }
    }
}

impl TSplineSubtransform {
    /// Effective inline program, including resolved references.
    #[must_use]
    pub fn inline(&self) -> &InlineTSplineSubtransform {
        match self {
            Self::Inline(inline) => inline,
            Self::Resolved { transform, .. } => transform,
        }
    }
}

/// Complete native `t_spl_sur` wrapper.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    try_from = "TSplineSurfaceConstructionWire",
    into = "TSplineSurfaceConstructionWire"
)]
pub struct TSplineSurfaceConstruction {
    /// Ordered U and V native parameter intervals.
    parameter_ranges: [crate::topology::ParameterInterval; 2],
    /// Native T-spline type integer.
    type_code: i64,
    /// Inline or referenced shared subtransform object.
    subtransform: TSplineSubtransform,
    /// Native trailing integer.
    trailing_value: i64,
    /// Six ordered solved-surface discontinuity arrays.
    discontinuities: [Vec<FiniteReal>; 6],
    /// Native discontinuity tail flag.
    discontinuity_flag: bool,
    /// Cache contract: the revision-gated form, or the legacy solved-cache
    /// tolerance this construction states instead. The revision layout stores
    /// the shared tail first, then four optional parameter values
    /// (`support_bounds`), the type code as an enum, the nested subtransform
    /// scope, and the trailing integer.
    #[serde(default, skip_serializing_if = "CacheContract::is_bare_legacy")]
    cache: CacheContract<RevisionSurfaceForm<Vec<bool>, FiniteReal>>,
}

impl TSplineSurfaceConstruction {
    /// Admit finite ordered ranges, finite discontinuities, a valid revision
    /// cache, and a resolved subtransform.
    pub fn try_new(
        parameter_ranges: [[f64; 2]; 2],
        type_code: i64,
        subtransform: TSplineSubtransform,
        trailing_value: i64,
        discontinuities: [Vec<f64>; 6],
        discontinuity_flag: bool,
        cache: CacheContract<RevisionSurfaceForm>,
    ) -> Result<Self, ProceduralGeometryError> {
        let parameter_ranges = [
            crate::topology::ParameterInterval::new(parameter_ranges[0])
                .map_err(ProceduralGeometryError::Payload)?,
            crate::topology::ParameterInterval::new(parameter_ranges[1])
                .map_err(ProceduralGeometryError::Payload)?,
        ];
        let discontinuities = FiniteReal::lanes(discontinuities).ok_or(
            ProceduralGeometryError::Payload("T-spline discontinuities must be finite"),
        )?;
        let cache = cache.admit_form(RevisionSurfaceForm::admit).ok_or(
            ProceduralGeometryError::Payload("T-spline revision cache form is invalid"),
        )?;
        Ok(Self {
            parameter_ranges,
            type_code,
            subtransform,
            trailing_value,
            discontinuities,
            discontinuity_flag,
            cache,
        })
    }

    /// Return ordered U and V intervals.
    pub fn parameter_ranges(&self) -> [crate::topology::ParameterInterval; 2] {
        self.parameter_ranges
    }

    /// Return the native type code value.
    pub const fn type_code(&self) -> i64 {
        self.type_code
    }

    /// Return the native subtransform value.
    pub const fn subtransform(&self) -> &TSplineSubtransform {
        &self.subtransform
    }

    /// Return the native trailing integer.
    pub const fn trailing_value(&self) -> i64 {
        self.trailing_value
    }

    /// Return the native discontinuities value.
    pub const fn discontinuities(&self) -> &[Vec<FiniteReal>; 6] {
        &self.discontinuities
    }

    /// Return the native discontinuity flag value.
    pub const fn discontinuity_flag(&self) -> bool {
        self.discontinuity_flag
    }

    /// Return the native revision form value.
    pub const fn revision_form(&self) -> Option<&RevisionSurfaceForm<Vec<bool>, FiniteReal>> {
        self.cache.form()
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "TSplineSurfaceConstruction"))]
#[serde(deny_unknown_fields)]
struct TSplineSurfaceConstructionWire {
    /// Ordered U and V native parameter intervals.
    parameter_ranges: [[f64; 2]; 2],
    /// Native T-spline type integer.
    type_code: i64,
    /// Inline or referenced shared subtransform object.
    subtransform: TSplineSubtransform,
    /// Native trailing integer.
    trailing_value: i64,
    /// Six ordered solved-surface discontinuity arrays.
    discontinuities: [Vec<f64>; 6],
    /// Native discontinuity tail flag.
    discontinuity_flag: bool,
    /// Cache contract: the revision-gated form, or the legacy solved-cache
    /// tolerance this construction states instead. The revision layout stores
    /// the shared tail first, then four optional parameter values
    /// (`support_bounds`), the type code as an enum, the nested subtransform
    /// scope, and the trailing integer.
    #[serde(default, skip_serializing_if = "CacheContract::is_bare_legacy")]
    cache: CacheContract<RevisionSurfaceForm>,
}

impl TryFrom<TSplineSurfaceConstructionWire> for TSplineSurfaceConstruction {
    type Error = ProceduralGeometryError;

    fn try_from(wire: TSplineSurfaceConstructionWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.parameter_ranges,
            wire.type_code,
            wire.subtransform,
            wire.trailing_value,
            wire.discontinuities,
            wire.discontinuity_flag,
            wire.cache,
        )
    }
}

/// One oriented support of a procedural blend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct BlendSupport {
    /// The support surface.
    pub surface: SurfaceId,
    /// Selects the opposite surface-normal side when true.
    #[serde(default)]
    pub reversed: bool,
}

/// One parameter station of a rolling-ball jet, with its complete value rows.
// A source states raw values; `RollingBallJetStations` holds the admitted
// station, whose scalars, vectors and points are checked.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RollingBallJetStation<R = f64, V = Vector3, P = Point3> {
    /// Native spine parameter.
    pub knot: R,
    /// Multiplicity of this parameter in the native knot vector.
    pub multiplicity: u32,
    /// Values and derivatives at this parameter.
    pub site: RollingBallJetSite<R, V, P>,
}

const EPS_ROLLING_BALL_RADIUS: f64 = 1.0e-9;

const ROLLING_BALL_KNOTS: &str = "rolling-ball jet knots must be finite and strictly increasing";

/// Refuse a site whose radii are not finite, whose first radius is not
/// positive, or whose two radii disagree beyond the relative tolerance.
fn admit_rolling_ball_radii(
    site: &RollingBallJetSite<FiniteReal, FiniteVector3, FinitePoint3>,
) -> Result<(), &'static str> {
    let first_radius = site.first_limit.distance(site.center.get());
    let second_radius = site.second_limit.distance(site.center.get());
    if !first_radius.is_finite()
        || first_radius <= 0.0
        || !second_radius.is_finite()
        || (first_radius - second_radius).abs()
            > EPS_ROLLING_BALL_RADIUS * first_radius.max(second_radius).max(1.0)
    {
        return Err("rolling-ball jet site radii must be finite and agree within tolerance, with a positive first radius");
    }
    Ok(())
}

/// Degree and finite clamped station data of a rolling-ball jet.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(try_from = "RollingBallJetReadWire")]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct RollingBallJetStations {
    degree: u32,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<RollingBallJetStation>"))]
    stations: Vec<RollingBallJetStation<FiniteReal, FiniteVector3, FinitePoint3>>,
}

/// Station invariant or context-free reconstruction failure.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RollingBallJetError {
    /// A station invariant failed.
    #[error("{0}")]
    Invalid(&'static str),
    /// The admission channel could not complete.
    #[error("{0}")]
    Admission(String),
}

impl RollingBallJetStations {
    /// Admit raw station controls.
    pub fn try_new(
        degree: u32,
        stations: Vec<RollingBallJetStation>,
    ) -> Result<Self, &'static str> {
        Self::admit_controls(degree, &stations, |row| row.knot)?;
        let mut admitted = Vec::new();
        for row in stations {
            let knot = FiniteReal::new(row.knot).ok_or(ROLLING_BALL_KNOTS)?;
            let site = row.site.admit()?;
            admit_rolling_ball_radii(&site)?;
            admitted.push(RollingBallJetStation {
                knot,
                multiplicity: row.multiplicity,
                site,
            });
        }
        Ok(Self {
            degree,
            stations: admitted,
        })
    }

    /// Validate finite station rows without copying their owned storage.
    pub fn from_parts(
        degree: u32,
        stations: Vec<RollingBallJetStation<FiniteReal, FiniteVector3, FinitePoint3>>,
    ) -> Result<Self, &'static str> {
        Self::admit_controls(degree, &stations, |row| row.knot.get())?;
        for station in &stations {
            admit_rolling_ball_radii(&station.site)?;
        }
        Ok(Self { degree, stations })
    }

    fn admit_controls<R, V, P>(
        degree: u32,
        stations: &[RollingBallJetStation<R, V, P>],
        knot: impl Fn(&RollingBallJetStation<R, V, P>) -> f64,
    ) -> Result<(), &'static str> {
        let Some(maximum) = degree.checked_add(1).filter(|_| degree != 0) else {
            return Err(
                "rolling-ball jet degree must be positive with a representable end multiplicity",
            );
        };
        if stations.len() < 2 {
            return Err("rolling-ball jet stations must contain at least two rows");
        }
        if stations[0].multiplicity != maximum
            || stations[stations.len() - 1].multiplicity != maximum
        {
            return Err(
                "rolling-ball jet multiplicities must be in 1..=degree+1 with clamped ends",
            );
        }
        for station in stations {
            if station.multiplicity == 0 || station.multiplicity > maximum {
                return Err(
                    "rolling-ball jet multiplicities must be in 1..=degree+1 with clamped ends",
                );
            }
        }
        let mut previous = None;
        for station in stations {
            let value = knot(station);
            if !value.is_finite() || previous.is_some_and(|last| value <= last) {
                return Err(ROLLING_BALL_KNOTS);
            }
            previous = Some(value);
        }
        Ok(())
    }

    /// Return the polynomial degree of each scalar channel.
    #[must_use]
    pub const fn degree(&self) -> u32 {
        self.degree
    }

    /// Return the ordered station data.
    #[must_use]
    pub fn stations(&self) -> &[RollingBallJetStation<FiniteReal, FiniteVector3, FinitePoint3>] {
        &self.stations
    }
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct RollingBallJetReadWire {
    /// Polynomial degree of each scalar channel.
    degree: u32,
    /// Ordered station data.
    stations: Vec<RollingBallJetStation>,
}

impl TryFrom<RollingBallJetReadWire> for RollingBallJetStations {
    type Error = RollingBallJetError;

    fn try_from(wire: RollingBallJetReadWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.degree, wire.stations).map_err(RollingBallJetError::Invalid)
    }
}

#[derive(Serialize)]
struct RollingBallJetWriteWire<'a> {
    degree: u32,
    stations: &'a [RollingBallJetStation<FiniteReal, FiniteVector3, FinitePoint3>],
}

impl Serialize for RollingBallJetStations {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        RollingBallJetWriteWire {
            degree: self.degree,
            stations: &self.stations,
        }
        .serialize(serializer)
    }
}

/// One aligned knot site of an exact rolling-ball surface jet.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RollingBallJetSite<R = f64, V = Vector3, P = Point3> {
    /// First limiting point at the knot.
    pub first_limit: P,
    /// Second limiting point at the knot.
    pub second_limit: P,
    /// Rolling-ball center at the knot.
    pub center: P,
    /// Signed opening angle at the knot, in radians.
    pub angle: R,
    /// First parameter derivative of all four value channels.
    pub first_derivative: RollingBallJetDerivative<R, V>,
    /// Second parameter derivative of all four value channels.
    pub second_derivative: RollingBallJetDerivative<R, V>,
}

/// One derivative row for the four channels of a rolling-ball jet.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RollingBallJetDerivative<R = f64, V = Vector3> {
    /// Derivative of the first limiting point.
    pub first_limit: V,
    /// Derivative of the second limiting point.
    pub second_limit: V,
    /// Derivative of the rolling-ball center.
    pub center: V,
    /// Derivative of the signed opening angle.
    pub angle: R,
}

/// Cross-section family of a procedural blend.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum BlendCrossSection {
    /// Constant-radius circular cross-section.
    Circular,
    /// Conic (non-circular quadric) cross-section.
    Conic,
    /// Free-form polynomial cross-section.
    Polynomial,
}

/// Shared fields of a revision-gated spline-surface form: the revision
/// integer, optional support bounds and reference-curve endpoints, a
/// carrier-specific boolean run, and the shared tail enum, discontinuity
/// arrays, tail boolean, and post-tail boolean run.
// A source states raw scalars; a surface construction holds the admitted
// form, whose scalars are `FiniteReal` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "F: Deserialize<'de> + Default, R: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "F: JsonSchema + Default, R: JsonSchema + Serialize")
)]
pub struct RevisionSurfaceForm<F: Default = Vec<bool>, R = f64> {
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Optional U/V bound fields following the support surface.
    #[serde(default)]
    pub support_bounds: [Option<R>; 4],
    /// Optional parameter endpoints following the embedded reference curve.
    #[serde(default)]
    pub reference_endpoints: [Option<R>; 2],
    /// Optional parameter endpoints following a second embedded curve, used
    /// by two-curve carriers such as `sum_spl_sur`.
    #[serde(default)]
    pub second_endpoints: [Option<R>; 2],
    /// Carrier-specific boolean run preceding the shared tail.
    #[serde(default)]
    pub flags: F,
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: RevisionCacheForm<RevisionSurfaceParameterization<R>>,
    /// Six ordered discontinuity arrays following the fit tolerance.
    #[serde(default)]
    pub discontinuities: [Vec<R>; 6],
    /// Boolean terminating the shared tail.
    pub tail_flag: bool,
    /// Boolean run following the shared tail.
    #[serde(default)]
    pub trailing_flags: Vec<bool>,
}

/// Mutually exclusive payloads of a revision-gated approximation cache.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RevisionCacheForm<P = RevisionSurfaceParameterization> {
    /// A solved cache followed by its carrier-specific cache contract.
    SolvedCache {
        /// Carrier-specific solved-cache contract.
        fit_tolerance: FitTolerance,
    },
    /// Parameterization stored in place of a solved cache.
    Parameterization(P),
}

impl<P> RevisionCacheForm<P> {
    /// State the fit tolerance this form carries for its solved cache.
    fn write_fit_tolerance(&mut self, write: ToleranceWrite) -> RevisionCacheWrite {
        match self {
            Self::SolvedCache { fit_tolerance } => {
                match write {
                    ToleranceWrite::State(value) => *fit_tolerance = value,
                    ToleranceWrite::Raise(value) => {
                        if value.get() > fit_tolerance.get() {
                            *fit_tolerance = value;
                        }
                    }
                    ToleranceWrite::Scale(scale) => {
                        let Some(scaled) = fit_tolerance.scaled(scale) else {
                            return RevisionCacheWrite::InvalidValue(
                                fit_tolerance.get() * scale.get(),
                            );
                        };
                        *fit_tolerance = scaled;
                    }
                }
                RevisionCacheWrite::Written
            }
            Self::Parameterization(_) => RevisionCacheWrite::Parameterized,
        }
    }

    /// Parameterization carried in place of a solved cache.
    #[must_use]
    pub const fn parameterization(&self) -> Option<&P> {
        match self {
            Self::SolvedCache { .. } => None,
            Self::Parameterization(parameterization) => Some(parameterization),
        }
    }

    /// Fit tolerance carried by a solved cache.
    #[must_use]
    pub const fn fit_tolerance(&self) -> Option<FitTolerance> {
        match self {
            Self::SolvedCache { fit_tolerance } => Some(*fit_tolerance),
            Self::Parameterization(_) => None,
        }
    }
}

/// Approximation state and its dependent fit contract for a variable blend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub enum VariableBlendCache<R = f64> {
    /// A nonzero approximation-current flag with an active fit contract.
    Current {
        /// Native approximation-current flag.
        shape_prefix: NonZeroI64,
        /// Fit tolerance in document length units.
        fit_tolerance: FitTolerance,
    },
    /// A zero approximation-current flag without an active fit contract.
    Stale {},
    /// Parameterization in place of a solved cache.
    Parameterization {
        /// Native approximation-current flag, independent of the parameterization.
        shape_prefix: i64,
        /// Surface parameterization.
        parameterization: RevisionSurfaceParameterization<R>,
    },
}

impl<R> VariableBlendCache<R> {
    /// Scale the tolerance only when this cache carries a solved one.
    fn scale_fit_tolerance(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), CacheContractError> {
        if let Self::Current { fit_tolerance, .. } = self {
            let value = *fit_tolerance;
            *fit_tolerance =
                value
                    .scaled(scale)
                    .ok_or_else(|| CacheContractError::InvalidValue {
                        value: value.get() * scale.get(),
                    })?;
        }
        Ok(())
    }

    /// Native approximation-current flag.
    #[must_use]
    pub const fn shape_prefix(&self) -> i64 {
        match self {
            Self::Current { shape_prefix, .. } => shape_prefix.get(),
            Self::Stale {} => 0,
            Self::Parameterization { shape_prefix, .. } => *shape_prefix,
        }
    }

    /// Parameterization carried in place of a solved cache.
    #[must_use]
    pub const fn parameterization(&self) -> Option<&RevisionSurfaceParameterization<R>> {
        match self {
            Self::Parameterization {
                parameterization, ..
            } => Some(parameterization),
            _ => None,
        }
    }

    /// Active fit tolerance, absent for a stale or parameterized approximation.
    #[must_use]
    pub const fn fit_tolerance(&self) -> Option<FitTolerance> {
        match self {
            Self::Current { fit_tolerance, .. } => Some(*fit_tolerance),
            _ => None,
        }
    }
}

/// Parameterization carried by tail-enum form `2` of the shared revision-gated
/// spline-surface tail. This form stores no approximation cache and no fit
/// tolerance; it stores the two parameter intervals followed by four enums, in
/// the order the fields appear below.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct RevisionSurfaceParameterization<R = f64> {
    /// U parameter interval, an ordered `[lo, hi]` pair of optional bounds.
    /// `None` is a false bound-presence flag.
    #[serde(default)]
    pub u_interval: [Option<R>; 2],
    /// V parameter interval, an ordered `[lo, hi]` pair of optional bounds.
    /// `None` is a false bound-presence flag.
    #[serde(default)]
    pub v_interval: [Option<R>; 2],
    /// U closure enum.
    pub u_closure: i64,
    /// V closure enum.
    pub v_closure: i64,
    /// U singularity enum.
    pub u_singularity: i64,
    /// V singularity enum.
    pub v_singularity: i64,
}

impl<R> Default for RevisionSurfaceParameterization<R> {
    /// Absent interval bounds and zero enums.
    fn default() -> Self {
        Self {
            u_interval: [None, None],
            v_interval: [None, None],
            u_closure: 0,
            v_closure: 0,
            u_singularity: 0,
            v_singularity: 0,
        }
    }
}

/// Subtype-specific tail of a native taper spline surface.
// A source states raw values; a `TaperSurfaceConstruction` holds the admitted
// tail, whose scalars and draft vector are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum TaperSurfaceKind<R = f64, V = Vector3> {
    /// Standard taper without a subtype-specific tail.
    Standard {},
    /// Orthogonal taper with a native sense flag.
    Orthogonal {
        /// Native orientation sense.
        sense: bool,
    },
    /// Edge taper with a model-space draft vector.
    Edge {
        /// Native draft vector.
        draft: V,
    },
    /// Shadow taper with a pre-factored draft angle.
    Shadow {
        /// Native draft vector.
        draft: V,
        /// Stored draft-angle sine.
        sine: R,
        /// Stored draft-angle cosine.
        cosine: R,
    },
    /// Ruled taper with a pre-factored angle and factor.
    Ruled {
        /// Native draft vector.
        draft: V,
        /// Stored draft-angle sine.
        sine: R,
        /// Stored draft-angle cosine.
        cosine: R,
        /// Native ruled-taper factor.
        factor: R,
    },
    /// Swept taper with a pre-factored draft angle.
    Swept {
        /// Native draft vector.
        draft: V,
        /// Stored draft-angle sine.
        sine: R,
        /// Stored draft-angle cosine.
        cosine: R,
    },
}

/// One scalar row in native loft subdata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct LoftSubdataRow<R = f64> {
    /// Leading ordered scalar pair.
    pub parameters: [R; 2],
    /// Ordered per-column scalar pairs; empty for subdata type 211.
    pub columns: Vec<[R; 2]>,
    /// Trailing scalar pair stored by the revision-gated row encoding.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_extra"
    )]
    pub extra: Option<[R; 2]>,
}

/// Native loft constraint table with structurally consistent dimensions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "form", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub enum LoftSubdata<R = f64> {
    /// Type 211 stores exactly one leading pair and no column pairs.
    Type211 {
        /// Native row/column header values. They do not count this form's payload.
        dimensions: [i64; 2],
        /// The sole leading scalar pair.
        row: [R; 2],
    },
    /// All other table types store rows of one shared column width.
    Table(LoftSubdataTable<R>),
}

/// Checked non-211 loft table payload.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(into = "LoftSubdataTableWire<R>"))]
#[serde(
    try_from = "LoftSubdataTableWire<R>",
    bound(deserialize = "R: Deserialize<'de>")
)]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct LoftSubdataTable<R = f64> {
    type_code: i64,
    rows: Vec<LoftSubdataRow<R>>,
    row_count: i64,
    column_count: i64,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
struct LoftSubdataTableWire<R = f64> {
    /// Native loft table type code.
    type_code: i64,
    /// Table rows, all of one column width.
    rows: Vec<LoftSubdataRow<R>>,
}

/// The written form of a loft table, borrowing its rows.
#[derive(Serialize)]
struct LoftSubdataTableWriteWire<'a, R> {
    type_code: i64,
    rows: &'a [LoftSubdataRow<R>],
}

impl<R: Serialize> Serialize for LoftSubdataTable<R> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        LoftSubdataTableWriteWire {
            type_code: self.type_code,
            rows: &self.rows,
        }
        .serialize(serializer)
    }
}

/// The rows of a loft table do not share one column width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("loft subdata rows do not share one column width")]
pub struct RaggedLoftTable;

impl<R> LoftSubdataTable<R> {
    /// Admit a table whose rows share one column width.
    pub fn new(type_code: i64, rows: Vec<LoftSubdataRow<R>>) -> Result<Self, RaggedLoftTable> {
        let row_count = i64::try_from(rows.len()).map_err(|_| RaggedLoftTable)?;
        let column_count = rows.first().map_or(0, |row| row.columns.len());
        let column_count_i64 = i64::try_from(column_count).map_err(|_| RaggedLoftTable)?;
        if rows.iter().any(|row| row.columns.len() != column_count) {
            return Err(RaggedLoftTable);
        }
        Ok(Self {
            type_code,
            rows,
            row_count,
            column_count: column_count_i64,
        })
    }
}

impl<R> TryFrom<LoftSubdataTableWire<R>> for LoftSubdataTable<R> {
    type Error = RaggedLoftTable;

    fn try_from(wire: LoftSubdataTableWire<R>) -> Result<Self, Self::Error> {
        Self::new(wire.type_code, wire.rows)
    }
}

impl LoftSubdata {
    /// Construct the fixed type-211 form.
    #[must_use]
    pub fn type_211(dimensions: [i64; 2], row: [f64; 2]) -> Self {
        Self::Type211 { dimensions, row }
    }

    /// Construct a non-211 table whose rows have one shared column width.
    #[must_use]
    pub fn table(type_code: i64, rows: Vec<LoftSubdataRow>) -> Option<Self> {
        LoftSubdataTable::new(type_code, rows).ok().map(Self::Table)
    }
}

impl<R> LoftSubdata<R> {
    /// Native table type discriminator.
    #[must_use]
    pub fn type_code(&self) -> i64 {
        match self {
            Self::Type211 { .. } => 211,
            Self::Table(table) => table.type_code,
        }
    }

    /// Native row header: a stored value for type 211, otherwise the row count.
    #[must_use]
    pub fn row_count(&self) -> i64 {
        match self {
            Self::Type211 { dimensions, .. } => dimensions[0],
            Self::Table(table) => table.row_count,
        }
    }

    /// Native column header: stored for type 211, otherwise the shared row width.
    #[must_use]
    pub fn column_count(&self) -> i64 {
        match self {
            Self::Type211 { dimensions, .. } => dimensions[1],
            Self::Table(table) => table.column_count,
        }
    }

    /// Visit the leading and column pairs in each row.
    pub fn visit_rows(&self, mut visit: impl FnMut(&[R; 2], &[[R; 2]], Option<&[R; 2]>)) {
        match self {
            Self::Type211 { row, .. } => visit(row, &[], None),
            Self::Table(table) => {
                for row in &table.rows {
                    visit(&row.parameters, &row.columns, row.extra.as_ref());
                }
            }
        }
    }
}

/// The complete constraint payload of a classic loft or skin profile.
///
/// Every field the classic form carries is required and every field it cannot
/// carry is absent from the type, so the revision-gated `support_bounds` and
/// the type-zero `secondary_pcurve` are unknown keys here rather than values a
/// reader has to refuse.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "LoftProfileData"))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct ClassicLoftProfileData<R = f64, V = Vector3> {
    /// Required support surface.
    pub surface: SurfaceId,
    /// Nullable parameter curve on the support.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_pcurve"
    )]
    pub pcurve: Option<PcurveGeometry>,
    /// First native constraint flag.
    pub first_flag: bool,
    /// ASM extension integer preceding the subdata.
    pub asm_extension: i64,
    /// Native constraint table.
    pub subdata: LoftSubdata<R>,
    /// Optional direction selected by the second native flag.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_direction"
    )]
    pub direction: Option<V>,
}

/// Type-selected fields of one loft profile member.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub enum LoftMemberForm<R = f64, V = Vector3> {
    /// Support-surface form. Legacy layouts can use type zero; revision-gated
    /// layouts select this form with a nonzero type code.
    Support {
        /// Native member type discriminator.
        type_code: i64,
        /// Constraint support surface, absent for the native `null_surface`
        /// sentinel.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_surface"
        )]
        surface: Option<SurfaceId>,
        /// Optional U/V bound fields following the support surface in the
        /// revision-gated encoding.
        #[serde(default)]
        support_bounds: [Option<R>; 4],
        /// UV curve on the support, absent for `nullbs`.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_pcurve"
        )]
        pcurve: Option<PcurveGeometry>,
        /// First native constraint flag.
        first_flag: bool,
        /// ASM extension integer when the stream version carries it.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_asm_extension"
        )]
        asm_extension: Option<i64>,
        /// Native constraint table.
        subdata: LoftSubdata<R>,
        /// Optional direction selected by the second native flag.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_direction"
        )]
        direction: Option<V>,
    },
    /// Revision-gated type-zero form with two nullable UV curve slots.
    PcurvePair {
        /// First UV curve slot, absent for `nullbs`.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_pcurve"
        )]
        pcurve: Option<PcurveGeometry>,
        /// Second UV curve slot, absent for `nullbs`.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_secondary_pcurve"
        )]
        secondary_pcurve: Option<PcurveGeometry>,
        /// ASM extension integer when the stream version carries it.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_asm_extension"
        )]
        asm_extension: Option<i64>,
        /// Native constraint table.
        subdata: LoftSubdata<R>,
        /// Optional direction selected by the second native flag.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_direction"
        )]
        direction: Option<V>,
    },
}

impl<R, V> LoftMemberForm<R, V> {
    /// Return the native type code selected by this form.
    #[must_use]
    pub fn type_code(&self) -> i64 {
        match self {
            Self::Support { type_code, .. } => *type_code,
            Self::PcurvePair { .. } => 0,
        }
    }

    /// Return the support surface when this is the support form.
    #[must_use]
    pub fn surface(&self) -> Option<&SurfaceId> {
        match self {
            Self::Support { surface, .. } => surface.as_ref(),
            Self::PcurvePair { .. } => None,
        }
    }

    /// Return the constraint subdata.
    #[must_use]
    pub fn subdata(&self) -> &LoftSubdata<R> {
        match self {
            Self::Support { subdata, .. } | Self::PcurvePair { subdata, .. } => subdata,
        }
    }

    /// Return the optional direction selected by the second native flag.
    #[must_use]
    pub fn direction(&self) -> Option<&V> {
        match self {
            Self::Support { direction, .. } | Self::PcurvePair { direction, .. } => {
                direction.as_ref()
            }
        }
    }
}

/// One referenced curve together with its optional native parameter bounds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct LoftPathCurve<R = f64> {
    /// Referenced curve carrier.
    #[serde(rename = "curve")]
    pub id: CurveId,
    /// Optional parameter endpoints following the curve in a revision-gated encoding.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_endpoints"
    )]
    pub endpoints: Option<[Option<R>; 2]>,
}

/// One curve member of a loft profile.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct LoftProfileMember<R = f64, V = Vector3> {
    /// Profile curve and its revision-gated parameter endpoints.
    pub profile: LoftPathCurve<R>,
    /// Structurally selected surface-side constraint form.
    pub form: LoftMemberForm<R, V>,
}

/// Native path data attached to one loft section entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct LoftPath<R = f64> {
    /// Primary path curve and its optional endpoints, absent for `null_curve`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_path"
    )]
    pub path: Option<LoftPathCurve<R>>,
    /// Ordered auxiliary BS3 curves.
    pub auxiliaries: Vec<CurveId>,
    /// Native path tail integer.
    pub flag: i64,
}

/// One parameterized entry in a native loft section.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct LoftSectionEntry<R = f64, V = Vector3> {
    /// Native section parameter.
    pub parameter: R,
    /// Ordered profile members.
    pub profile: Vec<LoftProfileMember<R, V>>,
    /// Native path data.
    pub path: LoftPath<R>,
}

/// Revision-gated `loft_spl_sur` form fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct LoftRevisionForm<R = f64> {
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Four booleans following the parameter intervals.
    #[serde(default)]
    pub flags: [bool; 4],
    /// Two integers preceding the shared tail.
    #[serde(default)]
    pub ints: [i64; 2],
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: RevisionCacheForm<RevisionSurfaceParameterization<R>>,
    /// Six ordered discontinuity arrays following the fit tolerance.
    #[serde(default)]
    pub discontinuities: [Vec<R>; 6],
    /// Boolean terminating the shared tail.
    pub tail_flag: bool,
}

/// Ordered native loft section.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct LoftSection<R = f64, V = Vector3> {
    /// Ordered entries in the section.
    pub entries: Vec<LoftSectionEntry<R, V>>,
}

/// Token retained from the variable bridge preceding a loft solved cache.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum LoftBridgeToken<R = f64> {
    /// Native boolean token.
    Boolean(bool),
    /// Native integer token.
    Integer(i64),
    /// Native double token.
    Double(R),
    /// Native string token.
    Text(String),
    /// Native enum token.
    Enum(i64),
}

/// Common carrier fields of one G2 blend side.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct G2BlendSide<V = Vector3> {
    /// Native side label.
    pub label: String,
    /// Primary support surface.
    pub surface: SurfaceId,
    /// Primary side curve.
    pub curve: CurveId,
    /// First and second ordered BS2 pcurves; each may be `nullbs`.
    pub pcurves: [Option<PcurveGeometry>; 2],
    /// Native side direction.
    pub direction: V,
}

/// Singularity-specific payload of the first G2 blend side.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub enum G2BlendFirstShape<R = f64> {
    /// Full singularity with an optional BS3 support surface.
    Full {
        /// Exact BS3 support and fit tolerance, when serialized.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_support"
        )]
        support: Option<G2BlendFullSupport>,
    },
    /// Non-singular nine-scalar frame and tertiary pcurve.
    None {
        /// Ordered native frame scalars.
        coefficients: [R; 9],
        /// Native fit tolerance.
        tolerance: FitTolerance,
        /// Optional intervening native token.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_extension"
        )]
        extension: Option<LoftBridgeToken<R>>,
        /// Tertiary BS2 pcurve, absent for `nullbs`.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_pcurve"
        )]
        pcurve: Option<PcurveGeometry>,
    },
}

/// Exact support surface and fit tolerance of a full G2 first-side shape.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct G2BlendFullSupport {
    /// Exact BS3 support surface.
    pub surface: SurfaceId,
    /// Fit tolerance of the support, in document length units.
    pub tolerance: FitTolerance,
}

/// Full native G2 blend construction graph.
// A source states raw values; a `G2BlendSurfacePayload` holds the admitted
// construction, whose scalars and vectors are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct G2BlendConstruction<R = f64, V = Vector3> {
    /// First side common fields.
    pub first: G2BlendSide<V>,
    /// Native first-side singularity enum.
    pub singularity: i64,
    /// First-side singularity payload.
    pub first_shape: G2BlendFirstShape<R>,
    /// Second side common fields.
    pub second: G2BlendSide<V>,
    /// Exact second-side spline support.
    pub second_exact_surface: SurfaceId,
    /// Center or transition curve.
    pub center_curve: CurveId,
    /// Ordered center-curve scalars.
    pub center_parameters: [R; 2],
    /// Native center tail integer.
    pub center_flag: i64,
    /// Native U and V intervals.
    pub parameter_ranges: [[R; 2]; 2],
    /// Four ordered trailing scalars.
    pub trailing_parameters: [R; 4],
    /// Three ordered ASM discontinuity arrays.
    pub discontinuities: [Vec<R>; 3],
}

/// A present rolling-ball support surface and its native UV bounds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RollingBallSupportSurface<S = SurfaceId, R = f64> {
    /// Support surface or embedded geometry.
    pub surface: S,
    /// Optional native U and V endpoints.
    pub parameter_ranges: [[Option<R>; 2]; 2],
}

/// A present rolling-ball side curve and its native parameter bounds.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RollingBallSupportCurve<C = CurveId, R = f64> {
    /// Side curve or embedded geometry.
    pub curve: C,
    /// Optional native parameter endpoints.
    pub parameter_range: [Option<R>; 2],
}

/// The optional rolling-ball extension clause.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(bound(deserialize = "P: Deserialize<'de>"))]
#[serde(deny_unknown_fields)]
pub struct RollingBallSideExtension<P = PcurveGeometry> {
    /// Native integer introducing the clause.
    pub value: i64,
    /// Tertiary BS2 pcurve, absent for `nullbs`.
    #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
    pub pcurve: Option<P>,
}

/// One complete native rolling-ball support side.
// A source states raw values; a blend construction holds the admitted side,
// whose endpoints are `FiniteReal` values and whose location is a
// `FinitePoint3`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(bound(
    serialize = "S: Serialize, C: Serialize, P: Serialize, R: Serialize, L: Serialize",
    deserialize = "S: Deserialize<'de>, C: Deserialize<'de>, P: Deserialize<'de>, R: Deserialize<'de>, L: Deserialize<'de>"
))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "S: JsonSchema + Serialize, C: JsonSchema + Serialize, P: JsonSchema + Serialize, R: JsonSchema + Serialize, L: JsonSchema + Serialize"
    )
)]
pub struct RollingBallSide<S = SurfaceId, C = CurveId, P = PcurveGeometry, R = f64, L = Point3> {
    /// Geometry role selected by the support-side discriminator.
    pub support_kind: VariableBlendSupportKind,
    /// Primary support surface and bounds, absent for `null_surface`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_rolling_ball_side_surface"
    )]
    pub surface: Option<RollingBallSupportSurface<S, R>>,
    /// Side curve and bounds, absent for `null_curve`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_curve"
    )]
    pub curve: Option<RollingBallSupportCurve<C, R>>,
    /// Primary BS2 pcurve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_rolling_ball_side_pcurve"
    )]
    pub pcurve: Option<P>,
    /// Native model-space side location.
    pub location: L,
    /// ASM secondary BS2 pcurve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_rolling_ball_side_secondary_pcurve"
    )]
    pub secondary_pcurve: Option<P>,
    /// Native extension integer and nullable tertiary pcurve.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_rolling_ball_side_extension"
    )]
    pub extension: Option<RollingBallSideExtension<P>>,
}

/// Third support graph appended by `sss_blend_spl_sur`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct RollingBallThirdSide<V = Vector3> {
    /// Native side label.
    pub label: String,
    /// Third support surface.
    pub surface: SurfaceId,
    /// Third side curve.
    pub curve: CurveId,
    /// Primary BS2 pcurve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_pcurve"
    )]
    pub pcurve: Option<PcurveGeometry>,
    /// Native side vector.
    pub direction: V,
    /// ASM secondary BS2 pcurve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_secondary_pcurve"
    )]
    pub secondary_pcurve: Option<PcurveGeometry>,
    /// Native ASM integer following the secondary pcurve.
    pub extension: i64,
    /// ASM tertiary BS2 pcurve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_tertiary_pcurve"
    )]
    pub tertiary_pcurve: Option<PcurveGeometry>,
    /// Final ASM flag.
    pub flag: bool,
}

/// Native optional-radius selector in a rolling-ball construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RollingBallRadiusSelector<T = f64> {
    /// The construction states no radius.
    None {},
    /// Explicit native selector scalar.
    Value {
        /// Stored scalar value.
        value: T,
    },
}

/// Complete byte-backed rolling-ball or three-surface blend context.
// A source states raw values; a `BlendSurfacePayload` holds the admitted
// construction, whose scalars, vectors and points are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct RollingBallConstruction<R = f64, V = Vector3, P = Point3> {
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Two ordered primary support sides.
    pub sides: [RollingBallSide<SurfaceId, CurveId, PcurveGeometry, R, P>; 2],
    /// Stored slice or center curve.
    pub slice: CurveId,
    /// Optional native slice-curve parameter endpoints.
    #[serde(default)]
    pub slice_range: [Option<R>; 2],
    /// Two signed support offsets in document length units.
    pub offsets: [R; 2],
    /// Optional-radius selector field.
    pub radius_selector: RollingBallRadiusSelector<R>,
    /// Native optional U interval endpoints.
    pub u_range: [Option<R>; 2],
    /// Native optional V interval endpoints.
    pub v_range: [Option<R>; 2],
    /// Native integer preceding the trailing scalars.
    pub shape_prefix: i64,
    /// Two ordered trailing scalars.
    pub parameters: [R; 2],
    /// Native long following the trailing scalars.
    pub tail: i64,
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: RevisionCacheForm<RevisionSurfaceParameterization<R>>,
    /// Six ordered ASM discontinuity arrays closing the shared tail.
    pub discontinuities: [Vec<R>; 6],
    /// Native Boolean closing the shared tail.
    #[serde(default)]
    pub tail_flag: bool,
    /// Third side present only for `sss_blend_spl_sur`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_third"
    )]
    pub third: Option<Box<RollingBallThirdSide<V>>>,
    /// Three ASM integers preceding the subtype close.
    #[serde(default)]
    pub tail_extensions: [i64; 3],
}

/// Geometry role selected by a variable-blend support-side discriminator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum VariableBlendSupportKind {
    /// Support defined by a cosine curve.
    CosineCurve,
    /// Support defined by a general curve.
    Curve,
    /// Support defined by a point curve.
    PointCurve,
    /// Support defined by a surface.
    Surface,
    /// Support defined by a zero curve.
    ZeroCurve,
}

/// Convexity selected for a variable-radius blend surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum VariableBlendConvexity {
    /// The blend bends toward the support intersection.
    Convex,
    /// The blend bends away from the support intersection.
    Concave,
}

/// Solved-surface representation selected for a variable-radius blend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum VariableBlendRenderMode {
    /// The solved surface is the rolling-ball envelope.
    RollingBallEnvelope,
    /// The solved surface is a rolling-ball snapshot.
    RollingBallSnapshot,
}

/// One interpolation control point in a variable blend-value law.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VariableBlendInterpolationPoint<R = f64, V = Vector3, P = Point3> {
    /// Law parameter.
    pub parameter: R,
    /// Radius in document length units.
    pub radius: R,
    /// Optional first and second derivative scalars.
    pub tangents: [Option<R>; 2],
    /// Model-space control location.
    pub location: P,
    /// Control normal.
    pub normal: V,
}

/// Native edge-offset blend-value sub-discriminator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "i64", into = "i64")]
pub enum EdgeOffsetDiscriminator {
    /// Explicit zero sub-discriminator.
    Zero,
    /// One sub-discriminator, including the elided default.
    One,
}

impl EdgeOffsetDiscriminator {
    /// Admit the two native edge-offset codes.
    pub const fn from_code(code: i64) -> Option<Self> {
        match code {
            0 => Some(Self::Zero),
            1 => Some(Self::One),
            _ => None,
        }
    }

    /// Native integer code.
    pub const fn code(self) -> i64 {
        match self {
            Self::Zero => 0,
            Self::One => 1,
        }
    }
}

/// An edge-offset blend value carries sub-discriminator 0 or 1.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("edge-offset discriminator must be 0 or 1")]
pub struct EdgeOffsetDiscriminatorCode;

impl TryFrom<i64> for EdgeOffsetDiscriminator {
    type Error = EdgeOffsetDiscriminatorCode;

    fn try_from(code: i64) -> Result<Self, Self::Error> {
        Self::from_code(code).ok_or(EdgeOffsetDiscriminatorCode)
    }
}

impl From<EdgeOffsetDiscriminator> for i64 {
    fn from(discriminator: EdgeOffsetDiscriminator) -> Self {
        discriminator.code()
    }
}

/// Numeric or symbolic terminal of a functional blend-value law.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum VariableBlendTerminal<R = f64> {
    /// Native double token.
    Double(R),
    /// Native string token.
    Text(String),
}

/// Complete recursive native `getBlendValues` payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VariableBlendValue<R = f64, V = Vector3, P = Point3> {
    /// Native Boolean following the calibrated enum.
    pub modern_flag: bool,
    /// Native calibrated enum.
    pub calibrated: i64,
    /// Type-specific payload with its native sub-discriminator.
    pub payload: VariableBlendValuePayload<R, V, P>,
}

/// Type-specific payload of a variable blend value.
///
/// Each arm carries the native sub-discriminator it admits: the edge-offset
/// arm is one of two codes, so an edge-offset value with any other
/// sub-discriminator has no spelling.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum VariableBlendValuePayload<R = f64, V = Vector3, P = Point3> {
    /// Law-domain parameter range and two endpoint radii.
    TwoEnds {
        /// Native sub-discriminator preceding the calibrated enum.
        discriminator: i64,
        /// Law-domain parameter range (lower, upper).
        parameters: [R; 2],
        /// Endpoint radii in document length units.
        radii: [R; 2],
    },
    /// Fixed-width branch: the parameter-range bounds and the chamfer width
    /// scalar, stored unscaled.
    FixedWidth {
        /// Native sub-discriminator preceding the calibrated enum.
        discriminator: i64,
        /// Parameter-range lower and upper bounds.
        parameters: [R; 2],
        /// Chamfer width.
        width: R,
    },
    /// Edge-offset branch.
    EdgeOffset {
        /// Native sub-discriminator preceding the calibrated enum.
        discriminator: EdgeOffsetDiscriminator,
        /// Ordered native scalar payload.
        scalars: [R; 2],
        /// Ordered length payload in document units.
        lengths: [R; 1],
    },
    /// Functional radius law carried by a BS2 pcurve.
    Functional {
        /// Native sub-discriminator preceding the calibrated enum.
        discriminator: i64,
        /// Leading scalar.
        parameter: R,
        /// Leading length in document units.
        radius: R,
        /// Scalar function whose first coordinate is radius in document units.
        function: PcurveGeometry,
        /// Numeric or symbolic terminal value.
        terminal: VariableBlendTerminal<R>,
    },
    /// Constant law followed by a recursive chamfer value.
    Constant {
        /// Native sub-discriminator preceding the calibrated enum.
        discriminator: i64,
        /// Ordered native scalars.
        parameters: [R; 2],
        /// Radius in document length units.
        radius: R,
        /// Native variable-chamfer enum.
        variable_chamfer: i64,
        /// Native chamfer-type enum.
        chamfer_type: i64,
        /// Recursively nested blend value.
        nested: Box<VariableBlendValue<R, V, P>>,
    },
    /// Interpolated radius law.
    Interpolated {
        /// Native sub-discriminator preceding the calibrated enum.
        discriminator: i64,
        /// Leading scalar.
        parameter: R,
        /// Leading radius in document length units.
        radius: R,
        /// Scalar function whose first coordinate is radius in document units.
        function: PcurveGeometry,
        /// Native extension enum, stored ahead of the radius-point count. It
        /// gates nothing; the payload ends at the last radius point.
        enum_count: i64,
        /// Whether the extension enum is stored as a `0x15` enum token
        /// (revision-gated streams) rather than a `0x04` integer.
        #[serde(default)]
        enum_tagged: bool,
        /// Counted radius-point array: each control carries a parameter,
        /// radius, two derivative scalars, a position, and a vector.
        points: Vec<VariableBlendInterpolationPoint<R, V, P>>,
    },
}

impl<R, V, P> VariableBlendValuePayload<R, V, P> {
    /// Native sub-discriminator preceding the calibrated enum.
    pub const fn discriminator(&self) -> i64 {
        match self {
            Self::EdgeOffset { discriminator, .. } => discriminator.code(),
            Self::TwoEnds { discriminator, .. }
            | Self::FixedWidth { discriminator, .. }
            | Self::Functional { discriminator, .. }
            | Self::Constant { discriminator, .. }
            | Self::Interpolated { discriminator, .. } => *discriminator,
        }
    }

    /// Native type name introducing this payload.
    pub const fn native_name(&self) -> &'static str {
        match self {
            Self::TwoEnds { .. } => "two_ends",
            Self::FixedWidth { .. } => "fixed_width",
            Self::EdgeOffset { .. } => "edge_offset",
            Self::Functional { .. } => "functional",
            Self::Constant { .. } => "const",
            Self::Interpolated { .. } => "interp",
        }
    }
}

/// Radius-law payloads of a variable blend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum VariableBlendRadii<R = f64, V = Vector3, P = Point3> {
    /// One radius law controls both support sides.
    Single {
        /// Shared radius law.
        value: VariableBlendValue<R, V, P>,
    },
    /// Each support side has an independent radius law.
    Two {
        /// First support-side radius law.
        first: VariableBlendValue<R, V, P>,
        /// Second support-side radius law.
        second: VariableBlendValue<R, V, P>,
    },
}

impl<R, V, P> VariableBlendRadii<R, V, P> {
    /// First radius law in native order.
    #[must_use]
    pub const fn first(&self) -> &VariableBlendValue<R, V, P> {
        match self {
            Self::Single { value } | Self::Two { first: value, .. } => value,
        }
    }

    /// Second radius law when both sides are controlled independently.
    #[must_use]
    pub const fn second(&self) -> Option<&VariableBlendValue<R, V, P>> {
        match self {
            Self::Single { .. } => None,
            Self::Two { second, .. } => Some(second),
        }
    }

    /// Whether one radius law controls both sides.
    #[must_use]
    pub const fn is_single(&self) -> bool {
        matches!(self, Self::Single { .. })
    }
}

/// Cross-section clause following the variable-radius laws.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub enum VariableBlendCrossSection<R = f64, V = Vector3, P = Point3> {
    /// Circular section with no additional parameters.
    Circular {},
    /// Thumbweight-controlled section with two ordered shape parameters.
    Thumbweights {
        /// Ordered native shape parameters.
        parameters: [R; 2],
    },
    /// Rounded chamfer with an optional independent rounding-radius law.
    RoundedChamfer {
        /// Rounding-radius law; absent when the clause stores `no_radius`.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_radius"
        )]
        radius: Option<Box<VariableBlendValue<R, V, P>>>,
    },
    /// Curvature-continuous round with two ordered shape parameters.
    G2Round {
        /// Ordered native shape parameters.
        parameters: [R; 2],
    },
    /// A zero-width native selector whose record framing is known but whose
    /// geometric cross-section law is not classified.
    UnclassifiedBare {
        /// Exact numeric selector retained from the native record.
        selector: VariableBlendBareCrossSection,
    },
}

/// Native zero-width variable-blend cross-section selectors whose framing is
/// established while their geometric laws remain unclassified.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[repr(i64)]
#[serde(deny_unknown_fields)]
pub enum VariableBlendBareCrossSection {
    /// Native selector `2`.
    Selector2 = 2,
    /// Native selector `4`.
    Selector4 = 4,
    /// Native selector `5`.
    Selector5 = 5,
    /// Native selector `6`.
    Selector6 = 6,
}

impl VariableBlendBareCrossSection {
    /// Numeric selector stored in the native variable-blend record.
    pub const fn native_selector(self) -> i64 {
        match self {
            Self::Selector2 => 2,
            Self::Selector4 => 4,
            Self::Selector5 => 5,
            Self::Selector6 => 6,
        }
    }
}

impl TryFrom<i64> for VariableBlendBareCrossSection {
    type Error = ();

    fn try_from(value: i64) -> Result<Self, Self::Error> {
        match value {
            2 => Ok(Self::Selector2),
            4 => Ok(Self::Selector4),
            5 => Ok(Self::Selector5),
            6 => Ok(Self::Selector6),
            _ => Err(()),
        }
    }
}

/// Native variable-radius blend surface subtype.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum VariableBlendSurfaceSubtype {
    /// General variable-blend surface.
    #[default]
    VariableBlend,
    /// Surface-to-surface variable blend.
    SurfaceSurface,
    /// Curve-to-curve variable blend.
    CurveCurve,
    /// Curve-to-surface variable blend.
    CurveSurface,
    /// Free surface-curve variable blend.
    SurfaceCurveFree,
}

/// Complete native variable-radius blend construction graph.
// A source states raw values; a `VariableBlendSurfacePayload` holds the
// admitted construction, whose scalars, vectors and points are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct VariableBlendConstruction<R = f64, V = Vector3, P = Point3> {
    /// Native surface subtype selecting the variable-blend behavior class.
    #[serde(default)]
    pub subtype: VariableBlendSurfaceSubtype,
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Two ordered support-side graphs in the rolling-ball side layout.
    pub sides: [RollingBallSide<SurfaceId, CurveId, PcurveGeometry, R, P>; 2],
    /// Stored slice curve.
    pub slice: CurveId,
    /// Optional native slice-curve parameter endpoints.
    #[serde(default)]
    pub slice_range: [Option<R>; 2],
    /// Two signed support offsets in document length units.
    pub offsets: [R; 2],
    /// Structurally selected radius-control payloads.
    pub radii: VariableBlendRadii<R, V, P>,
    /// Cross-section clause following the complete radius-law sequence.
    /// Absence denotes an elided default circular section; an explicit
    /// circular clause remains distinct.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_cross_section"
    )]
    pub cross_section: Option<VariableBlendCrossSection<R, V, P>>,
    /// Support-side parameter interval `(T0, T1)`; both bounds present in
    /// every instance.
    pub u_range: [R; 2],
    /// Second interval: a lower bound with an unbounded-above marker,
    /// encoded as `(T lo, F)` and decoding to `[Some(lo), None]`. The `F`
    /// upper-bound marker is an interval bound, not a standalone Boolean.
    #[serde(
        rename = "v_lower",
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_v_lower"
    )]
    pub v_lower: Option<R>,
    /// Requested fit tolerance for the surface cache.
    pub shape_parameter: R,
    /// Achieved fit tolerance for the surface cache, in document units.
    pub shape_length: R,
    /// Native integer immediately before the shared tail's enum.
    pub shape_tail: i64,
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: VariableBlendCache<R>,
    /// Six ordered ASM discontinuity arrays closing the shared tail.
    pub discontinuities: [Vec<R>; 6],
    /// Native Boolean following the discontinuity arrays.
    pub tail_flag: bool,
    /// Three ASM integers following the tail Boolean.
    pub tail_extensions: [i64; 3],
    /// Secondary curve and its bounds, absent for `null_curve`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_secondary_curve"
    )]
    pub secondary_curve: Option<RollingBallSupportCurve<CurveId, R>>,
    /// Blend convexity.
    pub convexity: VariableBlendConvexity,
    /// Solved-surface representation.
    pub render_mode: VariableBlendRenderMode,
    /// Native optional post-shape interval endpoints.
    pub post_range: [Option<R>; 2],
    /// Native post-shape BS3 curve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_post_curve"
    )]
    pub post_curve: Option<CurveId>,
    /// Native post-shape BS2 pcurve, absent for `nullbs`.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_post_pcurve"
    )]
    pub post_pcurve: Option<PcurveGeometry>,
}

/// Complete native revision-gated `g2_blend_spl_sur` construction. The
/// revision layout stores the two support sides in the variable-blend side
/// layout and ends with the shared revision-gated surface tail.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "RevisionG2BlendConstructionWire")]
pub struct RevisionG2BlendConstruction {
    revision: PositiveI64,
    leading_parameters: [FiniteReal; 2],
    #[cfg_attr(feature = "schema", schemars(with = "Box<[RollingBallSide; 2]>"))]
    sides: [RollingBallSide<SurfaceId, CurveId, PcurveGeometry, FiniteReal, FinitePoint3>; 2],
    center: CurveId,
    #[serde(default)]
    center_range: [Option<FiniteReal>; 2],
    radii: [FiniteReal; 2],
    radius_selector: RollingBallRadiusSelector<PositiveI64>,
    u_range: [Option<FiniteReal>; 2],
    v_range: [Option<FiniteReal>; 2],
    shape_prefix: i64,
    shape_parameter: FiniteReal,
    shape_length: FiniteReal,
    shape_tail: i64,
    #[cfg_attr(feature = "schema", schemars(with = "RevisionCacheForm"))]
    cache: RevisionCacheForm<RevisionSurfaceParameterization<FiniteReal>>,
    #[serde(default)]
    discontinuities: [Vec<FiniteReal>; 6],
    tail_flag: bool,
    tail_extensions: [i64; 3],
}

/// Stored fields of a revision-gated `g2_blend_spl_sur` construction before
/// admission. This is the wire shape the deserializer reads and the only
/// input `RevisionG2BlendConstruction::admit` accepts.
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "RevisionG2BlendConstruction"))]
#[serde(deny_unknown_fields)]
pub struct RevisionG2BlendConstructionWire {
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Two native scalars following the revision integer.
    pub leading_parameters: [f64; 2],
    /// Two ordered support-side graphs in the variable-blend side layout.
    pub sides: Box<[RollingBallSide; 2]>,
    /// Stored center curve.
    pub center: CurveId,
    /// Optional native center-curve parameter endpoints.
    #[serde(default)]
    pub center_range: [Option<f64>; 2],
    /// Two signed blend radii in document length units.
    pub radii: [f64; 2],
    /// Integer-valued optional-radius selector following the radii.
    pub radius_selector: RollingBallRadiusSelector<PositiveI64>,
    /// Native optional U interval endpoints.
    pub u_range: [Option<f64>; 2],
    /// Native optional V interval endpoints.
    pub v_range: [Option<f64>; 2],
    /// Native integer before the solved shape.
    pub shape_prefix: i64,
    /// Native scalar before the solved shape.
    pub shape_parameter: f64,
    /// Native length before the solved shape, in document units.
    pub shape_length: f64,
    /// Native integer immediately before the shared tail.
    pub shape_tail: i64,
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: RevisionCacheForm,
    /// Six ordered discontinuity arrays following the fit tolerance.
    #[serde(default)]
    pub discontinuities: [Vec<f64>; 6],
    /// Boolean terminating the shared tail.
    pub tail_flag: bool,
    /// Three ASM integers following the shared tail.
    pub tail_extensions: [i64; 3],
}

impl RevisionG2BlendConstruction {
    /// Admit stored fields whose scalars are all finite. This is the
    /// admission of the `revision_g2_blend` procedural surface: a decoder
    /// that reads the fields admits them here, and the deserializer runs the
    /// same walk. The fields are private, so this and the deserializer are
    /// the only routes to a value.
    pub fn admit(wire: RevisionG2BlendConstructionWire) -> Result<Self, ProceduralGeometryError> {
        let invalid = || {
            ProceduralGeometryError::Payload("revision g2 blend construction payload is invalid")
        };
        let [first, second] = *wire.sides;
        let (
            Some(leading_parameters),
            Some(center_range),
            Some(radii),
            Some(u_range),
            Some(v_range),
            Some([shape_parameter, shape_length]),
            Some(discontinuities),
            Some(first),
            Some(second),
            Some(cache),
        ) = (
            FiniteReal::array(wire.leading_parameters),
            FiniteReal::optional(wire.center_range),
            FiniteReal::array(wire.radii),
            FiniteReal::optional(wire.u_range),
            FiniteReal::optional(wire.v_range),
            FiniteReal::array([wire.shape_parameter, wire.shape_length]),
            FiniteReal::lanes(wire.discontinuities),
            first.admit(),
            second.admit(),
            wire.cache.admit(),
        )
        else {
            return Err(invalid());
        };
        Ok(Self {
            revision: wire.revision,
            leading_parameters,
            sides: [first, second],
            center: wire.center,
            center_range,
            radii,
            radius_selector: wire.radius_selector,
            u_range,
            v_range,
            shape_prefix: wire.shape_prefix,
            shape_parameter,
            shape_length,
            shape_tail: wire.shape_tail,
            cache,
            discontinuities,
            tail_flag: wire.tail_flag,
            tail_extensions: wire.tail_extensions,
        })
    }

    /// Return the positive serializer-revision integer.
    #[must_use]
    pub const fn revision(&self) -> PositiveI64 {
        self.revision
    }

    /// Return the two native scalars following the revision integer.
    #[must_use]
    pub const fn leading_parameters(&self) -> [FiniteReal; 2] {
        self.leading_parameters
    }

    /// Return the two ordered support-side graphs.
    #[must_use]
    pub const fn sides(
        &self,
    ) -> &[RollingBallSide<SurfaceId, CurveId, PcurveGeometry, FiniteReal, FinitePoint3>; 2] {
        &self.sides
    }

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

    /// Return the optional center-curve parameter endpoints.
    #[must_use]
    pub const fn center_range(&self) -> [Option<FiniteReal>; 2] {
        self.center_range
    }

    /// Return the two signed blend radii.
    #[must_use]
    pub const fn radii(&self) -> [FiniteReal; 2] {
        self.radii
    }

    /// Return the optional-radius selector.
    #[must_use]
    pub const fn radius_selector(&self) -> &RollingBallRadiusSelector<PositiveI64> {
        &self.radius_selector
    }

    /// Return the optional U interval endpoints.
    #[must_use]
    pub const fn u_range(&self) -> [Option<FiniteReal>; 2] {
        self.u_range
    }

    /// Return the optional V interval endpoints.
    #[must_use]
    pub const fn v_range(&self) -> [Option<FiniteReal>; 2] {
        self.v_range
    }

    /// Return the integer before the solved shape.
    #[must_use]
    pub const fn shape_prefix(&self) -> i64 {
        self.shape_prefix
    }

    /// Return the scalar before the solved shape.
    #[must_use]
    pub const fn shape_parameter(&self) -> FiniteReal {
        self.shape_parameter
    }

    /// Return the length before the solved shape.
    #[must_use]
    pub const fn shape_length(&self) -> FiniteReal {
        self.shape_length
    }

    /// Return the integer immediately before the shared tail.
    #[must_use]
    pub const fn shape_tail(&self) -> i64 {
        self.shape_tail
    }

    /// Return the approximation-cache form.
    #[must_use]
    pub const fn cache(&self) -> &RevisionCacheForm<RevisionSurfaceParameterization<FiniteReal>> {
        &self.cache
    }

    /// Return the six ordered discontinuity arrays.
    #[must_use]
    pub const fn discontinuities(&self) -> &[Vec<FiniteReal>; 6] {
        &self.discontinuities
    }

    /// Return the Boolean terminating the shared tail.
    #[must_use]
    pub const fn tail_flag(&self) -> bool {
        self.tail_flag
    }

    /// Return the three ASM integers following the shared tail.
    #[must_use]
    pub const fn tail_extensions(&self) -> [i64; 3] {
        self.tail_extensions
    }
}

impl TryFrom<RevisionG2BlendConstructionWire> for RevisionG2BlendConstruction {
    type Error = ProceduralGeometryError;

    fn try_from(wire: RevisionG2BlendConstructionWire) -> Result<Self, Self::Error> {
        Self::admit(wire)
    }
}

/// Complete native revision-gated `cl_loft_spl_sur` construction. The
/// revision layout is cache-first: the revision integer and shared
/// revision-gated surface tail precede the construction fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "RevisionCompoundLoftConstructionWire")]
pub struct RevisionCompoundLoftConstruction {
    revision: PositiveI64,
    #[cfg_attr(feature = "schema", schemars(with = "RevisionCacheForm"))]
    cache: RevisionCacheForm<RevisionSurfaceParameterization<FiniteReal>>,
    #[serde(default)]
    discontinuities: [Vec<FiniteReal>; 6],
    tail_flag: bool,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<LoftProfileMember>"))]
    base_profile: Vec<LoftProfileMember<FiniteReal, FiniteVector3>>,
    #[cfg_attr(feature = "schema", schemars(with = "LoftPath"))]
    base_path: LoftPath<FiniteReal>,
    #[cfg_attr(feature = "schema", schemars(with = "Vec<LoftSectionEntry>"))]
    entries: Vec<LoftSectionEntry<FiniteReal, FiniteVector3>>,
    flags: [bool; 2],
    kind_flags: [bool; 2],
    #[cfg_attr(feature = "schema", schemars(with = "CompoundLoftDirection"))]
    direction: CompoundLoftDirection<FiniteVector3>,
    tail: RevisionCompoundLoftTail<CurveId, FiniteReal>,
}

/// Stored fields of a revision-gated `cl_loft_spl_sur` construction before
/// admission. This is the wire shape the deserializer reads and the only
/// input `RevisionCompoundLoftConstruction::admit` accepts.
#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(
    feature = "schema",
    schemars(rename = "RevisionCompoundLoftConstruction")
)]
#[serde(deny_unknown_fields)]
pub struct RevisionCompoundLoftConstructionWire {
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: RevisionCacheForm,
    /// Six ordered discontinuity arrays following the fit tolerance.
    #[serde(default)]
    pub discontinuities: [Vec<f64>; 6],
    /// Boolean terminating the shared tail.
    pub tail_flag: bool,
    /// Leading unparameterized scale block: ordered profile members and path.
    pub base_profile: Vec<LoftProfileMember>,
    /// Path data of the leading scale block.
    pub base_path: LoftPath,
    /// Counted parameterized entries; the native parameter trails each
    /// entry's fields.
    pub entries: Vec<LoftSectionEntry>,
    /// Two flags following the entries.
    pub flags: [bool; 2],
    /// Two flags opening the kind-zero payload.
    pub kind_flags: [bool; 2],
    /// Direction carrier selected by the kind-zero direction tag.
    pub direction: CompoundLoftDirection,
    /// Trailing bounds and their dependent BS3 curve.
    pub tail: RevisionCompoundLoftTail<CurveId>,
}

impl RevisionCompoundLoftConstruction {
    /// Admit stored fields whose scalars are all finite. This is the
    /// admission of the `revision_compound_loft` procedural surface: a
    /// decoder that reads the fields admits them here, and the deserializer
    /// runs the same walk. The fields are private, so this and the
    /// deserializer are the only routes to a value.
    pub fn admit(
        wire: RevisionCompoundLoftConstructionWire,
    ) -> Result<Self, ProceduralGeometryError> {
        let invalid = || {
            ProceduralGeometryError::Payload(
                "revision compound loft construction payload is invalid",
            )
        };
        let (
            Some(discontinuities),
            Some(tail),
            Some(cache),
            Some(base_profile),
            Some(base_path),
            Some(entries),
            Some(direction),
        ) = (
            FiniteReal::lanes(wire.discontinuities),
            wire.tail.admit(),
            wire.cache.admit(),
            wire.base_profile
                .into_iter()
                .map(LoftProfileMember::admit)
                .collect::<Option<Vec<_>>>(),
            wire.base_path.admit(),
            wire.entries
                .into_iter()
                .map(LoftSectionEntry::admit)
                .collect::<Option<Vec<_>>>(),
            wire.direction.admit(),
        )
        else {
            return Err(invalid());
        };
        Ok(Self {
            revision: wire.revision,
            cache,
            discontinuities,
            tail_flag: wire.tail_flag,
            base_profile,
            base_path,
            entries,
            flags: wire.flags,
            kind_flags: wire.kind_flags,
            direction,
            tail,
        })
    }

    /// Return the positive serializer-revision integer.
    #[must_use]
    pub const fn revision(&self) -> PositiveI64 {
        self.revision
    }

    /// Return the approximation-cache form.
    #[must_use]
    pub const fn cache(&self) -> &RevisionCacheForm<RevisionSurfaceParameterization<FiniteReal>> {
        &self.cache
    }

    /// Return the six ordered discontinuity arrays.
    #[must_use]
    pub const fn discontinuities(&self) -> &[Vec<FiniteReal>; 6] {
        &self.discontinuities
    }

    /// Return the Boolean terminating the shared tail.
    #[must_use]
    pub const fn tail_flag(&self) -> bool {
        self.tail_flag
    }

    /// Return the profile members of the leading scale block.
    #[must_use]
    pub fn base_profile(&self) -> &[LoftProfileMember<FiniteReal, FiniteVector3>] {
        &self.base_profile
    }

    /// Return the path data of the leading scale block.
    #[must_use]
    pub const fn base_path(&self) -> &LoftPath<FiniteReal> {
        &self.base_path
    }

    /// Return the counted parameterized entries.
    #[must_use]
    pub fn entries(&self) -> &[LoftSectionEntry<FiniteReal, FiniteVector3>] {
        &self.entries
    }

    /// Return the two flags following the entries.
    #[must_use]
    pub const fn flags(&self) -> [bool; 2] {
        self.flags
    }

    /// Return the two flags opening the kind-zero payload.
    #[must_use]
    pub const fn kind_flags(&self) -> [bool; 2] {
        self.kind_flags
    }

    /// Return the direction carrier of the kind-zero payload.
    #[must_use]
    pub const fn direction(&self) -> &CompoundLoftDirection<FiniteVector3> {
        &self.direction
    }

    /// Return the trailing bounds and their dependent BS3 curve.
    #[must_use]
    pub const fn tail(&self) -> &RevisionCompoundLoftTail<CurveId, FiniteReal> {
        &self.tail
    }
}

impl TryFrom<RevisionCompoundLoftConstructionWire> for RevisionCompoundLoftConstruction {
    type Error = ProceduralGeometryError;

    fn try_from(wire: RevisionCompoundLoftConstructionWire) -> Result<Self, Self::Error> {
        Self::admit(wire)
    }
}

/// Trailing parameter bounds of a revision compound loft.
/// Both bounds select a trailing curve; all other forms contain no curve.
// A source states raw bounds; a `RevisionCompoundLoftConstruction` holds the
// admitted tail, whose bounds are `FiniteReal` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    tag = "kind",
    rename_all = "snake_case",
    deny_unknown_fields,
    bound(
        serialize = "T: Serialize, S: Serialize",
        deserialize = "T: Deserialize<'de>, S: Deserialize<'de>"
    )
)]
pub enum RevisionCompoundLoftTail<T, S = f64> {
    /// Neither parameter bound is present.
    Unbounded {},
    /// Only the lower parameter bound is present.
    LowerBound {
        /// Lower parameter bound.
        lower: S,
    },
    /// Only the upper parameter bound is present.
    UpperBound {
        /// Upper parameter bound.
        upper: S,
    },
    /// Both parameter bounds and their selected curve.
    Curve {
        /// Ordered lower and upper parameter bounds.
        interval: [S; 2],
        /// Curve selected by the complete parameter pair.
        curve: T,
    },
}

impl<T> RevisionCompoundLoftTail<T> {
    /// The tail with admitted bounds, absent when a stored bound is not
    /// finite.
    fn admit(self) -> Option<RevisionCompoundLoftTail<T, FiniteReal>> {
        Some(match self {
            Self::Unbounded {} => RevisionCompoundLoftTail::Unbounded {},
            Self::LowerBound { lower } => RevisionCompoundLoftTail::LowerBound {
                lower: FiniteReal::new(lower)?,
            },
            Self::UpperBound { upper } => RevisionCompoundLoftTail::UpperBound {
                upper: FiniteReal::new(upper)?,
            },
            Self::Curve { interval, curve } => RevisionCompoundLoftTail::Curve {
                interval: FiniteReal::array(interval)?,
                curve,
            },
        })
    }
}

impl<T, S: Copy> RevisionCompoundLoftTail<T, S> {
    /// Optional bounds in native order.
    #[must_use]
    pub const fn interval(&self) -> [Option<S>; 2] {
        match self {
            Self::Unbounded {} => [None, None],
            Self::LowerBound { lower } => [Some(*lower), None],
            Self::UpperBound { upper } => [None, Some(*upper)],
            Self::Curve { interval, .. } => [Some(interval[0]), Some(interval[1])],
        }
    }

    /// Curve selected by a complete parameter pair.
    #[must_use]
    pub const fn curve(&self) -> Option<&T> {
        match self {
            Self::Curve { curve, .. } => Some(curve),
            _ => None,
        }
    }
}

/// One boundary record in a native vertex-blend patch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct VertexBlendBoundary<R = f64, V = Vector3, P = Point3> {
    /// Native cross flag. The wire form is a logical, so the value is the
    /// tag itself and no payload follows.
    pub boundary_type: bool,
    /// Native magic direction with finite components, stored as read. It is a
    /// direction, never a length, so it carries no unit scale.
    pub magic: V,
    /// Native U-smoothing flag, a logical on the wire.
    pub u_smoothing: bool,
    /// Native V-smoothing flag, a logical on the wire.
    pub v_smoothing: bool,
    /// Native fullness scalar.
    pub fullness: R,
    /// Structurally selected boundary geometry.
    pub geometry: VertexBlendBoundaryGeometry<R, V, P>,
}

/// Twist payload selected by a vertex-blend circle form.
#[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 VertexBlendTwists<P = Point3> {
    /// Native form zero: no twist entries.
    None {},
    /// Native form one: one twist entry.
    One {
        /// The one twist entry.
        twist: P,
    },
    /// Native form three: two ordered twist entries.
    Two {
        /// The two ordered twist entries.
        twists: [P; 2],
    },
}

impl<P> VertexBlendTwists<P> {
    /// Native form selected by the twist payload.
    #[must_use]
    pub const fn form(&self) -> i64 {
        match self {
            Self::None {} => 0,
            Self::One { .. } => 1,
            Self::Two { .. } => 3,
        }
    }

    /// Ordered twist entries. Their coordinate semantics depend on the layout revision.
    #[must_use]
    pub fn entries(&self) -> &[P] {
        match self {
            Self::None {} => &[],
            Self::One { twist } => std::slice::from_ref(twist),
            Self::Two { twists } => twists,
        }
    }
}

/// Type-specific geometry of a vertex-blend boundary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub enum VertexBlendBoundaryGeometry<R = f64, V = Vector3, P = Point3> {
    /// Curve boundary with a circle/ellipse/unknown twist form.
    Circle {
        /// Boundary curve.
        curve: CurveId,
        /// Optional native curve parameter endpoints stored by the
        /// revision-gated layout.
        #[serde(default)]
        curve_endpoints: [Option<R>; 2],
        /// Twist payload. Pre-revision layouts store model-space locations;
        /// the revision-gated layout stores unscaled twist vectors.
        twists: VertexBlendTwists<P>,
        /// Two ordered curve parameters.
        parameters: [R; 2],
        /// Native sense flag, a logical on the wire.
        sense: bool,
    },
    /// Degenerate boundary at a model-space location.
    Degenerate {
        /// Degenerate location.
        location: P,
        /// Two ordered boundary normals.
        normals: [V; 2],
    },
    /// Surface pcurve boundary.
    Pcurve {
        /// Support surface.
        surface: SurfaceId,
        /// Optional U/V bound fields stored after the support by the
        /// revision-gated layout.
        #[serde(default)]
        support_bounds: [Option<R>; 4],
        /// Native BS2 pcurve, absent for `nullbs`.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_pcurve"
        )]
        pcurve: Option<PcurveGeometry>,
        /// Native sense flag, a logical on the wire.
        sense: bool,
        /// Parameter-space fit tolerance.
        fit_tolerance: FitTolerance,
    },
    /// Planar boundary described by a normal and curve.
    Plane {
        /// Plane normal.
        normal: V,
        /// Two ordered plane parameters.
        parameters: [R; 2],
        /// Boundary curve.
        curve: CurveId,
        /// Optional native curve parameter endpoints stored by the
        /// revision-gated layout.
        #[serde(default)]
        curve_endpoints: [Option<R>; 2],
    },
}

/// Complete native vertex-blend surface construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct VertexBlendConstruction<R = f64, V = Vector3, P = Point3> {
    /// Positive serializer-revision integer selecting the revision-gated
    /// layout; absent from the pre-revision layout.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_revision"
    )]
    pub revision: Option<PositiveI64>,
    /// Ordered boundary records.
    pub boundaries: Vec<VertexBlendBoundary<R, V, P>>,
    /// Native grid-size integer.
    pub grid_size: i64,
    /// Native model-space fit tolerance.
    pub fit_tolerance: FitTolerance,
}

/// One member of a compound-loft scale block.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct CompoundLoftScaleMember<R = f64, V = Vector3> {
    /// Native member integer.
    pub type_code: i64,
    /// Member curve.
    pub curve: CurveId,
    /// Native loft constraint data.
    pub data: ClassicLoftProfileData<R, V>,
}

/// Complete `_readScaleClLoft` payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct CompoundLoftScale<R = f64, V = Vector3> {
    /// Ordered scale members.
    pub members: Vec<CompoundLoftScaleMember<R, V>>,
    /// Scale path curve.
    pub path: CurveId,
    /// Ordered BS3 auxiliary curves.
    pub auxiliaries: Vec<CurveId>,
    /// Two native trailing integers.
    pub tail: [i64; 2],
}

/// Direction carrier in the zero-kind compound-loft tail.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CompoundLoftDirection<V = Vector3> {
    /// Inline direction vector. This form has no native selector.
    Vector {
        /// Stored direction.
        value: V,
    },
    /// BS3 direction curve and its nonzero native selector.
    Curve {
        /// Stored curve.
        curve: CurveId,
        /// Exact nonzero native selector retained for byte-faithful export.
        selector: NonZeroI64,
    },
}

impl<V> CompoundLoftDirection<V> {
    /// Native selector for this direction form.
    #[must_use]
    pub const fn selector(&self) -> i64 {
        match self {
            Self::Vector { .. } => 0,
            Self::Curve { selector, .. } => selector.get(),
        }
    }
}

/// Structurally selected tail of `cl_loft_spl_sur`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub enum CompoundLoftTail<R = f64, V = Vector3> {
    /// Native kind `6` tail.
    Six {
        /// Two leading flags.
        flags: [bool; 2],
        /// Required scale block.
        scale: Box<CompoundLoftScale<R, V>>,
        /// Native integer following the scale.
        selector: i64,
        /// Stored direction.
        direction: V,
        /// Native parameter interval.
        parameter_range: [R; 2],
        /// BS3 tail curve.
        curve: CurveId,
    },
    /// Native kind `7` tail.
    Seven {
        /// First flag.
        first_flag: bool,
        /// First optional scale block.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_first_scale"
        )]
        first_scale: Option<Box<CompoundLoftScale<R, V>>>,
        /// Second flag.
        second_flag: bool,
        /// Required second scale block.
        second_scale: Box<CompoundLoftScale<R, V>>,
        /// Native selector integer.
        selector: i64,
        /// Stored direction.
        direction: V,
        /// Two trailing flags.
        trailing_flags: [bool; 2],
    },
    /// Native kind `0` tail.
    Zero {
        /// Two leading flags.
        flags: [bool; 2],
        /// Vector or BS3 curve with its derived native selector.
        direction: CompoundLoftDirection<V>,
        /// Two trailing flags.
        trailing_flags: [bool; 2],
    },
}

/// A bounded list of compound-loft scales.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(
    try_from = "Vec<CompoundLoftScale<R, V>>",
    bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>")
)]
pub struct CompoundLoftScales<const CAPACITY: usize, R = f64, V = Vector3>(
    Vec<CompoundLoftScale<R, V>>,
);

impl<const CAPACITY: usize, R: Serialize, V: Serialize> Serialize
    for CompoundLoftScales<CAPACITY, R, V>
{
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize(serializer)
    }
}

#[cfg(feature = "schema")]
impl<const CAPACITY: usize, R, V> JsonSchema for CompoundLoftScales<CAPACITY, R, V>
where
    CompoundLoftScale<R, V>: JsonSchema,
{
    fn schema_name() -> std::borrow::Cow<'static, str> {
        format!("CompoundLoftScales_{CAPACITY}").into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        let mut schema = Vec::<CompoundLoftScale<R, V>>::json_schema(generator);
        schema.insert("maxItems".into(), CAPACITY.into());
        schema
    }
}

impl<const CAPACITY: usize, R, V> CompoundLoftScales<CAPACITY, R, V> {
    /// Admit a leading scale list within the native slot capacity.
    pub fn try_new(scales: Vec<CompoundLoftScale<R, V>>) -> Result<Self, &'static str> {
        if scales.len() > CAPACITY {
            return Err("compound loft scales exceed slot capacity");
        }
        Ok(Self(scales))
    }

    /// Admit native optional slots whose present values form a leading prefix.
    pub fn try_from_slots(
        slots: impl IntoIterator<Item = Option<CompoundLoftScale<R, V>>>,
    ) -> Result<Self, &'static str> {
        let mut scales = Vec::new();
        let mut absent = false;
        for (index, slot) in slots.into_iter().enumerate() {
            if index >= CAPACITY {
                return Err("compound loft scales exceed slot capacity");
            }
            match slot {
                Some(scale) if !absent => scales.push(scale),
                Some(_) => return Err("compound loft scales must form a leading prefix"),
                None => absent = true,
            }
        }
        Ok(Self(scales))
    }

    /// Present scales in native order.
    #[must_use]
    pub fn as_slice(&self) -> &[CompoundLoftScale<R, V>] {
        &self.0
    }
}

impl<const CAPACITY: usize, R, V> TryFrom<Vec<CompoundLoftScale<R, V>>>
    for CompoundLoftScales<CAPACITY, R, V>
{
    type Error = &'static str;
    fn try_from(scales: Vec<CompoundLoftScale<R, V>>) -> Result<Self, Self::Error> {
        Self::try_new(scales)
    }
}

/// Complete native compound-loft construction graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct CompoundLoftConstruction<R = f64, V = Vector3> {
    /// Present scales, up to the five native slots.
    pub scales: CompoundLoftScales<5, R, V>,
    /// Two flags before the tail kind.
    pub flags: [bool; 2],
    /// Kind-specific trailing graph.
    pub tail: CompoundLoftTail<R, V>,
}

/// Initial solved-shape branch of a scaled compound loft.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum ScaledCompoundLoftShape<R = f64> {
    /// A solved NURBS cache follows the singularity enum.
    Full {},
    /// The cache is replaced by two intervals and two scalar arrays.
    None {
        /// Two ordered native intervals.
        parameter_ranges: [[R; 2]; 2],
        /// Two ordered native scalar arrays.
        parameters: [Vec<R>; 2],
    },
}

/// Structurally selected middle branch of a scaled compound loft.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub enum ScaledCompoundLoftBranch<R = f64, V = Vector3> {
    /// Extended branch ending in a direction vector.
    ExtendedVector {
        /// Optional first scale block.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_first_scale"
        )]
        first_scale: Option<Box<CompoundLoftScale<R, V>>>,
        /// Required second scale block.
        second_scale: Box<CompoundLoftScale<R, V>>,
        /// Native selector integer.
        selector: i64,
        /// Stored direction vector.
        direction: V,
    },
    /// Extended branch ending in a singularity and curve.
    ExtendedCurve {
        /// Optional scale block.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_scale"
        )]
        scale: Option<Box<CompoundLoftScale<R, V>>>,
        /// Native branch flag.
        flag: bool,
        /// Native singularity enum.
        singularity: i64,
        /// Stored BS3 curve.
        curve: CurveId,
    },
    /// Direct vector-or-curve branch.
    Direct {
        /// Native branch flag.
        flag: bool,
        /// Vector or BS3 curve with its derived native selector.
        direction: CompoundLoftDirection<V>,
    },
}

/// Complete native scaled compound-loft construction graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct ScaledCompoundLoftConstruction<R = f64, V = Vector3> {
    /// Native leading singularity enum.
    pub singularity: i64,
    /// Singularity-selected solved-shape payload.
    pub shape: ScaledCompoundLoftShape<R>,
    /// Six ordered discontinuity arrays.
    pub discontinuities: [Vec<R>; 6],
    /// Native discontinuity tail flag.
    pub discontinuity_flag: bool,
    /// Present leading scales within the three native slots.
    pub scales: CompoundLoftScales<3, R, V>,
    /// Two native flags preceding the selector.
    pub flags: [bool; 2],
    /// Native integer preceding the middle branch.
    pub selector: i64,
    /// Structurally selected middle branch.
    pub branch: ScaledCompoundLoftBranch<R, V>,
    /// Two trailing branch flags.
    pub trailing_flags: [bool; 2],
    /// Native trailing kind integer.
    pub tail_kind: i64,
    /// Two native trailing vectors.
    pub tail_directions: [V; 2],
    /// Native trailing singularity enum.
    pub tail_singularity: i64,
    /// Native trailing BS3 curve.
    pub tail_curve: CurveId,
}

/// One recursively framed native law formula.
// A source states raw values; a law store holds the admitted formula, whose
// scalars, vectors and points are checked.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub enum LawFormula<R = f64, V = Vector3, P = Point3> {
    /// The native null law, with no variables.
    Null {},
    /// Named formula and its ordered recursive variables.
    Named {
        /// Native formula name.
        name: cadmpeg_core::text::NonBlankString,
        /// Ordered recursive variables.
        variables: Vec<LawExpression<R, V, P>>,
    },
}

impl<R, V, P> LawFormula<R, V, P> {
    /// Ordered recursive variables; empty for the null variant.
    #[must_use]
    pub fn variables(&self) -> &[LawExpression<R, V, P>] {
        match self {
            Self::Null {} => &[],
            Self::Named { variables, .. } => variables,
        }
    }
}

/// A law formula whose expression tree carries only finite scalars.
///
/// The carrier of the `law_int_cur` formulas. It serializes as the formula it
/// holds, so the curve wire states the formula alone.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "LawFormula")]
pub struct FiniteLawFormula(
    #[cfg_attr(feature = "schema", schemars(with = "LawFormula"))]
    LawFormula<FiniteReal, FiniteVector3, FinitePoint3>,
);

impl TryFrom<LawFormula> for FiniteLawFormula {
    type Error = &'static str;

    fn try_from(formula: LawFormula) -> Result<Self, Self::Error> {
        Self::try_new(formula)
    }
}

impl FiniteLawFormula {
    /// Admit a law formula whose expression tree carries only finite scalars.
    pub fn try_new(formula: LawFormula) -> Result<Self, &'static str> {
        formula.admit().map(Self).ok_or(LAW_FORMULA_NOT_FINITE)
    }

    /// The admitted law formula.
    #[must_use]
    pub const fn formula(&self) -> &LawFormula<FiniteReal, FiniteVector3, FinitePoint3> {
        &self.0
    }
}

/// Refusal of a law formula that carries a non-finite scalar.
const LAW_FORMULA_NOT_FINITE: &str = "law formula constants must be finite";

/// Recursion bound of the law-expression walk. An expression nested deeper than
/// this is refused.
const LAW_EXPRESSION_DEPTH_LIMIT: usize = 64;

/// Complete recursive construction stored by a native law spline surface.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct LawSurfaceConstruction<R = f64, V = Vector3, P = Point3> {
    /// Legacy U and V parameter intervals; absent from modern layouts.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_parameter_ranges"
    )]
    pub parameter_ranges: Option<[[R; 2]; 2]>,
    /// Primary recursive surface law.
    pub primary: LawFormula<R, V, P>,
    /// Ordered counted auxiliary laws referenced by the primary law.
    pub additional: Vec<LawFormula<R, V, P>>,
    /// Standard surface-tail mode and its mode-specific fields.
    pub tail: LawSurfaceTail<R>,
    /// Six ordered discontinuity arrays from the standard surface tail.
    pub discontinuities: [Vec<R>; 6],
}

/// Mode-specific payload of a native law surface's standard surface tail.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum LawSurfaceTail<R = f64> {
    /// Selector 0; the surface record carries a solved NURBS cache, whose fit
    /// contract this tail states.
    Full {
        /// Fit contract of the solved cache this tail requires.
        cache: LegacyCache,
    },
    /// Selector 1; compact parameter summaries replace the solved cache.
    Summary {
        /// Ordered U and V parameter summaries.
        parameters: [Vec<R>; 2],
        /// Native model-space fit tolerance.
        fit_tolerance: FitTolerance,
        /// Ordered U and V closure enums.
        closures: [i64; 2],
        /// Ordered U and V singularity enums.
        singularities: [i64; 2],
    },
    /// Selector 2; exact parameter intervals and boundary classifications.
    None {
        /// Ordered U and V parameter intervals.
        parameter_ranges: [[R; 2]; 2],
        /// Ordered U and V closure enums.
        closures: [i64; 2],
        /// Ordered U and V singularity enums.
        singularities: [i64; 2],
    },
    /// Selector 3; no mode-specific payload.
    Historical {},
    /// Selector 4; no mode-specific payload.
    Optimal {},
}

/// One native law-expression node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub enum LawExpression<R = f64, V = Vector3, P = Point3> {
    /// Zero-payload spelling of the native null law.
    Null {},
    /// Serializer-preserved textual law expression.
    Text {
        /// Exact text stored in the native law slot.
        value: cadmpeg_core::text::NonBlankString,
    },
    /// Tagged integer constant.
    Integer {
        /// Stored integer value.
        value: i64,
    },
    /// Tagged double constant.
    Double {
        /// Stored scalar value.
        value: R,
    },
    /// Tagged model-space point constant.
    Point {
        /// Stored point value.
        value: P,
    },
    /// Tagged direction-vector constant.
    Vector {
        /// Stored vector value.
        value: V,
    },
    /// Inline transform-law payload.
    Transform {
        /// Thirteen ordered transform scalars.
        scalars: [R; 13],
        /// Three ordered transform enums.
        enums: [i64; 3],
    },
    /// Vector-serialized transform-law payload: four ordered vectors, a scale,
    /// and three flags, in place of the thirteen-scalar/three-enum form.
    TransformVec {
        /// Four ordered transform vectors.
        vectors: [V; 4],
        /// Trailing transform scale.
        scale: R,
        /// Three ordered transform flags.
        flags: [bool; 3],
    },
    /// Curve-backed edge law.
    Edge {
        /// Embedded curve carrier and its optional revision-gated endpoints.
        #[serde(flatten)]
        curve: LoftPathCurve<R>,
        /// Two native curve parameters.
        parameters: [R; 2],
    },
    /// Spline-law payload.
    Spline {
        /// Native spline-law integer.
        native_id: i64,
        /// Ordered spline-law knots.
        knots: Vec<R>,
        /// Ordered spline-law controls.
        controls: Vec<R>,
        /// Native model-space point.
        point: P,
    },
    /// Algebraic operator and its recursively framed operands.
    Algebraic {
        /// Native operator token.
        operator: String,
        /// Ordered operands.
        operands: Vec<LawExpression<R, V, P>>,
    },
}

/// One profile entry in the expanded skin layout.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub struct SkinSurfaceProfile<R = f64, V = Vector3> {
    /// Native profile type integer.
    pub type_code: i64,
    /// Profile curve.
    pub curve: CurveId,
    /// Native loft constraint data.
    pub data: ClassicLoftProfileData<R, V>,
}

/// Structurally selected native skin payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize")
)]
pub enum SkinSurfaceLayout<R = f64, V = Vector3> {
    /// Expanded sequence of profile curves and loft constraints.
    Profiles {
        /// Ordered profile entries.
        profiles: Vec<SkinSurfaceProfile<R, V>>,
        /// Trailing path curve.
        path: CurveId,
        /// Two native trailing integers.
        tail: [i64; 2],
    },
    /// Compact curve/subdata form.
    Compact {
        /// Native compact-layout inner integer.
        inner_count: i64,
        /// Primary curve.
        curve: CurveId,
        /// Native loft subdata.
        subdata: LoftSubdata<R>,
        /// Integer after the subdata.
        first_tail: i64,
        /// Secondary curve.
        secondary_curve: CurveId,
        /// Final compact-layout integer.
        second_tail: i64,
    },
}

impl<R, V> SkinSurfaceLayout<R, V> {
    /// Native inner count, derived from the profile list in the expanded form.
    pub fn inner_count(&self) -> Result<i64, cadmpeg_core::CodecError> {
        match self {
            Self::Profiles { profiles, .. } => i64::try_from(profiles.len()).map_err(|_| {
                cadmpeg_core::CodecError::malformed(
                    "skin surface profile count exceeds the native integer range",
                )
            }),
            Self::Compact { inner_count, .. } => Ok(*inner_count),
        }
    }
}

/// Complete native `skin_spl_sur` construction graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct SkinSurfaceConstruction<R = f64, V = Vector3, P = Point3> {
    /// Native `SURF_BOOL` enum.
    pub surface_boolean: i64,
    /// Native `SURF_NORM` enum.
    pub surface_normal: i64,
    /// Native `SURF_DIR` enum.
    pub surface_direction: i64,
    /// Native leading count.
    pub count: i64,
    /// Native leading scalar.
    pub parameter: R,
    /// Structurally selected skin payload.
    pub layout: SkinSurfaceLayout<R, V>,
    /// Stored direction vector.
    pub direction: V,
    /// Native scalar before the formula.
    pub trailing_parameter: R,
    /// Recursive parametric law.
    pub formula: LawFormula<R, V, P>,
    /// Trailing curve after the formula.
    pub parameter_curve: CurveId,
    /// Six ordered solved-surface discontinuity arrays.
    pub discontinuities: [Vec<R>; 6],
    /// Native discontinuity tail flag.
    pub discontinuity_flag: bool,
}

/// Complete native `net_spl_sur` construction graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct NetSurfaceConstruction<R = f64, V = Vector3, P = Point3> {
    /// Two ordered loft-section graphs.
    pub sections: Box<[LoftSection<R, V>; 2]>,
    /// Twelve ordered frame scalars.
    pub frame_parameters: [R; 12],
    /// Native frame integer.
    pub flag: i64,
    /// Four ordered frame directions.
    pub directions: [V; 4],
    /// Four ordered parameter laws.
    pub formulas: Box<[LawFormula<R, V, P>; 4]>,
    /// Six ordered solved-surface discontinuity arrays.
    pub discontinuities: [Vec<R>; 6],
    /// Native discontinuity tail flag.
    pub discontinuity_flag: bool,
}

/// Structurally selected native sweep payload.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub enum SweepSurfaceLayout<R = f64, V = Vector3, P = Point3> {
    /// Profile-first modern ASM sweep layout.
    ProfileFirst {
        /// Second native sweep enum.
        secondary_kind: i64,
        /// Five ordered frame directions.
        directions: [V; 5],
        /// Native model-space frame origin.
        origin: P,
        /// Four ordered native frame scalars.
        parameters: [R; 4],
        /// Three ordered parametric laws.
        formulas: Box<[LawFormula<R, V, P>; 3]>,
    },
    /// Explicit sweep layout whose trajectory is controlled by a formula.
    ExplicitFormula {
        /// Native explicit-layout integer.
        mode: i64,
        /// Profile parameter interval.
        profile_range: [R; 2],
        /// Optional explicit profile frame.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        profile_frame: Option<(P, V)>,
        /// Sweep frame origin.
        origin: P,
        /// Three ordered sweep frame directions.
        directions: [V; 3],
        /// Native trajectory boolean.
        trajectory_flag: bool,
        /// Path parameter interval in model length units.
        path_range: [R; 2],
        /// Native trajectory scalar.
        path_parameter: R,
        /// Native formula-side boolean.
        formula_flag: bool,
        /// Parametric trajectory formula.
        formula: LawFormula<R, V, P>,
        /// Native trailing boolean.
        trailing_flag: bool,
    },
    /// Explicit sweep layout controlled by an auxiliary guide curve.
    ExplicitGuide {
        /// Native explicit-layout integer.
        mode: i64,
        /// Profile parameter interval.
        profile_range: [R; 2],
        /// Optional explicit profile frame.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        profile_frame: Option<(P, V)>,
        /// Sweep frame origin.
        origin: P,
        /// Three ordered sweep frame directions.
        directions: [V; 3],
        /// Native trajectory boolean.
        trajectory_flag: bool,
        /// Path parameter interval in model length units.
        path_range: [R; 2],
        /// Native trajectory scalar.
        path_parameter: R,
        /// Two guide-side booleans.
        guide_flags: [bool; 2],
        /// Auxiliary guide curve.
        guide_curve: CurveId,
        /// Guide parameter interval.
        guide_range: [R; 2],
        /// Two native guide integers.
        guide_modes: [i64; 2],
        /// Six ordered guide scalars.
        guide_parameters: [R; 6],
        /// Three trailing guide booleans.
        trailing_flags: [bool; 3],
    },
    /// Explicit sweep layout controlled by a support surface.
    ExplicitSurface {
        /// Native explicit-layout integer.
        mode: i64,
        /// Profile parameter interval.
        profile_range: [R; 2],
        /// Optional explicit profile frame.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        profile_frame: Option<(P, V)>,
        /// Sweep frame origin.
        origin: P,
        /// Three ordered sweep frame directions.
        directions: [V; 3],
        /// Native trajectory boolean.
        trajectory_flag: bool,
        /// Path parameter interval in model length units.
        path_range: [R; 2],
        /// Native trajectory scalar.
        path_parameter: R,
        /// Native singularity enum.
        singularity: i64,
        /// Support surface controlling the sweep.
        support_surface: SurfaceId,
        /// Optional auxiliary curve.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        auxiliary_curve: Option<CurveId>,
        /// Native support-side boolean.
        support_flag: bool,
        /// Legacy pre-219 trailing boolean when present.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        legacy_flag: Option<bool>,
    },
    /// Explicit-prefix sweep layout controlled by recursive laws.
    LawDriven {
        /// Native explicit-layout integer.
        mode: i64,
        /// Profile parameter interval.
        profile_range: [R; 2],
        /// Optional explicit profile frame.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        profile_frame: Option<(P, V)>,
        /// Sweep frame origin.
        origin: P,
        /// Three ordered sweep frame directions.
        directions: [V; 3],
        /// Leading recursive sweep law.
        first_law: Box<LawExpression<R, V, P>>,
        /// Native integer after the leading law.
        first_mode: i64,
        /// First law parameter interval.
        first_range: [R; 2],
        /// Native law direction.
        law_direction: V,
        /// Native path integer.
        path_mode: i64,
        /// Native path boolean.
        path_flag: bool,
        /// Path parameter interval.
        path_range: [R; 2],
        /// Native path scalar.
        path_parameter: R,
        /// Native second-law boolean.
        second_law_flag: bool,
        /// Trailing recursive sweep law.
        second_law: Box<LawExpression<R, V, P>>,
        /// Native integer before the formula.
        formula_mode: i64,
        /// Parametric trajectory formula.
        formula: LawFormula<R, V, P>,
        /// Native trailing boolean.
        trailing_flag: bool,
    },
}

/// Revision-gated `sweep_sur` form fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct SweepRevisionForm<R = f64> {
    /// Positive serializer-revision integer following the subtype name.
    pub revision: PositiveI64,
    /// Boolean replacing the pre-revision primary enum.
    pub primary_flag: bool,
    /// Optional parameter endpoints following the embedded profile curve.
    #[serde(default)]
    pub profile_endpoints: [Option<R>; 2],
    /// Optional parameter endpoints following the embedded path curve.
    #[serde(default)]
    pub path_endpoints: [Option<R>; 2],
    /// Approximation-cache form selected by the shared tail enum.
    pub cache: RevisionCacheForm<RevisionSurfaceParameterization<R>>,
}

/// Complete native `sweep_spl_sur` construction graph.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>, V: Deserialize<'de>, P: Deserialize<'de>"))]
#[cfg_attr(
    feature = "schema",
    schemars(
        bound = "R: JsonSchema + Serialize, V: JsonSchema + Serialize, P: JsonSchema + Serialize"
    )
)]
pub struct SweepSurfaceConstruction<R = f64, V = Vector3, P = Point3> {
    /// Leading native sweep enum.
    pub primary_kind: i64,
    /// Cache contract: the revision-gated form, or the legacy solved-cache
    /// tolerance this construction states instead.
    #[serde(default, skip_serializing_if = "CacheContract::is_bare_legacy")]
    pub cache: CacheContract<SweepRevisionForm<R>>,
    /// Structurally selected sweep layout.
    pub layout: SweepSurfaceLayout<R, V, P>,
    /// Six ordered solved-surface discontinuity arrays.
    pub discontinuities: [Vec<R>; 6],
    /// Native discontinuity tail flag.
    pub discontinuity_flag: bool,
}

/// Radius law for a procedural blend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum BlendRadiusLaw {
    /// Constant blend radius along the whole spine.
    Constant {
        /// Signed radius, in document length units; sign selects the support offset side.
        signed_radius: crate::scalar::Length,
    },
    /// Radius varying linearly from `start` to `end` along the spine.
    Linear {
        /// Signed radius at the spine start, in document length units.
        start: crate::scalar::Length,
        /// Signed radius at the spine end, in document length units.
        end: crate::scalar::Length,
    },
    /// Radius varying along the spine per an explicit law curve.
    Law {
        /// Curve whose parameterization gives the signed radius along the spine.
        curve: NurbsCurve,
    },
}

/// The refusal of a blend radius law with a non-finite radius.
const NON_FINITE_BLEND_RADIUS: ProceduralGeometryError =
    ProceduralGeometryError::Payload("blend radius law is not finite");

impl BlendRadiusLaw {
    /// Admit a constant law from a finite signed radius. The sign of a radius
    /// selects the support offset side, so a negative radius is admitted.
    pub fn constant(signed_radius: f64) -> Result<Self, ProceduralGeometryError> {
        Ok(Self::Constant {
            signed_radius: crate::scalar::Length::new(signed_radius)
                .ok_or(NON_FINITE_BLEND_RADIUS)?,
        })
    }

    /// Admit a linear law from finite signed radii at the spine start and
    /// end, with the refusal of [`BlendRadiusLaw::constant`].
    pub fn linear(start: f64, end: f64) -> Result<Self, ProceduralGeometryError> {
        Ok(Self::Linear {
            start: crate::scalar::Length::new(start).ok_or(NON_FINITE_BLEND_RADIUS)?,
            end: crate::scalar::Length::new(end).ok_or(NON_FINITE_BLEND_RADIUS)?,
        })
    }
}

/// A neutral curve construction linked to its solved carrier.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ProceduralCurve {
    /// Stable construction identity.
    pub id: ProceduralCurveId,
    /// Neutral construction definition, which states its own cache contract.
    definition: ProceduralCurveDefinition,
}

/// A parameter-space support curve and its optional affine parameter map.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SupportPcurve {
    /// UV curve carried by the support side.
    pub geometry: PcurveGeometry,
    /// Directed pcurve interval corresponding to the solved interval.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_parameter_range"
    )]
    pub parameter_range: Option<DirectedParameterRange>,
}

impl SupportPcurve {
    /// Pair a pcurve geometry with an optional checked parameter interval.
    #[must_use]
    pub const fn new(
        geometry: PcurveGeometry,
        parameter_range: Option<DirectedParameterRange>,
    ) -> Self {
        Self {
            geometry,
            parameter_range,
        }
    }
}

impl From<PcurveGeometry> for SupportPcurve {
    fn from(geometry: PcurveGeometry) -> Self {
        Self::new(geometry, None)
    }
}

/// A finite, non-zero-width directed parameter interval.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct DirectedParameterRange([f64; 2]);

/// Error returned when a directed parameter range cannot be admitted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParameterRangeError;

impl std::fmt::Display for ParameterRangeError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("parameter range endpoints must be finite and distinct")
    }
}

impl std::error::Error for ParameterRangeError {}

impl DirectedParameterRange {
    /// Build from finite angle endpoints, checking only that they differ.
    pub fn from_angle_endpoints(
        values: [crate::scalar::Angle; 2],
    ) -> Result<Self, ParameterRangeError> {
        (values[0] != values[1])
            .then_some(Self(values.map(crate::scalar::Angle::get)))
            .ok_or(ParameterRangeError)
    }

    /// Build from finite endpoints, checking only that they differ.
    pub fn from_finite_endpoints(
        values: [crate::scalar::FiniteReal; 2],
    ) -> Result<Self, ParameterRangeError> {
        (values[0] != values[1])
            .then_some(Self(values.map(crate::scalar::FiniteReal::get)))
            .ok_or(ParameterRangeError)
    }

    /// Construct an interval. Either ascending or descending direction is valid.
    pub fn new(values: [f64; 2]) -> Result<Self, ParameterRangeError> {
        let [first, second] = values.map(FiniteReal::new);
        let [Some(first), Some(second)] = [first, second] else {
            return Err(ParameterRangeError);
        };
        Self::from_finite_endpoints([first, second])
    }

    /// Return the directed endpoints.
    #[must_use]
    pub const fn endpoints(self) -> [f64; 2] {
        self.0
    }
}

impl<'de> Deserialize<'de> for DirectedParameterRange {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Self::new(<[f64; 2]>::deserialize(deserializer)?).map_err(serde::de::Error::custom)
    }
}

/// Refuse a zero-width interval under a support side with an explicit pcurve
/// mapping.
fn require_mapped_interval(
    sides: &[IntcurveSupportSide; 2],
    parameter_range: crate::topology::ParameterInterval,
) -> Result<(), &'static str> {
    let [start, end] = parameter_range.endpoints();
    if start == end
        && sides.iter().any(|side| {
            side.pcurve
                .as_ref()
                .is_some_and(|pcurve| pcurve.parameter_range.is_some())
        })
    {
        return Err(
            "support context parameter_range must be nonzero for an explicit pcurve mapping",
        );
    }
    Ok(())
}

/// One paired surface and parameter-space curve in an intcurve construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct IntcurveSupportSide {
    /// Supporting surface, absent for the native `null_surface` sentinel.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_surface"
    )]
    pub surface: Option<SurfaceId>,
    /// UV curve on `surface`, absent for the native `nullbs` sentinel.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_intcurve_support_side_pcurve"
    )]
    pub pcurve: Option<SupportPcurve>,
}

impl IntcurveSupportSide {
    /// Return the mapped pcurve interval, when this side's pcurve states one.
    #[must_use]
    pub fn pcurve_parameter_range(&self) -> Option<DirectedParameterRange> {
        self.pcurve
            .as_ref()
            .and_then(|pcurve| pcurve.parameter_range)
    }

    /// Map one solved-curve parameter into this side's pcurve parameter.
    ///
    /// Returns `None` when this side has no pcurve, an explicit map has a
    /// zero-width solved interval, or the mapped parameter cannot be
    /// represented as finite. Each branch admits the parameter it returns
    /// where it computes it.
    #[must_use]
    pub fn pcurve_parameter(
        &self,
        solved_parameter_range: crate::topology::ParameterInterval,
        parameter: f64,
    ) -> Option<FiniteReal> {
        let admitted_parameter = FiniteReal::new(parameter)?;
        let Some(pcurve_interval) = self.pcurve.as_ref()?.parameter_range else {
            return Some(admitted_parameter);
        };
        let [pcurve_start, pcurve_end] = pcurve_interval.finite_endpoints();
        let pcurve_range = pcurve_interval.endpoints();
        let solved_parameter_range = solved_parameter_range.endpoints();
        let solved_span = solved_parameter_range[1] - solved_parameter_range[0];
        if solved_span == 0.0 {
            return None;
        }
        if parameter == solved_parameter_range[0] {
            return Some(pcurve_start);
        }
        if parameter == solved_parameter_range[1] {
            return Some(pcurve_end);
        }
        let offset = parameter - solved_parameter_range[0];
        let mapped_span = pcurve_range[1] - pcurve_range[0];
        if solved_span.is_finite() && offset.is_finite() && mapped_span.is_finite() {
            let fraction = offset / solved_span;
            let advance = fraction * mapped_span;
            if fraction.is_normal() && advance.is_normal() {
                if let Some(mapped) = fast_dot(
                    [pcurve_range[0], advance],
                    [1.0, 1.0],
                    [pcurve_range[0], advance],
                ) {
                    return Some(mapped);
                }
            }
        }
        // Evaluate the affine numerator before division. A tiny fraction can
        // underflow even when the final mapped parameter is representable.
        let mut numerator = ExactSignedSum::default();
        numerator.add_product(pcurve_range[0], solved_parameter_range[1]);
        numerator.add_product(-pcurve_range[0], parameter);
        numerator.add_product(pcurve_range[1], parameter);
        numerator.add_product(-pcurve_range[1], solved_parameter_range[0]);
        let mut denominator = ExactSignedSum::default();
        denominator.add_product(solved_parameter_range[1], 1.0);
        denominator.add_product(-solved_parameter_range[0], 1.0);
        let denominator = denominator.finish()?;
        numerator.finish().map_or(Some(FiniteReal::ZERO), |value| {
            value.quotient(denominator).ok()
        })
    }
}

/// Version-stamp prefix and unbounded interval carried by the stamped
/// `law_int_cur` serializer form.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "LawCurveVersionFormWire")]
pub struct LawCurveVersionForm {
    /// Serializer version stamp emitted after the subtype name.
    stamp: i64,
    /// Native enum following the version stamp.
    post_enum: i64,
    /// Solved-curve interval endpoints; `None` records an unbounded bound.
    parameter_range: [Option<FiniteReal>; 2],
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct LawCurveVersionFormWire {
    /// Serializer version stamp emitted after the subtype name.
    stamp: i64,
    /// Native enum following the version stamp.
    post_enum: i64,
    /// Solved-curve interval endpoints; `None` records an unbounded bound.
    parameter_range: [Option<f64>; 2],
}

impl TryFrom<LawCurveVersionFormWire> for LawCurveVersionForm {
    type Error = &'static str;

    fn try_from(wire: LawCurveVersionFormWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.stamp, wire.post_enum, wire.parameter_range)
    }
}

impl LawCurveVersionForm {
    /// Admit a stamped law-curve form whose interval endpoints are finite.
    pub fn try_new(
        stamp: i64,
        post_enum: i64,
        parameter_range: [Option<f64>; 2],
    ) -> Result<Self, &'static str> {
        let parameter_range = FiniteReal::optional(parameter_range)
            .ok_or("law curve parameter_range bounds must be finite")?;
        Ok(Self {
            stamp,
            post_enum,
            parameter_range,
        })
    }

    /// Serializer version stamp emitted after the subtype name.
    #[must_use]
    pub const fn stamp(&self) -> i64 {
        self.stamp
    }

    /// Native enum following the version stamp.
    #[must_use]
    pub const fn post_enum(&self) -> i64 {
        self.post_enum
    }

    /// Solved-curve interval endpoints; `None` records an unbounded bound.
    #[must_use]
    pub const fn parameter_range(&self) -> [Option<FiniteReal>; 2] {
        self.parameter_range
    }
}

/// Shared support surfaces, UV curves, interval, and discontinuity arrays of a native intcurve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "IntcurveSupportContextWire")]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct IntcurveSupportContext {
    sides: [IntcurveSupportSide; 2],
    parameter_range: crate::topology::ParameterInterval,
    discontinuities: [Vec<FiniteReal>; 3],
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct IntcurveSupportContextWire {
    /// Ordered support sides.
    sides: [IntcurveSupportSide; 2],
    /// Solved-curve interval.
    parameter_range: [f64; 2],
    /// Ordered discontinuity arrays.
    discontinuities: [Vec<f64>; 3],
}

impl TryFrom<IntcurveSupportContextWire> for IntcurveSupportContext {
    type Error = &'static str;

    fn try_from(wire: IntcurveSupportContextWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.sides, wire.parameter_range, wire.discontinuities)
    }
}

impl IntcurveSupportContext {
    /// Construct a support context with a finite ordered interval and finite discontinuities.
    pub fn try_new(
        sides: [IntcurveSupportSide; 2],
        parameter_range: [f64; 2],
        discontinuities: [Vec<f64>; 3],
    ) -> Result<Self, &'static str> {
        let parameter_range = crate::topology::ParameterInterval::new(parameter_range)
            .map_err(|_| "support context parameter_range must be finite and ordered")?;
        require_mapped_interval(&sides, parameter_range)?;
        let discontinuities = FiniteReal::lanes(discontinuities)
            .ok_or("support context discontinuities must be finite")?;
        Ok(Self {
            sides,
            parameter_range,
            discontinuities,
        })
    }

    /// Construct a support context from an admitted interval and admitted
    /// discontinuities. Only the interval's width against an explicit pcurve
    /// mapping is tested.
    pub fn from_parts(
        sides: [IntcurveSupportSide; 2],
        parameter_range: crate::topology::ParameterInterval,
        discontinuities: [Vec<FiniteReal>; 3],
    ) -> Result<Self, &'static str> {
        require_mapped_interval(&sides, parameter_range)?;
        Ok(Self {
            sides,
            parameter_range,
            discontinuities,
        })
    }

    /// Build a support context over an increasing interval with no
    /// discontinuities. The interval type states finite, ordered and nonzero
    /// endpoints, which is the whole interval condition of [`Self::try_new`],
    /// so nothing is checked.
    #[must_use]
    pub fn over_interval(
        sides: [IntcurveSupportSide; 2],
        parameter_range: crate::topology::IncreasingParameterInterval,
    ) -> Self {
        Self {
            sides,
            parameter_range: parameter_range.into(),
            discontinuities: std::array::from_fn(|_| Vec::new()),
        }
    }

    /// Set a support surface without changing its pcurve mapping.
    pub fn set_surface(&mut self, side: usize, surface: Option<SurfaceId>) {
        self.sides[side].surface = surface;
    }

    /// Set a support pcurve with the solved-curve parameterization.
    pub fn set_unmapped_pcurve(&mut self, side: usize, geometry: Option<PcurveGeometry>) {
        self.sides[side].pcurve = geometry.map(SupportPcurve::from);
    }

    /// Copy the support pcurve of side `source` onto side `target`.
    pub fn copy_pcurve(&mut self, source: usize, target: usize) {
        if source == target {
            return;
        }
        let copied = self.sides[source]
            .pcurve
            .as_ref()
            .map(|pcurve| SupportPcurve::new(pcurve.geometry.clone(), pcurve.parameter_range));
        self.sides[target].pcurve = copied;
    }

    /// Return the ordered support sides.
    #[must_use]
    pub const fn sides(&self) -> &[IntcurveSupportSide; 2] {
        &self.sides
    }

    /// Return the solved-curve interval.
    #[must_use]
    pub const fn parameter_range(&self) -> crate::topology::ParameterInterval {
        self.parameter_range
    }

    /// Return the ordered discontinuity arrays.
    #[must_use]
    pub const fn discontinuities(&self) -> &[Vec<FiniteReal>; 3] {
        &self.discontinuities
    }
}

/// Finite endpoint witnesses and distinct supports of a tolerant intersection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "TolerantIntersectionConstructionWire")]
pub struct TolerantIntersectionConstruction {
    supports: [SurfaceId; 2],
    endpoints: [FinitePoint3; 2],
    tolerance: NonNegativeReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct TolerantIntersectionConstructionWire {
    /// Distinct support surfaces of the intersection.
    supports: [SurfaceId; 2],
    /// Model-space endpoint witnesses.
    endpoints: [Point3; 2],
    /// Finite non-negative intersection tolerance.
    tolerance: f64,
}

impl TryFrom<TolerantIntersectionConstructionWire> for TolerantIntersectionConstruction {
    type Error = &'static str;
    fn try_from(wire: TolerantIntersectionConstructionWire) -> Result<Self, Self::Error> {
        Self::try_new(wire.supports, wire.endpoints, wire.tolerance)
    }
}

impl TolerantIntersectionConstruction {
    /// Admit distinct supports, finite endpoints, and a finite non-negative tolerance.
    pub fn try_new(
        supports: [SurfaceId; 2],
        endpoints: [Point3; 2],
        tolerance: f64,
    ) -> Result<Self, &'static str> {
        if supports[0] == supports[1] {
            return Err("tolerant intersection supports must be distinct");
        }
        let [start, end] = endpoints.map(FinitePoint3::new);
        let (Some(start), Some(end)) = (start, end) else {
            return Err("tolerant intersection endpoints must be finite");
        };
        let endpoints = [start, end];
        let tolerance = NonNegativeReal::new(tolerance)
            .ok_or("tolerant intersection tolerance must be finite and non-negative")?;
        Ok(Self {
            supports,
            endpoints,
            tolerance,
        })
    }

    /// Admit distinct supports with admitted endpoints and tolerance. The
    /// endpoint and tolerance types state their conditions, so only the
    /// distinctness of the supports is checked.
    pub fn from_parts(
        supports: [SurfaceId; 2],
        endpoints: [FinitePoint3; 2],
        tolerance: NonNegativeReal,
    ) -> Result<Self, &'static str> {
        if supports[0] == supports[1] {
            return Err("tolerant intersection supports must be distinct");
        }
        Ok(Self {
            supports,
            endpoints,
            tolerance,
        })
    }

    /// Return the supports.
    #[must_use]
    pub const fn supports(&self) -> &[SurfaceId; 2] {
        &self.supports
    }

    /// Return the endpoints.
    #[must_use]
    pub const fn endpoints(&self) -> &[FinitePoint3; 2] {
        &self.endpoints
    }

    /// Return the admitted tolerance.
    #[must_use]
    pub const fn tolerance(&self) -> NonNegativeReal {
        self.tolerance
    }
}

/// Complete neutral parameterization of one topology-bounded intersection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "TolerantIntersectionParameterizationWire")]
pub struct TolerantIntersectionParameterization {
    /// Coincident support charts in support order.
    pub pcurves: [PcurveGeometry; 2],
    parameter_range: crate::topology::IncreasingParameterInterval,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct TolerantIntersectionParameterizationWire {
    /// Coincident support charts in support order.
    pcurves: [PcurveGeometry; 2],
    /// Common finite solved-curve interval.
    parameter_range: [f64; 2],
}

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

impl TolerantIntersectionParameterization {
    /// Admit a finite strictly increasing solved-curve interval.
    pub fn try_new(
        pcurves: [PcurveGeometry; 2],
        parameter_range: [f64; 2],
    ) -> Result<Self, &'static str> {
        let parameter_range = crate::topology::IncreasingParameterInterval::new(parameter_range)
            .ok_or(
                "tolerant intersection parameter_range must be finite and strictly increasing",
            )?;
        Ok(Self {
            pcurves,
            parameter_range,
        })
    }

    /// Common finite solved-curve interval.
    #[must_use]
    pub const fn parameter_range(&self) -> crate::topology::IncreasingParameterInterval {
        self.parameter_range
    }
}

/// Cache-first shared-context fields absent from the context-first layout.
// A source states raw scalars; a curve construction holds the admitted form,
// whose scalars are `FiniteReal` values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct CacheFirstCurveForm<R = f64> {
    /// Positive serializer-revision integer selecting the cache-first layout.
    pub revision: PositiveI64,
    /// Approximation-cache form selected by the shared context enum.
    pub cache: RevisionCacheForm<CacheFirstCurveParameterization<R>>,
    /// Optional U/V bound fields following each ordered support surface.
    #[serde(default)]
    pub support_bounds: [[Option<R>; 4]; 2],
    /// Optional solved-curve interval endpoints; absent endpoints inherit the
    /// solved NURBS domain.
    #[serde(default)]
    pub solved_range: [Option<R>; 2],
    /// Native integer ASM extension following the discontinuity arrays.
    pub extension: i64,
}

/// One support slot in a context-first spring construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    tag = "kind",
    content = "value",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum SpringSupport<R = f64> {
    /// Resolved support surface.
    Surface(SurfaceId),
    /// Native U/V ranges stored in place of `null_surface`.
    Ranges([[R; 2]; 2]),
}

/// First pcurve slot in a context-first spring construction.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(
    tag = "kind",
    content = "value",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum SpringPcurve<R = f64> {
    /// Resolved parameter-space curve.
    Pcurve(PcurveGeometry),
    /// Native interval stored in place of `nullbs`.
    Range([R; 2]),
}

/// Mutually exclusive spring construction layouts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
#[cfg_attr(
    feature = "schema",
    schemars(bound = "R: JsonSchema + Serialize, I: JsonSchema + Serialize")
)]
pub enum SpringLayout<R = f64, I = [f64; 2]> {
    /// Support-first layout with inline null-carrier replacement ranges.
    ContextFirst {
        /// Two ordered support slots.
        supports: [SpringSupport<R>; 2],
        /// First pcurve or its null replacement range.
        first_pcurve: Box<SpringPcurve<R>>,
        /// Nullable second pcurve slot.
        #[serde(deserialize_with = "cadmpeg_core::absent_key::nullable")]
        second_pcurve: Option<PcurveGeometry>,
        /// Native solved-curve parameter interval.
        parameter_range: I,
        /// Three ordered discontinuity arrays.
        discontinuities: [Vec<R>; 3],
        /// Native boolean following the discontinuity arrays.
        discontinuity_flag: bool,
        /// Solved-cache fit contract this layout states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    /// Cache-first layout, which carries no inline replacement ranges or
    /// context-first discontinuity flag.
    CacheFirst {
        /// Shared support context following the solved cache.
        context: IntcurveSupportContext,
        /// Cache-first serializer fields.
        form: CacheFirstCurveForm<R>,
    },
}

impl<R, I> SpringLayout<R, I> {
    fn cache_first(&self) -> Option<&CacheFirstCurveForm<R>> {
        match self {
            Self::CacheFirst { form, .. } => Some(form),
            Self::ContextFirst { .. } => None,
        }
    }

    /// Write the fit tolerance of the cache-first layout's cache form.
    ///
    /// The narrow write route: the borrow of the form stays inside this
    /// method, so the layout lends no interior of the admitted payload that
    /// holds it. The context-first layout owns no cache form.
    fn write_revision_fit_tolerance(&mut self, write: ToleranceWrite) -> RevisionCacheWrite {
        match self {
            Self::CacheFirst { form, .. } => form.cache.write_fit_tolerance(write),
            Self::ContextFirst { .. } => RevisionCacheWrite::NoForm,
        }
    }
}

/// Parameterization carried by cache form `2` of the shared cache-first
/// intcurve context. This form stores no solved curve cache and no fit
/// tolerance; it stores the curve interval followed by the closed-form enum, in
/// the order the fields appear below.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(bound(deserialize = "R: Deserialize<'de>"))]
#[cfg_attr(feature = "schema", schemars(bound = "R: JsonSchema + Serialize"))]
pub struct CacheFirstCurveParameterization<R = f64> {
    /// Curve interval, an ordered `[lo, hi]` pair of optional bounds. `None` is
    /// a false bound-presence flag.
    #[serde(default)]
    pub interval: [Option<R>; 2],
    /// Closed-form enum following the interval.
    pub closed_form: i64,
}

/// Family-independent tail fields carried by a cache-first surface curve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "SurfaceCurveTailWire")]
pub struct SurfaceCurveTail {
    /// Native integer following the discontinuity arrays.
    extension: i64,
    /// Positive serializer-revision integer opening the cache-first layout.
    revision: PositiveI64,
    /// Approximation-cache form selected by the shared context enum.
    #[cfg_attr(
        feature = "schema",
        schemars(with = "RevisionCacheForm<CacheFirstCurveParameterization>")
    )]
    cache: RevisionCacheForm<CacheFirstCurveParameterization<FiniteReal>>,
    /// Optional U/V bound fields following each ordered support surface.
    support_bounds: [RecordBounds; 2],
    /// Optional solved-curve interval endpoints; absent endpoints inherit the
    /// solved NURBS domain.
    #[serde(default)]
    solved_range: [Option<FiniteReal>; 2],
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SurfaceCurveTailWire {
    /// Native integer following the discontinuity arrays.
    extension: i64,
    /// Positive serializer-revision integer opening the cache-first layout.
    revision: PositiveI64,
    /// Approximation-cache form selected by the shared context enum.
    cache: RevisionCacheForm<CacheFirstCurveParameterization>,
    /// Optional U/V bound fields following each ordered support surface.
    #[serde(default)]
    support_bounds: [[Option<f64>; 4]; 2],
    /// Optional solved-curve interval endpoints; absent endpoints inherit the
    /// solved NURBS domain.
    #[serde(default)]
    solved_range: [Option<f64>; 2],
}

impl TryFrom<SurfaceCurveTailWire> for SurfaceCurveTail {
    type Error = &'static str;

    fn try_from(wire: SurfaceCurveTailWire) -> Result<Self, Self::Error> {
        Self::try_new(
            wire.extension,
            wire.revision,
            wire.cache,
            wire.support_bounds,
            wire.solved_range,
        )
    }
}

impl SurfaceCurveTail {
    /// Admit a cache-first surface-curve tail around an admitted revision.
    /// The support bounds, the solved range and the cache interval are raw
    /// values; a non-finite one is refused.
    pub fn try_new(
        extension: i64,
        revision: PositiveI64,
        cache: RevisionCacheForm<CacheFirstCurveParameterization>,
        support_bounds: [[Option<f64>; 4]; 2],
        solved_range: [Option<f64>; 2],
    ) -> Result<Self, &'static str> {
        const INVALID: &str = "surface curve tail bounds must be finite";
        let [first, second] = support_bounds.map(|bounds| RecordBounds::try_new(bounds).ok());
        let (Some(first), Some(second), Some(solved_range), Some(cache)) = (
            first,
            second,
            FiniteReal::optional(solved_range),
            cache.admit(),
        ) else {
            return Err(INVALID);
        };
        Ok(Self {
            extension,
            revision,
            cache,
            support_bounds: [first, second],
            solved_range,
        })
    }

    /// Native integer following the discontinuity arrays.
    #[must_use]
    pub const fn extension(&self) -> i64 {
        self.extension
    }

    /// Serializer-revision integer opening the cache-first layout.
    #[must_use]
    pub const fn revision(&self) -> PositiveI64 {
        self.revision
    }

    /// Approximation-cache form selected by the shared context enum.
    #[must_use]
    pub const fn cache(&self) -> &RevisionCacheForm<CacheFirstCurveParameterization<FiniteReal>> {
        &self.cache
    }

    /// Optional U/V bound fields following each ordered support surface.
    #[must_use]
    pub const fn support_bounds(&self) -> &[RecordBounds; 2] {
        &self.support_bounds
    }

    /// Optional solved-curve interval endpoints.
    #[must_use]
    pub const fn solved_range(&self) -> &[Option<FiniteReal>; 2] {
        &self.solved_range
    }
}

/// Cache-first surface-curve tail paired with its family-specific flags.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SurfaceCurveCacheFirst<F> {
    /// Family-independent cache-first fields.
    pub form: SurfaceCurveTail,
    /// Flags admitted by the selected surface-curve family.
    pub flags: F,
}

/// Two terminating flags carried only by a parametric surface curve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ParametricSurfaceCurveFlags {
    /// Support-slot selector.
    pub flag: bool,
    /// Optional later-revision terminating flag.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_second_flag"
    )]
    pub second_flag: Option<bool>,
}

/// Mutually exclusive tail forms of a native projected intcurve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ProjectionTail<R = f64> {
    /// The ASM flag is followed immediately by the subtype close.
    EarlyClose {
        /// Native ASM projection flag.
        flag: bool,
    },
    /// The ASM flag is followed by a retained source interval and role text.
    Ranged {
        /// Native ASM projection flag.
        flag: bool,
        /// Native parameter interval on the projected source curve.
        parameter_range: [R; 2],
        /// Projection support role.
        role: ProjectionRole,
    },
}

/// Support selected by a ranged projection tail.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub enum ProjectionRole {
    /// First support surface.
    #[serde(rename = "surf1")]
    Surf1,
    /// Second support surface.
    #[serde(rename = "surf2")]
    Surf2,
}

impl ProjectionRole {
    /// Parse the native ASM identifier.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "surf1" => Some(Self::Surf1),
            "surf2" => Some(Self::Surf2),
            _ => None,
        }
    }

    /// Native ASM identifier.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Surf1 => "surf1",
            Self::Surf2 => "surf2",
        }
    }
}

impl<'de> Deserialize<'de> for ProjectionRole {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::parse(&value).ok_or_else(|| {
            serde::de::Error::custom(format!(
                "invalid projection role field value `{value}`; expected `surf1` or `surf2`"
            ))
        })
    }
}

/// Native surface-curve family with its support context and optional
/// cache-first form.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "family", rename_all = "snake_case", deny_unknown_fields)]
pub enum SurfaceCurveFamily {
    /// Blend edge curve whose construction details live on its blend support.
    Blend {
        /// Shared support context.
        context: IntcurveSupportContext,
        /// Cache-first fields, when this is not the prefix-first layout.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_tail"
        )]
        tail: Option<SurfaceCurveCacheFirst<bool>>,
    },
    /// Curve constrained to a support surface.
    SurfaceConstrained {
        /// Shared support context.
        context: IntcurveSupportContext,
        /// Cache-first fields, when this is not the prefix-first layout.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_tail"
        )]
        tail: Option<SurfaceCurveCacheFirst<bool>>,
    },
    /// Parametric curve on a support surface.
    Parametric {
        /// Shared support context.
        context: IntcurveSupportContext,
        /// Cache-first fields with the parametric-only second flag.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_surface_curve_family_tail"
        )]
        tail: Option<SurfaceCurveCacheFirst<ParametricSurfaceCurveFlags>>,
    },
    /// Skin curve on a support surface.
    Skin {
        /// Shared support context.
        context: IntcurveSupportContext,
        /// Cache-first fields, when this is not the prefix-first layout.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_tail"
        )]
        tail: Option<SurfaceCurveCacheFirst<bool>>,
    },
}

/// Discriminant of a native surface-curve family.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SurfaceCurveFamilyKind {
    /// Blend edge curve whose construction details live on its blend support.
    Blend,
    /// Curve constrained to a support surface.
    SurfaceConstrained,
    /// Parametric curve on a support surface.
    Parametric,
    /// Skin curve on a support surface.
    Skin,
}

impl SurfaceCurveFamily {
    /// Return the family discriminant.
    #[must_use]
    pub const fn kind(&self) -> SurfaceCurveFamilyKind {
        match self {
            Self::Blend { .. } => SurfaceCurveFamilyKind::Blend,
            Self::SurfaceConstrained { .. } => SurfaceCurveFamilyKind::SurfaceConstrained,
            Self::Parametric { .. } => SurfaceCurveFamilyKind::Parametric,
            Self::Skin { .. } => SurfaceCurveFamilyKind::Skin,
        }
    }

    /// Borrow the shared support context.
    #[must_use]
    pub const fn context(&self) -> &IntcurveSupportContext {
        match self {
            Self::Blend { context, .. }
            | Self::SurfaceConstrained { context, .. }
            | Self::Parametric { context, .. }
            | Self::Skin { context, .. } => context,
        }
    }

    fn revision_cache(
        &self,
    ) -> Option<&RevisionCacheForm<CacheFirstCurveParameterization<FiniteReal>>> {
        match self {
            Self::Blend { tail, .. }
            | Self::SurfaceConstrained { tail, .. }
            | Self::Skin { tail, .. } => tail.as_ref().map(|first| &first.form.cache),
            Self::Parametric { tail, .. } => tail.as_ref().map(|first| &first.form.cache),
        }
    }

    /// Write the fit tolerance of the revision-gated solved cache.
    ///
    /// The narrow write route: the borrow of the cache form stays inside this
    /// method, so the family lends no admitted interior for writing.
    fn write_revision_fit_tolerance(&mut self, write: ToleranceWrite) -> RevisionCacheWrite {
        let form = match self {
            Self::Blend { tail, .. }
            | Self::SurfaceConstrained { tail, .. }
            | Self::Skin { tail, .. } => tail.as_mut().map(|first| &mut first.form.cache),
            Self::Parametric { tail, .. } => tail.as_mut().map(|first| &mut first.form.cache),
        };
        write_revision_form_tolerance(form, write)
    }

    /// Return whether two families have the same discriminant and cache-first
    /// tail, excluding the editable support context.
    #[must_use]
    pub fn has_same_form(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Blend { tail: first, .. }, Self::Blend { tail: second, .. })
            | (
                Self::SurfaceConstrained { tail: first, .. },
                Self::SurfaceConstrained { tail: second, .. },
            )
            | (Self::Skin { tail: first, .. }, Self::Skin { tail: second, .. }) => first == second,
            (Self::Parametric { tail: first, .. }, Self::Parametric { tail: second, .. }) => {
                first == second
            }
            _ => false,
        }
    }
}

/// Native silhouette construction family and its exclusive tail fields.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum SilhouetteKind {
    /// Standard implicit silhouette.
    Standard {},
    /// Parametric silhouette.
    Parametric {},
    /// Draft/taper silhouette with an explicit factor.
    Taper {
        /// Native unscaled draft factor.
        draft_factor: crate::scalar::FiniteReal,
    },
}

/// Discriminator-specific payload of a deformable native intcurve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum DeformableCurveData<R = f64, V = Vector3, P = Point3> {
    /// Mode 8 vector field followed by ordered scalar pairs.
    VectorField {
        /// Four ordered native vectors.
        vectors: [V; 4],
        /// Ordered pairs from the mode-8 scalar table.
        parameter_pairs: Vec<[R; 2]>,
    },
    /// Mode 3 fixed deformation payload.
    Mode3 {
        /// Four vectors at the start of the payload.
        leading_vectors: [V; 4],
        /// Scalar following the leading vectors.
        leading_parameter: R,
        /// Three flags following the leading scalar.
        leading_flags: [bool; 3],
        /// Position following the leading flags.
        trailing_point: P,
        /// Two vectors following the position.
        trailing_vectors: [V; 2],
        /// Scalar following the trailing frame.
        frame_parameter: R,
        /// Two flags following the frame scalar.
        frame_flags: [bool; 2],
        /// Three ordered scalars following the frame flags.
        parameters: [R; 3],
        /// Five flags following the ordered scalars.
        trailing_flags: [bool; 5],
        /// Final scalar before the trailing integer.
        trailing_parameter: R,
        /// Integer closing the mode-3 payload.
        trailing_value: i64,
    },
}

/// Source slot of a deformable native intcurve.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum DeformableCurveSource {
    /// Source geometry resolved to a neutral curve carrier.
    Curve {
        /// Curve being deformed.
        curve: CurveId,
    },
    /// Native intcurve reference whose target is absent from the active subtype table.
    NativeReference {
        /// Boolean stored before the reference scope.
        flag: bool,
        /// Integer stored by the native `ref` subtype.
        index: i64,
    },
}

/// Orientation carrier of a planar curve offset.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "side", rename_all = "snake_case", deny_unknown_fields)]
pub enum OffsetSide<V = Vector3> {
    /// Unit plane normal defining the positive offset side.
    PlaneNormal {
        /// Unit plane normal.
        normal: V,
    },
    /// Explicit offset direction, optionally constrained to a support surface.
    Direction {
        /// Nonzero offset direction.
        direction: V,
        /// Support surface within which the offset is measured.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_offset_side_support"
        )]
        support: Option<SurfaceId>,
    },
}

/// Parameter interval and optional variable-distance law of a curve offset.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CurveOffsetRange<R = f64> {
    /// Constant-distance offset over a retained source interval.
    Uniform {
        /// Parameter interval on the source curve.
        #[serde(deserialize_with = "deserialize_curve_offset_interval")]
        parameter_range: crate::topology::IncreasingParameterInterval,
    },
    /// Variable-distance offset over the interval used by its law.
    Variable {
        /// Parameter interval on the source curve.
        #[serde(deserialize_with = "deserialize_curve_offset_interval")]
        parameter_range: crate::topology::IncreasingParameterInterval,
        /// Variable signed-distance law.
        distance_law: CurveOffsetDistanceLaw<R>,
    },
}

/// The refusal of a curve offset whose distance, side, range or law is
/// invalid.
pub(crate) const INVALID_CURVE_OFFSET: &str =
    "curve offset distance, side, range, or law is invalid";

/// Admit a curve-offset interval with the curve-offset refusal.
fn admit_curve_offset_interval(
    range: [f64; 2],
) -> Result<crate::topology::IncreasingParameterInterval, ProceduralGeometryError> {
    crate::topology::IncreasingParameterInterval::new(range)
        .ok_or(ProceduralGeometryError::Payload(INVALID_CURVE_OFFSET))
}

/// Read a curve-offset interval with the curve-offset refusal.
fn deserialize_curve_offset_interval<'de, D: serde::Deserializer<'de>>(
    deserializer: D,
) -> Result<crate::topology::IncreasingParameterInterval, D::Error> {
    crate::topology::IncreasingParameterInterval::new(<[f64; 2]>::deserialize(deserializer)?)
        .ok_or_else(|| serde::de::Error::custom(INVALID_CURVE_OFFSET))
}

impl CurveOffsetRange {
    /// Admit a constant-distance range over a strictly increasing source
    /// interval. The refusal is the one
    /// [`OffsetCurveConstruction::try_new`](crate::geometry::curve_payloads::OffsetCurveConstruction::try_new)
    /// states for an invalid offset.
    pub fn uniform(parameter_range: [f64; 2]) -> Result<Self, ProceduralGeometryError> {
        Ok(Self::Uniform {
            parameter_range: admit_curve_offset_interval(parameter_range)?,
        })
    }

    /// Admit a variable-distance range over a strictly increasing source
    /// interval, with the refusal of [`CurveOffsetRange::uniform`].
    pub fn variable(
        parameter_range: [f64; 2],
        distance_law: CurveOffsetDistanceLaw,
    ) -> Result<Self, ProceduralGeometryError> {
        Ok(Self::Variable {
            parameter_range: admit_curve_offset_interval(parameter_range)?,
            distance_law,
        })
    }
}

/// Neutral semantics for a procedural curve.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ProceduralCurveDefinition {
    /// An exact native intcurve whose solved NURBS cache is authoritative.
    Exact {
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
    /// Curve defined by recursive native law formulas.
    Law {
        /// Shared support surfaces, UV curves, interval, and discontinuities.
        context: IntcurveSupportContext,
        /// Version-stamped serializer form, absent for the legacy layout.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        version: Option<LawCurveVersionForm>,
        /// Native ASM extension integer.
        extension: i64,
        /// Primary recursive law formula.
        #[cfg_attr(feature = "schema", schemars(with = "LawFormula"))]
        primary: FiniteLawFormula,
        /// Counted additional recursive law formulas.
        #[cfg_attr(feature = "schema", schemars(with = "Vec<LawFormula>"))]
        additional: Vec<FiniteLawFormula>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
    /// Ordered compound of native child curves with construction parameters.
    Compound(CompoundCurveConstruction),
    /// Circular or conical helix around an axis.
    Helix(HelixCurveConstruction),
    /// Intersection of two support surfaces.
    Intersection {
        /// Shared surfaces, UV curves, interval, and discontinuity metadata.
        context: IntcurveSupportContext,
        /// Native boolean following the discontinuity arrays.
        discontinuity_flag: bool,
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
    /// Tolerance-bounded intersection relation selected by topology endpoints.
    TolerantIntersection {
        /// Distinct supports and finite endpoint bounds.
        construction: TolerantIntersectionConstruction,
        /// Atomic neutral parameterization established by validated support charts.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        parameterization: Option<TolerantIntersectionParameterization>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
    /// Intersection constrained by a third ordered support surface.
    ThreeSurfaceIntersection(curve_payloads::ThreeSurfaceIntersectionCurvePayload),
    /// Surface-related curve whose native subtype has no tail beyond the shared prefix.
    SurfaceCurve {
        /// Native family, support context, and optional cache-first tail.
        family: SurfaceCurveFamily,
    },
    /// Silhouette of a cast surface in a light direction.
    Silhouette(curve_payloads::SilhouetteCurveConstruction),
    /// Curve offset relative to a surface parameterization.
    SurfaceOffset(curve_payloads::SurfaceOffsetCurveConstruction),
    /// Blend spring guide between two support sides.
    Spring(curve_payloads::SpringCurvePayload),
    /// Deformation of an embedded source curve.
    Deformable(curve_payloads::DeformableCurveConstruction),
    /// Projection of a source curve onto a support surface.
    Projection(curve_payloads::ProjectionCurvePayload),
    /// Offset from a source curve.
    Offset(curve_payloads::OffsetCurveConstruction),
    /// Free-space 3D offset using a reference direction.
    SpatialOffset(curve_payloads::SpatialOffsetCurveConstruction),
    /// Intersection of two surfaces after applying independent signed offsets.
    TwoSidedOffset(curve_payloads::TwoSidedOffsetCurveConstruction),
    /// Free-space vector offset of a source curve over a parameter interval.
    VectorOffset(curve_payloads::VectorOffsetCurveConstruction),
    /// A parameter sub-range of a parent curve.
    Subset(curve_payloads::SubsetCurveConstruction),
    /// Affine replica of a curve carrier, retaining the parent curve's
    /// parameter range and parameterization.
    Replica {
        /// Curve being replicated.
        source: CurveId,
        /// Affine map from the parent curve coordinates to this curve.
        transform: Transform,
    },
    /// Spine or center curve of a blend surface.
    BlendSpine {
        /// The blend surface this curve is the spine of, when known.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        blend_surface: Option<SurfaceId>,
    },
    /// Preserved construction without a neutral interpretation.
    Unknown {
        /// Source construction-family discriminator, when known.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        native_kind: Option<String>,
        /// Reference to the preserved raw source record, when retained.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        record: Option<UnknownId>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cache: Option<LegacyCache>,
    },
}

#[derive(Deserialize)]
#[serde(
    remote = "ProceduralCurveDefinition",
    tag = "kind",
    rename_all = "snake_case",
    deny_unknown_fields
)]
enum ProceduralCurveDefinitionWire {
    Exact {
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    Law {
        context: IntcurveSupportContext,
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_version"
        )]
        version: Option<LawCurveVersionForm>,
        extension: i64,
        primary: FiniteLawFormula,
        additional: Vec<FiniteLawFormula>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    Compound(CompoundCurveConstruction),
    Helix(HelixCurveConstruction),
    Intersection {
        context: IntcurveSupportContext,
        discontinuity_flag: bool,
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    TolerantIntersection {
        construction: TolerantIntersectionConstruction,
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_parameterization"
        )]
        parameterization: Option<TolerantIntersectionParameterization>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
    ThreeSurfaceIntersection(curve_payloads::ThreeSurfaceIntersectionCurvePayload),
    SurfaceCurve {
        family: SurfaceCurveFamily,
    },
    Silhouette(curve_payloads::SilhouetteCurveConstruction),
    SurfaceOffset(curve_payloads::SurfaceOffsetCurveConstruction),
    Spring(curve_payloads::SpringCurvePayload),
    Deformable(curve_payloads::DeformableCurveConstruction),
    Projection(curve_payloads::ProjectionCurvePayload),
    Offset(curve_payloads::OffsetCurveConstruction),
    SpatialOffset(curve_payloads::SpatialOffsetCurveConstruction),
    TwoSidedOffset(curve_payloads::TwoSidedOffsetCurveConstruction),
    VectorOffset(curve_payloads::VectorOffsetCurveConstruction),
    Subset(curve_payloads::SubsetCurveConstruction),
    Replica {
        source: CurveId,
        transform: Transform,
    },
    BlendSpine {
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_blend_surface"
        )]
        blend_surface: Option<SurfaceId>,
    },
    Unknown {
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_native_kind"
        )]
        native_kind: Option<String>,
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_record"
        )]
        record: Option<UnknownId>,
        /// Solved-cache fit contract this construction states itself.
        #[serde(
            default,
            skip_serializing_if = "Option::is_none",
            deserialize_with = "deserialize_cache"
        )]
        cache: Option<LegacyCache>,
    },
}

impl<'de> Deserialize<'de> for ProceduralCurveDefinition {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        ProceduralCurveDefinitionWire::deserialize(deserializer)
    }
}

/// Codes attached to the two native vector-offset roles.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct VectorOffsetRoles {
    /// Code of the source role.
    pub source: i64,
    /// Code of the offset role.
    pub offset: i64,
}

impl ProceduralCurveDefinition {
    fn revision_cache(
        &self,
    ) -> Option<&RevisionCacheForm<CacheFirstCurveParameterization<FiniteReal>>> {
        match self {
            Self::SurfaceCurve { family } => family.revision_cache(),
            Self::SurfaceOffset(payload) => payload.cache_first().as_ref().map(|form| &form.cache),
            Self::Spring(definition_payload) => {
                let layout = definition_payload.layout();
                layout.cache_first().map(|form| &form.cache)
            }
            Self::Deformable(definition_payload) => {
                let cache_first = definition_payload.cache_first();
                Some(&cache_first.cache)
            }
            _ => None,
        }
    }

    /// Write the fit tolerance of the revision-gated solved cache.
    ///
    /// The narrow write route: the borrow of the cache form stays inside this
    /// method, so no construction lends its admitted interior for writing.
    fn write_revision_fit_tolerance(&mut self, write: ToleranceWrite) -> RevisionCacheWrite {
        match self {
            Self::SurfaceCurve { family } => family.write_revision_fit_tolerance(write),
            Self::SurfaceOffset(payload) => payload.write_revision_fit_tolerance(write),
            Self::Spring(payload) => payload.write_revision_fit_tolerance(write),
            Self::Deformable(payload) => payload.write_revision_fit_tolerance(write),
            _ => RevisionCacheWrite::NoForm,
        }
    }
}

impl ProceduralCurveDefinition {
    /// Whether the construction owns a revision-gated cache form, which then
    /// states its solved-cache fit tolerance.
    #[must_use]
    pub fn owns_revision_cache(&self) -> bool {
        self.revision_cache().is_some()
    }
}

impl ProceduralCurve {
    /// Build a procedural curve from its construction definition.
    pub fn new(id: ProceduralCurveId, definition: ProceduralCurveDefinition) -> Self {
        Self { id, definition }
    }

    /// Borrow the neutral construction definition.
    #[must_use]
    pub fn definition(&self) -> &ProceduralCurveDefinition {
        &self.definition
    }

    /// Replace the construction definition. The cache contract travels with
    /// the definition, so nothing outside it changes.
    pub fn replace_definition(&mut self, definition: ProceduralCurveDefinition) {
        self.definition = definition;
    }

    /// Edit the definition in place.
    pub fn edit_definition<R>(
        &mut self,
        edit: impl FnOnce(&mut ProceduralCurveDefinition) -> R,
    ) -> R {
        edit(&mut self.definition)
    }

    /// Mutable checked support context of an intersection construction.
    pub fn intersection_context_mut(&mut self) -> Option<&mut IntcurveSupportContext> {
        match &mut self.definition {
            ProceduralCurveDefinition::Intersection { context, .. } => Some(context),
            _ => None,
        }
    }

    /// Effective fit tolerance of the solved cache.
    #[must_use]
    pub fn cache_fit_tolerance(&self) -> Option<FitTolerance> {
        self.definition.cache_fit_tolerance()
    }

    /// Change the effective fit tolerance without permitting a parameterized
    /// cache to acquire one or a solved cache to lose it.
    pub fn set_cache_fit_tolerance(
        &mut self,
        value: Option<f64>,
    ) -> Result<(), CacheContractError> {
        let value = value.map(FitTolerance::try_new).transpose()?;
        self.definition.set_cache_fit_tolerance(value)
    }

    /// State that a solved carrier of this construction was fitted to `value`,
    /// raising an existing contract rather than lowering it.
    pub fn require_cache_fit_tolerance(
        &mut self,
        value: FitTolerance,
    ) -> Result<(), CacheContractError> {
        self.definition.require_cache_fit_tolerance(value)
    }

    /// Scale the effective cache-fit tolerance in place.
    ///
    /// A positive scale keeps the tolerance non-negative, so the scaled
    /// tolerance is refused only when it overflows, with the admission's own
    /// error.
    pub fn scale_cache_fit_tolerance(
        &mut self,
        scale: crate::scalar::PositiveReal,
    ) -> Result<(), CacheContractError> {
        self.definition.scale_cache_fit_tolerance(scale)
    }
}

/// One procedural-surface row: the construction and the carrier it produces.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub(crate) struct ProceduralSurfaceRow {
    /// Stable construction identity.
    id: ProceduralSurfaceId,
    /// Carrier surface this construction produces.
    surface: SurfaceId,
    /// Neutral construction definition.
    definition: ProceduralSurfaceDefinition,
    /// Four optional U/V parameter bounds following the record's subtype scope.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_record_bounds"
    )]
    record_bounds: Option<RecordBounds>,
}

/// One procedural-curve row: the construction and the carrier it produces.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub(crate) struct ProceduralCurveRow {
    /// Stable construction identity.
    id: ProceduralCurveId,
    /// Carrier curve this construction produces.
    curve: CurveId,
    /// Neutral construction definition.
    definition: ProceduralCurveDefinition,
}

impl ProceduralSurfaceRow {
    /// The row a construction and its carrier state.
    pub(crate) fn new(surface: SurfaceId, procedural: &ProceduralSurface) -> Self {
        Self {
            id: procedural.id.clone(),
            surface,
            definition: procedural.definition.clone(),
            record_bounds: procedural.record_bounds,
        }
    }

    /// The carrier and the construction this row states.
    pub(crate) fn into_parts(self) -> (SurfaceId, ProceduralSurface) {
        (
            self.surface,
            ProceduralSurface::new(self.id, self.definition, self.record_bounds),
        )
    }
}

impl ProceduralCurveRow {
    /// The row a construction and its carrier state.
    pub(crate) fn new(curve: CurveId, procedural: &ProceduralCurve) -> Self {
        Self {
            id: procedural.id.clone(),
            curve,
            definition: procedural.definition.clone(),
        }
    }

    /// The carrier and the construction this row states.
    pub(crate) fn into_parts(self) -> (CurveId, ProceduralCurve) {
        (
            self.curve,
            ProceduralCurve {
                id: self.id,
                definition: self.definition,
            },
        )
    }
}

/// Independent variable used by a curve-offset distance law.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum CurveOffsetLawBasis {
    /// Distance measured along the source curve from the offset interval start.
    ArcLength,
    /// Native source-curve parameter.
    Parameter,
}

/// A one-based coordinate of a curve-offset distance function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(try_from = "u8", into = "u8")]
pub struct CurveOffsetCoordinate(u8);

impl CurveOffsetCoordinate {
    /// Admit coordinate one, two, or three.
    pub fn try_new(coordinate: u8) -> Result<Self, &'static str> {
        match coordinate {
            1..=3 => Ok(Self(coordinate)),
            _ => Err("curve offset coordinate must be 1, 2, or 3"),
        }
    }

    /// One-based coordinate number.
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

impl TryFrom<u8> for CurveOffsetCoordinate {
    type Error = &'static str;
    fn try_from(coordinate: u8) -> Result<Self, Self::Error> {
        Self::try_new(coordinate)
    }
}

impl From<CurveOffsetCoordinate> for u8 {
    fn from(coordinate: CurveOffsetCoordinate) -> Self {
        coordinate.get()
    }
}

/// Variable signed distance law for a planar curve offset.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CurveOffsetDistanceLaw<R = f64> {
    /// Linear interpolation between two distance controls.
    Linear {
        /// Independent-variable interpretation.
        basis: CurveOffsetLawBasis,
        /// Ordered signed distances in document length units.
        distances: [R; 2],
        /// Ordered arc-length or neutral carrier-parameter controls.
        #[serde(deserialize_with = "deserialize_curve_offset_interval")]
        control_range: crate::topology::IncreasingParameterInterval,
    },
    /// One coordinate of another curve defines the signed distance.
    Coordinate {
        /// Curve carrying the distance function.
        function: CurveId,
        /// One-based coordinate number on `function`.
        coordinate: CurveOffsetCoordinate,
        /// Independent-variable interpretation.
        basis: CurveOffsetLawBasis,
        /// Function parameter at zero source parameter or arc length.
        function_parameter_offset: R,
        /// Function-parameter change per neutral source parameter or length unit.
        function_parameter_scale: R,
    },
}

impl CurveOffsetDistanceLaw {
    /// Admit a linear law over strictly increasing controls, with the refusal
    /// of [`CurveOffsetRange::uniform`]. The distances are checked by the
    /// offset construction.
    pub fn linear(
        basis: CurveOffsetLawBasis,
        distances: [f64; 2],
        control_range: [f64; 2],
    ) -> Result<Self, ProceduralGeometryError> {
        Ok(Self::Linear {
            basis,
            distances,
            control_range: admit_curve_offset_interval(control_range)?,
        })
    }
}

#[cfg(test)]
mod tests;

impl CompoundCurveConstruction {
    /// Solved-cache fit contract this construction states.
    #[must_use]
    pub const fn legacy_cache(&self) -> Option<LegacyCache> {
        self.cache
    }

    /// Mutable legacy solved-cache slot this construction states.
    const fn legacy_cache_slot_mut(&mut self) -> &mut Option<LegacyCache> {
        &mut self.cache
    }
}

impl HelixCurveConstruction {
    /// Solved-cache fit contract this construction states.
    #[must_use]
    pub const fn legacy_cache(&self) -> Option<LegacyCache> {
        self.cache
    }

    /// Mutable legacy solved-cache slot this construction states.
    const fn legacy_cache_slot_mut(&mut self) -> &mut Option<LegacyCache> {
        &mut self.cache
    }
}

impl TSplineSurfaceConstruction {
    /// Solved-cache fit contract this construction states.
    #[must_use]
    pub const fn legacy_cache(&self) -> Option<LegacyCache> {
        match self.cache.legacy_fit_tolerance() {
            Some(fit_tolerance) => Some(LegacyCache { fit_tolerance }),
            None => None,
        }
    }

    /// Mutable legacy solved-cache slot, absent when a revision-gated form
    /// states the tolerance instead.
    fn legacy_cache_slot_mut(&mut self) -> Option<LegacyCacheSlot<'_>> {
        self.cache.legacy_cache_mut().map(LegacyCacheSlot::Optional)
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(
    deserialize_carrier_parameter_range,
    crate::topology::IncreasingParameterInterval,
    "parameter_range"
);
cadmpeg_core::named_optional_field!(deserialize_tertiary, bool, "tertiary");
cadmpeg_core::named_optional_field!(deserialize_cache, LegacyCache, "cache");
cadmpeg_core::named_optional_field!(deserialize_record, UnknownId, "record");
cadmpeg_core::named_optional_field!(
    deserialize_surface_geometry_cache,
    SolvedSurfaceGeometry,
    "cache"
);
cadmpeg_core::named_optional_field!(
    deserialize_source_object,
    SourceObjectAssociation,
    "source_object"
);
cadmpeg_core::named_optional_field!(
    deserialize_curve_geometry_cache,
    SolvedCurveGeometry,
    "cache"
);
cadmpeg_core::named_optional_field!(deserialize_extra<R>, [R; 2], "extra");
cadmpeg_core::named_optional_field!(deserialize_pcurve, PcurveGeometry, "pcurve");
cadmpeg_core::named_optional_field!(deserialize_direction<V>, V, "direction");
cadmpeg_core::named_optional_field!(deserialize_surface, SurfaceId, "surface");
cadmpeg_core::named_optional_field!(deserialize_asm_extension, i64, "asm_extension");
cadmpeg_core::named_optional_field!(
    deserialize_secondary_pcurve,
    PcurveGeometry,
    "secondary_pcurve"
);
cadmpeg_core::named_optional_field!(deserialize_endpoints<R>, [Option<R>; 2], "endpoints");
cadmpeg_core::named_optional_field!(deserialize_path<R>, LoftPathCurve<R>, "path");
cadmpeg_core::named_optional_field!(deserialize_support, G2BlendFullSupport, "support");
cadmpeg_core::named_optional_field!(deserialize_extension<R>, LoftBridgeToken<R>, "extension");
cadmpeg_core::named_optional_field!(
    deserialize_rolling_ball_side_surface<S, R>,
    RollingBallSupportSurface<S, R>,
    "surface"
);
cadmpeg_core::named_optional_field!(
    deserialize_curve<C, R>,
    RollingBallSupportCurve<C, R>,
    "curve"
);
cadmpeg_core::named_optional_field!(deserialize_rolling_ball_side_pcurve<P>, P, "pcurve");
cadmpeg_core::named_optional_field!(
    deserialize_rolling_ball_side_secondary_pcurve<P>,
    P,
    "secondary_pcurve"
);
cadmpeg_core::named_optional_field!(
    deserialize_rolling_ball_side_extension<P>,
    RollingBallSideExtension<P>,
    "extension"
);
cadmpeg_core::named_optional_field!(
    deserialize_tertiary_pcurve,
    PcurveGeometry,
    "tertiary_pcurve"
);
cadmpeg_core::named_optional_field!(deserialize_third<V>, Box<RollingBallThirdSide<V>>, "third");
cadmpeg_core::named_optional_field!(
    deserialize_radius<R, V, P>,
    Box<VariableBlendValue<R, V, P>>,
    "radius"
);
cadmpeg_core::named_optional_field!(
    deserialize_cross_section<R, V, P>,
    VariableBlendCrossSection<R, V, P>,
    "cross_section"
);
cadmpeg_core::named_optional_field!(deserialize_v_lower<R>, R, "v_lower");
cadmpeg_core::named_optional_field!(
    deserialize_secondary_curve<R>,
    RollingBallSupportCurve<CurveId, R>,
    "secondary_curve"
);
cadmpeg_core::named_optional_field!(deserialize_post_curve, CurveId, "post_curve");
cadmpeg_core::named_optional_field!(deserialize_post_pcurve, PcurveGeometry, "post_pcurve");
cadmpeg_core::named_optional_field!(deserialize_revision, PositiveI64, "revision");
cadmpeg_core::named_optional_field!(
    deserialize_first_scale<R, V>,
    Box<CompoundLoftScale<R, V>>,
    "first_scale"
);
cadmpeg_core::named_optional_field!(
    deserialize_scale<R, V>,
    Box<CompoundLoftScale<R, V>>,
    "scale"
);
cadmpeg_core::named_optional_field!(
    deserialize_parameter_ranges<R>,
    [[R; 2]; 2],
    "parameter_ranges"
);
cadmpeg_core::named_optional_field!(
    deserialize_parameter_range,
    DirectedParameterRange,
    "parameter_range"
);
cadmpeg_core::named_optional_field!(
    deserialize_intcurve_support_side_pcurve,
    SupportPcurve,
    "pcurve"
);
cadmpeg_core::named_optional_field!(deserialize_second_flag, bool, "second_flag");
cadmpeg_core::named_optional_field!(deserialize_tail, SurfaceCurveCacheFirst<bool>, "tail");
cadmpeg_core::named_optional_field!(
    deserialize_surface_curve_family_tail,
    SurfaceCurveCacheFirst<ParametricSurfaceCurveFlags>,
    "tail"
);
cadmpeg_core::named_optional_field!(deserialize_offset_side_support, SurfaceId, "support");
cadmpeg_core::named_optional_field!(deserialize_version, LawCurveVersionForm, "version");
cadmpeg_core::named_optional_field!(
    deserialize_parameterization,
    TolerantIntersectionParameterization,
    "parameterization"
);
cadmpeg_core::named_optional_field!(deserialize_blend_surface, SurfaceId, "blend_surface");
cadmpeg_core::named_optional_field!(deserialize_native_kind, String, "native_kind");
cadmpeg_core::named_optional_field!(deserialize_record_bounds, RecordBounds, "record_bounds");

mod identity_rewrite;

mod serialization;