Skip to main content

elevator_core/components/
elevator.rs

1//! Elevator state and configuration component.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashSet;
5
6use super::units::{Accel, Speed, Weight};
7use crate::door::{DoorCommand, DoorState};
8use crate::entity::EntityId;
9
10/// Maximum number of manual door commands queued per elevator.
11///
12/// Beyond this cap, the oldest entry is dropped (after adjacent-duplicate
13/// collapsing). Prevents runaway growth if a game submits commands faster
14/// than the sim can apply them.
15pub const DOOR_COMMAND_QUEUE_CAP: usize = 16;
16
17/// Direction an elevator's indicator lamps are signalling.
18///
19/// Derived from the pair of `going_up` / `going_down` flags on [`Elevator`].
20/// `Either` corresponds to both lamps lit — the car is idle and will accept
21/// riders heading either way. `Up` / `Down` correspond to an actively
22/// committed direction.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[non_exhaustive]
25pub enum Direction {
26    /// Car will serve upward trips only.
27    Up,
28    /// Car will serve downward trips only.
29    Down,
30    /// Car will serve either direction (idle).
31    Either,
32}
33
34impl std::fmt::Display for Direction {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        match self {
37            Self::Up => write!(f, "Up"),
38            Self::Down => write!(f, "Down"),
39            Self::Either => write!(f, "Either"),
40        }
41    }
42}
43
44/// Operational phase of an elevator.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
46#[non_exhaustive]
47pub enum ElevatorPhase {
48    /// Parked with no pending requests.
49    Idle,
50    /// Travelling toward a specific stop in response to a dispatch
51    /// assignment (carrying or about to pick up riders).
52    MovingToStop(EntityId),
53    /// Travelling toward a stop for repositioning — no rider service
54    /// obligation, will transition directly to [`Idle`] on arrival
55    /// without opening doors. Distinct from [`MovingToStop`] so that
56    /// downstream code (dispatch, UI, metrics) can treat opportunistic
57    /// moves differently from scheduled trips.
58    ///
59    /// [`MovingToStop`]: Self::MovingToStop
60    /// [`Idle`]: Self::Idle
61    Repositioning(EntityId),
62    /// Doors are currently opening.
63    DoorOpening,
64    /// Doors open; riders may board or exit.
65    Loading,
66    /// Doors are currently closing.
67    DoorClosing,
68    /// Stopped at a floor (doors closed, awaiting dispatch).
69    Stopped,
70}
71
72impl ElevatorPhase {
73    /// Whether the elevator is currently travelling (in either a dispatched
74    /// or a repositioning move).
75    #[must_use]
76    pub const fn is_moving(&self) -> bool {
77        matches!(self, Self::MovingToStop(_) | Self::Repositioning(_))
78    }
79
80    /// The target stop of a moving elevator, if any.
81    ///
82    /// Returns `Some(stop)` for both [`MovingToStop`] and [`Repositioning`]
83    /// variants; `None` otherwise.
84    ///
85    /// [`MovingToStop`]: Self::MovingToStop
86    /// [`Repositioning`]: Self::Repositioning
87    #[must_use]
88    pub const fn moving_target(&self) -> Option<EntityId> {
89        match self {
90            Self::MovingToStop(s) | Self::Repositioning(s) => Some(*s),
91            _ => None,
92        }
93    }
94}
95
96impl std::fmt::Display for ElevatorPhase {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        match self {
99            Self::Idle => write!(f, "Idle"),
100            Self::MovingToStop(id) => write!(f, "MovingToStop({id:?})"),
101            Self::Repositioning(id) => write!(f, "Repositioning({id:?})"),
102            Self::DoorOpening => write!(f, "DoorOpening"),
103            Self::Loading => write!(f, "Loading"),
104            Self::DoorClosing => write!(f, "DoorClosing"),
105            Self::Stopped => write!(f, "Stopped"),
106        }
107    }
108}
109
110/// Component for an elevator entity.
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub struct Elevator {
113    /// Current operational phase.
114    pub(crate) phase: ElevatorPhase,
115    /// Door finite-state machine.
116    pub(crate) door: DoorState,
117    /// Maximum travel speed (distance/tick).
118    pub(crate) max_speed: Speed,
119    /// Acceleration rate (distance/tick^2).
120    pub(crate) acceleration: Accel,
121    /// Deceleration rate (distance/tick^2).
122    pub(crate) deceleration: Accel,
123    /// Maximum weight the car can carry.
124    pub(crate) weight_capacity: Weight,
125    /// Total weight of riders currently aboard.
126    pub(crate) current_load: Weight,
127    /// Entity IDs of riders currently aboard.
128    pub(crate) riders: Vec<EntityId>,
129    /// Stop entity the car is heading toward, if any.
130    pub(crate) target_stop: Option<EntityId>,
131    /// Ticks for a door open/close transition.
132    pub(crate) door_transition_ticks: u32,
133    /// Ticks the door stays fully open.
134    pub(crate) door_open_ticks: u32,
135    /// Line entity this car belongs to.
136    #[serde(alias = "group")]
137    pub(crate) line: EntityId,
138    /// Whether this elevator is currently repositioning (not serving a dispatch).
139    #[serde(default)]
140    pub(crate) repositioning: bool,
141    /// Stop entity IDs this elevator cannot serve (access restriction).
142    #[serde(default)]
143    pub(crate) restricted_stops: HashSet<EntityId>,
144    /// Speed multiplier for Inspection mode (0.0..1.0).
145    #[serde(default = "default_inspection_speed_factor")]
146    pub(crate) inspection_speed_factor: f64,
147    /// Up-direction indicator lamp: whether this car will serve upward trips.
148    ///
149    /// Auto-managed by the dispatch phase: set true when heading up (or idle),
150    /// false while actively committed to a downward trip. Affects boarding:
151    /// a rider whose next leg goes up will not board a car with `going_up=false`.
152    #[serde(default = "default_true")]
153    pub(crate) going_up: bool,
154    /// Down-direction indicator lamp: whether this car will serve downward trips.
155    ///
156    /// Auto-managed by the dispatch phase: set true when heading down (or idle),
157    /// false while actively committed to an upward trip. Affects boarding:
158    /// a rider whose next leg goes down will not board a car with `going_down=false`.
159    #[serde(default = "default_true")]
160    pub(crate) going_down: bool,
161    /// Count of rounded-floor transitions (passing-floors + arrivals).
162    /// Useful as a scoring axis for efficiency — fewer moves per delivery
163    /// means less wasted travel.
164    #[serde(default)]
165    pub(crate) move_count: u64,
166    /// Pending manual door-control commands. Processed at the start of the
167    /// doors phase; commands that aren't yet valid remain queued.
168    #[serde(default)]
169    pub(crate) door_command_queue: Vec<DoorCommand>,
170    /// Target velocity commanded by the game while in
171    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
172    ///
173    /// `None` means no command is active — the car coasts to a stop using
174    /// `deceleration`. Read the current target via
175    /// [`Elevator::manual_target_velocity`].
176    #[serde(default)]
177    pub(crate) manual_target_velocity: Option<f64>,
178}
179
180/// Default inspection speed factor (25% of normal speed).
181const fn default_inspection_speed_factor() -> f64 {
182    0.25
183}
184
185/// Default value for direction indicator fields (both lamps on = idle/either direction).
186const fn default_true() -> bool {
187    true
188}
189
190impl Elevator {
191    /// Current operational phase.
192    #[must_use]
193    pub const fn phase(&self) -> ElevatorPhase {
194        self.phase
195    }
196
197    /// Door finite-state machine.
198    #[must_use]
199    pub const fn door(&self) -> &DoorState {
200        &self.door
201    }
202
203    /// Maximum travel speed (distance/tick).
204    #[must_use]
205    pub const fn max_speed(&self) -> Speed {
206        self.max_speed
207    }
208
209    /// Acceleration rate (distance/tick^2).
210    #[must_use]
211    pub const fn acceleration(&self) -> Accel {
212        self.acceleration
213    }
214
215    /// Deceleration rate (distance/tick^2).
216    #[must_use]
217    pub const fn deceleration(&self) -> Accel {
218        self.deceleration
219    }
220
221    /// Maximum weight the car can carry.
222    #[must_use]
223    pub const fn weight_capacity(&self) -> Weight {
224        self.weight_capacity
225    }
226
227    /// Total weight of riders currently aboard.
228    #[must_use]
229    pub const fn current_load(&self) -> Weight {
230        self.current_load
231    }
232
233    /// Entity IDs of riders currently aboard.
234    #[must_use]
235    pub fn riders(&self) -> &[EntityId] {
236        &self.riders
237    }
238
239    /// Stop entity the car is heading toward, if any.
240    #[must_use]
241    pub const fn target_stop(&self) -> Option<EntityId> {
242        self.target_stop
243    }
244
245    /// Ticks for a door open/close transition.
246    #[must_use]
247    pub const fn door_transition_ticks(&self) -> u32 {
248        self.door_transition_ticks
249    }
250
251    /// Ticks the door stays fully open.
252    #[must_use]
253    pub const fn door_open_ticks(&self) -> u32 {
254        self.door_open_ticks
255    }
256
257    /// Line entity this car belongs to.
258    #[must_use]
259    pub const fn line(&self) -> EntityId {
260        self.line
261    }
262
263    /// Whether this elevator is currently repositioning (not serving a dispatch).
264    #[must_use]
265    pub const fn repositioning(&self) -> bool {
266        self.repositioning
267    }
268
269    /// Stop entity IDs this elevator cannot serve (access restriction).
270    #[must_use]
271    pub const fn restricted_stops(&self) -> &HashSet<EntityId> {
272        &self.restricted_stops
273    }
274
275    /// Speed multiplier applied during Inspection mode.
276    #[must_use]
277    pub const fn inspection_speed_factor(&self) -> f64 {
278        self.inspection_speed_factor
279    }
280
281    /// Whether this car's up-direction indicator lamp is lit.
282    ///
283    /// A lit up-lamp signals the car will serve upward-travelling riders.
284    /// Both lamps lit means the car is idle and will accept either direction.
285    #[must_use]
286    pub const fn going_up(&self) -> bool {
287        self.going_up
288    }
289
290    /// Whether this car's down-direction indicator lamp is lit.
291    ///
292    /// A lit down-lamp signals the car will serve downward-travelling riders.
293    /// Both lamps lit means the car is idle and will accept either direction.
294    #[must_use]
295    pub const fn going_down(&self) -> bool {
296        self.going_down
297    }
298
299    /// Direction this car is currently committed to, derived from the pair
300    /// of indicator-lamp flags.
301    ///
302    /// - `Direction::Up` — only `going_up` is set
303    /// - `Direction::Down` — only `going_down` is set
304    /// - `Direction::Either` — both lamps lit (car is idle / accepting
305    ///   either direction), or neither is set (treated as `Either` too,
306    ///   though the dispatch phase normally keeps at least one lit)
307    #[must_use]
308    pub const fn direction(&self) -> Direction {
309        match (self.going_up, self.going_down) {
310            (true, false) => Direction::Up,
311            (false, true) => Direction::Down,
312            _ => Direction::Either,
313        }
314    }
315
316    /// Count of rounded-floor transitions this elevator has made
317    /// (both passing-floor crossings and arrivals).
318    #[must_use]
319    pub const fn move_count(&self) -> u64 {
320        self.move_count
321    }
322
323    /// Pending manual door-control commands for this elevator.
324    ///
325    /// Populated by
326    /// [`Simulation::open_door`](crate::sim::Simulation::open_door)
327    /// and its siblings. Commands are drained at the start of each doors-phase
328    /// tick; any that aren't yet valid remain queued.
329    #[must_use]
330    pub fn door_command_queue(&self) -> &[DoorCommand] {
331        &self.door_command_queue
332    }
333
334    /// Currently commanded target velocity for
335    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
336    ///
337    /// Returns `None` if no target is set, meaning the car coasts to a
338    /// stop using the configured deceleration. Positive values command
339    /// upward travel, negative values command downward travel.
340    #[must_use]
341    pub const fn manual_target_velocity(&self) -> Option<f64> {
342        self.manual_target_velocity
343    }
344}