concinnity-core 0.18.65

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
// The rigid-body simulation driver. An internal system (not a declarable
// asset): a schedule constructs one when the world declares a `PhysicsConfig`,
// a `RigidBody`, a `PropBody`, or a `TriggerVolume`, reading the optional
// `PhysicsConfig` for the floor / terrain.

use alloc::boxed::Box;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

use concinnity_physics::{
    BodyHandle, CharacterCapsule, CharacterMoveInput, ColliderShape, ContactHit, GRAVITY,
    PhysicsBudget, SensorCrossing, SimConfig, Simulation,
};

use crate::components::{
    BodyDynamics, Camera3D, Collider, ContactEvent, Held, PhysicsConfig, PhysicsJoint, Pickup,
    RigidBody, Transform, TriggerFilter, TriggerVolume, VolumeEvent,
};
use crate::ecs::asset_id::AssetId;
use crate::ecs::{
    Entity, EntityByName, EventCursor, MenuActive, PipelineContext, ScheduleMode, SimTiming,
    StepResult, System, WorldPhysicsBudget,
};
use crate::math::{cos, sin, sqrt};

use super::budget::DriverCapacities;
use super::contacts::{ContactBatch, ContactGate};
use super::convert::{collider_shape, joint_spec};
use super::fanout::{PhysicsFanout, SerialFanout};
use super::index::SortedMap;
use super::interp::PointInterp;
use super::layers::{LAYER_CHARACTER, LAYER_PROP, LAYER_TRIGGER, LAYER_WORLD, LayerTable};
use super::props::{PropBodies, PropCollSnap, STATIC_FRICTION};
use super::terrain::{TerrainParams, build_heightfield, build_heightfield_collider};

// Reach distance for picking up a Prop, in world units.
const PICKUP_REACH: f32 = 3.0;
// Minimum facing dot product (~60-degree cone) for a pickup.
const PICKUP_MIN_DOT: f32 = 0.5;
// Distance ahead of the camera a carried prop hovers.
const HOLD_DISTANCE: f32 = 1.8;
// Drop of a carried prop below eye level.
const HOLD_DROP: f32 = 0.35;
// Launch speed applied to a prop when it is dropped/thrown.
const THROW_SPEED: f32 = 6.0;

/// Rigid-body simulation behavior. Constructed internally by `World::start`
/// from the world's `PhysicsConfig`; never a declarable asset.
///
/// [`new`](PhysicsSystem::new) steps the simulation on the calling thread; a
/// host lends it threads through [`with_fanout`](PhysicsSystem::with_fanout).
#[derive(Debug)]
pub struct PhysicsSystem {
    // Camera eye Y at spawn; the flat-floor fallback derives nothing from it,
    // but it seeds a sensible fallback camera position.
    floor_y: f32,
    // Terrain parameters. None when terrain_subdivisions == 0 (flat floor).
    terrain: Option<TerrainParams>,
    // Reference to a `ProceduralMesh` asset whose `heightfield` generator
    // drives the physics collider. Resolved against the live component list
    // at `init`. Takes precedence over `terrain` when both are set.
    terrain_mesh: Option<AssetId>,
    // World-space Y offset applied to whichever terrain source is active
    // (procedural noise or heightfield mesh). Matches the rendering Prop's
    // `position[1]`.
    terrain_offset_y: f32,
    // The simulation, built in init() and sized from the world's budget.
    world: Option<Simulation>,
    // The player capsule, when the world has a Camera3D + RigidBody.
    player: Option<PlayerPhysics>,
    // One capsule per root-motion character rig (see `super::rig`).
    rigs: Vec<super::rig::RigPhysics>,
    // One entry per Prop that carries a collider.
    props: PropBodies,
    // Reader cursor over the `RootMotionEvent` event queue.
    root_cursor: EventCursor,
    // Scratch for the per-tick scan for freshly spawned collider-bearing
    // entities, refilled every step.
    new_props: Vec<(Entity, PropCollSnap)>,
    // Per-step drain scratch, reused so the event handoffs never reallocate.
    motion_scratch: Vec<crate::components::RootMotionEvent>,
    contact_scratch: Vec<ContactHit>,
    sensor_scratch: Vec<SensorCrossing>,
    // Index into `props` of the prop currently being carried.
    held: Option<usize>,
    // Sensor tag -> the TriggerVolume it senses for, with its filter. Tags are
    // the volume's AssetId, stamped into the sensor collider's user_data.
    sensor_filters: SortedMap<u64, (AssetId, TriggerFilter)>,
    // Layer-name resolution and the collide matrix from the PhysicsConfig.
    layers: LayerTable,
    // Minimum contact impulse for publishing a ContactEvent.
    contact_min_impulse: f32,
    // Strongest contact per body pair across the frame's ticks.
    contact_batch: ContactBatch,
    // Per-pair refractory so sustained contact reports once per impact.
    contact_gate: ContactGate,
    // Bodies the world authored room for beyond the ones it declares.
    spawn_headroom: u32,
    // Hard ceiling on live bodies: the simulation's whole reservation, so a
    // spawn past it is refused rather than silently declined by a full pool.
    // Resolved at init, along with the reservation itself.
    body_cap: u32,
    // Where a step's independent work runs. `SerialFanout` until a host lends
    // its own.
    fanout: Box<dyn PhysicsFanout>,
}

// Runtime physics state for the player camera capsule.
#[derive(Debug)]
struct PlayerPhysics {
    handle: BodyHandle,
    // The capsule each tick's move is resolved against. Its dimensions come
    // from the RigidBody at init and never change afterwards.
    shape: CharacterCapsule,
    // Camera eye Y minus capsule-centre Y.
    eye_offset: f32,
    // False for a free-flying camera (no RigidBody): no gravity, no jump.
    has_gravity: bool,
    gravity_scale: f32,
    jump_height: f32,
    // Current vertical velocity (world units/second).
    vy: f32,
    // Whether the capsule rested on a surface last tick.
    grounded: bool,
    // Authoritative simulated capsule centre with its render blend snapshots.
    center: PointInterp,
    // The eye position written back last frame. A Camera3D position that
    // differs was moved externally (free-fly, a teleport) and is adopted with
    // no blend across the jump.
    written_eye: Option<[f32; 3]>,
}

impl PhysicsSystem {
    // Number of rigid bodies the physics world holds. Test-only observable for
    // the body-reaping path.
    #[cfg(test)]
    fn physics_body_count(&self) -> usize {
        self.world.as_ref().map_or(0, |w| w.body_count())
    }

    // Number of colliders the physics world holds. Test-only observable for
    // the spawn/despawn leak checks.
    #[cfg(test)]
    fn physics_collider_count(&self) -> usize {
        self.world.as_ref().map_or(0, |w| w.collider_count())
    }

