alice-physics 3.0.1

Deterministic physics engine: 128-bit fixed-point rigid bodies with bit-exact, replayable results, typed observation and rollback for search and planning, plus FEM, CFD and 3D-print analysis modules
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
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
//! Swept and overlap queries against the geometry a [`PhysicsWorld`] actually
//! collides with.
//!
//! [`crate::query::sphere_cast`], [`crate::query::capsule_cast`],
//! [`crate::query::overlap_sphere`] and [`crate::query::overlap_aabb`] test each
//! body's bounding sphere (or its position) and see no static or SDF collider.
//! The world methods here test the same geometry as
//! [`PhysicsWorld::cast_ray`] (see [`crate::shape_raycast`]): body shapes,
//! compound children, planes, height fields, triangle meshes and (`std` only) SDF
//! colliders.
//!
//! | method | query |
//! |---|---|
//! | [`PhysicsWorld::cast_sphere`] | a sphere swept along a direction, nearest hit |
//! | [`PhysicsWorld::cast_capsule`] | a capsule (segment `a`–`b` grown by a radius) swept along a direction, nearest hit |
//! | [`PhysicsWorld::overlap_sphere`] | every collider a sphere overlaps |
//! | [`PhysicsWorld::overlap_aabb`] | every collider an axis-aligned box overlaps |
//!
//! # How each geometry is tested
//!
//! A swept sphere of radius `r` first touches a solid `S` where its centre
//! reaches the boundary of the Minkowski sum `S ⊕ ball(r)`; a ray against that sum
//! is used wherever it has a closed form:
//!
//! | geometry | sphere cast | capsule cast |
//! |---|---|---|
//! | sphere (body radius, compound child) | ray vs sphere of `R + r` | ray from the sphere's centre along `−direction` vs the capsule grown by `R` |
//! | box (shape, compound child) | ray vs rounded box (3 slabs + 12 edge capsules) | convex time of impact |
//! | cylinder | ray vs rounded cylinder (2 cylinders + 2 rim tori) | convex time of impact |
//! | torus | ray vs torus of tube `minor + r` | arcs of the ring: time of impact against each arc's hull grown by `minor`, arcs split until the hull is within `2⁻³²` of the arc |
//! | compound capsule | ray vs capsule of `radius + r` | convex time of impact |
//! | cone, ellipsoid, wedge, convex hull child | convex time of impact | convex time of impact |
//! | plane | closed form (two-sided) | closed form at the nearer end |
//! | triangle mesh | per triangle: the two offset triangles + 3 edge capsules | convex time of impact per triangle |
//! | height field | per cell: time of impact against the hull of the cell's corners, the cell split into parts until each hull is within `2⁻³²` of the surface (a planar cell is its own hull) | the same, with the segment |
//! | SDF (`std`) | sphere tracing of `field − r` | sphere tracing of the field minimum along the segment |
//!
//! Overlaps use the distance from the sphere's centre to the geometry (closed form
//! for spheres, capsules, boxes, cylinders, tori, planes and triangles, GJK for the
//! other convex pieces). A box overlaps a convex piece when GJK finds them
//! intersecting, a plane when the plane passes between its corners, a height field
//! when the surface heights over the box's footprint (the bilinear surface takes
//! its extremes at the corners of each cell's part of the footprint) reach into
//! its `Y` range, and an SDF when an octree subdivision of the box finds a point
//! inside.
//!
//! # Conventions
//!
//! Those of [`crate::shape_raycast`], with these additions:
//!
//! - The direction need not be unit length; it is normalized and `t` is a
//!   **distance** along it. A zero direction or `max_t ≤ 0` gives no hit.
//! - A negative radius is not a sphere: no hit, no overlap. Radius `0` is allowed:
//!   [`PhysicsWorld::cast_sphere`] with radius `0` **is** [`PhysicsWorld::cast_ray`]
//!   (same target, `t`, point and normal), and an overlap of radius `0` is a point
//!   strictly inside a solid.
//! - A capsule whose two ends coincide is a sphere: [`PhysicsWorld::cast_capsule`]
//!   then returns [`PhysicsWorld::cast_sphere`].
//! - A cast that starts overlapping a collider by more than `2⁻³²` reports it at
//!   `t = 0`, normal `−direction`, point the cast shape's centre (the sphere's
//!   centre, the capsule segment's midpoint). Otherwise the hit's point is the
//!   contact point on the collider and the normal is the collider's surface
//!   normal there, pointing toward the cast shape (for surfaces: toward the side
//!   the shape comes from).
//! - A cast that starts touching a collider (within `2⁻³²`) hits it at `t = 0`
//!   only when the direction goes into the surface (`direction·normal < 0`);
//!   moving away from it or along it is not a hit, and the cast goes on to what
//!   lies further along the path. The same holds wherever a cast touches a
//!   surface on its way: a contact whose direction is within `2⁻⁶` of the
//!   tangent plane is a hit only if the path then goes more than `2⁻³²` into
//!   that piece, so a shape resting on a mesh floor or a flat height field
//!   crosses the edges between triangles and cells.
//! - Touching is not overlapping: an overlap needs a distance below the radius
//!   (or, for boxes against convex pieces, a GJK intersection).
//! - Ties in `t` are broken by target (bodies, then static colliders, then SDF
//!   colliders, each by index); overlaps are returned sorted by target. Neither
//!   depends on the order the BVH visits bodies in.
//! - An [`AABB`] with `min > max` on any axis contains nothing.
//!
//! # Precision
//!
//! Closed-form paths are exact up to `Fix128` truncation and the CORDIC rotations,
//! like the ray queries (`tests/analytic_world_shape_query.rs` checks them to
//! `1e-12`).
//!
//! The convex time of impact steps by Newton's method on the gap `g(t)` (GJK
//! distance less the radii; GJK stops when its bound is within `2⁻⁴⁰` of the
//! distance). For two convex sets moving apart linearly `g` is convex in `t`,
//! so the tangent's root never passes the first contact, and a gap that is not
//! decreasing proves there is none. It stops when the gap is below `2⁻³²`
//! (checked to `1e-9`); a grazing approach converges linearly instead of
//! quadratically but still in a few dozen steps (an approach `0.1°` from
//! tangent is checked). Meshes, height-field cells and torus arcs are split into
//! convex parts, so moving along one part (a mesh floor) costs nothing against
//! another (a wall of the same mesh).
//!
//! **No missed hits:** a cast reports no hit only when there is none within
//! `max_t` (to the `2⁻³²` gap tolerance). If a step budget runs out (a part
//! hierarchy deeper than its node budget, an SDF traced for more than 4096
//! steps), the cast reports the earliest position it could not rule out, which
//! is never after the true contact.
//!
//! A bilinear height-field cell restricted to a rectangle of its `(u, v)` is
//! again bilinear with its four corners as control points, so it lies inside
//! their convex hull, within a quarter of the part's twist `|h00 − h10 − h01 +
//! h11|·Δu·Δv` of it. Distances to a cell are found by branch-and-bound over
//! such parts (the hull distance bounds a part from below), so they never
//! exceed the true distance by more than `2⁻³²`; casts take the earliest hull
//! contact over parts, splitting a part until its hull is that close to it, so
//! a cast never moves past the surface. The contact is then moved onto the
//! surface by Newton's method. Cells are visited in the order the swept shape
//! reaches their boxes. Segment distances to tori and
//! SDFs minimise a 1-Lipschitz point distance along the segment by
//! branch-and-bound to `2⁻¹⁶` and golden-section refinement after it. SDF fields
//! are `f32`: a hit is where `field − r` drops below [`crate::sdf_ccd::SdfCcdConfig::tolerance`].
//!
//! Author: Moroya Sakamoto

use crate::body_collider::BodyCollider;
use crate::collider::{Capsule, Support, AABB};
use crate::compound::{CompoundChild, ShapeRef};
use crate::heightfield::HeightField;
use crate::math::{Fix128, QuatFix, Vec3Fix};
use crate::plane_collider::PlaneCollider;
#[cfg(feature = "std")]
use crate::sdf_ccd::SdfCcdConfig;
use crate::shape::{PosedShape, Shape};
use crate::shape_raycast::{
    box_planes, nearer, ray_local_cylinder, ray_local_torus, ray_planes, ray_solid_capsule,
    ray_solid_sphere, to_local, to_world, torus_distance, LocalHit, RayFilter, RayTarget,
    PARALLEL_EPSILON,
};
use crate::solver::PhysicsWorld;
use crate::static_collider::StaticCollider;
use crate::trimesh::{ray_triangle, TriMesh, Triangle};

#[cfg(not(feature = "std"))]
use alloc::{vec, vec::Vec};

/// Conservative advancement stops when the gap is below this: `2⁻³²`.
const TRACE_TOLERANCE: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0000_0001_0000_0000,
};

/// A touching contact whose motion is closer than this to the surface's tangent
/// plane (`|d·n| < 2⁻⁶`) is a hit only if the path then goes more than
/// [`TRACE_TOLERANCE`] into the piece (see [`dips_below`]); a steeper one is.
const NEAR_TANGENT: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0400_0000_0000_0000,
};

/// Newton steps of a convex time of impact before the last clear time is
/// reported (it needs a few dozen at most, even at a grazing approach).
const TRACE_MAX_STEPS: usize = 1024;

/// Sphere-tracing steps for an SDF before the last position is reported.
#[cfg(feature = "std")]
const SDF_MAX_STEPS: usize = 4096;

/// GJK stops when `|v|² − v·w ≤ |v|² · 2⁻⁴⁰`.
const GJK_RELATIVE: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0000_0000_0100_0000,
};

/// GJK treats `|v|² ≤ 2⁻⁶⁴` as intersecting: `|v| ≤ 2⁻³²`, the conservative
/// advancement tolerance. `lo` is a 64-bit fraction (`lo = 1` is `2⁻⁶⁴`, the
/// smallest positive `Fix128`), so this is the smallest threshold a squared
/// length can be compared with; a larger one (`lo = 1 << 48` is `2⁻¹⁶`, `|v| ≤
/// 2⁻⁸`) would count any pair nearer than about `0.0039` as intersecting.
const GJK_INTERSECT: Fix128 = Fix128 { hi: 0, lo: 1 };

const GJK_MAX_ITERATIONS: usize = 64;

/// Branch-and-bound along a segment stops subdividing below this bound gap:
/// `2⁻¹⁶`.
const CURVE_COARSE: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0001_0000_0000_0000,
};

/// Golden-section steps after the branch-and-bound (shrinks by `0.618⁶⁴`).
const GOLDEN_STEPS: usize = 64;

/// Branch-and-bound node budget per minimisation.
const CURVE_MAX_NODES: usize = 256;

/// Branch-and-bound parts per height-field cell distance.
const CELL_MAX_NODES: usize = 512;

/// Parts expanded per hierarchical time of impact (one height-field cell).
const TREE_MAX_NODES: usize = 1024;

/// SDF box overlap: octree depth.
#[cfg(feature = "std")]
const SDF_BOX_DEPTH: u32 = 10;

// ============================================================================
// Public types
// ============================================================================

/// A hit of [`PhysicsWorld::cast_sphere`] or [`PhysicsWorld::cast_capsule`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct WorldShapeHit {
    /// Distance the shape travels along the (normalized) direction before it
    /// touches.
    pub t: Fix128,
    /// The contact point on the collider (the cast shape's centre for a cast that
    /// starts overlapping; see the module conventions).
    pub point: Vec3Fix,
    /// Unit surface normal of the collider at the contact, toward the cast shape
    /// (`−direction` for a cast that starts overlapping).
    pub normal: Vec3Fix,
    /// The collider hit.
    pub target: RayTarget,
    /// The body the hit belongs to, as in [`crate::shape_raycast::WorldRayHit::body`].
    pub body: Option<usize>,
}

/// One collider a capsule overlaps (see [`PhysicsWorld::capsule_penetrations`]).
#[derive(Clone, Copy, Debug)]
pub(crate) struct Penetration {
    /// The collider.
    pub(crate) target: RayTarget,
    /// How far the capsule reaches into it, `r −` the segment's distance (`> 0`).
    pub(crate) depth: Fix128,
    /// Unit normal of the collider at the nearest point, toward the segment:
    /// moving the capsule by `depth · normal` makes it touch.
    pub(crate) normal: Vec3Fix,
}

// ============================================================================
// Distances
// ============================================================================

/// The distance from a query core (a point or a segment) to one piece of geometry.
#[derive(Clone, Copy, Debug)]
enum Dist {
    /// The core meets the inside of a solid (or lies on a surface).
    Inside,
    /// The nearest point of the geometry, its distance and the unit normal there
    /// pointing toward the core.
    Outside {
        dist: Fix128,
        point: Vec3Fix,
        normal: Vec3Fix,
    },
    /// Nothing nearer than this.
    AtLeast(Fix128),
}

impl Dist {
    /// A lower bound on the distance (`−1` inside), for comparisons.
    fn value(&self) -> Fix128 {
        match *self {
            Self::Inside => Fix128::NEG_ONE,
            Self::Outside { dist, .. } => dist,
            Self::AtLeast(d) => d,
        }
    }

    /// Whether a sphere of `r` about the core overlaps the geometry.
    fn within(&self, r: Fix128) -> bool {
        match *self {
            Self::Inside => true,
            Self::Outside { dist, .. } => dist < r,
            Self::AtLeast(_) => false,
        }
    }

    /// The outside distance from `core` to `point`, the normal toward the core.
    fn toward(core: Vec3Fix, point: Vec3Fix) -> Self {
        let (n, dist) = (core - point).normalize_with_length();
        if dist.is_zero() {
            return Self::Inside;
        }
        Self::Outside {
            dist,
            point,
            normal: n,
        }
    }

    /// This distance less `amount` (the core grown, a solid's radius).
    fn shrunk(self, amount: Fix128) -> Self {
        match self {
            Self::Outside {
                dist,
                point,
                normal,
            } => {
                let d = dist - amount;
                if d.is_negative() {
                    Self::Inside
                } else {
                    Self::Outside {
                        dist: d,
                        point: point + normal * amount,
                        normal,
                    }
                }
            }
            Self::AtLeast(d) => Self::AtLeast(d - amount),
            Self::Inside => Self::Inside,
        }
    }
}

/// Whether a cast of radius `r` starts overlapping a piece at distance `d`: more
/// than [`TRACE_TOLERANCE`] inside it. Within the tolerance it is touching, and
/// the sweep decides by the direction of motion.
fn starts_overlapping(d: &Dist, r: Fix128) -> bool {
    match *d {
        Dist::Inside => true,
        Dist::Outside { dist, .. } => dist + TRACE_TOLERANCE < r,
        Dist::AtLeast(_) => false,
    }
}

fn half_vec(v: Vec3Fix) -> Vec3Fix {
    Vec3Fix::new(v.x.half(), v.y.half(), v.z.half())
}

fn min_fix(a: Fix128, b: Fix128) -> Fix128 {
    if b < a {
        b
    } else {
        a
    }
}

fn max_fix(a: Fix128, b: Fix128) -> Fix128 {
    if b > a {
        b
    } else {
        a
    }
}

/// Below this squared length (`|v| < 2⁻¹⁶`) a length or direction is taken from
/// `v` scaled up by a power of two: `length_squared` keeps only multiples of
/// `2⁻⁶⁴`, so `|v|` near `2⁻³²` would have one or two significant bits.
const FINE_LENGTH_SQUARED: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0000_0001_0000_0000,
};

/// `2⁻¹⁶`, the square root of [`FINE_LENGTH_SQUARED`].
const FINE_LENGTH: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0001_0000_0000_0000,
};

/// `v · 2ᵏ` with the largest component in `[1, 2)` and that `k`, for
/// `0 < |v| < 1` (`k > 0`, an exact scaling); zero gives `(ZERO, 0)`.
fn scaled_up(v: Vec3Fix) -> (Vec3Fix, u32) {
    let raw = |f: Fix128| ((f.hi as i128) << 64) | (f.lo as i128);
    let (x, y, z) = (raw(v.x), raw(v.y), raw(v.z));
    let m = x.unsigned_abs().max(y.unsigned_abs()).max(z.unsigned_abs());
    if m == 0 {
        return (Vec3Fix::ZERO, 0);
    }
    // bit 64 is 1.0
    let msb = 127 - m.leading_zeros();
    if msb >= 64 {
        return (v, 0);
    }
    let k = 64 - msb;
    let up = |r: i128| {
        let s = r << k;
        Fix128::from_raw((s >> 64) as i64, s as u64)
    };
    (Vec3Fix::new(up(x), up(y), up(z)), k)
}

/// `|v|`, accurate for a short `v` too (measured on `v` scaled up, see
/// [`FINE_LENGTH_SQUARED`]); `None` for zero. A `v` not shorter than `2⁻¹⁶`
/// gives `v.length()`.
fn fine_length(v: Vec3Fix) -> Option<Fix128> {
    if v.length_squared() >= FINE_LENGTH_SQUARED {
        let len = v.length();
        return (!len.is_zero()).then_some(len);
    }
    let (s, k) = scaled_up(v);
    let len = s.length();
    if len.is_zero() {
        return None;
    }
    let back = (((len.hi as i128) << 64) | (len.lo as i128)) >> k;
    Some(Fix128::from_raw((back >> 64) as i64, back as u64))
}

fn clamp(x: Fix128, lo: Fix128, hi: Fix128) -> Fix128 {
    max_fix(lo, min_fix(x, hi))
}

/// The point of segment `a`–`b` nearest `p`.
fn closest_on_segment(a: Vec3Fix, b: Vec3Fix, p: Vec3Fix) -> Vec3Fix {
    let ab = b - a;
    let len2 = ab.length_squared();
    if len2.is_zero() {
        return a;
    }
    a + ab * clamp((p - a).dot(ab) / len2, Fix128::ZERO, Fix128::ONE)
}

/// The point of `aabb` nearest `p` (the point itself inside).
fn closest_on_aabb(aabb: &AABB, p: Vec3Fix) -> Vec3Fix {
    Vec3Fix::new(
        clamp(p.x, aabb.min.x, aabb.max.x),
        clamp(p.y, aabb.min.y, aabb.max.y),
        clamp(p.z, aabb.min.z, aabb.max.z),
    )
}

/// A point, for GJK.
struct PointSupport(Vec3Fix);

impl Support for PointSupport {
    fn support(&self, _direction: Vec3Fix) -> Vec3Fix {
        self.0
    }
}

/// A segment, for GJK.
struct SegmentSupport(Vec3Fix, Vec3Fix);

impl Support for SegmentSupport {
    fn support(&self, direction: Vec3Fix) -> Vec3Fix {
        if self.1.dot(direction) > self.0.dot(direction) {
            self.1
        } else {
            self.0
        }
    }
}

/// A triangle, for GJK.
struct TriangleSupport<'a>(&'a Triangle);

impl Support for TriangleSupport<'_> {
    fn support(&self, direction: Vec3Fix) -> Vec3Fix {
        let t = self.0;
        let (d0, d1, d2) = (
            t.v0.dot(direction),
            t.v1.dot(direction),
            t.v2.dot(direction),
        );
        if d1 > d0 && d1 >= d2 {
            t.v1
        } else if d2 > d0 && d2 > d1 {
            t.v2
        } else {
            t.v0
        }
    }
}

/// A compound child placed in the world, for GJK.
struct ChildSupport<'a> {
    child: &'a CompoundChild,
    position: Vec3Fix,
    rotation: QuatFix,
}

/// An ellipsoid, whose support mapping normalizes its direction, given that
/// direction scaled up to a largest component
/// in `[1, 2)`: GJK's direction near a contact is about as long as the gap, and
/// such a mapping (which leaves directions down to `2⁻²⁴` unscaled) loses that
/// many bits of the support point, enough to put it about `2⁻³²` off the
/// surface. The scaling is exact and the direction unchanged. Polytopes are not
/// wrapped: their support compares dot products, and a different rounding would
/// only pick another of two tied vertices. Cylinders and cones are not wrapped
/// either: their support jumps between the rims (and the apex), and with the
/// scaled direction casts onto their sides went further in, and some stopped
/// early, so they keep the previous support direction.
struct RoundSupport<'a>(&'a PosedShape);

impl Support for RoundSupport<'_> {
    fn support(&self, direction: Vec3Fix) -> Vec3Fix {
        self.0.support(scaled_up(direction).0)
    }
}

/// Whether a posed shape is wrapped in [`RoundSupport`] (an ellipsoid).
fn is_round(posed: &PosedShape) -> bool {
    matches!(posed.shape, Shape::Ellipsoid { .. })
}

impl Support for ChildSupport<'_> {
    fn support(&self, direction: Vec3Fix) -> Vec3Fix {
        self.child
            .support_world(direction, self.position, self.rotation)
    }
}

/// One vertex of a GJK simplex: the Minkowski-difference point and the two
/// support points it came from.
#[derive(Clone, Copy)]
struct Vertex {
    w: Vec3Fix,
    a: Vec3Fix,
    b: Vec3Fix,
}

fn vertex<A: Support, B: Support>(a: &A, b: &B, direction: Vec3Fix) -> Vertex {
    let pa = a.support(direction);
    let pb = b.support(-direction);
    Vertex {
        w: pa - pb,
        a: pa,
        b: pb,
    }
}

/// A sub-simplex, its weights, and whether it is a face whose barycentric
/// weights are not precise (see [`closest_on_triangle`] and [`gjk_distance`]).
type Nearest = (Vec<Vertex>, Vec<Fix128>, bool);

/// The point of the simplex nearest the origin, the sub-simplex it lies on and
/// its barycentric weights; `None` when the origin is inside a tetrahedron.
///
/// The weights are the same for the simplex scaled about the origin, and are
/// computed on it scaled up by `2ᵏ` (exactly) when its edges are shorter than
/// [`SMALL_SIMPLEX`]: their dot products, of the size of an edge to the fourth
/// power, would otherwise keep few significant bits (on a curved surface the
/// simplex shrinks around the nearest point as GJK converges).
fn closest_on_simplex(s: &[Vertex]) -> Option<Nearest> {
    let k = simplex_scale(s);
    if k == 0 {
        return closest_on_scaled_simplex(s, 0);
    }
    let up: Vec<Vertex> = s
        .iter()
        .map(|v| Vertex {
            w: shift_vec(v.w, k as i32),
            ..*v
        })
        .collect();
    let (sub, lambda, face) = closest_on_scaled_simplex(&up, k)?;
    let sub = sub
        .into_iter()
        .map(|v| Vertex {
            w: shift_vec(v.w, -(k as i32)),
            ..v
        })
        .collect();
    Some((sub, lambda, face))
}

/// [`closest_on_simplex`] for `s` scaled up by `2ᵏ`.
fn closest_on_scaled_simplex(s: &[Vertex], k: u32) -> Option<Nearest> {
    match s.len() {
        1 => Some((s.to_vec(), vec![Fix128::ONE], false)),
        2 => {
            let (sub, lambda) = closest_on_edge(s[0], s[1]);
            Some((sub, lambda, false))
        }
        3 => Some(closest_on_triangle(s[0], s[1], s[2])),
        _ => closest_on_tetrahedron(s[0], s[1], s[2], s[3], k),
    }
}

/// A simplex whose edges have every component below this (`2⁻⁸`) is scaled up
/// for its barycentric weights (see [`closest_on_simplex`]).
const SMALL_SIMPLEX_BITS: u32 = 56;

/// The `k` that brings the largest edge component of `s` to `[1, 2)`, `0` when
/// it is at least `2⁻⁸` (or the simplex is a point), and limited so that no
/// vertex gets a component of `2²⁴` or more.
fn simplex_scale(s: &[Vertex]) -> u32 {
    let raw = |f: Fix128| ((f.hi as i128) << 64) | (f.lo as i128);
    let mag = |v: Vec3Fix| {
        raw(v.x)
            .unsigned_abs()
            .max(raw(v.y).unsigned_abs())
            .max(raw(v.z).unsigned_abs())
    };
    let Some(first) = s.first() else {
        return 0;
    };
    let edge = s.iter().map(|v| mag(v.w - first.w)).max().unwrap_or(0);
    if edge == 0 {
        return 0;
    }
    // bit 64 is 1.0
    let msb = 127 - edge.leading_zeros();
    if msb >= SMALL_SIMPLEX_BITS {
        return 0;
    }
    let far = s.iter().map(|v| mag(v.w)).max().unwrap_or(0);
    let far_msb = 127 - far.leading_zeros();
    // keep components below 2²⁴ (bit 88)
    (64 - msb).min(88u32.saturating_sub(far_msb))
}

/// `v · 2ᵏ` (`k` may be negative), exact when no bit leaves the range.
fn shift_vec(v: Vec3Fix, k: i32) -> Vec3Fix {
    let raw = |f: Fix128| ((f.hi as i128) << 64) | (f.lo as i128);
    let sh = |f: Fix128| {
        let r = raw(f);
        let s = if k >= 0 { r << k } else { r >> (-k) };
        Fix128::from_raw((s >> 64) as i64, s as u64)
    };
    Vec3Fix::new(sh(v.x), sh(v.y), sh(v.z))
}

fn closest_on_edge(a: Vertex, b: Vertex) -> (Vec<Vertex>, Vec<Fix128>) {
    let ab = b.w - a.w;
    let len2 = ab.length_squared();
    let t = if len2.is_zero() {
        Fix128::ZERO
    } else {
        -a.w.dot(ab) / len2
    };
    if t <= Fix128::ZERO {
        (vec![a], vec![Fix128::ONE])
    } else if t >= Fix128::ONE {
        (vec![b], vec![Fix128::ONE])
    } else {
        (vec![a, b], vec![Fix128::ONE - t, t])
    }
}

/// [`log2_size`] of zero.
const NO_SIZE: i32 = i32::MIN / 4;

/// `⌊log₂⌋` of the largest component of `v` ([`NO_SIZE`] for zero).
fn log2_size(v: Vec3Fix) -> i32 {
    let raw = |f: Fix128| ((f.hi as i128) << 64) | (f.lo as i128);
    let m = raw(v.x)
        .unsigned_abs()
        .max(raw(v.y).unsigned_abs())
        .max(raw(v.z).unsigned_abs());
    if m == 0 {
        return NO_SIZE;
    }
    // bit 64 is 1.0
    63 - m.leading_zeros() as i32
}

/// Whether the barycentric form gives `point`, the nearest point of triangle
/// `a b c`, to within `2⁻³²` of its length, so that its direction (GJK's next
/// search direction) is within `2⁻³²` rad. The ratio does not depend on a
/// scaling of the simplex.
///
/// Its region tests and weights are differences of products of two dot
/// products: each dot product of vectors of sizes `L` (an edge) and `P` (a
/// vertex) is rounded to about `2⁻⁶²·(L + P)`, so a weight, such a difference
/// over `|n|²` (`n = (b − a) × (c − a)`), is off by about `2⁻⁶²·L·P / |n|²`,
/// and the point by `L` times that. On a curved solid the simplex near the
/// surface is a long thin triangle of support points far from the origin
/// (`|n|` a small fraction of `L²`): the point was off by up to `2⁻²⁶` there,
/// its direction turned the next support back to a vertex already in the
/// simplex, and GJK stopped up to `2⁻²⁶` away from the surface. The faces of
/// the polytopes cast at (boxes, wedges, meshes) stay well below the bound and
/// keep the barycentric form. The sizes are taken from the leading bits of
/// the components, so the estimate is within a factor of 8.
fn barycentric_is_precise(a: Vertex, b: Vertex, c: Vertex, point: Vec3Fix) -> bool {
    let ab = b.w - a.w;
    let ac = c.w - a.w;
    let n = log2_size(ab.cross(ac));
    let near = log2_size(point);
    if n == NO_SIZE || near == NO_SIZE {
        return false;
    }
    let l = log2_size(ab).max(log2_size(ac)).max(log2_size(c.w - b.w));
    let p = log2_size(a.w).max(log2_size(b.w)).max(log2_size(c.w));
    // log₂ of the point's error over its length
    -62 + 2 * l + p - 2 * n - near <= -32
}

/// The point of triangle `a b c` nearest the origin: by
/// [`closest_on_triangle_barycentric`] when that is precise (see
/// [`barycentric_is_precise`]), otherwise by [`closest_on_triangle_by_area`]
/// (the third element tells [`gjk_distance`] that it is such a face).
fn closest_on_triangle(a: Vertex, b: Vertex, c: Vertex) -> Nearest {
    let (sub, lambda) = closest_on_triangle_barycentric(a, b, c);
    if barycentric_is_precise(a, b, c, weighted(&(sub.clone(), lambda.clone()))) {
        return (sub, lambda, false);
    }
    let (sub, lambda) = closest_on_triangle_by_area(a, b, c);
    let face = sub.len() == 3;
    (sub, lambda, face)
}

