Skip to main content

elevator_core/sim/
construction.rs

1//! Simulation construction, validation, and topology assembly.
2//!
3//! Split out from `sim.rs` to keep each concern readable. Holds:
4//!
5//! - [`Simulation::new`] and [`Simulation::new_with_hooks`]
6//! - Config validation ([`Simulation::validate_config`] and helpers)
7//! - Legacy and explicit topology builders
8//! - [`Simulation::from_parts`] for snapshot restore
9//! - Dispatch, reposition, and hook registration helpers
10//!
11//! Since this is a child module of `crate::sim`, it can access `Simulation`'s
12//! private fields directly — no visibility relaxation required.
13
14use std::collections::{BTreeMap, HashMap, HashSet};
15use std::sync::Mutex;
16
17use crate::components::{Elevator, ElevatorPhase, Line, Orientation, Position, Stop, Velocity};
18use crate::config::SimConfig;
19use crate::dispatch::{
20    BuiltinReposition, BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo,
21    RepositionStrategy,
22};
23use crate::door::DoorState;
24use crate::entity::EntityId;
25use crate::error::SimError;
26use crate::events::EventBus;
27use crate::hooks::{Phase, PhaseHooks};
28use crate::ids::GroupId;
29use crate::metrics::Metrics;
30use crate::rider_index::RiderIndex;
31use crate::stop::StopId;
32use crate::time::TimeAdapter;
33use crate::topology::TopologyGraph;
34use crate::world::World;
35
36use super::Simulation;
37
38/// Bundled topology result: groups, dispatchers, and strategy IDs.
39type TopologyResult = (
40    Vec<ElevatorGroup>,
41    BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
42    BTreeMap<GroupId, BuiltinStrategy>,
43);
44
45/// Ensure DCS groups have `HallCallMode::Destination` at construction
46/// time. Non-DCS groups are left at whatever the config specified —
47/// forcing Classic here would clobber explicit config overrides (e.g. a
48/// Scan group that the author deliberately set to Destination mode).
49///
50/// Runtime swaps via [`Simulation::set_dispatch`] do a full bidirectional
51/// sync because a strategy change is an explicit user action where
52/// resetting the mode is expected.
53fn sync_hall_call_modes(
54    groups: &mut [ElevatorGroup],
55    strategy_ids: &BTreeMap<GroupId, BuiltinStrategy>,
56) {
57    for group in groups.iter_mut() {
58        if strategy_ids.get(&group.id()) == Some(&BuiltinStrategy::Destination) {
59            group.set_hall_call_mode(crate::dispatch::HallCallMode::Destination);
60        }
61    }
62}
63
64/// Validate the physics fields shared by [`crate::config::ElevatorConfig`]
65/// and [`super::ElevatorParams`]. Both construction-time validation and
66/// the runtime `add_elevator` path call this so an invalid set of params
67/// can never reach the world (zeroes blow up movement; zero door ticks
68/// stall the door FSM).
69#[allow(clippy::too_many_arguments)]
70pub(super) fn validate_elevator_physics(
71    max_speed: f64,
72    acceleration: f64,
73    deceleration: f64,
74    weight_capacity: f64,
75    inspection_speed_factor: f64,
76    door_transition_ticks: u32,
77    door_open_ticks: u32,
78    bypass_load_up_pct: Option<f64>,
79    bypass_load_down_pct: Option<f64>,
80) -> Result<(), SimError> {
81    if !max_speed.is_finite() || max_speed <= 0.0 {
82        return Err(SimError::InvalidConfig {
83            field: "elevators.max_speed",
84            reason: format!("must be finite and positive, got {max_speed}"),
85        });
86    }
87    if !acceleration.is_finite() || acceleration <= 0.0 {
88        return Err(SimError::InvalidConfig {
89            field: "elevators.acceleration",
90            reason: format!("must be finite and positive, got {acceleration}"),
91        });
92    }
93    if !deceleration.is_finite() || deceleration <= 0.0 {
94        return Err(SimError::InvalidConfig {
95            field: "elevators.deceleration",
96            reason: format!("must be finite and positive, got {deceleration}"),
97        });
98    }
99    if !weight_capacity.is_finite() || weight_capacity <= 0.0 {
100        return Err(SimError::InvalidConfig {
101            field: "elevators.weight_capacity",
102            reason: format!("must be finite and positive, got {weight_capacity}"),
103        });
104    }
105    if !inspection_speed_factor.is_finite() || inspection_speed_factor <= 0.0 {
106        return Err(SimError::InvalidConfig {
107            field: "elevators.inspection_speed_factor",
108            reason: format!("must be finite and positive, got {inspection_speed_factor}"),
109        });
110    }
111    if door_transition_ticks == 0 {
112        return Err(SimError::InvalidConfig {
113            field: "elevators.door_transition_ticks",
114            reason: "must be > 0".into(),
115        });
116    }
117    if door_open_ticks == 0 {
118        return Err(SimError::InvalidConfig {
119            field: "elevators.door_open_ticks",
120            reason: "must be > 0".into(),
121        });
122    }
123    validate_bypass_pct("elevators.bypass_load_up_pct", bypass_load_up_pct)?;
124    validate_bypass_pct("elevators.bypass_load_down_pct", bypass_load_down_pct)?;
125    Ok(())
126}
127
128/// `bypass_load_{up,down}_pct` must be a finite fraction in `(0.0, 1.0]`
129/// when set. `pct = 0.0` would bypass at an empty car (nonsense); `NaN`
130/// and infinities silently disable the bypass under the dispatch guard,
131/// which is a silent foot-gun. Reject at config time instead.
132fn validate_bypass_pct(field: &'static str, pct: Option<f64>) -> Result<(), SimError> {
133    let Some(pct) = pct else {
134        return Ok(());
135    };
136    if !pct.is_finite() || pct <= 0.0 || pct > 1.0 {
137        return Err(SimError::InvalidConfig {
138            field,
139            reason: format!("must be finite in (0.0, 1.0] when set, got {pct}"),
140        });
141    }
142    Ok(())
143}
144
145impl Simulation {
146    /// Create a new simulation from config and a dispatch strategy.
147    ///
148    /// Returns `Err` if the config is invalid (zero stops, duplicate IDs,
149    /// negative speeds, etc.).
150    ///
151    /// # Errors
152    ///
153    /// Returns [`SimError::InvalidConfig`] if the configuration has zero stops,
154    /// duplicate stop IDs, zero elevators, non-positive physics parameters,
155    /// invalid starting stops, or non-positive tick rate.
156    pub fn new(
157        config: &SimConfig,
158        dispatch: impl DispatchStrategy + 'static,
159    ) -> Result<Self, SimError> {
160        let mut dispatchers = BTreeMap::new();
161        dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
162        Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
163    }
164
165    /// Create a simulation with pre-configured lifecycle hooks.
166    ///
167    /// Used by [`SimulationBuilder`](crate::builder::SimulationBuilder).
168    #[allow(clippy::too_many_lines)]
169    pub(crate) fn new_with_hooks(
170        config: &SimConfig,
171        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
172        hooks: PhaseHooks,
173    ) -> Result<Self, SimError> {
174        Self::validate_config(config)?;
175
176        let mut world = World::new();
177
178        // Create stop entities.
179        let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
180        for sc in &config.building.stops {
181            let eid = world.spawn();
182            world.set_stop(
183                eid,
184                Stop {
185                    name: sc.name.clone(),
186                    position: sc.position,
187                },
188            );
189            world.set_position(eid, Position { value: sc.position });
190            stop_lookup.insert(sc.id, eid);
191        }
192
193        // Build sorted-stops index for O(log n) PassingFloor detection.
194        let mut sorted: Vec<(f64, EntityId)> = world
195            .iter_stops()
196            .map(|(eid, stop)| (stop.position, eid))
197            .collect();
198        sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
199        world.insert_resource(crate::world::SortedStops(sorted));
200
201        // Per-stop arrival signal, appended on rider spawn and queried
202        // by dispatch/reposition strategies to drive traffic-mode
203        // switches and predictive parking. The destination mirror is
204        // what powers down-peak detection — without it the classifier
205        // sees `total_dest = 0` and silently never emits `DownPeak`.
206        world.insert_resource(crate::arrival_log::ArrivalLog::default());
207        world.insert_resource(crate::arrival_log::DestinationLog::default());
208        world.insert_resource(crate::arrival_log::CurrentTick::default());
209        world.insert_resource(crate::arrival_log::ArrivalLogRetention::default());
210        // Traffic-mode classifier. Auto-refreshed in the metrics phase
211        // from the same rolling window; strategies read the current
212        // mode via `World::resource::<TrafficDetector>()`.
213        world.insert_resource(crate::traffic_detector::TrafficDetector::default());
214        // Per-car reposition cooldown. Populated by the movement
215        // phase when a repositioning car arrives; consulted by the
216        // reposition phase to skip cars that just parked so the
217        // hot-stop ranking can't flip them around again the next
218        // tick.
219        world.insert_resource(crate::dispatch::reposition::RepositionCooldowns::default());
220        // Expose tick rate to strategies that need to unit-convert
221        // tick-denominated elevator fields (door cycle, ack latency)
222        // into the second-denominated terms of their cost functions.
223        // Without this, ETD's door-overhead term was summing ticks
224        // into a seconds expression and getting ~60× over-weighted.
225        world.insert_resource(crate::time::TickRate(config.simulation.ticks_per_second));
226
227        let (mut groups, dispatchers, strategy_ids) =
228            if let Some(line_configs) = &config.building.lines {
229                Self::build_explicit_topology(
230                    &mut world,
231                    config,
232                    line_configs,
233                    &stop_lookup,
234                    builder_dispatchers,
235                )
236            } else {
237                Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
238            };
239        sync_hall_call_modes(&mut groups, &strategy_ids);
240
241        let dt = 1.0 / config.simulation.ticks_per_second;
242
243        world.insert_resource(crate::tagged_metrics::MetricTags::default());
244
245        // Collect line tag info (entity + name + elevator entities) before
246        // borrowing world mutably for MetricTags.
247        let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
248            .iter()
249            .flat_map(|group| {
250                group.lines().iter().filter_map(|li| {
251                    let line_comp = world.line(li.entity())?;
252                    Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
253                })
254            })
255            .collect();
256
257        // Tag line entities and their elevators with "line:{name}".
258        if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
259            for (line_eid, name, elevators) in &line_tag_info {
260                let tag = format!("line:{name}");
261                tags.tag(*line_eid, tag.clone());
262                for elev_eid in elevators {
263                    tags.tag(*elev_eid, tag.clone());
264                }
265            }
266        }
267
268        // Wire reposition strategies from group configs.
269        let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
270        let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
271        if let Some(group_configs) = &config.building.groups {
272            for gc in group_configs {
273                if let Some(ref repo_id) = gc.reposition
274                    && let Some(strategy) = repo_id.instantiate()
275                {
276                    let gid = GroupId(gc.id);
277                    repositioners.insert(gid, strategy);
278                    reposition_ids.insert(gid, repo_id.clone());
279                }
280            }
281        }
282
283        Ok(Self {
284            world,
285            events: EventBus::default(),
286            pending_output: Vec::new(),
287            tick: 0,
288            dt,
289            groups,
290            stop_lookup,
291            dispatchers,
292            strategy_ids,
293            repositioners,
294            reposition_ids,
295            metrics: Metrics::new(),
296            time: TimeAdapter::new(config.simulation.ticks_per_second),
297            hooks,
298            elevator_ids_buf: Vec::new(),
299            reposition_buf: Vec::new(),
300            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
301            topo_graph: Mutex::new(TopologyGraph::new()),
302            rider_index: RiderIndex::default(),
303            tick_in_progress: false,
304        })
305    }
306
307    /// Spawn a single elevator entity from an `ElevatorConfig` onto `line`.
308    ///
309    /// Sets position, velocity, all `Elevator` fields, optional energy profile,
310    /// optional service mode, and an empty `DestinationQueue`.
311    /// Returns the new entity ID.
312    fn spawn_elevator_entity(
313        world: &mut World,
314        ec: &crate::config::ElevatorConfig,
315        line: EntityId,
316        stop_lookup: &HashMap<StopId, EntityId>,
317        start_pos_lookup: &[crate::stop::StopConfig],
318    ) -> EntityId {
319        let eid = world.spawn();
320        let start_pos = start_pos_lookup
321            .iter()
322            .find(|s| s.id == ec.starting_stop)
323            .map_or(0.0, |s| s.position);
324        world.set_position(eid, Position { value: start_pos });
325        world.set_velocity(eid, Velocity { value: 0.0 });
326        let restricted: HashSet<EntityId> = ec
327            .restricted_stops
328            .iter()
329            .filter_map(|sid| stop_lookup.get(sid).copied())
330            .collect();
331        world.set_elevator(
332            eid,
333            Elevator {
334                phase: ElevatorPhase::Idle,
335                door: DoorState::Closed,
336                max_speed: ec.max_speed,
337                acceleration: ec.acceleration,
338                deceleration: ec.deceleration,
339                weight_capacity: ec.weight_capacity,
340                current_load: crate::components::Weight::ZERO,
341                riders: Vec::new(),
342                target_stop: None,
343                door_transition_ticks: ec.door_transition_ticks,
344                door_open_ticks: ec.door_open_ticks,
345                line,
346                repositioning: false,
347                restricted_stops: restricted,
348                inspection_speed_factor: ec.inspection_speed_factor,
349                going_up: true,
350                going_down: true,
351                move_count: 0,
352                door_command_queue: Vec::new(),
353                manual_target_velocity: None,
354                bypass_load_up_pct: ec.bypass_load_up_pct,
355                bypass_load_down_pct: ec.bypass_load_down_pct,
356            },
357        );
358        #[cfg(feature = "energy")]
359        if let Some(ref profile) = ec.energy_profile {
360            world.set_energy_profile(eid, profile.clone());
361            world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
362        }
363        if let Some(mode) = ec.service_mode {
364            world.set_service_mode(eid, mode);
365        }
366        world.set_destination_queue(eid, crate::components::DestinationQueue::new());
367        eid
368    }
369
370    /// Build topology from the legacy flat elevator list (single default line + group).
371    fn build_legacy_topology(
372        world: &mut World,
373        config: &SimConfig,
374        stop_lookup: &HashMap<StopId, EntityId>,
375        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
376    ) -> TopologyResult {
377        let all_stop_entities: Vec<EntityId> = stop_lookup.values().copied().collect();
378        let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
379        let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
380        let max_pos = stop_positions
381            .iter()
382            .copied()
383            .fold(f64::NEG_INFINITY, f64::max);
384
385        let default_line_eid = world.spawn();
386        world.set_line(
387            default_line_eid,
388            Line {
389                name: "Default".into(),
390                group: GroupId(0),
391                orientation: Orientation::Vertical,
392                position: None,
393                min_position: min_pos,
394                max_position: max_pos,
395                max_cars: None,
396            },
397        );
398
399        let mut elevator_entities = Vec::new();
400        for ec in &config.elevators {
401            let eid = Self::spawn_elevator_entity(
402                world,
403                ec,
404                default_line_eid,
405                stop_lookup,
406                &config.building.stops,
407            );
408            elevator_entities.push(eid);
409        }
410
411        let default_line_info =
412            LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
413
414        let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
415
416        // Legacy topology has exactly one group: GroupId(0). Honour a
417        // builder-provided dispatcher for that group; ignore any builder
418        // entry keyed on a different GroupId (it would have nothing to
419        // attach to). Pre-fix this used `into_iter().next()` which
420        // discarded the GroupId entirely and could attach a dispatcher
421        // intended for a different group to GroupId(0). (#288)
422        let mut dispatchers = BTreeMap::new();
423        let mut strategy_ids = BTreeMap::new();
424        let user_dispatcher = builder_dispatchers
425            .into_iter()
426            .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
427        // Infer the snapshot identity from the dispatcher itself via
428        // `DispatchStrategy::builtin_id`. Pre-fix this was hard-coded to
429        // `BuiltinStrategy::Scan` regardless of the impl actually passed,
430        // so `Simulation::new(config, NearestCarDispatch::new())` would
431        // record `Scan` as the group's identity — and a snapshot round-
432        // trip would silently swap the running strategy back to Scan,
433        // breaking determinism. Built-ins override `builtin_id` to
434        // return their own variant; custom strategies can override it
435        // to return `BuiltinStrategy::Custom(name)` for snapshot fidelity.
436        // Strategies that don't override (returning `None`) still fall
437        // back to Scan, matching the previous behaviour for callers that
438        // never cared about round-trip identity.
439        let inferred_id = user_dispatcher
440            .as_ref()
441            .and_then(|d| d.builtin_id())
442            .unwrap_or(BuiltinStrategy::Scan);
443        if let Some(d) = user_dispatcher {
444            dispatchers.insert(GroupId(0), d);
445        } else {
446            dispatchers.insert(
447                GroupId(0),
448                Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
449            );
450        }
451        strategy_ids.insert(GroupId(0), inferred_id);
452
453        (vec![group], dispatchers, strategy_ids)
454    }
455
456    /// Build topology from explicit `LineConfig`/`GroupConfig` definitions.
457    #[allow(clippy::too_many_lines)]
458    fn build_explicit_topology(
459        world: &mut World,
460        config: &SimConfig,
461        line_configs: &[crate::config::LineConfig],
462        stop_lookup: &HashMap<StopId, EntityId>,
463        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
464    ) -> TopologyResult {
465        // Map line config id → (line EntityId, LineInfo).
466        let mut line_map: HashMap<u32, (EntityId, LineInfo)> = HashMap::new();
467
468        for lc in line_configs {
469            // Resolve served stop entities.
470            let served_entities: Vec<EntityId> = lc
471                .serves
472                .iter()
473                .filter_map(|sid| stop_lookup.get(sid).copied())
474                .collect();
475
476            // Compute min/max from stops if not explicitly set.
477            let stop_positions: Vec<f64> = lc
478                .serves
479                .iter()
480                .filter_map(|sid| {
481                    config
482                        .building
483                        .stops
484                        .iter()
485                        .find(|s| s.id == *sid)
486                        .map(|s| s.position)
487                })
488                .collect();
489            let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
490            let auto_max = stop_positions
491                .iter()
492                .copied()
493                .fold(f64::NEG_INFINITY, f64::max);
494
495            let min_pos = lc.min_position.unwrap_or(auto_min);
496            let max_pos = lc.max_position.unwrap_or(auto_max);
497
498            let line_eid = world.spawn();
499            // The group assignment will be set when we process GroupConfigs.
500            // Default to GroupId(0) initially.
501            world.set_line(
502                line_eid,
503                Line {
504                    name: lc.name.clone(),
505                    group: GroupId(0),
506                    orientation: lc.orientation,
507                    position: lc.position,
508                    min_position: min_pos,
509                    max_position: max_pos,
510                    max_cars: lc.max_cars,
511                },
512            );
513
514            // Spawn elevators for this line.
515            let mut elevator_entities = Vec::new();
516            for ec in &lc.elevators {
517                let eid = Self::spawn_elevator_entity(
518                    world,
519                    ec,
520                    line_eid,
521                    stop_lookup,
522                    &config.building.stops,
523                );
524                elevator_entities.push(eid);
525            }
526
527            let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
528            line_map.insert(lc.id, (line_eid, line_info));
529        }
530
531        // Build groups from GroupConfigs, or auto-infer a single group.
532        let group_configs = config.building.groups.as_deref();
533        let mut groups = Vec::new();
534        let mut dispatchers = BTreeMap::new();
535        let mut strategy_ids = BTreeMap::new();
536
537        if let Some(gcs) = group_configs {
538            for gc in gcs {
539                let group_id = GroupId(gc.id);
540
541                let mut group_lines = Vec::new();
542
543                for &lid in &gc.lines {
544                    if let Some((line_eid, li)) = line_map.get(&lid) {
545                        // Update the line's group assignment.
546                        if let Some(line_comp) = world.line_mut(*line_eid) {
547                            line_comp.group = group_id;
548                        }
549                        group_lines.push(li.clone());
550                    }
551                }
552
553                let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
554                if let Some(mode) = gc.hall_call_mode {
555                    group.set_hall_call_mode(mode);
556                }
557                if let Some(ticks) = gc.ack_latency_ticks {
558                    group.set_ack_latency_ticks(ticks);
559                }
560                groups.push(group);
561
562                // GroupConfig strategy; builder overrides applied after this loop.
563                let dispatch: Box<dyn DispatchStrategy> = gc
564                    .dispatch
565                    .instantiate()
566                    .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
567                dispatchers.insert(group_id, dispatch);
568                strategy_ids.insert(group_id, gc.dispatch.clone());
569            }
570        } else {
571            // No explicit groups — create a single default group with all lines.
572            let group_id = GroupId(0);
573            let mut group_lines = Vec::new();
574
575            for (line_eid, li) in line_map.values() {
576                if let Some(line_comp) = world.line_mut(*line_eid) {
577                    line_comp.group = group_id;
578                }
579                group_lines.push(li.clone());
580            }
581
582            let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
583            groups.push(group);
584
585            let dispatch: Box<dyn DispatchStrategy> =
586                Box::new(crate::dispatch::scan::ScanDispatch::new());
587            dispatchers.insert(group_id, dispatch);
588            strategy_ids.insert(group_id, BuiltinStrategy::Scan);
589        }
590
591        // Override with builder-provided dispatchers (they take precedence).
592        // Pre-fix this could mismatch `strategy_ids` against `dispatchers`
593        // when both config and builder specified a strategy for the same
594        // group (#287). The new precedence: builder wins for the dispatcher
595        // and, for snapshot fidelity, we prefer the dispatcher's own
596        // `builtin_id()` over any stale config-supplied id. Falling back
597        // to the config id when the dispatcher is unidentified matches
598        // the pre-fix behaviour for custom strategies that don't override
599        // `builtin_id`.
600        for (gid, d) in builder_dispatchers {
601            let inferred_id = d.builtin_id();
602            dispatchers.insert(gid, d);
603            match inferred_id {
604                Some(id) => {
605                    strategy_ids.insert(gid, id);
606                }
607                None => {
608                    strategy_ids
609                        .entry(gid)
610                        .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
611                }
612            }
613        }
614
615        (groups, dispatchers, strategy_ids)
616    }
617
618    /// Restore a simulation from pre-built parts (used by snapshot restore).
619    #[allow(clippy::too_many_arguments)]
620    pub(crate) fn from_parts(
621        world: World,
622        tick: u64,
623        dt: f64,
624        groups: Vec<ElevatorGroup>,
625        stop_lookup: HashMap<StopId, EntityId>,
626        dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
627        strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
628        metrics: Metrics,
629        ticks_per_second: f64,
630    ) -> Self {
631        let mut rider_index = RiderIndex::default();
632        rider_index.rebuild(&world);
633        // Ensure the dispatch-visible tick rate matches the simulation
634        // tick rate after a snapshot restore; a snapshot that predates
635        // the `TickRate` resource leaves it absent and dispatch would
636        // otherwise fall back to the 60 Hz default even for a 30 Hz
637        // sim, silently halving ETD's door-cost scale.
638        let mut world = world;
639        world.insert_resource(crate::time::TickRate(ticks_per_second));
640        // Re-insert the traffic detector for the same forward-compat
641        // reason as `TickRate`: a snapshot taken before this resource
642        // existed wouldn't carry it, and `refresh_traffic_detector` in
643        // the metrics phase would silently no-op forever post-restore
644        // (greptile review of #361). `insert_resource` is
645        // last-writer-wins, so snapshots that already carry a
646        // detector keep their stored state.
647        if world
648            .resource::<crate::traffic_detector::TrafficDetector>()
649            .is_none()
650        {
651            world.insert_resource(crate::traffic_detector::TrafficDetector::default());
652        }
653        // Same forward-compat pattern for the destination log. An
654        // older snapshot would leave the detector unable to detect
655        // down-peak post-restore; a fresh empty log lets it resume
656        // classification after a few ticks of observed traffic.
657        if world
658            .resource::<crate::arrival_log::DestinationLog>()
659            .is_none()
660        {
661            world.insert_resource(crate::arrival_log::DestinationLog::default());
662        }
663        // Auto-register dispatch-internal extension types the sim itself
664        // owns, and immediately load their data from the pending
665        // resource. Without this, DCS sticky assignments
666        // (`AssignedCar`) evaporate across snapshot round-trip and
667        // `DestinationDispatch` re-computes every commitment from
668        // scratch — producing different decisions than the original
669        // sim and breaking tick-for-tick determinism.
670        //
671        // `deserialize_extensions` takes a `&` of the pending map and
672        // silently skips types that aren't registered, so the call is
673        // safe to make with user-owned extensions still in the map.
674        // The `PendingExtensions` resource stays in place for a later
675        // `load_extensions_with` call to materialize the caller's own
676        // types.
677        world.register_ext::<crate::dispatch::destination::AssignedCar>(
678            crate::dispatch::destination::ASSIGNED_CAR_KEY,
679        );
680        if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
681            let data = pending.0.clone();
682            world.deserialize_extensions(&data);
683        }
684        Self {
685            world,
686            events: EventBus::default(),
687            pending_output: Vec::new(),
688            tick,
689            dt,
690            groups,
691            stop_lookup,
692            dispatchers,
693            strategy_ids,
694            repositioners: BTreeMap::new(),
695            reposition_ids: BTreeMap::new(),
696            metrics,
697            time: TimeAdapter::new(ticks_per_second),
698            hooks: PhaseHooks::default(),
699            elevator_ids_buf: Vec::new(),
700            reposition_buf: Vec::new(),
701            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
702            topo_graph: Mutex::new(TopologyGraph::new()),
703            rider_index,
704            tick_in_progress: false,
705        }
706    }
707
708    /// Validate configuration before constructing the simulation.
709    pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
710        if config.building.stops.is_empty() {
711            return Err(SimError::InvalidConfig {
712                field: "building.stops",
713                reason: "at least one stop is required".into(),
714            });
715        }
716
717        // Check for duplicate stop IDs and validate positions.
718        let mut seen_ids = HashSet::new();
719        for stop in &config.building.stops {
720            if !seen_ids.insert(stop.id) {
721                return Err(SimError::InvalidConfig {
722                    field: "building.stops",
723                    reason: format!("duplicate {}", stop.id),
724                });
725            }
726            if !stop.position.is_finite() {
727                return Err(SimError::InvalidConfig {
728                    field: "building.stops.position",
729                    reason: format!("{} has non-finite position {}", stop.id, stop.position),
730                });
731            }
732        }
733
734        let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
735
736        if let Some(line_configs) = &config.building.lines {
737            // ── Explicit topology validation ──
738            Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
739        } else {
740            // ── Legacy flat elevator list validation ──
741            Self::validate_legacy_elevators(&config.elevators, &config.building)?;
742        }
743
744        if !config.simulation.ticks_per_second.is_finite()
745            || config.simulation.ticks_per_second <= 0.0
746        {
747            return Err(SimError::InvalidConfig {
748                field: "simulation.ticks_per_second",
749                reason: format!(
750                    "must be finite and positive, got {}",
751                    config.simulation.ticks_per_second
752                ),
753            });
754        }
755
756        Self::validate_passenger_spawning(&config.passenger_spawning)?;
757
758        Ok(())
759    }
760
761    /// Validate `PassengerSpawnConfig`. Without this, bad inputs reach
762    /// `PoissonSource::from_config` and panic later (NaN/negative weights
763    /// crash `random_range`/`Weight::from`; zero `mean_interval_ticks`
764    /// burst-fires every catch-up tick). (#272)
765    fn validate_passenger_spawning(
766        spawn: &crate::config::PassengerSpawnConfig,
767    ) -> Result<(), SimError> {
768        let (lo, hi) = spawn.weight_range;
769        if !lo.is_finite() || !hi.is_finite() {
770            return Err(SimError::InvalidConfig {
771                field: "passenger_spawning.weight_range",
772                reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
773            });
774        }
775        if lo < 0.0 || hi < 0.0 {
776            return Err(SimError::InvalidConfig {
777                field: "passenger_spawning.weight_range",
778                reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
779            });
780        }
781        if lo > hi {
782            return Err(SimError::InvalidConfig {
783                field: "passenger_spawning.weight_range",
784                reason: format!("min must be <= max, got ({lo}, {hi})"),
785            });
786        }
787        if spawn.mean_interval_ticks == 0 {
788            return Err(SimError::InvalidConfig {
789                field: "passenger_spawning.mean_interval_ticks",
790                reason: "must be > 0; mean_interval_ticks=0 burst-fires \
791                         every catch-up tick"
792                    .into(),
793            });
794        }
795        Ok(())
796    }
797
798    /// Validate the legacy flat elevator list.
799    fn validate_legacy_elevators(
800        elevators: &[crate::config::ElevatorConfig],
801        building: &crate::config::BuildingConfig,
802    ) -> Result<(), SimError> {
803        if elevators.is_empty() {
804            return Err(SimError::InvalidConfig {
805                field: "elevators",
806                reason: "at least one elevator is required".into(),
807            });
808        }
809
810        for elev in elevators {
811            Self::validate_elevator_config(elev, building)?;
812        }
813
814        Ok(())
815    }
816
817    /// Validate a single elevator config's physics and starting stop.
818    fn validate_elevator_config(
819        elev: &crate::config::ElevatorConfig,
820        building: &crate::config::BuildingConfig,
821    ) -> Result<(), SimError> {
822        validate_elevator_physics(
823            elev.max_speed.value(),
824            elev.acceleration.value(),
825            elev.deceleration.value(),
826            elev.weight_capacity.value(),
827            elev.inspection_speed_factor,
828            elev.door_transition_ticks,
829            elev.door_open_ticks,
830            elev.bypass_load_up_pct,
831            elev.bypass_load_down_pct,
832        )?;
833        if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
834            return Err(SimError::InvalidConfig {
835                field: "elevators.starting_stop",
836                reason: format!("references non-existent {}", elev.starting_stop),
837            });
838        }
839        Ok(())
840    }
841
842    /// Validate explicit line/group topology.
843    fn validate_explicit_topology(
844        line_configs: &[crate::config::LineConfig],
845        stop_ids: &HashSet<StopId>,
846        building: &crate::config::BuildingConfig,
847    ) -> Result<(), SimError> {
848        // No duplicate line IDs.
849        let mut seen_line_ids = HashSet::new();
850        for lc in line_configs {
851            if !seen_line_ids.insert(lc.id) {
852                return Err(SimError::InvalidConfig {
853                    field: "building.lines",
854                    reason: format!("duplicate line id {}", lc.id),
855                });
856            }
857        }
858
859        // Every line's serves must reference existing stops and be non-empty.
860        for lc in line_configs {
861            if lc.serves.is_empty() {
862                return Err(SimError::InvalidConfig {
863                    field: "building.lines.serves",
864                    reason: format!("line {} has no stops", lc.id),
865                });
866            }
867            for sid in &lc.serves {
868                if !stop_ids.contains(sid) {
869                    return Err(SimError::InvalidConfig {
870                        field: "building.lines.serves",
871                        reason: format!("line {} references non-existent {}", lc.id, sid),
872                    });
873                }
874            }
875            // Validate elevators within each line.
876            for ec in &lc.elevators {
877                Self::validate_elevator_config(ec, building)?;
878            }
879
880            // Validate max_cars is not exceeded.
881            if let Some(max) = lc.max_cars
882                && lc.elevators.len() > max
883            {
884                return Err(SimError::InvalidConfig {
885                    field: "building.lines.max_cars",
886                    reason: format!(
887                        "line {} has {} elevators but max_cars is {max}",
888                        lc.id,
889                        lc.elevators.len()
890                    ),
891                });
892            }
893        }
894
895        // At least one line with at least one elevator.
896        let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
897        if !has_elevator {
898            return Err(SimError::InvalidConfig {
899                field: "building.lines",
900                reason: "at least one line must have at least one elevator".into(),
901            });
902        }
903
904        // No orphaned stops: every stop must be served by at least one line.
905        let served: HashSet<StopId> = line_configs
906            .iter()
907            .flat_map(|lc| lc.serves.iter().copied())
908            .collect();
909        for sid in stop_ids {
910            if !served.contains(sid) {
911                return Err(SimError::InvalidConfig {
912                    field: "building.lines",
913                    reason: format!("orphaned stop {sid} not served by any line"),
914                });
915            }
916        }
917
918        // Validate groups if present.
919        if let Some(group_configs) = &building.groups {
920            let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
921
922            let mut seen_group_ids = HashSet::new();
923            for gc in group_configs {
924                if !seen_group_ids.insert(gc.id) {
925                    return Err(SimError::InvalidConfig {
926                        field: "building.groups",
927                        reason: format!("duplicate group id {}", gc.id),
928                    });
929                }
930                for &lid in &gc.lines {
931                    if !line_id_set.contains(&lid) {
932                        return Err(SimError::InvalidConfig {
933                            field: "building.groups.lines",
934                            reason: format!(
935                                "group {} references non-existent line id {}",
936                                gc.id, lid
937                            ),
938                        });
939                    }
940                }
941            }
942
943            // Check for orphaned lines (not referenced by any group).
944            let referenced_line_ids: HashSet<u32> = group_configs
945                .iter()
946                .flat_map(|g| g.lines.iter().copied())
947                .collect();
948            for lc in line_configs {
949                if !referenced_line_ids.contains(&lc.id) {
950                    return Err(SimError::InvalidConfig {
951                        field: "building.lines",
952                        reason: format!("line {} is not assigned to any group", lc.id),
953                    });
954                }
955            }
956        }
957
958        Ok(())
959    }
960
961    // ── Dispatch management ──────────────────────────────────────────
962
963    /// Replace the dispatch strategy for a group.
964    ///
965    /// Also synchronises `HallCallMode`: `Destination` for DCS, `Classic`
966    /// for other built-ins; `Custom` strategies leave the mode untouched.
967    ///
968    /// The stored snapshot identity is taken from the strategy's own
969    /// [`DispatchStrategy::builtin_id`] when it returns `Some(..)`, so
970    /// built-in strategies always round-trip as themselves even if the
971    /// `id` argument drifts out of sync with the actual impl. Custom
972    /// strategies that don't override `builtin_id` fall back to the
973    /// caller-supplied `id`, preserving the prior API for registered
974    /// custom factories. Mirrors the pattern applied to
975    /// [`set_reposition`](Self::set_reposition) in #414.
976    pub fn set_dispatch(
977        &mut self,
978        group: GroupId,
979        strategy: Box<dyn DispatchStrategy>,
980        id: crate::dispatch::BuiltinStrategy,
981    ) {
982        let resolved_id = strategy.builtin_id().unwrap_or(id);
983        let mode = match &resolved_id {
984            BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
985            BuiltinStrategy::Custom(_) => None,
986            BuiltinStrategy::Scan
987            | BuiltinStrategy::Look
988            | BuiltinStrategy::NearestCar
989            | BuiltinStrategy::Etd
990            | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
991        };
992        if let Some(mode) = mode
993            && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
994        {
995            g.set_hall_call_mode(mode);
996        }
997        self.dispatchers.insert(group, strategy);
998        self.strategy_ids.insert(group, resolved_id);
999    }
1000
1001    // ── Reposition management ─────────────────────────────────────────
1002
1003    /// Set the reposition strategy for a group.
1004    ///
1005    /// Enables the reposition phase for this group. Idle elevators will
1006    /// be repositioned according to the strategy after each dispatch phase.
1007    ///
1008    /// The stored snapshot identity is taken from the strategy's own
1009    /// [`RepositionStrategy::builtin_id`] when it returns `Some(..)`,
1010    /// so built-in strategies always round-trip as themselves even if
1011    /// the `id` argument drifts out of sync with the actual impl.
1012    /// Custom strategies that don't override `builtin_id` fall back
1013    /// to the caller-supplied `id`, preserving the prior API for
1014    /// registered custom factories.
1015    pub fn set_reposition(
1016        &mut self,
1017        group: GroupId,
1018        strategy: Box<dyn RepositionStrategy>,
1019        id: BuiltinReposition,
1020    ) {
1021        let resolved_id = strategy.builtin_id().unwrap_or(id);
1022        self.repositioners.insert(group, strategy);
1023        self.reposition_ids.insert(group, resolved_id);
1024    }
1025
1026    /// Remove the reposition strategy for a group, disabling repositioning.
1027    pub fn remove_reposition(&mut self, group: GroupId) {
1028        self.repositioners.remove(&group);
1029        self.reposition_ids.remove(&group);
1030    }
1031
1032    /// Get the reposition strategy identifier for a group.
1033    #[must_use]
1034    pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1035        self.reposition_ids.get(&group)
1036    }
1037
1038    // ── Hooks ────────────────────────────────────────────────────────
1039
1040    /// Register a hook to run before a simulation phase.
1041    ///
1042    /// Hooks are called in registration order. The hook receives mutable
1043    /// access to the world, allowing entity inspection or modification.
1044    pub fn add_before_hook(
1045        &mut self,
1046        phase: Phase,
1047        hook: impl Fn(&mut World) + Send + Sync + 'static,
1048    ) {
1049        self.hooks.add_before(phase, Box::new(hook));
1050    }
1051
1052    /// Register a hook to run after a simulation phase.
1053    ///
1054    /// Hooks are called in registration order. The hook receives mutable
1055    /// access to the world, allowing entity inspection or modification.
1056    pub fn add_after_hook(
1057        &mut self,
1058        phase: Phase,
1059        hook: impl Fn(&mut World) + Send + Sync + 'static,
1060    ) {
1061        self.hooks.add_after(phase, Box::new(hook));
1062    }
1063
1064    /// Register a hook to run before a phase for a specific group.
1065    pub fn add_before_group_hook(
1066        &mut self,
1067        phase: Phase,
1068        group: GroupId,
1069        hook: impl Fn(&mut World) + Send + Sync + 'static,
1070    ) {
1071        self.hooks.add_before_group(phase, group, Box::new(hook));
1072    }
1073
1074    /// Register a hook to run after a phase for a specific group.
1075    pub fn add_after_group_hook(
1076        &mut self,
1077        phase: Phase,
1078        group: GroupId,
1079        hook: impl Fn(&mut World) + Send + Sync + 'static,
1080    ) {
1081        self.hooks.add_after_group(phase, group, Box::new(hook));
1082    }
1083}