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