cadmpeg-asm 0.6.2

Parse and write Autodesk Shape Manager record streams.
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
// SPDX-License-Identifier: Apache-2.0
//! Procedural curve embedded types, decoders, resolving-ref walkers, and writer-facing patch layouts.

use crate::kernel_header::RefWidth;
use crate::nurbs::blend::{
    decode_optional_rolling_ball_surface, decode_rolling_ball_side, optional_rolling_ball_surface,
    surface_ranges,
};
use crate::nurbs::core::{
    curve_block, decode_curve_block, decode_surface_block, owned_curve_cache_resolving_refs,
    owned_surface_cache_resolving_refs, surface_block,
};
use crate::nurbs::pcurve::{decode_pcurve_block_with_end, pcurve_block_with_end};
use crate::nurbs::proc_surface::{
    decode_nullable_embedded_pcurve, ellipse_to_nurbs, law_formula, nullable_embedded_pcurve,
    EmbeddedLawFormula,
};
use crate::nurbs::reader::{
    normalized, take_bool, take_double_payload, take_float_array_payloads, take_native_ident,
    take_native_string, take_native_vec3, take_range_value, take_tagged_int, Nullable, LEN_TO_MM,
};
use crate::nurbs::subtypes::{
    find_owned_intcurve_subtype, find_owned_subtype_marker, subtype_span,
};
use crate::nurbs::support_chart::{cone_axis_reversed, cone_is_circular_cylinder, SupportChart};
use crate::nurbs::toks::{Cur, SubtypeTable};
use crate::sab::Token;
use cadmpeg_ir::features::FinitePoint3;
use cadmpeg_ir::geometry::analytic::{
    ConeSurface, CylinderSurface, PlaneSurface, SphereSurface, TorusSurface,
};
use cadmpeg_ir::geometry::{
    nurbs::NurbsCurve, pcurve::PcurveNurbs, SolvedSurfaceGeometry, SurfaceGeometry,
};
use cadmpeg_ir::math::{Point3, Vector3};
use cadmpeg_ir::scalar::{
    Angle, NonNegativeLength, NonZeroLength, PositiveI64, PositiveLength, PositiveReal,
};
use cadmpeg_ir::units::{OrthonormalFrame3, UnitVector3};

const EPS_PARAMETER_AGREEMENT: f64 = 1.0e-12;

macro_rules! propagate_resource {
    ($result:expr) => {
        match $result {
            Ok(value) => value,
            Err(error) => return Some(Err(error)),
        }
    };
}

/// Source curve and tail fields decoded from an `offset_int_cur` construction.
pub type VectorOffsetDefinition = (
    NurbsCurve,
    [f64; 2],
    Vector3,
    cadmpeg_ir::geometry::VectorOffsetRoles,
);

/// Parent curve and retained range decoded from a `subset_int_cur` construction.
pub type SubsetDefinition = (NurbsCurve, [f64; 2]);

/// Parameter arrays and child curves decoded from a `comp_int_cur` construction.
pub struct CompoundDefinition {
    /// Leading native parameter array.
    pub parameters: Vec<f64>,
    /// Ordered child curves and their construction scalars.
    pub components: Vec<cadmpeg_ir::geometry::CompoundComponent<NurbsCurve>>,
}

/// Embedded freeform support carriers and tail fields of an `off_int_cur`.
pub struct EmbeddedTwoSidedOffset {
    /// Two ordered embedded support surfaces.
    pub surfaces: [Option<SurfaceGeometry>; 2],
    /// Two ordered embedded NURBS parameter curves.
    pub pcurves: [Option<PcurveNurbs>; 2],
    /// Shared native parameter interval.
    pub parameter_range: [f64; 2],
    /// Three discontinuity arrays.
    pub discontinuities: [Vec<f64>; 3],
    /// The boolean serialized after the discontinuity arrays.
    pub discontinuity_flag: bool,
    /// Signed side offsets in document length units.
    pub offsets: [f64; 2],
}

/// Native support presence and its optional standalone geometry cache.
pub enum SupportSlot {
    /// The native slot has no support.
    Absent,
    /// A valid native support has no standalone geometry cache.
    DeclaredOnly,
    /// The support has a standalone geometry cache.
    Surface(SurfaceGeometry),
}

impl SupportSlot {
    pub(crate) fn into_surface(self) -> Option<SurfaceGeometry> {
        match self {
            Self::Surface(surface) => Some(surface),
            Self::Absent | Self::DeclaredOnly => None,
        }
    }
}

/// Embedded support carriers and shared fields of an `int_int_cur`.
pub struct EmbeddedIntersection {
    /// Two ordered native support slots.
    pub surfaces: [SupportSlot; 2],
    /// Two ordered embedded NURBS parameter curves.
    pub pcurves: [Option<PcurveNurbs>; 2],
    /// Shared native parameter interval.
    pub parameter_range: [f64; 2],
    /// Three discontinuity arrays.
    pub discontinuities: [Vec<f64>; 3],
}

/// A surface-curve context selected by its native layout.
pub enum EmbeddedSurfaceCurveLayout<F> {
    /// The explicit context-first fields.
    ContextFirst(EmbeddedIntersection),
    /// The cache-first source fields and family flags.
    CacheFirst {
        /// The cache-first context.
        context: CacheFirstCurveContext,
        /// The family flags.
        flags: F,
    },
}

impl<F> EmbeddedSurfaceCurveLayout<F> {
    fn selected_pcurve(&self, slot: usize) -> Option<&PcurveNurbs> {
        let (surfaces, pcurves) = match self {
            Self::ContextFirst(context) => (&context.surfaces, &context.pcurves),
            Self::CacheFirst { context, .. } => (&context.surfaces, &context.pcurves),
        };
        selected_support_pcurve(surfaces, pcurves, slot)
    }

    fn try_map_flags<G>(
        self,
        map: impl FnOnce(F) -> Option<G>,
    ) -> Option<EmbeddedSurfaceCurveLayout<G>> {
        Some(match self {
            Self::ContextFirst(context) => EmbeddedSurfaceCurveLayout::ContextFirst(context),
            Self::CacheFirst { context, flags } => EmbeddedSurfaceCurveLayout::CacheFirst {
                context,
                flags: map(flags)?,
            },
        })
    }
}

/// The family-selected surface curve construction.
pub enum EmbeddedSurfaceCurve {
    /// The blend family.
    Blend(EmbeddedSurfaceCurveLayout<bool>),
    /// The surface-constrained family.
    SurfaceConstrained(EmbeddedSurfaceCurveLayout<bool>),
    /// The parametric family.
    Parametric(EmbeddedSurfaceCurveLayout<cadmpeg_ir::geometry::ParametricSurfaceCurveFlags>),
    /// The skin family.
    Skin(EmbeddedSurfaceCurveLayout<bool>),
}

impl EmbeddedSurfaceCurve {
    fn selected_pcurve(&self, slot: usize) -> Option<&PcurveNurbs> {
        match self {
            Self::Blend(layout) | Self::SurfaceConstrained(layout) | Self::Skin(layout) => {
                layout.selected_pcurve(slot)
            }
            Self::Parametric(layout) => layout.selected_pcurve(slot),
        }
    }
}

struct RequiredSupportPair {
    surfaces: [SurfaceGeometry; 2],
    pcurves: [PcurveNurbs; 2],
}

fn required_support_pair(cur: &mut Cur<'_>) -> Option<RequiredSupportPair> {
    let first = embedded_support(cur)?;
    let second = embedded_support(cur)?;
    let (mut first_pcurve, first_end) = pcurve_block_with_end(cur.toks(), cur.pos())?;
    cur.set_pos(first_end);
    let (mut second_pcurve, second_end) = pcurve_block_with_end(cur.toks(), cur.pos())?;
    cur.set_pos(second_end);
    first.chart.normalize(&mut first_pcurve)?;
    second.chart.normalize(&mut second_pcurve)?;
    Some(RequiredSupportPair {
        surfaces: [first.surface, second.surface],
        pcurves: [first_pcurve, second_pcurve],
    })
}

/// Three ordered support carriers and selector of an `sss_int_cur`.
pub struct EmbeddedThreeSurfaceIntersection {
    /// Three ordered embedded support surfaces.
    pub surfaces: [SurfaceGeometry; 3],
    /// Three ordered embedded NURBS parameter curves.
    pub pcurves: [PcurveNurbs; 3],
    /// Shared native parameter interval.
    pub parameter_range: [f64; 2],
    /// Three discontinuity arrays.
    pub discontinuities: [Vec<f64>; 3],
    /// The integer selector serialized after the discontinuity arrays.
    pub selector: i64,
}

/// Embedded support context, source curve, and tail of a `proj_int_cur`.
pub struct EmbeddedProjection {
    /// Two ordered embedded support surfaces.
    pub surfaces: [SurfaceGeometry; 2],
    /// Two ordered embedded NURBS parameter curves.
    pub pcurves: [PcurveNurbs; 2],
    /// Shared native parameter interval.
    pub parameter_range: [f64; 2],
    /// Three discontinuity arrays.
    pub discontinuities: [Vec<f64>; 3],
    /// The boolean serialized after the discontinuity arrays.
    pub discontinuity_flag: bool,
    /// The embedded projected source curve.
    pub source: NurbsCurve,
    /// Neutral tail fields decoded after the source curve.
    pub tail: cadmpeg_ir::geometry::ProjectionTail,
}

/// Shared context and tail fields of a silhouette intcurve.
pub struct EmbeddedSilhouette {
    /// Two ordered support surfaces.
    pub surfaces: [SurfaceGeometry; 2],
    /// Two ordered parameter curves.
    pub pcurves: [PcurveNurbs; 2],
    /// The shared parameter interval.
    pub parameter_range: [f64; 2],
    /// The three discontinuity arrays.
    pub discontinuities: [Vec<f64>; 3],
    /// The silhouette family the subtype name selects.
    pub silhouette: cadmpeg_ir::geometry::SilhouetteKind,
    /// The embedded surface the silhouette is cast on.
    pub cast_surface: SurfaceGeometry,
    /// The projection direction of the silhouette light.
    pub light_direction: cadmpeg_ir::units::UnitVector3,
}

/// Shared context and tail fields of an `off_surf_int_cur`.
pub struct EmbeddedSurfaceOffset {
    /// The native field layout.
    pub layout: EmbeddedSurfaceOffsetLayout,
    /// U parameter interval of the base surface.
    pub base_u_range: [f64; 2],
    /// V parameter interval of the base surface.
    pub base_v_range: [f64; 2],
    /// The embedded base curve the offset follows.
    pub base: NurbsCurve,
    /// Native parameter interval of the base curve.
    pub base_range: [f64; 2],
    /// Signed offset distance in document length units.
    pub distance: f64,
    /// The shift value serialized after the distance.
    pub shift: f64,
    /// The scale value serialized after the shift.
    pub scale: f64,
}

/// The mutually exclusive surface-offset curve layouts.
pub enum EmbeddedSurfaceOffsetLayout {
    /// The support context precedes the cache.
    ContextFirst {
        /// The explicit support context.
        context: Box<EmbeddedIntersection>,
        /// The flag after the discontinuity arrays.
        discontinuity_flag: bool,
    },
    /// The solved cache precedes the support context.
    CacheFirst {
        /// The cache-first source context.
        context: Box<CacheFirstCurveContext>,
        /// The base curve endpoint bounds.
        base_endpoints: [Option<f64>; 2],
    },
}

/// One context-first spring support slot.
pub enum EmbeddedSpringSupport {
    /// Embedded support surface.
    Surface(SurfaceGeometry),
    /// U/V ranges stored in place of a null support.
    Ranges([[f64; 2]; 2]),
}

/// First context-first spring pcurve slot.
pub enum EmbeddedSpringPcurve {
    /// Embedded pcurve.
    Pcurve(PcurveNurbs),
    /// Parameter range stored in place of a null pcurve.
    Range([f64; 2]),
}

/// Structurally selected spring layout.
pub enum EmbeddedSpringLayout {
    /// Context-first form with inline replacement ranges.
    ContextFirst {
        /// Ordered support slots.
        supports: Box<[EmbeddedSpringSupport; 2]>,
        /// First pcurve slot.
        first_pcurve: Box<EmbeddedSpringPcurve>,
        /// Nullable second pcurve slot.
        second_pcurve: Option<PcurveNurbs>,
        /// Shared parameter interval.
        parameter_range: [f64; 2],
        /// Three discontinuity arrays.
        discontinuities: [Vec<f64>; 3],
        /// Boolean following the discontinuity arrays.
        discontinuity_flag: bool,
    },
    /// Cache-first form with no inline replacement ranges.
    CacheFirst {
        /// Shared embedded support context.
        context: Box<CacheFirstCurveContext>,
    },
}

/// Spring construction and direction enum.
pub struct EmbeddedSpring {
    /// Context-first or cache-first payload.
    pub layout: EmbeddedSpringLayout,
    /// The direction enum serialized at the construction tail.
    pub direction: i64,
}

/// Embedded support context and recursive formulas of a `law_int_cur`.
pub struct EmbeddedLawCurve {
    /// The ordered support slots.
    pub surfaces: [SupportSlot; 2],
    /// The ordered parameter curves.
    pub pcurves: [Option<PcurveNurbs>; 2],
    /// The three discontinuity arrays.
    pub discontinuities: [Vec<f64>; 3],
    /// The source parameter range and serializer layout.
    pub layout: EmbeddedLawCurveLayout,
    /// The extension enum serialized before the primary formula.
    pub extension: i64,
    /// The law formula that drives the curve.
    pub primary: EmbeddedLawFormula,
    /// Additional law formulas serialized after the primary.
    pub additional: Vec<EmbeddedLawFormula>,
}

/// The legacy and version-stamped law curve layouts.
pub enum EmbeddedLawCurveLayout {
    /// The explicit legacy parameter interval.
    Legacy([f64; 2]),
    /// The version fields and optional source bounds.
    Version {
        /// The serializer version stamp.
        stamp: i64,
        /// The enum after the stamp.
        post_enum: i64,
        /// The optional parameter bounds.
        parameter_range: [Option<f64>; 2],
    },
}

/// Mode-discriminated payload of a `defm_int_cur` construction.
pub enum EmbeddedDeformableData {
    /// The vector-field payload: four frame vectors and a parameter-pair list.
    VectorField {
        /// Four ordered frame vectors.
        vectors: [Vector3; 4],
        /// Counted list of parameter pairs.
        parameter_pairs: Vec<[f64; 2]>,
    },
    /// The mode-3 payload: leading frame, trailing frame, and scalar tail.
    Mode3 {
        /// Four ordered leading frame vectors.
        leading_vectors: [Vector3; 4],
        /// The parameter serialized after the leading vectors.
        leading_parameter: f64,
        /// Three booleans serialized after the leading parameter.
        leading_flags: [bool; 3],
        /// The point that anchors the trailing frame.
        trailing_point: Point3,
        /// Two ordered trailing frame vectors.
        trailing_vectors: [Vector3; 2],
        /// The parameter serialized after the trailing vectors.
        frame_parameter: f64,
        /// Two booleans serialized after the frame parameter.
        frame_flags: [bool; 2],
        /// Three scalar parameters of the tail.
        parameters: [f64; 3],
        /// Five booleans serialized after the tail parameters.
        trailing_flags: [bool; 5],
        /// The parameter serialized after the trailing flags.
        trailing_parameter: f64,
        /// The integer serialized at the payload end.
        trailing_value: i64,
    },
}

