elevator-core 20.13.0

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
//! Phase 3: update position/velocity for moving elevators.

use crate::components::{ElevatorPhase, Route};
use crate::door::DoorState;
use crate::entity::EntityId;
use crate::events::{Event, EventBus};
use crate::metrics::Metrics;
use crate::movement::tick_movement;
#[cfg(feature = "loop_lines")]
use crate::movement::tick_movement_cyclic;
use crate::world::{SortedStops, World};

use super::PhaseContext;
use super::dispatch::update_indicators;

/// Compute direction lamps for a just-arrived car from aboard-rider
/// destinations and the remaining destination queue. The travel-leg
/// direction (`going_up` / `going_down` during `MovingToStop`) reflects
/// where the car came *from* — on arrival at an edge floor (top or
/// bottom) or after delivering the last passenger for one direction,
/// it's stale. The loading-phase direction filter trusts these lamps,
/// so a stale `(up=true, down=false)` silently rejects every down-rider
/// waiting at the top floor.
///
/// Returns `(true, true)` when there's no committed next direction (no
/// aboard riders and no queued stops) — the car is effectively idle at
/// this stop and should accept hall calls in either direction. The same
/// rule applies when the car will continue in both directions (unusual
/// but possible with a multi-destination queue that crosses back over
/// the stop).
fn direction_from_remaining_work(world: &World, eid: EntityId, stop_pos: f64) -> (bool, bool) {
    let Some(car) = world.elevator(eid) else {
        return (true, true);
    };
    let mut needs_up = false;
    let mut needs_down = false;
    for &rid in &car.riders {
        if let Some(dest) = world.route(rid).and_then(Route::current_destination)
            && let Some(dest_pos) = world.stop_position(dest)
        {
            if dest_pos > stop_pos {
                needs_up = true;
            } else if dest_pos < stop_pos {
                needs_down = true;
            }
        }
    }
    if let Some(q) = world.destination_queue(eid) {
        for &next_stop in q {
            if let Some(next_pos) = world.stop_position(next_stop) {
                if next_pos > stop_pos {
                    needs_up = true;
                } else if next_pos < stop_pos {
                    needs_down = true;
                }
            }
        }
    }
    // No committed next direction → accept both. Ensures a car that
    // arrived for an unassigned hall call doesn't bounce a rider going
    // the opposite direction from its last leg.
    if !needs_up && !needs_down {
        return (true, true);
    }
    (needs_up, needs_down)
}

