concinnity-core 0.19.24

Runtime vocabulary for the Concinnity engine: GPU layouts, ECS components, registry, CPU kernels
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
// The simulation itself: body storage, and the order the stages run in.
//
// Bodies live in a fixed-capacity pool, so a full world declines a body rather
// than growing under a caller's feet, and a slot's generation makes a handle
// to a removed body read as absent. That is also what lets every other stage
// index its own arrays by slot: the pool's slot is the one identity the whole
// step agrees on.
//
// Nothing on the step path allocates, and neither does a query. Every buffer
// is reserved when the simulation is built and reused, which is what lets the
// step run inside a frame budget rather than at the allocator's convenience.

use alloc::vec::Vec;

use crate::memory::{Pool, PoolHandle};

use crate::physics::{
    BodyHandle, CharacterMove, CharacterMoveInput, ColliderShape, ContactHit, DynamicParams,
    Fanout, JointSpec, LayerMask, RayHit, SensorCrossing,
};

use super::body::Body;
use super::broadphase::{Proxy, Role, SweepPrune};
use super::ccd::{self, Ccd};
use super::character::{self, CharacterCapsule, CharacterConfig};
use super::collide::heightfield::{Heightfield, Heightfields};
use super::config::SimConfig;
use super::contact::{ContactCache, Manifold, carry_impulses};
use super::impact::Impacts;
use super::island::Islands;
use super::joint::{Joint, JointFrame, JointSet};
#[cfg(test)]
use super::math::Mat3;
use super::math::{Quat, Vec3};
use super::narrow::{self, Narrow};
use super::query::{self, RayQuery};
#[cfg(test)]
use super::query::{ShapeCast, ShapeCastHit};
use super::scene::Scene;
use super::sensor::Sensors;
use super::solver::{self, Solver, SolverBody};

// Friction of a character capsule against what it is driven into. A character
// is moved by resolving a translation rather than by the solver, so this only
// governs what the capsule pushes.
const CHARACTER_FRICTION: f32 = 0.5;

// What a step is worth handing out, in units of one body's integration -- a
// contact costs about twenty of those and a joint about sixteen.
//
// The threshold is high on purpose. Gathering a pool's workers from a thread
// that is not one of them costs about as much as three hundred of these units,
// and the gathering is serial: a step that only just covers it comes out level
// at best. So a step hands its work out once it is worth an order of magnitude
// more than the gathering, and keeps it otherwise.
const CONTACT_COST: usize = 20;
const JOINT_COST: usize = 16;
const MIN_FANOUT_COST: usize = 4000;

/// A rigid-body simulation: bodies fall under gravity, collide, and come to
/// rest.
///
/// The capacity given at construction is the whole reservation. Adding past it
/// returns `None`; stepping never allocates.
///
/// # Examples
///
/// ```
/// use concinnity_core::physics::{ColliderShape, DynamicParams, LayerMask, Simulation};
///
/// let mut sim = Simulation::with_capacity(2);
/// sim.add_fixed(
///     &ColliderShape::Cuboid { half_extents: [10.0, 0.5, 10.0] },
///     [0.0, -0.5, 0.0],
///     [0.0; 3],
///     0.8,
///     LayerMask::ALL,
/// );
/// let ball = sim
///     .add_dynamic(
///         &ColliderShape::Ball { radius: 0.5 },
///         [0.0, 5.0, 0.0],
///         [0.0; 3],
///         DynamicParams {
///             mass: 1.0,
///             friction: 0.5,
///             restitution: 0.0,
///             gravity_scale: 1.0,
///             linear_damping: 0.0,
///         },
///         LayerMask::ALL,
///     )
///     .expect("room in the pool");
///
/// for _ in 0..180 {
///     sim.step(1.0 / 60.0);
/// }
///
/// let (position, _rotation) = sim.body_pose_quat(ball).expect("a live body");
/// assert!(
///     (position[1] - 0.5).abs() < 0.02,
///     "the ball rests on the floor, at y = {}",
///     position[1]
/// );
/// ```
pub struct Simulation {
    config: SimConfig,
    character: CharacterConfig,
    bodies: Pool<Body>,
    broadphase: SweepPrune,
    contacts: ContactCache,
    fields: Heightfields,
    narrow: Narrow,
    joints: JointSet,
    islands: Islands,
    solver: Solver,
    sensors: Sensors,
    impacts: Impacts,
    ccd: Ccd,
    /// Workers the per-worker scratch was reserved for. One until a caller
    /// says otherwise, which is what makes the serial path the default.
    workers: usize,
    /// Steps asked to split further than the reservation allows.
    worker_overflows: u32,
}

impl core::fmt::Debug for Simulation {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Simulation")
            .field("bodies", &self.bodies.len())
            .field("capacity", &self.bodies.capacity())
            .field("joints", &self.joints.len())
            .finish()
    }
}

impl Simulation {
    /// Reserve room for `capacity` bodies, with the default tuning.
    pub fn with_capacity(capacity: usize) -> Self {
        Self::new(SimConfig::default(), capacity)
    }

    /// Reserve room for `capacity` bodies, tuned by `config`.
    pub fn new(config: SimConfig, capacity: usize) -> Self {
        Simulation {
            config,
            character: CharacterConfig::default(),
            bodies: Pool::with_capacity(capacity),
            broadphase: SweepPrune::with_capacity(capacity),
            // Two contacts per body covers a stack, which is what the
            // reservation is sized for. A scene denser than that grows these
            // buffers once, early, and never again.
            contacts: ContactCache::with_capacity(capacity * 2),
            fields: Heightfields::new(),
            narrow: Narrow::new(),
            // A world with more joints than bodies is unusual enough to pay
            // for one reservation while it is being built; nothing added
            // afterwards is on the step path.
            joints: JointSet::with_capacity(capacity),
            islands: Islands::with_capacity(capacity),
            solver: Solver::with_capacity(capacity),
            // A crossing is a boundary rather than a state, so a world
            // records far fewer of them than it has bodies. A hit is one per
            // contact pair, so the queue is reserved the way the contact list
            // above is.
            sensors: Sensors::with_capacity(capacity),
            impacts: Impacts::with_capacity(capacity * 2),
            ccd: Ccd::with_capacity(capacity),
            workers: 1,
            worker_overflows: 0,
        }
    }

    /// Reserve the scratch a step needs to split into `workers` pieces, and
    /// return how many it will actually use.
    ///
    /// Call this once while the world is built, with the worker count of the
    /// fan-out that will be stepping it. A simulation nobody calls this on
    /// reserves nothing and steps on the calling thread, which is what lets a
    /// host with no threads use the same simulation unchanged.
    ///
    /// Splitting never changes what a step produces, so the reserved count is
    /// a ceiling rather than a promise: a step handed a wider fan-out uses
    /// this many pieces of it and leaves the rest of it idle.
    pub fn reserve_workers(&mut self, workers: usize) -> usize {
        let capacity = self.bodies.capacity();
        self.workers = workers.clamp(1, solver::MAX_WORKERS);
        self.broadphase.reserve_workers(self.workers, capacity);
        self.narrow.reserve_workers(self.workers, capacity);
        self.workers
    }

    /// Workers the step splits into at most: what
    /// [`Simulation::reserve_workers`] settled on.
    pub fn workers(&self) -> usize {
        self.workers
    }

    #[cfg(test)]
    /// Steps that were handed a wider fan-out than the reservation covers,
    /// since the count was last cleared. Each one ran on the reserved number
    /// of workers instead, which changes nothing about the result.
    pub(crate) fn worker_overflows(&self) -> u32 {
        self.worker_overflows
    }

    #[cfg(test)]
    /// Forget the count above.
    pub(crate) fn clear_worker_overflows(&mut self) {
        self.worker_overflows = 0;
    }

    /// Tune the character controller. `grounded` is true for a gravity-bound
    /// character, which climbs steps and stays attached to the ground, and
    /// false for a free-flying camera, which does neither. A `max_slope_deg`
    /// of `0` disables the climb limit.
    pub fn configure_character(&mut self, max_slope_deg: f32, step_height: f32, grounded: bool) {
        self.character = CharacterConfig::new(max_slope_deg, step_height, grounded);
    }

    /// Build the capsule a character move is resolved against: a cylinder of
    /// `2 * half_height` capped by hemispheres of `radius`.
    ///
    /// A caller holds one per character across the fixed ticks rather than
    /// building one per move.
    pub fn character_shape(half_height: f32, radius: f32) -> CharacterCapsule {
        CharacterCapsule::new(half_height, radius)
    }

    /// The tuning this simulation steps with.
    pub fn config(&self) -> &SimConfig {
        &self.config
    }

    #[cfg(test)]
    /// Re-tune the simulation. Takes effect on the next step.
    pub(crate) fn set_config(&mut self, config: SimConfig) {
        self.config = config;
    }

    /// Bodies the pool can hold.
    pub fn capacity(&self) -> usize {
        self.bodies.capacity()
    }

    /// Bodies currently in the simulation.
    pub fn body_count(&self) -> usize {
        self.bodies.len()
    }

    /// Colliders currently in the simulation. A body carries exactly one
    /// shape, so this is the body count until compound shapes exist.
    pub fn collider_count(&self) -> usize {
        self.bodies.len()
    }

    /// Joints currently constraining bodies.
    pub fn joint_count(&self) -> usize {
        self.joints.len()
    }

    #[cfg(test)]
    /// Sensor pairs currently overlapping: what the regions are holding,
    /// rather than what crossed a boundary to get there.
    pub(crate) fn sensor_overlap_count(&self) -> usize {
        self.sensors.overlap_count()
    }

    /// Contact points the last step solved.
    #[cfg(test)]
    pub(crate) fn contact_count(&self) -> usize {
        self.contacts
            .manifolds()
            .iter()
            .map(|m| m.count as usize)
            .sum()
    }

    /// Bytes reserved for bodies, bounds, contacts, the solver's arrays, and
    /// the per-worker buffers [`Simulation::reserve_workers`] set aside: what
    /// the simulation costs whatever its occupancy.
    pub fn reserved_bytes(&self) -> u64 {
        self.bodies.reserved_bytes()
            + self.broadphase.reserved_bytes()
            + self.contacts.reserved_bytes()
            + self.fields.reserved_bytes()
            + self.narrow.reserved_bytes()
            + self.joints.reserved_bytes()
            + self.islands.reserved_bytes()
            + self.solver.reserved_bytes()
            + self.sensors.reserved_bytes()
            + self.impacts.reserved_bytes()
            + self.ccd.reserved_bytes()
    }

