Skip to main content

elevator_core/
builder.rs

1//! Fluent builder for constructing a [`Simulation`](crate::sim::Simulation)
2//! programmatically.
3
4use serde::{Serialize, de::DeserializeOwned};
5
6use crate::components::{Accel, Speed, Weight};
7use crate::config::{
8    BuildingConfig, ElevatorConfig, GroupConfig, LineConfig, PassengerSpawnConfig, SimConfig,
9    SimulationParams,
10};
11use crate::dispatch::scan::ScanDispatch;
12use crate::dispatch::{BuiltinReposition, DispatchStrategy, RepositionStrategy};
13use crate::error::SimError;
14use crate::hooks::{Phase, PhaseHooks};
15use crate::ids::GroupId;
16use crate::sim::Simulation;
17use crate::stop::{StopConfig, StopId};
18use crate::world::World;
19use std::collections::BTreeMap;
20
21/// A deferred extension registration closure.
22type ExtRegistration = Box<dyn FnOnce(&mut World) + Send>;
23
24/// Fluent builder for constructing a [`Simulation`].
25///
26/// Builds a [`SimConfig`] internally and delegates to [`Simulation::new()`].
27/// Provides a more ergonomic API for programmatic construction compared to
28/// assembling a config struct manually.
29///
30/// # Constructors
31///
32/// - [`SimulationBuilder::new`] — empty builder. You must add at least one
33///   stop and at least one elevator before `.build()`, or it errors.
34///   `ScanDispatch` is the default strategy, 60 ticks/s the default rate.
35/// - [`SimulationBuilder::demo`] — pre-populated with two stops (Ground at
36///   0.0, Top at 10.0) and one elevator, for doctests and quick
37///   prototyping. Override any piece with the fluent methods.
38pub struct SimulationBuilder {
39    /// Simulation configuration (stops, elevators, timing).
40    config: SimConfig,
41    /// Per-group dispatch strategies.
42    dispatchers: BTreeMap<GroupId, Box<dyn DispatchStrategy>>,
43    /// Per-group reposition strategies.
44    repositioners: Vec<(GroupId, Box<dyn RepositionStrategy>, BuiltinReposition)>,
45    /// Lifecycle hooks for before/after each tick phase.
46    hooks: PhaseHooks,
47    /// Deferred extension registrations (applied after build).
48    ext_registrations: Vec<ExtRegistration>,
49}
50
51impl Default for SimulationBuilder {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl SimulationBuilder {
58    /// Create an empty builder — no stops, no elevators, `ScanDispatch` as
59    /// the default strategy, and 60 ticks per second.
60    ///
61    /// You must add at least one stop and at least one elevator (via
62    /// [`stops`](Self::stops) / [`stop`](Self::stop) and
63    /// [`elevators`](Self::elevators) / [`elevator`](Self::elevator))
64    /// before [`build`](Self::build), or the build fails with
65    /// [`SimError::InvalidConfig`].
66    ///
67    /// If you want a quick, already-valid sim for prototyping or examples,
68    /// use [`demo`](Self::demo).
69    ///
70    /// ```
71    /// use elevator_core::prelude::*;
72    /// use elevator_core::components::{Speed, Accel, Weight};
73    /// use elevator_core::config::ElevatorConfig;
74    /// use elevator_core::stop::StopConfig;
75    ///
76    /// // An empty builder errors on build — you must configure it first.
77    /// assert!(SimulationBuilder::new().build().is_err());
78    ///
79    /// // Minimum valid configuration: at least one stop and one elevator.
80    /// let sim = SimulationBuilder::new()
81    ///     .stops(vec![
82    ///         StopConfig { id: StopId(0), name: "Ground".into(), position: 0.0 },
83    ///         StopConfig { id: StopId(1), name: "Top".into(), position: 10.0 },
84    ///     ])
85    ///     .elevator(ElevatorConfig {
86    ///         id: 0,
87    ///         name: "Main".into(),
88    ///         max_speed: Speed::from(2.0),
89    ///         acceleration: Accel::from(1.5),
90    ///         deceleration: Accel::from(2.0),
91    ///         weight_capacity: Weight::from(800.0),
92    ///         starting_stop: StopId(0),
93    ///         door_open_ticks: 10,
94    ///         door_transition_ticks: 5,
95    ///         restricted_stops: Vec::new(),
96    ///         # #[cfg(feature = "energy")]
97    ///         # energy_profile: None,
98    ///         service_mode: None,
99    ///         inspection_speed_factor: 0.25,
100    ///         bypass_load_up_pct: None,
101    ///         bypass_load_down_pct: None,
102    ///     })
103    ///     .build()
104    ///     .unwrap();
105    /// assert_eq!(sim.current_tick(), 0);
106    /// ```
107    #[must_use]
108    pub fn new() -> Self {
109        let config = SimConfig {
110            building: BuildingConfig {
111                name: "Untitled".into(),
112                stops: Vec::new(),
113                lines: None,
114                groups: None,
115            },
116            elevators: Vec::new(),
117            simulation: SimulationParams {
118                ticks_per_second: 60.0,
119            },
120            passenger_spawning: PassengerSpawnConfig {
121                mean_interval_ticks: 120,
122                weight_range: (50.0, 100.0),
123            },
124        };
125
126        let mut dispatchers = BTreeMap::new();
127        dispatchers.insert(
128            GroupId(0),
129            Box::new(ScanDispatch::new()) as Box<dyn DispatchStrategy>,
130        );
131
132        Self {
133            config,
134            dispatchers,
135            repositioners: Vec::new(),
136            hooks: PhaseHooks::default(),
137            ext_registrations: Vec::new(),
138        }
139    }
140
141    /// Pre-populated builder for zero-config examples, doctests, and quick
142    /// prototyping where the building layout isn't the point.
143    ///
144    /// Provides two stops (Ground at 0.0, Top at 10.0) and one elevator
145    /// with SCAN dispatch. Use this when you want a working `Simulation`
146    /// in one call and don't care about the specific stops.
147    ///
148    /// ```
149    /// use elevator_core::prelude::*;
150    ///
151    /// let sim = SimulationBuilder::demo().build().unwrap();
152    /// assert_eq!(sim.current_tick(), 0);
153    /// ```
154    ///
155    /// If you need a specific stop layout or elevator physics, use
156    /// [`new`](Self::new) and configure every field explicitly — it reads
157    /// more clearly than threading overrides on top of `demo`'s defaults.
158    /// [`.stop()`](Self::stop) is a *push* onto the current stops list,
159    /// so calling it after `demo()` appends to the two defaults rather
160    /// than replacing them.
161    #[must_use]
162    pub fn demo() -> Self {
163        let mut b = Self::new();
164        b.config.building.name = "Demo".into();
165        b.config.building.stops = vec![
166            StopConfig {
167                id: StopId(0),
168                name: "Ground".into(),
169                position: 0.0,
170            },
171            StopConfig {
172                id: StopId(1),
173                name: "Top".into(),
174                position: 10.0,
175            },
176        ];
177        b.config.elevators = vec![ElevatorConfig {
178            id: 0,
179            name: "Elevator 1".into(),
180            max_speed: Speed::from(2.0),
181            acceleration: Accel::from(1.5),
182            deceleration: Accel::from(2.0),
183            weight_capacity: Weight::from(800.0),
184            starting_stop: StopId(0),
185            door_open_ticks: 10,
186            door_transition_ticks: 5,
187            restricted_stops: Vec::new(),
188            #[cfg(feature = "energy")]
189            energy_profile: None,
190            service_mode: None,
191            inspection_speed_factor: 0.25,
192            bypass_load_up_pct: None,
193            bypass_load_down_pct: None,
194        }];
195        b
196    }
197
198    /// Create a builder from an existing [`SimConfig`].
199    ///
200    /// Honours the `dispatch` field on each `GroupConfig` from the config —
201    /// no default is pre-seeded. Call [`.dispatch()`](Self::dispatch) or
202    /// [`.dispatch_for_group()`](Self::dispatch_for_group) to override the
203    /// per-group strategy from code; otherwise the config's choice (or
204    /// `ScanDispatch` if neither config nor builder specifies) is used.
205    /// Pre-fix this function unconditionally seeded `ScanDispatch` for
206    /// `GroupId(0)` and the override loop in construction stomped any
207    /// config-supplied strategy for that group (#287).
208    #[must_use]
209    pub fn from_config(config: SimConfig) -> Self {
210        Self {
211            config,
212            dispatchers: BTreeMap::new(),
213            repositioners: Vec::new(),
214            hooks: PhaseHooks::default(),
215            ext_registrations: Vec::new(),
216        }
217    }
218
219    /// Replace all stops with the given list.
220    ///
221    /// Clears any previously added stops.
222    #[must_use]
223    pub fn stops(mut self, stops: Vec<StopConfig>) -> Self {
224        self.config.building.stops = stops;
225        self
226    }
227
228    /// Add a single stop to the building.
229    #[must_use]
230    pub fn stop(mut self, id: StopId, name: impl Into<String>, position: f64) -> Self {
231        self.config.building.stops.push(StopConfig {
232            id,
233            name: name.into(),
234            position,
235        });
236        self
237    }
238
239    /// Replace all elevators with the given list.
240    ///
241    /// Clears any previously added elevators.
242    #[must_use]
243    pub fn elevators(mut self, elevators: Vec<ElevatorConfig>) -> Self {
244        self.config.elevators = elevators;
245        self
246    }
247
248    /// Add a single elevator configuration.
249    #[must_use]
250    pub fn elevator(mut self, config: ElevatorConfig) -> Self {
251        self.config.elevators.push(config);
252        self
253    }
254
255    /// Add a single line configuration.
256    ///
257    /// Switches from legacy flat-elevator mode to explicit topology.
258    #[must_use]
259    pub fn line(mut self, config: LineConfig) -> Self {
260        self.config
261            .building
262            .lines
263            .get_or_insert_with(Vec::new)
264            .push(config);
265        self
266    }
267
268    /// Replace all lines with the given list.
269    ///
270    /// Switches from legacy flat-elevator mode to explicit topology.
271    #[must_use]
272    pub fn lines(mut self, lines: Vec<LineConfig>) -> Self {
273        self.config.building.lines = Some(lines);
274        self
275    }
276
277    /// Add a single group configuration.
278    #[must_use]
279    pub fn group(mut self, config: GroupConfig) -> Self {
280        self.config
281            .building
282            .groups
283            .get_or_insert_with(Vec::new)
284            .push(config);
285        self
286    }
287
288    /// Replace all groups with the given list.
289    #[must_use]
290    pub fn groups(mut self, groups: Vec<GroupConfig>) -> Self {
291        self.config.building.groups = Some(groups);
292        self
293    }
294
295    /// Set the simulation tick rate (ticks per second).
296    #[must_use]
297    pub const fn ticks_per_second(mut self, tps: f64) -> Self {
298        self.config.simulation.ticks_per_second = tps;
299        self
300    }
301
302    /// Set the building name.
303    #[must_use]
304    pub fn building_name(mut self, name: impl Into<String>) -> Self {
305        self.config.building.name = name.into();
306        self
307    }
308
309    /// Set the default dispatch strategy for the default group.
310    #[must_use]
311    pub fn dispatch(mut self, strategy: impl DispatchStrategy + 'static) -> Self {
312        self.dispatchers.insert(GroupId(0), Box::new(strategy));
313        self
314    }
315
316    /// Set a dispatch strategy for a specific group.
317    #[must_use]
318    pub fn dispatch_for_group(
319        mut self,
320        group: GroupId,
321        strategy: impl DispatchStrategy + 'static,
322    ) -> Self {
323        self.dispatchers.insert(group, Box::new(strategy));
324        self
325    }
326
327    /// Register a hook to run before a simulation phase.
328    #[must_use]
329    pub fn before(
330        mut self,
331        phase: Phase,
332        hook: impl Fn(&mut World) + Send + Sync + 'static,
333    ) -> Self {
334        self.hooks.add_before(phase, Box::new(hook));
335        self
336    }
337
338    /// Register a hook to run after a simulation phase.
339    #[must_use]
340    pub fn after(
341        mut self,
342        phase: Phase,
343        hook: impl Fn(&mut World) + Send + Sync + 'static,
344    ) -> Self {
345        self.hooks.add_after(phase, Box::new(hook));
346        self
347    }
348
349    /// Register a hook to run before a phase for a specific group.
350    #[must_use]
351    pub fn before_group(
352        mut self,
353        phase: Phase,
354        group: GroupId,
355        hook: impl Fn(&mut World) + Send + Sync + 'static,
356    ) -> Self {
357        self.hooks.add_before_group(phase, group, Box::new(hook));
358        self
359    }
360
361    /// Register a hook to run after a phase for a specific group.
362    #[must_use]
363    pub fn after_group(
364        mut self,
365        phase: Phase,
366        group: GroupId,
367        hook: impl Fn(&mut World) + Send + Sync + 'static,
368    ) -> Self {
369        self.hooks.add_after_group(phase, group, Box::new(hook));
370        self
371    }
372
373    /// Set a reposition strategy for the default group.
374    ///
375    /// Enables the reposition phase, which runs after dispatch to
376    /// move idle elevators for better coverage.
377    #[must_use]
378    pub fn reposition(
379        self,
380        strategy: impl RepositionStrategy + 'static,
381        id: BuiltinReposition,
382    ) -> Self {
383        self.reposition_for_group(GroupId(0), strategy, id)
384    }
385
386    /// Set a reposition strategy for a specific group.
387    #[must_use]
388    pub fn reposition_for_group(
389        mut self,
390        group: GroupId,
391        strategy: impl RepositionStrategy + 'static,
392        id: BuiltinReposition,
393    ) -> Self {
394        self.repositioners.push((group, Box::new(strategy), id));
395        self
396    }
397
398    /// Pre-register an extension type for snapshot deserialization.
399    ///
400    /// Extensions registered here will be available immediately after [`build()`](Self::build)
401    /// without needing to call `register_ext` manually.
402    #[must_use]
403    pub fn with_ext<T: 'static + Send + Sync + Serialize + DeserializeOwned>(mut self) -> Self {
404        self.ext_registrations
405            .push(Box::new(move |world: &mut World| {
406                world.register_ext::<T>(crate::world::ExtKey::from_type_name());
407            }));
408        self
409    }
410
411    /// Validate the configuration without building the simulation.
412    ///
413    /// Runs the same validation as [`build()`](Self::build) but does not
414    /// allocate entities or construct the simulation. Useful for CLI tools,
415    /// config editors, and dry-run checks.
416    ///
417    /// # Errors
418    ///
419    /// Returns [`SimError::InvalidConfig`] if the configuration is invalid.
420    pub fn validate(&self) -> Result<(), SimError> {
421        Simulation::validate_config(&self.config)
422    }
423
424    /// Build the simulation, validating the configuration.
425    ///
426    /// Returns `Err(SimError)` if the configuration is invalid.
427    ///
428    /// # Errors
429    ///
430    /// Returns [`SimError::InvalidConfig`] if the assembled configuration is invalid.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use elevator_core::prelude::*;
436    /// use elevator_core::stop::StopConfig;
437    ///
438    /// let mut sim = SimulationBuilder::demo()
439    ///     .stops(vec![
440    ///         StopConfig { id: StopId(0), name: "Lobby".into(), position: 0.0 },
441    ///         StopConfig { id: StopId(1), name: "Roof".into(), position: 20.0 },
442    ///     ])
443    ///     .build()
444    ///     .unwrap();
445    ///
446    /// sim.spawn_rider(StopId(0), StopId(1), 75.0).unwrap();
447    ///
448    /// for _ in 0..1000 {
449    ///     sim.step();
450    /// }
451    ///
452    /// assert!(sim.metrics().total_delivered() > 0);
453    /// ```
454    pub fn build(self) -> Result<Simulation, SimError> {
455        let mut sim = Simulation::new_with_hooks(&self.config, self.dispatchers, self.hooks)?;
456
457        for (group, strategy, id) in self.repositioners {
458            sim.set_reposition(group, strategy, id);
459        }
460
461        for register in self.ext_registrations {
462            register(sim.world_mut());
463        }
464
465        Ok(sim)
466    }
467}