opensubdiv-rs 0.7.0

A faithful Rust port of Pixar's OpenSubdiv subdivision-surface library (Sdc / Vtr / Far layers)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
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
//! Patch tables for parametric limit-surface evaluation.
//!
//! Port of the essential functionality of `opensubdiv/far/patchTable.h`,
//! `far/patchTableFactory.h`, `far/patchParam.h` and `far/patchMap.h`: a
//! collection of parametric patches covering the refined mesh, addressable
//! by ptex face and `(u, v)` location, and evaluable — with first
//! derivatives — anywhere on their domain.
//!
//! For a uniformly refined mesh, every non-hole face of the last level
//! yields one patch. For a feature-adaptively refined mesh
//! ([`TopologyRefiner::refine_adaptive`](super::TopologyRefiner::refine_adaptive)),
//! each face is patched at the level where it becomes regular, and only
//! the irregular remainder descends to the isolation cap — the patch count
//! grows with the mesh's features rather than with `4^level`. Adjacent
//! patches at different depths evaluate the same limit surface, so
//! parametric evaluation is seamless (crack-free *tessellation* support —
//! transition-edge tagging — is not needed for evaluation and is not
//! provided).
//!
//! ## Patch types
//!
//! * [`PatchType::Regular`] — where the face's four corners are *regular*
//!   (interior valence-4 smooth vertices; regular boundary vertices with
//!   sharpened boundaries; pinned corners; and vertices on an infinitely
//!   sharp crease whose span of faces on the patch's side is regular), the
//!   limit surface over the face is exactly a bicubic B-spline patch on 16
//!   control vertices of the last level. Boundary, crease and corner
//!   patches are represented by marking the missing control vertices and
//!   folding their *phantom-point* reflection (`2a - b`) into the basis
//!   weights at evaluation time — mathematically equivalent to OpenSubdiv's
//!   boundary/corner basis masks, with infinitely sharp creases treated as
//!   boundaries (OpenSubdiv's `useInfSharpPatch`).
//!
//!   With [`AdaptiveOptions::use_single_crease_patch`](super::AdaptiveOptions::use_single_crease_patch)
//!   (OpenSubdiv's `useSingleCreasePatch`), a regular face bounded on one
//!   side by a semi-sharp crease is a *single-crease* regular patch: its
//!   16 control vertices are weighted across the crease by the exact limit
//!   profile of the crease's sharpness
//!   ([`PatchTable::single_crease_sharpness`]), so the crease needs no
//!   isolation.
//! * [`PatchType::GregoryBasis`] — every other face at its isolation
//!   level is capped with a Gregory patch (see [`super::gregory`]):
//!   extraordinary vertices, irregular boundary and crease corners, sharp
//!   corners and darts. The 20 derived points give corner limit-point
//!   interpolation, exact C0 boundaries and approximate G1 smoothness, as
//!   OpenSubdiv's `ENDCAP_GREGORY_BASIS` does.
//! * Non-manifold edges and vertices are infinitely sharp, as in
//!   OpenSubdiv, so the faces around them are patched over their own
//!   manifold span like any other: regular where that span is regular,
//!   Gregory caps elsewhere.
//! * [`PatchType::Quads`] — irregular faces on unsharpened boundaries
//!   (`VtxBoundaryInterpolation::None`), and every face of the Bilinear
//!   scheme (whose mesh is its own limit surface) fall back to bilinear
//!   interpolation of the refined face.
//!
//! For the Loop scheme the same structure holds on triangles (see
//! [`super::loop_patch`]): [`PatchType::Loop`] quartic box-spline patches
//! on 12 control vertices where the three corners are regular (interior
//! valence 6, regular boundary and crease vertices, pinned corners),
//! [`PatchType::GregoryTriangle`] end caps on 18 derived points elsewhere,
//! and [`PatchType::Triangles`] for the linear fallback. A triangular
//! patch's domain is `s, t >= 0`, `s + t <= 1`; its [`PatchParam`] carries
//! only rotations 0 (upright) and 2 (inverted, for the central child of a
//! subdivided triangle).
//!
//! [`PatchTableFactory::create_with_options_selected`] (OpenSubdiv's
//! `selectedFaces`) builds the patches of chosen base faces only — with
//! [`TopologyRefiner::refine_adaptive_selected`](super::TopologyRefiner::refine_adaptive_selected),
//! refinement and patches then cost what those faces need, not what the
//! cage does, and the patches are the ones a full table gives them.
//!
//! Control-vertex indices refer to the **concatenation of every level's
//! vertices**, base level first: evaluate patches against the base values
//! followed by each level's
//! [`PrimvarRefiner::interpolate`](super::PrimvarRefiner::interpolate)
//! output.
//!
//! ## Face-varying patches
//!
//! With [`PatchTableOptions::generate_fvar_tables`], the table also holds,
//! for each face-varying channel, one patch per vertex patch, over the same
//! domain (OpenSubdiv's `generateFVarTables`). A channel's values form a
//! mesh of their own, refined in lockstep with the geometry, in which seams
//! are boundaries and the channel's linear-interpolation rule is encoded as
//! sharpness (see [`super::fvar`]); its patch for a face is the one that
//! value mesh gets at the vertex patch's level, by the rules above — or a
//! linear patch, for [`FVarLinearInterpolation::All`] and under
//! [`PatchTableOptions::generate_fvar_legacy_linear_patches`]. Its control
//! values are the channel's values at every level, base level first.

use super::gregory::{self, corner_span, is_edge_singular, vertex_rule, SparsePoint};
use super::loop_patch::{self, NUM_GREGORY_TRI_POINTS};
use super::primvar_refiner::Primvar;
use super::ptex::PtexIndices;
use super::topology_refiner::TopologyRefiner;
use crate::sdc::{Crease, FVarLinearInterpolation, Rule, SchemeType, Split};
use crate::vtr::{Level, TopologyError};
use crate::{Index, INDEX_INVALID};

/// The basis of a patch (`Far::PatchDescriptor::Type`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatchType {
    /// Bicubic B-spline patch on a 4x4 control-vertex grid.
    Regular,
    /// Gregory end-cap patch: 20 derived points around an extraordinary
    /// vertex (`PatchDescriptor::GREGORY_BASIS`).
    GregoryBasis,
    /// Bilinear quad on the face's 4 vertices.
    Quads,
    /// Quartic box-spline triangle patch on 12 control vertices
    /// (`PatchDescriptor::LOOP`), for regular faces of the Loop scheme.
    Loop,
    /// Gregory triangle end-cap patch: 18 derived points around an
    /// irregular triangle (`PatchDescriptor::GREGORY_TRIANGLE`).
    GregoryTriangle,
    /// Linear triangle on the face's 3 vertices
    /// (`PatchDescriptor::TRIANGLES`).
    Triangles,
}

/// Location and orientation of a patch within the parametric space of its
/// ptex face (`Far::PatchParam`).
///
/// A patch's local coordinates `(s, t) ∈ [0,1]²` map to ptex-face
/// coordinates via `(u, v) = origin + R(rotation) · (s, t) / 2^depth`.
///
/// Triangular patches (the Loop scheme) use the same transform over the
/// domain `s, t >= 0`, `s + t <= 1`: the three corner children of a
/// subdivided triangle keep their parent's orientation (rotation 0), and
/// the central child is inverted (rotation 2, its `(0, 0)` corner at the
/// parent's `(1/2, 1/2)`), as with OpenSubdiv's *rotated triangle* flag.
#[derive(Debug, Clone, Copy)]
pub struct PatchParam {
    /// The ptex face this patch belongs to.
    pub ptex_face: Index,
    /// Subdivision depth of the patch below its ptex root face.
    pub depth: u8,
    /// Orientation of the patch within the ptex face: number of 90° CCW
    /// rotations from patch frame to ptex frame.
    pub rotation: u8,
    /// Ptex-frame coordinates of the patch's `(0, 0)` corner.
    pub origin: [f32; 2],
    /// Is the patch triangular (the Loop scheme), its domain `s, t >= 0`,
    /// `s + t <= 1` rather than the unit square?
    pub triangular: bool,
}

impl PatchParam {
    /// The deepest [`depth`](Self::depth) a [`PatchTable`] stores: its
    /// parameters are packed into 8 bytes, as OpenSubdiv packs its own
    /// (whose depth stops at 10). Adaptive refinement never goes deeper
    /// than [`AdaptiveOptions::MAX_ISOLATION_LEVEL`](super::AdaptiveOptions::MAX_ISOLATION_LEVEL);
    /// [`PatchTableFactory::create`] rejects uniform refinement past it.
    pub const MAX_DEPTH: u8 = 12;

    /// Convert ptex-face coordinates to the patch's local `(s, t)`
    /// (`PatchParam::Normalize`).
    pub fn normalize(&self, u: f32, v: f32) -> (f32, f32) {
        let scale = (1u32 << self.depth) as f32;
        let x = (u - self.origin[0]) * scale;
        let y = (v - self.origin[1]) * scale;
        rotate_ccw((4 - self.rotation as u32) % 4, x, y)
    }

    /// Convert the patch's local `(s, t)` to ptex-face coordinates — the
    /// inverse of [`normalize`](Self::normalize).
    pub fn unnormalize(&self, s: f32, t: f32) -> (f32, f32) {
        let scale = 1.0 / (1u32 << self.depth) as f32;
        let (x, y) = rotate_ccw(self.rotation as u32, s, t);
        (self.origin[0] + x * scale, self.origin[1] + y * scale)
    }

    /// Is this triangular patch inverted with respect to its ptex face
    /// (`PatchParam::IsTriangleRotated`)? Always false for quad patches,
    /// whose rotation 2 is a plain 180° turn.
    pub fn is_triangle_rotated(&self) -> bool {
        self.triangular && self.rotation == 2
    }

    /// The Jacobian `d(s,t)/d(u,v)` of [`normalize`](Self::normalize), as
    /// `[ds/du, ds/dv, dt/du, dt/dv]`.
    fn derivative_matrix(&self) -> [f32; 4] {
        let s = (1u32 << self.depth) as f32;
        match self.rotation % 4 {
            0 => [s, 0.0, 0.0, s],
            1 => [0.0, s, -s, 0.0],
            2 => [-s, 0.0, 0.0, -s],
            _ => [0.0, -s, s, 0.0],
        }
    }
}

/// A [`PatchParam`] packed into 8 bytes (`Far::PatchParam`'s role): the
/// ptex face in the low 32 bits, then the depth (4 bits), the rotation (2),
/// the triangle flag (1) and the integer cell `(u, v)` the patch occupies
/// in its ptex face's `2^depth`-square grid (12 bits each).
///
/// The cell, rather than the origin, is what fits in `depth` bits: the
/// origin is the cell's corner [`CORNER_UV`]`[rotation]`, for quads at any
/// rotation and for triangles alike (an inverted triangle is the upper-right
/// half of its cell). Origins are exact multiples of `2^-depth`, so
/// unpacking returns them bit-for-bit.
#[derive(Debug, Clone, Copy)]
struct PackedPatchParam(u64);

impl PackedPatchParam {
    const CELL_BITS: u32 = 12;

    /// Pack `param`, or `None` when its depth exceeds
    /// [`PatchParam::MAX_DEPTH`].
    fn pack(param: &PatchParam) -> Option<Self> {
        if param.depth > PatchParam::MAX_DEPTH {
            return None;
        }
        let scale = (1u32 << param.depth) as f32;
        let corner = CORNER_UV[param.rotation as usize % 4];
        let cell = [0, 1].map(|k| (param.origin[k] * scale - corner[k]) as u64);
        debug_assert!(cell.iter().all(|&c| c < 1 << param.depth));
        let high = param.depth as u64
            | (param.rotation as u64 % 4) << 4
            | (param.triangular as u64) << 6
            | cell[0] << 7
            | cell[1] << (7 + Self::CELL_BITS);
        Some(Self(param.ptex_face as u64 | high << 32))
    }

    fn unpack(self) -> PatchParam {
        let high = self.0 >> 32;
        let depth = (high & 0xf) as u8;
        let rotation = ((high >> 4) & 0x3) as u8;
        let mask = (1u64 << Self::CELL_BITS) - 1;
        let cell = [(high >> 7) & mask, (high >> (7 + Self::CELL_BITS)) & mask];
        let scale = (1u32 << depth) as f32;
        let corner = CORNER_UV[rotation as usize];
        PatchParam {
            ptex_face: self.0 as Index,
            depth,
            rotation,
            origin: [0, 1].map(|k| (cell[k] as f32 + corner[k]) / scale),
            triangular: (high >> 6) & 1 != 0,
        }
    }
}

