elevator_core/sim/lifecycle.rs
1//! Rider lifecycle, population queries, and entity state control.
2//!
3//! Covers reroute/settle/despawn/disable/enable, population queries,
4//! per-entity metrics, service mode, and route invalidation. Split out
5//! from `sim.rs` to keep each concern readable.
6
7use std::collections::HashSet;
8
9use crate::components::{Elevator, ElevatorPhase, RiderPhase, RiderPhaseKind, Route};
10use crate::entity::{ElevatorId, EntityId, RiderId};
11use crate::error::SimError;
12use crate::events::Event;
13use crate::ids::GroupId;
14
15use super::Simulation;
16
17impl Simulation {
18 // ── Extension restore ────────────────────────────────────────────
19
20 /// Deserialize extension components from a snapshot.
21 ///
22 /// Call this after restoring from a snapshot and registering all
23 /// extension types via `world.register_ext::<T>(key)`.
24 ///
25 /// Returns the names of any extension types present in the snapshot
26 /// that were not registered. An empty vec means all extensions were
27 /// deserialized successfully.
28 ///
29 /// Prefer [`load_extensions_with`](Self::load_extensions_with) which
30 /// combines registration and loading in one call.
31 #[must_use]
32 pub fn load_extensions(&mut self) -> Vec<String> {
33 let Some(pending) = self
34 .world
35 .remove_resource::<crate::snapshot::PendingExtensions>()
36 else {
37 return Vec::new();
38 };
39 let unregistered = self.world.unregistered_ext_names(pending.0.keys());
40 self.world.deserialize_extensions(&pending.0);
41 unregistered
42 }
43
44 /// Register extension types and load their data from a snapshot
45 /// in one step.
46 ///
47 /// This is the recommended way to restore extensions. It replaces the
48 /// manual 3-step ceremony of `register_ext` → `load_extensions`:
49 ///
50 /// ```no_run
51 /// # use elevator_core::prelude::*;
52 /// # use elevator_core::register_extensions;
53 /// # use elevator_core::snapshot::WorldSnapshot;
54 /// # use serde::{Serialize, Deserialize};
55 /// # #[derive(Clone, Serialize, Deserialize)] struct VipTag;
56 /// # #[derive(Clone, Serialize, Deserialize)] struct TeamId;
57 /// # fn before(snapshot: WorldSnapshot) -> Result<(), SimError> {
58 /// // Before (3-step ceremony):
59 /// let mut sim = snapshot.restore(None)?;
60 /// sim.world_mut().register_ext::<VipTag>(ExtKey::from_type_name());
61 /// sim.world_mut().register_ext::<TeamId>(ExtKey::from_type_name());
62 /// sim.load_extensions();
63 /// # Ok(()) }
64 /// # fn after(snapshot: WorldSnapshot) -> Result<(), SimError> {
65 ///
66 /// // After:
67 /// let mut sim = snapshot.restore(None)?;
68 /// let unregistered = sim.load_extensions_with(|world| {
69 /// register_extensions!(world, VipTag, TeamId);
70 /// });
71 /// assert!(unregistered.is_empty(), "missing: {unregistered:?}");
72 /// # Ok(()) }
73 /// ```
74 ///
75 /// Returns the names of any extension types in the snapshot that were
76 /// not registered. This catches "forgot to register" bugs at load time.
77 #[must_use]
78 pub fn load_extensions_with<F>(&mut self, register: F) -> Vec<String>
79 where
80 F: FnOnce(&mut crate::world::World),
81 {
82 register(&mut self.world);
83 self.load_extensions()
84 }
85
86 // ── Helpers ──────────────────────────────────────────────────────
87
88 /// Extract the `GroupId` from the current leg of a route.
89 ///
90 /// For Walk legs, looks ahead to the next leg to find the group.
91 /// Falls back to `GroupId(0)` when no route exists or no group leg is found.
92 pub(super) fn group_from_route(&self, route: Option<&Route>) -> GroupId {
93 if let Some(route) = route {
94 // Scan forward from current_leg looking for a Group or Line transport mode.
95 for leg in route.legs.iter().skip(route.current_leg) {
96 match leg.via {
97 crate::components::TransportMode::Group(g) => return g,
98 crate::components::TransportMode::Line(l) => {
99 if let Some(line) = self.world.line(l) {
100 return line.group();
101 }
102 }
103 crate::components::TransportMode::Walk => {}
104 }
105 }
106 }
107 GroupId(0)
108 }
109
110 // ── Re-routing ───────────────────────────────────────────────────
111
112 /// Change a rider's destination mid-route.
113 ///
114 /// Replaces remaining route legs with a single direct leg to `new_destination`,
115 /// keeping the rider's current stop as origin.
116 ///
117 /// Returns `Err` if the rider does not exist or is not in `Waiting` phase
118 /// (riding/boarding riders cannot be rerouted until they exit).
119 ///
120 /// # Errors
121 ///
122 /// Returns [`SimError::EntityNotFound`] if `rider` does not exist.
123 /// Returns [`SimError::WrongRiderPhase`] if the rider is not in
124 /// [`RiderPhase::Waiting`], or [`SimError::RiderHasNoStop`] if the
125 /// rider has no current stop.
126 pub fn reroute(&mut self, rider: RiderId, new_destination: EntityId) -> Result<(), SimError> {
127 let rider = rider.entity();
128 let r = self
129 .world
130 .rider(rider)
131 .ok_or(SimError::EntityNotFound(rider))?;
132
133 if r.phase != RiderPhase::Waiting {
134 return Err(SimError::WrongRiderPhase {
135 rider,
136 expected: RiderPhaseKind::Waiting,
137 actual: r.phase.kind(),
138 });
139 }
140
141 let origin = r.current_stop.ok_or(SimError::RiderHasNoStop(rider))?;
142
143 let group = self.group_from_route(self.world.route(rider));
144 self.world
145 .set_route(rider, Route::direct(origin, new_destination, group));
146
147 self.events.emit(Event::RiderRerouted {
148 rider,
149 new_destination,
150 tick: self.tick,
151 });
152
153 Ok(())
154 }
155
156 /// Replace a rider's entire remaining route.
157 ///
158 /// # Errors
159 ///
160 /// Returns [`SimError::EntityNotFound`] if `rider` does not exist.
161 pub fn set_rider_route(&mut self, rider: EntityId, route: Route) -> Result<(), SimError> {
162 if self.world.rider(rider).is_none() {
163 return Err(SimError::EntityNotFound(rider));
164 }
165 self.world.set_route(rider, route);
166 Ok(())
167 }
168
169 // ── Rider settlement & population ─────────────────────────────
170
171 /// Transition an `Arrived` or `Abandoned` rider to `Resident` at their
172 /// current stop.
173 ///
174 /// Resident riders are parked — invisible to dispatch and loading, but
175 /// queryable via [`residents_at()`](Self::residents_at). They can later
176 /// be given a new route via [`reroute_rider()`](Self::reroute_rider).
177 ///
178 /// # Errors
179 ///
180 /// Returns [`SimError::EntityNotFound`] if `id` does not exist.
181 /// Returns [`SimError::WrongRiderPhase`] if the rider is not in
182 /// `Arrived` or `Abandoned` phase, or [`SimError::RiderHasNoStop`]
183 /// if the rider has no current stop.
184 pub fn settle_rider(&mut self, id: RiderId) -> Result<(), SimError> {
185 let id = id.entity();
186 let rider = self.world.rider(id).ok_or(SimError::EntityNotFound(id))?;
187
188 let old_phase = rider.phase;
189 match old_phase {
190 RiderPhase::Arrived | RiderPhase::Abandoned => {}
191 _ => {
192 return Err(SimError::WrongRiderPhase {
193 rider: id,
194 expected: RiderPhaseKind::Arrived,
195 actual: old_phase.kind(),
196 });
197 }
198 }
199
200 let stop = rider.current_stop.ok_or(SimError::RiderHasNoStop(id))?;
201
202 // Update index: remove from old partition (only Abandoned is indexed).
203 if old_phase == RiderPhase::Abandoned {
204 self.rider_index.remove_abandoned(stop, id);
205 }
206 self.rider_index.insert_resident(stop, id);
207
208 if let Some(r) = self.world.rider_mut(id) {
209 r.phase = RiderPhase::Resident;
210 }
211
212 self.metrics.record_settle();
213 self.events.emit(Event::RiderSettled {
214 rider: id,
215 stop,
216 tick: self.tick,
217 });
218 Ok(())
219 }
220
221 /// Give a `Resident` rider a new route, transitioning them to `Waiting`.
222 ///
223 /// The rider begins waiting at their current stop for an elevator
224 /// matching the route's transport mode. If the rider has a
225 /// [`Patience`](crate::components::Patience) component, its
226 /// `waited_ticks` is reset to zero.
227 ///
228 /// # Errors
229 ///
230 /// Returns [`SimError::EntityNotFound`] if `id` does not exist.
231 /// Returns [`SimError::WrongRiderPhase`] if the rider is not in `Resident`
232 /// phase, [`SimError::EmptyRoute`] if the route has no legs, or
233 /// [`SimError::RouteOriginMismatch`] if the route's first leg origin does
234 /// not match the rider's current stop.
235 pub fn reroute_rider(&mut self, id: EntityId, route: Route) -> Result<(), SimError> {
236 let rider = self.world.rider(id).ok_or(SimError::EntityNotFound(id))?;
237
238 if rider.phase != RiderPhase::Resident {
239 return Err(SimError::WrongRiderPhase {
240 rider: id,
241 expected: RiderPhaseKind::Resident,
242 actual: rider.phase.kind(),
243 });
244 }
245
246 let stop = rider.current_stop.ok_or(SimError::RiderHasNoStop(id))?;
247
248 let new_destination = route.final_destination().ok_or(SimError::EmptyRoute)?;
249
250 // Validate that the route departs from the rider's current stop.
251 if let Some(leg) = route.current()
252 && leg.from != stop
253 {
254 return Err(SimError::RouteOriginMismatch {
255 expected_origin: stop,
256 route_origin: leg.from,
257 });
258 }
259
260 self.rider_index.remove_resident(stop, id);
261 self.rider_index.insert_waiting(stop, id);
262
263 if let Some(r) = self.world.rider_mut(id) {
264 r.phase = RiderPhase::Waiting;
265 }
266 self.world.set_route(id, route);
267
268 // Reset patience if present.
269 if let Some(p) = self.world.patience_mut(id) {
270 p.waited_ticks = 0;
271 }
272
273 self.metrics.record_reroute();
274 self.events.emit(Event::RiderRerouted {
275 rider: id,
276 new_destination,
277 tick: self.tick,
278 });
279 Ok(())
280 }
281
282 /// Remove a rider from the simulation entirely.
283 ///
284 /// Cleans up the population index, metric tags, and elevator cross-references
285 /// (if the rider is currently aboard). Emits [`Event::RiderDespawned`].
286 ///
287 /// All rider removal should go through this method rather than calling
288 /// `world.despawn()` directly, to keep the population index consistent.
289 ///
290 /// # Errors
291 ///
292 /// Returns [`SimError::EntityNotFound`] if `id` does not exist or is
293 /// not a rider.
294 pub fn despawn_rider(&mut self, id: RiderId) -> Result<(), SimError> {
295 let id = id.entity();
296 let rider = self.world.rider(id).ok_or(SimError::EntityNotFound(id))?;
297
298 // Targeted index removal based on current phase (O(1) vs O(n) scan).
299 if let Some(stop) = rider.current_stop {
300 match rider.phase {
301 RiderPhase::Waiting => self.rider_index.remove_waiting(stop, id),
302 RiderPhase::Resident => self.rider_index.remove_resident(stop, id),
303 RiderPhase::Abandoned => self.rider_index.remove_abandoned(stop, id),
304 _ => {} // Boarding/Riding/Exiting/Walking/Arrived — not indexed
305 }
306 }
307
308 if let Some(tags) = self
309 .world
310 .resource_mut::<crate::tagged_metrics::MetricTags>()
311 {
312 tags.remove_entity(id);
313 }
314
315 self.world.despawn(id);
316
317 self.events.emit(Event::RiderDespawned {
318 rider: id,
319 tick: self.tick,
320 });
321 Ok(())
322 }
323
324 // ── Access control ──────────────────────────────────────────────
325
326 /// Set the allowed stops for a rider.
327 ///
328 /// When set, the rider will only be allowed to board elevators that
329 /// can take them to a stop in the allowed set. See
330 /// [`AccessControl`](crate::components::AccessControl) for details.
331 ///
332 /// # Errors
333 ///
334 /// Returns [`SimError::EntityNotFound`] if the rider does not exist.
335 pub fn set_rider_access(
336 &mut self,
337 rider: EntityId,
338 allowed_stops: HashSet<EntityId>,
339 ) -> Result<(), SimError> {
340 if self.world.rider(rider).is_none() {
341 return Err(SimError::EntityNotFound(rider));
342 }
343 self.world
344 .set_access_control(rider, crate::components::AccessControl::new(allowed_stops));
345 Ok(())
346 }
347
348 /// Set the restricted stops for an elevator.
349 ///
350 /// Riders whose current destination is in this set will be rejected
351 /// with [`RejectionReason::AccessDenied`](crate::error::RejectionReason::AccessDenied)
352 /// during the loading phase.
353 ///
354 /// # Errors
355 ///
356 /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
357 pub fn set_elevator_restricted_stops(
358 &mut self,
359 elevator: EntityId,
360 restricted_stops: HashSet<EntityId>,
361 ) -> Result<(), SimError> {
362 let car = self
363 .world
364 .elevator_mut(elevator)
365 .ok_or(SimError::EntityNotFound(elevator))?;
366 car.restricted_stops = restricted_stops;
367 Ok(())
368 }
369
370 // ── Population queries ──────────────────────────────────────────
371
372 /// Iterate over resident rider IDs at a stop (O(1) lookup).
373 pub fn residents_at(&self, stop: EntityId) -> impl Iterator<Item = EntityId> + '_ {
374 self.rider_index.residents_at(stop).iter().copied()
375 }
376
377 /// Count of residents at a stop (O(1)).
378 #[must_use]
379 pub fn resident_count_at(&self, stop: EntityId) -> usize {
380 self.rider_index.resident_count_at(stop)
381 }
382
383 /// Iterate over waiting rider IDs at a stop (O(1) lookup).
384 pub fn waiting_at(&self, stop: EntityId) -> impl Iterator<Item = EntityId> + '_ {
385 self.rider_index.waiting_at(stop).iter().copied()
386 }
387
388 /// Count of waiting riders at a stop (O(1)).
389 #[must_use]
390 pub fn waiting_count_at(&self, stop: EntityId) -> usize {
391 self.rider_index.waiting_count_at(stop)
392 }
393
394 /// Iterate over abandoned rider IDs at a stop (O(1) lookup).
395 pub fn abandoned_at(&self, stop: EntityId) -> impl Iterator<Item = EntityId> + '_ {
396 self.rider_index.abandoned_at(stop).iter().copied()
397 }
398
399 /// Count of abandoned riders at a stop (O(1)).
400 #[must_use]
401 pub fn abandoned_count_at(&self, stop: EntityId) -> usize {
402 self.rider_index.abandoned_count_at(stop)
403 }
404
405 /// Get the rider entities currently aboard an elevator.
406 ///
407 /// Returns an empty slice if the elevator does not exist.
408 #[must_use]
409 pub fn riders_on(&self, elevator: EntityId) -> &[EntityId] {
410 self.world
411 .elevator(elevator)
412 .map_or(&[], |car| car.riders())
413 }
414
415 /// Get the number of riders aboard an elevator.
416 ///
417 /// Returns 0 if the elevator does not exist.
418 #[must_use]
419 pub fn occupancy(&self, elevator: EntityId) -> usize {
420 self.world
421 .elevator(elevator)
422 .map_or(0, |car| car.riders().len())
423 }
424
425 // ── Entity lifecycle ────────────────────────────────────────────
426
427 /// Disable an entity. Disabled entities are skipped by all systems.
428 ///
429 /// If the entity is an elevator in motion, it is reset to `Idle` with
430 /// zero velocity to prevent stale target references on re-enable.
431 ///
432 /// If the entity is a stop, any `Resident` riders parked there are
433 /// transitioned to `Abandoned` and appropriate events are emitted.
434 ///
435 /// Emits `EntityDisabled`. Returns `Err` if the entity does not exist.
436 ///
437 /// # Errors
438 ///
439 /// Returns [`SimError::EntityNotFound`] if `id` does not refer to a
440 /// living entity.
441 pub fn disable(&mut self, id: EntityId) -> Result<(), SimError> {
442 if !self.world.is_alive(id) {
443 return Err(SimError::EntityNotFound(id));
444 }
445 // If this is an elevator, eject all riders and reset state.
446 if let Some(car) = self.world.elevator(id) {
447 let rider_ids = car.riders.clone();
448 let pos = self.world.position(id).map_or(0.0, |p| p.value);
449 let nearest_stop = self.world.find_nearest_stop(pos);
450
451 for rid in &rider_ids {
452 if let Some(r) = self.world.rider_mut(*rid) {
453 r.phase = RiderPhase::Waiting;
454 r.current_stop = nearest_stop;
455 r.board_tick = None;
456 }
457 if let Some(stop) = nearest_stop {
458 self.rider_index.insert_waiting(stop, *rid);
459 self.events.emit(Event::RiderEjected {
460 rider: *rid,
461 elevator: id,
462 stop,
463 tick: self.tick,
464 });
465 }
466 }
467
468 let had_load = self
469 .world
470 .elevator(id)
471 .is_some_and(|c| c.current_load.value() > 0.0);
472 let capacity = self.world.elevator(id).map(|c| c.weight_capacity.value());
473 if let Some(car) = self.world.elevator_mut(id) {
474 car.riders.clear();
475 car.current_load = crate::components::Weight::ZERO;
476 car.phase = ElevatorPhase::Idle;
477 car.target_stop = None;
478 }
479 if had_load && let Some(cap) = capacity {
480 self.events.emit(Event::CapacityChanged {
481 elevator: id,
482 current_load: ordered_float::OrderedFloat(0.0),
483 capacity: ordered_float::OrderedFloat(cap),
484 tick: self.tick,
485 });
486 }
487 }
488 if let Some(vel) = self.world.velocity_mut(id) {
489 vel.value = 0.0;
490 }
491
492 // If this is a stop, abandon resident riders and invalidate routes.
493 if self.world.stop(id).is_some() {
494 let resident_ids: Vec<EntityId> =
495 self.rider_index.residents_at(id).iter().copied().collect();
496 for rid in resident_ids {
497 self.rider_index.remove_resident(id, rid);
498 self.rider_index.insert_abandoned(id, rid);
499 if let Some(r) = self.world.rider_mut(rid) {
500 r.phase = RiderPhase::Abandoned;
501 }
502 self.events.emit(Event::RiderAbandoned {
503 rider: rid,
504 stop: id,
505 tick: self.tick,
506 });
507 }
508 self.invalidate_routes_for_stop(id);
509 }
510
511 self.world.disable(id);
512 self.events.emit(Event::EntityDisabled {
513 entity: id,
514 tick: self.tick,
515 });
516 Ok(())
517 }
518
519 /// Re-enable a disabled entity.
520 ///
521 /// Emits `EntityEnabled`. Returns `Err` if the entity does not exist.
522 ///
523 /// # Errors
524 ///
525 /// Returns [`SimError::EntityNotFound`] if `id` does not refer to a
526 /// living entity.
527 pub fn enable(&mut self, id: EntityId) -> Result<(), SimError> {
528 if !self.world.is_alive(id) {
529 return Err(SimError::EntityNotFound(id));
530 }
531 self.world.enable(id);
532 self.events.emit(Event::EntityEnabled {
533 entity: id,
534 tick: self.tick,
535 });
536 Ok(())
537 }
538
539 /// Invalidate routes for all riders referencing a disabled stop.
540 ///
541 /// Attempts to reroute riders to the nearest enabled alternative stop.
542 /// If no alternative exists, emits `RouteInvalidated` with `NoAlternative`.
543 fn invalidate_routes_for_stop(&mut self, disabled_stop: EntityId) {
544 use crate::events::RouteInvalidReason;
545
546 // Find the group this stop belongs to.
547 let group_stops: Vec<EntityId> = self
548 .groups
549 .iter()
550 .filter(|g| g.stop_entities().contains(&disabled_stop))
551 .flat_map(|g| g.stop_entities().iter().copied())
552 .filter(|&s| s != disabled_stop && !self.world.is_disabled(s))
553 .collect();
554
555 // Find all Waiting riders whose route references this stop.
556 // Riding riders are skipped — they'll be rerouted when they exit.
557 let rider_ids: Vec<EntityId> = self.world.rider_ids();
558 for rid in rider_ids {
559 let is_waiting = self
560 .world
561 .rider(rid)
562 .is_some_and(|r| r.phase == RiderPhase::Waiting);
563
564 if !is_waiting {
565 continue;
566 }
567
568 let references_stop = self.world.route(rid).is_some_and(|route| {
569 route
570 .legs
571 .iter()
572 .skip(route.current_leg)
573 .any(|leg| leg.to == disabled_stop || leg.from == disabled_stop)
574 });
575
576 if !references_stop {
577 continue;
578 }
579
580 // Try to find nearest alternative (excluding rider's current stop).
581 let rider_current_stop = self.world.rider(rid).and_then(|r| r.current_stop);
582
583 let disabled_stop_pos = self.world.stop(disabled_stop).map_or(0.0, |s| s.position);
584
585 let alternative = group_stops
586 .iter()
587 .filter(|&&s| Some(s) != rider_current_stop)
588 .filter_map(|&s| {
589 self.world
590 .stop(s)
591 .map(|stop| (s, (stop.position - disabled_stop_pos).abs()))
592 })
593 .min_by(|a, b| a.1.total_cmp(&b.1))
594 .map(|(s, _)| s);
595
596 if let Some(alt_stop) = alternative {
597 // Reroute to nearest alternative.
598 let origin = rider_current_stop.unwrap_or(alt_stop);
599 let group = self.group_from_route(self.world.route(rid));
600 self.world
601 .set_route(rid, Route::direct(origin, alt_stop, group));
602 self.events.emit(Event::RouteInvalidated {
603 rider: rid,
604 affected_stop: disabled_stop,
605 reason: RouteInvalidReason::StopDisabled,
606 tick: self.tick,
607 });
608 } else {
609 // No alternative — rider abandons immediately.
610 let abandon_stop = rider_current_stop.unwrap_or(disabled_stop);
611 self.events.emit(Event::RouteInvalidated {
612 rider: rid,
613 affected_stop: disabled_stop,
614 reason: RouteInvalidReason::NoAlternative,
615 tick: self.tick,
616 });
617 if let Some(r) = self.world.rider_mut(rid) {
618 r.phase = RiderPhase::Abandoned;
619 }
620 if let Some(stop) = rider_current_stop {
621 self.rider_index.remove_waiting(stop, rid);
622 self.rider_index.insert_abandoned(stop, rid);
623 }
624 self.events.emit(Event::RiderAbandoned {
625 rider: rid,
626 stop: abandon_stop,
627 tick: self.tick,
628 });
629 }
630 }
631 }
632
633 /// Check if an entity is disabled.
634 #[must_use]
635 pub fn is_disabled(&self, id: EntityId) -> bool {
636 self.world.is_disabled(id)
637 }
638
639 // ── Entity type queries ─────────────────────────────────────────
640
641 /// Check if an entity is an elevator.
642 ///
643 /// ```
644 /// use elevator_core::prelude::*;
645 ///
646 /// let sim = SimulationBuilder::demo().build().unwrap();
647 /// let stop = sim.stop_entity(StopId(0)).unwrap();
648 /// assert!(!sim.is_elevator(stop));
649 /// assert!(sim.is_stop(stop));
650 /// ```
651 #[must_use]
652 pub fn is_elevator(&self, id: EntityId) -> bool {
653 self.world.elevator(id).is_some()
654 }
655
656 /// Check if an entity is a rider.
657 #[must_use]
658 pub fn is_rider(&self, id: EntityId) -> bool {
659 self.world.rider(id).is_some()
660 }
661
662 /// Check if an entity is a stop.
663 #[must_use]
664 pub fn is_stop(&self, id: EntityId) -> bool {
665 self.world.stop(id).is_some()
666 }
667
668 // ── Aggregate queries ───────────────────────────────────────────
669
670 /// Count of elevators currently in the [`Idle`](ElevatorPhase::Idle) phase.
671 ///
672 /// Excludes disabled elevators (whose phase is reset to `Idle` on disable).
673 ///
674 /// ```
675 /// use elevator_core::prelude::*;
676 ///
677 /// let sim = SimulationBuilder::demo().build().unwrap();
678 /// assert_eq!(sim.idle_elevator_count(), 1);
679 /// ```
680 #[must_use]
681 pub fn idle_elevator_count(&self) -> usize {
682 self.world.iter_idle_elevators().count()
683 }
684
685 /// Current total weight aboard an elevator, or `None` if the entity is
686 /// not an elevator.
687 ///
688 /// ```
689 /// use elevator_core::prelude::*;
690 ///
691 /// let sim = SimulationBuilder::demo().build().unwrap();
692 /// let stop = sim.stop_entity(StopId(0)).unwrap();
693 /// assert_eq!(sim.elevator_load(ElevatorId::from(stop)), None); // not an elevator
694 /// ```
695 #[must_use]
696 pub fn elevator_load(&self, id: ElevatorId) -> Option<f64> {
697 let id = id.entity();
698 self.world.elevator(id).map(|e| e.current_load.value())
699 }
700
701 /// Whether the elevator's up-direction indicator lamp is lit.
702 ///
703 /// Returns `None` if the entity is not an elevator. See
704 /// [`Elevator::going_up`] for semantics.
705 #[must_use]
706 pub fn elevator_going_up(&self, id: EntityId) -> Option<bool> {
707 self.world.elevator(id).map(Elevator::going_up)
708 }
709
710 /// Whether the elevator's down-direction indicator lamp is lit.
711 ///
712 /// Returns `None` if the entity is not an elevator. See
713 /// [`Elevator::going_down`] for semantics.
714 #[must_use]
715 pub fn elevator_going_down(&self, id: EntityId) -> Option<bool> {
716 self.world.elevator(id).map(Elevator::going_down)
717 }
718
719 /// Direction the elevator is currently signalling, derived from the
720 /// indicator-lamp pair. Returns `None` if the entity is not an elevator.
721 #[must_use]
722 pub fn elevator_direction(&self, id: EntityId) -> Option<crate::components::Direction> {
723 self.world.elevator(id).map(Elevator::direction)
724 }
725
726 /// Count of rounded-floor transitions for an elevator (passing-floor
727 /// crossings plus arrivals). Returns `None` if the entity is not an
728 /// elevator.
729 #[must_use]
730 pub fn elevator_move_count(&self, id: EntityId) -> Option<u64> {
731 self.world.elevator(id).map(Elevator::move_count)
732 }
733
734 /// Distance the elevator would travel while braking to a stop from its
735 /// current velocity, at its configured deceleration rate.
736 ///
737 /// Uses the standard `v² / (2·a)` kinematic formula. A stationary
738 /// elevator returns `Some(0.0)`. Returns `None` if the entity is not
739 /// an elevator or lacks a velocity component.
740 ///
741 /// Useful for writing opportunistic dispatch strategies (e.g. "stop at
742 /// this floor if we can brake in time") without duplicating the physics
743 /// computation.
744 #[must_use]
745 pub fn braking_distance(&self, id: EntityId) -> Option<f64> {
746 let car = self.world.elevator(id)?;
747 let vel = self.world.velocity(id)?.value;
748 Some(crate::movement::braking_distance(
749 vel,
750 car.deceleration.value(),
751 ))
752 }
753
754 /// The position where the elevator would come to rest if it began braking
755 /// this instant. Current position plus a signed braking distance in the
756 /// direction of travel.
757 ///
758 /// Returns `None` if the entity is not an elevator or lacks the required
759 /// components.
760 #[must_use]
761 pub fn future_stop_position(&self, id: EntityId) -> Option<f64> {
762 let pos = self.world.position(id)?.value;
763 let vel = self.world.velocity(id)?.value;
764 let car = self.world.elevator(id)?;
765 let dist = crate::movement::braking_distance(vel, car.deceleration.value());
766 Some(vel.signum().mul_add(dist, pos))
767 }
768
769 /// Count of elevators currently in the given phase.
770 ///
771 /// Excludes disabled elevators (whose phase is reset to `Idle` on disable).
772 ///
773 /// ```
774 /// use elevator_core::prelude::*;
775 ///
776 /// let sim = SimulationBuilder::demo().build().unwrap();
777 /// assert_eq!(sim.elevators_in_phase(ElevatorPhase::Idle), 1);
778 /// assert_eq!(sim.elevators_in_phase(ElevatorPhase::Loading), 0);
779 /// ```
780 #[must_use]
781 pub fn elevators_in_phase(&self, phase: ElevatorPhase) -> usize {
782 self.world
783 .iter_elevators()
784 .filter(|(id, _, e)| e.phase() == phase && !self.world.is_disabled(*id))
785 .count()
786 }
787
788 // ── Service mode ────────────────────────────────────────────────
789
790 /// Set the service mode for an elevator.
791 ///
792 /// Emits [`Event::ServiceModeChanged`] if the mode actually changes.
793 ///
794 /// # Errors
795 ///
796 /// Returns [`SimError::EntityNotFound`] if the elevator does not exist.
797 pub fn set_service_mode(
798 &mut self,
799 elevator: EntityId,
800 mode: crate::components::ServiceMode,
801 ) -> Result<(), SimError> {
802 if self.world.elevator(elevator).is_none() {
803 return Err(SimError::EntityNotFound(elevator));
804 }
805 let old = self
806 .world
807 .service_mode(elevator)
808 .copied()
809 .unwrap_or_default();
810 if old == mode {
811 return Ok(());
812 }
813 // Leaving Manual: clear the pending velocity command and zero
814 // the velocity component. Otherwise a car moving at transition
815 // time is stranded — the Normal movement system only runs for
816 // MovingToStop/Repositioning phases, so velocity would linger
817 // forever without producing any position change.
818 if old == crate::components::ServiceMode::Manual {
819 if let Some(car) = self.world.elevator_mut(elevator) {
820 car.manual_target_velocity = None;
821 }
822 if let Some(v) = self.world.velocity_mut(elevator) {
823 v.value = 0.0;
824 }
825 }
826 self.world.set_service_mode(elevator, mode);
827 self.events.emit(Event::ServiceModeChanged {
828 elevator,
829 from: old,
830 to: mode,
831 tick: self.tick,
832 });
833 Ok(())
834 }
835
836 /// Get the current service mode for an elevator.
837 #[must_use]
838 pub fn service_mode(&self, elevator: EntityId) -> crate::components::ServiceMode {
839 self.world
840 .service_mode(elevator)
841 .copied()
842 .unwrap_or_default()
843 }
844}