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 {
297 let with_velocities = self
298 .cfg
299 .snapshot
300 .keys
301 .get(&map.set_id)
302 .is_some_and(|schema| schema.optional_from.is_some());
303
304 blocks.push((
305 map.set_id.clone(),
306 Block::IndexedNoNull8(map.dynamic_map_data(&self.world, with_velocities)),
307 ));
308 }
309
310 self.last_body_has_events = has_events;
311
312 blocks
313 }
314
315 pub fn body_has_events(&self) -> bool {
318 self.last_body_has_events
319 }
320
321 pub fn remove_players_and_shots(&mut self) -> Vec<String> {
326 self.sim.remove_players_and_shots(&mut self.world)
327 }
328
329 pub fn clear(&mut self) {
331 if let Some(mut map) = self.map.take() {
334 map.destroy(&mut self.world);
335 }
336
337 let handles: Vec<RigidBodyHandle> = self.world.rigid_bodies().map(|(handle, _)| handle).collect();
338
339 for handle in handles {
340 self.world.remove_body(handle);
341 }
342
343 self.sim.clear();
344 self.nav = None;
345 self.spatial.clear();
346 self.bodies_to_destroy.clear();
347
348 self.accumulator = 0.0;
349 }
350
351 pub fn debug_json(&self) -> String {
357 crate::debug::engine_json(
358 &self.world,
359 &self.map,
360 &self.nav,
361 &self.spatial,
362 &self.rng,
363 self.accumulator,
364 self.time_step,
365 )
366 .to_string()
367 }
368
369 pub fn serialize_state(&self) -> Result<Vec<u8>, String> {
375 let dump = EngineDump {
376 world: WorldDump {
377 gravity: [self.world.gravity.x, self.world.gravity.y],
378 integration_parameters: self.world.integration_parameters,
379 islands: self.world.islands.clone(),
380 broad_phase: self.world.broad_phase.clone(),
381 narrow_phase: self.world.narrow_phase.clone(),
382 bodies: self.world.bodies.clone(),
383 colliders: self.world.colliders.clone(),
384 impulse_joints: self.world.impulse_joints.clone(),
385 multibody_joints: self.world.multibody_joints.clone(),
386 },
387 map: &self.map,
388 rng: &self.rng,
389 accumulator: self.accumulator,
390 sim: self.sim.serialize(),
391 };
392
393 serde_json::to_vec(&dump).map_err(|e| e.to_string())
394 }
395
396 pub fn deserialize_state(&mut self, data: &[u8]) -> Result<(), String> {
399 let dump: EngineDumpOwned = serde_json::from_slice(data).map_err(|e| e.to_string())?;
400
401 let mut world = PhysicsWorld::new();
402
403 world.gravity = Vector::new(dump.world.gravity[0], dump.world.gravity[1]);
404 world.integration_parameters = dump.world.integration_parameters;
405 world.islands = dump.world.islands;
406 world.broad_phase = dump.world.broad_phase;
407 world.narrow_phase = dump.world.narrow_phase;
408 world.bodies = dump.world.bodies;
409 world.colliders = dump.world.colliders;
410 world.impulse_joints = dump.world.impulse_joints;
411 world.multibody_joints = dump.world.multibody_joints;
412
413 self.world = world;
414 self.map = dump.map;
415 self.rng = dump.rng;
416 self.accumulator = dump.accumulator;
417 self.sim.deserialize(dump.sim)?;
418
419 self.bodies_to_destroy.clear();
420 self.events.clear();
421
422 self.nav = self
425 .map
426 .as_ref()
427 .map(|map| NavigationSystem::generate(&map.grid, &map.physics_static, map.step));
428
429 self.sim.rebuild_spatial_grid(&self.world, &mut self.spatial);
430 self.sim.refresh_cached(&self.world);
431
432 Ok(())
433 }
434}
435
436#[derive(Serialize)]
437struct WorldDump {
438 gravity: [f32; 2],
439 integration_parameters: IntegrationParameters,
440 islands: IslandManager,
441 broad_phase: BroadPhaseBvh,
442 narrow_phase: NarrowPhase,
443 bodies: RigidBodySet,
444 colliders: ColliderSet,
445 impulse_joints: ImpulseJointSet,
446 multibody_joints: MultibodyJointSet,
447}
448
449#[derive(Deserialize)]
450struct WorldDumpOwned {
451 gravity: [f32; 2],
452 integration_parameters: IntegrationParameters,
453 islands: IslandManager,
454 broad_phase: BroadPhaseBvh,
455 narrow_phase: NarrowPhase,
456 bodies: RigidBodySet,
457 colliders: ColliderSet,
458 impulse_joints: ImpulseJointSet,
459 multibody_joints: MultibodyJointSet,
460}
461
462#[derive(Serialize)]
463struct EngineDump<'a> {
464 world: WorldDump,
465 map: &'a Option<GameMap>,
466 rng: &'a Rng,
467 accumulator: f32,
468 sim: serde_json::Value,
469}
470
471#[derive(Deserialize)]
472struct EngineDumpOwned {
473 world: WorldDumpOwned,
474 map: Option<GameMap>,
475 rng: Rng,
476 accumulator: f32,
477 sim: serde_json::Value,
478}
479
480#[cfg(test)]
487mod fixture {
488 use super::*;
489 use crate::config::FieldValue;
490 use serde::Deserialize;
491 use std::collections::{BTreeMap, BTreeSet};
492
493 #[derive(Deserialize)]
494 pub struct TestConfig {}
495
496 pub struct TestGame;
497
498 impl GameDef for TestGame {
499 type Config = TestConfig;
500 type Sim = TestSim;
501 }
502
503 #[derive(Clone, Copy)]
504 struct TestActor {
505 x: f32,
506 y: f32,
507 vx: f32,
508 vy: f32,
509 team: u8,
510 alive: bool,
511 }
512
513 pub struct TestSim {
514 actors: BTreeMap<u32, TestActor>,
515 scripted: BTreeSet<u32>,
516 }
517
518 impl GameSim<TestGame> for TestSim {
519 fn new(_cfg: &TestConfig, _engine_cfg: &EngineConfig) -> Self {
520 Self {
521 actors: BTreeMap::new(),
522 scripted: BTreeSet::new(),
523 }
524 }
525
526 fn spawn_actor(
527 &mut self,
528 _world: &mut PhysicsWorld,
529 _events: &mut Vec<CoreEvent>,
530 game_id: u32,
531 _model_name: &str,
532 team_id: u8,
533 x: f32,
534 y: f32,
535 _angle_deg: f32,
536 ) -> Result<(), String> {
537 self.actors.insert(
538 game_id,
539 TestActor { x, y, vx: 0.0, vy: 0.0, team: team_id, alive: true },
540 );
541
542 Ok(())
543 }
544
545 fn remove_actor(&mut self, _world: &mut PhysicsWorld, game_id: u32) {
546 self.actors.remove(&game_id);
547 self.scripted.remove(&game_id);
548 }
549
550 fn reset_actor(&mut self, _world: &mut PhysicsWorld, game_id: u32, team_id: u8, x: f32, y: f32, _angle_deg: f32) {
551 if let Some(actor) = self.actors.get_mut(&game_id) {
552 actor.x = x;
553 actor.y = y;
554 actor.team = team_id;
555 actor.alive = true;
556 }
557 }
558
559 fn reset_all_vitals(&mut self, _events: &mut Vec<CoreEvent>) {
560 for actor in self.actors.values_mut() {
561 actor.alive = true;
562 }
563 }
564
565 fn spawn_scripted_actor(
566 &mut self,
567 world: &mut PhysicsWorld,
568 _rng: &mut Rng,
569 events: &mut Vec<CoreEvent>,
570 game_id: u32,
571 model_name: &str,
572 team_id: u8,
573 x: f32,
574 y: f32,
575 angle_deg: f32,
576 ) -> Result<(), String> {
577 self.spawn_actor(world, events, game_id, model_name, team_id, x, y, angle_deg)?;
578 self.scripted.insert(game_id);
579
580 Ok(())
581 }
582
583 fn remove_scripted_actor(&mut self, world: &mut PhysicsWorld, game_id: u32) {
584 self.remove_actor(world, game_id);
585 }
586
587 fn apply_input(&mut self, game_id: u32, _seq: u32, action: &str, key_name: &str) {
588 let Some(actor) = self.actors.get_mut(&game_id) else {
589 return;
590 };
591
592 let magnitude = if action == "down" { 40.0 } else { 0.0 };
593
594 match key_name {
595 "forward" => actor.vy = -magnitude,
596 "back" => actor.vy = magnitude,
597 _ => {}
598 }
599 }
600
601 fn last_input_seq(&self, _game_id: u32) -> u32 {
602 0
603 }
604
605 fn is_alive(&self, game_id: u32) -> bool {
606 self.actors.get(&game_id).is_some_and(|a| a.alive)
607 }
608
609 fn actor_position(&self, _world: &PhysicsWorld, game_id: u32) -> Option<[f32; 2]> {
610 self.actors.get(&game_id).map(|a| [a.x, a.y])
611 }
612
613 fn prediction_state(&self, _world: &PhysicsWorld, game_id: u32) -> Option<([f32; PLAYER_STATE_LEN], bool)> {
614 self.actors
615 .get(&game_id)
616 .map(|a| ([a.x, a.y, 0.0, a.vx, a.vy, 0.0, 0.0, 0.0], false))
617 }
618
619 fn alive_players_flat(&self, _world: &PhysicsWorld) -> Vec<f32> {
620 self.actors
621 .iter()
622 .filter(|(_, a)| a.alive)
623 .flat_map(|(id, a)| [*id as f32, a.x, a.y])
624 .collect()
625 }
626
627 fn players_json(&self) -> String {
628 let rows: Vec<serde_json::Value> = self
629 .actors
630 .iter()
631 .map(|(id, a)| serde_json::json!({ "id": id, "x": a.x, "y": a.y, "team": a.team }))
632 .collect();
633
634 serde_json::to_string(&rows).unwrap()
635 }
636
637 fn on_fixed_step(&mut self, _ctx: &mut SimCtx, dt: f32) {
638 for actor in self.actors.values_mut() {
639 actor.x += actor.vx * dt;
640 actor.y += actor.vy * dt;
641 }
642 }
643
644 fn on_contacts(&mut self, _ctx: &mut SimCtx, _pairs: &[(ColliderHandle, ColliderHandle)]) {}
645
646 fn on_before_destroy(&mut self, _world: &PhysicsWorld, _handle: RigidBodyHandle) {}
647
648 fn on_ai_tick(&mut self, _ctx: &mut SimCtx, _dt: f32) {
649 for &id in &self.scripted {
651 if let Some(actor) = self.actors.get_mut(&id) {
652 actor.vx = 1.0;
653 }
654 }
655 }
656
657 fn refresh_cached(&mut self, _world: &PhysicsWorld) {}
658
659 fn build_snapshot_blocks(&mut self) -> (Vec<(String, Block)>, bool) {
660 let rows: Vec<(u8, Option<Vec<FieldValue>>)> = self
661 .actors
662 .iter()
663 .map(|(id, a)| (*id as u8, Some(vec![FieldValue::F32(a.x), FieldValue::F32(a.y)])))
664 .collect();
665
666 (vec![("actor".to_string(), Block::Indexed8(rows))], false)
667 }
668
669 fn remove_players_and_shots(&mut self, _world: &mut PhysicsWorld) -> Vec<String> {
670 let names: Vec<String> = self.actors.keys().map(|id| id.to_string()).collect();
671
672 self.actors.clear();
673 self.scripted.clear();
674
675 names
676 }
677
678 fn clear(&mut self) {
679 self.actors.clear();
680 self.scripted.clear();
681 }
682
683 fn serialize(&self) -> serde_json::Value {
684 let rows: Vec<serde_json::Value> = self
685 .actors
686 .iter()
687 .map(|(id, a)| serde_json::json!({ "id": id, "x": a.x, "y": a.y, "team": a.team }))
688 .collect();
689
690 serde_json::json!({ "actors": rows })
691 }
692
693 fn deserialize(&mut self, value: serde_json::Value) -> Result<(), String> {
694 let rows = value["actors"].as_array().ok_or("missing actors")?;
695
696 self.actors.clear();
697
698 for row in rows {
699 let id = row["id"].as_u64().ok_or("bad id")? as u32;
700 let x = row["x"].as_f64().ok_or("bad x")? as f32;
701 let y = row["y"].as_f64().ok_or("bad y")? as f32;
702 let team = row["team"].as_u64().ok_or("bad team")? as u8;
703
704 self.actors.insert(id, TestActor { x, y, vx: 0.0, vy: 0.0, team, alive: true });
705 }
706
707 Ok(())
708 }
709
710 fn rebuild_spatial_grid(&self, _world: &PhysicsWorld, _spatial: &mut SpatialGrid) {}
711 }
712}
713
714#[cfg(test)]
715mod tests {
716 use super::fixture::{TestConfig, TestGame};
717 use super::*;
718 use crate::snapshot::SnapshotPacker;
719
720 fn engine_config() -> EngineConfig {
721 serde_json::from_value(serde_json::json!({
722 "timeStep": 1.0 / 120.0,
723 "snapshot": {
724 "version": 3,
725 "port": 5,
726 "keys": {
727 "actor": { "id": 1, "kind": "indexed8", "class": "hot", "fields": [
728 { "name": "x", "ty": "f32", "interp": "lerp" },
729 { "name": "y", "ty": "f32", "interp": "lerp" }
730 ] }
731 }
732 },
733 "seed": 42
734 }))
735 .unwrap()
736 }
737
738 fn make_sim() -> EngineSim<TestGame> {
739 EngineSim::new(engine_config(), &TestConfig {})
740 }
741
742 #[test]
743 fn spawn_actor_and_fixed_step_moves_position() {
744 let mut sim = make_sim();
745
746 sim.spawn_actor(1, "m", 1, 0.0, 0.0, 0.0).unwrap();
747 sim.apply_input(1, 1, "down", "forward");
748
749 for _ in 0..60 {
750 sim.step(1.0 / 120.0);
751 }
752
753 let pos = sim.actor_position(1).unwrap();
754
755 assert!(pos[1] < 0.0); }
757
758 #[test]
759 fn remove_actor_clears_state() {
760 let mut sim = make_sim();
761
762 sim.spawn_actor(1, "m", 1, 5.0, 5.0, 0.0).unwrap();
763 assert!(sim.is_alive(1));
764
765 sim.remove_actor(1);
766 assert!(!sim.is_alive(1));
767 assert!(sim.actor_position(1).is_none());
768 }
769
770 #[test]
771 fn scripted_actor_runs_ai_tick() {
772 let mut sim = make_sim();
773
774 sim.spawn_scripted_actor(9, "m", 1, 0.0, 0.0, 0.0).unwrap();
775
776 sim.step(1.0 / 120.0);
779 sim.step(1.0 / 120.0);
780
781 let after = sim.actor_position(9).unwrap();
782
783 assert!(after[0] > 0.0); }
785
786 #[test]
787 fn build_snapshot_blocks_packs_through_generic_schema() {
788 let mut sim = make_sim();
789
790 sim.spawn_actor(1, "m", 1, 3.0, 4.0, 0.0).unwrap();
791 sim.spawn_actor(2, "m", 1, 7.0, 8.0, 0.0).unwrap();
792
793 let blocks = sim.build_snapshot_blocks();
794 let mut packer = SnapshotPacker::new(engine_config().snapshot);
795
796 assert!(packer.pack_body(&blocks).is_ok());
797 }
798
799 #[test]
800 fn clear_removes_all_actors() {
801 let mut sim = make_sim();
802
803 sim.spawn_actor(1, "m", 1, 0.0, 0.0, 0.0).unwrap();
804 sim.spawn_scripted_actor(2, "m", 1, 0.0, 0.0, 0.0).unwrap();
805
806 sim.clear();
807
808 assert!(!sim.is_alive(1));
809 assert!(!sim.is_alive(2));
810 assert_eq!(sim.alive_players_flat().len(), 0);
811 }
812
813 fn tiny_map_json() -> &'static str {
816 r#"{
817 "setId": "tiny",
818 "scale": 1,
819 "step": 10,
820 "map": [[1, 0], [0, 0]],
821 "physicsStatic": [1],
822 "respawns": { "team1": [[5, 5, 0]] }
823 }"#
824 }
825
826 #[test]
827 fn debug_json_dumps_world_map_and_rng() {
828 let mut sim = make_sim();
829
830 sim.load_map(tiny_map_json()).unwrap();
831
832 let dump: serde_json::Value = serde_json::from_str(&sim.debug_json()).unwrap();
833
834 let bodies = dump["bodies"].as_array().unwrap();
835 let colliders = dump["colliders"].as_array().unwrap();
836
837 assert_eq!(bodies.len(), 1);
838 assert_eq!(colliders.len(), 1);
839 assert_eq!(bodies[0]["bodyType"], "Fixed");
840 assert_eq!(bodies[0]["translation"], serde_json::json!([5.0, 5.0]));
841 assert_eq!(colliders[0]["shape"], "cuboid");
842 assert_eq!(colliders[0]["halfExtents"], serde_json::json!([5.0, 5.0]));
843 assert_eq!(colliders[0]["isSensor"], false);
844 assert_eq!(colliders[0]["parent"], bodies[0]["handle"]);
845
846 assert_eq!(dump["map"]["setId"], "tiny");
847 assert_eq!(dump["map"]["staticBodies"], 1);
848 assert_eq!(dump["map"]["grid"]["rows"], 2);
849 assert_eq!(dump["map"]["respawns"]["team1"], 1);
850
851 assert!(dump["nav"]["nodes"].as_u64().unwrap() > 0);
852 assert_eq!(dump["spatial"]["cells"], 0);
853 assert_eq!(dump["rng"]["state"], "42");
854 assert_eq!(dump["step"]["accumulator"], 0.0);
855 }
856
857 #[test]
858 fn debug_json_is_null_for_map_and_nav_without_map() {
859 let dump: serde_json::Value = serde_json::from_str(&make_sim().debug_json()).unwrap();
860
861 assert!(dump["map"].is_null());
862 assert!(dump["nav"].is_null());
863 assert_eq!(dump["bodies"].as_array().unwrap().len(), 0);
864 }
865
866 #[test]
867 fn debug_json_is_stable_between_identical_runs() {
868 let mut a = make_sim();
869 let mut b = make_sim();
870
871 for sim in [&mut a, &mut b] {
872 sim.load_map(tiny_map_json()).unwrap();
873 sim.spawn_actor(1, "m", 1, 3.0, 4.0, 0.0).unwrap();
874 sim.step(1.0 / 120.0);
875 }
876
877 assert_eq!(a.debug_json(), b.debug_json());
878 }
879
880 #[test]
881 fn serialize_deserialize_round_trips_actors() {
882 let mut sim = make_sim();
883
884 sim.spawn_actor(1, "m", 3, 11.0, 22.0, 0.0).unwrap();
885
886 let dump = sim.sim.serialize();
887 let mut restored = make_sim();
888
889 restored.sim.deserialize(dump).unwrap();
890
891 assert_eq!(restored.actor_position(1), Some([11.0, 22.0]));
892 }
893}