/// Embedded bend curve and discriminator payload of a `defm_int_cur`.
pub struct EmbeddedDeformable {
    /// The cache-first source context.
    pub context: Box<CacheFirstCurveContext>,
    /// The source the deformation bends.
    pub source: EmbeddedDeformableSource,
    /// Optional parameter bounds of the source; `None` marks an unbounded end.
    pub source_parameter_range: [Option<f64>; 2],
    /// The mode-discriminated payload.
    pub data: EmbeddedDeformableData,
}

/// The source a `defm_int_cur` deformation bends.
pub enum EmbeddedDeformableSource {
    /// An embedded source curve.
    Curve(NurbsCurve),
    /// A flag and index referencing a curve serialized elsewhere in the stream.
    NativeReference {
        /// The boolean serialized before the index.
        flag: bool,
        /// The native reference index.
        index: i64,
    },
}

/// Native helix construction without an approximation cache.
pub struct HelixDefinition {
    /// Native angular interval.
    pub angle_range: [f64; 2],
    /// Helix center in document length units.
    pub center: Point3,
    /// Major radial vector.
    pub major: Vector3,
    /// Minor radial vector.
    pub minor: Vector3,
    /// Pitch vector.
    pub pitch: Vector3,
    /// Apex factor.
    pub apex_factor: f64,
    /// Axis direction.
    pub axis: Vector3,
}

impl HelixDefinition {
    pub(crate) fn into_definition(
        self,
    ) -> Result<cadmpeg_ir::geometry::ProceduralCurveDefinition, &'static str> {
        Ok(cadmpeg_ir::geometry::ProceduralCurveDefinition::Helix(
            cadmpeg_ir::geometry::HelixCurveConstruction::try_new(
                self.angle_range,
                cadmpeg_ir::geometry::HelixFrame {
                    center: self.center,
                    major: self.major,
                    minor: self.minor,
                    pitch: self.pitch,
                    axis: self.axis,
                },
                self.apex_factor,
                None,
            )?,
        ))
    }
}

/// The single construction selected by a procedural curve's native subtype.
pub enum ProceduralCurveConstruction {
    /// An exact curve cache.
    Exact,
    /// Native helix parameters.
    Helix(HelixDefinition),
    /// Source curve and vector-offset fields.
    VectorOffset(VectorOffsetDefinition),
    /// Source curve and bounded subset interval.
    Subset(SubsetDefinition),
    /// Ordered child curves and their parameter arrays.
    Compound(CompoundDefinition),
    /// Two-sided offset support context.
    TwoSidedOffset(EmbeddedTwoSidedOffset),
    /// Intersection support context and discontinuity flag.
    Intersection(EmbeddedIntersection, bool),
    /// Three ordered surface-intersection supports.
    ThreeSurface(EmbeddedThreeSurfaceIntersection),
    /// A surface-constrained curve family.
    SurfaceCurve(EmbeddedSurfaceCurve),
    /// Silhouette support and projection fields.
    Silhouette(EmbeddedSilhouette),
    /// Support context and surface-offset fields.
    SurfaceOffset(EmbeddedSurfaceOffset),
    /// Spring support context and direction.
    Spring(EmbeddedSpring),
    /// Deformation source and fields.
    Deformable(EmbeddedDeformable),
    /// Projection support and source.
    Projection(EmbeddedProjection),
    /// Support context and recursive law formulas.
    Law(EmbeddedLawCurve),
    /// A retained native construction with no decoded payload.
    Unknown(String),
}

/// A procedural curve cache and its selected native construction.
pub struct DecodedProceduralCurve {
    /// The cached B-spline curve in document length units.
    pub curve: NurbsCurve,
    /// The layout-specific construction fields.
    pub construction: ProceduralCurveConstruction,
    /// The cached block's fit tolerance, when present.
    pub cache_fit_tolerance: Option<f64>,
}

/// Decode a procedural 3D curve cache while following subtype-table references.
pub fn procedural_curve_resolving_refs(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
) -> Option<Result<DecodedProceduralCurve, cadmpeg_core::CodecError>> {
    procedural_curve_recursive(ctx, toks, table, &mut std::collections::HashSet::new())
}

/// Resolve the signed pcurve slot carried by an `intcurve` reference.
///
/// A typed construction owns its pcurves alongside the corresponding support
/// surfaces. A plain generated `intcurve` has one direct UV block, which is
/// the second slot in the ref-form grammar. The selector's sign is handled by
/// the owning PCURVE decoder because it composes with the intcurve sense bit.
///
/// Returns whether the pcurve remains in the standalone face surface's
/// native parameter chart.
pub fn pcurve_for_selector_with_chart(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    selector: i64,
    table: &SubtypeTable,
) -> Option<Result<(PcurveNurbs, bool), cadmpeg_core::CodecError>> {
    let slot = match selector {
        1 | -1 => 0,
        2 | -2 => 1,
        _ => return None,
    };
    pcurve_for_selector_recursive(
        ctx,
        toks,
        slot,
        table,
        &mut std::collections::HashSet::new(),
    )
}

fn pcurve_for_selector_recursive(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    slot: usize,
    table: &SubtypeTable,
    seen: &mut std::collections::HashSet<usize>,
) -> Option<Result<(PcurveNurbs, bool), cadmpeg_core::CodecError>> {
    let _depth = propagate_resource!(ctx.enter_nested("resolve ASM pcurve reference"));
    // A record-level intcurve wrapper can carry only a compact `{ref N}`
    // scope. Follow that one construction reference before decoding the
    // wrapper. Typed constructions may contain support references, but their
    // own ordered slots remain authoritative and must not be searched here.
    if let Some(index) = direct_subtype_reference(toks) {
        if !seen.contains(&index) {
            seen.insert(index);
            // Not the search refusal the four `for` loops over
            // `subtype_refs` state. This is the single record-level
            // delegation, and the wrapper's own routes below run whenever the
            // delegation yields no pcurve, including when it yields one from a
            // resolvable target. An index the table does not hold takes the
            // same route as a target that states no pcurve.
            if let Some(target) = table.span(index) {
                if let Some(result) =
                    pcurve_for_selector_recursive(ctx, target.tokens(), slot, table, seen)
                {
                    return Some(result);
                }
            }
        }
    }
    let has_typed_construction = crate::nurbs::toks::owned_construction_subtype(toks).is_some();
    if let Some(decoded) = procedural_curve_resolving_refs(ctx, toks, table) {
        let decoded = match decoded {
            Ok(decoded) => decoded,
            Err(error) => return Some(Err(error)),
        };
        if let Some(pcurve) = selected_pcurve(&decoded, slot) {
            let pcurve = pcurve.clone();
            return Some(Ok((pcurve, false)));
        }
        if !matches!(&decoded.construction, ProceduralCurveConstruction::Unknown(kind) if kind == "intcurve")
        {
            // Modern exact curves can carry the same cache-first support
            // context as the surface-related intcurve families. Their
            // construction remains exact, but the pcurve selector still
            // names one of that context's ordered support slots. Parse the
            // context only from the exact-intcurve marker; do not search
            // arbitrary BS2/BS3 blocks in the record.
            if let Some(marker) =
                crate::nurbs::toks::find_owned_intcurve_subtype(toks, "exact_int_cur")
            {
                let mut cur = Cur::at(toks, marker + 2);
                if let Some(context) = cache_first_curve_context(ctx, &mut cur, table) {
                    let context = match context {
                        Ok(context) => context,
                        Err(error) => return Some(Err(error)),
                    };
                    if let Some(pcurve) =
                        selected_support_pcurve(&context.surfaces, &context.pcurves, slot)
                    {
                        let pcurve = pcurve.clone();
                        return Some(Ok((pcurve, false)));
                    }
                }
            }
            return None;
        }
    }
    if has_typed_construction {
        return None;
    }
    (slot == 1)
        .then(|| direct_pcurve_after_curve(toks))?
        .map(|pcurve| Ok((pcurve, true)))
}

/// Return the sole record-level subtype-table reference of an untyped wrapper.
///
/// A nested reference inside a typed construction is deliberately excluded:
/// its owner has a structural pcurve slot, while an untyped wrapper has no
/// carrier of its own and delegates the complete construction.
fn direct_subtype_reference(toks: &[Token]) -> Option<usize> {
    if crate::nurbs::toks::owned_construction_subtype(toks).is_some() {
        return None;
    }
    let mut depth = 0usize;
    let mut candidate = None;
    for (position, token) in toks.iter().enumerate() {
        match token {
            Token::SubtypeOpen => {
                if depth == 0 {
                    let scope = crate::nurbs::toks::subtype_span(toks, position)?.tokens();
                    let index = match scope {
                        [Token::SubtypeOpen, Token::Long(index), Token::SubtypeClose]
                            if *index >= 0 =>
                        {
                            usize::try_from(*index).ok()
                        }
                        [Token::SubtypeOpen, Token::Ident(name), Token::Long(index), Token::SubtypeClose]
                            if name == "ref" && *index >= 0 =>
                        {
                            usize::try_from(*index).ok()
                        }
                        _ => None,
                    }?;
                    if candidate.replace(index).is_some() {
                        return None;
                    }
                }
                depth += 1;
            }
            Token::SubtypeClose => depth = depth.checked_sub(1)?,
            _ => {}
        }
    }
    candidate
}

fn selected_support_pcurve<'a>(
    surfaces: &[SupportSlot; 2],
    pcurves: &'a [Option<PcurveNurbs>; 2],
    slot: usize,
) -> Option<&'a PcurveNurbs> {
    match surfaces.get(slot)? {
        SupportSlot::Surface(_) => pcurves.get(slot)?.as_ref(),
        SupportSlot::Absent | SupportSlot::DeclaredOnly => None,
    }
}

fn selected_optional_pcurve<'a>(
    surfaces: &[Option<SurfaceGeometry>; 2],
    pcurves: &'a [Option<PcurveNurbs>; 2],
    slot: usize,
) -> Option<&'a PcurveNurbs> {
    surfaces.get(slot)?.as_ref()?;
    pcurves.get(slot)?.as_ref()
}

fn selected_pcurve(decoded: &DecodedProceduralCurve, slot: usize) -> Option<&PcurveNurbs> {
    match &decoded.construction {
        ProceduralCurveConstruction::TwoSidedOffset(context) => {
            selected_optional_pcurve(&context.surfaces, &context.pcurves, slot)
        }
        ProceduralCurveConstruction::Intersection(context, _) => {
            match context.surfaces.get(slot)? {
                SupportSlot::Absent => return None,
                SupportSlot::DeclaredOnly | SupportSlot::Surface(_) => {}
            }
            context.pcurves.get(slot)?.as_ref()
        }
        ProceduralCurveConstruction::ThreeSurface(context) => context.pcurves.get(slot),
        ProceduralCurveConstruction::SurfaceCurve(surface_curve) => {
            surface_curve.selected_pcurve(slot)
        }
        ProceduralCurveConstruction::Silhouette(context) => context.pcurves.get(slot),
        ProceduralCurveConstruction::SurfaceOffset(offset) => match &offset.layout {
            EmbeddedSurfaceOffsetLayout::ContextFirst { context, .. } => {
                selected_support_pcurve(&context.surfaces, &context.pcurves, slot)
            }
            EmbeddedSurfaceOffsetLayout::CacheFirst { context, .. } => {
                selected_support_pcurve(&context.surfaces, &context.pcurves, slot)
            }
        },
        ProceduralCurveConstruction::Spring(context) => match &context.layout {
            EmbeddedSpringLayout::CacheFirst { context, .. } => {
                selected_support_pcurve(&context.surfaces, &context.pcurves, slot)
            }
            EmbeddedSpringLayout::ContextFirst {
                supports,
                first_pcurve,
                second_pcurve,
                ..
            } => matches!(supports.get(slot), Some(EmbeddedSpringSupport::Surface(_)))
                .then(|| match slot {
                    0 => match first_pcurve.as_ref() {
                        EmbeddedSpringPcurve::Pcurve(pcurve) => Some(pcurve),
                        EmbeddedSpringPcurve::Range(_) => None,
                    },
                    1 => second_pcurve.as_ref(),
                    _ => None,
                })
                .flatten(),
        },
        ProceduralCurveConstruction::Deformable(embedded) => {
            selected_support_pcurve(&embedded.context.surfaces, &embedded.context.pcurves, slot)
        }
        ProceduralCurveConstruction::Projection(context) => context.pcurves.get(slot),
        ProceduralCurveConstruction::Law(context) => {
            selected_support_pcurve(&context.surfaces, &context.pcurves, slot)
        }
        ProceduralCurveConstruction::Exact
        | ProceduralCurveConstruction::Helix(_)
        | ProceduralCurveConstruction::VectorOffset(_)
        | ProceduralCurveConstruction::Subset(_)
        | ProceduralCurveConstruction::Compound(_)
        | ProceduralCurveConstruction::Unknown(_) => None,
    }
}

fn direct_pcurve_after_curve(toks: &[Token]) -> Option<PcurveNurbs> {
    let position = crate::nurbs::toks::owned_marker_positions(toks)?
        .into_iter()
        .next()?;
    let (_, end) = curve_block(toks, position)?;
    pcurve_block_with_end(toks, end).map(|(pcurve, _)| pcurve)
}

/// Decode an exact procedural curve construction that has no solved cache.
pub fn cacheless_procedural_curve_resolving_refs(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
) -> Option<Result<HelixDefinition, cadmpeg_core::CodecError>> {
    cacheless_procedural_curve_recursive(ctx, toks, table, &mut std::collections::HashSet::new())
}

fn cacheless_procedural_curve_recursive(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
    seen: &mut std::collections::HashSet<usize>,
) -> Option<Result<HelixDefinition, cadmpeg_core::CodecError>> {
    let _depth = propagate_resource!(ctx.enter_nested("resolve ASM cacheless curve reference"));
    if let Some(definition) = helix_definition(toks) {
        return Some(Ok(definition));
    }
    for index in crate::nurbs::toks::subtype_refs(toks) {
        if seen.contains(&index) {
            continue;
        }
        // The doc states what the index means. `docs/formats/asm.md`: "A named
        // `ref N` scope or compact `0x0F LONG N 0x10` scope nested inside a
        // surface, curve, or pcurve body indexes a per-file subtype table, not
        // a byte offset. Each subtype definition -- a `0x0F` opening followed
        // by a `0x0d`/`0x0e` name token other than `ref` -- contributes one
        // table entry in stream order." An index at or beyond the table's
        // length therefore names no definition the stream states. What the
        // decoder does about it is the decoder's decision: the search refuses
        // the stream rather than skipping the reference and reading the one
        // behind it.
        seen.insert(index);
        let target = table.span(index)?;
        if let Some(decoded) =
            cacheless_procedural_curve_recursive(ctx, target.tokens(), table, seen)
        {
            return Some(decoded);
        }
    }
    None
}