/// Basis weights of a patch at one parametric location: the limit point is
/// `Σ weights[i] · control[indices[i]]`, and similarly for the first
/// derivatives with respect to the ptex-face `(u, v)`.
#[derive(Debug, Clone, Default)]
pub struct PatchBasis {
    /// Indices of the contributing control vertices.
    pub indices: Vec<Index>,
    /// Weight of each control vertex for the limit position.
    pub weights: Vec<f32>,
    /// Weight of each control vertex for the derivative along `u`.
    pub du_weights: Vec<f32>,
    /// Weight of each control vertex for the derivative along `v`.
    pub dv_weights: Vec<f32>,
}

/// The internal patch arrays of a [`PatchTable`], in table order: each
/// holds patches of one kind contiguously (`Far::PatchTable`'s patch
/// arrays). Single-crease patches are [`PatchType::Regular`] patches with
/// their own array, so that plain regular patches carry no crease data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ArrayKind {
    Regular,
    SingleCrease,
    Gregory,
    Quads,
    Loop,
    GregoryTriangle,
    Triangles,
}

impl ArrayKind {
    const ALL: [ArrayKind; 7] = [
        ArrayKind::Regular,
        ArrayKind::SingleCrease,
        ArrayKind::Gregory,
        ArrayKind::Quads,
        ArrayKind::Loop,
        ArrayKind::GregoryTriangle,
        ArrayKind::Triangles,
    ];

    /// The number of entries each patch of this kind has in the table's
    /// control-vertex buffer (end caps keep theirs in [`LocalPoints`]).
    fn num_cvs(self) -> usize {
        match self {
            ArrayKind::Regular | ArrayKind::SingleCrease => 16,
            ArrayKind::Loop => 12,
            ArrayKind::Quads => 4,
            ArrayKind::Triangles => 3,
            ArrayKind::Gregory | ArrayKind::GregoryTriangle => 0,
        }
    }

    /// The basis type of the patches of this kind.
    fn patch_type(self) -> PatchType {
        match self {
            ArrayKind::Regular | ArrayKind::SingleCrease => PatchType::Regular,
            ArrayKind::Gregory => PatchType::GregoryBasis,
            ArrayKind::Quads => PatchType::Quads,
            ArrayKind::Loop => PatchType::Loop,
            ArrayKind::GregoryTriangle => PatchType::GregoryTriangle,
            ArrayKind::Triangles => PatchType::Triangles,
        }
    }
}

/// One non-empty patch array: its patches are `start..` in table order, and
/// their control vertices, single-crease data or end-cap ranges start at
/// `first_cv` and `first_aux` in the table's buffers.
#[derive(Debug, Clone, Copy)]
struct PatchArray {
    kind: ArrayKind,
    start: usize,
    first_cv: usize,
    first_aux: usize,
}

/// A borrowed view of one patch's data in a [`PatchTable`].
pub(crate) enum PatchRef<'a> {
    /// A 4x4 control-vertex grid (row-major, rows along `t`), with
    /// `INDEX_INVALID` marking phantom boundary slots.
    Regular(&'a [Index; 16]),
    /// A complete 4x4 control-vertex grid (as for `Regular`) with a
    /// semi-sharp crease along face edge `edge`.
    SingleCrease {
        cvs: &'a [Index; 16],
        edge: u8,
        sharpness: f32,
    },
    /// The 20 Gregory control points, stored in the table's
    /// [`LocalPoints`].
    Gregory(LocalPointRange),
    /// The face's 4 corner vertices.
    Quads(&'a [Index; 4]),
    /// The 12 control vertices of a box-spline triangle (laid out as in
    /// [`loop_patch::gather_regular_patch`]), with `INDEX_INVALID` marking
    /// phantom slots beyond boundaries and infinitely sharp creases.
    Loop(&'a [Index; 12]),
    /// The 18 Gregory triangle control points, stored in the table's
    /// [`LocalPoints`].
    GregoryTriangle(LocalPointRange),
    /// The face's 3 corner vertices.
    Triangles(&'a [Index; 3]),
}

/// Where the derived control points of one end-cap patch lie in
/// [`LocalPoints`].
#[derive(Debug, Clone, Copy)]
pub(crate) enum LocalPointRange {
    /// Compact storage: the patch's `support_len` support vertices start at
    /// `support`, its points are consecutive from `first_point` and their
    /// entries consecutive from `first_entry`.
    Compact {
        support: usize,
        first_point: usize,
        first_entry: usize,
        support_len: u8,
    },
    /// The stencils of a patch whose support is too large for compact
    /// storage (only around vertices of extreme valence), kept whole.
    Wide(usize),
}

/// The largest patch support [`LocalPoints`] stores compactly: slots and
/// per-point entry counts are bytes.
const MAX_COMPACT_SUPPORT: usize = u8::MAX as usize;

/// The derived control points of every end-cap patch (Gregory and Gregory
/// triangle), as one flat stencil table on the concatenated control values
/// — the role of OpenSubdiv's local-point stencil table for
/// `ENDCAP_GREGORY_BASIS`.
///
/// Each patch lists its *support* — the distinct control values its points
/// depend on, in order of first use — once, and each stencil entry refers
/// to its vertex by a one-byte slot in that list: an end cap costs four
/// bytes per support vertex, one per point and five per entry, with no
/// allocation of its own. Point `p` has `sizes[p]` entries, and the entries
/// of consecutive points are consecutive in `slots` and `weights`.
#[derive(Debug, Clone, Default)]
struct LocalPoints {
    support: Vec<Index>,
    sizes: Vec<u8>,
    slots: Vec<u8>,
    weights: Vec<f32>,
    /// The stencils of the [`LocalPointRange::Wide`] patches.
    wide: Vec<Box<[SparsePoint]>>,
}

impl LocalPoints {
    /// Append the stencils of one patch's `points`, moving their vertex
    /// indices into the concatenated control values with `map` and
    /// dropping zero weights. Exact zeros are common (a regular corner
    /// scales its neighbor's points by `cos(pi / 2) = 0` in the face-point
    /// blend) and contribute nothing.
    ///
    /// Entries of one point whose vertices `map` sends to the same control
    /// value are merged. That only happens for face-varying patches at the
    /// base level, where a value index the caller reused at several
    /// vertices is one value-mesh vertex at each of them.
    fn push(&mut self, points: &[SparsePoint], map: impl Fn(Index) -> Index) -> LocalPointRange {
        let support = self.support.len();
        let first_point = self.sizes.len();
        let first_entry = self.slots.len();
        'compact: {
            for point in points {
                let start = self.slots.len();
                for &(cv, w) in point.0.iter().filter(|&&(_, w)| w != 0.0) {
                    let cv = map(cv);
                    let slot = match self.support[support..].iter().position(|&s| s == cv) {
                        Some(slot) => slot,
                        None if self.support.len() - support < MAX_COMPACT_SUPPORT => {
                            self.support.push(cv);
                            self.support.len() - support - 1
                        }
                        None => break 'compact,
                    };
                    match self.slots[start..].iter().position(|&s| s as usize == slot) {
                        Some(entry) => self.weights[start + entry] += w,
                        None => {
                            self.slots.push(slot as u8);
                            self.weights.push(w);
                        }
                    }
                }
                // A point's entries have distinct slots, so their count is
                // at most the support's.
                self.sizes.push((self.slots.len() - start) as u8);
            }
            return LocalPointRange::Compact {
                support,
                first_point,
                first_entry,
                support_len: (self.support.len() - support) as u8,
            };
        }
        self.support.truncate(support);
        self.sizes.truncate(first_point);
        self.slots.truncate(first_entry);
        self.weights.truncate(first_entry);
        let nonzero = |point: &SparsePoint| {
            let mut mapped = SparsePoint::default();
            for &(cv, w) in point.0.iter().filter(|&&(_, w)| w != 0.0) {
                mapped.add(map(cv), w);
            }
            mapped
        };
        self.wide.push(points.iter().map(nonzero).collect());
        LocalPointRange::Wide(self.wide.len() - 1)
    }

    /// Call `f(point, control value, weight)` for every stencil entry of
    /// the `count` points of `range`, in order.
    fn for_each_entry(
        &self,
        range: LocalPointRange,
        count: usize,
        mut f: impl FnMut(usize, Index, f32),
    ) {
        match range {
            LocalPointRange::Compact {
                support,
                first_point,
                first_entry,
                ..
            } => {
                let support = &self.support[support..];
                let mut entry = first_entry;
                let sizes = &self.sizes[first_point..first_point + count];
                for (point, &size) in sizes.iter().enumerate() {
                    let entries = entry..entry + size as usize;
                    for (&slot, &w) in self.slots[entries.clone()]
                        .iter()
                        .zip(&self.weights[entries])
                    {
                        f(point, support[slot as usize], w);
                    }
                    entry += size as usize;
                }
            }
            LocalPointRange::Wide(patch) => {
                for (point, stencil) in self.wide[patch].iter().enumerate() {
                    for &(cv, w) in &stencil.0 {
                        f(point, cv, w);
                    }
                }
            }
        }
    }

    /// The distinct control values the points of `range` depend on, in
    /// order of first use.
    fn support(&self, range: LocalPointRange, count: usize) -> Vec<Index> {
        if let LocalPointRange::Compact {
            support,
            support_len,
            ..
        } = range
        {
            return self.support[support..support + support_len as usize].to_vec();
        }
        let mut cvs: Vec<Index> = Vec::new();
        self.for_each_entry(range, count, |_, cv, _| {
            if !cvs.contains(&cv) {
                cvs.push(cv);
            }
        });
        cvs
    }

    fn shrink_to_fit(&mut self) {
        self.support.shrink_to_fit();
        self.sizes.shrink_to_fit();
        self.slots.shrink_to_fit();
        self.weights.shrink_to_fit();
        self.wide.shrink_to_fit();
    }
}

/// The patches of a [`PatchTable`], or of one of its face-varying channels,
/// grouped into arrays by kind (`Far::PatchTable`'s patch arrays), with the
/// buffers the arrays index into.
#[derive(Debug, Clone, Default)]
struct PatchArrays {
    /// The non-empty patch arrays, in [`ArrayKind`] order.
    arrays: Vec<PatchArray>,
    /// The control vertices of the patches of every array that has them,
    /// [`ArrayKind::num_cvs`] per patch.
    cvs: Vec<Index>,
    /// Per single-crease patch: the crease's sharpness and face edge.
    creases: Vec<(f32, u8)>,
    /// Per end-cap patch: where its derived points lie in `local_points`.
    end_caps: Vec<LocalPointRange>,
    /// The derived control points of the end-cap patches.
    local_points: LocalPoints,
}

impl PatchArrays {
    /// The data of the patch at `offset` in `array`.
    fn patch_ref(&self, array: &PatchArray, offset: usize) -> PatchRef<'_> {
        let num_cvs = array.kind.num_cvs();
        let first = array.first_cv + offset * num_cvs;
        let cvs = &self.cvs[first..first + num_cvs];
        let aux = array.first_aux + offset;
        match array.kind {
            ArrayKind::Regular => PatchRef::Regular(cvs.try_into().unwrap()),
            ArrayKind::SingleCrease => {
                let (sharpness, edge) = self.creases[aux];
                PatchRef::SingleCrease {
                    cvs: cvs.try_into().unwrap(),
                    edge,
                    sharpness,
                }
            }
            ArrayKind::Gregory => PatchRef::Gregory(self.end_caps[aux]),
            ArrayKind::Quads => PatchRef::Quads(cvs.try_into().unwrap()),
            ArrayKind::Loop => PatchRef::Loop(cvs.try_into().unwrap()),
            ArrayKind::GregoryTriangle => PatchRef::GregoryTriangle(self.end_caps[aux]),
            ArrayKind::Triangles => PatchRef::Triangles(cvs.try_into().unwrap()),
        }
    }

    /// The control values `patch` depends on (see
    /// [`PatchTable::patch_vertices`]).
    fn vertices(&self, patch: PatchRef<'_>) -> Vec<Index> {
        match patch {
            PatchRef::Regular(cvs) => cvs
                .iter()
                .copied()
                .filter(|&cv| cv != INDEX_INVALID)
                .collect(),
            PatchRef::Loop(cvs) => cvs
                .iter()
                .copied()
                .filter(|&cv| cv != INDEX_INVALID)
                .collect(),
            PatchRef::SingleCrease { cvs, .. } => cvs.to_vec(),
            PatchRef::Quads(cvs) => cvs.to_vec(),
            PatchRef::Triangles(cvs) => cvs.to_vec(),
            PatchRef::Gregory(range) => self.local_points.support(range, gregory::NUM_POINTS),
            PatchRef::GregoryTriangle(range) => {
                self.local_points.support(range, NUM_GREGORY_TRI_POINTS)
            }
        }
    }

    /// The basis of `patch`, parameterized by `param`, at ptex-face
    /// coordinates `(u, v)` (see [`PatchTable::evaluate_basis`]).
    fn evaluate_basis(
        &self,
        patch: PatchRef<'_>,
        param: &PatchParam,
        u: f32,
        v: f32,
    ) -> PatchBasis {
        let (s, t) = param.normalize(u, v);
        // Chain rule to ptex frame: dP/du = Ps·ds/du + Pt·dt/du with
        // m = [ds/du, ds/dv, dt/du, dt/dv].
        let m = param.derivative_matrix();

        let mut basis = PatchBasis::default();
        let mut push = |cv: Index, w: f32, ws: f32, wt: f32| {
            let du = ws * m[0] + wt * m[2];
            let dv = ws * m[1] + wt * m[3];
            match basis.indices.iter().position(|&i| i == cv) {
                Some(k) => {
                    basis.weights[k] += w;
                    basis.du_weights[k] += du;
                    basis.dv_weights[k] += dv;
                }
                None => {
                    basis.indices.push(cv);
                    basis.weights.push(w);
                    basis.du_weights.push(du);
                    basis.dv_weights.push(dv);
                }
            }
        };

        match patch {
            PatchRef::Regular(cvs) => {
                let (bu, dbu) = bspline_basis(s);
                let (bv, dbv) = bspline_basis(t);
                let mut w = [0.0f32; 16];
                let mut ws = [0.0f32; 16];
                let mut wt = [0.0f32; 16];
                for j in 0..4 {
                    for i in 0..4 {
                        w[4 * j + i] = bu[i] * bv[j];
                        ws[4 * j + i] = dbu[i] * bv[j];
                        wt[4 * j + i] = bu[i] * dbv[j];
                    }
                }
                fold_phantom_weights(cvs, &mut w);
                fold_phantom_weights(cvs, &mut ws);
                fold_phantom_weights(cvs, &mut wt);
                for (slot, &cv) in cvs.iter().enumerate() {
                    if cv == INDEX_INVALID {
                        debug_assert!(w[slot] == 0.0 && ws[slot] == 0.0 && wt[slot] == 0.0);
                        continue;
                    }
                    push(cv, w[slot], ws[slot], wt[slot]);
                }
            }
            PatchRef::SingleCrease {
                cvs,
                edge,
                sharpness,
            } => {
                // Edges 3 and 1 are the columns at s = 0 and s = 1, edges 0
                // and 2 the rows at t = 0 and t = 1.
                let (bu, dbu) = match edge {
                    3 => crease_basis_oriented(s, sharpness, false),
                    1 => crease_basis_oriented(s, sharpness, true),
                    _ => bspline_basis(s),
                };
                let (bv, dbv) = match edge {
                    0 => crease_basis_oriented(t, sharpness, false),
                    2 => crease_basis_oriented(t, sharpness, true),
                    _ => bspline_basis(t),
                };
                for j in 0..4 {
                    for i in 0..4 {
                        push(
                            cvs[4 * j + i],
                            bu[i] * bv[j],
                            dbu[i] * bv[j],
                            bu[i] * dbv[j],
                        );
                    }
                }
            }
            PatchRef::Quads(cvs) => {
                let w = [(1.0 - s) * (1.0 - t), s * (1.0 - t), s * t, (1.0 - s) * t];
                let ws = [-(1.0 - t), 1.0 - t, t, -t];
                let wt = [-(1.0 - s), -s, s, 1.0 - s];
                for (slot, &cv) in cvs.iter().enumerate() {
                    push(cv, w[slot], ws[slot], wt[slot]);
                }
            }
            PatchRef::Gregory(range) => {
                let (w20, ws20, wt20) = gregory::evaluate_basis(s, t);
                self.local_points
                    .for_each_entry(range, gregory::NUM_POINTS, |point, cv, sw| {
                        push(cv, w20[point] * sw, ws20[point] * sw, wt20[point] * sw);
                    });
            }
            PatchRef::Loop(cvs) => {
                let (mut w, mut ws, mut wt) = loop_patch::box_spline_basis(s, t);
                loop_patch::fold_phantom_weights(cvs, &mut w);
                loop_patch::fold_phantom_weights(cvs, &mut ws);
                loop_patch::fold_phantom_weights(cvs, &mut wt);
                for (slot, &cv) in cvs.iter().enumerate() {
                    if cv == INDEX_INVALID {
                        debug_assert!(w[slot] == 0.0 && ws[slot] == 0.0 && wt[slot] == 0.0);
                        continue;
                    }
                    push(cv, w[slot], ws[slot], wt[slot]);
                }
            }
            PatchRef::GregoryTriangle(range) => {
                let (w18, ws18, wt18) = loop_patch::evaluate_basis(s, t);
                self.local_points
                    .for_each_entry(range, NUM_GREGORY_TRI_POINTS, |point, cv, sw| {
                        push(cv, w18[point] * sw, ws18[point] * sw, wt18[point] * sw);
                    });
            }
            PatchRef::Triangles(cvs) => {
                let w = [1.0 - s - t, s, t];
                let ws = [-1.0, 1.0, 0.0];
                let wt = [-1.0, 0.0, 1.0];
                for (slot, &cv) in cvs.iter().enumerate() {
                    push(cv, w[slot], ws[slot], wt[slot]);
                }
            }
        }
        basis
    }
}

/// The face-varying patches of one channel of a [`PatchTable`]
/// (`Far::PatchTable::FVarPatchChannel`): one per patch of the table, over
/// the same parametric domain, but built from the channel's own topology —
/// its value mesh at the patch's level.
#[derive(Debug, Clone)]
struct FVarPatches {
    /// The refiner's index of the channel.
    channel: usize,
    linear_interpolation: FVarLinearInterpolation,
    /// The number of face-varying values the patches index into.
    num_values: usize,
    patches: PatchArrays,
    /// Per patch: the index in `patches.arrays` of the array holding its
    /// face-varying patch, and its offset within that array. Both are empty
    /// when one array holds every patch (always so for linear patches): the
    /// offset is then the patch index.
    arrays: Vec<u8>,
    offsets: Vec<u32>,
}

impl FVarPatches {
    /// The array holding the face-varying patch of `patch`, and the
    /// patch's offset within it.
    fn locate(&self, patch: usize) -> (&PatchArray, usize) {
        if self.offsets.is_empty() {
            (&self.patches.arrays[0], patch)
        } else {
            let array = &self.patches.arrays[self.arrays[patch] as usize];
            (array, self.offsets[patch] as usize)
        }
    }

    fn patch_ref(&self, patch: usize) -> PatchRef<'_> {
        let (array, offset) = self.locate(patch);
        self.patches.patch_ref(array, offset)
    }
}