    /// Build the simulation from the world's `PhysicsConfig` (floor / terrain).
    /// Bodies and colliders are added from the ECS in [`System::init`].
    pub fn new(config: PhysicsConfig) -> Self {
        let terrain = if config.terrain_subdivisions > 0 {
            Some(TerrainParams {
                half_width: config.terrain_half_width,
                half_depth: config.terrain_half_depth,
                subdivisions: config.terrain_subdivisions,
                amplitude: config.terrain_amplitude,
                offset_y: config.terrain_offset_y,
            })
        } else {
            None
        };
        Self {
            floor_y: config.floor_y,
            terrain,
            terrain_mesh: config.terrain_mesh,
            terrain_offset_y: config.terrain_offset_y,
            world: None,
            player: None,
            rigs: Vec::new(),
            props: PropBodies::default(),
            root_cursor: EventCursor::default(),
            new_props: Vec::new(),
            motion_scratch: Vec::new(),
            contact_scratch: Vec::new(),
            sensor_scratch: Vec::new(),
            held: None,
            sensor_filters: SortedMap::default(),
            layers: LayerTable::new(&config),
            contact_min_impulse: config.contact_min_impulse.max(0.0),
            contact_batch: ContactBatch::default(),
            contact_gate: ContactGate::default(),
            spawn_headroom: config.spawn_headroom,
            body_cap: 0,
            fanout: Box::new(SerialFanout),
        }
    }

    /// Run the step's independent work through `fanout` rather than on the
    /// calling thread. What a step hands out and the order its results load
    /// back in are the simulation's; a fan-out decides only where the work
    /// runs, so this cannot change the state a tick lands on.
    pub fn with_fanout(mut self, fanout: Box<dyn PhysicsFanout>) -> Self {
        self.fanout = fanout;
        self
    }

    // The world's body budget: the record cook shipped, or, when no record
    // shipped, the same derivation over the loaded components with the
    // headroom its `PhysicsConfig` authored. Only a shipped record is checked
    // against the live world.
    //
    // The two headrooms can differ: a shipped one is already raised to cover
    // the spawners whose cadence bounds their population, while a directly
    // constructed World gets only what its config authored, since nothing
    // counted its spawners.
    //
    // Whichever it came from, the budget is the whole reservation: the
    // simulation is sized from it and never grows, so its cap is the ceiling
    // spawns are refused against.
    fn resolve_budget(&self, ctx: &PipelineContext) -> PhysicsBudget {
        let scan = super::budget::scan_counts(ctx);
        let Some(record) = ctx.resource::<WorldPhysicsBudget>().map(|b| b.0) else {
            tracing::debug!("PhysicsSystem: no shipped budget; reserving from the loaded world");
            return PhysicsBudget::derive(&scan, self.spawn_headroom);
        };
        let shipped = super::budget::budget_of(&record);
        debug_assert_eq!(
            shipped,
            PhysicsBudget::derive(&scan, record.spawn_headroom),
            "the shipped physics budget does not match the loaded world"
        );
        shipped
    }

    // Size every container the driver holds per body from the budget, once,
    // before anything is built.
    fn reserve(&mut self, budget: &PhysicsBudget) {
        let caps = DriverCapacities::derive(budget);
        self.props = PropBodies::with_capacity(&caps);
        self.rigs = Vec::with_capacity(caps.rigs);
        self.new_props = Vec::with_capacity(caps.new_props);
        self.motion_scratch = Vec::with_capacity(caps.root_motions);
        self.contact_scratch = Vec::with_capacity(caps.contacts);
        self.sensor_scratch = Vec::with_capacity(caps.sensor_crossings);
        self.contact_batch = ContactBatch::with_capacity(caps.contact_pairs);
        self.contact_gate = ContactGate::with_capacity(caps.contact_pairs);
        self.sensor_filters = SortedMap::with_capacity(caps.sensor_filters);
    }

    // Build one body per collider-bearing entity from its per-instance
    // components (Transform + Collider + optional BodyDynamics + the Pickup
    // tag), keying `body_handles` by AssetId (via the name index's inverse)
    // so the joint wiring resolves.
    fn build_prop_bodies(
        &mut self,
        ctx: &PipelineContext,
        world: &mut Simulation,
        body_handles: &mut BTreeMap<AssetId, BodyHandle>,
    ) {
        let entity_name: BTreeMap<Entity, AssetId> = ctx
            .resource::<EntityByName>()
            .map(|n| n.0.iter().map(|(&id, &e)| (e, id)).collect())
            .unwrap_or_default();
        let pickup: BTreeSet<Entity> = ctx.query_with_entity::<Pickup>().map(|(e, _)| e).collect();
        let dynamics: BTreeMap<Entity, BodyDynamics> = ctx
            .query_with_entity::<BodyDynamics>()
            .map(|(e, b)| (e, *b))
            .collect();
        let snaps: Vec<(Entity, PropCollSnap)> = ctx
            .join2::<Collider, Transform>()
            .map(|(entity, collider, transform)| {
                (
                    entity,
                    PropCollSnap {
                        shape: collider_shape(&collider.0, transform.scale),
                        layer: collider.0.layer.clone(),
                        position: transform.position,
                        rotation_deg: transform.rotation_deg,
                        pickup: pickup.contains(&entity),
                        dynamics: dynamics.get(&entity).copied(),
                    },
                )
            })
            .collect();

        for (entity, snap) in snaps {
            let Some(handle) = self.props.add(&self.layers, world, entity, snap) else {
                continue;
            };
            if let Some(&id) = entity_name.get(&entity) {
                body_handles.insert(id, handle);
            }
        }
    }
}