/// The point of triangle `a b c` nearest the origin, its sub-simplex and
/// weights, for a triangle whose barycentric form is not precise (see
/// [`barycentric_is_precise`]). The regions are decided by the signed areas
/// `n·((q − p) × (o − p))` of the origin `o` projected on the plane, one per
/// edge `p q` (`n = (b − a) × (c − a)`, scaled up to a largest component in
/// `[1, 2)`): each is one cross product of edge vectors and a dot product, so
/// its rounding is about `2⁻⁶²` of the size of the triangle, and a weight,
/// such an area over their sum `n·n`, is off by that over `|n|`. The
/// barycentric form ([`closest_on_triangle_barycentric`]) takes the same
/// quantities as differences of products of dot products, whose weights are
/// off by that size squared over `|n|²`.
///
/// When the origin is outside an edge (a negative area), the nearest point is
/// on such an edge (the nearest point of a convex polygon to a point outside it
/// is on an edge whose line separates them), and the nearest of those edges is
/// taken.
fn closest_on_triangle_by_area(a: Vertex, b: Vertex, c: Vertex) -> (Vec<Vertex>, Vec<Fix128>) {
    let ab = b.w - a.w;
    let ac = c.w - a.w;
    let bc = c.w - b.w;
    let n = scaled_up(ab.cross(ac)).0;
    // the area for the edge opposite each vertex (positive inside)
    let area_a = n.dot(bc.cross(-b.w));
    let area_b = n.dot((-ac).cross(-c.w));
    let area_c = n.dot(ab.cross(-a.w));
    let sum = area_a + area_b + area_c;
    if n.length_squared().is_zero() || sum <= Fix128::ZERO {
        // A degenerate (flat) triangle: the nearest of its edges.
        let mut best = closest_on_edge(a, b);
        for cand in [closest_on_edge(b, c), closest_on_edge(a, c)] {
            if shorter(weighted(&cand), weighted(&best)) {
                best = cand;
            }
        }
        return best;
    }
    if !area_a.is_negative() && !area_b.is_negative() && !area_c.is_negative() {
        let (wb, wc) = (area_b / sum, area_c / sum);
        return (vec![a, b, c], vec![Fix128::ONE - wb - wc, wb, wc]);
    }
    let mut best: Option<(Vec<Vertex>, Vec<Fix128>)> = None;
    for (area, p, q) in [(area_c, a, b), (area_a, b, c), (area_b, a, c)] {
        if !area.is_negative() {
            continue;
        }
        let cand = closest_on_edge(p, q);
        if best
            .as_ref()
            .is_none_or(|b| shorter(weighted(&cand), weighted(b)))
        {
            best = Some(cand);
        }
    }
    // not reached: one of the areas is negative here
    best.unwrap_or_else(|| (vec![a], vec![Fix128::ONE]))
}

/// Ericson, *Real-Time Collision Detection* §5.1.5, for the origin.
fn closest_on_triangle_barycentric(a: Vertex, b: Vertex, c: Vertex) -> (Vec<Vertex>, Vec<Fix128>) {
    let ab = b.w - a.w;
    let ac = c.w - a.w;
    let ap = -a.w;
    let d1 = ab.dot(ap);
    let d2 = ac.dot(ap);
    if d1 <= Fix128::ZERO && d2 <= Fix128::ZERO {
        return (vec![a], vec![Fix128::ONE]);
    }
    let bp = -b.w;
    let d3 = ab.dot(bp);
    let d4 = ac.dot(bp);
    if d3 >= Fix128::ZERO && d4 <= d3 {
        return (vec![b], vec![Fix128::ONE]);
    }
    let vc = d1 * d4 - d3 * d2;
    if vc <= Fix128::ZERO && d1 >= Fix128::ZERO && d3 <= Fix128::ZERO {
        let v = d1 / (d1 - d3);
        return (vec![a, b], vec![Fix128::ONE - v, v]);
    }
    let cp = -c.w;
    let d5 = ab.dot(cp);
    let d6 = ac.dot(cp);
    if d6 >= Fix128::ZERO && d5 <= d6 {
        return (vec![c], vec![Fix128::ONE]);
    }
    let vb = d5 * d2 - d1 * d6;
    if vb <= Fix128::ZERO && d2 >= Fix128::ZERO && d6 <= Fix128::ZERO {
        let w = d2 / (d2 - d6);
        return (vec![a, c], vec![Fix128::ONE - w, w]);
    }
    let va = d3 * d6 - d5 * d4;
    if va <= Fix128::ZERO && d4 - d3 >= Fix128::ZERO && d5 - d6 >= Fix128::ZERO {
        let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
        return (vec![b, c], vec![Fix128::ONE - w, w]);
    }
    let denom = va + vb + vc;
    if denom <= Fix128::ZERO {
        // A degenerate (flat) triangle: the nearest of its edges.
        let mut best = closest_on_edge(a, b);
        for cand in [closest_on_edge(b, c), closest_on_edge(a, c)] {
            if weighted(&cand).length_squared() < weighted(&best).length_squared() {
                best = cand;
            }
        }
        return best;
    }
    let v = vb / denom;
    let w = vc / denom;
    (vec![a, b, c], vec![Fix128::ONE - v - w, v, w])
}

/// The nearest point of tetrahedron `a b c d` (scaled up by `2ᵏ`), `None` when
/// the origin is inside it.
///
/// A tetrahedron whose least height (the volume `n·(d − a)` over its largest
/// face's `|n|`, both from differences of its vertices) is at most `h = 2⁻³²`
/// (in unscaled units) is taken as flat: four support points on one circle or
/// one generator of a curved solid are coplanar but for rounding, and the
/// sign of such a volume (and of the origin's side of a face) is that
/// rounding, which counted the origin inside and reported an intersection far
/// from the surface. Its nearest face is returned instead: every point of the
/// flat tetrahedron is within `h` of a face, so an origin inside it is within
/// `h` of that face, and GJK then stops at its own intersection tolerance
/// (`|v| ≤ 2⁻³²`).
fn closest_on_tetrahedron(a: Vertex, b: Vertex, c: Vertex, d: Vertex, k: u32) -> Option<Nearest> {
    let faces = [(a, b, c, d), (a, c, d, b), (a, d, b, c), (b, d, c, a)];
    let flat_height = if k >= 32 {
        Fix128::from_raw(1i64 << (k - 32), 0)
    } else {
        Fix128::from_raw(0, 1u64 << (32 + k))
    };
    let flat = faces.iter().any(|&(p, q, r, opposite)| {
        let n = (q.w - p.w).cross(r.w - p.w);
        n.dot(opposite.w - p.w).abs() <= n.length() * flat_height
    });
    let mut best: Option<Nearest> = None;
    let mut inside = true;
    for (p, q, r, opposite) in faces {
        let n = (q.w - p.w).cross(r.w - p.w);
        let origin_side = n.dot(-p.w);
        let other_side = n.dot(opposite.w - p.w);
        // The origin is outside this face when it is strictly on the other side
        // from the fourth vertex.
        let outside = other_side.is_zero()
            || (!origin_side.is_zero() && origin_side.is_negative() != other_side.is_negative());
        if outside {
            inside = false;
        }
        if outside || flat {
            let cand = closest_on_triangle(p, q, r);
            if best
                .as_ref()
                .is_none_or(|b| shorter(nearest_point(&cand), nearest_point(b)))
            {
                best = Some(cand);
            }
        }
    }
    if inside && !flat {
        None
    } else {
        best
    }
}

/// Whether `x` is shorter than `y`. Squared lengths keep multiples of `2⁻⁶⁴`
/// only, so two candidate points about `2⁻³²` from the origin (GJK's last
/// steps) differ by less than one unit there and the first was kept whichever
/// was nearer: below `2⁻¹⁶` the lengths are compared on the vectors scaled up
/// ([`fine_length`]). Longer vectors are compared by their squared lengths as
/// before.
fn shorter(x: Vec3Fix, y: Vec3Fix) -> bool {
    let (xx, yy) = (x.length_squared(), y.length_squared());
    if xx >= FINE_LENGTH_SQUARED && yy >= FINE_LENGTH_SQUARED {
        return xx < yy;
    }
    let len = |v: Vec3Fix| fine_length(v).unwrap_or(Fix128::ZERO);
    len(x) < len(y)
}

/// The point of a [`Nearest`] by its weights.
fn nearest_point(n: &Nearest) -> Vec3Fix {
    n.0.iter()
        .zip(&n.1)
        .fold(Vec3Fix::ZERO, |acc, (v, &l)| acc + v.w * l)
}

/// The point of the line or plane through the sub-simplex `s` (1 to 3 vertices,
/// the one [`closest_on_simplex`] chose) nearest the origin, by projection: when
/// the simplex is near the origin its barycentric combination cancels terms of
/// the size of its vertices and keeps few significant bits, while `a − (a·ê)ê`
/// and `(a·n̂)n̂` lose only rounding of that size.
fn nearest_on_affine_hull(s: &[Vertex]) -> Vec3Fix {
    match *s {
        [a] => a.w,
        [a, b] => {
            let e = scaled_up(b.w - a.w).0;
            let ee = e.length_squared();
            if ee.is_zero() {
                return a.w;
            }
            a.w - e * (a.w.dot(e) / ee)
        }
        [a, b, c, ..] => {
            let n = scaled_up((b.w - a.w).cross(c.w - a.w)).0;
            let nn = n.length_squared();
            if nn.is_zero() {
                return a.w;
            }
            n * (a.w.dot(n) / nn)
        }
        [] => Vec3Fix::ZERO,
    }
}

fn weighted(s: &(Vec<Vertex>, Vec<Fix128>)) -> Vec3Fix {
    s.0.iter()
        .zip(&s.1)
        .fold(Vec3Fix::ZERO, |acc, (v, &l)| acc + v.w * l)
}

/// The distance between two convex sets by GJK: `(distance, point on a, point on
/// b)`, or `None` when they intersect (closer than `2⁻³²`).
///
/// # A face whose barycentric weights are not precise
///
/// Near a curved surface the simplex is a long thin triangle of support points
/// (see [`barycentric_is_precise`]); its weights come from signed areas
/// ([`closest_on_triangle_by_area`]). `v` is then its projection on the
/// face's plane ([`nearest_on_affine_hull`]), both as the next search
/// direction and as the distance (`u = 2⁻⁶⁴`, `L` its longest edge, `P` its
/// farthest vertex, `N` twice its area, `D` the distance; measured on the
/// faces of the casts in `tests/analytic_world_query_curved_casts.rs` and
/// `tests/analytic_world_query_precision.rs` against the nearest point in
/// exact rational arithmetic): the plane's normal is off by less than
/// `2√3·u / N` rad (each component of the cross product of two exact edges is
/// truncated by less than `2u`), `9·10⁻¹¹` rad or less on those faces, and the
/// projected length by up to `2√3·P·u / N` either way, within `10⁻⁶·2⁻³²` on
/// them. The point within the face, from the area weights, is off along the
/// face by `δ < 60·L·u / N`, so its direction by `δ / D`, which grows as `D`
/// drops: `9·10⁻⁷` rad at `D ≈ 1.3·2⁻³²`, where support points along it
/// repeated and GJK stopped at `1.3·2⁻³²` from a segment that reached
/// `2.7·2⁻³²` into an ellipsoid. Where the projected length's error could
/// matter (a time of impact near its tolerance), the lower bound below and
/// an exact distance decide (see [`toi_convex_refined`]).
///
/// The witness `pa − pb` is `v`.
///
/// # A lower bound
///
/// [`gjk_bounds`] also returns `lower`, the largest `v̂·w` over the
/// iterations (`w` the support point toward `−v`), capped by the distance. In
/// exact arithmetic every point `x` of the Minkowski difference has
/// `v̂·x ≥ v̂·w`, since `w` minimises `v̂·x` over it, so
///
/// `dist ≥ v̂·w`
///
/// for every `v`, whatever GJK did afterwards (a simplex that stops on a face
/// without enclosing the origin leaves the distance it reports above the true
/// one, not this). Only the support points can lift `v̂·w` above it: a
/// computed support point `w̃` that lies `e` farther along `v̂` than the true
/// minimiser gives `v̂·w̃ ≤ dist + e`, so `lower − e ≤ dist` with `e` the
/// support's error toward the core. For a posed cylinder or cone it is the rim
/// point taken on the axis for a direction within `2⁻⁴²` of it
/// (`Vec3Fix::rescaled_xz`: lower by `radius·√2·2⁻⁴²` along it) and a few
/// `2⁻⁶⁴` of rounding per unit of coordinate, `e ≤ radius·2⁻⁴¹ + 2⁻⁵⁶`
/// ([`round_support_slack`]), which [`convex_bounds`] subtracts; the products
/// `u·w / |u|` add a few `2⁻⁶⁴`, inside that. The test
/// `the_lower_bound_is_not_above_the_distance` checks `lower ≤ dist` against an
/// independent `f64` distance.
///
/// # Stopping
///
/// The loop stops as before: at `|v| ≤ 2⁻³²` (intersecting), when the support
/// point gains less than `2⁻⁴⁰` of `|v|²`, repeats a vertex, or the new nearest
/// point is no nearer (`v` compared as before: its length, on the scaled
/// vector below `2⁻¹⁶`). A flat tetrahedron counts as intersecting exactly when
/// the origin is within `2⁻³²` of one of its faces ([`closest_on_tetrahedron`]),
/// and candidate points are compared by [`shorter`]. Callers:
/// [`convex_dist`] (casts, overlaps of spheres and capsules), [`segment_segment`],
/// [`cell_dist`] (height-field cells) and the box overlaps of
/// [`Piece::meets_aabb`] (a capsule's against its radius, the others only
/// `None`, an intersection).
fn gjk_distance<A: Support, B: Support>(a: &A, b: &B) -> Option<(Fix128, Vec3Fix, Vec3Fix)> {
    gjk_bounds(a, b).map(|g| (g.dist, g.pa, g.pb))
}

/// The result of [`gjk_bounds`].
struct GjkBounds {
    /// The distance, as [`gjk_distance`] reports it.
    dist: Fix128,
    /// The witness points on `a` and `b`.
    pa: Vec3Fix,
    pb: Vec3Fix,
    /// A lower bound on the distance (see [`gjk_distance`] § A lower bound).
    lower: Fix128,
    /// Whether the distance was taken on a face whose weights are not
    /// precise.
    face: bool,
}

/// [`gjk_distance`] with a lower bound on the distance.
fn gjk_bounds<A: Support, B: Support>(a: &A, b: &B) -> Option<GjkBounds> {
    let mut simplex = vec![vertex(a, b, Vec3Fix::UNIT_X)];
    let mut weights = vec![Fix128::ONE];
    let mut v = simplex[0].w;
    // `v` was projected on a face whose weights are not precise (see the doc
    // above).
    let mut on_face = false;
    // The largest `v̂·w` seen (see § A lower bound).
    let mut lower = Fix128::ZERO;
    for _ in 0..GJK_MAX_ITERATIONS {
        let vv = v.length_squared();
        if vv <= GJK_INTERSECT {
            return None;
        }
        // A short `v` is compared through `u`, `v` scaled up: `|v|² − v·w ≤
        // |v|²·ε` is `u·(v − w) ≤ (u·v)·ε`, whose terms keep their precision
        // where `|v|²` is a few multiples of `2⁻⁶⁴`.
        let fine = vv < FINE_LENGTH_SQUARED;
        let u = if fine { scaled_up(v).0 } else { v };
        let w = vertex(a, b, -u);
        if let Some(len) = fine_length(u) {
            let support = u.dot(w.w) / len;
            if support > lower {
                lower = support;
            }
        }
        let converged = if fine {
            u.dot(v - w.w) <= u.dot(v) * GJK_RELATIVE
        } else {
            vv - v.dot(w.w) <= vv * GJK_RELATIVE
        };
        if converged {
            break;
        }
        if simplex.iter().any(|s| s.w == w.w) {
            break;
        }
        let mut grown = simplex.clone();
        grown.push(w);
        let (sub, lambda, face) = closest_on_simplex(&grown)?;
        let next = if fine || face {
            nearest_on_affine_hull(&sub)
        } else {
            weighted(&(sub.clone(), lambda.clone()))
        };
        let no_progress = if fine {
            // Both short: compare the lengths measured on the scaled vectors.
            let len = |x: Vec3Fix| fine_length(x).unwrap_or(Fix128::ZERO);
            len(next) >= len(v)
        } else {
            next.length_squared() >= vv
        };
        if no_progress {
            // No progress (rounding): keep the previous simplex.
            break;
        }
        on_face = face;
        simplex = sub;
        weights = lambda;
        v = next;
    }
    let pa = simplex
        .iter()
        .zip(&weights)
        .fold(Vec3Fix::ZERO, |acc, (s, &l)| acc + s.a * l);
    let pb = simplex
        .iter()
        .zip(&weights)
        .fold(Vec3Fix::ZERO, |acc, (s, &l)| acc + s.b * l);
    let len = fine_length(v)?;
    if on_face || v.length_squared() < FINE_LENGTH_SQUARED {
        // `v` is projected (see `nearest_on_affine_hull`), the weights are not
        // as precise: the witness on `a` is taken as `pb + v`, so that `pa − pb`
        // is `v` exactly.
        return Some(GjkBounds {
            dist: len,
            pa: pb + v,
            pb,
            lower: min_fix(lower, len),
            face: on_face,
        });
    }
    Some(GjkBounds {
        dist: len,
        pa,
        pb,
        lower: min_fix(lower, len),
        face: false,
    })
}

/// The distance from the core `a`–`b` to a convex set, by GJK.
fn convex_dist<S: Support>(a: Vec3Fix, b: Vec3Fix, solid: &S) -> Dist {
    convex_bounds(a, b, solid, Fix128::ZERO).0
}

/// [`convex_dist`] and its [`Bound`], the lower bound less `slack`: how far
/// `solid`'s support points can be from its true ones toward the core (see
/// [`gjk_distance`] § A lower bound).
fn convex_bounds<S: Support>(a: Vec3Fix, b: Vec3Fix, solid: &S, slack: Fix128) -> (Dist, Bound) {
    let found = if a == b {
        gjk_bounds(&PointSupport(a), solid)
    } else {
        gjk_bounds(&SegmentSupport(a, b), solid)
    };
    match found {
        None => (
            Dist::Inside,
            Bound {
                lower: Fix128::ZERO,
                step_lower: false,
            },
        ),
        Some(g) => (
            Dist::Outside {
                dist: g.dist,
                point: g.pb,
                normal: gjk_normal(g.pa - g.pb, g.dist),
            },
            Bound {
                lower: max_fix(g.lower - slack, Fix128::ZERO),
                step_lower: g.face,
            },
        ),
    }
}

/// A lower bound on a piece's distance from the core, for [`toi_by`].
#[derive(Clone, Copy)]
struct Bound {
    /// Not above the distance (see [`gjk_distance`] § A lower bound).
    lower: Fix128,
    /// Whether the time of impact steps by `lower` rather than by the distance:
    /// for a distance taken on a face whose weights are not precise.
    step_lower: bool,
}

impl Bound {
    /// For a distance known exactly (a closed form): the distance itself.
    fn exact(d: &Dist) -> Self {
        let lower = match *d {
            Dist::Outside { dist, .. } => dist,
            _ => Fix128::ZERO,
        };
        Self {
            lower,
            step_lower: false,
        }
    }
}

/// The unit normal along `diff` (`pa − pb` of [`gjk_distance`]) of length
/// `dist`: `diff / dist`, or for a short `diff` the scaled-up `diff` normalized,
/// since a quotient of two lengths near `2⁻³²` is unit only to about `2⁻³³`.
fn gjk_normal(diff: Vec3Fix, dist: Fix128) -> Vec3Fix {
    if diff.length_squared() >= FINE_LENGTH_SQUARED {
        return diff / dist;
    }
    let s = scaled_up(diff).0;
    s / s.length()
}

/// The distance between two segments `p0`–`p1` and `q0`–`q1`, by GJK on the two
/// segments: `(distance, point on p, point on q)`, `None` when they cross.
fn segment_segment(
    p0: Vec3Fix,
    p1: Vec3Fix,
    q0: Vec3Fix,
    q1: Vec3Fix,
) -> Option<(Fix128, Vec3Fix, Vec3Fix)> {
    if p0 == p1 && q0 == q1 {
        let (_, d) = (p0 - q0).normalize_with_length();
        return (!d.is_zero()).then_some((d, p0, q0));
    }
    if p0 == p1 {
        let q = closest_on_segment(q0, q1, p0);
        let d = (p0 - q).length();
        return (!d.is_zero()).then_some((d, p0, q));
    }
    if q0 == q1 {
        let p = closest_on_segment(p0, p1, q0);
        let d = (p - q0).length();
        return (!d.is_zero()).then_some((d, p, q0));
    }
    gjk_distance(&SegmentSupport(p0, p1), &SegmentSupport(q0, q1))
}

/// The distance from the core `a`–`b` to a solid sphere.
fn sphere_dist(a: Vec3Fix, b: Vec3Fix, center: Vec3Fix, radius: Fix128) -> Dist {
    let s = closest_on_segment(a, b, center);
    let (n, d) = (s - center).normalize_with_length();
    if d < radius || d.is_zero() {
        return Dist::Inside;
    }
    Dist::Outside {
        dist: d - radius,
        point: center + n * radius,
        normal: n,
    }
}

/// The distance from the core `a`–`b` to a solid capsule.
fn capsule_dist(a: Vec3Fix, b: Vec3Fix, capsule: &Capsule) -> Dist {
    match segment_segment(a, b, capsule.a, capsule.b) {
        None => Dist::Inside,
        Some((d, pa, pb)) => Dist::Outside {
            dist: d,
            point: pb,
            normal: gjk_normal(pa - pb, d),
        }
        .shrunk(capsule.radius),
    }
}

/// The distance from `p` to a solid box of half-extents `h` about the origin, in
/// its frame.
fn point_box_local(p: Vec3Fix, h: Vec3Fix) -> Dist {
    if p.x.abs() < h.x && p.y.abs() < h.y && p.z.abs() < h.z {
        return Dist::Inside;
    }
    let q = Vec3Fix::new(
        clamp(p.x, -h.x, h.x),
        clamp(p.y, -h.y, h.y),
        clamp(p.z, -h.z, h.z),
    );
    if q == p {
        // On the boundary: touching, with the normal of a face it lies on.
        let axis = |v: Fix128, e: Fix128, unit: Vec3Fix| {
            (v.abs() == e).then(|| if v.is_negative() { -unit } else { unit })
        };
        let z = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ONE);
        let normal = axis(p.x, h.x, Vec3Fix::UNIT_X)
            .or_else(|| axis(p.y, h.y, Vec3Fix::UNIT_Y))
            .or_else(|| axis(p.z, h.z, z))
            .unwrap_or(Vec3Fix::UNIT_Y);
        return Dist::Outside {
            dist: Fix128::ZERO,
            point: p,
            normal,
        };
    }
    Dist::toward(p, q)
}

/// The distance from `p` to a solid cylinder along `Y` (radius `radius`, half
/// height `hh`), in its frame.
fn point_cylinder_local(p: Vec3Fix, radius: Fix128, hh: Fix128) -> Dist {
    let (dir, rho) = Vec3Fix::new(p.x, Fix128::ZERO, p.z).normalize_with_length();
    let qy = clamp(p.y, -hh, hh);
    if rho < radius && p.y.abs() < hh {
        return Dist::Inside;
    }
    let qr = min_fix(rho, radius);
    let q = if rho.is_zero() {
        Vec3Fix::new(Fix128::ZERO, qy, Fix128::ZERO)
    } else {
        Vec3Fix::new(dir.x * qr, qy, dir.z * qr)
    };
    if (q - p).length_squared().is_zero() {
        // On the boundary: touching, with the cap or side normal there.
        let normal = if p.y.abs() == hh {
            if p.y.is_negative() {
                -Vec3Fix::UNIT_Y
            } else {
                Vec3Fix::UNIT_Y
            }
        } else {
            dir
        };
        return Dist::Outside {
            dist: Fix128::ZERO,
            point: p,
            normal,
        };
    }
    Dist::toward(p, q)
}

/// The distance from `core` to `point` with a length accurate for a short
/// difference ([`fine_length`]), `Inside` when they coincide.
fn toward_fine(core: Vec3Fix, point: Vec3Fix) -> Dist {
    let diff = core - point;
    match fine_length(diff) {
        None => Dist::Inside,
        Some(dist) => Dist::Outside {
            dist,
            point,
            normal: gjk_normal(diff, dist),
        },
    }
}

/// `p`'s part across the `Y` axis turned to length `len` (`0 ≤ len ≤ ρ`, `ρ`
/// that part's length): `(x, z)·len/ρ`, or `p`'s own `(x, z)` when `len = ρ`.
fn toward_axis(p: Vec3Fix, rho: Fix128, len: Fix128) -> (Fix128, Fix128) {
    if len >= rho || rho.is_zero() {
        return (p.x, p.z);
    }
    let k = len / rho;
    (p.x * k, p.z * k)
}

/// The exact distance from `p` to a solid cylinder along `Y` (radius `radius`,
/// half height `hh`), in its frame: the nearest point is `p` clamped to the
/// cylinder, its part across the axis shortened to `radius` (taken as `p`'s own
/// when within it, so no rounding of a length enters), and the length is
/// [`fine_length`] of the difference.
fn point_cylinder_exact(p: Vec3Fix, radius: Fix128, hh: Fix128) -> Dist {
    let rho = fine_length(Vec3Fix::new(p.x, Fix128::ZERO, p.z)).unwrap_or(Fix128::ZERO);
    if rho < radius && p.y.abs() < hh {
        return Dist::Inside;
    }
    let (x, z) = toward_axis(p, rho, min_fix(rho, radius));
    toward_fine(p, Vec3Fix::new(x, clamp(p.y, -hh, hh), z))
}

/// The exact distance from `p` to a solid cone along `Y` (apex at `hh`, base of
/// `radius` at `−hh`), in its frame. In the half plane `(ρ, y)` of `p` the cone
/// is the triangle `(0, −hh)`, `(0, hh)`, `(radius, −hh)`; a point outside it is
/// nearest to its side `(0, hh)`–`(radius, −hh)` or its base, whichever is
/// nearer, and that point is turned back about the axis.
fn point_cone_exact(p: Vec3Fix, radius: Fix128, hh: Fix128) -> Dist {
    let rho = fine_length(Vec3Fix::new(p.x, Fix128::ZERO, p.z)).unwrap_or(Fix128::ZERO);
    let height = hh.double();
    if p.y >= -hh && rho * height <= radius * (hh - p.y) {
        return Dist::Inside;
    }
    let at = |q_rho: Fix128, q_y: Fix128| {
        let (x, z) = toward_axis(p, rho, q_rho);
        Vec3Fix::new(x, q_y, z)
    };
    // the base disc
    let base = at(min_fix(rho, radius), -hh);
    // the side: (0, hh) + s·(radius, −2hh), s clamped to [0, 1]
    let len2 = radius * radius + height * height;
    let s = clamp(
        (rho * radius - (p.y - hh) * height) / len2,
        Fix128::ZERO,
        Fix128::ONE,
    );
    let side = at(radius * s, hh - height * s);
    if shorter(p - side, p - base) {
        toward_fine(p, side)
    } else {
        toward_fine(p, base)
    }
}

/// How far a posed cylinder's or cone's support point can be from the true one
/// toward a direction: its rim point is replaced by the point on the axis for
/// a direction within `2⁻⁴²` of the axis (`Vec3Fix::rescaled_xz`), which is
/// `radius·√2·2⁻⁴²` lower along it, and the rim point is rounded by a few
/// `2⁻⁶⁴` per unit of coordinate (the normalization and the turn, below
/// `2⁻⁵⁶` for coordinates up to `2⁴`): `radius·2⁻⁴¹ + 2⁻⁵⁶`.
fn round_support_slack(posed: &PosedShape) -> Fix128 {
    let radius = match posed.shape {
        Shape::Cylinder { radius, .. } | Shape::Cone { radius, .. } => radius.abs(),
        _ => Fix128::ZERO,
    };
    let scaled = |r: Fix128, k: i32| {
        let raw = ((r.hi as i128) << 64) | (r.lo as i128);
        let s = raw >> k;
        Fix128::from_raw((s >> 64) as i64, s as u64)
    };
    scaled(radius, 41) + Fix128::from_raw(0, 1 << 8)
}

/// The exact distance from the core `a`–`b` to a posed cylinder or cone, `None`
/// for other shapes: the point distance in the solid's frame, minimised along
/// the segment by [`segment_min`].
fn exact_round_dist(posed: &PosedShape, a: Vec3Fix, b: Vec3Fix) -> Option<Dist> {
    let (center, rotation) = posed_frame(posed);
    let inv = rotation.conjugate();
    let point: fn(Vec3Fix, Fix128, Fix128) -> Dist = match posed.shape {
        Shape::Cylinder { .. } => point_cylinder_exact,
        Shape::Cone { .. } => point_cone_exact,
        _ => return None,
    };
    let (radius, hh) = match posed.shape {
        Shape::Cylinder {
            radius,
            half_height,
        }
        | Shape::Cone {
            radius,
            half_height,
        } => (radius, half_height),
        _ => return None,
    };
    // `rotation` is unit only to `2⁻³²` in its squared norm `n²`, and the
    // support mappings place the solid at `center + q v q*` = `n²·R v`: the
    // solid's own frame is `q* (x − center) q / n⁴` and its lengths are `n²`
    // times the world's (a turn from `from_axis_angle` has `n²` within about
    // `2⁻⁴⁶` of 1, which moved a point on a cap by `2⁻¹⁴·2⁻³²`).
    let n2 = rotation.length_squared();
    let n4 = n2 * n2;
    let f = |q: Vec3Fix| match point(inv.rotate_vec(q - center) / n4, radius, hh) {
        Dist::Outside {
            dist,
            point,
            normal,
        } => Dist::Outside {
            dist: dist * n2,
            point: center + rotation.rotate_vec(point),
            normal: rotation.rotate_vec(normal) / n2,
        },
        other => other,
    };
    Some(segment_min(a, b, f))
}

/// The distance from `p` to a solid torus (ring `major` in `XZ`, tube `minor`), in
/// its frame.
fn point_torus_local(p: Vec3Fix, major: Fix128, minor: Fix128) -> Dist {
    if torus_distance(p, major, minor).is_negative() {
        return Dist::Inside;
    }
    let (ring_dir, rho) = Vec3Fix::new(p.x, Fix128::ZERO, p.z).normalize_with_length();
    let ring_dir = if rho.is_zero() {
        Vec3Fix::UNIT_X
    } else {
        ring_dir
    };
    let ring = ring_dir * major;
    match Dist::toward(p, ring) {
        Dist::Outside { dist, normal, .. } => Dist::Outside {
            dist,
            point: ring,
            normal,
        }
        .shrunk(minor),
        other => other,
    }
}

