Skip to main content

World

Struct World 

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

The central container for the entire ECS, holding all entities, components, and metadata.

Implementations§

Source§

impl World

Source

pub fn new() -> Self

Creates a new, empty World with pre-registered internal component types.

Source

pub fn component_domain(&self, type_id: TypeId) -> Option<SemanticDomain>

Returns the SemanticDomain a component type was registered with, or None if it isn’t registered (yet) on this world. Used by the editor to categorise components in the “Add Component” menu and the inspector without hard-coding a per-type table.

Source

pub fn component_layout(&self, type_id: TypeId) -> Option<LayoutPolicy>

The LayoutPolicy a component type is currently stored with. Defaults to Soa; the layout-adaptation pass may change it.

Source

pub fn component_access_stats(&self, type_id: TypeId) -> Option<(u64, u64)>

Online access stats (query_count, rows_scanned) for a component type — the DCC / telemetry read these to drive memory-layout adaptation. The DCC only observes; it never mutates the layout (Data self-optimizes).

Source

pub fn entity_count(&self) -> usize

The number of live entities — the coarse workload size n the DCC’s cost model fits agent execution time against.

Source

pub fn component_access_snapshot(&self) -> Vec<(String, usize, u64, u64)>

A snapshot of every registered component’s access pattern as (type_name, size_bytes, query_count, rows_scanned). The hot path samples this at a low rate and publishes it through the observation tunnel; the DCC turns it into a read-only layout recommendation.

Source

pub fn domain_epoch(&self, domain: SemanticDomain) -> u64

Current change epoch of domain — a monotonic counter bumped by every mutation entry point that can affect the domain’s semantic content. Equal epochs across two reads guarantee the domain’s data (and its query iteration order) is unchanged; a different value only means “possibly changed” (bumps are conservative). Flows use this to validate cached Views.

Source

pub fn instance_id(&self) -> u64

Process-unique identifier of this World instance. Cache keys derived from domain_epoch must include it so that epochs from two different World instances never compare equal.

Source

pub fn spawn<B: ComponentBundle>(&mut self, bundle: B) -> EntityId

Spawns a new entity with the given bundle of components.

This is the primary method for creating entities. It orchestrates the entire process:

  1. Allocates a new EntityId.
  2. Finds or creates a suitable ComponentPage for the component bundle.
  3. Pushes the component data into the page’s columns.
  4. Updates the entity’s metadata to point to the new data’s location.
  5. Updates domain bitsets and stats for the newly created entity components.

Returns the EntityId of the newly created entity.

Source

pub fn despawn(&mut self, entity_id: EntityId) -> bool

Despawns an entity, removing all its components and freeing its ID for recycling.

This method performs the following steps:

  1. Verifies that the EntityId is valid by checking its index and generation.
  2. Removes the entity’s component data from all pages where it is stored.
  3. Marks the entity’s metadata slot as vacant and adds its index to the free list.

Returns true if the entity was valid and despawned, false otherwise.

Source

pub fn query<'a, Q: WorldQuery>(&'a self) -> Query<'a, Q>

Creates an iterator that queries the world for entities matching a set of components and filters.

This is the primary method for reading and writing data in the ECS. The query Q is specified as a tuple via turbofish syntax. It can include component references (e.g., &Position, &mut Velocity) and filters (e.g., Without<Parent>).

This method is very cheap to call. It performs an efficient search to identify all ComponentPages that satisfy the query’s criteria. The returned iterator then efficiently iterates over the data in only those pages.

§Examples
// Find all entities with a `Transform` and `GlobalTransform`.
for (transform, global) in world.query::<(&Transform, &GlobalTransform)>() {
    // ...
}

// Find all root entities (those with a `Transform` but without a `Parent`).
for (transform,) in world.query::<(&Transform, Without<Parent>)>() {
    // ...
}
Source

pub fn query_mut<'a, Q: WorldQuery>(&'a mut self) -> QueryMut<'a, Q>

Creates a mutable iterator that queries the world for entities matching a set of components and filters.

This method is similar to query, but it allows mutable access to the components. It uses the same dynamic plan re-finding to ensure thread-safe consistency.

Source

pub fn register_component<T: Component>(&mut self, domain: SemanticDomain)

Registers a component type with a specific semantic domain.

This is a crucial setup step. Before a component of type T can be used in a bundle, it must be registered with the world to define which semantic page group its data will be stored in.

Source

pub fn add_component<C: Component>( &mut self, entity_id: EntityId, component: C, ) -> Result<Option<PageIndex>, AddComponentError>

This operation is designed to be fast. It performs the necessary data migration to move the entity’s components for the given SemanticDomain to a new ComponentPage that matches the new layout.

Crucially, it does NOT clean up the “hole” left in the old page. Instead, it returns the location of the orphaned data, delegating the cleanup task to an asynchronous garbage collection system.

§Returns
  • Ok(Option<PageIndex>): On success. The Option contains the location of orphaned data if a migration occurred, which should be sent to a garbage collector. It is None if no migration was needed (e.g., adding to a new domain).
  • Err(AddComponentError): If the operation failed (e.g., entity not alive, component not registered, or component already present).
Source

pub fn remove_component<C: Component>( &mut self, entity_id: EntityId, ) -> Result<Option<PageIndex>, RemoveComponentError>

Removes a single component C from entity, preserving every other component the entity carries (in any domain).