impl System for PhysicsSystem {
    fn init(&mut self, ctx: &mut PipelineContext) {
        // Before anything is built, and before the joint wiring below drains
        // the column the scan counts.
        let budget = self.resolve_budget(ctx);
        self.body_cap = budget.body_cap();
        self.reserve(&budget);

        // The simulation reserves the whole budget here, so nothing on the
        // step path allocates and a body past the reservation is refused
        // rather than grown into.
        let mut world = Simulation::new(
            SimConfig {
                gravity: GRAVITY,
                ..SimConfig::default()
            },
            budget.body_cap() as usize,
        );
        world.set_contact_min_impulse(self.contact_min_impulse, SimTiming::TICK_DT);
        // The step's per-worker scratch, reserved from the schedule this world
        // will run under. A serial schedule reserves one worker's worth, which
        // is what a simulation that is never lent threads keeps.
        world.reserve_workers(
            self.fanout
                .worker_count(ScheduleMode::current(ctx.resources)),
        );
        let world_mask = self.layers.mask(LAYER_WORLD);

        // floor: heightfield-mesh-driven, procedural noise, or flat slab
        let mut floor_built = false;
        if let Some(mesh_id) = self.terrain_mesh {
            let mesh_snap = ctx
                .query::<crate::components::ProceduralMesh>()
                .find(|m| m.asset_id == mesh_id)
                .cloned();
            match mesh_snap {
                Some(m) if m.generator == "heightfield" => {
                    match build_heightfield_collider(
                        &mut world,
                        &m,
                        self.terrain_offset_y,
                        world_mask,
                        ctx,
                    ) {
                        Ok(()) => floor_built = true,
                        Err(e) => tracing::warn!(
                            "physics: heightfield collider load failed ({}); falling back to flat slab",
                            e
                        ),
                    }
                }
                Some(m) => {
                    tracing::warn!(
                        "physics: terrain_mesh '{}' has generator '{}', expected 'heightfield'; falling back",
                        mesh_id,
                        m.generator
                    );
                }
                None => {
                    tracing::warn!(
                        "physics: terrain_mesh asset {} not found; falling back",
                        mesh_id
                    );
                }
            }
        }
        if !floor_built {
            let floor = if let Some(terrain) = self.terrain.clone() {
                build_heightfield(&mut world, &terrain, world_mask)
            } else {
                // A large thin slab whose top face sits at Y = 0.
                world.add_fixed(
                    &ColliderShape::Cuboid {
                        half_extents: [500.0, 5.0, 500.0],
                    },
                    [0.0, -5.0, 0.0],
                    [0.0; 3],
                    STATIC_FRICTION,
                    world_mask,
                )
            };
            if floor.is_none() {
                tracing::error!("physics: the world's reservation had no room for its floor");
            }
        }

        // Sensor regions: one fixed sensor body per TriggerVolume, tagged with
        // the volume's AssetId so step's crossing drain maps back to it.
        let trigger_mask = self.layers.mask(LAYER_TRIGGER);
        let volumes: Vec<TriggerVolume> = ctx.query::<TriggerVolume>().cloned().collect();
        for volume in &volumes {
            let shape = collider_shape(&volume.collider, [1.0; 3]);
            let tag = u64::from(volume.asset_id.0);
            if world
                .add_sensor(
                    &shape,
                    volume.position,
                    volume.rotation_deg,
                    tag,
                    trigger_mask,
                )
                .is_none()
            {
                continue;
            }
            self.sensor_filters
                .insert(tag, (volume.asset_id, volume.detects));
        }
        if !volumes.is_empty() {
            tracing::debug!("PhysicsSystem: {} trigger volume(s)", volumes.len());
        }

        // Prop name -> BodyHandle, populated alongside `self.prop_bodies`.
        // Joints resolve their `body_a`/`body_b` references through this map.
        let mut body_handles: BTreeMap<AssetId, BodyHandle> = BTreeMap::new();
        self.build_prop_bodies(ctx, &mut world, &mut body_handles);
        tracing::debug!(
            "PhysicsSystem: {} prop bodies ({} dynamic)",
            self.props.len(),
            self.props.dynamic_count(),
        );

        // joints
        // Each PhysicsJoint references one or two Props by AssetId. Cross-reference
        // validation already guarantees the Prop exists; here we additionally
        // require the Prop to own a collider (and therefore a body). A PhysicsJoint
        // with body_b empty anchors body_a to a hidden static body created on
        // demand at the world-space `anchor_b`.
        let joints: Vec<PhysicsJoint> = ctx.drain::<PhysicsJoint>();
        let mut wired = 0usize;
        for joint in joints {
            let Some(body_a_id) = joint.body_a else {
                tracing::warn!(
                    "PhysicsJoint '{}': body_a is required; skipping",
                    joint.asset_id
                );
                continue;
            };
            let Some(handle_a) = body_handles.get(&body_a_id).copied() else {
                tracing::warn!(
                    "PhysicsJoint '{}': body_a Prop has no collider; skipping",
                    joint.asset_id
                );
                continue;
            };
            let handle_b = if let Some(body_b_id) = joint.body_b {
                match body_handles.get(&body_b_id).copied() {
                    Some(h) => h,
                    None => {
                        tracing::warn!(
                            "PhysicsJoint '{}': body_b Prop has no collider; skipping",
                            joint.asset_id
                        );
                        continue;
                    }
                }
            } else {
                // Static world anchor at anchor_b. Sub-millimetre ball so it
                // takes effectively no space in the broad phase.
                let anchor = world.add_fixed(
                    &ColliderShape::Ball { radius: 0.001 },
                    joint.anchor_b,
                    [0.0; 3],
                    0.0,
                    world_mask,
                );
                match anchor {
                    Some(handle) => handle,
                    None => continue,
                }
            };
            // When body_b is the implicit world anchor, the anchor sits at the
            // origin of that hidden body, not at the authored offset.
            let anchor_b = if joint.body_b.is_some() {
                joint.anchor_b
            } else {
                [0.0, 0.0, 0.0]
            };
            if !world.add_joint(
                handle_a,
                handle_b,
                joint.anchor_a,
                anchor_b,
                joint_spec(&joint),
            ) {
                tracing::warn!(
                    "PhysicsJoint '{}': the simulation declined it; skipping",
                    joint.asset_id
                );
                continue;
            }
            wired += 1;
        }
        if wired > 0 {
            tracing::debug!("PhysicsSystem: wired {} joint(s)", wired);
        }

        // player capsule for the Camera3D
        // Every first-person camera is collided as a capsule. A RigidBody
        // upgrades it from a free-flying spectator to a grounded,
        // gravity-bound character. A third-person camera (a controller with
        // a `follow` block) gets no capsule: it is a virtual orbit around the
        // followed character, whose own rig capsule is the collided body.
        let camera_pos = ctx
            .query::<Camera3D>()
            .next()
            .filter(|c| {
                c.controller
                    .as_ref()
                    .is_none_or(|ctrl| ctrl.follow.is_none())
            })
            .map(|c| c.position);
        if let Some(cam_pos) = camera_pos {
            let rb_opt = ctx.query::<RigidBody>().next().cloned();
            let has_gravity = rb_opt.is_some();
            let rb = rb_opt.unwrap_or_default();
            if self.floor_y == 0.0 {
                self.floor_y = cam_pos[1];
            }
            let radius = rb.capsule_radius.max(0.05);
            let half_height = ((rb.capsule_height * 0.5) - radius).max(0.05);
            // a grounded character's eye sits at the capsule top; a flying
            // camera's capsule is centred on the eye.
            let eye_offset = if has_gravity {
                (rb.capsule_height * 0.5).max(radius + 0.05)
            } else {
                0.0
            };
            let center = [cam_pos[0], cam_pos[1] - eye_offset, cam_pos[2]];
            world.configure_character(rb.max_slope_deg, rb.step_height, has_gravity);
            let handle = world.add_character(
                half_height,
                radius,
                center,
                self.layers.mask(LAYER_CHARACTER),
            );
            self.player = handle.map(|handle| PlayerPhysics {
                handle,
                shape: CharacterCapsule::new(half_height, radius),
                eye_offset,
                has_gravity,
                gravity_scale: rb.gravity_scale.max(0.0),
                jump_height: rb.jump_height.max(0.0),
                vy: 0.0,
                grounded: true,
                center: PointInterp::new(center),
                written_eye: None,
            });
            tracing::debug!(
                "PhysicsSystem: player capsule r={:.2} h={:.2} gravity={}",
                radius,
                half_height,
                has_gravity,
            );
        }

        // Kinematic capsules for the root-motion character rigs published by
        // GraphicsSystem (which ran init first this tick).
        super::rig::init_rigs(
            &mut world,
            ctx,
            self.layers.mask(LAYER_CHARACTER),
            &mut self.rigs,
        );

        // Everything the budget reserved has now been built. A shortfall means
        // the counts the reservation came from disagree with what the world
        // actually holds, which leaves bodies missing from the simulation
        // rather than merely mis-sized.
        let built = world.body_count() as u32;
        if built != budget.body_total() {
            tracing::error!(
                "physics: the world built {} of the {} bodies its budget reserved",
                built,
                budget.body_total()
            );
        }

        // Published from the built world: the simulation's own storage is only
        // knowable once it is reserved.
        super::budget::publish_reservation(concinnity_memory::ledger(), &budget, &world);
        self.world = Some(world);
    }