fn procedural_curve_recursive(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
    seen: &mut std::collections::HashSet<usize>,
) -> Option<Result<DecodedProceduralCurve, cadmpeg_core::CodecError>> {
    let _depth = propagate_resource!(ctx.enter_nested("resolve ASM procedural curve reference"));
    let vector_offset = vector_offset_definition(toks);
    let subset = subset_definition(toks);
    let compound = compound_definition(toks);
    // Wrapper constructions serialize their source curves before the record's
    // own cache, so the cache is the last decodable curve block. Every other
    // intcurve opens with its cache — the first block, followed by the fit
    // tolerance; later blocks belong to nested construction machinery
    // (support surfaces, blend spines, progenitors) and are not the carrier.
    let cache_scope = crate::nurbs::toks::cache_scope(toks)?;
    let positions = crate::nurbs::toks::owned_marker_positions(cache_scope)?;
    let solved = if vector_offset.is_some() || subset.is_some() || compound.is_some() {
        positions
            .into_iter()
            .rev()
            .find_map(|position| curve_block(cache_scope, position))
    } else {
        positions
            .into_iter()
            .find_map(|position| curve_block(cache_scope, position))
    };
    if let Some(decoded) = solved {
        let (curve, end) = decoded;
        let cache_fit_tolerance = match cache_scope.get(end) {
            Some(Token::Double(value)) => Some(*value * LEN_TO_MM),
            _ => None,
        };
        let construction = vector_offset
            .map(ProceduralCurveConstruction::VectorOffset)
            .map(Ok)
            .or_else(|| subset.map(ProceduralCurveConstruction::Subset).map(Ok))
            .or_else(|| {
                embedded_two_sided_offset(toks)
                    .map(ProceduralCurveConstruction::TwoSidedOffset)
                    .map(Ok)
            })
            .or_else(|| {
                embedded_intersection(ctx, toks, &curve, table).map(|result| {
                    result.map(|(context, flag)| {
                        ProceduralCurveConstruction::Intersection(context, flag)
                    })
                })
            })
            .or_else(|| {
                embedded_three_surface_intersection(toks)
                    .map(ProceduralCurveConstruction::ThreeSurface)
                    .map(Ok)
            })
            .or_else(|| {
                embedded_surface_curve(ctx, toks, table)
                    .map(|result| result.map(ProceduralCurveConstruction::SurfaceCurve))
            })
            .or_else(|| {
                embedded_silhouette(toks)
                    .map(ProceduralCurveConstruction::Silhouette)
                    .map(Ok)
            })
            .or_else(|| {
                embedded_surface_offset(ctx, toks, table)
                    .map(|result| result.map(ProceduralCurveConstruction::SurfaceOffset))
            })
            .or_else(|| {
                embedded_spring(ctx, toks, table)
                    .map(|result| result.map(ProceduralCurveConstruction::Spring))
            })
            .or_else(|| {
                embedded_deformable(ctx, toks, table)
                    .map(|result| result.map(ProceduralCurveConstruction::Deformable))
            })
            .or_else(|| {
                embedded_projection(toks)
                    .map(ProceduralCurveConstruction::Projection)
                    .map(Ok)
            })
            .or_else(|| {
                embedded_law_curve(ctx, toks)
                    .map(|result| result.map(ProceduralCurveConstruction::Law))
            })
            .or_else(|| compound.map(ProceduralCurveConstruction::Compound).map(Ok))
            .unwrap_or_else(|| {
                let native_kind = crate::nurbs::toks::owned_construction_subtype(toks)
                    .unwrap_or_else(|| "intcurve".to_string());
                if native_kind == "exact_int_cur" {
                    Ok(ProceduralCurveConstruction::Exact)
                } else {
                    Ok(helix_definition(toks)
                        .map(ProceduralCurveConstruction::Helix)
                        .unwrap_or(ProceduralCurveConstruction::Unknown(native_kind)))
                }
            });
        let construction = match construction {
            Ok(construction) => construction,
            Err(error) => return Some(Err(error)),
        };
        return Some(Ok(DecodedProceduralCurve {
            curve,
            construction,
            cache_fit_tolerance,
        }));
    }
    for index in crate::nurbs::toks::subtype_refs(toks) {
        if seen.contains(&index) {
            continue;
        }
        // The doc states what the index means. `docs/formats/asm.md`: "A named
        // `ref N` scope or compact `0x0F LONG N 0x10` scope nested inside a
        // surface, curve, or pcurve body indexes a per-file subtype table, not
        // a byte offset. Each subtype definition -- a `0x0F` opening followed
        // by a `0x0d`/`0x0e` name token other than `ref` -- contributes one
        // table entry in stream order." An index at or beyond the table's
        // length therefore names no definition the stream states. What the
        // decoder does about it is the decoder's decision: the search refuses
        // the stream rather than skipping the reference and reading the one
        // behind it.
        seen.insert(index);
        let target = table.span(index)?;
        if let Some(decoded) = procedural_curve_recursive(ctx, target.tokens(), table, seen) {
            return Some(decoded);
        }
    }
    None
}

fn embedded_deformable(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
) -> Option<Result<EmbeddedDeformable, cadmpeg_core::CodecError>> {
    let (marker, _) = crate::nurbs::toks::find_owned_subtype_marker(toks, &["defm_int_cur"])?;
    let mut cur = Cur::at(toks, marker + 2);
    let context = match cache_first_curve_context(ctx, &mut cur, table)? {
        Ok(context) => context,
        Err(error) => return Some(Err(error)),
    };
    let source_start = cur.pos();
    let source = if let Some(curve) = embedded_base_curve_resolving_refs(&mut cur, table) {
        EmbeddedDeformableSource::Curve(curve)
    } else {
        cur.set_pos(source_start);
        (cur.take_ident()? == "intcurve").then_some(())?;
        let flag = cur.take_bool()?;
        let reference = cur.pos();
        matches!(toks.get(reference), Some(Token::SubtypeOpen)).then_some(())?;
        matches!(toks.get(reference + 1), Some(Token::Ident(name)) if name == "ref")
            .then_some(())?;
        let Some(Token::Long(index)) = toks.get(reference + 2) else {
            return None;
        };
        let reference_span = crate::nurbs::toks::subtype_span(toks, reference)?.tokens();
        cur.set_pos(reference + reference_span.len());
        EmbeddedDeformableSource::NativeReference {
            flag,
            index: *index,
        }
    };
    let source_parameter_range = [
        cur.take_optional_range_value()?.value(),
        cur.take_optional_range_value()?.value(),
    ];
    let mode = cur.take_long()?;
    let data = match mode {
        8 => {
            let mut vectors = [Vector3::new(0.0, 0.0, 0.0); 4];
            for vector in &mut vectors {
                let value = cur.take_vector3()?;
                *vector = Vector3::new(value[0], value[1], value[2]);
            }
            let count = cur.take_long()?;
            let count = usize::try_from(count).ok()?;
            let mut parameter_pairs = Vec::new();
            for _ in 0..count {
                parameter_pairs.push([cur.take_f64()?, cur.take_f64()?]);
            }
            EmbeddedDeformableData::VectorField {
                vectors,
                parameter_pairs,
            }
        }
        3 => {
            let mut leading_vectors = [Vector3::new(0.0, 0.0, 0.0); 4];
            for vector in &mut leading_vectors {
                let value = cur.take_vector3()?;
                *vector = Vector3::new(value[0], value[1], value[2]);
            }
            let leading_parameter = cur.take_f64()?;
            let leading_flags = [cur.take_bool()?, cur.take_bool()?, cur.take_bool()?];
            let value = cur.take_position()?;
            let trailing_point = Point3::new(
                value[0] * LEN_TO_MM,
                value[1] * LEN_TO_MM,
                value[2] * LEN_TO_MM,
            );
            let mut trailing_vectors = [Vector3::new(0.0, 0.0, 0.0); 2];
            for vector in &mut trailing_vectors {
                let value = cur.take_vector3()?;
                *vector = Vector3::new(value[0], value[1], value[2]);
            }
            let frame_parameter = cur.take_f64()?;
            let frame_flags = [cur.take_bool()?, cur.take_bool()?];
            let parameters = [cur.take_f64()?, cur.take_f64()?, cur.take_f64()?];
            let trailing_flags = [
                cur.take_bool()?,
                cur.take_bool()?,
                cur.take_bool()?,
                cur.take_bool()?,
                cur.take_bool()?,
            ];
            let trailing_parameter = cur.take_f64()?;
            let trailing_value = cur.take_long()?;
            EmbeddedDeformableData::Mode3 {
                leading_vectors,
                leading_parameter,
                leading_flags,
                trailing_point,
                trailing_vectors,
                frame_parameter,
                frame_flags,
                parameters,
                trailing_flags,
                trailing_parameter,
                trailing_value,
            }
        }
        _ => return None,
    };
    matches!(toks.get(cur.pos()), Some(Token::SubtypeClose)).then_some(Ok(EmbeddedDeformable {
        context: Box::new(context),
        source,
        source_parameter_range,
        data,
    }))
}

/// Decode one law support surface, mapping the `null_surface` sentinel to an
/// absent side.
fn nullable_law_surface(cur: &mut Cur<'_>) -> Option<Nullable<EmbeddedSupport>> {
    let saved = cur.pos();
    if cur.take_ident() == Some("null_surface") {
        return Some(Nullable::Null);
    }
    cur.set_pos(saved);
    Some(Nullable::Value(embedded_support(cur)?))
}

/// Consume one version-form interval bound: a bare `false` unbounded sentinel
/// or a `true`-prefixed double. Any other encoding fails the strict match so
/// the record falls back to verbatim retention.
fn law_version_bound(cur: &mut Cur<'_>) -> Option<Nullable<f64>> {
    match cur.peek()? {
        Token::False => {
            cur.bump();
            Some(Nullable::Null)
        }
        Token::True => {
            cur.bump();
            cur.take_f64().map(Nullable::Value)
        }
        _ => None,
    }
}

fn embedded_law_curve(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
) -> Option<Result<EmbeddedLawCurve, cadmpeg_core::CodecError>> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "law_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    // The stamped serializer form opens with an integer stamp and an enum
    // before the solved cache; the legacy form opens directly with the cache
    // marker.
    let stamp_start = cur.pos();
    let stamp = matches!(cur.peek(), Some(Token::Long(_)))
        .then(|| {
            let stamp = cur.take_long()?;
            let post_enum = cur.take_enum()?;
            Some((stamp, post_enum))
        })
        .flatten();
    if stamp.is_none() {
        // Restore any tokens consumed by a partially-matched stamp prefix so
        // the legacy path (and, on its failure, verbatim retention) sees the
        // record from the cache marker rather than mid-prefix.
        cur.set_pos(stamp_start);
    }
    let (_, solved_end) = curve_block(toks, cur.pos())?;
    cur.set_pos(solved_end);
    cur.take_f64()?;
    let supports = [
        nullable_law_surface(&mut cur)?.value(),
        nullable_law_surface(&mut cur)?.value(),
    ];
    let mut pcurves = [
        nullable_embedded_pcurve(&mut cur)?.value(),
        nullable_embedded_pcurve(&mut cur)?.value(),
    ];
    for (pcurve, support) in pcurves.iter_mut().zip(&supports) {
        if let (Some(pcurve), Some(support)) = (pcurve, support) {
            support.chart.normalize(pcurve)?;
        }
    }
    let surfaces = supports.map(|support| support.map(|support| support.surface));
    let layout = if let Some((stamp, post_enum)) = stamp {
        EmbeddedLawCurveLayout::Version {
            stamp,
            post_enum,
            parameter_range: [
                law_version_bound(&mut cur)?.value(),
                law_version_bound(&mut cur)?.value(),
            ],
        }
    } else {
        EmbeddedLawCurveLayout::Legacy([cur.take_range_value()?, cur.take_range_value()?])
    };
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let extension = cur.take_long()?;
    let primary = propagate_resource!(law_formula(ctx, &mut cur)?);
    let count = usize::try_from(cur.take_long()?).ok()?;
    if count > 100_000 {
        return None;
    }
    let mut additional = Vec::new();
    for _ in 0..count {
        additional.push(propagate_resource!(law_formula(ctx, &mut cur)?));
    }
    Some(Ok(EmbeddedLawCurve {
        surfaces: surfaces.map(|surface| surface.map_or(SupportSlot::Absent, SupportSlot::Surface)),
        pcurves,
        discontinuities,
        layout,
        extension,
        primary,
        additional,
    }))
}

fn embedded_spring(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
) -> Option<Result<EmbeddedSpring, cadmpeg_core::CodecError>> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "spring_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    if matches!(cur.peek(), Some(Token::Long(_))) {
        let context = match cache_first_curve_context(ctx, &mut cur, table)? {
            Ok(context) => context,
            Err(error) => return Some(Err(error)),
        };
        let direction = cur.take_enum()?;
        return Some(Ok(EmbeddedSpring {
            layout: EmbeddedSpringLayout::CacheFirst {
                context: Box::new(context),
            },
            direction,
        }));
    }
    let mut take_support = || -> Option<Result<_, cadmpeg_core::CodecError>> {
        let saved = cur.pos();
        if cur.take_ident() == Some("null_surface") {
            Some(Ok((
                EmbeddedSpringSupport::Ranges([
                    [cur.take_range_value()?, cur.take_range_value()?],
                    [cur.take_range_value()?, cur.take_range_value()?],
                ]),
                SupportChart::Canonical,
            )))
        } else {
            cur.set_pos(saved);
            let EmbeddedSupport { surface, chart, .. } = embedded_support(&mut cur)?;
            Some(Ok((EmbeddedSpringSupport::Surface(surface), chart)))
        }
    };
    let [(first_support, first_chart), (second_support, second_chart)] = [
        propagate_resource!(take_support()?),
        propagate_resource!(take_support()?),
    ];
    let saved = cur.pos();
    let mut first_pcurve = if cur.take_ident() == Some("nullbs") {
        EmbeddedSpringPcurve::Range([cur.take_range_value()?, cur.take_range_value()?])
    } else {
        cur.set_pos(saved);
        let (pcurve, end) = pcurve_block_with_end(toks, cur.pos())?;
        cur.set_pos(end);
        EmbeddedSpringPcurve::Pcurve(pcurve)
    };
    let saved = cur.pos();
    let second_pcurve = if cur.take_ident() == Some("nullbs") {
        None
    } else {
        cur.set_pos(saved);
        let (pcurve, end) = pcurve_block_with_end(toks, cur.pos())?;
        cur.set_pos(end);
        Some(pcurve)
    };
    if let EmbeddedSpringPcurve::Pcurve(pcurve) = &mut first_pcurve {
        first_chart.normalize(pcurve)?;
    }
    let mut second_pcurve = second_pcurve;
    if let Some(pcurve) = &mut second_pcurve {
        second_chart.normalize(pcurve)?;
    }
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let discontinuity_flag = cur.take_bool()?;
    let direction = cur.take_enum()?;
    Some(Ok(EmbeddedSpring {
        layout: EmbeddedSpringLayout::ContextFirst {
            supports: Box::new([first_support, second_support]),
            first_pcurve: Box::new(first_pcurve),
            second_pcurve,
            parameter_range,
            discontinuities,
            discontinuity_flag,
        },
        direction,
    }))
}

/// Writable fields in the shared context tail of a `spring_int_cur` subtype.
pub struct SpringPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
    /// Byte offset of the boolean after the discontinuity arrays.
    pub discontinuity_flag: usize,
    /// Byte offset of the direction enum.
    pub direction: usize,
}

/// Locate spring context fields by walking the subtype grammar at `int_width`.
pub fn spring_patch_layout(bytes: &[u8], int_width: RefWidth) -> Option<SpringPatchLayout> {
    let (marker, name_len) = find_owned_intcurve_subtype(bytes, b"spring_int_cur", int_width)?;
    let mut position = marker + name_len + 3;
    for _ in 0..2 {
        let saved = position;
        if take_native_ident(bytes, &mut position).as_deref() == Some("null_surface") {
            for _ in 0..4 {
                take_double_payload(bytes, &mut position)?;
            }
        } else {
            position = saved;
            decode_embedded_surface(bytes, &mut position, int_width)?;
        }
    }
    let saved = position;
    if take_native_ident(bytes, &mut position).as_deref() == Some("nullbs") {
        take_double_payload(bytes, &mut position)?;
        take_double_payload(bytes, &mut position)?;
    } else {
        position = decode_pcurve_block_with_end(bytes, saved, int_width)?.1;
    }
    let saved = position;
    if take_native_ident(bytes, &mut position).as_deref() != Some("nullbs") {
        position = decode_pcurve_block_with_end(bytes, saved, int_width)?.1;
    }
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    let discontinuity_flag = position;
    take_bool(bytes, &mut position)?;
    let direction = position;
    take_tagged_int(bytes, &mut position, 0x15, int_width)?;
    Some(SpringPatchLayout {
        parameter_range,
        discontinuities,
        discontinuity_flag,
        direction,
    })
}

