### Complete HECS Setup Example Source: https://github.com/ralith/hecs/blob/master/_autodocs/macros.md Demonstrates the complete setup and usage of HECS with custom bundles, dynamic bundles, and queries. ```rust use hecs::{World, Bundle, DynamicBundleClone, Query}; // Define a bundle for game objects #[derive(Bundle, Clone)] struct Actor { position: (f32, f32), name: String, } // Define a reusable NPC template #[derive(DynamicBundleClone, Clone)] struct EnemyTemplate { health: i32, damage: i32, } // Define a query for movement systems #[derive(Query)] pub struct Mover { pub position: &'static mut (f32, f32), } fn main() { let mut world = World::new(); // Spawn with derived bundle let actor = world.spawn(Actor { position: (0.0, 0.0), name: "Player".into(), }); // Spawn from template multiple times let template = EnemyTemplate { health: 100, damage: 10, }; for _ in 0..10 { world.spawn(&template); } // Use derived query for mut mover in world.query_mut::() { mover.position.0 += 1.0; } } ``` -------------------------------- ### Serializable Bundle Example Source: https://github.com/ralith/hecs/blob/master/_autodocs/macros.md Shows how to create a bundle that can be serialized and deserialized using serde. ```rust use hecs::Bundle; use serde::{Serialize, Deserialize}; #[derive(Bundle, Serialize, Deserialize, Clone)] struct SerializableEntity { x: f32, y: f32, name: String, } ``` -------------------------------- ### Hierarchical Query Example Source: https://github.com/ralith/hecs/blob/master/_autodocs/macros.md Demonstrates creating queries with filters using With and Without. ```rust use hecs::{Query, With, Without}; #[derive(Query)] pub struct PhysicsObjects { pub position: &'static mut (f32, f32), #[query(filter)] pub has_velocity: With<(f32, f32)>, } #[derive(Query)] pub struct StaticObjects { pub position: &'static (f32, f32), #[query(filter)] pub no_velocity: Without<(f32, f32)>, } ``` -------------------------------- ### Create a New EntityBuilder Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Demonstrates creating an empty `EntityBuilder` to start constructing an entity's components. ```rust use hecs::{World, EntityBuilder}; let mut world = World::new(); let mut builder = EntityBuilder::new(); builder.add(123).add("abc"); let e = world.spawn(builder.build()); ``` -------------------------------- ### Tagged Bundle Example Source: https://github.com/ralith/hecs/blob/master/_autodocs/macros.md Illustrates the use of zero-sized marker bundles to tag entities. ```rust use hecs::Bundle; #[derive(Bundle)] struct Player; // Zero-sized marker bundle #[derive(Bundle)] struct Enemy; // Zero-sized marker bundle let mut world = hecs::World::new(); world.spawn((Player,)); ``` -------------------------------- ### Create a new CommandBuffer Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Initializes an empty CommandBuffer. Use this to start recording operations. ```rust use hecs::{World, CommandBuffer}; let world = World::new(); let mut cmd = CommandBuffer::new(); // Record operations... ``` -------------------------------- ### Example Component Usage Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md Demonstrates how to define custom components (`Position`, `Velocity`) and spawn an entity with these components in a HECS world. ```rust use hecs::World; #[derive(Clone)] struct Position { x: f32, y: f32, } #[derive(Clone)] struct Velocity { dx: f32, dy: f32, } let mut world = World::new(); let entity = world.spawn(( Position { x: 0.0, y: 0.0 }, Velocity { dx: 1.0, dy: 2.0 }, )); ``` -------------------------------- ### World::new Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Creates a new, empty World instance. This is the starting point for any hecs-based application. ```APIDOC ## World::new ### Description Creates an empty world with no entities. ### Method `new()` ### Parameters No parameters. ### Return type `World` ### Example ```rust use hecs::World; let world = World::new(); assert_eq!(world.len(), 0); ``` ``` -------------------------------- ### Create an empty World Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use `World::new()` to initialize an empty world. This is useful for starting a new simulation or testing component interactions. ```rust use hecs::World; let world = World::new(); assert_eq!(world.len(), 0); ``` -------------------------------- ### Query with multiple component types and filters Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/entity-and-queries.md Demonstrates querying entities with a combination of component types, including mutable references and string slices. This example iterates over entities matching the query. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, "a")); world.spawn((2, "b")); for (entity, i, s) in world.query_mut::<(Entity, &mut i32, &&str)>() { println!("Entity {}, i={}, s={}", entity.id(), i, s); } ``` -------------------------------- ### World::get Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Shorthand for getting a single component from an entity. Equivalent to `entity().get()`. ```APIDOC ## World::get ### Description Shorthand for getting a single component from an entity. Equivalent to `entity().get()`. ### Method GET (conceptual) ### Endpoint `/world/{entity}` (conceptual) ### Parameters #### Path Parameters - **entity** (`Entity`) - Yes - The entity to get the component from ### Return type `Result` where `T` is a component reference type ### Throws - `ComponentError::MissingComponent` - if the component type is not present - `ComponentError::NoSuchEntity` - if the entity doesn't exist ### Example ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42,)); let val = world.get::<&i32>(e).unwrap(); assert_eq!(*val, 42); ``` ``` -------------------------------- ### Query Caching Example (Rust) Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Demonstrates how HECS automatically caches query results for performance. Subsequent identical queries are faster due to reused cached state. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, 2.0)); world.spawn((3, 4.0)); // First query - builds cache for (i, f) in world.query::<(&i32, &f32)>().iter() { println!("{} {}", i, f); } // Subsequent queries are faster for (i, f) in world.query::<(&i32, &f32)>().iter() { println!("{} {}", i, f); } ``` -------------------------------- ### Get Shared Component Reference from EntityBuilder Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Shows how to borrow a shared reference to a component from an `EntityBuilder` if it exists, using `get`. ```rust use hecs::EntityBuilder; let mut builder = EntityBuilder::new(); builder.add(42); let val = builder.get::<&i32>(); ``` -------------------------------- ### Get Component Layout Information Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md Retrieve the memory layout (size and alignment) for a component type from its TypeInfo. ```rust pub const fn layout(self) -> Layout ``` -------------------------------- ### Get a Component from an Entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use World::get to retrieve a component reference from a specific entity. This is a shorthand for entity().get(). ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42,)); let val = world.get::<&i32>(e).unwrap(); assert_eq!(*val, 42); ``` -------------------------------- ### Iterate Over All Entities Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use World::iter to get an iterator over all entities currently in the world. The iteration order is not guaranteed. ```rust use hecs::World; let mut world = World::new(); world.spawn((1,)); world.spawn((2,)); let count = world.iter().count(); assert_eq!(count, 2); ``` -------------------------------- ### ColumnBatchType::new Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Creates an empty batch type, ready to have component types added. This is the starting point for defining the structure of a ColumnBatch. ```APIDOC ## ColumnBatchType::new ### Description Create an empty batch type. ### Method `new` ### Return type `ColumnBatchType` ### Example ```rust use hecs::ColumnBatchType; let mut batch_type = ColumnBatchType::new(); batch_type.add::(); batch_type.add::(); ``` ``` -------------------------------- ### Inspecting World State Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Shows how to get the total number of entities and iterate through archetypes to inspect their component types. Requires World import. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, "a")); world.spawn((2, "b")); // Number of entities println!("Entities: {}", world.len()); // Inspect archetypes for archetype in world.archetypes() { println!("Archetype with {} entities", archetype.len()); for type_id in archetype.component_types() { println!(" - {:?}", type_id); } } ``` -------------------------------- ### Handling MissingComponent Error Source: https://github.com/ralith/hecs/blob/master/_autodocs/errors.md Shows how to handle errors when trying to get or remove a component that an entity does not possess. It also demonstrates using Option for component access. ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42,)); // Handle missing component match world.get::<&f64>(e) { Ok(val) => println!("Value: {}", val), Err(hecs::ComponentError::MissingComponent(err)) => { println!("Missing: {}", err); } Err(_) => {} } // Or use Option if let Some(val) = world.entity(e).ok().and_then(|r| r.get::<&i32>()) { println!("Has i32: {}", val); } // Remove returns error if component missing match world.remove::<(i32, f64)>(e) { Ok((i, f)) => println!("Removed: {} {}", i, f), Err(hecs::ComponentError::MissingComponent(err)) => { println!("One component missing: {}", err); } Err(_) => {} } ``` -------------------------------- ### Prepare and Reuse a Query Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Demonstrates how to pre-prepare a query for reuse. This is useful for optimizing repeated queries, such as those found in game systems. ```rust use hecs::{World, PreparedQuery}; let mut world = World::new(); world.spawn((1, 2.0)); world.spawn((3, 4.0)); let mut prepared = PreparedQuery::<(&i32, &f32)>::default(); // Query can be reused multiple times for (i, f) in prepared.query(&world).iter() { println!("{} {}", i, f); } ``` -------------------------------- ### Get Component Column from Archetype Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md The `get` method allows borrowing all components of a single type from all entities within an archetype. This is particularly useful for operations like serialization. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, "a")); world.spawn((2, "b")); let archetype = world.archetypes().next().unwrap(); let column = archetype.get::<&i32>(); ``` -------------------------------- ### Component Initialization Methods Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Shows three ways to initialize components on entities: using tuples, an EntityBuilder, and a derived Bundle struct. Requires World and EntityBuilder imports. ```rust use hecs::{World, EntityBuilder}; let mut world = World::new(); // Option 1: Tuple let e1 = world.spawn((100, "name")); // Option 2: Builder let mut builder = EntityBuilder::new(); builder.add(100).add("name"); let e2 = world.spawn(builder.build()); // Option 3: Bundle #[derive(hecs::Bundle)] struct Entity { health: i32, name: String } let e3 = world.spawn(Entity { health: 100, name: "test".into() }); ``` -------------------------------- ### Modify Entity Components (Get, Insert, Remove) Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Manage entity components by getting their values, inserting new ones, or removing existing ones. This covers the core entity modification operations. ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((100,)); // Get a component let health = *world.get::<&i32>(e).unwrap(); println!("Health: {}", health); // Insert new components world.insert(e, (3.0, "name")).unwrap(); // Remove components let old_health = world.remove_one::(e).unwrap(); ``` -------------------------------- ### EntityRef::entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/entity-and-queries.md Get the `Entity` handle associated with this reference. ```APIDOC ## EntityRef::entity ### Description Get the `Entity` handle associated with this reference. ### Method `pub fn entity(&self) -> Entity` ### Return type `Entity` ### Example ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42,)); let eref = world.entity(e).unwrap(); assert_eq!(eref.entity(), e); ``` ``` -------------------------------- ### EntityBuilderClone: Create, Add Components, and Spawn Multiple Entities Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Shows how to use EntityBuilderClone to add multiple components and then spawn multiple entities from the same built bundle. ```rust use hecs::{World, EntityBuilderClone}; let mut world = World::new(); let mut builder = EntityBuilderClone::new(); builder.add(123).add("abc"); let bundle = builder.build(); let e1 = world.spawn(&bundle); let e2 = world.spawn(&bundle); // Can reuse ``` -------------------------------- ### Get Component Type ID Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md Obtain the unique TypeId for a component type from its TypeInfo. ```rust pub const fn id(self) -> TypeId ``` -------------------------------- ### EntityBuilder: Add Component and Build Entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Demonstrates how to create an EntityBuilder, add a component, build the entity, and spawn it into a Hecs world. ```rust use hecs::{World, EntityBuilder}; let mut world = World::new(); let mut builder = EntityBuilder::new(); builder.add(123); let built = builder.build(); let e = world.spawn(built); ``` -------------------------------- ### Spawn Entities Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Demonstrates various ways to spawn entities: individually with components, using derived bundles, and in batches for efficiency. ```rust use hecs::World; let mut world = World::new(); // Simple spawn let e1 = world.spawn((42,)); // Spawn with derived bundle #[derive(hecs::Bundle)] struct MyBundle { x: i32 } let e2 = world.spawn(MyBundle { x: 99 }); // Spawn batch let entities: Vec<_> = world.spawn_batch((0..100).map(|i| (i,))).collect(); ``` -------------------------------- ### EntityBuilderClone: Build Reusable Entity Bundle Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Illustrates building a reusable entity bundle using EntityBuilderClone and then spawning entities from it. ```rust use hecs::{World, EntityBuilderClone}; let mut builder = EntityBuilderClone::new(); builder.add(123).add("abc"); let bundle = builder.build(); let mut world = World::new(); let e1 = world.spawn(&bundle); let e2 = world.spawn(&bundle); ``` -------------------------------- ### BuiltEntityClone: Spawn Multiple Entities from a Reusable Bundle Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Demonstrates spawning multiple entities using a pre-built, reusable bundle created with EntityBuilderClone. ```rust use hecs::{World, EntityBuilderClone}; let mut builder = EntityBuilderClone::new(); builder.add(123).add("abc"); let bundle = builder.build(); let mut world = World::new(); let e1 = world.spawn(&bundle); let e2 = world.spawn(&bundle); let e3 = world.spawn(&bundle); ``` -------------------------------- ### Get Current Fill Count with BatchWriter Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Retrieves the number of components currently added to the ColumnBatchBuilder via BatchWriter. ```rust use hecs::ColumnBatchType; let mut batch_type = ColumnBatchType::new(); batch_type.add::(); let builder = batch_type.into_batch(2); let mut writer = builder.writer::().unwrap(); writer.push(42).unwrap(); assert_eq!(writer.fill(), 1); ``` -------------------------------- ### Deferred Operations with CommandBuffer Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Illustrates queuing operations like inserting components, spawning, and despawning entities using CommandBuffer, then applying them all at once. Requires World and CommandBuffer imports. ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let e = world.spawn((42,)); let mut commands = CommandBuffer::new(); // Queue operations commands.insert(e, (3.0, "added")); commands.spawn((100, "new entity")); commands.despawn(e); // Apply all at once commands.run_on(&mut world); ``` -------------------------------- ### Spawning Entities with Tuple and Derived Bundles Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Shows how to spawn entities using both tuple bundles and custom structs annotated with `#[derive(Bundle)]`. ```rust use hecs::World; let mut world = World::new(); // Tuple bundle let e1 = world.spawn((42, "hello", true)); // With #[derive(Bundle)] #[derive(Bundle] struct MyBundle { value: i32, name: String, } let e2 = world.spawn(MyBundle { value: 99, name: "test".into() }); ``` -------------------------------- ### Add Bundle to EntityBuilder Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Shows how to add all components from another `DynamicBundle` into an `EntityBuilder` using `add_bundle`. ```rust use hecs::EntityBuilder; let mut builder = EntityBuilder::new(); builder.add_bundle((1, 2.0, "hello")); ``` -------------------------------- ### World::query_one Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Query a single entity with dynamic borrow checking. The returned `QueryOne` must outlive any borrows from `get()`. ```APIDOC ## World::query_one ### Description Query a single entity with dynamic borrow checking. The returned `QueryOne` must outlive any borrows from `get()`. ### Method `query_one` ### Parameters - **entity** (`Entity`) - Required - The entity to query ### Return type `QueryOne<'_, Q>` - Call `.get()` to retrieve the query results ### Example ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42, "hello")); let query = world.query_one::<(&i32, &&str)>(e); let (i, s) = query.get().unwrap(); ``` ``` -------------------------------- ### Get Mutable Component Reference from EntityBuilder Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Demonstrates borrowing a mutable reference to a component from an `EntityBuilder` if it exists, using `get_mut`. ```rust use hecs::EntityBuilder; let mut builder = EntityBuilder::new(); builder.add(42); let val = builder.get_mut::<&mut i32>(); ``` -------------------------------- ### Enumerate component types of an entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/entity-and-queries.md Use EntityRef::component_types to get an iterator over the TypeIds of an entity's components. This is useful for introspection. ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42, "hello")); let eref = world.entity(e).unwrap(); let type_count = eref.component_types().count(); assert_eq!(type_count, 2); ``` -------------------------------- ### EntityBuilderClone::new Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Creates a new `EntityBuilderClone` instance, representing an entity with no components initially. ```APIDOC ## EntityBuilderClone::new ### Description Create a builder representing an entity with no components. ### Returns A new `EntityBuilderClone` instance. ### Example ```rust use hecs::{World, EntityBuilderClone}; let mut world = World::new(); let mut builder = EntityBuilderClone::new(); builder.add(123).add("abc"); let bundle = builder.build(); let e1 = world.spawn(&bundle); let e2 = world.spawn(&bundle); // Can reuse ``` ### Source `src/entity_builder.rs:158` ``` -------------------------------- ### ChangeTracker Initialization Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Demonstrates the initialization of a ChangeTracker. This is used to track modifications to entities and components for incremental updates or replication. ```rust use hecs::ChangeTracker; let tracker = ChangeTracker::new(); // Track changes during world operations // Used in systems to determine what to update ``` -------------------------------- ### Get Component Type Information Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md Retrieve type information for a given component type T. This is useful for introspection and understanding component metadata. ```rust pub const fn of() -> TypeInfo ``` ```rust use hecs::TypeInfo; let info = TypeInfo::of::(); ``` -------------------------------- ### Spawn Entities with Components Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Create a new world and spawn entities with initial components. You can check if an entity exists using `world.contains()`. ```rust use hecs::World; fn main() { let mut world = World::new(); // Spawn entities with components let player = world.spawn((100, "Player", 5.0)); // health, name, speed let enemy = world.spawn((50, "Enemy", 3.0)); // Check if entity exists assert!(world.contains(player)); } ``` -------------------------------- ### Column Serialization Pattern Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Demonstrates the pattern for serializing entities in a columnar format using serde. This is efficient for storage and network transmission. ```rust use hecs::World; use std::fs::File; let mut world = World::new(); world.spawn((1, "a")); world.spawn((2, "b")); // Serialize using serde with column format // Then deserialize with ColumnBatchType and spawn_column_batch ``` -------------------------------- ### Inspect Archetypes in the World Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use World::archetypes to get an iterator over the archetypes that organize entities. This is useful for inspecting storage layout and scheduling concurrent queries. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, 2.0)); world.spawn((3, 4.0)); for archetype in world.archetypes() { println!("Archetype with {} entities", archetype.len()); } ``` -------------------------------- ### Handle Component Access Errors Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md Demonstrates how to handle errors that occur when trying to access components for a given entity. This includes cases where the entity does not exist or is missing the requested component. ```rust use hecs::World; let world = World::new(); let fake_entity = hecs::Entity::DANGLING; let result = world.get::<&i32>(fake_entity); assert!(result.is_err()); ``` -------------------------------- ### CommandBuffer::run_on Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Applies all recorded commands to the world and clears the buffer for reuse. This is a core method for executing batched operations. ```APIDOC ## CommandBuffer::run_on ### Description Apply all recorded commands to the world, clearing the buffer for reuse. ### Method `run_on` ### Parameters #### Path Parameters - **world** (`&mut World`) - Required - World to apply commands to ### Return type `()` ### Example ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let mut cmd = CommandBuffer::new(); cmd.spawn((42, "hello")); cmd.spawn((99, "world")); cmd.run_on(&mut world); assert_eq!(world.len(), 2); ``` ``` -------------------------------- ### Create and Use TypeIdMap Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md Demonstrates the creation and usage of a TypeIdMap, which is a specialized HashMap optimized for TypeId keys. This is useful for efficient lookups based on component types. ```rust use hecs::TypeIdMap; use std::any::TypeId; let mut map: TypeIdMap = TypeIdMap::default(); map.insert(TypeId::of::(), 42); ``` -------------------------------- ### Dynamic Component Type Inspection (Rust) Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Shows how to add components with types determined at runtime and inspect an entity's component types. Useful for flexible data structures. ```rust use hecs::{World, EntityBuilder, TypeInfo}; use std::any::TypeId; let mut world = World::new(); let mut builder = EntityBuilder::new(); // Add components dynamically builder.add(42); builder.add("hello"); let entity = world.spawn(builder.build()); // Inspect component types let e_ref = world.entity(entity).unwrap(); for type_id in e_ref.component_types() { println!("Component type: {:?}", type_id); } ``` -------------------------------- ### Get Type Information for Components in Archetype Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md The `types` method returns a slice of `TypeInfo` structs, detailing the components present in the archetype. The information is sorted by alignment and type ID. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, "hello")); let archetype = world.archetypes().next().unwrap(); let types = archetype.types(); println!("Archetype has {} component types", types.len()); ``` -------------------------------- ### Get Type IDs for Components in Archetype Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md The `type_ids` method returns a slice of `TypeId`s, representing the runtime identifiers for all components within an archetype. This is useful for introspection and dynamic component handling. ```rust pub fn type_ids(&self) -> &[TypeId] ``` -------------------------------- ### Spawn a new entity with components Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Queues the spawning of a new entity with specified components. The entity is actually spawned when `run_on` is called. ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let mut cmd = CommandBuffer::new(); cmd.spawn((42, "hello")); cmd.run_on(&mut world); ``` -------------------------------- ### World::take Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Despawn an entity and yield a `DynamicBundle` of its components. This is useful for moving entities between worlds. ```APIDOC ## World::take ### Description Despawn an entity and yield a `DynamicBundle` of its components. Useful for moving entities between worlds. ### Method `take` ### Parameters #### Path Parameters - **entity** (`Entity`) - Required - The entity to take ### Return type `Result, NoSuchEntity>` - A `TakenEntity` that implements `DynamicBundle` ### Throws `NoSuchEntity` - if the entity doesn't exist ### Example ```rust use hecs::World; let mut world1 = World::new(); let e = world1.spawn((42, "hello")); let bundle = world1.take(e).unwrap(); let mut world2 = World::new(); world2.spawn(bundle); ``` ``` -------------------------------- ### Get Number of Entities in Archetype Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/archetype-and-components.md The `len` method returns the number of entities currently stored within a specific archetype. This indicates the count of entities that share the same set of component types. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, "a")); world.spawn((2, "b")); let archetype = world.archetypes().next().unwrap(); assert_eq!(archetype.len(), 2); ``` -------------------------------- ### World::spawn_batch Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Efficiently spawns multiple entities that share the same component types. This method is optimized for performance when creating many entities at once. ```APIDOC ## World::spawn_batch ### Description Efficiently spawn many entities with the same statically-typed components. Faster than calling `spawn` repeatedly. ### Method `spawn_batch(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter> where I: IntoIterator, I::Item: Bundle + 'static, ` ### Parameters #### Request Body - **iter** (`impl IntoIterator`) - Required - Iterator of bundles to spawn (all bundles must have identical types) ### Return type `SpawnBatchIter<'_, I::IntoIter>` - An iterator that yields entity handles as entities are spawned ### Example ```rust use hecs::World; let mut world = World::new(); let entities: Vec<_> = world.spawn_batch( (0..100).map(|i| (i as i32, "data")) ).collect(); assert_eq!(entities.len(), 100); ``` ``` -------------------------------- ### Spawn an entity with components Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use `world.spawn()` to create an entity with a dynamic set of components. The components can be provided as a tuple or a struct that derives `Bundle`. ```rust use hecs::World; let mut world = World::new(); let entity = world.spawn((123, "hello", true)); assert!(world.contains(entity)); ``` -------------------------------- ### Access an Entity by Handle Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use World::entity to get an EntityRef for a given entity handle. This method does not immediately borrow components and can be used to inspect entity metadata like its component count. ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42, "hello")); let entity_ref = world.entity(e).unwrap(); assert_eq!(entity_ref.len(), 2); ``` -------------------------------- ### World::spawn_at Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Spawns an entity with a specific, pre-determined Entity handle. If an entity already exists with that handle, it will be despawned first. ```APIDOC ## World::spawn_at ### Description Spawn an entity with a specific `Entity` handle, despawning any existing entity with the same ID. ### Method `spawn_at(&mut self, handle: Entity, components: impl DynamicBundle) ` ### Parameters #### Path Parameters - **handle** (`Entity`) - Required - The entity handle to use for the spawned entity #### Request Body - **components** (`impl DynamicBundle`) - Required - Components for the entity ### Return type `()` ### Example ```rust use hecs::World; let mut world = World::new(); let a = world.spawn((1, 2)); world.despawn(a).unwrap(); world.spawn_at(a, (3, 4)); assert!(world.contains(a)); ``` ``` -------------------------------- ### Random Access to Components Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Demonstrates how to directly access component data for specific entities using their handles. Requires World import and entities with components. ```rust use hecs::World; let mut world = World::new(); let e1 = world.spawn((100,)); let e2 = world.spawn((200,)); // Direct access by entity handle let health1 = *world.get::<&i32>(e1).unwrap(); let health2 = *world.get::<&i32>(e2).unwrap(); println!("Entity 1: {}, Entity 2: {}", health1, health2); ``` -------------------------------- ### Query Entities with Optional Components Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Handle components that may or may not be present on an entity using `Option<&T>` in the query. This allows for flexible querying. ```rust use hecs::World; let mut world = World::new(); world.spawn((100, 5.0)); // health and speed world.spawn((50,)); // just health // Speed is optional for (health, speed) in world.query::<(&i32, Option<&f32>)>().iter() { let speed_str = speed.map(|s| format!("{}", s)).unwrap_or("none".into()); println!("Health: {}, Speed: {}", health, speed_str); } ``` -------------------------------- ### Reference Documentation Source: https://github.com/ralith/hecs/blob/master/_autodocs/README.md This section details the reference documentation available for types, errors, macros, and advanced features. ```APIDOC ## Reference Documentation This section details the reference documentation available for types, errors, macros, and advanced features. ### Types - **[types.md](types.md)** - Complete type definitions and field descriptions ### Errors - **[errors.md](errors.md)** - Error types, when they occur, and how to handle them ### Macros - **[macros.md](macros.md)** - Derive macros (Bundle, DynamicBundleClone, Query) ### Advanced Features - **[advanced-features.md](advanced-features.md)** - Serialization, hierarchies, unsafe APIs, no-std support ``` -------------------------------- ### EntityBuilderClone::build Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Constructs a `BuiltEntityClone` from the components added to the builder, suitable for repeated spawning. ```APIDOC ## EntityBuilderClone::build ### Description Build a reusable entity bundle. ### Returns A `BuiltEntityClone` instance. ### Example ```rust use hecs::{World, EntityBuilderClone}; let mut builder = EntityBuilderClone::new(); builder.add(123).add("abc"); let bundle = builder.build(); let mut world = World::new(); let e1 = world.spawn(&bundle); let e2 = world.spawn(&bundle); ``` ### Source `src/entity_builder.rs:192` ``` -------------------------------- ### Spawn multiple entities efficiently Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use `world.spawn_batch()` to efficiently spawn many entities that share the same statically-typed components. This is faster than repeated calls to `spawn`. ```rust use hecs::World; let mut world = World::new(); let entities: Vec<_> = world.spawn_batch( (0..100).map(|i| (i as i32, "data")) ).collect(); assert_eq!(entities.len(), 100); ``` -------------------------------- ### World::spawn Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Spawns a new entity into the world with the specified components. Returns a handle to the newly created entity. ```APIDIDOC ## World::spawn ### Description Create an entity with certain components and return its entity handle. ### Method `spawn(&mut self, components: impl DynamicBundle) -> Entity` ### Parameters #### Request Body - **components** (`impl DynamicBundle`) - Required - A bundle of components (tuple, struct with `#[derive(Bundle)]`, or `EntityBuilder`) ### Return type `Entity` - The unique handle for the newly spawned entity ### Example ```rust use hecs::World; let mut world = World::new(); let entity = world.spawn((123, "hello", true)); assert!(world.contains(entity)); ``` ``` -------------------------------- ### Basic hecs World Usage Source: https://github.com/ralith/hecs/blob/master/README.md Demonstrates creating a new world, spawning entities with various component types, querying and modifying components in a loop, and accessing components by entity handle. Nearly any type can be used as a component with zero boilerplate. ```rust let mut world = hecs::World::new(); // Nearly any type can be used as a component with zero boilerplate let a = world.spawn((123, true, "abc")); let b = world.spawn((42, false)); // Systems can be simple for loops for (number, &flag) in world.query_mut::<(&mut i32, &bool)>() { if flag { *number *= 2; } } // Random access is simple and safe assert_eq!(*world.get::<&i32>(a).unwrap(), 246); assert_eq!(*world.get::<&i32>(b).unwrap(), 42); ``` -------------------------------- ### Take and Despawn an Entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use World::take to despawn an entity and retrieve its components as a DynamicBundle. This is useful for moving entities between different worlds. ```rust use hecs::World; let mut world1 = World::new(); let e = world1.spawn((42, "hello")); let bundle = world1.take(e).unwrap(); let mut world2 = World::new(); world2.spawn(bundle); ``` -------------------------------- ### Spawn Entities with EntityBuilder Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Use `EntityBuilder` to incrementally add components before spawning an entity. This is useful for complex entity constructions. ```rust use hecs::{World, EntityBuilder}; let mut world = World::new(); let mut builder = EntityBuilder::new(); builder.add(100).add("Player").add(3.0); let player = world.spawn(builder.build()); ``` -------------------------------- ### World::flush Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Convert all reserved entities into fully real entities. This is called implicitly by `spawn`, `despawn`, `insert`, and `remove`. ```APIDOC ## World::flush ### Description Convert all reserved entities into fully real entities. Called implicitly by `spawn`, `despawn`, `insert`, and `remove`. ### Method `flush` ### Parameters No parameters ### Return type `()` ### Example ```rust use hecs::World; let mut world = World::new(); let reserved = world.reserve_entity(); // Entity not yet visible to queries world.flush(); // Now the entity is real ``` ``` -------------------------------- ### Basic Game Loop with Hecs Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Demonstrates spawning entities with Position and Velocity components and updating their positions within a game loop. Assumes Position and Velocity bundles are defined. ```rust use hecs::{World, Bundle}; #[derive(Bundle)] struct Position { x: f32, y: f32, } #[derive(Bundle)] struct Velocity { dx: f32, dy: f32, } let mut world = World::new(); // Spawn entities for _ in 0..100 { world.spawn((Position { x: 0.0, y: 0.0 }, Velocity { dx: 1.0, dy: 1.0 })); } // Game loop for _frame in 0..60 { // Update positions based on velocity for (pos, vel) in world.query_mut::<(&mut Position, &Velocity)>() { pos.x += vel.dx; pos.y += vel.dy; } // Render (would iterate and draw) for pos in world.query::<&Position>().iter() { // println!("Draw at ({}, {})", pos.x, pos.y); } } ``` -------------------------------- ### EntityBuilder::new Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Creates a new EntityBuilder representing an entity with no components. ```APIDOC ## EntityBuilder::new `pub fn new() -> Self` ### Description Create a builder representing an entity with no components. ### Return type `EntityBuilder` ### Example ```rust use hecs::{World, EntityBuilder}; let mut world = World::new(); let mut builder = EntityBuilder::new(); builder.add(123).add("abc"); let e = world.spawn(builder.build()); ``` ``` -------------------------------- ### CommandBuffer::spawn Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Queues the spawning of a new entity with specified components. This operation is recorded in the CommandBuffer and applied later. ```APIDOC ## CommandBuffer::spawn ### Description Queue the spawning of a new entity. ### Parameters #### Request Body - **components** (`impl DynamicBundle`) - Required - Components for the new entity ### Return type `()` ### Example ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let mut cmd = CommandBuffer::new(); cmd.spawn((42, "hello")); cmd.run_on(&mut world); ``` ``` -------------------------------- ### Iterate over entities with dynamic borrow checking Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use `query` to iterate over all entities matching a query with dynamic borrow checking. This allows concurrent access using shared references. The `Q` type parameter specifies what to query. ```rust use hecs::World; let mut world = World::new(); world.spawn((1, "a")); world.spawn((2, "b")); for (i, s) in world.query::<(&i32, &&str)>().iter() { println!("i={}, s={}", i, s); } ``` -------------------------------- ### Create and Configure ColumnBatchType Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Creates an empty batch type and adds component types for building a ColumnBatch. Use for defining the structure of component data. ```rust use hecs::ColumnBatchType; let mut batch_type = ColumnBatchType::new(); batch_type.add::(); batch_type.add::(); ``` -------------------------------- ### BatchWriter::fill Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Returns the number of components that have been added to the batch writer so far. ```APIDOC ## BatchWriter::fill ### Description How many components have been added so far. ### Method `fill` ### Return type `u32` ### Example ```rust use hecs::ColumnBatchType; let mut batch_type = ColumnBatchType::new(); batch_type.add::(); let builder = batch_type.into_batch(2); let mut writer = builder.writer::().unwrap(); writer.push(42).unwrap(); assert_eq!(writer.fill(), 1); ``` ``` -------------------------------- ### Provide random access to entities with dynamic borrow checking Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use `view` to provide random access to entities matching a query with dynamic borrow checking. The `Q` type parameter specifies what to query. ```rust use hecs::World; let mut world = World::new(); let e1 = world.spawn((1,)); let e2 = world.spawn((2,)); let view = world.view::<&i32>(); // Access entities directly by handle ``` -------------------------------- ### Spawn Column Batch from External Data (Rust) Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Creates entities from pre-defined column batches, useful for deserialization or loading data. Requires specifying component types and providing writers. ```rust use hecs::{World, ColumnBatchType}; let mut batch_type = ColumnBatchType::new(); batch_type.add::().add::(); let mut builder = batch_type.into_batch(1000); let mut i_writer = builder.writer::().unwrap(); let mut s_writer = builder.writer::().unwrap(); for i in 0..1000 { i_writer.push(i).unwrap(); s_writer.push(format!("Item {}", i)).unwrap(); } let batch = builder.build().unwrap(); let entities: Vec<_> = world.spawn_column_batch(batch).collect(); ``` -------------------------------- ### Run CommandBuffer on World Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Applies all recorded commands to the world and clears the buffer for reuse. Use this to execute batched operations. ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let mut cmd = CommandBuffer::new(); cmd.spawn((42, "hello")); cmd.spawn((99, "world")); cmd.run_on(&mut world); assert_eq!(world.len(), 2); ``` -------------------------------- ### Build ColumnBatch from Builder Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Builds a ColumnBatch from a ColumnBatchBuilder. Fails if any component type has fewer than the specified number of values written. ```rust use hecs::ColumnBatchType; let mut batch_type = ColumnBatchType::new(); batch_type.add::(); let builder = batch_type.into_batch(2); let mut writer = builder.writer::().unwrap(); writer.push(42).unwrap(); writer.push(99).unwrap(); drop(writer); let batch = builder.build().unwrap(); ``` -------------------------------- ### Add Component to EntityBuilder Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/bundles-and-builders.md Illustrates adding components to an `EntityBuilder` using the `add` method, which replaces existing components of the same type. ```rust use hecs::{World, EntityBuilder}; let mut builder = EntityBuilder::new(); builder .add(42) .add("hello") .add(3.14); ``` -------------------------------- ### CommandBuffer::insert Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Queues the addition of components to an existing entity. This is useful for adding multiple components at once to an entity that may have been reserved. ```APIDOC ## CommandBuffer::insert ### Description Queue adding components to an entity (which may be reserved). ### Parameters #### Request Body - **entity** (`Entity`) - Required - Entity to modify - **components** (`impl DynamicBundle`) - Required - Components to add ### Return type `()` ### Example ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let entity = world.reserve_entity(); let mut cmd = CommandBuffer::new(); cmd.insert(entity, (42, "hello")); cmd.run_on(&mut world); ``` ``` -------------------------------- ### Entity Hierarchies Pattern Source: https://github.com/ralith/hecs/blob/master/_autodocs/advanced-features.md Shows how to manage parent-child relationships between entities using component data. Includes creating parent and child entities and querying for children. ```rust use hecs::World; #[derive(Clone, Copy)] struct Parent(hecs::Entity); #[derive(Clone)] struct Children(Vec); let mut world = World::new(); // Create parent let parent = world.spawn((/* components */,)); // Create children let child1 = world.spawn((Parent(parent), /* components */)); let child2 = world.spawn((Parent(parent), /* components */)); // Query children of parent for (entity, Parent(parent_id)) in world.query::<(hecs::Entity, &Parent)>().iter() { if *parent_id == parent { println!("Found child: {:?}", entity); } } ``` -------------------------------- ### Spawn an entity with a specific handle Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/world.md Use `world.spawn_at()` to spawn an entity with a predefined `Entity` handle. This will despawn any existing entity with the same ID. Ensure the handle is valid. ```rust use hecs::World; let mut world = World::new(); let a = world.spawn((1, 2)); world.despawn(a).unwrap(); world.spawn_at(a, (3, 4)); assert!(world.contains(a)); ``` -------------------------------- ### Resolving Mutable Borrow Error Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Illustrates how to correctly handle mutable borrows of the world by dropping existing borrows before performing mutable queries. Shows a problematic scenario and its resolution. ```rust let mut world = World::new(); let e = world.spawn((42,)); { let val = world.get::<&i32>(e).unwrap(); println!("Value: {}", val); } // Drop the borrow for (i,) in world.query_mut::<(&mut i32,)>() { *i = 99; } ``` -------------------------------- ### Insert components into an existing entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Queues adding components to an existing entity. This is useful for entities that may have been reserved but not yet fully initialized. ```rust use hecs::{World, CommandBuffer}; let mut world = World::new(); let entity = world.reserve_entity(); let mut cmd = CommandBuffer::new(); cmd.insert(entity, (42, "hello")); cmd.run_on(&mut world); ``` -------------------------------- ### Insert and Remove Components Source: https://github.com/ralith/hecs/blob/master/_autodocs/quick-start.md Add new components to an existing entity using `insert` or remove a specific component using `remove_one`. Returns the removed component if successful. ```rust use hecs::World; let mut world = World::new(); let entity = world.spawn((100,)); // Add more components world.insert(entity, ("Player", 3.0)).unwrap(); // Remove a component let health = world.remove_one::(entity).unwrap(); println!("Removed health: {}", health); ``` -------------------------------- ### ColumnBatchBuilder::new Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/command-buffer-and-batch.md Creates a new batch builder with specified component types and size. This is used internally after `ColumnBatchType::into_batch`. ```APIDOC ## ColumnBatchBuilder::new ### Description Create a batch builder. ### Method `new` ### Parameters #### Path Parameters - **ty** (`ColumnBatchType`) - Required - Component types for batch - **size** (`u32`) - Required - Exact number of entities ### Return type `ColumnBatchBuilder` ``` -------------------------------- ### Run a query against an entity Source: https://github.com/ralith/hecs/blob/master/_autodocs/api-reference/entity-and-queries.md Use EntityRef::query to run a query against a specific entity, equivalent to World::query_one. The query type Q must implement the Query trait. ```rust use hecs::World; let mut world = World::new(); let e = world.spawn((42, "hello")); let eref = world.entity(e).unwrap(); let query = eref.query::<(&i32, &&str)>(); let (i, s) = query.get().unwrap(); ```