Skip to main content

World

Struct World 

Source
pub struct World { /* private fields */ }
Expand description

Central storage for all simulation entities and their components.

Uses separate SecondaryMap per component type (struct-of-arrays pattern) to enable independent mutable borrows of different component storages within the same system function.

Built-in components are accessed via typed methods. Games can attach custom data via the extension storage (insert_ext / ext). The query builder (world.query::<...>()) provides ECS-style iteration.

§Component-accessor semantics

All <component>(&self, id) accessors return Option. They return None when the entity is dead or when it is alive but lacks that component — slotmap semantics make these two cases indistinguishable through this surface. Use World::is_alive (or check the typed component you expect to be present, e.g. elevator() for an elevator entity) when the distinction matters.

Implementations§

Source§

impl World

Source

pub const STOP_POSITION_EPSILON: f64 = 1e-6

Tolerance for find_stop_at_position and find_stop_at_position_in. Sub-micrometre — small enough that no two distinct floors should land within it, large enough to absorb floating-point noise from trapezoidal-velocity arrival math.

Source

pub fn new() -> Self

Create an empty world with no entities.

Source

pub fn spawn(&mut self) -> EntityId

Allocate a new entity. Returns its id. No components attached yet.

Source

pub fn despawn(&mut self, id: EntityId)

Remove an entity and all its components (built-in and extensions).

World::despawn is a low-level operation: it removes the entity’s arena entries and performs the cross-references that World can safely maintain on its own. It does not perform rider lifecycle transitions (which require RiderIndex, owned by Simulation).

Cross-references handled here:

  • If the entity is a rider aboard an elevator, it is removed from the elevator’s rider list and current_load is adjusted.

Despawning an elevator with aboard riders is the caller’s responsibility to clean up. Use Simulation::remove_elevator (which calls Simulation::disable first to transition aboard riders to Waiting via the transition gateway). Calling this method directly on a populated elevator leaves aboard riders pointing at a now-dead EntityId in their phase — a footgun this method no longer attempts to paper over, since any reset it produced would silently desync RiderIndex.

Source

pub fn is_alive(&self, id: EntityId) -> bool

Check if an entity is alive.

Source

pub fn entity_count(&self) -> usize

Number of live entities.

Source

pub fn position(&self, id: EntityId) -> Option<&Position>

Get an entity’s position.

Source

pub fn position_mut(&mut self, id: EntityId) -> Option<&mut Position>

Get an entity’s position mutably.

Source

pub fn set_position(&mut self, id: EntityId, pos: Position)

Set an entity’s position.

Source

pub fn prev_position(&self, id: EntityId) -> Option<&Position>

Snapshot of an entity’s position at the start of the current tick.

Pairs with position to support sub-tick interpolation (see Simulation::position_at).

Source

pub fn velocity(&self, id: EntityId) -> Option<&Velocity>

Get an entity’s velocity.

Source

pub fn velocity_mut(&mut self, id: EntityId) -> Option<&mut Velocity>

Get an entity’s velocity mutably.

Source

pub fn set_velocity(&mut self, id: EntityId, vel: Velocity)

Set an entity’s velocity.

Source

pub fn elevator(&self, id: EntityId) -> Option<&Elevator>

Get an entity’s elevator component.

Source

pub fn elevator_mut(&mut self, id: EntityId) -> Option<&mut Elevator>

Get an entity’s elevator component mutably.

Source

pub fn set_elevator(&mut self, id: EntityId, elev: Elevator)

Set an entity’s elevator component.

Source

pub fn rider(&self, id: EntityId) -> Option<&Rider>

Get an entity’s rider component.

Source

pub fn rider_mut(&mut self, id: EntityId) -> Option<&mut Rider>

Get an entity’s rider component mutably.

Source

pub fn stop(&self, id: EntityId) -> Option<&Stop>

Get an entity’s stop component.

Source

pub fn stop_mut(&mut self, id: EntityId) -> Option<&mut Stop>

Get an entity’s stop component mutably.

Source

pub fn set_stop(&mut self, id: EntityId, stop: Stop)

Set an entity’s stop component.

Source

pub fn route(&self, id: EntityId) -> Option<&Route>

Get an entity’s route.

Source

pub fn route_mut(&mut self, id: EntityId) -> Option<&mut Route>

Get an entity’s route mutably.

Source

pub fn set_route(&mut self, id: EntityId, route: Route)

Set an entity’s route.

Source

pub fn line(&self, id: EntityId) -> Option<&Line>

Get an entity’s line component.

Source

pub fn line_mut(&mut self, id: EntityId) -> Option<&mut Line>

Get an entity’s line component mutably.

Source

pub fn set_line(&mut self, id: EntityId, line: Line)

Set an entity’s line component.

Source

pub fn remove_line(&mut self, id: EntityId) -> Option<Line>

Remove an entity’s line component.

Source

pub fn iter_lines(&self) -> impl Iterator<Item = (EntityId, &Line)>

Iterate all line entities.

Source