/// A table of patches describing the limit surface of a refined mesh
/// (`Far::PatchTable`).
///
/// Patches may live at *mixed depths* (feature-adaptive refinement emits a
/// patch at the level where its face becomes regular). Control-vertex
/// indices refer to the **concatenation of every level's vertices**, base
/// level first — the buffer produced by evaluating
/// [`PrimvarRefiner::interpolate`](super::PrimvarRefiner::interpolate)
/// level by level and appending each result to the base values
/// ([`num_control_values`](Self::num_control_values) in total).
///
/// As in OpenSubdiv's patch arrays, patches are grouped by type: indices
/// run through the regular patches (single-crease ones last), then the
/// Gregory, quad, Loop, Gregory-triangle and linear-triangle patches, each
/// group with its control vertices in one flat buffer and every patch's
/// [`PatchParam`] packed into 8 bytes. Within a group, patches follow
/// their faces level by level. Use [`PatchMap::find_patch`] to locate the
/// patch covering a ptex location.
///
/// ## Face-varying patches
///
/// Built with [`PatchTableOptions::generate_fvar_tables`], the table also
/// holds, per face-varying channel, one patch for each of its patches
/// (`GetPatchFVarValues`, `EvaluateBasisFaceVarying`). A channel's patch
/// covers the same domain as the vertex patch of the same index — the
/// patch [`PatchMap::find_patch`] returns serves both — but its type and
/// control values come from the channel's own topology, so seams, and the
/// channel's [`FVarLinearInterpolation`], are respected: see
/// [`fvar_patch_type`](Self::fvar_patch_type). Its control values are the
/// channel's values at every level, base level first
/// ([`num_fvar_values`](Self::num_fvar_values) in total): the base values
/// the channel was described with, followed by each level's
/// [`PrimvarRefiner::interpolate_face_varying`](super::PrimvarRefiner::interpolate_face_varying)
/// output.
#[derive(Debug, Clone)]
pub struct PatchTable {
    /// The patches, grouped into arrays.
    patches: PatchArrays,
    /// Per patch: its parameterization.
    params: Vec<PackedPatchParam>,
    /// Per patch: the face it covers.
    faces: Vec<Index>,
    /// Per level: patch index of each face (`INDEX_INVALID` where no patch
    /// was emitted — holes, refined faces, or unsupported support faces).
    face_to_patch: Vec<Vec<Index>>,
    ptex: PtexIndices,
    max_level: usize,
    /// Per refinement step: first child face of each parent face
    /// (`INDEX_INVALID` for faces without children under sparse
    /// refinement).
    first_child: Vec<Vec<Index>>,
    /// Total control values (sum of all levels' vertex counts).
    num_control_values: usize,
    /// Are the patches triangular (the Loop scheme)?
    triangular: bool,
    /// The face-varying patches of each channel the table was built for.
    fvar: Vec<FVarPatches>,
}

impl PatchTable {
    /// The number of patches in the table (`GetNumPatchesTotal`).
    pub fn num_patches(&self) -> usize {
        self.params.len()
    }

    /// The array holding patch `patch`, and the patch's offset within it.
    fn locate(&self, patch: usize) -> (&PatchArray, usize) {
        assert!(
            patch < self.num_patches(),
            "patch {patch} out of range ({} patches)",
            self.num_patches()
        );
        let array = self
            .patches
            .arrays
            .iter()
            .rfind(|array| array.start <= patch)
            .expect("a non-empty table has an array starting at patch 0");
        (array, patch - array.start)
    }

