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::{
18    Elevator, ElevatorPhase, Line, LineKind, Orientation, Position, Stop, Velocity,
19};
20use crate::config::SimConfig;
21use crate::dispatch::{
22    BuiltinReposition, BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo,
23    RepositionStrategy,
24};
25use crate::door::DoorState;
26use crate::entity::EntityId;
27use crate::error::SimError;
28use crate::events::EventBus;
29use crate::hooks::{Phase, PhaseHooks};
30use crate::ids::GroupId;
31use crate::metrics::Metrics;
32use crate::rider_index::RiderIndex;
33use crate::stop::StopId;
34use crate::time::TimeAdapter;
35use crate::topology::TopologyGraph;
36use crate::world::World;
37
38use super::Simulation;
39
40/// Bundled topology result: groups, dispatchers, and strategy IDs.
41type TopologyResult = (
42    Vec<ElevatorGroup>,
43    BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
44    BTreeMap<GroupId, BuiltinStrategy>,
45);
46
47/// Canonical [`HallCallMode`](crate::dispatch::HallCallMode) for a
48/// built-in dispatch strategy.
49///
50/// Returns `None` for [`BuiltinStrategy::Custom`] — custom strategies
51/// don't have a canonical mode and keep whatever the group already
52/// carries. Returns `Some(Destination)` only for the destination
53/// dispatch; every other built-in is `Some(Classic)`.
54///
55/// One source of truth for the construction-time and runtime sync paths
56/// (`sync_hall_call_modes` and [`Simulation::set_dispatch`]). Add the
57/// match arm here when introducing a new built-in dispatch.
58pub(super) const fn canonical_hall_call_mode(
59    strategy: &BuiltinStrategy,
60) -> Option<crate::dispatch::HallCallMode> {
61    match strategy {
62        BuiltinStrategy::Destination => Some(crate::dispatch::HallCallMode::Destination),
63        BuiltinStrategy::Custom(_) => None,
64        BuiltinStrategy::Scan
65        | BuiltinStrategy::Look
66        | BuiltinStrategy::NearestCar
67        | BuiltinStrategy::Etd
68        | BuiltinStrategy::Rsr => Some(crate::dispatch::HallCallMode::Classic),
69        // Loop groups use a one-way patrol model — no concept of an
70        // "Up" vs "Down" hall call, and the boarding phase doesn't gate
71        // on assignment. Classic collective control is the closest fit
72        // (every car serves every waiter regardless of direction lamps).
73        #[cfg(feature = "loop_lines")]
74        BuiltinStrategy::LoopSweep | BuiltinStrategy::LoopSchedule => {
75            Some(crate::dispatch::HallCallMode::Classic)
76        }
77    }
78}
79
80/// Ensure DCS groups have `HallCallMode::Destination` at construction
81/// time. Non-DCS groups are left at whatever the config specified —
82/// forcing Classic here would clobber explicit config overrides (e.g. a
83/// Scan group that the author deliberately set to Destination mode).
84///
85/// Runtime swaps via [`Simulation::set_dispatch`] do a full bidirectional
86/// sync because a strategy change is an explicit user action where
87/// resetting the mode is expected.
88fn sync_hall_call_modes(
89    groups: &mut [ElevatorGroup],
90    strategy_ids: &BTreeMap<GroupId, BuiltinStrategy>,
91) {
92    for group in groups.iter_mut() {
93        if let Some(strategy) = strategy_ids.get(&group.id())
94            && canonical_hall_call_mode(strategy)
95                == Some(crate::dispatch::HallCallMode::Destination)
96        {
97            group.set_hall_call_mode(crate::dispatch::HallCallMode::Destination);
98        }
99    }
100}
101
102/// Validate the physics fields shared by [`crate::config::ElevatorConfig`]
103/// and [`super::ElevatorParams`]. Both construction-time validation and
104/// the runtime `add_elevator` path call this so an invalid set of params
105/// can never reach the world (zeroes blow up movement; zero door ticks
106/// stall the door FSM).
107#[allow(clippy::too_many_arguments)]
108pub(super) fn validate_elevator_physics(
109    max_speed: f64,
110    acceleration: f64,
111    deceleration: f64,
112    weight_capacity: f64,
113    inspection_speed_factor: f64,
114    door_transition_ticks: u32,
115    door_open_ticks: u32,
116    bypass_load_up_pct: Option<f64>,
117    bypass_load_down_pct: Option<f64>,
118) -> Result<(), SimError> {
119    if !max_speed.is_finite() || max_speed <= 0.0 {
120        return Err(SimError::InvalidConfig {
121            field: "elevators.max_speed",
122            reason: format!("must be finite and positive, got {max_speed}"),
123        });
124    }
125    if !acceleration.is_finite() || acceleration <= 0.0 {
126        return Err(SimError::InvalidConfig {
127            field: "elevators.acceleration",
128            reason: format!("must be finite and positive, got {acceleration}"),
129        });
130    }
131    if !deceleration.is_finite() || deceleration <= 0.0 {
132        return Err(SimError::InvalidConfig {
133            field: "elevators.deceleration",
134            reason: format!("must be finite and positive, got {deceleration}"),
135        });
136    }
137    if !weight_capacity.is_finite() || weight_capacity <= 0.0 {
138        return Err(SimError::InvalidConfig {
139            field: "elevators.weight_capacity",
140            reason: format!("must be finite and positive, got {weight_capacity}"),
141        });
142    }
143    if !inspection_speed_factor.is_finite() || inspection_speed_factor <= 0.0 {
144        return Err(SimError::InvalidConfig {
145            field: "elevators.inspection_speed_factor",
146            reason: format!("must be finite and positive, got {inspection_speed_factor}"),
147        });
148    }
149    if door_transition_ticks == 0 {
150        return Err(SimError::InvalidConfig {
151            field: "elevators.door_transition_ticks",
152            reason: "must be > 0".into(),
153        });
154    }
155    if door_open_ticks == 0 {
156        return Err(SimError::InvalidConfig {
157            field: "elevators.door_open_ticks",
158            reason: "must be > 0".into(),
159        });
160    }
161    validate_bypass_pct("elevators.bypass_load_up_pct", bypass_load_up_pct)?;
162    validate_bypass_pct("elevators.bypass_load_down_pct", bypass_load_down_pct)?;
163    Ok(())
164}
165
166/// `bypass_load_{up,down}_pct` must be a finite fraction in `(0.0, 1.0]`
167/// when set. `pct = 0.0` would bypass at an empty car (nonsense); `NaN`
168/// and infinities silently disable the bypass under the dispatch guard,
169/// which is a silent foot-gun. Reject at config time instead.
170fn validate_bypass_pct(field: &'static str, pct: Option<f64>) -> Result<(), SimError> {
171    let Some(pct) = pct else {
172        return Ok(());
173    };
174    if !pct.is_finite() || pct <= 0.0 || pct > 1.0 {
175        return Err(SimError::InvalidConfig {
176            field,
177            reason: format!("must be finite in (0.0, 1.0] when set, got {pct}"),
178        });
179    }
180    Ok(())
181}
182
183impl Simulation {
184    /// Create a new simulation from config and a dispatch strategy.
185    ///
186    /// Returns `Err` if the config is invalid (zero stops, duplicate IDs,
187    /// negative speeds, etc.).
188    ///
189    /// # Errors
190    ///
191    /// Returns [`SimError::InvalidConfig`] if the configuration has zero stops,
192    /// duplicate stop IDs, zero elevators, non-positive physics parameters,
193    /// invalid starting stops, or non-positive tick rate.
194    pub fn new(
195        config: &SimConfig,
196        dispatch: impl DispatchStrategy + 'static,
197    ) -> Result<Self, SimError> {
198        let mut dispatchers = BTreeMap::new();
199        dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
200        Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
201    }
202
203    /// Create a simulation with pre-configured lifecycle hooks.
204    ///
205    /// Used by [`SimulationBuilder`](crate::builder::SimulationBuilder).
206    #[allow(clippy::too_many_lines)]
207    pub(crate) fn new_with_hooks(
208        config: &SimConfig,
209        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
210        hooks: PhaseHooks,
211    ) -> Result<Self, SimError> {
212        Self::validate_config(config)?;
213
214        let mut world = World::new();
215
216        // Create stop entities.
217        let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
218        for sc in &config.building.stops {
219            let eid = world.spawn();
220            world.set_stop(
221                eid,
222                Stop {
223                    name: sc.name.clone(),
224                    position: sc.position,
225                },
226            );
227            world.set_position(eid, Position { value: sc.position });
228            stop_lookup.insert(sc.id, eid);
229        }
230
231        // Build sorted-stops index for O(log n) PassingFloor detection.
232        let mut sorted: Vec<(f64, EntityId)> = world
233            .iter_stops()
234            .map(|(eid, stop)| (stop.position, eid))
235            .collect();
236        sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
237        world.insert_resource(crate::world::SortedStops(sorted));
238
239        // Per-stop arrival signal, appended on rider spawn and queried
240        // by dispatch/reposition strategies to drive traffic-mode
241        // switches and predictive parking. The destination mirror is
242        // what powers down-peak detection — without it the classifier
243        // sees `total_dest = 0` and silently never emits `DownPeak`.
244        // Both resources must exist before the first `RiderSpawned`
245        // event fires (i.e. before any user-driven `spawn_rider` call):
246        // `record_spawn` is fire-and-forget on missing resources, so a
247        // later insert wouldn't replay history.
248        world.insert_resource(crate::arrival_log::ArrivalLog::default());
249        world.insert_resource(crate::arrival_log::DestinationLog::default());
250        world.insert_resource(crate::arrival_log::CurrentTick::default());
251        world.insert_resource(crate::arrival_log::ArrivalLogRetention::default());
252        // Traffic-mode classifier. Auto-refreshed in the metrics phase
253        // from the same rolling window; strategies read the current
254        // mode via `World::resource::<TrafficDetector>()`.
255        world.insert_resource(crate::traffic_detector::TrafficDetector::default());
256        // Per-car reposition cooldown. Populated by the movement
257        // phase when a repositioning car arrives; consulted by the
258        // reposition phase to skip cars that just parked so the
259        // hot-stop ranking can't flip them around again the next
260        // tick.
261        world.insert_resource(crate::dispatch::reposition::RepositionCooldowns::default());
262        // Expose tick rate to strategies that need to unit-convert
263        // tick-denominated elevator fields (door cycle, ack latency)
264        // into the second-denominated terms of their cost functions.
265        // Without this, ETD's door-overhead term was summing ticks
266        // into a seconds expression and getting ~60× over-weighted.
267        world.insert_resource(crate::time::TickRate(config.simulation.ticks_per_second));
268
269        let (mut groups, dispatchers, strategy_ids) =
270            if let Some(line_configs) = &config.building.lines {
271                Self::build_explicit_topology(
272                    &mut world,
273                    config,
274                    line_configs,
275                    &stop_lookup,
276                    builder_dispatchers,
277                )
278            } else {
279                Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
280            };
281        sync_hall_call_modes(&mut groups, &strategy_ids);
282
283        let dt = 1.0 / config.simulation.ticks_per_second;
284
285        world.insert_resource(crate::tagged_metrics::MetricTags::default());
286
287        // Auto-register dispatch-internal extension types the sim itself
288        // owns. The same registration runs in `from_parts` (the
289        // snapshot-restore path); doing it here too means snapshot bytes
290        // taken from a fresh sim and from a restored sim agree on the
291        // extensions BTreeMap shape (#534's review surfaced this
292        // asymmetry: pre-fix, fresh sims had no `assigned_car` extension
293        // entry while restored sims did, breaking byte-equality of the
294        // snapshot bytes round-trip and the lockstep checksum).
295        world.register_ext::<crate::dispatch::destination::AssignedCar>(
296            crate::dispatch::destination::ASSIGNED_CAR_KEY,
297        );
298
299        // Collect line tag info (entity + name + elevator entities) before
300        // borrowing world mutably for MetricTags.
301        let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
302            .iter()
303            .flat_map(|group| {
304                group.lines().iter().filter_map(|li| {
305                    let line_comp = world.line(li.entity())?;
306                    Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
307                })
308            })
309            .collect();
310
311        // Tag line entities and their elevators with "line:{name}".
312        if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
313            for (line_eid, name, elevators) in &line_tag_info {
314                let tag = format!("line:{name}");
315                tags.tag(*line_eid, tag.clone());
316                for elev_eid in elevators {
317                    tags.tag(*elev_eid, tag.clone());
318                }
319            }
320        }
321
322        // Wire reposition strategies from group configs.
323        let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
324        let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
325        if let Some(group_configs) = &config.building.groups {
326            for gc in group_configs {
327                if let Some(ref repo_id) = gc.reposition
328                    && let Some(strategy) = repo_id.instantiate()
329                {
330                    let gid = GroupId(gc.id);
331                    repositioners.insert(gid, strategy);
332                    reposition_ids.insert(gid, repo_id.clone());
333                }
334            }
335        }
336
337        Ok(Self {
338            world,
339            events: EventBus::default(),
340            pending_output: Vec::new(),
341            tick: 0,
342            dt,
343            groups,
344            stop_lookup,
345            dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
346            repositioner_set: super::RepositionerSet::from_parts(repositioners, reposition_ids),
347            metrics: Metrics::new(),
348            time: TimeAdapter::new(config.simulation.ticks_per_second),
349            hooks,
350            elevator_ids_buf: Vec::new(),
351            reposition_buf: Vec::new(),
352            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
353            topo_graph: Mutex::new(TopologyGraph::new()),
354            rider_index: RiderIndex::default(),
355            tick_in_progress: false,
356        })
357    }
358
359    /// Spawn a single elevator entity from an `ElevatorConfig` onto `line`.
360    ///
361    /// Sets position, velocity, all `Elevator` fields, optional energy profile,
362    /// optional service mode, and an empty `DestinationQueue`.
363    /// Returns the new entity ID.
364    fn spawn_elevator_entity(
365        world: &mut World,
366        ec: &crate::config::ElevatorConfig,
367        line: EntityId,
368        stop_lookup: &HashMap<StopId, EntityId>,
369        start_pos_lookup: &[crate::stop::StopConfig],
370    ) -> EntityId {
371        let eid = world.spawn();
372        let start_pos = start_pos_lookup
373            .iter()
374            .find(|s| s.id == ec.starting_stop)
375            .map_or(0.0, |s| s.position);
376        world.set_position(eid, Position { value: start_pos });
377        world.set_velocity(eid, Velocity { value: 0.0 });
378        let restricted: HashSet<EntityId> = ec
379            .restricted_stops
380            .iter()
381            .filter_map(|sid| stop_lookup.get(sid).copied())
382            .collect();
383        world.set_elevator(
384            eid,
385            Elevator {
386                phase: ElevatorPhase::Idle,
387                door: DoorState::Closed,
388                max_speed: ec.max_speed,
389                acceleration: ec.acceleration,
390                deceleration: ec.deceleration,
391                weight_capacity: ec.weight_capacity,
392                current_load: crate::components::Weight::ZERO,
393                riders: Vec::new(),
394                target_stop: None,
395                door_transition_ticks: ec.door_transition_ticks,
396                door_open_ticks: ec.door_open_ticks,
397                line,
398                repositioning: false,
399                restricted_stops: restricted,
400                inspection_speed_factor: ec.inspection_speed_factor,
401                going_up: true,
402                going_down: true,
403                going_forward: false,
404                move_count: 0,
405                door_command_queue: Vec::new(),
406                manual_target_velocity: None,
407                bypass_load_up_pct: ec.bypass_load_up_pct,
408                bypass_load_down_pct: ec.bypass_load_down_pct,
409                home_stop: None,
410            },
411        );
412        #[cfg(feature = "energy")]
413        if let Some(ref profile) = ec.energy_profile {
414            world.set_energy_profile(eid, profile.clone());
415            world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
416        }
417        if let Some(mode) = ec.service_mode {
418            world.set_service_mode(eid, mode);
419        }
420        world.set_destination_queue(eid, crate::components::DestinationQueue::new());
421        eid
422    }
423
424    /// Build topology from the legacy flat elevator list (single default line + group).
425    fn build_legacy_topology(
426        world: &mut World,
427        config: &SimConfig,
428        stop_lookup: &HashMap<StopId, EntityId>,
429        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
430    ) -> TopologyResult {
431        // Iterate the config's stop list (deterministic Vec order) and
432        // resolve each through the lookup. Walking `stop_lookup.values()`
433        // would expose `HashMap` iteration order — which varies by
434        // per-process hash seed — into `LineInfo.serves` and from
435        // there into snapshot bytes.
436        let all_stop_entities: Vec<EntityId> = config
437            .building
438            .stops
439            .iter()
440            .filter_map(|s| stop_lookup.get(&s.id).copied())
441            .collect();
442        let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
443        let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
444        let max_pos = stop_positions
445            .iter()
446            .copied()
447            .fold(f64::NEG_INFINITY, f64::max);
448
449        let default_line_eid = world.spawn();
450        world.set_line(
451            default_line_eid,
452            Line {
453                name: "Default".into(),
454                group: GroupId(0),
455                orientation: Orientation::Vertical,
456                position: None,
457                kind: LineKind::Linear {
458                    min: min_pos,
459                    max: max_pos,
460                },
461                max_cars: None,
462            },
463        );
464
465        let mut elevator_entities = Vec::new();
466        for ec in &config.elevators {
467            let eid = Self::spawn_elevator_entity(
468                world,
469                ec,
470                default_line_eid,
471                stop_lookup,
472                &config.building.stops,
473            );
474            elevator_entities.push(eid);
475        }
476
477        let default_line_info =
478            LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
479
480        let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
481
482        // Legacy topology has exactly one group: GroupId(0). Take a builder
483        // entry keyed on that group; ignore entries keyed on any other group
484        // (they would have nothing to attach to in the legacy schema).
485        let mut dispatchers = BTreeMap::new();
486        let mut strategy_ids = BTreeMap::new();
487        let user_dispatcher = builder_dispatchers
488            .into_iter()
489            .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
490        // Snapshot identity comes from the dispatcher's own `builtin_id`, not
491        // from a hard-coded variant — otherwise a snapshot round-trip would
492        // silently swap a custom strategy back to Scan. Strategies that
493        // return `None` fall back to Scan for snapshot fidelity.
494        let inferred_id = user_dispatcher
495            .as_ref()
496            .and_then(|d| d.builtin_id())
497            .unwrap_or(BuiltinStrategy::Scan);
498        if let Some(d) = user_dispatcher {
499            dispatchers.insert(GroupId(0), d);
500        } else {
501            dispatchers.insert(
502                GroupId(0),
503                Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
504            );
505        }
506        strategy_ids.insert(GroupId(0), inferred_id);
507
508        (vec![group], dispatchers, strategy_ids)
509    }
510
511    /// Build topology from explicit `LineConfig`/`GroupConfig` definitions.
512    #[allow(clippy::too_many_lines)]
513    fn build_explicit_topology(
514        world: &mut World,
515        config: &SimConfig,
516        line_configs: &[crate::config::LineConfig],
517        stop_lookup: &HashMap<StopId, EntityId>,
518        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
519    ) -> TopologyResult {
520        // Map line config id → (line EntityId, LineInfo). `BTreeMap`
521        // (not `HashMap`) so the auto-inferred-groups branch iterates
522        // `.values()` in deterministic key order — otherwise the
523        // resulting `LineInfo` sequence permutes across processes and
524        // leaks into snapshot bytes via `GroupSnapshot::lines`.
525        let mut line_map: BTreeMap<u32, (EntityId, LineInfo)> = BTreeMap::new();
526
527        for lc in line_configs {
528            // Resolve served stop entities.
529            let served_entities: Vec<EntityId> = lc
530                .serves
531                .iter()
532                .filter_map(|sid| stop_lookup.get(sid).copied())
533                .collect();
534
535            // Compute min/max from stops if not explicitly set.
536            let stop_positions: Vec<f64> = lc
537                .serves
538                .iter()
539                .filter_map(|sid| {
540                    config
541                        .building
542                        .stops
543                        .iter()
544                        .find(|s| s.id == *sid)
545                        .map(|s| s.position)
546                })
547                .collect();
548            let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
549            let auto_max = stop_positions
550                .iter()
551                .copied()
552                .fold(f64::NEG_INFINITY, f64::max);
553
554            let min_pos = lc.min_position.unwrap_or(auto_min);
555            let max_pos = lc.max_position.unwrap_or(auto_max);
556
557            let line_eid = world.spawn();
558            // The group assignment will be set when we process GroupConfigs.
559            // Default to GroupId(0) initially. `kind` was validated in
560            // `validate_explicit_topology` before this builder ran.
561            world.set_line(
562                line_eid,
563                Line {
564                    name: lc.name.clone(),
565                    group: GroupId(0),
566                    orientation: lc.orientation,
567                    position: lc.position,
568                    kind: lc.kind.unwrap_or(LineKind::Linear {
569                        min: min_pos,
570                        max: max_pos,
571                    }),
572                    max_cars: lc.max_cars,
573                },
574            );
575
576            // Spawn elevators for this line.
577            let mut elevator_entities = Vec::new();
578            for ec in &lc.elevators {
579                let eid = Self::spawn_elevator_entity(
580                    world,
581                    ec,
582                    line_eid,
583                    stop_lookup,
584                    &config.building.stops,
585                );
586                elevator_entities.push(eid);
587            }
588
589            let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
590            line_map.insert(lc.id, (line_eid, line_info));
591        }
592
593        // Build groups from GroupConfigs, or auto-infer a single group.
594        let group_configs = config.building.groups.as_deref();
595        let mut groups = Vec::new();
596        let mut dispatchers = BTreeMap::new();
597        let mut strategy_ids = BTreeMap::new();
598
599        if let Some(gcs) = group_configs {
600            for gc in gcs {
601                let group_id = GroupId(gc.id);
602
603                let mut group_lines = Vec::new();
604
605                for &lid in &gc.lines {
606                    if let Some((line_eid, li)) = line_map.get(&lid) {
607                        // Update the line's group assignment.
608                        if let Some(line_comp) = world.line_mut(*line_eid) {
609                            line_comp.group = group_id;
610                        }
611                        group_lines.push(li.clone());
612                    }
613                }
614
615                let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
616                if let Some(mode) = gc.hall_call_mode {
617                    group.set_hall_call_mode(mode);
618                }
619                if let Some(ticks) = gc.ack_latency_ticks {
620                    group.set_ack_latency_ticks(ticks);
621                }
622                groups.push(group);
623
624                // GroupConfig strategy; builder overrides applied after this loop.
625                let dispatch: Box<dyn DispatchStrategy> = gc
626                    .dispatch
627                    .instantiate()
628                    .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
629                dispatchers.insert(group_id, dispatch);
630                strategy_ids.insert(group_id, gc.dispatch.clone());
631            }
632        } else {
633            // No explicit groups — create a single default group with all lines.
634            let group_id = GroupId(0);
635            let mut group_lines = Vec::new();
636
637            for (line_eid, li) in line_map.values() {
638                if let Some(line_comp) = world.line_mut(*line_eid) {
639                    line_comp.group = group_id;
640                }
641                group_lines.push(li.clone());
642            }
643
644            let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
645            groups.push(group);
646
647            let dispatch: Box<dyn DispatchStrategy> =
648                Box::new(crate::dispatch::scan::ScanDispatch::new());
649            dispatchers.insert(group_id, dispatch);
650            strategy_ids.insert(group_id, BuiltinStrategy::Scan);
651        }
652
653        // Builder-provided dispatchers override the config. For the matching
654        // `strategy_ids` entry, prefer the dispatcher's own `builtin_id()`
655        // (snapshot fidelity); fall back to the config id only when the
656        // dispatcher is unidentified (custom strategies that don't override).
657        for (gid, d) in builder_dispatchers {
658            let inferred_id = d.builtin_id();
659            dispatchers.insert(gid, d);
660            match inferred_id {
661                Some(id) => {
662                    strategy_ids.insert(gid, id);
663                }
664                None => {
665                    strategy_ids
666                        .entry(gid)
667                        .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
668                }
669            }
670        }
671
672        (groups, dispatchers, strategy_ids)
673    }
674
675    /// Restore a simulation from pre-built parts (used by snapshot restore).
676    #[allow(clippy::too_many_arguments)]
677    pub(crate) fn from_parts(
678        world: World,
679        tick: u64,
680        dt: f64,
681        groups: Vec<ElevatorGroup>,
682        stop_lookup: HashMap<StopId, EntityId>,
683        dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
684        strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
685        metrics: Metrics,
686        ticks_per_second: f64,
687    ) -> Self {
688        let mut rider_index = RiderIndex::default();
689        rider_index.rebuild(&world);
690        // Forward-compat: snapshots predating these resources won't carry
691        // them. `TickRate` would otherwise default to 60 Hz and silently
692        // halve ETD's door-cost scale on a 30 Hz sim; the traffic detector
693        // would no-op forever in the metrics phase. `insert_resource` is
694        // last-writer-wins, so snapshots that already carry them are kept.
695        let mut world = world;
696        world.insert_resource(crate::time::TickRate(ticks_per_second));
697        if world
698            .resource::<crate::traffic_detector::TrafficDetector>()
699            .is_none()
700        {
701            world.insert_resource(crate::traffic_detector::TrafficDetector::default());
702        }
703        // Same forward-compat pattern for the destination log. An
704        // older snapshot would leave the detector unable to detect
705        // down-peak post-restore; a fresh empty log lets it resume
706        // classification after a few ticks of observed traffic.
707        if world
708            .resource::<crate::arrival_log::DestinationLog>()
709            .is_none()
710        {
711            world.insert_resource(crate::arrival_log::DestinationLog::default());
712        }
713        // Auto-register dispatch-internal extension types the sim itself
714        // owns, and immediately load their data from the pending
715        // resource. Without this, DCS sticky assignments
716        // (`AssignedCar`) evaporate across snapshot round-trip and
717        // `DestinationDispatch` re-computes every commitment from
718        // scratch — producing different decisions than the original
719        // sim and breaking tick-for-tick determinism.
720        //
721        // `deserialize_extensions` takes a `&` of the pending map and
722        // silently skips types that aren't registered, so the call is
723        // safe to make with user-owned extensions still in the map.
724        // The `PendingExtensions` resource stays in place for a later
725        // `load_extensions_with` call to materialize the caller's own
726        // types.
727        world.register_ext::<crate::dispatch::destination::AssignedCar>(
728            crate::dispatch::destination::ASSIGNED_CAR_KEY,
729        );
730        if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
731            let data = pending.0.clone();
732            world.deserialize_extensions(&data);
733        }
734        Self {
735            world,
736            events: EventBus::default(),
737            pending_output: Vec::new(),
738            tick,
739            dt,
740            groups,
741            stop_lookup,
742            dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
743            repositioner_set: super::RepositionerSet::new(),
744            metrics,
745            time: TimeAdapter::new(ticks_per_second),
746            hooks: PhaseHooks::default(),
747            elevator_ids_buf: Vec::new(),
748            reposition_buf: Vec::new(),
749            dispatch_scratch: crate::dispatch::DispatchScratch::default(),
750            topo_graph: Mutex::new(TopologyGraph::new()),
751            rider_index,
752            tick_in_progress: false,
753        }
754    }
755
756    /// Validate configuration before constructing the simulation.
757    pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
758        // Schema-version gate: reject forward-incompatible configs (a
759        // future build's RON would silently mis-deserialize fields a
760        // current build doesn't know about) and surface legacy
761        // pre-versioning configs (`schema_version = 0`) as an explicit
762        // upgrade prompt rather than a silent serde-default smear. See
763        // `docs/src/config-versioning.md` for the migration playbook.
764        if config.schema_version > crate::config::CURRENT_CONFIG_SCHEMA_VERSION {
765            return Err(SimError::InvalidConfig {
766                field: "schema_version",
767                reason: format!(
768                    "config schema_version={} is newer than this build's CURRENT_CONFIG_SCHEMA_VERSION={}; upgrade elevator-core or downgrade the config",
769                    config.schema_version,
770                    crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
771                ),
772            });
773        }
774        if config.schema_version == 0 {
775            return Err(SimError::InvalidConfig {
776                field: "schema_version",
777                reason: format!(
778                    "config schema_version=0 (pre-versioning legacy file) — set schema_version: {} explicitly after auditing field defaults; see docs/src/config-versioning.md",
779                    crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
780                ),
781            });
782        }
783
784        if config.building.stops.is_empty() {
785            return Err(SimError::InvalidConfig {
786                field: "building.stops",
787                reason: "at least one stop is required".into(),
788            });
789        }
790
791        // Check for duplicate stop IDs and validate positions.
792        let mut seen_ids = HashSet::new();
793        for stop in &config.building.stops {
794            if !seen_ids.insert(stop.id) {
795                return Err(SimError::InvalidConfig {
796                    field: "building.stops",
797                    reason: format!("duplicate {}", stop.id),
798                });
799            }
800            if !stop.position.is_finite() {
801                return Err(SimError::InvalidConfig {
802                    field: "building.stops.position",
803                    reason: format!("{} has non-finite position {}", stop.id, stop.position),
804                });
805            }
806        }
807
808        let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
809
810        if let Some(line_configs) = &config.building.lines {
811            // ── Explicit topology validation ──
812            Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
813        } else {
814            // ── Legacy flat elevator list validation ──
815            Self::validate_legacy_elevators(&config.elevators, &config.building)?;
816        }
817
818        if !config.simulation.ticks_per_second.is_finite()
819            || config.simulation.ticks_per_second <= 0.0
820        {
821            return Err(SimError::InvalidConfig {
822                field: "simulation.ticks_per_second",
823                reason: format!(
824                    "must be finite and positive, got {}",
825                    config.simulation.ticks_per_second
826                ),
827            });
828        }
829
830        Self::validate_passenger_spawning(&config.passenger_spawning)?;
831
832        Ok(())
833    }
834
835    /// Validate `PassengerSpawnConfig`. Without this, bad inputs reach
836    /// `PoissonSource::from_config` and panic later (NaN/negative weights
837    /// crash `random_range`/`Weight::from`; zero `mean_interval_ticks`
838    /// burst-fires every catch-up tick). (#272)
839    fn validate_passenger_spawning(
840        spawn: &crate::config::PassengerSpawnConfig,
841    ) -> Result<(), SimError> {
842        let (lo, hi) = spawn.weight_range;
843        if !lo.is_finite() || !hi.is_finite() {
844            return Err(SimError::InvalidConfig {
845                field: "passenger_spawning.weight_range",
846                reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
847            });
848        }
849        if lo < 0.0 || hi < 0.0 {
850            return Err(SimError::InvalidConfig {
851                field: "passenger_spawning.weight_range",
852                reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
853            });
854        }
855        if lo > hi {
856            return Err(SimError::InvalidConfig {
857                field: "passenger_spawning.weight_range",
858                reason: format!("min must be <= max, got ({lo}, {hi})"),
859            });
860        }
861        if spawn.mean_interval_ticks == 0 {
862            return Err(SimError::InvalidConfig {
863                field: "passenger_spawning.mean_interval_ticks",
864                reason: "must be > 0; mean_interval_ticks=0 burst-fires \
865                         every catch-up tick"
866                    .into(),
867            });
868        }
869        Ok(())
870    }
871
872    /// Validate the legacy flat elevator list.
873    fn validate_legacy_elevators(
874        elevators: &[crate::config::ElevatorConfig],
875        building: &crate::config::BuildingConfig,
876    ) -> Result<(), SimError> {
877        if elevators.is_empty() {
878            return Err(SimError::InvalidConfig {
879                field: "elevators",
880                reason: "at least one elevator is required".into(),
881            });
882        }
883
884        for elev in elevators {
885            Self::validate_elevator_config(elev, building)?;
886        }
887
888        Ok(())
889    }
890
891    /// Validate a single elevator config's physics and starting stop.
892    fn validate_elevator_config(
893        elev: &crate::config::ElevatorConfig,
894        building: &crate::config::BuildingConfig,
895    ) -> Result<(), SimError> {
896        validate_elevator_physics(
897            elev.max_speed.value(),
898            elev.acceleration.value(),
899            elev.deceleration.value(),
900            elev.weight_capacity.value(),
901            elev.inspection_speed_factor,
902            elev.door_transition_ticks,
903            elev.door_open_ticks,
904            elev.bypass_load_up_pct,
905            elev.bypass_load_down_pct,
906        )?;
907        if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
908            return Err(SimError::InvalidConfig {
909                field: "elevators.starting_stop",
910                reason: format!("references non-existent {}", elev.starting_stop),
911            });
912        }
913        Ok(())
914    }
915
916    /// Validate explicit line/group topology.
917    #[allow(
918        clippy::too_many_lines,
919        reason = "validation reads top-to-bottom; extracting helpers would scatter related rejections across files"
920    )]
921    fn validate_explicit_topology(
922        line_configs: &[crate::config::LineConfig],
923        stop_ids: &HashSet<StopId>,
924        building: &crate::config::BuildingConfig,
925    ) -> Result<(), SimError> {
926        // No duplicate line IDs.
927        let mut seen_line_ids = HashSet::new();
928        for lc in line_configs {
929            if !seen_line_ids.insert(lc.id) {
930                return Err(SimError::InvalidConfig {
931                    field: "building.lines",
932                    reason: format!("duplicate line id {}", lc.id),
933                });
934            }
935        }
936
937        // Every line's serves must reference existing stops and be non-empty.
938        for lc in line_configs {
939            if lc.serves.is_empty() {
940                return Err(SimError::InvalidConfig {
941                    field: "building.lines.serves",
942                    reason: format!("line {} has no stops", lc.id),
943                });
944            }
945            for sid in &lc.serves {
946                if !stop_ids.contains(sid) {
947                    return Err(SimError::InvalidConfig {
948                        field: "building.lines.serves",
949                        reason: format!("line {} references non-existent {}", lc.id, sid),
950                    });
951                }
952            }
953            // Validate elevators within each line.
954            for ec in &lc.elevators {
955                Self::validate_elevator_config(ec, building)?;
956            }
957
958            // Validate max_cars is not exceeded.
959            if let Some(max) = lc.max_cars
960                && lc.elevators.len() > max
961            {
962                return Err(SimError::InvalidConfig {
963                    field: "building.lines.max_cars",
964                    reason: format!(
965                        "line {} has {} elevators but max_cars is {max}",
966                        lc.id,
967                        lc.elevators.len()
968                    ),
969                });
970            }
971
972            // Validate the explicit topology kind, if any. Linear-only
973            // configs (kind = None) are validated by the auto-derived
974            // bounds check inside `build_explicit_topology` instead.
975            if let Some(kind) = lc.kind
976                && let Err((field, reason)) = kind.validate()
977            {
978                return Err(SimError::InvalidConfig { field, reason });
979            }
980
981            // Loop-specific cross-field invariant: every car must fit
982            // around the loop with at least `min_headway` between
983            // successive cars. Without this guard, the second car
984            // configured on a too-short loop would instantly violate
985            // the no-overtake invariant the headway clamp is designed
986            // to preserve.
987            #[cfg(feature = "loop_lines")]
988            if let Some(crate::components::LineKind::Loop {
989                circumference,
990                min_headway,
991            }) = lc.kind
992            {
993                let car_count = lc
994                    .max_cars
995                    .map_or_else(|| lc.elevators.len(), |max| max.max(lc.elevators.len()));
996                if car_count > 0 {
997                    #[allow(
998                        clippy::cast_precision_loss,
999                        reason = "car_count is bounded by usize and the comparison is against a finite f64"
1000                    )]
1001                    let required = (car_count as f64) * min_headway;
1002                    if required > circumference {
1003                        return Err(SimError::InvalidConfig {
1004                            field: "building.lines.kind",
1005                            reason: format!(
1006                                "loop line {}: {car_count} cars × min_headway {min_headway} = {required} \
1007                                 exceeds circumference {circumference}",
1008                                lc.id,
1009                            ),
1010                        });
1011                    }
1012                }
1013            }
1014        }
1015
1016        // At least one line with at least one elevator.
1017        let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
1018        if !has_elevator {
1019            return Err(SimError::InvalidConfig {
1020                field: "building.lines",
1021                reason: "at least one line must have at least one elevator".into(),
1022            });
1023        }
1024
1025        // No orphaned stops: every stop must be served by at least one line.
1026        let served: HashSet<StopId> = line_configs
1027            .iter()
1028            .flat_map(|lc| lc.serves.iter().copied())
1029            .collect();
1030        for sid in stop_ids {
1031            if !served.contains(sid) {
1032                return Err(SimError::InvalidConfig {
1033                    field: "building.lines",
1034                    reason: format!("orphaned stop {sid} not served by any line"),
1035                });
1036            }
1037        }
1038
1039        // Validate groups if present.
1040        if let Some(group_configs) = &building.groups {
1041            let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
1042
1043            let mut seen_group_ids = HashSet::new();
1044            for gc in group_configs {
1045                if !seen_group_ids.insert(gc.id) {
1046                    return Err(SimError::InvalidConfig {
1047                        field: "building.groups",
1048                        reason: format!("duplicate group id {}", gc.id),
1049                    });
1050                }
1051                for &lid in &gc.lines {
1052                    if !line_id_set.contains(&lid) {
1053                        return Err(SimError::InvalidConfig {
1054                            field: "building.groups.lines",
1055                            reason: format!(
1056                                "group {} references non-existent line id {}",
1057                                gc.id, lid
1058                            ),
1059                        });
1060                    }
1061                }
1062            }
1063
1064            // Check for orphaned lines (not referenced by any group).
1065            let referenced_line_ids: HashSet<u32> = group_configs
1066                .iter()
1067                .flat_map(|g| g.lines.iter().copied())
1068                .collect();
1069            for lc in line_configs {
1070                if !referenced_line_ids.contains(&lc.id) {
1071                    return Err(SimError::InvalidConfig {
1072                        field: "building.lines",
1073                        reason: format!("line {} is not assigned to any group", lc.id),
1074                    });
1075                }
1076            }
1077
1078            // Loop-specific group-level invariants. Run inside the
1079            // group-validation block so we can iterate `group_configs`
1080            // without recomputing the lookup. Skipped (compiles to a
1081            // no-op block) when `loop_lines` is off because no Loop
1082            // variant could possibly have been constructed.
1083            #[cfg(feature = "loop_lines")]
1084            for gc in group_configs {
1085                let lines: Vec<&crate::config::LineConfig> = gc
1086                    .lines
1087                    .iter()
1088                    .filter_map(|lid| line_configs.iter().find(|lc| lc.id == *lid))
1089                    .collect();
1090                let any_loop = lines
1091                    .iter()
1092                    .any(|lc| matches!(lc.kind, Some(crate::components::LineKind::Loop { .. })));
1093                // Positive match against the expected linear variant —
1094                // including the implicit-Linear case where `kind = None`.
1095                // Using a negative match against `Loop` would silently
1096                // absorb any future non-Loop variant (e.g. a hypothetical
1097                // `LineKind::Shuttle`) into the "linear" bucket and reject
1098                // intentional Loop+Shuttle mixes as "Linear+Loop", which
1099                // we wouldn't want.
1100                let any_linear = lines
1101                    .iter()
1102                    .any(|lc| lc.kind.as_ref().is_none_or(LineKind::is_linear));
1103                // Homogeneity: a group is either all-Linear or all-Loop.
1104                // Mixing means dispatch and reposition strategies would have
1105                // to handle both topologies in the same group, which the
1106                // strategy authors explicitly opted out of supporting.
1107                if any_loop && any_linear {
1108                    return Err(SimError::InvalidConfig {
1109                        field: "building.groups",
1110                        reason: format!(
1111                            "group {} mixes Loop and Linear lines; groups must be homogeneous",
1112                            gc.id,
1113                        ),
1114                    });
1115                }
1116                // Parking-style reposition strategies don't compose with
1117                // continuous-patrol Loop semantics: PR 4 will make the
1118                // reposition phase a no-op on Loop, but configuring one
1119                // is almost always a misunderstanding so we reject it
1120                // up front.
1121                if any_loop && gc.reposition.is_some() {
1122                    return Err(SimError::InvalidConfig {
1123                        field: "building.groups.reposition",
1124                        reason: format!(
1125                            "group {} contains Loop lines; reposition strategies are unsupported on Loop",
1126                            gc.id,
1127                        ),
1128                    });
1129                }
1130                // Strategy: Loop groups accept `LoopSweep` or
1131                // `LoopSchedule` only. Linear strategies don't apply
1132                // (Loop cars are excluded from the Hungarian idle pool
1133                // by `systems::dispatch::run`), and silently swapping a
1134                // misconfigured Linear strategy for the Loop default
1135                // would hide a bug — every other "wrong strategy" case
1136                // in this file rejects loud, so do the same here.
1137                if any_loop
1138                    && !matches!(
1139                        gc.dispatch,
1140                        BuiltinStrategy::LoopSweep | BuiltinStrategy::LoopSchedule,
1141                    )
1142                {
1143                    return Err(SimError::InvalidConfig {
1144                        field: "building.groups.dispatch",
1145                        reason: format!(
1146                            "group {} contains Loop lines but uses {} dispatch; \
1147                             only LoopSweep or LoopSchedule is supported for Loop groups",
1148                            gc.id, gc.dispatch,
1149                        ),
1150                    });
1151                }
1152            }
1153        }
1154
1155        // Per-line Loop invariants that don't depend on group context:
1156        // duplicate-position stops and initial car spacing.
1157        #[cfg(feature = "loop_lines")]
1158        for lc in line_configs {
1159            let Some(crate::components::LineKind::Loop {
1160                circumference,
1161                min_headway,
1162            }) = lc.kind
1163            else {
1164                continue;
1165            };
1166
1167            // Duplicate-position stops on a Loop are ambiguous in cyclic
1168            // order — `position_a == position_b` mod C means the dispatch
1169            // strategy can't decide which comes "first" deterministically.
1170            // Reject so authors notice the conflict explicitly.
1171            let stop_positions: Vec<f64> = lc
1172                .serves
1173                .iter()
1174                .filter_map(|sid| {
1175                    building
1176                        .stops
1177                        .iter()
1178                        .find(|s| s.id == *sid)
1179                        .map(|s| s.position)
1180                })
1181                .collect();
1182            for (i, &pi) in stop_positions.iter().enumerate() {
1183                for (j, &pj) in stop_positions.iter().enumerate().skip(i + 1) {
1184                    if (pi - pj).abs() < 1e-9 {
1185                        return Err(SimError::InvalidConfig {
1186                            field: "building.lines.serves",
1187                            reason: format!(
1188                                "loop line {} has duplicate stop positions at indices {i} and {j} (both at {pi})",
1189                                lc.id,
1190                            ),
1191                        });
1192                    }
1193                }
1194            }
1195
1196            // Initial car spacing: cars whose `starting_stop` positions
1197            // are closer than `min_headway` would violate the no-overtake
1198            // invariant on tick 0. Compare every pair in cyclic distance
1199            // (the shortest unsigned arc, since we don't know the cyclic
1200            // order from starting positions alone).
1201            let car_starts: Vec<f64> = lc
1202                .elevators
1203                .iter()
1204                .filter_map(|ec| {
1205                    building
1206                        .stops
1207                        .iter()
1208                        .find(|s| s.id == ec.starting_stop)
1209                        .map(|s| s.position)
1210                })
1211                .collect();
1212            for (i, &a) in car_starts.iter().enumerate() {
1213                for (j, &b) in car_starts.iter().enumerate().skip(i + 1) {
1214                    let d = crate::components::cyclic::cyclic_distance(a, b, circumference);
1215                    if d < min_headway - 1e-9 {
1216                        return Err(SimError::InvalidConfig {
1217                            field: "building.lines.elevators.starting_stop",
1218                            reason: format!(
1219                                "loop line {}: cars at indices {i} ({a}) and {j} ({b}) are {d} apart \
1220                                 — below min_headway {min_headway}",
1221                                lc.id,
1222                            ),
1223                        });
1224                    }
1225                }
1226            }
1227        }
1228
1229        Ok(())
1230    }
1231
1232    // ── Dispatch management ──────────────────────────────────────────
1233
1234    /// Replace the dispatch strategy for a group.
1235    ///
1236    /// Also synchronises `HallCallMode`: `Destination` for DCS, `Classic`
1237    /// for other built-ins; `Custom` strategies leave the mode untouched.
1238    ///
1239    /// The stored snapshot identity is taken from the strategy's own
1240    /// [`DispatchStrategy::builtin_id`] when it returns `Some(..)`, so
1241    /// built-in strategies always round-trip as themselves even if the
1242    /// `id` argument drifts out of sync with the actual impl. Custom
1243    /// strategies that don't override `builtin_id` fall back to the
1244    /// caller-supplied `id`, preserving the prior API for registered
1245    /// custom factories. Mirrors the pattern applied to
1246    /// [`set_reposition`](Self::set_reposition) in #414.
1247    pub fn set_dispatch(
1248        &mut self,
1249        group: GroupId,
1250        strategy: Box<dyn DispatchStrategy>,
1251        id: crate::dispatch::BuiltinStrategy,
1252    ) {
1253        let resolved_id = strategy.builtin_id().unwrap_or(id);
1254        if let Some(mode) = canonical_hall_call_mode(&resolved_id)
1255            && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1256        {
1257            g.set_hall_call_mode(mode);
1258        }
1259        self.dispatcher_set.insert(group, strategy, resolved_id);
1260    }
1261
1262    // ── Reposition management ─────────────────────────────────────────
1263
1264    /// Set the reposition strategy for a group.
1265    ///
1266    /// Enables the reposition phase for this group. Idle elevators will
1267    /// be repositioned according to the strategy after each dispatch phase.
1268    ///
1269    /// The stored snapshot identity is taken from the strategy's own
1270    /// [`RepositionStrategy::builtin_id`] when it returns `Some(..)`,
1271    /// so built-in strategies always round-trip as themselves even if
1272    /// the `id` argument drifts out of sync with the actual impl.
1273    /// Custom strategies that don't override `builtin_id` fall back
1274    /// to the caller-supplied `id`, preserving the prior API for
1275    /// registered custom factories.
1276    ///
1277    /// ## Retention
1278    /// Widens [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1279    /// to the strategy's
1280    /// [`min_arrival_log_window`](crate::dispatch::RepositionStrategy::min_arrival_log_window)
1281    /// when that exceeds current retention, never narrows it. This is
1282    /// monotonic by design — replacing a wide-window strategy with a
1283    /// narrow one (or [`remove_reposition`](Self::remove_reposition))
1284    /// leaves retention at the high-water mark rather than recomputing
1285    /// across the remaining strategies, since shrinking would also
1286    /// clobber any explicit
1287    /// [`set_arrival_log_retention_ticks`](Self::set_arrival_log_retention_ticks)
1288    /// the caller made afterwards. Long-running sims that hot-swap
1289    /// strategies pay a memory cost equal to the largest historic
1290    /// window; if that matters, call `set_arrival_log_retention_ticks`
1291    /// explicitly after the swap.
1292    pub fn set_reposition(
1293        &mut self,
1294        group: GroupId,
1295        strategy: Box<dyn RepositionStrategy>,
1296        id: BuiltinReposition,
1297    ) {
1298        let resolved_id = strategy.builtin_id().unwrap_or(id);
1299        let needed_window = strategy.min_arrival_log_window();
1300        self.repositioner_set.insert(group, strategy, resolved_id);
1301        // Widen the arrival-log retention if the freshly installed
1302        // strategy queries a window the pruner would otherwise truncate
1303        // under it. Without this, `PredictiveParking::with_window_ticks`
1304        // (or any custom strategy advertising a longer window) silently
1305        // sees only the last `DEFAULT_ARRIVAL_WINDOW_TICKS` of arrivals.
1306        if needed_window > 0
1307            && let Some(retention) = self
1308                .world
1309                .resource_mut::<crate::arrival_log::ArrivalLogRetention>()
1310            && needed_window > retention.0
1311        {
1312            retention.0 = needed_window;
1313        }
1314    }
1315
1316    /// Remove the reposition strategy for a group, disabling repositioning.
1317    ///
1318    /// Does not narrow
1319    /// [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1320    /// — see the retention note on
1321    /// [`set_reposition`](Self::set_reposition) for why retention is
1322    /// monotonic across strategy lifecycle changes. Call
1323    /// [`set_arrival_log_retention_ticks`](Self::set_arrival_log_retention_ticks)
1324    /// explicitly to shrink retention after removing a wide-window
1325    /// strategy.
1326    pub fn remove_reposition(&mut self, group: GroupId) {
1327        self.repositioner_set.remove(group);
1328    }
1329
1330    /// Get the reposition strategy identifier for a group.
1331    #[must_use]
1332    pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1333        self.repositioner_set.id_for(group)
1334    }
1335
1336    // ── Hooks ────────────────────────────────────────────────────────
1337
1338    /// Register a hook to run before a simulation phase.
1339    ///
1340    /// Hooks are called in registration order. The hook receives mutable
1341    /// access to the world, allowing entity inspection or modification.
1342    pub fn add_before_hook(
1343        &mut self,
1344        phase: Phase,
1345        hook: impl Fn(&mut World) + Send + Sync + 'static,
1346    ) {
1347        self.hooks.add_before(phase, Box::new(hook));
1348    }
1349
1350    /// Register a hook to run after a simulation phase.
1351    ///
1352    /// Hooks are called in registration order. The hook receives mutable
1353    /// access to the world, allowing entity inspection or modification.
1354    pub fn add_after_hook(
1355        &mut self,
1356        phase: Phase,
1357        hook: impl Fn(&mut World) + Send + Sync + 'static,
1358    ) {
1359        self.hooks.add_after(phase, Box::new(hook));
1360    }
1361
1362    /// Register a hook to run before a phase for a specific group.
1363    pub fn add_before_group_hook(
1364        &mut self,
1365        phase: Phase,
1366        group: GroupId,
1367        hook: impl Fn(&mut World) + Send + Sync + 'static,
1368    ) {
1369        self.hooks.add_before_group(phase, group, Box::new(hook));
1370    }
1371
1372    /// Register a hook to run after a phase for a specific group.
1373    pub fn add_after_group_hook(
1374        &mut self,
1375        phase: Phase,
1376        group: GroupId,
1377        hook: impl Fn(&mut World) + Send + Sync + 'static,
1378    ) {
1379        self.hooks.add_after_group(phase, group, Box::new(hook));
1380    }
1381}