pub fn patience(&self, id: EntityId) -> Option<&Patience>

Get an entity’s patience.

Source

pub fn patience_mut(&mut self, id: EntityId) -> Option<&mut Patience>

Get an entity’s patience mutably.

Source

pub fn set_patience(&mut self, id: EntityId, patience: Patience)

Set an entity’s patience.

Source

pub fn preferences(&self, id: EntityId) -> Option<&Preferences>

Get an entity’s preferences.

Source

pub fn set_preferences(&mut self, id: EntityId, prefs: Preferences)

Set an entity’s preferences.

Source

pub fn access_control(&self, id: EntityId) -> Option<&AccessControl>

Get an entity’s access control.

Source

pub fn access_control_mut(&mut self, id: EntityId) -> Option<&mut AccessControl>

Get an entity’s access control mutably.

Source

pub fn set_access_control(&mut self, id: EntityId, ac: AccessControl)

Set an entity’s access control.

Source

pub fn energy_profile(&self, id: EntityId) -> Option<&EnergyProfile>

Get an entity’s energy profile.

Source

pub fn energy_metrics(&self, id: EntityId) -> Option<&EnergyMetrics>

Get an entity’s energy metrics.

Source

pub fn energy_metrics_mut(&mut self, id: EntityId) -> Option<&mut EnergyMetrics>

Get an entity’s energy metrics mutably.

Source

pub fn set_energy_profile(&mut self, id: EntityId, profile: EnergyProfile)

Set an entity’s energy profile.

Source

pub fn set_energy_metrics(&mut self, id: EntityId, metrics: EnergyMetrics)

Set an entity’s energy metrics.

Source

pub fn service_mode(&self, id: EntityId) -> Option<&ServiceMode>

Get an entity’s service mode.

Source

pub fn set_service_mode(&mut self, id: EntityId, mode: ServiceMode)

Set an entity’s service mode.

Source

pub fn destination_queue(&self, id: EntityId) -> Option<&DestinationQueue>

Get an entity’s destination queue.

Source

pub fn set_destination_queue(&mut self, id: EntityId, queue: DestinationQueue)

Set an entity’s destination queue.

Source

pub fn stop_calls(&self, stop: EntityId) -> Option<&StopCalls>

Get the (up, down) hall call pair at a stop, if any exist.

Source

pub fn hall_call( &self, stop: EntityId, direction: CallDirection, ) -> Option<&HallCall>

Get a specific directional hall call at a stop.

Source

pub fn iter_hall_calls(&self) -> impl Iterator<Item = &HallCall>

Iterate every active hall call across the world.

Source

pub fn car_calls(&self, car: EntityId) -> &[CarCall]

Car calls currently registered inside car.

Source

pub fn iter_elevators( &self, ) -> impl Iterator<Item = (EntityId, &Position, &Elevator)>

Iterate all elevator entities (have Elevator + Position).

Source

pub fn elevator_ids(&self) -> Vec<EntityId>

Iterate all elevator entity IDs (allocates).

Source

pub fn elevator_ids_into(&self, buf: &mut Vec<EntityId>)

Fill the buffer with all elevator entity IDs, clearing it first.

Source

pub fn iter_riders(&self) -> impl Iterator<Item = (EntityId, &Rider)>

Iterate all rider entities.

Source

pub fn iter_riders_mut( &mut self, ) -> impl Iterator<Item = (EntityId, &mut Rider)>

Iterate all rider entities mutably.

Source

pub fn rider_ids(&self) -> Vec<EntityId>

Iterate all rider entity IDs (allocates).

Source

pub fn iter_stops(&self) -> impl Iterator<Item = (EntityId, &Stop)>

Iterate all stop entities.

Source

pub fn stop_ids(&self) -> Vec<EntityId>

Iterate all stop entity IDs (allocates).

Source

pub fn iter_idle_elevators( &self, ) -> impl Iterator<Item = (EntityId, &Position, &Elevator)>

Iterate elevators in Idle phase (not disabled).

Source

pub fn iter_moving_elevators( &self, ) -> impl Iterator<Item = (EntityId, &Position, &Elevator)>

Iterate elevators that are currently moving — either on a dispatched trip (MovingToStop) or a repositioning trip (Repositioning). Excludes disabled elevators.

Source

pub fn iter_waiting_riders(&self) -> impl Iterator<Item = (EntityId, &Rider)>

Iterate riders in Waiting phase (not disabled).

Source

pub fn find_stop_at_position(&self, position: f64) -> Option<EntityId>

Find the stop entity at a given position (within STOP_POSITION_EPSILON).

Global lookup — does not filter by line. When two stops on different lines share the same physical position the result is whichever wins the linear scan, which is rarely what the caller actually wants. Prefer find_stop_at_position_in when the caller knows which line’s stops to consider.

Source

pub fn find_stop_at_position_in( &self, position: f64, candidates: &[EntityId], ) -> Option<EntityId>

Find the stop at a given position from within candidates.

