elevator-core 7.0.1

Engine-agnostic elevator simulation library with pluggable dispatch strategies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Tests for the hall-call / car-call public API.

use crate::components::CallDirection;
use crate::entity::EntityId;
use crate::events::Event;
use crate::sim::Simulation;
use crate::stop::StopId;

use super::helpers::{default_config, scan};

/// Spawning a rider auto-presses the hall button in the correct direction.
#[test]
fn spawn_rider_auto_presses_hall_button() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    let rid = sim
        .spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    let origin = sim.stop_entity(StopId(0)).unwrap();
    let call = sim.world().hall_call(origin, CallDirection::Up).unwrap();
    assert_eq!(call.direction, CallDirection::Up);
    assert!(
        call.pending_riders.contains(&rid),
        "rider should be aggregated into the hall call's pending list"
    );
    let events = sim.drain_events();
    assert!(
        events.iter().any(|e| matches!(
            e,
            Event::HallButtonPressed {
                direction: CallDirection::Up,
                ..
            }
        )),
        "spawning a rider should emit HallButtonPressed"
    );
}

/// Two riders at the same stop heading the same direction aggregate
/// into one call and emit only one `HallButtonPressed`.
#[test]
fn multiple_riders_aggregate_into_one_hall_call() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    let r1 = sim
        .spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    sim.drain_events();
    let r2 = sim
        .spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    let origin = sim.stop_entity(StopId(0)).unwrap();
    let call = sim.world().hall_call(origin, CallDirection::Up).unwrap();
    assert!(call.pending_riders.contains(&r1));
    assert!(call.pending_riders.contains(&r2));
    let extra_events = sim.drain_events();
    let press_count = extra_events
        .iter()
        .filter(|e| matches!(e, Event::HallButtonPressed { .. }))
        .count();
    assert_eq!(
        press_count, 0,
        "second rider should not re-press the same call"
    );
}

/// Explicit `press_hall_button` works without a rider (scripted NPC / player input).
#[test]
fn explicit_press_hall_button_without_rider() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    let stop = sim.stop_entity(StopId(1)).unwrap();
    sim.press_hall_button(stop, CallDirection::Down).unwrap();
    let call = sim.world().hall_call(stop, CallDirection::Down).unwrap();
    assert!(call.pending_riders.is_empty());
    assert_eq!(call.direction, CallDirection::Down);
}

/// `pin_assignment` records the car and flags the call as pinned.
#[test]
fn pin_assignment_pins_and_assigns() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    let stop = sim.stop_entity(StopId(1)).unwrap();
    let car = sim.world().elevator_ids()[0];
    sim.press_hall_button(stop, CallDirection::Up).unwrap();
    sim.pin_assignment(car, stop, CallDirection::Up).unwrap();
    let call = sim.world().hall_call(stop, CallDirection::Up).unwrap();
    assert_eq!(call.assigned_car, Some(car));
    assert!(call.pinned);
    sim.unpin_assignment(stop, CallDirection::Up);
    let call = sim.world().hall_call(stop, CallDirection::Up).unwrap();
    assert!(!call.pinned);
}