    /// Add an immovable body. `None` when the pool is full.
    pub fn add_fixed(
        &mut self,
        shape: &ColliderShape,
        pos: [f32; 3],
        euler_deg: [f32; 3],
        friction: f32,
        mask: LayerMask,
    ) -> Option<BodyHandle> {
        self.add(Body::fixed(
            *shape,
            Vec3::from_array(pos),
            Quat::from_euler_deg(euler_deg),
            friction,
            mask,
        ))
    }

    /// Add a body driven to a position rather than by forces: infinite mass,
    /// untouched by gravity or impulses, but it pushes what it is driven
    /// into. Move it with [`Simulation::set_kinematic_translation`]. `None`
    /// when the pool is full.
    pub fn add_kinematic(
        &mut self,
        shape: &ColliderShape,
        pos: [f32; 3],
        euler_deg: [f32; 3],
        friction: f32,
        mask: LayerMask,
    ) -> Option<BodyHandle> {
        self.add(Body::kinematic(
            *shape,
            Vec3::from_array(pos),
            Quat::from_euler_deg(euler_deg),
            friction,
            mask,
        ))
    }

    /// Add a position-driven character capsule centred on `center`: a
    /// cylinder of `2 * half_height` capped by hemispheres of `radius`.
    ///
    /// Gravity does not move it and the solver does not push it. Resolve a
    /// desired move with [`Simulation::move_character`] and apply the answer
    /// with [`Simulation::set_kinematic_translation`]. `None` when the pool is
    /// full.
    pub fn add_character(
        &mut self,
        half_height: f32,
        radius: f32,
        center: [f32; 3],
        mask: LayerMask,
    ) -> Option<BodyHandle> {
        self.add_kinematic(
            &ColliderShape::Capsule {
                half_height,
                radius,
            },
            center,
            [0.0; 3],
            CHARACTER_FRICTION,
            mask,
        )
    }

    /// Add a region that records what overlaps it and resists nothing.
    ///
    /// It never collides, never blocks a query, and never moves. What crosses
    /// its boundary is reported as a [`SensorCrossing`] carrying `tag`,
    /// collected with [`Simulation::drain_sensor_crossings_into`]. Freely
    /// simulated and position-driven bodies cross it; immovable geometry does
    /// not, and two overlapping regions record a crossing each.
    ///
    /// `None` when the pool is full.
    ///
    /// # Examples
    ///
    /// ```
    /// use concinnity_core::physics::{ColliderShape, DynamicParams, LayerMask, Simulation};
    ///
    /// let mut sim = Simulation::with_capacity(2);
    /// sim.add_sensor(
    ///     &ColliderShape::Cuboid { half_extents: [1.0, 1.0, 1.0] },
    ///     [0.0, 2.0, 0.0],
    ///     [0.0; 3],
    ///     7,
    ///     LayerMask::ALL,
    /// )
    /// .expect("room in the pool");
    ///
    /// // Nothing holds the ball up, so it falls through the region.
    /// sim.add_dynamic(
    ///     &ColliderShape::Ball { radius: 0.25 },
    ///     [0.0, 6.0, 0.0],
    ///     [0.0; 3],
    ///     DynamicParams {
    ///         mass: 1.0,
    ///         friction: 0.5,
    ///         restitution: 0.0,
    ///         gravity_scale: 1.0,
    ///         linear_damping: 0.0,
    ///     },
    ///     LayerMask::ALL,
    /// )
    /// .expect("room in the pool");
    ///
    /// let mut crossings = Vec::new();
    /// let (mut entered, mut left) = (false, false);
    /// for _ in 0..300 {
    ///     sim.step(1.0 / 60.0);
    ///     sim.drain_sensor_crossings_into(&mut crossings);
    ///     for crossing in &crossings {
    ///         assert_eq!(crossing.tag, 7);
    ///         if crossing.entered { entered = true } else { left = true }
    ///     }
    /// }
    /// assert!(entered && left, "the ball went in and came out again");
    /// ```
    pub fn add_sensor(
        &mut self,
        shape: &ColliderShape,
        pos: [f32; 3],
        euler_deg: [f32; 3],
        tag: u64,
        mask: LayerMask,
    ) -> Option<BodyHandle> {
        self.add(Body::sensor(
            *shape,
            Vec3::from_array(pos),
            Quat::from_euler_deg(euler_deg),
            tag,
            mask,
        ))
    }

    /// Move the boundary crossings recorded since the last drain into `out`,
    /// oldest first. `out` is cleared first, and both it and the queue keep
    /// their capacity, so a per-tick drain never reallocates.
    pub fn drain_sensor_crossings_into(&mut self, out: &mut Vec<SensorCrossing>) {
        self.sensors.drain_into(out);
    }

    #[cfg(test)]
    /// Crossings and overlaps the reservation had no room for, since the
    /// count was last cleared.
    ///
    /// Both are reserved against the body capacity, which covers a caller
    /// draining every step and a world whose regions hold fewer bodies than
    /// it has. A non-zero count means something crossed a region and no
    /// caller was told about it.
    pub(crate) fn sensor_overflows(&self) -> u32 {
        self.sensors.overflows()
    }

    #[cfg(test)]
    /// Reset the count of declined crossings.
    pub(crate) fn clear_sensor_overflows(&mut self) {
        self.sensors.clear_overflows();
    }

    /// Set the smallest contact impulse worth reporting as a
    /// [`ContactHit`], measured at a step of `tick_dt`.
    ///
    /// The simulation gates on the force that impulse stands for, so a pair
    /// leaning on another at rest stays silent while the same pair colliding
    /// does not. It applies to every body, whenever it is called.
    pub fn set_contact_min_impulse(&mut self, min_impulse: f32, tick_dt: f32) {
        self.impacts.set_min_impulse(min_impulse, tick_dt);
    }

    /// Move the contact hits recorded since the last drain into `out`, oldest
    /// first. `out` is cleared first, and both it and the queue keep their
    /// capacity.
    ///
    /// Only pairs with a freely simulated body on at least one side, carrying
    /// more than the force [`Simulation::set_contact_min_impulse`] set, appear.
    pub fn drain_contact_hits_into(&mut self, out: &mut Vec<ContactHit>) {
        self.impacts.drain_into(out);
    }

    #[cfg(test)]
    /// Contact hits the reservation had no room for, since the count was last
    /// cleared.
    ///
    /// The queue is reserved for one hit per contact pair, which covers a
    /// caller draining every step. A non-zero count means a collision
    /// happened that no caller was told about.
    pub(crate) fn contact_hit_overflows(&self) -> u32 {
        self.impacts.overflows()
    }

    /// Add a static height grid: terrain, addressed like any other body.
    ///
    /// `heights` is a `rows * cols` row-major grid of world-space `y` values,
    /// with rows running along `z` and columns along `x`. `scale` is the whole
    /// extent `[width, height_multiplier, depth]`, and the grid is centred on
    /// `pos`.
    ///
    /// `None` when the pool is full or the grid names no surface: fewer than
    /// two rows or columns, the wrong number of heights, or no footprint.
    ///
    /// The body is immovable and never rotates. Contacts against it are
    /// answered along the surface's own face normals, so a shape crossing the
    /// boundary between two cells is not caught by the edge they share.
    ///
    /// # Examples
    ///
    /// ```
    /// use concinnity_core::physics::{ColliderShape, DynamicParams, LayerMask, Simulation};
    ///
    /// let mut sim = Simulation::with_capacity(2);
    /// // A flat five-by-five grid twenty units square, its surface at y = 0.
    /// sim.add_heightfield(
    ///     5,
    ///     5,
    ///     vec![0.0; 25],
    ///     [20.0, 1.0, 20.0],
    ///     [0.0; 3],
    ///     LayerMask::ALL,
    /// )
    /// .expect("room in the pool");
    ///
    /// let ball = sim
    ///     .add_dynamic(
    ///         &ColliderShape::Ball { radius: 0.5 },
    ///         [1.0, 5.0, -2.0],
    ///         [0.0; 3],
    ///         DynamicParams {
    ///             mass: 1.0,
    ///             friction: 0.5,
    ///             restitution: 0.0,
    ///             gravity_scale: 1.0,
    ///             linear_damping: 0.0,
    ///         },
    ///         LayerMask::ALL,
    ///     )
    ///     .expect("room in the pool");
    ///
    /// for _ in 0..240 {
    ///     sim.step(1.0 / 60.0);
    /// }
    ///
    /// let (position, _) = sim.body_pose_quat(ball).expect("a live body");
    /// assert!(
    ///     (position[1] - 0.5).abs() < 0.02,
    ///     "the ball rests on the terrain, at y = {}",
    ///     position[1]
    /// );
    /// ```
    pub fn add_heightfield(
        &mut self,
        rows: usize,
        cols: usize,
        heights: Vec<f32>,
        scale: [f32; 3],
        pos: [f32; 3],
        mask: LayerMask,
    ) -> Option<BodyHandle> {
        if self.bodies.len() >= self.bodies.capacity() {
            return None;
        }
        let origin = Vec3::from_array(pos);
        let field = Heightfield::new(rows, cols, heights, Vec3::from_array(scale), origin)?;
        let bounds = field.bounds();
        let index = self.fields.push(field);
        // Terrain is fully rough: a slope holds whatever the body resting on
        // it brings, rather than the surface capping it.
        self.add(Body::terrain(index, bounds, origin, 1.0, mask))
    }

    #[cfg(test)]
    /// Queries that gave up with terrain still to look at, since the count was
    /// last cleared.
    ///
    /// A query walks a bounded number of the grid's triangles and stops rather
    /// than growing a buffer. A non-zero count means some question was asked
    /// of more surface than that, and the answer covered only part of it.
    pub(crate) fn heightfield_overflows(&self) -> u32 {
        self.fields.overflows()
    }