/// Update position/velocity for all moving elevators.
#[allow(clippy::too_many_lines)]
pub fn run(
    world: &mut World,
    events: &mut EventBus,
    ctx: &PhaseContext,
    elevator_ids: &[crate::entity::EntityId],
    metrics: &mut Metrics,
) {
    for &eid in elevator_ids {
        if world.is_disabled(eid) {
            continue;
        }
        if world
            .service_mode(eid)
            .is_some_and(|m| *m == crate::components::ServiceMode::Manual)
        {
            tick_manual(world, events, ctx, eid, metrics);
            continue;
        }
        let target_stop_eid = match world.elevator(eid) {
            Some(car) => match car.phase {
                ElevatorPhase::MovingToStop(stop_eid) | ElevatorPhase::Repositioning(stop_eid) => {
                    stop_eid
                }
                _ => continue,
            },
            None => continue,
        };

        let Some(target_pos) = world.stop_position(target_stop_eid) else {
            continue;
        };
        let Some(pos_comp) = world.position(eid) else {
            continue;
        };
        let pos = pos_comp.value;
        let Some(vel_comp) = world.velocity(eid) else {
            continue;
        };
        let vel = vel_comp.value;

        let is_inspection = world
            .service_mode(eid)
            .is_some_and(|m| *m == crate::components::ServiceMode::Inspection);

        // Extract elevator params upfront — we already confirmed elevator(eid) is Some above.
        let Some(car) = world.elevator(eid) else {
            continue;
        };
        let max_speed = if is_inspection {
            car.max_speed.value() * car.inspection_speed_factor
        } else {
            car.max_speed.value()
        };
        let acceleration = car.acceleration.value();
        let deceleration = car.deceleration.value();
        let door_transition_ticks = car.door_transition_ticks;
        let door_open_ticks = car.door_open_ticks;
        // Authoritative source for "is this a reposition trip?" is the
        // phase variant. The `repositioning` bool is a legacy mirror kept
        // around for downstream predicates (e.g. `Elevator::repositioning`)
        // — asserted equivalent below so a desync in either direction is
        // caught early in debug builds.
        let is_repositioning = matches!(car.phase, ElevatorPhase::Repositioning(_));
        debug_assert_eq!(
            is_repositioning, car.repositioning,
            "ElevatorPhase::Repositioning and car.repositioning flag diverged at eid={eid:?}"
        );

        // Loop cars use cyclic motion: position wraps modulo the line's
        // circumference, the integrator picks the forward path to the
        // target, and seam-crossings (old_pos > new_pos within a single
        // tick) are emitted in two passing-floor ranges below. Linear
        // cars take the existing trapezoidal-on-axis path.
        #[cfg(feature = "loop_lines")]
        let circumference = world
            .line(
                world
                    .elevator(eid)
                    .map_or_else(EntityId::default, |c| c.line),
            )
            .and_then(crate::components::Line::circumference);
        // Mirrored unconditional binding so the seam-aware passing-floor
        // logic below (which is itself unconditional, just behaviourally
        // a no-op without a `circumference`) compiles on either feature
        // configuration.
        #[cfg(not(feature = "loop_lines"))]
        let circumference: Option<f64> = None;

        #[cfg(feature = "loop_lines")]
        #[allow(
            clippy::option_if_let_else,
            reason = "the two arms call different functions with different arities; map_or_else closures would just duplicate the eight-argument call"
        )]
        let result = match circumference {
            Some(c) => tick_movement_cyclic(
                pos,
                vel,
                target_pos,
                max_speed,
                acceleration,
                deceleration,
                ctx.dt,
                c,
            ),
            None => tick_movement(
                pos,
                vel,
                target_pos,
                max_speed,
                acceleration,
                deceleration,
                ctx.dt,
            ),
        };
        #[cfg(not(feature = "loop_lines"))]
        let result = tick_movement(
            pos,
            vel,
            target_pos,
            max_speed,
            acceleration,
            deceleration,
            ctx.dt,
        );

        let old_pos = pos;
        let new_pos = result.position;

        if let Some(p) = world.position_mut(eid) {
            p.value = new_pos;
        }
        if let Some(v) = world.velocity_mut(eid) {
            v.value = result.velocity;
        }

        // Track repositioning distance. On a Loop line a tick that wraps
        // through the seam has `new_pos < old_pos` even though the car
        // travelled forward; the chord `(new - old).abs()` would record
        // `circumference - arc` instead of the actual arc travelled.
        // Compute via forward cyclic distance when a circumference is
        // present so the metric tracks the *real* path.
        if is_repositioning {
            let dist = circumference.map_or_else(
                || (new_pos - old_pos).abs(),
                |c| crate::components::cyclic::forward_distance(old_pos, new_pos, c),
            );
            if dist > 0.0 {
                metrics.record_reposition_distance(dist);
            }
        }

        // Emit PassingFloor for any stops crossed between old and new position
        // (excluding the target stop — that gets an ElevatorArrived instead).
        //
        // On a Loop line a single tick can cross the seam: `old_pos > new_pos`
        // even though we travelled forward. In that case the swept range is
        // `[old_pos, circumference) ∪ [0, new_pos)` rather than a single
        // `[lo, hi)` interval, so we walk the sorted-stops index in two
        // passes. Linear and Loop-without-seam ticks fall through to the
        // single-pass path.
        let mut passing_moves: u64 = 0;
        if !result.arrived {
            let crossed_seam = circumference.is_some() && new_pos < old_pos;
            // Loop cars always patrol forward; otherwise the existing
            // sign-of-displacement rule still holds.
            let moving_up = circumference.is_some() || new_pos > old_pos;

            // `inclusive_lo = true` includes a stop at exactly `lo` in the
            // emitted range. The seam-crossing case uses this for the
            // wrap-around segment `[0, new_pos)`: the car physically
            // sweeps through position 0, so a stop sitting there should
            // fire `PassingFloor`. The default exclusive form is used for
            // the linear case and the seam's pre-wrap segment, where `lo`
            // is the position the car *left* this tick and would
            // double-count if included.
            let emit_range = |lo: f64,
                              hi: f64,
                              inclusive_lo: bool,
                              world_ref: &World,
                              events_ref: &mut EventBus| {
                if hi <= lo + 1e-9 {
                    return 0u64;
                }
                let Some(sorted) = world_ref.resource::<SortedStops>() else {
                    return 0;
                };
                let lo_threshold = if inclusive_lo { lo - 1e-9 } else { lo + 1e-9 };
                let start = sorted.0.partition_point(|&(p, _)| p <= lo_threshold);
                let end = sorted.0.partition_point(|&(p, _)| p < hi - 1e-9);
                let mut count = 0;
                for &(_, stop_eid) in &sorted.0[start..end] {
                    if stop_eid == target_stop_eid {
                        continue;
                    }
                    events_ref.emit(Event::PassingFloor {
                        elevator: eid,
                        stop: stop_eid,
                        moving_up,
                        tick: ctx.tick,
                    });
                    count += 1;
                }
                count
            };

            if crossed_seam {
                let c = circumference.unwrap_or(0.0);
                // Pre-wrap: car was at `old_pos`, exclude it.
                passing_moves += emit_range(old_pos, c, false, world, events);
                // Post-wrap: car physically crossed position 0 forward,
                // so include a stop sitting there.
                passing_moves += emit_range(0.0, new_pos, true, world, events);
            } else {
                let (lo, hi) = if moving_up {
                    (old_pos, new_pos)
                } else {
                    (new_pos, old_pos)
                };
                passing_moves += emit_range(lo, hi, false, world, events);
            }
        }
        if passing_moves > 0 {
            // Only credit the aggregate if the per-elevator counter could actually
            // be incremented — keep the invariant total_moves == sum(per-elevator).
            if let Some(car) = world.elevator_mut(eid) {
                car.move_count += passing_moves;
                metrics.total_moves += passing_moves;
            }
        }

        if result.arrived {
            // Pop the queue front if it matches the target we arrived at.
            if let Some(q) = world.destination_queue_mut(eid)
                && q.front() == Some(target_stop_eid)
            {
                q.pop_front();
            }
            // Tracked and applied after the `&mut car` block ends —
            // `world.resource_mut` can't coexist with the car borrow.
            let mut reposition_arrived = false;
            let Some(car) = world.elevator_mut(eid) else {
                continue;
            };
            // Arrival is a floor crossing too — count it for both repositioning
            // and normal arrivals so the passing-floor + arrival accounting stays
            // consistent. Passing floors during a repositioning trip are already
            // counted above; skipping the arrival here would undercount.
            car.move_count += 1;
            metrics.total_moves += 1;
            if is_repositioning {
                // Repositioned elevators go directly to Idle — no door cycle.
                // A reposition trip sets the indicators to its travel
                // direction (via `indicators_for_travel` in dispatch /
                // advance_queue), but once the car is parked with no
                // committed work the lamps should read "both" — otherwise
                // the next dispatch tick rejects opposite-direction hall
                // calls at this stop via `pair_is_useful`, and the
                // Hungarian picks a different, farther car to serve
                // them while this one sits there.
                let indicators_dirty = !(car.going_up && car.going_down);
                car.phase = ElevatorPhase::Idle;
                car.target_stop = None;
                car.repositioning = false;
                car.going_up = true;
                car.going_down = true;
                events.emit(Event::ElevatorRepositioned {
                    elevator: eid,
                    at_stop: target_stop_eid,
                    tick: ctx.tick,
                });
                events.emit(Event::ElevatorIdle {
                    elevator: eid,
                    at_stop: Some(target_stop_eid),
                    tick: ctx.tick,
                });
                if indicators_dirty {
                    events.emit(Event::DirectionIndicatorChanged {
                        elevator: eid,
                        going_up: true,
                        going_down: true,
                        tick: ctx.tick,
                    });
                }
                // Arm the reposition cooldown below, once the
                // `&mut car` borrow ends — `world.resource_mut`
                // needs `&mut world` and can't coexist with it.
                reposition_arrived = true;
            } else {
                car.phase = ElevatorPhase::DoorOpening;
                car.door = DoorState::request_open(door_transition_ticks, door_open_ticks);
                events.emit(Event::ElevatorArrived {
                    elevator: eid,
                    at_stop: target_stop_eid,
                    tick: ctx.tick,
                });
                // Refresh direction lamps from remaining work (aboard
                // riders + queue) rather than the just-ended travel leg.
                // Without this the loading-phase direction filter rejects
                // every rider wanting to go opposite to the travel
                // direction — the penthouse down-rider bug.
                let (new_up, new_down) = direction_from_remaining_work(world, eid, target_pos);
                update_indicators(world, events, eid, new_up, new_down, ctx.tick);
            }
            if reposition_arrived
                && let Some(cooldowns) =
                    world.resource_mut::<crate::dispatch::reposition::RepositionCooldowns>()
            {
                cooldowns.record_arrival(eid, ctx.tick);
            }
        }
    }
}