    /// The data of patch `patch`.
    pub(crate) fn patch_ref(&self, patch: usize) -> PatchRef<'_> {
        let (array, offset) = self.locate(patch);
        self.patches.patch_ref(array, offset)
    }

    /// Call `f(point, control value, weight)` for every stencil entry of
    /// the `count` derived points of an end-cap patch's `range`, in order.
    pub(crate) fn for_each_end_cap_entry(
        &self,
        range: LocalPointRange,
        count: usize,
        f: impl FnMut(usize, Index, f32),
    ) {
        self.patches.local_points.for_each_entry(range, count, f);
    }

    /// The basis type of patch `patch`.
    pub fn patch_type(&self, patch: usize) -> PatchType {
        self.locate(patch).0.kind.patch_type()
    }

    /// The [`PatchParam`] of patch `patch` (`GetPatchParam`).
    pub fn patch_param(&self, patch: usize) -> PatchParam {
        self.params[patch].unpack()
    }

    /// The face covered by patch `patch`, within the level given by the
    /// patch's [`PatchParam::depth`] ancestry (for uniform refiners, the
    /// last level).
    pub fn patch_face(&self, patch: usize) -> Index {
        self.faces[patch]
    }

    /// The control vertices of patch `patch` (`GetPatchVertices`), as
    /// indices into the concatenated control values. Phantom boundary
    /// slots of regular patches are omitted; for Gregory patches this is
    /// the union of the vertices supporting its derived points.
    pub fn patch_vertices(&self, patch: usize) -> Vec<Index> {
        self.patches.vertices(self.patch_ref(patch))
    }

    /// The sharpness of the semi-sharp crease carried by patch `patch`
    /// (`GetSingleCreasePatchSharpnessValue`): positive for single-crease
    /// patches — [`PatchType::Regular`] patches bounded by a semi-sharp
    /// crease, built when the refiner enabled
    /// [`AdaptiveOptions::use_single_crease_patch`](super::AdaptiveOptions::use_single_crease_patch)
    /// — and `0.0` for every other patch.
    pub fn single_crease_sharpness(&self, patch: usize) -> f32 {
        match self.patch_ref(patch) {
            PatchRef::SingleCrease { sharpness, .. } => sharpness,
            _ => 0.0,
        }
    }

    /// The ptex indexing of the base mesh.
    pub fn ptex_indices(&self) -> &PtexIndices {
        &self.ptex
    }

    /// The number of control values patch evaluation expects: one value per
    /// vertex of every refinement level, base level first
    /// (`GetNumControlVertices`).
    pub fn num_control_values(&self) -> usize {
        self.num_control_values
    }

    /// Evaluate the patch basis at a location given in the parametric space
    /// of the patch's *ptex face* (`EvaluateBasis`): returns point and
    /// first-derivative weights on the patch's control vertices.
    pub fn evaluate_basis(&self, patch: usize, u: f32, v: f32) -> PatchBasis {
        let param = self.patch_param(patch);
        self.patches
            .evaluate_basis(self.patch_ref(patch), &param, u, v)
    }

    /// Evaluate primvar data on patch `patch` at ptex-face coordinates
    /// `(u, v)`: returns the limit point and its two first derivatives.
    /// `control_values` holds one value per vertex of *every* refinement
    /// level, base level first
    /// ([`num_control_values`](Self::num_control_values) in total).
    pub fn evaluate<T: Primvar>(
        &self,
        patch: usize,
        u: f32,
        v: f32,
        control_values: &[T],
    ) -> (T, T, T) {
        combine(&self.evaluate_basis(patch, u, v), control_values)
    }

    // ------------------------------------------------------------------
    //  Face-varying patches
    // ------------------------------------------------------------------

    /// The number of face-varying channels the table holds patches for
    /// (`GetNumFVarChannels`): none unless it was built with
    /// [`PatchTableOptions::generate_fvar_tables`].
    pub fn num_fvar_channels(&self) -> usize {
        self.fvar.len()
    }

    /// The face-varying patches of table channel `channel`.
    fn fvar(&self, channel: usize) -> &FVarPatches {
        assert!(
            channel < self.fvar.len(),
            "face-varying channel {channel} out of range ({} channels in the table)",
            self.fvar.len()
        );
        &self.fvar[channel]
    }

    /// The face-varying data of patch `patch` in table channel `channel`.
    fn fvar_patch_ref(&self, patch: usize, channel: usize) -> PatchRef<'_> {
        self.locate(patch); // range check
        self.fvar(channel).patch_ref(patch)
    }

    /// The [`TopologyRefiner`]'s index of table channel `channel`: the
    /// entry at position `channel` of [`PatchTableOptions::fvar_channels`]
    /// (`fvarChannelIndices[channel]`), or `channel` itself when the table
    /// was built for every channel. With channels `&[2, 0]`, table channel
    /// 0 is refiner channel 2.
    pub fn fvar_refiner_channel(&self, channel: usize) -> usize {
        self.fvar(channel).channel
    }

    /// The linear-interpolation rule of table channel `channel`
    /// (`GetFVarChannelLinearInterpolation`).
    pub fn fvar_channel_linear_interpolation(&self, channel: usize) -> FVarLinearInterpolation {
        self.fvar(channel).linear_interpolation
    }

    /// The number of face-varying values the patches of table channel
    /// `channel` expect (`GetNumFVarValues`): the channel's values at every
    /// refinement level, base level first — at the base level, the values
    /// the channel was described with.
    pub fn num_fvar_values(&self, channel: usize) -> usize {
        self.fvar(channel).num_values
    }

    /// The basis type of the face-varying patch of `patch` in table channel
    /// `channel` (`GetFVarPatchDescriptor`, per patch).
    ///
    /// The type follows the channel's topology at the patch's level, and may
    /// differ from [`patch_type`](Self::patch_type):
    ///
    /// * linear patches — [`PatchType::Quads`], or [`PatchType::Triangles`]
    ///   for the Loop scheme — when the channel's interpolation is
    ///   [`FVarLinearInterpolation::All`], for the Bilinear scheme, and for
    ///   every channel when the table was built with
    ///   [`PatchTableOptions::generate_fvar_legacy_linear_patches`];
    /// * otherwise the patch the vertex topology would get from the
    ///   channel's value mesh: [`PatchType::Regular`] (including
    ///   single-crease patches) or [`PatchType::Loop`] where the channel is
    ///   regular around the face — seams act as infinitely sharp
    ///   boundaries, and the channel's interpolation rule as pinned corners
    ///   — and Gregory end caps ([`PatchType::GregoryBasis`],
    ///   [`PatchType::GregoryTriangle`]) where it is not. A face regular in
    ///   the vertex topology can be irregular in a channel's; refine with
    ///   [`AdaptiveOptions::consider_fvar_channels`](super::AdaptiveOptions::consider_fvar_channels)
    ///   to isolate such faces as well, rather than capping them at a
    ///   coarser level.
    pub fn fvar_patch_type(&self, patch: usize, channel: usize) -> PatchType {
        self.locate(patch);
        self.fvar(channel).locate(patch).0.kind.patch_type()
    }

    /// The face-varying values of `patch` in table channel `channel`
    /// (`GetPatchFVarValues`), as indices into the channel's concatenated
    /// values, laid out and filtered as
    /// [`patch_vertices`](Self::patch_vertices) does.
    pub fn fvar_patch_values(&self, patch: usize, channel: usize) -> Vec<Index> {
        let fvar = self.fvar(channel);
        fvar.patches.vertices(self.fvar_patch_ref(patch, channel))
    }

    /// The [`PatchParam`] of the face-varying patch of `patch` in table
    /// channel `channel` (`GetPatchFVarPatchParam`): face-varying patches
    /// share their vertex patch's domain, so this is
    /// [`patch_param`](Self::patch_param).
    pub fn fvar_patch_param(&self, patch: usize, channel: usize) -> PatchParam {
        self.fvar(channel);
        self.patch_param(patch)
    }

    /// Evaluate the face-varying patch basis of `patch` in table channel
    /// `channel` at ptex-face coordinates `(u, v)`
    /// (`EvaluateBasisFaceVarying`): point and first-derivative weights on
    /// the channel's concatenated values, at the same location
    /// [`evaluate_basis`](Self::evaluate_basis) evaluates the vertex patch.
    pub fn evaluate_basis_face_varying(
        &self,
        patch: usize,
        u: f32,
        v: f32,
        channel: usize,
    ) -> PatchBasis {
        let param = self.patch_param(patch);
        let fvar = self.fvar(channel);
        fvar.patches
            .evaluate_basis(self.fvar_patch_ref(patch, channel), &param, u, v)
    }

    /// Evaluate face-varying data of table channel `channel` on patch
    /// `patch` at ptex-face coordinates `(u, v)`: returns the value and its
    /// two first derivatives. `values` holds the channel's values at every
    /// refinement level, base level first
    /// ([`num_fvar_values`](Self::num_fvar_values) in total; see
    /// [`PrimvarRefiner::interpolate_face_varying_all`](super::PrimvarRefiner::interpolate_face_varying_all)).
    pub fn evaluate_face_varying<T: Primvar>(
        &self,
        patch: usize,
        u: f32,
        v: f32,
        values: &[T],
        channel: usize,
    ) -> (T, T, T) {
        combine(
            &self.evaluate_basis_face_varying(patch, u, v, channel),
            values,
        )
    }
}

/// Apply `basis` to `values`: the point and its two first derivatives.
fn combine<T: Primvar>(basis: &PatchBasis, values: &[T]) -> (T, T, T) {
    let mut point = values[0].clone();
    let mut du = values[0].clone();
    let mut dv = values[0].clone();
    point.clear();
    du.clear();
    dv.clear();
    for (k, &cv) in basis.indices.iter().enumerate() {
        let value = &values[cv as usize];
        point.add_with_weight(value, basis.weights[k]);
        du.add_with_weight(value, basis.du_weights[k]);
        dv.add_with_weight(value, basis.dv_weights[k]);
    }
    (point, du, dv)
}

/// Accelerated location of the patch covering a `(ptex face, u, v)`
/// location (`Far::PatchMap`).
///
/// The patch it returns also indexes the table's face-varying patches,
/// which share their vertex patch's domain
/// ([`PatchTable::evaluate_basis_face_varying`]).
pub struct PatchMap<'a> {
    table: &'a PatchTable,
}

impl<'a> PatchMap<'a> {
    /// Build a map over the patches of `table`.
    pub fn new(table: &'a PatchTable) -> Self {
        Self { table }
    }

    /// The patch covering coordinates `(u, v)` of `ptex_face`
    /// (`FindPatch`): descends the quadrant (or, for triangles, the
    /// sub-triangle) hierarchy until a patch is found, supporting
    /// mixed-depth (adaptive) tables. `None` only when the location lies in
    /// a hole, or on a face a selected-face table
    /// ([`PatchTableFactory::create_with_options_selected`]) leaves out.
    pub fn find_patch(&self, ptex_face: usize, u: f32, v: f32) -> Option<usize> {
        let table = self.table;
        let base_face = table.ptex.base_face(ptex_face) as usize;
        // Regular base faces map to exactly one ptex face; N-gons to N.
        let base_is_regular = table.ptex.face_ptex_count(base_face) == 1;

        let (mut face, mut level, mut u, mut v) = if base_is_regular {
            (base_face, 0usize, u, v)
        } else {
            // Non-quad base faces root their ptex faces at level 1 (their
            // isolation guarantees at least one refinement, unless the
            // table left them out with the rest of the unselected faces).
            let first_child = table.first_child.first().map(|fc| fc[base_face]);
            match first_child {
                Some(first_child) if first_child != INDEX_INVALID => {
                    let child = first_child as usize + table.ptex.base_face_corner(ptex_face);
                    (child, 1usize, u, v)
                }
                _ => return None,
            }
        };

        loop {
            match table.face_to_patch[level][face] {
                INDEX_INVALID => {}
                p => return Some(p as usize),
            }
            if level >= table.max_level {
                return None;
            }
            let first_child = table.first_child[level][face];
            if first_child == INDEX_INVALID {
                return None; // unrefined support face without a patch
            }
            let (k, nu, nv) = if table.triangular {
                descend_triangle(u, v)
            } else {
                descend_quadrant(u, v)
            };
            face = first_child as usize + k;
            u = nu;
            v = nv;
            level += 1;
        }
    }
}

/// Options controlling [`PatchTableFactory::create_with_options`]
/// (`Far::PatchTableFactory::Options`).
#[derive(Debug, Clone)]
pub struct PatchTableOptions {
    /// Build face-varying patches (`generateFVarTables`): for each selected
    /// channel, one patch per patch of the table, evaluated with
    /// [`PatchTable::evaluate_basis_face_varying`]. Off by default, as in
    /// OpenSubdiv.
    pub generate_fvar_tables: bool,
    /// The refiner channels to build face-varying patches for, in the order
    /// the table numbers them (`numFVarChannels` / `fvarChannelIndices`);
    /// `None` selects every channel of the refiner. Ignored unless
    /// [`generate_fvar_tables`](Self::generate_fvar_tables) is set.
    pub fvar_channels: Option<Vec<usize>>,
    /// Build every face-varying patch as a linear patch over its refined
    /// face, whatever the channel's interpolation
    /// (`generateFVarLegacyLinearPatches`). On by default, as in
    /// OpenSubdiv: turn it off for smooth face-varying patches that follow
    /// each channel's own topology and
    /// [`FVarLinearInterpolation`].
    pub generate_fvar_legacy_linear_patches: bool,
}

impl Default for PatchTableOptions {
    fn default() -> Self {
        Self {
            generate_fvar_tables: false,
            fvar_channels: None,
            generate_fvar_legacy_linear_patches: true,
        }
    }
}

impl PatchTableOptions {
    /// Options with every field set to its OpenSubdiv default.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable or disable face-varying patches
    /// ([`generate_fvar_tables`](Self::generate_fvar_tables)).
    pub fn with_fvar_tables(mut self, enabled: bool) -> Self {
        self.generate_fvar_tables = enabled;
        self
    }

    /// Build face-varying patches for the refiner channels `channels` only,
    /// numbered in that order in the table
    /// ([`fvar_channels`](Self::fvar_channels)).
    pub fn with_fvar_channels(mut self, channels: &[usize]) -> Self {
        self.fvar_channels = Some(channels.to_vec());
        self
    }

