Skip to main content

elevator_core/dispatch/
mod.rs

1//! Pluggable dispatch strategies for assigning elevators to stops.
2//!
3//! Strategies express preferences as scores on `(car, stop)` pairs via
4//! [`DispatchStrategy::rank`](crate::dispatch::DispatchStrategy::rank). The
5//! dispatch system then runs an optimal bipartite assignment (Kuhn–Munkres /
6//! Hungarian algorithm) so coordination — one car per hall call — is a library
7//! invariant, not a per-strategy responsibility. Cars left unassigned are
8//! handed to [`DispatchStrategy::fallback`](crate::dispatch::DispatchStrategy::fallback)
9//! for per-car policy (idle, park, etc.).
10//!
11//! # Example: custom dispatch strategy
12//!
13//! ```rust
14//! use elevator_core::dispatch::RankContext;
15//! use elevator_core::prelude::*;
16//!
17//! struct AlwaysFirstStop;
18//!
19//! impl DispatchStrategy for AlwaysFirstStop {
20//!     fn rank(&self, ctx: &RankContext<'_>) -> Option<f64> {
21//!         // Prefer the group's first stop; everything else is unavailable.
22//!         if Some(&ctx.stop) == ctx.group.stop_entities().first() {
23//!             Some((ctx.car_position() - ctx.stop_position()).abs())
24//!         } else {
25//!             None
26//!         }
27//!     }
28//! }
29//!
30//! let sim = SimulationBuilder::demo()
31//!     .dispatch(AlwaysFirstStop)
32//!     .build()
33//!     .unwrap();
34//! ```
35
36/// Hall-call destination dispatch algorithm.
37pub mod destination;
38/// Estimated Time to Destination dispatch algorithm.
39pub mod etd;
40/// LOOK dispatch algorithm.
41pub mod look;
42/// Nearest-car dispatch algorithm.
43pub mod nearest_car;
44/// Built-in repositioning strategies.
45pub mod reposition;
46/// Relative System Response (RSR) dispatch algorithm.
47pub mod rsr;
48/// SCAN dispatch algorithm.
49pub mod scan;
50/// Shared sweep-direction logic used by SCAN and LOOK.
51pub(crate) mod sweep;
52
53pub use destination::{AssignedCar, DestinationDispatch};
54pub use etd::EtdDispatch;
55pub use look::LookDispatch;
56pub use nearest_car::NearestCarDispatch;
57pub use rsr::RsrDispatch;
58pub use scan::ScanDispatch;
59
60use serde::{Deserialize, Serialize};
61
62use crate::components::{
63    CallDirection, CarCall, ElevatorPhase, HallCall, Route, TransportMode, Weight,
64};
65use crate::entity::EntityId;
66use crate::ids::GroupId;
67use crate::world::World;
68use std::collections::{BTreeMap, HashSet};
69
70/// Whether assigning `ctx.car` to `ctx.stop` is worth ranking.
71///
72/// Combines two checks every dispatch strategy needs at the top of its
73/// `rank` implementation:
74///
75/// 1. **Servability** — capacity, full-load bypass, and the loading-phase
76///    boarding filter. A pair that can't exit an aboard rider, board a
77///    waiter, or answer a rider-less hall call is a no-op move (and a
78///    zero-cost one when the car is already parked there) which would
79///    otherwise stall doors against unservable demand.
80/// 2. **Path discipline** (only when `respect_aboard_path` is `true`) —
81///    refuses pickups that would pull a car carrying routed riders off
82///    the direct path to every aboard rider's destination. Without it, a
83///    stream of closer-destination hall calls can indefinitely preempt a
84///    farther aboard rider's delivery (the "never reaches the
85///    passenger's desired stop" loop).
86///
87/// Strategies with their own direction discipline (SCAN, LOOK, ETD,
88/// Destination) pass `respect_aboard_path: false` because their
89/// sweep/direction terms already rule out backtracks. Strategies without
90/// it (`NearestCar`, RSR) pass `respect_aboard_path: true`. Custom
91/// strategies should pass `true` unless they enforce direction
92/// discipline themselves.
93///
94/// Aboard riders without a published route (game-managed manual riders)
95/// don't constrain the path — any pickup is trivially on-the-way for
96/// them, so the path check trivially passes when no aboard rider has a
97/// `Route::current_destination`.
98#[must_use]
99pub fn pair_is_useful(ctx: &RankContext<'_>, respect_aboard_path: bool) -> bool {
100    let Some(car) = ctx.world.elevator(ctx.car) else {
101        return false;
102    };
103    let can_exit_here = car
104        .riders()
105        .iter()
106        .any(|&rid| ctx.world.route(rid).and_then(Route::current_destination) == Some(ctx.stop));
107    if can_exit_here {
108        return true;
109    }
110
111    // Direction-dependent full-load bypass (Otis Elevonic 411 model,
112    // patent US5490580A). A car loaded above its configured threshold
113    // in the current travel direction ignores hall calls in that same
114    // direction. Aboard riders still get delivered — the `can_exit_here`
115    // short-circuit above guarantees their destinations remain rank-able.
116    if bypass_in_current_direction(car, ctx) {
117        return false;
118    }
119
120    let remaining_capacity = car.weight_capacity.value() - car.current_load.value();
121    if remaining_capacity <= 0.0 {
122        return false;
123    }
124    let waiting = ctx.manifest.waiting_riders_at(ctx.stop);
125    let servable = if waiting.is_empty() {
126        // No waiters at the stop, and no aboard rider of ours exits here
127        // (the `can_exit_here` short-circuit ruled that out above).
128        // Demand must therefore come from either another car's
129        // `riding_to_stop` (not work this car can perform) or a
130        // rider-less hall call (someone pressed a button with no rider
131        // attached yet — a press from `press_hall_button` or one whose
132        // riders have since been fulfilled or abandoned). Only the
133        // latter is actionable; without this filter an idle car parked
134        // at the stop collapses to cost 0, the Hungarian picks the
135        // self-pair every tick, and doors cycle open/close indefinitely
136        // while the other car finishes its trip.
137        ctx.manifest
138            .hall_calls_at_stop
139            .get(&ctx.stop)
140            .is_some_and(|calls| calls.iter().any(|c| c.pending_riders.is_empty()))
141    } else {
142        waiting
143            .iter()
144            .any(|r| rider_can_board(r, car, ctx, remaining_capacity))
145    };
146    if !servable {
147        return false;
148    }
149    if !respect_aboard_path || car.riders().is_empty() {
150        return true;
151    }
152
153    // Route-less aboard riders (game-managed manual riders) don't
154    // publish a destination, so there's no committed path to protect.
155    // Any pickup is trivially on-the-way — let it through. Otherwise
156    // we'd refuse every pickup the moment the car carried its first
157    // manually-managed passenger.
158    let has_routed_rider = car.riders().iter().any(|&rid| {
159        ctx.world
160            .route(rid)
161            .and_then(Route::current_destination)
162            .is_some()
163    });
164    if !has_routed_rider {
165        return true;
166    }
167
168    // Pickups allowed only on the path to an aboard rider's destination.
169    // Candidate at the car's position (to_cand = 0) trivially qualifies —
170    // useful for same-floor boards.
171    let to_cand = ctx.stop_position() - ctx.car_position();
172    car.riders().iter().any(|&rid| {
173        let Some(dest) = ctx.world.route(rid).and_then(Route::current_destination) else {
174            return false;
175        };
176        let Some(dest_pos) = ctx.world.stop_position(dest) else {
177            return false;
178        };
179        let to_dest = dest_pos - ctx.car_position();
180        to_dest * to_cand >= 0.0 && to_cand.abs() <= to_dest.abs()
181    })
182}
183
184/// Whether a waiting rider could actually board this car, matching the
185/// same filters the loading phase applies. Prevents `pair_is_useful`
186/// from approving a pickup whose only demand is direction-filtered or
187/// over-capacity — the loading phase would reject the rider, doors
188/// would cycle, and dispatch would re-pick the zero-cost self-pair.
189fn rider_can_board(
190    rider: &RiderInfo,
191    car: &crate::components::Elevator,
192    ctx: &RankContext<'_>,
193    remaining_capacity: f64,
194) -> bool {
195    if rider.weight.value() > remaining_capacity {
196        return false;
197    }
198    // Match `systems::loading`'s direction filter: a rider whose trip
199    // goes the opposite way of the car's committed direction will not
200    // be boarded. An unknown destination (no route yet) is treated as
201    // unconstrained — let the rider through and let the loading phase
202    // make the final call.
203    let Some(dest) = rider.destination else {
204        return true;
205    };
206    let Some(dest_pos) = ctx.world.stop_position(dest) else {
207        return true;
208    };
209    if dest_pos > ctx.stop_position() && !car.going_up() {
210        return false;
211    }
212    if dest_pos < ctx.stop_position() && !car.going_down() {
213        return false;
214    }
215    true
216}
217
218/// True when a full-load bypass applies: the car has a configured
219/// threshold for its current travel direction, is above that threshold,
220/// and the candidate stop lies in that same direction.
221fn bypass_in_current_direction(car: &crate::components::Elevator, ctx: &RankContext<'_>) -> bool {
222    // Derive travel direction from the car's current target, if any.
223    // An Idle or Stopped car has no committed direction → no bypass.
224    let Some(target) = car.phase().moving_target() else {
225        return false;
226    };
227    let Some(target_pos) = ctx.world.stop_position(target) else {
228        return false;
229    };
230    let going_up = target_pos > ctx.car_position();
231    let going_down = target_pos < ctx.car_position();
232    if !going_up && !going_down {
233        return false;
234    }
235    let threshold = if going_up {
236        car.bypass_load_up_pct()
237    } else {
238        car.bypass_load_down_pct()
239    };
240    let Some(pct) = threshold else {
241        return false;
242    };
243    let capacity = car.weight_capacity().value();
244    if capacity <= 0.0 {
245        return false;
246    }
247    let load_ratio = car.current_load().value() / capacity;
248    if load_ratio < pct {
249        return false;
250    }
251    // Only same-direction pickups get bypassed.
252    let stop_above = ctx.stop_position() > ctx.car_position();
253    let stop_below = ctx.stop_position() < ctx.car_position();
254    (going_up && stop_above) || (going_down && stop_below)
255}
256
257/// Metadata about a single rider, available to dispatch strategies.
258#[derive(Debug, Clone)]
259#[non_exhaustive]
260pub struct RiderInfo {
261    /// Rider entity ID.
262    pub id: EntityId,
263    /// Rider's destination stop entity (from route).
264    pub destination: Option<EntityId>,
265    /// Rider weight.
266    pub weight: Weight,
267    /// Ticks this rider has been waiting (0 if riding).
268    pub wait_ticks: u64,
269}
270
271/// Full demand picture for dispatch decisions.
272///
273/// Contains per-rider metadata grouped by stop, enabling entity-aware
274/// dispatch strategies (priority, weight-aware, VIP-first, etc.).
275///
276/// Uses `BTreeMap` for deterministic iteration order.
277#[derive(Debug, Clone, Default)]
278pub struct DispatchManifest {
279    /// Riders waiting at each stop, with full per-rider metadata.
280    pub(crate) waiting_at_stop: BTreeMap<EntityId, Vec<RiderInfo>>,
281    /// Riders currently aboard elevators, grouped by their destination stop.
282    pub(crate) riding_to_stop: BTreeMap<EntityId, Vec<RiderInfo>>,
283    /// Number of residents at each stop (read-only hint for dispatch strategies).
284    pub(crate) resident_count_at_stop: BTreeMap<EntityId, usize>,
285    /// Pending hall calls at each stop — at most two entries per stop
286    /// (one per [`CallDirection`]). Populated only for stops served by
287    /// the group being dispatched. Strategies read this to rank based on
288    /// call age, pending-rider count, pin flags, or DCS destinations.
289    pub(crate) hall_calls_at_stop: BTreeMap<EntityId, Vec<HallCall>>,
290    /// Floor buttons pressed inside each car in the group. Keyed by car
291    /// entity. Strategies read this to plan intermediate stops without
292    /// poking into `World` directly.
293    pub(crate) car_calls_by_car: BTreeMap<EntityId, Vec<CarCall>>,
294    /// Recent arrivals per stop, counted over
295    /// [`DispatchManifest::arrival_window_ticks`] ticks. Populated from
296    /// the [`crate::arrival_log::ArrivalLog`] world resource each pass
297    /// so strategies can read a traffic-rate signal without touching
298    /// world state directly.
299    pub(crate) arrivals_at_stop: BTreeMap<EntityId, u64>,
300    /// Window the `arrivals_at_stop` counts cover, in ticks. Exposed so
301    /// strategies interpreting the raw counts can convert them to a
302    /// rate (per tick or per second).
303    pub(crate) arrival_window_ticks: u64,
304}
305
306impl DispatchManifest {
307    /// Number of riders waiting at a stop.
308    #[must_use]
309    pub fn waiting_count_at(&self, stop: EntityId) -> usize {
310        self.waiting_at_stop.get(&stop).map_or(0, Vec::len)
311    }
312
313    /// Total weight of riders waiting at a stop.
314    #[must_use]
315    pub fn total_weight_at(&self, stop: EntityId) -> f64 {
316        self.waiting_at_stop
317            .get(&stop)
318            .map_or(0.0, |riders| riders.iter().map(|r| r.weight.value()).sum())
319    }
320
321    /// Number of riders heading to a stop (aboard elevators).
322    #[must_use]
323    pub fn riding_count_to(&self, stop: EntityId) -> usize {
324        self.riding_to_stop.get(&stop).map_or(0, Vec::len)
325    }
326
327    /// Whether a stop has any demand for this group: waiting riders,
328    /// riders heading there, or a *rider-less* hall call (one that
329    /// `press_hall_button` placed without a backing rider). Pre-fix
330    /// the rider-less case was invisible to every built-in dispatcher,
331    /// so explicit button presses with no associated rider went
332    /// unanswered indefinitely (#255).
333    ///
334    /// Hall calls *with* `pending_riders` are not double-counted —
335    /// those riders already appear in `waiting_count_at` for the
336    /// groups whose dispatch surface they belong to. Adding the call
337    /// to `has_demand` for *every* group that serves the stop would
338    /// pull cars from groups the rider doesn't even want, causing
339    /// open/close oscillation regression that the multi-group test
340    /// `dispatch_ignores_waiting_rider_targeting_another_group` pins.
341    #[must_use]
342    pub fn has_demand(&self, stop: EntityId) -> bool {
343        self.waiting_count_at(stop) > 0
344            || self.riding_count_to(stop) > 0
345            || self
346                .hall_calls_at_stop
347                .get(&stop)
348                .is_some_and(|calls| calls.iter().any(|c| c.pending_riders.is_empty()))
349    }
350
351    /// Number of residents at a stop (read-only hint, not active demand).
352    #[must_use]
353    pub fn resident_count_at(&self, stop: EntityId) -> usize {
354        self.resident_count_at_stop.get(&stop).copied().unwrap_or(0)
355    }
356
357    /// Rider arrivals at `stop` within the last
358    /// [`arrival_window_ticks`](Self::arrival_window_ticks) ticks. The
359    /// signal is the rolling-window per-stop arrival rate that
360    /// commercial controllers use to pick a traffic mode and that
361    /// [`crate::dispatch::reposition::PredictiveParking`] uses to
362    /// forecast demand. Unvisited stops return 0.
363    #[must_use]
364    pub fn arrivals_at(&self, stop: EntityId) -> u64 {
365        self.arrivals_at_stop.get(&stop).copied().unwrap_or(0)
366    }
367
368    /// Window size (in ticks) over which [`arrivals_at`](Self::arrivals_at)
369    /// counts events. Strategies convert counts to rates by dividing
370    /// by this.
371    #[must_use]
372    pub const fn arrival_window_ticks(&self) -> u64 {
373        self.arrival_window_ticks
374    }
375
376    /// The hall call at `(stop, direction)`, if pressed.
377    #[must_use]
378    pub fn hall_call_at(&self, stop: EntityId, direction: CallDirection) -> Option<&HallCall> {
379        self.hall_calls_at_stop
380            .get(&stop)?
381            .iter()
382            .find(|c| c.direction == direction)
383    }
384
385    /// All hall calls across every stop in the group (flattened iterator).
386    ///
387    /// No `#[must_use]` needed: `impl Iterator` already carries that
388    /// annotation, and adding our own triggers clippy's
389    /// `double_must_use` lint.
390    pub fn iter_hall_calls(&self) -> impl Iterator<Item = &HallCall> {
391        self.hall_calls_at_stop.values().flatten()
392    }
393
394    /// Floor buttons currently pressed inside `car`. Empty slice if the
395    /// car has no aboard riders or no outstanding presses.
396    #[must_use]
397    pub fn car_calls_for(&self, car: EntityId) -> &[CarCall] {
398        self.car_calls_by_car.get(&car).map_or(&[], Vec::as_slice)
399    }
400
401    /// Riders waiting at a specific stop.
402    #[must_use]
403    pub fn waiting_riders_at(&self, stop: EntityId) -> &[RiderInfo] {
404        self.waiting_at_stop.get(&stop).map_or(&[], Vec::as_slice)
405    }
406
407    /// Iterate over all `(stop, riders)` pairs with waiting demand.
408    pub fn iter_waiting_stops(&self) -> impl Iterator<Item = (&EntityId, &[RiderInfo])> {
409        self.waiting_at_stop
410            .iter()
411            .map(|(stop, riders)| (stop, riders.as_slice()))
412    }
413
414    /// Riders currently riding toward a specific stop.
415    #[must_use]
416    pub fn riding_riders_to(&self, stop: EntityId) -> &[RiderInfo] {
417        self.riding_to_stop.get(&stop).map_or(&[], Vec::as_slice)
418    }
419
420    /// Iterate over all `(stop, riders)` pairs with in-transit demand.
421    pub fn iter_riding_stops(&self) -> impl Iterator<Item = (&EntityId, &[RiderInfo])> {
422        self.riding_to_stop
423            .iter()
424            .map(|(stop, riders)| (stop, riders.as_slice()))
425    }
426
427    /// Iterate over all `(stop, hall_calls)` pairs with active calls.
428    pub fn iter_hall_call_stops(&self) -> impl Iterator<Item = (&EntityId, &[HallCall])> {
429        self.hall_calls_at_stop
430            .iter()
431            .map(|(stop, calls)| (stop, calls.as_slice()))
432    }
433}
434
435/// Serializable identifier for built-in dispatch strategies.
436///
437/// Used in snapshots and config files to restore the correct strategy
438/// without requiring the game to manually re-wire dispatch. Custom strategies
439/// are represented by the `Custom(String)` variant.
440#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
441#[non_exhaustive]
442pub enum BuiltinStrategy {
443    /// SCAN (elevator) algorithm — sweeps end-to-end.
444    Scan,
445    /// LOOK algorithm — reverses at last request.
446    Look,
447    /// Nearest-car — assigns closest idle elevator.
448    NearestCar,
449    /// Estimated Time to Destination — minimizes total cost.
450    Etd,
451    /// Hall-call destination dispatch — sticky per-rider assignment.
452    Destination,
453    /// Relative System Response — additive composite of ETA, direction,
454    /// car-call affinity, and load-share terms.
455    Rsr,
456    /// Custom strategy identified by name. The game must provide a factory.
457    Custom(String),
458}
459
460impl std::fmt::Display for BuiltinStrategy {
461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        match self {
463            Self::Scan => write!(f, "Scan"),
464            Self::Look => write!(f, "Look"),
465            Self::NearestCar => write!(f, "NearestCar"),
466            Self::Etd => write!(f, "Etd"),
467            Self::Destination => write!(f, "Destination"),
468            Self::Rsr => write!(f, "Rsr"),
469            Self::Custom(name) => write!(f, "Custom({name})"),
470        }
471    }
472}
473
474impl BuiltinStrategy {
475    /// Instantiate the dispatch strategy for this variant.
476    ///
477    /// Returns `None` for `Custom` — the game must provide those via
478    /// a factory function.
479    #[must_use]
480    pub fn instantiate(&self) -> Option<Box<dyn DispatchStrategy>> {
481        match self {
482            Self::Scan => Some(Box::new(scan::ScanDispatch::new())),
483            Self::Look => Some(Box::new(look::LookDispatch::new())),
484            Self::NearestCar => Some(Box::new(nearest_car::NearestCarDispatch::new())),
485            // `Default` ships the tuned stack (age-linear fairness term
486            // active); `new()` is the zero baseline for mutant/unit
487            // tests that isolate single terms. The playground's "ETD"
488            // dropdown entry should map to the strategy with fairness
489            // protection, not the raw version that lets the max-wait
490            // tail drift unbounded.
491            Self::Etd => Some(Box::new(etd::EtdDispatch::default())),
492            Self::Destination => Some(Box::new(destination::DestinationDispatch::new())),
493            // `Default` ships with the tuned penalty stack; `new()` is
494            // the zero baseline for additive-composition tests. The
495            // playground's "RSR" dropdown entry should map to the
496            // actual strategy, not to NearestCar-in-disguise, so use
497            // `Default` here.
498            Self::Rsr => Some(Box::new(rsr::RsrDispatch::default())),
499            Self::Custom(_) => None,
500        }
501    }
502}
503
504/// Decision returned by a dispatch strategy.
505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
506#[non_exhaustive]
507pub enum DispatchDecision {
508    /// Go to the specified stop entity.
509    GoToStop(EntityId),
510    /// Remain idle.
511    Idle,
512}
513
514/// Per-line relationship data within an [`ElevatorGroup`].
515///
516/// This is a denormalized cache maintained by [`Simulation`](crate::sim::Simulation).
517/// The source of truth for intrinsic line properties is the
518/// [`Line`](crate::components::Line) component in World.
519#[derive(Debug, Clone, Serialize, Deserialize)]
520pub struct LineInfo {
521    /// Line entity ID.
522    entity: EntityId,
523    /// Elevator entities on this line.
524    elevators: Vec<EntityId>,
525    /// Stop entities served by this line.
526    serves: Vec<EntityId>,
527}
528
529impl LineInfo {
530    /// Create a new `LineInfo`.
531    #[must_use]
532    pub const fn new(entity: EntityId, elevators: Vec<EntityId>, serves: Vec<EntityId>) -> Self {
533        Self {
534            entity,
535            elevators,
536            serves,
537        }
538    }
539
540    /// Line entity ID.
541    #[must_use]
542    pub const fn entity(&self) -> EntityId {
543        self.entity
544    }
545
546    /// Elevator entities on this line.
547    #[must_use]
548    pub fn elevators(&self) -> &[EntityId] {
549        &self.elevators
550    }
551
552    /// Stop entities served by this line.
553    #[must_use]
554    pub fn serves(&self) -> &[EntityId] {
555        &self.serves
556    }
557
558    /// Set the line entity ID (used during snapshot restore).
559    pub(crate) const fn set_entity(&mut self, entity: EntityId) {
560        self.entity = entity;
561    }
562
563    /// Add an elevator to this line, deduplicating against existing entries.
564    ///
565    /// Returns `true` if the elevator was inserted, `false` if it was
566    /// already present. Replaces direct `&mut Vec` access so callers
567    /// can't introduce duplicates the dedup invariants in
568    /// [`ElevatorGroup::rebuild_caches`] rely on.
569    pub(crate) fn add_elevator(&mut self, elevator: EntityId) -> bool {
570        if self.elevators.contains(&elevator) {
571            false
572        } else {
573            self.elevators.push(elevator);
574            true
575        }
576    }
577
578    /// Remove an elevator from this line.
579    ///
580    /// Returns `true` if the elevator was present and removed, `false`
581    /// if it was absent.
582    pub(crate) fn remove_elevator(&mut self, elevator: EntityId) -> bool {
583        let len_before = self.elevators.len();
584        self.elevators.retain(|&e| e != elevator);
585        self.elevators.len() != len_before
586    }
587
588    /// Add a stop to this line's served list, deduplicating against
589    /// existing entries.
590    ///
591    /// Returns `true` if the stop was inserted, `false` if it was
592    /// already present.
593    pub(crate) fn add_stop(&mut self, stop: EntityId) -> bool {
594        if self.serves.contains(&stop) {
595            false
596        } else {
597            self.serves.push(stop);
598            true
599        }
600    }
601
602    /// Remove a stop from this line's served list.
603    ///
604    /// Returns `true` if the stop was present and removed, `false`
605    /// if it was absent.
606    pub(crate) fn remove_stop(&mut self, stop: EntityId) -> bool {
607        let len_before = self.serves.len();
608        self.serves.retain(|&s| s != stop);
609        self.serves.len() != len_before
610    }
611}
612
613/// How hall calls expose rider destinations to dispatch.
614///
615/// Different building eras and controller designs reveal destinations
616/// at different moments. Groups pick a mode so the sim can model both
617/// traditional up/down collective-control elevators and modern
618/// destination-dispatch lobby kiosks within the same simulation.
619///
620/// Stops are expected to belong to exactly one group. When a stop
621/// overlaps multiple groups, the hall-call press consults the first
622/// group containing it (iteration order over
623/// [`Simulation::groups`](crate::sim::Simulation::groups)), which in
624/// turn determines the `HallCallMode` and ack latency applied to that
625/// call. Overlapping topologies are not validated at construction
626/// time; games that need them should be aware of this first-match
627/// rule.
628#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
629#[non_exhaustive]
630pub enum HallCallMode {
631    /// Traditional collective-control ("classic" Otis/Westinghouse).
632    ///
633    /// Riders press an up or down button in the hall; the destination
634    /// is revealed only *after* boarding, via a
635    /// [`CarCall`]. Dispatch sees a direction
636    /// per call but does not know individual rider destinations until
637    /// they're aboard.
638    #[default]
639    Classic,
640    /// Modern destination dispatch ("DCS" — Otis `CompassPlus`, KONE
641    /// Polaris, Schindler PORT).
642    ///
643    /// Riders enter their destination at a hall kiosk, so each
644    /// [`HallCall`] carries a destination
645    /// stop from the moment it's pressed. Required by
646    /// [`DestinationDispatch`].
647    Destination,
648}
649
650impl std::fmt::Display for HallCallMode {
651    /// ```
652    /// # use elevator_core::dispatch::HallCallMode;
653    /// assert_eq!(format!("{}", HallCallMode::Classic), "classic");
654    /// assert_eq!(format!("{}", HallCallMode::Destination), "destination");
655    /// ```
656    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
657        match self {
658            Self::Classic => f.write_str("classic"),
659            Self::Destination => f.write_str("destination"),
660        }
661    }
662}
663
664/// Runtime elevator group: a set of lines sharing a dispatch strategy.
665///
666/// A group is the logical dispatch unit. It contains one or more
667/// [`LineInfo`] entries, each representing a physical path with its
668/// elevators and served stops.
669///
670/// The flat `elevator_entities` and `stop_entities` fields are derived
671/// caches (union of all lines' elevators/stops), rebuilt automatically
672/// via [`rebuild_caches()`](Self::rebuild_caches).
673#[derive(Debug, Clone, Serialize, Deserialize)]
674pub struct ElevatorGroup {
675    /// Unique group identifier.
676    id: GroupId,
677    /// Human-readable group name.
678    name: String,
679    /// Lines belonging to this group.
680    lines: Vec<LineInfo>,
681    /// How hall calls reveal destinations to dispatch (Classic vs DCS).
682    hall_call_mode: HallCallMode,
683    /// Ticks between a button press and dispatch first seeing the call.
684    /// `0` = immediate (current behavior). Realistic values: 5–30 ticks
685    /// at 60 Hz, modeling controller processing latency.
686    ack_latency_ticks: u32,
687    /// Derived flat cache — rebuilt by `rebuild_caches()`.
688    elevator_entities: Vec<EntityId>,
689    /// Derived flat cache — rebuilt by `rebuild_caches()`.
690    stop_entities: Vec<EntityId>,
691}
692
693impl ElevatorGroup {
694    /// Create a new group with the given lines. Caches are built automatically.
695    /// Defaults: [`HallCallMode::Classic`], `ack_latency_ticks = 0`.
696    #[must_use]
697    pub fn new(id: GroupId, name: String, lines: Vec<LineInfo>) -> Self {
698        let mut group = Self {
699            id,
700            name,
701            lines,
702            hall_call_mode: HallCallMode::default(),
703            ack_latency_ticks: 0,
704            elevator_entities: Vec::new(),
705            stop_entities: Vec::new(),
706        };
707        group.rebuild_caches();
708        group
709    }
710
711    /// Override the hall call mode for this group.
712    #[must_use]
713    pub const fn with_hall_call_mode(mut self, mode: HallCallMode) -> Self {
714        self.hall_call_mode = mode;
715        self
716    }
717
718    /// Override the ack latency for this group.
719    #[must_use]
720    pub const fn with_ack_latency_ticks(mut self, ticks: u32) -> Self {
721        self.ack_latency_ticks = ticks;
722        self
723    }
724
725    /// Set the hall call mode in-place (for mutation via
726    /// [`Simulation::groups_mut`](crate::sim::Simulation::groups_mut)).
727    pub const fn set_hall_call_mode(&mut self, mode: HallCallMode) {
728        self.hall_call_mode = mode;
729    }
730
731    /// Set the ack latency in-place.
732    pub const fn set_ack_latency_ticks(&mut self, ticks: u32) {
733        self.ack_latency_ticks = ticks;
734    }
735
736    /// Hall call mode for this group.
737    #[must_use]
738    pub const fn hall_call_mode(&self) -> HallCallMode {
739        self.hall_call_mode
740    }
741
742    /// Controller ack latency for this group.
743    #[must_use]
744    pub const fn ack_latency_ticks(&self) -> u32 {
745        self.ack_latency_ticks
746    }
747
748    /// Unique group identifier.
749    #[must_use]
750    pub const fn id(&self) -> GroupId {
751        self.id
752    }
753
754    /// Human-readable group name.
755    #[must_use]
756    pub fn name(&self) -> &str {
757        &self.name
758    }
759
760    /// Lines belonging to this group.
761    #[must_use]
762    pub fn lines(&self) -> &[LineInfo] {
763        &self.lines
764    }
765
766    /// Mutable access to lines (call [`rebuild_caches()`](Self::rebuild_caches) after mutating).
767    pub const fn lines_mut(&mut self) -> &mut Vec<LineInfo> {
768        &mut self.lines
769    }
770
771    /// Elevator entities belonging to this group (derived from lines).
772    #[must_use]
773    pub fn elevator_entities(&self) -> &[EntityId] {
774        &self.elevator_entities
775    }
776
777    /// Stop entities served by this group (derived from lines, deduplicated).
778    #[must_use]
779    pub fn stop_entities(&self) -> &[EntityId] {
780        &self.stop_entities
781    }
782
783    /// Whether this group can serve a rider on `leg`. A `Group(g)` leg
784    /// matches by group id; a `Line(l)` leg matches if `l` belongs to
785    /// this group; `Walk` never rides an elevator.
786    #[must_use]
787    pub fn accepts_leg(&self, leg: &crate::components::RouteLeg) -> bool {
788        match leg.via {
789            crate::components::TransportMode::Group(g) => g == self.id,
790            crate::components::TransportMode::Line(l) => {
791                self.lines.iter().any(|li| li.entity() == l)
792            }
793            crate::components::TransportMode::Walk => false,
794        }
795    }
796
797    /// Push a stop entity directly into the group's stop cache.
798    ///
799    /// Use when a stop belongs to the group for dispatch purposes but is
800    /// not (yet) assigned to any line. Call `add_stop_to_line` later to
801    /// wire it into the topology graph.
802    pub(crate) fn push_stop(&mut self, stop: EntityId) {
803        if !self.stop_entities.contains(&stop) {
804            self.stop_entities.push(stop);
805        }
806    }
807
808    /// Push an elevator entity directly into the group's elevator cache
809    /// (in addition to the line it belongs to).
810    pub(crate) fn push_elevator(&mut self, elevator: EntityId) {
811        if !self.elevator_entities.contains(&elevator) {
812            self.elevator_entities.push(elevator);
813        }
814    }
815
816    /// Rebuild derived caches from lines. Call after mutating lines.
817    pub fn rebuild_caches(&mut self) {
818        self.elevator_entities = self
819            .lines
820            .iter()
821            .flat_map(|li| li.elevators.iter().copied())
822            .collect();
823        let mut stops: Vec<EntityId> = self
824            .lines
825            .iter()
826            .flat_map(|li| li.serves.iter().copied())
827            .collect();
828        stops.sort_unstable();
829        stops.dedup();
830        self.stop_entities = stops;
831    }
832}
833
834/// Look up the `serves` list for an elevator's line.
835///
836/// Walks `groups` to find the [`LineInfo`] whose entity matches the
837/// car's current `line()`. Returns `None` if the car has no line
838/// registered in any group (an inconsistent state — should be
839/// unreachable in a healthy sim).
840///
841/// Helper for callers of
842/// [`World::find_stop_at_position_in`](crate::world::World::find_stop_at_position_in)
843/// that already have group context: `find_stop_at_position(pos)` is
844/// global (any line wins) and ambiguous when two lines share a
845/// position; passing the elevator's serves list scopes the lookup to
846/// *its* line.
847///
848/// Cost: `O(groups × lines_per_group)` per call. For loops over many
849/// elevators per tick, prefer [`build_line_serves_index`] +
850/// [`elevator_line_serves_indexed`] to amortize the line walk.
851#[must_use]
852pub fn elevator_line_serves<'a>(
853    world: &World,
854    groups: &'a [ElevatorGroup],
855    elevator: EntityId,
856) -> Option<&'a [EntityId]> {
857    let line_eid = world.elevator(elevator)?.line();
858    groups
859        .iter()
860        .flat_map(ElevatorGroup::lines)
861        .find(|li| li.entity() == line_eid)
862        .map(LineInfo::serves)
863}
864
865/// Pre-built index mapping each line entity to its `serves` slice.
866/// Built once with [`build_line_serves_index`]; queried with
867/// [`elevator_line_serves_indexed`] for O(1) per-elevator lookup.
868pub type LineServesIndex<'a> = std::collections::HashMap<EntityId, &'a [EntityId]>;
869
870/// Build a [`LineServesIndex`] from the group list. O(groups × lines).
871/// Call once per substep / system and reuse across the elevator loop.
872#[must_use]
873pub fn build_line_serves_index(groups: &[ElevatorGroup]) -> LineServesIndex<'_> {
874    let mut idx: LineServesIndex<'_> = std::collections::HashMap::new();
875    for li in groups.iter().flat_map(ElevatorGroup::lines) {
876        idx.insert(li.entity(), li.serves());
877    }
878    idx
879}
880
881/// Indexed variant of [`elevator_line_serves`]. O(1) per call given
882/// a pre-built [`LineServesIndex`].
883#[must_use]
884pub fn elevator_line_serves_indexed<'a>(
885    world: &World,
886    index: &LineServesIndex<'a>,
887    elevator: EntityId,
888) -> Option<&'a [EntityId]> {
889    let line_eid = world.elevator(elevator)?.line();
890    index.get(&line_eid).copied()
891}
892
893/// Context passed to [`DispatchStrategy::rank`].
894///
895/// Bundles the per-call arguments into a single struct so future context
896/// fields can be added without breaking existing trait implementations.
897#[non_exhaustive]
898pub struct RankContext<'a> {
899    /// The elevator being evaluated.
900    pub car: EntityId,
901    /// The stop being evaluated as a candidate destination.
902    pub stop: EntityId,
903    /// The dispatch group this assignment belongs to.
904    pub group: &'a ElevatorGroup,
905    /// Demand snapshot for the current dispatch pass.
906    pub manifest: &'a DispatchManifest,
907    /// Read-only world state.
908    pub world: &'a World,
909}
910
911impl RankContext<'_> {
912    /// Position of [`car`](Self::car) along the shaft axis.
913    ///
914    /// Returns `0.0` for an entity that has no `Position` component
915    /// (which would never reach this method through normal dispatch
916    /// — `compute_assignments` filters out cars without positions
917    /// upstream — but the defensive default protects custom callers).
918    /// Derived from [`world`](Self::world) on each call: the dispatch
919    /// loop never moves elevators between rank calls, so re-deriving
920    /// is free, and skipping the duplicate field eliminates the
921    /// synchronisation risk of the old shape.
922    #[must_use]
923    pub fn car_position(&self) -> f64 {
924        self.world.position(self.car).map_or(0.0, |p| p.value)
925    }
926
927    /// Position of [`stop`](Self::stop) along the shaft axis.
928    ///
929    /// Returns `0.0` for an entity that has no `Stop` component (same
930    /// rationale as [`car_position`](Self::car_position)).
931    #[must_use]
932    pub fn stop_position(&self) -> f64 {
933        self.world.stop_position(self.stop).unwrap_or(0.0)
934    }
935}
936
937impl std::fmt::Debug for RankContext<'_> {
938    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
939        f.debug_struct("RankContext")
940            .field("car", &self.car)
941            .field("car_position", &self.car_position())
942            .field("stop", &self.stop)
943            .field("stop_position", &self.stop_position())
944            .field("group", &self.group)
945            .field("manifest", &self.manifest)
946            .field("world", &"World { .. }")
947            .finish()
948    }
949}
950
951/// Pluggable dispatch algorithm.
952///
953/// Strategies implement [`rank`](Self::rank) to score each `(car, stop)`
954/// pair; the dispatch system then performs an optimal assignment across
955/// the whole group, guaranteeing that no two cars are sent to the same
956/// hall call.
957///
958/// Returning `None` from `rank` excludes a pair from assignment — useful
959/// for capacity limits, direction preferences, restricted stops, or
960/// sticky commitments.
961///
962/// Cars that receive no stop fall through to [`fallback`](Self::fallback),
963/// which returns the policy for that car (idle, park, etc.).
964pub trait DispatchStrategy: Send + Sync {
965    /// Optional hook called once per group before the assignment pass.
966    ///
967    /// Strategies that need to mutate [`World`] extension storage (e.g.
968    /// [`DestinationDispatch`] writing sticky rider → car assignments)
969    /// or pre-populate [`crate::components::DestinationQueue`] entries
970    /// override this. Default: no-op.
971    fn pre_dispatch(
972        &mut self,
973        _group: &ElevatorGroup,
974        _manifest: &DispatchManifest,
975        _world: &mut World,
976    ) {
977    }
978
979    /// Optional hook called once per candidate car, before any
980    /// [`rank`](Self::rank) calls for that car in the current pass.
981    ///
982    /// Strategies whose ranking depends on stable per-car state (e.g. the
983    /// sweep direction used by SCAN/LOOK) set that state here so later
984    /// `rank` calls see a consistent view regardless of iteration order.
985    /// The default is a no-op.
986    fn prepare_car(
987        &mut self,
988        _car: EntityId,
989        _car_position: f64,
990        _group: &ElevatorGroup,
991        _manifest: &DispatchManifest,
992        _world: &World,
993    ) {
994    }
995
996    /// Score the cost of sending `car` to `stop`. Lower is better.
997    ///
998    /// Returning `None` marks this `(car, stop)` pair as unavailable;
999    /// the assignment algorithm will never pair them. Use this for
1000    /// capacity limits, wrong-direction stops, stops outside the line's
1001    /// topology, or pairs already committed via a sticky assignment.
1002    ///
1003    /// Must return a finite, non-negative value if `Some` — infinities
1004    /// and NaN can destabilize the underlying Hungarian solver.
1005    ///
1006    /// Takes `&self` so the assignment loop can score `(car, stop)` pairs
1007    /// in any order without producing an asymmetric cost matrix. Compute
1008    /// any per-car scratch in [`prepare_car`](Self::prepare_car) (which
1009    /// takes `&mut self`) before this method is called.
1010    fn rank(&self, ctx: &RankContext<'_>) -> Option<f64>;
1011
1012    /// Decide what an idle car should do when no stop was assigned to it.
1013    ///
1014    /// Called for each car the assignment phase could not pair with a
1015    /// stop (because there were no stops, or all candidate stops had
1016    /// rank `None` for this car). Default: [`DispatchDecision::Idle`].
1017    fn fallback(
1018        &mut self,
1019        _car: EntityId,
1020        _car_position: f64,
1021        _group: &ElevatorGroup,
1022        _manifest: &DispatchManifest,
1023        _world: &World,
1024    ) -> DispatchDecision {
1025        DispatchDecision::Idle
1026    }
1027
1028    /// Notify the strategy that an elevator has been removed.
1029    ///
1030    /// Implementations with per-elevator state (e.g. direction tracking)
1031    /// should clean up here to prevent unbounded memory growth.
1032    fn notify_removed(&mut self, _elevator: EntityId) {}
1033
1034    /// If this strategy is a known built-in variant, return it so
1035    /// [`Simulation::new`](crate::sim::Simulation::new) can stamp the
1036    /// correct [`BuiltinStrategy`] into the group's snapshot identity.
1037    ///
1038    /// Without this, legacy-topology sims constructed via
1039    /// `Simulation::new(config, SomeNonScanStrategy::new())` silently
1040    /// recorded `BuiltinStrategy::Scan` as their identity — so a
1041    /// snapshot round-trip replaced the running strategy with Scan
1042    /// and produced different dispatch decisions post-restore
1043    /// (determinism regression).
1044    ///
1045    /// Default: `None` (unidentified — the constructor falls back to
1046    /// recording [`BuiltinStrategy::Scan`], matching pre-fix behaviour
1047    /// for callers that never cared about round-trip identity). Custom
1048    /// strategies that DO care should override this to return
1049    /// [`BuiltinStrategy::Custom`] with a stable name.
1050    #[must_use]
1051    fn builtin_id(&self) -> Option<BuiltinStrategy> {
1052        None
1053    }
1054
1055    /// Serialize this strategy's tunable configuration to a string
1056    /// that [`restore_config`](Self::restore_config) can apply to a
1057    /// freshly-instantiated instance.
1058    ///
1059    /// Returning `Some(..)` makes the configuration survive snapshot
1060    /// round-trip: without it, [`crate::snapshot::WorldSnapshot::restore`]
1061    /// instantiates each built-in via [`BuiltinStrategy::instantiate`],
1062    /// which calls `::new()` with default weights — silently dropping
1063    /// any tuning applied via `with_*` builder methods (e.g.
1064    /// `EtdDispatch::with_delay_weight(2.5)` degrades to the default
1065    /// `1.0` on the restored sim).
1066    ///
1067    /// Default: `None` (no configuration to save). Built-ins with
1068    /// tunable weights override to return a RON-serialized copy of
1069    /// themselves; strategies with transient per-pass scratch should
1070    /// use `#[serde(skip)]` on those fields so the snapshot stays
1071    /// compact and deterministic.
1072    #[must_use]
1073    fn snapshot_config(&self) -> Option<String> {
1074        None
1075    }
1076
1077    /// Restore tunable configuration from a string previously produced
1078    /// by [`snapshot_config`](Self::snapshot_config) on the same
1079    /// strategy variant. Called by
1080    /// [`crate::snapshot::WorldSnapshot::restore`] immediately after
1081    /// [`BuiltinStrategy::instantiate`] builds the default instance,
1082    /// so the restore writes over the defaults.
1083    ///
1084    /// # Errors
1085    /// Returns the underlying parse error as a `String` when the
1086    /// serialized form doesn't round-trip. Default implementation
1087    /// ignores the argument and returns `Ok(())` — paired with the
1088    /// `None` default of `snapshot_config`, this means strategies that
1089    /// don't override either method skip configuration round-trip,
1090    /// matching pre-fix behaviour.
1091    fn restore_config(&mut self, _serialized: &str) -> Result<(), String> {
1092        Ok(())
1093    }
1094}
1095
1096/// Resolution of a single dispatch assignment pass for one group.
1097///
1098/// Produced by `assign` and consumed by
1099/// `crate::systems::dispatch::run` to apply decisions to the world.
1100#[derive(Debug, Clone)]
1101pub struct AssignmentResult {
1102    /// `(car, decision)` pairs for every idle car in the group.
1103    pub decisions: Vec<(EntityId, DispatchDecision)>,
1104}
1105
1106/// Per-simulation scratch buffers for the dispatch phase.
1107///
1108/// Every field is a `Vec`/`HashSet` whose allocations the hot path
1109/// would otherwise re-take on every tick per group (cost matrix
1110/// backing store, pending-stops list, servicing cars, pinned /
1111/// committed / idle-elevator filters). Owning them on the
1112/// simulation lets each dispatch pass `clear()` them in place and
1113/// reuse the capacity — on a 50-car × 200-stop group the cost matrix
1114/// alone is ~80 KB of heap churn per tick, and at the 500-car
1115/// `scaling_extreme` scale it's ~20 MB.
1116///
1117/// The scratch is always cleared before use; consumers should not
1118/// rely on any carry-over content between groups or ticks.
1119#[derive(Default)]
1120pub(crate) struct DispatchScratch {
1121    /// Reusable `Matrix<i64>` the Hungarian consumes by reference. When
1122    /// the dispatch pass can reuse the stored Matrix (`rows × cols`
1123    /// match), this is `Some` and gets filled in-place via `Matrix::fill`;
1124    /// when shapes change the slot is replaced with `Matrix::new`.
1125    pub cost_matrix_mx: Option<pathfinding::matrix::Matrix<i64>>,
1126    /// `(stop, line, remaining_capacity)` for door-cycling cars, used
1127    /// by `pending_stops_minus_covered` to avoid double-dispatching
1128    /// stops a car is already servicing.
1129    pub servicing: Vec<(EntityId, EntityId, f64)>,
1130    /// Stops with live demand, returned from `pending_stops_minus_covered`.
1131    pub pending_stops: Vec<(EntityId, f64)>,
1132    /// Aboard-rider destinations across idle cars — consulted so a
1133    /// stop that a car aboard wants to reach stays pickup-eligible.
1134    pub idle_rider_destinations: HashSet<EntityId>,
1135    /// Per-stop linestamp buffer reused inside `is_covered`.
1136    pub lines_here: Vec<EntityId>,
1137    /// Pinned hall-call `(car, stop)` pairs for the current group.
1138    pub pinned_pairs: Vec<(EntityId, EntityId)>,
1139    /// Committed `(car, target)` pairs — mid-flight cars whose trip
1140    /// still has demand; held out of the Hungarian idle pool.
1141    pub committed_pairs: Vec<(EntityId, EntityId)>,
1142    /// Idle elevator pool `(car, position)` for this group.
1143    pub idle_elevators: Vec<(EntityId, f64)>,
1144}
1145
1146impl DispatchScratch {
1147    /// Clear every buffer without freeing its backing capacity.
1148    ///
1149    /// `cost_matrix_mx` is re-sized/re-filled lazily in
1150    /// `assign_with_scratch`; leaving it alone here preserves its
1151    /// capacity when the group's (rows, cols) match the last
1152    /// dispatch pass.
1153    pub fn clear_all(&mut self) {
1154        self.servicing.clear();
1155        self.pending_stops.clear();
1156        self.idle_rider_destinations.clear();
1157        self.lines_here.clear();
1158        self.pinned_pairs.clear();
1159        self.committed_pairs.clear();
1160        self.idle_elevators.clear();
1161    }
1162}
1163
1164/// Sentinel weight used to pad unavailable `(car, stop)` pairs when
1165/// building the cost matrix for the Hungarian solver. Chosen so that
1166/// `n · SENTINEL` can't overflow `i64`: the Kuhn–Munkres implementation
1167/// sums weights and potentials across each row/column internally, so
1168/// headroom of ~2¹⁵ above the sentinel lets groups scale past 30 000
1169/// cars or stops before any arithmetic risk appears.
1170const ASSIGNMENT_SENTINEL: i64 = 1 << 48;
1171/// Fixed-point scale for converting `f64` costs to the `i64` values the
1172/// Hungarian solver requires. One unit ≈ one micro-tick / millimeter:
1173/// the smallest meaningful rank delta is sub-tick / sub-millimeter, so
1174/// scaling by 1e6 keeps that delta as a 1-unit `i64` difference and
1175/// preserves the strategy's tie-breaking precision through the cast.
1176const ASSIGNMENT_SCALE: f64 = 1_000_000.0;
1177
1178/// Convert a `f64` rank cost into the fixed-point `i64` the Hungarian
1179/// solver consumes. Non-finite, negative, or overflow-prone inputs map
1180/// to the unavailable sentinel.
1181fn scale_cost(cost: f64) -> i64 {
1182    if !cost.is_finite() || cost < 0.0 {
1183        debug_assert!(
1184            cost.is_finite() && cost >= 0.0,
1185            "DispatchStrategy::rank() returned invalid cost {cost}; must be finite and non-negative"
1186        );
1187        return ASSIGNMENT_SENTINEL;
1188    }
1189    // Cap at just below sentinel so any real rank always beats unavailable.
1190    (cost * ASSIGNMENT_SCALE)
1191        .round()
1192        .clamp(0.0, (ASSIGNMENT_SENTINEL - 1) as f64) as i64
1193}
1194
1195/// Build the pending-demand stop list, subtracting stops whose
1196/// demand is already being absorbed by a car — either currently in
1197/// its door cycle at the stop, or en route via `MovingToStop`.
1198///
1199/// Both phases count as "servicing" because they represent a
1200/// commitment to open doors at the target with remaining capacity
1201/// that waiting riders can (typically) fit into. Without the
1202/// `MovingToStop` case, a new idle car becoming available during
1203/// car A's trip to the lobby gets paired with the same lobby call
1204/// on the next dispatch tick — car B travels empty behind car A
1205/// and the playground shows two cars doing a lobby touch-and-go
1206/// for one rider. Composes with the commitment set in
1207/// [`systems::dispatch`](crate::systems::dispatch), which excludes
1208/// committed cars from the idle pool at the same time.
1209///
1210/// `Stopped` (parked-with-doors-closed) is deliberately *not* in
1211/// the list: that's a legitimately reassignable state.
1212/// `Repositioning` is also excluded — a repositioning car doesn't
1213/// open doors on arrival, so it cannot absorb waiting riders.
1214///
1215/// Line-pinned riders (`TransportMode::Line(L)`) keep a stop
1216/// pending even when a car is present, because a car on Shaft A
1217/// can't absorb a rider pinned to Shaft B. Coverage also fails
1218/// when the waiting riders' combined weight exceeds the servicing
1219/// car's remaining capacity — the leftover spills out when doors
1220/// close and deserves its own dispatch immediately.
1221fn pending_stops_minus_covered(
1222    group: &ElevatorGroup,
1223    manifest: &DispatchManifest,
1224    world: &World,
1225    idle_cars: &[(EntityId, f64)],
1226    scratch: &mut DispatchScratch,
1227) {
1228    // Refill `scratch.servicing` in place — the buffer survives across
1229    // ticks so the hot path doesn't reallocate per group.
1230    scratch.servicing.clear();
1231    for &eid in group.elevator_entities() {
1232        let Some(car) = world.elevator(eid) else {
1233            continue;
1234        };
1235        let Some(target) = car.target_stop() else {
1236            continue;
1237        };
1238        if !matches!(
1239            car.phase(),
1240            ElevatorPhase::MovingToStop(_)
1241                | ElevatorPhase::DoorOpening
1242                | ElevatorPhase::Loading
1243                | ElevatorPhase::DoorClosing
1244        ) {
1245            continue;
1246        }
1247        let remaining = car.weight_capacity().value() - car.current_load().value();
1248        scratch.servicing.push((target, car.line(), remaining));
1249    }
1250
1251    // Aboard-rider destinations — reused buffer, same owned semantics.
1252    scratch.idle_rider_destinations.clear();
1253    for &(car_eid, _) in idle_cars {
1254        if let Some(car) = world.elevator(car_eid) {
1255            for &rid in car.riders() {
1256                if let Some(dest) = world.route(rid).and_then(Route::current_destination) {
1257                    scratch.idle_rider_destinations.insert(dest);
1258                }
1259            }
1260        }
1261    }
1262
1263    // A stop is "covered" iff every waiting rider this group sees can
1264    // board at least one of the door-cycling cars here (line check)
1265    // AND the combined remaining capacity of the cars whose line
1266    // accepts the rider is enough to board them all (capacity check).
1267    //
1268    // Iterates `manifest.waiting_riders_at` rather than `world.iter_riders`
1269    // so `TransportMode::Walk` riders and cross-group-routed riders
1270    // (excluded by `build_manifest`) don't inflate the weight total.
1271    // `lines_here` is the same `scratch.lines_here` buffer each call —
1272    // cleared then refilled — so coverage checks don't churn the
1273    // allocator per stop.
1274    let mut lines_here: Vec<EntityId> = std::mem::take(&mut scratch.lines_here);
1275    let servicing = &scratch.servicing;
1276    let is_covered = |stop_eid: EntityId, lines_here: &mut Vec<EntityId>| -> bool {
1277        lines_here.clear();
1278        let mut capacity_here = 0.0;
1279        for &(stop, line, rem) in servicing {
1280            if stop == stop_eid {
1281                lines_here.push(line);
1282                capacity_here += rem;
1283            }
1284        }
1285        if lines_here.is_empty() {
1286            return false;
1287        }
1288        let mut total_weight = 0.0;
1289        for rider in manifest.waiting_riders_at(stop_eid) {
1290            let required_line = world
1291                .route(rider.id)
1292                .and_then(Route::current)
1293                .and_then(|leg| match leg.via {
1294                    TransportMode::Line(l) => Some(l),
1295                    _ => None,
1296                });
1297            if let Some(required) = required_line
1298                && !lines_here.contains(&required)
1299            {
1300                return false;
1301            }
1302            total_weight += rider.weight.value();
1303        }
1304        total_weight <= capacity_here
1305    };
1306
1307    scratch.pending_stops.clear();
1308    for &stop in group.stop_entities() {
1309        if !manifest.has_demand(stop) {
1310            continue;
1311        }
1312        let keep =
1313            scratch.idle_rider_destinations.contains(&stop) || !is_covered(stop, &mut lines_here);
1314        if !keep {
1315            continue;
1316        }
1317        if let Some(pos) = world.stop_position(stop) {
1318            scratch.pending_stops.push((stop, pos));
1319        }
1320    }
1321    // Return the lines_here buffer to scratch so its capacity survives.
1322    scratch.lines_here = lines_here;
1323}
1324
1325/// Run one group's assignment pass: build the cost matrix, solve the
1326/// optimal bipartite matching, then resolve unassigned cars via
1327/// [`DispatchStrategy::fallback`].
1328///
1329/// Visible to the `systems` module; not part of the public API.
1330/// Back-compat wrapper that allocates a throw-away scratch for
1331/// tests and one-off callers. Production paths (in
1332/// `crate::systems::dispatch::run`) must use
1333/// [`assign_with_scratch`] so the scratch capacity amortises
1334/// across ticks.
1335#[cfg(test)]
1336pub(crate) fn assign(
1337    strategy: &mut dyn DispatchStrategy,
1338    idle_cars: &[(EntityId, f64)],
1339    group: &ElevatorGroup,
1340    manifest: &DispatchManifest,
1341    world: &World,
1342) -> AssignmentResult {
1343    let mut scratch = DispatchScratch::default();
1344    assign_with_scratch(strategy, idle_cars, group, manifest, world, &mut scratch)
1345}
1346
1347/// Run one group's assignment pass: build the cost matrix, solve the
1348/// optimal bipartite matching, then resolve unassigned cars via
1349/// [`DispatchStrategy::fallback`]. Uses `scratch` so the per-tick
1350/// allocations (cost matrix, pending stops, etc.) reuse capacity
1351/// across invocations.
1352pub(crate) fn assign_with_scratch(
1353    strategy: &mut dyn DispatchStrategy,
1354    idle_cars: &[(EntityId, f64)],
1355    group: &ElevatorGroup,
1356    manifest: &DispatchManifest,
1357    world: &World,
1358    scratch: &mut DispatchScratch,
1359) -> AssignmentResult {
1360    // Fill `scratch.pending_stops` in place. The buffer's capacity
1361    // survives across ticks.
1362    pending_stops_minus_covered(group, manifest, world, idle_cars, scratch);
1363
1364    let n = idle_cars.len();
1365    let m = scratch.pending_stops.len();
1366
1367    if n == 0 {
1368        return AssignmentResult {
1369            decisions: Vec::new(),
1370        };
1371    }
1372
1373    let mut decisions: Vec<(EntityId, DispatchDecision)> = Vec::with_capacity(n);
1374
1375    if m == 0 {
1376        for &(eid, pos) in idle_cars {
1377            let d = strategy.fallback(eid, pos, group, manifest, world);
1378            decisions.push((eid, d));
1379        }
1380        return AssignmentResult { decisions };
1381    }
1382
1383    // Hungarian requires rows <= cols. Reuse the scratch `Matrix` when
1384    // the shape matches the previous dispatch pass — on a realistic
1385    // building the (rows, cols) tuple changes only when the car or
1386    // stop count does, so steady-state dispatch avoids any heap
1387    // traffic for the cost matrix at all. When the shape does change,
1388    // a fresh Matrix replaces the stored one and becomes the new
1389    // reusable buffer going forward.
1390    let cols = n.max(m);
1391    match &mut scratch.cost_matrix_mx {
1392        Some(mx) if mx.rows == n && mx.columns == cols => {
1393            mx.fill(ASSIGNMENT_SENTINEL);
1394        }
1395        slot => {
1396            *slot = Some(pathfinding::matrix::Matrix::new(
1397                n,
1398                cols,
1399                ASSIGNMENT_SENTINEL,
1400            ));
1401        }
1402    }
1403    let matrix_ref = scratch
1404        .cost_matrix_mx
1405        .as_mut()
1406        .unwrap_or_else(|| unreachable!("cost_matrix_mx populated by match above"));
1407
1408    {
1409        let pending_stops = &scratch.pending_stops;
1410        for (i, &(car_eid, car_pos)) in idle_cars.iter().enumerate() {
1411            strategy.prepare_car(car_eid, car_pos, group, manifest, world);
1412            // Borrow the car's restricted-stops set for this row so each
1413            // (car, stop) pair can short-circuit before calling rank().
1414            // Pre-fix only DCS consulted restricted_stops; SCAN/LOOK/NC/ETD
1415            // happily ranked restricted pairs and `commit_go_to_stop` later
1416            // silently dropped the assignment, starving the call. (#256)
1417            let restricted = world
1418                .elevator(car_eid)
1419                .map(crate::components::Elevator::restricted_stops);
1420
1421            // The car's line's `serves` list is the set of stops it can
1422            // physically reach. In a single-line group every stop is
1423            // served (filter is a no-op); in a multi-line group (e.g.
1424            // sky-lobby + service bank, low/high banks sharing a
1425            // transfer floor) a car on line A must not be assigned to
1426            // a stop only line B serves — it would commit, sit there
1427            // unable to reach, and starve the call. The pre-fix matrix
1428            // happily ranked such cross-line pairs because no other
1429            // gate caught them: `restricted_stops` is for explicit
1430            // access denials, `pending_stops_minus_covered` filters
1431            // stops not cars, and built-in strategies score on
1432            // distance/direction without consulting line topology.
1433            let car_serves: Option<&[EntityId]> = world
1434                .elevator(car_eid)
1435                .map(crate::components::Elevator::line)
1436                .and_then(|line_eid| {
1437                    group
1438                        .lines()
1439                        .iter()
1440                        .find(|li| li.entity() == line_eid)
1441                        .map(LineInfo::serves)
1442                });
1443            // `None` here means the car's line isn't in this group's
1444            // line list — a topology inconsistency that should be
1445            // unreachable. We can't fail the dispatch tick over it (the
1446            // sim still has to make progress), so the filter falls
1447            // open: the car is treated as if it could reach any stop.
1448            // The debug-assert catches it during testing without
1449            // affecting release builds.
1450            debug_assert!(
1451                world.elevator(car_eid).is_none() || car_serves.is_some(),
1452                "car {car_eid:?} on line not present in its group's lines list"
1453            );
1454
1455            for (j, &(stop_eid, _stop_pos)) in pending_stops.iter().enumerate() {
1456                if restricted.is_some_and(|r| r.contains(&stop_eid)) {
1457                    continue; // leave SENTINEL — this pair is unavailable
1458                }
1459                if car_serves.is_some_and(|s| !s.contains(&stop_eid)) {
1460                    continue; // car's line doesn't reach this stop
1461                }
1462                let ctx = RankContext {
1463                    car: car_eid,
1464                    stop: stop_eid,
1465                    group,
1466                    manifest,
1467                    world,
1468                };
1469                let scaled = strategy.rank(&ctx).map_or(ASSIGNMENT_SENTINEL, scale_cost);
1470                matrix_ref[(i, j)] = scaled;
1471            }
1472        }
1473    }
1474    let matrix = &*matrix_ref;
1475    let (_, assignments) = pathfinding::kuhn_munkres::kuhn_munkres_min(matrix);
1476
1477    for (i, &(car_eid, car_pos)) in idle_cars.iter().enumerate() {
1478        let col = assignments[i];
1479        // A real assignment is: col points to a real stop (col < m) AND
1480        // the cost isn't sentinel-padded (meaning rank() returned Some).
1481        if col < m && matrix[(i, col)] < ASSIGNMENT_SENTINEL {
1482            let (stop_eid, _) = scratch.pending_stops[col];
1483            decisions.push((car_eid, DispatchDecision::GoToStop(stop_eid)));
1484        } else {
1485            let d = strategy.fallback(car_eid, car_pos, group, manifest, world);
1486            decisions.push((car_eid, d));
1487        }
1488    }
1489
1490    AssignmentResult { decisions }
1491}
1492
1493/// Pluggable strategy for repositioning idle elevators.
1494///
1495/// After the dispatch phase, elevators that remain idle (no pending
1496/// assignments) are candidates for repositioning. The strategy decides
1497/// where each idle elevator should move to improve coverage and reduce
1498/// expected response times.
1499///
1500/// Implementations receive the set of idle elevator positions and the
1501/// group's stop positions, then return a target stop for each elevator
1502/// (or `None` to leave it in place).
1503pub trait RepositionStrategy: Send + Sync {
1504    /// Decide where to reposition idle elevators.
1505    ///
1506    /// Push `(elevator_entity, target_stop_entity)` pairs into `out`.
1507    /// The buffer is cleared before each call — implementations should
1508    /// only push, never read prior contents. Elevators not pushed remain idle.
1509    fn reposition(
1510        &mut self,
1511        idle_elevators: &[(EntityId, f64)],
1512        stop_positions: &[(EntityId, f64)],
1513        group: &ElevatorGroup,
1514        world: &World,
1515        out: &mut Vec<(EntityId, EntityId)>,
1516    );
1517
1518    /// If this strategy is a known built-in variant, return it so
1519    /// [`Simulation::set_reposition`](crate::sim::Simulation::set_reposition)
1520    /// callers don't have to pass a separate [`BuiltinReposition`] id
1521    /// that might drift from the dispatcher's actual type.
1522    ///
1523    /// Mirrors the pattern introduced for [`DispatchStrategy::builtin_id`]
1524    /// in #410: the runtime impl identifies itself so the snapshot
1525    /// identity always matches the executing behaviour, instead of
1526    /// depending on the caller to keep two parameters consistent.
1527    /// Default `None` — custom strategies should override to return
1528    /// [`BuiltinReposition::Custom`] with a stable name for snapshot
1529    /// fidelity.
1530    #[must_use]
1531    fn builtin_id(&self) -> Option<BuiltinReposition> {
1532        None
1533    }
1534
1535    /// Minimum [`ArrivalLog`](crate::arrival_log::ArrivalLog) retention
1536    /// (in ticks) the strategy needs to function. Strategies that read
1537    /// the log directly with a custom rolling window must override this
1538    /// so [`Simulation::set_reposition`](crate::sim::Simulation::set_reposition)
1539    /// can widen
1540    /// [`ArrivalLogRetention`](crate::arrival_log::ArrivalLogRetention)
1541    /// to keep the data alive long enough for the query.
1542    ///
1543    /// Default `0` — strategies that don't read the arrival log (or that
1544    /// only consume it through [`DispatchManifest::arrivals_at`], which
1545    /// already tracks retention) impose no requirement.
1546    #[must_use]
1547    fn min_arrival_log_window(&self) -> u64 {
1548        0
1549    }
1550}
1551
1552/// Serializable identifier for built-in repositioning strategies.
1553///
1554/// Used in config and snapshots to restore the correct strategy.
1555#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1556#[non_exhaustive]
1557pub enum BuiltinReposition {
1558    /// Distribute idle elevators evenly across stops.
1559    SpreadEvenly,
1560    /// Return idle elevators to a configured home stop.
1561    ReturnToLobby,
1562    /// Position near stops with historically high demand.
1563    DemandWeighted,
1564    /// Keep idle elevators where they are (no-op).
1565    NearestIdle,
1566    /// Pre-position cars near stops with the highest recent arrival rate.
1567    PredictiveParking,
1568    /// Mode-gated: picks between `ReturnToLobby` / `PredictiveParking`
1569    /// based on the current `TrafficDetector` mode.
1570    Adaptive,
1571    /// Custom strategy identified by name.
1572    Custom(String),
1573}
1574
1575impl std::fmt::Display for BuiltinReposition {
1576    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1577        match self {
1578            Self::SpreadEvenly => write!(f, "SpreadEvenly"),
1579            Self::ReturnToLobby => write!(f, "ReturnToLobby"),
1580            Self::DemandWeighted => write!(f, "DemandWeighted"),
1581            Self::NearestIdle => write!(f, "NearestIdle"),
1582            Self::PredictiveParking => write!(f, "PredictiveParking"),
1583            Self::Adaptive => write!(f, "Adaptive"),
1584            Self::Custom(name) => write!(f, "Custom({name})"),
1585        }
1586    }
1587}
1588
1589impl BuiltinReposition {
1590    /// Instantiate the reposition strategy for this variant.
1591    ///
1592    /// Returns `None` for `Custom` — the game must provide those via
1593    /// a factory function. `ReturnToLobby` uses stop index 0 as default.
1594    #[must_use]
1595    pub fn instantiate(&self) -> Option<Box<dyn RepositionStrategy>> {
1596        match self {
1597            Self::SpreadEvenly => Some(Box::new(reposition::SpreadEvenly)),
1598            Self::ReturnToLobby => Some(Box::new(reposition::ReturnToLobby::new())),
1599            Self::DemandWeighted => Some(Box::new(reposition::DemandWeighted)),
1600            Self::NearestIdle => Some(Box::new(reposition::NearestIdle)),
1601            Self::PredictiveParking => Some(Box::new(reposition::PredictiveParking::new())),
1602            Self::Adaptive => Some(Box::new(reposition::AdaptiveParking::new())),
1603            Self::Custom(_) => None,
1604        }
1605    }
1606}