World

Struct World 

Source
pub struct World<Registry, Resources = Null>
where Registry: Registry,
{ /* private fields */ }
Expand description

A container of entities.

A World can contain entities made of any combination of components contained in the Registry R. These entities are not stored in any defined order, and thier internal location is subject to change. Therefore, entities stored inside a World are uniquely identified using an entity::Identifier.

use brood::{
    entity,
    Registry,
    World,
};

// Define components.
struct Foo(u32);
struct Bar(bool);

// Create a world.
let mut world = World::<Registry!(Foo, Bar)>::new();

// Insert a new entity. The returned identifier uniquely identifies the entity.
let entity_identifier = world.insert(entity!(Foo(42), Bar(true)));

Note that a World can only contain entities made of components defined in the World’s registry. Attempting to insert entities containing components not in the registry will result in a panic.

Components of entities can be queried using the query() method. Systems can also be run over components of entities using the various run methods.

Implementations§

Source§

impl<Registry> World<Registry, Null>
where Registry: Registry,

Source

pub fn new() -> Self

Creates an empty World.

Often, calls to new() are accompanied with a Registry to tell the compiler what components the World can contain.

§Example
use brood::{
    Registry,
    World,
};

struct Foo(u32);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let world = World::<Registry>::new();
Source§

impl<Registry, Resources> World<Registry, Resources>
where Registry: Registry,

Source

pub fn with_resources(resources: Resources) -> Self

Creates an empty world containing the given resources.

§Example
use brood::{
    resources,
    Registry,
    World,
};

struct ResourceA(u32);
struct ResourceB(char);

let world = World::<Registry!(), _>::with_resources(resources!(ResourceA(0), ResourceB('a')));
Source

pub fn insert<Entity, Indices>(&mut self, entity: Entity) -> Identifier
where Registry: ContainsEntity<Entity, Indices>,

Insert an entity, returning an entity::Identifier.

§Example
use brood::{
    entity,
    Registry,
    World,
};

struct Foo(u32);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();

let entity_identifier = world.insert(entity!(Foo(42), Bar(false)));
Source

pub fn extend<Entities, Indices>( &mut self, entities: Batch<Entities>, ) -> Vec<Identifier>
where Registry: ContainsEntities<Entities, Indices>,

Insert multiple entities made from the same components, returning a Vec of entity::Identifiers.

§Example
use brood::{
    entities,
    Registry,
    World,
};

struct Foo(u32);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();

let entity_identiifers = world.extend(entities![(Foo(1), Bar(false)), (Foo(2), Bar(true))]);
Source

pub fn query<'a, Views, Filter, ResourceViews, EntryViews, QueryIndices, ResourceViewsIndices, DisjointIndices, EntryIndices>( &'a mut self, query: Query<Views, Filter, ResourceViews, EntryViews>, ) -> Result<'_, Registry, Resources, Iter<'a, Registry, Filter, Views, QueryIndices>, ResourceViews, EntryViews, EntryIndices>
where Views: Views<'a>, Registry: ContainsQuery<'a, Filter, Views, QueryIndices> + ContainsViews<'a, EntryViews, EntryIndices>, Resources: ContainsViews<'a, ResourceViews, ResourceViewsIndices>, EntryViews: Disjoint<Views, Registry, DisjointIndices> + Views<'a>,

Query for components contained within the World using the given Views V and Filter F, returning an Iterator over all components of entities matching the query.

Note that the order of the entities returned by a query is not specified.

§Example
use brood::{
    entity,
    query::{
        filter,
        result,
        Views,
    },
    Query,
    Registry,
    World,
};

struct Foo(u32);
struct Bar(bool);
struct Baz(u32);

type Registry = Registry!(Foo, Bar, Baz);

let mut world = World::<Registry>::new();
let inserted_entity_identifier = world.insert(entity!(Foo(42), Bar(true), Baz(100)));