    /// Enable or disable legacy linear face-varying patches
    /// ([`generate_fvar_legacy_linear_patches`](Self::generate_fvar_legacy_linear_patches)).
    pub fn with_fvar_legacy_linear_patches(mut self, enabled: bool) -> Self {
        self.generate_fvar_legacy_linear_patches = enabled;
        self
    }
}

/// Factory constructing a [`PatchTable`] from a refined [`TopologyRefiner`]
/// (`Far::PatchTableFactory`).
pub struct PatchTableFactory;

impl PatchTableFactory {
    /// Build a [`PatchTable`] covering the limit surface of `refiner`
    /// (`PatchTableFactory::Create`), with the default
    /// [`PatchTableOptions`]: vertex patches only.
    ///
    /// # Errors
    ///
    /// Returns [`TopologyError::PatchesRequireRefinement`] when the base
    /// mesh contains non-quad faces (under a quad-split scheme) and
    /// `refiner` has not refined them — not refined at all, or refined with
    /// [`TopologyRefiner::refine_adaptive_selected`] around other faces —
    /// and
    /// [`TopologyError::PatchDepthTooDeep`] when a patch would lie deeper
    /// than [`PatchParam::MAX_DEPTH`] below its ptex face (uniform
    /// refinement past that level).
    pub fn create(refiner: &TopologyRefiner) -> Result<PatchTable, TopologyError> {
        Self::create_with_options(refiner, &PatchTableOptions::default())
    }

    /// Build a [`PatchTable`] covering the limit surface of `refiner`, and
    /// the face-varying patches `options` asks for
    /// (`PatchTableFactory::Create` with `Options`).
    ///
    /// # Errors
    ///
    /// As [`create`](Self::create), and
    /// [`TopologyError::FVarChannelOutOfRange`] when
    /// [`PatchTableOptions::fvar_channels`] names a channel the refiner
    /// does not have.
    ///
    /// # Example
    ///
    /// Evaluate a seamed UV chart at the same location as the surface:
    ///
    /// ```
    /// use opensubdiv_rs::far::{
    ///     AdaptiveOptions, FVarChannelDescriptor, PatchMap, PatchTableFactory,
    ///     PatchTableOptions, PrimvarRefiner, TopologyDescriptor, TopologyRefinerFactory,
    /// };
    /// use opensubdiv_rs::sdc;
    ///
    /// // Two quads whose shared edge is a UV seam.
    /// let face_verts = [0u32, 1, 4, 3, 1, 2, 5, 4];
    /// let uv_indices = [0u32, 1, 2, 3, 4, 5, 6, 7];
    /// let uvs: Vec<[f32; 2]> = vec![
    ///     [0.0, 0.0], [0.45, 0.0], [0.45, 1.0], [0.0, 1.0],
    ///     [0.55, 0.0], [1.0, 0.0], [1.0, 1.0], [0.55, 1.0],
    /// ];
    /// let channels = [FVarChannelDescriptor::new(uvs.len(), &uv_indices)];
    /// let descriptor = TopologyDescriptor::new(6, &[4, 4], &face_verts)
    ///     .with_fvar_channels(&channels);
    /// let mut refiner = TopologyRefinerFactory::create(
    ///     descriptor,
    ///     sdc::SchemeType::Catmark,
    ///     sdc::Options::default(),
    /// )?;
    /// refiner.refine_adaptive(AdaptiveOptions::new(3).with_consider_fvar_channels(true));
    ///
    /// let options = PatchTableOptions::new()
    ///     .with_fvar_tables(true)
    ///     .with_fvar_legacy_linear_patches(false);
    /// let table = PatchTableFactory::create_with_options(&refiner, &options)?;
    ///
    /// // The channel's values at every level, base level first.
    /// let mut values = uvs.clone();
    /// for level in PrimvarRefiner::new(&refiner).interpolate_face_varying_all(0, &uvs) {
    ///     values.extend(level);
    /// }
    /// assert_eq!(values.len(), table.num_fvar_values(0));
    ///
    /// let patch = PatchMap::new(&table).find_patch(1, 0.0, 0.5).unwrap();
    /// let (uv, _du, _dv) = table.evaluate_face_varying(patch, 0.0, 0.5, &values, 0);
    /// // On the seam, face 1 takes its own side of the chart.
    /// assert!((uv[0] - 0.55).abs() < 1e-6);
    /// # Ok::<(), opensubdiv_rs::vtr::TopologyError>(())
    /// ```
    pub fn create_with_options(
        refiner: &TopologyRefiner,
        options: &PatchTableOptions,
    ) -> Result<PatchTable, TopologyError> {
        Self::create_impl(refiner, options, None)
    }

    /// Build a [`PatchTable`] covering the limit surface of the base faces
    /// `selected_faces` of `refiner` only, and their face-varying patches
    /// if `options` asks for them (`PatchTableFactory::Create` with
    /// `selectedFaces`).
    ///
    /// Only the selected faces and their descendants get patches: those a
    /// full table would give them, at the same levels and with the same
    /// types, [`PatchParam`]s, sharpness and control vertices. They are
    /// numbered compactly (grouped by type, as in a full table), and
    /// [`PatchMap::find_patch`] returns `None` on every ptex face of an
    /// unselected face. Pair it with
    /// [`TopologyRefiner::refine_adaptive_selected`] on the same faces, so
    /// that refinement, too, costs only what the selected faces need; the
    /// patches then evaluate the same limit surface as a full refinement's
    /// and a full table's on those faces. Control values remain the
    /// concatenation of every level's vertices, as for a full table.
    ///
    /// Unlike OpenSubdiv, where an empty `selectedFaces` array means every
    /// face, an empty `selected_faces` yields a table without patches.
    /// Duplicates and holes are ignored.
    ///
    /// # Errors
    ///
    /// As [`create_with_options`](Self::create_with_options) — with
    /// [`TopologyError::PatchesRequireRefinement`] returned when a selected
    /// non-quad face was not refined — and
    /// [`TopologyError::SelectedFaceOutOfRange`] when a selected face is
    /// not a face of the base level.
    ///
    /// # Example
    ///
    /// Patch two faces of a cube, refining only around them:
    ///
    /// ```
    /// use opensubdiv_rs::far::{
    ///     AdaptiveOptions, PatchMap, PatchTableFactory, PatchTableOptions, TopologyDescriptor,
    ///     TopologyRefinerFactory,
    /// };
    /// use opensubdiv_rs::sdc;
    ///
    /// let face_verts = [0u32, 1, 3, 2, 2, 3, 5, 4, 4, 5, 7, 6, 6, 7, 1, 0, 1, 7, 5, 3, 6, 0, 2, 4];
    /// let descriptor = TopologyDescriptor::new(8, &[4; 6], &face_verts);
    /// let mut refiner = TopologyRefinerFactory::create(
    ///     descriptor,
    ///     sdc::SchemeType::Catmark,
    ///     sdc::Options::default(),
    /// )?;
    /// let selected = [0, 1];
    /// refiner.refine_adaptive_selected(AdaptiveOptions::new(3), &selected);
    /// let table = PatchTableFactory::create_with_options_selected(
    ///     &refiner,
    ///     &PatchTableOptions::new(),
    ///     &selected,
    /// )?;
    ///
    /// let map = PatchMap::new(&table);
    /// assert!(map.find_patch(1, 0.3, 0.6).is_some());
    /// assert!(map.find_patch(2, 0.3, 0.6).is_none()); // not selected
    /// # Ok::<(), opensubdiv_rs::vtr::TopologyError>(())
    /// ```
    pub fn create_with_options_selected(
        refiner: &TopologyRefiner,
        options: &PatchTableOptions,
        selected_faces: &[Index],
    ) -> Result<PatchTable, TopologyError> {
        let num_faces = refiner.level(0).num_faces();
        let mut selected = vec![false; num_faces];
        for &face in selected_faces {
            *selected
                .get_mut(face as usize)
                .ok_or(TopologyError::SelectedFaceOutOfRange { face, num_faces })? = true;
        }
        Self::create_impl(refiner, options, Some(selected))
    }

    /// Build the patches of every face, or of the base faces flagged in
    /// `selected` and their descendants.
    fn create_impl(
        refiner: &TopologyRefiner,
        options: &PatchTableOptions,
        selected: Option<Vec<bool>>,
    ) -> Result<PatchTable, TopologyError> {
        let num_channels = refiner.num_fvar_channels();
        let fvar_channels: Vec<usize> = match (&options.fvar_channels, options.generate_fvar_tables)
        {
            (_, false) => Vec::new(),
            (None, true) => (0..num_channels).collect(),
            (Some(channels), true) => {
                if let Some(&channel) = channels.iter().find(|&&c| c >= num_channels) {
                    return Err(TopologyError::FVarChannelOutOfRange {
                        channel,
                        num_channels,
                    });
                }
                channels.clone()
            }
        };

        let scheme_type = refiner.scheme_type();
        let triangular = scheme_type.topological_split_type() == Split::ToTris;
        let regular_size = scheme_type.regular_face_size();

        let max_level = refiner.max_level();

        // Per refinement step: the first child face of each parent face
        // (children of one parent are contiguous, in corner order).
        let mut first_child: Vec<Vec<Index>> = Vec::with_capacity(max_level);
        for l in 1..=max_level {
            let refinement = refiner.refinement(l);
            let mut fc = vec![INDEX_INVALID; refiner.level(l - 1).num_faces()];
            for cf in 0..refiner.level(l).num_faces() {
                let parent = refinement.child_face_parent_face(cf) as usize;
                if fc[parent] == INDEX_INVALID {
                    fc[parent] = cf as Index;
                }
            }
            first_child.push(fc);
        }

        // Control values are the concatenation of every level's vertices.
        let mut level_offsets = Vec::with_capacity(max_level + 1);
        let mut total = 0usize;
        for l in 0..=max_level {
            level_offsets.push(total as Index);
            total += refiner.level(l).num_vertices();
        }

        let ptex = PtexIndices::new(refiner);
        let single_crease = refiner.uses_single_crease_patch();

        // Each patch goes to the array of its kind; `face_to_patch` holds
        // its offset there, and `face_kind` the array, until the arrays are
        // laid out one after another. The per-patch data — parameterization,
        // face and level — is gathered per kind too.
        let mut builder = PatchArraysBuilder::default();
        let mut params: [Vec<PackedPatchParam>; 7] = Default::default();
        let mut faces: [Vec<Index>; 7] = Default::default();
        let mut levels: [Vec<u8>; 7] = Default::default();
        let mut face_to_patch: Vec<Vec<Index>> = (0..=max_level)
            .map(|l| vec![INDEX_INVALID; refiner.level(l).num_faces()])
            .collect();
        let mut face_kind: Vec<Vec<u8>> = (0..=max_level)
            .map(|l| vec![0; refiner.level(l).num_faces()])
            .collect();

        // With selected faces: per face of the current level, does it
        // descend from a selected base face?
        let mut covered = selected;
        for level in 0..=max_level {
            let level_view = refiner.level(level);
            let inner = level_view.inner();
            let offset = level_offsets[level];
            if level > 0 {
                covered = covered.map(|parent_covered| {
                    let refinement = refiner.refinement(level);
                    (0..level_view.num_faces())
                        .map(|f| parent_covered[refinement.child_face_parent_face(f) as usize])
                        .collect()
                });
            }
            for (face, (patch_slot, kind_slot)) in face_to_patch[level]
                .iter_mut()
                .zip(face_kind[level].iter_mut())
                .enumerate()
            {
                if covered.as_ref().is_some_and(|covered| !covered[face]) {
                    continue;
                }
                if level_view.is_face_hole(face) || !refiner.face_is_candidate(level, face) {
                    continue;
                }
                if level < max_level && refiner.face_is_selected(level, face) {
                    continue; // refined further; patches come from children
                }
                if level == 0 && level_view.face_vertices(face).len() != regular_size {
                    // A non-quad (under a quad split) base face is patched
                    // over its children, one ptex face per corner.
                    return Err(TopologyError::PatchesRequireRefinement);
                }
                let param =
                    compute_patch_param(refiner, &ptex, &first_child, face, level, triangular);
                let packed =
                    PackedPatchParam::pack(&param).ok_or(TopologyError::PatchDepthTooDeep {
                        depth: param.depth as usize,
                        max: PatchParam::MAX_DEPTH as usize,
                    })?;
                debug_assert!(same_param(&packed.unpack(), &param));
                let source = classify_patch(inner, face, scheme_type, false, single_crease);
                let (kind, index) = builder.push(source, |cv| cv + offset);
                *patch_slot = index as Index;
                *kind_slot = kind as u8;
                params[kind as usize].push(packed);
                faces[kind as usize].push(face as Index);
                levels[kind as usize].push(level as u8);
            }
        }

        let (patches, starts) = builder.finish();
        let params: Vec<PackedPatchParam> = flatten(params);
        let faces: Vec<Index> = flatten(faces);
        let levels: Vec<u8> = flatten(levels);
        for (patches, kinds) in face_to_patch.iter_mut().zip(&face_kind) {
            for (patch, &kind) in patches.iter_mut().zip(kinds) {
                if *patch != INDEX_INVALID {
                    *patch += starts[kind as usize] as Index;
                }
            }
        }

        let fvar = fvar_channels
            .into_iter()
            .map(|channel| {
                build_fvar_patches(
                    refiner,
                    channel,
                    options.generate_fvar_legacy_linear_patches,
                    &levels,
                    &faces,
                )
            })
            .collect();

        Ok(PatchTable {
            patches,
            params,
            faces,
            face_to_patch,
            ptex,
            max_level,
            first_child,
            num_control_values: total,
            triangular,
            fvar,
        })
    }
}

