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