/// Nonzero `ack_latency_ticks`: a hall call pressed at tick T only
/// becomes acknowledged at tick T+N, and `HallCallAcknowledged` fires
/// on exactly that tick. Locks in the deferred-ack path in
/// `advance_transient::ack_hall_calls`.
#[test]
fn nonzero_ack_latency_delays_acknowledgement() {
    use crate::dispatch::HallCallMode;
    use crate::ids::GroupId;

    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    // Configure a 5-tick ack latency on the only group, leaving Classic
    // mode unchanged.
    for g in sim.groups_mut() {
        if g.id() == GroupId(0) {
            g.set_ack_latency_ticks(5);
            g.set_hall_call_mode(HallCallMode::Classic);
        }
    }

    let press_tick = sim.current_tick();
    let stop = sim.stop_entity(StopId(1)).unwrap();
    sim.press_hall_button(stop, CallDirection::Up).unwrap();

    // Press tick: call exists but unacknowledged.
    let call = sim.world().hall_call(stop, CallDirection::Up).unwrap();
    assert_eq!(call.press_tick, press_tick);
    assert_eq!(call.acknowledged_at, None);
    sim.drain_events();

    // Step forward. At each step `advance_transient` runs with the
    // current tick *before* the end-of-step advance, so `current_tick()`
    // afterwards equals the tick the ack pass ran on, plus one. The
    // call should remain pending until the pass processes a tick whose
    // delta ≥ `ack_latency_ticks`.
    let mut ack_tick: Option<u64> = None;
    for _ in 0..10 {
        sim.step();
        let call = sim.world().hall_call(stop, CallDirection::Up).unwrap();
        if let Some(t) = call.acknowledged_at {
            ack_tick = Some(t);
            break;
        }
    }
    let ack_tick = ack_tick.expect("ack should fire within 10 steps");
    assert_eq!(
        ack_tick.saturating_sub(press_tick),
        5,
        "ack should fire exactly `ack_latency_ticks` ticks after the press"
    );
    // One HallCallAcknowledged event (not one per step).
    let events = sim.drain_events();
    let acks = events
        .iter()
        .filter(|e| matches!(e, Event::HallCallAcknowledged { .. }))
        .count();
    assert!(acks <= 1, "HallCallAcknowledged should fire at most once");
}

/// DCS mode: a hall call press by a rider populates the call's
/// destination so destination-aware strategies can read it directly.
#[test]
fn destination_mode_records_destination_on_call() {
    use crate::dispatch::HallCallMode;
    use crate::ids::GroupId;

    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    for g in sim.groups_mut() {
        if g.id() == GroupId(0) {
            g.set_hall_call_mode(HallCallMode::Destination);
        }
    }
    let origin = sim.stop_entity(StopId(0)).unwrap();
    let dest = sim.stop_entity(StopId(2)).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    let call = sim.world().hall_call(origin, CallDirection::Up).unwrap();
    assert_eq!(
        call.destination,
        Some(dest),
        "DCS kiosk entry should populate the hall call's destination"
    );
}

/// Public `Simulation::hall_calls()` and `car_calls(car)` expose the
/// active call state without requiring `sim.world()` traversal.
#[test]
fn public_call_queries_return_active_calls() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    // One hall call registered at the origin going up.
    let count = sim.hall_calls().count();
    assert_eq!(count, 1);
    // No car calls yet (rider hasn't boarded).
    let car = sim.world().elevator_ids()[0];
    assert!(sim.car_calls(car).is_empty());
}

/// `CarCall`s are cleaned up when the rider who pressed the button exits
/// at that floor. Regression against unbounded growth of per-car
/// `car_calls` vectors reported in PR review.
#[test]
fn car_call_removed_on_exit() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    let car = sim.world().elevator_ids()[0];

    // Run until the rider reaches Arrived.
    let mut boarded = false;
    for _ in 0..2000 {
        sim.step();
        if !boarded && !sim.car_calls(car).is_empty() {
            boarded = true;
        }
        if boarded && sim.car_calls(car).is_empty() {
            break;
        }
    }
    assert!(
        sim.car_calls(car).is_empty(),
        "car_calls should be drained once the rider exits"
    );
}

/// An explicit `press_car_button` (no rider associated) emits
/// `CarButtonPressed { rider: None, ... }`. Regression against the
/// previous sentinel-entity behavior flagged in PR review.
#[test]
fn press_car_button_without_rider_emits_none_rider() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    let car = sim.world().elevator_ids()[0];
    let floor = sim.stop_entity(StopId(2)).unwrap();
    sim.press_car_button(car, floor).unwrap();
    let events = sim.drain_events();
    let pressed = events
        .iter()
        .find_map(|e| match e {
            Event::CarButtonPressed { rider, .. } => Some(*rider),
            _ => None,
        })
        .expect("CarButtonPressed should fire");
    assert_eq!(
        pressed, None,
        "synthetic press should emit None rider, not EntityId::default()"
    );
}