// Note that the views provide implicit filters.
for result!(foo, baz, entity_identifier) in world
    .query(Query::<
        Views!(&mut Foo, &Baz, entity::Identifier),
        filter::Has<Bar>,
    >::new())
    .iter
{
    // Allows immutable or mutable access to queried components.
    foo.0 = baz.0;
    // Also allows access to entity identifiers.
    assert_eq!(entity_identifier, inserted_entity_identifier);
}

For more information about Views and Filter, see the query module documentaion.

Source

pub fn par_query<'a, Views, Filter, ResourceViews, EntryViews, QueryIndices, ResourceViewsIndices, DisjointIndices, EntryIndices>( &'a mut self, query: Query<Views, Filter, ResourceViews, EntryViews>, ) -> Result<'_, Registry, Resources, ParIter<'a, Registry, Filter, Views, QueryIndices>, ResourceViews, EntryViews, EntryIndices>
where Views: ParViews<'a>, Registry: ContainsParQuery<'a, Filter, Views, QueryIndices> + ContainsViews<'a, EntryViews, EntryIndices>, Resources: ContainsViews<'a, ResourceViews, ResourceViewsIndices>, EntryViews: Disjoint<Views, Registry, DisjointIndices> + Views<'a>,

Available on crate feature rayon only.

Query for components contained within the World using the given ParViews V and Filter F, returning a ParallelIterator over all components of entities matching the query.

The difference between this method and query() is that this method allow results to be operated on in parallel rather than sequentially.

§Example
use brood::{
    entity,
    query::{
        filter,
        result,
        Views,
    },
    Query,
    Registry,
    World,
};
use rayon::iter::ParallelIterator;

struct Foo(u32);
struct Bar(bool);
struct Baz(u32);

type Registry = Registry!(Foo, Bar, Baz);

let mut world = World::<Registry>::new();
let inserted_entity_identifier = world.insert(entity!(Foo(42), Bar(true), Baz(100)));

// Note that the views provide implicit filters.
world
    .par_query(Query::<
        Views!(&mut Foo, &Baz, entity::Identifier),
        filter::Has<Bar>,
    >::new())
    .iter
    .for_each(|result!(foo, baz, entity_identifier)| {
        // Allows immutable or mutable access to queried components.
        foo.0 = baz.0;
        // Also allows access to entity identifiers.
        assert_eq!(entity_identifier, inserted_entity_identifier);
    });

For more information about ParViews and Filter, see the query module documentaion.

Source

pub fn run_system<'a, System, QueryIndices, ResourceViewsIndices, DisjointIndices, EntryIndices>( &'a mut self, system: &mut System, )
where System: System, Registry: ContainsQuery<'a, System::Filter, System::Views<'a>, QueryIndices> + ContainsViews<'a, System::EntryViews<'a>, EntryIndices>, Resources: ContainsViews<'a, System::ResourceViews<'a>, ResourceViewsIndices>, System::EntryViews<'a>: Disjoint<System::Views<'a>, Registry, DisjointIndices> + Views<'a>,

Run a System over the entities in this World.

§Example
use brood::{
    entity,
    query::{
        filter,
        filter::Filter,
        result,
        Result,
        Views,
    },
    registry,
    system::System,
    Registry,
    World,
};

// Define components.
struct Foo(usize);
struct Bar(usize);

type Registry = Registry!(Foo, Bar);

// Define system.
struct MySystem;

impl System for MySystem {
    type Views<'a> = Views!(&'a mut Foo, &'a Bar);
    type Filter = filter::None;
    type ResourceViews<'a> = Views!();
    type EntryViews<'a> = Views!();

    fn run<'a, R, S, I, E>(
        &mut self,
        query_results: Result<R, S, I, Self::ResourceViews<'a>, Self::EntryViews<'a>, E>,
    ) where
        R: registry::Registry,
        I: Iterator<Item = Self::Views<'a>>,
    {
        for result!(foo, bar) in query_results.iter {
            // Increment `Foo` by `Bar`.
            foo.0 += bar.0;
        }
    }
}

