Skip to main content

Crate elevator_core

Crate elevator_core 

Source
Expand description

§elevator-core

Engine-agnostic, tick-based elevator simulation library for Rust.

This crate provides the building blocks for modeling vertical transportation systems — from a 3-story office building to an orbital space elevator. Stops sit at arbitrary positions rather than uniform floors, and the simulation is driven by a deterministic 7-phase tick loop.

§Key capabilities

§Quick start

use elevator_core::prelude::*;
use elevator_core::stop::StopConfig;

let mut sim = SimulationBuilder::new()
    .stops(vec![
        StopConfig { id: StopId(0), name: "Ground".into(), position: 0.0 },
        StopConfig { id: StopId(1), name: "Floor 2".into(), position: 4.0 },
        StopConfig { id: StopId(2), name: "Floor 3".into(), position: 8.0 },
    ])
    .build()
    .unwrap();

sim.spawn_rider_by_stop_id(StopId(0), StopId(2), 75.0).unwrap();

for _ in 0..1000 {
    sim.step();
}

assert!(sim.metrics().total_delivered() > 0);

§Crate layout

ModulePurpose
builderFluent SimulationBuilder API
simTop-level Simulation runner and tick loop
dispatchDispatch strategies and the DispatchStrategy trait
worldECS-style World with typed component storage
componentsData types: Elevator, Rider, Stop, etc.
eventsEvent variants and the EventBus
metricsAggregate Metrics (wait time, throughput, etc.)
configRON-deserializable SimConfig
hooksLifecycle hook registration by Phase
queryEntity query builder for filtering by component composition

§Architecture overview

§7-phase tick loop

Each call to Simulation::step() runs these phases in order:

  1. AdvanceTransient — transitions Boarding→Riding, Exiting→Arrived, teleports walkers.
  2. Dispatch — builds a DispatchManifest and calls each group’s DispatchStrategy.
  3. Reposition — optional phase; moves idle elevators via RepositionStrategy for better coverage.
  4. Movement — applies trapezoidal velocity profiles, detects stop arrivals and emits PassingFloor events.
  5. Doors — ticks the DoorState FSM per elevator.
  6. Loading — boards/exits riders with capacity and preference checks.
  7. Metrics — aggregates wait/ride times into Metrics and per-tag accumulators.

§Component relationships

Group ──contains──▶ Line ──has──▶ Elevator ──carries──▶ Rider
  │                  │              │                      │
  └── DispatchStrategy              └── Position           └── Route (optional)
       RepositionStrategy               Velocity               Patience
                     │                  DoorState               Preferences
                     └── Stop (served stops along the shaft)

§Rider lifecycle

Riders progress through phases managed by the simulation:

Waiting → Boarding → Riding → Exiting → Arrived
   ↑         (1 tick)           (1 tick)     │
   │                                         ├── settle_rider() → Resident
   │                                         │                       │
   │                                         └── despawn_rider()     │
   │                                                                 │
   └──────── reroute_rider() ────────────────────────────────────────┘

Waiting ──(patience exceeded)──→ Abandoned ──→ settle/despawn

§Extension storage

Games attach custom data to any entity without modifying the library:

// Attach a VIP flag to a rider.
world.insert_ext(rider_id, VipTag { priority: 1 }, "vip_tag");

// Query it alongside built-in components.
for (id, rider, vip) in world.query::<(EntityId, &Rider, &Ext<VipTag>)>().iter() {
    // ...
}

Extensions participate in snapshots via serialize_extensions() / register_ext::<T>(name) + load_extensions().

§Snapshot lifecycle

  1. Capture: sim.snapshot()WorldSnapshot
  2. Serialize: serde (RON, JSON, bincode, etc.)
  3. Deserialize + restore: snapshot.restore(factory) → new Simulation
  4. Re-register extensions: world.register_ext::<T>(name) per type
  5. Load extension data: sim.load_extensions()

§Performance

OperationComplexity
Entity iterationO(n) via SlotMap secondary maps
Stop-passing detectionO(log n) via SortedStops binary search
Dispatch manifest buildO(riders) per group
Population queriesO(1) via RiderIndex reverse index
Topology graph queriesO(V+E) BFS, lazy rebuild

For narrative guides, tutorials, and architecture walkthroughs, see the mdBook documentation.

Modules§

builder
Fluent builder for constructing a Simulation programmatically. Fluent builder for constructing a [Simulation] programmatically.
components
Entity-component data types for the simulation. Entity components — the data attached to simulation entities.
config
Building and elevator configuration (RON deserialization). Building and elevator configuration (RON-deserializable).
dispatch
Pluggable dispatch strategies (SCAN, LOOK, nearest-car, ETD). Pluggable dispatch strategies for assigning elevators to stops.
door
Door finite-state machine. Door open/close finite-state machine.
entity
Entity identity and allocation. Entity identity and allocation via generational keys.
error
Simulation error types. Error types for configuration validation and runtime failures.
events
Simulation event bus and event types. Simulation event bus and typed event channels.
hooks
Lifecycle hooks for injecting logic before/after simulation phases. Lifecycle hooks for injecting custom logic before/after simulation phases.
ids
Typed identifiers for groups and other sim concepts. Typed identifiers for simulation concepts (groups).
metrics
Aggregate simulation metrics. Aggregate simulation metrics (wait times, throughput, distance).
prelude
Common imports for consumers of this library.
query
ECS-style query builder for iterating entities by component composition. ECS-style query builder for iterating entities by component composition.
scenario
Scenario replay from recorded event streams. Scenario replay: timed rider spawns with pass/fail conditions.
sim
Top-level simulation runner. Top-level simulation runner and tick loop.
snapshot
World snapshot for save/load. World snapshot for save/load functionality.
stop
Stop configuration helpers. Stop identifiers and configuration.
systems
Tick-loop system phases (dispatch, reposition, movement, doors, loading, metrics). Tick-loop system phases run in sequence each simulation step.
tagged_metrics
Tag-based per-entity metrics. Tag-based per-entity metrics with string labels.
time
Tick-to-wall-clock time conversion. Tick-to-wall-clock time conversion.
topology
Topology graph for cross-line connectivity queries. Lazy-rebuilt connectivity graph for cross-line topology queries.
traffic
Traffic generation (arrival patterns). Traffic generation for rider arrivals.
world
Central entity/component storage. Central entity/component storage (struct-of-arrays ECS).

Macros§

register_extensions
Register multiple extension types for snapshot deserialization in one call.