/// A pin applied while a car is in `Loading` phase must not clobber its
/// door-cycle state. Regression against the PR-review finding that the
/// pin pre-commit bypassed the phase-eligibility gate.
#[test]
fn pinned_pin_does_not_clobber_loading_car() {
    use crate::components::ElevatorPhase;

    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    // Run until the car reaches Loading phase at some stop.
    let car = sim.world().elevator_ids()[0];
    let mut loading_stop: Option<EntityId> = None;
    for _ in 0..2000 {
        sim.step();
        if let Some(c) = sim.world().elevator(car)
            && c.phase == ElevatorPhase::Loading
        {
            loading_stop = c.target_stop;
            break;
        }
    }
    let loading_stop = loading_stop.expect("car should reach Loading phase within 2000 ticks");
    // Spawn a second rider elsewhere and pin the loading car to that stop.
    let other = sim.stop_entity(StopId(1)).unwrap();
    if other != loading_stop {
        sim.press_hall_button(other, CallDirection::Down).ok();
        let _ = sim.pin_assignment(car, other, CallDirection::Down);
        sim.drain_events();
        // One tick of dispatch must not yank the car out of Loading.
        sim.step();
        let phase_after = sim.world().elevator(car).map(|c| c.phase);
        assert!(
            !matches!(phase_after, Some(ElevatorPhase::MovingToStop(s)) if s == other),
            "pin should not override a Loading car mid-door-cycle"
        );
    }
}

/// `rebalk_on_full = true` escalates a balk into immediate abandonment.
/// Regression guard — the flag was documented but previously inert.
#[test]
fn rebalk_on_full_abandons_immediately() {
    use crate::components::Preferences;
    let mut config = default_config();
    // Tight capacity so any preload fills the car.
    config.elevators[0].weight_capacity = 100.0;
    let mut sim = Simulation::new(&config, scan()).unwrap();

    // Rider with rebalk_on_full who skips anything with load > 0.5.
    let picky = sim
        .build_rider_by_stop_id(StopId(0), StopId(2))
        .unwrap()
        .weight(30.0)
        .preferences(Preferences::default().with_rebalk_on_full(true))
        .spawn()
        .unwrap();
    // Note: Preferences::default has skip_full_elevator = false, but
    // max_crowding_factor 0.8 means a 60-weight preload still exceeds.
    sim.world_mut().set_preferences(
        picky,
        Preferences {
            skip_full_elevator: true,
            max_crowding_factor: 0.5,
            balk_threshold_ticks: None,
            rebalk_on_full: true,
        },
    );

    // Force the elevator to Loading phase at the picky rider's stop
    // with a ballast preload that trips the preference filter.
    let elev = sim.world().elevator_ids()[0];
    let stop0 = sim.stop_entity(StopId(0)).unwrap();
    let stop0_pos = sim.world().stop(stop0).unwrap().position;
    {
        let w = sim.world_mut();
        if let Some(pos) = w.position_mut(elev) {
            pos.value = stop0_pos;
        }
        if let Some(vel) = w.velocity_mut(elev) {
            vel.value = 0.0;
        }
        if let Some(car) = w.elevator_mut(elev) {
            car.phase = crate::components::ElevatorPhase::Loading;
            car.current_load = 60.0;
            car.target_stop = None;
        }
    }
    sim.run_loading();
    sim.advance_tick();
    let phase = sim.world().rider(picky).map(|r| r.phase);
    assert_eq!(
        phase,
        Some(crate::components::RiderPhase::Abandoned),
        "rebalk_on_full should escalate the balk into Abandoned"
    );
}