let mut world = World::<Registry>::new();
world.insert(entity!(Foo(42), Bar(100)));

world.run_system(&mut MySystem);
Source

pub fn run_par_system<'a, ParSystem, QueryIndices, ResourceViewsIndices, DisjointIndices, EntryIndices>( &'a mut self, par_system: &mut ParSystem, )
where ParSystem: ParSystem, Registry: ContainsParQuery<'a, ParSystem::Filter, ParSystem::Views<'a>, QueryIndices> + ContainsViews<'a, ParSystem::EntryViews<'a>, EntryIndices>, Resources: ContainsViews<'a, ParSystem::ResourceViews<'a>, ResourceViewsIndices>, ParSystem::EntryViews<'a>: Disjoint<ParSystem::Views<'a>, Registry, DisjointIndices> + Views<'a>,

Available on crate feature rayon only.

Run a ParSystem over the entities in this World.

§Example
use brood::{
    entity,
    query::{
        filter,
        filter::Filter,
        result,
        Result,
        Views,
    },
    registry,
    system::ParSystem,
    Registry,
    World,
};
use rayon::iter::ParallelIterator;

// Define components.
struct Foo(usize);
struct Bar(usize);

type Registry = Registry!(Foo, Bar);

// Define system.
struct MySystem;

impl ParSystem for MySystem {
    type Views<'a> = Views!(&'a mut Foo, &'a Bar);
    type Filter = filter::None;
    type ResourceViews<'a> = Views!();
    type EntryViews<'a> = Views!();

    fn run<'a, R, S, I, E>(
        &mut self,
        query_results: Result<R, S, I, Self::ResourceViews<'a>, Self::EntryViews<'a>, E>,
    ) where
        R: registry::Registry,
        I: ParallelIterator<Item = Self::Views<'a>>,
    {
        query_results
            .iter
            .for_each(|result!(foo, bar)| foo.0 += bar.0);
    }
}

let mut world = World::<Registry>::new();
world.insert(entity!(Foo(42), Bar(100)));

world.run_par_system(&mut MySystem);
Source

pub fn run_schedule<'a, Schedule, Indices>( &mut self, schedule: &'a mut Schedule, )
where Resources: Resources, Schedule: Schedule<'a, Registry, Resources, Indices>,

Available on crate feature rayon only.

Run a Schedule over the entities in this World.

§Example
use brood::{
    entity,
    query::{
        filter,
        filter::Filter,
        result,
        Result,
        Views,
    },
    registry,
    system::{
        schedule,
        schedule::task,
        Schedule,
        System,
    },
    Registry,
    World,
};

// Define components.
struct Foo(usize);
struct Bar(usize);

type Registry = Registry!(Foo, Bar);

// Define systems.
struct SystemA;
struct SystemB;

impl System for SystemA {
    type Views<'a> = Views!(&'a mut Foo);
    type Filter = filter::None;
    type ResourceViews<'a> = Views!();
    type EntryViews<'a> = Views!();

    fn run<'a, R, S, I, E>(
        &mut self,
        query_results: Result<R, S, I, Self::ResourceViews<'a>, Self::EntryViews<'a>, E>,
    ) where
        R: registry::Registry,
        I: Iterator<Item = Self::Views<'a>>,
    {
        for result!(foo) in query_results.iter {
            foo.0 += 1;
        }
    }
}

impl System for SystemB {
    type Views<'a> = Views!(&'a mut Bar);
    type Filter = filter::None;
    type ResourceViews<'a> = Views!();
    type EntryViews<'a> = Views!();

    fn run<'a, R, S, I, E>(
        &mut self,
        query_results: Result<R, S, I, Self::ResourceViews<'a>, Self::EntryViews<'a>, E>,
    ) where
        R: registry::Registry,
        I: Iterator<Item = Self::Views<'a>>,
    {
        for result!(bar) in query_results.iter {
            bar.0 += 1;
        }
    }
}

