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/// Validate the physics fields shared by [`crate::config::ElevatorConfig`]
46/// and [`super::ElevatorParams`]. Both construction-time validation and
47/// the runtime `add_elevator` path call this so an invalid set of params
48/// can never reach the world (zeroes blow up movement; zero door ticks
49/// stall the door FSM).
50pub(super) fn validate_elevator_physics(
51    max_speed: f64,
52    acceleration: f64,
53    deceleration: f64,
54    weight_capacity: f64,
55    inspection_speed_factor: f64,
56    door_transition_ticks: u32,
57    door_open_ticks: u32,
58) -> Result<(), SimError> {
59    if !max_speed.is_finite() || max_speed <= 0.0 {
60        return Err(SimError::InvalidConfig {
61            field: "elevators.max_speed",
62            reason: format!("must be finite and positive, got {max_speed}"),
63        });
64    }
65    if !acceleration.is_finite() || acceleration <= 0.0 {
66        return Err(SimError::InvalidConfig {
67            field: "elevators.acceleration",
68            reason: format!("must be finite and positive, got {acceleration}"),
69        });
70    }
71    if !deceleration.is_finite() || deceleration <= 0.0 {
72        return Err(SimError::InvalidConfig {
73            field: "elevators.deceleration",
74            reason: format!("must be finite and positive, got {deceleration}"),
75        });
76    }
77    if !weight_capacity.is_finite() || weight_capacity <= 0.0 {
78        return Err(SimError::InvalidConfig {
79            field: "elevators.weight_capacity",
80            reason: format!("must be finite and positive, got {weight_capacity}"),
81        });
82    }
83    if !inspection_speed_factor.is_finite() || inspection_speed_factor <= 0.0 {
84        return Err(SimError::InvalidConfig {
85            field: "elevators.inspection_speed_factor",
86            reason: format!("must be finite and positive, got {inspection_speed_factor}"),
87        });
88    }
89    if door_transition_ticks == 0 {
90        return Err(SimError::InvalidConfig {
91            field: "elevators.door_transition_ticks",
92            reason: "must be > 0".into(),
93        });
94    }
95    if door_open_ticks == 0 {
96        return Err(SimError::InvalidConfig {
97            field: "elevators.door_open_ticks",
98            reason: "must be > 0".into(),
99        });
100    }
101    Ok(())
102}
103
104impl Simulation {
105    /// Create a new simulation from config and a dispatch strategy.
106    ///
107    /// Returns `Err` if the config is invalid (zero stops, duplicate IDs,
108    /// negative speeds, etc.).
109    ///
110    /// # Errors
111    ///
112    /// Returns [`SimError::InvalidConfig`] if the configuration has zero stops,
113    /// duplicate stop IDs, zero elevators, non-positive physics parameters,
114    /// invalid starting stops, or non-positive tick rate.
115    pub fn new(
116        config: &SimConfig,
117        dispatch: impl DispatchStrategy + 'static,
118    ) -> Result<Self, SimError> {
119        let mut dispatchers = BTreeMap::new();
120        dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
121        Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
122    }
123
124    /// Create a simulation with pre-configured lifecycle hooks.
125    ///
126    /// Used by [`SimulationBuilder`](crate::builder::SimulationBuilder).
127    #[allow(clippy::too_many_lines)]
128    pub(crate) fn new_with_hooks(
129        config: &SimConfig,
130        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
131        hooks: PhaseHooks,
132    ) -> Result<Self, SimError> {
133        Self::validate_config(config)?;
134
135        let mut world = World::new();
136
137        // Create stop entities.
138        let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
139        for sc in &config.building.stops {
140            let eid = world.spawn();
141            world.set_stop(
142                eid,
143                Stop {
144                    name: sc.name.clone(),
145                    position: sc.position,
146                },
147            );
148            world.set_position(eid, Position { value: sc.position });
149            stop_lookup.insert(sc.id, eid);
150        }
151
152        // Build sorted-stops index for O(log n) PassingFloor detection.
153        let mut sorted: Vec<(f64, EntityId)> = world
154            .iter_stops()
155            .map(|(eid, stop)| (stop.position, eid))
156            .collect();
157        sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
158        world.insert_resource(crate::world::SortedStops(sorted));
159
160        let (groups, dispatchers, strategy_ids) = if let Some(line_configs) = &config.building.lines
161        {
162            Self::build_explicit_topology(
163                &mut world,
164                config,
165                line_configs,
166                &stop_lookup,
167                builder_dispatchers,
168            )
169        } else {
170            Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
171        };
172
173        let dt = 1.0 / config.simulation.ticks_per_second;
174
175        world.insert_resource(crate::tagged_metrics::MetricTags::default());
176
177        // Collect line tag info (entity + name + elevator entities) before
178        // borrowing world mutably for MetricTags.
179        let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
180            .iter()
181            .flat_map(|group| {
182                group.lines().iter().filter_map(|li| {
183                    let line_comp = world.line(li.entity())?;
184                    Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
185                })
186            })
187            .collect();
188
189        // Tag line entities and their elevators with "line:{name}".
190        if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
191            for (line_eid, name, elevators) in &line_tag_info {
192                let tag = format!("line:{name}");
193                tags.tag(*line_eid, tag.clone());
194                for elev_eid in elevators {
195                    tags.tag(*elev_eid, tag.clone());
196                }
197            }
198        }
199
200        // Wire reposition strategies from group configs.
201        let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
202        let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
203        if let Some(group_configs) = &config.building.groups {
204            for gc in group_configs {
205                if let Some(ref repo_id) = gc.reposition
206                    && let Some(strategy) = repo_id.instantiate()
207                {
208                    let gid = GroupId(gc.id);
209                    repositioners.insert(gid, strategy);
210                    reposition_ids.insert(gid, repo_id.clone());
211                }
212            }
213        }
214
215        Ok(Self {
216            world,
217            events: EventBus::default(),
218            pending_output: Vec::new(),
219            tick: 0,
220            dt,
221            groups,
222            stop_lookup,
223            dispatchers,
224            strategy_ids,
225            repositioners,
226            reposition_ids,
227            metrics: Metrics::new(),
228            time: TimeAdapter::new(config.simulation.ticks_per_second),
229            hooks,
230            elevator_ids_buf: Vec::new(),
231            reposition_buf: Vec::new(),
232            topo_graph: Mutex::new(TopologyGraph::new()),
233            rider_index: RiderIndex::default(),
234        })
235    }
236
237    /// Spawn a single elevator entity from an `ElevatorConfig` onto `line`.
238    ///
239    /// Sets position, velocity, all `Elevator` fields, optional energy profile,
240    /// optional service mode, and an empty `DestinationQueue`.
241    /// Returns the new entity ID.
242    fn spawn_elevator_entity(
243        world: &mut World,
244        ec: &crate::config::ElevatorConfig,
245        line: EntityId,
246        stop_lookup: &HashMap<StopId, EntityId>,
247        start_pos_lookup: &[crate::stop::StopConfig],
248    ) -> EntityId {
249        let eid = world.spawn();
250        let start_pos = start_pos_lookup
251            .iter()
252            .find(|s| s.id == ec.starting_stop)
253            .map_or(0.0, |s| s.position);
254        world.set_position(eid, Position { value: start_pos });
255        world.set_velocity(eid, Velocity { value: 0.0 });
256        let restricted: HashSet<EntityId> = ec
257            .restricted_stops
258            .iter()
259            .filter_map(|sid| stop_lookup.get(sid).copied())
260            .collect();
261        world.set_elevator(
262            eid,
263            Elevator {
264                phase: ElevatorPhase::Idle,
265                door: DoorState::Closed,
266                max_speed: ec.max_speed,
267                acceleration: ec.acceleration,
268                deceleration: ec.deceleration,
269                weight_capacity: ec.weight_capacity,
270                current_load: crate::components::Weight::ZERO,
271                riders: Vec::new(),
272                target_stop: None,
273                door_transition_ticks: ec.door_transition_ticks,
274                door_open_ticks: ec.door_open_ticks,
275                line,
276                repositioning: false,
277                restricted_stops: restricted,
278                inspection_speed_factor: ec.inspection_speed_factor,
279                going_up: true,
280                going_down: true,
281                move_count: 0,
282                door_command_queue: Vec::new(),
283                manual_target_velocity: None,
284            },
285        );
286        #[cfg(feature = "energy")]
287        if let Some(ref profile) = ec.energy_profile {
288            world.set_energy_profile(eid, profile.clone());
289            world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
290        }
291        if let Some(mode) = ec.service_mode {
292            world.set_service_mode(eid, mode);
293        }
294        world.set_destination_queue(eid, crate::components::DestinationQueue::new());
295        eid
296    }
297
298    /// Build topology from the legacy flat elevator list (single default line + group).
299    fn build_legacy_topology(
300        world: &mut World,
301        config: &SimConfig,
302        stop_lookup: &HashMap<StopId, EntityId>,
303        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
304    ) -> TopologyResult {
305        let all_stop_entities: Vec<EntityId> = stop_lookup.values().copied().collect();
306        let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
307        let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
308        let max_pos = stop_positions
309            .iter()
310            .copied()
311            .fold(f64::NEG_INFINITY, f64::max);
312
313        let default_line_eid = world.spawn();
314        world.set_line(
315            default_line_eid,
316            Line {
317                name: "Default".into(),
318                group: GroupId(0),
319                orientation: Orientation::Vertical,
320                position: None,
321                min_position: min_pos,
322                max_position: max_pos,
323                max_cars: None,
324            },
325        );
326
327        let mut elevator_entities = Vec::new();
328        for ec in &config.elevators {
329            let eid = Self::spawn_elevator_entity(
330                world,
331                ec,
332                default_line_eid,
333                stop_lookup,
334                &config.building.stops,
335            );
336            elevator_entities.push(eid);
337        }
338
339        let default_line_info =
340            LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
341
342        let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
343
344        // Use builder-provided dispatcher or default Scan.
345        let mut dispatchers = BTreeMap::new();
346        let dispatch = builder_dispatchers.into_iter().next().map_or_else(
347            || Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
348            |(_, d)| d,
349        );
350        dispatchers.insert(GroupId(0), dispatch);
351
352        let mut strategy_ids = BTreeMap::new();
353        strategy_ids.insert(GroupId(0), BuiltinStrategy::Scan);
354
355        (vec![group], dispatchers, strategy_ids)
356    }
357
358    /// Build topology from explicit `LineConfig`/`GroupConfig` definitions.
359    #[allow(clippy::too_many_lines)]
360    fn build_explicit_topology(
361        world: &mut World,
362        config: &SimConfig,
363        line_configs: &[crate::config::LineConfig],
364        stop_lookup: &HashMap<StopId, EntityId>,
365        builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
366    ) -> TopologyResult {
367        // Map line config id → (line EntityId, LineInfo).
368        let mut line_map: HashMap<u32, (EntityId, LineInfo)> = HashMap::new();
369
370        for lc in line_configs {
371            // Resolve served stop entities.
372            let served_entities: Vec<EntityId> = lc
373                .serves
374                .iter()
375                .filter_map(|sid| stop_lookup.get(sid).copied())
376                .collect();
377
378            // Compute min/max from stops if not explicitly set.
379            let stop_positions: Vec<f64> = lc
380                .serves
381                .iter()
382                .filter_map(|sid| {
383                    config
384                        .building
385                        .stops
386                        .iter()
387                        .find(|s| s.id == *sid)
388                        .map(|s| s.position)
389                })
390                .collect();
391            let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
392            let auto_max = stop_positions
393                .iter()
394                .copied()
395                .fold(f64::NEG_INFINITY, f64::max);
396
397            let min_pos = lc.min_position.unwrap_or(auto_min);
398            let max_pos = lc.max_position.unwrap_or(auto_max);
399
400            let line_eid = world.spawn();
401            // The group assignment will be set when we process GroupConfigs.
402            // Default to GroupId(0) initially.
403            world.set_line(
404                line_eid,
405                Line {
406                    name: lc.name.clone(),
407                    group: GroupId(0),
408                    orientation: lc.orientation,
409                    position: lc.position,
410                    min_position: min_pos,
411                    max_position: max_pos,
412                    max_cars: lc.max_cars,
413                },
414            );
415
416            // Spawn elevators for this line.
417            let mut elevator_entities = Vec::new();
418            for ec in &lc.elevators {
419                let eid = Self::spawn_elevator_entity(
420                    world,
421                    ec,
422                    line_eid,
423                    stop_lookup,
424                    &config.building.stops,
425                );
426                elevator_entities.push(eid);
427            }
428
429            let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
430            line_map.insert(lc.id, (line_eid, line_info));
431        }
432
433        // Build groups from GroupConfigs, or auto-infer a single group.
434        let group_configs = config.building.groups.as_deref();
435        let mut groups = Vec::new();
436        let mut dispatchers = BTreeMap::new();
437        let mut strategy_ids = BTreeMap::new();
438
439        if let Some(gcs) = group_configs {
440            for gc in gcs {
441                let group_id = GroupId(gc.id);
442
443                let mut group_lines = Vec::new();
444
445                for &lid in &gc.lines {
446                    if let Some((line_eid, li)) = line_map.get(&lid) {
447                        // Update the line's group assignment.
448                        if let Some(line_comp) = world.line_mut(*line_eid) {
449                            line_comp.group = group_id;
450                        }
451                        group_lines.push(li.clone());
452                    }
453                }
454
455                let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
456                if let Some(mode) = gc.hall_call_mode {
457                    group.set_hall_call_mode(mode);
458                }
459                if let Some(ticks) = gc.ack_latency_ticks {
460                    group.set_ack_latency_ticks(ticks);
461                }
462                groups.push(group);
463
464                // GroupConfig strategy; builder overrides applied after this loop.
465                let dispatch: Box<dyn DispatchStrategy> = gc
466                    .dispatch
467                    .instantiate()
468                    .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
469                dispatchers.insert(group_id, dispatch);
470                strategy_ids.insert(group_id, gc.dispatch.clone());
471            }
472        } else {
473            // No explicit groups — create a single default group with all lines.
474            let group_id = GroupId(0);
475            let mut group_lines = Vec::new();
476
477            for (line_eid, li) in line_map.values() {
478                if let Some(line_comp) = world.line_mut(*line_eid) {
479                    line_comp.group = group_id;
480                }
481                group_lines.push(li.clone());
482            }
483
484            let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
485            groups.push(group);
486
487            let dispatch: Box<dyn DispatchStrategy> =
488                Box::new(crate::dispatch::scan::ScanDispatch::new());
489            dispatchers.insert(group_id, dispatch);
490            strategy_ids.insert(group_id, BuiltinStrategy::Scan);
491        }
492
493        // Override with builder-provided dispatchers (they take precedence).
494        for (gid, d) in builder_dispatchers {
495            dispatchers.insert(gid, d);
496        }
497
498        (groups, dispatchers, strategy_ids)
499    }
500
501    /// Restore a simulation from pre-built parts (used by snapshot restore).
502    #[allow(clippy::too_many_arguments)]
503    pub(crate) fn from_parts(
504        world: World,
505        tick: u64,
506        dt: f64,
507        groups: Vec<ElevatorGroup>,
508        stop_lookup: HashMap<StopId, EntityId>,
509        dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
510        strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
511        metrics: Metrics,
512        ticks_per_second: f64,
513    ) -> Self {
514        let mut rider_index = RiderIndex::default();
515        rider_index.rebuild(&world);
516        Self {
517            world,
518            events: EventBus::default(),
519            pending_output: Vec::new(),
520            tick,
521            dt,
522            groups,
523            stop_lookup,
524            dispatchers,
525            strategy_ids,
526            repositioners: BTreeMap::new(),
527            reposition_ids: BTreeMap::new(),
528            metrics,
529            time: TimeAdapter::new(ticks_per_second),
530            hooks: PhaseHooks::default(),
531            elevator_ids_buf: Vec::new(),
532            reposition_buf: Vec::new(),
533            topo_graph: Mutex::new(TopologyGraph::new()),
534            rider_index,
535        }
536    }
537
538    /// Validate configuration before constructing the simulation.
539    pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
540        if config.building.stops.is_empty() {
541            return Err(SimError::InvalidConfig {
542                field: "building.stops",
543                reason: "at least one stop is required".into(),
544            });
545        }
546
547        // Check for duplicate stop IDs and validate positions.
548        let mut seen_ids = HashSet::new();
549        for stop in &config.building.stops {
550            if !seen_ids.insert(stop.id) {
551                return Err(SimError::InvalidConfig {
552                    field: "building.stops",
553                    reason: format!("duplicate {}", stop.id),
554                });
555            }
556            if !stop.position.is_finite() {
557                return Err(SimError::InvalidConfig {
558                    field: "building.stops.position",
559                    reason: format!("{} has non-finite position {}", stop.id, stop.position),
560                });
561            }
562        }
563
564        let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
565
566        if let Some(line_configs) = &config.building.lines {
567            // ── Explicit topology validation ──
568            Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
569        } else {
570            // ── Legacy flat elevator list validation ──
571            Self::validate_legacy_elevators(&config.elevators, &config.building)?;
572        }
573
574        if !config.simulation.ticks_per_second.is_finite()
575            || config.simulation.ticks_per_second <= 0.0
576        {
577            return Err(SimError::InvalidConfig {
578                field: "simulation.ticks_per_second",
579                reason: format!(
580                    "must be finite and positive, got {}",
581                    config.simulation.ticks_per_second
582                ),
583            });
584        }
585
586        Self::validate_passenger_spawning(&config.passenger_spawning)?;
587
588        Ok(())
589    }
590
591    /// Validate `PassengerSpawnConfig`. Without this, bad inputs reach
592    /// `PoissonSource::from_config` and panic later (NaN/negative weights
593    /// crash `random_range`/`Weight::from`; zero `mean_interval_ticks`
594    /// burst-fires every catch-up tick). (#272)
595    fn validate_passenger_spawning(
596        spawn: &crate::config::PassengerSpawnConfig,
597    ) -> Result<(), SimError> {
598        let (lo, hi) = spawn.weight_range;
599        if !lo.is_finite() || !hi.is_finite() {
600            return Err(SimError::InvalidConfig {
601                field: "passenger_spawning.weight_range",
602                reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
603            });
604        }
605        if lo < 0.0 || hi < 0.0 {
606            return Err(SimError::InvalidConfig {
607                field: "passenger_spawning.weight_range",
608                reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
609            });
610        }
611        if lo > hi {
612            return Err(SimError::InvalidConfig {
613                field: "passenger_spawning.weight_range",
614                reason: format!("min must be <= max, got ({lo}, {hi})"),
615            });
616        }
617        if spawn.mean_interval_ticks == 0 {
618            return Err(SimError::InvalidConfig {
619                field: "passenger_spawning.mean_interval_ticks",
620                reason: "must be > 0; mean_interval_ticks=0 burst-fires \
621                         every catch-up tick"
622                    .into(),
623            });
624        }
625        Ok(())
626    }
627
628    /// Validate the legacy flat elevator list.
629    fn validate_legacy_elevators(
630        elevators: &[crate::config::ElevatorConfig],
631        building: &crate::config::BuildingConfig,
632    ) -> Result<(), SimError> {
633        if elevators.is_empty() {
634            return Err(SimError::InvalidConfig {
635                field: "elevators",
636                reason: "at least one elevator is required".into(),
637            });
638        }
639
640        for elev in elevators {
641            Self::validate_elevator_config(elev, building)?;
642        }
643
644        Ok(())
645    }
646
647    /// Validate a single elevator config's physics and starting stop.
648    fn validate_elevator_config(
649        elev: &crate::config::ElevatorConfig,
650        building: &crate::config::BuildingConfig,
651    ) -> Result<(), SimError> {
652        validate_elevator_physics(
653            elev.max_speed.value(),
654            elev.acceleration.value(),
655            elev.deceleration.value(),
656            elev.weight_capacity.value(),
657            elev.inspection_speed_factor,
658            elev.door_transition_ticks,
659            elev.door_open_ticks,
660        )?;
661        if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
662            return Err(SimError::InvalidConfig {
663                field: "elevators.starting_stop",
664                reason: format!("references non-existent {}", elev.starting_stop),
665            });
666        }
667        Ok(())
668    }
669
670    /// Validate explicit line/group topology.
671    fn validate_explicit_topology(
672        line_configs: &[crate::config::LineConfig],
673        stop_ids: &HashSet<StopId>,
674        building: &crate::config::BuildingConfig,
675    ) -> Result<(), SimError> {
676        // No duplicate line IDs.
677        let mut seen_line_ids = HashSet::new();
678        for lc in line_configs {
679            if !seen_line_ids.insert(lc.id) {
680                return Err(SimError::InvalidConfig {
681                    field: "building.lines",
682                    reason: format!("duplicate line id {}", lc.id),
683                });
684            }
685        }
686
687        // Every line's serves must reference existing stops and be non-empty.
688        for lc in line_configs {
689            if lc.serves.is_empty() {
690                return Err(SimError::InvalidConfig {
691                    field: "building.lines.serves",
692                    reason: format!("line {} has no stops", lc.id),
693                });
694            }
695            for sid in &lc.serves {
696                if !stop_ids.contains(sid) {
697                    return Err(SimError::InvalidConfig {
698                        field: "building.lines.serves",
699                        reason: format!("line {} references non-existent {}", lc.id, sid),
700                    });
701                }
702            }
703            // Validate elevators within each line.
704            for ec in &lc.elevators {
705                Self::validate_elevator_config(ec, building)?;
706            }
707
708            // Validate max_cars is not exceeded.
709            if let Some(max) = lc.max_cars
710                && lc.elevators.len() > max
711            {
712                return Err(SimError::InvalidConfig {
713                    field: "building.lines.max_cars",
714                    reason: format!(
715                        "line {} has {} elevators but max_cars is {max}",
716                        lc.id,
717                        lc.elevators.len()
718                    ),
719                });
720            }
721        }
722
723        // At least one line with at least one elevator.
724        let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
725        if !has_elevator {
726            return Err(SimError::InvalidConfig {
727                field: "building.lines",
728                reason: "at least one line must have at least one elevator".into(),
729            });
730        }
731
732        // No orphaned stops: every stop must be served by at least one line.
733        let served: HashSet<StopId> = line_configs
734            .iter()
735            .flat_map(|lc| lc.serves.iter().copied())
736            .collect();
737        for sid in stop_ids {
738            if !served.contains(sid) {
739                return Err(SimError::InvalidConfig {
740                    field: "building.lines",
741                    reason: format!("orphaned stop {sid} not served by any line"),
742                });
743            }
744        }
745
746        // Validate groups if present.
747        if let Some(group_configs) = &building.groups {
748            let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
749
750            let mut seen_group_ids = HashSet::new();
751            for gc in group_configs {
752                if !seen_group_ids.insert(gc.id) {
753                    return Err(SimError::InvalidConfig {
754                        field: "building.groups",
755                        reason: format!("duplicate group id {}", gc.id),
756                    });
757                }
758                for &lid in &gc.lines {
759                    if !line_id_set.contains(&lid) {
760                        return Err(SimError::InvalidConfig {
761                            field: "building.groups.lines",
762                            reason: format!(
763                                "group {} references non-existent line id {}",
764                                gc.id, lid
765                            ),
766                        });
767                    }
768                }
769            }
770
771            // Check for orphaned lines (not referenced by any group).
772            let referenced_line_ids: HashSet<u32> = group_configs
773                .iter()
774                .flat_map(|g| g.lines.iter().copied())
775                .collect();
776            for lc in line_configs {
777                if !referenced_line_ids.contains(&lc.id) {
778                    return Err(SimError::InvalidConfig {
779                        field: "building.lines",
780                        reason: format!("line {} is not assigned to any group", lc.id),
781                    });
782                }
783            }
784        }
785
786        Ok(())
787    }
788
789    // ── Dispatch management ──────────────────────────────────────────
790
791    /// Replace the dispatch strategy for a group.
792    ///
793    /// The `id` parameter identifies the strategy for snapshot serialization.
794    /// Use `BuiltinStrategy::Custom("name")` for custom strategies.
795    pub fn set_dispatch(
796        &mut self,
797        group: GroupId,
798        strategy: Box<dyn DispatchStrategy>,
799        id: crate::dispatch::BuiltinStrategy,
800    ) {
801        self.dispatchers.insert(group, strategy);
802        self.strategy_ids.insert(group, id);
803    }
804
805    // ── Reposition management ─────────────────────────────────────────
806
807    /// Set the reposition strategy for a group.
808    ///
809    /// Enables the reposition phase for this group. Idle elevators will
810    /// be repositioned according to the strategy after each dispatch phase.
811    pub fn set_reposition(
812        &mut self,
813        group: GroupId,
814        strategy: Box<dyn RepositionStrategy>,
815        id: BuiltinReposition,
816    ) {
817        self.repositioners.insert(group, strategy);
818        self.reposition_ids.insert(group, id);
819    }
820
821    /// Remove the reposition strategy for a group, disabling repositioning.
822    pub fn remove_reposition(&mut self, group: GroupId) {
823        self.repositioners.remove(&group);
824        self.reposition_ids.remove(&group);
825    }
826
827    /// Get the reposition strategy identifier for a group.
828    #[must_use]
829    pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
830        self.reposition_ids.get(&group)
831    }
832
833    // ── Hooks ────────────────────────────────────────────────────────
834
835    /// Register a hook to run before a simulation phase.
836    ///
837    /// Hooks are called in registration order. The hook receives mutable
838    /// access to the world, allowing entity inspection or modification.
839    pub fn add_before_hook(
840        &mut self,
841        phase: Phase,
842        hook: impl Fn(&mut World) + Send + Sync + 'static,
843    ) {
844        self.hooks.add_before(phase, Box::new(hook));
845    }
846
847    /// Register a hook to run after a simulation phase.
848    ///
849    /// Hooks are called in registration order. The hook receives mutable
850    /// access to the world, allowing entity inspection or modification.
851    pub fn add_after_hook(
852        &mut self,
853        phase: Phase,
854        hook: impl Fn(&mut World) + Send + Sync + 'static,
855    ) {
856        self.hooks.add_after(phase, Box::new(hook));
857    }
858
859    /// Register a hook to run before a phase for a specific group.
860    pub fn add_before_group_hook(
861        &mut self,
862        phase: Phase,
863        group: GroupId,
864        hook: impl Fn(&mut World) + Send + Sync + 'static,
865    ) {
866        self.hooks.add_before_group(phase, group, Box::new(hook));
867    }
868
869    /// Register a hook to run after a phase for a specific group.
870    pub fn add_after_group_hook(
871        &mut self,
872        phase: Phase,
873        group: GroupId,
874        hook: impl Fn(&mut World) + Send + Sync + 'static,
875    ) {
876        self.hooks.add_after_group(phase, group, Box::new(hook));
877    }
878}