    fn step(&mut self, ctx: &mut PipelineContext) -> StepResult {
        // Freeze while a menu is open: skip the solve and the write-back so the
        // world truly pauses (and an external editor's edits to simulated
        // Transforms are not stomped by a stale blend). The simulation clock
        // holds its accumulator across the pause, so resuming costs one normal
        // frame. The flag is published by whichever system owns the menu, which
        // runs first in the table, so it reflects this same tick.
        if ctx.resource::<MenuActive>().is_some_and(|m| m.0) {
            return StepResult::Continue;
        }

        if self.world.is_none() {
            return StepResult::Continue;
        }

        // The frame's fixed-tick budget and render blend factor. Absent (a
        // directly-stepped world with no App), every step runs exactly one tick
        // and writes the freshly simulated state.
        let timing = ctx.resource::<SimTiming>().copied().unwrap_or_default();

        // snapshot reads (released before any query_mut below)
        let (cam_pos, cam_yaw, cam_pitch, desired_move, jump_req, interact_req) = ctx
            .query::<Camera3D>()
            .next()
            .map(|c| {
                (
                    c.position,
                    c.yaw,
                    c.pitch,
                    c.desired_move,
                    c.jump_requested,
                    c.interact_requested,
                )
            })
            .unwrap_or(([0.0, self.floor_y, 0.0], 0.0, 0.0, [0.0; 3], false, false));

        // camera-space basis vectors
        let fwd_flat = [-sin(cam_yaw), 0.0, -cos(cam_yaw)];
        let fwd_full = [
            -(sin(cam_yaw) * cos(cam_pitch)),
            -sin(cam_pitch),
            -(cos(cam_yaw) * cos(cam_pitch)),
        ];

        // Whichever pool the schedule names, read once for the frame. Both
        // land in the same place; only how long the step takes differs.
        let mode = ScheduleMode::current(ctx.resources);

        let world = self.world.as_mut().expect("world checked above");

        // Reap bodies whose entity was despawned before the step, keeping
        // self.held a valid index into the compacted list.
        self.held = self
            .props
            .reap(world, self.held, |entity| ctx.is_alive(entity));

        // Adopt collider-bearing entities that appeared since init (runtime
        // spawns): each gets a body at its spawn transform, with its pose
        // snapshots seeded there so the render blend starts clean. The scan
        // materializes into scratch because adopting one mutates the tracked
        // set the scan itself reads.
        self.new_props.clear();
        self.new_props.extend(
            ctx.join2::<Collider, Transform>()
                .filter(|(entity, _, _)| {
                    !self.props.is_tracked(*entity) && !self.props.is_refused(*entity)
                })
                .map(|(entity, collider, transform)| {
                    (
                        entity,
                        PropCollSnap {
                            shape: collider_shape(&collider.0, transform.scale),
                            layer: collider.0.layer.clone(),
                            position: transform.position,
                            rotation_deg: transform.rotation_deg,
                            pickup: false,
                            dynamics: None,
                        },
                    )
                }),
        );
        for (entity, mut snap) in self.new_props.drain(..) {
            snap.pickup = ctx.get::<Pickup>(entity).is_some();
            snap.dynamics = ctx.get::<BodyDynamics>(entity).copied();
            self.props
                .adopt(&self.layers, world, entity, snap, self.body_cap);
        }

        // pickup / drop on the interact edge; held_changed carries the entity to
        // toggle the Held tag on in the write-back.
        let mut held_changed: Option<(Entity, bool)> = None;
        if interact_req {
            if let Some(held_idx) = self.held.take() {
                // drop: hand the prop back to dynamic simulation with a throw.
                let pp = self.props.get(held_idx).expect("held index is valid");
                let throw = [
                    fwd_full[0] * THROW_SPEED,
                    fwd_full[1] * THROW_SPEED + 1.0,
                    fwd_full[2] * THROW_SPEED,
                ];
                world.make_dynamic(pp.handle, throw);
                held_changed = Some((pp.entity, false));
            } else {
                // pickup: nearest carriable prop within reach the player faces.
                // Entity positions for the reach test, read from the Transform
                // column only on the interact edge (not every frame).
                let entity_positions: BTreeMap<Entity, [f32; 3]> = ctx
                    .query_with_entity::<Transform>()
                    .map(|(e, t)| (e, t.position))
                    .collect();
                let mut best: Option<(f32, usize)> = None;
                for (idx, pp) in self.props.iter().enumerate() {
                    if !pp.pickup {
                        continue;
                    }
                    let pos = entity_positions.get(&pp.entity).copied().unwrap_or(cam_pos);
                    let dx = pos[0] - cam_pos[0];
                    let dz = pos[2] - cam_pos[2];
                    let dist = sqrt(dx * dx + dz * dz);
                    if dist >= PICKUP_REACH || dist <= 0.0 {
                        continue;
                    }
                    let dot = (fwd_flat[0] * dx + fwd_flat[2] * dz) / dist;
                    if dot > PICKUP_MIN_DOT && best.is_none_or(|(d, _)| dist < d) {
                        best = Some((dist, idx));
                    }
                }
                if let Some((_, idx)) = best {
                    let pp = self.props.get(idx).expect("scanned index is valid");
                    world.make_kinematic(pp.handle);
                    held_changed = Some((pp.entity, true));
                    self.held = Some(idx);
                }
            }
        }

        // Adopt an externally moved camera (free-fly, a teleport): a position
        // that differs from the eye written back last frame was not ours, so
        // the capsule snaps to it with no blend across the jump.
        if let Some(player) = self.player.as_mut()
            && player.written_eye != Some(cam_pos)
        {
            player
                .center
                .snap([cam_pos[0], cam_pos[1] - player.eye_offset, cam_pos[2]]);
        }

        // The carried prop's hover point in front of the camera, refreshed
        // from this frame's camera pose.
        let hold_pos = [
            cam_pos[0] + fwd_full[0] * HOLD_DISTANCE,
            cam_pos[1] + fwd_full[1] * HOLD_DISTANCE - HOLD_DROP,
            cam_pos[2] + fwd_full[2] * HOLD_DISTANCE,
        ];

        // Root-motion displacements published since last frame, applied on the
        // frame's first tick. Rig capsules whose entity moved externally snap
        // before any tick runs.
        super::rig::drain_motions_into(ctx, &mut self.root_cursor, &mut self.motion_scratch);
        super::rig::sync_rigs(ctx, &mut self.rigs);

        for tick in 0..timing.ticks {
            let dt = timing.tick_dt;

            // carried prop hovers in front of the camera
            if let Some(prop) = self.held.and_then(|idx| self.props.get(idx)) {
                world.set_kinematic_translation(prop.handle, hold_pos);
            }

            // move the player capsule
            if let Some(player) = self.player.as_mut() {
                if player.has_gravity {
                    if tick == 0 && jump_req && player.grounded && player.jump_height > 0.0 {
                        player.vy = sqrt(2.0 * GRAVITY * player.gravity_scale * player.jump_height);
                    }
                    player.vy -= GRAVITY * player.gravity_scale * dt;
                }

                let center = player.center.current();
                let desired = [desired_move[0] * dt, player.vy * dt, desired_move[2] * dt];
                let moved = world.move_character(
                    &player.shape,
                    &CharacterMoveInput {
                        center,
                        desired,
                        dt,
                        exclude: player.handle,
                        mask: self.layers.mask(LAYER_CHARACTER),
                    },
                );
                let new_center = [
                    center[0] + moved.translation[0],
                    center[1] + moved.translation[1],
                    center[2] + moved.translation[2],
                ];
                world.set_kinematic_translation(player.handle, new_center);

                player.grounded = moved.grounded;
                if moved.grounded && player.vy < 0.0 {
                    player.vy = 0.0;
                }
                player.center.push(new_center);
            }

            // move the root-motion character rig capsules
            super::rig::tick_rigs(
                world,
                ctx,
                &mut self.rigs,
                if tick == 0 { &self.motion_scratch } else { &[] },
                dt,
                GRAVITY,
                self.layers.mask(LAYER_CHARACTER),
            );

            // advance the simulation
            self.fanout.step(world, dt, mode);

            // batch the tick's contact hits (strongest per pair this frame)
            self.contact_gate.advance_tick();
            world.drain_contact_hits_into(&mut self.contact_scratch);
            for hit in self.contact_scratch.drain(..) {
                self.contact_batch.add(hit);
            }

            // record the tick's dynamic prop poses for the render blend
            self.props.record_tick_poses(world);
        }

        // answer the IK ground probes and the follow camera's occlusion probe
        super::probes::step_probes(
            world,
            ctx,
            &self.rigs,
            self.layers
                .query_mask(LAYER_CHARACTER, &[LAYER_WORLD, LAYER_PROP]),
        );

        // publish the frame's contact events: one per body pair that passed
        // the impulse threshold, gated by the per-pair refractory. `a` is
        // always a prop entity; a hit whose sides both lack one (terrain,
        // capsules) has no consumer-visible subject and is dropped.
        for hit in self.contact_batch.drain() {
            let event = match (self.props.entity_of(hit.a), self.props.entity_of(hit.b)) {
                (Some(a), b) => ContactEvent {
                    a,
                    b,
                    point: hit.point,
                    normal: hit.normal,
                    impulse: hit.impulse,
                },
                (None, Some(b)) => ContactEvent {
                    a: b,
                    b: None,
                    point: hit.point,
                    normal: [-hit.normal[0], -hit.normal[1], -hit.normal[2]],
                    impulse: hit.impulse,
                },
                (None, None) => continue,
            };
            if self.contact_gate.admit(&hit) {
                ctx.events_mut::<ContactEvent>().send(event);
            }
        }

        // publish the sensor boundary crossings that pass their volume's
        // filter. A crossing whose body was removed this same step has no
        // `other` to classify, so only an `any` volume reports it.
        world.drain_sensor_crossings_into(&mut self.sensor_scratch);
        for crossing in self.sensor_scratch.drain(..) {
            let Some(&(volume, filter)) = self.sensor_filters.get(&crossing.tag) else {
                continue;
            };
            let passes = match filter {
                TriggerFilter::Player => crossing.other.is_some_and(|h| {
                    self.player.as_ref().is_some_and(|p| p.handle == h)
                        || self.rigs.iter().any(|r| r.handle == h)
                }),
                TriggerFilter::Props => crossing
                    .other
                    .is_some_and(|h| self.props.entity_of(h).is_some()),
                TriggerFilter::Any => true,
            };
            if passes {
                ctx.events_mut::<VolumeEvent>().send(VolumeEvent {
                    volume,
                    entered: crossing.entered,
                });
            }
        }

        // Write each dynamic prop's blended pose back to its Transform:
        // positions lerped, rotations slerped as quaternions, with the Euler
        // decomposition happening only here at the write boundary.
        let alpha = timing.alpha;
        for &(entity, pos, rot) in self.props.sample_poses(alpha) {
            if let Some(t) = ctx.get_mut::<Transform>(entity) {
                t.position = pos;
                t.rotation_deg = rot;
            }
        }
        if let Some((entity, is_held)) = held_changed {
            if is_held {
                if ctx.get::<Held>(entity).is_none() {
                    ctx.insert(entity, Held);
                }
            } else {
                ctx.remove::<Held>(entity);
            }
        }

        // write the blended camera position + view matrix
        let mut grounded = true;
        if let Some(player) = self.player.as_mut() {
            let center = player.center.sample(alpha);
            let eye = [center[0], center[1] + player.eye_offset, center[2]];
            player.written_eye = Some(eye);
            grounded = player.grounded;
            for camera in ctx.query_mut::<Camera3D>() {
                camera.position = eye;
                camera.view_matrix =
                    crate::gfx::camera::view_matrix(camera.position, camera.yaw, camera.pitch);
            }
        }

        // publish grounded state for jump gating
        for body in ctx.query_mut::<RigidBody>() {
            body.is_grounded = grounded;
        }

        // write the blended rig positions for the render follow
        super::rig::publish_rigs(ctx, &mut self.rigs, alpha);

        StepResult::Continue
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;

    use crate::components::{CameraController, CharacterRig, FollowController, PropCollider};
    use crate::ecs::SkinnedMeshHandle;
    use crate::physics::budget::{record_of, scan_counts};
    use crate::physics::test_world::TestWorld;

    // Make a spawned prop dynamic, exactly as the load-time PropBody
    // decomposition would.
    fn make_dynamic(world: &mut TestWorld, entity: Entity) {
        world.components.insert_typed(entity, ball_dynamics());
    }

    fn controlled_camera() -> Camera3D {
        Camera3D {
            fov_y_degrees: 75.0,
            near: 0.05,
            far: 200.0,
            view_matrix: [[0.0; 4]; 4],
            position: [0.0, 1.0, 0.0],
            yaw: 0.0,
            pitch: 0.0,
            desired_move: [0.0; 3],
            jump_requested: false,
            interact_requested: false,
            controller: Some(CameraController::default()),
        }
    }

    // A third-person camera is a virtual orbit: no player capsule is created
    // for it. (Regression: the spectator capsule spawned at the camera eye
    // overlapped the followed rig's capsule and squeezed it through the
    // floor.) A first-person camera keeps its capsule. The schedule gate that
    // builds the system at all is covered by the engine's schedule tests.
    #[test]
    fn third_person_camera_gets_no_player_capsule() {
        // Third-person (follow) camera: a virtual orbit, so no player capsule.
        let mut world = TestWorld::new();
        let mut camera = controlled_camera();
        camera.controller = Some(CameraController {
            follow: Some(FollowController {
                target: Some(SkinnedMeshHandle(1)),
                ..FollowController::default()
            }),
            ..CameraController::default()
        });
        world.components.push_typed(camera);
        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        assert!(physics.player.is_none(), "no capsule for the orbit camera");

        // First-person camera keeps its capsule.
        let mut world = TestWorld::new();
        world.components.push_typed(controlled_camera());
        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        assert!(
            physics.player.is_some(),
            "first-person camera keeps its capsule"
        );
    }

    fn ball_dynamics() -> BodyDynamics {
        BodyDynamics {
            mass: 1.0,
            friction: 0.5,
            linear_damping: 0.0,
            ..Default::default()
        }
    }

    // A camera looking down -Z with the interact field latched on, so the
    // PhysicsSystem (which reads Camera3D.interact_requested) triggers a pickup.
    fn interacting_camera(position: [f32; 3]) -> Camera3D {
        Camera3D {
            interact_requested: true,
            controller: None,
            position,
            ..controlled_camera()
        }
    }

    // The simulated pose is written back to the prop's Transform. With no
    // `SimTiming` published, each step runs exactly one fixed tick.
    #[test]
    fn dynamic_prop_writes_transform() {
        let id = AssetId(1);
        let mut world = TestWorld::new();
        let entity = world.spawn_prop(id, [0.0, 5.0, 0.0], false);
        make_dynamic(&mut world, entity);

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        for _ in 0..10 {
            physics.step(&mut world.ctx());
        }

        let transform_y = world.components.get::<Transform>(entity).unwrap().position[1];
        assert!(
            transform_y < 5.0,
            "the simulated pose falls the Transform (y={transform_y})"
        );
    }

    // A menu freezes the solve: while `MenuActive(true)` is published the body
    // does not fall, and clearing it resumes the fall from where it froze.
    // (The App-level simulation clock additionally holds its accumulator
    // across the pause, so a live run resumes without a catch-up burst.)
    #[test]
    fn menu_active_freezes_then_resumes_physics() {
        let id = AssetId(1);
        let mut world = TestWorld::new();
        let entity = world.spawn_prop(id, [0.0, 5.0, 0.0], false);
        make_dynamic(&mut world, entity);

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());

        // Paused: the body stays put however many frames pass.
        world.resources.insert(MenuActive(true));
        for _ in 0..5 {
            physics.step(&mut world.ctx());
        }
        let y_paused = world.components.get::<Transform>(entity).unwrap().position[1];
        assert!(
            (y_paused - 5.0).abs() < 1e-3,
            "the body must not fall while a menu is active (y={y_paused})"
        );

        // Resumed: the body falls again.
        world.resources.insert(MenuActive(false));
        for _ in 0..5 {
            physics.step(&mut world.ctx());
        }
        let y_resumed = world.components.get::<Transform>(entity).unwrap().position[1];
        assert!(
            y_resumed < y_paused - 1e-3,
            "the body must fall once the menu closes (y={y_resumed})"
        );
    }