// Define schedule.
let mut schedule = schedule!(task::System(SystemA), task::System(SystemB));

let mut world = World::<Registry>::new();
world.insert(entity!(Foo(42), Bar(100)));

world.run_schedule(&mut schedule);
Source

pub fn contains(&self, entity_identifier: Identifier) -> bool

Returns true if the world contains an entity identified by entity_identifier.

§Example
use brood::{
    entity,
    Registry,
    World,
};

struct Foo(usize);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();
let entity_identifier = world.insert(entity!(Foo(42), Bar(true)));

assert!(world.contains(entity_identifier));
world.remove(entity_identifier);
assert!(!world.contains(entity_identifier));
Source

pub fn entry( &mut self, entity_identifier: Identifier, ) -> Option<Entry<'_, Registry, Resources>>

Gets an Entry for the entity associated with an entity::Identifier for component-level manipulation.

If no such entity exists, None is returned.

§Example
use brood::{
    entity,
    Registry,
    World,
};

struct Foo(u32);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();
let entity_identifier = world.insert(entity!(Foo(42), Bar(true)));

let mut entry = world.entry(entity_identifier).unwrap();
// Remove the `Bar` component.
entry.remove::<Bar, _>();
Source

pub fn remove(&mut self, entity_identifier: Identifier)

Remove the entity associated with an entity::Identifier.

If the entity has already been removed, this method will do nothing.

§Example
use brood::{
    entity,
    Registry,
    World,
};

struct Foo(u32);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();
let entity_identifier = world.insert(entity!(Foo(42), Bar(true)));

world.remove(entity_identifier);
Source

pub fn clear(&mut self)

Removes all entities.

Keeps the allocated memory for reuse.

§Example
use brood::{
    entity,
    Registry,
    World,
};

struct Foo(usize);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();
world.insert(entity!(Foo(42), Bar(true)));

world.clear();
Source

pub fn len(&self) -> usize

Returns the number of entities in the world.

§Example
use brood::{entities, Registry, World};

#[derive(Clone)]
struct Foo(usize);
#[derive(Clone)]
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();
world.extend(entities!((Foo(42), Bar(false)); 100));

assert_eq!(world.len(), 100);
Source

pub fn is_empty(&self) -> bool

Returns true if the world contains no entities.

§Example
use brood::{
    entity,
    Registry,
    World,
};

struct Foo(usize);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();

assert!(world.is_empty());

world.insert(entity!(Foo(42), Bar(false)));

assert!(!world.is_empty());
Source

pub fn shrink_to_fit(&mut self)

Shrinks the allocated capacity of the internal storage as much as possible.

§Example
use brood::{entities, Registry, World};

#[derive(Clone)]
struct Foo(usize);
#[derive(Clone)]
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();

world.extend(entities!((Foo(42), Bar(false)); 10));
world.clear();
world.extend(entities!((Foo(42), Bar(false)); 3));

// This will reduce the current allocation.
world.shrink_to_fit();
Source

pub fn reserve<Entity, Indices>(&mut self, additional: usize)
where Registry: ContainsEntity<Entity, Indices>,

Reserve capacity for at least additional more entities of type E.

Note that the capacity is reserved for all future entities that contain the components of E, regardless of order.

§Panics

Panics if the new capacity for entities of type E exceeds isize::MAX bytes.

§Example
use brood::{
    Entity,
    Registry,
    World,
};

struct Foo(usize);
struct Bar(bool);

type Registry = Registry!(Foo, Bar);

let mut world = World::<Registry>::new();

world.reserve::<Entity!(Foo, Bar), _>(10);
Source

pub fn get<Resource, Index>(&self) -> &Resource
where Resources: ContainsResource<Resource, Index>,

View a single resource immutably.

The Index parameter can be inferred.

§Example
use brood::{
    resources,
    Registry,
    World,
};

#[derive(Debug, PartialEq)]
struct Resource(u32);

let world = World::<Registry!(), _>::with_resources(resources!(Resource(100)));