/// A distance in a solid's frame turned back into the world.
fn dist_to_world(d: Dist, center: Vec3Fix, rotation: QuatFix) -> Dist {
    match d {
        Dist::Outside {
            dist,
            point,
            normal,
        } => Dist::Outside {
            dist,
            point: center + rotation.rotate_vec(point),
            normal: rotation.rotate_vec(normal),
        },
        other => other,
    }
}

/// The minimum over `s ∈ [0, 1]` of an `L`-Lipschitz distance `f(s)`:
/// branch-and-bound to [`CURVE_COARSE`], then golden-section refinement about
/// the best node. `f` may report [`Dist::AtLeast`] (a lower bound).
fn curve_min(lipschitz: Fix128, f: impl Fn(Fix128) -> Dist) -> Dist {
    const SEEDS: i64 = 16;
    // (s, half width of its node, distance)
    let mut best: Option<(Fix128, Fix128, Dist)> = None;
    // Open nodes: (midpoint, half width, lower bound).
    let mut stack: Vec<(Fix128, Fix128, Fix128)> = Vec::new();
    let seed_half = Fix128::from_ratio(1, 2 * SEEDS);
    let mut nodes = 0usize;
    let mut todo: Vec<(Fix128, Fix128)> = (0..SEEDS)
        .map(|k| (Fix128::from_ratio(2 * k + 1, 2 * SEEDS), seed_half))
        .collect();
    loop {
        for (m, hw) in todo.drain(..) {
            let d = f(m);
            if matches!(d, Dist::Inside) {
                return Dist::Inside;
            }
            if best.as_ref().is_none_or(|(_, _, b)| d.value() < b.value()) {
                best = Some((m, hw, d));
            }
            // A node's lower bound: the Lipschitz cone below its midpoint value.
            stack.push((m, hw, d.value() - lipschitz * hw));
        }
        let best_value = best.as_ref().map_or(Fix128::ZERO, |(_, _, b)| b.value());
        // Drop the nodes that cannot hold a value below the best by more than the
        // coarse tolerance, and the ones already narrow enough.
        stack.retain(|&(_, hw, bound)| {
            bound < best_value - CURVE_COARSE && lipschitz * hw > CURVE_COARSE
        });
        // Best first: the lowest bound (the first such node on a tie).
        let Some(k) = (0..stack.len()).min_by_key(|&k| stack[k].2) else {
            break;
        };
        nodes += 1;
        if nodes > CURVE_MAX_NODES {
            break;
        }
        let (mid, hw, _) = stack.remove(k);
        let quarter = hw.half();
        todo.push((mid - quarter, quarter));
        todo.push((mid + quarter, quarter));
    }
    let Some((s_best, hw_best, d_best)) = best else {
        return Dist::AtLeast(Fix128::ZERO);
    };
    // Golden-section over the best node and its neighbours.
    let mut lo = max_fix(Fix128::ZERO, s_best - hw_best.double());
    let mut hi = min_fix(Fix128::ONE, s_best + hw_best.double());
    let ratio = Fix128::from_ratio(618_033_988_749_895, 1_000_000_000_000_000);
    let mut x1 = hi - (hi - lo) * ratio;
    let mut x2 = lo + (hi - lo) * ratio;
    let mut f1 = f(x1);
    let mut f2 = f(x2);
    let mut refined = d_best;
    for _ in 0..GOLDEN_STEPS {
        for d in [f1, f2] {
            if matches!(d, Dist::Inside) {
                return Dist::Inside;
            }
            if d.value() < refined.value() {
                refined = d;
            }
        }
        if f1.value() <= f2.value() {
            hi = x2;
            x2 = x1;
            f2 = f1;
            x1 = hi - (hi - lo) * ratio;
            f1 = f(x1);
        } else {
            lo = x1;
            x1 = x2;
            f1 = f2;
            x2 = lo + (hi - lo) * ratio;
            f2 = f(x2);
        }
    }
    refined
}

/// The distance from the segment `a`–`b` to a geometry given by its point
/// distance `f`.
fn segment_min(a: Vec3Fix, b: Vec3Fix, f: impl Fn(Vec3Fix) -> Dist) -> Dist {
    if a == b {
        return f(a);
    }
    let ab = b - a;
    curve_min(ab.length(), |s| f(a + ab * s))
}

// ============================================================================
// Height fields
// ============================================================================

/// Whether the field has a surface (see [`crate::shape_raycast`]).
fn field_has_surface(field: &HeightField) -> bool {
    field.width >= 2 && field.depth >= 2 && field.spacing > Fix128::ZERO
}

/// The cell range `[lo, hi]` (clamped to the grid) covering `[x0, x1]` along an
/// axis with `n` points.
fn cell_range(
    x0: Fix128,
    x1: Fix128,
    origin: Fix128,
    spacing: Fix128,
    n: u32,
) -> Option<(u32, u32)> {
    let last = i64::from(n) - 2;
    let lo = ((x0 - origin) / spacing).floor().hi;
    let hi = ((x1 - origin) / spacing).floor().hi;
    if hi < 0 || lo > last {
        return None;
    }
    Some((lo.clamp(0, last) as u32, hi.clamp(0, last) as u32))
}

/// The world `(x, z)` of cell `(gx, gz)`'s first corner.
fn cell_origin(field: &HeightField, gx: u32, gz: u32) -> (Fix128, Fix128) {
    (
        field.origin.x + field.spacing * Fix128::from_int(i64::from(gx)),
        field.origin.z + field.spacing * Fix128::from_int(i64::from(gz)),
    )
}

/// The four corner heights of cell `(gx, gz)`: `(h00, h10, h01, h11)`.
fn cell_heights(field: &HeightField, gx: u32, gz: u32) -> [Fix128; 4] {
    [
        field.get_height(gx, gz),
        field.get_height(gx + 1, gz),
        field.get_height(gx, gz + 1),
        field.get_height(gx + 1, gz + 1),
    ]
}

/// Four points, for GJK: their convex hull. The control points of a bilinear
/// patch, whose hull contains the patch.
struct QuadSupport([Vec3Fix; 4]);

impl Support for QuadSupport {
    fn support(&self, direction: Vec3Fix) -> Vec3Fix {
        let mut best = self.0[0];
        let mut best_dot = best.dot(direction);
        for &p in &self.0[1..] {
            let d = p.dot(direction);
            if d > best_dot {
                best = p;
                best_dot = d;
            }
        }
        best
    }
}

/// One bilinear height-field cell: first corner `(x0, z0)`, spacing `s`, corner
/// heights `(h00, h10, h01, h11)`.
#[derive(Clone, Copy)]
struct Cell {
    x0: Fix128,
    z0: Fix128,
    s: Fix128,
    h: [Fix128; 4],
}

impl Cell {
    fn new(field: &HeightField, gx: u32, gz: u32) -> Self {
        let (x0, z0) = cell_origin(field, gx, gz);
        Self {
            x0,
            z0,
            s: field.spacing,
            h: cell_heights(field, gx, gz),
        }
    }

    /// The bilinear height at `(u, v) ∈ [0, 1]²`.
    fn height(&self, u: Fix128, v: Fix128) -> Fix128 {
        let [h00, h10, h01, h11] = self.h;
        let one = Fix128::ONE;
        h00 * (one - u) * (one - v) + h10 * u * (one - v) + h01 * (one - u) * v + h11 * u * v
    }

    fn point(&self, u: Fix128, v: Fix128) -> Vec3Fix {
        Vec3Fix::new(
            self.x0 + self.s * u,
            self.height(u, v),
            self.z0 + self.s * v,
        )
    }

    /// `h00 − h10 − h01 + h11`: zero for a planar cell.
    fn twist(&self) -> Fix128 {
        let [h00, h10, h01, h11] = self.h;
        h00 - h10 - h01 + h11
    }

    /// The unit upward normal of the surface at `(u, v)`.
    fn normal(&self, u: Fix128, v: Fix128) -> Vec3Fix {
        let [h00, h10, h01, h11] = self.h;
        let one = Fix128::ONE;
        let hu = (h10 - h00) * (one - v) + (h11 - h01) * v;
        let hv = (h01 - h00) * (one - u) + (h11 - h10) * u;
        Vec3Fix::new(-hu, self.s, -hv).normalize()
    }

    /// The `(u, v)` of the world `(x, z)` of `p`, clamped to `[u0, u1] × [v0, v1]`.
    fn uv(&self, p: Vec3Fix, part: &Patch) -> (Fix128, Fix128) {
        (
            clamp((p.x - self.x0) / self.s, part.u0, part.u1),
            clamp((p.z - self.z0) / self.s, part.v0, part.v1),
        )
    }
}

/// The part `u ∈ [u0, u1]`, `v ∈ [v0, v1]` of a [`Cell`]. A bilinear patch
/// restricted to a rectangle of `(u, v)` is again bilinear, with its four corners
/// as control points, so it lies inside the convex hull of those corners.
#[derive(Clone, Copy)]
struct Patch {
    u0: Fix128,
    u1: Fix128,
    v0: Fix128,
    v1: Fix128,
}

impl Patch {
    const WHOLE: Self = Self {
        u0: Fix128::ZERO,
        u1: Fix128::ONE,
        v0: Fix128::ZERO,
        v1: Fix128::ONE,
    };

    fn hull(&self, cell: &Cell) -> QuadSupport {
        QuadSupport([
            cell.point(self.u0, self.v0),
            cell.point(self.u1, self.v0),
            cell.point(self.u0, self.v1),
            cell.point(self.u1, self.v1),
        ])
    }

    /// A bound on how far a point of the hull is from the patch: the hull lies
    /// between the two triangulations of the corners, which differ from the
    /// bilinear surface by at most a quarter of the part's twist
    /// `|k|·(u1 − u0)·(v1 − v0)` along `Y`.
    fn thickness(&self, cell: &Cell) -> Fix128 {
        (cell.twist().abs() * (self.u1 - self.u0) * (self.v1 - self.v0))
            .half()
            .half()
    }

    fn split(&self) -> [Self; 4] {
        let um = (self.u0 + self.u1).half();
        let vm = (self.v0 + self.v1).half();
        [
            Self {
                u1: um,
                v1: vm,
                ..*self
            },
            Self {
                u0: um,
                v1: vm,
                ..*self
            },
            Self {
                u1: um,
                v0: vm,
                ..*self
            },
            Self {
                u0: um,
                v0: vm,
                ..*self
            },
        ]
    }

    /// The surface point of this part over the `(x, z)` of `p`.
    fn surface_under(&self, cell: &Cell, p: Vec3Fix) -> Vec3Fix {
        let (u, v) = cell.uv(p, self);
        cell.point(u, v)
    }
}

/// The distance from the core `a`–`b` to one cell and the nearest surface point
/// found, by branch-and-bound over parts of the cell: the distance to a part's
/// hull is a lower bound for the part, the distance to the surface point under
/// the hull's nearest point an upper bound, and parts are split until the two
/// meet within [`TRACE_TOLERANCE`]. The result is never above the true distance
/// by more than that tolerance; if the node budget runs out it is the lowest
/// open lower bound (below the true distance).
fn cell_dist(cell: &Cell, a: Vec3Fix, b: Vec3Fix) -> (Fix128, Vec3Fix) {
    let to_core = |q: Vec3Fix| (closest_on_segment(a, b, q) - q).length();
    let eval = |part: &Patch| {
        let hull = part.hull(cell);
        let found = if a == b {
            gjk_distance(&PointSupport(a), &hull)
        } else {
            gjk_distance(&SegmentSupport(a, b), &hull)
        };
        let (lower, near) = match found {
            Some((d, _, pb)) => (d, pb),
            None => (
                Fix128::ZERO,
                cell.point((part.u0 + part.u1).half(), (part.v0 + part.v1).half()),
            ),
        };
        let q = part.surface_under(cell, near);
        (lower, q, to_core(q))
    };
    let (lower, q, upper) = eval(&Patch::WHOLE);
    let mut best = (upper, q);
    let mut open = vec![(lower, Patch::WHOLE)];
    let mut nodes = 0usize;
    while let Some(k) = (0..open.len()).min_by_key(|&k| open[k].0) {
        let (lower, part) = open.remove(k);
        // Every open part is at least `lower` away: nothing can beat the best by
        // more than the tolerance.
        if lower + TRACE_TOLERANCE >= best.0 {
            break;
        }
        nodes += 1;
        if nodes > CELL_MAX_NODES {
            return (lower, best.1);
        }
        for child in part.split() {
            let (lower, q, upper) = eval(&child);
            if upper < best.0 {
                best = (upper, q);
            }
            // A part thinner than the tolerance has its upper bound within the
            // tolerance of its lower bound, so it is settled by `best`.
            if lower + TRACE_TOLERANCE < best.0 && child.thickness(cell) > TRACE_TOLERANCE {
                open.push((lower, child));
            }
        }
    }
    best
}

/// The distance from the core `a`–`b` to the height-field surface, searching the
/// cells within `cap` of it ([`Dist::AtLeast`] beyond). A core within
/// [`TRACE_TOLERANCE`] of the surface is touching: a point gets distance `0` and
/// the surface normal on its side, a segment is [`Dist::Inside`] (it meets the
/// surface).
fn heightfield_dist(field: &HeightField, a: Vec3Fix, b: Vec3Fix, cap: Fix128) -> Dist {
    if !field_has_surface(field) {
        return Dist::AtLeast(cap);
    }
    let core = core_box(a, b, Fix128::ZERO);
    let far = aabb_gap(&core, &field.aabb());
    if far >= cap {
        return Dist::AtLeast(far);
    }
    let reach = core_box(a, b, cap);
    let s = field.spacing;
    let (Some((gx0, gx1)), Some((gz0, gz1))) = (
        cell_range(reach.min.x, reach.max.x, field.origin.x, s, field.width),
        cell_range(reach.min.z, reach.max.z, field.origin.z, s, field.depth),
    ) else {
        return Dist::AtLeast(cap);
    };
    // The cells by their box's distance from the core, nearest first: once a
    // cell's box is farther than the best distance found, no later cell is nearer.
    let mut cells: Vec<(Fix128, u32, u32)> = Vec::new();
    for gz in gz0..=gz1 {
        for gx in gx0..=gx1 {
            let lower = aabb_gap(&core, &cell_box(field, gx, gz));
            if lower < cap {
                cells.push((lower, gz, gx));
            }
        }
    }
    cells.sort_unstable();
    let mut best: Option<(Fix128, Vec3Fix, Cell)> = None;
    for (lower, gz, gx) in cells {
        if best.is_some_and(|(d, _, _)| lower >= d) {
            break;
        }
        let cell = Cell::new(field, gx, gz);
        let (d, q) = cell_dist(&cell, a, b);
        if best.is_none_or(|(bd, _, _)| d < bd) {
            best = Some((d, q, cell));
        }
    }
    let Some((d, q, cell)) = best.filter(|&(d, _, _)| d < cap) else {
        return Dist::AtLeast(cap);
    };
    let core_point = closest_on_segment(a, b, q);
    if d <= TRACE_TOLERANCE {
        if a != b {
            return Dist::Inside;
        }
        let (u, v) = cell.uv(q, &Patch::WHOLE);
        let n = cell.normal(u, v);
        let side = if (a - q).dot(n).is_negative() { -n } else { n };
        return Dist::Outside {
            dist: d,
            point: q,
            normal: side,
        };
    }
    let normal = match (core_point - q).try_normalize() {
        Some(n) => n,
        None => return Dist::Inside,
    };
    Dist::Outside {
        dist: d,
        point: q,
        normal,
    }
}

/// The box of cell `(gx, gz)`: its `XZ` square and the range of its corner
/// heights (the bilinear surface stays within them).
fn cell_box(field: &HeightField, gx: u32, gz: u32) -> AABB {
    let h = cell_heights(field, gx, gz);
    let (x0, z0) = cell_origin(field, gx, gz);
    let s = field.spacing;
    let lo = min_fix(min_fix(h[0], h[1]), min_fix(h[2], h[3]));
    let hi = max_fix(max_fix(h[0], h[1]), max_fix(h[2], h[3]));
    AABB::new(Vec3Fix::new(x0, lo, z0), Vec3Fix::new(x0 + s, hi, z0 + s))
}

/// The first time the core `a`–`b` grown by `r`, moving along the unit `d`,
/// touches one cell: against the hull of the whole cell when it is planar (the
/// hull is the cell), otherwise by [`toi_tree`] over its parts, which accepts a
/// part once its hull is within [`TRACE_TOLERANCE`] of its surface.
fn cell_toi(
    cell: &Cell,
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
) -> Option<Contact> {
    let toi = |part: &Patch| toi_convex(a, b, r, Fix128::ZERO, d, max_t, &part.hull(cell));
    if cell.twist().is_zero() {
        return toi(&Patch::WHOLE);
    }
    let found = toi_tree(
        &[Patch::WHOLE],
        toi,
        |part| part.thickness(cell) <= TRACE_TOLERANCE,
        |part| part.split().to_vec(),
    )?;
    let off = d * found.t;
    Some(refine_on_cell(cell, a + off, b + off, found))
}

/// A contact found on a part's hull moved onto the surface: Newton's method on
/// the squared distance from the core to the bilinear surface, started at the
/// contact's `(u, v)`. The hull contact is within the part (a few `2⁻¹⁶` of the
/// cell), where the distance has a single minimum; the refined point is taken
/// only if it is not farther from the core than the hull contact.
fn refine_on_cell(cell: &Cell, a: Vec3Fix, b: Vec3Fix, found: Contact) -> Contact {
    let [h00, h10, h01, h11] = cell.h;
    let k = cell.twist();
    let s = cell.s;
    let one = Fix128::ONE;
    let (mut u, mut v) = cell.uv(found.point, &Patch::WHOLE);
    for _ in 0..8 {
        let q = cell.point(u, v);
        let e = q - closest_on_segment(a, b, q);
        let hu = (h10 - h00) * (one - v) + (h11 - h01) * v;
        let hv = (h01 - h00) * (one - u) + (h11 - h10) * u;
        let pu = Vec3Fix::new(s, hu, Fix128::ZERO);
        let pv = Vec3Fix::new(Fix128::ZERO, hv, s);
        let (gu, gv) = (e.dot(pu), e.dot(pv));
        let (huu, hvv) = (pu.dot(pu), pv.dot(pv));
        let huv = pu.dot(pv) + e.y * k;
        let det = huu * hvv - huv * huv;
        if det <= Fix128::ZERO {
            return found;
        }
        u = clamp(u - (hvv * gu - huv * gv) / det, Fix128::ZERO, one);
        v = clamp(v - (huu * gv - huv * gu) / det, Fix128::ZERO, one);
    }
    let q = cell.point(u, v);
    let core = closest_on_segment(a, b, q);
    let before = (closest_on_segment(a, b, found.point) - found.point).length();
    match (core - q).normalize_with_length() {
        (n, dist)
            if !dist.is_zero()
                && dist <= before + TRACE_TOLERANCE + TRACE_TOLERANCE
                && n.dot(found.normal) > Fix128::ZERO =>
        {
            Contact {
                t: found.t,
                point: q,
                normal: n,
            }
        }
        _ => found,
    }
}

/// The first contact of the core `a`–`b` grown by `r` moving along the unit `d`
/// with a height field: every cell its swept box crosses, in order of the time
/// the moving box first reaches the cell's box, stopping once that time is past
/// the best contact.
fn sweep_heightfield(
    field: &HeightField,
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
) -> Option<Contact> {
    if !field_has_surface(field) {
        return None;
    }
    let start = core_box(a, b, r);
    let swept = swept_box(a, b, r, d, max_t);
    let s = field.spacing;
    let (Some((gx0, gx1)), Some((gz0, gz1))) = (
        cell_range(swept.min.x, swept.max.x, field.origin.x, s, field.width),
        cell_range(swept.min.z, swept.max.z, field.origin.z, s, field.depth),
    ) else {
        return None;
    };
    let mut cells: Vec<(Fix128, u32, u32)> = Vec::new();
    for gz in gz0..=gz1 {
        for gx in gx0..=gx1 {
            if let Some(entry) = box_entry(&start, d, max_t, &cell_box(field, gx, gz)) {
                cells.push((entry, gz, gx));
            }
        }
    }
    cells.sort_unstable();
    let mut best: Option<Contact> = None;
    for (entry, gz, gx) in cells {
        if best.is_some_and(|c| c.t < entry) {
            break;
        }
        if let Some(c) = cell_toi(&Cell::new(field, gx, gz), a, b, r, d, max_t) {
            if best.is_none_or(|bc| c.t < bc.t) {
                best = Some(c);
            }
        }
    }
    best
}

/// `num / den` limited to `[−big, big]` (no overflow for a tiny `den`).
fn ratio_within(num: Fix128, den: Fix128, big: Fix128) -> Fix128 {
    if num.abs() >= den.abs() * big {
        if num.is_negative() == den.is_negative() {
            big
        } else {
            -big
        }
    } else {
        num / den
    }
}

/// The first `t ∈ [0, max_t]` at which `moving` shifted by `t·d` meets `target`
/// (boxes touching count), or `None`.
fn box_entry(moving: &AABB, d: Vec3Fix, max_t: Fix128, target: &AABB) -> Option<Fix128> {
    let big = max_t + Fix128::ONE;
    let mut lo = Fix128::ZERO;
    let mut hi = max_t;
    for (m0, m1, t0, t1, di) in [
        (moving.min.x, moving.max.x, target.min.x, target.max.x, d.x),
        (moving.min.y, moving.max.y, target.min.y, target.max.y, d.y),
        (moving.min.z, moving.max.z, target.min.z, target.max.z, d.z),
    ] {
        if di.abs() < PARALLEL_EPSILON {
            // Nearly no motion on this axis: at most max_t·|di| either way.
            let slack = max_t * di.abs();
            if m1 + slack < t0 || m0 - slack > t1 {
                return None;
            }
            continue;
        }
        let (enter, leave) = if di.is_negative() {
            (
                ratio_within(t1 - m0, di, big),
                ratio_within(t0 - m1, di, big),
            )
        } else {
            (
                ratio_within(t0 - m1, di, big),
                ratio_within(t1 - m0, di, big),
            )
        };
        lo = max_fix(lo, enter);
        hi = min_fix(hi, leave);
    }
    (lo <= hi).then_some(lo)
}

/// The box swept by the core `a`–`b` grown by `r` moving along `d` for `max_t`.
fn swept_box(a: Vec3Fix, b: Vec3Fix, r: Fix128, d: Vec3Fix, max_t: Fix128) -> AABB {
    let start = core_box(a, b, r);
    let end = core_box(a + d * max_t, b + d * max_t, r);
    AABB::new(
        Vec3Fix::new(
            min_fix(start.min.x, end.min.x),
            min_fix(start.min.y, end.min.y),
            min_fix(start.min.z, end.min.z),
        ),
        Vec3Fix::new(
            max_fix(start.max.x, end.max.x),
            max_fix(start.max.y, end.max.y),
            max_fix(start.max.z, end.max.z),
        ),
    )
}

/// The first contact of the core `a`–`b` grown by `r` moving along the unit `d`
/// with a triangle mesh: a convex time of impact per triangle the swept box
/// meets, in order of the time the moving box reaches the triangle's box. Each
/// triangle is convex, so running along one triangle (a floor) is not a step
/// budget spent against another (a wall).
fn sweep_mesh(
    mesh: &TriMesh,
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
) -> Option<Contact> {
    let start = core_box(a, b, r);
    let mut order: Vec<(Fix128, u32)> = mesh_candidates(mesh, &swept_box(a, b, r, d, max_t))
        .into_iter()
        .filter_map(|i| {
            let tri = &mesh.triangles[i as usize];
            let tri_box = AABB::new(
                Vec3Fix::new(
                    min_fix(min_fix(tri.v0.x, tri.v1.x), tri.v2.x),
                    min_fix(min_fix(tri.v0.y, tri.v1.y), tri.v2.y),
                    min_fix(min_fix(tri.v0.z, tri.v1.z), tri.v2.z),
                ),
                Vec3Fix::new(
                    max_fix(max_fix(tri.v0.x, tri.v1.x), tri.v2.x),
                    max_fix(max_fix(tri.v0.y, tri.v1.y), tri.v2.y),
                    max_fix(max_fix(tri.v0.z, tri.v1.z), tri.v2.z),
                ),
            );
            box_entry(&start, d, max_t, &tri_box).map(|entry| (entry, i))
        })
        .collect();
    order.sort_unstable();
    let mut best: Option<Contact> = None;
    for (entry, i) in order {
        if best.is_some_and(|c| c.t < entry) {
            break;
        }
        let tri = &mesh.triangles[i as usize];
        if let Some(c) = toi_convex(a, b, r, Fix128::ZERO, d, max_t, &TriangleSupport(tri)) {
            if best.is_none_or(|bc| c.t < bc.t) {
                best = Some(c);
            }
        }
    }
    best
}

/// The ring of a torus (radius `major` in its local `XZ` plane) and its tube
/// radius: the solid torus is the ring grown by `minor`.
#[derive(Clone, Copy)]
struct Ring {
    center: Vec3Fix,
    rotation: QuatFix,
    major: Fix128,
    minor: Fix128,
}

/// The arc of a [`Ring`] from the unit local direction `e0` counter-clockwise
/// (from `+X` toward `+Z`) to `e1`, less than half a turn.
#[derive(Clone, Copy)]
struct RingArc {
    e0: Vec3Fix,
    e1: Vec3Fix,
}

/// `(a × b)·Y` for vectors in the `XZ` plane: positive when `b` is
/// counter-clockwise from `a` (from `+X` toward `+Z`).
fn turn(a: Vec3Fix, b: Vec3Fix) -> Fix128 {
    a.x * b.z - a.z * b.x
}

impl RingArc {
    /// How far the chord is inside the arc (the sagitta): every point of the
    /// arc's hull is within it of the arc.
    fn thickness(&self, major: Fix128) -> Fix128 {
        let half_chord = ((self.e1 - self.e0).length() * major).half();
        major - (major * major - half_chord * half_chord).sqrt()
    }

    fn split(&self) -> [Self; 2] {
        let mid = (self.e0 + self.e1).normalize();
        [
            Self {
                e0: self.e0,
                e1: mid,
            },
            Self {
                e0: mid,
                e1: self.e1,
            },
        ]
    }
}

/// An arc of a ring placed in the world, for GJK: its convex hull (the circular
/// segment).
struct ArcSupport {
    ring: Ring,
    arc: RingArc,
}

impl Support for ArcSupport {
    fn support(&self, direction: Vec3Fix) -> Vec3Fix {
        let local = self.ring.rotation.conjugate().rotate_vec(direction);
        let flat = Vec3Fix::new(local.x, Fix128::ZERO, local.z);
        let (e0, e1) = (self.arc.e0, self.arc.e1);
        let e = match flat.try_normalize() {
            Some(u) if !turn(e0, u).is_negative() && !turn(u, e1).is_negative() => u,
            _ if e1.dot(flat) > e0.dot(flat) => e1,
            _ => e0,
        };
        self.ring.center + self.ring.rotation.rotate_vec(e * self.ring.major)
    }
}

impl Ring {
    /// The first contact of the core `a`–`b` grown by `r` with the solid torus:
    /// [`toi_tree`] over arcs of the ring, each arc's hull grown by the tube
    /// radius (a convex set containing that part of the torus), split until the
    /// hull is within [`TRACE_TOLERANCE`] of the arc.
    fn sweep(
        &self,
        a: Vec3Fix,
        b: Vec3Fix,
        r: Fix128,
        d: Vec3Fix,
        max_t: Fix128,
    ) -> Option<Contact> {
        let x = Vec3Fix::UNIT_X;
        let z = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ONE);
        let quarters = [
            RingArc { e0: x, e1: z },
            RingArc { e0: z, e1: -x },
            RingArc { e0: -x, e1: -z },
            RingArc { e0: -z, e1: x },
        ];
        toi_tree(
            &quarters,
            |arc| {
                let hull = ArcSupport {
                    ring: *self,
                    arc: *arc,
                };
                toi_convex(a, b, r, self.minor, d, max_t, &hull)
            },
            |arc| arc.thickness(self.major) <= TRACE_TOLERANCE,
            |arc| arc.split().to_vec(),
        )
        .map(|c| self.refine(a + d * c.t, b + d * c.t, c))
    }

    /// A contact found on an arc's hull moved onto the torus: the ring point
    /// nearest the core point nearest the contact, grown by the tube radius
    /// (the hull contact is within the arc's sagitta of it).
    fn refine(&self, a: Vec3Fix, b: Vec3Fix, found: Contact) -> Contact {
        let core = closest_on_segment(a, b, found.point);
        let inv = self.rotation.conjugate();
        let local = inv.rotate_vec(core - self.center);
        let Some(dir) = Vec3Fix::new(local.x, Fix128::ZERO, local.z).try_normalize() else {
            return found;
        };
        let ring = self.center + self.rotation.rotate_vec(dir * self.major);
        match (core - ring).try_normalize() {
            Some(n) if n.dot(found.normal) > Fix128::ZERO => Contact {
                t: found.t,
                point: ring + n * self.minor,
                normal: n,
            },
            _ => found,
        }
    }
}

// ============================================================================
// Time of impact
// ============================================================================