/// The per-kind vectors `arrays` concatenated in [`ArrayKind`] order, with
/// exactly the capacity they need.
fn flatten<T>(arrays: [Vec<T>; 7]) -> Vec<T> {
    let mut flat = Vec::with_capacity(arrays.iter().map(Vec::len).sum());
    arrays.into_iter().for_each(|array| flat.extend(array));
    flat
}

/// Build the face-varying patches of refiner channel `channel`: for each
/// patch of the table, in table order, the patch its face gets from the
/// channel's value mesh at the patch's level (`levels`, `faces`).
fn build_fvar_patches(
    refiner: &TopologyRefiner,
    channel: usize,
    legacy_linear: bool,
    levels: &[u8],
    faces: &[Index],
) -> FVarPatches {
    let fvar = refiner.fvar_channel(channel);
    let scheme_type = refiner.scheme_type();
    let linear = legacy_linear || fvar.is_linear();
    let single_crease = refiner.uses_single_crease_patch();

    // The channel's values are the concatenation of every level's: the
    // caller's at the base level, the value mesh's vertices above.
    let mut level_offsets = Vec::with_capacity(refiner.num_levels());
    let mut num_values = 0usize;
    for l in 0..refiner.num_levels() {
        level_offsets.push(num_values as Index);
        num_values += fvar.num_values(l);
    }
    // A base value-mesh vertex split off a value index reused at several
    // vertices refers back to that index.
    let base_sources = fvar.base_value_sources();

    let mut builder = PatchArraysBuilder::default();
    let mut kinds = Vec::with_capacity(faces.len());
    let mut offsets = Vec::with_capacity(faces.len());
    for (&level, &face) in levels.iter().zip(faces) {
        let level = level as usize;
        let source = classify_patch(
            fvar.level(level),
            face as usize,
            scheme_type,
            linear,
            single_crease,
        );
        let (kind, offset) = match (level, base_sources) {
            (0, Some(sources)) => builder.push(source, |value| sources[value as usize]),
            _ => {
                let first = level_offsets[level];
                builder.push(source, |value| value + first)
            }
        };
        kinds.push(kind);
        offsets.push(offset as u32);
    }

    let (patches, _) = builder.finish();
    let (arrays, offsets) = if patches.arrays.len() <= 1 {
        (Vec::new(), Vec::new())
    } else {
        let array_of = |kind: ArrayKind| {
            let index = patches.arrays.iter().position(|a| a.kind == kind);
            index.expect("every patch kind used has an array") as u8
        };
        (kinds.into_iter().map(array_of).collect(), offsets)
    };
    FVarPatches {
        channel,
        linear_interpolation: fvar.linear_interpolation(),
        num_values,
        patches,
        arrays,
        offsets,
    }
}

/// The patch a face gets, before its control indices move into a table.
enum PatchSource {
    /// A patch stored as its control vertices: the first
    /// [`ArrayKind::num_cvs`] entries, phantom slots `INDEX_INVALID`.
    Cvs(ArrayKind, [Index; 16]),
    SingleCrease(SingleCrease),
    Gregory(gregory::GregoryPoints),
    GregoryTriangle(loop_patch::GregoryTriPoints),
}

/// The patch covering `face` of `level` — the geometry's level, or a
/// face-varying channel's value mesh at that level. `linear` asks for a
/// linear patch over the face whatever its neighborhood.
fn classify_patch(
    level: &Level,
    face: usize,
    scheme_type: SchemeType,
    linear: bool,
    single_crease: bool,
) -> PatchSource {
    let linear_patch = || {
        let fv = level.face_vertices(face);
        let mut cvs = [INDEX_INVALID; 16];
        cvs[..fv.len()].copy_from_slice(fv);
        let kind = if fv.len() == 3 {
            ArrayKind::Triangles
        } else {
            ArrayKind::Quads
        };
        debug_assert_eq!(fv.len(), kind.num_cvs());
        PatchSource::Cvs(kind, cvs)
    };
    if linear {
        return linear_patch();
    }
    match scheme_type {
        SchemeType::Catmark => {
            if let Some(cvs) = gather_regular_patch(level, face) {
                PatchSource::Cvs(ArrayKind::Regular, cvs)
            } else if let Some(patch) = single_crease
                .then(|| single_crease_patch(level, face))
                .flatten()
            {
                PatchSource::SingleCrease(patch)
            } else if let Some(points) = gregory::build(level, face) {
                // Irregular neighborhood (extraordinary, boundary, crease,
                // sharp, dart or non-manifold corners): Gregory end cap.
                PatchSource::Gregory(points)
            } else {
                // Unsharpened boundary or non-quad ring: bilinear fallback.
                linear_patch()
            }
        }
        SchemeType::Loop => {
            if let Some(loop_cvs) = loop_patch::gather_regular_patch(level, face) {
                let mut cvs = [INDEX_INVALID; 16];
                cvs[..12].copy_from_slice(&loop_cvs);
                PatchSource::Cvs(ArrayKind::Loop, cvs)
            } else if let Some(points) = loop_patch::build(level, face) {
                PatchSource::GregoryTriangle(points)
            } else {
                // Unsharpened boundary: linear fallback.
                linear_patch()
            }
        }
        // Bilinear: the mesh is its own limit surface.
        SchemeType::Bilinear => linear_patch(),
    }
}

/// The patches of one [`ArrayKind`] while a table is built.
#[derive(Default)]
struct ArrayBuilder {
    len: usize,
    cvs: Vec<Index>,
    creases: Vec<(f32, u8)>,
    end_caps: Vec<LocalPointRange>,
}

/// [`PatchArrays`] under construction: patches are added in any order of
/// kinds, then laid out array by array.
#[derive(Default)]
struct PatchArraysBuilder {
    arrays: [ArrayBuilder; 7],
    local_points: LocalPoints,
}

impl PatchArraysBuilder {
    /// Add the patch `source`, moving its control indices into the table's
    /// control values with `map` (phantom slots stay `INDEX_INVALID`).
    /// Returns the patch's kind and its offset within that kind's array.
    fn push(&mut self, source: PatchSource, map: impl Fn(Index) -> Index) -> (ArrayKind, usize) {
        let shift = |cv: Index| {
            if cv == INDEX_INVALID {
                cv
            } else {
                map(cv)
            }
        };
        let kind = match source {
            PatchSource::Cvs(kind, cvs) => {
                let array = &mut self.arrays[kind as usize];
                array
                    .cvs
                    .extend(cvs[..kind.num_cvs()].iter().map(|&cv| shift(cv)));
                kind
            }
            PatchSource::SingleCrease(patch) => {
                let array = &mut self.arrays[ArrayKind::SingleCrease as usize];
                array.cvs.extend(patch.cvs.iter().map(|&cv| shift(cv)));
                array.creases.push((patch.sharpness, patch.edge));
                ArrayKind::SingleCrease
            }
            PatchSource::Gregory(points) => {
                let range = self.local_points.push(&points, &map);
                self.arrays[ArrayKind::Gregory as usize]
                    .end_caps
                    .push(range);
                ArrayKind::Gregory
            }
            PatchSource::GregoryTriangle(points) => {
                let range = self.local_points.push(&points, &map);
                self.arrays[ArrayKind::GregoryTriangle as usize]
                    .end_caps
                    .push(range);
                ArrayKind::GregoryTriangle
            }
        };
        let array = &mut self.arrays[kind as usize];
        array.len += 1;
        (kind, array.len - 1)
    }

    /// Lay the arrays out one after another, in [`ArrayKind`] order, with
    /// exactly the capacity they need. Also returns the index of the first
    /// patch of each kind.
    fn finish(self) -> (PatchArrays, [usize; 7]) {
        let Self {
            arrays: builders,
            mut local_points,
        } = self;
        let total_of = |f: fn(&ArrayBuilder) -> usize| builders.iter().map(f).sum::<usize>();
        let mut arrays = Vec::new();
        let mut cvs = Vec::with_capacity(total_of(|b| b.cvs.len()));
        let mut creases = Vec::with_capacity(total_of(|b| b.creases.len()));
        let mut end_caps = Vec::with_capacity(total_of(|b| b.end_caps.len()));
        let mut starts = [0usize; 7];
        let mut start = 0;
        for (kind, builder) in ArrayKind::ALL.into_iter().zip(builders) {
            starts[kind as usize] = start;
            if builder.len == 0 {
                continue;
            }
            arrays.push(PatchArray {
                kind,
                start,
                first_cv: cvs.len(),
                first_aux: match kind {
                    ArrayKind::SingleCrease => creases.len(),
                    ArrayKind::Gregory | ArrayKind::GregoryTriangle => end_caps.len(),
                    _ => 0,
                },
            });
            start += builder.len;
            cvs.extend(builder.cvs);
            creases.extend(builder.creases);
            end_caps.extend(builder.end_caps);
        }
        local_points.shrink_to_fit();
        let patches = PatchArrays {
            arrays,
            cvs,
            creases,
            end_caps,
            local_points,
        };
        (patches, starts)
    }
}

/// Are `a` and `b` the same parameterization, bit for bit?
fn same_param(a: &PatchParam, b: &PatchParam) -> bool {
    a.ptex_face == b.ptex_face
        && a.depth == b.depth
        && a.rotation == b.rotation
        && a.triangular == b.triangular
        && a.origin.map(f32::to_bits) == b.origin.map(f32::to_bits)
}

// ----------------------------------------------------------------------
//  Parametric transforms
// ----------------------------------------------------------------------

/// Positions of a quad's corners in its unit parametric square.
const CORNER_UV: [[f32; 2]; 4] = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];

fn rotate_ccw(times: u32, x: f32, y: f32) -> (f32, f32) {
    match times % 4 {
        0 => (x, y),
        1 => (-y, x),
        2 => (-x, -y),
        _ => (y, -x),
    }
}

/// Select the child quadrant containing `(u, v)` and transform into the
/// child's parametric frame. Child `k` of a quad occupies the quarter at
/// corner `k`, rotated by `k`·90°: its corners are
/// `[corner_k, edge_k, center, edge_{k-1}]`.
fn descend_quadrant(u: f32, v: f32) -> (usize, f32, f32) {
    let k = match (u < 0.5, v < 0.5) {
        (true, true) => 0,
        (false, true) => 1,
        (false, false) => 2,
        (true, false) => 3,
    };
    let (x, y) = (u - CORNER_UV[k][0], v - CORNER_UV[k][1]);
    let (x, y) = rotate_ccw((4 - k as u32) % 4, x, y);
    (k, x * 2.0, y * 2.0)
}

/// Origins and rotations of the four children of a triangle within their
/// parent: the corner children are upright at the corners, the central
/// child inverted about the center.
const TRI_CHILD_ORIGIN: [[f32; 2]; 4] = [[0.0, 0.0], [0.5, 0.0], [0.0, 0.5], [0.5, 0.5]];
const TRI_CHILD_ROTATION: [usize; 4] = [0, 0, 0, 2];