/// Writable radius-law payloads in a rolling-ball blend surface subtype.
pub struct RollingBallPatchLayout {
    /// Byte offsets of the two radius-law doubles.
    pub radii: [usize; 2],
}

/// Writable leading fields in a translational-extrusion surface subtype.
pub struct ExtrusionPatchLayout {
    /// Byte offsets of the two parameter-interval doubles.
    pub parameter_interval: [usize; 2],
    /// Byte offset of the extrusion direction vector.
    pub direction: usize,
    /// Byte offset of the native position triple.
    pub native_position: usize,
}

/// Writable construction fields in a `helix_int_cur` subtype.
pub struct HelixPatchLayout {
    /// Byte offsets of the two angle-range doubles.
    pub angle_range: [usize; 2],
    /// Byte offsets of the four frame vectors.
    pub frame_vectors: [usize; 4],
    /// Byte offset of the apex factor double.
    pub apex_factor: usize,
    /// Byte offset of the axis vector.
    pub axis: usize,
}

/// Writable fields following the source cache in an `offset_int_cur` subtype.
pub struct VectorOffsetPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offset of the offset vector.
    pub offset: usize,
}

/// Writable parameter range following the parent curve in `subset_int_cur`.
pub struct SubsetPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
}

/// Writable parameter arrays in a `comp_int_cur` subtype.
pub struct CompoundPatchLayout {
    /// Byte offsets of the values in the parameter array.
    pub parameters: Vec<usize>,
    /// Byte offsets of the values in the component-parameter array.
    pub component_parameters: Vec<usize>,
}

/// Locate both compound parameter arrays from their native counts.
pub fn compound_patch_layout(bytes: &[u8], int_width: RefWidth) -> Option<CompoundPatchLayout> {
    let name = b"comp_int_cur";
    let marker = find_owned_subtype_marker(bytes, &[name], int_width).map(|(marker, _)| marker)?;
    subtype_span(bytes, marker, int_width)?;
    let mut position = marker + name.len() + 3;
    let parameters = take_float_array_payloads(bytes, &mut position, int_width)?;
    let component_count =
        usize::try_from(take_tagged_int(bytes, &mut position, 0x04, int_width)?).ok()?;
    if component_count == 0 {
        return None;
    }
    let mut component_parameters = Vec::new();
    for _ in 0..component_count {
        component_parameters.push(take_double_payload(bytes, &mut position)?);
    }
    Some(CompoundPatchLayout {
        parameters,
        component_parameters,
    })
}

/// Locate the subset range by consuming the subtype-owned parent curve.
pub fn subset_patch_layout(bytes: &[u8], int_width: RefWidth) -> Option<SubsetPatchLayout> {
    let name = b"subset_int_cur";
    let marker = find_owned_subtype_marker(bytes, &[name], int_width).map(|(marker, _)| marker)?;
    subtype_span(bytes, marker, int_width)?;
    let mut position = marker + name.len() + 3;
    position = decode_curve_block(bytes, position, int_width)?.end();
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    Some(SubsetPatchLayout { parameter_range })
}

/// Locate vector-offset fields by consuming the wrapper flag and source curve.
pub fn vector_offset_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
) -> Option<VectorOffsetPatchLayout> {
    let name = b"offset_int_cur";
    let marker = find_owned_subtype_marker(bytes, &[name], int_width).map(|(marker, _)| marker)?;
    subtype_span(bytes, marker, int_width)?;
    let mut position = marker + name.len() + 3;
    take_bool(bytes, &mut position)?;
    position = decode_curve_block(bytes, position, int_width)?.end();
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let offset = position + 1;
    take_native_vec3(bytes, &mut position, 0x14)?;
    Some(VectorOffsetPatchLayout {
        parameter_range,
        offset,
    })
}

/// Locate helix fields by consuming the subtype prefix grammar.
pub fn helix_patch_layout(bytes: &[u8], int_width: RefWidth) -> Option<HelixPatchLayout> {
    let name = b"helix_int_cur";
    let marker = find_owned_subtype_marker(bytes, &[name], int_width).map(|(marker, _)| marker)?;
    subtype_span(bytes, marker, int_width)?;
    let mut position = marker + name.len() + 3;
    let current_layout = take_optional_helix_revision(bytes, &mut position, int_width)?;
    let take_range_payload = |position: &mut usize| {
        if matches!(bytes.get(*position), Some(0x0a | 0x0b)) {
            *position += 1;
        }
        take_double_payload(bytes, position)
    };
    let angle_range = [
        take_range_payload(&mut position)?,
        take_range_payload(&mut position)?,
    ];
    let mut frame_vectors = [0usize; 4];
    let frame_tags = if current_layout {
        [0x13, 0x14, 0x14, 0x14]
    } else {
        [0x13; 4]
    };
    for (offset, tag) in frame_vectors.iter_mut().zip(frame_tags) {
        *offset = position + 1;
        take_native_vec3(bytes, &mut position, tag)?;
    }
    let apex_factor = take_double_payload(bytes, &mut position)?;
    let axis = position + 1;
    take_native_vec3(bytes, &mut position, 0x14)?;
    Some(HelixPatchLayout {
        angle_range,
        frame_vectors,
        apex_factor,
        axis,
    })
}

/// Locate extrusion fields from the `cyl_spl_sur` subtype header.
pub fn extrusion_patch_layout(bytes: &[u8], int_width: RefWidth) -> Option<ExtrusionPatchLayout> {
    let names: [&[u8]; 2] = [b"cyl_spl_sur", b"cylsur"];
    let (start, name_len) = find_owned_subtype_marker(bytes, &names, int_width)
        .map(|(start, name)| (start, name.len()))?;
    subtype_span(bytes, start, int_width)?;
    let mut position = start + name_len + 3;
    let parameter_interval = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let direction = position + 1;
    take_native_vec3(bytes, &mut position, 0x14)?;
    let native_position = position + 1;
    take_native_vec3(bytes, &mut position, 0x13)?;
    Some(ExtrusionPatchLayout {
        parameter_interval,
        direction,
        native_position,
    })
}

/// Locate the rolling-ball radius pair by walking both supports and the slice curve.
pub fn rolling_ball_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
) -> Option<Result<RollingBallPatchLayout, cadmpeg_core::decode::ResourceLimit>> {
    let names: [&[u8]; 6] = [
        b"rb_blend_spl_sur",
        b"rbblnsur",
        b"pipe_spl_sur",
        b"pipesur",
        b"sss_blend_spl_sur",
        b"sssblndsur",
    ];
    let (start, name_len) = find_owned_subtype_marker(bytes, &names, int_width)
        .map(|(start, name)| (start, name.len()))?;
    let span = subtype_span(bytes, start, int_width)?.bytes();
    let payload_start = name_len + 3;
    let radii = (|| {
        let mut position = payload_start;
        take_tagged_int(span, &mut position, 0x04, int_width)?;
        for _ in 0..2 {
            match decode_rolling_ball_side(span, &mut position, int_width)? {
                Ok(_) => {}
                Err(limit) => return Some(Err(limit)),
            }
        }
        position = decode_curve_block(span, position, int_width)?.end();
        Some(Ok([
            start + take_double_payload(span, &mut position)?,
            start + take_double_payload(span, &mut position)?,
        ]))
    })()
    .or_else(|| {
        let mut position = payload_start;
        for _ in 0..2 {
            take_native_string(span, &mut position, int_width)?;
            let support_kind = take_native_ident(span, &mut position)?;
            if !matches!(support_kind.as_str(), "plane" | "sphere" | "cone" | "torus") {
                return None;
            }
            position = decode_surface_block(span, position, int_width)?.end();
        }
        position = decode_curve_block(span, position, int_width)?.end();
        Some(Ok([
            start + take_double_payload(span, &mut position)?,
            start + take_double_payload(span, &mut position)?,
        ]))
    })?;
    Some(radii.map(|radii| RollingBallPatchLayout { radii }))
}

/// Embedded cache-first base curve: a direct NURBS block, an analytic
/// `straight`, or a referenced `intcurve` resolved to its solved cache.
pub(super) fn embedded_base_curve_resolving_refs(
    cur: &mut Cur<'_>,
    table: &SubtypeTable,
) -> Option<NurbsCurve> {
    let toks = cur.toks();
    if let Some(decoded) = curve_block(toks, cur.pos()) {
        let (curve, end) = decoded;
        cur.set_pos(end);
        return Some(curve);
    }
    let saved = cur.pos();
    // Some revision-gated owners omit the redundant `intcurve` identifier and
    // store only its sense followed by the compact subtype-table reference.
    if matches!(cur.peek(), Some(Token::True | Token::False)) {
        cur.take_bool()?;
        let reference = cur.pos();
        if matches!(toks.get(reference), Some(Token::SubtypeOpen)) {
            let scope = crate::nurbs::toks::subtype_span(toks, reference)?;
            if let Some(curve) = owned_curve_cache_resolving_refs(scope, table) {
                cur.set_pos(reference + scope.tokens().len());
                return Some(curve);
            }
        }
        cur.set_pos(saved);
    }
    match cur.take_ident()? {
        "straight" => {
            let origin = cur.take_position()?;
            let direction = cur.take_vector3()?;
            let start = Point3::new(
                origin[0] * LEN_TO_MM,
                origin[1] * LEN_TO_MM,
                origin[2] * LEN_TO_MM,
            );
            let end = Point3::new(
                (origin[0] + direction[0]) * LEN_TO_MM,
                (origin[1] + direction[1]) * LEN_TO_MM,
                (origin[2] + direction[2]) * LEN_TO_MM,
            );
            NurbsCurve::new(
                1,
                vec![0.0, 0.0, 1.0, 1.0],
                cadmpeg_ir::geometry::nurbs::NurbsPoles3::Polynomial {
                    points: vec![start, end],
                },
                false,
            )
            .ok()
        }
        "ellipse" => {
            let center = cur.take_position()?;
            let normal = cur.take_vector3()?;
            let major = cur.take_vector3()?;
            let ratio = cur.take_f64()?;
            ellipse_to_nurbs(center, normal, major, ratio)
        }
        "degenerate_curve" => {
            let point = cur.take_position()?;
            let at = Point3::new(
                point[0] * LEN_TO_MM,
                point[1] * LEN_TO_MM,
                point[2] * LEN_TO_MM,
            );
            NurbsCurve::new(
                1,
                vec![0.0, 0.0, 1.0, 1.0],
                cadmpeg_ir::geometry::nurbs::NurbsPoles3::Polynomial {
                    points: vec![at, at],
                },
                false,
            )
            .ok()
        }
        "intcurve" => {
            cur.take_bool()?;
            let reference = cur.pos();
            let compact_ref = matches!(toks.get(reference), Some(Token::SubtypeOpen))
                && matches!(toks.get(reference + 1), Some(Token::Ident(name)) if name == "ref")
                && matches!(toks.get(reference + 2), Some(Token::Long(_)));
            if !compact_ref {
                if matches!(toks.get(reference), Some(Token::SubtypeOpen)) {
                    // Inline subtype scope: resolve its solved curve cache.
                    let scope = crate::nurbs::toks::subtype_span(toks, reference)?;
                    let curve = owned_curve_cache_resolving_refs(scope, table)?;
                    cur.set_pos(reference + scope.tokens().len());
                    return Some(curve);
                }
                cur.set_pos(saved);
                return None;
            }
            let Some(Token::Long(index)) = toks.get(reference + 2) else {
                return None;
            };
            let index = usize::try_from(*index).ok()?;
            let reference_span = crate::nurbs::toks::subtype_span(toks, reference)?.tokens();
            cur.set_pos(reference + reference_span.len());
            table
                .span(index)
                .and_then(|target| owned_curve_cache_resolving_refs(target, table))
        }
        _ => {
            cur.set_pos(saved);
            None
        }
    }
}

fn embedded_surface_offset(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
) -> Option<Result<EmbeddedSurfaceOffset, cadmpeg_core::CodecError>> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "off_surf_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    if matches!(cur.peek(), Some(Token::Long(_))) {
        let context = match cache_first_curve_context(ctx, &mut cur, table)? {
            Ok(context) => context,
            Err(error) => return Some(Err(error)),
        };
        let base_u_range = [
            cur.take_optional_range_value()?.value()?,
            cur.take_optional_range_value()?.value()?,
        ];
        let base_v_range = [
            cur.take_optional_range_value()?.value()?,
            cur.take_optional_range_value()?.value()?,
        ];
        let base = embedded_base_curve_resolving_refs(&mut cur, table)?;
        let base_endpoints = [
            cur.take_optional_range_value()?.value(),
            cur.take_optional_range_value()?.value(),
        ];
        let base_range = [
            cur.take_optional_range_value()?.value()?,
            cur.take_optional_range_value()?.value()?,
        ];
        return Some(Ok(EmbeddedSurfaceOffset {
            layout: EmbeddedSurfaceOffsetLayout::CacheFirst {
                context: Box::new(context),
                base_endpoints,
            },
            base_u_range,
            base_v_range,
            base,
            base_range,
            distance: cur.take_f64()? * LEN_TO_MM,
            shift: cur.take_f64()?,
            scale: cur.take_f64()?,
        }));
    }
    let RequiredSupportPair { surfaces, pcurves } = required_support_pair(&mut cur)?;
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let discontinuity_flag = cur.take_bool()?;
    let base_u_range = [cur.take_range_value()?, cur.take_range_value()?];
    let base_v_range = [cur.take_range_value()?, cur.take_range_value()?];
    let (base, base_end) = curve_block(toks, cur.pos())?;
    cur.set_pos(base_end);
    let base_range = [cur.take_range_value()?, cur.take_range_value()?];
    Some(Ok(EmbeddedSurfaceOffset {
        layout: EmbeddedSurfaceOffsetLayout::ContextFirst {
            context: Box::new(EmbeddedIntersection {
                surfaces: surfaces.map(SupportSlot::Surface),
                pcurves: pcurves.map(Some),
                parameter_range,
                discontinuities,
            }),
            discontinuity_flag,
        },
        base_u_range,
        base_v_range,
        base,
        base_range,
        distance: cur.take_f64()? * LEN_TO_MM,
        shift: cur.take_f64()?,
        scale: cur.take_f64()?,
    }))
}

/// Writable scalar fields in an `off_surf_int_cur` subtype.
pub struct SurfaceOffsetPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
    /// Byte offset of the boolean after the discontinuity arrays.
    pub discontinuity_flag: usize,
    /// Byte offsets of the two base-surface U-range doubles.
    pub base_u_range: [usize; 2],
    /// Byte offsets of the two base-surface V-range doubles.
    pub base_v_range: [usize; 2],
    /// Byte offsets of the two base-curve range doubles.
    pub base_range: [usize; 2],
    /// Byte offset of the offset-distance double.
    pub distance: usize,
    /// Byte offset of the shift double.
    pub shift: usize,
    /// Byte offset of the scale double.
    pub scale: usize,
}