/// The first time the core `a`–`b` grown by `r`, moving along the unit `d` for at
/// most `max_t`, touches a convex `solid` grown by `inflate`.
///
/// The gap `g(t) = dist(core + t·d, solid) − r − inflate` of two convex sets
/// moving apart linearly is convex in `t`, and `g′(t) = d·n` with `n` the unit
/// normal from the solid toward the core. Newton's step from below,
/// `t + g / (−g′)`, then never passes the first root (the tangent of a convex
/// function lies below it) and converges quadratically (linearly at a grazing,
/// double root); a gap that is not decreasing (`g′ ≥ 0`) never decreases again,
/// which proves there is no contact. A step that lands past the root (the
/// distance and normal are computed to within GJK's tolerance) is undone by
/// bisection between the last clear time and that time; once the two are within
/// the tolerance, the tangent's root from the clear time is the contact (a core
/// of reach `0` always ends this way, since it is touching only within GJK's
/// intersection tolerance).
///
/// Returns the contact once the gap is within [`TRACE_TOLERANCE`] and the core
/// moves into the solid (see [`touch_is_hit`]): a core touching the solid and
/// moving away from it or along it does not hit. A core that overlaps the solid at `t = 0` by
/// more than the tolerance hits at `t = 0` with normal `−d`. If the step budget
/// runs out (it does not in practice: Newton needs a few dozen steps even at a
/// grazing approach), the last clear time is reported, which is never after the
/// true contact.
fn toi_convex<S: Support>(
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    inflate: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
    solid: &S,
) -> Option<Contact> {
    toi_convex_refined(a, b, r, inflate, d, max_t, solid, Fix128::ZERO, |_, _| None)
}

/// [`toi_convex`] with an exact distance `exact` (`None` where there is none).
///
/// GJK's distance is an upper bound and its lower bound (see [`gjk_distance`]
/// § A lower bound) a lower one; where they straddle a decision of the time of
/// impact (touching at `2⁻³²`, going in at `−2⁻³²`, see [`straddles`]) GJK
/// cannot tell which side the gap is on. A segment of radius 0 that enters a
/// cylinder through its side just below a cap left GJK on a face `2` to
/// `25·2⁻³²` from the origin with the segment already `1.25·2⁻³²` in: taken as
/// clear, the cast went past the contact; taken as touching (by the lower
/// bound), other casts stopped up to `10·2⁻³²` early. There the exact distance
/// decides. Pieces with an exact distance: a posed cylinder and cone, point
/// and segment cores ([`exact_round_dist`]); the other convex pieces (boxes,
/// wedges, ellipsoids, hulls, mesh triangles, height-field cells) keep GJK's
/// bounds (`slack` is zero for them; their support points are not moved
/// onto an axis).
#[allow(clippy::too_many_arguments)]
fn toi_convex_refined<S: Support>(
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    inflate: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
    solid: &S,
    slack: Fix128,
    exact: impl Fn(Vec3Fix, Vec3Fix) -> Option<Dist>,
) -> Option<Contact> {
    let reach = r + inflate;
    toi_by(a, b, r, inflate, d, max_t, |a, b, along| {
        if along {
            // the search along a near-tangent path takes the exact distance
            // where there is one (one source of distance, no mixed rounding)
            if let Some(e) = exact(a, b) {
                let exact_bound = Bound::exact(&e);
                return (e, exact_bound);
            }
        }
        let (found, bound) = convex_bounds(a, b, solid, slack);
        if let Dist::Outside { dist, .. } = found {
            if straddles(bound.lower - reach, dist - reach) {
                if let Some(e) = exact(a, b) {
                    let exact_bound = Bound::exact(&e);
                    return (e, exact_bound);
                }
            }
        }
        (found, bound)
    })
}

/// Whether a gap known within `[lower, upper]` straddles one of the decisions
/// of a time of impact: touching (`2⁻³²`) or going in (`−2⁻³²`).
fn straddles(lower: Fix128, upper: Fix128) -> bool {
    let crosses = |x: Fix128| lower <= x && x < upper;
    crosses(TRACE_TOLERANCE) || crosses(-TRACE_TOLERANCE)
}

/// [`toi_convex`] for a convex piece given by its distance from a core:
/// `core_dist(a, b, along)` is GJK for [`toi_convex`] (with its lower bound,
/// see [`Bound`]), or a closed form; `along` is set by the search along a
/// near-tangent path ([`dips_below`]), which takes an exact distance where
/// there is one.
///
/// The step from a clear time goes by the gap (the tangent's root), from
/// the distance as before, or for a distance taken on an imprecise face
/// from the lower bound, and at least by the tolerance (a step of the tolerance
/// goes at most that far in). Touching is decided by the distance.
fn toi_by(
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    inflate: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
    core_dist: impl Fn(Vec3Fix, Vec3Fix, bool) -> (Dist, Bound),
) -> Option<Contact> {
    let reach = r + inflate;
    let mut t = Fix128::ZERO;
    // The last time known clear (gap above the tolerance), its near contact, and
    // the gap and closing speed there.
    let mut clear: Option<Contact> = None;
    let mut clear_gap = (Fix128::ZERO, Fix128::ZERO, false);
    // A time known to overlap, once a step has gone past the root.
    let mut deep: Option<Fix128> = None;
    for _ in 0..TRACE_MAX_STEPS {
        let off = d * t;
        let (found, bound) = core_dist(a + off, b + off, false);
        let state = match found {
            Dist::Outside {
                dist,
                point,
                normal,
            } if dist - reach >= -TRACE_TOLERANCE => {
                // The distance decides touching, as before; the step goes by
                // the lower bound (see `gjk_distance`), and at least by the
                // tolerance: the lower bound can be below it while the distance
                // is not, and a step of the tolerance goes at most that far in.
                let gap = if bound.step_lower {
                    max_fix(bound.lower - reach, TRACE_TOLERANCE)
                } else {
                    dist - reach
                };
                let touching = dist - reach <= TRACE_TOLERANCE;
                let slope = d.dot(normal);
                let contact = Contact {
                    t,
                    point: point + normal * inflate,
                    normal,
                };
                if touching {
                    let gap_at = |t: Fix128| {
                        let off = d * t;
                        match core_dist(a + off, b + off, true).0 {
                            Dist::Outside { dist, .. } => Some(dist - reach),
                            _ => None,
                        }
                    };
                    return touch_is_hit(contact, d, max_t, gap_at).then_some(contact);
                }
                if !slope.is_negative() {
                    if slope < NEAR_TANGENT && gap <= GRAZE_GAP {
                        // Not a proof of separation: see `GRAZE_GAP`.
                        let probe = |t: Fix128| {
                            let off = d * t;
                            core_dist(a + off, b + off, true).0
                        };
                        return graze_contact(probe, reach, inflate, t, max_t);
                    }
                    return None;
                }
                Some((gap, -slope, contact, dist < FINE_LENGTH))
            }
            _ => None,
        };
        match state {
            Some((gap, speed, contact, fine)) => {
                clear = Some(contact);
                clear_gap = (gap, speed, fine);
                let limit = deep.unwrap_or(max_t);
                // The tangent's root, unless it is at or past the limit.
                if gap >= (limit - t) * speed {
                    match deep {
                        None if gap > (limit - t) * speed => return None,
                        None => t = limit,
                        Some(hi) => t = (t + hi).half(),
                    }
                } else {
                    t = t + gap / speed;
                }
            }
            None => {
                if t.is_zero() {
                    return Some(Contact {
                        t,
                        point: half_vec(a + b),
                        normal: -d,
                    });
                }
                deep = Some(t);
                let lo = clear.map_or(Fix128::ZERO, |c| c.t);
                if t - lo <= TRACE_TOLERANCE {
                    // Bracketed to within the tolerance. When the clear end is
                    // nearer than 2⁻¹⁶ (a core of reach below that), report the
                    // tangent's root from it, which is not past the contact
                    // (convexity): a core of reach 0 never sees a touching gap
                    // (GJK counts `|v| ≤ 2⁻³²` as intersecting), so every such
                    // cast ends here; at `t` its gap is at most 2⁻³², not
                    // necessarily below 0, so the contact is before
                    // `t + 2⁻³² / speed`. Otherwise the clear end itself.
                    let (gap, speed, fine) = clear_gap;
                    if !fine {
                        return clear;
                    }
                    return clear.map(|c| {
                        let slack = ratio_within(TRACE_TOLERANCE, speed, max_t);
                        let step = ratio_within(gap, speed, t - lo + slack);
                        Contact {
                            t: min_fix(lo + max_fix(step, Fix128::ZERO), max_t),
                            ..c
                        }
                    });
                }
                t = (lo + t).half();
            }
        }
    }
    clear
}

/// A clear gap up to this (`2⁻²⁴`) with the motion within [`NEAR_TANGENT`] of
/// the tangent plane but not into it: the slope `d·n` then is not a proof that
/// the gap only grows. The normal is known to about the error of the distance
/// over the distance, and a path at `9·10⁻¹⁰` rad to a cone's base showed a
/// slope of `+3·10⁻⁹` where it was `−1.5·10⁻⁹`, at a gap of
/// `3·2⁻³²`, and went `1.7·2⁻³²` in further on: `2⁻²⁸` of slope error over a
/// path of 16 is `2⁻²⁴` of gap.
const GRAZE_GAP: Fix128 = Fix128 {
    hi: 0,
    lo: 0x0000_0100_0000_0000,
};

/// The contact of a path that is near tangent at `t0` (see [`GRAZE_GAP`]): the
/// gap (`dist` less `reach`, convex) is minimised on `[t0, max_t]` by
/// golden-section search, and if it goes below `−2⁻³²` the time it first comes
/// within `2⁻³²` is found by bisection between `t0` and that point (a clear
/// end, never after the contact, if the bisection does not land on it); `None`
/// if it does not go in.
fn graze_contact(
    dist: impl Fn(Fix128) -> Dist,
    reach: Fix128,
    inflate: Fix128,
    t0: Fix128,
    max_t: Fix128,
) -> Option<Contact> {
    let gap_at = |t: Fix128| match dist(t) {
        Dist::Outside { dist, .. } => Some(dist - reach),
        _ => None,
    };
    let deep = |g: Option<Fix128>| g.is_none_or(|g| g < -TRACE_TOLERANCE);
    let mut inside = deep(gap_at(max_t)).then_some(max_t);
    if inside.is_none() {
        let ratio = Fix128::from_ratio(618_033_988_749_895, 1_000_000_000_000_000);
        let (mut lo, mut hi) = (t0, max_t);
        for _ in 0..GOLDEN_STEPS {
            let x1 = hi - (hi - lo) * ratio;
            let x2 = lo + (hi - lo) * ratio;
            let (g1, g2) = (gap_at(x1), gap_at(x2));
            if deep(g1) {
                inside = Some(x1);
                break;
            }
            if deep(g2) {
                inside = Some(x2);
                break;
            }
            if g1 <= g2 {
                hi = x2;
            } else {
                lo = x1;
            }
        }
    }
    let (mut lo, mut hi) = (t0, inside?);
    for _ in 0..GOLDEN_STEPS {
        let mid = (lo + hi).half();
        match gap_at(mid) {
            Some(g) if g > TRACE_TOLERANCE => lo = mid,
            Some(g) if g >= -TRACE_TOLERANCE => {
                lo = mid;
                break;
            }
            _ => hi = mid,
        }
    }
    match dist(lo) {
        Dist::Outside { point, normal, .. } => Some(Contact {
            t: lo,
            point: point + normal * inflate,
            normal,
        }),
        _ => None,
    }
}

/// Whether a contact found touching a convex piece (gap at most `2⁻³²`, normal
/// `n` toward the core) is a hit for the motion along the unit `d`: moving away
/// or along the surface (`d·n ≥ 0`) is not; moving into it is, except that when
/// the motion is within [`NEAR_TANGENT`] of the tangent plane the contact is a
/// hit only if `gap_at` (the gap along the path, `None` inside) then drops
/// below `−2⁻³²` before `max_t`. A shape resting on a mesh floor or a flat
/// height field touches the next triangle or cell only tangentially at their
/// shared edge, and must not stop there; a grazing approach that really goes
/// in is still a hit.
fn touch_is_hit(
    contact: Contact,
    d: Vec3Fix,
    max_t: Fix128,
    gap_at: impl Fn(Fix128) -> Option<Fix128>,
) -> bool {
    let slope = d.dot(contact.normal);
    if slope < -NEAR_TANGENT {
        return true;
    }
    if !slope.is_negative() {
        return false;
    }
    match gap_at(contact.t) {
        None => true,
        Some(gap) => dips_below(gap_at, contact.t, gap, -slope, max_t),
    }
}

/// A gap has grown in [`dips_below`] only when it is above the previous one by
/// this (`2⁻⁵⁶`, `2⁻²⁴` of the tolerance): an exact distance
/// ([`exact_round_dist`]) is still off by its rounding, the turn into the
/// solid's frame (`12·2⁻⁶⁴` per unit of coordinate, see
/// `Vec3Fix::rescaled_xz`) and a few truncated products, below `2⁻⁵⁷` for
/// coordinates up to `2⁴`. A path that runs along a face sinking by
/// `4·10⁻⁵·2⁻³²` over its length changed by less than that between two steps,
/// a rounding-level rise bracketed a minimum that is not there, and a path
/// that went `1.00004·2⁻³²` in was not a hit.
const DIPS_GROWTH: Fix128 = Fix128 { hi: 0, lo: 1 << 8 };

/// Whether a convex gap function (`None` inside) that is `f0` at `t0` and
/// decreasing at `speed` drops below `−2⁻³²` in `[t0, max_t]`: steps doubling
/// from the tangent's root until the gap goes below that (yes), grows again
/// (its minimum is then bracketed and found by golden-section search) or
/// `max_t` is reached.
fn dips_below(
    gap_at: impl Fn(Fix128) -> Option<Fix128>,
    t0: Fix128,
    f0: Fix128,
    speed: Fix128,
    max_t: Fix128,
) -> bool {
    let deep = |g: Option<Fix128>| g.is_none_or(|g| g < -TRACE_TOLERANCE);
    // The far end first: a path that sinks so slowly that a doubling step
    // changes the gap by less than its rounding would see no decrease and stop
    // the search before it reaches the depth it has by `max_t`.
    if deep(gap_at(max_t)) {
        return true;
    }
    let big = max_t + Fix128::ONE;
    let mut step = max_fix(
        ratio_within(max_fix(f0, Fix128::ZERO), speed, big),
        TRACE_TOLERANCE,
    );
    let (mut before, mut last, mut last_gap) = (t0, t0, f0);
    for _ in 0..GOLDEN_STEPS {
        let t1 = min_fix(t0 + step, max_t);
        let g1 = gap_at(t1);
        if deep(g1) {
            return true;
        }
        let g1 = g1.unwrap_or(Fix128::ZERO);
        if g1 > last_gap + DIPS_GROWTH || t1 >= max_t {
            // Convex: the minimum is in [before, t1].
            let (mut lo, mut hi) = (before, t1);
            let ratio = Fix128::from_ratio(618_033_988_749_895, 1_000_000_000_000_000);
            for _ in 0..GOLDEN_STEPS {
                let x1 = hi - (hi - lo) * ratio;
                let x2 = lo + (hi - lo) * ratio;
                let (g1, g2) = (gap_at(x1), gap_at(x2));
                if deep(g1) || deep(g2) {
                    return true;
                }
                let (g1, g2) = (g1.unwrap_or(Fix128::ZERO), g2.unwrap_or(Fix128::ZERO));
                if g1 <= g2 {
                    hi = x2;
                } else {
                    lo = x1;
                }
            }
            return false;
        }
        before = last;
        last = t1;
        last_gap = g1;
        step = step.double();
    }
    false
}

/// The first contact with a non-convex surface described as a hierarchy of parts
/// whose convex hulls contain them: `toi` is the contact with a part's hull,
/// `leaf` says a part's hull is within tolerance of the part, `split` divides a
/// part. Parts are taken best first (earliest hull contact); a hull contact is
/// never after the contact with the part it contains, so the first leaf taken is
/// the first contact of the whole surface to within the leaf tolerance. If the
/// node budget runs out, the earliest open hull contact is reported (never after
/// the true contact).
fn toi_tree<N: Copy>(
    roots: &[N],
    toi: impl Fn(&N) -> Option<Contact>,
    leaf: impl Fn(&N) -> bool,
    split: impl Fn(&N) -> Vec<N>,
) -> Option<Contact> {
    let mut open: Vec<(Contact, N)> = roots
        .iter()
        .filter_map(|n| toi(n).map(|c| (c, *n)))
        .collect();
    let mut nodes = 0usize;
    loop {
        let k = (0..open.len()).min_by_key(|&k| open[k].0.t)?;
        let (contact, node) = open.remove(k);
        if leaf(&node) {
            return Some(contact);
        }
        nodes += 1;
        if nodes > TREE_MAX_NODES {
            return Some(contact);
        }
        for child in split(&node) {
            if let Some(c) = toi(&child) {
                open.push((c, child));
            }
        }
    }
}

/// Whether the height-field surface passes through `aabb`: over each cell's part
/// of the box's `XZ` footprint the bilinear surface takes its extremes at the
/// corners of that part.
fn heightfield_meets_aabb(field: &HeightField, aabb: &AABB) -> bool {
    if !field_has_surface(field) {
        return false;
    }
    let s = field.spacing;
    let x_end = field.origin.x + s * Fix128::from_int(i64::from(field.width) - 1);
    let z_end = field.origin.z + s * Fix128::from_int(i64::from(field.depth) - 1);
    let fx0 = max_fix(aabb.min.x, field.origin.x);
    let fx1 = min_fix(aabb.max.x, x_end);
    let fz0 = max_fix(aabb.min.z, field.origin.z);
    let fz1 = min_fix(aabb.max.z, z_end);
    if fx0 > fx1 || fz0 > fz1 {
        return false;
    }
    let (Some((gx0, gx1)), Some((gz0, gz1))) = (
        cell_range(fx0, fx1, field.origin.x, s, field.width),
        cell_range(fz0, fz1, field.origin.z, s, field.depth),
    ) else {
        return false;
    };
    for gz in gz0..=gz1 {
        for gx in gx0..=gx1 {
            let x0 = field.origin.x + s * Fix128::from_int(i64::from(gx));
            let z0 = field.origin.z + s * Fix128::from_int(i64::from(gz));
            let ux0 = max_fix(fx0, x0);
            let ux1 = min_fix(fx1, x0 + s);
            let uz0 = max_fix(fz0, z0);
            let uz1 = min_fix(fz1, z0 + s);
            if ux0 > ux1 || uz0 > uz1 {
                continue;
            }
            let [h00, h10, h01, h11] = cell_heights(field, gx, gz);
            let mut lo: Option<Fix128> = None;
            let mut hi: Option<Fix128> = None;
            for x in [ux0, ux1] {
                for z in [uz0, uz1] {
                    let u = (x - x0) / s;
                    let v = (z - z0) / s;
                    let one = Fix128::ONE;
                    let h = h00 * (one - u) * (one - v)
                        + h10 * u * (one - v)
                        + h01 * (one - u) * v
                        + h11 * u * v;
                    lo = Some(lo.map_or(h, |l| min_fix(l, h)));
                    hi = Some(hi.map_or(h, |m| max_fix(m, h)));
                }
            }
            if let (Some(lo), Some(hi)) = (lo, hi) {
                if lo < aabb.max.y && hi > aabb.min.y {
                    return true;
                }
            }
        }
    }
    false
}

// ============================================================================
// Triangle meshes
// ============================================================================

/// The triangles of `mesh` whose box meets `query`, in BVH order.
fn mesh_candidates(mesh: &TriMesh, query: &AABB) -> Vec<u32> {
    mesh.bvh.query(query)
}

/// The distance from the core `a`–`b` to the mesh, searching the triangles within
/// `cap`.
fn mesh_dist(mesh: &TriMesh, a: Vec3Fix, b: Vec3Fix, cap: Fix128) -> Dist {
    if mesh.triangles.is_empty() {
        return Dist::AtLeast(cap);
    }
    let core = core_box(a, b, Fix128::ZERO);
    let far = aabb_gap(&core, &mesh.bounds);
    if far >= cap {
        return Dist::AtLeast(far);
    }
    let mut best: Option<Dist> = None;
    for i in mesh_candidates(mesh, &core_box(a, b, cap)) {
        let tri = &mesh.triangles[i as usize];
        let d = if a == b {
            match Dist::toward(a, tri.closest_point(a)) {
                // On the triangle: touching, with its normal.
                Dist::Inside => Dist::Outside {
                    dist: Fix128::ZERO,
                    point: a,
                    normal: tri.normal().try_normalize().unwrap_or(Vec3Fix::UNIT_Y),
                },
                other => other,
            }
        } else {
            convex_dist(a, b, &TriangleSupport(tri))
        };
        if matches!(d, Dist::Inside) {
            return Dist::Inside;
        }
        if best.as_ref().is_none_or(|x| d.value() < x.value()) {
            best = Some(d);
        }
    }
    match best {
        Some(d) if d.value() < cap => d,
        _ => Dist::AtLeast(cap),
    }
}

/// A sphere swept against one triangle: the two copies of the triangle moved
/// `±r` along its normal and the three edges grown into capsules of `r`.
fn sweep_triangle(
    o: Vec3Fix,
    d: Vec3Fix,
    tri: &Triangle,
    r: Fix128,
    max_t: Fix128,
) -> Option<LocalHit> {
    let ray = crate::raycast::Ray {
        origin: o,
        direction: d,
    };
    let mut best = None;
    if let Some(n) = tri.normal().try_normalize() {
        for off in [n * r, -(n * r)] {
            let moved = Triangle::new(tri.v0 + off, tri.v1 + off, tri.v2 + off);
            best = nearer(
                best,
                ray_triangle(&ray, &moved, max_t).map(|h| LocalHit {
                    t: h.t,
                    normal: h.normal,
                }),
            );
        }
    }
    for (e0, e1) in [(tri.v0, tri.v1), (tri.v1, tri.v2), (tri.v2, tri.v0)] {
        best = nearer(
            best,
            ray_solid_capsule(o, d, &Capsule::new(e0, e1, r), max_t),
        );
    }
    best
}

// ============================================================================
// Geometry pieces
// ============================================================================

