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