/// Cross-line pin is rejected at `pin_assignment` time rather than
/// silently orphaning the call at dispatch. Regression against the
/// gap flagged in the multi-line audit.
#[test]
fn pin_across_lines_is_rejected() {
    use crate::components::Orientation;
    use crate::config::{ElevatorConfig, GroupConfig, LineConfig};
    use crate::dispatch::BuiltinStrategy;
    use crate::dispatch::scan::ScanDispatch;
    use crate::stop::StopConfig;

    // Two lines in one group: Low serves Ground+Mid, High serves Mid+Top.
    let mut config = default_config();
    config.building.stops = vec![
        StopConfig {
            id: StopId(0),
            name: "Ground".into(),
            position: 0.0,
        },
        StopConfig {
            id: StopId(1),
            name: "Mid".into(),
            position: 10.0,
        },
        StopConfig {
            id: StopId(2),
            name: "Top".into(),
            position: 20.0,
        },
    ];
    let mk_elev = |id: u32, name: &str, start: StopId| ElevatorConfig {
        id,
        name: name.into(),
        starting_stop: start,
        ..ElevatorConfig::default()
    };
    config.building.lines = Some(vec![
        LineConfig {
            id: 1,
            name: "Low".into(),
            serves: vec![StopId(0), StopId(1)],
            elevators: vec![mk_elev(1, "L1", StopId(0))],
            orientation: Orientation::Vertical,
            position: None,
            min_position: None,
            max_position: None,
            max_cars: None,
        },
        LineConfig {
            id: 2,
            name: "High".into(),
            serves: vec![StopId(1), StopId(2)],
            elevators: vec![mk_elev(2, "H1", StopId(1))],
            orientation: Orientation::Vertical,
            position: None,
            min_position: None,
            max_position: None,
            max_cars: None,
        },
    ]);
    config.building.groups = Some(vec![GroupConfig {
        id: 0,
        name: "SplitGroup".into(),
        lines: vec![1, 2],
        dispatch: BuiltinStrategy::Scan,
        reposition: None,
    }]);
    config.elevators = Vec::new();
    let mut sim = Simulation::new(&config, ScanDispatch::new()).unwrap();

    let top = sim.stop_entity(StopId(2)).unwrap();
    sim.press_hall_button(top, CallDirection::Down).unwrap();

    // Locate the Low car (its line does NOT serve Top).
    let low_car = sim
        .world()
        .elevator_ids()
        .into_iter()
        .find(|&e| {
            let Some(line) = sim.world().elevator(e).map(|c| c.line) else {
                return false;
            };
            sim.groups()
                .iter()
                .flat_map(|g| g.lines().iter())
                .find(|li| li.entity() == line)
                .is_some_and(|li| !li.serves().contains(&top))
        })
        .expect("Low elevator should exist and not serve Top");

    let err = sim.pin_assignment(low_car, top, CallDirection::Down);
    assert!(
        matches!(err, Err(crate::error::SimError::InvalidState { .. })),
        "cross-line pin should return InvalidState, got {err:?}"
    );
    let call = sim.world().hall_call(top, CallDirection::Down).unwrap();
    assert!(!call.pinned, "failed pin must not flag the call pinned");
}

/// Multi-line: a shared stop serving two groups creates one hall call
/// attributable to the group its rider is routed through. Verifies the
/// "first group wins" documentation on `HallCallMode`.
#[test]
fn shared_stop_attributes_call_to_first_group() {
    // Uses the default single-group / single-line config (no shared
    // groups exist there), but exercises the cross-tick shape of the
    // audit: call is created, assigned_car reflects dispatch, and no
    // duplicate HallCall exists. The stricter overlapping-groups
    // scenario isn't constructable via the public builder; covering it
    // here as the one-group variant is sufficient until a public API
    // for overlapping groups is added.
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(1), StopId(2), 70.0)
        .unwrap();
    let origin = sim.stop_entity(StopId(1)).unwrap();
    let calls: Vec<_> = sim.hall_calls().collect();
    assert_eq!(calls.len(), 1, "one call per (stop, direction)");
    assert_eq!(calls[0].stop, origin);
    assert_eq!(calls[0].direction, CallDirection::Up);
}

