elevator_core/dispatch/destination.rs
1//! Hall-call destination dispatch ("DCS").
2//!
3//! Destination dispatch assigns each rider to a specific car at hall-call
4//! time (when their destination is first known) and the assignment is
5//! **sticky** — it never changes for the rider's lifetime, and no other car
6//! will pick them up. The controller minimizes each rider's own travel time,
7//! using a simple cost model:
8//!
9//! ```text
10//! J(C) = pickup_time(C, origin)
11//! + ride_time(origin, dest)
12//! + stop_penalty * new_stops_added(C, origin, dest)
13//! ```
14//!
15//! Assignments are recorded as an [`AssignedCar`] extension component on the
16//! rider; the loading filter in `crate::systems::loading` consults this to
17//! enforce the stickiness invariant.
18//!
19//! This is a sim — not a faithful reproduction of any vendor's controller.
20//! Each assigned car's [`DestinationQueue`](crate::components::DestinationQueue)
21//! is rebuilt every dispatch tick from the set of live sticky commitments
22//! (waiting riders contribute origin + dest; riding riders contribute dest)
23//! and arranged into a direction-aware two-run (plus fallback third-run)
24//! monotone sequence so the car visits stops in sweep order rather than
25//! in the order assignments arrived.
26
27use std::collections::HashSet;
28
29use serde::{Deserialize, Serialize};
30
31use crate::components::{DestinationQueue, Direction, ElevatorPhase};
32use crate::entity::EntityId;
33use crate::world::{ExtKey, World};
34
35use super::{DispatchManifest, DispatchStrategy, ElevatorGroup, RankContext, pair_can_do_work};
36
37/// Sticky rider → car assignment produced by [`DestinationDispatch`].
38///
39/// Stored as an extension component on the rider entity. Once set, the
40/// assignment is never mutated; the loading phase uses it to enforce
41/// that only the assigned car may board the rider.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43pub struct AssignedCar(pub EntityId);
44
45/// Typed extension key for [`AssignedCar`] storage.
46pub const ASSIGNED_CAR_KEY: ExtKey<AssignedCar> = ExtKey::new("assigned_car");
47
48/// Hall-call destination dispatch (DCS).
49///
50/// ## API shape
51///
52/// Uses [`DispatchStrategy::pre_dispatch`] to write sticky
53/// [`AssignedCar`] extensions and rebuild each car's committed stop
54/// queue during a `&mut World` phase. [`DispatchStrategy::rank`] then
55/// routes each car to its own queue front and returns `None` for every
56/// other stop, so the group-wide Hungarian assignment trivially pairs
57/// each car with the stop it has already committed to.
58#[derive(serde::Serialize, serde::Deserialize)]
59pub struct DestinationDispatch {
60 /// Weight for per-stop door overhead in the cost function. A positive
61 /// value biases assignments toward cars whose route change adds no
62 /// fresh stops; set via [`with_stop_penalty`](Self::with_stop_penalty).
63 ///
64 /// Units: ticks per newly-added stop. `None` ⇒ derive from the car's
65 /// own door timings (~`open + 2 * transition`).
66 stop_penalty: Option<f64>,
67 /// Deferred-commitment window. When `Some(window)`, a rider's
68 /// sticky assignment is re-evaluated each pass until the assigned
69 /// car is within `window` ticks of the rider's origin — modelling
70 /// KONE Polaris's two-button reallocation regime (DCS calls fix on
71 /// press; two-button hall calls re-allocate continuously until
72 /// commitment). `None` ⇒ immediate sticky (the default), matching
73 /// fixed-on-press DCS behavior.
74 commitment_window_ticks: Option<u64>,
75}
76
77impl DestinationDispatch {
78 /// Create a new `DestinationDispatch` with defaults (immediate sticky,
79 /// no commitment window).
80 #[must_use]
81 pub const fn new() -> Self {
82 Self {
83 stop_penalty: None,
84 commitment_window_ticks: None,
85 }
86 }
87
88 /// Override the fresh-stop penalty (ticks per new stop added to a
89 /// car's committed route when it picks this rider up).
90 #[must_use]
91 pub const fn with_stop_penalty(mut self, penalty: f64) -> Self {
92 self.stop_penalty = Some(penalty);
93 self
94 }
95
96 /// Enable deferred commitment: riders' sticky assignments are
97 /// re-evaluated each pass until the currently-assigned car is
98 /// within `window` ticks of the rider's origin. At that point the
99 /// commitment latches and later ticks leave the assignment alone.
100 #[must_use]
101 pub const fn with_commitment_window_ticks(mut self, window: u64) -> Self {
102 self.commitment_window_ticks = Some(window);
103 self
104 }
105}
106
107impl Default for DestinationDispatch {
108 fn default() -> Self {
109 Self::new()
110 }
111}
112
113impl DispatchStrategy for DestinationDispatch {
114 #[allow(clippy::too_many_lines)]
115 fn pre_dispatch(
116 &mut self,
117 group: &ElevatorGroup,
118 manifest: &DispatchManifest,
119 world: &mut World,
120 ) {
121 // DCS requires the group to be in `HallCallMode::Destination` — that
122 // mode is what makes the kiosk-style "rider announces destination
123 // at press time" assumption hold. In Classic collective-control
124 // mode destinations aren't known until riders board, so running
125 // DCS there would commit assignments based on information a real
126 // controller wouldn't have. Early-return makes DCS a no-op for
127 // misconfigured groups; pair it with the right mode to activate.
128 if group.hall_call_mode() != super::HallCallMode::Destination {
129 return;
130 }
131
132 // Candidate cars in this group that are operable for dispatch.
133 let candidate_cars: Vec<EntityId> = group
134 .elevator_entities()
135 .iter()
136 .copied()
137 .filter(|eid| !world.is_disabled(*eid))
138 .filter(|eid| {
139 !world
140 .service_mode(*eid)
141 .is_some_and(|m| m.is_dispatch_excluded())
142 })
143 .filter(|eid| world.elevator(*eid).is_some())
144 .collect();
145
146 if candidate_cars.is_empty() {
147 return;
148 }
149
150 // Collect unassigned waiting riders in this group. A sticky
151 // assignment whose target car is dead or disabled is treated as
152 // void — re-assign rather than strand. (Lifecycle hooks in
153 // `disable`/`remove_elevator` normally clear these; this is the
154 // defense layer if cleanup is ever missed.)
155 let mut stale_assignments: Vec<EntityId> = Vec::new();
156 let mut pending: Vec<(EntityId, EntityId, EntityId, f64)> = Vec::new();
157 for (_, riders) in manifest.iter_waiting_stops() {
158 for info in riders {
159 if let Some(AssignedCar(c)) = world.ext::<AssignedCar>(info.id) {
160 // An assignment stays sticky only when the target
161 // car is still alive and (no commitment window is
162 // configured, or the car is already inside the
163 // latch window). Otherwise strip it so the rider
164 // re-competes below.
165 let alive = world.elevator(c).is_some() && !world.is_disabled(c);
166 let latched = self
167 .commitment_window_ticks
168 .is_none_or(|w| assigned_car_within_window(world, info.id, c, w));
169 if alive && latched {
170 continue; // sticky and live
171 }
172 stale_assignments.push(info.id);
173 }
174 let Some(dest) = info.destination else {
175 continue;
176 };
177 let Some(route) = world.route(info.id) else {
178 continue;
179 };
180 let Some(leg) = route.current() else {
181 continue;
182 };
183 if !group.accepts_leg(leg) {
184 continue;
185 }
186 pending.push((info.id, leg.from, dest, info.weight.value()));
187 }
188 }
189 pending.sort_by_key(|(rid, ..)| *rid);
190 // Drop stale extensions so subsequent ticks see them as unassigned.
191 for rid in stale_assignments {
192 world.remove_ext::<AssignedCar>(rid);
193 }
194
195 // Pre-compute committed-load per candidate car: aboard total
196 // (`current_load`) plus Waiting riders sticky-assigned to it.
197 // Terminal-phase riders whose `AssignedCar` was not cleaned up
198 // are filtered by the `RiderPhase::Waiting` check below.
199 let mut committed_load: std::collections::BTreeMap<EntityId, f64> =
200 std::collections::BTreeMap::new();
201 for &eid in &candidate_cars {
202 if let Some(car) = world.elevator(eid) {
203 committed_load.insert(eid, car.current_load().value());
204 }
205 }
206 let waiting_assignments: Vec<(EntityId, EntityId)> = world
207 .ext_map::<AssignedCar>()
208 .map(|m| m.iter().map(|(rid, AssignedCar(c))| (rid, *c)).collect())
209 .unwrap_or_default();
210 for (rid, car) in waiting_assignments {
211 if let Some(rider) = world.rider(rid)
212 && rider.phase() == crate::components::RiderPhase::Waiting
213 {
214 *committed_load.entry(car).or_insert(0.0) += rider.weight.value();
215 }
216 }
217
218 for (rid, origin, dest, weight) in pending {
219 let best = candidate_cars
220 .iter()
221 .filter_map(|&eid| {
222 let car = world.elevator(eid)?;
223 if car.restricted_stops().contains(&dest)
224 || car.restricted_stops().contains(&origin)
225 {
226 return None;
227 }
228 if car.weight_capacity().value() > 0.0 && weight > car.weight_capacity().value()
229 {
230 return None;
231 }
232 let com = committed_load.get(&eid).copied().unwrap_or(0.0);
233 let cost = self.compute_cost(eid, origin, dest, world, com);
234 if cost.is_finite() {
235 Some((eid, cost))
236 } else {
237 None
238 }
239 })
240 .min_by(|a, b| a.1.total_cmp(&b.1))
241 .map(|(eid, _)| eid);
242
243 let Some(car_eid) = best else {
244 continue;
245 };
246 world.insert_ext(rid, AssignedCar(car_eid), ASSIGNED_CAR_KEY);
247 *committed_load.entry(car_eid).or_insert(0.0) += weight;
248 }
249
250 // Rebuild each candidate car's destination queue from the current
251 // set of sticky commitments, arranged in direction-aware two-run
252 // monotone order. This is the source of truth per tick and avoids
253 // incremental-insertion drift (duplicates, orphaned entries).
254 for &car_eid in &candidate_cars {
255 rebuild_car_queue(world, car_eid);
256 }
257 }
258
259 fn rank(&mut self, ctx: &RankContext<'_>) -> Option<f64> {
260 // The queue is the source of truth — route each car strictly to
261 // its own queue front. Every other stop is unavailable for this
262 // car, so the Hungarian assignment reduces to the identity match
263 // between each car and the stop it has already committed to.
264 //
265 // The `pair_can_do_work` gate guards against the same full-car
266 // self-assign stall the other built-ins close: a sticky DCS
267 // assignment whose car has filled up with earlier riders and
268 // whose queue front is still the *pickup* for an un-boarded
269 // rider would otherwise rank 0.0, win the Hungarian every tick,
270 // and cycle doors forever.
271 let front = ctx
272 .world
273 .destination_queue(ctx.car)
274 .and_then(DestinationQueue::front)?;
275 if front == ctx.stop && pair_can_do_work(ctx) {
276 Some(0.0)
277 } else {
278 None
279 }
280 }
281
282 fn builtin_id(&self) -> Option<super::BuiltinStrategy> {
283 Some(super::BuiltinStrategy::Destination)
284 }
285
286 fn snapshot_config(&self) -> Option<String> {
287 ron::to_string(self).ok()
288 }
289
290 fn restore_config(&mut self, serialized: &str) -> Result<(), String> {
291 let restored: Self = ron::from_str(serialized).map_err(|e| e.to_string())?;
292 *self = restored;
293 Ok(())
294 }
295}
296
297impl DestinationDispatch {
298 /// Compute the assignment cost of sending car `eid` to pick up a rider
299 /// whose route is `origin → dest`.
300 fn compute_cost(
301 &self,
302 eid: EntityId,
303 origin: EntityId,
304 dest: EntityId,
305 world: &World,
306 committed_load: f64,
307 ) -> f64 {
308 let Some(car) = world.elevator(eid) else {
309 return f64::INFINITY;
310 };
311 if car.max_speed().value() <= 0.0 {
312 return f64::INFINITY;
313 }
314
315 let Some(car_pos) = world.position(eid).map(|p| p.value) else {
316 return f64::INFINITY;
317 };
318 let Some(origin_pos) = world.stop_position(origin) else {
319 return f64::INFINITY;
320 };
321 let Some(dest_pos) = world.stop_position(dest) else {
322 return f64::INFINITY;
323 };
324
325 let door_overhead = f64::from(car.door_transition_ticks() * 2 + car.door_open_ticks());
326 let penalty = self.stop_penalty.unwrap_or_else(|| door_overhead.max(1.0));
327
328 // Pickup time: direct distance + per-stop door overhead for each
329 // committed stop that lies between the car and the origin.
330 let pickup_dist = (car_pos - origin_pos).abs();
331 let pickup_travel = pickup_dist / car.max_speed().value();
332 let intervening_committed = world.destination_queue(eid).map_or(0usize, |q| {
333 let (lo, hi) = if car_pos < origin_pos {
334 (car_pos, origin_pos)
335 } else {
336 (origin_pos, car_pos)
337 };
338 q.queue()
339 .iter()
340 .filter_map(|s| world.stop_position(*s))
341 .filter(|p| *p > lo + 1e-9 && *p < hi - 1e-9)
342 .count()
343 });
344 let pickup_time = (intervening_committed as f64).mul_add(door_overhead, pickup_travel);
345
346 // Ride time: origin → dest travel + door overhead at origin pickup.
347 let ride_dist = (origin_pos - dest_pos).abs();
348 let ride_time = ride_dist / car.max_speed().value() + door_overhead;
349
350 // Fresh stops added: 0, 1, or 2 depending on whether origin/dest
351 // are already queued for this car. Probe the queue slice directly
352 // instead of cloning it — `compute_cost` runs once per
353 // (car, candidate-rider) pair each DCS tick, and at the scale of a
354 // busy commercial group the Vec clone was the dominant allocation
355 // in `pre_dispatch`.
356 let queue_contains = |s: EntityId| {
357 world
358 .destination_queue(eid)
359 .is_some_and(|q| q.queue().contains(&s))
360 };
361 let mut new_stops = 0f64;
362 if !queue_contains(origin) {
363 new_stops += 1.0;
364 }
365 if dest != origin && !queue_contains(dest) {
366 new_stops += 1.0;
367 }
368
369 // Idle bias: empty cars get a small bonus so the load spreads.
370 let idle_bonus = if car.phase() == ElevatorPhase::Idle && car.riders().is_empty() {
371 -0.1 * pickup_travel
372 } else {
373 0.0
374 };
375
376 // Load bias: include both aboard and already-assigned-but-waiting
377 // riders so dispatch spreads load even before any boarding happens.
378 let load_penalty = if car.weight_capacity().value() > 0.0 {
379 let effective = car.current_load().value().max(committed_load);
380 let ratio = (effective / car.weight_capacity().value()).min(2.0);
381 ratio * door_overhead * 4.0
382 } else {
383 0.0
384 };
385
386 pickup_time + ride_time + penalty * new_stops + idle_bonus + load_penalty
387 }
388}
389
390/// True when the `car` assigned to `rider` is within `window` ticks of
391/// the rider's origin, measured by raw distance / `max_speed`. Used to
392/// decide whether a deferred commitment has latched.
393fn assigned_car_within_window(
394 world: &crate::world::World,
395 rider: EntityId,
396 car: EntityId,
397 window: u64,
398) -> bool {
399 let Some(leg) = world.route(rider).and_then(|r| r.current()) else {
400 return false;
401 };
402 let Some(origin_pos) = world.stop_position(leg.from) else {
403 return false;
404 };
405 let Some(car_pos) = world.position(car).map(|p| p.value) else {
406 return false;
407 };
408 let Some(car_data) = world.elevator(car) else {
409 return false;
410 };
411 let speed = car_data.max_speed().value();
412 if !speed.is_finite() || speed <= 0.0 {
413 return false;
414 }
415 // `distance / speed` is seconds (speed is distance/second); convert
416 // to ticks so `window` is apples-to-apples. Same class of unit fix
417 // as ETD's door-cost conversion (see `etd.rs`). Fall back to 60 Hz
418 // for bare-World fixtures that don't seat a `TickRate` resource.
419 let tick_rate = world
420 .resource::<crate::time::TickRate>()
421 .map_or(60.0, |r| r.0);
422 let eta_ticks = (car_pos - origin_pos).abs() / speed * tick_rate;
423 // A non-finite ETA (NaN from corrupted position) would saturate
424 // the `as u64` cast to 0 and erroneously latch the commitment —
425 // refuse to latch instead.
426 if !eta_ticks.is_finite() {
427 return false;
428 }
429 eta_ticks.round() as u64 <= window
430}
431
432/// Drop every sticky [`AssignedCar`] assignment that points at `car_eid`.
433///
434/// Called by `Simulation::disable` and `Simulation::remove_elevator` when an
435/// elevator leaves service, so DCS-routed riders are not stranded behind a
436/// dead reference.
437pub fn clear_assignments_to(world: &mut crate::world::World, car_eid: EntityId) {
438 let stale: Vec<EntityId> = world
439 .ext_map::<AssignedCar>()
440 .map(|m| {
441 m.iter()
442 .filter_map(|(rid, AssignedCar(c))| (*c == car_eid).then_some(rid))
443 .collect()
444 })
445 .unwrap_or_default();
446 for rid in stale {
447 world.remove_ext::<AssignedCar>(rid);
448 }
449}
450
451/// Rebuild `car_eid`'s destination queue from all live sticky commitments.
452///
453/// Scans all riders assigned to this car and collects the set of stops it
454/// must visit:
455/// - waiting riders contribute both their origin and destination,
456/// - riding/boarding riders contribute just their destination (origin
457/// already visited).
458///
459/// The stops are then arranged into a two-run monotone sequence: the
460/// current sweep (in the car's current direction) followed by the reverse
461/// sweep. A third run is appended when a rider's trip reverses the sweep
462/// twice (origin behind, dest ahead of origin in the original sweep).
463#[allow(clippy::too_many_lines)]
464fn rebuild_car_queue(world: &mut crate::world::World, car_eid: EntityId) {
465 use crate::components::RiderPhase;
466
467 // Local type for gathered (origin?, dest) trips.
468 struct Trip {
469 origin: Option<EntityId>,
470 dest: EntityId,
471 }
472
473 let Some(car) = world.elevator(car_eid) else {
474 return;
475 };
476 let car_pos = world.position(car_eid).map_or(0.0, |p| p.value);
477 let sweep_up = match car.direction() {
478 Direction::Up | Direction::Either => true,
479 Direction::Down => false,
480 };
481
482 // Skip inserting a stop the car is currently parked at and loading.
483 let at_stop_loading: Option<EntityId> = {
484 let stopped_here = !matches!(
485 car.phase(),
486 ElevatorPhase::MovingToStop(_) | ElevatorPhase::Repositioning(_)
487 );
488 if stopped_here {
489 world.find_stop_at_position(car_pos)
490 } else {
491 None
492 }
493 };
494
495 // Gather (origin?, dest) pairs from sticky-assigned riders on this car.
496 let assigned_ids: Vec<EntityId> = world
497 .ext_map::<AssignedCar>()
498 .map(|m| {
499 m.iter()
500 .filter_map(|(rid, AssignedCar(c))| (*c == car_eid).then_some(rid))
501 .collect()
502 })
503 .unwrap_or_default();
504
505 let mut trips: Vec<Trip> = Vec::new();
506 for rid in assigned_ids {
507 let Some(rider) = world.rider(rid) else {
508 continue;
509 };
510 let Some(dest) = world
511 .route(rid)
512 .and_then(crate::components::Route::current_destination)
513 else {
514 continue;
515 };
516 match rider.phase() {
517 RiderPhase::Waiting => {
518 let origin = world
519 .route(rid)
520 .and_then(|r| r.current().map(|leg| leg.from));
521 // Strip origin if car is parked at it right now.
522 let origin = origin.filter(|o| Some(*o) != at_stop_loading);
523 trips.push(Trip { origin, dest });
524 }
525 RiderPhase::Boarding(_) | RiderPhase::Riding(_) => {
526 trips.push(Trip { origin: None, dest });
527 }
528 _ => {}
529 }
530 }
531
532 if trips.is_empty() {
533 if let Some(q) = world.destination_queue_mut(car_eid) {
534 q.clear();
535 }
536 return;
537 }
538
539 // Bucket each stop into up to three runs based on the car's direction:
540 // run1 = current sweep (same direction as car)
541 // run2 = reverse sweep
542 // run3 = second sweep in the original direction (for trips whose
543 // origin is behind the sweep but dest is further in it)
544 let mut run1: Vec<(EntityId, f64)> = Vec::new();
545 let mut run2: Vec<(EntityId, f64)> = Vec::new();
546 let mut run3: Vec<(EntityId, f64)> = Vec::new();
547
548 let in_run1 = |sp: f64| -> bool {
549 if sweep_up {
550 sp >= car_pos - 1e-9
551 } else {
552 sp <= car_pos + 1e-9
553 }
554 };
555
556 let push_unique = |v: &mut Vec<(EntityId, f64)>, s: EntityId, p: f64| {
557 if !v.iter().any(|(e, _)| *e == s) {
558 v.push((s, p));
559 }
560 };
561
562 for trip in &trips {
563 let dp = world.stop_position(trip.dest).unwrap_or(car_pos);
564 if let Some(o) = trip.origin {
565 let op = world.stop_position(o).unwrap_or(car_pos);
566 let o_in_run1 = in_run1(op);
567 let d_in_run1 = in_run1(dp);
568 if o_in_run1 {
569 push_unique(&mut run1, o, op);
570 if d_in_run1 {
571 // Both in run1: dest must be further in sweep than origin.
572 let d_fits = if sweep_up {
573 dp >= op - 1e-9
574 } else {
575 dp <= op + 1e-9
576 };
577 if d_fits {
578 push_unique(&mut run1, trip.dest, dp);
579 } else {
580 // Dest is behind origin in sweep: needs reverse run.
581 push_unique(&mut run2, trip.dest, dp);
582 }
583 } else {
584 push_unique(&mut run2, trip.dest, dp);
585 }
586 } else {
587 // Origin is behind sweep: both go in reverse/second run.
588 push_unique(&mut run2, o, op);
589 if d_in_run1 {
590 // Origin behind, dest ahead: need a third sweep.
591 push_unique(&mut run3, trip.dest, dp);
592 } else {
593 // Both behind sweep. Within reverse run, order dest
594 // after origin (dest further into reverse direction).
595 let d_further = if sweep_up {
596 dp <= op + 1e-9
597 } else {
598 dp >= op - 1e-9
599 };
600 if d_further {
601 push_unique(&mut run2, trip.dest, dp);
602 } else {
603 push_unique(&mut run3, trip.dest, dp);
604 }
605 }
606 }
607 } else {
608 // No origin: just drop off. Place dest in whichever run contains it.
609 if in_run1(dp) {
610 push_unique(&mut run1, trip.dest, dp);
611 } else {
612 push_unique(&mut run2, trip.dest, dp);
613 }
614 }
615 }
616
617 // Sort each run monotonically.
618 if sweep_up {
619 run1.sort_by(|a, b| a.1.total_cmp(&b.1));
620 run2.sort_by(|a, b| b.1.total_cmp(&a.1));
621 run3.sort_by(|a, b| a.1.total_cmp(&b.1));
622 } else {
623 run1.sort_by(|a, b| b.1.total_cmp(&a.1));
624 run2.sort_by(|a, b| a.1.total_cmp(&b.1));
625 run3.sort_by(|a, b| b.1.total_cmp(&a.1));
626 }
627
628 let mut out: Vec<EntityId> = Vec::with_capacity(run1.len() + run2.len() + run3.len());
629 out.extend(run1.into_iter().map(|(e, _)| e));
630 out.extend(run2.into_iter().map(|(e, _)| e));
631 out.extend(run3.into_iter().map(|(e, _)| e));
632 let mut seen = HashSet::with_capacity(out.len());
633 out.retain(|e| seen.insert(*e));
634
635 if let Some(q) = world.destination_queue_mut(car_eid) {
636 q.replace(out);
637 }
638}