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
use std::{any::Any, f32::consts::PI, iter::repeat_n, mem};
use arrayvec::ArrayVec;
use fastrand::Rng;
use glam::{Affine3A, EulerRot, Mat3A, Vec3A};
use super::ArenaContactTracker;
use crate::{
ARENA_COLLISION_SHAPES, ArenaConfig,
ArenaEvent::{BallHitWorld, CarPickupBoost},
ArenaMemWeightMode, ArenaState, BallHitWorldEvent, BoostPadConfig, BoostPadGrid, BoostPadState,
Car, CarBodyConfig, CarControls, CarCore, CarInfo, CarPickupBoostEvent, CarState, GameMode,
MutatorConfig, PhysState, RaycastHitInfo, RaycastQuery, Team, TileDamageState, TileStates,
bullet::{
collision::{
broadphase::{CollisionFilterGroups, GridBroadphase},
dispatch::{
collision_dispatcher::CollisionDispatcher, collision_world::CollisionWorld,
quad_ray_callbacks::ClosestQuadRayResultCallback,
},
narrowphase::{
manifold_point::ManifoldPoint, persistent_manifold::ContactAddedCallback,
},
shapes::{
box_shape::BoxShape, collision_shape::CollisionShapes,
compound_shape::CompoundShape, static_plane_shape::StaticPlaneShape,
},
},
dynamics::{
discrete_dynamics_world::DiscreteDynamicsWorld,
rigid_body::{
CollisionFlags, RigidBody, RigidBodyConstructionInfo, RigidBodyUpdateInfo,
},
},
},
consts::{self, BT_TO_UU, TICK_RATE, TICK_TIME, UU_TO_BT},
make_tile_shapes,
shared::{Aabb, quantize},
sim::{
ArenaEvent, Ball, BallState, BoostPad, CarHitBallEvent, CarHitCarEvent, CarHitWorldEvent,
CarLandedEvent, DemoMode, UserInfoType, arena::ArenaEventList,
},
};
// Synchronize in-place edits on both normal return and panic unwinding.
struct StateEditGuard<'a, T, F: FnMut(&mut T)> {
target: &'a mut T,
sync: F,
}
impl<T, F: FnMut(&mut T)> Drop for StateEditGuard<'_, T, F> {
fn drop(&mut self) {
(self.sync)(self.target);
}
}
/// Optional visualization hook, called with a snapshot after each tick.
///
/// Implement this in your own crate (see `rocketsim_vis`) to render or log
/// the game. Register with `arena.vis = Some(Box::new(my_vis))`.
pub trait Vis: Send + Sync + Any {
/// Called after [`Arena::step_tick`] with the fresh state and `dt`
/// ([`crate::consts::TICK_TIME`]).
fn update(&mut self, arena_state: &ArenaState, dt: f32);
}
/// Combine per-world-object contact normal sums into the world-contact normal.
///
/// Each object sum is normalized. The object normals are added. The total is
/// normalized. An object whose sum is near zero is skipped. Returns `None`
/// when no object sum or the total is usable.
fn combine_world_contact_normal_sums(sums: impl IntoIterator<Item = Vec3A>) -> Option<Vec3A> {
const MIN_LEN_SQ: f32 = 1e-8;
let mut total = Vec3A::ZERO;
for sum in sums {
let len_sq = sum.length_squared();
if len_sq >= MIN_LEN_SQ {
total += sum / len_sq.sqrt();
}
}
let len_sq = total.length_squared();
(len_sq >= MIN_LEN_SQ).then(|| total / len_sq.sqrt())
}
/// A full Rocket League game: ball, cars, boost pads/tiles, and physics.
///
/// Create with [`Arena::new`] (Soccar defaults) or
/// [`Arena::new_with_config`], then [`Arena::add_car`], then
/// [`Arena::reset_to_random_kickoff`]. Drive with
/// [`Arena::set_car_controls`] + [`Arena::step_tick`] at 120 Hz.
///
/// ```no_run
/// use rocketsim::{Arena, CarBodyConfig, GameMode, Team, init_from_default};
/// init_from_default(true).unwrap();
/// let mut arena = Arena::new(GameMode::Soccar);
/// arena.add_car(Team::Blue, CarBodyConfig::OCTANE);
/// arena.reset_to_random_kickoff(Some(0));
/// let events = arena.step_tick();
/// ```
pub struct Arena {
pub(crate) bullet_world: DiscreteDynamicsWorld,
config: ArenaConfig,
pub(crate) ball: Ball,
pub(crate) cars: Vec<Car>,
pub(crate) tick_count: u64,
pub(crate) boost_pad_grid: Option<BoostPadGrid>,
pub(crate) tile_states: Option<TileStates>,
pub(crate) contact_tracker: ArenaContactTracker,
pub(crate) events: ArenaEventList,
ball_only: bool,
pub rng: Rng,
pub vis: Option<Box<dyn Vis>>,
}
impl Clone for Arena {
/// Clones this arena with the same physics state.
///
/// This clones all physics state. The clone steps the same as the original.
/// Static collision meshes stay shared. Static meshes never change. Sharing them does not change physics.
/// This clones the random generator state. Random kickoffs stay in sync if you make the same calls on both arenas.
/// This clones contact history and pending events. The clone reports the same last-step events.
///
/// # Limitations
///
/// The clone sets `vis` to `None`. `Vis` has no clone operation. Attach your visualizer again after cloning if you need it. `vis` does not change physics.
///
/// No other limitation exists. The clone does not diverge unless you change one arena.
fn clone(&self) -> Self {
Self {
bullet_world: self.bullet_world.clone(),
config: self.config.clone(),
ball: self.ball,
cars: self.cars.clone(),
tick_count: self.tick_count,
boost_pad_grid: self.boost_pad_grid.clone(),
tile_states: self.tile_states,
contact_tracker: self.contact_tracker.clone(),
events: self.events.clone(),
ball_only: self.ball_only,
rng: self.rng.clone(),
vis: None,
}
}
}
impl Arena {
/// Creates a Soccar-defaults arena for `game_mode` (see [`ArenaConfig::new`]).
///
/// # Panics
///
/// Panics if collision meshes were not loaded via `crate::init*` (except
/// [`GameMode::TheVoid`], which needs no meshes).
#[must_use]
pub fn new(game_mode: GameMode) -> Self {
Self::new_with_config(ArenaConfig::new(game_mode))
}
/// Creates an arena from a full [`ArenaConfig`] (mutators, pads, RNG, ...).
///
/// # Panics
///
/// Same as [`Arena::new`]: panics without loaded meshes (except `TheVoid`).
pub fn new_with_config(config: ArenaConfig) -> Self {
let (cell_size, initial_handle_size) = match config.mem_weight_mode {
ArenaMemWeightMode::Light => ((config.max_pos - config.min_pos).max_element(), 1),
ArenaMemWeightMode::Balanced => (config.max_aabb_len * 3.0, 1),
ArenaMemWeightMode::Heavy => (config.max_aabb_len, 8),
};
let broadphase = GridBroadphase::new(
config.min_pos * UU_TO_BT,
config.max_pos * UU_TO_BT,
cell_size * UU_TO_BT,
initial_handle_size,
);
let mut bullet_world =
DiscreteDynamicsWorld::new(broadphase, config.mutators.gravity * UU_TO_BT);
if config.game_mode != GameMode::TheVoid {
Self::setup_arena_collision_shapes(&mut bullet_world, config.game_mode);
}
let ball = Ball::new(
config.game_mode,
&mut bullet_world,
&config.mutators,
config.no_ball_rot,
);
let boost_pad_grid =
if config.game_mode != GameMode::TheVoid && config.game_mode != GameMode::Dropshot {
let mut boost_pad_configs = Vec::new();
if let Some(custom_boost_pads) = config.custom_boost_pads.as_ref() {
boost_pad_configs.extend_from_slice(custom_boost_pads);
} else {
let small_pad_locs = consts::boost_pads::get_locations(config.game_mode, false);
let big_pad_locs = consts::boost_pads::get_locations(config.game_mode, true);
boost_pad_configs.reserve(small_pad_locs.len() + big_pad_locs.len());
for small_pos in small_pad_locs {
boost_pad_configs.push(BoostPadConfig {
pos: *small_pos,
is_big: false,
});
}
for big_pos in big_pad_locs {
boost_pad_configs.push(BoostPadConfig {
pos: *big_pos,
is_big: true,
});
}
}
Some(BoostPadGrid::new(&boost_pad_configs, &config.mutators))
} else {
None
};
let tile_states = if config.game_mode == GameMode::Dropshot {
Some(TileStates::DEFAULT)
} else {
None
};
let rng = config.rng_seed.map_or_else(Rng::new, Rng::with_seed);
let ball_only = tile_states.is_none();
Self {
rng,
config,
ball,
boost_pad_grid,
tick_count: 0,
cars: Vec::with_capacity(6),
bullet_world,
tile_states,
contact_tracker: ArenaContactTracker::new(),
events: ArenaEventList::new(),
ball_only,
vis: None,
}
}
/// Borrow the current Arena configuration, including active mutators.
#[must_use]
pub const fn get_config(&self) -> &ArenaConfig {
&self.config
}
fn add_static_collision_shape(
bullet_world: &mut DiscreteDynamicsWorld,
shape: CollisionShapes,
pos_bt: Vec3A,
group: Option<u8>,
) -> usize {
let mut rb_info = RigidBodyConstructionInfo::new(0.0, shape);
rb_info.restitution = consts::arena::BASE_COEFS.restitution;
rb_info.friction = consts::arena::BASE_COEFS.friction;
rb_info.start_world_trans.translation = pos_bt;
let shape_rb = RigidBody::new(rb_info);
if let Some(group) = group {
bullet_world.add_rigid_body(
shape_rb,
group | CollisionFilterGroups::Static,
group ^ CollisionFilterGroups::Static,
)
} else {
bullet_world.add_rigid_body_default(shape_rb)
}
}
/// Face count identifying the Hoops net mesh component: it collides
/// with the ball only (cars pass through), and the viewer draws it
/// translucent for the same reason.
pub const HOOPS_NET_FACE_COUNT: usize = 798;
fn setup_arena_collision_shapes(bullet_world: &mut DiscreteDynamicsWorld, game_mode: GameMode) {
debug_assert!(game_mode != GameMode::TheVoid);
let mesh_game_mode = match game_mode {
GameMode::Heatseeker | GameMode::Snowday => GameMode::Soccar,
_ => game_mode,
};
let collision_shapes = ARENA_COLLISION_SHAPES.read().unwrap();
let collision_meshes = &collision_shapes
.as_ref()
.expect("Arena collision shapes are uninitialized - please call init(..) first.")
[&mesh_game_mode];
assert!(
!collision_meshes.is_empty(),
"No arena meshes found for the game mode {game_mode:?}"
);
for mesh in collision_meshes {
let is_hoops_net = if game_mode == GameMode::Hoops {
// Detect net mesh and disable car collision
mesh.shape.get_mesh_interface().get_total_num_faces() == Self::HOOPS_NET_FACE_COUNT
} else {
false
};
let mask = if is_hoops_net {
Some(CollisionFilterGroups::HoopsNet as u8)
} else {
None
};
Self::add_static_collision_shape(
bullet_world,
CollisionShapes::TriangleMesh(mesh.shape.clone()),
mesh.translation,
mask,
);
}
drop(collision_shapes);
let arena_aabb = consts::arena::get_aabb(game_mode);
let mut add_plane = |pos_uu: Vec3A, normal: Vec3A, mask: Option<u8>| {
debug_assert!(normal.is_normalized());
let pos_bt = pos_uu * UU_TO_BT;
let trans = Affine3A {
matrix3: Mat3A::IDENTITY,
translation: pos_bt,
};
let plane_shape = StaticPlaneShape::new(trans, normal);
Self::add_static_collision_shape(
bullet_world,
CollisionShapes::StaticPlane(plane_shape),
pos_bt,
mask,
);
};
let floor_mask = if game_mode == GameMode::Dropshot {
Some(CollisionFilterGroups::DropshotFloor as u8)
} else {
None
};
// Floor
add_plane(Vec3A::new(0.0, 0.0, arena_aabb.min.z), Vec3A::Z, floor_mask);
// Ceiling
add_plane(Vec3A::new(0.0, 0.0, arena_aabb.max.z), Vec3A::NEG_Z, None);
if game_mode != GameMode::Dropshot {
// Side walls
add_plane(
Vec3A::new(arena_aabb.min.x, 0.0, arena_aabb.max.z / 2.0),
Vec3A::X,
None,
);
add_plane(
Vec3A::new(arena_aabb.max.x, 0.0, arena_aabb.max.z / 2.0),
Vec3A::NEG_X,
None,
);
}
match game_mode {
GameMode::Hoops => {
// Y walls
add_plane(
Vec3A::new(0.0, arena_aabb.min.y, arena_aabb.max.z / 2.0),
Vec3A::Y,
None,
);
add_plane(
Vec3A::new(0.0, arena_aabb.max.y, arena_aabb.max.z / 2.0),
Vec3A::NEG_Y,
None,
);
}
GameMode::Dropshot => {
for (i, tile) in make_tile_shapes().enumerate() {
// Shift down so the collision doesn't peek through the floor
let pos = Vec3A::new(0.0, 0.0, -tile.get_margin());
let rb_idx = Self::add_static_collision_shape(
bullet_world,
CollisionShapes::ConvexHull(tile),
pos,
Some(CollisionFilterGroups::DropshotTile as u8),
);
let rb = &mut bullet_world.bodies_mut()[rb_idx];
rb.user_idx = UserInfoType::DropshotTile;
rb.user_pointer = i;
}
}
_ => {}
}
}
fn ball_within_hoops_goal_xy_margin_eq(x: f32, y: f32) -> f32 {
const SCALE_Y: f32 = 0.9;
const OFFSET_Y: f32 = 2770.0;
const RADIUS_SQ: f32 = 716.0 * 716.0;
let dy = y.abs() * SCALE_Y - OFFSET_Y;
let dist_sq = x * x + dy * dy;
dist_sq - RADIUS_SQ
}
/// Returns `true` if the ball is fully inside a goal (Soccar/Hoops) or
/// has fallen through broken Dropshot tiles. Always `false` for `TheVoid`.
///
/// Check this after [`Arena::step_tick`]; RocketSim does not reset or
/// award points itself.
#[must_use]
pub fn is_ball_scored(&self) -> bool {
let ball_pos = self.bullet_world.bodies()[self.ball.rigid_body_idx]
.get_world_trans()
.translation
* BT_TO_UU;
match self.config.game_mode {
GameMode::Soccar | GameMode::Heatseeker | GameMode::Snowday => {
ball_pos.y.abs()
> self.config.mutators.goal_base_threshold_y + self.config.mutators.ball_radius
}
GameMode::Hoops => {
if ball_pos.z < consts::goal::HOOPS_GOAL_SCORE_THRESHOLD_Z {
Self::ball_within_hoops_goal_xy_margin_eq(ball_pos.x, ball_pos.y) < 0.0
} else {
false
}
}
GameMode::Dropshot => ball_pos.z < -self.config.mutators.ball_radius * 1.75,
GameMode::TheVoid => false,
}
}
/// Teleports cars to kickoff spawns and resets ball/pads (Dropshot tiles too).
///
/// Cars are assigned in team order to shuffled
/// `consts::car::spawn::get_kickoff_spawn_locations`. Orange spawns are
/// mirrored/rotated 180°. Extra cars past the mode kickoff spots overflow to
/// respawn locations. `rng_seed` overrides the arena RNG for this call
/// only; `None` uses the arena RNG (seed via `ArenaConfig::with_rng_seed`
/// for replays).
pub fn reset_to_random_kickoff(&mut self, rng_seed: Option<u64>) {
let kickoff_locs = consts::car::spawn::get_kickoff_spawn_locations(self.config.game_mode);
let respawn_locs = consts::car::spawn::get_respawn_locations(self.config.game_mode);
let mut kickoff_order_perm = ArrayVec::<usize, 5>::new();
kickoff_order_perm.extend(0..kickoff_locs.len());
let mut seeded_rng = rng_seed.map(Rng::with_seed);
if let Some(rng) = seeded_rng.as_mut() {
rng.shuffle(&mut kickoff_order_perm);
} else {
self.rng.shuffle(&mut kickoff_order_perm);
}
let mut num_blue_cars = 0;
let mut num_orange_cars = 0;
for car in &mut self.cars {
if car.team == Team::Blue {
num_blue_cars += 1;
} else {
num_orange_cars += 1;
}
}
let mut num_cars_at_respawn_pos = ArrayVec::<usize, 4>::new();
num_cars_at_respawn_pos.extend(repeat_n(0, 4));
let kickoff_pos_amount = num_blue_cars.max(num_orange_cars);
for i in 0..kickoff_pos_amount {
let spawn_pos = if i < kickoff_locs.len() {
kickoff_locs[kickoff_order_perm[i]]
} else {
const CAR_SPAWN_EXTRA_OFFSET_Y: f32 = 250.0;
let respawn_pos_idx = (i - kickoff_locs.len()) % respawn_locs.len();
let mut pos = respawn_locs[respawn_pos_idx];
pos.y += CAR_SPAWN_EXTRA_OFFSET_Y * num_cars_at_respawn_pos[respawn_pos_idx] as f32;
num_cars_at_respawn_pos[respawn_pos_idx] += 1;
pos
};
let mut spawn_state = CarState::from(CarCore::grounded(
PhysState {
pos: Vec3A::new(spawn_pos.x, spawn_pos.y, consts::car::spawn::REST_Z),
rot_mat: Mat3A::IDENTITY,
vel: Vec3A::ZERO,
ang_vel: Vec3A::ZERO,
},
self.config.mutators.car_spawn_boost_amount,
));
spawn_state.cache.is_on_ground = true;
for cur_team in Team::ALL {
let is_blue = cur_team == Team::Blue;
let mut team_car_count = 0;
let mut car_idx = None;
for car in &self.cars {
if car.team == cur_team {
team_car_count += 1;
if team_car_count == i + 1 {
car_idx = Some(car.idx);
break;
}
}
}
if let Some(car_idx) = car_idx {
spawn_state.phys.rot_mat = Mat3A::from_euler(
EulerRot::ZYX,
if is_blue {
spawn_pos.yaw_ang
} else {
spawn_state.phys.pos *= Vec3A::new(-1.0, -1.0, 1.0);
spawn_pos.yaw_ang + if is_blue { 0.0 } else { PI }
},
0.0,
0.0,
);
let car = &mut self.cars[car_idx];
let rb = &mut self.bullet_world.bodies_mut()[car.rigid_body_idx];
car.set_state(rb, &spawn_state);
// Drop driving contacts so the next tick matches a fresh arena
car.bullet_vehicle.reset_transient_contacts();
car.sticky_gate_prev = false;
}
}
}
let mut ball_state = BallState::DEFAULT;
match self.config.game_mode {
GameMode::Heatseeker => {
let next_rand = seeded_rng
.as_mut()
.map_or_else(|| self.rng.bool(), Rng::bool);
let y_sign = f32::from(i8::from(next_rand) * 2 - 1);
let scale = Vec3A::new(-y_sign, y_sign, 1.0);
ball_state.phys.pos = consts::heatseeker::BALL_START_POS * scale;
ball_state.phys.vel = consts::heatseeker::BALL_START_VEL * scale;
}
GameMode::Snowday => {
ball_state.phys.vel.z = f32::EPSILON;
}
GameMode::Dropshot => {
self.tile_states = Some(TileStates::DEFAULT);
self.ball_only = false;
self.update_tile_states();
}
_ => {}
}
self.set_ball_state(ball_state);
if let Some(boost_pad_grid) = self.boost_pad_grid.as_mut() {
boost_pad_grid.reset();
}
}
/// Spawns a car, respawns it at a team respawn pad, and returns its index.
///
/// Use the index with `get_car_*/set_car_*`. Removing a car with
/// [`Arena::remove_car`] decreases the indices of all later cars by one.
///
/// # Panics
///
/// Panics if the car exceeds the broadphase limit of 16,384 collision
/// objects. This count includes arena shapes and the ball.
///
/// ```no_run
/// # use rocketsim::{Arena, CarBodyConfig, GameMode, Team, init_from_default};
/// # init_from_default(true).unwrap();
/// # let mut arena = Arena::new(GameMode::Soccar);
/// let blue = arena.add_car(Team::Blue, CarBodyConfig::OCTANE);
/// let orange = arena.add_car(Team::Orange, CarBodyConfig::DOMINUS);
/// ```
pub fn add_car(&mut self, team: Team, config: CarBodyConfig) -> usize {
let idx = self.cars.len();
let mut car = Car::new(
idx,
team,
&mut self.bullet_world,
&self.config.mutators,
config,
);
car.respawn(
&mut self.bullet_world.bodies_mut()[car.rigid_body_idx],
&mut self.rng,
self.config.game_mode,
self.config.mutators.car_spawn_boost_amount,
);
self.bullet_world.bodies_mut()[car.rigid_body_idx].user_pointer = idx;
self.cars.push(car);
self.ball_only = false;
idx
}
/// Removes a car and its physics body from the arena.
///
/// Keeps the order of the remaining cars. Each car after `car_idx` gets
/// an index that is one less than its old index. Update any car indices
/// stored by your application. Old snapshots and copied events keep their
/// old indices; do not use those indices with the changed arena.
///
/// Removes the car from boost-pad membership and bump cooldowns. Updates
/// stored physics indices and removes contacts with the car. Queries
/// exported wheel contacts again if they included a car. Clears the last
/// step's events. Does not advance time or reset the remaining bodies.
///
/// # Panics
///
/// Panics if `car_idx` is out of bounds. The arena stays unchanged.
///
/// ```
/// use rocketsim::{Arena, CarBodyConfig, GameMode, Team};
///
/// let mut arena = Arena::new(GameMode::TheVoid);
/// let blue = arena.add_car(Team::Blue, CarBodyConfig::OCTANE);
/// let orange = arena.add_car(Team::Orange, CarBodyConfig::DOMINUS);
/// arena.remove_car(blue);
/// assert_eq!(arena.get_car_info(orange - 1).team, Team::Orange);
/// ```
pub fn remove_car(&mut self, car_idx: usize) {
let body_idx = self.cars[car_idx].rigid_body_idx;
self.bullet_world.remove_rigid_body(body_idx);
self.cars.remove(car_idx);
if self.ball.rigid_body_idx > body_idx {
self.ball.rigid_body_idx -= 1;
}
for (idx, car) in self.cars.iter_mut().enumerate() {
car.info.idx = idx;
if car.rigid_body_idx > body_idx {
car.rigid_body_idx -= 1;
}
self.bullet_world.bodies_mut()[car.rigid_body_idx].user_pointer = idx;
car.bullet_vehicle.remove_body(body_idx);
if let Some(victim) = &mut car.state.bump_cooldown_victim {
if *victim == car_idx {
// None with a positive timer blocks bumps against all cars.
car.state.bump_cooldown_victim = None;
car.state.bump_cooldown_timer = 0.0;
} else if *victim > car_idx {
*victim -= 1;
}
}
if let Some(demoer) = car.state.cache.demoer_idx {
if demoer == car_idx {
car.state.cache.demoer_idx = None;
car.state.cache.demo_tick = u64::MAX;
} else if demoer > car_idx {
car.state.cache.demoer_idx = Some(demoer - 1);
}
}
}
// Exported wheel hits store the body type, not the body index.
// Query these hits again without clearing unrelated suspension history.
if self.cars.iter().any(|car| {
car.state
.wheels_with_contact()
.iter()
.flatten()
.any(|hit| hit.user_info == UserInfoType::Car)
}) {
self.bullet_world.refresh_aabbs();
for car in &mut self.cars {
if car
.state
.wheels_with_contact()
.iter()
.flatten()
.any(|hit| hit.user_info == UserInfoType::Car)
{
car.refresh_contact_state(&self.bullet_world);
}
}
}
if let Some(grid) = &mut self.boost_pad_grid {
grid.remove_car(
car_idx,
&self.cars,
self.config.mutators.car_max_boost_amount,
);
}
self.contact_tracker.clear_records();
self.events.clear();
self.ball_only = self.cars.is_empty() && self.tile_states.is_none();
}
/// Removes all cars and their physics bodies in one batch.
///
/// Removes car contacts and boost-pad membership. Clears the last step's
/// events, even if there are no cars. Keeps the ball, arena geometry,
/// boost-pad cooldowns, tile states, tick count, and random generator state.
/// Does not advance time. Retains storage for later cars.
///
/// All previous car indices become invalid. The next [`Arena::add_car`]
/// returns `0`. Old snapshots and copied events keep their old indices.
///
/// ```
/// use rocketsim::{Arena, CarBodyConfig, GameMode, Team};
///
/// let mut arena = Arena::new(GameMode::TheVoid);
/// arena.add_car(Team::Blue, CarBodyConfig::OCTANE);
/// arena.add_car(Team::Orange, CarBodyConfig::DOMINUS);
/// arena.remove_cars();
/// assert_eq!(arena.num_cars(), 0);
/// assert_eq!(arena.add_car(Team::Blue, CarBodyConfig::OCTANE), 0);
/// ```
pub fn remove_cars(&mut self) {
if let Some(first_car) = self.cars.first() {
// Arena geometry and the ball precede the contiguous car bodies.
let body_count = first_car.rigid_body_idx;
debug_assert_eq!(
self.bullet_world.bodies().len(),
body_count + self.cars.len()
);
self.bullet_world.truncate_rigid_bodies(body_count);
self.cars.clear();
}
if let Some(grid) = &mut self.boost_pad_grid {
grid.remove_cars();
}
self.contact_tracker.clear_records();
self.events.clear();
self.ball_only = self.tile_states.is_none();
}
/// Advances the game one tick (`1/120` s) and returns that tick's events.
///
/// Set inputs with [`Arena::set_car_controls`] before calling. The
/// returned slice is only valid until the next `step_tick` — copy it if
/// you need it longer. See [`Arena::get_last_step_events`].
///
/// ```no_run
/// # use rocketsim::{Arena, CarBodyConfig, CarControls, GameMode, Team, init_from_default};
/// # init_from_default(true).unwrap();
/// # let mut arena = Arena::new(GameMode::Soccar);
/// # let car = arena.add_car(Team::Blue, CarBodyConfig::OCTANE);
/// arena.set_car_controls(car, CarControls::default().with_throttle(1.0));
/// for event in arena.step_tick() {
/// println!("{event:?}");
/// }
/// ```
pub fn step_tick(&mut self) -> &[ArenaEvent] {
self.events.clear();
// NOTE: This needs to be called manually
// TODO: Make it not need to be called manually
self.bullet_world.clear_accum_forces();
// Limit velocities, then quantize physics values
{
use consts::{ball, car};
if !self.ball_only {
for car_idx in 0..self.cars.len() {
let car_rb =
&mut self.bullet_world.bodies_mut()[self.cars[car_idx].rigid_body_idx];
car_rb.limit_vels(car::MAX_SPEED * UU_TO_BT, car::MAX_ANG_SPEED);
quantize::quantize(car_rb);
// Sync the cached state after rigid-body limits.
self.cars[car_idx].state.phys.vel = car_rb.lin_vel * BT_TO_UU;
self.cars[car_idx].state.phys.ang_vel = car_rb.ang_vel;
}
}
let ball_rb = &mut self.bullet_world.bodies_mut()[self.ball.rigid_body_idx];
ball_rb.limit_vels(
self.config.mutators.ball_max_speed * UU_TO_BT,
ball::MAX_ANG_SPEED,
);
quantize::quantize(ball_rb);
self.ball.state.phys.vel = ball_rb.lin_vel * BT_TO_UU;
self.ball.state.phys.ang_vel = ball_rb.ang_vel;
}
if !self.ball_only {
// Apply flip damping before another car's wheels read its velocity.
for car in &mut self.cars {
car.apply_flip_zdamp_prepass(&mut self.bullet_world);
}
for car_idx in 0..self.cars.len() {
let was_on_ground = self.cars[car_idx].state.cache.is_on_ground;
self.cars[car_idx].pre_tick_update(
&mut self.bullet_world,
&mut self.rng,
self.config.game_mode,
&self.config.mutators,
);
if !was_on_ground && self.cars[car_idx].state.cache.is_on_ground {
self.events.push(ArenaEvent::CarLanded(CarLandedEvent {
car_idx,
wheels: self.cars[car_idx].state.cache.wheels_with_contact,
}));
}
}
}
self.ball.pre_tick_update(
&mut self.bullet_world.bodies_mut()[self.ball.rigid_body_idx],
self.config.game_mode,
);
let ball_only = self.ball_only;
self.contact_tracker.set_ball_only(ball_only);
self.bullet_world.set_ball_only(ball_only);
self.bullet_world
.step_simulation(TICK_TIME, &mut self.contact_tracker);
if ball_only {
let contact_count = self.contact_tracker.num_ball_world_records();
for idx in 0..contact_count {
let contact = *self.contact_tracker.get_ball_world_record(idx);
self.on_ball_world_collision_parts(
contact.rb_idx,
contact.contact_point,
contact.contact_normal,
);
}
} else {
let contact_count = self.contact_tracker.num_records();
for idx in 0..contact_count {
let contact = *self.contact_tracker.get_record(idx);
let bodies = self.bullet_world.bodies();
let rb_a = &bodies[contact.rb_idx_a];
let rb_b = &bodies[contact.rb_idx_b];
let user_idx_a = rb_a.user_idx;
let user_idx_b = rb_b.user_idx;
let user_pointer_a = rb_a.user_pointer;
let user_pointer_b = rb_b.user_pointer;
match user_idx_a {
UserInfoType::Car => match user_idx_b {
UserInfoType::Ball => {
self.on_car_ball_collision(
user_pointer_a,
&contact.manifold_point,
contact.is_swap,
);
}
UserInfoType::Car => {
self.on_car_car_collision(
user_pointer_a,
user_pointer_b,
&contact.manifold_point,
);
}
_ => self.on_car_world_collision(user_pointer_a, &contact.manifold_point),
},
UserInfoType::Ball => match user_idx_b {
UserInfoType::DropshotTile => {
self.on_ball_tile_collision(user_pointer_b);
}
UserInfoType::None => {
self.on_ball_world_collision(&contact.manifold_point, contact.rb_idx_a);
}
_ => {}
},
_ => {}
}
}
self.update_world_contact_normal();
}
self.contact_tracker.clear_records();
if !self.ball_only {
for car in &mut self.cars {
car.post_tick_update(&mut self.bullet_world);
let rb = &mut self.bullet_world.bodies_mut()[car.rigid_body_idx];
car.finish_physics_tick(rb);
}
if self.config.mutators.boost_pads_enabled
&& let Some(grid) = self.boost_pad_grid.as_mut()
{
grid.update_membership(&self.cars, self.config.mutators.car_max_boost_amount);
for car_idx in 0..self.cars.len() {
let collected = {
let car = &mut self.cars[car_idx];
grid.maybe_give_car_boost(
&mut car.state,
&self.config.mutators,
self.tick_count,
car_idx,
)
};
if let Some(boost_pad_idx) = collected {
self.events.push(CarPickupBoost(CarPickupBoostEvent {
car_idx,
boost_pad_idx,
}));
grid.refresh_winner(
boost_pad_idx,
&self.cars,
self.config.mutators.car_max_boost_amount,
);
}
}
}
}
let ball_rb = &mut self.bullet_world.bodies_mut()[self.ball.rigid_body_idx];
self.ball.finish_physics_tick(ball_rb);
if self.config.game_mode == GameMode::Dropshot
&& self.ball.state.ds_info.last_damage_tick == Some(self.tick_count)
{
self.update_tile_states();
}
self.tick_count += 1;
if self.vis.is_some() {
let arena_state = self.get_arena_state();
if let Some(vis) = self.vis.as_mut() {
vis.update(&arena_state, TICK_TIME);
}
};
self.get_last_step_events()
}
/// Ticks simulated so far (starts at 0, increments per [`Arena::step_tick`]).
#[inline]
pub const fn tick_count(&self) -> u64 {
self.tick_count
}
/// The game mode this arena was built with.
#[inline]
pub const fn game_mode(&self) -> GameMode {
self.config.game_mode
}
/// Current mutators (physics/rules). Initially set by `ArenaConfig`.
#[inline]
pub const fn mutator_config(&self) -> &MutatorConfig {
&self.config.mutators
}
/// Replace active mutators without recreating this Arena.
///
/// This keeps positions, velocities, timers, pad cooldown timestamps, and event
/// history. It updates gravity, body mass and inertia, ball geometry and drag,
/// and pad amount and cooldown values. A ball-radius or body-mass change clears
/// persistent contact manifolds because cached geometry or impulses are stale.
/// Other changes keep contact manifolds. A car mass change updates and wakes
/// cars. A ball mass, radius, or drag change updates and wakes the ball. Gravity
/// changes do not wake sleeping bodies. Body updates clear pending accumulators.
/// Changing pad cooldown durations keeps each pad's pickup tick and applies the
/// new duration to it. Pad membership is retained while disabled and refreshed
/// before the first pickup check after re-enabling.
///
/// # Panics
///
/// Panics if either the current or new mass is not finite and strictly
/// positive. The Arena remains unchanged when this validation fails.
pub fn set_mutator_config(&mut self, mutators: MutatorConfig) {
let old = self.config.mutators;
assert!(
old.car_mass.is_finite() && old.car_mass > 0.0,
"runtime updates require an Arena with a finite, positive car mass"
);
assert!(
old.ball_mass.is_finite() && old.ball_mass > 0.0,
"runtime updates require an Arena with a finite, positive ball mass"
);
assert!(
mutators.car_mass.is_finite() && mutators.car_mass > 0.0,
"runtime car mass must be finite and strictly positive"
);
assert!(
mutators.ball_mass.is_finite() && mutators.ball_mass > 0.0,
"runtime ball mass must be finite and strictly positive"
);
let car_mass_changed = old.car_mass != mutators.car_mass;
let ball_properties_changed = old.ball_radius != mutators.ball_radius
|| old.ball_mass != mutators.ball_mass
|| old.ball_drag != mutators.ball_drag;
let geometry_changed = old.ball_radius != mutators.ball_radius
|| old.ball_mass != mutators.ball_mass
|| car_mass_changed;
if old.gravity != mutators.gravity {
self.bullet_world.set_gravity(mutators.gravity * UU_TO_BT);
}
if car_mass_changed {
for car in &mut self.cars {
let config = car.info.config;
let child = BoxShape::new(config.hitbox_size * UU_TO_BT * 0.5);
let inertia = child.calculate_local_intertia(mutators.car_mass);
let offset = Affine3A {
matrix3: Mat3A::IDENTITY,
translation: config.hitbox_pos_offset * UU_TO_BT,
};
let shape = CollisionShapes::Compound(CompoundShape::new(child, offset));
self.bullet_world.update_body_properties(
car.rigid_body_idx,
RigidBodyUpdateInfo {
shape,
mass: mutators.car_mass,
local_inertia: inertia,
friction: crate::sim::consts::car::BASE_COEFS.friction,
restitution: crate::sim::consts::car::BASE_COEFS.restitution,
linear_damping: 0.0,
invalidate_contacts: geometry_changed,
},
);
car.refresh_mass_dependent_state(mutators.car_mass);
car.vel_impulse_cache = Vec3A::ZERO;
}
}
if ball_properties_changed {
let (ball_shape, ball_inertia) =
Ball::make_ball_collision_shape(self.config.game_mode, &mutators);
let ball_coefs = if self.config.game_mode == GameMode::Snowday {
crate::sim::consts::snowday::PUCK_COEFS
} else {
crate::sim::consts::ball::COEFS
};
self.bullet_world.update_body_properties(
self.ball.rigid_body_idx,
RigidBodyUpdateInfo {
shape: ball_shape,
mass: mutators.ball_mass,
local_inertia: ball_inertia,
friction: ball_coefs.friction,
restitution: ball_coefs.restitution,
linear_damping: mutators.ball_drag,
invalidate_contacts: geometry_changed,
},
);
}
if let Some(grid) = self.boost_pad_grid.as_mut() {
for pad in &mut grid.all_pads {
pad.max_cooldown = if pad.config.is_big {
mutators.boost_pad_cooldown_big
} else {
mutators.boost_pad_cooldown_small
};
pad.boost_amount = if pad.config.is_big {
mutators.boost_pad_amount_big
} else {
mutators.boost_pad_amount_small
};
}
}
self.config.mutators = mutators;
}
/// Teleports the ball (position/velocity/rotation + mode state).
///
/// Use to place kickoffs, restore snapshots, or inject test states.
/// For Heatseeker also set `hs_info`; for Dropshot `ds_info`.
/// Persistent manifolds auto-cull stale points on the next tick via the
/// contact breaking threshold; call `clear_persistent_manifolds` first
/// only if you need bit-identical fresh-arena matching for large
/// planning jumps.
///
/// This operation activates the ball and resets its deactivation timer,
/// even when both velocity vectors are zero.
pub fn set_ball_state(&mut self, ball_state: BallState) {
self.ball.set_state(
&mut self.bullet_world.bodies_mut()[self.ball.rigid_body_idx],
ball_state,
);
}
/// Set the ball's linear and angular velocity to zero, then put it to sleep.
/// The ball remains asleep until a collision or state update activates it.
pub fn sleep_ball(&mut self) {
let ball = &mut self.ball;
let rb = &mut self.bullet_world.bodies_mut()[ball.rigid_body_idx];
ball.state.phys.vel = Vec3A::ZERO;
ball.state.phys.ang_vel = Vec3A::ZERO;
rb.set_lin_vel(Vec3A::ZERO);
rb.set_ang_vel(Vec3A::ZERO);
rb.clear_accum_vels();
rb.set_activation_state(crate::bullet::dynamics::rigid_body::ActivationState::Sleeping);
}
/// Edit ball state in place. Synchronize its body as in [`Arena::set_ball_state`].
/// This operation activates the ball and resets its deactivation timer,
/// even when both velocity vectors are zero.
///
/// If the callback panics, completed edits remain. The body is synchronized
/// during unwinding.
pub fn edit_ball_state(&mut self, edit: impl FnOnce(&mut BallState)) {
let rb = &mut self.bullet_world.bodies_mut()[self.ball.rigid_body_idx];
let guard = StateEditGuard {
target: &mut self.ball,
sync: |ball: &mut Ball| ball.sync_state_to_body(rb),
};
edit(&mut guard.target.state);
}
/// Explicitly drop cached collision contacts.
///
/// Opt-in for planning code reusing one arena across far-apart poses that
/// needs fresh-arena matching. Normal per-tick replay corrections should
/// NOT call this; auto-culling preserves continuity there.
pub fn clear_persistent_manifolds(&mut self) {
self.bullet_world.clear_persistent_manifolds();
}
/// Current ball state (updated after every [`Arena::step_tick`]).
pub const fn get_ball_state(&self) -> &BallState {
&self.ball.state
}
/// Count cached contact manifolds for reuse diagnostics.
#[inline]
#[must_use]
pub fn num_persistent_manifolds(&self) -> usize {
self.bullet_world.num_persistent_manifolds()
}
/// All current cars in add order. Indices match the `get_car_*/set_car_*` APIs.
/// Removing a car shifts all later indices down by one.
#[inline]
pub const fn cars(&self) -> &Vec<Car> {
&self.cars
}
/// Number of cars currently in the arena.
#[inline]
pub const fn num_cars(&self) -> usize {
self.cars.len()
}
/// Immutable car info (team, hitbox preset). Panics if `car_idx` is OOB.
pub fn get_car_info(&self, car_idx: usize) -> &CarInfo {
&self.cars[car_idx].info
}
/// Current car state (updated after every [`Arena::step_tick`]).
pub fn get_car_state(&self, car_idx: usize) -> &CarState {
self.cars[car_idx].get_state()
}
/// Last controls set for a car (equals applied controls after the tick).
pub fn get_car_controls(&self, car_idx: usize) -> &CarControls {
&self.cars[car_idx].state.controls
}
/// Re-syncs the sticky wheel-contact gate after externally teleporting a car.
///
/// Also updates the cached previous world-wheel count.
/// Call after [`Arena::set_car_state_full`] when you restore snapshots mid-drive,
/// otherwise the next tick may apply a one-tick sticking artifact.
/// Normal `set_car_controls` + `step_tick` loops don't need this.
pub fn refresh_car_sticky_gate(&mut self, car_idx: usize) {
self.cars[car_idx].refresh_sticky_gate(&self.bullet_world);
}
/// Refresh wheel contacts at the current car pose without advancing time.
///
/// Updates Bullet wheel contacts, exported wheel hits, grounding, the cached
/// previous world-wheel count, and the sticky gate. Clears the stale world-contact normal; wheel queries do not
/// reconstruct body contact manifolds. Applies no forces and keeps physics,
/// tuning, and previous controls unchanged. Demoed cars keep empty contacts.
/// Place all cars and the ball before refreshing contacts after a reset.
/// For continuous corrections, [`Arena::refresh_car_contact_state`] preserves
/// suspension history and the retained world-contact normal instead.
/// Panics if `car_idx` is out of bounds.
///
/// ```no_run
/// # use rocketsim::{Arena, CarControls, CarCore, PhysState};
/// # fn place_car(arena: &mut Arena, car_idx: usize, phys: PhysState) {
/// arena.set_car_state(car_idx, CarCore::grounded(phys, 50.0));
/// arena.refresh_car_contacts(car_idx);
/// arena.set_car_controls(
/// car_idx,
/// CarControls {
/// jump: true,
/// ..CarControls::DEFAULT
/// },
/// );
/// // The next tick can jump without a warm-up tick.
/// # }
/// ```
pub fn refresh_car_contacts(&mut self, car_idx: usize) {
let car = &mut self.cars[car_idx];
self.bullet_world.refresh_aabbs();
car.refresh_contacts(&self.bullet_world);
}
/// Calculate exported wheel contacts and grounding from the current pose.
///
/// Preserves Bullet wheel and suspension history, the sticky gate, and the
/// retained world-contact normal. Does not advance time or apply forces.
/// Keeps core state, tuning, and previous controls unchanged. Demoed cars
/// get empty wheel contacts. Place all bodies before querying contacts.
/// Use [`Arena::refresh_car_contacts`] for full contact initialization instead.
/// Panics if `car_idx` is out of bounds.
///
/// ```no_run
/// # use rocketsim::{Arena, PhysState};
/// # fn correct_car(arena: &mut Arena, car_idx: usize, phys: PhysState) {
/// arena.edit_car_state_full(car_idx, |state| state.phys = phys);
/// arena.refresh_car_contact_state(car_idx);
/// # }
/// ```
pub fn refresh_car_contact_state(&mut self, car_idx: usize) {
let car = &mut self.cars[car_idx];
self.bullet_world.refresh_aabbs();
car.refresh_contact_state(&self.bullet_world);
}
/// Convenience getter returning `(info, state)` together.
pub fn get_car_info_and_state(&self, car_idx: usize) -> (&CarInfo, &CarState) {
let car = &self.cars[car_idx];
(&car.info, &car.state)
}
/// Set primary car state. Derive tuning from velocity and clear contacts.
///
/// Clamps boost to `0..100` and sets jump/flip flags required by active phases.
/// Sets previous controls to the supplied controls. Contacts are unknown until
/// the next tick or [`Arena::refresh_car_contacts`]. Resets wheel contacts,
/// the previous world-wheel count, cached impulses, the sticky gate, and demo
/// attribution.
/// For far teleports, also call [`Arena::clear_persistent_manifolds`].
/// Use [`Arena::set_car_state_full`] to preserve tuning for replay or cloning.
pub fn set_car_state(&mut self, car_idx: usize, core: CarCore) {
self.set_car_state_full(car_idx, CarState::from(core));
self.reset_car_transient_contacts(car_idx);
}
/// Restore an exact car snapshot. Use only for replay or cloning.
///
/// Copies core, tuning, and cache without validation or normalization.
/// The cache includes the previous world-wheel count and demo attribution,
/// so a full snapshot restores both gates exactly.
/// Clears cached body impulses. Hidden Bullet wheel contacts and the sticky gate
/// carry over. For replay corrections, call [`Arena::refresh_car_sticky_gate`].
/// For planning reuse, call [`Arena::reset_car_transient_contacts`] instead.
/// Also call [`Arena::clear_persistent_manifolds`] for far teleports.
pub fn set_car_state_full(&mut self, car_idx: usize, state: CarState) {
let car = &mut self.cars[car_idx];
car.set_state(
&mut self.bullet_world.bodies_mut()[car.rigid_body_idx],
&state,
);
}
/// Edit full car state in place. Use only for replay or cloning.
///
/// Keeps unedited fields unchanged. Does not validate or normalize values.
/// Cache fields, including the previous world-wheel count and demo
/// attribution, stay unchanged.
/// Body and contact handling match [`Arena::set_car_state_full`].
/// If the callback panics, completed edits remain. The body is synchronized
/// during unwinding.
///
/// ```no_run
/// # use rocketsim::Arena;
/// # fn restore_handbrake(arena: &mut Arena, car_idx: usize) {
/// arena.edit_car_state_full(car_idx, |state| {
/// state.handbrake_val = 0.5;
/// state.jump_hold_broken = true;
/// });
/// # }
/// ```
pub fn edit_car_state_full(&mut self, car_idx: usize, edit: impl FnOnce(&mut CarState)) {
let car = &mut self.cars[car_idx];
let rb = &mut self.bullet_world.bodies_mut()[car.rigid_body_idx];
let guard = StateEditGuard {
target: car,
sync: |car: &mut Car| car.sync_state_to_body(rb),
};
edit(&mut guard.target.state);
}
/// Clear a car's stored and Bullet contacts for planning reuse.
///
/// Drops wheel raycasts/impulses, the sticky gate, exported wheel hits,
/// grounding, and the world-contact normal. Keeps core state, tuning, and
/// previous controls. Call [`Arena::refresh_car_contacts`] to query contacts
/// at the new pose. Also clear persistent manifolds after far teleports.
/// Replay following must not call this; it would break contact continuity.
pub fn reset_car_transient_contacts(&mut self, car_idx: usize) {
self.cars[car_idx].reset_transient_contacts();
}
/// Set boost, clamped to `0..100`. Leave all other state unchanged.
///
/// Keeps contacts, tuning, jump history, and cached impulses.
/// Use this instead of replacing car state to refill boost during simulation.
pub fn set_car_boost(&mut self, car_idx: usize, boost: f32) {
self.cars[car_idx].state.boost = boost.clamp(0.0, consts::car::boost::MAX);
}
/// Sets the inputs applied on the next [`Arena::step_tick`].
///
/// [`Arena::step_tick`] clamps analog inputs to `-1..1` (see [`CarControls::clamp`]).
/// `jump` is edge-triggered (only the rising edge jumps/flips).
pub fn set_car_controls(&mut self, car_idx: usize, controls: CarControls) {
self.cars[car_idx].state.controls = controls;
}
/// Sets a car's dodge deadzone (`|yaw| + |pitch| + |roll|` must reach this to flip instead of double-jumping).
///
/// Defaults to `0.5` (see [`CarBodyConfig::dodge_deadzone`]). `0.0` always flips on second jump,
/// values above `3.0` never flip. Takes effect on the next [`Arena::step_tick`].
/// Panics if `car_idx` is OOB.
pub fn set_car_dodge_deadzone(&mut self, car_idx: usize, dodge_deadzone: f32) {
self.cars[car_idx].info.config.dodge_deadzone = dodge_deadzone;
}
/// Respawns a car at a random team respawn pad with spawn boost.
///
/// Normally demos auto-respawn after `mutators.respawn_delay`; use this
/// to force it (e.g. after [`Arena::reset_to_random_kickoff`] tests).
pub fn respawn_car(&mut self, car_idx: usize) {
let car = &mut self.cars[car_idx];
car.respawn(
&mut self.bullet_world.bodies_mut()[car.rigid_body_idx],
&mut self.rng,
self.config.game_mode,
self.config.mutators.car_spawn_boost_amount,
);
}
/// Demolishes a car, disabling its physics until the respawn timer ends.
///
/// Uses `mutators.respawn_delay` for the timer, matching demos from
/// car-car collisions. The car auto-respawns via [`Arena::respawn_car`]
/// logic once the timer expires; use [`Arena::respawn_car`] to force an
/// immediate respawn instead of waiting.
pub fn demolish_car(&mut self, car_idx: usize) {
self.cars[car_idx].demolish(self.config.mutators.respawn_delay);
}
/// Returns pad cooldown and ordered car members. Membership uses the
/// acquisition cylinder and hitbox retention box. A car appears on one pad
/// only. The order preserves first entry while membership continues.
///
/// # Panics
///
/// Panics in `TheVoid`/`Dropshot` (no pads) or for an OOB index.
#[must_use]
pub fn get_boost_pad_state(&self, idx: usize) -> BoostPadState {
let pad = &self.boost_pads()[idx];
let cooldown = pad.gave_boost_tick_count.map_or(0.0, |gave_boost_tick| {
let max_cooldown = pad.max_cooldown;
let time_since = ((self.tick_count() as i64 - gave_boost_tick) as f32) * TICK_TIME;
(max_cooldown - time_since).max(0.0)
});
BoostPadState {
cooldown,
touching_car_idxs: pad.touching_car_idxs.clone(),
}
}
/// Restores pad cooldown and ordered membership. `cooldown <= 0` reactivates the pad.
/// Add all cars before restoring this state. Invalid car IDs are discarded, and duplicate
/// IDs in this list keep their first position. Do not restore one car on multiple pads.
/// If restored data does so, the next tick keeps that car on the lowest-index pad that still
/// retains it. Membership changes take effect on the next tick.
pub fn set_boost_pad_state(&mut self, idx: usize, state: BoostPadState) {
let boost_pad_grid = self.boost_pad_grid.as_mut().unwrap();
let tick_count = self.tick_count;
let pad = &mut boost_pad_grid.all_pads[idx];
pad.touching_car_idxs.clear();
for car_idx in state.touching_car_idxs.iter().copied() {
if car_idx < self.cars.len() && !pad.touching_car_idxs.contains(&car_idx) {
pad.touching_car_idxs.push(car_idx);
}
}
if state.cooldown > 0.0 {
let time_since_pickup = (pad.max_cooldown - state.cooldown).max(0.0);
let ticks_since_pickup = (time_since_pickup * TICK_RATE).round() as i64;
pad.gave_boost_tick_count = Some(tick_count as i64 - ticks_since_pickup);
} else {
boost_pad_grid.all_pads[idx].gave_boost_tick_count = None;
}
}
/// Edit a local pad snapshot, then apply it with [`Arena::set_boost_pad_state`].
///
/// Cooldown is derived from pickup ticks, so this editor uses a temporary value.
/// Conversion keeps the setter's tick quantization. If the callback panics,
/// the snapshot is not applied. Panics outside pad modes
/// or for an out-of-bounds `idx`, as the getter does.
pub fn edit_boost_pad_state(&mut self, idx: usize, edit: impl FnOnce(&mut BoostPadState)) {
let mut state = self.get_boost_pad_state(idx);
edit(&mut state);
self.set_boost_pad_state(idx, state);
}
/// Static pad layout (`pos`, `is_big`). Order is RLBot/RLGym (Y, then X).
#[must_use]
pub fn get_boost_pad_config(&self, idx: usize) -> &BoostPadConfig {
self.boost_pads()[idx].config()
}
pub(crate) fn boost_pads(&self) -> &[BoostPad] {
&self.boost_pad_grid.as_ref().unwrap().all_pads
}
/// Number of pads (`0` in `TheVoid`/`Dropshot`; 34 Soccar, 20 Hoops).
#[must_use]
pub fn num_boost_pads(&self) -> usize {
self.boost_pad_grid
.as_ref()
.map_or(0, |grid| grid.all_pads.len())
}
/// All pad cooldowns and ordered memberships in pad order.
#[must_use]
pub fn get_all_boost_pad_states(&self) -> Vec<BoostPadState> {
(0..self.num_boost_pads())
.map(|i| self.get_boost_pad_state(i))
.collect()
}
/// All pad layouts in pad order.
#[must_use]
pub fn get_all_boost_pad_configs(&self) -> Vec<BoostPadConfig> {
(0..self.num_boost_pads())
.map(|i| *self.get_boost_pad_config(i))
.collect()
}
/// Dropshot tile damage grid. Panics outside Dropshot.
pub fn get_tile_states(&self) -> &TileStates {
self.tile_states.as_ref().unwrap()
}
fn update_tile_states(&mut self) {
let tile_states = &self.tile_states.as_ref().unwrap().states;
for rb in self.bullet_world.bodies_mut() {
if rb.user_idx != UserInfoType::DropshotTile {
continue;
}
let team_idx = rb.user_pointer / consts::dropshot::NUM_TILES_PER_TEAM;
let tile_idx = rb.user_pointer % consts::dropshot::NUM_TILES_PER_TEAM;
if tile_states[team_idx][tile_idx] == TileDamageState::Broken {
rb.collision_flags |= CollisionFlags::NoContactResponse;
} else {
rb.collision_flags &= !CollisionFlags::NoContactResponse;
}
}
}
/// Replaces the Dropshot tile grid and updates collision (broken tiles
/// stop colliding). Also clears ball-only mode so tiles simulate.
pub fn set_tile_states(&mut self, tile_states: TileStates) {
self.tile_states = Some(tile_states);
self.ball_only = false;
self.update_tile_states();
}
/// Edit tile state in place. Update collision as in [`Arena::set_tile_states`].
///
/// If the callback panics, completed edits remain. Collision flags and
/// ball-only mode are updated during unwinding. Panics outside Dropshot,
/// as the getter does.
pub fn edit_tile_states(&mut self, edit: impl FnOnce(&mut TileStates)) {
self.get_tile_states();
let guard = StateEditGuard {
target: self,
sync: |arena: &mut Self| {
arena.ball_only = false;
arena.update_tile_states();
},
};
edit(guard.target.tile_states.as_mut().unwrap());
}
/// Total tiles across both teams (`0` outside Dropshot, else 140).
pub fn num_tiles(&self) -> usize {
self.tile_states
.as_ref()
.map_or(0, |ts| ts.states[0].len() * ts.states.len())
}
/// Full snapshot (cars, ball, pads, tiles) for replays/debugging.
///
/// Cheap clones of state only (no physics-world copy). Pair with
/// `set_*` methods to restore. [`crate::ArenaState::new_empty`] builds
/// an empty placeholder when you only need the type.
#[must_use]
pub fn get_arena_state(&self) -> ArenaState {
let cars = self
.cars
.iter()
.map(|c| (c.info, c.state))
.collect::<Vec<_>>();
let ball = *self.get_ball_state();
let boost_pads = (0..self.num_boost_pads())
.map(|i| (*self.get_boost_pad_config(i), self.get_boost_pad_state(i)))
.collect();
ArenaState {
game_mode: self.config.game_mode,
tick_count: self.tick_count,
cars,
ball,
boost_pads,
tile_states: self.tile_states,
}
}
/// Events from the last [`Arena::step_tick`] (same slice `step_tick` returned).
///
/// Cleared at the start of each tick and by [`Arena::remove_car`].
/// See [`ArenaEvent`] for variants.
#[must_use]
pub fn get_last_step_events(&self) -> &[ArenaEvent] {
self.events.events()
}
/// Casts `N` rays against the arena (`None` on a miss).
///
/// Fixed-size in and out (no allocation): pass `[RaycastQuery; N]`, get
/// back the hit (if any) for each query in the same order. Rays run 4 at
/// a time via SIMD, so multiples of 4 are fastest
/// (e.g. `let [hit] = arena.cast_rays([query]);`).
///
/// Short rays use the broadphase grid; rays longer than one grid cell
/// (`ArenaConfig::max_aabb_len`, scaled by the memory-weight mode) fall
/// back to testing every body, so any length works. Coordinates are in
/// uu, like the rest of the API. A ray that starts inside a sphere does
/// not report the sphere's exit point as a hit.
///
/// A query with `include_dynamics: false` ignores cars and the ball
/// (a dynamic body hiding a wall reports a miss — split the batch if the
/// static hit behind it matters).
///
/// ```no_run
/// # use rocketsim::{Arena, GameMode, RaycastQuery, init_from_default};
/// # init_from_default(true).unwrap();
/// # let arena = Arena::new(GameMode::Soccar);
/// # let from = arena.get_ball_state().pos;
/// # let to = from - glam::Vec3A::new(0., 0., 300.);
/// let [hit] = arena.cast_rays([RaycastQuery {
/// from,
/// to,
/// include_dynamics: false,
/// }]);
/// if let Some(hit) = hit {
/// assert!(hit.hit_point.z >= 0.0);
/// }
/// ```
#[must_use]
pub fn cast_rays<const N: usize>(
&self,
ray_queries: [RaycastQuery; N],
) -> [Option<RaycastHitInfo>; N] {
// Grid cell size mirrors `new_with_config` (there in uu, here in BT).
let cell_size_uu = match self.config.mem_weight_mode {
ArenaMemWeightMode::Light => (self.config.max_pos - self.config.min_pos).max_element(),
ArenaMemWeightMode::Balanced => self.config.max_aabb_len * 3.0,
ArenaMemWeightMode::Heavy => self.config.max_aabb_len,
};
let cell_size_sq = (cell_size_uu * UU_TO_BT) * (cell_size_uu * UU_TO_BT);
let mut results = [None; N];
for (chunk_idx, query_batch) in ray_queries.chunks(4).enumerate() {
let (mut froms, mut tos) = ([Vec3A::ZERO; 4], [Vec3A::ZERO; 4]);
for (i, query) in query_batch.iter().enumerate() {
froms[i] = query.from * UU_TO_BT;
tos[i] = query.to * UU_TO_BT;
}
let static_only = query_batch.iter().all(|q| !q.include_dynamics);
let mut callback = ClosestQuadRayResultCallback::new(&froms, &tos, None);
if static_only {
callback.base.collision_filter_mask = CollisionFilterGroups::Static as u8;
}
let is_long =
(0..query_batch.len()).any(|i| froms[i].distance_squared(tos[i]) >= cell_size_sq);
if is_long {
// Global fallback: no grid limit, test every body directly.
for body in self.bullet_world.bodies() {
if static_only && !body.is_static_obj() {
continue;
}
CollisionWorld::quad_ray_test(
&froms,
&tos,
body,
body.world_array_idx,
&mut callback,
);
}
} else {
self.bullet_world.ray_test(&froms, &tos, &mut callback);
}
for i in 0..query_batch.len() {
let hit_obj_idx = callback.base.collision_obj_idx[i];
let hit_info = match hit_obj_idx {
Some(obj_idx)
if !query_batch[i].include_dynamics
&& !self.bullet_world.bodies()[obj_idx].is_static_obj() =>
{
None
}
Some(obj_idx) => Some(RaycastHitInfo {
hit_point: callback.hit_point_world[i] * BT_TO_UU,
hit_normal: callback.hit_normal_world[i],
hit_fraction: callback.base.closest_hit_fraction[i],
user_info: self.bullet_world.bodies()[obj_idx].user_idx,
}),
_ => None,
};
results[chunk_idx * 4 + i] = hit_info;
}
}
results
}
/// Overlap test: would an object here collide with anything?
///
/// Pass `Some(body_config)` to test a car hitbox, `None` to test the ball
/// (built from the arena's game mode and mutators, so Snowday pucks
/// work). Set `include_dynamics` to also test against cars and the ball;
/// otherwise only static arena geometry (walls, floor, ceiling) is tested.
/// Useful for spawn-point checks and teleport validation without stepping
/// the sim.
///
/// Cars are tested by hitbox only — wheels and suspension are ignored, so
/// a car at normal rest height (~17 uu) does *not* touch the floor. A
/// `false` result means "no contact at this transform", not "the path
/// here is clear" — use [`Arena::cast_rays`] for swept queries.
///
/// ```no_run
/// # use rocketsim::{Arena, CarBodyConfig, GameMode, init_from_default};
/// # init_from_default(true).unwrap();
/// # let arena = Arena::new(GameMode::Soccar);
/// # let mut phys = arena.get_ball_state().phys;
/// # phys.pos.z = 3000.0;
/// // Mid-air ball: no overlap.
/// assert!(!arena.test_collision(phys, None, false));
/// // Same spot with a car hitbox (Octane is ~39 uu tall): still clear.
/// assert!(!arena.test_collision(phys, Some(CarBodyConfig::OCTANE), false));
/// ```
#[must_use]
pub fn test_collision(
&self,
phys: PhysState,
car_config: Option<CarBodyConfig>,
include_dynamics: bool,
) -> bool {
let game_mode = self.config.game_mode;
let pos_bt = phys.pos * UU_TO_BT;
let world_trans = Affine3A {
matrix3: phys.rot_mat,
translation: pos_bt,
};
let (query_shape, query_aabb) = if let Some(config) = car_config {
let box_shape = BoxShape::new(config.hitbox_size * UU_TO_BT * 0.5);
let hitbox_offset = Affine3A {
matrix3: Mat3A::IDENTITY,
translation: config.hitbox_pos_offset * UU_TO_BT,
};
let compound_shape = CompoundShape::new(box_shape, hitbox_offset);
let aabb = compound_shape.get_aabb(&world_trans);
(CollisionShapes::Compound(compound_shape), aabb)
} else {
let (shape, _) = Ball::make_ball_collision_shape(game_mode, &self.config.mutators);
let aabb = shape.get_aabb(&world_trans);
(shape, aabb)
};
// Query AABB is in Bullet units, so convert the arena bounds too.
// Statics-only: anything outside the arena can't hit. With dynamics,
// a car or the ball could be out of bounds, so test them anyway.
if !include_dynamics {
let arena_aabb = Aabb::new(
self.config.min_pos * UU_TO_BT,
self.config.max_pos * UU_TO_BT,
);
if !arena_aabb.intersects(&query_aabb) {
return false;
}
}
let mut rb_info = RigidBodyConstructionInfo::new(0.0, query_shape);
rb_info.start_world_trans = world_trans;
let mut query_body = RigidBody::new(rb_info);
query_body.world_array_idx = usize::MAX;
let mut callback = NopContactAddedCallback;
for body in self.bullet_world.bodies() {
if !include_dynamics && !body.is_static_obj() {
continue;
}
let body_aabb = body.get_collision_shape().get_aabb(body.get_world_trans());
if !query_aabb.intersects(&body_aabb) {
continue;
}
let mut out = None;
CollisionDispatcher::process_collision(&query_body, body, &mut callback, &mut out);
if out.is_some() {
return true;
}
}
false
}
/// Returns `true` when a [`Vis`] hook is registered.
pub fn is_vis_enabled(&self) -> bool {
self.vis.is_some()
}
}
/// A no-op contact callback used when only checking for collision existence.
struct NopContactAddedCallback;
impl ContactAddedCallback for NopContactAddedCallback {
fn callback(
&mut self,
_contact_point: &mut ManifoldPoint,
_body_a: &RigidBody,
_body_b: &RigidBody,
_idx: Option<usize>,
) {
}
}
/// Keep a vector whose squared length is already 1 bit-exact,
/// and use a zero vector below the small guard.
fn normalize_unless_one(v: Vec3A) -> Vec3A {
let len_sq = v.length_squared();
if len_sq != 1.0 {
if len_sq < 1e-8 {
Vec3A::ZERO
} else {
v * (1.0 / len_sq.sqrt())
}
} else {
v
}
}
fn hitbox_center(state: &CarState, config: &CarBodyConfig) -> Vec3A {
let rot_mat = state.phys.rot_mat;
let offset = config.hitbox_pos_offset;
state.phys.pos + rot_mat.transpose_mul_vec3a(offset)
}
/// The victim's hitbox center direction is measured in the attacker's frame.
/// Each angle removes the other axis component scaled by 1/1.01 (1.01 when negative).
///
/// Pitch is the angle off the forward/up plane;
/// yaw is the angle off the forward/right plane.
/// The caller supplies both limits so the bump and demo gates cannot drift apart.
fn is_within_forward_cone(
attacker: &CarState,
attacker_config: &CarBodyConfig,
victim: &CarState,
victim_config: &CarBodyConfig,
reverse: bool,
max_yaw_deg: f32,
max_pitch_deg: f32,
) -> bool {
let fwd = attacker.phys.get_forward_dir();
let delta = normalize_unless_one(
hitbox_center(victim, victim_config) - hitbox_center(attacker, attacker_config),
);
let fwd = if reverse { -fwd } else { fwd };
let angle_deg = |axis: Vec3A| {
let mut k = delta.dot(axis);
k = if k >= 0.0 { k / 1.01 } else { k * 1.01 };
let projected = normalize_unless_one(delta - axis * k);
fwd.dot(projected).clamp(-1.0, 1.0).acos() * 57.29578
};
// Pitch first: the PR helper rejects on pitch before it reads yaw.
if angle_deg(attacker.phys.get_right_dir()) > max_pitch_deg {
return false;
}
angle_deg(attacker.phys.get_up_dir()) <= max_yaw_deg
}
/// Result of the same-tick demolition gate for one contact direction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DemoGate {
/// Neither car is demolished. The contact may demolish or bump.
Normal,
/// The contact must be ignored.
Skip,
/// The attacker was demolished earlier in this tick by this victim. It may
/// still demolish the victim, but it must not bump it.
DemoOnly,
}
impl DemoGate {
/// Only an undemolished pair may bump.
const fn may_bump(self) -> bool {
matches!(self, Self::Normal)
}
}
/// The same-tick demolition gate.
fn demo_gate(
attacker_demoed: bool,
victim_demoed: bool,
attacker_demoed_by_victim_this_tick: bool,
) -> DemoGate {
if !(attacker_demoed || victim_demoed) {
DemoGate::Normal
} else if victim_demoed || !attacker_demoed_by_victim_this_tick {
DemoGate::Skip
} else {
DemoGate::DemoOnly
}
}
/// Integrate a car pose over `t` seconds with a constant velocity and
/// angular velocity.
fn integrate_pose(state: &mut CarState, vel: Vec3A, t: f32) {
state.phys.pos += vel * t;
let ang_vel = state.phys.ang_vel;
let ang_speed = ang_vel.length();
let theta = ang_speed * t;
if ang_speed > 0.0 && theta != 0.0 {
let axis = ang_vel / ang_speed;
let c = theta.cos();
let s = theta.sin();
let rot = |x: Vec3A| x * c + axis.cross(x) * s + axis * (axis.dot(x) * (1.0 - c));
let rot_mat = state.phys.rot_mat;
state.phys.rot_mat = Mat3A::from_cols(
rot(rot_mat.x_axis),
rot(rot_mat.y_axis),
rot(rot_mat.z_axis),
);
}
}
/// Separating-axis depth of two oriented hitboxes, in uu.
/// Positive values are separated;
/// the depth is the largest gap over the 15 candidate axes.
fn hitbox_separation(
a: &CarState,
a_config: &CarBodyConfig,
b: &CarState,
b_config: &CarBodyConfig,
) -> f32 {
let a_rot = a.phys.rot_mat;
let b_rot = b.phys.rot_mat;
let a_half = a_config.hitbox_size * 0.5;
let b_half = b_config.hitbox_size * 0.5;
let a_center = a.phys.pos + a_rot * a_config.hitbox_pos_offset;
let b_center = b.phys.pos + b_rot * b_config.hitbox_pos_offset;
let delta = b_center - a_center;
let mut best = -1e30f32;
let mut test = |axis: Vec3A| {
// Reach of each box along `axis`:
// the row-dot projections onto its own axes,
// scaled by the half extents.
let a_reach = a_rot.transpose_mul_vec3a(axis).abs();
let b_reach = b_rot.transpose_mul_vec3a(axis).abs();
let mut depth = delta.dot(axis).abs();
for i in 0..3 {
depth -= a_reach[i] * a_half[i] + b_reach[i] * b_half[i];
}
best = best.max(depth);
};
let a_cols = [a_rot.x_axis, a_rot.y_axis, a_rot.z_axis];
let b_cols = [b_rot.x_axis, b_rot.y_axis, b_rot.z_axis];
for col in a_cols.into_iter().chain(b_cols) {
test(col);
}
for a_col in a_cols {
for b_col in b_cols {
let axis = a_col.cross(b_col);
let len = axis.length();
if len > 1e-6 {
test(axis / len);
}
}
}
best
}
/// Replace both poses with the time-of-impact poses that the game uses for
/// the demolition cone.
///
/// Both hitboxes are swept from one tick before to one tick after their
/// start-of-tick poses. The hit is where they overlap by the allowed
/// penetration. With no hit, the start-of-tick poses stay.
fn get_time_of_impact_poses(
a: &mut CarState,
a_config: &CarBodyConfig,
a_vel: Vec3A,
b: &mut CarState,
b_config: &CarBodyConfig,
b_vel: Vec3A,
tick_time: f32,
) {
/// Allowed penetration 0.04 BT minus btContinuousConvexCollision's 0.001 BT.
const PENETRATION: f32 = 0.039 * 50.0;
let separation = |lambda: f32| {
let t = (2.0 * lambda - 1.0) * tick_time;
let mut ai = *a;
let mut bi = *b;
integrate_pose(&mut ai, a_vel, t);
integrate_pose(&mut bi, b_vel, t);
hitbox_separation(&ai, a_config, &bi, b_config) + PENETRATION
};
let lambda = if separation(0.0) <= 0.0 {
0.0
} else if separation(1.0) > 0.0 {
return;
} else {
let mut lo = 0.0f32;
let mut hi = 1.0f32;
for _ in 0..24 {
let mid = (lo + hi) * 0.5;
if separation(mid) > 0.0 {
lo = mid;
} else {
hi = mid;
}
}
hi
};
let t = (2.0 * lambda - 1.0) * tick_time;
integrate_pose(a, a_vel, t);
integrate_pose(b, b_vel, t);
}
fn should_demolish(
attacker: &CarState,
attacker_config: &CarBodyConfig,
victim: &CarState,
victim_config: &CarBodyConfig,
tick_time: f32,
) -> bool {
use consts::car::{demo, supersonic};
if !attacker.is_supersonic {
return false;
}
let start_vel = attacker.phys.vel;
let forward_speed = start_vel.dot(attacker.phys.get_forward_dir());
if forward_speed.abs() < supersonic::MAINTAIN_MIN_SPEED {
return false;
}
let mut attacker_pose = *attacker;
let mut victim_pose = *victim;
get_time_of_impact_poses(
&mut attacker_pose,
attacker_config,
start_vel,
&mut victim_pose,
victim_config,
victim.phys.vel,
tick_time,
);
is_within_forward_cone(
&attacker_pose,
attacker_config,
&victim_pose,
victim_config,
forward_speed < 0.0,
demo::YAW_LIMIT_DEG,
demo::PITCH_LIMIT_DEG,
)
}
impl Arena {
fn on_ball_tile_collision(&mut self, tile_idx: usize) {
self.ball.on_dropshot_tile_collision(
self.tile_states.as_mut().unwrap(),
tile_idx,
self.tick_count,
);
}
fn on_ball_world_collision(&mut self, manifold_point: &ManifoldPoint, rb_index: usize) {
self.on_ball_world_collision_parts(
rb_index,
manifold_point.pos_world_on_b,
manifold_point.normal_world_on_b,
);
}
fn on_ball_world_collision_parts(
&mut self,
rb_index: usize,
contact_point: Vec3A,
contact_normal: Vec3A,
) {
let contact_point = contact_point * BT_TO_UU;
let rb = &mut self.bullet_world.bodies_mut()[rb_index];
self.ball
.on_world_hit(rb, self.config.game_mode, contact_normal);
self.events.push(BallHitWorld(BallHitWorldEvent {
contact_point,
contact_normal,
}));
}
fn on_car_ball_collision(
&mut self,
car_idx: usize,
manifold_point: &ManifoldPoint,
ball_is_body_a: bool,
) {
let ball_rb = &mut self.bullet_world.bodies_mut()[self.ball.rigid_body_idx];
let ball_lin_vel_before = ball_rb.lin_vel;
self.ball.on_hit(
&mut self.cars[car_idx],
self.config.game_mode,
&self.config.mutators,
self.tick_count,
ball_rb,
);
let contact_point = if ball_is_body_a {
manifold_point.pos_world_on_a
} else {
manifold_point.pos_world_on_b
} * BT_TO_UU;
let extra_hit_vel = (ball_rb.lin_vel - ball_lin_vel_before) * BT_TO_UU;
self.events.push(ArenaEvent::CarHitBall(CarHitBallEvent {
car_idx,
contact_point,
extra_hit_vel,
}));
}
fn on_car_world_collision(&mut self, car_idx: usize, manifold_point: &ManifoldPoint) {
self.events.push(ArenaEvent::CarHitWorld(CarHitWorldEvent {
car_idx,
contact_point: manifold_point.pos_world_on_b * BT_TO_UU,
contact_normal: manifold_point.normal_world_on_b,
}));
self.cars[car_idx].state.cache.world_contact_normal =
Some(manifold_point.normal_world_on_b);
}
/// Build the game's car world-contact normal for this tick.
///
/// Per world object, sum the contact normals and normalize the sum. Then
/// sum the object normals and normalize the result. A car whose sums are
/// all unusable keeps its last contact normal. No object count limit
/// applies.
fn update_world_contact_normal(&mut self) {
let car_count = self.cars.len();
for car_idx in 0..car_count {
let combined = combine_world_contact_normal_sums(
self.contact_tracker
.world_contact_normal_groups()
.iter()
.filter(|group| group.car_idx == car_idx)
.map(|group| group.sum),
);
if let Some(normal) = combined {
self.cars[car_idx].state.cache.world_contact_normal = Some(normal);
}
}
}
fn on_car_car_collision(
&mut self,
car_1_idx: usize,
car_2_idx: usize,
manifold_point: &ManifoldPoint,
) {
let Ok(both_cars) = self.cars.get_disjoint_mut([car_1_idx, car_2_idx]) else {
panic!(
"on_car_car_collision() called with invalid or duplicate car indices: {car_1_idx}, {car_2_idx}"
);
};
let (mut attacker, mut victim) = both_cars.into();
// Test collision both ways
for is_swapped in [false, true] {
let mut attacker_idx = car_1_idx;
let mut victim_idx = car_2_idx;
if is_swapped {
mem::swap(&mut attacker, &mut victim);
mem::swap(&mut attacker_idx, &mut victim_idx);
}
let attacker_state = &attacker.state;
let victim_state = &victim.state;
// A car demolished by the other car earlier in this tick can still demolish it,
// but not bump it.
let gate = demo_gate(
attacker_state.is_demoed,
victim_state.is_demoed,
attacker.state.cache.demo_tick == self.tick_count
&& attacker.state.cache.demoer_idx == Some(victim_idx),
);
if gate == DemoGate::Skip {
continue;
}
let delta_pos = victim_state.phys.pos - attacker_state.phys.pos;
if attacker_state.phys.vel.dot(delta_pos) < 0.0 {
// Moving away from the other car
continue;
}
let vel_dir = attacker_state.phys.vel.normalize_or_zero();
let dir_to_victim = delta_pos.normalize_or_zero();
let speed_towards_other_car = attacker_state.phys.vel.dot(dir_to_victim);
let other_car_away_speed = victim_state.phys.vel.dot(vel_dir);
if speed_towards_other_car <= other_car_away_speed {
// Going towards other car slower than they're going away
continue;
}
// The game bumps only when the other car's hitbox center is in the
// bumper's 70 deg forward cone.
let bumper = is_within_forward_cone(
attacker_state,
&attacker.info.config,
victim_state,
&victim.info.config,
false,
consts::car::bump::YAW_LIMIT_DEG,
consts::car::bump::PITCH_LIMIT_DEG,
);
// Demolitions are checked before the bump cooldown.
let mut is_demo = match self.config.mutators.demo_mode {
DemoMode::OnContact => true,
DemoMode::Disabled => false,
DemoMode::Normal => should_demolish(
attacker_state,
&attacker.info.config,
victim_state,
&victim.info.config,
TICK_TIME,
),
};
if is_demo && !self.config.mutators.enable_team_demos {
is_demo = attacker.team != victim.team;
}
let contact_point = if is_swapped {
manifold_point.pos_world_on_b
} else {
manifold_point.pos_world_on_a
} * BT_TO_UU;
if is_demo {
victim.demolish(self.config.mutators.respawn_delay);
victim.state.cache.demo_tick = self.tick_count;
victim.state.cache.demoer_idx = Some(attacker_idx);
self.events.push(ArenaEvent::CarHitCar(CarHitCarEvent {
bumper_car_idx: attacker_idx,
victim_car_idx: victim_idx,
contact_point,
is_demo: true,
}));
continue;
}
if !gate.may_bump() {
continue;
}
if attacker_state.bump_cooldown_timer > 0.0
&& attacker_state
.bump_cooldown_victim
.is_none_or(|v| v == victim_idx)
{
// In cooldown for this victim pair (None = all victims)
continue;
}
if bumper {
use consts::curves;
let ground_hit = victim_state.cache.is_on_ground;
let attacker_speed = attacker_state.phys.vel.length().min(2200.0);
let bump_impulse = if ground_hit {
// Grounded victim: Ground and Z curves on total attacker speed.
let base_scale = curves::BUMP_VEL_AMOUNT_GROUND.get_output(attacker_speed);
let upward_force = curves::BUMP_UPWARD_VEL_AMOUNT.get_output(attacker_speed);
let hit_up_dir = victim_state.phys.rot_mat.z_axis;
(vel_dir * base_scale) + (hit_up_dir * upward_force)
} else {
// Airborne victim: Air curve on total attacker speed; no up term.
vel_dir * curves::BUMP_VEL_AMOUNT_AIR.get_output(attacker_speed)
};
victim.vel_impulse_cache +=
bump_impulse * self.config.mutators.bump_force_scale * UU_TO_BT;
}
// The game's next bump needs the physics time strictly past the cooldown: half a tick longer.
// It also starts without a bump.
attacker.state.bump_cooldown_timer =
self.config.mutators.bump_cooldown_time + TICK_TIME * 0.5;
attacker.state.bump_cooldown_victim = Some(victim_idx);
if bumper {
self.events.push(ArenaEvent::CarHitCar(CarHitCarEvent {
bumper_car_idx: attacker_idx,
victim_car_idx: victim_idx,
contact_point,
is_demo: false,
}));
}
}
}
}
#[cfg(test)]
mod bump_demo_tests {
use std::sync::Once;
use super::*;
fn ensure_init() {
static INIT: Once = Once::new();
INIT.call_once(|| {
crate::init(
concat!(env!("CARGO_MANIFEST_DIR"), "/../collision_meshes"),
true,
)
.expect("load collision meshes");
});
}
fn tilted_arena() -> (Arena, usize) {
let mut arena = Arena::new(GameMode::Soccar);
let car = arena.add_car(Team::Blue, CarBodyConfig::OCTANE);
let mut state = CarState::DEFAULT;
state.phys.pos = Vec3A::new(200.0, 0.0, 35.0);
state.phys.rot_mat = Mat3A::from_rotation_x(50.0f32.to_radians());
state.phys.vel = Vec3A::ZERO;
state.phys.ang_vel = Vec3A::ZERO;
arena.set_car_state_full(car, state);
arena.refresh_car_contacts(car);
(arena, car)
}
/// A full snapshot must restore the cached world-wheel count. The count is
/// populated by a contact refresh, then changed before the restore. The
/// next tick must match an arena that never changed it.
#[test]
fn full_snapshot_restores_the_world_wheel_count() {
ensure_init();
let (mut arena, car) = tilted_arena();
let (mut control, control_car) = tilted_arena();
assert_eq!(arena.cars[car].state.cache.world_wheels_prev, 2);
let snapshot = *arena.get_car_state(car);
arena.cars[car].state.cache.world_wheels_prev = 0;
arena.set_car_state_full(car, snapshot);
let controls = CarControls::DEFAULT.with_throttle(1.0);
for (arena, car) in [(&mut arena, car), (&mut control, control_car)] {
arena.set_car_controls(car, controls);
arena.edit_car_state_full(car, |state| state.set_prev_controls(controls));
}
arena.step_tick();
control.step_tick();
assert_eq!(
arena.get_car_state(car).phys,
control.get_car_state(control_car).phys
);
}
fn car_state(pos: Vec3A, rot_mat: Mat3A, vel: Vec3A) -> CarState {
CarState::from(CarCore::grounded(
PhysState {
pos,
rot_mat,
vel,
ang_vel: Vec3A::ZERO,
},
0.0,
))
}
#[test]
fn hitbox_center_uses_the_row_dot_convention() {
let config = CarBodyConfig::OCTANE;
let yaw_90 = Mat3A::from_euler(EulerRot::ZYX, PI / 2.0, 0.0, 0.0);
let state = car_state(Vec3A::new(1.0, 2.0, 3.0), yaw_90, Vec3A::ZERO);
// Yaw 90: forward = +Y, right = -X, up = +Z. The PR transform is
// (offset . forward, offset . right, offset . up), not the direct
// local-to-world product.
let expected = Vec3A::new(
1.0,
2.0 - config.hitbox_pos_offset.x,
3.0 + config.hitbox_pos_offset.z,
);
assert!((hitbox_center(&state, &config) - expected).length() < 1e-4);
}
#[test]
fn forward_cone_uses_the_pr_yaw_and_pitch_limits() {
let config = CarBodyConfig::OCTANE;
let attacker = car_state(Vec3A::ZERO, Mat3A::IDENTITY, Vec3A::new(2300.0, 0.0, 0.0));
let yaw_46 = 46.0f32.to_radians();
let victim = car_state(
Vec3A::new(200.0 * yaw_46.cos(), 200.0 * yaw_46.sin(), 0.0),
Mat3A::IDENTITY,
Vec3A::ZERO,
);
assert!(is_within_forward_cone(
&attacker,
&config,
&victim,
&config,
false,
consts::car::bump::YAW_LIMIT_DEG,
consts::car::bump::PITCH_LIMIT_DEG
));
assert!(!is_within_forward_cone(
&attacker,
&config,
&victim,
&config,
false,
consts::car::demo::YAW_LIMIT_DEG,
consts::car::demo::PITCH_LIMIT_DEG
));
let pitch_40 = 40.0f32.to_radians();
let above = car_state(
Vec3A::new(200.0 * pitch_40.cos(), 0.0, 200.0 * pitch_40.sin()),
Mat3A::IDENTITY,
Vec3A::ZERO,
);
assert!(!is_within_forward_cone(
&attacker,
&config,
&above,
&config,
false,
consts::car::bump::YAW_LIMIT_DEG,
consts::car::bump::PITCH_LIMIT_DEG
));
}
#[test]
fn forward_cone_uses_both_hitbox_offsets() {
let mut flat = CarBodyConfig::OCTANE;
flat.hitbox_pos_offset = Vec3A::ZERO;
let mut shifted = CarBodyConfig::OCTANE;
shifted.hitbox_pos_offset = Vec3A::new(0.0, 0.0, -25.0);
let attacker = car_state(Vec3A::ZERO, Mat3A::IDENTITY, Vec3A::new(2300.0, 0.0, 0.0));
// Raw position pitch is 37.95 degrees: outside the 36.87 pitch limit.
let victim = car_state(Vec3A::new(100.0, 0.0, 78.0), Mat3A::IDENTITY, Vec3A::ZERO);
assert!(!is_within_forward_cone(
&attacker,
&flat,
&victim,
&flat,
false,
consts::car::bump::YAW_LIMIT_DEG,
consts::car::bump::PITCH_LIMIT_DEG
));
// The victim offset lowers its center by 25 uu, so the center pitch
// is about 27.95 degrees: inside the limit.
assert!(is_within_forward_cone(
&attacker,
&flat,
&victim,
&shifted,
false,
consts::car::bump::YAW_LIMIT_DEG,
consts::car::bump::PITCH_LIMIT_DEG
));
}
#[test]
fn same_tick_demo_gate_rejects_a_different_demoer_and_blocks_bumps() {
use DemoGate::{DemoOnly, Normal, Skip};
assert_eq!(demo_gate(false, false, false), Normal);
// A victim that is already demolished never takes a second demo.
assert_eq!(demo_gate(false, true, false), Skip);
assert_eq!(demo_gate(false, true, true), Skip);
// A different demoer in the same tick is rejected.
assert_eq!(demo_gate(true, false, false), Skip);
// Both cars already demolished: skip, even with the same demoer.
assert_eq!(demo_gate(true, true, true), Skip);
// The same demoer can still demolish the car that demolished it, but
// that contact may not bump.
assert_eq!(demo_gate(true, false, true), DemoOnly);
assert!(Normal.may_bump());
assert!(!DemoOnly.may_bump());
assert!(!Skip.may_bump());
}
#[test]
fn time_of_impact_moves_both_cars_toward_the_overlap() {
let config = CarBodyConfig::OCTANE;
let a_vel = Vec3A::new(2300.0, 0.0, 0.0);
let b_vel = Vec3A::new(-2300.0, 0.0, 0.0);
let mut a = car_state(Vec3A::ZERO, Mat3A::IDENTITY, a_vel);
let mut b = car_state(Vec3A::new(120.0, 0.0, 0.0), Mat3A::IDENTITY, b_vel);
get_time_of_impact_poses(&mut a, &config, a_vel, &mut b, &config, b_vel, TICK_TIME);
assert!(a.phys.pos.x > 0.0);
assert!(b.phys.pos.x < 120.0);
// Both cars stop at the allowed penetration, not at the sweep end.
let gap = b.phys.pos.x - a.phys.pos.x;
assert!(gap < 120.0 && gap > 100.0, "gap {gap}");
}
#[test]
fn should_demolish_needs_supersonic_speed_and_cone() {
let config = CarBodyConfig::OCTANE;
let front = car_state(Vec3A::new(120.0, 0.0, 0.0), Mat3A::IDENTITY, Vec3A::ZERO);
let mut attacker = car_state(Vec3A::ZERO, Mat3A::IDENTITY, Vec3A::new(2300.0, 0.0, 0.0));
attacker.is_supersonic = true;
assert!(should_demolish(
&attacker, &config, &front, &config, TICK_TIME
));
attacker.is_supersonic = false;
assert!(!should_demolish(
&attacker, &config, &front, &config, TICK_TIME
));
attacker.is_supersonic = true;
attacker.phys.vel = Vec3A::new(2000.0, 0.0, 0.0);
assert!(!should_demolish(
&attacker, &config, &front, &config, TICK_TIME
));
// Reverse uses the forward speed sign and the reversed cone.
let behind = car_state(Vec3A::new(-120.0, 0.0, 0.0), Mat3A::IDENTITY, Vec3A::ZERO);
attacker.phys.vel = Vec3A::new(-2300.0, 0.0, 0.0);
assert!(should_demolish(
&attacker, &config, &behind, &config, TICK_TIME
));
assert!(!should_demolish(
&attacker, &config, &front, &config, TICK_TIME
));
}
}