/// One piece of geometry a query tests, placed in the world.
enum Piece<'a> {
    Sphere {
        center: Vec3Fix,
        radius: Fix128,
    },
    Capsule(Capsule),
    Box {
        center: Vec3Fix,
        half: Vec3Fix,
        rotation: QuatFix,
    },
    Posed(PosedShape),
    Hull(ChildSupport<'a>),
    Plane(&'a PlaneCollider),
    Height(&'a HeightField),
    Mesh(&'a TriMesh),
    #[cfg(feature = "std")]
    Sdf(&'a crate::sdf_collider::SdfCollider),
}

/// The pieces of a body (see [`crate::shape_raycast`] for which geometry).
fn body_pieces(world: &PhysicsWorld, i: usize) -> Vec<Piece<'_>> {
    let Some((radius, collider)) = world.ray_geometry(i) else {
        return Vec::new();
    };
    let body = &world.bodies[i];
    match collider {
        None => vec![Piece::Sphere {
            center: body.position,
            radius,
        }],
        Some(BodyCollider::Shape(shape)) => {
            let posed = PosedShape {
                shape: *shape,
                position: body.position,
                rotation: body.rotation,
            };
            vec![match *shape {
                Shape::Box { half_extents } => {
                    let rotation = body.rotation.unit_rotation();
                    Piece::Box {
                        center: body.position - rotation.rotate_vec(shape.center_of_mass_offset()),
                        half: half_extents,
                        rotation,
                    }
                }
                _ => Piece::Posed(posed),
            }]
        }
        Some(BodyCollider::Compound(compound)) => compound
            .children
            .iter()
            .map(|child| child_piece(child, body.position, body.rotation))
            .collect(),
    }
}

/// One compound child, placed the way [`CompoundChild::support_world`] places it.
fn child_piece(child: &CompoundChild, body_pos: Vec3Fix, body_rot: QuatFix) -> Piece<'_> {
    let body_rot = body_rot.unit_rotation();
    let child_rot = body_rot.mul(child.local_rotation);
    let child_pos = body_pos + body_rot.rotate_vec(child.local_position);
    match &child.shape {
        ShapeRef::Sphere(s) => Piece::Sphere {
            center: child_pos + child_rot.rotate_vec(s.center),
            radius: s.radius,
        },
        ShapeRef::Capsule(c) => Piece::Capsule(Capsule::new(
            child_pos + child_rot.rotate_vec(c.a),
            child_pos + child_rot.rotate_vec(c.b),
            c.radius,
        )),
        ShapeRef::Box(b) => Piece::Box {
            center: child_pos + child_rot.rotate_vec(b.center),
            half: b.half_extents,
            rotation: child_rot.mul(b.rotation),
        },
        ShapeRef::ConvexHull(_) => Piece::Hull(ChildSupport {
            child,
            position: body_pos,
            rotation: body_rot,
        }),
    }
}

/// The geometric centre and frame of a posed shape.
fn posed_frame(posed: &PosedShape) -> (Vec3Fix, QuatFix) {
    let rotation = posed.rotation.unit_rotation();
    (
        posed.position - rotation.rotate_vec(posed.shape.center_of_mass_offset()),
        rotation,
    )
}

/// The query settings that pieces need.
struct Settings {
    #[cfg(feature = "std")]
    sdf: SdfCcdConfig,
}

impl Piece<'_> {
    /// The distance from the core `a`–`b`; `cap` bounds the search where a piece
    /// searches cells or triangles (it may report [`Dist::AtLeast`] beyond).
    fn dist(&self, a: Vec3Fix, b: Vec3Fix, cap: Fix128) -> Dist {
        match self {
            Self::Sphere { center, radius } => sphere_dist(a, b, *center, *radius),
            Self::Capsule(c) => capsule_dist(a, b, c),
            Self::Box {
                center,
                half,
                rotation,
            } => {
                if a == b {
                    let inv = rotation.conjugate();
                    let p = inv.rotate_vec(a - *center);
                    dist_to_world(point_box_local(p, *half), *center, *rotation)
                } else {
                    let obb = crate::box_collider::OrientedBox::new(*center, *half, *rotation);
                    convex_dist(a, b, &obb)
                }
            }
            Self::Posed(posed) => {
                let (center, rotation) = posed_frame(posed);
                let inv = rotation.conjugate();
                match posed.shape {
                    Shape::Cylinder {
                        radius,
                        half_height,
                    } if a == b => dist_to_world(
                        point_cylinder_local(inv.rotate_vec(a - center), radius, half_height),
                        center,
                        rotation,
                    ),
                    Shape::Torus {
                        major_radius,
                        minor_radius,
                    } => {
                        let f = |p: Vec3Fix| {
                            dist_to_world(
                                point_torus_local(
                                    inv.rotate_vec(p - center),
                                    major_radius,
                                    minor_radius,
                                ),
                                center,
                                rotation,
                            )
                        };
                        segment_min(a, b, f)
                    }
                    _ if is_round(posed) => convex_dist(a, b, &RoundSupport(posed)),
                    _ => convex_dist(a, b, posed),
                }
            }
            Self::Hull(child) => convex_dist(a, b, child),
            Self::Plane(plane) => plane_dist(plane, a, b),
            Self::Height(field) => heightfield_dist(field, a, b, cap),
            Self::Mesh(mesh) => mesh_dist(mesh, a, b, cap),
            #[cfg(feature = "std")]
            Self::Sdf(sdf) => segment_min(a, b, |p| point_sdf(sdf, p)),
        }
    }

    /// The first time the core `a`–`b` grown by `r` touches this piece moving
    /// along the unit `d`, when it does not overlap it at the start: closed forms
    /// for a point core against spheres, capsules, boxes, cylinders, tori,
    /// planes and triangles, the convex time of impact ([`toi_convex`]) for a
    /// segment core and the other convex pieces, a hierarchy of hulls for
    /// height-field cells and torus arcs ([`toi_tree`]), one time of impact per
    /// triangle for meshes, and sphere tracing for SDFs.
    fn sweep(
        &self,
        a: Vec3Fix,
        b: Vec3Fix,
        r: Fix128,
        d: Vec3Fix,
        max_t: Fix128,
        settings: &Settings,
    ) -> Option<Contact> {
        #[cfg(not(feature = "std"))]
        let _ = settings;
        let point_core = a == b;
        match self {
            Self::Sphere { center, radius } => {
                let c = if point_core {
                    let h = ray_solid_sphere(a, d, *center, *radius + r, max_t)?;
                    Contact::from_ray(a, d, r, h)
                } else {
                    // The capsule moving +d meets the sphere when the sphere's
                    // centre, moving −d, meets the capsule grown by its radius.
                    let grown = Capsule::new(a, b, r + *radius);
                    let h = ray_solid_capsule(*center, -d, &grown, max_t)?;
                    let normal = -h.normal;
                    Contact {
                        t: h.t,
                        point: *center + normal * *radius,
                        normal,
                    }
                };
                self.entering(c, a, b, r, d, max_t)
            }
            Self::Capsule(c) => {
                if point_core {
                    let grown = Capsule::new(c.a, c.b, c.radius + r);
                    let h = ray_solid_capsule(a, d, &grown, max_t)?;
                    self.entering(Contact::from_ray(a, d, r, h), a, b, r, d, max_t)
                } else {
                    toi_convex(a, b, r, c.radius, d, max_t, &SegmentSupport(c.a, c.b))
                }
            }
            Self::Box {
                center,
                half,
                rotation,
            } => {
                if point_core {
                    let (o, dl) = to_local(a, d, *center, *rotation);
                    let h = to_world(sweep_local_box(o, dl, *half, r, max_t), *rotation)?;
                    self.entering(Contact::from_ray(a, d, r, h), a, b, r, d, max_t)
                } else {
                    let obb = crate::box_collider::OrientedBox::new(*center, *half, *rotation);
                    toi_convex(a, b, r, Fix128::ZERO, d, max_t, &obb)
                }
            }
            Self::Posed(posed) => {
                let (center, rotation) = posed_frame(posed);
                match posed.shape {
                    Shape::Cylinder {
                        radius,
                        half_height,
                    } if point_core => {
                        let (o, dl) = to_local(a, d, center, rotation);
                        let found = to_world(
                            sweep_local_cylinder(o, dl, radius, half_height, r, max_t),
                            rotation,
                        );
                        let cap = r + r + Fix128::ONE;
                        // The closed form is the first ray hit on the cylinder
                        // grown by `r` (two cylinders and two tori); taken only
                        // where the exact distance agrees (see
                        // `sweep_local_cylinder`), with the contact's point and
                        // normal from the nearest point of the cylinder.
                        let checked = found.and_then(|h| {
                            if h.t.is_zero() {
                                return Some(Contact::from_ray(a, d, r, h));
                            }
                            let c = a + d * h.t;
                            match self.dist(c, c, cap) {
                                Dist::Outside {
                                    dist,
                                    point,
                                    normal,
                                } if dist - r >= -TRACE_TOLERANCE => Some(Contact {
                                    t: h.t,
                                    point,
                                    normal,
                                }),
                                _ => None,
                            }
                        });
                        match checked {
                            Some(c) => self.entering(c, a, b, r, d, max_t),
                            None => toi_by(a, b, r, Fix128::ZERO, d, max_t, |p, q, _| {
                                let found = self.dist(p, q, cap);
                                let bound = Bound::exact(&found);
                                (found, bound)
                            }),
                        }
                    }
                    Shape::Torus {
                        major_radius,
                        minor_radius,
                    } => {
                        let ring = Ring {
                            center,
                            rotation,
                            major: major_radius,
                            minor: minor_radius,
                        };
                        if point_core {
                            let (o, dl) = to_local(a, d, center, rotation);
                            let h = ray_local_torus(o, dl, major_radius, minor_radius + r, max_t);
                            let c = Contact::from_ray(a, d, r, to_world(h, rotation)?);
                            // A torus is not convex: leaving it where the sphere
                            // touches it, the path can still enter it further on.
                            self.entering(c, a, b, r, d, max_t)
                                .or_else(|| ring.sweep(a, b, r, d, max_t))
                        } else {
                            ring.sweep(a, b, r, d, max_t)
                        }
                    }
                    _ if is_round(posed) => {
                        toi_convex(a, b, r, Fix128::ZERO, d, max_t, &RoundSupport(posed))
                    }
                    Shape::Cylinder { .. } | Shape::Cone { .. } => toi_convex_refined(
                        a,
                        b,
                        r,
                        Fix128::ZERO,
                        d,
                        max_t,
                        posed,
                        round_support_slack(posed),
                        |p, q| exact_round_dist(posed, p, q),
                    ),
                    _ => toi_convex(a, b, r, Fix128::ZERO, d, max_t, posed),
                }
            }
            Self::Hull(child) => toi_convex(a, b, r, Fix128::ZERO, d, max_t, child),
            Self::Plane(plane) => sweep_plane(plane, a, b, r, d, max_t),
            Self::Height(field) => sweep_heightfield(field, a, b, r, d, max_t),
            Self::Mesh(mesh) => {
                if point_core {
                    let swept = core_box(a, a + d * max_t, r);
                    let mut best: Option<Contact> = None;
                    for i in mesh_candidates(mesh, &swept) {
                        let tri = &mesh.triangles[i as usize];
                        let Some(h) = sweep_triangle(a, d, tri, r, max_t) else {
                            continue;
                        };
                        let gap_at = |t: Fix128| {
                            let p = a + d * t;
                            match Dist::toward(p, tri.closest_point(p)) {
                                Dist::Outside { dist, .. } => Some(dist - r),
                                _ => None,
                            }
                        };
                        let mut c = Contact::from_ray(a, d, r, h);
                        if c.t <= TRACE_TOLERANCE {
                            // Touching this triangle at the start: its own
                            // nearest point and normal (see `entering`).
                            if let Dist::Outside { point, normal, .. } =
                                Dist::toward(a, tri.closest_point(a))
                            {
                                c = Contact {
                                    t: Fix128::ZERO,
                                    point,
                                    normal,
                                };
                            }
                        }
                        if !touch_is_hit(c, d, max_t, gap_at) {
                            continue;
                        }
                        if best.is_none_or(|bc| c.t < bc.t) {
                            best = Some(c);
                        }
                    }
                    best
                } else {
                    sweep_mesh(mesh, a, b, r, d, max_t)
                }
            }
            #[cfg(feature = "std")]
            Self::Sdf(_) => {
                let tol = Fix128::from_f32(settings.sdf.tolerance);
                self.trace(a, b, r, d, max_t, tol)
            }
        }
        .filter(|c| c.t >= Fix128::ZERO && c.t <= max_t)
    }

    /// A closed-form contact is a hit by [`touch_is_hit`]. One at `t ≤ 2⁻³²`
    /// comes from a cast that starts touching the piece (an overlap is reported
    /// before the sweep): its normal and point are the piece's nearest point and
    /// normal toward the core (a closed form may report a touching origin as
    /// inside). Moving away or along the surface is not a hit, nor is a tangent
    /// arrival.
    fn entering(
        &self,
        c: Contact,
        a: Vec3Fix,
        b: Vec3Fix,
        r: Fix128,
        d: Vec3Fix,
        max_t: Fix128,
    ) -> Option<Contact> {
        let cap = r + r + Fix128::ONE;
        let gap_at = |t: Fix128| {
            let off = d * t;
            match self.dist(a + off, b + off, cap) {
                Dist::Outside { dist, .. } => Some(dist - r),
                Dist::AtLeast(bound) => Some(bound - r),
                Dist::Inside => None,
            }
        };
        let c = if c.t > TRACE_TOLERANCE {
            c
        } else {
            match self.dist(a, b, cap) {
                Dist::Outside { point, normal, .. } => Contact {
                    t: Fix128::ZERO,
                    point,
                    normal,
                },
                _ => return Some(c),
            }
        };
        touch_is_hit(c, d, max_t, gap_at).then_some(c)
    }

    /// Sphere tracing (for SDFs): step by the gap (the distance less `r`) until
    /// it is below `tol`. A field that is a true distance never lets a step pass
    /// the surface; if the step budget runs out the last position is reported
    /// (never after the contact), not "no hit".
    #[cfg(feature = "std")]
    fn trace(
        &self,
        a: Vec3Fix,
        b: Vec3Fix,
        r: Fix128,
        d: Vec3Fix,
        max_t: Fix128,
        tol: Fix128,
    ) -> Option<Contact> {
        let mut t = Fix128::ZERO;
        let cap = r + r + Fix128::ONE;
        let mut last: Option<Contact> = None;
        for _ in 0..SDF_MAX_STEPS {
            let off = d * t;
            let gap = match self.dist(a + off, b + off, cap) {
                Dist::Inside => {
                    return Some(Contact {
                        t,
                        point: half_vec(a + b) + off,
                        normal: -d,
                    })
                }
                Dist::AtLeast(bound) => bound - r,
                Dist::Outside {
                    dist,
                    point,
                    normal,
                } => {
                    let gap = dist - r;
                    let contact = Contact { t, point, normal };
                    last = Some(contact);
                    if gap <= tol {
                        // Touching: a hit only when moving into the surface;
                        // moving away or along it, step past by the tolerance.
                        if d.dot(normal).is_negative() {
                            return Some(contact);
                        }
                        tol
                    } else {
                        gap
                    }
                }
            };
            if gap <= Fix128::ZERO {
                return None;
            }
            t = t + gap;
            if t > max_t {
                return None;
            }
        }
        last
    }

    /// Whether this piece overlaps `aabb` (see the module doc).
    fn meets_aabb(&self, aabb: &AABB) -> bool {
        match self {
            Self::Sphere { center, radius } => {
                (closest_on_aabb(aabb, *center) - *center).length_squared() < *radius * *radius
            }
            Self::Capsule(c) => match gjk_distance(&SegmentSupport(c.a, c.b), aabb) {
                None => true,
                Some((dist, _, _)) => dist < c.radius,
            },
            Self::Box {
                center,
                half,
                rotation,
            } => obb_meets_aabb(*center, *half, *rotation, aabb),
            Self::Posed(posed) => match posed.shape {
                Shape::Torus {
                    major_radius,
                    minor_radius,
                } => torus_meets_aabb(posed, major_radius, minor_radius, aabb),
                _ => gjk_distance(posed, aabb).is_none(),
            },
            Self::Hull(child) => gjk_distance(child, aabb).is_none(),
            Self::Plane(plane) => {
                let c = half_vec(aabb.min + aabb.max);
                let h = half_vec(aabb.max - aabb.min);
                let n = plane.normal;
                let reach = n.x.abs() * h.x + n.y.abs() * h.y + n.z.abs() * h.z;
                (n.dot(c) - plane.offset).abs() < reach
            }
            Self::Height(field) => heightfield_meets_aabb(field, aabb),
            Self::Mesh(mesh) => mesh_candidates(mesh, aabb).into_iter().any(|i| {
                gjk_distance(&TriangleSupport(&mesh.triangles[i as usize]), aabb).is_none()
            }),
            #[cfg(feature = "std")]
            Self::Sdf(sdf) => sdf_meets_aabb(sdf, aabb),
        }
    }
}

/// A contact of a cast: distance along the direction, contact point, normal.
#[derive(Clone, Copy, Debug)]
struct Contact {
    t: Fix128,
    point: Vec3Fix,
    normal: Vec3Fix,
}

impl Contact {
    /// A ray hit on the Minkowski sum turned into the contact of the sphere of `r`
    /// whose centre moved from `o` along `d`.
    fn from_ray(o: Vec3Fix, d: Vec3Fix, r: Fix128, h: LocalHit) -> Self {
        Self {
            t: h.t,
            point: o + d * h.t - h.normal * r,
            normal: h.normal,
        }
    }
}

/// A box of half-extents `h` grown by `r` (rounded), in its frame: the three
/// slabs (the box pushed out by `r` along one axis) and the 12 edges as capsules.
fn sweep_local_box(
    o: Vec3Fix,
    d: Vec3Fix,
    h: Vec3Fix,
    r: Fix128,
    max_t: Fix128,
) -> Option<LocalHit> {
    let mut best = None;
    for grow in [
        Vec3Fix::new(r, Fix128::ZERO, Fix128::ZERO),
        Vec3Fix::new(Fix128::ZERO, r, Fix128::ZERO),
        Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, r),
    ] {
        best = nearer(best, ray_planes(o, d, &box_planes(h + grow), max_t));
    }
    let signs = [Fix128::ONE, Fix128::NEG_ONE];
    for &s1 in &signs {
        for &s2 in &signs {
            for (a, b) in [
                (
                    Vec3Fix::new(-h.x, s1 * h.y, s2 * h.z),
                    Vec3Fix::new(h.x, s1 * h.y, s2 * h.z),
                ),
                (
                    Vec3Fix::new(s1 * h.x, -h.y, s2 * h.z),
                    Vec3Fix::new(s1 * h.x, h.y, s2 * h.z),
                ),
                (
                    Vec3Fix::new(s1 * h.x, s2 * h.y, -h.z),
                    Vec3Fix::new(s1 * h.x, s2 * h.y, h.z),
                ),
            ] {
                best = nearer(best, ray_solid_capsule(o, d, &Capsule::new(a, b, r), max_t));
            }
        }
    }
    best
}

/// A cylinder along `Y` grown by `r` (rounded), in its frame: the cylinder of
/// radius `radius + r`, the one of half height `hh + r`, and the two rim tori.
///
/// The faces of the two cylinders beyond the rims (the side of the tall one
/// above a cap, the caps of the wide one outside the radius) are inside the
/// tori; they are the first hit only when a torus is not found. The torus ray
/// is sphere traced, and a path at a small angle to a cap (`10⁻⁶` rad) or
/// along its plane through the rounded rim takes more than its step budget:
/// it was then reported on the tall cylinder's side, `r` off the surface with a
/// horizontal normal, or deep in the cap, or not at all. The caller checks a
/// hit against the exact distance and falls back to the time of impact on that
/// distance.
fn sweep_local_cylinder(
    o: Vec3Fix,
    d: Vec3Fix,
    radius: Fix128,
    hh: Fix128,
    r: Fix128,
    max_t: Fix128,
) -> Option<LocalHit> {
    let mut best = ray_local_cylinder(o, d, radius + r, hh, max_t);
    best = nearer(best, ray_local_cylinder(o, d, radius, hh + r, max_t));
    for y in [hh, -hh] {
        let shift = Vec3Fix::new(Fix128::ZERO, y, Fix128::ZERO);
        best = nearer(best, ray_local_torus(o - shift, d, radius, r, max_t));
    }
    best
}

/// Whether an oriented box overlaps an axis-aligned one, by the separating axis
/// theorem (the 3 + 3 face axes and the 9 edge cross products): they overlap
/// when no axis separates them, and boxes that only touch (projections meeting
/// at a point) do not overlap. Cross products of parallel edges are zero and
/// separate nothing; they are skipped.
fn obb_meets_aabb(center: Vec3Fix, half: Vec3Fix, rotation: QuatFix, aabb: &AABB) -> bool {
    let z = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ONE);
    let a_axes = [
        rotation.rotate_vec(Vec3Fix::UNIT_X),
        rotation.rotate_vec(Vec3Fix::UNIT_Y),
        rotation.rotate_vec(z),
    ];
    let a_half = [half.x, half.y, half.z];
    let b_axes = [Vec3Fix::UNIT_X, Vec3Fix::UNIT_Y, z];
    let b_center = half_vec(aabb.min + aabb.max);
    let b_ext = half_vec(aabb.max - aabb.min);
    let b_half = [b_ext.x, b_ext.y, b_ext.z];
    let between = b_center - center;
    let separates = |l: Vec3Fix| {
        let reach_a: Fix128 = (0..3).fold(Fix128::ZERO, |acc, i| {
            acc + a_half[i] * a_axes[i].dot(l).abs()
        });
        let reach_b: Fix128 = (0..3).fold(Fix128::ZERO, |acc, i| {
            acc + b_half[i] * b_axes[i].dot(l).abs()
        });
        between.dot(l).abs() >= reach_a + reach_b
    };
    let mut axes: Vec<Vec3Fix> = Vec::with_capacity(15);
    axes.extend_from_slice(&a_axes);
    axes.extend_from_slice(&b_axes);
    for ea in a_axes {
        for eb in b_axes {
            let l = ea.cross(eb);
            if !l.length_squared().is_zero() {
                axes.push(l);
            }
        }
    }
    !axes.into_iter().any(separates)
}

/// The distance from the core `a`–`b` to a two-sided plane.
fn plane_dist(plane: &PlaneCollider, a: Vec3Fix, b: Vec3Fix) -> Dist {
    let n = plane.normal;
    let sa = n.dot(a) - plane.offset;
    let sb = n.dot(b) - plane.offset;
    if !sa.is_zero() && !sb.is_zero() && sa.is_negative() != sb.is_negative() {
        // The segment crosses the plane.
        return Dist::Inside;
    }
    let (p, s) = if sb.abs() < sa.abs() {
        (b, sb)
    } else {
        (a, sa)
    };
    // An end on the plane is touching it, on the side of the other end.
    let other = if sb.abs() < sa.abs() { sa } else { sb };
    let side = if s.is_negative() || (s.is_zero() && other.is_negative()) {
        -n
    } else {
        n
    };
    Dist::Outside {
        dist: s.abs(),
        point: p - n * s,
        normal: side,
    }
}

/// A capsule (or sphere) swept against a two-sided plane: the nearer end reaches
/// distance `r`.
fn sweep_plane(
    plane: &PlaneCollider,
    a: Vec3Fix,
    b: Vec3Fix,
    r: Fix128,
    d: Vec3Fix,
    max_t: Fix128,
) -> Option<Contact> {
    let n = plane.normal;
    let sa = n.dot(a) - plane.offset;
    let sb = n.dot(b) - plane.offset;
    if sa.is_zero() || sb.is_zero() || sa.is_negative() != sb.is_negative() {
        return None;
    }
    // The nearer end (the first on a tie).
    let (p, s) = if sb.abs() < sa.abs() {
        (b, sb)
    } else {
        (a, sa)
    };
    let normal = if s.is_negative() { -n } else { n };
    let speed = -normal.dot(d);
    if speed <= Fix128::ZERO {
        return None;
    }
    let gap = s.abs() - r;
    // A sink slower than 2⁻³² per unit of travel is a hit when the core is more
    // than 2⁻³² inside the plane by `max_t` (the rule of `touch_is_hit` for a
    // motion near the tangent plane); its time is bounded by `ratio_within`.
    if speed < PARALLEL_EPSILON && gap - speed * max_t >= -TRACE_TOLERANCE {
        return None;
    }
    // A start within the tolerance inside the plane's reach (deeper is a start
    // overlap, reported before the sweep) is touching: contact at once.
    let t = max_fix(ratio_within(gap, speed, max_t + Fix128::ONE), Fix128::ZERO);
    if t > max_t {
        return None;
    }
    Some(Contact {
        t,
        point: p + d * t - normal * r,
        normal,
    })
}

/// Whether a torus meets `aabb`: its ring comes within `minor` of the box.
fn torus_meets_aabb(posed: &PosedShape, major: Fix128, minor: Fix128, aabb: &AABB) -> bool {
    let (center, rotation) = posed_frame(posed);
    // Quick rejection by the bounding sphere.
    if (closest_on_aabb(aabb, center) - center).length() >= major + minor {
        return false;
    }
    let ring = |s: Fix128| {
        let (sin, cos) = (Fix128::TWO_PI * s).sin_cos();
        center + rotation.rotate_vec(Vec3Fix::new(major * cos, Fix128::ZERO, major * sin))
    };
    let d = curve_min(Fix128::TWO_PI * major, |s| {
        let p = ring(s);
        let q = closest_on_aabb(aabb, p);
        if q == p {
            Dist::Inside
        } else {
            Dist::toward(p, q)
        }
    });
    d.within(minor)
}

#[cfg(feature = "std")]
fn point_sdf(sdf: &crate::sdf_collider::SdfCollider, p: Vec3Fix) -> Dist {
    let (lx, ly, lz) = sdf.world_to_local(p);
    let (d, (nx, ny, nz)) = sdf.field.distance_and_normal(lx, ly, lz);
    let d = d * sdf.scale_f32;
    if !d.is_finite() || d < 0.0 {
        return Dist::Inside;
    }
    let dist = Fix128::from_f32(d);
    let normal = sdf.local_normal_to_world(nx, ny, nz);
    Dist::Outside {
        dist,
        point: p - normal * dist,
        normal,
    }
}

/// Whether an SDF solid meets `aabb`: an octree subdivision of the box, pruning
/// cells whose centre is farther than their half-diagonal from the surface and
/// accepting a centre inside; a leaf (depth `SDF_BOX_DEPTH`) within its
/// half-diagonal is counted as meeting.
#[cfg(feature = "std")]
fn sdf_meets_aabb(sdf: &crate::sdf_collider::SdfCollider, aabb: &AABB) -> bool {
    let mut stack = vec![(aabb.min, aabb.max, 0u32)];
    while let Some((lo, hi, depth)) = stack.pop() {
        let c = half_vec(lo + hi);
        let half_diag = half_vec(hi - lo).length();
        let d = match point_sdf(sdf, c) {
            Dist::Inside => return true,
            Dist::Outside { dist, .. } => dist,
            Dist::AtLeast(d) => d,
        };
        if d >= half_diag {
            continue;
        }
        if depth >= SDF_BOX_DEPTH {
            return true;
        }
        for k in 0..8u8 {
            let pick = |bit: u8, l: Fix128, m: Fix128, h: Fix128| {
                if k & bit == 0 {
                    (l, m)
                } else {
                    (m, h)
                }
            };
            let (x0, x1) = pick(1, lo.x, c.x, hi.x);
            let (y0, y1) = pick(2, lo.y, c.y, hi.y);
            let (z0, z1) = pick(4, lo.z, c.z, hi.z);
            stack.push((
                Vec3Fix::new(x0, y0, z0),
                Vec3Fix::new(x1, y1, z1),
                depth + 1,
            ));
        }
    }
    false
}

/// The box of the segment `a`–`b` grown by `r`.
fn core_box(a: Vec3Fix, b: Vec3Fix, r: Fix128) -> AABB {
    let lo = Vec3Fix::new(min_fix(a.x, b.x), min_fix(a.y, b.y), min_fix(a.z, b.z));
    let hi = Vec3Fix::new(max_fix(a.x, b.x), max_fix(a.y, b.y), max_fix(a.z, b.z));
    let g = Vec3Fix::new(r, r, r);
    AABB::new(lo - g, hi + g)
}

/// The distance between two boxes (zero when they meet).
fn aabb_gap(a: &AABB, b: &AABB) -> Fix128 {
    let gap = |lo1: Fix128, hi1: Fix128, lo2: Fix128, hi2: Fix128| {
        max_fix(Fix128::ZERO, max_fix(lo2 - hi1, lo1 - hi2))
    };
    Vec3Fix::new(
        gap(a.min.x, a.max.x, b.min.x, b.max.x),
        gap(a.min.y, a.max.y, b.min.y, b.max.y),
        gap(a.min.z, a.max.z, b.min.z, b.max.z),
    )
    .length()
}

/// `direction` scaled down by its largest component when that is above `2²⁰`,
/// so that normalizing it does not overflow the squared length (`i64::MAX / 2`
/// squared wraps); smaller directions are returned as they are.
fn tame_direction(direction: Vec3Fix) -> Vec3Fix {
    let m = max_fix(
        max_fix(direction.x.abs(), direction.y.abs()),
        direction.z.abs(),
    );
    if m > Fix128::from_int(1 << 20) {
        direction / m
    } else {
        direction
    }
}

fn box_is_valid(aabb: &AABB) -> bool {
    aabb.min.x <= aabb.max.x && aabb.min.y <= aabb.max.y && aabb.min.z <= aabb.max.z
}

// ============================================================================
// World queries
// ============================================================================