    #[cfg(test)]
    /// Reset the count of terrain queries that gave up.
    pub(crate) fn clear_heightfield_overflows(&mut self) {
        self.fields.clear_overflows();
    }

    #[cfg(test)]
    /// Fast bodies and swept region crossings the continuous-collision
    /// reservation had no room for, since the count was last cleared.
    ///
    /// The reservation holds one entry per body, which covers every body in
    /// the world moving fast at once. A non-zero count means a body took a
    /// step long enough to pass through something and was not swept.
    pub(crate) fn ccd_overflows(&self) -> u32 {
        self.ccd.overflows()
    }

    #[cfg(test)]
    /// Bodies the last step swept along their own path because they moved
    /// too far for its contact test to have seen what they crossed.
    ///
    /// Zero for a world at ordinary speeds, which is what the gate is for:
    /// a non-zero count is the number of bodies that paid for the expensive
    /// path on the last step.
    pub(crate) fn swept_body_count(&self) -> usize {
        self.ccd.mover_count()
    }

    /// Add a freely simulated body. `None` when the pool is full.
    pub fn add_dynamic(
        &mut self,
        shape: &ColliderShape,
        pos: [f32; 3],
        euler_deg: [f32; 3],
        params: DynamicParams,
        mask: LayerMask,
    ) -> Option<BodyHandle> {
        self.add(Body::dynamic(
            *shape,
            Vec3::from_array(pos),
            Quat::from_euler_deg(euler_deg),
            params,
            mask,
        ))
    }

    /// Constrain two bodies to each other. Anchors are in each body's own
    /// frame, and the joint holds the relative pose the bodies are in when it
    /// is made.
    ///
    /// Returns whether the joint was made. It needs two different live bodies;
    /// past that, degenerate input is repaired rather than refused, so a
    /// zero-length axis becomes `+Y` and limits given the wrong way round are
    /// read low to high.
    ///
    /// A joint is removed by removing either of the bodies it holds.
    ///
    /// # Examples
    ///
    /// ```
    /// use concinnity_core::physics::{
    ///     ColliderShape, DynamicParams, JointSpec, LayerMask, Simulation,
    /// };
    ///
    /// let mut sim = Simulation::with_capacity(2);
    /// let post = sim
    ///     .add_fixed(
    ///         &ColliderShape::Ball { radius: 0.1 },
    ///         [0.0, 4.0, 0.0],
    ///         [0.0; 3],
    ///         0.5,
    ///         LayerMask::ALL,
    ///     )
    ///     .expect("room in the pool");
    /// let bob = sim
    ///     .add_dynamic(
    ///         &ColliderShape::Ball { radius: 0.2 },
    ///         [1.0, 4.0, 0.0],
    ///         [0.0; 3],
    ///         DynamicParams {
    ///             mass: 1.0,
    ///             friction: 0.5,
    ///             restitution: 0.0,
    ///             gravity_scale: 1.0,
    ///             linear_damping: 0.0,
    ///         },
    ///         LayerMask::ALL,
    ///     )
    ///     .expect("room in the pool");
    ///
    /// assert!(sim.add_joint(post, bob, [0.0; 3], [-1.0, 0.0, 0.0], JointSpec::Spherical));
    ///
    /// for _ in 0..120 {
    ///     sim.step(1.0 / 60.0);
    /// }
    ///
    /// // The bob swings, but it stays one unit from the post it hangs off.
    /// let (position, _) = sim.body_pose_quat(bob).expect("a live body");
    /// let reach = ((position[0] - 0.0).powi(2)
    ///     + (position[1] - 4.0).powi(2)
    ///     + (position[2] - 0.0).powi(2))
    /// .sqrt();
    /// assert!((reach - 1.0).abs() < 0.01, "hanging {reach} from the post");
    /// ```
    pub fn add_joint(
        &mut self,
        body_a: BodyHandle,
        body_b: BodyHandle,
        anchor_a: [f32; 3],
        anchor_b: [f32; 3],
        spec: JointSpec,
    ) -> bool {
        let (slot_a, slot_b) = (body_a.index(), body_b.index());
        if slot_a == slot_b {
            return false;
        }
        let (anchor_a, anchor_b) = (Vec3::from_array(anchor_a), Vec3::from_array(anchor_b));
        if !anchor_a.is_finite() || !anchor_b.is_finite() {
            return false;
        }
        let (Some(a), Some(b)) = (
            self.bodies.get(pool_handle(body_a)),
            self.bodies.get(pool_handle(body_b)),
        ) else {
            return false;
        };
        let frame = JointFrame::new(spec, a.orientation, b.orientation);
        self.joints.push(Joint {
            a: slot_a,
            b: slot_b,
            anchor_a,
            anchor_b,
            frame,
            impulses: Default::default(),
        });
        // A joint arriving on a settled body has to be able to disturb it.
        for slot in [slot_a, slot_b] {
            if let Some(body) = self.bodies.get_at_mut(slot as usize) {
                body.wake();
            }
        }
        true
    }

    /// Send a position-driven body to `pos` over the next step. It arrives
    /// exactly there, pushing whatever it meets on the way. Returns whether
    /// the handle named a live position-driven body.
    ///
    /// The target is consumed by the step, so a body that is to keep moving
    /// is given a fresh one each tick and a body that is left alone stops.
    pub fn set_kinematic_translation(&mut self, handle: BodyHandle, pos: [f32; 3]) -> bool {
        let Some(body) = self.bodies.get_mut(pool_handle(handle)) else {
            return false;
        };
        if !body.is_kinematic() {
            return false;
        }
        body.kinematic_target = Some(Vec3::from_array(pos));
        true
    }

    /// Switch a body to position-driven control, keeping its handle and the
    /// mass it was authored with. Returns whether the handle named a live
    /// body.
    pub fn make_kinematic(&mut self, handle: BodyHandle) -> bool {
        self.reclassify(handle, |body| body.make_kinematic())
    }

    /// Hand a body back to the solver with a launch velocity, restoring the
    /// mass it was authored with. Returns whether the handle named a live
    /// body.
    pub fn make_dynamic(&mut self, handle: BodyHandle, linear_velocity: [f32; 3]) -> bool {
        let velocity = Vec3::from_array(linear_velocity);
        self.reclassify(handle, move |body| body.make_dynamic(velocity))
    }

    /// Whether a body is driven by position rather than by forces.
    #[cfg(test)]
    pub(crate) fn is_kinematic(&self, handle: BodyHandle) -> Option<bool> {
        Some(self.bodies.get(pool_handle(handle))?.is_kinematic())
    }

