Skip to main content

elevator_core/
config.rs

1//! Building and elevator configuration (RON-deserializable).
2
3use crate::components::{Accel, Orientation, SpatialPosition, Speed, Weight};
4use crate::dispatch::{BuiltinReposition, BuiltinStrategy, HallCallMode};
5use crate::stop::{StopConfig, StopId};
6use serde::{Deserialize, Serialize};
7
8/// Top-level simulation configuration, loadable from RON.
9///
10/// Validated at construction time by [`Simulation::new()`](crate::sim::Simulation::new)
11/// or [`SimulationBuilder::build()`](crate::builder::SimulationBuilder::build).
12#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct SimConfig {
14    /// Building layout describing the stops (floors/stations) along the shaft.
15    pub building: BuildingConfig,
16    /// Elevator cars to install in the building.
17    ///
18    /// Legacy flat list — used when `building.lines` is `None`.
19    /// When explicit lines are provided, elevators live inside each
20    /// [`LineConfig`] instead.
21    #[serde(default)]
22    pub elevators: Vec<ElevatorConfig>,
23    /// Global simulation timing parameters.
24    pub simulation: SimulationParams,
25    /// Passenger spawning parameters used by the game layer.
26    ///
27    /// The core library does not consume these directly; they are stored here
28    /// for games and traffic generators that read the config.
29    pub passenger_spawning: PassengerSpawnConfig,
30}
31
32/// Building layout.
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct BuildingConfig {
35    /// Human-readable building name, displayed in UIs and logs.
36    pub name: String,
37    /// Ordered list of stops in the building.
38    ///
39    /// Must contain at least one stop. Each stop has a unique [`StopId`] and
40    /// an arbitrary position along the shaft axis. Positions need not be
41    /// uniformly spaced — this enables buildings, skyscrapers, and space
42    /// elevators with varying inter-stop distances.
43    pub stops: Vec<StopConfig>,
44    /// Lines (physical paths). If `None`, auto-inferred from the flat
45    /// elevator list on [`SimConfig`].
46    #[serde(default)]
47    pub lines: Option<Vec<LineConfig>>,
48    /// Dispatch groups. If `None`, auto-inferred (single group with all lines).
49    #[serde(default)]
50    pub groups: Option<Vec<GroupConfig>>,
51}
52
53/// Configuration for a single elevator car.
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct ElevatorConfig {
56    /// Numeric identifier for this elevator, unique within the config.
57    ///
58    /// Mapped to an [`EntityId`](crate::entity::EntityId) at construction
59    /// time; not used at runtime.
60    pub id: u32,
61    /// Human-readable elevator name, displayed in UIs and logs.
62    pub name: String,
63    /// Maximum travel speed in distance units per second.
64    ///
65    /// Must be positive. The trapezoidal velocity profile accelerates up to
66    /// this speed, cruises, then decelerates to stop at the target.
67    ///
68    /// Default (from `SimulationBuilder`): `2.0`.
69    pub max_speed: Speed,
70    /// Acceleration rate in distance units per second squared.
71    ///
72    /// Must be positive. Controls how quickly the elevator reaches
73    /// `max_speed` from rest.
74    ///
75    /// Default (from `SimulationBuilder`): `1.5`.
76    pub acceleration: Accel,
77    /// Deceleration rate in distance units per second squared.
78    ///
79    /// Must be positive. Controls how quickly the elevator slows to a stop
80    /// when approaching a target. May differ from `acceleration` for
81    /// asymmetric motion profiles.
82    ///
83    /// Default (from `SimulationBuilder`): `2.0`.
84    pub deceleration: Accel,
85    /// Maximum total weight the elevator car can carry.
86    ///
87    /// Must be positive. Riders whose weight would exceed this limit are
88    /// rejected during the loading phase.
89    ///
90    /// Units: same as rider weight (typically kilograms).
91    /// Default (from `SimulationBuilder`): `800.0`.
92    pub weight_capacity: Weight,
93    /// The [`StopId`] where this elevator starts at simulation init.
94    ///
95    /// Must reference an existing stop in the building config.
96    pub starting_stop: StopId,
97    /// How many ticks the doors remain fully open before closing.
98    ///
99    /// During this window, riders may board or exit. Longer values
100    /// increase loading opportunity but reduce throughput.
101    ///
102    /// Units: simulation ticks.
103    /// Default (from `SimulationBuilder`): `10`.
104    pub door_open_ticks: u32,
105    /// How many ticks a door open or close transition takes.
106    ///
107    /// Models the mechanical travel time of the door panels. No boarding
108    /// or exiting occurs during transitions.
109    ///
110    /// Units: simulation ticks.
111    /// Default (from `SimulationBuilder`): `5`.
112    pub door_transition_ticks: u32,
113    /// Stop IDs this elevator cannot serve (access restriction).
114    ///
115    /// Riders whose current destination is in this list are rejected
116    /// with [`RejectionReason::AccessDenied`](crate::error::RejectionReason::AccessDenied)
117    /// during the loading phase.
118    ///
119    /// Default: empty (no restrictions).
120    #[serde(default)]
121    pub restricted_stops: Vec<StopId>,
122    /// Energy profile for this elevator. If `None`, energy is not tracked.
123    ///
124    /// Requires the `energy` feature.
125    #[cfg(feature = "energy")]
126    #[serde(default)]
127    pub energy_profile: Option<crate::energy::EnergyProfile>,
128    /// Service mode at simulation start. Defaults to `Normal`.
129    #[serde(default)]
130    pub service_mode: Option<crate::components::ServiceMode>,
131    /// Speed multiplier for Inspection mode (0.0..1.0). Defaults to 0.25.
132    #[serde(default = "default_inspection_speed_factor")]
133    pub inspection_speed_factor: f64,
134}
135
136/// Default inspection speed factor (25% of normal speed).
137const fn default_inspection_speed_factor() -> f64 {
138    0.25
139}
140
141impl Default for ElevatorConfig {
142    /// Reasonable defaults matching the physics values the rest of
143    /// this struct's field docs advertise. Override any field with
144    /// struct-update syntax:
145    ///
146    /// ```
147    /// use elevator_core::config::ElevatorConfig;
148    /// use elevator_core::components::Speed;
149    /// use elevator_core::stop::StopId;
150    ///
151    /// let fast = ElevatorConfig {
152    ///     name: "Express".into(),
153    ///     max_speed: Speed::from(6.0),
154    ///     starting_stop: StopId(0),
155    ///     ..Default::default()
156    /// };
157    /// # let _ = fast;
158    /// ```
159    ///
160    /// `starting_stop` defaults to `StopId(0)` — the conventional lobby
161    /// id. Override if your config uses a different bottom-stop id.
162    fn default() -> Self {
163        Self {
164            id: 0,
165            name: "Elevator 1".into(),
166            max_speed: Speed::from(2.0),
167            acceleration: Accel::from(1.5),
168            deceleration: Accel::from(2.0),
169            weight_capacity: Weight::from(800.0),
170            starting_stop: StopId(0),
171            door_open_ticks: 10,
172            door_transition_ticks: 5,
173            restricted_stops: Vec::new(),
174            #[cfg(feature = "energy")]
175            energy_profile: None,
176            service_mode: None,
177            inspection_speed_factor: default_inspection_speed_factor(),
178        }
179    }
180}
181
182impl Default for BuildingConfig {
183    fn default() -> Self {
184        Self {
185            name: "Building".into(),
186            stops: Vec::new(),
187            lines: None,
188            groups: None,
189        }
190    }
191}
192
193/// Global simulation timing parameters.
194#[derive(Debug, Clone, Serialize, Deserialize)]
195pub struct SimulationParams {
196    /// Number of simulation ticks per real-time second.
197    ///
198    /// Must be positive. Determines the time delta per tick (`dt = 1.0 / ticks_per_second`).
199    /// Higher values yield finer-grained simulation at the cost of more
200    /// computation per wall-clock second.
201    ///
202    /// Default (from `SimulationBuilder`): `60.0`.
203    pub ticks_per_second: f64,
204}
205
206impl Default for SimulationParams {
207    fn default() -> Self {
208        Self {
209            ticks_per_second: 60.0,
210        }
211    }
212}
213
214/// Passenger spawning parameters (used by the game layer).
215///
216/// The core simulation does not spawn passengers automatically; these values
217/// are advisory and consumed by game code or traffic generators.
218///
219/// This struct is always available regardless of feature flags. The built-in
220/// traffic generation that consumes it requires the `traffic` feature.
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct PassengerSpawnConfig {
223    /// Mean interval in ticks between passenger spawns.
224    ///
225    /// Used by traffic generators for Poisson-distributed arrivals.
226    ///
227    /// Units: simulation ticks.
228    /// Default (from `SimulationBuilder`): `120`.
229    pub mean_interval_ticks: u32,
230    /// `(min, max)` weight range for randomly spawned passengers.
231    ///
232    /// Weights are drawn uniformly from this range by traffic generators.
233    ///
234    /// Units: same as elevator `weight_capacity` (typically kilograms).
235    /// Default (from `SimulationBuilder`): `(50.0, 100.0)`.
236    pub weight_range: (f64, f64),
237}
238
239impl Default for PassengerSpawnConfig {
240    fn default() -> Self {
241        Self {
242            mean_interval_ticks: 120,
243            weight_range: (50.0, 100.0),
244        }
245    }
246}
247
248/// Configuration for a single line (physical path).
249///
250/// A line represents a shaft, tether, track, or other physical pathway
251/// that one or more elevator cars travel along. Lines belong to a
252/// [`GroupConfig`] for dispatch purposes.
253#[derive(Debug, Clone, Default, Serialize, Deserialize)]
254pub struct LineConfig {
255    /// Unique line identifier (within the config).
256    pub id: u32,
257    /// Human-readable name.
258    pub name: String,
259    /// Stops served by this line (references [`StopConfig::id`]).
260    pub serves: Vec<StopId>,
261    /// Elevators on this line.
262    pub elevators: Vec<ElevatorConfig>,
263    /// Physical orientation (defaults to Vertical).
264    #[serde(default)]
265    pub orientation: Orientation,
266    /// Optional floor-plan position.
267    #[serde(default)]
268    pub position: Option<SpatialPosition>,
269    /// Lowest reachable position (auto-computed from stops if `None`).
270    #[serde(default)]
271    pub min_position: Option<f64>,
272    /// Highest reachable position (auto-computed from stops if `None`).
273    #[serde(default)]
274    pub max_position: Option<f64>,
275    /// Max cars on this line (`None` = unlimited).
276    #[serde(default)]
277    pub max_cars: Option<usize>,
278}
279
280/// Configuration for an elevator dispatch group.
281///
282/// A group is the logical dispatch unit containing one or more lines.
283/// All elevators within the group share a single [`BuiltinStrategy`].
284///
285/// ## RON example — destination dispatch with controller latency
286///
287/// ```ron
288/// GroupConfig(
289///     id: 0,
290///     name: "Main",
291///     lines: [1],
292///     dispatch: Destination,
293///     hall_call_mode: Some(Destination),
294///     ack_latency_ticks: Some(15),
295/// )
296/// ```
297///
298/// `hall_call_mode` and `ack_latency_ticks` are optional; omitting them
299/// keeps the legacy behavior (Classic collective control, zero latency).
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub struct GroupConfig {
302    /// Unique group identifier.
303    pub id: u32,
304    /// Human-readable name.
305    pub name: String,
306    /// Line IDs belonging to this group (references [`LineConfig::id`]).
307    pub lines: Vec<u32>,
308    /// Dispatch strategy for this group.
309    pub dispatch: BuiltinStrategy,
310    /// Optional repositioning strategy for idle elevators.
311    ///
312    /// When `None`, idle elevators in this group stay where they stopped.
313    #[serde(default)]
314    pub reposition: Option<BuiltinReposition>,
315    /// How hall calls reveal rider destinations to dispatch.
316    ///
317    /// `None` defers to [`HallCallMode::default()`] (Classic collective
318    /// control). Set to `Some(HallCallMode::Destination)` to model a
319    /// DCS lobby-kiosk group, which is required to make
320    /// [`crate::dispatch::DestinationDispatch`] consult hall-call
321    /// destinations.
322    #[serde(default)]
323    pub hall_call_mode: Option<HallCallMode>,
324    /// Controller ack latency in ticks (button press → dispatch sees
325    /// the call). `None` means zero — dispatch sees presses immediately.
326    /// Realistic values at 60 Hz land around 5–30 ticks.
327    #[serde(default)]
328    pub ack_latency_ticks: Option<u32>,
329}