assert_eq!(world.get::<Resource, _>(), &Resource(100));
Source

pub fn get_mut<Resource, Index>(&mut self) -> &mut Resource
where Resources: ContainsResource<Resource, Index>,

View a single resource mutably.

The Index parameter can be inferred.

§Example
use brood::{
    resources,
    Registry,
    World,
};

#[derive(Debug, PartialEq)]
struct Resource(u32);

let mut world = World::<Registry!(), _>::with_resources(resources!(Resource(100)));

world.get_mut::<Resource, _>().0 *= 2;
assert_eq!(world.get::<Resource, _>(), &Resource(200));
Source

pub fn view_resources<'a, Views, Indices>(&'a mut self) -> Views
where Resources: ContainsViews<'a, Views, Indices>,

View multiple resources at once.

All generic parameters besides Views can be omitted.

§Example
use brood::{
    query::{
        result,
        Views,
    },
    resources,
    Query,
    Registry,
    World,
};

#[derive(Debug, PartialEq)]
struct ResourceA(u32);
#[derive(Debug, PartialEq)]
struct ResourceB(char);

let mut world =
    World::<Registry!(), _>::with_resources(resources!(ResourceA(0), ResourceB('a')));

let result!(a, b) = world.view_resources::<Views!(&ResourceA, &mut ResourceB), _>();

assert_eq!(a, &ResourceA(0));

b.0 = 'b';
assert_eq!(b, &mut ResourceB('b'));

Trait Implementations§

Source§

impl<Registry, Resources> Clone for World<Registry, Resources>
where Registry: Clone, Resources: Clone,

Source§

fn clone(&self) -> Self

Performs a full clone of the World and all of its components.

Any entity::Identifiers that were valid for the old World will be valid for the newly-cloned World.

Source§

fn clone_from(&mut self, source: &Self)

Performs a full clone of source into self, cloning all of its components.

Any entity::Identifiers that were valid for the source World will be valid for self after this. Old entity::Identifiers that were valid for self before this clone will no longer be valid.

This method reuses the existing allocations for the clone. In some cases, this can be more efficient than calling clone() directly.

Source§

impl<Registry, Resources> Debug for World<Registry, Resources>
where Registry: Debug, Resources: Debug,

Source§

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

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

impl<Registry, Resources> Default for World<Registry, Resources>
where Registry: Registry, Resources: Resources + Default,

Source§

fn default() -> Self

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

impl<'de, Registry, Resources> Deserialize<'de> for World<Registry, Resources>
where Registry: Deserialize<'de>, Resources: Resources + Deserialize<'de>,

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<Registry, Resources> PartialEq for World<Registry, Resources>
where Registry: PartialEq, Resources: PartialEq,

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<Registry, Resources> Serialize for World<Registry, Resources>
where Registry: Serialize, Resources: Resources + Serialize,

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<Registry, Resources> Eq for World<Registry, Resources>
where Registry: Eq, Resources: Eq,

Source§

impl<Registry, Resources> Send for World<Registry, Resources>
where Registry: Registry + Send, Resources: Send,

Source§

impl<Registry, Resources> Sync for World<Registry, Resources>
where Registry: Registry + Sync, Resources: Sync,

Auto Trait Implementations§

§

impl<Registry, Resources> Freeze for World<Registry, Resources>
where Resources: Freeze,

§

impl<Registry, Resources> RefUnwindSafe for World<Registry, Resources>
where Resources: RefUnwindSafe, Registry: RefUnwindSafe,

§

impl<Registry, Resources> Unpin for World<Registry, Resources>
where Resources: Unpin, Registry: Unpin,

§

impl<Registry, Resources> UnwindSafe for World<Registry, Resources>
where Resources: UnwindSafe, Registry: UnwindSafe,

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. 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> 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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<Component> Component for Component
where Component: Any,

Source§

impl<'a, Views, Filter, Index> ContainsFilter<'a, Filter, Index> for Views
where Views: Sealed<'a, Filter, Index>,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

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