Skip to main content

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