/// Locate surface-offset fields by walking supports and the base curve.
pub fn surface_offset_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
) -> Option<SurfaceOffsetPatchLayout> {
    let (marker, name_len) = find_owned_intcurve_subtype(bytes, b"off_surf_int_cur", int_width)?;
    let mut position = marker + name_len + 3;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    let discontinuity_flag = position;
    take_bool(bytes, &mut position)?;
    let base_u_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let base_v_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    position = decode_curve_block(bytes, position, int_width)?.end();
    let base_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let distance = take_double_payload(bytes, &mut position)?;
    let shift = take_double_payload(bytes, &mut position)?;
    let scale = take_double_payload(bytes, &mut position)?;
    Some(SurfaceOffsetPatchLayout {
        parameter_range,
        discontinuities,
        discontinuity_flag,
        base_u_range,
        base_v_range,
        base_range,
        distance,
        shift,
        scale,
    })
}

/// Draft factor of the marker template, replaced by the native tail value.
const ZERO_DRAFT_FACTOR: cadmpeg_ir::scalar::FiniteReal = cadmpeg_ir::scalar::FiniteReal::ZERO;

fn embedded_silhouette(toks: &[Token]) -> Option<EmbeddedSilhouette> {
    use cadmpeg_ir::geometry::SilhouetteKind;
    let names = [
        ("silh_int_cur", SilhouetteKind::Standard {}),
        ("para_silh_int_cur", SilhouetteKind::Parametric {}),
        ("parasil", SilhouetteKind::Parametric {}),
        (
            "taper_silh_int_cur",
            SilhouetteKind::Taper {
                draft_factor: ZERO_DRAFT_FACTOR,
            },
        ),
    ];
    let candidates: Vec<&str> = names.iter().map(|(name, _)| *name).collect();
    let (marker, name) = crate::nurbs::toks::find_owned_subtype_marker(toks, &candidates)?;
    let mut silhouette = names
        .iter()
        .find_map(|(candidate, silhouette)| (*candidate == name).then(|| silhouette.clone()))?;
    let mut cur = Cur::at(toks, marker + 2);
    let RequiredSupportPair { surfaces, pcurves } = required_support_pair(&mut cur)?;
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let cast_surface = embedded_surface(&mut cur)?;
    let light = cur.take_vector3()?;
    let light_direction = normalized(light)?;
    if matches!(silhouette, SilhouetteKind::Taper { .. }) {
        silhouette = SilhouetteKind::Taper {
            draft_factor: cadmpeg_ir::scalar::FiniteReal::new(cur.take_f64()?)?,
        };
    }
    Some(EmbeddedSilhouette {
        surfaces,
        pcurves,
        parameter_range,
        discontinuities,
        silhouette,
        cast_surface,
        light_direction,
    })
}

/// Writable light and optional taper fields in a silhouette subtype.
pub struct SilhouettePatchLayout {
    /// Byte offset of the light-direction vector.
    pub light_direction: usize,
    /// Byte offset of the draft-factor double, for tapered silhouettes.
    pub draft_factor: Option<usize>,
}

/// Locate silhouette fields by walking its context and cast surface.
pub fn silhouette_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
    silhouette: &cadmpeg_ir::geometry::SilhouetteKind,
) -> Option<SilhouettePatchLayout> {
    use cadmpeg_ir::geometry::SilhouetteKind;
    let (names, tapered): (&[&[u8]], bool) = match silhouette {
        SilhouetteKind::Standard {} => (&[b"silh_int_cur"], false),
        SilhouetteKind::Parametric {} => (&[b"para_silh_int_cur", b"parasil"], false),
        SilhouetteKind::Taper { .. } => (&[b"taper_silh_int_cur"], true),
    };
    let (marker, name) = find_owned_subtype_marker(bytes, names, int_width)?;
    let mut position = marker + name.len() + 3;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    take_double_payload(bytes, &mut position)?;
    take_double_payload(bytes, &mut position)?;
    for _ in 0..3 {
        take_float_array_payloads(bytes, &mut position, int_width)?;
    }
    decode_embedded_surface(bytes, &mut position, int_width)?;
    (*bytes.get(position)? == 0x14).then_some(())?;
    let light_direction = position + 1;
    bytes.get(light_direction..light_direction + 24)?;
    position = light_direction + 24;
    let draft_factor = if tapered {
        Some(take_double_payload(bytes, &mut position)?)
    } else {
        None
    };
    Some(SilhouettePatchLayout {
        light_direction,
        draft_factor,
    })
}

fn embedded_surface_curve(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    table: &SubtypeTable,
) -> Option<Result<EmbeddedSurfaceCurve, cadmpeg_core::CodecError>> {
    use cadmpeg_ir::geometry::SurfaceCurveFamilyKind;
    let names = [
        ("blend_int_cur", SurfaceCurveFamilyKind::Blend),
        ("bldcur", SurfaceCurveFamilyKind::Blend),
        ("surf_int_cur", SurfaceCurveFamilyKind::SurfaceConstrained),
        ("surfcur", SurfaceCurveFamilyKind::SurfaceConstrained),
        ("par_int_cur", SurfaceCurveFamilyKind::Parametric),
        ("parcur", SurfaceCurveFamilyKind::Parametric),
        ("skin_int_cur", SurfaceCurveFamilyKind::Skin),
        ("d5c2_cur", SurfaceCurveFamilyKind::Skin),
    ];
    let candidates: Vec<&str> = names.iter().map(|(name, _)| *name).collect();
    let (marker, name) = crate::nurbs::toks::find_owned_subtype_marker(toks, &candidates)?;
    let family = names
        .iter()
        .find_map(|(candidate, family)| (*candidate == name).then_some(*family))?;
    let position = marker + 2;
    context_first_surface_curve(toks, position, family)
        .map(Ok)
        .or_else(|| cache_first_surface_curve(ctx, toks, position, family, table))
}

/// Decode a form-2 `par_int_cur` scope into the curve it denotes.
///
/// Form 2 replaces the solved cache and its fit tolerance with a bool-gated
/// curve interval and a closed-form enum; the members from the supports onward
/// are the shared cache-first context. The construction is therefore the
/// occupied support surface restricted to the parameter curve in the matching
/// slot.
///
/// Only a pcurve that holds one surface parameter constant across the support's
/// whole domain in the other is decoded: that restriction is exactly a NURBS
/// curve of the support's degree over the support's knot vector. Any other
/// pcurve denotes a curve a NURBS cache can only approximate, so it is refused.
pub fn decode_par_int_cur_isoline(
    scope: &[u8],
    int_width: RefWidth,
) -> Option<Result<NurbsCurve, cadmpeg_core::decode::ResourceLimit>> {
    let names: [&[u8]; 2] = [b"par_int_cur", b"parcur"];
    let (start, name) = find_owned_subtype_marker(scope, &names, int_width)?;
    let mut position = start + name.len() + 3;
    (take_tagged_int(scope, &mut position, 0x04, int_width)? > 0).then_some(())?;
    (take_tagged_int(scope, &mut position, 0x15, int_width)? == 2).then_some(())?;
    take_range_value(scope, &mut position)?;
    take_range_value(scope, &mut position)?;
    take_tagged_int(scope, &mut position, 0x15, int_width)?;
    let supports = [
        decode_optional_rolling_ball_surface(scope, &mut position, int_width)?
            .value()
            .map(|support| support.surface),
        decode_optional_rolling_ball_surface(scope, &mut position, int_width)?
            .value()
            .map(|support| support.surface),
    ];
    let pcurves = [
        decode_nullable_embedded_pcurve(scope, &mut position, int_width)?.value(),
        decode_nullable_embedded_pcurve(scope, &mut position, int_width)?.value(),
    ];
    // The support-slot selector puts the parametric support and its parameter
    // curve in the same slot and nulls the other; a support without its pcurve,
    // or two occupied slots, is not this construction.
    let occupied: Vec<usize> = (0..2)
        .filter(|slot| supports[*slot].is_some() || pcurves[*slot].is_some())
        .collect();
    let [slot] = occupied.as_slice() else {
        return None;
    };
    let (Some(SurfaceGeometry::Solved(SolvedSurfaceGeometry::Nurbs(support))), Some(pcurve)) =
        (&supports[*slot], &pcurves[*slot])
    else {
        return None;
    };
    surface_isoline_along(
        cadmpeg_ir::eval::admission::EvaluationAdmission::Standard,
        support,
        pcurve,
    )
    .transpose()
}

/// Decode a form-2 `par_int_cur` scope into the curve it denotes. Token-space
/// counterpart of [`decode_par_int_cur_isoline`].
pub(super) fn par_int_cur_isoline(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    scope: &[Token],
    reference_context: Option<&SubtypeTable>,
) -> Option<Result<NurbsCurve, cadmpeg_core::CodecError>> {
    let (start, _) =
        crate::nurbs::toks::find_owned_subtype_marker(scope, &["par_int_cur", "parcur"])?;
    let mut cur = Cur::at(scope, start + 2);
    (cur.take_long()? > 0).then_some(())?;
    (cur.take_enum()? == 2).then_some(())?;
    cur.take_range_value()?;
    cur.take_range_value()?;
    cur.take_enum()?;
    let supports = [
        propagate_resource!(optional_rolling_ball_surface(
            ctx,
            &mut cur,
            reference_context
        )?)
        .value()
        .map(|(support, _)| support.surface),
        propagate_resource!(optional_rolling_ball_surface(
            ctx,
            &mut cur,
            reference_context
        )?)
        .value()
        .map(|(support, _)| support.surface),
    ];
    let pcurves = [
        nullable_embedded_pcurve(&mut cur)?.value(),
        nullable_embedded_pcurve(&mut cur)?.value(),
    ];
    // The support-slot selector puts the parametric support and its parameter
    // curve in the same slot and nulls the other; a support without its pcurve,
    // or two occupied slots, is not this construction.
    let occupied: Vec<usize> = (0..2)
        .filter(|slot| supports[*slot].is_some() || pcurves[*slot].is_some())
        .collect();
    let [slot] = occupied.as_slice() else {
        return None;
    };
    let (Some(SurfaceGeometry::Solved(SolvedSurfaceGeometry::Nurbs(support))), Some(pcurve)) =
        (&supports[*slot], &pcurves[*slot])
    else {
        return None;
    };
    surface_isoline_along(ctx.into(), support, pcurve)
        .transpose()
        .map(|result| result.map_err(Into::into))
}

/// The support isoline a uv pcurve selects, or `None` when the pcurve is not an
/// isoline of the support's full domain.
fn surface_isoline_along(
    admission: cadmpeg_ir::eval::admission::EvaluationAdmission<'_, '_>,
    support: &cadmpeg_ir::geometry::nurbs::NurbsSurface,
    pcurve: &PcurveNurbs,
) -> Result<Option<NurbsCurve>, cadmpeg_core::decode::ResourceLimit> {
    use cadmpeg_ir::eval::IsolineDirection;
    let Some((direction, at)) = (|| {
        let poles = pcurve.pole_rows();
        (pcurve.degree() == 1 && poles.count() == 2 && poles.weight_at(0).is_none())
            .then_some(())?;
        let start = poles.point_at(0)?.get();
        let end = poles.point_at(1)?.get();
        let domain = [*pcurve.knots().first()?, *pcurve.knots().last()?];
        let u_domain = [*support.u_knots().first()?, *support.u_knots().last()?];
        let v_domain = [*support.v_knots().first()?, *support.v_knots().last()?];
        let (direction, at, free_domain, travel) = if agree(start.u, end.u, width(u_domain)) {
            (
                IsolineDirection::ConstantU,
                start.u,
                v_domain,
                [start.v, end.v],
            )
        } else if agree(start.v, end.v, width(v_domain)) {
            (
                IsolineDirection::ConstantV,
                start.v,
                u_domain,
                [start.u, end.u],
            )
        } else {
            return None;
        };
        // The pcurve's free coordinate must be the support parameter itself, and
        // must run the support's whole domain: anything shorter is a trim, which the
        // support's own knot vector cannot express.
        let scale = width(free_domain);
        (agree(travel[0], domain[0], scale)
            && agree(travel[1], domain[1], scale)
            && agree(free_domain[0], domain[0], scale)
            && agree(free_domain[1], domain[1], scale))
        .then_some(())?;
        Some((direction, at))
    })() else {
        return Ok(None);
    };
    cadmpeg_ir::eval::nurbs_surface_isoline(admission, support, direction, at)
}

/// Span of a parameter domain.
fn width(domain: [f64; 2]) -> f64 {
    (domain[1] - domain[0]).abs()
}

/// Two parameters name the same value at `scale`'s representable precision.
fn agree(left: f64, right: f64, scale: f64) -> bool {
    (left - right).abs() <= EPS_PARAMETER_AGREEMENT * scale
}

/// Shared cache-first intcurve context: revision, enum zero, solved cache and
/// fit tolerance, two bounded supports, two nullable pcurves, two optional
/// solved-interval endpoints, three discontinuity arrays, and one extension.
pub struct CacheFirstCurveContext {
    pub(super) form: cadmpeg_ir::geometry::CacheFirstCurveForm,
    pub(super) surfaces: [SupportSlot; 2],
    pub(super) pcurves: [Option<PcurveNurbs>; 2],
    discontinuities: [Vec<f64>; 3],
}

impl CacheFirstCurveContext {
    pub(crate) fn into_intersection(
        self,
        domain: [f64; 2],
    ) -> (
        EmbeddedIntersection,
        cadmpeg_ir::geometry::CacheFirstCurveForm,
    ) {
        let parameter_range =
            std::array::from_fn(|index| self.form.solved_range[index].unwrap_or(domain[index]));
        (
            EmbeddedIntersection {
                surfaces: self.surfaces,
                pcurves: self.pcurves,
                parameter_range,
                discontinuities: self.discontinuities,
            },
            self.form,
        )
    }
}

fn cache_first_curve_context(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    cur: &mut Cur<'_>,
    table: &SubtypeTable,
) -> Option<Result<CacheFirstCurveContext, cadmpeg_core::CodecError>> {
    let revision = PositiveI64::new(cur.take_long()?)?;
    // The leading enum selects the approximation-cache form. `0` stores the
    // solved curve cache and its fit tolerance; `2` stores neither and instead
    // stores a bool-gated curve interval and a closed-form enum. No other value
    // has a defined grammar, so it fails and the containing record is retained
    // verbatim.
    let cache_enum = cur.take_enum()?;
    let cache = match cache_enum {
        0 => {
            let (_, end) = curve_block(cur.toks(), cur.pos())?;
            cur.set_pos(end);
            cadmpeg_ir::geometry::RevisionCacheForm::SolvedCache {
                fit_tolerance: cadmpeg_ir::geometry::FitTolerance::try_new(
                    cur.take_f64()? * LEN_TO_MM,
                )
                .ok()?,
            }
        }
        2 => cadmpeg_ir::geometry::RevisionCacheForm::Parameterization(
            cadmpeg_ir::geometry::CacheFirstCurveParameterization {
                interval: [
                    cur.take_optional_range_value()?.value(),
                    cur.take_optional_range_value()?.value(),
                ],
                closed_form: cur.take_enum()?,
            },
        ),
        _ => return None,
    };
    let EmbeddedSurfaceWithBounds {
        surface: first_surface,
        chart: first_chart,
        bounds: first_bounds,
    } = match optional_embedded_surface_with_bounds(ctx, cur, table)? {
        Ok(surface) => surface,
        Err(error) => return Some(Err(error)),
    };
    let EmbeddedSurfaceWithBounds {
        surface: second_surface,
        chart: second_chart,
        bounds: second_bounds,
    } = match optional_embedded_surface_with_bounds(ctx, cur, table)? {
        Ok(surface) => surface,
        Err(error) => return Some(Err(error)),
    };
    let mut pcurves = [
        nullable_embedded_pcurve(cur)?.value(),
        nullable_embedded_pcurve(cur)?.value(),
    ];
    for (pcurve, chart) in pcurves.iter_mut().zip([first_chart, second_chart]) {
        if let Some(pcurve) = pcurve {
            chart.normalize(pcurve)?;
        }
    }
    let solved_range = [
        cur.take_optional_range_value()?.value(),
        cur.take_optional_range_value()?.value(),
    ];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let extension = cur.take_long()?;
    Some(Ok(CacheFirstCurveContext {
        form: cadmpeg_ir::geometry::CacheFirstCurveForm {
            revision,
            cache,
            support_bounds: [first_bounds, second_bounds],
            solved_range,
            extension,
        },
        surfaces: [first_surface, second_surface],
        pcurves,
        discontinuities,
    }))
}