/// One tick of manual-mode physics: ramp velocity toward
/// `manual_target_velocity` using the car's `acceleration`/`deceleration`
/// caps, then integrate position. Emits [`Event::PassingFloor`] for any
/// stops crossed during the tick.
fn tick_manual(
    world: &mut World,
    events: &mut EventBus,
    ctx: &PhaseContext,
    eid: crate::entity::EntityId,
    metrics: &mut Metrics,
) {
    let Some(car) = world.elevator(eid) else {
        return;
    };
    let target = car.manual_target_velocity.unwrap_or(0.0);
    let accel = car.acceleration.value();
    let decel = car.deceleration.value();
    let max_speed = car.max_speed.value();
    let Some(pos_comp) = world.position(eid) else {
        return;
    };
    let old_pos = pos_comp.value;
    let Some(vel_comp) = world.velocity(eid) else {
        return;
    };
    let vel = vel_comp.value;

    // Signed clamp of target to the kinematic cap.
    let target = target.clamp(-max_speed, max_speed);

    // Pick the right rate: if we're slowing down (target is closer to 0
    // than current speed, or opposite sign), use deceleration; otherwise
    // use acceleration.
    let slowing = target.abs() < vel.abs() || target.signum() * vel.signum() < 0.0;
    let rate = if slowing { decel } else { accel };
    let dv_max = rate * ctx.dt;

    let new_vel = if (target - vel).abs() <= dv_max {
        target
    } else if target > vel {
        vel + dv_max
    } else {
        vel - dv_max
    };

    let new_pos = crate::fp::fma(new_vel, ctx.dt, old_pos);

    if let Some(p) = world.position_mut(eid) {
        p.value = new_pos;
    }
    if let Some(v) = world.velocity_mut(eid) {
        v.value = new_vel;
    }

    // PassingFloor for every stop actually crossed.
    let mut passing_moves: u64 = 0;
    let (lo, hi) = if new_pos >= old_pos {
        (old_pos, new_pos)
    } else {
        (new_pos, old_pos)
    };
    let moving_up = new_pos > old_pos;
    if (hi - lo) > 1e-9
        && let Some(sorted) = world.resource::<SortedStops>()
    {
        let start = sorted.0.partition_point(|&(p, _)| p <= lo + 1e-9);
        let end = sorted.0.partition_point(|&(p, _)| p < hi - 1e-9);
        for &(_, stop_eid) in &sorted.0[start..end] {
            events.emit(Event::PassingFloor {
                elevator: eid,
                stop: stop_eid,
                moving_up,
                tick: ctx.tick,
            });
            passing_moves += 1;
        }
    }
    if passing_moves > 0
        && let Some(car) = world.elevator_mut(eid)
    {
        car.move_count += passing_moves;
        metrics.total_moves += passing_moves;
    }
}