candidates is typically the serves list of a particular LineInfo — i.e. the stops a specific line can reach. Use this when a car arrives at a position and you need its line’s stop entity, not whichever stop on any line happens to share the position. (Two parallel shafts at the same physical floor, or a sky-lobby served by both a low and high bank, both produce position collisions the global lookup can’t disambiguate.)

O(n) over candidates, which is typically small.

Source

pub fn find_nearest_stop(&self, position: f64) -> Option<EntityId>

Find the stop entity nearest to a given position.

Unlike find_stop_at_position, this finds the closest stop by minimum distance rather than requiring an exact match. Used when ejecting riders from a disabled/despawned elevator mid-transit.

Source

pub fn stop_position(&self, id: EntityId) -> Option<f64>

Get a stop’s position by entity id.

Source

pub fn insert_ext<T: 'static + Send + Sync + Serialize + DeserializeOwned>( &mut self, id: EntityId, value: T, key: ExtKey<T>, )

Insert a custom component for an entity.

Games use this to attach their own typed data to simulation entities. Extension components must be Serialize + DeserializeOwned to support snapshot save/load. An ExtKey is required for serialization roundtrips. Extension components are automatically cleaned up on despawn().

use elevator_core::world::{ExtKey, World};
use serde::{Serialize, Deserialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct VipTag { level: u32 }

let mut world = World::new();
let entity = world.spawn();
world.insert_ext(entity, VipTag { level: 3 }, ExtKey::from_type_name());
Source

pub fn ext<T: 'static + Send + Sync + Clone>(&self, id: EntityId) -> Option<T>

Get a clone of a custom component for an entity.

Source

pub fn ext_ref<T: 'static + Send + Sync>(&self, id: EntityId) -> Option<&T>

Shared reference to a custom component for an entity.

Zero-copy alternative to ext: prefer this when T is large or expensive to clone, or when the caller only needs a borrow. Unlike ext, T does not need to implement Clone.

Source

pub fn ext_mut<T: 'static + Send + Sync>( &mut self, id: EntityId, ) -> Option<&mut T>

Mutable reference to a custom component for an entity.

Source

pub fn remove_ext<T: 'static + Send + Sync>( &mut self, id: EntityId, ) -> Option<T>

Remove a custom component for an entity.

Source

pub fn register_ext<T: 'static + Send + Sync + Serialize + DeserializeOwned>( &mut self, key: ExtKey<T>, ) -> ExtKey<T>

Register an extension type for deserialization (creates empty storage).

Must be called before restore() for each extension type that was present in the original simulation. Returns the key for convenience.

Source

pub fn disable(&mut self, id: EntityId)

Mark an entity as disabled. Disabled entities are skipped by all systems.

Source

pub fn enable(&mut self, id: EntityId)

Re-enable a disabled entity.

Source

pub fn is_disabled(&self, id: EntityId) -> bool

Check if an entity is disabled.

Source

pub fn insert_resource<T: 'static + Send + Sync>(&mut self, value: T)

Insert a global resource. Replaces any existing resource of the same type.

Resources are singletons not attached to any entity. Games use them for event channels, score trackers, or any global state.

use elevator_core::world::World;
use elevator_core::events::EventChannel;

#[derive(Debug)]
enum MyEvent { Score(u32) }

let mut world = World::new();
world.insert_resource(EventChannel::<MyEvent>::new());
Source

pub fn resource<T: 'static + Send + Sync>(&self) -> Option<&T>

Get a shared reference to a global resource.

Source

pub fn resource_mut<T: 'static + Send + Sync>(&mut self) -> Option<&mut T>

Get a mutable reference to a global resource.

Source

pub fn remove_resource<T: 'static + Send + Sync>(&mut self) -> Option<T>

Remove a global resource, returning it if it existed.

Source

pub const fn query<Q: WorldQuery>(&self) -> QueryBuilder<'_, Q>

Create a query builder for iterating entities by component composition.

use elevator_core::components::{Position, Rider};
use elevator_core::prelude::*;

let mut sim = SimulationBuilder::demo().build().unwrap();
sim.spawn_rider(StopId(0), StopId(1), 75.0).unwrap();

let world = sim.world();
for (id, rider, pos) in world.query::<(EntityId, &Rider, &Position)>().iter() {
    println!("{id:?}: {:?} at {}", rider.phase(), pos.value());
}
Source

pub fn query_ext_mut<T: 'static + Send + Sync>(&mut self) -> ExtQueryMut<'_, T>

Create a mutable extension query builder.

Uses the keys-snapshot pattern: collects matching entity IDs upfront into an owned Vec, then iterates with mutable access via for_each_mut.

§Example
world.query_ext_mut::<VipTag>().for_each_mut(|id, tag| {
    tag.level += 1;
});

Trait Implementations§

Source§

impl Default for World

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl Freeze for World

§

impl !RefUnwindSafe for World

§

impl Send for World

§

impl Sync for World

§

impl Unpin for World

§

impl UnsafeUnpin for World

§

impl !UnwindSafe for World

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.