/// The colliders a query sees whose box meets `query`: each target with its body
/// and its pieces, in target order.
fn for_each_target<'w>(
    world: &'w PhysicsWorld,
    filter: &RayFilter,
    query: &AABB,
    mut visit: impl FnMut(RayTarget, Option<usize>, &[Piece<'w>]),
) {
    let (bvh, _) = world.query_body_bvh(filter);
    let mut bodies: Vec<u32> = bvh.query(query);
    bodies.sort_unstable();
    bodies.dedup();
    for i in bodies {
        let i = i as usize;
        let pieces = body_pieces(world, i);
        visit(RayTarget::Body(i), Some(i), &pieces);
    }
    if filter.include_static {
        for (j, collider) in world.static_colliders_slice().iter().enumerate() {
            let piece = match collider {
                StaticCollider::Plane(p) => Piece::Plane(p),
                StaticCollider::HeightField(f) => Piece::Height(f),
                StaticCollider::TriMesh(m) => Piece::Mesh(m),
            };
            visit(
                RayTarget::StaticCollider(j),
                None,
                core::slice::from_ref(&piece),
            );
        }
    }
    #[cfg(feature = "std")]
    if filter.include_sdf {
        for (k, sdf) in world.sdf_colliders.iter().enumerate() {
            let body = (sdf.body_index < world.bodies.len()).then_some(sdf.body_index);
            if body.is_some_and(|b| !filter.sees_body(world, b)) {
                continue;
            }
            let piece = Piece::Sdf(sdf);
            visit(RayTarget::Sdf(k), body, core::slice::from_ref(&piece));
        }
    }
}

impl PhysicsWorld {
    /// The nearest collider a sphere of `radius` touches when its centre moves
    /// from `center` along `direction` for at most `max_t` (see
    /// [`crate::world_shape_query`] for the conventions). Radius `0` is
    /// [`PhysicsWorld::cast_ray`]; a negative radius, a zero direction or
    /// `max_t ≤ 0` gives `None`.
    #[must_use]
    pub fn cast_sphere(
        &self,
        center: Vec3Fix,
        radius: Fix128,
        direction: Vec3Fix,
        max_t: Fix128,
        filter: &RayFilter,
    ) -> Option<WorldShapeHit> {
        if radius.is_negative() {
            return None;
        }
        let direction = tame_direction(direction);
        if radius.is_zero() {
            return self
                .cast_ray(center, direction, max_t, filter)
                .map(|h| WorldShapeHit {
                    t: h.t,
                    point: h.point,
                    normal: h.normal,
                    target: h.target,
                    body: h.body,
                });
        }
        self.cast_core(center, center, radius, direction, max_t, filter)
    }

    /// The nearest collider a capsule (segment `a`–`b` grown by `radius`) touches
    /// when it moves along `direction` for at most `max_t`. Coinciding ends are
    /// [`PhysicsWorld::cast_sphere`]; a negative radius, a zero direction or
    /// `max_t ≤ 0` gives `None`.
    #[must_use]
    pub fn cast_capsule(
        &self,
        a: Vec3Fix,
        b: Vec3Fix,
        radius: Fix128,
        direction: Vec3Fix,
        max_t: Fix128,
        filter: &RayFilter,
    ) -> Option<WorldShapeHit> {
        if a == b {
            return self.cast_sphere(a, radius, direction, max_t, filter);
        }
        if radius.is_negative() {
            return None;
        }
        self.cast_core(a, b, radius, tame_direction(direction), max_t, filter)
    }

    /// Every collider a sphere of `radius` about `center` overlaps, sorted by
    /// target. A negative radius gives an empty list; radius `0` finds the solids
    /// `center` is strictly inside.
    #[must_use]
    pub fn overlap_sphere(
        &self,
        center: Vec3Fix,
        radius: Fix128,
        filter: &RayFilter,
    ) -> Vec<RayTarget> {
        let mut out = Vec::new();
        if radius.is_negative() {
            return out;
        }
        let query = core_box(center, center, radius);
        let cap = radius + radius + Fix128::ONE;
        for_each_target(self, filter, &query, |target, _, pieces| {
            if pieces
                .iter()
                .any(|p| p.dist(center, center, cap).within(radius))
            {
                out.push(target);
            }
        });
        out.sort_unstable();
        out
    }

    /// Every collider `aabb` overlaps, sorted by target (see
    /// [`crate::world_shape_query`]). A box with `min > max` on any axis gives an
    /// empty list.
    #[must_use]
    pub fn overlap_aabb(&self, aabb: &AABB, filter: &RayFilter) -> Vec<RayTarget> {
        let mut out = Vec::new();
        if !box_is_valid(aabb) {
            return out;
        }
        for_each_target(self, filter, aabb, |target, _, pieces| {
            if pieces.iter().any(|p| p.meets_aabb(aabb)) {
                out.push(target);
            }
        });
        out.sort_unstable();
        out
    }

    /// The colliders the capsule (segment `a`–`b` grown by `r`) overlaps, each
    /// with its penetration along the normal at the segment point nearest it,
    /// sorted by target (the pieces of one target, such as compound children, in
    /// their order); `None` when the segment itself meets a solid (no distance, so
    /// no push-out direction). Used by [`PhysicsWorld::move_character`] to push a capsule out.
    pub(crate) fn capsule_penetrations(
        &self,
        a: Vec3Fix,
        b: Vec3Fix,
        r: Fix128,
        filter: &RayFilter,
    ) -> Option<Vec<Penetration>> {
        let query = core_box(a, b, r);
        let cap = r + r + Fix128::ONE;
        let mut out = Vec::new();
        let mut core_inside = false;
        for_each_target(self, filter, &query, |target, _, pieces| {
            for piece in pieces {
                match piece.dist(a, b, cap) {
                    Dist::Inside => core_inside = true,
                    Dist::Outside { dist, normal, .. } if dist + TRACE_TOLERANCE < r => {
                        out.push(Penetration {
                            target,
                            depth: r - dist,
                            normal,
                        })
                    }
                    _ => {}
                }
            }
        });
        if core_inside {
            return None;
        }
        out.sort_by_key(|x| x.target);
        Some(out)
    }

    /// The nearest hit of the core `a`–`b` grown by `r > 0` (or `r = 0` with
    /// `a ≠ b`) moving along `direction`.
    ///
    /// `direction` must have gone through `tame_direction` (both callers do):
    /// the `try_normalize` below squares it and wraps for components of `2³¹·⁵`
    /// or more.
    fn cast_core(
        &self,
        a: Vec3Fix,
        b: Vec3Fix,
        r: Fix128,
        direction: Vec3Fix,
        max_t: Fix128,
        filter: &RayFilter,
    ) -> Option<WorldShapeHit> {
        if max_t <= Fix128::ZERO {
            return None;
        }
        let d = direction.try_normalize()?;
        let settings = Settings {
            #[cfg(feature = "std")]
            sdf: filter.sdf,
        };
        let swept = {
            let start = core_box(a, b, r);
            let end = core_box(a + d * max_t, b + d * max_t, r);
            AABB::new(
                Vec3Fix::new(
                    min_fix(start.min.x, end.min.x),
                    min_fix(start.min.y, end.min.y),
                    min_fix(start.min.z, end.min.z),
                ),
                Vec3Fix::new(
                    max_fix(start.max.x, end.max.x),
                    max_fix(start.max.y, end.max.y),
                    max_fix(start.max.z, end.max.z),
                ),
            )
        };
        let start_cap = r + r + Fix128::ONE;
        let centre = half_vec(a + b);
        let mut best: Option<WorldShapeHit> = None;
        for_each_target(self, filter, &swept, |target, body, pieces| {
            let mut nearest: Option<Contact> = None;
            for piece in pieces {
                let c = if starts_overlapping(&piece.dist(a, b, start_cap), r) {
                    Some(Contact {
                        t: Fix128::ZERO,
                        point: centre,
                        normal: -d,
                    })
                } else {
                    piece.sweep(a, b, r, d, max_t, &settings)
                };
                if let Some(c) = c {
                    if nearest.is_none_or(|n| c.t < n.t) {
                        nearest = Some(c);
                    }
                }
            }
            if let Some(c) = nearest {
                let hit = WorldShapeHit {
                    t: c.t,
                    point: c.point,
                    normal: c.normal,
                    target,
                    body,
                };
                if best.is_none_or(|b| (hit.t, hit.target) < (b.t, b.target)) {
                    best = Some(hit);
                }
            }
        });
        best
    }
}

#[cfg(test)]
mod tests {
    //! Closed-form unit tests of the swept and overlap queries: every expected
    //! distance, normal and point is written from the geometry by hand (the
    //! closed form is in a comment next to each assertion); none calls the code
    //! under test. A sphere of radius `r` swept along a unit direction first
    //! touches a solid `S` where its centre reaches the boundary of
    //! `S ⊕ ball(r)`.
    //!
    //! `EXACT = 1e-12` for closed-form paths (spheres, boxes against a point
    //! core, planes, triangles, cylinders); `ITER = 1e-8` for iterative ones (GJK,
    //! convex time of impact, height-field parts, torus arcs).

    use super::*;
    use crate::box_collider::OrientedBox;
    use crate::collider::{ConvexHull, Sphere};
    use crate::compound::CompoundShape;
    use crate::solver::{PhysicsConfig, RigidBody};

    const EXACT: f64 = 1e-12;
    const ITER: f64 = 1e-8;

    fn fx(v: f64) -> Fix128 {
        Fix128::from_f64(v)
    }

    fn v3(x: f64, y: f64, z: f64) -> Vec3Fix {
        Vec3Fix::new(fx(x), fx(y), fx(z))
    }

    fn p3(p: [f64; 3]) -> Vec3Fix {
        v3(p[0], p[1], p[2])
    }

    fn world() -> PhysicsWorld {
        PhysicsWorld::new(PhysicsConfig::default())
    }

    fn all() -> RayFilter {
        RayFilter::default()
    }

    fn sphere_cast(
        w: &PhysicsWorld,
        c: [f64; 3],
        r: f64,
        d: [f64; 3],
        max: f64,
    ) -> Option<WorldShapeHit> {
        w.cast_sphere(p3(c), fx(r), p3(d), fx(max), &all())
    }

    fn capsule_cast(
        w: &PhysicsWorld,
        a: [f64; 3],
        b: [f64; 3],
        r: f64,
        d: [f64; 3],
        max: f64,
    ) -> Option<WorldShapeHit> {
        w.cast_capsule(p3(a), p3(b), fx(r), p3(d), fx(max), &all())
    }

    fn overlap_s(w: &PhysicsWorld, c: [f64; 3], r: f64) -> Vec<RayTarget> {
        w.overlap_sphere(p3(c), fx(r), &all())
    }

    fn overlap_b(w: &PhysicsWorld, lo: [f64; 3], hi: [f64; 3]) -> Vec<RayTarget> {
        w.overlap_aabb(&AABB::new(p3(lo), p3(hi)), &all())
    }

    fn unit(v: [f64; 3]) -> [f64; 3] {
        let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
        [v[0] / l, v[1] / l, v[2] / l]
    }

    #[track_caller]
    fn assert_vec(got: Vec3Fix, want: [f64; 3], tol: f64, what: &str) {
        let g = [got.x.to_f64(), got.y.to_f64(), got.z.to_f64()];
        for k in 0..3 {
            assert!(
                (g[k] - want[k]).abs() < tol,
                "{what} {g:?} but the closed form is {want:?}"
            );
        }
    }

    /// A hit on `target` at `t` with `normal` (normalized here) and `point`.
    #[track_caller]
    fn assert_hit(
        hit: Option<WorldShapeHit>,
        target: RayTarget,
        t: f64,
        normal: [f64; 3],
        point: [f64; 3],
        tol: f64,
    ) {
        let h = hit.unwrap_or_else(|| panic!("expected a hit at t = {t}, got none"));
        assert_eq!(h.target, target, "target");
        assert!(
            (h.t.to_f64() - t).abs() < tol,
            "t = {} but the closed form is {t}",
            h.t.to_f64()
        );
        assert_vec(h.normal, unit(normal), tol, "normal");
        assert_vec(h.point, point, tol, "point");
    }

    /// A capsule cast onto a flat face parallel to its segment: every point under
    /// the segment is a contact, so only `t`, the normal and the contact's height
    /// `y` are unique; its `x` lies between the ends' `x0..x1`.
    #[track_caller]
    fn assert_face_hit(
        hit: Option<WorldShapeHit>,
        target: RayTarget,
        t: f64,
        y: f64,
        x0: f64,
        x1: f64,
    ) {
        let h = hit.unwrap_or_else(|| panic!("expected a hit at t = {t}, got none"));
        assert_eq!(h.target, target, "target");
        assert!((h.t.to_f64() - t).abs() < ITER, "t = {}", h.t.to_f64());
        assert_vec(h.normal, [0.0, 1.0, 0.0], ITER, "normal");
        assert!(
            (h.point.y.to_f64() - y).abs() < ITER,
            "y = {}",
            h.point.y.to_f64()
        );
        let x = h.point.x.to_f64();
        assert!(x > x0 - ITER && x < x1 + ITER, "x = {x}");
    }

    fn shaped(w: &mut PhysicsWorld, shape: Shape, pos: Vec3Fix) -> usize {
        w.add_shaped_body(&shape, Fix128::ONE, pos)
            .expect("valid shape")
    }

    fn unit_box(w: &mut PhysicsWorld) -> usize {
        shaped(
            w,
            Shape::Box {
                half_extents: v3(1.0, 1.0, 1.0),
            },
            Vec3Fix::ZERO,
        )
    }

    fn sphere_body(w: &mut PhysicsWorld, pos: Vec3Fix, r: f64) -> usize {
        w.add_body_with_radius(RigidBody::new_static(pos), fx(r))
    }

    fn plane(w: &mut PhysicsWorld, normal: Vec3Fix, offset: f64) -> usize {
        w.add_static_collider(StaticCollider::Plane(PlaneCollider::new(
            normal,
            fx(offset),
        )))
    }

    /// The two triangles of the floor square `[0, 4]²` at `y = 0`.
    fn floor_mesh(w: &mut PhysicsWorld) -> usize {
        let verts = [
            v3(0.0, 0.0, 0.0),
            v3(4.0, 0.0, 0.0),
            v3(4.0, 0.0, 4.0),
            v3(0.0, 0.0, 4.0),
        ];
        w.add_static_collider(StaticCollider::TriMesh(TriMesh::from_indexed(
            &verts,
            &[0, 1, 2, 0, 2, 3],
        )))
    }

    /// One bilinear cell over `[0, 1]²` with corner heights `0, 0, 0, 1`: the
    /// twisted surface `y = x·z`.
    fn saddle_field(w: &mut PhysicsWorld) -> usize {
        let heights = vec![Fix128::ZERO, Fix128::ZERO, Fix128::ZERO, Fix128::ONE];
        w.add_static_collider(StaticCollider::HeightField(HeightField::new(
            heights,
            2,
            2,
            Fix128::ONE,
            Vec3Fix::ZERO,
        )))
    }

    // ------------------------------------------------------------ sphere cast

    #[test]
    fn sphere_cast_against_a_sphere_body() {
        let mut w = world();
        let b = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        // oracle: head-on, the centre reaches |c| = R + r = 1.5: t = 10 − 1.5;
        // the direction (2, 0, 0) is normalized first.
        assert_hit(
            sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [2.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.5,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
        // oracle: on the line y = 0.6, x = −√(1.5² − 0.36) = −√1.89 at contact,
        // t = 10 − √1.89, normal c/1.5, contact R·normal.
        let s = 1.89f64.sqrt();
        let n = [-s / 1.5, 0.6 / 1.5, 0.0];
        assert_hit(
            sphere_cast(&w, [-10.0, 0.6, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            10.0 - s,
            n,
            n,
            EXACT,
        );
        // oracle: the line y = 1.6 passes 1.6 > 1.5 from the centre: no contact.
        assert_eq!(
            sphere_cast(&w, [-10.0, 1.6, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            None
        );
        // oracle: the contact at t = 8.5 is beyond max_t = 5.
        assert_eq!(
            sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [1.0, 0.0, 0.0], 5.0),
            None
        );
        let h = sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0).expect("hit");
        assert_eq!(h.body, Some(b));
    }

    #[test]
    fn degenerate_casts_give_no_hit() {
        let mut w = world();
        sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        let c = [-10.0, 0.0, 0.0];
        // A negative radius, a zero direction and max_t ≤ 0 give no hit.
        assert_eq!(sphere_cast(&w, c, -0.5, [1.0, 0.0, 0.0], 100.0), None);
        assert_eq!(sphere_cast(&w, c, 0.5, [0.0, 0.0, 0.0], 100.0), None);
        assert_eq!(sphere_cast(&w, c, 0.5, [1.0, 0.0, 0.0], 0.0), None);
        assert_eq!(sphere_cast(&w, c, 0.5, [1.0, 0.0, 0.0], -1.0), None);
        assert_eq!(
            capsule_cast(&w, c, [-10.0, 1.0, 0.0], -0.5, [1.0, 0.0, 0.0], 100.0),
            None
        );
        assert_eq!(
            capsule_cast(&w, c, [-10.0, 1.0, 0.0], 0.5, [1.0, 0.0, 0.0], 0.0),
            None
        );
    }

    #[test]
    fn radius_zero_is_a_ray_and_a_huge_direction_is_normalized() {
        let mut w = world();
        let b = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        // oracle: a ray from x = −10 meets the unit sphere at x = −1: t = 9.
        assert_hit(
            sphere_cast(&w, [-10.0, 0.0, 0.0], 0.0, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            9.0,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
        // oracle: the direction (1e7, 0, 0) is the unit +X: t = 8.5.
        assert_hit(
            sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [1e7, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.5,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
    }

    #[test]
    fn a_cast_that_starts_overlapping_hits_at_zero() {
        let mut w = world();
        let b = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        // oracle: the centre 0.5 from a body of radius 1: overlapping, t = 0,
        // normal −direction, point the cast centre.
        assert_hit(
            sphere_cast(&w, [0.5, 0.0, 0.0], 0.5, [0.0, 1.0, 0.0], 100.0),
            RayTarget::Body(b),
            0.0,
            [0.0, -1.0, 0.0],
            [0.5, 0.0, 0.0],
            EXACT,
        );
        // oracle: a capsule with an end inside: t = 0, point the segment midpoint.
        assert_hit(
            capsule_cast(
                &w,
                [0.0, 0.0, 0.0],
                [0.0, 4.0, 0.0],
                0.5,
                [1.0, 0.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            0.0,
            [-1.0, 0.0, 0.0],
            [0.0, 2.0, 0.0],
            EXACT,
        );
    }

    #[test]
    fn a_cast_that_starts_touching_hits_only_when_it_moves_in() {
        let mut w = world();
        let b = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        // The cast sphere of radius 0.5 at (−1.5, 0, 0) touches the body.
        let c = [-1.5, 0.0, 0.0];
        // oracle: moving in (+X): t = 0, normal −X, contact (−1, 0, 0).
        assert_hit(
            sphere_cast(&w, c, 0.5, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            0.0,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
        // oracle: moving away (−X) or along the tangent plane (+Y): no hit.
        assert_eq!(sphere_cast(&w, c, 0.5, [-1.0, 0.0, 0.0], 100.0), None);
        assert_eq!(sphere_cast(&w, c, 0.5, [0.0, 1.0, 0.0], 100.0), None);

        // A sphere resting on a plane: down is a hit at 0, sideways and up not.
        let mut w = world();
        let p = plane(&mut w, Vec3Fix::UNIT_Y, 0.0);
        let c = [1.0, 0.5, 2.0];
        assert_hit(
            sphere_cast(&w, c, 0.5, [0.0, -1.0, 0.0], 100.0),
            RayTarget::StaticCollider(p),
            0.0,
            [0.0, 1.0, 0.0],
            [1.0, 0.0, 2.0],
            EXACT,
        );
        assert_eq!(sphere_cast(&w, c, 0.5, [1.0, 0.0, 0.0], 100.0), None);
        assert_eq!(sphere_cast(&w, c, 0.5, [0.0, 1.0, 0.0], 100.0), None);

        // A sphere resting on the unit box top: down hits at 0, sideways not.
        let mut w = world();
        let bx = unit_box(&mut w);
        let c = [0.2, 1.5, 0.3];
        assert_hit(
            sphere_cast(&w, c, 0.5, [0.0, -1.0, 0.0], 100.0),
            RayTarget::Body(bx),
            0.0,
            [0.0, 1.0, 0.0],
            [0.2, 1.0, 0.3],
            EXACT,
        );
        assert_eq!(sphere_cast(&w, c, 0.5, [1.0, 0.0, 0.0], 100.0), None);
    }

    #[test]
    fn sphere_cast_against_box_face_edge_and_turned_box() {
        let mut w = world();
        let b = unit_box(&mut w);
        // oracle: face x = −1 pushed out to x = −1.5: t = 8.5, contact on the face.
        assert_hit(
            sphere_cast(&w, [-10.0, 0.2, 0.3], 0.5, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.5,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.2, 0.3],
            EXACT,
        );
        // oracle: edge (x, y) = (−1, 1): the centre (x, 1.3) is 0.5 from it at
        // x = −1 − √(0.25 − 0.09) = −1.4, t = 8.6, normal (−0.4, 0.3)/0.5.
        assert_hit(
            sphere_cast(&w, [-10.0, 1.3, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.6,
            [-0.8, 0.6, 0.0],
            [-1.0, 1.0, 0.0],
            EXACT,
        );
        // The same box turned 45° about Y: its vertical edge points at −X, at
        // x = −√2. oracle: t = 10 − √2 − 0.5, normal −X, contact (−√2, 0, 0).
        let mut w = world();
        let b = unit_box(&mut w);
        w.bodies[b].rotation = QuatFix::from_axis_angle(Vec3Fix::UNIT_Y, Fix128::HALF_PI.half());
        let s2 = 2f64.sqrt();
        assert_hit(
            sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            9.5 - s2,
            [-1.0, 0.0, 0.0],
            [-s2, 0.0, 0.0],
            ITER,
        );
    }

    #[test]
    fn sphere_cast_against_cylinder_side_cap_and_rim() {
        let mut w = world();
        let b = shaped(
            &mut w,
            Shape::Cylinder {
                radius: Fix128::ONE,
                half_height: Fix128::ONE,
            },
            Vec3Fix::ZERO,
        );
        // oracle: side x = −1 pushed out to −1.5: t = 8.5.
        assert_hit(
            sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.5,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
        // oracle: top cap y = 1 pushed up to 1.5: t = 8.5.
        assert_hit(
            sphere_cast(&w, [0.2, 10.0, 0.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.5,
            [0.0, 1.0, 0.0],
            [0.2, 1.0, 0.0],
            EXACT,
        );
        // oracle: rim (1, 1, 0): the centre (1.3, y, 0) is 0.5 from it at
        // y = 1 + √(0.25 − 0.09) = 1.4, t = 8.6, normal (0.3, 0.4)/0.5.
        assert_hit(
            sphere_cast(&w, [1.3, 10.0, 0.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            RayTarget::Body(b),
            8.6,
            [0.6, 0.8, 0.0],
            [1.0, 1.0, 0.0],
            EXACT,
        );
        // oracle: a horizontal capsule over the cap: t = 5 − 1 − 0.5.
        assert_face_hit(
            capsule_cast(
                &w,
                [-0.5, 5.0, 0.0],
                [0.5, 5.0, 0.0],
                0.5,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            3.5,
            1.0,
            -0.5,
            0.5,
        );
        // Overlaps: 0.2 above the cap is within 0.3, not within 0.1.
        assert_eq!(
            overlap_s(&w, [0.0, 1.2, 0.0], 0.3),
            vec![RayTarget::Body(b)]
        );
        assert!(overlap_s(&w, [0.0, 1.2, 0.0], 0.1).is_empty());
        // Radius 0: a point strictly inside overlaps, one on the surface does not.
        assert_eq!(
            overlap_s(&w, [0.0, 0.0, 0.0], 0.0),
            vec![RayTarget::Body(b)]
        );
        assert!(overlap_s(&w, [0.0, 1.0, 0.0], 0.0).is_empty());
    }

    #[test]
    fn sphere_and_capsule_casts_against_an_ellipsoid() {
        let mut w = world();
        let b = shaped(
            &mut w,
            Shape::Ellipsoid {
                radii: v3(1.0, 2.0, 1.0),
            },
            Vec3Fix::ZERO,
        );
        // oracle: the top (0, 2, 0) reached at y = 2.5: t = 10 − 2.5.
        assert_hit(
            sphere_cast(&w, [0.0, 10.0, 0.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            RayTarget::Body(b),
            7.5,
            [0.0, 1.0, 0.0],
            [0.0, 2.0, 0.0],
            ITER,
        );
        // oracle: the side (1, 0, 0) reached by a vertical capsule at x = 1.5.
        assert_hit(
            capsule_cast(
                &w,
                [-10.0, -0.5, 0.0],
                [-10.0, 0.5, 0.0],
                0.5,
                [1.0, 0.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            8.5,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            ITER,
        );
        // oracle: the line x = 1.6 is 0.6 > 0.5 from the widest point: no contact.
        assert_eq!(
            sphere_cast(&w, [1.6, 10.0, 0.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            None
        );
        // Overlaps: the side point (1, 0, 0) is 0.2 from (1.2, 0, 0).
        assert_eq!(
            overlap_s(&w, [1.2, 0.0, 0.0], 0.3),
            vec![RayTarget::Body(b)]
        );
        assert!(overlap_s(&w, [1.2, 0.0, 0.0], 0.1).is_empty());
        assert_eq!(
            overlap_b(&w, [0.9, -0.1, -0.1], [1.5, 0.1, 0.1]),
            vec![RayTarget::Body(b)]
        );
        assert!(overlap_b(&w, [1.1, -0.1, -0.1], [1.5, 0.1, 0.1]).is_empty());
    }

    #[test]
    fn casts_and_overlaps_against_a_torus() {
        let mut w = world();
        // Ring of radius 2 in XZ, tube 0.5.
        let b = shaped(
            &mut w,
            Shape::Torus {
                major_radius: fx(2.0),
                minor_radius: fx(0.5),
            },
            Vec3Fix::ZERO,
        );
        // oracle: the top of the tube (2, 0.5, 0) reached at y = 0.75: t = 9.25.
        assert_hit(
            sphere_cast(&w, [2.0, 10.0, 0.0], 0.25, [0.0, -1.0, 0.0], 100.0),
            RayTarget::Body(b),
            9.25,
            [0.0, 1.0, 0.0],
            [2.0, 0.5, 0.0],
            EXACT,
        );
        // oracle: down the hole, 1.5 > 0.25 from the tube: no contact.
        assert_eq!(
            sphere_cast(&w, [0.0, 10.0, 0.0], 0.25, [0.0, -1.0, 0.0], 100.0),
            None
        );
        // oracle: a capsule across the tube, its point (2, y, 0) nearest the ring:
        // y = 0.5 + 0.25, t = 4.25.
        assert_hit(
            capsule_cast(
                &w,
                [1.5, 5.0, 0.0],
                [2.5, 5.0, 0.0],
                0.25,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            4.25,
            [0.0, 1.0, 0.0],
            [2.0, 0.5, 0.0],
            ITER,
        );
        // Overlaps: the axis is 1.5 from the tube.
        assert!(overlap_s(&w, [0.0, 0.0, 0.0], 1.4).is_empty());
        assert_eq!(
            overlap_s(&w, [0.0, 0.0, 0.0], 1.6),
            vec![RayTarget::Body(b)]
        );
        assert_eq!(
            overlap_s(&w, [2.0, 0.0, 0.0], 0.1),
            vec![RayTarget::Body(b)]
        );
        // oracle: the ring at 45° (√2, 0, √2) is (√2 − c)·√2 from the box corner
        // (c, ·, c): c = 1 gives 2 − √2 = 0.59 > 0.5 (no overlap), c = 1.2 gives
        // 0.30 < 0.5 (overlap).
        assert!(overlap_b(&w, [-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]).is_empty());
        assert_eq!(
            overlap_b(&w, [-1.2, -1.0, -1.2], [1.2, 1.0, 1.2]),
            vec![RayTarget::Body(b)]
        );
        // oracle: a box far outside the bounding sphere (radius 2.5).
        assert!(overlap_b(&w, [5.0, 5.0, 5.0], [6.0, 6.0, 6.0]).is_empty());
    }

    #[test]
    fn casts_and_overlaps_against_compound_children() {
        let mut w = world();
        // Box children at x = ±3, sphere children at z = ±3, a capsule child
        // along X and cube hull children at y = ±4: symmetric, centre of mass at
        // the origin.
        let mut c = CompoundShape::new();
        for s in [3.0, -3.0] {
            c.add_box(
                OrientedBox::new(Vec3Fix::ZERO, v3(0.5, 0.5, 0.5), QuatFix::IDENTITY),
                v3(s, 0.0, 0.0),
                QuatFix::IDENTITY,
            );
            c.add_sphere(
                Sphere::new(Vec3Fix::ZERO, fx(0.5)),
                v3(0.0, 0.0, s),
                QuatFix::IDENTITY,
            );
            let mut cube = Vec::new();
            for x in [-0.5, 0.5] {
                for y in [-0.5, 0.5] {
                    for z in [-0.5, 0.5] {
                        cube.push(v3(x, y, z));
                    }
                }
            }
            c.add_convex_hull(
                ConvexHull::new(cube),
                v3(0.0, s + s / 3.0, 0.0),
                QuatFix::IDENTITY,
            );
        }
        c.add_capsule(
            Capsule::new(v3(-1.5, 0.0, 0.0), v3(1.5, 0.0, 0.0), fx(0.5)),
            Vec3Fix::ZERO,
            QuatFix::IDENTITY,
        );
        let b = w
            .add_compound_body(&c, Fix128::ONE, Vec3Fix::ZERO)
            .expect("valid compound");
        let body = RayTarget::Body(b);
        // oracle: box child top y = 0.5 reached at 0.75: t = 9.25.
        assert_hit(
            sphere_cast(&w, [3.0, 10.0, 0.0], 0.25, [0.0, -1.0, 0.0], 100.0),
            body,
            9.25,
            [0.0, 1.0, 0.0],
            [3.0, 0.5, 0.0],
            EXACT,
        );
        // oracle: sphere child at (0, 0, 3): radius 0.75 above it, t = 9.25.
        assert_hit(
            sphere_cast(&w, [0.0, 10.0, 3.0], 0.25, [0.0, -1.0, 0.0], 100.0),
            body,
            9.25,
            [0.0, 1.0, 0.0],
            [0.0, 0.5, 3.0],
            EXACT,
        );
        // oracle: capsule child side at x = 1, from +Z: 0.75 from the segment,
        // t = 10 − 0.75.
        assert_hit(
            sphere_cast(&w, [1.0, 0.0, 10.0], 0.25, [0.0, 0.0, -1.0], 100.0),
            body,
            9.25,
            [0.0, 0.0, 1.0],
            [1.0, 0.0, 0.5],
            EXACT,
        );
        // oracle: hull cube at y = 4 (top 4.5) from the side: its face x = 0.5
        // reached at x = 0.75, t = 10 − 0.75.
        assert_hit(
            sphere_cast(&w, [10.0, 4.0, 0.0], 0.25, [-1.0, 0.0, 0.0], 100.0),
            body,
            9.25,
            [1.0, 0.0, 0.0],
            [0.5, 4.0, 0.0],
            ITER,
        );
        // oracle: a capsule over the box child at x = 3: t = 5 − 0.5 − 0.25.
        assert_face_hit(
            capsule_cast(
                &w,
                [2.8, 5.0, 0.0],
                [3.2, 5.0, 0.0],
                0.25,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            body,
            4.25,
            0.5,
            2.8,
            3.2,
        );
        // oracle: a capsule crossing over the capsule child (below the hull cube
        // at y = 4): t = 2 − 0.75.
        assert_hit(
            capsule_cast(
                &w,
                [0.0, 2.0, -1.0],
                [0.0, 2.0, 1.0],
                0.25,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            body,
            1.25,
            [0.0, 1.0, 0.0],
            [0.0, 0.5, 0.0],
            ITER,
        );
        // oracle: a capsule over the sphere child at (0, 0, −3): t = 5 − 0.75.
        assert_hit(
            capsule_cast(
                &w,
                [-1.0, 5.0, -3.0],
                [1.0, 5.0, -3.0],
                0.25,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            body,
            4.25,
            [0.0, 1.0, 0.0],
            [0.0, 0.5, -3.0],
            EXACT,
        );
        // oracle: (2.1, 0, 0) is 0.1 from the capsule child (its end cap reaches
        // x = 2) and 0.4 from the box child (face x = 2.5): not within 0.05,
        // within 0.45.
        assert!(overlap_s(&w, [2.1, 0.0, 0.0], 0.05).is_empty());
        assert_eq!(overlap_s(&w, [2.1, 0.0, 0.0], 0.45), vec![body]);
        // Box overlaps: each child alone, and the empty space between them.
        assert_eq!(overlap_b(&w, [3.4, 0.4, -0.1], [3.6, 0.6, 0.1]), vec![body]);
        assert_eq!(overlap_b(&w, [-0.1, 0.4, 2.9], [0.1, 0.6, 3.1]), vec![body]);
        assert_eq!(overlap_b(&w, [1.0, 0.4, -0.1], [1.2, 0.6, 0.1]), vec![body]);
        assert_eq!(overlap_b(&w, [0.4, 4.4, -0.1], [0.6, 4.6, 0.1]), vec![body]);
        assert!(overlap_b(&w, [1.0, 2.0, 1.0], [2.0, 3.0, 2.0]).is_empty());
    }

    #[test]
    fn casts_and_overlaps_against_a_plane() {
        let mut w = world();
        let p = plane(&mut w, Vec3Fix::UNIT_Y, 0.0);
        let sp = RayTarget::StaticCollider(p);
        // oracle: oblique (1, −1, 0)/√2: the height drops 4.5 after 4.5·√2.
        assert_hit(
            sphere_cast(&w, [0.0, 5.0, 0.0], 0.5, [1.0, -1.0, 0.0], 100.0),
            sp,
            4.5 * 2f64.sqrt(),
            [0.0, 1.0, 0.0],
            [4.5, 0.0, 0.0],
            EXACT,
        );
        // oracle: two-sided: from below the centre reaches y = −0.5.
        assert_hit(
            sphere_cast(&w, [0.0, -5.0, 0.0], 0.5, [0.0, 1.0, 0.0], 100.0),
            sp,
            4.5,
            [0.0, -1.0, 0.0],
            [0.0, 0.0, 0.0],
            EXACT,
        );
        // oracle: parallel 1 above: never closer than 1 > 0.5.
        assert_eq!(
            sphere_cast(&w, [0.0, 1.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            None
        );
        // oracle: capsule, the lower end (−1, 5, 0) reaches y = 0.5: t = 4.5.
        assert_hit(
            capsule_cast(
                &w,
                [-1.0, 5.0, 0.0],
                [1.0, 6.0, 0.0],
                0.5,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            sp,
            4.5,
            [0.0, 1.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
        // oracle: a capsule whose segment crosses the plane starts overlapping.
        assert_hit(
            capsule_cast(
                &w,
                [0.0, -1.0, 0.0],
                [0.0, 1.0, 0.0],
                0.5,
                [1.0, 0.0, 0.0],
                100.0,
            ),
            sp,
            0.0,
            [-1.0, 0.0, 0.0],
            [0.0, 0.0, 0.0],
            EXACT,
        );
        // Overlaps: 0.4 above is within 0.5; 0.6 is not.
        assert_eq!(overlap_s(&w, [0.0, 0.4, 0.0], 0.5), vec![sp]);
        assert!(overlap_s(&w, [0.0, 0.6, 0.0], 0.5).is_empty());
        // oracle: a box straddling y = 0 overlaps, one resting on it does not.
        assert_eq!(overlap_b(&w, [0.0, -0.1, 0.0], [1.0, 0.1, 1.0]), vec![sp]);
        assert!(overlap_b(&w, [0.0, 0.0, 0.0], [1.0, 1.0, 1.0]).is_empty());
    }

    #[test]
    fn casts_along_a_mesh_floor_cross_its_edges() {
        let mut w = world();
        let m = floor_mesh(&mut w);
        let sm = RayTarget::StaticCollider(m);
        // oracle: face region: the plane y = 0 reached at y = 0.5: t = 2.5.
        assert_hit(
            sphere_cast(&w, [1.0, 3.0, 3.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            sm,
            2.5,
            [0.0, 1.0, 0.0],
            [1.0, 0.0, 3.0],
            EXACT,
        );
        // oracle: edge x = 0: the centre (x, 0.3, 1) is 0.5 from (0, 0, 1) at
        // x = −0.4, t = 9.6, normal (−0.8, 0.6, 0).
        assert_hit(
            sphere_cast(&w, [-10.0, 0.3, 1.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            sm,
            9.6,
            [-0.8, 0.6, 0.0],
            [0.0, 0.0, 1.0],
            EXACT,
        );
        // oracle: a sphere resting on the floor sliding across the diagonal
        // edge, and a capsule doing the same: tangent, no hit.
        assert_eq!(
            sphere_cast(&w, [1.0, 0.5, 3.0], 0.5, [1.0, 0.0, -1.0], 2.0),
            None
        );
        assert_eq!(
            capsule_cast(
                &w,
                [1.0, 0.5, 2.0],
                [1.0, 1.5, 2.0],
                0.5,
                [1.0, 0.0, 0.0],
                2.0
            ),
            None
        );
        // oracle: resting and moving down: t = 0 on the floor.
        assert_hit(
            sphere_cast(&w, [1.0, 0.5, 3.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            sm,
            0.0,
            [0.0, 1.0, 0.0],
            [1.0, 0.0, 3.0],
            EXACT,
        );
        // oracle: tilted capsule, lower end (2, 3, 1) reaches y = 0.5: t = 2.5.
        assert_hit(
            capsule_cast(
                &w,
                [2.0, 3.0, 1.0],
                [3.0, 4.0, 1.0],
                0.5,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            sm,
            2.5,
            [0.0, 1.0, 0.0],
            [2.0, 0.0, 1.0],
            ITER,
        );
        // Overlaps: 0.3 above the floor is within 0.5, outside it 0.6 is not.
        assert_eq!(overlap_s(&w, [2.0, 0.3, 2.0], 0.5), vec![sm]);
        assert!(overlap_s(&w, [-0.6, 0.0, 2.0], 0.5).is_empty());
        assert_eq!(overlap_b(&w, [1.0, -0.1, 1.0], [2.0, 0.1, 2.0]), vec![sm]);
        assert!(overlap_b(&w, [1.0, 0.1, 1.0], [2.0, 1.0, 2.0]).is_empty());
    }

    #[test]
    fn casts_and_overlaps_against_height_fields() {
        // oracle: flat field at 0.25 over [0, 4]²: t = 5 − 0.25 − 0.5.
        let mut w = world();
        let h = w.add_static_collider(StaticCollider::HeightField(HeightField::flat(
            5,
            5,
            Fix128::ONE,
            Vec3Fix::ZERO,
            fx(0.25),
        )));
        let sh = RayTarget::StaticCollider(h);
        assert_hit(
            sphere_cast(&w, [2.0, 5.0, 2.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            sh,
            4.25,
            [0.0, 1.0, 0.0],
            [2.0, 0.25, 2.0],
            ITER,
        );
        // oracle: a horizontal capsule over it: the same t.
        assert_face_hit(
            capsule_cast(
                &w,
                [1.5, 5.0, 2.0],
                [2.5, 5.0, 2.0],
                0.5,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            sh,
            4.25,
            0.25,
            1.5,
            2.5,
        );
        // oracle: resting on it and sliding across cells: no hit.
        assert_eq!(
            sphere_cast(&w, [0.5, 0.75, 0.5], 0.5, [1.0, 0.0, 0.0], 3.0),
            None
        );
        // oracle: outside the field's footprint: no hit.
        assert_eq!(
            sphere_cast(&w, [10.0, 5.0, 10.0], 0.5, [0.0, -1.0, 0.0], 100.0),
            None
        );
        assert_eq!(overlap_s(&w, [2.0, 0.5, 2.0], 0.3), vec![sh]);
        assert!(overlap_s(&w, [2.0, 0.6, 2.0], 0.3).is_empty());
        assert_eq!(overlap_b(&w, [1.0, 0.2, 1.0], [3.0, 0.3, 3.0]), vec![sh]);
        assert!(overlap_b(&w, [1.0, 0.3, 1.0], [3.0, 1.0, 3.0]).is_empty());
        assert!(overlap_b(&w, [5.0, 0.0, 5.0], [6.0, 1.0, 6.0]).is_empty());
    }

    #[test]
    fn casts_and_overlaps_against_a_twisted_height_field_cell() {
        let mut w = world();
        let h = saddle_field(&mut w);
        let sh = RayTarget::StaticCollider(h);
        // The surface y = x·z at (0.5, 0.25, 0.5) has the unit normal
        // n = (−0.5, 1, −0.5)/√1.5. A sphere of radius 0.1 (its curvature 10
        // beats the surface's ±1, so the contact is unique) whose centre moves
        // down the line through (0.5, 0.25, 0.5) + 0.1·n touches there.
        let k = 1.5f64.sqrt();
        let n = [-0.5 / k, 1.0 / k, -0.5 / k];
        let r = 0.1;
        let cx = 0.5 + r * n[0];
        // oracle: t = 5 − (0.25 + r·n.y).
        assert_hit(
            sphere_cast(&w, [cx, 5.0, cx], r, [0.0, -1.0, 0.0], 100.0),
            sh,
            5.0 - (0.25 + r * n[1]),
            n,
            [0.5, 0.25, 0.5],
            ITER,
        );
        // oracle: a point 0.09 along n from the surface point is within 0.1 of
        // the surface, one 0.11 along n is not.
        let at = |s: f64| [0.5 + s * n[0], 0.25 + s * n[1], 0.5 + s * n[2]];
        assert_eq!(overlap_s(&w, at(0.09), 0.1), vec![sh]);
        assert!(overlap_s(&w, at(0.11), 0.1).is_empty());
        // oracle: the surface spans y ∈ [0, 1]: a box at y ∈ [0.9, 2] over the
        // corner (1, 1) meets it (height 1 there), one over (0, 0) does not.
        assert_eq!(overlap_b(&w, [0.9, 0.9, 0.9], [1.0, 2.0, 1.0]), vec![sh]);
        assert!(overlap_b(&w, [0.0, 0.9, 0.0], [0.1, 2.0, 0.1]).is_empty());
    }

    #[cfg(feature = "std")]
    #[test]
    fn casts_and_overlaps_against_an_sdf() {
        use crate::sdf_collider::{ClosureSdf, SdfCollider};
        let mut w = world();
        // The unit-sphere field about the origin.
        w.sdf_colliders.push(SdfCollider::new_static(
            Box::new(ClosureSdf::new(
                |x, y, z| (x * x + y * y + z * z).sqrt() - 1.0,
                |x, y, z| {
                    let l = (x * x + y * y + z * z).sqrt();
                    (x / l, y / l, z / l)
                },
            )),
            Vec3Fix::ZERO,
            QuatFix::IDENTITY,
        ));
        let tol = f64::from(all().sdf.tolerance);
        // oracle: the centre reaches |c| = 1.5: t ∈ [3.5 − tol, 3.5].
        let h = sphere_cast(&w, [-5.0, 0.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0).expect("hit");
        assert_eq!(h.target, RayTarget::Sdf(0));
        assert!(h.t.to_f64() > 3.5 - tol - 1e-5 && h.t.to_f64() < 3.5 + 1e-5);
        assert_vec(h.normal, [-1.0, 0.0, 0.0], 1e-3, "normal");
        // oracle: a vertical capsule at the same height: the same t.
        let h = capsule_cast(
            &w,
            [-5.0, -0.5, 0.0],
            [-5.0, 0.5, 0.0],
            0.5,
            [1.0, 0.0, 0.0],
            100.0,
        )
        .expect("hit");
        assert!(h.t.to_f64() > 3.5 - tol - 1e-4 && h.t.to_f64() < 3.5 + 1e-4);
        // oracle: the line y = 2 stays 2 − 1 = 1 > 0.5 from the surface.
        assert_eq!(
            sphere_cast(&w, [-5.0, 2.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0),
            None
        );
        // Overlaps: (1.2, 0, 0) is 0.2 from the surface.
        assert_eq!(overlap_s(&w, [1.2, 0.0, 0.0], 0.3), vec![RayTarget::Sdf(0)]);
        assert!(overlap_s(&w, [1.2, 0.0, 0.0], 0.1).is_empty());
        assert_eq!(
            overlap_b(&w, [0.8, -0.1, -0.1], [1.2, 0.1, 0.1]),
            vec![RayTarget::Sdf(0)]
        );
        assert!(overlap_b(&w, [2.0, 2.0, 2.0], [3.0, 3.0, 3.0]).is_empty());
        // The filter can hide it.
        assert!(w
            .overlap_sphere(v3(1.2, 0.0, 0.0), fx(0.3), &all().with_sdf(false))
            .is_empty());
    }

    #[test]
    fn capsule_cast_against_a_sphere_body_and_a_box() {
        let mut w = world();
        let b = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        // oracle: the segment (1..3, y, 0): its end (1, y, 0) reaches 1.5 from
        // the centre at y = √1.25: t = 5 − √1.25, normal (1, √1.25, 0)/1.5.
        let s = 1.25f64.sqrt();
        let n = [1.0 / 1.5, s / 1.5, 0.0];
        assert_hit(
            capsule_cast(
                &w,
                [1.0, 5.0, 0.0],
                [3.0, 5.0, 0.0],
                0.5,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            5.0 - s,
            n,
            n,
            EXACT,
        );
        // oracle: coinciding ends are the sphere cast: t = 8.5.
        assert_hit(
            capsule_cast(
                &w,
                [-10.0, 0.0, 0.0],
                [-10.0, 0.0, 0.0],
                0.5,
                [1.0, 0.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            8.5,
            [-1.0, 0.0, 0.0],
            [-1.0, 0.0, 0.0],
            EXACT,
        );
        let mut w = world();
        let b = unit_box(&mut w);
        // oracle: horizontal capsule over the top face y = 1: t = 5 − 1 − 0.5.
        assert_face_hit(
            capsule_cast(
                &w,
                [-0.5, 5.0, 0.0],
                [0.5, 5.0, 0.0],
                0.5,
                [0.0, -1.0, 0.0],
                100.0,
            ),
            RayTarget::Body(b),
            3.5,
            1.0,
            -0.5,
            0.5,
        );
        // oracle: moving away from the box: no hit.
        assert_eq!(
            capsule_cast(
                &w,
                [-0.5, 5.0, 0.0],
                [0.5, 5.0, 0.0],
                0.5,
                [0.0, 1.0, 0.0],
                100.0
            ),
            None
        );
    }

    #[test]
    fn overlaps_of_bodies_and_the_box_edge_gap() {
        let mut w = world();
        let s = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        // oracle: (1.4, 0, 0) is 0.4 from the sphere: within 0.5, not 0.3.
        assert_eq!(
            overlap_s(&w, [1.4, 0.0, 0.0], 0.5),
            vec![RayTarget::Body(s)]
        );
        assert!(overlap_s(&w, [1.4, 0.0, 0.0], 0.3).is_empty());
        // A negative radius overlaps nothing.
        assert!(overlap_s(&w, [0.0, 0.0, 0.0], -1.0).is_empty());
        // oracle: the box [0.5, 2]³'s nearest point (0.5, 0.5, 0.5) is √0.75 =
        // 0.866 from the centre: inside radius 1.
        assert_eq!(
            overlap_b(&w, [0.5, 0.5, 0.5], [2.0, 2.0, 2.0]),
            vec![RayTarget::Body(s)]
        );
        // oracle: the box [0.6, 2]³: √1.08 = 1.04 > 1, no overlap.
        assert!(overlap_b(&w, [0.6, 0.6, 0.6], [2.0, 2.0, 2.0]).is_empty());
        // A box with min > max contains nothing.
        assert!(overlap_b(&w, [1.0, -1.0, -1.0], [-1.0, 1.0, 1.0]).is_empty());

        let mut w = world();
        let b = unit_box(&mut w);
        // oracle: (1.3, 1.3, 0) is 0.3·√2 = 0.424 from the edge (1, 1, z): within
        // 0.5, not 0.4.
        assert_eq!(
            overlap_s(&w, [1.3, 1.3, 0.0], 0.5),
            vec![RayTarget::Body(b)]
        );
        assert!(overlap_s(&w, [1.3, 1.3, 0.0], 0.4).is_empty());
        // The box turned 45° about Y reaches x = √2 at z = 0: an AABB from
        // x = 1.3 meets it, one from x = 1.5 does not.
        w.bodies[b].rotation = QuatFix::from_axis_angle(Vec3Fix::UNIT_Y, Fix128::HALF_PI.half());
        assert_eq!(
            overlap_b(&w, [1.3, -0.5, -0.1], [2.0, 0.5, 0.1]),
            vec![RayTarget::Body(b)]
        );
        assert!(overlap_b(&w, [1.5, -0.5, -0.1], [2.0, 0.5, 0.1]).is_empty());
    }

    #[test]
    fn filters_and_ties() {
        let mut w = world();
        let b = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        let p = plane(&mut w, Vec3Fix::UNIT_Y, -5.0);
        // oracle: down from (0, 10, 0): the sphere first (t = 10 − 1.5), the
        // plane y = −5 at t = 14.5 when the body is excluded, nothing when the
        // static colliders are hidden too.
        let c = v3(0.0, 10.0, 0.0);
        let down = -Vec3Fix::UNIT_Y;
        let h = w
            .cast_sphere(c, fx(0.5), down, fx(100.0), &all())
            .expect("hit");
        assert_eq!(h.target, RayTarget::Body(b));
        let h = w
            .cast_sphere(c, fx(0.5), down, fx(100.0), &all().excluding_body(b))
            .expect("hit");
        assert_eq!(h.target, RayTarget::StaticCollider(p));
        assert!((h.t.to_f64() - 14.5).abs() < EXACT);
        assert_eq!(
            w.cast_sphere(
                c,
                fx(0.5),
                down,
                fx(100.0),
                &all().excluding_body(b).with_static(false)
            ),
            None
        );
        // Two identical bodies: the tie goes to the lower index; overlaps are
        // sorted by target.
        let mut w = world();
        let b0 = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        let b1 = sphere_body(&mut w, Vec3Fix::ZERO, 1.0);
        let h = sphere_cast(&w, [-10.0, 0.0, 0.0], 0.5, [1.0, 0.0, 0.0], 100.0).expect("hit");
        assert_eq!(h.target, RayTarget::Body(b0));
        assert_eq!(
            overlap_s(&w, [0.0, 0.0, 0.0], 0.1),
            vec![RayTarget::Body(b0), RayTarget::Body(b1)]
        );
    }

    #[test]
    fn capsule_penetrations_closed_forms() {
        let mut w = world();
        let p = plane(&mut w, Vec3Fix::UNIT_Y, 0.0);
        // oracle: the segment's lower end is 0.2 above the plane: depth
        // 0.3 − 0.2 = 0.1 along +Y.
        let pens = w
            .capsule_penetrations(v3(0.0, 0.2, 0.0), v3(0.0, 1.4, 0.0), fx(0.3), &all())
            .expect("the segment is outside");
        assert_eq!(pens.len(), 1);
        assert_eq!(pens[0].target, RayTarget::StaticCollider(p));
        assert!((pens[0].depth.to_f64() - 0.1).abs() < EXACT);
        assert_vec(pens[0].normal, [0.0, 1.0, 0.0], EXACT, "normal");
        // oracle: 0.4 above: no overlap.
        assert!(w
            .capsule_penetrations(v3(0.0, 0.4, 0.0), v3(0.0, 1.4, 0.0), fx(0.3), &all())
            .expect("outside")
            .is_empty());
        // oracle: a segment crossing the plane has no push-out direction.
        assert!(w
            .capsule_penetrations(v3(0.0, -0.2, 0.0), v3(0.0, 1.4, 0.0), fx(0.3), &all())
            .is_none());
    }

    #[test]
    fn helper_closed_forms() {
        // aabb_gap: x gap 1, z gap 2, y overlapping: √5.
        let a = AABB::new(v3(0.0, 0.0, 0.0), v3(1.0, 1.0, 1.0));
        let b = AABB::new(v3(2.0, 0.5, 3.0), v3(3.0, 2.0, 4.0));
        assert!((aabb_gap(&a, &b).to_f64() - 5f64.sqrt()).abs() < EXACT);
        assert_eq!(aabb_gap(&a, &a), Fix128::ZERO);
        // box_entry: [0, 1]³ moving +X meets [3, 4] × [0, 1]² at t = 2; not
        // within max_t = 1; never when the Y ranges are apart.
        let target = AABB::new(v3(3.0, 0.0, 0.0), v3(4.0, 1.0, 1.0));
        let entry = box_entry(&a, Vec3Fix::UNIT_X, fx(10.0), &target).expect("meets");
        assert!((entry.to_f64() - 2.0).abs() < EXACT);
        assert_eq!(box_entry(&a, Vec3Fix::UNIT_X, Fix128::ONE, &target), None);
        let above = AABB::new(v3(3.0, 5.0, 0.0), v3(4.0, 6.0, 1.0));
        assert_eq!(box_entry(&a, Vec3Fix::UNIT_X, fx(10.0), &above), None);
        // oracle: moving −X toward [−4, −3]: t = 3.
        let behind = AABB::new(v3(-4.0, 0.0, 0.0), v3(-3.0, 1.0, 1.0));
        let entry = box_entry(&a, -Vec3Fix::UNIT_X, fx(10.0), &behind).expect("meets");
        assert!((entry.to_f64() - 3.0).abs() < EXACT);
        // ratio_within: 1/4 = 0.25; a tiny denominator is clamped to ±big.
        let tiny = Fix128 { hi: 0, lo: 1 };
        assert!((ratio_within(Fix128::ONE, fx(4.0), fx(5.0)).to_f64() - 0.25).abs() < EXACT);
        assert_eq!(ratio_within(Fix128::ONE, tiny, fx(5.0)), fx(5.0));
        assert_eq!(ratio_within(Fix128::NEG_ONE, tiny, fx(5.0)), fx(-5.0));
        // tame_direction: (2²¹, 0, 0) is scaled to (1, 0, 0); (3, 4, 0) is kept.
        assert_eq!(
            tame_direction(Vec3Fix::new(
                Fix128::from_int(1 << 21),
                Fix128::ZERO,
                Fix128::ZERO
            )),
            Vec3Fix::UNIT_X
        );
        assert_eq!(tame_direction(v3(3.0, 4.0, 0.0)), v3(3.0, 4.0, 0.0));
        assert!(box_is_valid(&a));
        assert!(!box_is_valid(&AABB::new(
            v3(0.0, 1.0, 0.0),
            v3(1.0, 0.0, 1.0)
        )));
        // closest_on_segment: clamped to the ends, degenerate segment.
        let (s0, s1) = (v3(0.0, 0.0, 0.0), v3(2.0, 0.0, 0.0));
        assert_eq!(
            closest_on_segment(s0, s1, v3(1.0, 5.0, 0.0)),
            v3(1.0, 0.0, 0.0)
        );
        assert_eq!(closest_on_segment(s0, s1, v3(-3.0, 1.0, 0.0)), s0);
        assert_eq!(closest_on_segment(s0, s0, v3(5.0, 5.0, 5.0)), s0);
        // segment_segment: crossing → None; skew at distance 1; point cases.
        assert!(segment_segment(
            v3(-1.0, 0.0, 0.0),
            v3(1.0, 0.0, 0.0),
            v3(0.0, -1.0, 0.0),
            v3(0.0, 1.0, 0.0)
        )
        .is_none());
        let (d, _, _) = segment_segment(
            v3(-1.0, 0.0, 0.0),
            v3(1.0, 0.0, 0.0),
            v3(0.0, -1.0, 1.0),
            v3(0.0, 1.0, 1.0),
        )
        .expect("apart");
        assert!((d.to_f64() - 1.0).abs() < ITER);
        let (d, _, _) =
            segment_segment(s0, s0, v3(3.0, 4.0, 0.0), v3(3.0, 4.0, 0.0)).expect("apart");
        assert!((d.to_f64() - 5.0).abs() < EXACT);
        let (d, _, _) =
            segment_segment(v3(1.0, 3.0, 0.0), v3(1.0, 3.0, 0.0), s0, s1).expect("apart");
        assert!((d.to_f64() - 3.0).abs() < EXACT);
        let (d, _, _) =
            segment_segment(s0, s1, v3(1.0, 0.0, 2.0), v3(1.0, 0.0, 2.0)).expect("apart");
        assert!((d.to_f64() - 2.0).abs() < EXACT);
        // point_box_local: on the face x = 1 it touches with normal +X; outside
        // it is the distance to the clamped point; inside it is Inside.
        let h = v3(1.0, 1.0, 1.0);
        match point_box_local(v3(1.0, 0.5, 0.5), h) {
            Dist::Outside { dist, normal, .. } => {
                assert_eq!(dist, Fix128::ZERO);
                assert_eq!(normal, Vec3Fix::UNIT_X);
            }
            other => panic!("expected touching, got {other:?}"),
        }
        assert!((point_box_local(v3(4.0, 5.0, 0.0), h).value().to_f64() - 5.0).abs() < EXACT);
        assert!(matches!(point_box_local(Vec3Fix::ZERO, h), Dist::Inside));
        // point_cylinder_local: on the cap; 2 beside the side.
        match point_cylinder_local(v3(0.0, -1.0, 0.0), Fix128::ONE, Fix128::ONE) {
            Dist::Outside { dist, normal, .. } => {
                assert_eq!(dist, Fix128::ZERO);
                assert_eq!(normal, -Vec3Fix::UNIT_Y);
            }
            other => panic!("expected touching, got {other:?}"),
        }
        assert!(
            (point_cylinder_local(v3(3.0, 0.0, 0.0), Fix128::ONE, Fix128::ONE)
                .value()
                .to_f64()
                - 2.0)
                .abs()
                < EXACT
        );
        // Dist: a distance shrunk past zero is Inside; a bound shrinks by it.
        assert!(matches!(
            Dist::toward(v3(2.0, 0.0, 0.0), Vec3Fix::ZERO).shrunk(fx(3.0)),
            Dist::Inside
        ));
        assert_eq!(
            Dist::AtLeast(fx(2.0)).shrunk(Fix128::ONE).value(),
            Fix128::ONE
        );
        assert!(!Dist::AtLeast(Fix128::ZERO).within(fx(10.0)));
        assert!(Dist::Inside.within(Fix128::ZERO));
        assert_eq!(Dist::Inside.value(), Fix128::NEG_ONE);
        assert!(matches!(
            Dist::toward(Vec3Fix::ZERO, Vec3Fix::ZERO),
            Dist::Inside
        ));
    }

    /// The lower bound of [`gjk_bounds`] (less the support slack) is never
    /// above the distance: against an independent `f64` distance (the
    /// meridian half-plane of a cone or a cylinder) for points and segments
    /// near their sides, caps, rims and apex, aligned and turned, including
    /// segments of radius 0 through a cap's edge, where GJK stops on a face
    /// whose length is up to `25·2⁻³²` above the distance.
    #[test]
    #[allow(clippy::disallowed_methods)] // f64 oracle, not production arithmetic
    fn the_lower_bound_is_not_above_the_distance() {
        struct Rng(u64);
        impl Rng {
            fn u(&mut self) -> f64 {
                self.0 = self
                    .0
                    .wrapping_mul(6_364_136_223_846_793_005)
                    .wrapping_add(1_442_695_040_888_963_407);
                ((self.0 >> 11) as f64) / ((1u64 << 53) as f64)
            }
            fn r(&mut self, a: f64, b: f64) -> f64 {
                a + (b - a) * self.u()
            }
        }
        fn seg2(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
            let (ex, ey) = (b.0 - a.0, b.1 - a.1);
            let t = (((p.0 - a.0) * ex + (p.1 - a.1) * ey) / (ex * ex + ey * ey)).clamp(0.0, 1.0);
            ((p.0 - a.0 - t * ex).powi(2) + (p.1 - a.1 - t * ey).powi(2)).sqrt()
        }
        // outside distance in the frame of the geometric centre (0 inside)
        let dist_local = |cone: bool, r: f64, h: f64, l: [f64; 3]| {
            let rho = (l[0] * l[0] + l[2] * l[2]).sqrt();
            if cone {
                if l[1] >= -h && rho * 2.0 * h <= r * (h - l[1]) {
                    return 0.0;
                }
                let p = (rho, l[1]);
                seg2(p, (0.0, h), (r, -h)).min(seg2(p, (r, -h), (0.0, -h)))
            } else {
                let (dx, dy) = ((rho - r).max(0.0), (l[1].abs() - h).max(0.0));
                (dx * dx + dy * dy).sqrt()
            }
        };
        let rot_inv = |q: [f64; 4], v: [f64; 3]| {
            let n = q.iter().map(|x| x * x).sum::<f64>();
            let (w, x, y, z) = (q[0], -q[1], -q[2], -q[3]);
            let t = [
                2.0 * (y * v[2] - z * v[1]),
                2.0 * (z * v[0] - x * v[2]),
                2.0 * (x * v[1] - y * v[0]),
            ];
            let o = [
                v[0] + w * t[0] + (y * t[2] - z * t[1]),
                v[1] + w * t[1] + (z * t[0] - x * t[2]),
                v[2] + w * t[2] + (x * t[1] - y * t[0]),
            ];
            [o[0] / (n * n), o[1] / (n * n), o[2] / (n * n)]
        };
        let rot = |q: [f64; 4], v: [f64; 3]| {
            let (w, x, y, z) = (q[0], q[1], q[2], q[3]);
            let t = [
                2.0 * (y * v[2] - z * v[1]),
                2.0 * (z * v[0] - x * v[2]),
                2.0 * (x * v[1] - y * v[0]),
            ];
            [
                v[0] + w * t[0] + (y * t[2] - z * t[1]),
                v[1] + w * t[1] + (z * t[0] - x * t[2]),
                v[2] + w * t[2] + (x * t[1] - y * t[0]),
            ]
        };
        let mut rng = Rng(0x1046_b0d5);
        let (mut checked, mut stalled) = (0usize, 0usize);
        for cone in [false, true] {
            for turned in [false, true] {
                let (r, h) = if cone { (1.0, 0.8) } else { (0.9, 0.7) };
                let shape = if cone {
                    Shape::Cone {
                        radius: fx(r),
                        half_height: fx(h),
                    }
                } else {
                    Shape::Cylinder {
                        radius: fx(r),
                        half_height: fx(h),
                    }
                };
                let rotation = if turned {
                    let k = (0.36f64 + 0.49 + 0.04).sqrt();
                    QuatFix::from_axis_angle(v3(0.6 / k, 0.7 / k, -0.2 / k), fx(0.9))
                } else {
                    QuatFix::IDENTITY
                };
                let posed = PosedShape {
                    shape,
                    position: v3(0.25, -0.5, 0.75),
                    rotation,
                };
                let (center, _) = posed_frame(&posed);
                let c = [center.x.to_f64(), center.y.to_f64(), center.z.to_f64()];
                let q = [
                    rotation.w.to_f64(),
                    rotation.x.to_f64(),
                    rotation.y.to_f64(),
                    rotation.z.to_f64(),
                ];
                let local = |p: [f64; 3]| rot_inv(q, [p[0] - c[0], p[1] - c[1], p[2] - c[2]]);
                let world = |l: [f64; 3]| {
                    let w = rot(q, l);
                    [w[0] + c[0], w[1] + c[1], w[2] + c[2]]
                };
                let slack = round_support_slack(&posed);
                for _ in 0..300 {
                    // a point near the side, a cap or base, a rim or the apex, just
                    // outside or just inside, and a segment along the axis from it
                    // (radius 0 through a cap's edge) or across
                    let phi = rng.r(0.0, std::f64::consts::TAU);
                    let pick = rng.u();
                    let (rho, y) = if pick < 0.3 {
                        (
                            if cone { r * rng.u() } else { r },
                            if cone { 0.0 } else { rng.r(-h, h) },
                        )
                    } else if pick < 0.6 {
                        (rng.r(0.0, r), -h)
                    } else if pick < 0.9 {
                        (r, -h)
                    } else if cone {
                        (0.0, h)
                    } else {
                        (r, h)
                    };
                    let y = if cone && pick < 0.3 {
                        h - 2.0 * h * rho / r
                    } else {
                        y
                    };
                    let off = [rng.r(-1.0, 1.0), rng.r(-1.0, 1.0), rng.r(-1.0, 1.0)];
                    let e = 2f64.powi(-(20 + (rng.u() * 14.0) as i32));
                    let p = [
                        rho * phi.cos() + e * off[0],
                        y + e * off[1],
                        rho * phi.sin() + e * off[2],
                    ];
                    let (pa, pb) = if rng.u() < 0.5 {
                        (p, p)
                    } else if rng.u() < 0.5 {
                        (p, [p[0], p[1] + 0.3 * y.signum(), p[2]])
                    } else {
                        let s = [rng.r(-0.2, 0.2), rng.r(-0.2, 0.2), rng.r(-0.2, 0.2)];
                        (p, [p[0] + s[0], p[1] + s[1], p[2] + s[2]])
                    };
                    let (wa, wb) = (world(pa), world(pb));
                    let (a, b) = (v3(wa[0], wa[1], wa[2]), v3(wb[0], wb[1], wb[2]));
                    let (fa, fb) = (
                        local([a.x.to_f64(), a.y.to_f64(), a.z.to_f64()]),
                        local([b.x.to_f64(), b.y.to_f64(), b.z.to_f64()]),
                    );
                    // the segment's distance: its minimum along it (convex), by
                    // ternary search
                    let at = |s: f64| {
                        dist_local(
                            cone,
                            r,
                            h,
                            [
                                fa[0] + s * (fb[0] - fa[0]),
                                fa[1] + s * (fb[1] - fa[1]),
                                fa[2] + s * (fb[2] - fa[2]),
                            ],
                        )
                    };
                    let (mut lo, mut hi) = (0.0f64, 1.0f64);
                    for _ in 0..200 {
                        let (m1, m2) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);
                        if at(m1) <= at(m2) {
                            hi = m2
                        } else {
                            lo = m1
                        }
                    }
                    let truth = at(0.5 * (lo + hi)).min(at(0.0)).min(at(1.0));
                    let (found, bound) = convex_bounds(a, b, &posed, slack);
                    if let Dist::Outside { dist, .. } = found {
                        checked += 1;
                        let (lower, dist) = (bound.lower.to_f64(), dist.to_f64());
                        if dist - lower > 2f64.powi(-32) {
                            stalled += 1;
                        }
                        // f64 rounding of the inputs and the truth: below 2⁻⁵⁰
                        assert!(
                            lower <= truth + 2f64.powi(-50),
                            "lower {lower:e} above the distance {truth:e} by {:e} (cone {cone}, turned {turned})",
                            lower - truth
                        );
                    }
                }
            }
        }
        // not vacuous: most samples are outside, and some have the bounds apart
        assert!(checked > 500, "{checked} outside");
        assert!(
            stalled > 0,
            "no sample with the lower bound below the distance"
        );
    }

    /// A tetrahedron just thicker than the flatness `h = 2⁻³²` of
    /// [`closest_on_tetrahedron`] is not flat: one around the origin is
    /// inside (`None`), whatever its least height between `2⁻³⁰` and `2⁻¹⁶`.
    /// Taken as flat, its nearest face would be returned at a distance up to
    /// half its height, and GJK would report the shapes apart by that much.
    #[test]
    fn a_tetrahedron_just_thicker_than_flat_holds_the_origin() {
        let vertex = |w: Vec3Fix| Vertex {
            w,
            a: w,
            b: Vec3Fix::ZERO,
        };
        for e in [17, 20, 24, 27] {
            let h = 1.0 / ((1u64 << e) as f64);
            // a base triangle below the origin and an apex above it
            let pts = [
                v3(-1.0, -1.0, -0.5 * h),
                v3(1.0, -1.0, -0.5 * h),
                v3(0.0, 1.0, -0.5 * h),
                v3(0.0, 0.0, 0.5 * h),
            ];
            // precondition: every height is above 2⁻³² (and not by much)
            let least = [(0, 1, 2, 3), (0, 2, 3, 1), (0, 3, 1, 2), (1, 3, 2, 0)]
                .iter()
                .map(|&(p, q, r, o)| {
                    let n = (pts[q] - pts[p]).cross(pts[r] - pts[p]);
                    (n.dot(pts[o] - pts[p]).abs() / n.length()).to_f64()
                })
                .fold(f64::MAX, f64::min);
            assert!(
                least > 2.0 / 4_294_967_296.0 && least < 1.0 / 32768.0,
                "least height {least:e} for h = 2^-{e}"
            );
            let [a, b, c, d] = pts.map(vertex);
            let got = closest_on_tetrahedron(a, b, c, d, 0);
            assert!(
                got.is_none(),
                "h = 2^-{e} (least height {least:e}): the origin is inside, got the face {:?}",
                got.map(|n| nearest_point(&n).length().to_f64())
            );
        }
    }

    /// An independent `f64` reference for a cone and a cylinder (solids of
    /// revolution): the distance of a point is the distance in its meridian
    /// half-plane `(ρ, y)` to a triangle or a rectangle, a segment's is the
    /// minimum of that convex function along it (ternary search), and along a
    /// straight path the gap is convex in time, so its minimum and first zero
    /// are found by ternary search and bisection. `f64` is exact to about
    /// `2⁻⁵²` here, far below the `2⁻³²` of the casts.
    #[allow(clippy::disallowed_methods)] // f64 oracle, not production arithmetic
    mod round_reference {
        use super::*;

        /// `2⁻³²`.
        pub(super) const TOL: f64 = 1.0 / 4_294_967_296.0;

        /// A cone (apex at `hh`, base of radius `r` at `−hh` about its
        /// geometric centre, which is `hh/2` above the body position) or a
        /// cylinder (about the body position).
        #[derive(Clone, Copy, Debug)]
        pub(super) struct Solid {
            pub(super) cone: bool,
            pub(super) r: f64,
            pub(super) hh: f64,
        }

        fn seg2(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
            let (ex, ey) = (b.0 - a.0, b.1 - a.1);
            let u = (((p.0 - a.0) * ex + (p.1 - a.1) * ey) / (ex * ex + ey * ey)).clamp(0.0, 1.0);
            ((p.0 - a.0 - u * ex).powi(2) + (p.1 - a.1 - u * ey).powi(2)).sqrt()
        }

        impl Solid {
            pub(super) fn shape(self) -> Shape {
                let (radius, half_height) = (fx(self.r), fx(self.hh));
                if self.cone {
                    Shape::Cone {
                        radius,
                        half_height,
                    }
                } else {
                    Shape::Cylinder {
                        radius,
                        half_height,
                    }
                }
            }

            /// The signed distance of `l` in the frame of the geometric
            /// centre (negative inside).
            pub(super) fn signed(self, l: [f64; 3]) -> f64 {
                let (r, h) = (self.r, self.hh);
                let rho = (l[0] * l[0] + l[2] * l[2]).sqrt();
                if self.cone {
                    let p = (rho, l[1]);
                    let (a, b, c) = ((0.0, -h), (0.0, h), (r, -h));
                    let to_side = seg2(p, b, c);
                    let to_base = seg2(p, c, a);
                    if p.1 >= -h && p.0 * 2.0 * h <= r * (h - p.1) {
                        -to_side.min(to_base)
                    } else {
                        seg2(p, a, b).min(to_side).min(to_base)
                    }
                } else {
                    let (dx, dy) = (rho - r, l[1].abs() - h);
                    let out = (dx.max(0.0).powi(2) + dy.max(0.0).powi(2)).sqrt();
                    out + dx.max(dy).min(0.0)
                }
            }
        }

        /// `v` turned by the quaternion `q = (w, x, y, z)`, or by its inverse.
        pub(super) fn rotate(q: [f64; 4], v: [f64; 3], inverse: bool) -> [f64; 3] {
            let s = if inverse { -1.0 } else { 1.0 };
            let (w, x, y, z) = (q[0], s * q[1], s * q[2], s * q[3]);
            let t = [
                2.0 * (y * v[2] - z * v[1]),
                2.0 * (z * v[0] - x * v[2]),
                2.0 * (x * v[1] - y * v[0]),
            ];
            [
                v[0] + w * t[0] + (y * t[2] - z * t[1]),
                v[1] + w * t[1] + (z * t[0] - x * t[2]),
                v[2] + w * t[2] + (x * t[1] - y * t[0]),
            ]
        }

        pub(super) fn f3(v: Vec3Fix) -> [f64; 3] {
            [v.x.to_f64(), v.y.to_f64(), v.z.to_f64()]
        }

        /// A solid posed at `position` turned by `turn`, in a world and in `f64`.
        pub(super) struct Scene {
            pub(super) solid: Solid,
            pub(super) world: PhysicsWorld,
            pub(super) posed: PosedShape,
            position: [f64; 3],
            q: [f64; 4],
        }

        impl Scene {
            pub(super) fn new(solid: Solid, position: [f64; 3], turn: QuatFix) -> Self {
                let mut world = world();
                let i = world.add_body(RigidBody::new_static(p3(position)));
                assert!(world.set_body_shape(i, &solid.shape()));
                world.bodies[i].rotation = turn;
                let r = world.bodies[i].rotation;
                Self {
                    solid,
                    world,
                    posed: PosedShape {
                        shape: solid.shape(),
                        position: p3(position),
                        rotation: r,
                    },
                    position: f3(p3(position)),
                    q: [r.w.to_f64(), r.x.to_f64(), r.y.to_f64(), r.z.to_f64()],
                }
            }

            /// Turned about `axis` by `angle`.
            pub(super) fn turned(
                solid: Solid,
                position: [f64; 3],
                axis: [f64; 3],
                angle: f64,
            ) -> Self {
                let turn = QuatFix::from_axis_angle(p3(unit(axis)), fx(angle));
                Self::new(solid, position, turn)
            }

            /// The signed distance of the world point `p`.
            pub(super) fn point(&self, p: [f64; 3]) -> f64 {
                let o = self.position;
                let mut l = rotate(self.q, [p[0] - o[0], p[1] - o[1], p[2] - o[2]], true);
                if self.solid.cone {
                    l[1] -= 0.5 * self.solid.hh;
                }
                self.solid.signed(l)
            }

            /// The signed distance of the segment `a`–`b`.
            pub(super) fn segment(&self, a: [f64; 3], b: [f64; 3]) -> f64 {
                let at = |s: f64| {
                    self.point([
                        a[0] + s * (b[0] - a[0]),
                        a[1] + s * (b[1] - a[1]),
                        a[2] + s * (b[2] - a[2]),
                    ])
                };
                if a == b {
                    return at(0.0);
                }
                let (mut lo, mut hi) = (0.0f64, 1.0f64);
                for _ in 0..100 {
                    let m1 = lo + (hi - lo) / 3.0;
                    let m2 = hi - (hi - lo) / 3.0;
                    if at(m1) <= at(m2) {
                        hi = m2;
                    } else {
                        lo = m1;
                    }
                }
                at(0.5 * (lo + hi)).min(at(0.0)).min(at(1.0))
            }
        }

        /// A cast of the core `a`–`b` grown by `r` along `d` (normalized by
        /// the cast) up to `max_t`: the inputs given to the code under test and
        /// the same in `f64`.
        pub(super) struct Cast {
            fixed: [Vec3Fix; 3],
            a: [f64; 3],
            b: [f64; 3],
            d: [f64; 3],
            r: f64,
            max_t: f64,
        }

        impl Cast {
            pub(super) fn new(a: [f64; 3], b: [f64; 3], d: [f64; 3], r: f64, max_t: f64) -> Self {
                let fixed = [p3(a), p3(b), p3(d)];
                Self {
                    a: f3(fixed[0]),
                    b: f3(fixed[1]),
                    d: unit(f3(fixed[2])),
                    fixed,
                    r,
                    max_t,
                }
            }

            /// The gap at `t`.
            pub(super) fn gap(&self, s: &Scene, t: f64) -> f64 {
                let mv = |p: [f64; 3]| {
                    [
                        p[0] + t * self.d[0],
                        p[1] + t * self.d[1],
                        p[2] + t * self.d[2],
                    ]
                };
                s.segment(mv(self.a), mv(self.b)) - self.r
            }

            /// The least gap on `[0, max_t]`.
            pub(super) fn least(&self, s: &Scene) -> f64 {
                let (mut lo, mut hi) = (0.0f64, self.max_t);
                for _ in 0..120 {
                    let m1 = lo + (hi - lo) / 3.0;
                    let m2 = hi - (hi - lo) / 3.0;
                    if self.gap(s, m1) <= self.gap(s, m2) {
                        hi = m2;
                    } else {
                        lo = m1;
                    }
                }
                self.gap(s, 0.5 * (lo + hi))
            }

            /// The time of the code under test's hit.
            pub(super) fn run(&self, s: &Scene) -> Option<f64> {
                let f = RayFilter::default();
                let (r, max_t) = (fx(self.r), fx(self.max_t));
                let h = if self.fixed[0] == self.fixed[1] {
                    s.world
                        .cast_sphere(self.fixed[0], r, self.fixed[2], max_t, &f)
                } else {
                    s.world
                        .cast_capsule(self.fixed[0], self.fixed[1], r, self.fixed[2], max_t, &f)
                };
                h.map(|h| h.t.to_f64())
            }
        }
    }

    /// The exact distance of a point to a cylinder and a cone in their frame
    /// ([`point_cylinder_exact`], [`point_cone_exact`]) against the meridian
    /// closed form: outside, the distance, a nearest point on the surface and
    /// the normal from it toward the point; inside or on the surface, `Inside`.
    /// Points beside, above and below each, at their rims, on the axis (where
    /// the part across it is 0) and beyond the cone's apex.
    #[test]
    #[allow(clippy::disallowed_methods)] // f64 oracle, not production arithmetic
    fn point_distances_to_a_cylinder_and_a_cone_are_their_meridian_closed_forms() {
        use round_reference::Solid;
        let solids = [
            Solid {
                cone: false,
                r: 0.9,
                hh: 0.7,
            },
            Solid {
                cone: true,
                r: 1.0,
                hh: 0.8,
            },
        ];
        // (ρ, y) in the meridian half-plane, turned about the axis by (c, s)
        let meridian = [
            (1.5, 0.1),
            (0.3, 1.4),
            (0.3, -1.6),
            (1.3, 1.2),
            (1.4, -1.1),
            (0.0, 2.0),
            (0.0, -2.0),
            (0.2, 0.0),
            (0.0, 0.0),
            (0.7, 0.5),
            (2.0, 2.0),
            (0.05, 1.3),
            (1.0, -0.79),
        ];
        let turns = [(1.0, 0.0), (0.6, 0.8), (-0.28, 0.96), (0.0, -1.0)];
        let (mut outside, mut inside) = (0, 0);
        for solid in solids {
            let (radius, hh) = (fx(solid.r), fx(solid.hh));
            for &(rho, y) in &meridian {
                for &(c, s) in &turns {
                    let p = [rho * c, y, rho * s];
                    let want = solid.signed(p);
                    let got = if solid.cone {
                        point_cone_exact(p3(p), radius, hh)
                    } else {
                        point_cylinder_exact(p3(p), radius, hh)
                    };
                    match got {
                        Dist::Outside {
                            dist,
                            point,
                            normal,
                        } => {
                            outside += 1;
                            assert!(want > 0.0, "{solid:?} {p:?}: outside, closed form {want}");
                            assert!(
                                (dist.to_f64() - want).abs() < EXACT,
                                "{solid:?} {p:?}: distance {} but the closed form is {want}",
                                dist.to_f64()
                            );
                            let q = round_reference::f3(point);
                            assert!(
                                solid.signed(q).abs() < EXACT,
                                "{solid:?} {p:?}: nearest point {q:?} is {} off the surface",
                                solid.signed(q)
                            );
                            let to = [
                                (p[0] - q[0]) / want,
                                (p[1] - q[1]) / want,
                                (p[2] - q[2]) / want,
                            ];
                            assert_vec(normal, to, 1e-10, "normal");
                        }
                        Dist::Inside => {
                            inside += 1;
                            assert!(want <= 0.0, "{solid:?} {p:?}: inside, closed form {want}");
                        }
                        Dist::AtLeast(_) => panic!("{solid:?} {p:?}: a bound, not a distance"),
                    }
                }
            }
            // on the surface: the cylinder's cap, the cone's base
            let on = if solid.cone {
                point_cone_exact(v3(0.5, -0.8, 0.0), radius, hh)
            } else {
                point_cylinder_exact(v3(0.3, 0.7, 0.0), radius, hh)
            };
            assert!(matches!(on, Dist::Inside), "{solid:?}: on the surface");
        }
        // not vacuous: both kinds of answer were checked
        assert!(
            outside >= 70 && inside >= 10,
            "{outside} outside, {inside} inside"
        );
    }

    /// [`exact_round_dist`] of points and segments to a posed cylinder and cone
    /// (aligned, turned, moved) against the `f64` reference: the least distance
    /// along the segment, and a nearest point on the surface; `None` for a solid
    /// that is not a cylinder or a cone.
    #[test]
    fn exact_round_distances_are_the_least_along_the_segment() {
        use round_reference::{Scene, Solid};
        let cylinder = Solid {
            cone: false,
            r: 0.9,
            hh: 0.7,
        };
        let cone = Solid {
            cone: true,
            r: 1.0,
            hh: 0.8,
        };
        let position = [0.25, -0.5, 0.75];
        let scenes = [
            Scene::new(cylinder, position, QuatFix::IDENTITY),
            Scene::turned(cylinder, position, [0.6, 0.7, -0.2], 0.9),
            Scene::new(cone, position, QuatFix::IDENTITY),
            Scene::turned(cone, position, [0.6, 0.7, -0.2], 0.9),
        ];
        let cores = [
            ([2.5, -0.4, 0.8], [2.5, -0.4, 0.8]),
            ([0.1, 2.0, 0.9], [0.6, 2.2, 0.4]),
            ([-1.5, -2.5, 1.0], [-1.0, -2.0, 2.0]),
            ([1.6, 1.0, -0.5], [1.4, 1.6, -0.9]),
            ([-2.0, 0.0, 0.75], [2.5, 0.0, 3.0]),
            ([0.25, 3.0, 0.75], [0.25, 3.0, 0.75]),
        ];
        let mut checked = 0;
        for s in &scenes {
            for &(a, b) in &cores {
                let (pa, pb) = (p3(a), p3(b));
                let (a, b) = (round_reference::f3(pa), round_reference::f3(pb));
                let want = s.segment(a, b);
                let got = exact_round_dist(&s.posed, pa, pb).expect("a cylinder or a cone");
                match got {
                    Dist::Outside { dist, point, .. } => {
                        checked += 1;
                        assert!(
                            (dist.to_f64() - want).abs() < 1e-10,
                            "{:?} {a:?}–{b:?}: distance {} but the reference is {want}",
                            s.solid,
                            dist.to_f64()
                        );
                        let q = round_reference::f3(point);
                        assert!(
                            s.point(q).abs() < 1e-10,
                            "{:?}: nearest point {q:?} is {} off the surface",
                            s.solid,
                            s.point(q)
                        );
                    }
                    _ => assert!(
                        want <= 0.0,
                        "{:?} {a:?}–{b:?}: inside, reference {want}",
                        s.solid
                    ),
                }
            }
        }
        assert!(checked >= 20, "only {checked} distances checked");
        let ball = PosedShape {
            shape: Shape::Box {
                half_extents: v3(1.0, 1.0, 1.0),
            },
            position: Vec3Fix::ZERO,
            rotation: QuatFix::IDENTITY,
        };
        assert!(exact_round_dist(&ball, v3(3.0, 0.0, 0.0), v3(3.0, 0.0, 0.0)).is_none());
    }

    /// Casts onto a cone and a cylinder at the edge of what a time of impact
    /// can tell apart (paths that graze a rim, a cap or a base, or go into the
    /// side just below a cap, `1` to `40·2⁻³²` deep): each path goes more than
    /// `2⁻³²` in, and the hit is within `[−1, +2]·2⁻³²` of the surface by the
    /// `f64` reference. These go through the lower bound's step, the exact
    /// distance where GJK's bounds straddle a decision, and the search along a
    /// near-tangent path.
    #[test]
    fn casts_at_the_edge_of_the_tolerance_stop_at_the_curved_surface() {
        use round_reference::{Cast, Scene, Solid, TOL};
        let cyl = |r, hh| Solid { cone: false, r, hh };
        let cone = |r, hh| Solid { cone: true, r, hh };
        let p = [0.25, -0.5, 0.75];
        let tilt = [0.6, 0.7, -0.2];
        let cases: Vec<(&str, Scene, Cast)> = vec![
            (
                "segment over a rim",
                Scene::new(cyl(0.9, 0.7), p, QuatFix::IDENTITY),
                Cast::new(
                    [-1.6640986290561979, 0.19999999975304572, 1.8206196513237867],
                    [-1.834506720909574, 0.41213203410901, 1.6942824745669378],
                    [0.5955591626715423, 0.0, -0.8033114487905494],
                    0.0,
                    4.0,
                ),
            ),
            (
                "segment over a rim, stepping by the lower bound",
                Scene::new(cyl(0.9, 0.7), p, QuatFix::IDENTITY),
                Cast::new(
                    [1.8673886946205231, 0.19999999967072768, -0.7312338808982968],
                    [2.0622378155658776, 0.41213203402669196, -0.6473660082245325],
                    [-0.3953569432753914, 0.0, 0.9185275648579845],
                    0.0,
                    4.0,
                ),
            ),
            (
                "segment over a turned rim",
                Scene::turned(cyl(0.9, 0.7), p, tilt, 0.9),
                Cast::new(
                    [-0.21852465418609512, -0.6507157640535539, 2.998948511156243],
                    [
                        -0.34405370476815655,
                        -0.41720885309588485,
                        3.139365675331331,
                    ],
                    [-0.06648810702703647, 0.487707135982694, -0.8704717578046512],
                    0.0,
                    4.0,
                ),
            ),
            (
                "sphere over a cone's rim",
                Scene::new(cone(1.0, 0.8), p, QuatFix::IDENTITY),
                Cast::new(
                    [-1.7015908184354425, -0.9027621356993638, 1.8439950540065662],
                    [-1.7015908184354425, -0.9027621356993638, 1.8439950540065662],
                    [0.5606127132316385, 0.0, -0.8280781278134695],
                    1.0 / 256.0,
                    4.0,
                ),
            ),
            (
                "sphere onto a turned cone",
                Scene::turned(cone(1.0, 0.8), p, tilt, 0.9),
                Cast::new(
                    [0.634936017399154, 0.008205912075554433, -1.4320403873864982],
                    [0.634936017399154, 0.008205912075554433, -1.4320403873864982],
                    [0.19818663470094447, -0.5210934105185997, 0.8301708952619384],
                    1.0 / 256.0,
                    4.0,
                ),
            ),
            (
                "sphere along a turned cone's base",
                Scene::turned(cone(1.0, 0.8), p, tilt, 0.9),
                Cast::new(
                    [1.4096423077353353, -1.9430159060992016, 1.6571642739508496],
                    [1.4096423077353353, -1.9430159060992016, 1.6571642739508496],
                    [-0.7361296676461404, 0.528908761536265, -0.422337109879486],
                    1.0 / 65536.0,
                    4.0,
                ),
            ),
            (
                "segment into a cylinder's side below its cap",
                Scene::new(cyl(0.9, 0.7), p, QuatFix::IDENTITY),
                Cast::new(
                    [-1.695761194159812, 0.19999999973806548, 0.2143570449433858],
                    [-1.695761194159812, 0.4999999997380655, 0.2143570449433858],
                    [0.9909759596810406, 0.0, 0.1340397229713666],
                    0.0,
                    4.0,
                ),
            ),
            (
                "segment into a turned cylinder's side below its cap",
                Scene::turned(cyl(0.9, 0.7), p, tilt, 0.9),
                Cast::new(
                    [
                        -0.7916938670894744,
                        1.1912886520345445,
                        -0.03569496775777914,
                    ],
                    [-0.6883045505593128, 1.4402697713519372, 0.09590689944358055],
                    [0.7223971058724328, -0.5328868033551468, 0.4406518764706059],
                    0.0,
                    4.0,
                ),
            ),
            (
                "sphere grazing into a turned cone",
                Scene::turned(cone(1.0, 0.8), [0.0; 3], tilt, 0.9),
                Cast::new(
                    [3.49676953785352, -1.9311419641957024, -0.20807093324643489],
                    [3.49676953785352, -1.9311419641957024, -0.20807093324643489],
                    [
                        -0.8417749934677569,
                        0.49646776600120957,
                        -0.21197787076514807,
                    ],
                    1.0 / 65536.0,
                    10.0,
                ),
            ),
            (
                "sphere at 9·10⁻¹⁰ rad to a turned cone's base",
                Scene::turned(
                    cone(0.6428203322684567, 0.7475816177966408),
                    [
                        -1.6526587531452606,
                        -1.2186799371102097,
                        0.18938048544987396,
                    ],
                    [
                        -0.5803070933934578,
                        0.7790505106677301,
                        -0.23732673508311564,
                    ],
                    1.8984897774453202,
                ),
                Cast::new(
                    [
                        -0.8965821042720563,
                        -3.3486672559565704,
                        -0.9839086836373099,
                    ],
                    [
                        -0.8965821042720563,
                        -3.3486672559565704,
                        -0.9839086836373099,
                    ],
                    [-0.1482674077997217, 0.8136896687128683, 0.5620728589901773],
                    1.0 / 65536.0,
                    10.0,
                ),
            ),
            (
                "capsule sliding onto a turned cylinder's cap at 9·10⁻¹⁰ rad",
                Scene::turned(
                    cyl(0.9012093363780878, 0.5179403340707722),
                    [
                        -0.4023466290173019,
                        -0.46594330930383876,
                        -1.2957395342946256,
                    ],
                    [
                        -0.6714485362126652,
                        -0.09612558018852724,
                        -0.7347902667097514,
                    ],
                    0.5010374581070209,
                ),
                Cast::new(
                    [1.8608221708009296, -2.0500185708660865, -1.4757067685941365],
                    [1.3062351220451092, -1.5734718199873896, -0.7798910803267063],
                    [
                        -0.9249401521738037,
                        0.2939600468880599,
                        -0.24098382877309632,
                    ],
                    1.0 / 65536.0,
                    10.0,
                ),
            ),
        ];
        for (what, scene, cast) in &cases {
            let least = cast.least(scene);
            assert!(
                least < -TOL,
                "{what}: the path goes only {} in",
                least / TOL
            );
            let t = cast
                .run(scene)
                .unwrap_or_else(|| panic!("{what}: no hit, the path goes {} in", least / TOL));
            let g = cast.gap(scene, t) / TOL;
            assert!(
                (-1.0..=2.0).contains(&g),
                "{what}: a hit at t = {t} with gap {g}·2⁻³², expected within [−1, +2]"
            );
        }
    }

    /// Paths that pass a cylinder's side tangentially, `2⁻²⁷` (32 tolerances)
    /// outside it, inside the gap where the slope is not a proof of separation
    /// (`2⁻²⁴`) and well outside it: none goes in, and none is a hit; the
    /// same paths `2⁻²⁷` inside the side are hits at its surface.
    #[test]
    fn paths_tangent_to_a_cylinder_hit_only_when_they_go_in() {
        use round_reference::{Cast, Scene, Solid, TOL};
        let solid = Solid {
            cone: false,
            r: 0.9,
            hh: 0.7,
        };
        let scene = Scene::new(solid, [0.0; 3], QuatFix::IDENTITY);
        let off = 1.0 / 134_217_728.0; // 2⁻²⁷
        for (g, hit) in [(off, false), (64.0 * off, false), (-off, true)] {
            for r in [0.0, 1.0 / 65536.0] {
                let z = 0.9 + r + g;
                let cast = if r == 0.0 {
                    // a short vertical segment of radius 0 across the axis' height
                    Cast::new([-3.0, 0.1, z], [-3.0, 0.3, z], [1.0, 0.0, 0.0], 0.0, 6.0)
                } else {
                    Cast::new([-3.0, 0.2, z], [-3.0, 0.2, z], [1.0, 0.0, 0.0], r, 6.0)
                };
                // the least gap is g, at x = 0 (`t = 3`)
                let least = cast.least(&scene);
                assert!(
                    (least - g).abs() < 1e-3 * TOL,
                    "g = {g:e}, r = {r}: least gap {least:e}"
                );
                match (cast.run(&scene), hit) {
                    (None, false) => {}
                    (Some(t), true) => {
                        let gt = cast.gap(&scene, t) / TOL;
                        assert!(
                            (-1.0..=2.0).contains(&gt),
                            "g = {g:e}, r = {r}: a hit at t = {t} with gap {gt}·2⁻³²"
                        );
                    }
                    (got, _) => panic!("g = {g:e}, r = {r}: {got:?}, expected a hit: {hit}"),
                }
            }
        }
    }

    /// [`graze_contact`] and [`dips_below`] on gap functions whose roots are
    /// known: `(t − 1)² − c` (into the solid by `c` at `t = 1`, first in at
    /// `1 − √c`), `(t − 1)² + c` (never in), a gap that is inside (`None`)
    /// below `−1/8`, and one that falls linearly and is in only at the far end.
    #[test]
    fn the_near_tangent_searches_find_the_roots_of_a_convex_gap() {
        type Gap<'a> = &'a dyn Fn(f64) -> Option<f64>;
        /// A gap function in `f64` given to the searches as `Fix128`.
        fn as_dist(g: Gap<'_>) -> impl Fn(Fix128) -> Dist + '_ {
            move |t: Fix128| match g(t.to_f64()) {
                Some(v) => Dist::Outside {
                    dist: fx(v),
                    point: Vec3Fix::ZERO,
                    normal: Vec3Fix::UNIT_Y,
                },
                None => Dist::Inside,
            }
        }
        let tol = 1.0 / 4_294_967_296.0;
        let quadratic = |c: f64| move |t: f64| Some((t - 1.0) * (t - 1.0) - c);
        let deep_inside = |t: f64| {
            let g = (t - 1.0) * (t - 1.0) - 0.25;
            (g >= -0.125).then_some(g)
        };
        let falling = |t: f64| Some(0.5 - 0.25 * t);
        let (t0, max_t) = (Fix128::ZERO, fx(3.0));
        // first in (the gap within ±2⁻³²) at 1 − √c
        let (q4, q20, never) = (
            quadratic(0.25),
            quadratic(1.0 / 1_048_576.0),
            quadratic(-1e-3),
        );
        let cases: [(&str, Gap<'_>, Option<f64>); 5] = [
            ("into by 1/4", &q4, Some(0.5)),
            ("into by 2⁻²⁰", &q20, Some(1.0 - 1.0 / 1024.0)),
            ("inside below −1/8", &deep_inside, Some(0.5)),
            ("in only at the far end", &falling, Some(2.0)),
            ("never in", &never, None),
        ];
        for (name, g, root) in cases {
            let got = graze_contact(as_dist(g), Fix128::ZERO, Fix128::ZERO, t0, max_t);
            match (got, root) {
                (None, None) => {}
                (Some(c), Some(root)) => {
                    let t = c.t.to_f64();
                    // the clear end of a bisection to within the tolerance
                    let gap = g(t).expect("the contact is outside");
                    assert!(
                        (-tol..=tol).contains(&gap) || (gap > 0.0 && (t - root).abs() < 1e-9),
                        "{name}: contact at t = {t} with gap {gap:e}, the root is {root}"
                    );
                    assert!(
                        (t - root).abs() < 1e-6,
                        "{name}: t = {t}, the root is {root}"
                    );
                    assert_vec(c.normal, [0.0, 1.0, 0.0], EXACT, "normal");
                }
                (got, _) => panic!(
                    "{name}: {:?}, the root is {root:?}",
                    got.map(|c| c.t.to_f64())
                ),
            }
            // dips_below from t0 with the gap and speed there
            let gap_at = |t: Fix128| g(t.to_f64()).map(fx);
            let f0 = g(0.0).expect("clear at the start");
            let speed = match name {
                "in only at the far end" => 0.25,
                _ => 2.0,
            };
            assert_eq!(
                dips_below(gap_at, t0, fx(f0), fx(speed), max_t),
                root.is_some(),
                "{name}: dips below"
            );
        }
        // a path that sinks too little to go in by the far end
        let shallow = |t: f64| Some((t - 1.0) * (t - 1.0) - 0.5 * tol);
        let gap_at = |t: Fix128| shallow(t.to_f64()).map(fx);
        assert!(
            !dips_below(gap_at, t0, fx(1.0), fx(2.0), max_t),
            "half a tolerance in"
        );
    }
}