fn context_first_surface_curve(
    toks: &[Token],
    position: usize,
    family: cadmpeg_ir::geometry::SurfaceCurveFamilyKind,
) -> Option<EmbeddedSurfaceCurve> {
    let mut cur = Cur::at(toks, position);
    let RequiredSupportPair { surfaces, pcurves } = required_support_pair(&mut cur)?;
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    embedded_surface_curve_from_parts(
        family,
        EmbeddedSurfaceCurveLayout::ContextFirst(EmbeddedIntersection {
            surfaces: surfaces.map(SupportSlot::Surface),
            pcurves: pcurves.map(Some),
            parameter_range,
            discontinuities,
        }),
    )
}

fn cache_first_surface_curve(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    position: usize,
    family: cadmpeg_ir::geometry::SurfaceCurveFamilyKind,
    table: &SubtypeTable,
) -> Option<Result<EmbeddedSurfaceCurve, cadmpeg_core::CodecError>> {
    let mut cur = Cur::at(toks, position);
    let context = match cache_first_curve_context(ctx, &mut cur, table)? {
        Ok(context) => context,
        Err(error) => return Some(Err(error)),
    };
    let flag = cur.take_bool()?;
    let second_flag = matches!(cur.peek(), Some(Token::True | Token::False))
        .then(|| cur.take_bool())
        .flatten();
    embedded_surface_curve_from_parts(
        family,
        EmbeddedSurfaceCurveLayout::CacheFirst {
            context,
            flags: (flag, second_flag),
        },
    )
    .map(Ok)
}

fn embedded_surface_curve_from_parts(
    family: cadmpeg_ir::geometry::SurfaceCurveFamilyKind,
    layout: EmbeddedSurfaceCurveLayout<(bool, Option<bool>)>,
) -> Option<EmbeddedSurfaceCurve> {
    use cadmpeg_ir::geometry::{ParametricSurfaceCurveFlags, SurfaceCurveFamilyKind};
    let single = |(flag, second): (bool, Option<bool>)| second.is_none().then_some(flag);
    Some(match family {
        SurfaceCurveFamilyKind::Blend => EmbeddedSurfaceCurve::Blend(layout.try_map_flags(single)?),
        SurfaceCurveFamilyKind::SurfaceConstrained => {
            EmbeddedSurfaceCurve::SurfaceConstrained(layout.try_map_flags(single)?)
        }
        SurfaceCurveFamilyKind::Parametric => {
            EmbeddedSurfaceCurve::Parametric(layout.try_map_flags(|(flag, second_flag)| {
                Some(ParametricSurfaceCurveFlags { flag, second_flag })
            })?)
        }
        SurfaceCurveFamilyKind::Skin => EmbeddedSurfaceCurve::Skin(layout.try_map_flags(single)?),
    })
}

/// Writable shared-context fields in a surface-related `intcurve` subtype.
pub struct SurfaceCurvePatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
}

/// Locate a surface-curve context by walking its two ordered support pairs.
pub fn surface_curve_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
    family: cadmpeg_ir::geometry::SurfaceCurveFamilyKind,
) -> Option<SurfaceCurvePatchLayout> {
    use cadmpeg_ir::geometry::SurfaceCurveFamilyKind;
    let names: &[&[u8]] = match family {
        SurfaceCurveFamilyKind::Blend => &[b"blend_int_cur", b"bldcur"],
        SurfaceCurveFamilyKind::SurfaceConstrained => &[b"surf_int_cur", b"surfcur"],
        SurfaceCurveFamilyKind::Parametric => &[b"par_int_cur", b"parcur"],
        SurfaceCurveFamilyKind::Skin => &[b"skin_int_cur", b"d5c2_cur"],
    };
    let (marker, name) = find_owned_subtype_marker(bytes, names, int_width)?;
    let mut position = marker + name.len() + 3;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    Some(SurfaceCurvePatchLayout {
        parameter_range,
        discontinuities,
    })
}

fn embedded_three_surface_intersection(toks: &[Token]) -> Option<EmbeddedThreeSurfaceIntersection> {
    let (marker, _) = crate::nurbs::toks::find_owned_subtype_marker(toks, &["sss_int_cur"])?;
    let mut cur = Cur::at(toks, marker + 2);
    let RequiredSupportPair {
        surfaces: [first, second],
        pcurves: [first_pcurve, second_pcurve],
    } = required_support_pair(&mut cur)?;
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let selector = cur.take_long()?;
    let third = embedded_support(&mut cur)?;
    let (mut third_pcurve, _) = pcurve_block_with_end(toks, cur.pos())?;
    third.chart.normalize(&mut third_pcurve)?;
    Some(EmbeddedThreeSurfaceIntersection {
        surfaces: [first, second, third.surface],
        pcurves: [first_pcurve, second_pcurve, third_pcurve],
        parameter_range,
        discontinuities,
        selector,
    })
}

/// Writable context fields in an `sss_int_cur` subtype.
pub struct ThreeSurfacePatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
    /// Byte offset of the selector integer.
    pub selector: usize,
}

/// Locate three-surface intersection fields by walking all three support pairs.
pub fn three_surface_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
) -> Option<ThreeSurfacePatchLayout> {
    let (marker, name_len) = find_owned_intcurve_subtype(bytes, b"sss_int_cur", int_width)?;
    let mut position = marker + name_len + 3;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    let selector = position;
    take_tagged_int(bytes, &mut position, 0x04, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_pcurve_block_with_end(bytes, position, int_width)?;
    Some(ThreeSurfacePatchLayout {
        parameter_range,
        discontinuities,
        selector,
    })
}

fn embedded_projection(toks: &[Token]) -> Option<EmbeddedProjection> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "proj_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    let RequiredSupportPair { surfaces, pcurves } = required_support_pair(&mut cur)?;
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let discontinuity_flag = cur.take_bool()?;
    let (source, source_end) = curve_block(toks, cur.pos())?;
    cur.set_pos(source_end);
    let flag = cur.take_bool()?;
    let tail = if matches!(cur.peek(), Some(Token::SubtypeClose)) {
        cadmpeg_ir::geometry::ProjectionTail::EarlyClose { flag }
    } else {
        cadmpeg_ir::geometry::ProjectionTail::Ranged {
            flag,
            parameter_range: [cur.take_range_value()?, cur.take_range_value()?],
            role: cadmpeg_ir::geometry::ProjectionRole::parse(cur.take_str()?)?,
        }
    };
    Some(EmbeddedProjection {
        surfaces,
        pcurves,
        parameter_range,
        discontinuities,
        discontinuity_flag,
        source,
        tail,
    })
}

/// A parsed five-byte projection role slot.
pub struct ProjectionRoleSlot(usize);

impl ProjectionRoleSlot {
    fn parse(bytes: &[u8], position: usize) -> Option<Self> {
        let encoded = bytes.get(position..position.checked_add(7)?)?;
        matches!(encoded, b"\x07\x05surf1" | b"\x07\x05surf2").then_some(Self(position + 2))
    }

    /// Byte range of the fixed-width role payload.
    pub fn range(&self) -> std::ops::Range<usize> {
        self.0..self.0 + 5
    }

    /// Write a projection role into its five-byte payload.
    pub fn write(
        &self,
        bytes: &mut [u8],
        role: cadmpeg_ir::geometry::ProjectionRole,
    ) -> Result<(), cadmpeg_core::CodecError> {
        let payload: &[u8; 5] = match role {
            cadmpeg_ir::geometry::ProjectionRole::Surf1 => b"surf1",
            cadmpeg_ir::geometry::ProjectionRole::Surf2 => b"surf2",
        };
        let target = bytes.get_mut(self.range()).ok_or_else(|| {
            cadmpeg_core::CodecError::Malformed("projection role payload is truncated".into())
        })?;
        target.copy_from_slice(payload);
        Ok(())
    }
}

/// Writable tail shape of a `proj_int_cur` subtype.
pub enum ProjectionTailPatchLayout {
    /// The tail closes directly after the flag.
    EarlyClose {
        /// Byte offset of the tail flag boolean.
        flag: usize,
    },
    /// The tail carries a parameter range and a role identifier.
    Ranged {
        /// Byte offset of the tail flag boolean.
        flag: usize,
        /// Byte offsets of the two tail parameter-range doubles.
        parameter_range: [usize; 2],
        /// Byte range of the role identifier payload.
        role: ProjectionRoleSlot,
    },
}

/// Writable shared-context and tail fields in a `proj_int_cur` subtype.
pub struct ProjectionPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
    /// Byte offset of the boolean after the discontinuity arrays.
    pub discontinuity_flag: usize,
    /// Writable tail shape.
    pub tail: ProjectionTailPatchLayout,
}

/// Locate projection fields by walking supports, source curve, and selected tail.
pub fn projection_patch_layout(bytes: &[u8], int_width: RefWidth) -> Option<ProjectionPatchLayout> {
    let (marker, name_len) = find_owned_intcurve_subtype(bytes, b"proj_int_cur", int_width)?;
    let mut position = marker + name_len + 3;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    let discontinuity_flag = position;
    take_bool(bytes, &mut position)?;
    position = decode_curve_block(bytes, position, int_width)?.end();
    let tail_flag = position;
    take_bool(bytes, &mut position)?;
    let tail = if bytes.get(position) == Some(&0x10) {
        ProjectionTailPatchLayout::EarlyClose { flag: tail_flag }
    } else {
        let parameter_range = [
            take_double_payload(bytes, &mut position)?,
            take_double_payload(bytes, &mut position)?,
        ];
        let role = ProjectionRoleSlot::parse(bytes, position)?;
        ProjectionTailPatchLayout::Ranged {
            flag: tail_flag,
            parameter_range,
            role,
        }
    };
    Some(ProjectionPatchLayout {
        parameter_range,
        discontinuities,
        discontinuity_flag,
        tail,
    })
}

fn embedded_intersection(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    solved: &NurbsCurve,
    table: &SubtypeTable,
) -> Option<Result<(EmbeddedIntersection, bool), cadmpeg_core::CodecError>> {
    let names = ["int_int_cur", "surf_surf_int_cur", "surfintcur"];
    let (marker, _) = crate::nurbs::toks::find_owned_subtype_marker(toks, &names)?;
    let position = marker + 2;
    context_first_intersection(toks, position)
        .map(Ok)
        .or_else(|| cache_first_intersection(ctx, toks, position, solved, table))
}

fn context_first_intersection(
    toks: &[Token],
    position: usize,
) -> Option<(EmbeddedIntersection, bool)> {
    let mut cur = Cur::at(toks, position);
    let RequiredSupportPair { surfaces, pcurves } = required_support_pair(&mut cur)?;
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let discontinuity_flag = cur.take_bool()?;
    Some((
        EmbeddedIntersection {
            surfaces: surfaces.map(SupportSlot::Surface),
            pcurves: pcurves.map(Some),
            parameter_range,
            discontinuities,
        },
        discontinuity_flag,
    ))
}

fn cache_first_intersection(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    position: usize,
    solved: &NurbsCurve,
    table: &SubtypeTable,
) -> Option<Result<(EmbeddedIntersection, bool), cadmpeg_core::CodecError>> {
    let mut cur = Cur::at(toks, position);
    (cur.take_long()? > 0).then_some(())?;
    (cur.take_enum()? == 0).then_some(())?;
    let (_, cache_end) = curve_block(toks, cur.pos())?;
    cur.set_pos(cache_end);
    cur.take_f64()?;
    let first = match optional_embedded_surface_with_bounds(ctx, &mut cur, table)? {
        Ok(surface) => surface,
        Err(error) => return Some(Err(error)),
    };
    let second = match optional_embedded_surface_with_bounds(ctx, &mut cur, table)? {
        Ok(surface) => surface,
        Err(error) => return Some(Err(error)),
    };
    let mut pcurves = [
        nullable_embedded_pcurve(&mut cur)?.value(),
        nullable_embedded_pcurve(&mut cur)?.value(),
    ];
    for (pcurve, chart) in pcurves.iter_mut().zip([first.chart, second.chart]) {
        if let Some(pcurve) = pcurve {
            chart.normalize(pcurve)?;
        }
    }
    let surfaces = [first.surface, second.surface];
    let domain = nurbs_curve_parameter_domain(solved)?;
    let parameter_range = [
        cur.take_optional_range_value()?
            .value()
            .unwrap_or(domain[0]),
        cur.take_optional_range_value()?
            .value()
            .unwrap_or(domain[1]),
    ];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let discontinuity_flag = cur.take_long()? != 0;
    Some(Ok((
        EmbeddedIntersection {
            surfaces,
            pcurves,
            parameter_range,
            discontinuities,
        },
        discontinuity_flag,
    )))
}

/// Writable shared-context fields in an `int_int_cur` subtype.
pub struct IntersectionPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
    /// Byte offset of the boolean after the discontinuity arrays.
    pub discontinuity_flag: usize,
}

/// Locate an intersection context by walking both ordered support pairs.
pub fn intersection_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
) -> Option<IntersectionPatchLayout> {
    let names: [&[u8]; 3] = [b"int_int_cur", b"surf_surf_int_cur", b"surfintcur"];
    let (marker, name) = find_owned_subtype_marker(bytes, &names, int_width)?;
    let mut position = marker + name.len() + 3;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    decode_embedded_surface(bytes, &mut position, int_width)?;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    position = decode_pcurve_block_with_end(bytes, position, int_width)?.1;
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    let discontinuity_flag = position;
    take_bool(bytes, &mut position)?;
    Some(IntersectionPatchLayout {
        parameter_range,
        discontinuities,
        discontinuity_flag,
    })
}

fn embedded_two_sided_offset(toks: &[Token]) -> Option<EmbeddedTwoSidedOffset> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "off_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    let supports = [
        optional_embedded_surface(&mut cur)?.value(),
        optional_embedded_surface(&mut cur)?.value(),
    ];
    let first_pcurve = optional_pcurve(&mut cur)?.value();
    let second_pcurve = optional_pcurve(&mut cur)?.value();
    let mut pcurves = [first_pcurve, second_pcurve];
    for (pcurve, support) in pcurves.iter_mut().zip(&supports) {
        if let (Some(pcurve), Some(support)) = (pcurve, support) {
            support.chart.normalize(pcurve)?;
        }
    }
    let surfaces = supports.map(|support| support.map(|support| support.surface));
    let parameter_range = [cur.take_range_value()?, cur.take_range_value()?];
    let discontinuities = [
        cur.take_float_array()?,
        cur.take_float_array()?,
        cur.take_float_array()?,
    ];
    let discontinuity_flag = cur.take_bool()?;
    let offsets = [
        cur.take_range_value()? * LEN_TO_MM,
        cur.take_range_value()? * LEN_TO_MM,
    ];
    Some(EmbeddedTwoSidedOffset {
        surfaces,
        pcurves,
        parameter_range,
        discontinuities,
        discontinuity_flag,
        offsets,
    })
}

fn optional_embedded_surface(cur: &mut Cur<'_>) -> Option<Nullable<EmbeddedSupport>> {
    let start = cur.pos();
    if cur.take_ident()? == "null_surface" {
        return Some(Nullable::Null);
    }
    cur.set_pos(start);
    embedded_support(cur).map(Nullable::Value)
}

