1use crate::components::Route;
8use crate::components::{Elevator, ElevatorPhase, Line, Position, Stop, Velocity};
9use crate::dispatch::{BuiltinStrategy, DispatchStrategy, ElevatorGroup, LineInfo};
10use crate::door::DoorState;
11use crate::entity::EntityId;
12use crate::error::SimError;
13use crate::events::Event;
14use crate::ids::GroupId;
15use crate::topology::TopologyGraph;
16
17use super::{ElevatorParams, LineParams, Simulation};
18
19impl Simulation {
20 fn mark_topo_dirty(&self) {
24 if let Ok(mut g) = self.topo_graph.lock() {
25 g.mark_dirty();
26 }
27 }
28
29 fn find_line(&self, line: EntityId) -> Result<(usize, usize), SimError> {
31 self.groups
32 .iter()
33 .enumerate()
34 .find_map(|(gi, g)| {
35 g.lines()
36 .iter()
37 .position(|li| li.entity() == line)
38 .map(|li_idx| (gi, li_idx))
39 })
40 .ok_or(SimError::LineNotFound(line))
41 }
42
43 pub fn add_stop(
53 &mut self,
54 name: String,
55 position: f64,
56 line: EntityId,
57 ) -> Result<EntityId, SimError> {
58 if !position.is_finite() {
59 return Err(SimError::InvalidConfig {
60 field: "position",
61 reason: format!(
62 "stop position must be finite (got {position}); NaN/±inf \
63 corrupt SortedStops ordering and find_stop_at_position lookup"
64 ),
65 });
66 }
67
68 let group_id = self
69 .world
70 .line(line)
71 .map(|l| l.group)
72 .ok_or(SimError::LineNotFound(line))?;
73
74 let (group_idx, line_idx) = self.find_line(line)?;
75
76 let eid = self.world.spawn();
77 self.world.set_stop(eid, Stop { name, position });
78 self.world.set_position(eid, Position { value: position });
79
80 self.groups[group_idx].lines_mut()[line_idx]
82 .serves_mut()
83 .push(eid);
84
85 self.groups[group_idx].push_stop(eid);
87
88 if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
90 let idx = sorted.0.partition_point(|&(p, _)| p < position);
91 sorted.0.insert(idx, (position, eid));
92 }
93
94 self.mark_topo_dirty();
95 self.events.emit(Event::StopAdded {
96 stop: eid,
97 line,
98 group: group_id,
99 tick: self.tick,
100 });
101 Ok(eid)
102 }
103
104 pub fn add_elevator(
110 &mut self,
111 params: &ElevatorParams,
112 line: EntityId,
113 starting_position: f64,
114 ) -> Result<EntityId, SimError> {
115 super::construction::validate_elevator_physics(
118 params.max_speed.value(),
119 params.acceleration.value(),
120 params.deceleration.value(),
121 params.weight_capacity.value(),
122 params.inspection_speed_factor,
123 params.door_transition_ticks,
124 params.door_open_ticks,
125 )?;
126 if !starting_position.is_finite() {
127 return Err(SimError::InvalidConfig {
128 field: "starting_position",
129 reason: format!(
130 "must be finite (got {starting_position}); NaN/±inf corrupt \
131 SortedStops ordering and find_stop_at_position lookup"
132 ),
133 });
134 }
135
136 let group_id = self
137 .world
138 .line(line)
139 .map(|l| l.group)
140 .ok_or(SimError::LineNotFound(line))?;
141
142 let (group_idx, line_idx) = self.find_line(line)?;
143
144 if let Some(max) = self.world.line(line).and_then(Line::max_cars) {
146 let current_count = self.groups[group_idx].lines()[line_idx].elevators().len();
147 if current_count >= max {
148 return Err(SimError::InvalidConfig {
149 field: "line.max_cars",
150 reason: format!("line already has {current_count} cars (max {max})"),
151 });
152 }
153 }
154
155 let eid = self.world.spawn();
156 self.world.set_position(
157 eid,
158 Position {
159 value: starting_position,
160 },
161 );
162 self.world.set_velocity(eid, Velocity { value: 0.0 });
163 self.world.set_elevator(
164 eid,
165 Elevator {
166 phase: ElevatorPhase::Idle,
167 door: DoorState::Closed,
168 max_speed: params.max_speed,
169 acceleration: params.acceleration,
170 deceleration: params.deceleration,
171 weight_capacity: params.weight_capacity,
172 current_load: crate::components::Weight::ZERO,
173 riders: Vec::new(),
174 target_stop: None,
175 door_transition_ticks: params.door_transition_ticks,
176 door_open_ticks: params.door_open_ticks,
177 line,
178 repositioning: false,
179 restricted_stops: params.restricted_stops.clone(),
180 inspection_speed_factor: params.inspection_speed_factor,
181 going_up: true,
182 going_down: true,
183 move_count: 0,
184 door_command_queue: Vec::new(),
185 manual_target_velocity: None,
186 },
187 );
188 self.world
189 .set_destination_queue(eid, crate::components::DestinationQueue::new());
190 self.groups[group_idx].lines_mut()[line_idx]
191 .elevators_mut()
192 .push(eid);
193 self.groups[group_idx].push_elevator(eid);
194
195 let line_name = self.world.line(line).map(|l| l.name.clone());
197 if let Some(name) = line_name
198 && let Some(tags) = self
199 .world
200 .resource_mut::<crate::tagged_metrics::MetricTags>()
201 {
202 tags.tag(eid, format!("line:{name}"));
203 }
204
205 self.mark_topo_dirty();
206 self.events.emit(Event::ElevatorAdded {
207 elevator: eid,
208 line,
209 group: group_id,
210 tick: self.tick,
211 });
212 Ok(eid)
213 }
214
215 pub fn add_line(&mut self, params: &LineParams) -> Result<EntityId, SimError> {
223 let group_id = params.group;
224 let group = self
225 .groups
226 .iter_mut()
227 .find(|g| g.id() == group_id)
228 .ok_or(SimError::GroupNotFound(group_id))?;
229
230 let line_tag = format!("line:{}", params.name);
231
232 let eid = self.world.spawn();
233 self.world.set_line(
234 eid,
235 Line {
236 name: params.name.clone(),
237 group: group_id,
238 orientation: params.orientation,
239 position: params.position,
240 min_position: params.min_position,
241 max_position: params.max_position,
242 max_cars: params.max_cars,
243 },
244 );
245
246 group
247 .lines_mut()
248 .push(LineInfo::new(eid, Vec::new(), Vec::new()));
249
250 if let Some(tags) = self
252 .world
253 .resource_mut::<crate::tagged_metrics::MetricTags>()
254 {
255 tags.tag(eid, line_tag);
256 }
257
258 self.mark_topo_dirty();
259 self.events.emit(Event::LineAdded {
260 line: eid,
261 group: group_id,
262 tick: self.tick,
263 });
264 Ok(eid)
265 }
266
267 pub fn remove_line(&mut self, line: EntityId) -> Result<(), SimError> {
277 let (group_idx, line_idx) = self.find_line(line)?;
278
279 let group_id = self.groups[group_idx].id();
280
281 let elevator_ids: Vec<EntityId> = self.groups[group_idx].lines()[line_idx]
283 .elevators()
284 .to_vec();
285
286 for eid in &elevator_ids {
288 let _ = self.disable(*eid);
290 }
291
292 self.groups[group_idx].lines_mut().remove(line_idx);
294
295 self.groups[group_idx].rebuild_caches();
297
298 self.world.remove_line(line);
300
301 self.mark_topo_dirty();
302 self.events.emit(Event::LineRemoved {
303 line,
304 group: group_id,
305 tick: self.tick,
306 });
307 Ok(())
308 }
309
310 pub fn remove_elevator(&mut self, elevator: EntityId) -> Result<(), SimError> {
319 let line = self
320 .world
321 .elevator(elevator)
322 .ok_or(SimError::EntityNotFound(elevator))?
323 .line();
324
325 let _ = self.disable(elevator);
327
328 let resolved_group: Option<GroupId> = match self.find_line(line) {
332 Ok((group_idx, line_idx)) => {
333 self.groups[group_idx].lines_mut()[line_idx]
334 .elevators_mut()
335 .retain(|&e| e != elevator);
336 self.groups[group_idx].rebuild_caches();
337
338 let gid = self.groups[group_idx].id();
339 if let Some(dispatcher) = self.dispatchers.get_mut(&gid) {
341 dispatcher.notify_removed(elevator);
342 }
343 Some(gid)
344 }
345 Err(_) => None,
346 };
347
348 if let Some(group_id) = resolved_group {
352 self.events.emit(Event::ElevatorRemoved {
353 elevator,
354 line,
355 group: group_id,
356 tick: self.tick,
357 });
358 }
359
360 self.world.despawn(elevator);
362
363 self.mark_topo_dirty();
364 Ok(())
365 }
366
367 pub fn remove_stop(&mut self, stop: EntityId) -> Result<(), SimError> {
376 if self.world.stop(stop).is_none() {
377 return Err(SimError::EntityNotFound(stop));
378 }
379
380 let residents: Vec<EntityId> = self
383 .rider_index
384 .residents_at(stop)
385 .iter()
386 .copied()
387 .collect();
388 if !residents.is_empty() {
389 self.events
390 .emit(Event::ResidentsAtRemovedStop { stop, residents });
391 }
392
393 let _ = self.disable(stop);
395
396 let elevator_ids: Vec<EntityId> =
400 self.world.iter_elevators().map(|(eid, _, _)| eid).collect();
401 for eid in elevator_ids {
402 if let Some(car) = self.world.elevator_mut(eid) {
403 if car.target_stop == Some(stop) {
404 car.target_stop = None;
405 }
406 car.restricted_stops.remove(&stop);
407 }
408 if let Some(q) = self.world.destination_queue_mut(eid) {
409 q.retain(|s| s != stop);
410 }
411 }
412
413 for group in &mut self.groups {
415 for line_info in group.lines_mut() {
416 line_info.serves_mut().retain(|&s| s != stop);
417 }
418 group.rebuild_caches();
419 }
420
421 if let Some(sorted) = self.world.resource_mut::<crate::world::SortedStops>() {
423 sorted.0.retain(|&(_, s)| s != stop);
424 }
425
426 self.stop_lookup.retain(|_, &mut eid| eid != stop);
428
429 self.events.emit(Event::StopRemoved {
430 stop,
431 tick: self.tick,
432 });
433
434 self.world.despawn(stop);
436
437 self.mark_topo_dirty();
438 Ok(())
439 }
440
441 pub fn add_group(
443 &mut self,
444 name: impl Into<String>,
445 dispatch: impl DispatchStrategy + 'static,
446 ) -> GroupId {
447 let next_id = self
448 .groups
449 .iter()
450 .map(|g| g.id().0)
451 .max()
452 .map_or(0, |m| m + 1);
453 let group_id = GroupId(next_id);
454
455 self.groups
456 .push(ElevatorGroup::new(group_id, name.into(), Vec::new()));
457
458 self.dispatchers.insert(group_id, Box::new(dispatch));
459 self.strategy_ids.insert(group_id, BuiltinStrategy::Scan);
460 self.mark_topo_dirty();
461 group_id
462 }
463
464 pub fn assign_line_to_group(
471 &mut self,
472 line: EntityId,
473 new_group: GroupId,
474 ) -> Result<GroupId, SimError> {
475 let (old_group_idx, line_idx) = self.find_line(line)?;
476
477 if !self.groups.iter().any(|g| g.id() == new_group) {
479 return Err(SimError::GroupNotFound(new_group));
480 }
481
482 let old_group_id = self.groups[old_group_idx].id();
483
484 let line_info = self.groups[old_group_idx].lines_mut().remove(line_idx);
486 self.groups[old_group_idx].rebuild_caches();
487
488 let new_group_idx = self
493 .groups
494 .iter()
495 .position(|g| g.id() == new_group)
496 .ok_or(SimError::GroupNotFound(new_group))?;
497 self.groups[new_group_idx].lines_mut().push(line_info);
498 self.groups[new_group_idx].rebuild_caches();
499
500 if let Some(line_comp) = self.world.line_mut(line) {
502 line_comp.group = new_group;
503 }
504
505 self.mark_topo_dirty();
506 self.events.emit(Event::LineReassigned {
507 line,
508 old_group: old_group_id,
509 new_group,
510 tick: self.tick,
511 });
512
513 Ok(old_group_id)
514 }
515
516 pub fn reassign_elevator_to_line(
527 &mut self,
528 elevator: EntityId,
529 new_line: EntityId,
530 ) -> Result<(), SimError> {
531 let old_line = self
532 .world
533 .elevator(elevator)
534 .ok_or(SimError::EntityNotFound(elevator))?
535 .line();
536
537 if old_line == new_line {
538 return Ok(());
539 }
540
541 let (old_group_idx, old_line_idx) = self.find_line(old_line)?;
543 let (new_group_idx, new_line_idx) = self.find_line(new_line)?;
544
545 if let Some(max) = self.world.line(new_line).and_then(Line::max_cars) {
547 let current_count = self.groups[new_group_idx].lines()[new_line_idx]
548 .elevators()
549 .len();
550 if current_count >= max {
551 return Err(SimError::InvalidConfig {
552 field: "line.max_cars",
553 reason: format!("target line already has {current_count} cars (max {max})"),
554 });
555 }
556 }
557
558 let old_group_id = self.groups[old_group_idx].id();
559 let new_group_id = self.groups[new_group_idx].id();
560
561 self.groups[old_group_idx].lines_mut()[old_line_idx]
562 .elevators_mut()
563 .retain(|&e| e != elevator);
564 self.groups[new_group_idx].lines_mut()[new_line_idx]
565 .elevators_mut()
566 .push(elevator);
567
568 if let Some(car) = self.world.elevator_mut(elevator) {
569 car.line = new_line;
570 }
571
572 self.groups[old_group_idx].rebuild_caches();
573 if new_group_idx != old_group_idx {
574 self.groups[new_group_idx].rebuild_caches();
575
576 if let Some(old_dispatcher) = self.dispatchers.get_mut(&old_group_id) {
580 old_dispatcher.notify_removed(elevator);
581 }
582 }
583
584 self.mark_topo_dirty();
585
586 let _ = new_group_id; self.events.emit(Event::ElevatorReassigned {
588 elevator,
589 old_line,
590 new_line,
591 tick: self.tick,
592 });
593
594 Ok(())
595 }
596
597 pub fn add_stop_to_line(&mut self, stop: EntityId, line: EntityId) -> Result<(), SimError> {
604 if self.world.stop(stop).is_none() {
606 return Err(SimError::EntityNotFound(stop));
607 }
608
609 let (group_idx, line_idx) = self.find_line(line)?;
610
611 let li = &mut self.groups[group_idx].lines_mut()[line_idx];
612 if !li.serves().contains(&stop) {
613 li.serves_mut().push(stop);
614 }
615
616 self.groups[group_idx].push_stop(stop);
617
618 self.mark_topo_dirty();
619 Ok(())
620 }
621
622 pub fn remove_stop_from_line(
628 &mut self,
629 stop: EntityId,
630 line: EntityId,
631 ) -> Result<(), SimError> {
632 let (group_idx, line_idx) = self.find_line(line)?;
633
634 self.groups[group_idx].lines_mut()[line_idx]
635 .serves_mut()
636 .retain(|&s| s != stop);
637
638 self.groups[group_idx].rebuild_caches();
640
641 self.mark_topo_dirty();
642 Ok(())
643 }
644
645 #[must_use]
649 pub fn all_lines(&self) -> Vec<EntityId> {
650 self.groups
651 .iter()
652 .flat_map(|g| g.lines().iter().map(LineInfo::entity))
653 .collect()
654 }
655
656 #[must_use]
658 pub fn line_count(&self) -> usize {
659 self.groups.iter().map(|g| g.lines().len()).sum()
660 }
661
662 #[must_use]
664 pub fn lines_in_group(&self, group: GroupId) -> Vec<EntityId> {
665 self.groups
666 .iter()
667 .find(|g| g.id() == group)
668 .map_or_else(Vec::new, |g| {
669 g.lines().iter().map(LineInfo::entity).collect()
670 })
671 }
672
673 #[must_use]
675 pub fn elevators_on_line(&self, line: EntityId) -> Vec<EntityId> {
676 self.groups
677 .iter()
678 .flat_map(ElevatorGroup::lines)
679 .find(|li| li.entity() == line)
680 .map_or_else(Vec::new, |li| li.elevators().to_vec())
681 }
682
683 #[must_use]
685 pub fn stops_served_by_line(&self, line: EntityId) -> Vec<EntityId> {
686 self.groups
687 .iter()
688 .flat_map(ElevatorGroup::lines)
689 .find(|li| li.entity() == line)
690 .map_or_else(Vec::new, |li| li.serves().to_vec())
691 }
692
693 #[must_use]
695 pub fn line_for_elevator(&self, elevator: EntityId) -> Option<EntityId> {
696 self.groups
697 .iter()
698 .flat_map(ElevatorGroup::lines)
699 .find(|li| li.elevators().contains(&elevator))
700 .map(LineInfo::entity)
701 }
702
703 pub fn iter_repositioning_elevators(&self) -> impl Iterator<Item = EntityId> + '_ {
705 self.world
706 .iter_elevators()
707 .filter_map(|(id, _pos, car)| if car.repositioning() { Some(id) } else { None })
708 }
709
710 #[must_use]
712 pub fn lines_serving_stop(&self, stop: EntityId) -> Vec<EntityId> {
713 self.groups
714 .iter()
715 .flat_map(ElevatorGroup::lines)
716 .filter(|li| li.serves().contains(&stop))
717 .map(LineInfo::entity)
718 .collect()
719 }
720
721 #[must_use]
723 pub fn groups_serving_stop(&self, stop: EntityId) -> Vec<GroupId> {
724 self.groups
725 .iter()
726 .filter(|g| g.stop_entities().contains(&stop))
727 .map(ElevatorGroup::id)
728 .collect()
729 }
730
731 fn ensure_graph_built(&self) {
735 if let Ok(mut graph) = self.topo_graph.lock()
736 && graph.is_dirty()
737 {
738 graph.rebuild(&self.groups);
739 }
740 }
741
742 pub fn reachable_stops_from(&self, stop: EntityId) -> Vec<EntityId> {
744 self.ensure_graph_built();
745 self.topo_graph
746 .lock()
747 .map_or_else(|_| Vec::new(), |g| g.reachable_stops_from(stop))
748 }
749
750 pub fn transfer_points(&self) -> Vec<EntityId> {
752 self.ensure_graph_built();
753 TopologyGraph::transfer_points(&self.groups)
754 }
755
756 pub fn shortest_route(&self, from: EntityId, to: EntityId) -> Option<Route> {
758 self.ensure_graph_built();
759 self.topo_graph
760 .lock()
761 .ok()
762 .and_then(|g| g.shortest_route(from, to))
763 }
764}