/// Select the child sub-triangle containing `(u, v)` and transform into the
/// child's parametric frame (see [`TRI_CHILD_ORIGIN`]).
fn descend_triangle(u: f32, v: f32) -> (usize, f32, f32) {
    let k = if u >= 0.5 {
        1
    } else if v >= 0.5 {
        2
    } else if u + v >= 0.5 {
        3
    } else {
        0
    };
    let (x, y) = (u - TRI_CHILD_ORIGIN[k][0], v - TRI_CHILD_ORIGIN[k][1]);
    let (x, y) = rotate_ccw((4 - TRI_CHILD_ROTATION[k] as u32) % 4, x, y);
    (k, x * 2.0, y * 2.0)
}

/// Compute the [`PatchParam`] of a face of level `level` by walking its
/// ancestry down to the ptex root, composing the quadrant (or
/// sub-triangle) transforms `uv = origin_k + R_k · (child uv) / 2`.
fn compute_patch_param(
    refiner: &TopologyRefiner,
    ptex: &PtexIndices,
    first_child: &[Vec<Index>],
    face: usize,
    level: usize,
    triangular: bool,
) -> PatchParam {
    let mut origin = [0.0f32; 2];
    let mut rotation = 0u8;
    let mut depth = 0u8;
    let mut face = face;

    let compose = |origin: &mut [f32; 2], rotation: &mut u8, depth: &mut u8, k: usize| {
        let (child_origin, child_rotation) = if triangular {
            (TRI_CHILD_ORIGIN[k], TRI_CHILD_ROTATION[k])
        } else {
            (CORNER_UV[k], k)
        };
        let (x, y) = rotate_ccw(child_rotation as u32, origin[0], origin[1]);
        origin[0] = child_origin[0] + 0.5 * x;
        origin[1] = child_origin[1] + 0.5 * y;
        *rotation = ((*rotation as usize + child_rotation) % 4) as u8;
        *depth += 1;
    };

    // Steps between levels >= 2 are always children of a regular parent.
    for l in (2..=level).rev() {
        let parent = refiner.refinement(l).child_face_parent_face(face) as usize;
        let k = face - first_child[l - 1][parent] as usize;
        compose(&mut origin, &mut rotation, &mut depth, k);
        face = parent;
    }

    if level == 0 {
        // A base-level (regular) face is its own patch domain.
        return PatchParam {
            ptex_face: ptex.face_id(face),
            depth: 0,
            rotation: 0,
            origin: [0.0, 0.0],
            triangular,
        };
    }

    // The final step from level 1 to the base: for regular base faces it
    // is a regular child step of the (single) ptex face; for N-gons the
    // level-1 child *is* the ptex root.
    let base = refiner.refinement(1).child_face_parent_face(face) as usize;
    let k = face - first_child[0][base] as usize;
    if ptex.face_ptex_count(base) == 1 {
        compose(&mut origin, &mut rotation, &mut depth, k);
        PatchParam {
            ptex_face: ptex.face_id(base),
            depth,
            rotation,
            origin,
            triangular,
        }
    } else {
        PatchParam {
            ptex_face: ptex.face_id(base) + k as Index,
            depth,
            rotation,
            origin,
            triangular,
        }
    }
}

// ----------------------------------------------------------------------
//  Regular-patch classification and control-vertex gathering
// ----------------------------------------------------------------------

/// Is corner `corner` of `face` regular for the purpose of B-spline patch
/// extraction (`PatchBuilder::IsPatchRegular`, one corner)?
///
/// Regularity is decided by the *span* of faces around the vertex that
/// contains the face — the fan bounded by boundary edges and infinitely
/// sharp creases, which the limit surface treats alike:
///
/// * a smooth vertex must be interior with valence 4;
/// * a vertex on an infinitely sharp crease (exactly two infinitely sharp
///   edges) must be a regular boundary vertex, or an interior vertex whose
///   span on the patch's side holds exactly two faces;
/// * an infinitely sharp corner (a pinned vertex, or three or more
///   infinitely sharp edges) must have a single-face span;
/// * darts are never regular.
///
/// Semi-sharp features are never regular: adaptive refinement isolates
/// them until they decay (or the isolation cap is reached, where they are
/// capped with Gregory patches) — unless single-crease patches cover them
/// ([`single_crease_patch`]).
fn is_corner_regular(level: &Level, face: usize, corner: usize) -> bool {
    let v = level.face_vertices(face)[corner] as usize;
    let edges = level.vertex_edges(v);
    let num_faces = level.vertex_faces(v).len();
    let vertex_sharpness = level.vertex_sharpness(v);

    if Crease::is_semi_sharp(vertex_sharpness)
        || edges
            .iter()
            .any(|&e| Crease::is_semi_sharp(level.edge_sharpness(e as usize)))
    {
        return false;
    }
    let inf_edges = edges
        .iter()
        .filter(|&&e| Crease::is_infinite(level.edge_sharpness(e as usize)))
        .count();
    let boundary = level.is_vertex_boundary(v);
    let span_faces = || corner_span(level, face, corner, true).map(|span| span.num_faces());

    match vertex_rule(vertex_sharpness, inf_edges) {
        Rule::Smooth => !boundary && edges.len() == 4 && num_faces == 4,
        Rule::Dart => false,
        Rule::Crease => {
            if boundary {
                num_faces == 2 && edges.len() == 3
            } else {
                span_faces() == Some(2)
            }
        }
        Rule::Corner => inf_edges > 0 && span_faces() == Some(1),
        Rule::Unknown => false,
    }
}

/// The face across `edge` from `face`, or `None` when the edge is a wall of
/// the patch's neighborhood: a boundary, a non-manifold edge or an
/// infinitely sharp crease.
fn cross_edge(level: &Level, edge: Index, face: Index) -> Option<Index> {
    if is_edge_singular(level, edge, true) {
        return None;
    }
    let faces = level.edge_faces(edge as usize);
    Some(if faces[0] == face { faces[1] } else { faces[0] })
}

/// The neighbor of `v` within (quad) `face` that is not `exclude`.
fn neighbor_in_face(level: &Level, face: Index, v: Index, exclude: Index) -> Option<Index> {
    let fv = level.face_vertices(face as usize);
    if fv.len() != 4 {
        return None;
    }
    let i = fv.iter().position(|&x| x == v)?;
    let n = fv.len();
    let prev = fv[(i + n - 1) % n];
    let next = fv[(i + 1) % n];
    if prev == exclude {
        Some(next)
    } else if next == exclude {
        Some(prev)
    } else {
        None
    }
}

/// The vertex of (quad) `face` diagonally opposite `v`.
fn diagonal_in_face(level: &Level, face: Index, v: Index) -> Option<Index> {
    let fv = level.face_vertices(face as usize);
    if fv.len() != 4 {
        return None;
    }
    let i = fv.iter().position(|&x| x == v)?;
    Some(fv[(i + 2) % 4])
}

/// Attempt to classify `face` as a regular B-spline patch and gather its
/// 4x4 control-vertex grid; phantom slots (beyond a boundary or an
/// infinitely sharp crease) are `INDEX_INVALID`. Also used by adaptive
/// refinement to decide which faces need isolation.
///
/// The grid is row-major with rows along `t`:
///
/// ```text
///   12 13 14 15
///    8  9 10 11        with the face being the center quad
///    4  5  6  7        (5, 6, 10, 9) = (c0, c1, c2, c3).
///    0  1  2  3
/// ```
pub(super) fn gather_regular_patch(level: &Level, face: usize) -> Option<[Index; 16]> {
    let fv = level.face_vertices(face);
    if fv.len() != 4 {
        return None;
    }
    for corner in 0..4 {
        if !is_corner_regular(level, face, corner) {
            return None;
        }
    }
    gather_grid(level, face)
}

/// Gather the 4x4 control-vertex grid around (quad) `face`, laid out as in
/// [`gather_regular_patch`], without judging the corners' regularity.
fn gather_grid(level: &Level, face: usize) -> Option<[Index; 16]> {
    let fv = level.face_vertices(face);
    let [c0, c1, c2, c3] = [fv[0], fv[1], fv[2], fv[3]];
    let fe = level.face_edges(face);
    let face = face as Index;
    let mut cvs = [INDEX_INVALID; 16];
    cvs[5] = c0;
    cvs[6] = c1;
    cvs[10] = c2;
    cvs[9] = c3;

    // Row/column neighbors across the face's four edges (missing across
    // boundaries and infinitely sharp creases).
    let a0 = cross_edge(level, fe[0], face); // below  (row 0/1)
    let a1 = cross_edge(level, fe[1], face); // right  (col 3)
    let a2 = cross_edge(level, fe[2], face); // above  (row 3)
    let a3 = cross_edge(level, fe[3], face); // left   (col 0)

    if let Some(a) = a0 {
        cvs[1] = neighbor_in_face(level, a, c0, c1)?;
        cvs[2] = neighbor_in_face(level, a, c1, c0)?;
    }
    if let Some(a) = a1 {
        cvs[7] = neighbor_in_face(level, a, c1, c2)?;
        cvs[11] = neighbor_in_face(level, a, c2, c1)?;
    }
    if let Some(a) = a2 {
        cvs[14] = neighbor_in_face(level, a, c2, c3)?;
        cvs[13] = neighbor_in_face(level, a, c3, c2)?;
    }
    if let Some(a) = a3 {
        cvs[4] = neighbor_in_face(level, a, c0, c3)?;
        cvs[8] = neighbor_in_face(level, a, c3, c0)?;
    }

    // Diagonal (corner) faces, reached across the row-neighbor faces.
    cvs[0] = gather_corner_cv(level, a0, c0, cvs[1])?; // via A0 across edge (c0, cv1)
    cvs[3] = gather_corner_cv(level, a0, c1, cvs[2])?;
    cvs[15] = gather_corner_cv(level, a1, c2, cvs[11])?;
    cvs[12] = gather_corner_cv(level, a3, c3, cvs[8])?;

    // The phantom pattern must consist of complete missing border rows and
    // columns — anything else indicates an irregular configuration.
    let row0 = a0.is_none();
    let col3 = a1.is_none();
    let row3 = a2.is_none();
    let col0 = a3.is_none();
    for j in 0..4 {
        for i in 0..4 {
            let phantom_expected =
                (j == 0 && row0) || (j == 3 && row3) || (i == 0 && col0) || (i == 3 && col3);
            let is_phantom = cvs[4 * j + i] == INDEX_INVALID;
            if (1..3).contains(&i) && (1..3).contains(&j) {
                debug_assert!(!is_phantom);
            }
            if phantom_expected != is_phantom {
                return None;
            }
        }
    }
    Some(cvs)
}

/// The diagonal control vertex at a grid corner, found by crossing from the
/// row-neighbor face `a` over the edge `(c, inner)` into the corner face.
/// Returns `INDEX_INVALID` (a phantom slot) when the neighborhood ends at a
/// boundary or infinitely sharp crease, and `None` when a non-quad face
/// makes the patch irregular.
fn gather_corner_cv(level: &Level, a: Option<Index>, c: Index, inner: Index) -> Option<Index> {
    if let Some(a) = a {
        if inner != INDEX_INVALID {
            if let Some(edge) = level.find_edge(c, inner) {
                if let Some(d) = cross_edge(level, edge, a) {
                    // A non-quad corner face is disqualifying, not phantom.
                    return diagonal_in_face(level, d, c);
                }
            }
        }
    }
    Some(INDEX_INVALID)
}

/// A regular face with one semi-sharp crease along one of its edges
/// (`Vtr::Level::isSingleCreasePatch`).
#[derive(Debug, Clone, Copy)]
pub(super) struct SingleCrease {
    /// The complete 4x4 control-vertex grid, laid out as in
    /// [`gather_regular_patch`].
    pub(super) cvs: [Index; 16],
    /// The face edge carrying the crease (`0..4`, edge `k` joining corners
    /// `k` and `k + 1`).
    pub(super) edge: u8,
    /// The crease's sharpness at the face's level.
    pub(super) sharpness: f32,
}