    // A zero-tick frame (the accumulator has not crossed a tick) advances
    // nothing; the written Transform blends between the last two ticks by the
    // frame's alpha.
    #[test]
    fn zero_tick_frames_blend_between_the_last_two_ticks() {
        let id = AssetId(1);
        let mut world = TestWorld::new();
        let entity = world.spawn_prop(id, [0.0, 5.0, 0.0], false);
        make_dynamic(&mut world, entity);

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());

        let tick = |ticks, alpha| SimTiming {
            ticks,
            tick_dt: SimTiming::TICK_DT,
            alpha,
        };
        world.resources.insert(tick(1, 1.0));
        physics.step(&mut world.ctx());
        let y_prev = world.components.get::<Transform>(entity).unwrap().position[1];
        physics.step(&mut world.ctx());
        let y_curr = world.components.get::<Transform>(entity).unwrap().position[1];
        assert!(y_curr < y_prev, "the body falls tick over tick");

        // No tick, alpha 0: the write-back returns to the previous tick's pose.
        world.resources.insert(tick(0, 0.0));
        physics.step(&mut world.ctx());
        let y_alpha0 = world.components.get::<Transform>(entity).unwrap().position[1];
        assert!(
            (y_alpha0 - y_prev).abs() < 1e-6,
            "alpha 0 samples the previous tick"
        );