fn optional_pcurve(cur: &mut Cur<'_>) -> Option<Nullable<PcurveNurbs>> {
    let start = cur.pos();
    if cur.take_ident()? == "nullbs" {
        return Some(Nullable::Null);
    }
    let (pcurve, end) = pcurve_block_with_end(cur.toks(), start)?;
    cur.set_pos(end);
    Some(Nullable::Value(pcurve))
}

/// Writable scalar locations in a retained `off_int_cur` construction.
pub struct TwoSidedOffsetPatchLayout {
    /// Byte offsets of the two parameter-range doubles.
    pub parameter_range: [usize; 2],
    /// Byte offsets of the values in each discontinuity array.
    pub discontinuities: [Vec<usize>; 3],
    /// Byte offset of the boolean after the discontinuity arrays.
    pub discontinuity_flag: usize,
    /// Byte offsets of the two side-offset doubles.
    pub offsets: [usize; 2],
}

/// Locates the fixed-width scalar payloads after variable embedded supports.
pub fn two_sided_offset_patch_layout(
    bytes: &[u8],
    int_width: RefWidth,
) -> Option<TwoSidedOffsetPatchLayout> {
    let name = b"off_int_cur";
    let (marker, name_len) = find_owned_intcurve_subtype(bytes, name, int_width)?;
    let mut position = marker + name_len + 3;
    skip_offset_support_surface(bytes, &mut position, int_width)?;
    skip_offset_support_surface(bytes, &mut position, int_width)?;
    skip_offset_support_pcurve(bytes, &mut position, int_width)?;
    skip_offset_support_pcurve(bytes, &mut position, int_width)?;
    let parameter_range = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    let discontinuities = [
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
        take_float_array_payloads(bytes, &mut position, int_width)?,
    ];
    let discontinuity_flag = position;
    take_bool(bytes, &mut position)?;
    let offsets = [
        take_double_payload(bytes, &mut position)?,
        take_double_payload(bytes, &mut position)?,
    ];
    Some(TwoSidedOffsetPatchLayout {
        parameter_range,
        discontinuities,
        discontinuity_flag,
        offsets,
    })
}

fn skip_offset_support_surface(
    bytes: &[u8],
    position: &mut usize,
    int_width: RefWidth,
) -> Option<()> {
    let start = *position;
    if take_native_ident(bytes, position)?.as_str() == "null_surface" {
        return Some(());
    }
    *position = start;
    decode_embedded_surface(bytes, position, int_width)?;
    Some(())
}

fn skip_offset_support_pcurve(
    bytes: &[u8],
    position: &mut usize,
    int_width: RefWidth,
) -> Option<()> {
    let start = *position;
    if take_native_ident(bytes, position)?.as_str() == "nullbs" {
        return Some(());
    }
    *position = decode_pcurve_block_with_end(bytes, start, int_width)?.1;
    Some(())
}

fn decode_embedded_surface(
    bytes: &[u8],
    position: &mut usize,
    int_width: RefWidth,
) -> Option<SurfaceGeometry> {
    decode_embedded_surface_fields(bytes, position, int_width, false).map(|support| support.surface)
}

/// Decode one embedded analytic or spline support surface.
pub(super) fn embedded_surface(cur: &mut Cur<'_>) -> Option<SurfaceGeometry> {
    embedded_surface_fields(cur, false).map(|value| value.surface)
}

/// An embedded support surface, the native chart of the pcurves on it, and
/// its four trailing U/V range fields.
pub(super) struct EmbeddedSupport {
    pub(super) surface: SurfaceGeometry,
    pub(super) chart: SupportChart,
    pub(super) ranges: [[Option<f64>; 2]; 2],
}

/// [`embedded_surface`] with the native chart of its pcurves. The range
/// fields are not preserved.
pub(super) fn embedded_support(cur: &mut Cur<'_>) -> Option<EmbeddedSupport> {
    embedded_surface_fields(cur, false)
}

/// [`embedded_support`], preserving the four trailing U/V range fields.
pub(super) fn embedded_surface_with_ranges(cur: &mut Cur<'_>) -> Option<EmbeddedSupport> {
    embedded_surface_fields(cur, true)
}

fn admitted_placement(
    point: Point3,
    axis: UnitVector3,
    reference: UnitVector3,
) -> Option<(FinitePoint3, OrthonormalFrame3)> {
    let frame = OrthonormalFrame3::from_units(axis, reference)?;
    let point = FinitePoint3::new(point)?;
    Some((point, frame))
}

/// Skip one cone interval bound: `TRUE` and a `DOUBLE`, or a bare `FALSE`.
fn skip_cone_bound(cur: &mut Cur<'_>) -> Option<()> {
    if cur.take_bool()? {
        cur.take_f64()?;
    }
    Some(())
}

/// Decode the fields of an analytic support `kind` from its origin through its
/// sense logical into the neutral surface and the native chart of the pcurves
/// on it ([spec §6.2](https://github.com/cadmpeg/cadmpeg/blob/main/docs/formats/asm.md#62-analytic-surface-byte-layouts)).
/// The four trailing parameter bounds are not read.
pub(crate) fn analytic_support(
    kind: &str,
    cur: &mut Cur<'_>,
) -> Option<(SurfaceGeometry, SupportChart)> {
    let point = cur.take_position()?;
    let point = Point3::new(
        point[0] * LEN_TO_MM,
        point[1] * LEN_TO_MM,
        point[2] * LEN_TO_MM,
    );
    match kind {
        "plane" => {
            let normal = normalized(cur.take_vector3()?)?;
            let u_axis = normalized(cur.take_vector3()?)?;
            let chart = SupportChart::plane(cur.take_bool()?);
            let (origin, frame) = admitted_placement(point, normal, u_axis)?;
            Some((
                SurfaceGeometry::Solved(SolvedSurfaceGeometry::Plane(PlaneSurface::new(
                    origin, frame,
                ))),
                chart,
            ))
        }
        "cone" => {
            let native_axis = normalized(cur.take_vector3()?)?;
            let major = cur.take_vector3()?;
            let radius = major[0].hypot(major[1]).hypot(major[2]) * LEN_TO_MM;
            let ref_direction = normalized(major)?;
            let ratio = cur.take_f64()?;
            skip_cone_bound(cur)?;
            skip_cone_bound(cur)?;
            let sine = cur.take_f64()?;
            let cosine = cur.take_f64()?;
            let u_scale = cur.take_f64()?;
            let chart = SupportChart::cone(sine, cosine, ratio, u_scale, cur.take_bool()?)?;
            let surface = if cone_is_circular_cylinder(sine, ratio) {
                let (origin, frame) = admitted_placement(point, native_axis, ref_direction)?;
                SurfaceGeometry::Solved(SolvedSurfaceGeometry::Cylinder(CylinderSurface::new(
                    origin,
                    frame,
                    PositiveLength::new(radius)?,
                )))
            } else {
                let axis = if cone_axis_reversed(sine, cosine, ratio) {
                    native_axis.negated()
                } else {
                    native_axis
                };
                let (origin, frame) = admitted_placement(point, axis, ref_direction)?;
                SurfaceGeometry::Solved(SolvedSurfaceGeometry::Cone(ConeSurface::new(
                    origin,
                    frame,
                    NonNegativeLength::new(radius)?,
                    PositiveReal::new(ratio)?,
                    Angle::new(sine.abs().atan2(cosine.abs()))?,
                )))
            };
            Some((surface, chart))
        }
        "sphere" => {
            let radius = cur.take_f64()? * LEN_TO_MM;
            let ref_direction = normalized(cur.take_vector3()?)?;
            let axis = normalized(cur.take_vector3()?)?;
            let chart = SupportChart::sphere(cur.take_bool()?);
            let (center, frame) = admitted_placement(point, axis, ref_direction)?;
            Some((
                SurfaceGeometry::Solved(SolvedSurfaceGeometry::Sphere(SphereSurface::new(
                    center,
                    frame,
                    NonZeroLength::new(radius)?,
                ))),
                chart,
            ))
        }
        "torus" => {
            let axis = normalized(cur.take_vector3()?)?;
            let major_radius = cur.take_f64()? * LEN_TO_MM;
            let minor_radius = cur.take_f64()? * LEN_TO_MM;
            let ref_direction = normalized(cur.take_vector3()?)?;
            let chart = SupportChart::torus(major_radius, cur.take_bool()?);
            let (center, frame) = admitted_placement(point, axis, ref_direction)?;
            Some((
                SurfaceGeometry::Solved(SolvedSurfaceGeometry::Torus(TorusSurface::new(
                    center,
                    frame,
                    PositiveLength::new(major_radius.abs())?,
                    NonZeroLength::new(minor_radius)?,
                ))),
                chart,
            ))
        }
        _ => None,
    }
}

fn embedded_surface_fields(cur: &mut Cur<'_>, preserve_ranges: bool) -> Option<EmbeddedSupport> {
    let no_ranges = [[None, None], [None, None]];
    let kind = cur.take_ident()?;
    if kind == "spline" {
        let (decoded, end) = surface_block(cur.toks(), cur.pos())?;
        cur.set_pos(end);
        let ranges = if preserve_ranges {
            surface_ranges(cur)?
        } else {
            no_ranges
        };
        return Some(EmbeddedSupport {
            surface: SurfaceGeometry::Solved(SolvedSurfaceGeometry::Nurbs(decoded)),
            chart: SupportChart::Canonical,
            ranges,
        });
    }
    let (surface, chart) = analytic_support(kind, cur)?;
    let ranges = if preserve_ranges {
        surface_ranges(cur)?
    } else {
        // A plane leaves its bounds to the caller; the other carriers
        // consume four absent bounds.
        if kind != "plane" {
            for _ in 0..4 {
                cur.take_bool()?;
            }
        }
        no_ranges
    };
    Some(EmbeddedSupport {
        surface,
        chart,
        ranges,
    })
}

/// [`embedded_surface_with_ranges`] over the bytes at `position`, advanced
/// past the support.
pub(super) fn decode_embedded_surface_with_ranges(
    bytes: &[u8],
    position: &mut usize,
    int_width: RefWidth,
) -> Option<(SurfaceGeometry, [[Option<f64>; 2]; 2])> {
    decode_embedded_surface_fields(bytes, position, int_width, true)
        .map(|support| (support.surface, support.ranges))
}

/// Lex the payload at `position` and read one embedded support with the token
/// grammar of [`embedded_surface_fields`], advancing `position` past it.
fn decode_embedded_surface_fields(
    bytes: &[u8],
    position: &mut usize,
    int_width: RefWidth,
    preserve_ranges: bool,
) -> Option<EmbeddedSupport> {
    let (tokens, offsets) = crate::sab::lex_payload(bytes, *position, int_width);
    let mut cur = Cur::at(&tokens, 0);
    let support = embedded_surface_fields(&mut cur, preserve_ranges)?;
    *position = *offsets.get(cur.pos())?;
    Some(support)
}

/// Native support presence, standalone geometry, the native chart of the
/// pcurves on it, and four optional U/V bounds.
pub(super) struct EmbeddedSurfaceWithBounds {
    pub(super) surface: SupportSlot,
    pub(super) chart: SupportChart,
    pub(super) bounds: [Option<f64>; 4],
}

/// Parse an optional embedded support surface and its U/V bounds.
pub(super) fn optional_embedded_surface_with_bounds(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    cur: &mut Cur<'_>,
    table: &SubtypeTable,
) -> Option<Result<EmbeddedSurfaceWithBounds, cadmpeg_core::CodecError>> {
    let toks = cur.toks();
    let saved = cur.pos();
    let kind = cur.take_ident();
    if kind == Some("null_surface") {
        return Some(Ok(EmbeddedSurfaceWithBounds {
            surface: SupportSlot::Absent,
            chart: SupportChart::Canonical,
            bounds: [None; 4],
        }));
    }
    if kind == Some("spline") {
        if matches!(cur.peek(), Some(Token::True | Token::False)) {
            cur.take_bool()?;
        }
        if let Some(scope) = crate::nurbs::toks::subtype_span(toks, cur.pos()) {
            let reference = match scope.interior() {
                [Token::Ident(name), Token::Long(index), ..] if name == "ref" => {
                    Some(usize::try_from(*index).ok()?)
                }
                _ => None,
            };
            let target = match reference {
                Some(index) => table.span(index),
                None => Some(scope),
            };
            let surface = if let Some(target) = target {
                if let Some(surface) = owned_surface_cache_resolving_refs(ctx, target, table) {
                    SupportSlot::Surface(SurfaceGeometry::Solved(SolvedSurfaceGeometry::Nurbs(
                        propagate_resource!(surface),
                    )))
                } else if propagate_resource!(
                    crate::nurbs::proc_surface::procedural_surface_resolving_refs(
                        ctx,
                        target.tokens(),
                        table,
                    )
                    .transpose()
                )
                .is_some()
                {
                    SupportSlot::DeclaredOnly
                } else if reference.is_some() {
                    SupportSlot::Absent
                } else {
                    return None;
                }
            } else {
                SupportSlot::Absent
            };
            cur.set_pos(cur.pos() + scope.tokens().len());
            let mut bounds = [None; 4];
            for bound in &mut bounds {
                *bound = cur.take_optional_range_value()?.value();
            }
            return Some(Ok(EmbeddedSurfaceWithBounds {
                surface,
                chart: SupportChart::Canonical,
                bounds,
            }));
        }
    }
    cur.set_pos(saved);
    let EmbeddedSupport { surface, chart, .. } = embedded_support(cur)?;
    let mut bounds = [None; 4];
    if kind == Some("plane") || kind == Some("spline") {
        for bound in &mut bounds {
            *bound = cur.take_optional_range_value()?.value();
        }
    }
    Some(Ok(EmbeddedSurfaceWithBounds {
        surface: SupportSlot::Surface(surface),
        chart,
        bounds,
    }))
}

fn compound_definition(toks: &[Token]) -> Option<CompoundDefinition> {
    let (marker, _) = crate::nurbs::toks::find_owned_subtype_marker(toks, &["comp_int_cur"])?;
    let mut cur = Cur::at(toks, marker + 2);
    let parameters = cur.take_float_array()?;
    let count = usize::try_from(cur.take_long()?).ok()?;
    if count == 0 {
        return None;
    }
    let mut component_parameters = Vec::new();
    for _ in 0..count {
        component_parameters.push(cur.take_f64()?);
    }
    if !matches!(cur.peek(), Some(Token::True | Token::False)) {
        return None;
    }
    cur.bump();
    let mut components = Vec::new();
    for parameter in component_parameters {
        let (curve, end) = curve_block(toks, cur.pos())?;
        components.push(cadmpeg_ir::geometry::CompoundComponent {
            parameter,
            component: curve,
        });
        cur.set_pos(end);
    }
    Some(CompoundDefinition {
        parameters,
        components,
    })
}

fn subset_definition(toks: &[Token]) -> Option<SubsetDefinition> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "subset_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    let (source, source_end) = curve_block(toks, cur.pos())?;
    cur.set_pos(source_end);
    let range = [cur.take_range_value()?, cur.take_range_value()?];
    Some((source, range))
}