/// Classify `face` as a single-crease patch: an interior quad whose four
/// corners are valence-4 vertices without vertex sharpness, crossed by a
/// single straight semi-sharp crease of uniform sharpness running along one
/// of its edges. Two corners are smooth (no sharp edge at all); the other
/// two are crease vertices whose only sharp edges are the face edge and its
/// straight continuation, both of the same sharpness.
///
/// Around such a face every mask of the refinement is the tensor product of
/// the cubic B-spline rule along the crease with a one-dimensional
/// semi-sharp crease rule across it — under `Uniform` and `Chaikin`
/// creasing alike, since the crease's sharpness is uniform — so the limit
/// surface is exactly the patch [`crease_basis`] evaluates.
pub(super) fn single_crease_patch(level: &Level, face: usize) -> Option<SingleCrease> {
    let fv = level.face_vertices(face);
    if fv.len() != 4 {
        return None;
    }
    for &v in fv {
        let v = v as usize;
        if level.is_vertex_boundary(v)
            || level.vertex_edges(v).len() != 4
            || level.vertex_faces(v).len() != 4
            || Crease::is_sharp(level.vertex_sharpness(v))
        {
            return None;
        }
    }

    let fe = level.face_edges(face);
    let mut crease = None;
    for (k, &e) in fe.iter().enumerate() {
        let sharpness = level.edge_sharpness(e as usize);
        if Crease::is_semi_sharp(sharpness) {
            if crease.is_some() {
                return None;
            }
            crease = Some((k, sharpness));
        } else if Crease::is_sharp(sharpness) {
            return None;
        }
    }
    let (k, sharpness) = crease?;
    let crease_edge = fe[k] as usize;

    for (corner, &v) in fv.iter().enumerate() {
        let on_crease = corner == k || corner == (k + 1) % 4;
        let mut sharp = level
            .vertex_edges(v as usize)
            .iter()
            .map(|&e| e as usize)
            .filter(|&e| Crease::is_sharp(level.edge_sharpness(e)));
        if !on_crease {
            if sharp.next().is_some() {
                return None;
            }
            continue;
        }
        // Exactly the crease edge and its straight continuation — the edge
        // sharing no face with it — both of the crease's sharpness.
        let others: Vec<usize> = sharp.filter(|&e| e != crease_edge).collect();
        let [other] = others[..] else {
            return None;
        };
        let crease_faces = level.edge_faces(crease_edge);
        if level.edge_sharpness(other) != sharpness
            || level
                .edge_faces(other)
                .iter()
                .any(|f| crease_faces.contains(f))
        {
            return None;
        }
    }

    let cvs = gather_grid(level, face)?;
    if cvs.contains(&INDEX_INVALID) {
        return None;
    }
    Some(SingleCrease {
        cvs,
        edge: k as u8,
        sharpness,
    })
}

/// Redistribute the weights of phantom (missing boundary) control-vertex
/// slots onto real slots via the reflection `p = 2a - b`: the B-spline
/// natural end-condition reproducing sharpened-boundary (crease) behavior,
/// and — after double reflection at corners — interpolating pinned corners.
fn fold_phantom_weights(cvs: &[Index; 16], weights: &mut [f32]) {
    // Which borders are actually missing (interior border slots are phantom
    // if and only if their whole row/column is).
    let row0 = cvs[1] == INDEX_INVALID;
    let row3 = cvs[13] == INDEX_INVALID;
    let col0 = cvs[4] == INDEX_INVALID;
    let col3 = cvs[7] == INDEX_INVALID;

    for _ in 0..2 {
        for j in 0..4usize {
            for i in 0..4usize {
                let slot = 4 * j + i;
                if cvs[slot] != INDEX_INVALID || weights[slot] == 0.0 {
                    continue;
                }
                // Reflect across the border the slot actually hangs off;
                // corner slots on two missing borders fold in two passes
                // (the reflections commute).
                let (a, b) = if j == 0 && row0 {
                    (4 + i, 8 + i) // reflect off rows 1, 2
                } else if j == 3 && row3 {
                    (8 + i, 4 + i)
                } else if i == 0 && col0 {
                    (4 * j + 1, 4 * j + 2) // reflect off cols 1, 2
                } else {
                    debug_assert!(i == 3 && col3);
                    (4 * j + 2, 4 * j + 1)
                };
                let w = weights[slot];
                weights[a] += 2.0 * w;
                weights[b] -= w;
                weights[slot] = 0.0;
            }
        }
    }
}

/// Uniform cubic B-spline basis functions (and derivatives) over the
/// central knot interval, `t ∈ [0, 1]`.
pub(crate) fn bspline_basis(t: f32) -> ([f32; 4], [f32; 4]) {
    let (b, d) = bspline_basis_f64(f64::from(t));
    (b.map(|x| x as f32), d.map(|x| x as f32))
}

/// Basis weights (and derivatives) across a semi-sharp crease of sharpness
/// `sharpness`: the limit curve over `[p0, p1]`, `t ∈ [0, 1]`, of control
/// points `(p-1, p0, p1, p2)` whose `p0` carries the crease — the profile of
/// a single-crease patch (Nießner et al., "Efficient Evaluation of
/// Semi-Smooth Creases in Catmull-Clark Subdivision Surfaces").
///
/// A fractional sharpness `n + f` is the crease rule applied `n` times and
/// blended with weight `f` at the next step, so the curve is the exact
/// linear blend of the curves of sharpness `n` and `n + 1`.
fn crease_basis(t: f32, sharpness: f32) -> ([f32; 4], [f32; 4]) {
    let n = sharpness.floor();
    let f = f64::from(sharpness - n);
    let t = f64::from(t);
    let (mut w, mut d) = integer_crease_basis(t, n as u32);
    if f > 0.0 {
        let (w1, d1) = integer_crease_basis(t, n as u32 + 1);
        for k in 0..4 {
            w[k] = (1.0 - f) * w[k] + f * w1[k];
            d[k] = (1.0 - f) * d[k] + f * d1[k];
        }
    }
    (w.map(|x| x as f32), d.map(|x| x as f32))
}

/// [`crease_basis`] for an integer sharpness `n`: `n` steps of the crease
/// rule, then smooth subdivision.
///
/// On the side of the crease, `n` crease steps refine the control polygon
/// exactly as an infinitely sharp crease would — as the B-spline whose
/// phantom point `2p0 - p1` replaces `p-1` — so beyond `h = 2^-n` the curve
/// is that of an infinitely sharp crease. Over `[0, h]` it is the B-spline
/// segment of the refined points at spacing `h`, whose point across the
/// crease is the true one: `p0 + h (p-1 - p0)`, refined by midpoints only.
fn integer_crease_basis(t: f64, n: u32) -> ([f64; 4], [f64; 4]) {
    let (b, db) = bspline_basis_f64(t);
    if n == 0 {
        return (b, db);
    }
    // Weights on (p-1, p0, p1, p2) of a p0 end with the phantom folded in.
    let fold = |x: [f64; 4]| [0.0, x[1] + 2.0 * x[0], x[2] - x[0], x[3]];
    let h = 0.5f64.powi(n as i32);
    if t >= h {
        return (fold(b), fold(db));
    }

    // Refine the window of points at indices -1..=2 around the crease, each
    // point as weights on (p-1, p0, p1, p2).
    let mut window = [
        [0.0, 2.0, -1.0, 0.0],
        [0.0, 1.0, 0.0, 0.0],
        [0.0, 0.0, 1.0, 0.0],
        [0.0, 0.0, 0.0, 1.0],
    ];
    let mix = |a: &[f64; 4], wa: f64, b: &[f64; 4], wb: f64, c: &[f64; 4], wc: f64| {
        [0, 1, 2, 3].map(|k| wa * a[k] + wb * b[k] + wc * c[k])
    };
    for _ in 0..n {
        let [q0, q1, q2, q3] = window;
        window = [
            mix(&q0, 0.5, &q1, 0.5, &q2, 0.0),
            mix(&q0, 0.125, &q1, 0.75, &q2, 0.125),
            mix(&q1, 0.5, &q2, 0.5, &q3, 0.0),
            mix(&q1, 0.125, &q2, 0.75, &q3, 0.125),
        ];
    }
    window[0] = [h, 1.0 - h, 0.0, 0.0];

    let (b, db) = bspline_basis_f64(t / h);
    let mut w = [0.0; 4];
    let mut d = [0.0; 4];
    for (point, weights) in window.iter().enumerate() {
        for k in 0..4 {
            w[k] += b[point] * weights[k];
            d[k] += db[point] / h * weights[k];
        }
    }
    (w, d)
}

/// [`bspline_basis`] in double precision.
fn bspline_basis_f64(t: f64) -> ([f64; 4], [f64; 4]) {
    let t2 = t * t;
    let t3 = t2 * t;
    let one_minus = 1.0 - t;
    let basis = [
        one_minus * one_minus * one_minus / 6.0,
        (3.0 * t3 - 6.0 * t2 + 4.0) / 6.0,
        (-3.0 * t3 + 3.0 * t2 + 3.0 * t + 1.0) / 6.0,
        t3 / 6.0,
    ];
    let deriv = [
        -0.5 * one_minus * one_minus,
        1.5 * t2 - 2.0 * t,
        -1.5 * t2 + t + 0.5,
        0.5 * t2,
    ];
    (basis, deriv)
}

/// The basis along one parametric direction of a single-crease patch whose
/// crease lies on the grid line at index 1 (`reversed == false`: `x = 0`)
/// or 2 (`reversed == true`: `x = 1`) of that direction.
pub(crate) fn crease_basis_oriented(
    x: f32,
    sharpness: f32,
    reversed: bool,
) -> ([f32; 4], [f32; 4]) {
    if !reversed {
        return crease_basis(x, sharpness);
    }
    let (w, d) = crease_basis(1.0 - x, sharpness);
    ([w[3], w[2], w[1], w[0]], [-d[3], -d[2], -d[1], -d[0]])
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::far::{AdaptiveOptions, TopologyDescriptor, TopologyRefinerFactory};
    use crate::sdc;

    fn param(depth: u8, rotation: u8, cell: [u32; 2], triangular: bool) -> PatchParam {
        let scale = (1u32 << depth) as f32;
        let corner = CORNER_UV[rotation as usize];
        PatchParam {
            ptex_face: 0xdead_beef,
            depth,
            rotation,
            origin: [0, 1].map(|k| (cell[k] as f32 + corner[k]) / scale),
            triangular,
        }
    }

    #[test]
    fn packed_params_round_trip_up_to_max_depth() {
        for depth in 0..=PatchParam::MAX_DEPTH {
            let last = (1u32 << depth) - 1;
            for rotation in 0..4 {
                for cell in [
                    [0, 0],
                    [last, 0],
                    [0, last],
                    [last, last],
                    [last / 3, last / 2],
                ] {
                    for triangular in [false, true] {
                        let p = param(depth, rotation, cell, triangular);
                        let packed = PackedPatchParam::pack(&p).unwrap();
                        assert!(same_param(&packed.unpack(), &p), "{p:?}");
                    }
                }
            }
        }
        let too_deep = param(PatchParam::MAX_DEPTH + 1, 0, [0, 0], false);
        assert!(PackedPatchParam::pack(&too_deep).is_none());
    }

    /// The factory checks every packed parameter against the computed one
    /// (a debug assertion); these tables reach every rotation, N-gon ptex
    /// roots and inverted triangles.
    #[test]
    fn tables_store_every_orientation_exactly() {
        // A pentagon ringed by quads, and a triangulated grid.
        let mut pentagon = (vec![5], vec![0, 1, 2, 3, 4]);
        for i in 0..5u32 {
            let j = (i + 1) % 5;
            pentagon.0.push(4);
            pentagon.1.extend([j, i, i + 5, j + 5]);
        }
        let mut tris = (Vec::new(), Vec::new());
        for j in 0..3u32 {
            for i in 0..3u32 {
                let v = j * 4 + i;
                tris.0.extend([3, 3]);
                tris.1.extend([v, v + 1, v + 5, v, v + 5, v + 4]);
            }
        }
        let options = sdc::Options::default()
            .with_vtx_boundary_interpolation(sdc::VtxBoundaryInterpolation::EdgeAndCorner);
        let mut seen = Vec::new();
        for (num_verts, mesh, scheme) in [
            (10, &pentagon, sdc::SchemeType::Catmark),
            (16, &tris, sdc::SchemeType::Loop),
        ] {
            let descriptor = TopologyDescriptor::new(num_verts, &mesh.0, &mesh.1);
            let mut refiner = TopologyRefinerFactory::create(descriptor, scheme, options).unwrap();
            refiner.refine_adaptive(AdaptiveOptions::new(3));
            let table = PatchTableFactory::create(&refiner).unwrap();
            for p in 0..table.num_patches() {
                let param = table.patch_param(p);
                seen.push((param.triangular, param.rotation));
            }
        }
        for expected in [
            (false, 0),
            (false, 1),
            (false, 2),
            (false, 3),
            (true, 0),
            (true, 2),
        ] {
            assert!(seen.contains(&expected), "no patch at {expected:?}");
        }
    }
}