Mirrors add_component in reverse: rebuilds the entity’s domain page signature without C, finds-or-creates a page matching the new signature, and copies the surviving same-domain components there. The old slot is orphaned and reported for the GC, exactly like an add migration.

Use this — not remove_component_domain — for surgical component removal (editor “delete component” button, set_parent unparenting, AGDF demotion). remove_component_domain is a low-level primitive that drops the entire domain bucket and should be reserved for entity teardown / GC paths.

§Returns
  • Ok(Some(PageIndex)) — old location to send to the GC.
  • Ok(None) — should not happen in practice (kept for symmetry with add_component).
  • Err(RemoveComponentError::EntityNotFound) — entity dead or stale.
  • Err(RemoveComponentError::ComponentNotRegistered) — type unknown.
  • Err(RemoveComponentError::ComponentNotPresent) — entity didn’t carry this component to begin with.
Source

pub fn remove_component_domain<C: Component>( &mut self, entity_id: EntityId, ) -> Option<PageIndex>

Logically removes all components belonging to a specific SemanticDomain from an entity.

This is an extremely fast, O(1) operation that only modifies the entity’s metadata. It does not immediately deallocate or move any component data. The component data is “orphaned” and will be cleaned up later by a garbage collection process.

This method is generic over a component C to determine which domain to remove.

§Returns
  • Some(PageIndex): Contains the location of the orphaned data if the components were successfully removed. This can be sent to a garbage collector.
  • None: If the entity is not alive or did not have any components in the specified SemanticDomain.
Source

pub fn get_mut<T: Component>(&mut self, entity_id: EntityId) -> Option<&mut T>

Gets a mutable reference to a single component T for a given entity.

This provides direct, “random” access to a component, which can be less performant than querying but is useful for targeted modifications.

§Returns

None if the entity is not alive or does not have the requested component.

Source

pub fn get_many_mut<T: Component, const N: usize>( &mut self, ids: [EntityId; N], ) -> [Option<&mut T>; N]

Gets mutable references to components of type T for multiple entities simultaneously.

This is safer than get_mut in a loop because it allows retrieving multiple disjoint mutable references to components of the same type.

§Returns

An array of Option<&mut T>. If any entity is not found, does not have the component, or if there are duplicate requests for the same component instance, that entry will be None.

Source

pub fn get<T: Component>(&self, entity_id: EntityId) -> Option<&T>

Gets an immutable reference to a single component T for a given entity.

This provides direct, “random” access to a component.

§Returns

None if the entity is not alive or does not have the requested component.

Source

pub fn clone_component<T: Component>(&self, entity_id: EntityId) -> Option<T>

Reads a component by value, working for any physical layout (AoS or field-SoA). This is the layout-agnostic read path: a field-SoA component can’t hand out &T (its bytes aren’t a contiguous T), so callers that must work regardless of layout — the serialization recipe, the Soa<T> query — go through here. For AoS it simply clones the &T.

None if the entity is not alive or lacks the component.

Source

pub fn set_component<T: Component>( &mut self, entity_id: EntityId, value: T, ) -> bool

Writes a component by value, working for any physical layout. The layout-agnostic write path (AoS assigns the slot; field-SoA scatters into its lanes). Returns false if the entity is not alive or lacks the component (nothing is written).

Source

pub fn for_each_soa_column_mut<T: SoaLayout>( &mut self, f: impl FnMut(&mut FieldSoaColumn<T>), )

Runs f over every field-SoA column of component T in the world — the bulk SIMD entry point. Each call hands the kernel a [FieldSoaColumn] whose per-field f32 lanes are contiguous, so it can tile them into f32x8 without gather (the resident layout that reaches ~4×).

Iterates per page so each lane slice is a single archetype’s run. A no-op for any page whose T column is not field-SoA.

Source

pub fn iter_entities(&self) -> impl Iterator<Item = EntityId> + '_

Returns an iterator over all currently living EntityIds in the world.

Source

pub fn serialize_archetype(&self) -> Result<Vec<u8>, EncodeError>

Serializes the entire World state using a direct memory layout strategy.

This method is highly unsafe as it reads raw component memory.

Source

pub fn deserialize_archetype( &mut self, data: &[u8], ) -> Result<(), DeserializeArchetypeError>

Deserializes and completely replaces the World state from a memory layout.

This method is highly unsafe as it writes raw bytes into component vectors.

Trait Implementations§

Source§

impl Default for World

Source§

fn default() -> Self

Creates a new, empty World via World::new().

Source§

impl UiLayoutView for World

Source§

fn get_all_ui_entities(&self) -> Vec<EntityId>

Returns the IDs of all entities that should be considered for layout.
Source§

fn get_node(&self, entity: EntityId) -> Option<CoreUiNode>

Returns the UI node definition for a given entity.
Source§

fn get_children(&self, entity: EntityId) -> Vec<EntityId>

Returns the children of a given entity.
Source§

fn has_parent(&self, entity: EntityId) -> bool

Returns true if the entity has a parent.
Source§

fn set_transform(&mut self, entity: EntityId, transform: CoreUiTransform)

Writes the computed transform back to the entity.
§

fn viewport_size(&self) -> (u32, u32)

The available layout viewport in physical pixels (width, height). 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
§

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

§

fn on_start(&mut self, ctx: &mut dyn AppContext)

Called once after the backend is up but before the first update. Apps install their theme / fonts here.
§

fn on_exit(&mut self)

Called once when the window is closing. Persist state here.
§

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

§

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

Returns a reference to the inner value as &dyn Any.
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.