legion::world

Struct World

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

A container of entities.

Each entity stored inside a world is uniquely identified by an Entity ID and may have an arbitrary collection of Components attached.

The entities in a world may be efficiently searched and iterated via queries.

Implementations§

Source§

impl World

Source

pub fn new(options: WorldOptions) -> Self

Creates a new world with the given options,

Source

pub fn id(&self) -> WorldId

Returns the world’s unique ID.

Source

pub fn len(&self) -> usize

Returns the number of entities in the world.

Source

pub fn is_empty(&self) -> bool

Returns true if the world contains no entities.

Source

pub fn contains(&self, entity: Entity) -> bool

Returns true if the world contains an entity with the given ID.

Source

pub fn push_with_id<T>(&mut self, entity_id: Entity, components: T)

Appends a named entity to the word, replacing any existing entity with the given ID.

Source

pub fn push<T>(&mut self, components: T) -> Entity

Appends a new entity to the world. Returns the ID of the new entity. components should be a tuple of components to attach to the entity.

§Examples

Pushing an entity with three components:

let mut world = World::default();
let _entity = world.push((1usize, false, 5.3f32));

Pushing an entity with one component (note the tuple syntax):

let mut world = World::default();
let _entity = world.push((1usize,));
Source

pub fn extend(&mut self, components: impl IntoComponentSource) -> &[Entity]

Appends a collection of entities to the world. Returns the IDs of the new entities.

§Examples

Inserting a vector of component tuples:

let mut world = World::default();
let _entities = world.extend(vec![
    (1usize, false, 5.3f32),
    (2usize, true, 5.3f32),
    (3usize, false, 5.3f32),
]);

Inserting a tuple of component vectors:

let mut world = World::default();
let _entities = world.extend(
    (
        vec![1usize, 2usize, 3usize],
        vec![false, true, false],
        vec![5.3f32, 5.3f32, 5.2f32],
    )
        .into_soa(),
);

SoA inserts require all vectors to have the same length. These inserts are faster than inserting via an iterator of tuples.

Source

pub fn remove(&mut self, entity: Entity) -> bool

Removes the specified entity from the world. Returns true if an entity was removed.

Source

pub fn clear(&mut self)

Removes all entities from the world.

Source

pub fn entry(&mut self, entity: Entity) -> Option<Entry<'_>>

Gets an Entry for an entity, allowing manipulation of the entity.

§Examples

Adding a component to an entity:

let mut world = World::default();
let entity = world.push((true, 0isize));
if let Some(mut entry) = world.entry(entity) {
    entry.add_component(0.2f32);
}
Source

pub fn subscribe<T, S>(&mut self, sender: S, filter: T)
where T: LayoutFilter + Send + Sync + 'static, S: EventSender + 'static,

Subscribes to entity Events.

Source

pub fn pack(&mut self, options: PackOptions)

Packs the world’s internal component storage to optimise iteration performance for queries which match a GroupDef defined when this world was created.

Source

pub fn components(&self) -> &Components

Returns the raw component storage.

Source

pub fn split<T: IntoView>(&mut self) -> (SubWorld<'_>, SubWorld<'_>)

Splits the world into two. The left world allows access only to the data declared by the view; the right world allows access to all else.

§Examples
let (left, right) = world.split::<&mut Position>();

With the above, ‘left’ contains a sub-world with access only to &Position and &mut Position, and right contains a sub-world with access to everything but &Position and &mut Position.

let (left, right) = world.split::<&Position>();

In this second example, left is provided access only to &Position. right is granted permission to everything but &mut Position.

Source

pub fn split_for_query<'q, V: IntoView, F: EntityFilter>( &mut self, _: &'q Query<V, F>, ) -> (SubWorld<'_>, SubWorld<'_>)

Splits the world into two. The left world allows access only to the data declared by the query’s view; the right world allows access to all else.

Source