/// `commit_go_to_stop` must not re-emit `ElevatorAssigned` every tick
/// for a car that's already `MovingToStop(stop)`. Regression guard for
/// the reassignment idempotence case.
#[test]
fn reassignment_does_not_spam_elevator_assigned() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    sim.drain_events();
    // Step enough ticks to let dispatch commit + keep the car moving
    // (it won't arrive instantly). Count ElevatorAssigned emissions.
    let mut assigned_events = 0usize;
    for _ in 0..20 {
        sim.step();
        for e in sim.drain_events() {
            if matches!(e, Event::ElevatorAssigned { .. }) {
                assigned_events += 1;
            }
        }
    }
    assert!(
        assigned_events <= 1,
        "ElevatorAssigned should fire at most once per trip, got {assigned_events}"
    );
}

/// With `ack_latency_ticks = 0` (default), a call is acknowledged on
/// the same tick it was pressed.
#[test]
fn zero_latency_acknowledges_immediately() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    let origin = sim.stop_entity(StopId(0)).unwrap();
    let call = sim.world().hall_call(origin, CallDirection::Up).unwrap();
    assert_eq!(
        call.acknowledged_at,
        Some(sim.current_tick()),
        "zero-latency controller should ack on press tick"
    );
    // A matching HallCallAcknowledged event should have fired.
    let events = sim.drain_events();
    assert!(
        events
            .iter()
            .any(|e| matches!(e, Event::HallCallAcknowledged { .. })),
        "zero-latency press should emit HallCallAcknowledged immediately"
    );
}

/// A pinned call forces dispatch to commit the pinned car even when
/// another car would be the optimal choice under the strategy's cost.
#[test]
fn pinned_call_forces_specific_car() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    // Spawn a rider at StopId(1) going up to StopId(2) — auto-presses
    // the hall call at the origin.
    sim.spawn_rider_by_stop_id(StopId(1), StopId(2), 70.0)
        .unwrap();
    let origin = sim.stop_entity(StopId(1)).unwrap();
    // Pin the call to elevator 0 even though SCAN would pick whichever
    // car is closest.
    let cars = sim.world().elevator_ids();
    assert!(!cars.is_empty());
    let pinned_car = cars[0];
    sim.pin_assignment(pinned_car, origin, CallDirection::Up)
        .unwrap();
    // Step a few ticks; dispatch should commit the pinned car.
    for _ in 0..10 {
        sim.step();
    }
    let car = sim.world().elevator(pinned_car).unwrap();
    assert!(
        matches!(
            car.phase,
            crate::components::ElevatorPhase::MovingToStop(_)
                | crate::components::ElevatorPhase::DoorOpening
                | crate::components::ElevatorPhase::Loading
                | crate::components::ElevatorPhase::DoorClosing
        ) || car.target_stop == Some(origin),
        "pinned car should be committed to the pinned stop"
    );
}

/// When the car opens doors at a stop, any hall call in the car's
/// indicated direction is cleared and a `HallCallCleared` event fires.
#[test]
fn door_opening_clears_hall_call() {
    let mut sim = Simulation::new(&default_config(), scan()).unwrap();
    sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 70.0)
        .unwrap();
    let origin = sim.stop_entity(StopId(0)).unwrap();
    assert!(sim.world().hall_call(origin, CallDirection::Up).is_some());

    // Step until a HallCallCleared event fires for the origin.
    let mut cleared = false;
    for _ in 0..500 {
        sim.step();
        for e in sim.drain_events() {
            if let Event::HallCallCleared {
                stop,
                direction: CallDirection::Up,
                ..
            } = e
                && stop == origin
            {
                cleared = true;
            }
        }
        if cleared {
            break;
        }
    }
    assert!(cleared, "HallCallCleared should fire when car opens doors");
    assert!(
        sim.world().hall_call(origin, CallDirection::Up).is_none(),
        "hall call should be removed once cleared"
    );
}