    /// What a query reads: the bodies, the sweep order, and the height grids.
    fn scene(&self) -> Scene<'_> {
        Scene {
            bodies: &self.bodies,
            broadphase: &self.broadphase,
            fields: &self.fields,
        }
    }

    /// Cast a ray, returning the nearest hit within `max_dist`.
    ///
    /// `dir` need not be unit length; a zero direction misses. `exclude`
    /// leaves one body out, and `mask` restricts the hit set to layers the
    /// query interacts with. A ray that begins inside a body hits it at zero
    /// distance with the normal turned back along the ray.
    pub fn raycast(
        &self,
        origin: [f32; 3],
        dir: [f32; 3],
        max_dist: f32,
        exclude: Option<BodyHandle>,
        mask: LayerMask,
    ) -> Option<RayHit> {
        query::raycast(
            self.scene(),
            &RayQuery {
                origin,
                dir,
                max_dist,
                exclude,
                mask,
            },
        )
    }

    /// Sweep a shape through the world, returning the nearest body it runs
    /// into and how far along the cast's motion that happens.
    #[cfg(test)]
    pub(crate) fn shape_cast(&self, cast: &ShapeCast) -> Option<ShapeCastHit> {
        query::shape_cast(self.scene(), cast)
    }

    /// Resolve a desired character move against the world without moving
    /// anything in it, returning the translation to apply and whether the
    /// capsule ends up on the ground.
    ///
    /// The capsule sweeps along the desired translation and slides along
    /// whatever it meets rather than stopping dead, up to a bounded number of
    /// deflections. `input.exclude` is the mover's own body, left out of the
    /// query so it does not collide with itself; other characters' capsules
    /// stay solid to it. What counts as ground, how high an obstacle is
    /// climbed, and whether the mover is gravity-bound at all come from
    /// [`Simulation::configure_character`].
    ///
    /// Apply the result with [`Simulation::set_kinematic_translation`].
    ///
    /// # Examples
    ///
    /// ```
    /// use concinnity_core::physics::{CharacterMoveInput, ColliderShape, LayerMask, Simulation};
    ///
    /// let mut sim = Simulation::with_capacity(3);
    /// sim.add_fixed(
    ///     &ColliderShape::Cuboid { half_extents: [10.0, 0.5, 10.0] },
    ///     [0.0, -0.5, 0.0],
    ///     [0.0; 3],
    ///     0.8,
    ///     LayerMask::ALL,
    /// );
    /// // A wall whose near face is at z = 1.
    /// sim.add_fixed(
    ///     &ColliderShape::Cuboid { half_extents: [4.0, 2.0, 0.5] },
    ///     [0.0, 2.0, 1.5],
    ///     [0.0; 3],
    ///     0.8,
    ///     LayerMask::ALL,
    /// );
    ///
    /// // The capsule stands on the floor: half height plus radius above it.
    /// let center = [0.0, 0.9, 0.0];
    /// let capsule = sim
    ///     .add_kinematic(
    ///         &ColliderShape::Capsule { half_height: 0.6, radius: 0.3 },
    ///         center,
    ///         [0.0; 3],
    ///         0.8,
    ///         LayerMask::ALL,
    ///     )
    ///     .expect("room in the pool");
    ///
    /// let shape = Simulation::character_shape(0.6, 0.3);
    /// let moved = sim.move_character(
    ///     &shape,
    ///     &CharacterMoveInput {
    ///         center,
    ///         desired: [0.0, -0.01, 2.0],
    ///         dt: 1.0 / 60.0,
    ///         exclude: capsule,
    ///         mask: LayerMask::ALL,
    ///     },
    /// );
    ///
    /// // Two units of walk, and the wall stops it a radius short of its face.
    /// assert!(
    ///     (moved.translation[2] - 0.7).abs() < 0.01,
    ///     "walked {}",
    ///     moved.translation[2]
    /// );
    /// assert!(moved.grounded, "the floor is still underfoot");
    /// ```
    pub fn move_character(
        &self,
        shape: &CharacterCapsule,
        input: &CharacterMoveInput,
    ) -> CharacterMove {
        character::resolve(self.scene(), &self.character, shape, input)
    }

    /// Remove a body, along with every joint it was in. Returns whether the
    /// handle named a live one.
    ///
    /// Purging the joints is part of the removal rather than something a
    /// caller does afterwards: a joint naming a slot whose body has gone would
    /// constrain whatever occupied that slot next.
    pub fn remove_body(&mut self, handle: BodyHandle) -> bool {
        let slot = handle.index();
        if self.bodies.remove(pool_handle(handle)).is_none() {
            return false;
        }
        self.broadphase.remove(slot);
        // Whatever this body was touching or holding has to be re-examined
        // without it, which has to happen before the joints are dropped.
        self.wake_neighbours(slot);
        self.joints.remove_incident(slot);
        true
    }

    #[cfg(test)]
    /// A body's world-space position and Euler-degree rotation.
    pub(crate) fn body_pose(&self, handle: BodyHandle) -> Option<([f32; 3], [f32; 3])> {
        let body = self.bodies.get(pool_handle(handle))?;
        Some((body.position.to_array(), body.orientation.to_euler_deg()))
    }

    /// A body's world-space position and `[x, y, z, w]` rotation quaternion.
    pub fn body_pose_quat(&self, handle: BodyHandle) -> Option<([f32; 3], [f32; 4])> {
        let body = self.bodies.get(pool_handle(handle))?;
        Some((body.position.to_array(), body.orientation.to_xyzw()))
    }

    #[cfg(test)]
    /// A body's linear velocity in world units per second.
    pub(crate) fn linear_velocity(&self, handle: BodyHandle) -> Option<[f32; 3]> {
        Some(
            self.bodies
                .get(pool_handle(handle))?
                .linear_velocity
                .to_array(),
        )
    }

    #[cfg(test)]
    /// A body's angular velocity in radians per second.
    pub(crate) fn angular_velocity(&self, handle: BodyHandle) -> Option<[f32; 3]> {
        Some(
            self.bodies
                .get(pool_handle(handle))?
                .angular_velocity
                .to_array(),
        )
    }

    /// A body's mass in kilograms. Immovable bodies report `0`.
    pub fn mass(&self, handle: BodyHandle) -> Option<f32> {
        Some(self.bodies.get(pool_handle(handle))?.mass)
    }

    #[cfg(test)]
    /// Whether a settled body has stopped being simulated.
    pub(crate) fn is_sleeping(&self, handle: BodyHandle) -> Option<bool> {
        Some(self.bodies.get(pool_handle(handle))?.sleeping)
    }

    #[cfg(test)]
    /// Set a body's linear velocity, waking it.
    pub(crate) fn set_linear_velocity(&mut self, handle: BodyHandle, velocity: [f32; 3]) {
        if let Some(body) = self.bodies.get_mut(pool_handle(handle)) {
            body.linear_velocity = Vec3::from_array(velocity);
            body.wake();
        }
    }

    #[cfg(test)]
    /// Set a body's angular velocity in radians per second, waking it.
    pub(crate) fn set_angular_velocity(&mut self, handle: BodyHandle, velocity: [f32; 3]) {
        if let Some(body) = self.bodies.get_mut(pool_handle(handle)) {
            body.angular_velocity = Vec3::from_array(velocity);
            body.wake();
        }
    }

    #[cfg(test)]
    /// Apply an impulse through a body's centre of mass, waking it.
    pub(crate) fn apply_impulse(&mut self, handle: BodyHandle, impulse: [f32; 3]) {
        if let Some(body) = self.bodies.get_mut(pool_handle(handle)) {
            body.linear_velocity += Vec3::from_array(impulse) * body.inv_mass;
            body.wake();
        }
    }

    #[cfg(test)]
    /// Kinetic plus gravitational potential energy over every dynamic body,
    /// with potential measured from `y = 0`.
    ///
    /// A settled world's total must not climb: a solver that injects energy
    /// says so here before it says so as a stack that will not stand.
    pub(crate) fn total_energy(&self) -> f32 {
        let mut total = 0.0;
        for (_, body) in self.bodies.iter() {
            if !body.is_dynamic() {
                continue;
            }
            let momentum = Mat3::diagonal_conjugated(body.orientation, body.inertia_local)
                .mul_vec3(body.angular_velocity);
            total += 0.5 * body.mass * body.linear_velocity.length_squared()
                + 0.5 * body.angular_velocity.dot(momentum)
                + body.mass * self.config.gravity * body.gravity_scale * body.position.y;
        }
        total
    }

    /// Advance the simulation by `dt` seconds on the calling thread.
    pub fn step(&mut self, dt: f32) {
        self.step_with(dt, &crate::physics::Inline);
    }

    /// Advance the simulation by `dt` seconds, offering the step's independent
    /// work to `fanout`.
    ///
    /// A step splits the same way whatever it is handed, so a world stepped
    /// across a thread pool and the same world stepped on one thread land in
    /// exactly the same place. Nothing is reserved for a fan-out that
    /// [`Simulation::reserve_workers`] was not told about, so a wider one is
    /// used only as far as the reservation goes.
    ///
    /// # Examples
    ///
    /// ```
    /// use concinnity_core::physics::{ColliderShape, DynamicParams, Inline, LayerMask, Simulation};
    ///
    /// let mut sim = Simulation::with_capacity(1);
    /// let ball = sim
    ///     .add_dynamic(
    ///         &ColliderShape::Ball { radius: 0.5 },
    ///         [0.0, 10.0, 0.0],
    ///         [0.0; 3],
    ///         DynamicParams {
    ///             mass: 1.0,
    ///             friction: 0.4,
    ///             restitution: 0.2,
    ///             gravity_scale: 1.0,
    ///             linear_damping: 0.0,
    ///         },
    ///         LayerMask::ALL,
    ///     )
    ///     .expect("room for one body");
    /// sim.step_with(1.0 / 60.0, &Inline);
    /// assert!(sim.body_pose_quat(ball).expect("a live body").0[1] < 10.0, "it fell");
    /// ```
    pub fn step_with(&mut self, dt: f32, fanout: &impl Fanout) {
        if !dt.is_finite() || dt <= 0.0 {
            return;
        }
        let asked = fanout.workers().max(1);
        if asked > self.workers {
            self.worker_overflows = self.worker_overflows.saturating_add(1);
        }
        let workers = asked.min(self.workers);
        self.drive_kinematics(dt);
        let awake = self.refresh_bounds();
        // Reaching a fan-out's workers costs the same whatever is handed to
        // them, so a step with little to do is worth more on the thread it is
        // already on.
        if workers > 1 && self.step_cost(awake) >= MIN_FANOUT_COST {
            fanout.scope(|| self.advance(dt, fanout, workers));
        } else {
            self.advance(dt, &crate::physics::Inline, 1);
        }
    }

    /// Roughly what the step ahead will cost, from what the world was holding
    /// last step.
    ///
    /// Only a moving body's contacts are work: a settled world keeps a full
    /// pair list and solves none of it, so the pairs are counted against what
    /// is still awake rather than taken at face value.
    fn step_cost(&self, awake: usize) -> usize {
        if awake == 0 {
            return 0;
        }
        let contacts = self.broadphase.pair_count().min(awake * 4);
        let joints = self.joints.len().min(awake * 2);
        awake + contacts * CONTACT_COST + joints * JOINT_COST
    }

    /// Everything a step does once the bounds are current and the workers, if
    /// any, have been gathered.
    fn advance(&mut self, dt: f32, fanout: &impl Fanout, workers: usize) {
        let Simulation {
            config,
            bodies,
            broadphase,
            contacts,
            fields,
            narrow,
            joints,
            islands,
            solver,
            sensors,
            impacts,
            ccd,
            ..
        } = self;
        let sweeping = ccd::enabled(config);

        let pairs = broadphase.sweep(fanout, workers);
        sensors.resolve(bodies, pairs.sensors);
        let (current, previous) = contacts.begin();
        narrow.build(
            narrow::Work {
                bodies,
                fields,
                pairs: pairs.contacts,
                previous,
                out: current,
                margin: config.speculative_margin,
            },
            fanout,
            workers,
        );
        carry_impulses(previous, current);
        wake_driven_contacts(bodies, current);

        solver.begin();
        gather(bodies, solver, current, joints.as_slice());
        solver.run(
            solver::Work {
                manifolds: current,
                joints: joints.as_mut_slice(),
                islands,
                config,
                dt,
            },
            fanout,
            workers,
        );
        // The solver is asked what it delivered, so a pair whose manifold was
        // carried forward untouched is not read as a fresh collision.
        impacts.collect(bodies, current, solver.loads(), dt);
        ccd.begin();
        for (handle, body) in bodies.iter_mut() {
            if !body.is_simulated() {
                continue;
            }
            let slot = handle.index() as u32;
            let solved = solver.body(slot);
            let began_at = body.position;
            body.linear_velocity = solved.linear_velocity;
            body.angular_velocity = solved.angular_velocity;
            body.position = solved.position;
            body.orientation = solved.rotation;
            // A position-driven body lands exactly where it was sent, not
            // wherever the substeps' arithmetic left it.
            if let Some(target) = body.kinematic_target.take() {
                body.position = target;
            }
            if sweeping {
                ccd.observe(slot, body, began_at, config.ccd_motion_ratio);
            }
        }

        // After the write-back, so a mover is swept along the path the step
        // actually took it on, and before sleep, so what it ran into is awake
        // when the islands are decided.
        if sweeping {
            let scene = Scene {
                bodies,
                broadphase,
                fields,
            };
            ccd.resolve(scene, config, dt);
            ccd.report_crossings(bodies, sensors);
            ccd.apply(bodies);
        }

        if !solver.is_idle() {
            update_sleep(config, bodies, islands, current, joints.as_slice(), dt);
        }
    }

    /// Change a body's kind and put the broad phase and its neighbours back
    /// in step with the change.
    fn reclassify(&mut self, handle: BodyHandle, change: impl FnOnce(&mut Body) -> bool) -> bool {
        let Some(body) = self.bodies.get_mut(pool_handle(handle)) else {
            return false;
        };
        if !change(body) {
            return true;
        }
        // Whether contact moves this body has changed, so the sweep's pair
        // filter and whatever was leaning on it both have to hear about it.
        let proxy = proxy_for(body);
        let slot = handle.index();
        self.broadphase.set_proxy(slot, proxy);
        self.wake_neighbours(slot);
        true
    }

    /// Give every driven body the velocity that carries it to its target over
    /// this step, so the solver sees the motion as motion.
    fn drive_kinematics(&mut self, dt: f32) {
        for (_, body) in self.bodies.iter_mut() {
            if body.is_kinematic() {
                body.drive_to_target(dt);
            }
        }
    }

    fn add(&mut self, mut body: Body) -> Option<BodyHandle> {
        body.refresh_bounds(self.config.bounds_margin);
        let proxy = proxy_for(&body);
        let handle = self.bodies.insert(body)?;
        let slot = handle.index() as u32;
        self.broadphase.insert(slot);
        self.broadphase.set_proxy(slot, proxy);
        // A body arriving inside a settled stack has to be able to disturb it.
        self.wake_neighbours(slot);
        Some(body_handle(handle))
    }

    /// Wake whatever the given slot was in contact with or jointed to, so a
    /// change at one body reaches the island it belonged to.
    fn wake_neighbours(&mut self, slot: u32) {
        let Simulation {
            bodies,
            contacts,
            joints,
            ..
        } = self;
        let mut wake = |other: u32| {
            if let Some(body) = bodies.get_at_mut(other as usize) {
                body.wake();
            }
        };
        for manifold in contacts.manifolds_mut() {
            let other = if manifold.a == slot {
                manifold.b
            } else if manifold.b == slot {
                manifold.a
            } else {
                continue;
            };
            wake(other);
        }
        for joint in joints.as_slice() {
            if let Some(other) = joint.other(slot) {
                wake(other);
            }
        }
    }

    /// Re-fatten the bounds of the bodies that moved, and tell the broad phase
    /// about the ones whose bounds actually changed.
    fn refresh_bounds(&mut self) -> usize {
        let margin = self.config.bounds_margin;
        let Simulation {
            bodies, broadphase, ..
        } = self;
        let mut awake = 0;
        for (handle, body) in bodies.iter_mut() {
            if !body.is_simulated() {
                continue;
            }
            awake += 1;
            if body.refresh_bounds(margin) {
                broadphase.set_proxy(handle.index() as u32, proxy_for(body));
            }
        }
        awake
    }
}

