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 fn validate_explicit_topology(
909 line_configs: &[crate::config::LineConfig],
910 stop_ids: &HashSet<StopId>,
911 building: &crate::config::BuildingConfig,
912 ) -> Result<(), SimError> {
913 let mut seen_line_ids = HashSet::new();
915 for lc in line_configs {
916 if !seen_line_ids.insert(lc.id) {
917 return Err(SimError::InvalidConfig {
918 field: "building.lines",
919 reason: format!("duplicate line id {}", lc.id),
920 });
921 }
922 }
923
924 for lc in line_configs {
926 if lc.serves.is_empty() {
927 return Err(SimError::InvalidConfig {
928 field: "building.lines.serves",
929 reason: format!("line {} has no stops", lc.id),
930 });
931 }
932 for sid in &lc.serves {
933 if !stop_ids.contains(sid) {
934 return Err(SimError::InvalidConfig {
935 field: "building.lines.serves",
936 reason: format!("line {} references non-existent {}", lc.id, sid),
937 });
938 }
939 }
940 for ec in &lc.elevators {
942 Self::validate_elevator_config(ec, building)?;
943 }
944
945 if let Some(max) = lc.max_cars
947 && lc.elevators.len() > max
948 {
949 return Err(SimError::InvalidConfig {
950 field: "building.lines.max_cars",
951 reason: format!(
952 "line {} has {} elevators but max_cars is {max}",
953 lc.id,
954 lc.elevators.len()
955 ),
956 });
957 }
958
959 if let Some(kind) = lc.kind
963 && let Err((field, reason)) = kind.validate()
964 {
965 return Err(SimError::InvalidConfig { field, reason });
966 }
967 }
968
969 let has_elevator = line_configs.iter().any(|lc| !lc.elevators.is_empty());
971 if !has_elevator {
972 return Err(SimError::InvalidConfig {
973 field: "building.lines",
974 reason: "at least one line must have at least one elevator".into(),
975 });
976 }
977
978 let served: HashSet<StopId> = line_configs
980 .iter()
981 .flat_map(|lc| lc.serves.iter().copied())
982 .collect();
983 for sid in stop_ids {
984 if !served.contains(sid) {
985 return Err(SimError::InvalidConfig {
986 field: "building.lines",
987 reason: format!("orphaned stop {sid} not served by any line"),
988 });
989 }
990 }
991
992 if let Some(group_configs) = &building.groups {
994 let line_id_set: HashSet<u32> = line_configs.iter().map(|lc| lc.id).collect();
995
996 let mut seen_group_ids = HashSet::new();
997 for gc in group_configs {
998 if !seen_group_ids.insert(gc.id) {
999 return Err(SimError::InvalidConfig {
1000 field: "building.groups",
1001 reason: format!("duplicate group id {}", gc.id),
1002 });
1003 }
1004 for &lid in &gc.lines {
1005 if !line_id_set.contains(&lid) {
1006 return Err(SimError::InvalidConfig {
1007 field: "building.groups.lines",
1008 reason: format!(
1009 "group {} references non-existent line id {}",
1010 gc.id, lid
1011 ),
1012 });
1013 }
1014 }
1015 }
1016
1017 let referenced_line_ids: HashSet<u32> = group_configs
1019 .iter()
1020 .flat_map(|g| g.lines.iter().copied())
1021 .collect();
1022 for lc in line_configs {
1023 if !referenced_line_ids.contains(&lc.id) {
1024 return Err(SimError::InvalidConfig {
1025 field: "building.lines",
1026 reason: format!("line {} is not assigned to any group", lc.id),
1027 });
1028 }
1029 }
1030 }
1031
1032 Ok(())
1033 }
1034
1035 pub fn set_dispatch(
1051 &mut self,
1052 group: GroupId,
1053 strategy: Box<dyn DispatchStrategy>,
1054 id: crate::dispatch::BuiltinStrategy,
1055 ) {
1056 let resolved_id = strategy.builtin_id().unwrap_or(id);
1057 if let Some(mode) = canonical_hall_call_mode(&resolved_id)
1058 && let Some(g) = self.groups.iter_mut().find(|g| g.id() == group)
1059 {
1060 g.set_hall_call_mode(mode);
1061 }
1062 self.dispatcher_set.insert(group, strategy, resolved_id);
1063 }
1064
1065 pub fn set_reposition(
1096 &mut self,
1097 group: GroupId,
1098 strategy: Box<dyn RepositionStrategy>,
1099 id: BuiltinReposition,
1100 ) {
1101 let resolved_id = strategy.builtin_id().unwrap_or(id);
1102 let needed_window = strategy.min_arrival_log_window();
1103 self.repositioner_set.insert(group, strategy, resolved_id);
1104 if needed_window > 0
1110 && let Some(retention) = self
1111 .world
1112 .resource_mut::<crate::arrival_log::ArrivalLogRetention>()
1113 && needed_window > retention.0
1114 {
1115 retention.0 = needed_window;
1116 }
1117 }
1118
1119 pub fn remove_reposition(&mut self, group: GroupId) {
1130 self.repositioner_set.remove(group);
1131 }
1132
1133 #[must_use]
1135 pub fn reposition_id(&self, group: GroupId) -> Option<&BuiltinReposition> {
1136 self.repositioner_set.id_for(group)
1137 }
1138
1139 pub fn add_before_hook(
1146 &mut self,
1147 phase: Phase,
1148 hook: impl Fn(&mut World) + Send + Sync + 'static,
1149 ) {
1150 self.hooks.add_before(phase, Box::new(hook));
1151 }
1152
1153 pub fn add_after_hook(
1158 &mut self,
1159 phase: Phase,
1160 hook: impl Fn(&mut World) + Send + Sync + 'static,
1161 ) {
1162 self.hooks.add_after(phase, Box::new(hook));
1163 }
1164
1165 pub fn add_before_group_hook(
1167 &mut self,
1168 phase: Phase,
1169 group: GroupId,
1170 hook: impl Fn(&mut World) + Send + Sync + 'static,
1171 ) {
1172 self.hooks.add_before_group(phase, group, Box::new(hook));
1173 }
1174
1175 pub fn add_after_group_hook(
1177 &mut self,
1178 phase: Phase,
1179 group: GroupId,
1180 hook: impl Fn(&mut World) + Send + Sync + 'static,
1181 ) {
1182 self.hooks.add_after_group(phase, group, Box::new(hook));
1183 }
1184}