### Example: Iterating Component Access Kinds (Bevy ECS) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/query/struct.Access.html Demonstrates how to use `try_iter_component_access` to retrieve and collect component access information. This example shows adding read, write, and archetypal access, then iterating over them. ```rust let mut access = Access::::default(); access.add_component_read(1); access.add_component_write(2); access.add_archetypal(3); let result = access .try_iter_component_access() .map(Iterator::collect::>); assert_eq!( result, Ok(vec![ ComponentAccessKind::Shared(1), ComponentAccessKind::Exclusive(2), ComponentAccessKind::Archetypal(3), ]), ); ``` -------------------------------- ### Initialize Resource and Get ID (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/component/struct.ComponentsQueuedRegistrator.html Example demonstrating how to initialize a resource and retrieve its ID using `valid_resource_id`. ```rust use bevy_ecs::prelude::* let mut world = World::new(); #[derive(Resource, Default)] struct ResourceA; let resource_a_id = world.init_resource::(); assert_eq!(resource_a_id, world.components().valid_resource_id::().unwrap()) ``` -------------------------------- ### Example: Configuring System Order with IntoScheduleConfigs in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/trait.IntoScheduleConfigs.html Demonstrates how to use the `IntoScheduleConfigs` trait's methods to configure the execution order of systems within a Bevy application. This example shows how to group systems and define their dependencies using `.after()`. ```rust fn handle_input() {} fn update_camera() {} fn update_character() {} app.add_systems( Update, ( handle_input, (update_camera, update_character).after(handle_input) ) ); ``` -------------------------------- ### Basic Bevy ECS System and World Setup in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/index.html Demonstrates the fundamental setup of Bevy ECS, including defining components, creating a system to process entities with those components, and managing entities and schedules within a World. This is the core pattern for Bevy ECS applications. ```rust use bevy_ecs::prelude::*; #[derive(Component)] struct Position { x: f32, y: f32 } #[derive(Component)] struct Velocity { x: f32, y: f32 } // This system moves each entity with a Position and Velocity component fn movement(mut query: Query<(&mut Position, &Velocity)>) { for (mut position, velocity) in &mut query { position.x += velocity.x; position.y += velocity.y; } } fn main() { // Create a new empty World to hold our Entities and Components let mut world = World::new(); // Spawn an entity with Position and Velocity components world.spawn(( Position { x: 0.0, y: 0.0 }, Velocity { x: 1.0, y: 0.0 }, )); // Create a new Schedule, which defines an execution strategy for Systems let mut schedule = Schedule::default(); // Add our system to the schedule schedule.add_systems(movement); // Run the schedule once. If your app has a "loop", you would run this once per loop schedule.run(&mut world); } ``` -------------------------------- ### Example of for_each_init for Parallel Data Aggregation (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/query/struct.QueryParManyIter.html An example demonstrating the usage of `for_each_init` for parallel aggregation of data. It utilizes a thread-local queue to collect results from parallel tasks, which are then summed up to produce a final value. ```rust use bevy_utils::Parallel; use crate::{bevy_ecs::prelude::{Component, Res, Resource, Entity}, bevy_ecs::system::Query}; use bevy_platform::prelude::Vec; #[derive(Component)] struct T; #[derive(Resource)] struct V(Vec); impl<'a> IntoIterator for &'a V { // ... } fn system(query: Query<&T>, entities: Res){ let mut queue: Parallel = Parallel::default(); // queue.borrow_local_mut() will get or create a thread_local queue for each task/thread; query.par_iter_many(&entities).for_each_init(|| queue.borrow_local_mut(),|local_queue, item| { **local_queue += some_expensive_operation(item); }); // collect value from every thread let final_value: usize = queue.iter_mut().map(|v| *v).sum(); } ``` -------------------------------- ### Rust: Spawning Entities with Components Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Shows various ways to spawn new entities with components using Commands, including single components, tuple bundles, and custom bundle structs. ```rust #[derive(Component)] struct ComponentA(u32); #[derive(Component)] struct ComponentB(u32); #[derive(Bundle)] struct ExampleBundle { a: ComponentA, b: ComponentB, } fn example_system(mut commands: Commands) { // Create a new entity with a single component. commands.spawn(ComponentA(1)); // Create a new entity with two components using a "tuple bundle". commands.spawn((ComponentA(2), ComponentB(1))); // Create a new entity with a component bundle. commands.spawn(ExampleBundle { a: ComponentA(3), b: ComponentB(2), }); } ``` -------------------------------- ### Get nth Element from Iterator Start in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/struct.UniqueEntityIter.html Returns the nth element from the start of the iterator. This method consumes elements up to and including the nth element. ```rust fn nth(&mut self, n: usize) -> Option ``` -------------------------------- ### Create and manage QueryState instances Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/query/struct.QueryState.html Examples of initializing QueryState from a World or QueryBuilder, and generating Query objects for data access. ```rust pub fn new(world: &mut World) -> Self; pub fn from_builder(builder: &mut QueryBuilder<'_, D, F>) -> Self; pub fn query<'w, 's>(&'s mut self, world: &'w World) -> Query<'w, 's, D::ReadOnly, F>; ``` -------------------------------- ### Get Component ID for Queued Registration (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/component/struct.ComponentsQueuedRegistrator.html Example demonstrating how to get a component's ID, including when it's queued for registration, using `component_id`. ```rust use bevy_ecs::prelude::* let mut world = World::new(); #[derive(Component)] struct ComponentA; let component_a_id = world.register_component::(); assert_eq!(component_a_id, world.components().component_id::().unwrap()) ``` -------------------------------- ### Rust: Spawning an Empty Entity and Adding Components Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Demonstrates spawning a new, empty entity and then using EntityCommands to insert component bundles and individual components. ```rust #[derive(Component)] struct Label(&'static str); #[derive(Component)] struct Strength(u32); #[derive(Component)] struct Agility(u32); fn example_system(mut commands: Commands) { // Create a new empty entity. commands.spawn_empty(); // Create another empty entity. commands.spawn_empty() // Add a new component bundle to the entity. .insert((Strength(1), Agility(2))) // Add a single component to the entity. .insert(Label("hello world")); } ``` -------------------------------- ### GET /string/match_indices Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/name/struct.Name.html Returns an iterator of matches and their starting indices. ```APIDOC ## GET /string/match_indices ### Description Returns an iterator over the disjoint matches of a pattern within the string slice as well as the index where the match starts. ### Method GET ### Endpoint /string/match_indices ### Parameters #### Query Parameters - **pattern** (Pattern) - Required - The pattern to search for. ### Request Example { "input": "abcXXXabc", "pattern": "abc" } ### Response #### Success Response (200) - **matches** (Array) - List of objects containing index and value. #### Response Example { "matches": [ {"index": 0, "value": "abc"}, {"index": 6, "value": "abc"} ] } ``` -------------------------------- ### Rust: Configuring Systems with Closures Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Local.html Illustrates an alternative to `Local` for passing configuration data into systems. This example shows how to use a capturing closure to initialize a system with specific values, demonstrating a pattern for setting up system behavior that is not intended to be modified by the system itself. ```rust use bevy_ecs::prelude::*; struct Config(u32); #[derive(Resource)] struct MyU32Wrapper(u32); fn reset_to_system(value: Config) -> impl FnMut(ResMut) { move |mut val: ResMut| val.0 = value.0 } // Example usage within a system setup (conceptual): // let my_config = Config(100); // app.add_systems(reset_to_system(my_config)); ``` -------------------------------- ### Register Component and Get ID (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/component/struct.ComponentsQueuedRegistrator.html Example demonstrating how to register a component and retrieve its ID using `valid_component_id`. ```rust use bevy_ecs::prelude::* let mut world = World::new(); #[derive(Component)] struct ComponentA; let component_a_id = world.register_component::(); assert_eq!(component_a_id, world.components().valid_component_id::().unwrap()) ``` -------------------------------- ### Create IntoAdapterSystem Instance in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.IntoAdapterSystem.html Provides a constructor function `new` for `IntoAdapterSystem`. This function takes a `func` (the adapter) and a `system` to be adapted, returning a new `IntoAdapterSystem` instance. This is crucial for setting up system adaptation pipelines. ```rust pub const fn new(func: Func, system: S) -> Self ``` -------------------------------- ### Example: Get Component by Single ID using EntityRef in Bevy ECS Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.EntityRef.html Demonstrates how to retrieve a component using its `ComponentId` when the type is not known at compile time. This involves spawning an entity with a component, registering its type to get its ID, and then using `get_by_id`. ```rust let entity = world.spawn(Foo(42)).id(); // Grab the component ID for `Foo` in whatever way you like. let component_id = world.register_component::(); // Then, get the component by ID. let ptr = world.entity(entity).get_by_id(component_id); ``` -------------------------------- ### Create New AdapterSystem Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/type.NotSystem.html The new constructor initializes an AdapterSystem by providing an adaptation function, the target system, and a name for identification. This is the primary method for creating systems that wrap existing functionality. ```rust pub const fn new(func: Func, system: S, name: Cow<'static, str>) -> Self ``` -------------------------------- ### Example: Get Components by Slice of IDs using EntityRef in Bevy ECS Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.EntityRef.html Shows how to retrieve components from an entity using a slice of `ComponentId`s. This method returns a `Vec` of component references, suitable for dynamic collections of components. ```rust let entity = world.spawn((X(42), Y(10))).id(); // Grab the component IDs for `X` and `Y` in whatever way you like. let x_id = world.register_component::(); let y_id = world.register_component::(); // Then, get the components by ID. You'll receive a vec of ptrs. let ptrs = world.entity(entity).get_by_id(&[x_id, y_id] as &[ComponentId]); ``` -------------------------------- ### Initialize and Configure Stepping Resource in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/struct.Stepping.html Demonstrates how to instantiate the Stepping resource and configure basic execution behaviors like enabling, disabling, and adding schedules for stepping. ```rust use bevy_ecs::schedule::Stepping; // Create a new instance let mut stepping = Stepping::new(); // Enable stepping for a specific schedule stepping.add_schedule(MainSchedule); // Check status if stepping.is_enabled() { stepping.disable(); } ``` -------------------------------- ### FilteredEntityMut Usage Example (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.FilteredEntityMut.html Demonstrates how to use `FilteredEntityMut` with `QueryBuilder` to get mutable access to components. It shows correct usage where `FilteredEntityMut` is the sole `QueryData` and incorrect usage where it's nested in a tuple, preventing component access. ```rust pub struct FilteredEntityMut<'w> { /* private fields */ } // This gives the `FilteredEntityMut` access to `&mut A`. let mut query = QueryBuilder::::new(&mut world) .data::<&mut A>() .build(); let mut filtered_entity: FilteredEntityMut = query.single_mut(&mut world).unwrap(); let component: Mut = filtered_entity.get_mut().unwrap(); // Here `FilteredEntityMut` is nested in a tuple, so it does not have access to `&mut A`. let mut query = QueryBuilder::<(Entity, FilteredEntityMut)>::new(&mut world) .data::<&mut A>() .build(); let (_, mut filtered_entity) = query.single_mut(&mut world).unwrap(); assert!(filtered_entity.get_mut::().is_none()); ``` -------------------------------- ### Executing Systems with RunSystemOnce Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/trait.RunSystemOnce.html Examples demonstrating how to use run_system_once for stateful local variables, command execution, and querying components within a World. ```rust #[derive(Resource, Default)] struct Counter(u8); fn increment(mut counter: Local) { counter.0 += 1; println!("{}", counter.0); } let mut world = World::default(); world.run_system_once(increment); // prints 1 world.run_system_once(increment); // still prints 1 // Command execution let entity = world.run_system_once(|mut commands: Commands| { commands.spawn_empty().id() }).unwrap(); // Querying components #[derive(Component)] struct T(usize); let count = world.run_system_once(|query: Query<&T>| { query.iter().filter(|t| t.0 == 1).count() }).unwrap(); ``` -------------------------------- ### Example: Get Multiple Components by IDs using EntityRef in Bevy ECS Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.EntityRef.html Illustrates fetching multiple components from an entity using an array of `ComponentId`s. The function returns a result containing an array of component references matching the input array's size. ```rust let entity = world.spawn((X(42), Y(10))).id(); // Grab the component IDs for `X` and `Y` in whatever way you like. let x_id = world.register_component::(); let y_id = world.register_component::(); // Then, get the components by ID. You'll receive a same-sized array. let Ok([x_ptr, y_ptr]) = world.entity(entity).get_by_id([x_id, y_id]) else { // Up to you to handle if a component is missing from the entity. }; ``` -------------------------------- ### Initialize and use SystemState in Bevy Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.SystemState.html Demonstrates how to construct a SystemState with a tuple of SystemParams and retrieve them using get_mut. This approach allows manual access to World data while maintaining proper borrow-checking. ```Rust let mut world = World::new(); world.init_resource::>(); let mut system_state: SystemState<( EventWriter, Option>, Query<&MyComponent>, )> = SystemState::new(&mut world); let (event_writer, maybe_resource, query) = system_state.get_mut(&mut world); ``` -------------------------------- ### Unsafe Slice Access Example (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/unique_array/struct.UniqueEntityEquivalentArray.html Demonstrates the use of `get_unchecked` for accessing slice elements without bounds checking. This method is unsafe and requires careful handling to avoid undefined behavior. It is similar to `get(index).unwrap_unchecked()` but with stricter safety requirements. ```rust let x = &[1, 2, 4]; unsafe { assert_eq!(x.get_unchecked(1), &2); } ``` -------------------------------- ### Join Queries with QueryLens Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Populated.html Shows how to combine multiple queries into a single QueryLens using the join method. This allows iterating over combined data from different query sources. ```rust fn system( mut transforms: Query<&Transform>, mut players: Query<&Player>, mut enemies: Query<&Enemy> ) { let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players); for (transform, player) in &players_transforms.query() { // do something with a and b } let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies); for (transform, enemy) in &enemies_transforms.query() { // do something with a and b } } ``` -------------------------------- ### Configure Component Hooks with Function Calls (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/component/trait.Component.html Illustrates configuring component hooks using function calls that return closures. This allows for more dynamic hook setup, such as passing arguments to hook-generating functions. The example uses a `my_msg_hook` function to create hooks that print messages. ```Rust use bevy_ecs::prelude::* use bevy_ecs::component::DeferredWorld; use bevy_ecs::component::HookContext; #[derive(Component)] #[component(on_add = my_msg_hook("hello"))] #[component(on_despawn = my_msg_hook("yoink"))] struct ComponentA; // a hook closure generating function fn my_msg_hook(message: &'static str) -> impl Fn(DeferredWorld, HookContext) { move |_world, _ctx| { println!("{message}"); } } ``` -------------------------------- ### Get Element Offset in Slice (Rust - Nightly) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/unique_vec/struct.UniqueEntityEquivalentVec.html Returns the index of a given element reference within a slice. This method uses pointer arithmetic and does not compare elements. It returns None if the element reference is not precisely at the start of an element in the slice. This API is experimental and requires the 'substr_range' feature. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Rust: Queuing Custom Commands Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Shows how to queue arbitrary commands with custom logic using a closure that mutates the World. Type annotations are required for the closure. ```rust // NOTE: type inference fails here, so annotations are required on the closure. commands.queue(|w: &mut World| { // Mutate the world however you want... }); ``` -------------------------------- ### Get Current Change Tick Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/unsafe_world_cell/struct.UnsafeWorldCell.html Gets the current change tick of the world, used for change detection. ```rust pub fn change_tick(&self) -> Tick ``` -------------------------------- ### Constructing Queries with QueryBuilder Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/query/struct.QueryBuilder.html Demonstrates how to initialize a QueryBuilder, apply filters like 'with' and 'without', and consume the resulting QueryState to fetch entities from the World. ```rust let mut world = World::new(); let entity_a = world.spawn((A, B)).id(); let entity_b = world.spawn((A, C)).id(); // Instantiate the builder using the type signature of the iterator you will consume let mut query = QueryBuilder::<(Entity, &B)>::new(&mut world) // Add additional terms through builder methods .with::() .without::() .build(); // Consume the QueryState let (entity, b) = query.single(&world).unwrap(); ``` -------------------------------- ### SystemParamBuilder Usage Examples Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/trait.SystemParamBuilder.html Examples demonstrating how to use SystemParamBuilder to build systems with various parameter types, including closures and resource access. ```APIDOC ### Usage Examples #### Building a simple system: ```rust fn some_system(param: MyParam) {} fn build_system(builder: impl SystemParamBuilder) { let mut world = World::new(); // To build a system, create a tuple of `SystemParamBuilder`s // with a builder for each parameter. // Note that the builder for a system must be a tuple, // even if there is only one parameter. (builder,) .build_state(&mut world) .build_system(some_system); } ``` #### Building a closure system with inferred parameter types: ```rust fn build_closure_system_infer(builder: impl SystemParamBuilder) { let mut world = World::new(); // Closures can be used in addition to named functions. // If a closure is used, the parameter types must all be inferred // from the builders, so you cannot use plain `ParamBuilder`. (builder, ParamBuilder::resource::>()) .build_state(&mut world) .build_system(|param, res| { let param: MyParam = param; let res: Res = res; }); } ``` #### Building a closure system with explicit parameter types: ```rust fn build_closure_system_explicit(builder: impl SystemParamBuilder) { let mut world = World::new(); // Alternately, you can provide all types in the closure // parameter list and call `build_any_system()`. (builder, ParamBuilder) .build_state(&mut world) .build_any_system(|param: MyParam, res: Res| {}); } ``` ``` -------------------------------- ### Get Resource Safely (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.DeferredWorld.html Safely gets an optional immutable reference to a resource of the given type. Returns `None` if the resource does not exist. ```rust pub fn get_resource(&self) -> Option<&R> ``` -------------------------------- ### Initialize System Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/trait.System.html Initializes the system. This method is part of the system's lifecycle and is called once during setup. ```rust fn initialize(&mut self, _world: &mut World) ``` -------------------------------- ### QueryState Get Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/query/struct.QueryState.html Gets the query result for a given World and Entity. This can only be called for read-only queries. This is always guaranteed to run in O(1) time. ```APIDOC ## GET /query/get ### Description Gets the query result for the given `World` and `Entity`. This can only be called for read-only queries. This is always guaranteed to run in `O(1)` time. ### Method GET ### Endpoint /query/get ### Parameters #### Query Parameters - **world** (&'w World) - Required - The world to query. - **entity** (Entity) - Required - The entity to get the query result for. ### Request Body (No request body for GET requests) ### Response #### Success Response (200) - **result** (ROQueryItem<'w, D>) - The query result for the entity. #### Error Response (400) - **error** (QueryEntityError) - An error if the entity does not exist or has mismatched components. #### Response Example ```json { "result": "" } ``` ``` -------------------------------- ### World Initialization API Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/component/struct.Components.html Methods for creating instances from the Bevy World context. ```APIDOC ## [METHOD] from_world ### Description Creates an instance of the type using the provided World context. ### Method N/A (Rust Method) ### Parameters - **_world** (&mut World) - Required - The ECS world instance. ### Response - **T** - The initialized instance. ``` -------------------------------- ### Rust: Using Commands in a System Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Demonstrates how to obtain and use a mutable Commands instance within a Bevy system to modify the World. ```rust fn my_system(mut commands: Commands) { // ... } ``` -------------------------------- ### Get Non-Send Resource (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.DeferredWorld.html Gets an immutable reference to a non-send resource of the given type. Panics if the resource does not exist or if called from a different thread. ```rust pub fn non_send_resource(&self) -> &R ``` -------------------------------- ### get method for FilteredEntityMut (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.FilteredEntityMut.html The `get` method attempts to retrieve an immutable reference to a component of type `T` from the current entity. It returns `Some(&T)` if the component exists and `None` if it does not. ```rust pub fn get(&self) -> Option<&T> ``` -------------------------------- ### Define and Run a Basic Schedule with a System in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/struct.Schedule.html Demonstrates how to create a `Schedule`, add a simple system to it, and then run the schedule with a `World`. This is the fundamental way to execute systems in Bevy. ```rust fn hello_world() { println!("Hello world!") } fn main() { let mut world = World::new(); let mut schedule = Schedule::default(); schedule.add_systems(hello_world); schedule.run(&mut world); } ``` -------------------------------- ### Get Type ID using Any Trait Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/hash_set/struct.EntityHashSet.html Provides a method to get the `TypeId` of a type implementing the `Any` trait. This is a fundamental part of dynamic typing in Rust. ```rust impl Any for T where T: 'static + ?Sized, { fn type_id(&self) -> TypeId { // ... implementation details ... } } ``` -------------------------------- ### POST /commands/insert_or_spawn_batch Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Pushes a command to the queue for creating entities and adding bundles. Note: This method is deprecated since 0.16.0 due to potential performance issues. ```APIDOC ## POST /commands/insert_or_spawn_batch ### Description Pushes a command to the queue for creating entities, if needed, and for adding a bundle to each entity. This method is faster than individual spawns due to memory pre-allocation. ### Method POST ### Endpoint /commands/insert_or_spawn_batch ### Parameters #### Request Body - **bundles_iter** (Iterator<(Entity, Bundle)>) - Required - An iterator of entity and bundle pairs to be processed. ### Response #### Success Response (200) - **status** (string) - Command successfully queued. #### Warning Deprecated since 0.16.0: This can cause extreme performance problems when used with lots of arbitrary free entities. ``` -------------------------------- ### EventCursor Struct Definition and Usage Example in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/event/struct.EventCursor.html Defines the `EventCursor` struct used for managing event reader/mutator state and provides a comprehensive example of its usage in a system that sends and receives events. This example demonstrates how to use `Local>` and `ResMut>` to handle event processing within a single system, including collecting events to resend. ```rust pub struct EventCursor { /* private fields */ } #[derive(Event, Clone, Debug)] struct MyEvent; /// A system that both sends and receives events using a [`Local`] [`EventCursor`]. fn send_and_receive_events( // The `Local` `SystemParam` stores state inside the system itself, rather than in the world. // `EventCursor` is the internal state of `EventMutator`, which tracks which events have been seen. mut local_event_reader: Local>, // We can access the `Events` resource mutably, allowing us to both read and write its contents. mut events: ResMut>, ) { // We must collect the events to resend, because we can't mutate events while we're iterating over the events. let mut events_to_resend = Vec::new(); for event in local_event_reader.read(&mut events) { events_to_resend.push(event.clone()); } for event in events_to_resend { events.send(MyEvent); } } ``` -------------------------------- ### Initialize Systems and Rebuild Schedule in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/struct.Schedule.html The `initialize` method prepares newly added systems and conditions, rebuilds the schedule's internal graph, and re-initializes the executor. It returns a `Result` to handle potential build errors. ```rust schedule.initialize(&mut world)?; ``` -------------------------------- ### FilteredEntityRef Methods: Getting Components Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.FilteredEntityRef.html Provides methods to get read-only references or `Ref` wrappers to components of a specific type or ID. Includes options for change detection. ```rust pub fn get(&self) -> Option<&'w T> pub fn get_ref(&self) -> Option> pub fn get_change_ticks(&self) -> Option pub fn get_change_ticks_by_id( &self, component_id: ComponentId, ) -> Option pub fn get_by_id(&self, component_id: ComponentId) -> Option> ``` -------------------------------- ### Get value by key in Bevy ECS HashMap Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/hash_map/struct.EntityHashMap.html The `get` function returns an immutable reference to the value associated with a given key. If the key is not found, it returns `None`. ```rust let mut map = HashMap::new(); map.insert("foo", 0); assert_eq!(map.get("foo"), Some(&0)); ``` -------------------------------- ### Initialize with Default using or_default Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/enum.Entry.html Uses the or_default method to insert a component using its Default implementation if the entry is vacant. ```rust #[derive(Component, Default, Clone, Copy, Debug, PartialEq)] struct Comp(u32); let mut entity = world.spawn_empty(); entity.entry::().or_default(); assert_eq!(world.query::<&Comp>().single(&world).unwrap().0, 0); ``` -------------------------------- ### Iterate over query items with Populated Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Populated.html Demonstrates how to use a Query within a system to iterate over specific components. This example shows accessing the Player component for every entity that possesses it. ```rust fn report_names_system(query: Query<&Player>) { for player in &query { println!("Say hello to {}!", player.name); } } ``` -------------------------------- ### EventReader::par_read Example (Multi-threaded) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/event/struct.EventReader.html Shows how to use `par_read` for parallel event iteration, available when the `multi_threaded` feature is enabled. This example processes events concurrently using `for_each`. ```rust #[derive(Event)] struct MyEvent { value: usize, } #[derive(Resource, Default)] struct Counter(AtomicUsize); // setup let mut world = World::new(); world.init_resource::>(); world.insert_resource(Counter::default()); let mut schedule = Schedule::default(); schedule.add_systems(|mut events: EventReader, counter: Res| { events.par_read().for_each(|MyEvent { value }| { counter.0.fetch_add(*value, Ordering::Relaxed); }); }); for value in 0..100 { world.send_event(MyEvent { value }); } schedule.run(&mut world); let Counter(counter) = world.remove_resource::().unwrap(); // all events were processed assert_eq!(counter.into_inner(), 4950); ``` -------------------------------- ### Building ParamSet with Tuple of System Parameters Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.ParamSetBuilder.html Demonstrates how to build a ParamSet using a tuple of QueryParamBuilders and ParamBuilder. This example shows accessing parameters by index (p0, p1, p2) for iteration over entities. ```rust let system = (ParamSetBuilder(( QueryParamBuilder::new(|builder| { builder.with::(); }), QueryParamBuilder::new(|builder| { builder.with::(); }), ParamBuilder, )),) .build_state(&mut world) .build_system(buildable_system_with_tuple); fn buildable_system_with_tuple( mut set: ParamSet<(Query<&mut Health>, Query<&mut Health>, &World)>, ) { // The first parameter is built from the first builder, // so this will iterate over enemies. for mut health in set.p0().iter_mut() {} // And the second parameter is built from the second builder, // so this will iterate over allies. for mut health in set.p1().iter_mut() {} // Parameters that don't need special building can use `ParamBuilder`. let entities = set.p2().entities(); } ``` -------------------------------- ### Get Resource Reference Safely with Change Detection (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.DeferredWorld.html Safely gets an optional reference with change detection to a resource of the given type. Returns `None` if the resource does not exist. ```rust pub fn get_resource_ref(&self) -> Option> ``` -------------------------------- ### Get Component by ID (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.EntityRefExcept.html Retrieves a raw pointer (Ptr<'w>) to a component identified by its ComponentId. Prefer the typed `get` method when possible. The pointer is only valid while EntityRefExcept is alive. ```rust pub fn get_by_id(&self, component_id: ComponentId) -> Option> ``` -------------------------------- ### POST /commands/insert_batch_if_new Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Adds bundles to entities while preserving existing components if they already exist. ```APIDOC ## POST /commands/insert_batch_if_new ### Description Adds a series of Bundles to each Entity they are paired with. This will keep any pre-existing components shared by the Bundle type and discard the new values. ### Method POST ### Endpoint /commands/insert_batch_if_new ### Parameters #### Request Body - **batch** (Iterator<(Entity, Bundle)>) - Required - A collection of (Entity, Bundle) tuples. ### Response #### Success Response (200) - **status** (string) - Batch insertion queued. #### Error Handling - **400** - Fails if any of the given entities do not exist. ``` -------------------------------- ### Get HashMap Allocation Size (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/hash_map/struct.EntityHashMap.html Demonstrates how to get the internal memory allocation size of a HashMap in bytes using `allocation_size`. This can be helpful for performance analysis and memory management. ```rust let mut map = HashMap::new(); assert_eq!(map.allocation_size(), 0); map.insert("foo", 0u32); assert!(map.allocation_size() >= size_of::<&'static str>() + size_of::()); ``` -------------------------------- ### Reference to Any Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/enum.ScheduleConfigs.html Provides methods to convert references (`&Trait` and `&mut Trait`) to `&dyn Any`. ```APIDOC ## `as_any` and `as_any_mut` ### Description Converts `&Trait` to `&Any` and `&mut Trait` to `&mut Any`. This is necessary because Rust cannot automatically generate v-tables for `&Any` from `&Trait`. ### Method - `&self.as_any() -> &(dyn Any + 'static)` - `&mut self.as_any_mut() -> &mut (dyn Any + 'static)` ### Endpoint N/A (Methods on `&Trait` and `&mut Trait`) ### Parameters None ### Request Example ```rust use std::any::Any; // Assuming Trait is defined elsewhere // let instance: Trait = ...; // let any_ref: &dyn Any = instance.as_any(); // let mut instance_mut: Trait = ...; // let any_mut_ref: &mut dyn Any = instance_mut.as_any_mut(); ``` ### Response #### Success Response - `&(dyn Any + 'static)`: A reference to the `Any` trait object. - `&mut (dyn Any + 'static)`: A mutable reference to the `Any` trait object. #### Response Example ```json // No direct JSON response, this is a Rust type conversion. ``` ``` -------------------------------- ### Get EntityCommands for Existing Entity in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/lifetimeless/type.SCommands.html Demonstrates how to get an `EntityCommands` for a specific, existing `Entity`. This allows modifying components or despawning the entity. It returns `EntityDoesNotExistError` if the entity is not found. ```rust pub fn entity(&mut self, entity: Entity) -> EntityCommands<'_> ``` ```rust #[derive(Resource)] struct PlayerEntity { entity: Entity } #[derive(Component)] struct Label(&'static str); fn example_system(mut commands: Commands, player: Res) { // Get the entity and add a component. commands.entity(player.entity).insert(Label("hello world")); } ``` ```rust pub fn get_entity( &mut self, entity: Entity, ) -> Result, EntityDoesNotExistError> ``` -------------------------------- ### Initialize and Access SystemNode Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/schedule/struct.SystemNode.html Demonstrates how to instantiate a new SystemNode from a ScheduleSystem and retrieve references to the underlying system. These methods allow for safe access to the system data stored within the graph node. ```rust use bevy_ecs::schedule::{SystemNode, ScheduleSystem}; // Create a new SystemNode let node = SystemNode::new(my_schedule_system); // Obtain an immutable reference if let Some(system) = node.get() { // Access system properties } // Obtain a mutable reference if let Some(system_mut) = node.get_mut() { // Modify system properties } ``` -------------------------------- ### Initialize and manage EntityIndexSet in Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/index_set/struct.EntityIndexSet.html Demonstrates how to instantiate an EntityIndexSet and access its core functionality. It supports both default construction and capacity-based initialization. ```Rust use bevy_ecs::entity::EntityIndexSet; // Create an empty set let mut set = EntityIndexSet::new(); // Create a set with specific capacity let mut capacity_set = EntityIndexSet::with_capacity(10); // Check properties let len = set.len(); let is_empty = set.is_empty(); // Clear the set set.clear(); ``` -------------------------------- ### SpawnOne Example (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/spawn/trait.SpawnRelated.html Demonstrates the usage of the spawn_one method from the SpawnRelated trait to spawn a single related entity. This example shows how to add a 'Child' entity with a 'Name' component to a 'Root' entity. ```rust let mut world = World::new(); world.spawn(( Name::new("Root"), Children::spawn_one(Name::new("Child")), )); ``` -------------------------------- ### Queue Entity Command (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.EntityCommands.html Illustrates how to queue an `EntityCommand` to be executed for a specific entity. This allows for deferred execution of commands, including custom logic via closures. ```rust commands .spawn_empty() // Closures with this signature implement `EntityCommand`. .queue(|entity: EntityWorldMut| { println!("Executed an EntityCommand for {}", entity.id()); }); ``` -------------------------------- ### Get Non-Send Resource Safely (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.DeferredWorld.html Safely gets an optional immutable reference to a non-send resource of the given type. Returns `None` if the resource does not exist. Panics if called from a different thread. ```rust pub fn get_non_send_resource(&self) -> Option<&R> ``` -------------------------------- ### Get Mutable Resource by ID (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/struct.DeferredWorld.html Gets a mutable pointer to a resource using its `ComponentId`. This is useful when the resource type is not known at compile time. Prefer `World::get_resource_mut` when types are known. ```rust use bevy_ecs::prelude::*; // Assuming 'world' is a mutable reference to a World // let mut world: World; // Placeholder for World, ComponentId, and MutUntyped types struct World; impl World { fn get_resource_mut_by_id( &mut self, component_id: ComponentId, ) -> Option> { // Dummy implementation None } fn get_non_send_mut_by_id( &mut self, component_id: ComponentId, ) -> Option> { // Dummy implementation None } } struct ComponentId(usize); struct MutUntyped<'a> { _marker: std::marker::PhantomData<&'a ()> } // Example usage: // fn example_usage(mut world: World, resource_id: ComponentId) { // if let Some(resource_ptr) = world.get_resource_mut_by_id(resource_id) { // // Use the untyped mutable pointer // } // } ``` -------------------------------- ### Entity Spawning API Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.Commands.html Methods for spawning entities, either individually or in batches. ```APIDOC ## POST /spawn_batch ### Description Spawns multiple entities with the same combination of components, based on a batch of `Bundles`. This method is equivalent to iterating the batch and calling `spawn` for each bundle, but is faster by pre-allocating memory and having exclusive `World` access. ### Method POST ### Endpoint `/spawn_batch` ### Parameters #### Request Body - **batch** (Array) - Required - An iterable collection of bundles to spawn as entities. ### Request Example ```json [ {"Name": "Alice", "Score": 0}, {"Name": "Bob", "Score": 0} ] ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful spawning of entities. #### Response Example ```json { "message": "Entities spawned successfully." } ``` ``` -------------------------------- ### Conversion Utilities Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/enum.Entry.html Standard conversion traits including Into, TryInto, and From implementations. ```APIDOC ## [METHOD] try_into ### Description Performs a fallible conversion from one type to another. ### Parameters #### Request Body - **self** (T) - Required - The source value. ### Response #### Success Response (200) - **Result** - The converted value or an error if conversion fails. ``` -------------------------------- ### Inserting Before an Index Example Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/index_set/struct.EntityIndexSet.html Demonstrates using insert_before to place elements at specific indices, showing how existing items are shifted and how the method handles duplicates. ```rust use indexmap::IndexSet; let mut set: IndexSet = ('a'..='z').collect(); assert_eq!(set.get_index_of(&'*'), None); assert_eq!(set.insert_before(10, '*'), (10, true)); assert_eq!(set.get_index_of(&'*'), Some(10)); assert_eq!(set.insert_before(10, 'a'), (9, false)); assert_eq!(set.get_index_of(&'a'), Some(9)); ``` -------------------------------- ### Get Resource Reference (Unsafe) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/unsafe_world_cell/struct.UnsafeWorldCell.html Safely gets an immutable reference to a resource of the specified type if it exists. The caller must ensure the `UnsafeWorldCell` has permission to access the resource and that no mutable references exist concurrently. ```rust pub unsafe fn get_resource(&self) -> Option<&'w R> ``` -------------------------------- ### CloneToUninit (Nightly Experimental) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/unsafe_world_cell/struct.UnsafeEntityCell.html An experimental, nightly-only API for performing copy-assignment from a source to an uninitialized destination. Requires the type to implement `Clone`. ```rust impl CloneToUninit for T where T: Clone, { unsafe fn clone_to_uninit(&self, dest: *mut u8) } ``` -------------------------------- ### Get Data Slice from ThinColumn - Rust Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/storage/struct.ThinColumn.html Provides an unsafe function to get a slice of the data stored within a ThinColumn. Requires the type T to match the stored data and len to match the column's length. ```rust pub unsafe fn get_data_slice(&self, len: usize) -> &[UnsafeCell] ``` -------------------------------- ### ComponentSparseSet Contains and Get Operations (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/storage/struct.ComponentSparseSet.html Enables checking for the presence of a component for a given entity and retrieving component data. `contains()` returns a boolean, while `get()` returns an optional reference to the component's data. ```rust pub fn contains(&self, entity: Entity) -> bool pub fn get(&self, entity: Entity) -> Option> ``` -------------------------------- ### SystemParam Builder Implementation (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/trait.SystemParam.html Shows how to enable and use a SystemParam builder with a derived SystemParam implementation. The `#[system_param(builder)]` attribute generates a builder struct, and a custom method can expose this builder for creating SystemParam instances. ```Rust mod custom_param { use bevy_ecs::prelude::*; #[derive(SystemParam)] #[system_param(builder)] pub struct CustomParam<'w, 's> { query: Query<'w, 's, ()>, local: Local<'s, usize>, } impl<'w, 's> CustomParam<'w, 's> { pub fn builder( local: usize, query: impl FnOnce(&mut QueryBuilder<()>), ) -> impl SystemParamBuilder { CustomParamBuilder { local: LocalBuilder(local), query: QueryParamBuilder::new(query), } } } } use custom_param::CustomParam; // Example usage within a system setup context (requires a World and App setup) // let mut world = World::new(); // let system = (CustomParam::builder(100, |builder| { // builder.with::(); // Example component // }),) // .build_state(&mut world) // .build_system(|param: CustomParam| {}); ``` -------------------------------- ### Binary Search and Partitioning in Slices Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/hierarchy/struct.Children.html Provides examples of using binary_search to locate elements in sorted slices and partition_point to identify ranges or insertion indices. These methods are essential for maintaining sorted order and performing efficient lookups. ```rust let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; assert_eq!(s.binary_search(&13), Ok(9)); let low = s.partition_point(|x| x < &1); let high = s.partition_point(|x| x <= &1); assert_eq!(low, 1); assert_eq!(high, 5); ``` -------------------------------- ### Get Resource Reference with Change Detection (Unsafe) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/world/unsafe_world_cell/struct.UnsafeWorldCell.html Gets a reference to a resource, including change detection capabilities. This method is unsafe and requires the caller to ensure proper permissions and the absence of conflicting mutable borrows. ```rust pub unsafe fn get_resource_ref(&self) -> Option> ``` -------------------------------- ### HashMap Remove Example (Rust) Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/entity/hash_map/struct.EntityHashMap.html Shows how to use the `remove` method to delete a key-value pair from a HashMap. It returns the value if the key was present and `None` otherwise. The example verifies the map's state after removal. ```rust use hashbrown::HashMap; let mut map = HashMap::new(); // The map is empty assert!(map.is_empty() && map.capacity() == 0); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); // Now map holds none elements assert!(map.is_empty()); ``` -------------------------------- ### Insert Components and Bundles into Entities Source: https://docs.rs/bevy_ecs/0.16.1/bevy_ecs/system/struct.EntityCommands.html Illustrates various ways to insert individual components, pre-defined bundles, or tuples of components into an entity using EntityCommands. ```rust #[derive(Component)] struct Health(u32); #[derive(Component)] struct Strength(u32); #[derive(Component)] struct Defense(u32); #[derive(Bundle)] struct CombatBundle { health: Health, strength: Strength, } fn add_combat_stats_system(mut commands: Commands, player: Res) { commands .entity(player.entity) .insert(Defense(10)) .insert(CombatBundle { health: Health(100), strength: Strength(40), }); } ```