fn vector_offset_definition(toks: &[Token]) -> Option<VectorOffsetDefinition> {
    let marker = crate::nurbs::toks::find_owned_intcurve_subtype(toks, "offset_int_cur")?;
    let mut cur = Cur::at(toks, marker + 2);
    cur.take_bool()?;
    let (source, source_end) = curve_block(toks, cur.pos())?;
    cur.set_pos(source_end);
    if !matches!(toks.get(cur.pos()), Some(Token::Double(_)))
        || !matches!(toks.get(cur.pos() + 1), Some(Token::Double(_)))
    {
        return None;
    }
    let parameter_range = [cur.take_f64()?, cur.take_f64()?];
    let offset = cur.take_vector3()?;
    let first_label = cur.take_str()?;
    let first_code = cur.take_long()?;
    let second_label = cur.take_str()?;
    let second_code = cur.take_long()?;
    if first_label != "source" || second_label != "offset" {
        return None;
    }
    Some((
        source,
        parameter_range,
        Vector3::new(
            offset[0] * LEN_TO_MM,
            offset[1] * LEN_TO_MM,
            offset[2] * LEN_TO_MM,
        ),
        cadmpeg_ir::geometry::VectorOffsetRoles {
            source: first_code,
            offset: second_code,
        },
    ))
}

/// Decode the `helix_int_cur` construction fields. Token-space counterpart of
/// the byte helix walk retained by [`helix_patch_layout`].
pub(super) fn helix_definition(toks: &[Token]) -> Option<HelixDefinition> {
    let (marker, _) = crate::nurbs::toks::find_owned_subtype_marker(toks, &["helix_int_cur"])?;
    let mut cur = Cur::at(toks, marker + 2);
    let current_layout = optional_helix_revision(&mut cur)?;
    let lower = cur.take_range_value()?;
    let upper = cur.take_range_value()?;
    let center = cur.take_position()?;
    let take_frame_vector = |cur: &mut Cur<'_>| {
        if current_layout {
            cur.take_vector3()
        } else {
            cur.take_position()
        }
    };
    let major = take_frame_vector(&mut cur)?;
    let minor = take_frame_vector(&mut cur)?;
    let pitch = take_frame_vector(&mut cur)?;
    let apex_factor = cur.take_f64()?;
    let axis = cur.take_vector3()?;
    Some(HelixDefinition {
        angle_range: [lower, upper],
        center: Point3::new(
            center[0] * LEN_TO_MM,
            center[1] * LEN_TO_MM,
            center[2] * LEN_TO_MM,
        ),
        major: Vector3::new(
            major[0] * LEN_TO_MM,
            major[1] * LEN_TO_MM,
            major[2] * LEN_TO_MM,
        ),
        minor: Vector3::new(
            minor[0] * LEN_TO_MM,
            minor[1] * LEN_TO_MM,
            minor[2] * LEN_TO_MM,
        ),
        pitch: Vector3::new(
            pitch[0] * LEN_TO_MM,
            pitch[1] * LEN_TO_MM,
            pitch[2] * LEN_TO_MM,
        ),
        apex_factor,
        axis: Vector3::new(axis[0], axis[1], axis[2]),
    })
}

/// Consume the current helix subtype's ASM release word when present. The
/// earlier form begins directly with an optional range-bound flag or double.
fn take_optional_helix_revision(
    bytes: &[u8],
    position: &mut usize,
    int_width: RefWidth,
) -> Option<bool> {
    if bytes.get(*position) != Some(&0x04) {
        return Some(false);
    }
    let revision = take_tagged_int(bytes, position, 0x04, int_width)?;
    (20_000..=99_999).contains(&revision).then_some(true)
}

/// Consume the current helix subtype's ASM release word when present. The
/// earlier form begins directly with an optional range-bound flag or double.
/// Token-space counterpart of [`take_optional_helix_revision`].
pub(super) fn optional_helix_revision(cur: &mut Cur<'_>) -> Option<bool> {
    if !matches!(cur.peek(), Some(Token::Long(_))) {
        return Some(false);
    }
    let revision = cur.take_long()?;
    (20_000..=99_999).contains(&revision).then_some(true)
}

/// Four optional U/V parameter bounds following a surface record's first
/// top-level subtype scope, or `None` when the record stores no bound fields.
/// `toks` is the record's payload tokens.
pub fn record_trailing_surface_bounds(toks: &[Token]) -> Option<[Option<f64>; 4]> {
    // Walk the fixed spline-record header: any leading payload identifiers,
    // attrib ref, history int, geometry ref, sense boolean, then the subtype
    // scope.
    let mut position = 0usize;
    while toks.get(position).is_some_and(Token::is_payload_ident) {
        position += 1;
    }
    if !matches!(toks.get(position), Some(Token::Ref(_))) {
        return None;
    }
    position += 1;
    if !matches!(toks.get(position), Some(Token::Long(_))) {
        return None;
    }
    position += 1;
    if !matches!(toks.get(position), Some(Token::Ref(_))) {
        return None;
    }
    position += 1;
    if !matches!(toks.get(position), Some(Token::True | Token::False)) {
        return None;
    }
    position += 1;
    if !matches!(toks.get(position), Some(Token::SubtypeOpen)) {
        return None;
    }
    let scope = crate::nurbs::toks::subtype_span(toks, position)?.tokens();
    position += scope.len();
    if !matches!(toks.get(position), Some(Token::True | Token::False)) {
        return None;
    }
    let mut cur = Cur::at(toks, position);
    let mut bounds = [None; 4];
    for bound in &mut bounds {
        *bound = cur.take_optional_range_value()?.value();
    }
    Some(bounds)
}

pub(crate) fn nurbs_curve_parameter_domain(curve: &NurbsCurve) -> Option<[f64; 2]> {
    let degree = usize::try_from(curve.degree()).ok()?;
    Some([
        *curve.knots().get(degree)?,
        *curve.knots().get(curve.pole_rows().count())?,
    ])
}

#[cfg(test)]
mod cache_form_tests {
    use super::{cache_first_curve_context, nurbs_curve_parameter_domain, ProjectionRoleSlot};
    use crate::kernel_header::RefWidth;
    use crate::nurbs::toks::Cur;
    use crate::sab::Token;
    use cadmpeg_ir::geometry::nurbs::NurbsCurve;
    use cadmpeg_ir::math::Point3;

    #[test]
    fn cache_first_support_decodes_the_solved_nurbs_support() {
        use crate::nurbs::toks::SubtypeTable;
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy};

        const AXIS_POLES: u32 = 16;
        let mut support = vec![
            Token::Ident("spline".into()),
            Token::Ident("nubs".into()),
            Token::Long(1),
            Token::Long(1),
            Token::Enum(0),
            Token::Enum(0),
            Token::Enum(0),
            Token::Enum(0),
            Token::Long(i64::from(AXIS_POLES)),
            Token::Long(i64::from(AXIS_POLES)),
        ];
        for _ in 0..2 {
            for knot in 0..AXIS_POLES {
                support.extend([Token::Double(f64::from(knot)), Token::Long(1)]);
            }
        }
        for v in 0..AXIS_POLES {
            for u in 0..AXIS_POLES {
                support.extend([
                    Token::Double(f64::from(u)),
                    Token::Double(f64::from(v)),
                    Token::Double(0.0),
                ]);
            }
        }
        support.extend([
            Token::False,
            Token::False,
            Token::False,
            Token::False,
            Token::Ident("null_surface".into()),
            Token::Ident("nullbs".into()),
            Token::Ident("nullbs".into()),
            Token::False,
            Token::False,
            Token::Long(0),
            Token::Long(0),
            Token::Long(0),
            Token::Long(7),
        ]);
        for intersection in [false, true] {
            let mut tokens = if intersection {
                vec![
                    Token::Long(23_100),
                    Token::Enum(0),
                    Token::Ident("nubs".into()),
                    Token::Long(1),
                    Token::Enum(0),
                    Token::Long(2),
                    Token::Double(0.0),
                    Token::Long(1),
                    Token::Double(1.0),
                    Token::Long(1),
                    Token::Double(0.0),
                    Token::Double(0.0),
                    Token::Double(0.0),
                    Token::Double(1.0),
                    Token::Double(0.0),
                    Token::Double(0.0),
                    Token::Double(0.0),
                ]
            } else {
                vec![
                    Token::Long(23_100),
                    Token::Enum(2),
                    Token::False,
                    Token::False,
                    Token::Enum(0),
                ]
            };
            tokens.extend(support.clone());
            let arena = DecodeArena::new();
            let (ctx, _) =
                DecodeContext::from_root_bytes(&[], &arena, &DecodePolicy::service()).unwrap();
            let table = SubtypeTable::from_records(&[]);
            let surfaces = if intersection {
                super::cache_first_intersection(&ctx, &tokens, 0, &solved_curve(), &table)
                    .unwrap()
                    .unwrap()
                    .0
                    .surfaces
            } else {
                let mut cur = Cur::at(&tokens, 0);
                let context = cache_first_curve_context(&ctx, &mut cur, &table)
                    .unwrap()
                    .unwrap();
                assert_eq!(cur.pos(), tokens.len());
                context.surfaces
            };
            let [super::SupportSlot::Surface(surface), super::SupportSlot::Absent] = surfaces
            else {
                panic!("one solved support and one absent support");
            };
            let Some(cadmpeg_ir::geometry::SolvedSurfaceGeometry::Nurbs(surface)) =
                surface.solved()
            else {
                panic!("solved NURBS support");
            };
            assert_eq!(surface.u_count(), usize::try_from(AXIS_POLES).unwrap());
            assert_eq!(surface.v_count(), usize::try_from(AXIS_POLES).unwrap());
            assert_eq!(surface.poles()[0].get(), Point3::new(0.0, 0.0, 0.0));
            assert_eq!(surface.poles()[255].get(), Point3::new(150.0, 150.0, 0.0));
            ctx.finish_session().unwrap();
        }
    }

    #[test]
    fn projection_role_slot_rejects_a_truncated_payload() {
        let original = b"\x07\x05surf1";
        let slot = ProjectionRoleSlot::parse(original, 0).unwrap();
        let mut bytes = original[..6].to_vec();
        let before = bytes.clone();
        let error = slot
            .write(&mut bytes, cadmpeg_ir::geometry::ProjectionRole::Surf2)
            .unwrap_err();
        assert!(matches!(error, cadmpeg_core::CodecError::Malformed(_)));
        assert_eq!(bytes, before);
    }

    /// A tagged integer field.
    fn push_int(bytes: &mut Vec<u8>, tag: u8, value: i64, int_width: RefWidth) {
        bytes.push(tag);
        match int_width {
            RefWidth::Eight => bytes.extend_from_slice(&value.to_le_bytes()),
            RefWidth::Four => bytes.extend_from_slice(
                &(i32::try_from(value).expect("test integer fits")).to_le_bytes(),
            ),
        }
    }

    /// A native identifier.
    fn push_ident(bytes: &mut Vec<u8>, value: &str) {
        bytes.push(0x0d);
        bytes.push(u8::try_from(value.len()).expect("short identifier"));
        bytes.extend_from_slice(value.as_bytes());
    }

    /// The shared cache-first intcurve context after its leading enum: two null
    /// supports, two null pcurves, two absent solved-interval endpoints, three
    /// empty discontinuity arrays, and the ASM extension integer.
    fn push_cache_first_remainder(bytes: &mut Vec<u8>, int_width: RefWidth) {
        push_ident(bytes, "null_surface");
        push_ident(bytes, "null_surface");
        push_ident(bytes, "nullbs");
        push_ident(bytes, "nullbs");
        bytes.extend_from_slice(&[0x0b, 0x0b]);
        for _ in 0..3 {
            push_int(bytes, 0x04, 0, int_width);
        }
        push_int(bytes, 0x04, 7, int_width);
    }

    /// A degree-one solved curve whose parameter domain is `[0, 1]`.
    fn solved_curve() -> NurbsCurve {
        NurbsCurve::from_lanes(
            1,
            vec![0.0, 0.0, 1.0, 1.0],
            vec![Point3::new(0.0, 0.0, 0.0), Point3::new(1.0, 0.0, 0.0)],
            None,
            false,
        )
        .unwrap()
    }

    /// Cache form `2` stores no `bs3_curve` and no fit tolerance: the leading
    /// enum is followed by the bool-gated curve interval and the closed-form
    /// enum, and the rest of the context continues unchanged.
    #[test]
    fn parameterized_cache_form_reads_the_interval_and_closed_form_enum() {
        let asm_decode_arena = cadmpeg_core::decode::DecodeArena::new();
        let (asm_decode_ctx, _) = cadmpeg_core::decode::DecodeContext::from_root_bytes(
            &[],
            &asm_decode_arena,
            &cadmpeg_core::decode::DecodePolicy::default(),
        )
        .expect("test decode context");
        for int_width in [RefWidth::Four, RefWidth::Eight] {
            let mut bytes = Vec::new();
            push_int(&mut bytes, 0x04, 23_100, int_width);
            push_int(&mut bytes, 0x15, 2, int_width);
            bytes.push(0x0a);
            bytes.push(0x06);
            bytes.extend_from_slice(&0.125f64.to_le_bytes());
            bytes.push(0x0b);
            push_int(&mut bytes, 0x15, 1, int_width);
            push_cache_first_remainder(&mut bytes, int_width);

            let solved = solved_curve();
            let toks = crate::nurbs::toks::lex_test_span(&bytes, int_width)
                .expect("valid single-record byte fixture");
            let table = crate::nurbs::toks::test_table(&bytes, int_width)
                .expect("valid single-record byte fixture");
            let mut cur = Cur::at(&toks, 0);
            let context = cache_first_curve_context(&asm_decode_ctx, &mut cur, &table)
                .transpose()
                .expect("decode the cache-first curve context")
                .unwrap_or_else(|| {
                    panic!("parameterized cache-first context at width {int_width}")
                });
            // Every field of the context is read: the walk ends on the last
            // token of the ASM extension integer.
            assert_eq!(cur.pos(), toks.len());
            assert_eq!(context.form.revision.get(), 23_100);
            assert!(context.form.cache.parameterization().is_some());
            let (context, form) =
                context.into_intersection(nurbs_curve_parameter_domain(&solved).unwrap());
            let parameterization = match form.cache {
                cadmpeg_ir::geometry::RevisionCacheForm::Parameterization(value) => value,
                cadmpeg_ir::geometry::RevisionCacheForm::SolvedCache { .. } => {
                    panic!("parameterized cache-first context")
                }
            };
            assert_eq!(parameterization.interval, [Some(0.125), None]);
            assert_eq!(parameterization.closed_form, 1);
            assert_eq!(form.extension, 7);
            assert_eq!(form.solved_range, [None, None]);
            // Absent solved-interval endpoints inherit the solved domain.
            assert_eq!(context.parameter_range, [0.0, 1.0]);
        }
    }

    /// A cache form with no defined grammar fails, so the containing record is
    /// retained verbatim rather than misparsed.
    #[test]
    fn undefined_cache_form_is_rejected_for_verbatim_retention() {
        let asm_decode_arena = cadmpeg_core::decode::DecodeArena::new();
        let (asm_decode_ctx, _) = cadmpeg_core::decode::DecodeContext::from_root_bytes(
            &[],
            &asm_decode_arena,
            &cadmpeg_core::decode::DecodePolicy::default(),
        )
        .expect("test decode context");
        for int_width in [RefWidth::Four, RefWidth::Eight] {
            let mut bytes = Vec::new();
            push_int(&mut bytes, 0x04, 23_100, int_width);
            push_int(&mut bytes, 0x15, 1, int_width);
            push_cache_first_remainder(&mut bytes, int_width);

            let toks = crate::nurbs::toks::lex_test_span(&bytes, int_width)
                .expect("valid single-record byte fixture");
            let table = crate::nurbs::toks::test_table(&bytes, int_width)
                .expect("valid single-record byte fixture");
            let mut cur = Cur::at(&toks, 0);
            assert!(cache_first_curve_context(&asm_decode_ctx, &mut cur, &table)
                .transpose()
                .expect("decode the cache-first curve context")
                .is_none());
        }
    }
}