1use 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
40type TopologyResult = (
42 Vec<ElevatorGroup>,
43 BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
44 BTreeMap<GroupId, BuiltinStrategy>,
45);
46
47pub(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 }
70}
71
72fn sync_hall_call_modes(
81 groups: &mut [ElevatorGroup],
82 strategy_ids: &BTreeMap<GroupId, BuiltinStrategy>,
83) {
84 for group in groups.iter_mut() {
85 if let Some(strategy) = strategy_ids.get(&group.id())
86 && canonical_hall_call_mode(strategy)
87 == Some(crate::dispatch::HallCallMode::Destination)
88 {
89 group.set_hall_call_mode(crate::dispatch::HallCallMode::Destination);
90 }
91 }
92}
93
94#[allow(clippy::too_many_arguments)]
100pub(super) fn validate_elevator_physics(
101 max_speed: f64,
102 acceleration: f64,
103 deceleration: f64,
104 weight_capacity: f64,
105 inspection_speed_factor: f64,
106 door_transition_ticks: u32,
107 door_open_ticks: u32,
108 bypass_load_up_pct: Option<f64>,
109 bypass_load_down_pct: Option<f64>,
110) -> Result<(), SimError> {
111 if !max_speed.is_finite() || max_speed <= 0.0 {
112 return Err(SimError::InvalidConfig {
113 field: "elevators.max_speed",
114 reason: format!("must be finite and positive, got {max_speed}"),
115 });
116 }
117 if !acceleration.is_finite() || acceleration <= 0.0 {
118 return Err(SimError::InvalidConfig {
119 field: "elevators.acceleration",
120 reason: format!("must be finite and positive, got {acceleration}"),
121 });
122 }
123 if !deceleration.is_finite() || deceleration <= 0.0 {
124 return Err(SimError::InvalidConfig {
125 field: "elevators.deceleration",
126 reason: format!("must be finite and positive, got {deceleration}"),
127 });
128 }
129 if !weight_capacity.is_finite() || weight_capacity <= 0.0 {
130 return Err(SimError::InvalidConfig {
131 field: "elevators.weight_capacity",
132 reason: format!("must be finite and positive, got {weight_capacity}"),
133 });
134 }
135 if !inspection_speed_factor.is_finite() || inspection_speed_factor <= 0.0 {
136 return Err(SimError::InvalidConfig {
137 field: "elevators.inspection_speed_factor",
138 reason: format!("must be finite and positive, got {inspection_speed_factor}"),
139 });
140 }
141 if door_transition_ticks == 0 {
142 return Err(SimError::InvalidConfig {
143 field: "elevators.door_transition_ticks",
144 reason: "must be > 0".into(),
145 });
146 }
147 if door_open_ticks == 0 {
148 return Err(SimError::InvalidConfig {
149 field: "elevators.door_open_ticks",
150 reason: "must be > 0".into(),
151 });
152 }
153 validate_bypass_pct("elevators.bypass_load_up_pct", bypass_load_up_pct)?;
154 validate_bypass_pct("elevators.bypass_load_down_pct", bypass_load_down_pct)?;
155 Ok(())
156}
157
158fn validate_bypass_pct(field: &'static str, pct: Option<f64>) -> Result<(), SimError> {
163 let Some(pct) = pct else {
164 return Ok(());
165 };
166 if !pct.is_finite() || pct <= 0.0 || pct > 1.0 {
167 return Err(SimError::InvalidConfig {
168 field,
169 reason: format!("must be finite in (0.0, 1.0] when set, got {pct}"),
170 });
171 }
172 Ok(())
173}
174
175impl Simulation {
176 pub fn new(
187 config: &SimConfig,
188 dispatch: impl DispatchStrategy + 'static,
189 ) -> Result<Self, SimError> {
190 let mut dispatchers = BTreeMap::new();
191 dispatchers.insert(GroupId(0), Box::new(dispatch) as Box<dyn DispatchStrategy>);
192 Self::new_with_hooks(config, dispatchers, PhaseHooks::default())
193 }
194
195 #[allow(clippy::too_many_lines)]
199 pub(crate) fn new_with_hooks(
200 config: &SimConfig,
201 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
202 hooks: PhaseHooks,
203 ) -> Result<Self, SimError> {
204 Self::validate_config(config)?;
205
206 let mut world = World::new();
207
208 let mut stop_lookup: HashMap<StopId, EntityId> = HashMap::new();
210 for sc in &config.building.stops {
211 let eid = world.spawn();
212 world.set_stop(
213 eid,
214 Stop {
215 name: sc.name.clone(),
216 position: sc.position,
217 },
218 );
219 world.set_position(eid, Position { value: sc.position });
220 stop_lookup.insert(sc.id, eid);
221 }
222
223 let mut sorted: Vec<(f64, EntityId)> = world
225 .iter_stops()
226 .map(|(eid, stop)| (stop.position, eid))
227 .collect();
228 sorted.sort_by(|a, b| a.0.total_cmp(&b.0));
229 world.insert_resource(crate::world::SortedStops(sorted));
230
231 world.insert_resource(crate::arrival_log::ArrivalLog::default());
241 world.insert_resource(crate::arrival_log::DestinationLog::default());
242 world.insert_resource(crate::arrival_log::CurrentTick::default());
243 world.insert_resource(crate::arrival_log::ArrivalLogRetention::default());
244 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
248 world.insert_resource(crate::dispatch::reposition::RepositionCooldowns::default());
254 world.insert_resource(crate::time::TickRate(config.simulation.ticks_per_second));
260
261 let (mut groups, dispatchers, strategy_ids) =
262 if let Some(line_configs) = &config.building.lines {
263 Self::build_explicit_topology(
264 &mut world,
265 config,
266 line_configs,
267 &stop_lookup,
268 builder_dispatchers,
269 )
270 } else {
271 Self::build_legacy_topology(&mut world, config, &stop_lookup, builder_dispatchers)
272 };
273 sync_hall_call_modes(&mut groups, &strategy_ids);
274
275 let dt = 1.0 / config.simulation.ticks_per_second;
276
277 world.insert_resource(crate::tagged_metrics::MetricTags::default());
278
279 world.register_ext::<crate::dispatch::destination::AssignedCar>(
288 crate::dispatch::destination::ASSIGNED_CAR_KEY,
289 );
290
291 let line_tag_info: Vec<(EntityId, String, Vec<EntityId>)> = groups
294 .iter()
295 .flat_map(|group| {
296 group.lines().iter().filter_map(|li| {
297 let line_comp = world.line(li.entity())?;
298 Some((li.entity(), line_comp.name.clone(), li.elevators().to_vec()))
299 })
300 })
301 .collect();
302
303 if let Some(tags) = world.resource_mut::<crate::tagged_metrics::MetricTags>() {
305 for (line_eid, name, elevators) in &line_tag_info {
306 let tag = format!("line:{name}");
307 tags.tag(*line_eid, tag.clone());
308 for elev_eid in elevators {
309 tags.tag(*elev_eid, tag.clone());
310 }
311 }
312 }
313
314 let mut repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>> = BTreeMap::new();
316 let mut reposition_ids: BTreeMap<GroupId, BuiltinReposition> = BTreeMap::new();
317 if let Some(group_configs) = &config.building.groups {
318 for gc in group_configs {
319 if let Some(ref repo_id) = gc.reposition
320 && let Some(strategy) = repo_id.instantiate()
321 {
322 let gid = GroupId(gc.id);
323 repositioners.insert(gid, strategy);
324 reposition_ids.insert(gid, repo_id.clone());
325 }
326 }
327 }
328
329 Ok(Self {
330 world,
331 events: EventBus::default(),
332 pending_output: Vec::new(),
333 tick: 0,
334 dt,
335 groups,
336 stop_lookup,
337 dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
338 repositioner_set: super::RepositionerSet::from_parts(repositioners, reposition_ids),
339 metrics: Metrics::new(),
340 time: TimeAdapter::new(config.simulation.ticks_per_second),
341 hooks,
342 elevator_ids_buf: Vec::new(),
343 reposition_buf: Vec::new(),
344 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
345 topo_graph: Mutex::new(TopologyGraph::new()),
346 rider_index: RiderIndex::default(),
347 tick_in_progress: false,
348 })
349 }
350
351 fn spawn_elevator_entity(
357 world: &mut World,
358 ec: &crate::config::ElevatorConfig,
359 line: EntityId,
360 stop_lookup: &HashMap<StopId, EntityId>,
361 start_pos_lookup: &[crate::stop::StopConfig],
362 ) -> EntityId {
363 let eid = world.spawn();
364 let start_pos = start_pos_lookup
365 .iter()
366 .find(|s| s.id == ec.starting_stop)
367 .map_or(0.0, |s| s.position);
368 world.set_position(eid, Position { value: start_pos });
369 world.set_velocity(eid, Velocity { value: 0.0 });
370 let restricted: HashSet<EntityId> = ec
371 .restricted_stops
372 .iter()
373 .filter_map(|sid| stop_lookup.get(sid).copied())
374 .collect();
375 world.set_elevator(
376 eid,
377 Elevator {
378 phase: ElevatorPhase::Idle,
379 door: DoorState::Closed,
380 max_speed: ec.max_speed,
381 acceleration: ec.acceleration,
382 deceleration: ec.deceleration,
383 weight_capacity: ec.weight_capacity,
384 current_load: crate::components::Weight::ZERO,
385 riders: Vec::new(),
386 target_stop: None,
387 door_transition_ticks: ec.door_transition_ticks,
388 door_open_ticks: ec.door_open_ticks,
389 line,
390 repositioning: false,
391 restricted_stops: restricted,
392 inspection_speed_factor: ec.inspection_speed_factor,
393 going_up: true,
394 going_down: true,
395 move_count: 0,
396 door_command_queue: Vec::new(),
397 manual_target_velocity: None,
398 bypass_load_up_pct: ec.bypass_load_up_pct,
399 bypass_load_down_pct: ec.bypass_load_down_pct,
400 home_stop: None,
401 },
402 );
403 #[cfg(feature = "energy")]
404 if let Some(ref profile) = ec.energy_profile {
405 world.set_energy_profile(eid, profile.clone());
406 world.set_energy_metrics(eid, crate::energy::EnergyMetrics::default());
407 }
408 if let Some(mode) = ec.service_mode {
409 world.set_service_mode(eid, mode);
410 }
411 world.set_destination_queue(eid, crate::components::DestinationQueue::new());
412 eid
413 }
414
415 fn build_legacy_topology(
417 world: &mut World,
418 config: &SimConfig,
419 stop_lookup: &HashMap<StopId, EntityId>,
420 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
421 ) -> TopologyResult {
422 let all_stop_entities: Vec<EntityId> = config
428 .building
429 .stops
430 .iter()
431 .filter_map(|s| stop_lookup.get(&s.id).copied())
432 .collect();
433 let stop_positions: Vec<f64> = config.building.stops.iter().map(|s| s.position).collect();
434 let min_pos = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
435 let max_pos = stop_positions
436 .iter()
437 .copied()
438 .fold(f64::NEG_INFINITY, f64::max);
439
440 let default_line_eid = world.spawn();
441 world.set_line(
442 default_line_eid,
443 Line {
444 name: "Default".into(),
445 group: GroupId(0),
446 orientation: Orientation::Vertical,
447 position: None,
448 kind: LineKind::Linear {
449 min: min_pos,
450 max: max_pos,
451 },
452 max_cars: None,
453 },
454 );
455
456 let mut elevator_entities = Vec::new();
457 for ec in &config.elevators {
458 let eid = Self::spawn_elevator_entity(
459 world,
460 ec,
461 default_line_eid,
462 stop_lookup,
463 &config.building.stops,
464 );
465 elevator_entities.push(eid);
466 }
467
468 let default_line_info =
469 LineInfo::new(default_line_eid, elevator_entities, all_stop_entities);
470
471 let group = ElevatorGroup::new(GroupId(0), "Default".into(), vec![default_line_info]);
472
473 let mut dispatchers = BTreeMap::new();
477 let mut strategy_ids = BTreeMap::new();
478 let user_dispatcher = builder_dispatchers
479 .into_iter()
480 .find_map(|(gid, d)| if gid == GroupId(0) { Some(d) } else { None });
481 let inferred_id = user_dispatcher
486 .as_ref()
487 .and_then(|d| d.builtin_id())
488 .unwrap_or(BuiltinStrategy::Scan);
489 if let Some(d) = user_dispatcher {
490 dispatchers.insert(GroupId(0), d);
491 } else {
492 dispatchers.insert(
493 GroupId(0),
494 Box::new(crate::dispatch::scan::ScanDispatch::new()) as Box<dyn DispatchStrategy>,
495 );
496 }
497 strategy_ids.insert(GroupId(0), inferred_id);
498
499 (vec![group], dispatchers, strategy_ids)
500 }
501
502 #[allow(clippy::too_many_lines)]
504 fn build_explicit_topology(
505 world: &mut World,
506 config: &SimConfig,
507 line_configs: &[crate::config::LineConfig],
508 stop_lookup: &HashMap<StopId, EntityId>,
509 builder_dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
510 ) -> TopologyResult {
511 let mut line_map: BTreeMap<u32, (EntityId, LineInfo)> = BTreeMap::new();
517
518 for lc in line_configs {
519 let served_entities: Vec<EntityId> = lc
521 .serves
522 .iter()
523 .filter_map(|sid| stop_lookup.get(sid).copied())
524 .collect();
525
526 let stop_positions: Vec<f64> = lc
528 .serves
529 .iter()
530 .filter_map(|sid| {
531 config
532 .building
533 .stops
534 .iter()
535 .find(|s| s.id == *sid)
536 .map(|s| s.position)
537 })
538 .collect();
539 let auto_min = stop_positions.iter().copied().fold(f64::INFINITY, f64::min);
540 let auto_max = stop_positions
541 .iter()
542 .copied()
543 .fold(f64::NEG_INFINITY, f64::max);
544
545 let min_pos = lc.min_position.unwrap_or(auto_min);
546 let max_pos = lc.max_position.unwrap_or(auto_max);
547
548 let line_eid = world.spawn();
549 world.set_line(
553 line_eid,
554 Line {
555 name: lc.name.clone(),
556 group: GroupId(0),
557 orientation: lc.orientation,
558 position: lc.position,
559 kind: lc.kind.unwrap_or(LineKind::Linear {
560 min: min_pos,
561 max: max_pos,
562 }),
563 max_cars: lc.max_cars,
564 },
565 );
566
567 let mut elevator_entities = Vec::new();
569 for ec in &lc.elevators {
570 let eid = Self::spawn_elevator_entity(
571 world,
572 ec,
573 line_eid,
574 stop_lookup,
575 &config.building.stops,
576 );
577 elevator_entities.push(eid);
578 }
579
580 let line_info = LineInfo::new(line_eid, elevator_entities, served_entities);
581 line_map.insert(lc.id, (line_eid, line_info));
582 }
583
584 let group_configs = config.building.groups.as_deref();
586 let mut groups = Vec::new();
587 let mut dispatchers = BTreeMap::new();
588 let mut strategy_ids = BTreeMap::new();
589
590 if let Some(gcs) = group_configs {
591 for gc in gcs {
592 let group_id = GroupId(gc.id);
593
594 let mut group_lines = Vec::new();
595
596 for &lid in &gc.lines {
597 if let Some((line_eid, li)) = line_map.get(&lid) {
598 if let Some(line_comp) = world.line_mut(*line_eid) {
600 line_comp.group = group_id;
601 }
602 group_lines.push(li.clone());
603 }
604 }
605
606 let mut group = ElevatorGroup::new(group_id, gc.name.clone(), group_lines);
607 if let Some(mode) = gc.hall_call_mode {
608 group.set_hall_call_mode(mode);
609 }
610 if let Some(ticks) = gc.ack_latency_ticks {
611 group.set_ack_latency_ticks(ticks);
612 }
613 groups.push(group);
614
615 let dispatch: Box<dyn DispatchStrategy> = gc
617 .dispatch
618 .instantiate()
619 .unwrap_or_else(|| Box::new(crate::dispatch::scan::ScanDispatch::new()));
620 dispatchers.insert(group_id, dispatch);
621 strategy_ids.insert(group_id, gc.dispatch.clone());
622 }
623 } else {
624 let group_id = GroupId(0);
626 let mut group_lines = Vec::new();
627
628 for (line_eid, li) in line_map.values() {
629 if let Some(line_comp) = world.line_mut(*line_eid) {
630 line_comp.group = group_id;
631 }
632 group_lines.push(li.clone());
633 }
634
635 let group = ElevatorGroup::new(group_id, "Default".into(), group_lines);
636 groups.push(group);
637
638 let dispatch: Box<dyn DispatchStrategy> =
639 Box::new(crate::dispatch::scan::ScanDispatch::new());
640 dispatchers.insert(group_id, dispatch);
641 strategy_ids.insert(group_id, BuiltinStrategy::Scan);
642 }
643
644 for (gid, d) in builder_dispatchers {
649 let inferred_id = d.builtin_id();
650 dispatchers.insert(gid, d);
651 match inferred_id {
652 Some(id) => {
653 strategy_ids.insert(gid, id);
654 }
655 None => {
656 strategy_ids
657 .entry(gid)
658 .or_insert_with(|| BuiltinStrategy::Custom("user-supplied".into()));
659 }
660 }
661 }
662
663 (groups, dispatchers, strategy_ids)
664 }
665
666 #[allow(clippy::too_many_arguments)]
668 pub(crate) fn from_parts(
669 world: World,
670 tick: u64,
671 dt: f64,
672 groups: Vec<ElevatorGroup>,
673 stop_lookup: HashMap<StopId, EntityId>,
674 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
675 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
676 metrics: Metrics,
677 ticks_per_second: f64,
678 ) -> Self {
679 let mut rider_index = RiderIndex::default();
680 rider_index.rebuild(&world);
681 let mut world = world;
687 world.insert_resource(crate::time::TickRate(ticks_per_second));
688 if world
689 .resource::<crate::traffic_detector::TrafficDetector>()
690 .is_none()
691 {
692 world.insert_resource(crate::traffic_detector::TrafficDetector::default());
693 }
694 if world
699 .resource::<crate::arrival_log::DestinationLog>()
700 .is_none()
701 {
702 world.insert_resource(crate::arrival_log::DestinationLog::default());
703 }
704 world.register_ext::<crate::dispatch::destination::AssignedCar>(
719 crate::dispatch::destination::ASSIGNED_CAR_KEY,
720 );
721 if let Some(pending) = world.resource::<crate::snapshot::PendingExtensions>() {
722 let data = pending.0.clone();
723 world.deserialize_extensions(&data);
724 }
725 Self {
726 world,
727 events: EventBus::default(),
728 pending_output: Vec::new(),
729 tick,
730 dt,
731 groups,
732 stop_lookup,
733 dispatcher_set: super::DispatcherSet::from_parts(dispatchers, strategy_ids),
734 repositioner_set: super::RepositionerSet::new(),
735 metrics,
736 time: TimeAdapter::new(ticks_per_second),
737 hooks: PhaseHooks::default(),
738 elevator_ids_buf: Vec::new(),
739 reposition_buf: Vec::new(),
740 dispatch_scratch: crate::dispatch::DispatchScratch::default(),
741 topo_graph: Mutex::new(TopologyGraph::new()),
742 rider_index,
743 tick_in_progress: false,
744 }
745 }
746
747 pub(crate) fn validate_config(config: &SimConfig) -> Result<(), SimError> {
749 if config.schema_version > crate::config::CURRENT_CONFIG_SCHEMA_VERSION {
756 return Err(SimError::InvalidConfig {
757 field: "schema_version",
758 reason: format!(
759 "config schema_version={} is newer than this build's CURRENT_CONFIG_SCHEMA_VERSION={}; upgrade elevator-core or downgrade the config",
760 config.schema_version,
761 crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
762 ),
763 });
764 }
765 if config.schema_version == 0 {
766 return Err(SimError::InvalidConfig {
767 field: "schema_version",
768 reason: format!(
769 "config schema_version=0 (pre-versioning legacy file) — set schema_version: {} explicitly after auditing field defaults; see docs/src/config-versioning.md",
770 crate::config::CURRENT_CONFIG_SCHEMA_VERSION,
771 ),
772 });
773 }
774
775 if config.building.stops.is_empty() {
776 return Err(SimError::InvalidConfig {
777 field: "building.stops",
778 reason: "at least one stop is required".into(),
779 });
780 }
781
782 let mut seen_ids = HashSet::new();
784 for stop in &config.building.stops {
785 if !seen_ids.insert(stop.id) {
786 return Err(SimError::InvalidConfig {
787 field: "building.stops",
788 reason: format!("duplicate {}", stop.id),
789 });
790 }
791 if !stop.position.is_finite() {
792 return Err(SimError::InvalidConfig {
793 field: "building.stops.position",
794 reason: format!("{} has non-finite position {}", stop.id, stop.position),
795 });
796 }
797 }
798
799 let stop_ids: HashSet<StopId> = config.building.stops.iter().map(|s| s.id).collect();
800
801 if let Some(line_configs) = &config.building.lines {
802 Self::validate_explicit_topology(line_configs, &stop_ids, &config.building)?;
804 } else {
805 Self::validate_legacy_elevators(&config.elevators, &config.building)?;
807 }
808
809 if !config.simulation.ticks_per_second.is_finite()
810 || config.simulation.ticks_per_second <= 0.0
811 {
812 return Err(SimError::InvalidConfig {
813 field: "simulation.ticks_per_second",
814 reason: format!(
815 "must be finite and positive, got {}",
816 config.simulation.ticks_per_second
817 ),
818 });
819 }
820
821 Self::validate_passenger_spawning(&config.passenger_spawning)?;
822
823 Ok(())
824 }
825
826 fn validate_passenger_spawning(
831 spawn: &crate::config::PassengerSpawnConfig,
832 ) -> Result<(), SimError> {
833 let (lo, hi) = spawn.weight_range;
834 if !lo.is_finite() || !hi.is_finite() {
835 return Err(SimError::InvalidConfig {
836 field: "passenger_spawning.weight_range",
837 reason: format!("both endpoints must be finite, got ({lo}, {hi})"),
838 });
839 }
840 if lo < 0.0 || hi < 0.0 {
841 return Err(SimError::InvalidConfig {
842 field: "passenger_spawning.weight_range",
843 reason: format!("both endpoints must be non-negative, got ({lo}, {hi})"),
844 });
845 }
846 if lo > hi {
847 return Err(SimError::InvalidConfig {
848 field: "passenger_spawning.weight_range",
849 reason: format!("min must be <= max, got ({lo}, {hi})"),
850 });
851 }
852 if spawn.mean_interval_ticks == 0 {
853 return Err(SimError::InvalidConfig {
854 field: "passenger_spawning.mean_interval_ticks",
855 reason: "must be > 0; mean_interval_ticks=0 burst-fires \
856 every catch-up tick"
857 .into(),
858 });
859 }
860 Ok(())
861 }
862
863 fn validate_legacy_elevators(
865 elevators: &[crate::config::ElevatorConfig],
866 building: &crate::config::BuildingConfig,
867 ) -> Result<(), SimError> {
868 if elevators.is_empty() {
869 return Err(SimError::InvalidConfig {
870 field: "elevators",
871 reason: "at least one elevator is required".into(),
872 });
873 }
874
875 for elev in elevators {
876 Self::validate_elevator_config(elev, building)?;
877 }
878
879 Ok(())
880 }
881
882 fn validate_elevator_config(
884 elev: &crate::config::ElevatorConfig,
885 building: &crate::config::BuildingConfig,
886 ) -> Result<(), SimError> {
887 validate_elevator_physics(
888 elev.max_speed.value(),
889 elev.acceleration.value(),
890 elev.deceleration.value(),
891 elev.weight_capacity.value(),
892 elev.inspection_speed_factor,
893 elev.door_transition_ticks,
894 elev.door_open_ticks,
895 elev.bypass_load_up_pct,
896 elev.bypass_load_down_pct,
897 )?;
898 if !building.stops.iter().any(|s| s.id == elev.starting_stop) {
899 return Err(SimError::InvalidConfig {
900 field: "elevators.starting_stop",
901 reason: format!("references non-existent {}", elev.starting_stop),
902 });
903 }
904 Ok(())
905 }
906
907 #[allow(
909 clippy::too_many_lines,
910 reason = "validation reads top-to-bottom; extracting helpers would scatter related rejections across files"
911 )]
912 fn validate_explicit_topology(
913 line_configs: &[crate::config::LineConfig],
914 stop_ids: &HashSet<StopId>,
915 building: &crate::config::BuildingConfig,
916 ) -> Result<(), SimError> {
917 let mut seen_line_ids = HashSet::new();
919 for lc in line_configs {
920 if !seen_line_ids.insert(lc.id) {
921 return Err(SimError::InvalidConfig {
922 field: "building.lines",
923 reason: format!("duplicate line id {}", lc.id),
924 });
925 }
926 }
927
928 for lc in line_configs {
930 if lc.serves.is_empty() {
931 return Err(SimError::InvalidConfig {
932 field: "building.lines.serves",
933 reason: format!("line {} has no stops", lc.id),
934 });
935 }
936 for sid in &lc.serves {
937 if !stop_ids.contains(sid) {
938 return Err(SimError::InvalidConfig {
939 field: "building.lines.serves",
940 reason: format!("line {} references non-existent {}", lc.id, sid),
941 });
942 }
943 }
944 for ec in &lc.elevators {
946 Self::validate_elevator_config(ec, building)?;
947 }
948
949 if let Some(max) = lc.max_cars
951 && lc.elevators.len() > max
952 {
953 return Err(SimError::InvalidConfig {
954 field: "building.lines.max_cars",
955 reason: format!(
956 "line {} has {} elevators but max_cars is {max}",
957 lc.id,
958 lc.elevators.len()
959 ),
960 });
961 }
962
963 if let Some(kind) = lc.kind
967 && let Err((field, reason)) = kind.validate()
968 {
969 return Err(SimError::InvalidConfig { field, reason });
970 }
971
972 #[cfg(feature = "loop_lines")]
979 if let Some(crate::components::LineKind::Loop {
980 circumference,
981 min_headway,
982 }) = lc.kind
983 {
984 let car_count = lc
985 .max_cars
986 .map_or_else(|| lc.elevators.len(), |max| max.max(lc.elevators.len()));
987 if car_count > 0 {
988 #[allow(
989 clippy::cast_precision_loss,
990 reason = "car_count is bounded by usize and the comparison is against a finite f64"
991 )]
992 let required = (car_count as f64) * min_headway;
993 if required > circumference {
994 return Err(SimError::InvalidConfig {
995 field: "building.lines.kind",
996 reason: format!(
997 "loop line {}: {car_count} cars × min_headway {min_headway} = {required} \
998 exceeds circumference {circumference}",
999 lc.id,
1000 ),
1001 });
1002 }
1003 }
1004 }
1005 }
1006
1007 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
1009 if !has_elevator {
1010 return Err(SimError::InvalidConfig {
1011 field: "building.lines",
1012 reason: "at least one line must have at least one elevator".into(),
1013 });
1014 }
1015
1016 let served: HashSet<StopId> = line_configs
1018 .iter()
1019 .flat_map(|lc| lc.serves.iter().copied())
1020 .collect();
1021 for sid in stop_ids {
1022 if !served.contains(sid) {
1023 return Err(SimError::InvalidConfig {
1024 field: "building.lines",
1025 reason: format!("orphaned stop {sid} not served by any line"),
1026 });
1027 }
1028 }
1029
1030 if let Some(group_configs) = &building.groups {
1032 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
1033
1034 let mut seen_group_ids = HashSet::new();
1035 for gc in group_configs {
1036 if !seen_group_ids.insert(gc.id) {
1037 return Err(SimError::InvalidConfig {
1038 field: "building.groups",
1039 reason: format!("duplicate group id {}", gc.id),
1040 });
1041 }
1042 for &lid in &gc.lines {
1043 if !line_id_set.contains(&lid) {
1044 return Err(SimError::InvalidConfig {
1045 field: "building.groups.lines",
1046 reason: format!(
1047 "group {} references non-existent line id {}",
1048 gc.id, lid
1049 ),
1050 });
1051 }
1052 }
1053 }
1054
1055 let referenced_line_ids: HashSet<u32> = group_configs
1057 .iter()
1058 .flat_map(|g| g.lines.iter().copied())
1059 .collect();
1060 for lc in line_configs {
1061 if !referenced_line_ids.contains(&lc.id) {
1062 return Err(SimError::InvalidConfig {
1063 field: "building.lines",
1064 reason: format!("line {} is not assigned to any group", lc.id),
1065 });
1066 }
1067 }
1068 }
1069
1070 Ok(())
1071 }
1072
1073 pub fn set_dispatch(
1089 &mut self,
1090 group: GroupId,
1091 strategy: Box<dyn DispatchStrategy>,
1092 id: crate::dispatch::BuiltinStrategy,
1093 ) {
1094 let resolved_id = strategy.builtin_id().unwrap_or(id);
1095 if let Some(mode) = canonical_hall_call_mode(&resolved_id)
1096 && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1097 {
1098 g.set_hall_call_mode(mode);
1099 }
1100 self.dispatcher_set.insert(group, strategy, resolved_id);
1101 }
1102
1103 pub fn set_reposition(
1134 &mut self,
1135 group: GroupId,
1136 strategy: Box<dyn RepositionStrategy>,
1137 id: BuiltinReposition,
1138 ) {
1139 let resolved_id = strategy.builtin_id().unwrap_or(id);
1140 let needed_window = strategy.min_arrival_log_window();
1141 self.repositioner_set.insert(group, strategy, resolved_id);
1142 if needed_window > 0
1148 && let Some(retention) = self
1149 .world
1150 .resource_mut::<crate::arrival_log::ArrivalLogRetention>()
1151 && needed_window > retention.0
1152 {
1153 retention.0 = needed_window;
1154 }
1155 }
1156
1157 pub fn remove_reposition(&mut self, group: GroupId) {
1168 self.repositioner_set.remove(group);
1169 }
1170
1171 #[must_use]
1173 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1174 self.repositioner_set.id_for(group)
1175 }
1176
1177 pub fn add_before_hook(
1184 &mut self,
1185 phase: Phase,
1186 hook: impl Fn(&mut World) + Send + Sync + 'static,
1187 ) {
1188 self.hooks.add_before(phase, Box::new(hook));
1189 }
1190
1191 pub fn add_after_hook(
1196 &mut self,
1197 phase: Phase,
1198 hook: impl Fn(&mut World) + Send + Sync + 'static,
1199 ) {
1200 self.hooks.add_after(phase, Box::new(hook));
1201 }
1202
1203 pub fn add_before_group_hook(
1205 &mut self,
1206 phase: Phase,
1207 group: GroupId,
1208 hook: impl Fn(&mut World) + Send + Sync + 'static,
1209 ) {
1210 self.hooks.add_before_group(phase, group, Box::new(hook));
1211 }
1212
1213 pub fn add_after_group_hook(
1215 &mut self,
1216 phase: Phase,
1217 group: GroupId,
1218 hook: impl Fn(&mut World) + Send + Sync + 'static,
1219 ) {
1220 self.hooks.add_after_group(phase, group, Box::new(hook));
1221 }
1222}