/// Hand the solver the bodies this step can reach: the ones it moves, and the
/// immovable ones a contact leans against. Everything else keeps whatever
/// state it had, because nothing will read it, which is what makes a settled
/// world cost close to nothing.
fn gather(bodies: &Pool<Body>, solver: &mut Solver, manifolds: &[Manifold], joints: &[Joint]) {
    for (handle, body) in bodies.iter() {
        if body.is_simulated() {
            solver.set_body(handle.index() as u32, SolverBody::from_body(body));
        }
    }
    for manifold in manifolds {
        gather_partner(bodies, solver, manifold.a, manifold.b);
    }
    for joint in joints {
        gather_partner(bodies, solver, joint.a, joint.b);
    }
}

/// Take the immovable half of a constraint, so the moving half has something
/// to lean on.
fn gather_partner(bodies: &Pool<Body>, solver: &mut Solver, a: u32, b: u32) {
    let simulated = |slot: u32| {
        bodies
            .get_at(slot as usize)
            .is_some_and(|body| body.is_simulated())
    };
    let (moves_a, moves_b) = (simulated(a), simulated(b));
    if moves_a == moves_b {
        // Both moving: already taken. Neither moving: the constraint is
        // skipped, so neither is needed.
        return;
    }
    let resting = if moves_a { b } else { a };
    if let Some(body) = bodies.get_at(resting as usize) {
        solver.set_body(resting, SolverBody::from_body(body));
    }
}

fn proxy_for(body: &Body) -> Proxy {
    let role = if body.is_sensor() {
        Role::Sensor
    } else if body.responds_to_contact() {
        Role::Dynamic
    } else if body.is_kinematic() {
        Role::Driven
    } else {
        Role::Static
    };
    Proxy {
        bounds: body.bounds,
        mask: body.mask,
        role,
    }
}

fn pool_handle(handle: BodyHandle) -> PoolHandle {
    PoolHandle::from_parts(handle.index(), handle.generation())
}

/// The body a handle still names, or `None` once it has been removed. What a
/// caller holding a handle from an earlier step asks.
pub(super) fn body_at(bodies: &Pool<Body>, handle: BodyHandle) -> Option<&Body> {
    bodies.get(pool_handle(handle))
}

fn body_handle(handle: PoolHandle) -> BodyHandle {
    BodyHandle::from_parts(handle.index() as u32, handle.generation())
}

/// The handle naming whatever occupies a slot, for a caller that walked the
/// broad phase and holds a slot rather than a handle.
pub(super) fn handle_at(bodies: &Pool<Body>, slot: u32) -> Option<BodyHandle> {
    bodies.handle_at(slot as usize).map(body_handle)
}

/// Wake whatever a driven body is about to move into, so a platform can
/// disturb a stack that has settled on it.
///
/// Without this a sleeping body would be gathered as immovable and the
/// platform would slide straight through it.
fn wake_driven_contacts(bodies: &mut Pool<Body>, manifolds: &[Manifold]) {
    for manifold in manifolds {
        for (slot, other) in [(manifold.a, manifold.b), (manifold.b, manifold.a)] {
            let driving = bodies.get_at(slot as usize).is_some_and(|body| {
                body.kinematic_target
                    .is_some_and(|target| target != body.position)
            });
            if driving && let Some(body) = bodies.get_at_mut(other as usize) {
                body.wake();
            }
        }
    }
}

/// Decide which islands have settled, and stop simulating the ones that have.
fn update_sleep(
    config: &SimConfig,
    bodies: &mut Pool<Body>,
    islands: &mut Islands,
    manifolds: &[Manifold],
    joints: &[Joint],
    dt: f32,
) {
    for (_, body) in bodies.iter_mut() {
        if !body.is_dynamic() {
            continue;
        }
        if !config.allow_sleep {
            body.wake();
            continue;
        }
        if body.sleeping {
            continue;
        }
        if body.is_still(config.sleep_linear_velocity, config.sleep_angular_velocity) {
            body.sleep_timer += dt;
        } else {
            body.sleep_timer = 0.0;
        }
    }
    if !config.allow_sleep {
        return;
    }

    islands.clear();
    let movable = |slot: u32| {
        bodies
            .get_at(slot as usize)
            .is_some_and(|body| body.is_dynamic())
    };
    for manifold in manifolds {
        if movable(manifold.a) && movable(manifold.b) {
            islands.union(manifold.a, manifold.b);
        }
    }
    // Two bodies a joint holds settle together or not at all, exactly as two
    // bodies leaning on each other do.
    for joint in joints {
        if movable(joint.a) && movable(joint.b) {
            islands.union(joint.a, joint.b);
        }
    }
    for (handle, body) in bodies.iter() {
        if body.is_dynamic() {
            islands.mark(
                handle.index() as u32,
                body.sleep_timer >= config.time_to_sleep,
            );
        }
    }
    // A motor with somewhere to go is still doing work however still the
    // bodies look, so its island stays awake.
    for joint in joints {
        if !joint.frame.is_driven() {
            continue;
        }
        for slot in [joint.a, joint.b] {
            if movable(slot) {
                islands.mark(slot, false);
            }
        }
    }
    for (handle, body) in bodies.iter_mut() {
        if !body.is_dynamic() {
            continue;
        }
        if islands.island_is_still(handle.index() as u32) {
            body.sleep();
        } else {
            body.sleeping = false;
        }
    }
}

#[cfg(test)]
mod tests {

    // A capsule swept at a floor stops where its lower cap meets it, and the
    // hit reports the surface it landed on.
    #[test]
    fn a_shape_cast_stops_at_the_first_body_in_its_path() {
        let mut sim = Simulation::with_capacity(1);
        sim.add_fixed(
            &ColliderShape::Cuboid {
                half_extents: [10.0, 0.5, 10.0],
            },
            [0.0, -0.5, 0.0],
            [0.0; 3],
            0.8,
            LayerMask::ALL,
        );

        let capsule = ColliderShape::Capsule {
            half_height: 0.6,
            radius: 0.3,
        };
        let hit = sim
            .shape_cast(&ShapeCast::new(capsule, [0.0, 4.0, 0.0], [0.0, -8.0, 0.0]))
            .expect("the floor is down there");

        // The capsule reaches 0.9 below its centre, so it stops with its
        // centre 0.9 above the floor.
        let landed = 4.0 - hit.toi * 8.0;
        assert!((landed - 0.9).abs() < 0.01, "landed at {landed}");
        assert!(hit.normal[1] > 0.99, "standing on it: {:?}", hit.normal);
    }
    use super::*;

    const TICK: f32 = 1.0 / 60.0;

    fn params(restitution: f32, damping: f32) -> DynamicParams {
        DynamicParams {
            mass: 1.0,
            friction: 0.5,
            restitution,
            gravity_scale: 1.0,
            linear_damping: damping,
        }
    }

    fn floor(sim: &mut Simulation) -> BodyHandle {
        sim.add_fixed(
            &ColliderShape::Cuboid {
                half_extents: [50.0, 1.0, 50.0],
            },
            [0.0, -1.0, 0.0],
            [0.0; 3],
            0.8,
            LayerMask::ALL,
        )
        .expect("room")
    }

    #[test]
    fn a_body_falls_under_gravity() {
        let mut sim = Simulation::with_capacity(1);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 10.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        for _ in 0..60 {
            sim.step(TICK);
        }
        let (pos, _) = sim.body_pose(ball).expect("live");
        // One second of free fall at g = 20 covers about ten units.
        assert!((pos[1] - (10.0 - 10.0)).abs() < 0.4, "y = {}", pos[1]);
        assert!(sim.linear_velocity(ball).expect("live")[1] < -19.0);
    }

