elevator_core/sim.rs
1//! Top-level simulation runner and tick loop.
2//!
3//! # Essential API
4//!
5//! `Simulation` exposes a large surface, but most users only need the
6//! ~15 methods below, grouped by the order they appear in a typical
7//! game loop.
8//!
9//! ### Construction
10//!
11//! - [`SimulationBuilder::demo()`](crate::builder::SimulationBuilder::demo)
12//! or [`SimulationBuilder::from_config()`](crate::builder::SimulationBuilder::from_config)
13//! — fluent entry point; call [`.build()`](crate::builder::SimulationBuilder::build)
14//! to get a `Simulation`.
15//! - [`Simulation::new()`](crate::sim::Simulation::new) — direct construction from
16//! `&SimConfig` + a dispatch strategy.
17//!
18//! ### Per-tick driving
19//!
20//! - [`Simulation::step()`](crate::sim::Simulation::step) — run all 8 phases.
21//! - [`Simulation::current_tick()`](crate::sim::Simulation::current_tick) — the
22//! current tick counter.
23//!
24//! ### Spawning and rerouting riders
25//!
26//! - [`Simulation::spawn_rider()`](crate::sim::Simulation::spawn_rider)
27//! — simple origin/destination/weight spawn (accepts `EntityId` or `StopId`).
28//! - [`Simulation::build_rider()`](crate::sim::Simulation::build_rider)
29//! — fluent [`RiderBuilder`](crate::sim::RiderBuilder) for patience, preferences, access
30//! control, explicit groups, multi-leg routes (accepts `EntityId` or `StopId`).
31//! - [`Simulation::reroute()`](crate::sim::Simulation::reroute) — change a waiting
32//! rider's destination mid-trip.
33//! - [`Simulation::settle_rider()`](crate::sim::Simulation::settle_rider) /
34//! [`Simulation::despawn_rider()`](crate::sim::Simulation::despawn_rider) —
35//! terminal-state cleanup for `Arrived`/`Abandoned` riders.
36//!
37//! ### Observability
38//!
39//! - [`Simulation::drain_events()`](crate::sim::Simulation::drain_events) — consume
40//! the event stream emitted by the last tick.
41//! - [`Simulation::metrics()`](crate::sim::Simulation::metrics) — aggregate
42//! wait/ride/throughput stats.
43//! - [`Simulation::waiting_at()`](crate::sim::Simulation::waiting_at) /
44//! [`Simulation::residents_at()`](crate::sim::Simulation::residents_at) — O(1)
45//! population queries by stop.
46//!
47//! ### Imperative control
48//!
49//! - [`Simulation::push_destination()`](crate::sim::Simulation::push_destination) /
50//! [`Simulation::push_destination_front()`](crate::sim::Simulation::push_destination_front) /
51//! [`Simulation::clear_destinations()`](crate::sim::Simulation::clear_destinations)
52//! — override dispatch by pushing/clearing stops on an elevator's
53//! [`DestinationQueue`](crate::components::DestinationQueue).
54//! - [`Simulation::abort_movement()`](crate::sim::Simulation::abort_movement)
55//! — hard-abort an in-flight trip, braking the car to the nearest
56//! reachable stop without opening doors (riders stay aboard).
57//!
58//! ### Persistence
59//!
60//! - [`Simulation::snapshot()`](crate::sim::Simulation::snapshot) — capture full
61//! state as a serializable [`WorldSnapshot`](crate::snapshot::WorldSnapshot).
62//! - [`WorldSnapshot::restore()`](crate::snapshot::WorldSnapshot::restore)
63//! — rebuild a `Simulation` from a snapshot.
64//!
65//! Everything else (phase-runners, world-level accessors, energy, tag
66//! metrics, topology queries) is available for advanced use but is not
67//! required for the common case.
68
69mod accessors;
70mod calls;
71mod construction;
72mod destinations;
73mod eta;
74mod lifecycle;
75mod manual;
76mod rider;
77mod runtime;
78mod substep;
79mod tagging;
80mod topology;
81#[allow(clippy::redundant_pub_crate)]
82pub(crate) mod transition;
83
84use crate::components::{
85 Accel, AccessControl, Orientation, Patience, Preferences, Route, SpatialPosition, Speed, Weight,
86};
87use crate::dispatch::{BuiltinReposition, DispatchStrategy, ElevatorGroup, RepositionStrategy};
88use crate::entity::{EntityId, RiderId};
89use crate::error::SimError;
90use crate::events::{Event, EventBus};
91use crate::hooks::PhaseHooks;
92use crate::ids::GroupId;
93use crate::metrics::Metrics;
94use crate::rider_index::RiderIndex;
95use crate::stop::StopId;
96use crate::time::TimeAdapter;
97use crate::topology::TopologyGraph;
98use crate::world::World;
99use std::collections::{BTreeMap, HashMap, HashSet};
100use std::fmt;
101use std::sync::Mutex;
102
103/// Parameters for creating a new elevator at runtime.
104#[derive(Debug, Clone)]
105pub struct ElevatorParams {
106 /// Maximum travel speed (distance/tick).
107 pub max_speed: Speed,
108 /// Acceleration rate (distance/tick^2).
109 pub acceleration: Accel,
110 /// Deceleration rate (distance/tick^2).
111 pub deceleration: Accel,
112 /// Maximum weight the car can carry.
113 pub weight_capacity: Weight,
114 /// Ticks for a door open/close transition.
115 pub door_transition_ticks: u32,
116 /// Ticks the door stays fully open.
117 pub door_open_ticks: u32,
118 /// Stop entity IDs this elevator cannot serve (access restriction).
119 pub restricted_stops: HashSet<EntityId>,
120 /// Speed multiplier for Inspection mode (0.0..1.0).
121 pub inspection_speed_factor: f64,
122 /// Full-load bypass threshold for upward pickups (see
123 /// [`Elevator::bypass_load_up_pct`](crate::components::Elevator::bypass_load_up_pct)).
124 pub bypass_load_up_pct: Option<f64>,
125 /// Full-load bypass threshold for downward pickups.
126 pub bypass_load_down_pct: Option<f64>,
127}
128
129impl Default for ElevatorParams {
130 fn default() -> Self {
131 Self {
132 max_speed: Speed::from(2.0),
133 acceleration: Accel::from(1.5),
134 deceleration: Accel::from(2.0),
135 weight_capacity: Weight::from(800.0),
136 door_transition_ticks: 5,
137 door_open_ticks: 10,
138 restricted_stops: HashSet::new(),
139 inspection_speed_factor: 0.25,
140 bypass_load_up_pct: None,
141 bypass_load_down_pct: None,
142 }
143 }
144}
145
146/// Parameters for creating a new line at runtime.
147#[derive(Debug, Clone)]
148pub struct LineParams {
149 /// Human-readable name.
150 pub name: String,
151 /// Dispatch group to add this line to.
152 pub group: GroupId,
153 /// Physical orientation.
154 pub orientation: Orientation,
155 /// Lowest reachable position on the line axis.
156 pub min_position: f64,
157 /// Highest reachable position on the line axis.
158 pub max_position: f64,
159 /// Optional floor-plan position.
160 pub position: Option<SpatialPosition>,
161 /// Maximum cars on this line (None = unlimited).
162 pub max_cars: Option<usize>,
163}
164
165impl LineParams {
166 /// Create line parameters with the given name and group, defaulting
167 /// everything else.
168 pub fn new(name: impl Into<String>, group: GroupId) -> Self {
169 Self {
170 name: name.into(),
171 group,
172 orientation: Orientation::default(),
173 min_position: 0.0,
174 max_position: 0.0,
175 position: None,
176 max_cars: None,
177 }
178 }
179}
180
181/// Fluent builder for spawning riders with optional configuration.
182///
183/// Created via [`Simulation::build_rider`].
184///
185/// ```
186/// use elevator_core::prelude::*;
187///
188/// let mut sim = SimulationBuilder::demo().build().unwrap();
189/// let rider = sim.build_rider(StopId(0), StopId(1))
190/// .unwrap()
191/// .weight(80.0)
192/// .spawn()
193/// .unwrap();
194/// ```
195pub struct RiderBuilder<'a> {
196 /// Mutable reference to the simulation (consumed on spawn).
197 sim: &'a mut Simulation,
198 /// Origin stop entity.
199 origin: EntityId,
200 /// Destination stop entity.
201 destination: EntityId,
202 /// Rider weight (default: 75.0).
203 weight: Weight,
204 /// Explicit dispatch group (skips auto-detection).
205 group: Option<GroupId>,
206 /// Explicit multi-leg route.
207 route: Option<Route>,
208 /// Maximum wait ticks before abandoning.
209 patience: Option<u64>,
210 /// Boarding preferences.
211 preferences: Option<Preferences>,
212 /// Per-rider access control.
213 access_control: Option<AccessControl>,
214}
215
216impl RiderBuilder<'_> {
217 /// Set the rider's weight (default: 75.0).
218 #[must_use]
219 pub fn weight(mut self, weight: impl Into<Weight>) -> Self {
220 self.weight = weight.into();
221 self
222 }
223
224 /// Set the dispatch group explicitly, skipping auto-detection.
225 #[must_use]
226 pub const fn group(mut self, group: GroupId) -> Self {
227 self.group = Some(group);
228 self
229 }
230
231 /// Provide an explicit multi-leg route.
232 #[must_use]
233 pub fn route(mut self, route: Route) -> Self {
234 self.route = Some(route);
235 self
236 }
237
238 /// Set maximum wait ticks before the rider abandons.
239 #[must_use]
240 pub const fn patience(mut self, max_wait_ticks: u64) -> Self {
241 self.patience = Some(max_wait_ticks);
242 self
243 }
244
245 /// Set boarding preferences.
246 #[must_use]
247 pub const fn preferences(mut self, prefs: Preferences) -> Self {
248 self.preferences = Some(prefs);
249 self
250 }
251
252 /// Set per-rider access control (allowed stops).
253 #[must_use]
254 pub fn access_control(mut self, ac: AccessControl) -> Self {
255 self.access_control = Some(ac);
256 self
257 }
258
259 /// Spawn the rider with the configured options.
260 ///
261 /// # Errors
262 ///
263 /// Returns [`SimError::NoRoute`] if no group serves both stops (when auto-detecting).
264 /// Returns [`SimError::AmbiguousRoute`] if multiple groups serve both stops (when auto-detecting).
265 /// Returns [`SimError::GroupNotFound`] if an explicit group does not exist.
266 /// Returns [`SimError::RouteOriginMismatch`] if an explicit route's first leg
267 /// does not start at `origin`.
268 pub fn spawn(self) -> Result<RiderId, SimError> {
269 let route = if let Some(route) = self.route {
270 // Validate route origin matches the spawn origin.
271 if let Some(leg) = route.current()
272 && leg.from != self.origin
273 {
274 return Err(SimError::RouteOriginMismatch {
275 expected_origin: self.origin,
276 route_origin: leg.from,
277 });
278 }
279 route
280 } else {
281 // No explicit route: must build one from origin → destination.
282 // Same origin/destination produces a Route::direct that no hall
283 // call can summon a car for — rider deadlocks Waiting (#273).
284 // Trust users that supply their own route.
285 if self.origin == self.destination {
286 return Err(SimError::InvalidConfig {
287 field: "destination",
288 reason: "origin and destination must differ; same-stop \
289 spawns deadlock with no hall call to summon a car"
290 .into(),
291 });
292 }
293 if let Some(group) = self.group {
294 if !self.sim.groups.iter().any(|g| g.id() == group) {
295 return Err(SimError::GroupNotFound(group));
296 }
297 Route::direct(self.origin, self.destination, group)
298 } else {
299 // Auto-detect the single-group case first; on `NoRoute` or
300 // `AmbiguousRoute`, fall back to the multi-leg topology
301 // search so zoned buildings and specialty-overlap floors
302 // work through the plain `spawn_rider` API without callers
303 // having to thread a group pick through transfer points.
304 match self.sim.auto_detect_group(self.origin, self.destination) {
305 Ok(group) => Route::direct(self.origin, self.destination, group),
306 Err(
307 original @ (SimError::NoRoute { .. } | SimError::AmbiguousRoute { .. }),
308 ) => {
309 match self.sim.shortest_route(self.origin, self.destination) {
310 Some(route) => route,
311 // Preserve the original diagnostic context (which
312 // groups serve origin / destination) so callers
313 // still see the misconfiguration, not just a
314 // bare "no route" from the fallback.
315 None => return Err(original),
316 }
317 }
318 Err(other) => return Err(other),
319 }
320 }
321 };
322
323 let eid = self
324 .sim
325 .spawn_rider_inner(self.origin, self.destination, self.weight, route);
326
327 // Apply optional components.
328 if let Some(max_wait) = self.patience {
329 self.sim.world.set_patience(
330 eid,
331 Patience {
332 max_wait_ticks: max_wait,
333 waited_ticks: 0,
334 },
335 );
336 }
337 if let Some(prefs) = self.preferences {
338 self.sim.world.set_preferences(eid, prefs);
339 }
340 if let Some(ac) = self.access_control {
341 self.sim.world.set_access_control(eid, ac);
342 }
343
344 Ok(RiderId::from(eid))
345 }
346}
347
348/// The core simulation state, advanced by calling `step()`.
349pub struct Simulation {
350 /// The ECS world containing all entity data.
351 world: World,
352 /// Internal event bus — only holds events from the current tick.
353 events: EventBus,
354 /// Events from completed ticks, available to consumers via `drain_events()`.
355 pending_output: Vec<Event>,
356 /// Current simulation tick.
357 tick: u64,
358 /// Time delta per tick (seconds).
359 dt: f64,
360 /// Elevator groups in this simulation.
361 groups: Vec<ElevatorGroup>,
362 /// Config `StopId` to `EntityId` mapping for spawn helpers.
363 stop_lookup: HashMap<StopId, EntityId>,
364 /// Dispatch strategies keyed by group.
365 dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
366 /// Serializable strategy identifiers (for snapshot).
367 strategy_ids: BTreeMap<GroupId, crate::dispatch::BuiltinStrategy>,
368 /// Reposition strategies keyed by group (optional per group).
369 repositioners: BTreeMap<GroupId, Box<dyn RepositionStrategy>>,
370 /// Serializable reposition strategy identifiers (for snapshot).
371 reposition_ids: BTreeMap<GroupId, BuiltinReposition>,
372 /// Aggregated metrics.
373 metrics: Metrics,
374 /// Time conversion utility.
375 time: TimeAdapter,
376 /// Lifecycle hooks (before/after each phase).
377 hooks: PhaseHooks,
378 /// Reusable buffer for elevator IDs (avoids per-tick allocation).
379 elevator_ids_buf: Vec<EntityId>,
380 /// Reusable buffer for reposition decisions (avoids per-tick allocation).
381 reposition_buf: Vec<(EntityId, EntityId)>,
382 /// Scratch buffers owned by the dispatch phase — the cost matrix,
383 /// pending-stops list, servicing slice, pinned / committed /
384 /// idle-elevator filters. Holding them on the sim means each
385 /// dispatch pass reuses capacity instead of re-allocating.
386 pub(crate) dispatch_scratch: crate::dispatch::DispatchScratch,
387 /// Lazy-rebuilt connectivity graph for cross-line topology queries.
388 topo_graph: Mutex<TopologyGraph>,
389 /// Phase-partitioned reverse index for O(1) population queries.
390 rider_index: RiderIndex,
391 /// True between the first per-phase `run_*` call and the matching
392 /// `advance_tick()`. Used by [`try_snapshot`](Self::try_snapshot) to
393 /// reject mid-tick captures that would lose in-progress event-bus
394 /// state. Always false outside the substep API path because
395 /// [`step()`](Self::step) takes `&mut self` and snapshots take
396 /// `&self`. (#297)
397 pub(crate) tick_in_progress: bool,
398}
399
400impl fmt::Debug for Simulation {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 f.debug_struct("Simulation")
403 .field("tick", &self.tick)
404 .field("dt", &self.dt)
405 .field("groups", &self.groups.len())
406 .field("entities", &self.world.entity_count())
407 .finish_non_exhaustive()
408 }
409}