        // No tick, alpha 0.5: halfway between the two ticks.
        world.resources.insert(tick(0, 0.5));
        physics.step(&mut world.ctx());
        let y_mid = world.components.get::<Transform>(entity).unwrap().position[1];
        let expected = (y_prev + y_curr) * 0.5;
        assert!(
            (y_mid - expected).abs() < 1e-6,
            "alpha 0.5 blends the tick poses (y={y_mid}, expected {expected})"
        );
    }

    // The same number of fixed ticks produces bit-identical world state
    // however they are grouped into frames: 30 fps frames (two ticks each)
    // against 120 fps frames (a tick every other frame).
    #[test]
    fn tick_grouping_does_not_change_the_outcome() {
        let run = |frames: &[u32]| -> ([f32; 3], [f32; 3]) {
            let id = AssetId(1);
            let mut world = TestWorld::new();
            let entity = world.spawn_prop(id, [0.3, 5.0, 0.1], false);
            make_dynamic(&mut world, entity);

            let mut physics = PhysicsSystem::new(PhysicsConfig::default());
            physics.init(&mut world.ctx());
            for &ticks in frames {
                world.resources.insert(SimTiming {
                    ticks,
                    tick_dt: SimTiming::TICK_DT,
                    alpha: 1.0,
                });
                physics.step(&mut world.ctx());
            }
            let t = world.components.get::<Transform>(entity).unwrap();
            (t.position, t.rotation_deg)
        };

        // One simulated second: 30 frames of 2 ticks vs 120 frames alternating
        // 0 and 1 ticks. Both run exactly 60 fixed ticks.
        let thirty: Vec<u32> = core::iter::repeat_n(2, 30).collect();
        let one_twenty: Vec<u32> = (0..120).map(|i| i % 2).collect();
        assert_eq!(
            run(&thirty),
            run(&one_twenty),
            "the fixed-tick outcome must not depend on frame grouping"
        );
    }

    // Despawning a decomposed prop reaps its body, so it stops simulating
    // (and colliding) once its entity is gone.
    #[test]
    fn despawning_a_prop_reaps_its_physics_body() {
        let id = AssetId(1);
        let mut world = TestWorld::new();
        let ball = world.spawn_prop(id, [0.0, 5.0, 0.0], false);
        make_dynamic(&mut world, ball);

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());

        // Settle so the body is live and falling.
        for _ in 0..2 {
            physics.step(&mut world.ctx());
        }
        let before = physics.physics_body_count();

        // Despawn the ball (stand-in for GraphicsSystem) and step: PhysicsSystem
        // reaps the orphaned body.
        world.components.despawn(ball);
        physics.step(&mut world.ctx());
        let after = physics.physics_body_count();
        assert_eq!(after, before - 1, "the despawned prop's body was removed");

        // The sim keeps running cleanly with the body gone (no further removals).
        physics.step(&mut world.ctx());
        assert_eq!(
            physics.physics_body_count(),
            after,
            "no further bodies removed"
        );
    }

    // Picking up a carriable prop tags its entity with Held.
    #[test]
    fn pickup_sets_held_tag() {
        let id = AssetId(1);
        let mut world = TestWorld::new();
        let carriable = world.spawn_prop(id, [0.0, 1.0, -2.0], true);
        make_dynamic(&mut world, carriable);
        world
            .components
            .push_typed(interacting_camera([0.0, 1.0, 0.0]));

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());

        physics.step(&mut world.ctx());

        assert_eq!(
            world.ctx().query::<Held>().count(),
            1,
            "pickup inserts the Held tag on the entity"
        );
    }

    // A collider-bearing entity that appears after init (a runtime spawn) is
    // adopted on the next step: it gets a body and falls like an authored one.
    // The headroom is what reserves the body for it: the simulation is sized
    // once at init and a spawn past the reservation is refused.
    #[test]
    fn runtime_spawned_prop_gets_a_body_and_falls() {
        let mut world = TestWorld::new();
        let mut physics = PhysicsSystem::new(PhysicsConfig {
            spawn_headroom: 1,
            ..PhysicsConfig::default()
        });
        physics.init(&mut world.ctx());
        let baseline = physics.physics_body_count();

        let spawned = world.spawn_prop(AssetId(7), [0.0, 5.0, 0.0], false);
        make_dynamic(&mut world, spawned);
        physics.step(&mut world.ctx());
        assert_eq!(
            physics.physics_body_count(),
            baseline + 1,
            "the spawned entity got a body on its first step"
        );
        for _ in 0..30 {
            physics.step(&mut world.ctx());
        }
        let y = world.components.get::<Transform>(spawned).unwrap().position[1];
        assert!(y < 4.5, "the spawned body falls (y = {y})");
        for _ in 0..300 {
            physics.step(&mut world.ctx());
        }
        let y = world.components.get::<Transform>(spawned).unwrap().position[1];
        assert!(
            (y - 0.5).abs() < 0.1,
            "the spawned ball rests on the flat floor (y = {y})"
        );
    }

    // Spawn, despawn, and respawn leave no bodies or colliders behind: a
    // reaped body hands its slot back, so one body's worth of headroom covers
    // any number of rounds.
    #[test]
    fn spawn_despawn_respawn_cycle_is_leak_free() {
        let mut world = TestWorld::new();
        let mut physics = PhysicsSystem::new(PhysicsConfig {
            spawn_headroom: 1,
            ..PhysicsConfig::default()
        });
        physics.init(&mut world.ctx());
        let bodies = physics.physics_body_count();
        let colliders = physics.physics_collider_count();

        for round in 0..3 {
            let spawned = world.spawn_prop(AssetId(100 + round), [0.0, 3.0, 0.0], false);
            make_dynamic(&mut world, spawned);
            physics.step(&mut world.ctx());
            assert_eq!(physics.physics_body_count(), bodies + 1, "round {round}");
            world.components.despawn(spawned);
            physics.step(&mut world.ctx());
            assert_eq!(
                physics.physics_body_count(),
                bodies,
                "round {round} reaped the body"
            );
            assert_eq!(
                physics.physics_collider_count(),
                colliders,
                "round {round} reaped the collider"
            );
        }
    }

    // A world whose shipped budget was counted from the same content it holds
    // passes the init assert, and reserves the cap that budget implies.
    #[test]
    fn a_shipped_budget_matching_the_world_is_adopted() {
        let mut world = TestWorld::new();
        let entity = world.spawn_prop(AssetId(1), [0.0, 3.0, 0.0], false);
        make_dynamic(&mut world, entity);
        world.components.push_typed(controlled_camera());

        // The record cook would have written for this world: one dynamic prop,
        // the floor, the player capsule, and room for two spawns.
        let counts = scan_counts(&world.ctx());
        let budget = PhysicsBudget::derive(&counts, 2);
        assert_eq!(budget.dynamic, 1);
        assert_eq!(budget.kinematic, 1, "the first-person camera capsule");
        world
            .resources
            .insert(WorldPhysicsBudget(record_of(&budget)));

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        assert_eq!(physics.body_cap, budget.body_cap());
        assert_eq!(
            physics.physics_body_count(),
            budget.body_total() as usize,
            "init built exactly the bodies the budget reserved"
        );
    }

    // A world with no shipped budget (built in memory, as every test world is)
    // reserves from what it holds plus the headroom its config authored, and
    // caps spawns there. The cap used to be left open for such a world, on the
    // grounds that nothing had counted its spawns; a fixed-capacity simulation
    // cannot honour that -- a spawn past the reservation gets no body either
    // way, and the cap is what turns a silently declined one into a refusal
    // naming the knob to raise.
    #[test]
    fn a_world_without_a_shipped_budget_reserves_from_what_it_holds() {
        let mut world = TestWorld::new();
        let entity = world.spawn_prop(AssetId(1), [0.0, 3.0, 0.0], false);
        make_dynamic(&mut world, entity);

        let mut physics = PhysicsSystem::new(PhysicsConfig {
            spawn_headroom: 4,
            ..PhysicsConfig::default()
        });
        physics.init(&mut world.ctx());

        assert_eq!(
            physics.physics_body_count(),
            2,
            "the floor and the one authored prop"
        );
        assert_eq!(physics.body_cap, 2 + 4, "plus the authored headroom");
    }

    // Past the cap, a spawned prop gets no body and the world keeps stepping.
    // The refusal happens once: the next tick's scan passes over the entity
    // rather than re-refusing it.
    #[test]
    fn a_spawn_past_the_shipped_budget_is_refused() {
        let mut world = TestWorld::new();
        let authored = world.spawn_prop(AssetId(1), [0.0, 3.0, 0.0], false);
        make_dynamic(&mut world, authored);

        // A budget with no headroom: the floor and the one authored prop.
        let counts = scan_counts(&world.ctx());
        let budget = PhysicsBudget::derive(&counts, 0);
        world
            .resources
            .insert(WorldPhysicsBudget(record_of(&budget)));

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        let full = physics.physics_body_count();
        assert_eq!(full, budget.body_cap() as usize, "the budget is spent");

        let spawned = world.spawn_prop(AssetId(2), [0.0, 6.0, 0.0], false);
        make_dynamic(&mut world, spawned);
        physics.step(&mut world.ctx());
        assert_eq!(physics.physics_body_count(), full, "no body was built");
        assert!(physics.props.is_refused(spawned));

        // Stepping on keeps the refusal: the entity is skipped, not retried,
        // and the authored prop carries on simulating.
        for _ in 0..10 {
            physics.step(&mut world.ctx());
        }
        assert_eq!(physics.physics_body_count(), full);
        let refused_y = world.components.get::<Transform>(spawned).unwrap().position[1];
        assert_eq!(refused_y, 6.0, "a refused prop is not simulated at all");
        let live_y = world
            .components
            .get::<Transform>(authored)
            .unwrap()
            .position[1];
        assert!(live_y < 3.0, "the authored prop still falls");
    }

    // A rig capsule authored standing exactly on the floor stays there: it
    // neither sinks tick after tick nor is lifted off it. The driver used to
    // spawn one a fingernail above its authored position, because the
    // controller ignored a hit a downward move started already touching and
    // the capsule sank a little every frame; the controller now separates
    // along the contact normal instead, so the authored position is the one
    // that holds.
    #[test]
    fn a_rig_capsule_spawned_on_the_floor_neither_sinks_nor_rises() {
        let identity = [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ];
        let mut world = TestWorld::new();
        world.components.push_typed(CharacterRig::new(
            SkinnedMeshHandle(1),
            0,
            identity,
            0.6,
            0.3,
        ));

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        let rig_y = |world: &mut TestWorld| {
            world
                .ctx()
                .query::<CharacterRig>()
                .next()
                .expect("the rig is there")
                .position[1]
        };
        assert_eq!(
            rig_y(&mut world),
            0.0,
            "the capsule spawns at its authored position, unlifted"
        );

        for _ in 0..30 {
            physics.step(&mut world.ctx());
        }
        let settled = rig_y(&mut world);
        for _ in 0..300 {
            physics.step(&mut world.ctx());
        }
        let held = rig_y(&mut world);

        assert!(
            settled.abs() < 0.01,
            "the capsule stayed on the floor (y = {settled})"
        );
        assert!(
            (held - settled).abs() < 1.0e-4,
            "and stopped moving ({settled} -> {held})"
        );
    }

    // A hard landing publishes one ContactEvent naming the prop; resting
    // afterwards stays silent.
    #[test]
    fn contact_event_fires_on_impact_and_not_at_rest() {
        let id = AssetId(1);
        let mut world = TestWorld::new();
        let entity = world.spawn_prop(id, [0.0, 5.0, 0.0], false);
        make_dynamic(&mut world, entity);

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());

        let mut cursor = EventCursor::default();
        let mut impacts: Vec<ContactEvent> = Vec::new();
        for _ in 0..120 {
            physics.step(&mut world.ctx());
            let ctx = world.ctx();
            if let Some(events) = ctx.events::<ContactEvent>() {
                impacts.extend(events.read(&mut cursor).copied());
            }
        }
        assert_eq!(impacts.len(), 1, "one landing, one event: {impacts:?}");
        let impact = impacts[0];
        assert_eq!(impact.a, entity);
        assert_eq!(impact.b, None, "the floor slab has no entity");
        assert!(
            impact.impulse > 3.0 && impact.impulse < 50.0,
            "impulse {} out of the plausible landing range",
            impact.impulse
        );

        // Settled: hundreds of resting ticks publish nothing further.
        for _ in 0..300 {
            physics.step(&mut world.ctx());
            let ctx = world.ctx();
            if let Some(events) = ctx.events::<ContactEvent>() {
                assert_eq!(
                    events.read(&mut cursor).count(),
                    0,
                    "resting contact must not publish events"
                );
            }
        }
    }

    // A sensor region reports a prop crossing it, in and then out, naming the
    // volume that saw it.
    #[test]
    fn a_trigger_volume_reports_a_prop_crossing_it() {
        let volume_id = AssetId(9);
        let mut world = TestWorld::new();
        world.components.push_typed(TriggerVolume {
            asset_id: volume_id,
            position: [0.0, 3.0, 0.0],
            rotation_deg: [0.0; 3],
            collider: PropCollider {
                shape: "cuboid".to_string(),
                half_extents: [1.0, 0.5, 1.0],
                ..Default::default()
            },
            detects: TriggerFilter::Props,
        });
        let ball = world.spawn_prop(AssetId(1), [0.0, 6.0, 0.0], false);
        make_dynamic(&mut world, ball);

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());

        let mut cursor = EventCursor::default();
        let mut crossings: Vec<VolumeEvent> = Vec::new();
        for _ in 0..180 {
            physics.step(&mut world.ctx());
            let ctx = world.ctx();
            if let Some(events) = ctx.events::<VolumeEvent>() {
                crossings.extend(events.read(&mut cursor).copied());
            }
        }
        assert_eq!(crossings.len(), 2, "in, then out: {crossings:?}");
        assert!(crossings.iter().all(|c| c.volume == volume_id));
        assert!(crossings[0].entered, "the ball entered first");
        assert!(!crossings[1].entered, "and left afterwards");
    }

    // A joint anchored to the world holds its body up: the hidden anchor body
    // the driver mints for it is part of the reservation, and the prop hangs
    // off it instead of falling.
    #[test]
    fn a_world_anchored_joint_holds_its_prop_up() {
        let bob_id = AssetId(1);
        let mut world = TestWorld::new();
        let bob = world.spawn_prop(bob_id, [1.0, 4.0, 0.0], false);
        make_dynamic(&mut world, bob);
        world.components.push_typed(PhysicsJoint {
            asset_id: AssetId(2),
            kind: "spherical".to_string(),
            body_a: Some(bob_id),
            body_b: None,
            // The bob's own centre hangs one unit from the anchor point.
            anchor_a: [-1.0, 0.0, 0.0],
            anchor_b: [0.0, 4.0, 0.0],
            ..Default::default()
        });

        let mut physics = PhysicsSystem::new(PhysicsConfig::default());
        physics.init(&mut world.ctx());
        for _ in 0..240 {
            physics.step(&mut world.ctx());
        }

        let position = world.components.get::<Transform>(bob).unwrap().position;
        let reach =
            ((position[0]).powi(2) + (position[1] - 4.0).powi(2) + (position[2]).powi(2)).sqrt();
        assert!(
            (reach - 1.0).abs() < 0.05,
            "the bob hangs one unit from the anchor, at {position:?} ({reach})"
        );
        assert!(
            position[1] > 2.5,
            "and is held up rather than falling ({position:?})"
        );
    }

    // The config's no_collide pairs reach the built colliders: a prop on a
    // layer that ignores `world` falls straight through the floor.
    #[test]
    fn no_collide_config_lets_a_layered_prop_fall_through_the_floor() {
        let config = PhysicsConfig {
            layers: vec!["ghost".to_string()],
            no_collide: vec![["ghost".to_string(), "world".to_string()]],
            ..PhysicsConfig::default()
        };

        let mut world = TestWorld::new();
        let entity = world.spawn_prop(AssetId(1), [0.0, 2.0, 0.0], false);
        make_dynamic(&mut world, entity);
        world
            .components
            .get_mut::<Collider>(entity)
            .unwrap()
            .0
            .layer = "ghost".to_string();

        let mut physics = PhysicsSystem::new(config);
        physics.init(&mut world.ctx());
        for _ in 0..240 {
            physics.step(&mut world.ctx());
        }
        let y = world.components.get::<Transform>(entity).unwrap().position[1];
        assert!(
            y < -10.0,
            "the ghost-layer prop fell through the floor (y = {y})"
        );
    }
}