elevator_core/snapshot.rs
1//! World snapshot for save/load functionality.
2//!
3//! Provides [`WorldSnapshot`](crate::snapshot::WorldSnapshot) which captures the full simulation state
4//! (all entities, components, groups, metrics, tick counter) in a
5//! serializable form. Games choose the serialization format via serde.
6//!
7//! Extension component *data* is included in the snapshot. After restoring,
8//! call [`Simulation::load_extensions_with`](crate::sim::Simulation::load_extensions_with)
9//! to register types and materialize the data.
10
11use crate::components::{
12 AccessControl, CarCall, DestinationQueue, Elevator, HallCall, Line, Patience, Position,
13 Preferences, Rider, Route, Stop, Velocity,
14};
15use crate::entity::EntityId;
16use crate::ids::GroupId;
17use crate::metrics::Metrics;
18use crate::stop::StopId;
19use crate::tagged_metrics::MetricTags;
20use serde::{Deserialize, Serialize};
21use std::collections::{BTreeMap, HashMap, HashSet};
22
23/// Serializable snapshot of a single entity's components.
24#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct EntitySnapshot {
26 /// The original `EntityId` (used for remapping cross-references on restore).
27 pub original_id: EntityId,
28 /// Position component (if present).
29 pub position: Option<Position>,
30 /// Velocity component (if present).
31 pub velocity: Option<Velocity>,
32 /// Elevator component (if present).
33 pub elevator: Option<Elevator>,
34 /// Stop component (if present).
35 pub stop: Option<Stop>,
36 /// Rider component (if present).
37 pub rider: Option<Rider>,
38 /// Route component (if present).
39 pub route: Option<Route>,
40 /// Line component (if present).
41 #[serde(default)]
42 pub line: Option<Line>,
43 /// Patience component (if present).
44 pub patience: Option<Patience>,
45 /// Preferences component (if present).
46 pub preferences: Option<Preferences>,
47 /// Access control component (if present).
48 #[serde(default)]
49 pub access_control: Option<AccessControl>,
50 /// Whether this entity is disabled.
51 pub disabled: bool,
52 /// Energy profile (if present, requires `energy` feature).
53 #[cfg(feature = "energy")]
54 #[serde(default)]
55 pub energy_profile: Option<crate::energy::EnergyProfile>,
56 /// Energy metrics (if present, requires `energy` feature).
57 #[cfg(feature = "energy")]
58 #[serde(default)]
59 pub energy_metrics: Option<crate::energy::EnergyMetrics>,
60 /// Service mode (if present).
61 #[serde(default)]
62 pub service_mode: Option<crate::components::ServiceMode>,
63 /// Destination queue (per-elevator; absent in legacy snapshots).
64 #[serde(default)]
65 pub destination_queue: Option<DestinationQueue>,
66 /// Car calls pressed inside this elevator (per-car; absent in legacy snapshots).
67 #[serde(default)]
68 pub car_calls: Vec<CarCall>,
69}
70
71/// Serializable snapshot of the entire simulation state.
72///
73/// Capture via [`Simulation::snapshot()`](crate::sim::Simulation::snapshot)
74/// and restore via [`WorldSnapshot::restore()`]. The game chooses the serde format
75/// (RON, JSON, bincode, etc.).
76///
77/// **Determinism:** the map fields below all use `BTreeMap` instead of
78/// `HashMap` so postcard/RON/JSON serialize entries in a deterministic
79/// (key-sorted) order. With `HashMap`, two snapshots of the same sim
80/// taken in different processes produced different bytes, defeating
81/// content-addressed caching and bit-equality replay (#254).
82///
83/// **Extension components are included** (via `extensions`); games must
84/// register types via `register_ext` before `restore()` to materialize them.
85/// **Custom resources** inserted via `world.insert_resource` are NOT
86/// snapshotted — only the built-in `MetricTags` resource is captured
87/// in `metric_tags`. Games using custom resources must save and restore
88/// them out-of-band (#296).
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct WorldSnapshot {
91 /// Schema version of this snapshot. Bumped on incompatible changes
92 /// to the snapshot layout. Loading a snapshot whose version differs
93 /// from the current crate's expected version returns
94 /// [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion).
95 /// Legacy snapshots default to `0` (#295).
96 #[serde(default)]
97 pub version: u32,
98 /// Current simulation tick.
99 pub tick: u64,
100 /// Time delta per tick.
101 pub dt: f64,
102 /// All entities indexed by position in this vec.
103 /// `EntityId`s are regenerated on restore.
104 pub entities: Vec<EntitySnapshot>,
105 /// Elevator groups (references into entities by index).
106 pub groups: Vec<GroupSnapshot>,
107 /// Stop ID → entity index mapping. `BTreeMap` for deterministic
108 /// snapshot bytes across processes (#254).
109 pub stop_lookup: BTreeMap<StopId, usize>,
110 /// Global metrics at snapshot time.
111 pub metrics: Metrics,
112 /// Per-tag metric accumulators and entity-tag associations.
113 pub metric_tags: MetricTags,
114 /// Serialized extension component data: name → (`EntityId` → RON string).
115 /// Both maps are `BTreeMap` for deterministic snapshot bytes (#254).
116 pub extensions: BTreeMap<String, BTreeMap<EntityId, String>>,
117 /// Ticks per second (for `TimeAdapter` reconstruction).
118 pub ticks_per_second: f64,
119 /// All pending hall calls across every stop. Absent in legacy snapshots.
120 #[serde(default)]
121 pub hall_calls: Vec<HallCall>,
122 /// Rolling per-stop arrival log. Empty in legacy snapshots; on
123 /// restore the log's `(tick, stop)` entries have their stop IDs
124 /// remapped through `id_remap` so they line up with the newly
125 /// allocated entity IDs.
126 #[serde(default)]
127 pub arrival_log: crate::arrival_log::ArrivalLog,
128 /// Retention window for the arrival log (ticks). Captured so a
129 /// host-configured value (e.g. via
130 /// `Simulation::set_arrival_log_retention_ticks`) survives
131 /// snapshot round-trip; legacy snapshots default to
132 /// [`DEFAULT_ARRIVAL_WINDOW_TICKS`](crate::arrival_log::DEFAULT_ARRIVAL_WINDOW_TICKS).
133 #[serde(default)]
134 pub arrival_log_retention: crate::arrival_log::ArrivalLogRetention,
135 /// Mirror of `arrival_log` keyed on rider *destination* — what
136 /// powers the `DownPeak` classifier branch. Same remap semantics
137 /// as `arrival_log` on restore. Empty in legacy snapshots; the
138 /// detector silently under-classifies `DownPeak` until the post-
139 /// restore log refills.
140 #[serde(default)]
141 pub destination_log: crate::arrival_log::DestinationLog,
142 /// Traffic-mode classifier state. Carries the current mode,
143 /// thresholds, and last-update tick across snapshot round-trip
144 /// so a restored sim doesn't momentarily reset to `Idle` when
145 /// the metrics phase hasn't run yet.
146 #[serde(default)]
147 pub traffic_detector: crate::traffic_detector::TrafficDetector,
148 /// Per-car reposition cooldown eligibility. Entries map to the
149 /// tick when each car next becomes eligible for reposition. Empty
150 /// in legacy snapshots; on restore the map is remapped through
151 /// `id_remap` to match newly-allocated entity IDs.
152 #[serde(default)]
153 pub reposition_cooldowns: crate::dispatch::reposition::RepositionCooldowns,
154 /// Per-group serialized dispatcher configuration produced by
155 /// [`crate::dispatch::DispatchStrategy::snapshot_config`] and
156 /// replayed via
157 /// [`crate::dispatch::DispatchStrategy::restore_config`] on
158 /// restore. Round-trips the tunable weights configured via
159 /// `with_*` builder methods (e.g. `EtdDispatch::with_delay_weight`)
160 /// that [`BuiltinStrategy::instantiate`](crate::dispatch::BuiltinStrategy::instantiate)
161 /// can't reconstruct because it always calls `::new()`. Absent /
162 /// empty in legacy snapshots — they restore to default weights,
163 /// matching pre-fix behaviour.
164 #[serde(default)]
165 pub dispatch_config: BTreeMap<GroupId, String>,
166}
167
168/// Per-line snapshot info within a group.
169#[derive(Debug, Clone, Serialize, Deserialize)]
170pub struct LineSnapshotInfo {
171 /// Index into the `entities` vec for the line entity.
172 pub entity_index: usize,
173 /// Indices into the `entities` vec for elevators on this line.
174 pub elevator_indices: Vec<usize>,
175 /// Indices into the `entities` vec for stops served by this line.
176 pub stop_indices: Vec<usize>,
177}
178
179/// Serializable representation of an elevator group.
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct GroupSnapshot {
182 /// Group identifier.
183 pub id: GroupId,
184 /// Group name.
185 pub name: String,
186 /// Indices into the `entities` vec for elevators in this group.
187 pub elevator_indices: Vec<usize>,
188 /// Indices into the `entities` vec for stops in this group.
189 pub stop_indices: Vec<usize>,
190 /// The dispatch strategy used by this group.
191 pub strategy: crate::dispatch::BuiltinStrategy,
192 /// Per-line snapshot data. Empty in legacy snapshots.
193 #[serde(default)]
194 pub lines: Vec<LineSnapshotInfo>,
195 /// Optional repositioning strategy for idle elevators.
196 #[serde(default)]
197 pub reposition: Option<crate::dispatch::BuiltinReposition>,
198 /// Hall call mode for this group. Legacy snapshots default to `Classic`.
199 #[serde(default)]
200 pub hall_call_mode: crate::dispatch::HallCallMode,
201 /// Controller ack latency in ticks. Legacy snapshots default to `0`.
202 #[serde(default)]
203 pub ack_latency_ticks: u32,
204}
205
206/// Pending extension data from a snapshot, awaiting type registration.
207///
208/// Stored as a world resource after `restore()`. Call
209/// `sim.load_extensions()` after registering extension types to
210/// deserialize the data.
211pub(crate) struct PendingExtensions(pub(crate) BTreeMap<String, BTreeMap<EntityId, String>>);
212
213/// Factory function type for instantiating custom dispatch strategies by name.
214type CustomStrategyFactory<'a> =
215 Option<&'a dyn Fn(&str) -> Option<Box<dyn crate::dispatch::DispatchStrategy>>>;
216
217impl WorldSnapshot {
218 /// Restore a simulation from this snapshot.
219 ///
220 /// Built-in strategies (Scan, Look, `NearestCar`, ETD) are auto-restored.
221 /// For `Custom` strategies, provide a factory function that maps strategy
222 /// names to instances. Pass `None` if only using built-in strategies.
223 ///
224 /// # Errors
225 /// Returns [`SimError::UnresolvedCustomStrategy`](crate::error::SimError::UnresolvedCustomStrategy)
226 /// if a snapshot group uses a `Custom` strategy and the factory returns `None`.
227 ///
228 /// To restore extension components, call
229 /// [`Simulation::load_extensions_with`](crate::sim::Simulation::load_extensions_with)
230 /// on the returned simulation.
231 pub fn restore(
232 self,
233 custom_strategy_factory: CustomStrategyFactory<'_>,
234 ) -> Result<crate::sim::Simulation, crate::error::SimError> {
235 use crate::world::{SortedStops, World};
236
237 // Reject snapshots from incompatible schema versions. Without this
238 // guard, `#[serde(default)]` on newly-added fields would silently
239 // fill them in and mask the mismatch. The bytes envelope path
240 // separately checks the crate semver string.
241 if self.version != SNAPSHOT_SCHEMA_VERSION {
242 return Err(crate::error::SimError::SnapshotVersion {
243 saved: format!("schema {}", self.version),
244 current: format!("schema {SNAPSHOT_SCHEMA_VERSION}"),
245 });
246 }
247
248 let mut world = World::new();
249
250 // Phase 1: spawn all entities and build old→new EntityId mapping.
251 let (index_to_id, id_remap) = Self::spawn_entities(&mut world, &self.entities);
252
253 // Phase 2: attach components with remapped EntityIds.
254 Self::attach_components(&mut world, &self.entities, &index_to_id, &id_remap);
255
256 // Phase 2b: re-register hall calls (cross-reference stops/cars/riders).
257 self.attach_hall_calls(&mut world, &id_remap);
258
259 // Rebuild sorted stops index.
260 let mut sorted: Vec<(f64, EntityId)> = world
261 .iter_stops()
262 .map(|(eid, stop)| (stop.position, eid))
263 .collect();
264 sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
265 world.insert_resource(SortedStops(sorted));
266
267 // Rebuild groups, stop lookup, dispatchers, and extensions (borrows self).
268 let (mut groups, stop_lookup, dispatchers, strategy_ids) =
269 self.rebuild_groups_and_dispatchers(&index_to_id, custom_strategy_factory)?;
270
271 Self::fix_legacy_line_entities(&mut groups, &mut world);
272
273 // Resource installation moves several fields out of self via partial
274 // moves; remaining fields (dispatch_config, groups, entities, hall_calls,
275 // metrics, etc.) stay accessible for the construction steps below.
276 Self::install_runtime_resources(
277 &mut world,
278 &id_remap,
279 self.tick,
280 &self.extensions,
281 self.metric_tags,
282 self.arrival_log,
283 self.arrival_log_retention,
284 self.destination_log,
285 self.traffic_detector,
286 self.reposition_cooldowns,
287 );
288
289 let mut sim = crate::sim::Simulation::from_parts(
290 world,
291 self.tick,
292 self.dt,
293 groups,
294 stop_lookup,
295 dispatchers,
296 strategy_ids,
297 self.metrics,
298 self.ticks_per_second,
299 );
300
301 Self::replay_dispatcher_tuning(&mut sim, &self.dispatch_config);
302 Self::restore_reposition_strategies(&mut sim, &self.groups);
303
304 Self::emit_dangling_warnings(
305 &self.entities,
306 &self.hall_calls,
307 &id_remap,
308 self.tick,
309 &mut sim,
310 );
311
312 Ok(sim)
313 }
314
315 /// Replace synthetic legacy `LineInfo` entries (entity = `EntityId::default()`)
316 /// with real line entities spawned in the world. Pre-line snapshots stored
317 /// only group-level elevator/stop indices; the legacy single-line `LineInfo`
318 /// is materialised here so dispatch and rendering see a real entity.
319 fn fix_legacy_line_entities(
320 groups: &mut [crate::dispatch::ElevatorGroup],
321 world: &mut crate::world::World,
322 ) {
323 for group in groups.iter_mut() {
324 let group_id = group.id();
325 for line_info in group.lines_mut().iter_mut() {
326 if line_info.entity() != EntityId::default() {
327 continue;
328 }
329 let (min_pos, max_pos) = line_info
330 .serves()
331 .iter()
332 .filter_map(|&sid| world.stop(sid).map(|s| s.position))
333 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| {
334 (lo.min(p), hi.max(p))
335 });
336 let line_eid = world.spawn();
337 world.set_line(
338 line_eid,
339 Line {
340 name: format!("Legacy-{group_id}"),
341 group: group_id,
342 orientation: crate::components::Orientation::Vertical,
343 position: None,
344 min_position: if min_pos.is_finite() { min_pos } else { 0.0 },
345 max_position: if max_pos.is_finite() { max_pos } else { 0.0 },
346 max_cars: None,
347 },
348 );
349 for &elev_eid in line_info.elevators() {
350 if let Some(car) = world.elevator_mut(elev_eid) {
351 car.line = line_eid;
352 }
353 }
354 line_info.set_entity(line_eid);
355 }
356 }
357 }
358
359 /// Insert all post-entity world resources, remapping `EntityId`s where
360 /// they cross-reference. Without these `PredictiveParking`,
361 /// `DispatchManifest::arrivals_at`, the down-peak classifier branch,
362 /// host-configured retention, and reposition cooldowns silently no-op
363 /// or fall back to defaults post-restore.
364 #[allow(clippy::too_many_arguments)]
365 fn install_runtime_resources(
366 world: &mut crate::world::World,
367 id_remap: &HashMap<EntityId, EntityId>,
368 tick: u64,
369 extensions: &BTreeMap<String, BTreeMap<EntityId, String>>,
370 metric_tags: MetricTags,
371 arrival_log: crate::arrival_log::ArrivalLog,
372 arrival_log_retention: crate::arrival_log::ArrivalLogRetention,
373 destination_log: crate::arrival_log::DestinationLog,
374 traffic_detector: crate::traffic_detector::TrafficDetector,
375 reposition_cooldowns: crate::dispatch::reposition::RepositionCooldowns,
376 ) {
377 let remapped_exts = Self::remap_extensions(extensions, id_remap);
378 world.insert_resource(PendingExtensions(remapped_exts));
379
380 let mut tags = metric_tags;
381 tags.remap_entity_ids(id_remap);
382 world.insert_resource(tags);
383
384 let mut log = arrival_log;
385 log.remap_entity_ids(id_remap);
386 world.insert_resource(log);
387 world.insert_resource(crate::arrival_log::CurrentTick(tick));
388 world.insert_resource(arrival_log_retention);
389
390 let mut dest_log = destination_log;
391 dest_log.remap_entity_ids(id_remap);
392 world.insert_resource(dest_log);
393
394 // Detector is re-inserted last-writer-wins so the *classified* state
395 // carries forward; refresh_traffic_detector updates on the next
396 // metrics phase with fresh counts.
397 world.insert_resource(traffic_detector);
398
399 let mut cooldowns = reposition_cooldowns;
400 cooldowns.remap_entity_ids(id_remap);
401 world.insert_resource(cooldowns);
402 }
403
404 /// Replay per-group dispatcher tuning captured in the snapshot. Built-ins
405 /// with `with_*` builders override `snapshot_config`/`restore_config` to
406 /// round-trip their weights; strategies that don't override silently skip
407 /// (default `restore_config` is `Ok(())`), preserving pre-fix behaviour. A
408 /// deserialization failure surfaces as an event rather than a hard error
409 /// — the restored sim runs with defaults, same as a legacy snapshot.
410 fn replay_dispatcher_tuning(
411 sim: &mut crate::sim::Simulation,
412 dispatch_config: &std::collections::BTreeMap<GroupId, String>,
413 ) {
414 for (gid, serialized) in dispatch_config {
415 if let Some(dispatcher) = sim.dispatchers_mut().get_mut(gid)
416 && let Err(err) = dispatcher.restore_config(serialized)
417 {
418 sim.push_event(crate::events::Event::DispatchConfigNotRestored {
419 group: *gid,
420 reason: err,
421 });
422 }
423 }
424 }
425
426 /// Restore reposition strategies from group snapshots, emitting
427 /// [`Event::RepositionStrategyNotRestored`](crate::events::Event::RepositionStrategyNotRestored)
428 /// when an id can't be re-instantiated.
429 fn restore_reposition_strategies(sim: &mut crate::sim::Simulation, groups: &[GroupSnapshot]) {
430 for gs in groups {
431 let Some(ref repo_id) = gs.reposition else {
432 continue;
433 };
434 if let Some(strategy) = repo_id.instantiate() {
435 sim.set_reposition(gs.id, strategy, repo_id.clone());
436 } else {
437 sim.push_event(crate::events::Event::RepositionStrategyNotRestored {
438 group: gs.id,
439 });
440 }
441 }
442 }
443
444 /// Spawn entities in the world and build the old→new `EntityId` mapping.
445 fn spawn_entities(
446 world: &mut crate::world::World,
447 entities: &[EntitySnapshot],
448 ) -> (Vec<EntityId>, HashMap<EntityId, EntityId>) {
449 let mut index_to_id: Vec<EntityId> = Vec::with_capacity(entities.len());
450 let mut id_remap: HashMap<EntityId, EntityId> = HashMap::new();
451 for snap in entities {
452 let new_id = world.spawn();
453 index_to_id.push(new_id);
454 id_remap.insert(snap.original_id, new_id);
455 }
456 (index_to_id, id_remap)
457 }
458
459 /// Attach components to spawned entities, remapping cross-references.
460 fn attach_components(
461 world: &mut crate::world::World,
462 entities: &[EntitySnapshot],
463 index_to_id: &[EntityId],
464 id_remap: &HashMap<EntityId, EntityId>,
465 ) {
466 let remap = |old: EntityId| -> EntityId { id_remap.get(&old).copied().unwrap_or(old) };
467 let remap_opt = |old: Option<EntityId>| -> Option<EntityId> { old.map(&remap) };
468
469 for (i, snap) in entities.iter().enumerate() {
470 let eid = index_to_id[i];
471
472 if let Some(pos) = snap.position {
473 world.set_position(eid, pos);
474 }
475 if let Some(vel) = snap.velocity {
476 world.set_velocity(eid, vel);
477 }
478 if let Some(ref elev) = snap.elevator {
479 let mut e = elev.clone();
480 e.riders = e.riders.iter().map(|&r| remap(r)).collect();
481 e.target_stop = remap_opt(e.target_stop);
482 e.line = remap(e.line);
483 e.restricted_stops = e.restricted_stops.iter().map(|&s| remap(s)).collect();
484 e.phase = match e.phase {
485 crate::components::ElevatorPhase::MovingToStop(s) => {
486 crate::components::ElevatorPhase::MovingToStop(remap(s))
487 }
488 crate::components::ElevatorPhase::Repositioning(s) => {
489 crate::components::ElevatorPhase::Repositioning(remap(s))
490 }
491 other => other,
492 };
493 world.set_elevator(eid, e);
494 }
495 if let Some(ref stop) = snap.stop {
496 world.set_stop(eid, stop.clone());
497 }
498 if let Some(ref rider) = snap.rider {
499 use crate::components::RiderPhase;
500 let mut r = rider.clone();
501 r.current_stop = remap_opt(r.current_stop);
502 r.phase = match r.phase {
503 RiderPhase::Boarding(e) => RiderPhase::Boarding(remap(e)),
504 RiderPhase::Riding(e) => RiderPhase::Riding(remap(e)),
505 RiderPhase::Exiting(e) => RiderPhase::Exiting(remap(e)),
506 other => other,
507 };
508 world.set_rider(eid, r);
509 }
510 if let Some(ref route) = snap.route {
511 let mut rt = route.clone();
512 for leg in &mut rt.legs {
513 leg.from = remap(leg.from);
514 leg.to = remap(leg.to);
515 if let crate::components::TransportMode::Line(ref mut l) = leg.via {
516 *l = remap(*l);
517 }
518 }
519 world.set_route(eid, rt);
520 }
521 if let Some(ref line) = snap.line {
522 world.set_line(eid, line.clone());
523 }
524 if let Some(patience) = snap.patience {
525 world.set_patience(eid, patience);
526 }
527 if let Some(prefs) = snap.preferences {
528 world.set_preferences(eid, prefs);
529 }
530 if let Some(ref ac) = snap.access_control {
531 let remapped =
532 AccessControl::new(ac.allowed_stops().iter().map(|&s| remap(s)).collect());
533 world.set_access_control(eid, remapped);
534 }
535 if snap.disabled {
536 world.disable(eid);
537 }
538 #[cfg(feature = "energy")]
539 if let Some(ref profile) = snap.energy_profile {
540 world.set_energy_profile(eid, profile.clone());
541 }
542 #[cfg(feature = "energy")]
543 if let Some(ref em) = snap.energy_metrics {
544 world.set_energy_metrics(eid, em.clone());
545 }
546 if let Some(mode) = snap.service_mode {
547 world.set_service_mode(eid, mode);
548 }
549 if let Some(ref dq) = snap.destination_queue {
550 use crate::components::DestinationQueue as DQ;
551 let mut new_dq = DQ::new();
552 for &e in dq.queue() {
553 new_dq.push_back(remap(e));
554 }
555 world.set_destination_queue(eid, new_dq);
556 }
557 Self::attach_car_calls(world, eid, &snap.car_calls, id_remap);
558 }
559 }
560
561 /// Re-register per-car floor button presses after entities are spawned.
562 fn attach_car_calls(
563 world: &mut crate::world::World,
564 car: EntityId,
565 car_calls: &[CarCall],
566 id_remap: &HashMap<EntityId, EntityId>,
567 ) {
568 if car_calls.is_empty() {
569 return;
570 }
571 let remap = |old: EntityId| -> EntityId { id_remap.get(&old).copied().unwrap_or(old) };
572 let Some(slot) = world.car_calls_mut(car) else {
573 return;
574 };
575 for cc in car_calls {
576 let mut c = cc.clone();
577 c.car = car;
578 c.floor = remap(c.floor);
579 c.pending_riders = c.pending_riders.iter().map(|&r| remap(r)).collect();
580 slot.push(c);
581 }
582 }
583
584 /// Re-register hall calls in the world after entities are spawned.
585 ///
586 /// `HallCall` cross-references stops, cars, riders, and optional
587 /// destinations — all `EntityId`s must be remapped through `id_remap`.
588 /// Pre-15.23 snapshots stored a single `assigned_car` field, silently
589 /// dropped by `#[serde(default)]` on `assigned_cars_by_line`; the
590 /// next dispatch pass repopulates the empty map, so no explicit
591 /// migration is attempted here.
592 fn attach_hall_calls(
593 &self,
594 world: &mut crate::world::World,
595 id_remap: &HashMap<EntityId, EntityId>,
596 ) {
597 let remap = |old: EntityId| -> EntityId { id_remap.get(&old).copied().unwrap_or(old) };
598 let remap_opt = |old: Option<EntityId>| -> Option<EntityId> { old.map(&remap) };
599 for hc in &self.hall_calls {
600 let mut c = hc.clone();
601 c.stop = remap(c.stop);
602 c.destination = remap_opt(c.destination);
603 c.assigned_cars_by_line = c
604 .assigned_cars_by_line
605 .iter()
606 .map(|(&line, &car)| (remap(line), remap(car)))
607 .collect();
608 c.pending_riders = c.pending_riders.iter().map(|&r| remap(r)).collect();
609 world.set_hall_call(c);
610 }
611 }
612
613 /// Rebuild groups, stop lookup, and dispatchers from snapshot data.
614 #[allow(clippy::type_complexity)]
615 fn rebuild_groups_and_dispatchers(
616 &self,
617 index_to_id: &[EntityId],
618 custom_strategy_factory: CustomStrategyFactory<'_>,
619 ) -> Result<
620 (
621 Vec<crate::dispatch::ElevatorGroup>,
622 HashMap<StopId, EntityId>,
623 std::collections::BTreeMap<GroupId, Box<dyn crate::dispatch::DispatchStrategy>>,
624 std::collections::BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
625 ),
626 crate::error::SimError,
627 > {
628 use crate::dispatch::ElevatorGroup;
629
630 let groups: Vec<ElevatorGroup> = self
631 .groups
632 .iter()
633 .map(|gs| {
634 let elevator_entities: Vec<EntityId> = gs
635 .elevator_indices
636 .iter()
637 .filter_map(|&i| index_to_id.get(i).copied())
638 .collect();
639 let stop_entities: Vec<EntityId> = gs
640 .stop_indices
641 .iter()
642 .filter_map(|&i| index_to_id.get(i).copied())
643 .collect();
644
645 let lines = if gs.lines.is_empty() {
646 // Legacy snapshots have no per-line data; create a single
647 // synthetic LineInfo containing all elevators and stops.
648 vec![crate::dispatch::LineInfo::new(
649 EntityId::default(),
650 elevator_entities,
651 stop_entities,
652 )]
653 } else {
654 gs.lines
655 .iter()
656 .filter_map(|lsi| {
657 let entity = index_to_id.get(lsi.entity_index).copied()?;
658 Some(crate::dispatch::LineInfo::new(
659 entity,
660 lsi.elevator_indices
661 .iter()
662 .filter_map(|&i| index_to_id.get(i).copied())
663 .collect(),
664 lsi.stop_indices
665 .iter()
666 .filter_map(|&i| index_to_id.get(i).copied())
667 .collect(),
668 ))
669 })
670 .collect()
671 };
672
673 ElevatorGroup::new(gs.id, gs.name.clone(), lines)
674 .with_hall_call_mode(gs.hall_call_mode)
675 .with_ack_latency_ticks(gs.ack_latency_ticks)
676 })
677 .collect();
678
679 let stop_lookup: HashMap<StopId, EntityId> = self
680 .stop_lookup
681 .iter()
682 .filter_map(|(sid, &idx)| index_to_id.get(idx).map(|&eid| (*sid, eid)))
683 .collect();
684
685 let mut dispatchers = std::collections::BTreeMap::new();
686 let mut strategy_ids = std::collections::BTreeMap::new();
687 for (gs, group) in self.groups.iter().zip(groups.iter()) {
688 let strategy: Box<dyn crate::dispatch::DispatchStrategy> =
689 if let Some(builtin) = gs.strategy.instantiate() {
690 builtin
691 } else if let crate::dispatch::BuiltinStrategy::Custom(ref name) = gs.strategy {
692 custom_strategy_factory
693 .and_then(|f| f(name))
694 .ok_or_else(|| crate::error::SimError::UnresolvedCustomStrategy {
695 name: name.clone(),
696 group: group.id(),
697 })?
698 } else {
699 Box::new(crate::dispatch::scan::ScanDispatch::new())
700 };
701 dispatchers.insert(group.id(), strategy);
702 strategy_ids.insert(group.id(), gs.strategy.clone());
703 }
704
705 Ok((groups, stop_lookup, dispatchers, strategy_ids))
706 }
707
708 /// Remap `EntityId`s in extension data using the old→new mapping.
709 fn remap_extensions(
710 extensions: &BTreeMap<String, BTreeMap<EntityId, String>>,
711 id_remap: &HashMap<EntityId, EntityId>,
712 ) -> BTreeMap<String, BTreeMap<EntityId, String>> {
713 extensions
714 .iter()
715 .map(|(name, entries)| {
716 let remapped: BTreeMap<EntityId, String> = entries
717 .iter()
718 .map(|(old_id, data)| {
719 let new_id = id_remap.get(old_id).copied().unwrap_or(*old_id);
720 (new_id, data.clone())
721 })
722 .collect();
723 (name.clone(), remapped)
724 })
725 .collect()
726 }
727
728 /// Emit `SnapshotDanglingReference` events for entity IDs not in `id_remap`.
729 fn emit_dangling_warnings(
730 entities: &[EntitySnapshot],
731 hall_calls: &[HallCall],
732 id_remap: &HashMap<EntityId, EntityId>,
733 tick: u64,
734 sim: &mut crate::sim::Simulation,
735 ) {
736 let mut seen = HashSet::new();
737 let mut check = |old: EntityId| {
738 if !id_remap.contains_key(&old) && seen.insert(old) {
739 sim.push_event(crate::events::Event::SnapshotDanglingReference {
740 stale_id: old,
741 tick,
742 });
743 }
744 };
745 for snap in entities {
746 Self::collect_referenced_ids(snap, &mut check);
747 }
748 for hc in hall_calls {
749 check(hc.stop);
750 for (&line, &car) in &hc.assigned_cars_by_line {
751 check(line);
752 check(car);
753 }
754 if let Some(dest) = hc.destination {
755 check(dest);
756 }
757 for &rider in &hc.pending_riders {
758 check(rider);
759 }
760 }
761 }
762
763 /// Visit all cross-referenced `EntityId`s inside an entity snapshot.
764 fn collect_referenced_ids(snap: &EntitySnapshot, mut visit: impl FnMut(EntityId)) {
765 if let Some(ref elev) = snap.elevator {
766 for &r in &elev.riders {
767 visit(r);
768 }
769 if let Some(t) = elev.target_stop {
770 visit(t);
771 }
772 visit(elev.line);
773 match elev.phase {
774 crate::components::ElevatorPhase::MovingToStop(s)
775 | crate::components::ElevatorPhase::Repositioning(s) => visit(s),
776 _ => {}
777 }
778 for &s in &elev.restricted_stops {
779 visit(s);
780 }
781 }
782 if let Some(ref rider) = snap.rider {
783 if let Some(s) = rider.current_stop {
784 visit(s);
785 }
786 match rider.phase {
787 crate::components::RiderPhase::Boarding(e)
788 | crate::components::RiderPhase::Riding(e)
789 | crate::components::RiderPhase::Exiting(e) => visit(e),
790 _ => {}
791 }
792 }
793 if let Some(ref route) = snap.route {
794 for leg in &route.legs {
795 visit(leg.from);
796 visit(leg.to);
797 if let crate::components::TransportMode::Line(l) = leg.via {
798 visit(l);
799 }
800 }
801 }
802 if let Some(ref ac) = snap.access_control {
803 for &s in ac.allowed_stops() {
804 visit(s);
805 }
806 }
807 if let Some(ref dq) = snap.destination_queue {
808 for &e in dq.queue() {
809 visit(e);
810 }
811 }
812 for cc in &snap.car_calls {
813 visit(cc.floor);
814 for &r in &cc.pending_riders {
815 visit(r);
816 }
817 }
818 }
819}
820
821/// Magic bytes identifying a postcard snapshot blob.
822const SNAPSHOT_MAGIC: [u8; 8] = *b"ELEVSNAP";
823
824/// Schema version for [`WorldSnapshot`]. Bump on incompatible layout
825/// changes so RON/JSON restore can reject older snapshots loudly
826/// instead of silently filling new fields with `#[serde(default)]`.
827///
828/// See `docs/src/snapshot-versioning.md` for the full bump-trigger
829/// policy, the asymmetry between this `u32` and the crate-version
830/// string in the bytes envelope, and the migration path.
831const SNAPSHOT_SCHEMA_VERSION: u32 = 1;
832
833/// Byte-level snapshot envelope: magic + crate version + payload.
834///
835/// Serialized via postcard. The magic and version fields are checked on
836/// restore to reject blobs from other tools or from a different
837/// `elevator-core` version.
838#[derive(Debug, Serialize, Deserialize)]
839struct SnapshotEnvelope {
840 /// Magic bytes; must equal [`SNAPSHOT_MAGIC`] or the blob is rejected.
841 magic: [u8; 8],
842 /// `elevator-core` crate version that produced the blob.
843 version: String,
844 /// The captured simulation state.
845 payload: WorldSnapshot,
846}
847
848impl crate::sim::Simulation {
849 /// Create a serializable snapshot of the current simulation state.
850 ///
851 /// The snapshot captures all entities, components, groups, metrics,
852 /// the tick counter, and extension component data (game must
853 /// re-register types via `register_ext` before `restore`).
854 /// Custom resources inserted via `world.insert_resource` are NOT
855 /// captured — games using them must save/restore separately (#296).
856 ///
857 /// **Mid-tick safety:** `snapshot()` returns a snapshot regardless
858 /// of whether you are mid-tick (between phase calls in the substep
859 /// API). For substep callers that care about event-bus state, use
860 /// [`try_snapshot`](Self::try_snapshot) which returns
861 /// [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
862 /// when invoked between `run_*` and `advance_tick`. (#297)
863 #[must_use]
864 #[allow(clippy::too_many_lines)]
865 pub fn snapshot(&self) -> WorldSnapshot {
866 self.snapshot_inner()
867 }
868
869 /// Like [`snapshot`](Self::snapshot) but returns
870 /// [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
871 /// when called between phases of an in-progress tick. (#297)
872 ///
873 /// # Errors
874 ///
875 /// Returns [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
876 /// when invoked between a `run_*` phase call and the matching
877 /// `advance_tick`.
878 pub fn try_snapshot(&self) -> Result<WorldSnapshot, crate::error::SimError> {
879 if self.tick_in_progress {
880 return Err(crate::error::SimError::MidTickSnapshot);
881 }
882 Ok(self.snapshot())
883 }
884
885 /// Internal snapshot builder shared by [`snapshot`](Self::snapshot)
886 /// and [`try_snapshot`](Self::try_snapshot). Holds the line-count
887 /// allow so the public methods remain visible in nursery lints.
888 #[allow(clippy::too_many_lines)]
889 fn snapshot_inner(&self) -> WorldSnapshot {
890 let world = self.world();
891
892 // Build entity index: map EntityId → position in vec.
893 let all_ids: Vec<EntityId> = world.alive.keys().collect();
894 let id_to_index: HashMap<EntityId, usize> = all_ids
895 .iter()
896 .copied()
897 .enumerate()
898 .map(|(i, e)| (e, i))
899 .collect();
900
901 // Snapshot each entity.
902 let entities: Vec<EntitySnapshot> = all_ids
903 .iter()
904 .map(|&eid| EntitySnapshot {
905 original_id: eid,
906 position: world.position(eid).copied(),
907 velocity: world.velocity(eid).copied(),
908 elevator: world.elevator(eid).cloned(),
909 stop: world.stop(eid).cloned(),
910 rider: world.rider(eid).cloned(),
911 route: world.route(eid).cloned(),
912 line: world.line(eid).cloned(),
913 patience: world.patience(eid).copied(),
914 preferences: world.preferences(eid).copied(),
915 access_control: world.access_control(eid).cloned(),
916 disabled: world.is_disabled(eid),
917 #[cfg(feature = "energy")]
918 energy_profile: world.energy_profile(eid).cloned(),
919 #[cfg(feature = "energy")]
920 energy_metrics: world.energy_metrics(eid).cloned(),
921 service_mode: world.service_mode(eid).copied(),
922 destination_queue: world.destination_queue(eid).cloned(),
923 car_calls: world.car_calls(eid).to_vec(),
924 })
925 .collect();
926
927 // Snapshot groups (convert EntityIds to indices).
928 let groups: Vec<GroupSnapshot> = self
929 .groups()
930 .iter()
931 .map(|g| {
932 let lines: Vec<LineSnapshotInfo> = g
933 .lines()
934 .iter()
935 .filter_map(|li| {
936 let entity_index = id_to_index.get(&li.entity()).copied()?;
937 Some(LineSnapshotInfo {
938 entity_index,
939 elevator_indices: li
940 .elevators()
941 .iter()
942 .filter_map(|eid| id_to_index.get(eid).copied())
943 .collect(),
944 stop_indices: li
945 .serves()
946 .iter()
947 .filter_map(|eid| id_to_index.get(eid).copied())
948 .collect(),
949 })
950 })
951 .collect();
952 GroupSnapshot {
953 id: g.id(),
954 name: g.name().to_owned(),
955 elevator_indices: g
956 .elevator_entities()
957 .iter()
958 .filter_map(|eid| id_to_index.get(eid).copied())
959 .collect(),
960 stop_indices: g
961 .stop_entities()
962 .iter()
963 .filter_map(|eid| id_to_index.get(eid).copied())
964 .collect(),
965 strategy: self
966 .strategy_id(g.id())
967 .cloned()
968 .unwrap_or(crate::dispatch::BuiltinStrategy::Scan),
969 lines,
970 reposition: self.reposition_id(g.id()).cloned(),
971 hall_call_mode: g.hall_call_mode(),
972 ack_latency_ticks: g.ack_latency_ticks(),
973 }
974 })
975 .collect();
976
977 // Snapshot stop lookup (convert EntityIds to indices).
978 let stop_lookup: BTreeMap<StopId, usize> = self
979 .stop_lookup_iter()
980 .filter_map(|(sid, eid)| id_to_index.get(eid).map(|&idx| (*sid, idx)))
981 .collect();
982
983 WorldSnapshot {
984 version: SNAPSHOT_SCHEMA_VERSION,
985 tick: self.current_tick(),
986 dt: self.dt(),
987 entities,
988 groups,
989 stop_lookup,
990 metrics: self.metrics().clone(),
991 metric_tags: self
992 .world()
993 .resource::<MetricTags>()
994 .cloned()
995 .unwrap_or_default(),
996 extensions: self.world().serialize_extensions(),
997 ticks_per_second: 1.0 / self.dt(),
998 hall_calls: world.iter_hall_calls().cloned().collect(),
999 arrival_log: world
1000 .resource::<crate::arrival_log::ArrivalLog>()
1001 .cloned()
1002 .unwrap_or_default(),
1003 arrival_log_retention: world
1004 .resource::<crate::arrival_log::ArrivalLogRetention>()
1005 .copied()
1006 .unwrap_or_default(),
1007 destination_log: world
1008 .resource::<crate::arrival_log::DestinationLog>()
1009 .cloned()
1010 .unwrap_or_default(),
1011 traffic_detector: world
1012 .resource::<crate::traffic_detector::TrafficDetector>()
1013 .cloned()
1014 .unwrap_or_default(),
1015 reposition_cooldowns: world
1016 .resource::<crate::dispatch::reposition::RepositionCooldowns>()
1017 .cloned()
1018 .unwrap_or_default(),
1019 // Per-group dispatcher configuration. Only strategies that
1020 // override `snapshot_config` emit non-None here; the rest
1021 // default to empty and restore to built-in defaults,
1022 // preserving pre-fix behaviour for stateless strategies.
1023 dispatch_config: self
1024 .dispatchers()
1025 .iter()
1026 .filter_map(|(gid, d)| d.snapshot_config().map(|s| (*gid, s)))
1027 .collect(),
1028 }
1029 }
1030
1031 /// Serialize the current state to a self-describing byte blob.
1032 ///
1033 /// The blob is postcard-encoded and carries a magic prefix plus the
1034 /// `elevator-core` crate version. Use [`Self::restore_bytes`]
1035 /// on the receiving end. Determinism is bit-exact across builds of
1036 /// the same crate version; cross-version restores return
1037 /// [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion).
1038 ///
1039 /// Extension component *data* is serialized (identical to
1040 /// [`Self::snapshot`]); after restore, use
1041 /// [`Simulation::load_extensions_with`](crate::sim::Simulation::load_extensions_with)
1042 /// to register and load them.
1043 /// Custom dispatch strategies and arbitrary `World` resources are
1044 /// not included.
1045 ///
1046 /// # Errors
1047 /// - [`SimError::SnapshotFormat`](crate::error::SimError::SnapshotFormat)
1048 /// if postcard encoding fails. Unreachable for well-formed
1049 /// `WorldSnapshot` values, so callers that don't care can `unwrap`.
1050 /// - [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
1051 /// if invoked between phases of an in-progress tick (substep API
1052 /// path) — the in-flight `EventBus` would otherwise be lost. (#297)
1053 pub fn snapshot_bytes(&self) -> Result<Vec<u8>, crate::error::SimError> {
1054 let envelope = SnapshotEnvelope {
1055 magic: SNAPSHOT_MAGIC,
1056 version: env!("CARGO_PKG_VERSION").to_owned(),
1057 payload: self.try_snapshot()?,
1058 };
1059 postcard::to_allocvec(&envelope)
1060 .map_err(|e| crate::error::SimError::SnapshotFormat(e.to_string()))
1061 }
1062
1063 /// Cheap u64 checksum of the simulation's serializable state.
1064 /// FNV-1a over the postcard encoding of [`Self::snapshot`]'s
1065 /// `WorldSnapshot` payload — the envelope (magic + crate version
1066 /// string) is *not* hashed, so the value depends only on the
1067 /// logical sim state, not on the `elevator-core` version that
1068 /// produced it. The numeric value is FNV-1a-specific and not
1069 /// equivalent to other hash functions of the same bytes; consumers
1070 /// computing an independent hash for comparison must use this
1071 /// method (or run FNV-1a themselves with the same constants).
1072 ///
1073 /// Snapshot/restore is byte-symmetric: a fresh sim and a restored
1074 /// sim with the same logical state hash equal. (Earlier code had
1075 /// a first-restore asymmetry from the `AssignedCar` extension
1076 /// type registering on restore but not `new`; that was fixed.)
1077 ///
1078 /// Designed for divergence detection between runtimes that should
1079 /// be in lockstep (browser vs server, multi-client multiplayer)
1080 /// and for golden checksums that need to survive a
1081 /// release-please version bump. Two sims that have produced bit-
1082 /// identical inputs in bit-identical order must hash to the same
1083 /// value, regardless of `CARGO_PKG_VERSION`.
1084 ///
1085 /// # Errors
1086 /// - [`SimError::MidTickSnapshot`](crate::error::SimError::MidTickSnapshot)
1087 /// when invoked between phases of an in-progress tick (substep
1088 /// API path).
1089 /// - [`SimError::SnapshotFormat`](crate::error::SimError::SnapshotFormat)
1090 /// if postcard encoding of the payload fails. Unreachable for
1091 /// well-formed sims; callers that don't care can `unwrap`.
1092 pub fn snapshot_checksum(&self) -> Result<u64, crate::error::SimError> {
1093 // FNV-1a (64-bit). Small, allocation-free over the byte slice,
1094 // well-distributed for arbitrary input. Not cryptographic;
1095 // collision tolerance is fine for divergence detection.
1096 const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
1097 const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
1098 let snapshot = self.try_snapshot()?;
1099 let bytes = postcard::to_allocvec(&snapshot)
1100 .map_err(|e| crate::error::SimError::SnapshotFormat(e.to_string()))?;
1101 let mut h: u64 = FNV_OFFSET;
1102 for byte in &bytes {
1103 h ^= u64::from(*byte);
1104 h = h.wrapping_mul(FNV_PRIME);
1105 }
1106 Ok(h)
1107 }
1108
1109 /// Restore a simulation from bytes produced by [`Self::snapshot_bytes`].
1110 ///
1111 /// Built-in dispatch strategies are auto-restored. For groups using
1112 /// [`BuiltinStrategy::Custom`](crate::dispatch::BuiltinStrategy::Custom),
1113 /// provide a factory; pass `None` otherwise.
1114 ///
1115 /// # Errors
1116 /// - [`SimError::SnapshotFormat`](crate::error::SimError::SnapshotFormat)
1117 /// if the bytes are not a valid envelope or the magic prefix does
1118 /// not match.
1119 /// - [`SimError::SnapshotVersion`](crate::error::SimError::SnapshotVersion)
1120 /// if the blob was produced by a different crate version.
1121 /// - [`SimError::UnresolvedCustomStrategy`](crate::error::SimError::UnresolvedCustomStrategy)
1122 /// if a group uses a custom strategy that the factory cannot resolve.
1123 pub fn restore_bytes(
1124 bytes: &[u8],
1125 custom_strategy_factory: CustomStrategyFactory<'_>,
1126 ) -> Result<Self, crate::error::SimError> {
1127 let (envelope, tail): (SnapshotEnvelope, &[u8]) = postcard::take_from_bytes(bytes)
1128 .map_err(|e| crate::error::SimError::SnapshotFormat(e.to_string()))?;
1129 if !tail.is_empty() {
1130 return Err(crate::error::SimError::SnapshotFormat(format!(
1131 "trailing bytes: {} unread of {}",
1132 tail.len(),
1133 bytes.len()
1134 )));
1135 }
1136 if envelope.magic != SNAPSHOT_MAGIC {
1137 return Err(crate::error::SimError::SnapshotFormat(
1138 "magic bytes do not match".to_string(),
1139 ));
1140 }
1141 let current = env!("CARGO_PKG_VERSION");
1142 if envelope.version != current {
1143 return Err(crate::error::SimError::SnapshotVersion {
1144 saved: envelope.version,
1145 current: current.to_owned(),
1146 });
1147 }
1148 envelope.payload.restore(custom_strategy_factory)
1149 }
1150}