    #[test]
    fn a_zero_or_negative_step_changes_nothing() {
        let mut sim = Simulation::with_capacity(1);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 10.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        sim.step(0.0);
        sim.step(-1.0);
        assert_eq!(sim.body_pose(ball).expect("live").0, [0.0, 10.0, 0.0]);
    }

    #[test]
    fn a_full_pool_declines_rather_than_growing() {
        let mut sim = Simulation::with_capacity(1);
        assert!(
            sim.add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 1.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL
            )
            .is_some()
        );
        assert!(
            sim.add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 3.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL
            )
            .is_none()
        );
        assert_eq!(sim.body_count(), 1);
        assert_eq!(sim.capacity(), 1);
        assert!(sim.reserved_bytes() > 0);
    }

    #[test]
    fn a_removed_bodys_handle_stops_naming_anything() {
        let mut sim = Simulation::with_capacity(2);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 1.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        assert!(sim.remove_body(ball));
        assert!(!sim.remove_body(ball));
        assert!(sim.body_pose(ball).is_none());
        assert_eq!(sim.body_count(), 0);
    }

    #[test]
    fn a_body_lands_on_the_floor_and_stays_on_it() {
        let mut sim = Simulation::with_capacity(2);
        floor(&mut sim);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 6.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        for _ in 0..240 {
            sim.step(TICK);
        }
        let (pos, _) = sim.body_pose(ball).expect("live");
        assert!((pos[1] - 0.5).abs() < 0.02, "y = {}", pos[1]);
        assert!(sim.contact_count() > 0);
    }

    #[test]
    fn layers_that_do_not_interact_pass_through_each_other() {
        let mut sim = Simulation::with_capacity(2);
        sim.add_fixed(
            &ColliderShape::Cuboid {
                half_extents: [50.0, 1.0, 50.0],
            },
            [0.0, -1.0, 0.0],
            [0.0; 3],
            0.8,
            LayerMask {
                memberships: 0b01,
                filter: 0b01,
            },
        );
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 4.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask {
                    memberships: 0b10,
                    filter: 0b10,
                },
            )
            .expect("room");
        for _ in 0..120 {
            sim.step(TICK);
        }
        assert!(sim.body_pose(ball).expect("live").0[1] < -2.0);
    }

    #[test]
    fn an_impulse_moves_a_body_and_wakes_it() {
        let mut sim = Simulation::with_capacity(2);
        floor(&mut sim);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 0.5, 0.0],
                [0.0; 3],
                params(0.0, 0.5),
                LayerMask::ALL,
            )
            .expect("room");
        for _ in 0..120 {
            sim.step(TICK);
        }
        assert_eq!(sim.is_sleeping(ball), Some(true));
        sim.apply_impulse(ball, [0.0, 8.0, 0.0]);
        assert_eq!(sim.is_sleeping(ball), Some(false));
        sim.step(TICK);
        assert!(sim.body_pose(ball).expect("live").0[1] > 0.55);
    }

    #[test]
    fn velocity_can_be_set_and_read_back() {
        let mut sim = Simulation::with_capacity(1);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 5.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        sim.set_linear_velocity(ball, [1.0, 0.0, 0.0]);
        sim.set_angular_velocity(ball, [0.0, 2.0, 0.0]);
        assert_eq!(sim.linear_velocity(ball), Some([1.0, 0.0, 0.0]));
        assert_eq!(sim.angular_velocity(ball), Some([0.0, 2.0, 0.0]));
        assert!(sim.mass(ball).expect("live") > 0.0);
    }

    // The same world stepped twice must land on the same bits, or nothing
    // downstream can be reproduced.
    #[test]
    fn two_identical_runs_agree_bit_for_bit() {
        let run = || {
            let mut sim = Simulation::with_capacity(16);
            floor(&mut sim);
            let mut handles = Vec::new();
            for i in 0..12 {
                handles.push(
                    sim.add_dynamic(
                        &ColliderShape::Cuboid {
                            half_extents: [0.4, 0.4, 0.4],
                        },
                        [(i % 3) as f32 * 0.9, 1.0 + (i / 3) as f32 * 0.9, 0.0],
                        [0.0, i as f32 * 7.0, 0.0],
                        params(0.3, 0.0),
                        LayerMask::ALL,
                    )
                    .expect("room"),
                );
            }
            for _ in 0..90 {
                sim.step(TICK);
            }
            handles
                .iter()
                .map(|&h| {
                    let (p, r) = sim.body_pose(h).expect("live");
                    (
                        [p[0].to_bits(), p[1].to_bits(), p[2].to_bits()],
                        [r[0].to_bits(), r[1].to_bits(), r[2].to_bits()],
                    )
                })
                .collect::<Vec<_>>()
        };
        assert_eq!(run(), run());
    }

    #[test]
    fn a_ray_finds_the_nearest_body_along_it() {
        let mut sim = Simulation::with_capacity(4);
        for (index, z) in [2.0f32, 5.0, 9.0].into_iter().enumerate() {
            sim.add_fixed(
                &[
                    ColliderShape::Ball { radius: 0.5 },
                    ColliderShape::Cuboid {
                        half_extents: [0.5, 0.5, 0.5],
                    },
                    ColliderShape::Capsule {
                        half_height: 0.5,
                        radius: 0.25,
                    },
                ][index],
                [0.0, 0.0, z],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        }
        let hit = sim
            .raycast(
                [0.0, 0.0, -5.0],
                [0.0, 0.0, 1.0],
                100.0,
                None,
                LayerMask::ALL,
            )
            .expect("a hit");
        assert!((hit.distance - 6.5).abs() < 1.0e-4, "{hit:?}");
        assert!((hit.normal[2] + 1.0).abs() < 1.0e-4, "{hit:?}");
        assert!((hit.point[2] - 1.5).abs() < 1.0e-4, "{hit:?}");
    }

    #[test]
    fn a_ray_answers_the_same_way_from_either_end_of_the_scene() {
        let mut sim = Simulation::with_capacity(4);
        for z in [2.0f32, 5.0, 9.0] {
            sim.add_fixed(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 0.0, z],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        }
        sim.step(TICK);
        let forward = sim
            .raycast(
                [0.0, 0.0, -5.0],
                [0.0, 0.0, 1.0],
                100.0,
                None,
                LayerMask::ALL,
            )
            .expect("a hit");
        let backward = sim
            .raycast(
                [0.0, 0.0, 20.0],
                [0.0, 0.0, -1.0],
                100.0,
                None,
                LayerMask::ALL,
            )
            .expect("a hit");
        assert!((forward.distance - 6.5).abs() < 1.0e-4, "{forward:?}");
        assert!((backward.distance - 10.5).abs() < 1.0e-4, "{backward:?}");
    }

    #[test]
    fn a_ray_skips_layers_it_does_not_interact_with() {
        let mut sim = Simulation::with_capacity(2);
        let near = LayerMask {
            memberships: 0b01,
            filter: 0b11,
        };
        let far = LayerMask {
            memberships: 0b10,
            filter: 0b11,
        };
        sim.add_fixed(
            &ColliderShape::Ball { radius: 0.5 },
            [0.0, 0.0, 0.0],
            [0.0; 3],
            0.5,
            near,
        )
        .expect("room");
        sim.add_fixed(
            &ColliderShape::Ball { radius: 0.5 },
            [0.0, 0.0, 5.0],
            [0.0; 3],
            0.5,
            far,
        )
        .expect("room");

        let only_far = LayerMask {
            memberships: 0b11,
            filter: 0b10,
        };
        let hit = sim
            .raycast([0.0, 0.0, -5.0], [0.0, 0.0, 1.0], 100.0, None, only_far)
            .expect("a hit");
        assert!(
            (hit.distance - 9.5).abs() < 1.0e-4,
            "the near one is hidden"
        );
        // With no layer in common there is nothing to hit at all.
        assert!(
            sim.raycast(
                [0.0, 0.0, -5.0],
                [0.0, 0.0, 1.0],
                100.0,
                None,
                LayerMask {
                    memberships: 0b100,
                    filter: 0b100,
                },
            )
            .is_none()
        );
    }

    #[test]
    fn a_ray_can_be_told_to_leave_one_body_out() {
        let mut sim = Simulation::with_capacity(2);
        let near = sim
            .add_fixed(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 0.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        sim.add_fixed(
            &ColliderShape::Ball { radius: 0.5 },
            [0.0, 0.0, 5.0],
            [0.0; 3],
            0.5,
            LayerMask::ALL,
        )
        .expect("room");

        let cast = |exclude| {
            sim.raycast(
                [0.0, 0.0, -5.0],
                [0.0, 0.0, 1.0],
                100.0,
                exclude,
                LayerMask::ALL,
            )
        };
        assert!((cast(None).expect("a hit").distance - 4.5).abs() < 1.0e-4);
        assert!((cast(Some(near)).expect("a hit").distance - 9.5).abs() < 1.0e-4);
    }

    // A handle to a removed body must not exclude whatever took its slot.
    #[test]
    fn a_stale_exclusion_does_not_hide_the_slots_new_occupant() {
        let mut sim = Simulation::with_capacity(1);
        let first = sim
            .add_fixed(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 0.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        assert!(sim.remove_body(first));
        sim.add_fixed(
            &ColliderShape::Ball { radius: 0.5 },
            [0.0, 0.0, 0.0],
            [0.0; 3],
            0.5,
            LayerMask::ALL,
        )
        .expect("the freed slot");
        assert!(
            sim.raycast(
                [0.0, 0.0, -5.0],
                [0.0, 0.0, 1.0],
                100.0,
                Some(first),
                LayerMask::ALL,
            )
            .is_some(),
            "the stale handle names nobody"
        );
    }

    #[test]
    fn a_removed_body_stops_being_hit() {
        let mut sim = Simulation::with_capacity(1);
        let ball = sim
            .add_fixed(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 0.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        let cast = |sim: &Simulation| {
            sim.raycast(
                [0.0, 0.0, -5.0],
                [0.0, 0.0, 1.0],
                100.0,
                None,
                LayerMask::ALL,
            )
        };
        assert!(cast(&sim).is_some());
        sim.remove_body(ball);
        assert!(cast(&sim).is_none());
    }

    #[test]
    fn a_ray_respects_its_distance_limit_and_needs_a_direction() {
        let mut sim = Simulation::with_capacity(1);
        sim.add_fixed(
            &ColliderShape::Ball { radius: 0.5 },
            [0.0, 0.0, 0.0],
            [0.0; 3],
            0.5,
            LayerMask::ALL,
        )
        .expect("room");
        let cast =
            |dir: [f32; 3], max| sim.raycast([0.0, 0.0, -5.0], dir, max, None, LayerMask::ALL);
        // The surface is exactly 4.5 away.
        assert!(cast([0.0, 0.0, 1.0], 4.5).is_some());
        assert!(cast([0.0, 0.0, 1.0], 4.4).is_none());
        assert!(cast([0.0, 0.0, 0.0], 100.0).is_none(), "no direction");
        assert!(cast([0.0, 0.0, 1.0], 0.0).is_none(), "no reach");
        assert!(cast([0.0, 0.0, 1.0], -1.0).is_none());
        assert!(cast([f32::NAN, 0.0, 0.0], 100.0).is_none());
        // An unnormalised direction is the same ray.
        assert!((cast([0.0, 0.0, 7.0], 100.0).expect("a hit").distance - 4.5).abs() < 1.0e-4);
    }

    #[test]
    fn a_ray_finds_a_body_added_since_the_last_step() {
        let mut sim = Simulation::with_capacity(2);
        floor(&mut sim);
        sim.step(TICK);
        sim.add_fixed(
            &ColliderShape::Ball { radius: 0.5 },
            [0.0, 5.0, 0.0],
            [0.0; 3],
            0.5,
            LayerMask::ALL,
        )
        .expect("room");
        let hit = sim
            .raycast(
                [0.0, 9.0, 0.0],
                [0.0, -1.0, 0.0],
                100.0,
                None,
                LayerMask::ALL,
            )
            .expect("a hit");
        assert!((hit.distance - 3.5).abs() < 1.0e-4, "{hit:?}");
    }

    #[test]
    fn a_ray_hits_a_position_driven_body() {
        let mut sim = Simulation::with_capacity(1);
        sim.add_kinematic(
            &ColliderShape::Cuboid {
                half_extents: [1.0, 0.25, 1.0],
            },
            [0.0, 0.0, 0.0],
            [0.0; 3],
            0.5,
            LayerMask::ALL,
        )
        .expect("room");
        let hit = sim
            .raycast(
                [0.0, 5.0, 0.0],
                [0.0, -1.0, 0.0],
                100.0,
                None,
                LayerMask::ALL,
            )
            .expect("a hit");
        assert!((hit.distance - 4.75).abs() < 1.0e-4, "{hit:?}");
    }

    #[test]
    fn a_shape_cast_stops_at_the_nearest_body_and_names_it() {
        let mut sim = Simulation::with_capacity(3);
        let ground = floor(&mut sim);
        let ledge = sim
            .add_fixed(
                &ColliderShape::Cuboid {
                    half_extents: [2.0, 0.5, 2.0],
                },
                [0.0, 3.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        let capsule = ColliderShape::Capsule {
            half_height: 0.5,
            radius: 0.25,
        };
        let hit = sim
            .shape_cast(&ShapeCast::new(capsule, [0.0, 9.0, 0.0], [0.0, -12.0, 0.0]))
            .expect("a hit");
        assert_eq!(hit.body, ledge, "the ledge, not the ground under it");
        let landed = 9.0 - hit.toi * 12.0;
        assert!((landed - 4.25).abs() < 1.0e-2, "landed at {landed}");
        assert!(!hit.started_touching);
        assert_ne!(hit.body, ground);
    }

    #[test]
    fn a_shape_cast_that_reaches_nothing_reports_nothing() {
        let mut sim = Simulation::with_capacity(2);
        floor(&mut sim);
        let ball = ColliderShape::Ball { radius: 0.5 };
        assert!(
            sim.shape_cast(&ShapeCast::new(ball, [0.0, 9.0, 0.0], [0.0, -1.0, 0.0]))
                .is_none()
        );
        assert!(
            sim.shape_cast(&ShapeCast::new(ball, [0.0, 9.0, 0.0], [0.0, 5.0, 0.0]))
                .is_none(),
            "away from everything"
        );
    }

    #[test]
    fn a_shape_cast_says_when_it_began_in_contact() {
        let mut sim = Simulation::with_capacity(2);
        let ground = floor(&mut sim);
        let ball = ColliderShape::Ball { radius: 0.5 };
        let hit = sim
            .shape_cast(&ShapeCast::new(ball, [0.0, 0.4, 0.0], [3.0, 0.0, 0.0]))
            .expect("a hit");
        assert_eq!(hit.body, ground);
        assert_eq!(hit.toi, 0.0);
        assert!(hit.started_touching);
        assert!(hit.normal[1] > 0.9, "{hit:?}");
    }

    #[test]
    fn a_shape_cast_honours_its_layer_filter_and_its_exclusion() {
        let mut sim = Simulation::with_capacity(2);
        let near = sim
            .add_fixed(
                &ColliderShape::Cuboid {
                    half_extents: [2.0, 0.5, 2.0],
                },
                [0.0, 2.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask {
                    memberships: 0b01,
                    filter: 0b11,
                },
            )
            .expect("room");
        let far = sim
            .add_fixed(
                &ColliderShape::Cuboid {
                    half_extents: [2.0, 0.5, 2.0],
                },
                [0.0, 0.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask {
                    memberships: 0b10,
                    filter: 0b11,
                },
            )
            .expect("room");
        let ball = ColliderShape::Ball { radius: 0.5 };
        let straight = ShapeCast::new(ball, [0.0, 6.0, 0.0], [0.0, -8.0, 0.0]);
        assert_eq!(sim.shape_cast(&straight).expect("a hit").body, near);
        assert_eq!(
            sim.shape_cast(&ShapeCast {
                exclude: Some(near),
                ..straight
            })
            .expect("a hit")
            .body,
            far
        );
        assert_eq!(
            sim.shape_cast(&ShapeCast {
                mask: LayerMask {
                    memberships: 0b11,
                    filter: 0b10,
                },
                ..straight
            })
            .expect("a hit")
            .body,
            far
        );
    }

    #[test]
    fn a_driven_body_arrives_exactly_where_it_was_sent() {
        let mut sim = Simulation::with_capacity(1);
        let platform = sim
            .add_kinematic(
                &ColliderShape::Cuboid {
                    half_extents: [1.0, 0.25, 1.0],
                },
                [0.0, 0.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        assert!(sim.set_kinematic_translation(platform, [1.5, 2.0, -3.0]));
        sim.step(TICK);
        assert_eq!(sim.body_pose(platform).expect("live").0, [1.5, 2.0, -3.0]);
        // The target is spent, so a body left alone stops where it arrived.
        sim.step(TICK);
        assert_eq!(sim.body_pose(platform).expect("live").0, [1.5, 2.0, -3.0]);
        assert_eq!(sim.linear_velocity(platform), Some([0.0; 3]));
    }

    #[test]
    fn a_driven_body_ignores_gravity_and_impulses() {
        let mut sim = Simulation::with_capacity(1);
        let platform = sim
            .add_kinematic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 5.0, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");
        sim.apply_impulse(platform, [0.0, 100.0, 0.0]);
        for _ in 0..120 {
            sim.step(TICK);
        }
        assert_eq!(sim.body_pose(platform).expect("live").0, [0.0, 5.0, 0.0]);
        assert_eq!(sim.mass(platform), Some(0.0));
        assert_eq!(sim.is_kinematic(platform), Some(true));
    }

    // A character capsule is a position-driven body: it holds its place under
    // gravity and is moved by a target rather than by the solver.
    #[test]
    fn a_character_capsule_is_a_position_driven_body() {
        let mut sim = Simulation::with_capacity(1);
        let handle = sim
            .add_character(0.6, 0.3, [0.0, 4.0, 0.0], LayerMask::ALL)
            .expect("room in the pool");
        assert_eq!(sim.is_kinematic(handle), Some(true));

        for _ in 0..60 {
            sim.step(TICK);
        }
        let (position, _) = sim.body_pose(handle).expect("a live body");
        assert_eq!(position[1], 4.0, "gravity does not move a driven capsule");

        assert!(sim.set_kinematic_translation(handle, [0.0, 3.0, 0.0]));
        sim.step(TICK);
        let (position, _) = sim.body_pose(handle).expect("a live body");
        assert!((position[1] - 3.0).abs() < 1.0e-5, "{position:?}");
    }

    // A body set to a position it already holds must not read as motion, and
    // a body that is not driven by position must refuse the instruction.
    #[test]
    fn only_a_position_driven_body_takes_a_translation_target() {
        let mut sim = Simulation::with_capacity(2);
        let fixed = floor(&mut sim);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 5.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        assert!(!sim.set_kinematic_translation(fixed, [0.0, 9.0, 0.0]));
        assert!(!sim.set_kinematic_translation(ball, [0.0, 9.0, 0.0]));
        sim.step(TICK);
        assert!(sim.body_pose(ball).expect("live").0[1] < 5.0, "still falls");
    }

    #[test]
    fn a_driven_body_pushes_a_dynamic_one_it_is_moved_into() {
        let mut sim = Simulation::with_capacity(3);
        floor(&mut sim);
        let crate_body = sim
            .add_dynamic(
                &ColliderShape::Cuboid {
                    half_extents: [0.5, 0.5, 0.5],
                },
                [0.0, 0.5, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        let blade = sim
            .add_kinematic(
                &ColliderShape::Cuboid {
                    half_extents: [0.5, 0.5, 0.5],
                },
                [-3.0, 0.5, 0.0],
                [0.0; 3],
                0.5,
                LayerMask::ALL,
            )
            .expect("room");

        // Long enough for the crate to settle and doze off before the blade
        // arrives, so this also proves the push wakes it.
        let mut x = -3.0f32;
        for step in 0..180 {
            if step == 60 {
                assert_eq!(sim.is_sleeping(crate_body), Some(true), "settled first");
            }
            if step >= 60 {
                x += 0.03;
                assert!(sim.set_kinematic_translation(blade, [x, 0.5, 0.0]));
            }
            sim.step(TICK);
        }
        assert!((sim.body_pose(blade).expect("live").0[0] - x).abs() < 1.0e-5);
        let pushed = sim.body_pose(crate_body).expect("live").0[0];
        assert!(pushed > 1.5, "the crate was shoved along: {pushed}");
        assert!(
            pushed > x,
            "and it stays ahead of the blade: {pushed} vs {x}"
        );
    }

    #[test]
    fn switching_a_bodys_kind_keeps_its_handle_and_leaves_the_world_standing() {
        let mut sim = Simulation::with_capacity(2);
        floor(&mut sim);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 4.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        for _ in 0..180 {
            sim.step(TICK);
        }
        let resting = sim.body_pose(ball).expect("live").0;
        assert!((resting[1] - 0.5).abs() < 0.02, "{resting:?}");

        // Picked up: held in the air by position alone.
        assert!(sim.make_kinematic(ball));
        assert_eq!(sim.is_kinematic(ball), Some(true));
        assert!(sim.set_kinematic_translation(ball, [0.0, 6.0, 0.0]));
        sim.step(TICK);
        for _ in 0..60 {
            sim.step(TICK);
        }
        assert_eq!(sim.body_pose(ball).expect("live").0, [0.0, 6.0, 0.0]);

        // Thrown: the same handle, back under gravity, and it lands again.
        assert!(sim.make_dynamic(ball, [0.0, 0.0, 2.0]));
        assert_eq!(sim.is_kinematic(ball), Some(false));
        assert!(sim.mass(ball).expect("live") > 0.0);
        for _ in 0..300 {
            sim.step(TICK);
        }
        let landed = sim.body_pose(ball).expect("live").0;
        assert!(
            (landed[1] - 0.5).abs() < 0.02,
            "back on the floor: {landed:?}"
        );
        assert!(landed[2] > 0.5, "and it travelled: {landed:?}");
        assert_eq!(sim.body_count(), 2);
        assert_eq!(sim.collider_count(), sim.body_count());
    }

    // The broad phase filters pairs by whether contact can move either body,
    // so a switch that did not reach it would leave a stack leaning on
    // nothing.
    #[test]
    fn a_stack_stays_up_when_the_body_under_it_is_switched() {
        let mut sim = Simulation::with_capacity(3);
        floor(&mut sim);
        let cube = ColliderShape::Cuboid {
            half_extents: [0.5, 0.5, 0.5],
        };
        let lower = sim
            .add_dynamic(
                &cube,
                [0.0, 0.5, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        let upper = sim
            .add_dynamic(
                &cube,
                [0.0, 1.5, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        for _ in 0..180 {
            sim.step(TICK);
        }
        let held = sim.body_pose(lower).expect("live").0;
        assert!(sim.make_kinematic(lower));
        for _ in 0..180 {
            sim.step(TICK);
        }
        let top = sim.body_pose(upper).expect("live").0;
        assert!(
            (top[1] - 1.5).abs() < 0.05,
            "the top box still rests: {top:?}"
        );
        assert_eq!(
            sim.body_pose(lower).expect("live").0,
            held,
            "and the one below it has not stirred"
        );

        // And a lift carries the box above it up too.
        assert!(sim.set_kinematic_translation(lower, [held[0], 1.5, held[2]]));
        for _ in 0..120 {
            sim.step(TICK);
        }
        let lifted = sim.body_pose(upper).expect("live").0;
        assert!(lifted[1] > 2.0, "carried up: {lifted:?}");
    }

    #[test]
    fn switching_the_kind_of_a_body_that_is_not_there_reports_so() {
        let mut sim = Simulation::with_capacity(1);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 1.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        assert!(sim.remove_body(ball));
        assert!(!sim.make_kinematic(ball));
        assert!(!sim.make_dynamic(ball, [0.0; 3]));
        assert!(!sim.set_kinematic_translation(ball, [0.0; 3]));
        assert_eq!(sim.is_kinematic(ball), None);
    }

    // Two runs of the same query on the same world must agree bit for bit,
    // or nothing built on a query can be reproduced.
    #[test]
    fn queries_answer_the_same_bits_twice_running() {
        let mut sim = Simulation::with_capacity(17);
        floor(&mut sim);
        // Terrain answers along its own faces rather than through the sweep
        // the convex shapes use, so it needs its own place in this check.
        let side = 9usize;
        let mut heights = Vec::with_capacity(side * side);
        for row in 0..side {
            for col in 0..side {
                heights.push((row as f32 * 0.37).sin() * 0.4 + (col as f32 * 0.21).cos() * 0.3);
            }
        }
        sim.add_heightfield(
            side,
            side,
            heights,
            [24.0, 1.0, 24.0],
            [0.0, -3.0, 0.0],
            LayerMask::ALL,
        )
        .expect("room");
        for i in 0..12 {
            sim.add_dynamic(
                &ColliderShape::Cuboid {
                    half_extents: [0.4, 0.4, 0.4],
                },
                [(i % 3) as f32 * 0.9, 1.0 + (i / 3) as f32 * 0.9, 0.0],
                [0.0, i as f32 * 7.0, 0.0],
                params(0.3, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        }
        for _ in 0..90 {
            sim.step(TICK);
        }
        let ray = |sim: &Simulation| {
            sim.raycast(
                [-6.0, 1.3, 0.1],
                [1.0, -0.1, 0.0],
                40.0,
                None,
                LayerMask::ALL,
            )
            .map(|hit| (hit.distance.to_bits(), hit.point, hit.normal))
        };
        let sweep = |sim: &Simulation| {
            sim.shape_cast(&ShapeCast::new(
                ColliderShape::Capsule {
                    half_height: 0.3,
                    radius: 0.2,
                },
                [-6.0, 1.3, 0.1],
                [12.0, 0.0, 0.0],
            ))
            .map(|hit| (hit.toi.to_bits(), hit.point, hit.normal, hit.body))
        };
        let shape = Simulation::character_shape(0.3, 0.2);
        let capsule = sim
            .add_kinematic(
                &ColliderShape::Capsule {
                    half_height: 0.3,
                    radius: 0.2,
                },
                [-6.0, 1.3, 0.1],
                [0.0; 3],
                0.8,
                LayerMask::ALL,
            )
            .expect("room");
        let walk = |sim: &Simulation| {
            let moved = sim.move_character(
                &shape,
                &CharacterMoveInput {
                    center: [-6.0, 1.3, 0.1],
                    desired: [12.0, -0.05, 0.0],
                    dt: TICK,
                    exclude: capsule,
                    mask: LayerMask::ALL,
                },
            );
            (moved.translation.map(f32::to_bits), moved.grounded)
        };
        // Fired into the terrain rather than at the stack, so the two answers
        // below are about the height grid and not about the boxes on it.
        let terrain_ray = |sim: &Simulation| {
            sim.raycast(
                [-1.7, 6.0, 2.3],
                [0.0, -1.0, 0.0],
                40.0,
                None,
                LayerMask::ALL,
            )
            .map(|hit| (hit.distance.to_bits(), hit.point, hit.normal))
        };
        let terrain_sweep = |sim: &Simulation| {
            sim.shape_cast(&ShapeCast::new(
                ColliderShape::Ball { radius: 0.4 },
                [-9.0, -2.2, 2.3],
                [18.0, 0.0, 0.0],
            ))
            .map(|hit| (hit.toi.to_bits(), hit.point, hit.normal, hit.body))
        };
        assert!(
            ray(&sim).is_some() && sweep(&sim).is_some(),
            "the scene is in the way"
        );
        assert!(
            terrain_ray(&sim).is_some() && terrain_sweep(&sim).is_some(),
            "and so is the terrain"
        );
        assert_eq!(ray(&sim), ray(&sim));
        assert_eq!(sweep(&sim), sweep(&sim));
        assert_eq!(walk(&sim), walk(&sim));
        assert_eq!(terrain_ray(&sim), terrain_ray(&sim));
        assert_eq!(terrain_sweep(&sim), terrain_sweep(&sim));
    }

    #[test]
    fn config_round_trips_and_takes_effect() {
        // Sleeping is off for the weightless stretch: a body that settles
        // there would stop being simulated, and the test would be measuring
        // that rather than the gravity change.
        let mut sim = Simulation::new(
            SimConfig {
                gravity: 0.0,
                allow_sleep: false,
                ..SimConfig::default()
            },
            1,
        );
        assert_eq!(sim.config().gravity, 0.0);
        let ball = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 5.0, 0.0],
                [0.0; 3],
                params(0.0, 0.0),
                LayerMask::ALL,
            )
            .expect("room");
        for _ in 0..60 {
            sim.step(TICK);
        }
        assert_eq!(sim.body_pose(ball).expect("live").0[1], 5.0);
        sim.set_config(SimConfig::default());
        assert_eq!(sim.config().gravity, crate::physics::GRAVITY);
        sim.step(TICK);
        assert!(sim.body_pose(ball).expect("live").0[1] < 5.0);
    }

    #[test]
    fn gravity_scale_and_damping_do_what_they_say() {
        let mut sim = Simulation::with_capacity(2);
        let floating = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [0.0, 5.0, 0.0],
                [0.0; 3],
                DynamicParams {
                    gravity_scale: 0.0,
                    ..params(0.0, 0.0)
                },
                LayerMask::ALL,
            )
            .expect("room");
        let damped = sim
            .add_dynamic(
                &ColliderShape::Ball { radius: 0.5 },
                [5.0, 5.0, 0.0],
                [0.0; 3],
                DynamicParams {
                    gravity_scale: 0.0,
                    ..params(0.0, 4.0)
                },
                LayerMask::ALL,
            )
            .expect("room");
        sim.set_linear_velocity(floating, [3.0, 0.0, 0.0]);
        sim.set_linear_velocity(damped, [3.0, 0.0, 0.0]);
        for _ in 0..60 {
            sim.step(TICK);
        }
        assert_eq!(sim.body_pose(floating).expect("live").0[1], 5.0);
        let free = sim.linear_velocity(floating).expect("live")[0];
        let slowed = sim.linear_velocity(damped).expect("live")[0];
        assert!((free - 3.0).abs() < 1.0e-5, "{free}");
        assert!(slowed < 0.5, "damping must bleed the speed off: {slowed}");
    }
}