pub fn move_from<F: LayoutFilter>(&mut self, source: &mut World, filter: &F)

Merges the given world into this world by moving all entities out of the source world.

Source

pub fn clone_from<F: LayoutFilter, M: Merger>( &mut self, source: &World, filter: &F, merger: &mut M, ) -> HashMap<Entity, Entity, EntityHasher>

Clones the entities from a world into this world.

A LayoutFilter selects which entities to merge. A Merger describes how to perform the merge operation.

If any entity IDs are remapped by the policy, their mappings will be returned in the result.

More advanced operations such as component type transformations can be performed with the Duplicate merger.

§Examples

Cloning all entities from the source world, converting all i32 components to f64 components.

let mut world_a = World::default();
let mut world_b = World::default();

// any component types not registered with Duplicate will be ignored during the merge
let mut merger = Duplicate::default();
merger.register_copy::<isize>(); // copy is faster than clone
merger.register_clone::<String>();
merger.register_convert(|comp: &i32| *comp as f32);

let _ = world_a.clone_from(&world_b, &any(), &mut merger);
Source

pub fn clone_from_single<M: Merger>( &mut self, source: &World, entity: Entity, merger: &mut M, ) -> Entity

Clones a single entity from the source world into the destination world.

Source

pub fn as_serializable<'a, F: LayoutFilter, W: WorldSerializer, E: EntitySerializer>( &'a self, filter: F, world_serializer: &'a W, entity_serializer: &'a E, ) -> SerializableWorld<'a, F, W, E>

Creates a serde serializable representation of the world.

A LayoutFilter selects which entities shall be serialized. A WorldSerializer describes how components will be serialized.

As component types are not known at compile time, the world must be provided with the means to serialize each component. This is provided by the WorldSerializer implementation. This implementation also describes how ComponentTypeIds (which are not stable between compiles) are mapped to stable type identifiers. Components that are not known to the serializer will be omitted from the serialized output.

The Registry provides a WorldSerializer implementation suitable for most situations.

§Examples

Serializing all entities with a Position component to JSON.

// create a registry which uses strings as the external type ID
let mut registry = Registry::<String>::default();
registry.register::<Position>("position".to_string());
registry.register::<f32>("f32".to_string());
registry.register::<bool>("bool".to_string());

// serialize entities with the `Position` component
let entity_serializer = Canon::default();
let json = serde_json::to_value(&world.as_serializable(
    component::<Position>(),
    &registry,
    &entity_serializer,
))
.unwrap();
println!("{:#}", json);

// registries can also be used to deserialize
use serde::de::DeserializeSeed;
let world: World = registry
    .as_deserialize(&entity_serializer)
    .deserialize(json)
    .unwrap();

Trait Implementations§

Source§

impl Debug for World

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for World

Source§

fn default() -> Self

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

impl EntityStore for World

Source§

fn entry_ref(&self, entity: Entity) -> Result<EntryRef<'_>, EntityAccessError>

Returns an entity entry which can be used to access entity metadata and components.
Source§

fn entry_mut( &mut self, entity: Entity, ) -> Result<EntryMut<'_>, EntityAccessError>

Returns a mutable entity entry which can be used to access entity metadata and components.
Source§

fn get_component_storage<V: for<'b> View<'b>>( &self, ) -> Result<StorageAccessor<'_>, EntityAccessError>

Returns a component storage accessor for component types declared in the specified View.
Source§

fn id(&self) -> WorldId

Returns the world’s unique ID.
Source§

impl<'a> From<&'a mut World> for SubWorld<'a>

Source§

fn from(world: &'a mut World) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for World

§

impl !RefUnwindSafe for World

§

impl Send for World

§

impl Sync for World

§

impl Unpin 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> Component for T
where T: 'static + Send + Sync,

Source§

type Storage = PackedStorage<T>

The storage type required to hold all instances of this component in a world.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize = _

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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.
Source§

impl<T> Resource for T
where T: 'static,