1use std::sync::mpsc::channel;
2
3use rapier2d::prelude::*;
4use serde::{Deserialize, Serialize};
5
6use crate::nav::navigation::NavigationSystem;
7use crate::nav::spatial::SpatialGrid;
8use crate::config::{EngineConfig, PLAYER_STATE_LEN};
9use crate::events::CoreEvent;
10use crate::map::{GameMap, MapConfig};
11use crate::rng::Rng;
12use crate::sim::{GameDef, GameSim, SimCtx};
13use crate::snapshot::Block;
14
15const MAX_ACCUMULATED_TIME: f32 = 0.1;
17
18pub struct EngineSim<G: GameDef> {
26 pub cfg: EngineConfig,
27 pub world: PhysicsWorld,
28 pub map: Option<GameMap>,
29 pub nav: Option<NavigationSystem>,
30 pub spatial: SpatialGrid,
31 pub rng: Rng,
32
33 time_step: f32,
34 accumulator: f32,
35
36 pub events: Vec<CoreEvent>,
38
39 bodies_to_destroy: Vec<RigidBodyHandle>,
41
42 last_body_has_events: bool,
45
46 pub sim: G::Sim,
47}
48
49impl<G: GameDef> EngineSim<G> {
50 pub fn new(cfg: EngineConfig, game_cfg: &G::Config) -> Self {
51 let time_step = cfg.time_step;
52
53 let mut world = PhysicsWorld::new();
54
55 world.gravity = Vector::ZERO;
56 world.integration_parameters.dt = time_step;
57
58 let seed = cfg.seed;
59 let sim = G::Sim::new(game_cfg, &cfg);
60
61 Self {
62 world,
63 map: None,
64 nav: None,
65 spatial: SpatialGrid::new(600.0),
66 rng: Rng::new(seed),
67 time_step,
68 accumulator: 0.0,
69 events: Vec::new(),
70 bodies_to_destroy: Vec::new(),
71 last_body_has_events: false,
72 sim,
73 cfg,
74 }
75 }
76
77 pub fn load_map(&mut self, json: &str) -> Result<(), String> {
81 let map_cfg: MapConfig = serde_json::from_str(json).map_err(|e| format!("bad map json: {e}"))?;
82
83 if let Some(mut old) = self.map.take() {
84 old.destroy(&mut self.world);
85 }
86
87 let map = GameMap::create(&mut self.world, &map_cfg, self.cfg.map_scale, &self.cfg.map_set_id);
88
89 self.nav = Some(NavigationSystem::generate(&map.grid, &map.physics_static, map.step));
90 self.map = Some(map);
91
92 Ok(())
93 }
94
95 pub fn map_info_json(&self) -> String {
98 let Some(map) = &self.map else {
99 return "null".to_string();
100 };
101
102 let width = map.grid.first().map(|row| row.len()).unwrap_or(0) as f32 * map.step;
103 let height = map.grid.len() as f32 * map.step;
104
105 serde_json::json!({
106 "setId": map.set_id,
107 "step": map.step,
108 "width": width,
109 "height": height,
110 "respawns": map.respawns,
111 })
112 .to_string()
113 }
114
115 pub fn spawn_actor(&mut self, game_id: u32, model_name: &str, team_id: u8, x: f32, y: f32, angle_deg: f32) -> Result<(), String> {
118 self.sim
119 .spawn_actor(&mut self.world, &mut self.events, game_id, model_name, team_id, x, y, angle_deg)
120 }
121
122 pub fn remove_actor(&mut self, game_id: u32) {
123 self.sim.remove_actor(&mut self.world, game_id);
124 }
125
126 pub fn reset_actor(&mut self, game_id: u32, team_id: u8, x: f32, y: f32, angle_deg: f32) {
127 self.sim.reset_actor(&mut self.world, game_id, team_id, x, y, angle_deg);
128 }
129
130 pub fn reset_all_vitals(&mut self) {
131 self.sim.reset_all_vitals(&mut self.events);
132 }
133
134 pub fn spawn_scripted_actor(&mut self, game_id: u32, model_name: &str, team_id: u8, x: f32, y: f32, angle_deg: f32) -> Result<(), String> {
135 self.sim.spawn_scripted_actor(
136 &mut self.world,
137 &mut self.rng,
138 &mut self.events,
139 game_id,
140 model_name,
141 team_id,
142 x,
143 y,
144 angle_deg,
145 )
146 }
147
148 pub fn remove_scripted_actor(&mut self, game_id: u32) {
149 self.sim.remove_scripted_actor(&mut self.world, game_id);
150 }
151
152 pub fn apply_input(&mut self, game_id: u32, seq: u32, action: &str, key_name: &str) {
155 self.sim.apply_input(game_id, seq, action, key_name);
156 }
157
158 pub fn apply_aim(&mut self, game_id: u32, seq: u32, x: f32, y: f32, flags: u32) {
160 self.sim.apply_aim(game_id, seq, x, y, flags);
161 }
162
163 pub fn last_input_seq(&self, game_id: u32) -> u32 {
164 self.sim.last_input_seq(game_id)
165 }
166
167 pub fn take_events_json(&mut self) -> String {
170 let events: Vec<CoreEvent> = self.events.drain(..).collect();
171
172 serde_json::to_string(&events).unwrap_or_else(|_| "[]".to_string())
173 }
174
175 pub fn is_alive(&self, game_id: u32) -> bool {
178 self.sim.is_alive(game_id)
179 }
180
181 pub fn actor_position(&self, game_id: u32) -> Option<[f32; 2]> {
182 self.sim.actor_position(&self.world, game_id)
183 }
184
185 pub fn prediction_state(&self, game_id: u32) -> Option<([f32; PLAYER_STATE_LEN], bool)> {
186 self.sim.prediction_state(&self.world, game_id)
187 }
188
189 pub fn alive_players_flat(&self) -> Vec<f32> {
190 self.sim.alive_players_flat(&self.world)
191 }
192
193 pub fn players_json(&self) -> String {
196 self.sim.players_json()
197 }
198
199 pub fn step(&mut self, dt: f32) {
204 self.accumulator = (self.accumulator + dt).min(MAX_ACCUMULATED_TIME);
205
206 while self.accumulator >= self.time_step {
207 self.step_fixed();
208 self.accumulator -= self.time_step;
209 }
210
211 self.sim.refresh_cached(&self.world);
212
213 let mut ctx = SimCtx {
214 world: &mut self.world,
215 cfg: &self.cfg,
216 map: &self.map,
217 nav: &self.nav,
218 spatial: &mut self.spatial,
219 rng: &mut self.rng,
220 events: &mut self.events,
221 bodies_to_destroy: &mut self.bodies_to_destroy,
222 };
223
224 self.sim.on_ai_tick(&mut ctx, dt);
225 }
226
227 fn step_fixed(&mut self) {
229 let mut ctx = SimCtx {
230 world: &mut self.world,
231 cfg: &self.cfg,
232 map: &self.map,
233 nav: &self.nav,
234 spatial: &mut self.spatial,
235 rng: &mut self.rng,
236 events: &mut self.events,
237 bodies_to_destroy: &mut self.bodies_to_destroy,
238 };
239
240 self.sim.on_fixed_step(&mut ctx, self.time_step);
241
242 let (collision_send, collision_recv) = channel();
244 let (force_send, _force_recv) = channel();
245 let collector = ChannelEventCollector::new(collision_send, force_send);
246
247 self.world.step_with_events(&(), &collector);
248
249 let mut contacts = Vec::new();
250
251 while let Ok(event) = collision_recv.try_recv() {
252 if let CollisionEvent::Started(h1, h2, _) = event {
253 contacts.push((h1, h2));
254 }
255 }
256
257 let mut ctx = SimCtx {
258 world: &mut self.world,
259 cfg: &self.cfg,
260 map: &self.map,
261 nav: &self.nav,
262 spatial: &mut self.spatial,
263 rng: &mut self.rng,
264 events: &mut self.events,
265 bodies_to_destroy: &mut self.bodies_to_destroy,
266 };
267
268 self.sim.on_contacts(&mut ctx, &contacts);
269 self.destroy_queued_bodies();
270 }
271
272 fn destroy_queued_bodies(&mut self) {
274 if self.bodies_to_destroy.is_empty() {
275 return;
276 }
277
278 let handles: Vec<RigidBodyHandle> = self.bodies_to_destroy.drain(..).collect();
279
280 for handle in handles {
281 self.sim.on_before_destroy(&self.world, handle);
282 self.world.remove_body(handle);
283 }
284 }
285
286 pub fn build_snapshot_blocks(&mut self) -> Vec<(String, Block)> {
291 let (mut blocks, has_events) = self.sim.build_snapshot_blocks();
292
293 if let Some(map) = &self.map {
295 blocks.push((
296 map.set_id.clone(),
297 Block::IndexedNoNull8(map.dynamic_map_data(&self.world)),
298 ));
299 }
300
301 self.last_body_has_events = has_events;
302
303 blocks
304 }
305
306 pub fn body_has_events(&self) -> bool {
309 self.last_body_has_events
310 }
311
312 pub fn remove_players_and_shots(&mut self) -> Vec<String> {
317 self.sim.remove_players_and_shots(&mut self.world)
318 }
319
320 pub fn clear(&mut self) {
322 if let Some(mut map) = self.map.take() {
325 map.destroy(&mut self.world);
326 }
327
328 let handles: Vec<RigidBodyHandle> = self.world.rigid_bodies().map(|(handle, _)| handle).collect();
329
330 for handle in handles {
331 self.world.remove_body(handle);
332 }
333
334 self.sim.clear();
335 self.nav = None;
336 self.spatial.clear();
337 self.bodies_to_destroy.clear();
338
339 self.accumulator = 0.0;
340 }
341
342 pub fn debug_json(&self) -> String {
348 crate::debug::engine_json(
349 &self.world,
350 &self.map,
351 &self.nav,
352 &self.spatial,
353 &self.rng,
354 self.accumulator,
355 self.time_step,
356 )
357 .to_string()
358 }
359
360 pub fn serialize_state(&self) -> Result<Vec<u8>, String> {
366 let dump = EngineDump {
367 world: WorldDump {
368 gravity: [self.world.gravity.x, self.world.gravity.y],
369 integration_parameters: self.world.integration_parameters,
370 islands: self.world.islands.clone(),
371 broad_phase: self.world.broad_phase.clone(),
372 narrow_phase: self.world.narrow_phase.clone(),
373 bodies: self.world.bodies.clone(),
374 colliders: self.world.colliders.clone(),
375 impulse_joints: self.world.impulse_joints.clone(),
376 multibody_joints: self.world.multibody_joints.clone(),
377 },
378 map: &self.map,
379 rng: &self.rng,
380 accumulator: self.accumulator,
381 sim: self.sim.serialize(),
382 };
383
384 serde_json::to_vec(&dump).map_err(|e| e.to_string())
385 }
386
387 pub fn deserialize_state(&mut self, data: &[u8]) -> Result<(), String> {
390 let dump: EngineDumpOwned = serde_json::from_slice(data).map_err(|e| e.to_string())?;
391
392 let mut world = PhysicsWorld::new();
393
394 world.gravity = Vector::new(dump.world.gravity[0], dump.world.gravity[1]);
395 world.integration_parameters = dump.world.integration_parameters;
396 world.islands = dump.world.islands;
397 world.broad_phase = dump.world.broad_phase;
398 world.narrow_phase = dump.world.narrow_phase;
399 world.bodies = dump.world.bodies;
400 world.colliders = dump.world.colliders;
401 world.impulse_joints = dump.world.impulse_joints;
402 world.multibody_joints = dump.world.multibody_joints;
403
404 self.world = world;
405 self.map = dump.map;
406 self.rng = dump.rng;
407 self.accumulator = dump.accumulator;
408 self.sim.deserialize(dump.sim)?;
409
410 self.bodies_to_destroy.clear();
411 self.events.clear();
412
413 self.nav = self
416 .map
417 .as_ref()
418 .map(|map| NavigationSystem::generate(&map.grid, &map.physics_static, map.step));
419
420 self.sim.rebuild_spatial_grid(&self.world, &mut self.spatial);
421 self.sim.refresh_cached(&self.world);
422
423 Ok(())
424 }
425}
426
427#[derive(Serialize)]
428struct WorldDump {
429 gravity: [f32; 2],
430 integration_parameters: IntegrationParameters,
431 islands: IslandManager,
432 broad_phase: BroadPhaseBvh,
433 narrow_phase: NarrowPhase,
434 bodies: RigidBodySet,
435 colliders: ColliderSet,
436 impulse_joints: ImpulseJointSet,
437 multibody_joints: MultibodyJointSet,
438}
439
440#[derive(Deserialize)]
441struct WorldDumpOwned {
442 gravity: [f32; 2],
443 integration_parameters: IntegrationParameters,
444 islands: IslandManager,
445 broad_phase: BroadPhaseBvh,
446 narrow_phase: NarrowPhase,
447 bodies: RigidBodySet,
448 colliders: ColliderSet,
449 impulse_joints: ImpulseJointSet,
450 multibody_joints: MultibodyJointSet,
451}
452
453#[derive(Serialize)]
454struct EngineDump<'a> {
455 world: WorldDump,
456 map: &'a Option<GameMap>,
457 rng: &'a Rng,
458 accumulator: f32,
459 sim: serde_json::Value,
460}
461
462#[derive(Deserialize)]
463struct EngineDumpOwned {
464 world: WorldDumpOwned,
465 map: Option<GameMap>,
466 rng: Rng,
467 accumulator: f32,
468 sim: serde_json::Value,
469}
470
471#[cfg(test)]
478mod fixture {
479 use super::*;
480 use crate::config::FieldValue;
481 use serde::Deserialize;
482 use std::collections::{BTreeMap, BTreeSet};
483
484 #[derive(Deserialize)]
485 pub struct TestConfig {}
486
487 pub struct TestGame;
488
489 impl GameDef for TestGame {
490 type Config = TestConfig;
491 type Sim = TestSim;
492 }
493
494 #[derive(Clone, Copy)]
495 struct TestActor {
496 x: f32,
497 y: f32,
498 vx: f32,
499 vy: f32,
500 team: u8,
501 alive: bool,
502 }
503
504 pub struct TestSim {
505 actors: BTreeMap<u32, TestActor>,
506 scripted: BTreeSet<u32>,
507 }
508
509 impl GameSim<TestGame> for TestSim {
510 fn new(_cfg: &TestConfig, _engine_cfg: &EngineConfig) -> Self {
511 Self {
512 actors: BTreeMap::new(),
513 scripted: BTreeSet::new(),
514 }
515 }
516
517 fn spawn_actor(
518 &mut self,
519 _world: &mut PhysicsWorld,
520 _events: &mut Vec<CoreEvent>,
521 game_id: u32,
522 _model_name: &str,
523 team_id: u8,
524 x: f32,
525 y: f32,
526 _angle_deg: f32,
527 ) -> Result<(), String> {
528 self.actors.insert(
529 game_id,
530 TestActor { x, y, vx: 0.0, vy: 0.0, team: team_id, alive: true },
531 );
532
533 Ok(())
534 }
535
536 fn remove_actor(&mut self, _world: &mut PhysicsWorld, game_id: u32) {
537 self.actors.remove(&game_id);
538 self.scripted.remove(&game_id);
539 }
540
541 fn reset_actor(&mut self, _world: &mut PhysicsWorld, game_id: u32, team_id: u8, x: f32, y: f32, _angle_deg: f32) {
542 if let Some(actor) = self.actors.get_mut(&game_id) {
543 actor.x = x;
544 actor.y = y;
545 actor.team = team_id;
546 actor.alive = true;
547 }
548 }
549
550 fn reset_all_vitals(&mut self, _events: &mut Vec<CoreEvent>) {
551 for actor in self.actors.values_mut() {
552 actor.alive = true;
553 }
554 }
555
556 fn spawn_scripted_actor(
557 &mut self,
558 world: &mut PhysicsWorld,
559 _rng: &mut Rng,
560 events: &mut Vec<CoreEvent>,
561 game_id: u32,
562 model_name: &str,
563 team_id: u8,
564 x: f32,
565 y: f32,
566 angle_deg: f32,
567 ) -> Result<(), String> {
568 self.spawn_actor(world, events, game_id, model_name, team_id, x, y, angle_deg)?;
569 self.scripted.insert(game_id);
570
571 Ok(())
572 }
573
574 fn remove_scripted_actor(&mut self, world: &mut PhysicsWorld, game_id: u32) {
575 self.remove_actor(world, game_id);
576 }
577
578 fn apply_input(&mut self, game_id: u32, _seq: u32, action: &str, key_name: &str) {
579 let Some(actor) = self.actors.get_mut(&game_id) else {
580 return;
581 };
582
583 let magnitude = if action == "down" { 40.0 } else { 0.0 };
584
585 match key_name {
586 "forward" => actor.vy = -magnitude,
587 "back" => actor.vy = magnitude,
588 _ => {}
589 }
590 }
591
592 fn last_input_seq(&self, _game_id: u32) -> u32 {
593 0
594 }
595
596 fn is_alive(&self, game_id: u32) -> bool {
597 self.actors.get(&game_id).is_some_and(|a| a.alive)
598 }
599
600 fn actor_position(&self, _world: &PhysicsWorld, game_id: u32) -> Option<[f32; 2]> {
601 self.actors.get(&game_id).map(|a| [a.x, a.y])
602 }
603
604 fn prediction_state(&self, _world: &PhysicsWorld, game_id: u32) -> Option<([f32; PLAYER_STATE_LEN], bool)> {
605 self.actors
606 .get(&game_id)
607 .map(|a| ([a.x, a.y, 0.0, a.vx, a.vy, 0.0, 0.0, 0.0], false))
608 }
609
610 fn alive_players_flat(&self, _world: &PhysicsWorld) -> Vec<f32> {
611 self.actors
612 .iter()
613 .filter(|(_, a)| a.alive)
614 .flat_map(|(id, a)| [*id as f32, a.x, a.y])
615 .collect()
616 }
617
618 fn players_json(&self) -> String {
619 let rows: Vec<serde_json::Value> = self
620 .actors
621 .iter()
622 .map(|(id, a)| serde_json::json!({ "id": id, "x": a.x, "y": a.y, "team": a.team }))
623 .collect();
624
625 serde_json::to_string(&rows).unwrap()
626 }
627
628 fn on_fixed_step(&mut self, _ctx: &mut SimCtx, dt: f32) {
629 for actor in self.actors.values_mut() {
630 actor.x += actor.vx * dt;
631 actor.y += actor.vy * dt;
632 }
633 }
634
635 fn on_contacts(&mut self, _ctx: &mut SimCtx, _pairs: &[(ColliderHandle, ColliderHandle)]) {}
636
637 fn on_before_destroy(&mut self, _world: &PhysicsWorld, _handle: RigidBodyHandle) {}
638
639 fn on_ai_tick(&mut self, _ctx: &mut SimCtx, _dt: f32) {
640 for &id in &self.scripted {
642 if let Some(actor) = self.actors.get_mut(&id) {
643 actor.vx = 1.0;
644 }
645 }
646 }
647
648 fn refresh_cached(&mut self, _world: &PhysicsWorld) {}
649
650 fn build_snapshot_blocks(&mut self) -> (Vec<(String, Block)>, bool) {
651 let rows: Vec<(u8, Option<Vec<FieldValue>>)> = self
652 .actors
653 .iter()
654 .map(|(id, a)| (*id as u8, Some(vec![FieldValue::F32(a.x), FieldValue::F32(a.y)])))
655 .collect();
656
657 (vec![("actor".to_string(), Block::Indexed8(rows))], false)
658 }
659
660 fn remove_players_and_shots(&mut self, _world: &mut PhysicsWorld) -> Vec<String> {
661 let names: Vec<String> = self.actors.keys().map(|id| id.to_string()).collect();
662
663 self.actors.clear();
664 self.scripted.clear();
665
666 names
667 }
668
669 fn clear(&mut self) {
670 self.actors.clear();
671 self.scripted.clear();
672 }
673
674 fn serialize(&self) -> serde_json::Value {
675 let rows: Vec<serde_json::Value> = self
676 .actors
677 .iter()
678 .map(|(id, a)| serde_json::json!({ "id": id, "x": a.x, "y": a.y, "team": a.team }))
679 .collect();
680
681 serde_json::json!({ "actors": rows })
682 }
683
684 fn deserialize(&mut self, value: serde_json::Value) -> Result<(), String> {
685 let rows = value["actors"].as_array().ok_or("missing actors")?;
686
687 self.actors.clear();
688
689 for row in rows {
690 let id = row["id"].as_u64().ok_or("bad id")? as u32;
691 let x = row["x"].as_f64().ok_or("bad x")? as f32;
692 let y = row["y"].as_f64().ok_or("bad y")? as f32;
693 let team = row["team"].as_u64().ok_or("bad team")? as u8;
694
695 self.actors.insert(id, TestActor { x, y, vx: 0.0, vy: 0.0, team, alive: true });
696 }
697
698 Ok(())
699 }
700
701 fn rebuild_spatial_grid(&self, _world: &PhysicsWorld, _spatial: &mut SpatialGrid) {}
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::fixture::{TestConfig, TestGame};
708 use super::*;
709 use crate::snapshot::SnapshotPacker;
710
711 fn engine_config() -> EngineConfig {
712 serde_json::from_value(serde_json::json!({
713 "timeStep": 1.0 / 120.0,
714 "snapshot": {
715 "version": 3,
716 "port": 5,
717 "keys": {
718 "actor": { "id": 1, "kind": "indexed8", "class": "hot", "fields": [
719 { "name": "x", "ty": "f32", "interp": "lerp" },
720 { "name": "y", "ty": "f32", "interp": "lerp" }
721 ] }
722 }
723 },
724 "seed": 42
725 }))
726 .unwrap()
727 }
728
729 fn make_sim() -> EngineSim<TestGame> {
730 EngineSim::new(engine_config(), &TestConfig {})
731 }
732
733 #[test]
734 fn spawn_actor_and_fixed_step_moves_position() {
735 let mut sim = make_sim();
736
737 sim.spawn_actor(1, "m", 1, 0.0, 0.0, 0.0).unwrap();
738 sim.apply_input(1, 1, "down", "forward");
739
740 for _ in 0..60 {
741 sim.step(1.0 / 120.0);
742 }
743
744 let pos = sim.actor_position(1).unwrap();
745
746 assert!(pos[1] < 0.0); }
748
749 #[test]
750 fn remove_actor_clears_state() {
751 let mut sim = make_sim();
752
753 sim.spawn_actor(1, "m", 1, 5.0, 5.0, 0.0).unwrap();
754 assert!(sim.is_alive(1));
755
756 sim.remove_actor(1);
757 assert!(!sim.is_alive(1));
758 assert!(sim.actor_position(1).is_none());
759 }
760
761 #[test]
762 fn scripted_actor_runs_ai_tick() {
763 let mut sim = make_sim();
764
765 sim.spawn_scripted_actor(9, "m", 1, 0.0, 0.0, 0.0).unwrap();
766
767 sim.step(1.0 / 120.0);
770 sim.step(1.0 / 120.0);
771
772 let after = sim.actor_position(9).unwrap();
773
774 assert!(after[0] > 0.0); }
776
777 #[test]
778 fn build_snapshot_blocks_packs_through_generic_schema() {
779 let mut sim = make_sim();
780
781 sim.spawn_actor(1, "m", 1, 3.0, 4.0, 0.0).unwrap();
782 sim.spawn_actor(2, "m", 1, 7.0, 8.0, 0.0).unwrap();
783
784 let blocks = sim.build_snapshot_blocks();
785 let mut packer = SnapshotPacker::new(engine_config().snapshot);
786
787 assert!(packer.pack_body(&blocks).is_ok());
788 }
789
790 #[test]
791 fn clear_removes_all_actors() {
792 let mut sim = make_sim();
793
794 sim.spawn_actor(1, "m", 1, 0.0, 0.0, 0.0).unwrap();
795 sim.spawn_scripted_actor(2, "m", 1, 0.0, 0.0, 0.0).unwrap();
796
797 sim.clear();
798
799 assert!(!sim.is_alive(1));
800 assert!(!sim.is_alive(2));
801 assert_eq!(sim.alive_players_flat().len(), 0);
802 }
803
804 fn tiny_map_json() -> &'static str {
807 r#"{
808 "setId": "tiny",
809 "scale": 1,
810 "step": 10,
811 "map": [[1, 0], [0, 0]],
812 "physicsStatic": [1],
813 "respawns": { "team1": [[5, 5, 0]] }
814 }"#
815 }
816
817 #[test]
818 fn debug_json_dumps_world_map_and_rng() {
819 let mut sim = make_sim();
820
821 sim.load_map(tiny_map_json()).unwrap();
822
823 let dump: serde_json::Value = serde_json::from_str(&sim.debug_json()).unwrap();
824
825 let bodies = dump["bodies"].as_array().unwrap();
826 let colliders = dump["colliders"].as_array().unwrap();
827
828 assert_eq!(bodies.len(), 1);
829 assert_eq!(colliders.len(), 1);
830 assert_eq!(bodies[0]["bodyType"], "Fixed");
831 assert_eq!(bodies[0]["translation"], serde_json::json!([5.0, 5.0]));
832 assert_eq!(colliders[0]["shape"], "cuboid");
833 assert_eq!(colliders[0]["halfExtents"], serde_json::json!([5.0, 5.0]));
834 assert_eq!(colliders[0]["isSensor"], false);
835 assert_eq!(colliders[0]["parent"], bodies[0]["handle"]);
836
837 assert_eq!(dump["map"]["setId"], "tiny");
838 assert_eq!(dump["map"]["staticBodies"], 1);
839 assert_eq!(dump["map"]["grid"]["rows"], 2);
840 assert_eq!(dump["map"]["respawns"]["team1"], 1);
841
842 assert!(dump["nav"]["nodes"].as_u64().unwrap() > 0);
843 assert_eq!(dump["spatial"]["cells"], 0);
844 assert_eq!(dump["rng"]["state"], "42");
845 assert_eq!(dump["step"]["accumulator"], 0.0);
846 }
847
848 #[test]
849 fn debug_json_is_null_for_map_and_nav_without_map() {
850 let dump: serde_json::Value = serde_json::from_str(&make_sim().debug_json()).unwrap();
851
852 assert!(dump["map"].is_null());
853 assert!(dump["nav"].is_null());
854 assert_eq!(dump["bodies"].as_array().unwrap().len(), 0);
855 }
856
857 #[test]
858 fn debug_json_is_stable_between_identical_runs() {
859 let mut a = make_sim();
860 let mut b = make_sim();
861
862 for sim in [&mut a, &mut b] {
863 sim.load_map(tiny_map_json()).unwrap();
864 sim.spawn_actor(1, "m", 1, 3.0, 4.0, 0.0).unwrap();
865 sim.step(1.0 / 120.0);
866 }
867
868 assert_eq!(a.debug_json(), b.debug_json());
869 }
870
871 #[test]
872 fn serialize_deserialize_round_trips_actors() {
873 let mut sim = make_sim();
874
875 sim.spawn_actor(1, "m", 3, 11.0, 22.0, 0.0).unwrap();
876
877 let dump = sim.sim.serialize();
878 let mut restored = make_sim();
879
880 restored.sim.deserialize(dump).unwrap();
881
882 assert_eq!(restored.actor_position(1), Some([11.0, 22.0]));
883 }
884}