use bevy_utils::prelude::DebugName;12use crate::{3batching::BatchingStrategy,4component::Tick,5entity::{Entity, EntityDoesNotExistError, EntityEquivalent, EntitySet, UniqueEntityArray},6query::{7DebugCheckedUnwrap, NopWorldQuery, QueryCombinationIter, QueryData, QueryEntityError,8QueryFilter, QueryIter, QueryManyIter, QueryManyUniqueIter, QueryParIter, QueryParManyIter,9QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,10},11world::unsafe_world_cell::UnsafeWorldCell,12};13use core::{14marker::PhantomData,15mem::MaybeUninit,16ops::{Deref, DerefMut},17};1819/// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`].20///21/// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`].22/// Its iterators and getter methods return *query items*, which are types containing data related to an entity.23///24/// `Query` is a generic data structure that accepts two type parameters:25///26/// - **`D` (query data)**:27/// The type of data fetched by the query, which will be returned as the query item.28/// Only entities that match the requested data will generate an item.29/// Must implement the [`QueryData`] trait.30/// - **`F` (query filter)**:31/// An optional set of conditions that determine whether query items should be kept or discarded.32/// This defaults to [`unit`], which means no additional filters will be applied.33/// Must implement the [`QueryFilter`] trait.34///35/// [system parameter]: crate::system::SystemParam36/// [`Component`]: crate::component::Component37/// [`World`]: crate::world::World38/// [entity identifiers]: Entity39/// [components]: crate::component::Component40///41/// # Similar parameters42///43/// `Query` has few sibling [`SystemParam`]s, which perform additional validation:44///45/// - [`Single`] - Exactly one matching query item.46/// - [`Option<Single>`] - Zero or one matching query item.47/// - [`Populated`] - At least one matching query item.48///49/// These parameters will prevent systems from running if their requirements are not met.50///51/// [`SystemParam`]: crate::system::system_param::SystemParam52/// [`Option<Single>`]: Single53///54/// # System parameter declaration55///56/// A query should always be declared as a system parameter.57/// This section shows the most common idioms involving the declaration of `Query`.58///59/// ## Component access60///61/// You can fetch an entity's component by specifying a reference to that component in the query's data parameter:62///63/// ```64/// # use bevy_ecs::prelude::*;65/// #66/// # #[derive(Component)]67/// # struct ComponentA;68/// #69/// // A component can be accessed by a shared reference...70/// fn immutable_query(query: Query<&ComponentA>) {71/// // ...72/// }73///74/// // ...or by a mutable reference.75/// fn mutable_query(query: Query<&mut ComponentA>) {76/// // ...77/// }78/// #79/// # bevy_ecs::system::assert_is_system(immutable_query);80/// # bevy_ecs::system::assert_is_system(mutable_query);81/// ```82///83/// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile:84///85/// ```compile_fail,E027786/// # use bevy_ecs::prelude::*;87/// #88/// # #[derive(Component)]89/// # struct ComponentA;90/// #91/// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile.92/// fn invalid_query(query: Query<ComponentA>) {93/// // ...94/// }95/// ```96///97/// ## Query filtering98///99/// Setting the query filter type parameter will ensure that each query item satisfies the given condition:100///101/// ```102/// # use bevy_ecs::prelude::*;103/// #104/// # #[derive(Component)]105/// # struct ComponentA;106/// #107/// # #[derive(Component)]108/// # struct ComponentB;109/// #110/// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`.111/// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) {112/// // ...113/// }114/// #115/// # bevy_ecs::system::assert_is_system(filtered_query);116/// ```117///118/// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With`119/// does not require components to be behind a reference.120///121/// ## `QueryData` or `QueryFilter` tuples122///123/// Using [`tuple`]s, each `Query` type parameter can contain multiple elements.124///125/// In the following example two components are accessed simultaneously, and the query items are126/// filtered on two conditions:127///128/// ```129/// # use bevy_ecs::prelude::*;130/// #131/// # #[derive(Component)]132/// # struct ComponentA;133/// #134/// # #[derive(Component)]135/// # struct ComponentB;136/// #137/// # #[derive(Component)]138/// # struct ComponentC;139/// #140/// # #[derive(Component)]141/// # struct ComponentD;142/// #143/// fn complex_query(144/// query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>145/// ) {146/// // ...147/// }148/// #149/// # bevy_ecs::system::assert_is_system(complex_query);150/// ```151///152/// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to153/// get around this limit:154///155/// ```156/// # use bevy_ecs::prelude::*;157/// #158/// # #[derive(Component)]159/// # struct ComponentA;160/// #161/// # #[derive(Component)]162/// # struct ComponentB;163/// #164/// # #[derive(Component)]165/// # struct ComponentC;166/// #167/// # #[derive(Component)]168/// # struct ComponentD;169/// #170/// fn nested_query(171/// query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))>172/// ) {173/// // ...174/// }175/// #176/// # bevy_ecs::system::assert_is_system(nested_query);177/// ```178///179/// ## Entity identifier access180///181/// You can access [`Entity`], the entity identifier, by including it in the query data parameter:182///183/// ```184/// # use bevy_ecs::prelude::*;185/// #186/// # #[derive(Component)]187/// # struct ComponentA;188/// #189/// fn entity_id_query(query: Query<(Entity, &ComponentA)>) {190/// // ...191/// }192/// #193/// # bevy_ecs::system::assert_is_system(entity_id_query);194/// ```195///196/// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference.197///198/// ## Optional component access199///200/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a201/// query item will still be generated even if the queried entity does not contain `ComponentB`.202/// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`.203///204/// ```205/// # use bevy_ecs::prelude::*;206/// #207/// # #[derive(Component)]208/// # struct ComponentA;209/// #210/// # #[derive(Component)]211/// # struct ComponentB;212/// #213/// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will214/// // be fetched as well.215/// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) {216/// // ...217/// }218/// #219/// # bevy_ecs::system::assert_is_system(optional_component_query);220/// ```221///222/// Optional components can hurt performance in some cases, so please read the [performance]223/// section to learn more about them. Additionally, if you need to declare several optional224/// components, you may be interested in using [`AnyOf`].225///226/// [performance]: #performance227/// [`AnyOf`]: crate::query::AnyOf228///229/// ## Disjoint queries230///231/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic232/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries233/// disjoint.234///235/// In the following example, the two queries can mutably access the same `&mut Health` component236/// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic,237/// however, instead of breaking Rust's mutability rules:238///239/// ```should_panic240/// # use bevy_ecs::prelude::*;241/// #242/// # #[derive(Component)]243/// # struct Health;244/// #245/// # #[derive(Component)]246/// # struct Player;247/// #248/// # #[derive(Component)]249/// # struct Enemy;250/// #251/// fn randomize_health(252/// player_query: Query<&mut Health, With<Player>>,253/// enemy_query: Query<&mut Health, With<Enemy>>,254/// ) {255/// // ...256/// }257/// #258/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);259/// ```260///261/// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity262/// that has both the `Player` and `Enemy` components will be excluded from _both_ queries:263///264/// ```265/// # use bevy_ecs::prelude::*;266/// #267/// # #[derive(Component)]268/// # struct Health;269/// #270/// # #[derive(Component)]271/// # struct Player;272/// #273/// # #[derive(Component)]274/// # struct Enemy;275/// #276/// fn randomize_health(277/// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,278/// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,279/// ) {280/// // ...281/// }282/// #283/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);284/// ```285///286/// An alternative solution to this problem would be to wrap the conflicting queries in287/// [`ParamSet`].288///289/// [`Without`]: crate::query::Without290/// [`ParamSet`]: crate::system::ParamSet291///292/// ## Whole Entity Access293///294/// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity.295/// This is useful when dynamically fetching components instead of baking them into the query type.296///297/// ```298/// # use bevy_ecs::prelude::*;299/// #300/// # #[derive(Component)]301/// # struct ComponentA;302/// #303/// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) {304/// // ...305/// }306/// #307/// # bevy_ecs::system::assert_is_system(all_components_query);308/// ```309///310/// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any*311/// mutable component access.312///313/// ```should_panic314/// # use bevy_ecs::prelude::*;315/// #316/// # #[derive(Component)]317/// # struct ComponentA;318/// #319/// // `EntityRef` provides read access to *all* components on an entity. When combined with320/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read321/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing322/// // rules.323/// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) {324/// // ...325/// }326/// #327/// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query);328/// ```329///330/// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] /331/// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and332/// parallelization of the system, but it enables systems to gain mutable access to other333/// components:334///335/// ```336/// # use bevy_ecs::prelude::*;337/// #338/// # #[derive(Component)]339/// # struct ComponentA;340/// #341/// # #[derive(Component)]342/// # struct ComponentB;343/// #344/// // The first query only reads entities that have `ComponentA`, while the second query only345/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same346/// // entity, this system does not conflict.347/// fn disjoint_query(348/// query_a: Query<EntityRef, With<ComponentA>>,349/// query_b: Query<&mut ComponentB, Without<ComponentA>>,350/// ) {351/// // ...352/// }353/// #354/// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query);355/// ```356///357/// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never358/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the359/// queries on completely separate entities.360///361/// [`EntityRef`]: crate::world::EntityRef362/// [`With`]: crate::query::With363///364/// # Accessing query items365///366/// The following table summarizes the behavior of safe methods that can be used to get query367/// items:368///369/// |Query methods|Effect|370/// |-|-|371/// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.|372/// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.|373/// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.|374/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.|375/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.|376/// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.|377/// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.|378///379/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).380/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.381/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.382///383/// [`iter`]: Self::iter384/// [`iter_mut`]: Self::iter_mut385/// [`for_each`]: #iteratorfor_each386/// [`par_iter`]: Self::par_iter387/// [`par_iter_mut`]: Self::par_iter_mut388/// [`iter_many`]: Self::iter_many389/// [`iter_many_unique`]: Self::iter_many_unique390/// [`iter_many_mut`]: Self::iter_many_mut391/// [`iter_combinations`]: Self::iter_combinations392/// [`iter_combinations_mut`]: Self::iter_combinations_mut393/// [`single_mut`]: Self::single_mut394/// [`get`]: Self::get395/// [`get_mut`]: Self::get_mut396/// [`get_many`]: Self::get_many397/// [`get_many_unique`]: Self::get_many_unique398/// [`get_many_mut`]: Self::get_many_mut399///400/// # Performance401///402/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches403/// data from the world and generates items, which can have a significant computational cost.404///405/// Two systems cannot be executed in parallel if both access the same component type where at406/// least one of the accesses is mutable. Because of this, it is recommended for queries to only407/// fetch mutable access to components when necessary, since immutable access can be parallelized.408///409/// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of410/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be411/// parallelized by the scheduler.412///413/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and414/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is415/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the416/// query would iterate over all entities in the world.417///418/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers419/// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite:420/// it offers fast component insertion and removal speeds, but slower iteration speeds.421///422/// The following table compares the computational complexity of the various methods and423/// operations, where:424///425/// - **n** is the number of entities that match the query.426/// - **r** is the number of elements in a combination.427/// - **k** is the number of involved entities in the operation.428/// - **a** is the number of archetypes in the world.429/// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is430/// read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r*431/// elements that can be taken from a set of *n* elements.432///433/// |Query operation|Computational complexity|434/// |-|-|435/// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)|436/// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)|437/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)|438/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)|439/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)|440/// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)|441/// |[`get_many`]|O(k)|442/// |[`get_many_mut`]|O(k<sup>2</sup>)|443/// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)|444/// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)|445///446/// [component storage types]: crate::component::StorageType447/// [`Table`]: crate::storage::Table448/// [`SparseSet`]: crate::storage::SparseSet449/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient450/// [`Or`]: crate::query::Or451/// [`Added`]: crate::query::Added452/// [`Changed`]: crate::query::Changed453/// [`Spawned`]: crate::query::Spawned454///455/// # `Iterator::for_each`456///457/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with458/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It459/// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance.460/// *Always* profile or benchmark before and after the change!461///462/// ```rust463/// # use bevy_ecs::prelude::*;464/// #465/// # #[derive(Component)]466/// # struct ComponentA;467/// #468/// fn system(query: Query<&ComponentA>) {469/// // This may result in better performance...470/// query.iter().for_each(|component| {471/// // ...472/// });473///474/// // ...than this. Always benchmark to validate the difference!475/// for component in query.iter() {476/// // ...477/// }478/// }479/// #480/// # bevy_ecs::system::assert_is_system(system);481/// ```482///483/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization484pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {485// SAFETY: Must have access to the components registered in `state`.486world: UnsafeWorldCell<'world>,487state: &'state QueryState<D, F>,488last_run: Tick,489this_run: Tick,490}491492impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {493fn clone(&self) -> Self {494*self495}496}497498impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}499500impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {501fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {502f.debug_struct("Query")503.field("matched_entities", &self.iter().count())504.field("state", &self.state)505.field("last_run", &self.last_run)506.field("this_run", &self.this_run)507.field("world", &self.world)508.finish()509}510}511512impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {513/// Creates a new query.514///515/// # Safety516///517/// * This will create a query that could violate memory safety rules. Make sure that this is only518/// called in ways that ensure the queries have unique mutable access.519/// * `world` must be the world used to create `state`.520#[inline]521pub(crate) unsafe fn new(522world: UnsafeWorldCell<'w>,523state: &'s QueryState<D, F>,524last_run: Tick,525this_run: Tick,526) -> Self {527Self {528world,529state,530last_run,531this_run,532}533}534535/// Returns another `Query` from this that fetches the read-only version of the query items.536///537/// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.538/// This can be useful when working around the borrow checker,539/// or reusing functionality between systems via functions that accept query types.540///541/// # See also542///543/// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.544pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {545// SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access,546// and the original query is held with a shared borrow, so it cannot perform mutable access either.547unsafe { self.reborrow_unsafe() }.into_readonly()548}549550/// Returns another `Query` from this does not return any data, which can be faster.551fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {552let new_state = self.state.as_nop();553// SAFETY:554// - The reborrowed query is converted to read-only, so it cannot perform mutable access,555// and the original query is held with a shared borrow, so it cannot perform mutable access either.556// Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query,557// it has the original `QueryState::component_access` and could be `transmute`d to a read-only query.558// - The world matches because it was the same one used to construct self.559unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }560}561562/// Returns another `Query` from this that fetches the read-only version of the query items.563///564/// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.565/// This can be useful when working around the borrow checker,566/// or reusing functionality between systems via functions that accept query types.567///568/// # See also569///570/// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.571pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {572let new_state = self.state.as_readonly();573// SAFETY:574// - This is memory safe because it turns the query immutable.575// - The world matches because it was the same one used to construct self.576unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }577}578579/// Returns a new `Query` reborrowing the access from this one. The current query will be unusable580/// while the new one exists.581///582/// # Example583///584/// For example this allows to call other methods or other systems that require an owned `Query` without585/// completely giving up ownership of it.586///587/// ```588/// # use bevy_ecs::prelude::*;589/// #590/// # #[derive(Component)]591/// # struct ComponentA;592///593/// fn helper_system(query: Query<&ComponentA>) { /* ... */}594///595/// fn system(mut query: Query<&ComponentA>) {596/// helper_system(query.reborrow());597/// // Can still use query here:598/// for component in &query {599/// // ...600/// }601/// }602/// ```603pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {604// SAFETY: this query is exclusively borrowed while the new one exists, so605// no overlapping access can occur.606unsafe { self.reborrow_unsafe() }607}608609/// Returns a new `Query` reborrowing the access from this one.610/// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.611///612/// # Safety613///614/// This function makes it possible to violate Rust's aliasing guarantees.615/// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.616///617/// # See also618///619/// - [`reborrow`](Self::reborrow) for the safe versions.620pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> {621// SAFETY:622// - This is memory safe because the caller ensures that there are no conflicting references.623// - The world matches because it was the same one used to construct self.624unsafe { self.copy_unsafe() }625}626627/// Returns a new `Query` copying the access from this one.628/// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.629///630/// # Safety631///632/// This function makes it possible to violate Rust's aliasing guarantees.633/// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.634///635/// # See also636///637/// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.638unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> {639// SAFETY:640// - This is memory safe because the caller ensures that there are no conflicting references.641// - The world matches because it was the same one used to construct self.642unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }643}644645/// Returns an [`Iterator`] over the read-only query items.646///647/// This iterator is always guaranteed to return results from each matching entity once and only once.648/// Iteration order is not guaranteed.649///650/// # Example651///652/// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:653///654/// ```655/// # use bevy_ecs::prelude::*;656/// #657/// # #[derive(Component)]658/// # struct Player { name: String }659/// #660/// fn report_names_system(query: Query<&Player>) {661/// for player in &query {662/// println!("Say hello to {}!", player.name);663/// }664/// }665/// # bevy_ecs::system::assert_is_system(report_names_system);666/// ```667///668/// # See also669///670/// [`iter_mut`](Self::iter_mut) for mutable query items.671#[inline]672pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {673self.as_readonly().into_iter()674}675676/// Returns an [`Iterator`] over the query items.677///678/// This iterator is always guaranteed to return results from each matching entity once and only once.679/// Iteration order is not guaranteed.680///681/// # Example682///683/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:684///685/// ```686/// # use bevy_ecs::prelude::*;687/// #688/// # #[derive(Component)]689/// # struct Velocity { x: f32, y: f32, z: f32 }690/// fn gravity_system(mut query: Query<&mut Velocity>) {691/// const DELTA: f32 = 1.0 / 60.0;692/// for mut velocity in &mut query {693/// velocity.y -= 9.8 * DELTA;694/// }695/// }696/// # bevy_ecs::system::assert_is_system(gravity_system);697/// ```698///699/// # See also700///701/// [`iter`](Self::iter) for read-only query items.702#[inline]703pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {704self.reborrow().into_iter()705}706707/// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.708///709/// This iterator is always guaranteed to return results from each unique pair of matching entities.710/// Iteration order is not guaranteed.711///712/// # Example713///714/// ```715/// # use bevy_ecs::prelude::*;716/// # #[derive(Component)]717/// # struct ComponentA;718/// #719/// fn some_system(query: Query<&ComponentA>) {720/// for [a1, a2] in query.iter_combinations() {721/// // ...722/// }723/// }724/// ```725///726/// # See also727///728/// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.729/// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.730#[inline]731pub fn iter_combinations<const K: usize>(732&self,733) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {734self.as_readonly().iter_combinations_inner()735}736737/// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.738///739/// This iterator is always guaranteed to return results from each unique pair of matching entities.740/// Iteration order is not guaranteed.741///742/// # Example743///744/// ```745/// # use bevy_ecs::prelude::*;746/// # #[derive(Component)]747/// # struct ComponentA;748/// fn some_system(mut query: Query<&mut ComponentA>) {749/// let mut combinations = query.iter_combinations_mut();750/// while let Some([mut a1, mut a2]) = combinations.fetch_next() {751/// // mutably access components data752/// }753/// }754/// ```755///756/// # See also757///758/// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.759/// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.760#[inline]761pub fn iter_combinations_mut<const K: usize>(762&mut self,763) -> QueryCombinationIter<'_, 's, D, F, K> {764self.reborrow().iter_combinations_inner()765}766767/// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.768/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.769///770/// This iterator is always guaranteed to return results from each unique pair of matching entities.771/// Iteration order is not guaranteed.772///773/// # Example774///775/// ```776/// # use bevy_ecs::prelude::*;777/// # #[derive(Component)]778/// # struct ComponentA;779/// fn some_system(query: Query<&mut ComponentA>) {780/// let mut combinations = query.iter_combinations_inner();781/// while let Some([mut a1, mut a2]) = combinations.fetch_next() {782/// // mutably access components data783/// }784/// }785/// ```786///787/// # See also788///789/// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.790/// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.791#[inline]792pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K> {793// SAFETY: `self.world` has permission to access the required components.794unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }795}796797/// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.798///799/// Items are returned in the order of the list of entities, and may not be unique if the input800/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.801///802/// # Example803///804/// ```805/// # use bevy_ecs::prelude::*;806/// # #[derive(Component)]807/// # struct Counter {808/// # value: i32809/// # }810/// #811/// // A component containing an entity list.812/// #[derive(Component)]813/// struct Friends {814/// list: Vec<Entity>,815/// }816///817/// fn system(818/// friends_query: Query<&Friends>,819/// counter_query: Query<&Counter>,820/// ) {821/// for friends in &friends_query {822/// for counter in counter_query.iter_many(&friends.list) {823/// println!("Friend's counter: {}", counter.value);824/// }825/// }826/// }827/// # bevy_ecs::system::assert_is_system(system);828/// ```829///830/// # See also831///832/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.833/// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.834#[inline]835pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(836&self,837entities: EntityList,838) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {839self.as_readonly().iter_many_inner(entities)840}841842/// Returns an iterator over the query items generated from an [`Entity`] list.843///844/// Items are returned in the order of the list of entities, and may not be unique if the input845/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.846///847/// # Examples848///849/// ```850/// # use bevy_ecs::prelude::*;851/// #[derive(Component)]852/// struct Counter {853/// value: i32854/// }855///856/// #[derive(Component)]857/// struct Friends {858/// list: Vec<Entity>,859/// }860///861/// fn system(862/// friends_query: Query<&Friends>,863/// mut counter_query: Query<&mut Counter>,864/// ) {865/// for friends in &friends_query {866/// let mut iter = counter_query.iter_many_mut(&friends.list);867/// while let Some(mut counter) = iter.fetch_next() {868/// println!("Friend's counter: {}", counter.value);869/// counter.value += 1;870/// }871/// }872/// }873/// # bevy_ecs::system::assert_is_system(system);874/// ```875/// # See also876///877/// - [`iter_many`](Self::iter_many) to get read-only query items.878/// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.879#[inline]880pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(881&mut self,882entities: EntityList,883) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {884self.reborrow().iter_many_inner(entities)885}886887/// Returns an iterator over the query items generated from an [`Entity`] list.888/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.889///890/// Items are returned in the order of the list of entities, and may not be unique if the input891/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.892///893/// # See also894///895/// - [`iter_many`](Self::iter_many) to get read-only query items.896/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.897#[inline]898pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(899self,900entities: EntityList,901) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {902// SAFETY: `self.world` has permission to access the required components.903unsafe {904QueryManyIter::new(905self.world,906self.state,907entities,908self.last_run,909self.this_run,910)911}912}913914/// Returns an [`Iterator`] over the unique read-only query items generated from an [`EntitySet`].915///916/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.917///918/// # Example919///920/// ```921/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};922/// # use core::slice;923/// # #[derive(Component)]924/// # struct Counter {925/// # value: i32926/// # }927/// #928/// // `Friends` ensures that it only lists unique entities.929/// #[derive(Component)]930/// struct Friends {931/// unique_list: Vec<Entity>,932/// }933///934/// impl<'a> IntoIterator for &'a Friends {935///936/// type Item = &'a Entity;937/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;938///939/// fn into_iter(self) -> Self::IntoIter {940/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.941/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }942/// }943/// }944///945/// fn system(946/// friends_query: Query<&Friends>,947/// counter_query: Query<&Counter>,948/// ) {949/// for friends in &friends_query {950/// for counter in counter_query.iter_many_unique(friends) {951/// println!("Friend's counter: {:?}", counter.value);952/// }953/// }954/// }955/// # bevy_ecs::system::assert_is_system(system);956/// ```957///958/// # See also959///960/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.961/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.962#[inline]963pub fn iter_many_unique<EntityList: EntitySet>(964&self,965entities: EntityList,966) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {967self.as_readonly().iter_many_unique_inner(entities)968}969970/// Returns an iterator over the unique query items generated from an [`EntitySet`].971///972/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.973///974/// # Examples975///976/// ```977/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};978/// # use core::slice;979/// #[derive(Component)]980/// struct Counter {981/// value: i32982/// }983///984/// // `Friends` ensures that it only lists unique entities.985/// #[derive(Component)]986/// struct Friends {987/// unique_list: Vec<Entity>,988/// }989///990/// impl<'a> IntoIterator for &'a Friends {991/// type Item = &'a Entity;992/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;993///994/// fn into_iter(self) -> Self::IntoIter {995/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.996/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }997/// }998/// }999///1000/// fn system(1001/// friends_query: Query<&Friends>,1002/// mut counter_query: Query<&mut Counter>,1003/// ) {1004/// for friends in &friends_query {1005/// for mut counter in counter_query.iter_many_unique_mut(friends) {1006/// println!("Friend's counter: {:?}", counter.value);1007/// counter.value += 1;1008/// }1009/// }1010/// }1011/// # bevy_ecs::system::assert_is_system(system);1012/// ```1013/// # See also1014///1015/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.1016/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.1017#[inline]1018pub fn iter_many_unique_mut<EntityList: EntitySet>(1019&mut self,1020entities: EntityList,1021) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {1022self.reborrow().iter_many_unique_inner(entities)1023}10241025/// Returns an iterator over the unique query items generated from an [`EntitySet`].1026/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1027///1028/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.1029///1030/// # Examples1031///1032/// ```1033/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};1034/// # use core::slice;1035/// #[derive(Component)]1036/// struct Counter {1037/// value: i321038/// }1039///1040/// // `Friends` ensures that it only lists unique entities.1041/// #[derive(Component)]1042/// struct Friends {1043/// unique_list: Vec<Entity>,1044/// }1045///1046/// impl<'a> IntoIterator for &'a Friends {1047/// type Item = &'a Entity;1048/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;1049///1050/// fn into_iter(self) -> Self::IntoIter {1051/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.1052/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }1053/// }1054/// }1055///1056/// fn system(1057/// friends_query: Query<&Friends>,1058/// mut counter_query: Query<&mut Counter>,1059/// ) {1060/// let friends = friends_query.single().unwrap();1061/// for mut counter in counter_query.iter_many_unique_inner(friends) {1062/// println!("Friend's counter: {:?}", counter.value);1063/// counter.value += 1;1064/// }1065/// }1066/// # bevy_ecs::system::assert_is_system(system);1067/// ```1068/// # See also1069///1070/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.1071/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.1072#[inline]1073pub fn iter_many_unique_inner<EntityList: EntitySet>(1074self,1075entities: EntityList,1076) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter> {1077// SAFETY: `self.world` has permission to access the required components.1078unsafe {1079QueryManyUniqueIter::new(1080self.world,1081self.state,1082entities,1083self.last_run,1084self.this_run,1085)1086}1087}10881089/// Returns an [`Iterator`] over the query items.1090///1091/// This iterator is always guaranteed to return results from each matching entity once and only once.1092/// Iteration order is not guaranteed.1093///1094/// # Safety1095///1096/// This function makes it possible to violate Rust's aliasing guarantees.1097/// You must make sure this call does not result in multiple mutable references to the same component.1098///1099/// # See also1100///1101/// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.1102#[inline]1103pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {1104// SAFETY: The caller promises that this will not result in multiple mutable references.1105unsafe { self.reborrow_unsafe() }.into_iter()1106}11071108/// Iterates over all possible combinations of `K` query items without repetition.1109///1110/// This iterator is always guaranteed to return results from each unique pair of matching entities.1111/// Iteration order is not guaranteed.1112///1113/// # Safety1114///1115/// This allows aliased mutability.1116/// You must make sure this call does not result in multiple mutable references to the same component.1117///1118/// # See also1119///1120/// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.1121#[inline]1122pub unsafe fn iter_combinations_unsafe<const K: usize>(1123&self,1124) -> QueryCombinationIter<'_, 's, D, F, K> {1125// SAFETY: The caller promises that this will not result in multiple mutable references.1126unsafe { self.reborrow_unsafe() }.iter_combinations_inner()1127}11281129/// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.1130///1131/// Items are returned in the order of the list of entities, and may not be unique if the input1132/// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.1133///1134/// # Safety1135///1136/// This allows aliased mutability and does not check for entity uniqueness.1137/// You must make sure this call does not result in multiple mutable references to the same component.1138/// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].1139///1140/// # See also1141///1142/// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.1143pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(1144&self,1145entities: EntityList,1146) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {1147// SAFETY: The caller promises that this will not result in multiple mutable references.1148unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)1149}11501151/// Returns an [`Iterator`] over the unique query items generated from an [`Entity`] list.1152///1153/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.1154///1155/// # Safety1156///1157/// This allows aliased mutability.1158/// You must make sure this call does not result in multiple mutable references to the same component.1159///1160/// # See also1161///1162/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.1163/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.1164/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.1165pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(1166&self,1167entities: EntityList,1168) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {1169// SAFETY: The caller promises that this will not result in multiple mutable references.1170unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)1171}11721173/// Returns a parallel iterator over the query results for the given [`World`].1174///1175/// This parallel iterator is always guaranteed to return results from each matching entity once and1176/// only once. Iteration order and thread assignment is not guaranteed.1177///1178/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1179/// on [`QueryIter`].1180///1181/// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.1182///1183/// Note that you must use the `for_each` method to iterate over the1184/// results, see [`par_iter_mut`] for an example.1185///1186/// [`par_iter_mut`]: Self::par_iter_mut1187/// [`World`]: crate::world::World1188#[inline]1189pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {1190self.as_readonly().par_iter_inner()1191}11921193/// Returns a parallel iterator over the query results for the given [`World`].1194///1195/// This parallel iterator is always guaranteed to return results from each matching entity once and1196/// only once. Iteration order and thread assignment is not guaranteed.1197///1198/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1199/// on [`QueryIter`].1200///1201/// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.1202///1203/// # Example1204///1205/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:1206///1207/// ```1208/// # use bevy_ecs::prelude::*;1209/// #1210/// # #[derive(Component)]1211/// # struct Velocity { x: f32, y: f32, z: f32 }1212/// fn gravity_system(mut query: Query<&mut Velocity>) {1213/// const DELTA: f32 = 1.0 / 60.0;1214/// query.par_iter_mut().for_each(|mut velocity| {1215/// velocity.y -= 9.8 * DELTA;1216/// });1217/// }1218/// # bevy_ecs::system::assert_is_system(gravity_system);1219/// ```1220///1221/// [`par_iter`]: Self::par_iter1222/// [`World`]: crate::world::World1223#[inline]1224pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F> {1225self.reborrow().par_iter_inner()1226}12271228/// Returns a parallel iterator over the query results for the given [`World`](crate::world::World).1229/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1230///1231/// This parallel iterator is always guaranteed to return results from each matching entity once and1232/// only once. Iteration order and thread assignment is not guaranteed.1233///1234/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1235/// on [`QueryIter`].1236///1237/// # Example1238///1239/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:1240///1241/// ```1242/// # use bevy_ecs::prelude::*;1243/// #1244/// # #[derive(Component)]1245/// # struct Velocity { x: f32, y: f32, z: f32 }1246/// fn gravity_system(query: Query<&mut Velocity>) {1247/// const DELTA: f32 = 1.0 / 60.0;1248/// query.par_iter_inner().for_each(|mut velocity| {1249/// velocity.y -= 9.8 * DELTA;1250/// });1251/// }1252/// # bevy_ecs::system::assert_is_system(gravity_system);1253/// ```1254#[inline]1255pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F> {1256QueryParIter {1257world: self.world,1258state: self.state,1259last_run: self.last_run,1260this_run: self.this_run,1261batching_strategy: BatchingStrategy::new(),1262}1263}12641265/// Returns a parallel iterator over the read-only query items generated from an [`Entity`] list.1266///1267/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.1268///1269/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1270/// on [`QueryManyIter`].1271///1272/// This can only be called for read-only queries. To avoid potential aliasing, there is no `par_iter_many_mut` equivalent.1273/// See [`par_iter_many_unique_mut`] for an alternative using [`EntitySet`].1274///1275/// Note that you must use the `for_each` method to iterate over the1276/// results, see [`par_iter_mut`] for an example.1277///1278/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut1279/// [`par_iter_mut`]: Self::par_iter_mut1280#[inline]1281pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(1282&self,1283entities: EntityList,1284) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {1285QueryParManyIter {1286world: self.world,1287state: self.state.as_readonly(),1288entity_list: entities.into_iter().collect(),1289last_run: self.last_run,1290this_run: self.this_run,1291batching_strategy: BatchingStrategy::new(),1292}1293}12941295/// Returns a parallel iterator over the unique read-only query items generated from an [`EntitySet`].1296///1297/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.1298///1299/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1300/// on [`QueryManyUniqueIter`].1301///1302/// This can only be called for read-only queries, see [`par_iter_many_unique_mut`] for write-queries.1303///1304/// Note that you must use the `for_each` method to iterate over the1305/// results, see [`par_iter_mut`] for an example.1306///1307/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut1308/// [`par_iter_mut`]: Self::par_iter_mut1309#[inline]1310pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(1311&self,1312entities: EntityList,1313) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {1314QueryParManyUniqueIter {1315world: self.world,1316state: self.state.as_readonly(),1317entity_list: entities.into_iter().collect(),1318last_run: self.last_run,1319this_run: self.this_run,1320batching_strategy: BatchingStrategy::new(),1321}1322}13231324/// Returns a parallel iterator over the unique query items generated from an [`EntitySet`].1325///1326/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.1327///1328/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1329/// on [`QueryManyUniqueIter`].1330///1331/// This can only be called for mutable queries, see [`par_iter_many_unique`] for read-only-queries.1332///1333/// Note that you must use the `for_each` method to iterate over the1334/// results, see [`par_iter_mut`] for an example.1335///1336/// [`par_iter_many_unique`]: Self::par_iter_many_unique1337/// [`par_iter_mut`]: Self::par_iter_mut1338#[inline]1339pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(1340&mut self,1341entities: EntityList,1342) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item> {1343QueryParManyUniqueIter {1344world: self.world,1345state: self.state,1346entity_list: entities.into_iter().collect(),1347last_run: self.last_run,1348this_run: self.this_run,1349batching_strategy: BatchingStrategy::new(),1350}1351}13521353/// Returns the read-only query item for the given [`Entity`].1354///1355/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1356///1357/// This is always guaranteed to run in `O(1)` time.1358///1359/// # Example1360///1361/// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.1362///1363/// ```1364/// # use bevy_ecs::prelude::*;1365/// #1366/// # #[derive(Resource)]1367/// # struct SelectedCharacter { entity: Entity }1368/// # #[derive(Component)]1369/// # struct Character { name: String }1370/// #1371/// fn print_selected_character_name_system(1372/// query: Query<&Character>,1373/// selection: Res<SelectedCharacter>1374/// )1375/// {1376/// if let Ok(selected_character) = query.get(selection.entity) {1377/// println!("{}", selected_character.name);1378/// }1379/// }1380/// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);1381/// ```1382///1383/// # See also1384///1385/// - [`get_mut`](Self::get_mut) to get a mutable query item.1386#[inline]1387pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {1388self.as_readonly().get_inner(entity)1389}13901391/// Returns the read-only query items for the given array of [`Entity`].1392///1393/// The returned query items are in the same order as the input.1394/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1395/// The elements of the array do not need to be unique, unlike `get_many_mut`.1396///1397/// # Examples1398///1399/// ```1400/// use bevy_ecs::prelude::*;1401/// use bevy_ecs::query::QueryEntityError;1402///1403/// #[derive(Component, PartialEq, Debug)]1404/// struct A(usize);1405///1406/// let mut world = World::new();1407/// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();1408/// let entities: [Entity; 3] = entity_vec.try_into().unwrap();1409///1410/// world.spawn(A(73));1411///1412/// let mut query_state = world.query::<&A>();1413/// let query = query_state.query(&world);1414///1415/// let component_values = query.get_many(entities).unwrap();1416///1417/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);1418///1419/// let wrong_entity = Entity::from_raw_u32(365).unwrap();1420///1421/// assert_eq!(1422/// match query.get_many([wrong_entity]).unwrap_err() {1423/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1424/// _ => panic!(),1425/// },1426/// wrong_entity1427/// );1428/// ```1429///1430/// # See also1431///1432/// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.1433/// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.1434#[inline]1435pub fn get_many<const N: usize>(1436&self,1437entities: [Entity; N],1438) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {1439// Note that we call a separate `*_inner` method from `get_many_mut`1440// because we don't need to check for duplicates.1441self.as_readonly().get_many_inner(entities)1442}14431444/// Returns the read-only query items for the given [`UniqueEntityArray`].1445///1446/// The returned query items are in the same order as the input.1447/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1448///1449/// # Examples1450///1451/// ```1452/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};1453///1454/// #[derive(Component, PartialEq, Debug)]1455/// struct A(usize);1456///1457/// let mut world = World::new();1458/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();1459/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();1460///1461/// world.spawn(A(73));1462///1463/// let mut query_state = world.query::<&A>();1464/// let query = query_state.query(&world);1465///1466/// let component_values = query.get_many_unique(entity_set).unwrap();1467///1468/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);1469///1470/// let wrong_entity = Entity::from_raw_u32(365).unwrap();1471///1472/// assert_eq!(1473/// match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {1474/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1475/// _ => panic!(),1476/// },1477/// wrong_entity1478/// );1479/// ```1480///1481/// # See also1482///1483/// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.1484/// - [`get_many`](Self::get_many) to handle inputs with duplicates.1485#[inline]1486pub fn get_many_unique<const N: usize>(1487&self,1488entities: UniqueEntityArray<N>,1489) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {1490self.as_readonly().get_many_unique_inner(entities)1491}14921493/// Returns the query item for the given [`Entity`].1494///1495/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1496///1497/// This is always guaranteed to run in `O(1)` time.1498///1499/// # Example1500///1501/// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.1502///1503/// ```1504/// # use bevy_ecs::prelude::*;1505/// #1506/// # #[derive(Resource)]1507/// # struct PoisonedCharacter { character_id: Entity }1508/// # #[derive(Component)]1509/// # struct Health(u32);1510/// #1511/// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {1512/// if let Ok(mut health) = query.get_mut(poisoned.character_id) {1513/// health.0 -= 1;1514/// }1515/// }1516/// # bevy_ecs::system::assert_is_system(poison_system);1517/// ```1518///1519/// # See also1520///1521/// - [`get`](Self::get) to get a read-only query item.1522#[inline]1523pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {1524self.reborrow().get_inner(entity)1525}15261527/// Returns the query item for the given [`Entity`].1528/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1529///1530/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1531///1532/// This is always guaranteed to run in `O(1)` time.1533///1534/// # See also1535///1536/// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].1537#[inline]1538pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {1539// SAFETY: system runs without conflicts with other systems.1540// same-system queries have runtime borrow checks when they conflict1541unsafe {1542let location = self1543.world1544.entities()1545.get(entity)1546.ok_or(EntityDoesNotExistError::new(entity, self.world.entities()))?;1547if !self1548.state1549.matched_archetypes1550.contains(location.archetype_id.index())1551{1552return Err(QueryEntityError::QueryDoesNotMatch(1553entity,1554location.archetype_id,1555));1556}1557let archetype = self1558.world1559.archetypes()1560.get(location.archetype_id)1561.debug_checked_unwrap();1562let mut fetch = D::init_fetch(1563self.world,1564&self.state.fetch_state,1565self.last_run,1566self.this_run,1567);1568let mut filter = F::init_fetch(1569self.world,1570&self.state.filter_state,1571self.last_run,1572self.this_run,1573);15741575let table = self1576.world1577.storages()1578.tables1579.get(location.table_id)1580.debug_checked_unwrap();1581D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);1582F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);15831584if F::filter_fetch(1585&self.state.filter_state,1586&mut filter,1587entity,1588location.table_row,1589) {1590Ok(D::fetch(1591&self.state.fetch_state,1592&mut fetch,1593entity,1594location.table_row,1595))1596} else {1597Err(QueryEntityError::QueryDoesNotMatch(1598entity,1599location.archetype_id,1600))1601}1602}1603}16041605/// Returns the query items for the given array of [`Entity`].1606///1607/// The returned query items are in the same order as the input.1608/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1609///1610/// # Examples1611///1612/// ```1613/// use bevy_ecs::prelude::*;1614/// use bevy_ecs::query::QueryEntityError;1615///1616/// #[derive(Component, PartialEq, Debug)]1617/// struct A(usize);1618///1619/// let mut world = World::new();1620///1621/// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();1622/// let entities: [Entity; 3] = entities.try_into().unwrap();1623///1624/// world.spawn(A(73));1625/// let wrong_entity = Entity::from_raw_u32(57).unwrap();1626/// let invalid_entity = world.spawn_empty().id();1627///1628///1629/// let mut query_state = world.query::<&mut A>();1630/// let mut query = query_state.query_mut(&mut world);1631///1632/// let mut mutable_component_values = query.get_many_mut(entities).unwrap();1633///1634/// for mut a in &mut mutable_component_values {1635/// a.0 += 5;1636/// }1637///1638/// let component_values = query.get_many(entities).unwrap();1639///1640/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);1641///1642/// assert_eq!(1643/// match query1644/// .get_many_mut([wrong_entity])1645/// .unwrap_err()1646/// {1647/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1648/// _ => panic!(),1649/// },1650/// wrong_entity1651/// );1652/// assert_eq!(1653/// match query1654/// .get_many_mut([invalid_entity])1655/// .unwrap_err()1656/// {1657/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,1658/// _ => panic!(),1659/// },1660/// invalid_entity1661/// );1662/// assert_eq!(1663/// query1664/// .get_many_mut([entities[0], entities[0]])1665/// .unwrap_err(),1666/// QueryEntityError::AliasedMutability(entities[0])1667/// );1668/// ```1669/// # See also1670///1671/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1672#[inline]1673pub fn get_many_mut<const N: usize>(1674&mut self,1675entities: [Entity; N],1676) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {1677self.reborrow().get_many_mut_inner(entities)1678}16791680/// Returns the query items for the given [`UniqueEntityArray`].1681///1682/// The returned query items are in the same order as the input.1683/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1684///1685/// # Examples1686///1687/// ```1688/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};1689///1690/// #[derive(Component, PartialEq, Debug)]1691/// struct A(usize);1692///1693/// let mut world = World::new();1694///1695/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();1696/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();1697///1698/// world.spawn(A(73));1699/// let wrong_entity = Entity::from_raw_u32(57).unwrap();1700/// let invalid_entity = world.spawn_empty().id();1701///1702///1703/// let mut query_state = world.query::<&mut A>();1704/// let mut query = query_state.query_mut(&mut world);1705///1706/// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();1707///1708/// for mut a in &mut mutable_component_values {1709/// a.0 += 5;1710/// }1711///1712/// let component_values = query.get_many_unique(entity_set).unwrap();1713///1714/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);1715///1716/// assert_eq!(1717/// match query1718/// .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))1719/// .unwrap_err()1720/// {1721/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1722/// _ => panic!(),1723/// },1724/// wrong_entity1725/// );1726/// assert_eq!(1727/// match query1728/// .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))1729/// .unwrap_err()1730/// {1731/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,1732/// _ => panic!(),1733/// },1734/// invalid_entity1735/// );1736/// ```1737/// # See also1738///1739/// - [`get_many_unique`](Self::get_many) to get read-only query items.1740#[inline]1741pub fn get_many_unique_mut<const N: usize>(1742&mut self,1743entities: UniqueEntityArray<N>,1744) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {1745self.reborrow().get_many_unique_inner(entities)1746}17471748/// Returns the query items for the given array of [`Entity`].1749/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1750///1751/// The returned query items are in the same order as the input.1752/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1753///1754/// # See also1755///1756/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1757/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.1758/// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.1759#[inline]1760pub fn get_many_mut_inner<const N: usize>(1761self,1762entities: [Entity; N],1763) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1764// Verify that all entities are unique1765for i in 0..N {1766for j in 0..i {1767if entities[i] == entities[j] {1768return Err(QueryEntityError::AliasedMutability(entities[i]));1769}1770}1771}1772// SAFETY: All entities are unique, so the results don't alias.1773unsafe { self.get_many_impl(entities) }1774}17751776/// Returns the query items for the given array of [`Entity`].1777/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1778///1779/// The returned query items are in the same order as the input.1780/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1781///1782/// # See also1783///1784/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1785/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.1786/// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.1787#[inline]1788pub fn get_many_inner<const N: usize>(1789self,1790entities: [Entity; N],1791) -> Result<[D::Item<'w, 's>; N], QueryEntityError>1792where1793D: ReadOnlyQueryData,1794{1795// SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.1796unsafe { self.get_many_impl(entities) }1797}17981799/// Returns the query items for the given [`UniqueEntityArray`].1800/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1801///1802/// The returned query items are in the same order as the input.1803/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1804///1805/// # See also1806///1807/// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.1808/// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.1809#[inline]1810pub fn get_many_unique_inner<const N: usize>(1811self,1812entities: UniqueEntityArray<N>,1813) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1814// SAFETY: All entities are unique, so the results don't alias.1815unsafe { self.get_many_impl(entities.into_inner()) }1816}18171818/// Returns the query items for the given array of [`Entity`].1819/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1820///1821/// # Safety1822///1823/// The caller must ensure that the query data returned for the entities does not conflict,1824/// either because they are all unique or because the data is read-only.1825unsafe fn get_many_impl<const N: usize>(1826self,1827entities: [Entity; N],1828) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1829let mut values = [(); N].map(|_| MaybeUninit::uninit());18301831for (value, entity) in core::iter::zip(&mut values, entities) {1832// SAFETY: The caller asserts that the results don't alias1833let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;1834*value = MaybeUninit::new(item);1835}18361837// SAFETY: Each value has been fully initialized.1838Ok(values.map(|x| unsafe { x.assume_init() }))1839}18401841/// Returns the query item for the given [`Entity`].1842///1843/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1844///1845/// This is always guaranteed to run in `O(1)` time.1846///1847/// # Safety1848///1849/// This function makes it possible to violate Rust's aliasing guarantees.1850/// You must make sure this call does not result in multiple mutable references to the same component.1851///1852/// # See also1853///1854/// - [`get_mut`](Self::get_mut) for the safe version.1855#[inline]1856pub unsafe fn get_unchecked(1857&self,1858entity: Entity,1859) -> Result<D::Item<'_, 's>, QueryEntityError> {1860// SAFETY: The caller promises that this will not result in multiple mutable references.1861unsafe { self.reborrow_unsafe() }.get_inner(entity)1862}18631864/// Returns a single read-only query item when there is exactly one entity matching the query.1865///1866/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1867///1868/// # Example1869///1870/// ```1871/// # use bevy_ecs::prelude::*;1872/// # use bevy_ecs::query::QuerySingleError;1873/// # #[derive(Component)]1874/// # struct PlayerScore(i32);1875/// fn player_scoring_system(query: Query<&PlayerScore>) {1876/// match query.single() {1877/// Ok(PlayerScore(score)) => {1878/// println!("Score: {}", score);1879/// }1880/// Err(QuerySingleError::NoEntities(_)) => {1881/// println!("Error: There is no player!");1882/// }1883/// Err(QuerySingleError::MultipleEntities(_)) => {1884/// println!("Error: There is more than one player!");1885/// }1886/// }1887/// }1888/// # bevy_ecs::system::assert_is_system(player_scoring_system);1889/// ```1890///1891/// # See also1892///1893/// - [`single_mut`](Self::single_mut) to get the mutable query item.1894#[inline]1895pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {1896self.as_readonly().single_inner()1897}18981899/// Returns a single query item when there is exactly one entity matching the query.1900///1901/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1902///1903/// # Example1904///1905/// ```1906/// # use bevy_ecs::prelude::*;1907/// #1908/// # #[derive(Component)]1909/// # struct Player;1910/// # #[derive(Component)]1911/// # struct Health(u32);1912/// #1913/// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {1914/// let mut health = query.single_mut().expect("Error: Could not find a single player.");1915/// health.0 += 1;1916/// }1917/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);1918/// ```1919///1920/// # See also1921///1922/// - [`single`](Self::single) to get the read-only query item.1923#[inline]1924pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError> {1925self.reborrow().single_inner()1926}19271928/// Returns a single query item when there is exactly one entity matching the query.1929/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1930///1931/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1932///1933/// # Example1934///1935/// ```1936/// # use bevy_ecs::prelude::*;1937/// #1938/// # #[derive(Component)]1939/// # struct Player;1940/// # #[derive(Component)]1941/// # struct Health(u32);1942/// #1943/// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {1944/// let mut health = query.single_inner().expect("Error: Could not find a single player.");1945/// health.0 += 1;1946/// }1947/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);1948/// ```1949///1950/// # See also1951///1952/// - [`single`](Self::single) to get the read-only query item.1953/// - [`single_mut`](Self::single_mut) to get the mutable query item.1954/// - [`single_inner`](Self::single_inner) for the panicking version.1955#[inline]1956pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError> {1957let mut query = self.into_iter();1958let first = query.next();1959let extra = query.next().is_some();19601961match (first, extra) {1962(Some(r), false) => Ok(r),1963(None, _) => Err(QuerySingleError::NoEntities(DebugName::type_name::<Self>())),1964(Some(_), _) => Err(QuerySingleError::MultipleEntities(DebugName::type_name::<1965Self,1966>())),1967}1968}19691970/// Returns `true` if there are no query items.1971///1972/// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`1973/// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely1974/// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check1975/// each query result for a match.1976///1977/// # Example1978///1979/// Here, the score is increased only if an entity with a `Player` component is present in the world:1980///1981/// ```1982/// # use bevy_ecs::prelude::*;1983/// #1984/// # #[derive(Component)]1985/// # struct Player;1986/// # #[derive(Resource)]1987/// # struct Score(u32);1988/// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {1989/// if !query.is_empty() {1990/// score.0 += 1;1991/// }1992/// }1993/// # bevy_ecs::system::assert_is_system(update_score_system);1994/// ```1995///1996/// [`Added`]: crate::query::Added1997/// [`Changed`]: crate::query::Changed1998/// [`Spawned`]: crate::query::Spawned1999#[inline]2000pub fn is_empty(&self) -> bool {2001self.as_nop().iter().next().is_none()2002}20032004/// Returns `true` if the given [`Entity`] matches the query.2005///2006/// This is always guaranteed to run in `O(1)` time.2007///2008/// # Example2009///2010/// ```2011/// # use bevy_ecs::prelude::*;2012/// #2013/// # #[derive(Component)]2014/// # struct InRange;2015/// #2016/// # #[derive(Resource)]2017/// # struct Target {2018/// # entity: Entity,2019/// # }2020/// #2021/// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {2022/// if in_range_query.contains(target.entity) {2023/// println!("Bam!")2024/// }2025/// }2026/// # bevy_ecs::system::assert_is_system(targeting_system);2027/// ```2028#[inline]2029pub fn contains(&self, entity: Entity) -> bool {2030self.as_nop().get(entity).is_ok()2031}20322033/// Counts the number of entities that match the query.2034///2035/// This is equivalent to `self.iter().count()` but may be more efficient in some cases.2036///2037/// If [`F::IS_ARCHETYPAL`](QueryFilter::IS_ARCHETYPAL) is `true`,2038/// this will do work proportional to the number of matched archetypes or tables, but will not iterate each entity.2039/// If it is `false`, it will have to do work for each entity.2040///2041/// # Example2042///2043/// ```2044/// # use bevy_ecs::prelude::*;2045/// #2046/// # #[derive(Component)]2047/// # struct InRange;2048/// #2049/// fn targeting_system(in_range_query: Query<&InRange>) {2050/// let count = in_range_query.count();2051/// println!("{count} targets in range!");2052/// }2053/// # bevy_ecs::system::assert_is_system(targeting_system);2054/// ```2055pub fn count(&self) -> usize {2056let iter = self.as_nop().into_iter();2057if F::IS_ARCHETYPAL {2058// For archetypal queries, the `size_hint()` is exact,2059// and we can get the count from the archetype and table counts.2060iter.size_hint().02061} else {2062// If we have non-archetypal filters, we have to check each entity.2063iter.count()2064}2065}20662067/// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more2068/// restrictive access to the entities matched by the current query.2069///2070/// A transmute is valid only if `NewD` has a subset of the read, write, and required access2071/// of the current query. A precise description of the access required by each parameter2072/// type is given in the table below, but typical uses are to:2073/// * Remove components, e.g. `Query<(&A, &B)>` to `Query<&A>`.2074/// * Retrieve an existing component with reduced or equal access, e.g. `Query<&mut A>` to `Query<&A>`2075/// or `Query<&T>` to `Query<Ref<T>>`.2076/// * Add parameters with no new access, for example adding an `Entity` parameter.2077///2078/// Note that since filter terms are dropped, non-archetypal filters like2079/// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter2080/// terms see [`Self::transmute_lens_filtered`].2081///2082/// |`QueryData` parameter type|Access required|2083/// |----|----|2084/// |[`Entity`], [`EntityLocation`], [`SpawnDetails`], [`&Archetype`], [`Has<T>`], [`PhantomData<T>`]|No access|2085/// |[`EntityMut`]|Read and write access to all components, but no required access|2086/// |[`EntityRef`]|Read access to all components, but no required access|2087/// |`&T`, [`Ref<T>`]|Read and required access to `T`|2088/// |`&mut T`, [`Mut<T>`]|Read, write and required access to `T`|2089/// |[`Option<T>`], [`AnyOf<(D, ...)>`]|Read and write access to `T`, but no required access|2090/// |Tuples of query data and<br/>`#[derive(QueryData)]` structs|The union of the access of their subqueries|2091/// |[`FilteredEntityRef`], [`FilteredEntityMut`]|Determined by the [`QueryBuilder`] used to construct them. Any query can be transmuted to them, and they will receive the access of the source query. When combined with other `QueryData`, they will receive any access of the source query that does not conflict with the other data|2092///2093/// `transmute_lens` drops filter terms, but [`Self::transmute_lens_filtered`] supports returning a [`QueryLens`] with a new2094/// filter type - the access required by filter parameters are as follows.2095///2096/// |`QueryFilter` parameter type|Access required|2097/// |----|----|2098/// |[`Added<T>`], [`Changed<T>`]|Read and required access to `T`|2099/// |[`With<T>`], [`Without<T>`]|No access|2100/// |[`Or<(T, ...)>`]|Read access of the subqueries, but no required access|2101/// |Tuples of query filters and `#[derive(QueryFilter)]` structs|The union of the access of their subqueries|2102///2103/// [`Added`]: crate::query::Added2104/// [`Added<T>`]: crate::query::Added2105/// [`AnyOf<(D, ...)>`]: crate::query::AnyOf2106/// [`&Archetype`]: crate::archetype::Archetype2107/// [`Changed`]: crate::query::Changed2108/// [`Changed<T>`]: crate::query::Changed2109/// [`EntityMut`]: crate::world::EntityMut2110/// [`EntityLocation`]: crate::entity::EntityLocation2111/// [`EntityRef`]: crate::world::EntityRef2112/// [`FilteredEntityRef`]: crate::world::FilteredEntityRef2113/// [`FilteredEntityMut`]: crate::world::FilteredEntityMut2114/// [`Has<T>`]: crate::query::Has2115/// [`Mut<T>`]: crate::world::Mut2116/// [`Or<(T, ...)>`]: crate::query::Or2117/// [`QueryBuilder`]: crate::query::QueryBuilder2118/// [`Ref<T>`]: crate::world::Ref2119/// [`SpawnDetails`]: crate::query::SpawnDetails2120/// [`Spawned`]: crate::query::Spawned2121/// [`With<T>`]: crate::query::With2122/// [`Without<T>`]: crate::query::Without2123///2124/// ## Panics2125///2126/// This will panic if the access required by `NewD` is not a subset of that required by2127/// the original fetch `D`.2128///2129/// ## Example2130///2131/// ```rust2132/// # use bevy_ecs::prelude::*;2133/// # use bevy_ecs::system::QueryLens;2134/// #2135/// # #[derive(Component)]2136/// # struct A(usize);2137/// #2138/// # #[derive(Component)]2139/// # struct B(usize);2140/// #2141/// # let mut world = World::new();2142/// #2143/// # world.spawn((A(10), B(5)));2144/// #2145/// fn reusable_function(lens: &mut QueryLens<&A>) {2146/// assert_eq!(lens.query().single().unwrap().0, 10);2147/// }2148///2149/// // We can use the function in a system that takes the exact query.2150/// fn system_1(mut query: Query<&A>) {2151/// reusable_function(&mut query.as_query_lens());2152/// }2153///2154/// // We can also use it with a query that does not match exactly2155/// // by transmuting it.2156/// fn system_2(mut query: Query<(&mut A, &B)>) {2157/// let mut lens = query.transmute_lens::<&A>();2158/// reusable_function(&mut lens);2159/// }2160///2161/// # let mut schedule = Schedule::default();2162/// # schedule.add_systems((system_1, system_2));2163/// # schedule.run(&mut world);2164/// ```2165///2166/// ### Examples of valid transmutes2167///2168/// ```rust2169/// # use bevy_ecs::{2170/// # prelude::*,2171/// # archetype::Archetype,2172/// # entity::EntityLocation,2173/// # query::{QueryData, QueryFilter},2174/// # world::{FilteredEntityMut, FilteredEntityRef},2175/// # };2176/// # use std::marker::PhantomData;2177/// #2178/// # fn assert_valid_transmute<OldD: QueryData, NewD: QueryData>() {2179/// # assert_valid_transmute_filtered::<OldD, (), NewD, ()>();2180/// # }2181/// #2182/// # fn assert_valid_transmute_filtered<OldD: QueryData, OldF: QueryFilter, NewD: QueryData, NewF: QueryFilter>() {2183/// # let mut world = World::new();2184/// # // Make sure all components in the new query are initialized2185/// # let state = world.query_filtered::<NewD, NewF>();2186/// # let state = world.query_filtered::<OldD, OldF>();2187/// # state.transmute_filtered::<NewD, NewF>(&world);2188/// # }2189/// #2190/// # #[derive(Component)]2191/// # struct T;2192/// #2193/// # #[derive(Component)]2194/// # struct U;2195/// #2196/// # #[derive(Component)]2197/// # struct V;2198/// #2199/// // `&mut T` and `Mut<T>` access the same data and can be transmuted to each other,2200/// // `&T` and `Ref<T>` access the same data and can be transmuted to each other,2201/// // and mutable versions can be transmuted to read-only versions2202/// assert_valid_transmute::<&mut T, &T>();2203/// assert_valid_transmute::<&mut T, Mut<T>>();2204/// assert_valid_transmute::<Mut<T>, &mut T>();2205/// assert_valid_transmute::<&T, Ref<T>>();2206/// assert_valid_transmute::<Ref<T>, &T>();2207///2208/// // The structure can be rearranged, or subqueries dropped2209/// assert_valid_transmute::<(&T, &U), &T>();2210/// assert_valid_transmute::<((&T, &U), &V), (&T, (&U, &V))>();2211/// assert_valid_transmute::<Option<(&T, &U)>, (Option<&T>, Option<&U>)>();2212///2213/// // Queries with no access can be freely added2214/// assert_valid_transmute::<2215/// &T,2216/// (&T, Entity, EntityLocation, &Archetype, Has<U>, PhantomData<T>),2217/// >();2218///2219/// // Required access can be transmuted to optional,2220/// // and optional access can be transmuted to other optional access2221/// assert_valid_transmute::<&T, Option<&T>>();2222/// assert_valid_transmute::<AnyOf<(&mut T, &mut U)>, Option<&T>>();2223/// // Note that removing subqueries from `AnyOf` will result2224/// // in an `AnyOf` where all subqueries can yield `None`!2225/// assert_valid_transmute::<AnyOf<(&T, &U, &V)>, AnyOf<(&T, &U)>>();2226/// assert_valid_transmute::<EntityMut, Option<&mut T>>();2227///2228/// // Anything can be transmuted to `FilteredEntityRef` or `FilteredEntityMut`2229/// // This will create a `FilteredEntityMut` that only has read access to `T`2230/// assert_valid_transmute::<&T, FilteredEntityMut>();2231/// // This will create a `FilteredEntityMut` that has no access to `T`,2232/// // read access to `U`, and write access to `V`.2233/// assert_valid_transmute::<(&mut T, &mut U, &mut V), (&mut T, &U, FilteredEntityMut)>();2234///2235/// // `Added<T>` and `Changed<T>` filters have the same access as `&T` data2236/// // Remember that they are only evaluated on the transmuted query, not the original query!2237/// assert_valid_transmute_filtered::<Entity, Changed<T>, &T, ()>();2238/// assert_valid_transmute_filtered::<&mut T, (), &T, Added<T>>();2239/// // Nested inside of an `Or` filter, they have the same access as `Option<&T>`.2240/// assert_valid_transmute_filtered::<Option<&T>, (), Entity, Or<(Changed<T>, With<U>)>>();2241/// ```2242#[track_caller]2243pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {2244self.transmute_lens_filtered::<NewD, ()>()2245}22462247/// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive2248/// access to the entities matched by the current query.2249///2250/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2251///2252/// See [`Self::transmute_lens`] for a description of allowed transmutes.2253///2254/// ## Panics2255///2256/// This will panic if `NewD` is not a subset of the original fetch `D`2257///2258/// ## Example2259///2260/// ```rust2261/// # use bevy_ecs::prelude::*;2262/// # use bevy_ecs::system::QueryLens;2263/// #2264/// # #[derive(Component)]2265/// # struct A(usize);2266/// #2267/// # #[derive(Component)]2268/// # struct B(usize);2269/// #2270/// # let mut world = World::new();2271/// #2272/// # world.spawn((A(10), B(5)));2273/// #2274/// fn reusable_function(mut lens: QueryLens<&A>) {2275/// assert_eq!(lens.query().single().unwrap().0, 10);2276/// }2277///2278/// // We can use the function in a system that takes the exact query.2279/// fn system_1(query: Query<&A>) {2280/// reusable_function(query.into_query_lens());2281/// }2282///2283/// // We can also use it with a query that does not match exactly2284/// // by transmuting it.2285/// fn system_2(query: Query<(&mut A, &B)>) {2286/// let mut lens = query.transmute_lens_inner::<&A>();2287/// reusable_function(lens);2288/// }2289///2290/// # let mut schedule = Schedule::default();2291/// # schedule.add_systems((system_1, system_2));2292/// # schedule.run(&mut world);2293/// ```2294///2295/// # See also2296///2297/// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].2298#[track_caller]2299pub fn transmute_lens_inner<NewD: QueryData>(self) -> QueryLens<'w, NewD> {2300self.transmute_lens_filtered_inner::<NewD, ()>()2301}23022303/// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.2304///2305/// See [`Self::transmute_lens`] for a description of allowed transmutes.2306///2307/// Note that the lens will iterate the same tables and archetypes as the original query. This means that2308/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)2309/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),2310/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they2311/// are in the type signature.2312#[track_caller]2313pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(2314&mut self,2315) -> QueryLens<'_, NewD, NewF> {2316self.reborrow().transmute_lens_filtered_inner()2317}23182319/// Equivalent to [`Self::transmute_lens_inner`] but also includes a [`QueryFilter`] type.2320/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2321///2322/// See [`Self::transmute_lens`] for a description of allowed transmutes.2323///2324/// Note that the lens will iterate the same tables and archetypes as the original query. This means that2325/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)2326/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),2327/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they2328/// are in the type signature.2329///2330/// # See also2331///2332/// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].2333#[track_caller]2334pub fn transmute_lens_filtered_inner<NewD: QueryData, NewF: QueryFilter>(2335self,2336) -> QueryLens<'w, NewD, NewF> {2337let state = self.state.transmute_filtered::<NewD, NewF>(self.world);2338QueryLens {2339world: self.world,2340state,2341last_run: self.last_run,2342this_run: self.this_run,2343}2344}23452346/// Gets a [`QueryLens`] with the same accesses as the existing query2347pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {2348self.transmute_lens()2349}23502351/// Gets a [`QueryLens`] with the same accesses as the existing query2352///2353/// # See also2354///2355/// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].2356pub fn into_query_lens(self) -> QueryLens<'w, D> {2357self.transmute_lens_inner()2358}23592360/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.2361///2362/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.2363/// The returned query will only return items with both `A` and `B`. Note that since filters2364/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.2365/// To maintain or change filter terms see `Self::join_filtered`.2366///2367/// ## Example2368///2369/// ```rust2370/// # use bevy_ecs::prelude::*;2371/// # use bevy_ecs::system::QueryLens;2372/// #2373/// # #[derive(Component)]2374/// # struct Transform;2375/// #2376/// # #[derive(Component)]2377/// # struct Player;2378/// #2379/// # #[derive(Component)]2380/// # struct Enemy;2381/// #2382/// # let mut world = World::default();2383/// # world.spawn((Transform, Player));2384/// # world.spawn((Transform, Enemy));2385///2386/// fn system(2387/// mut transforms: Query<&Transform>,2388/// mut players: Query<&Player>,2389/// mut enemies: Query<&Enemy>2390/// ) {2391/// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);2392/// for (transform, player) in &players_transforms.query() {2393/// // do something with a and b2394/// }2395///2396/// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);2397/// for (transform, enemy) in &enemies_transforms.query() {2398/// // do something with a and b2399/// }2400/// }2401///2402/// # let mut schedule = Schedule::default();2403/// # schedule.add_systems(system);2404/// # schedule.run(&mut world);2405/// ```2406/// ## Panics2407///2408/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.2409///2410/// ## Allowed Transmutes2411///2412/// Like `transmute_lens` the query terms can be changed with some restrictions.2413/// See [`Self::transmute_lens`] for more details.2414pub fn join<'a, OtherD: QueryData, NewD: QueryData>(2415&'a mut self,2416other: &'a mut Query<OtherD>,2417) -> QueryLens<'a, NewD> {2418self.join_filtered(other)2419}24202421/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.2422/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2423///2424/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.2425/// The returned query will only return items with both `A` and `B`. Note that since filters2426/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.2427/// To maintain or change filter terms see `Self::join_filtered`.2428///2429/// ## Panics2430///2431/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.2432///2433/// ## Allowed Transmutes2434///2435/// Like `transmute_lens` the query terms can be changed with some restrictions.2436/// See [`Self::transmute_lens`] for more details.2437///2438/// # See also2439///2440/// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].2441pub fn join_inner<OtherD: QueryData, NewD: QueryData>(2442self,2443other: Query<'w, '_, OtherD>,2444) -> QueryLens<'w, NewD> {2445self.join_filtered_inner(other)2446}24472448/// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.2449///2450/// Note that the lens with iterate a subset of the original queries' tables2451/// and archetypes. This means that additional archetypal query terms like2452/// `With` and `Without` will not necessarily be respected and non-archetypal2453/// terms like `Added`, `Changed` and `Spawned` will only be respected if they2454/// are in the type signature.2455pub fn join_filtered<2456'a,2457OtherD: QueryData,2458OtherF: QueryFilter,2459NewD: QueryData,2460NewF: QueryFilter,2461>(2462&'a mut self,2463other: &'a mut Query<OtherD, OtherF>,2464) -> QueryLens<'a, NewD, NewF> {2465self.reborrow().join_filtered_inner(other.reborrow())2466}24672468/// Equivalent to [`Self::join_inner`] but also includes a [`QueryFilter`] type.2469/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2470///2471/// Note that the lens with iterate a subset of the original queries' tables2472/// and archetypes. This means that additional archetypal query terms like2473/// `With` and `Without` will not necessarily be respected and non-archetypal2474/// terms like `Added`, `Changed` and `Spawned` will only be respected if they2475/// are in the type signature.2476///2477/// # See also2478///2479/// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].2480pub fn join_filtered_inner<2481OtherD: QueryData,2482OtherF: QueryFilter,2483NewD: QueryData,2484NewF: QueryFilter,2485>(2486self,2487other: Query<'w, '_, OtherD, OtherF>,2488) -> QueryLens<'w, NewD, NewF> {2489let state = self2490.state2491.join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);2492QueryLens {2493world: self.world,2494state,2495last_run: self.last_run,2496this_run: self.this_run,2497}2498}2499}25002501impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {2502type Item = D::Item<'w, 's>;2503type IntoIter = QueryIter<'w, 's, D, F>;25042505fn into_iter(self) -> Self::IntoIter {2506// SAFETY:2507// - `self.world` has permission to access the required components.2508// - We consume the query, so mutable queries cannot alias.2509// Read-only queries are `Copy`, but may alias themselves.2510unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }2511}2512}25132514impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {2515type Item = ROQueryItem<'w, 's, D>;2516type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;25172518fn into_iter(self) -> Self::IntoIter {2519self.iter()2520}2521}25222523impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {2524type Item = D::Item<'w, 's>;2525type IntoIter = QueryIter<'w, 's, D, F>;25262527fn into_iter(self) -> Self::IntoIter {2528self.iter_mut()2529}2530}25312532impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter> Query<'w, 's, D, F> {2533/// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.2534///2535/// This can only return immutable data (mutable data will be cast to an immutable form).2536/// See [`Self::iter_mut`] for queries that contain at least one mutable component.2537///2538/// # Example2539///2540/// Here, the `report_names_system` iterates over the `Player` component of every entity2541/// that contains it:2542///2543/// ```2544/// # use bevy_ecs::prelude::*;2545/// #2546/// # #[derive(Component)]2547/// # struct Player { name: String }2548/// #2549/// fn report_names_system(query: Query<&Player>) {2550/// for player in &query {2551/// println!("Say hello to {}!", player.name);2552/// }2553/// }2554/// # bevy_ecs::system::assert_is_system(report_names_system);2555/// ```2556#[inline]2557pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {2558(*self).into_iter()2559}2560}25612562/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].2563///2564/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]2565pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {2566world: UnsafeWorldCell<'w>,2567state: QueryState<Q, F>,2568last_run: Tick,2569this_run: Tick,2570}25712572impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {2573/// Create a [`Query`] from the underlying [`QueryState`].2574pub fn query(&mut self) -> Query<'_, '_, Q, F> {2575Query {2576world: self.world,2577state: &self.state,2578last_run: self.last_run,2579this_run: self.this_run,2580}2581}2582}25832584impl<'w, Q: ReadOnlyQueryData, F: QueryFilter> QueryLens<'w, Q, F> {2585/// Create a [`Query`] from the underlying [`QueryState`].2586/// This returns results with the actual "inner" world lifetime,2587/// so it may only be used with read-only queries to prevent mutable aliasing.2588pub fn query_inner(&self) -> Query<'w, '_, Q, F> {2589Query {2590world: self.world,2591state: &self.state,2592last_run: self.last_run,2593this_run: self.this_run,2594}2595}2596}25972598impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>2599for Query<'s, 's, Q, F>2600{2601fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {2602value.query()2603}2604}26052606impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>2607for QueryLens<'q, Q, F>2608{2609fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {2610value.transmute_lens_filtered()2611}2612}26132614/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].2615///2616/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.2617/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).2618///2619/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.2620///2621/// See [`Query`] for more details.2622///2623/// [System parameter]: crate::system::SystemParam2624///2625/// # Example2626/// ```2627/// # use bevy_ecs::prelude::*;2628/// #[derive(Component)]2629/// struct Boss {2630/// health: f322631/// };2632///2633/// fn hurt_boss(mut boss: Single<&mut Boss>) {2634/// boss.health -= 4.0;2635/// }2636/// ```2637/// Note that because [`Single`] implements [`Deref`] and [`DerefMut`], methods and fields like `health` can be accessed directly.2638/// You can also access the underlying data manually, by calling `.deref`/`.deref_mut`, or by using the `*` operator.2639pub struct Single<'w, 's, D: QueryData, F: QueryFilter = ()> {2640pub(crate) item: D::Item<'w, 's>,2641pub(crate) _filter: PhantomData<F>,2642}26432644impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {2645type Target = D::Item<'w, 's>;26462647fn deref(&self) -> &Self::Target {2648&self.item2649}2650}26512652impl<'w, 's, D: QueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {2653fn deref_mut(&mut self) -> &mut Self::Target {2654&mut self.item2655}2656}26572658impl<'w, 's, D: QueryData, F: QueryFilter> Single<'w, 's, D, F> {2659/// Returns the inner item with ownership.2660pub fn into_inner(self) -> D::Item<'w, 's> {2661self.item2662}2663}26642665/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.2666///2667/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.2668/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).2669///2670/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.2671/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added),2672/// [`Changed`](crate::query::Changed) of [`Spawned`](crate::query::Spawned) which must individually check each query2673/// result for a match.2674///2675/// See [`Query`] for more details.2676///2677/// [System parameter]: crate::system::SystemParam2678pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);26792680impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {2681type Target = Query<'w, 's, D, F>;26822683fn deref(&self) -> &Self::Target {2684&self.02685}2686}26872688impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {2689fn deref_mut(&mut self) -> &mut Self::Target {2690&mut self.02691}2692}26932694impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {2695/// Returns the inner item with ownership.2696pub fn into_inner(self) -> Query<'w, 's, D, F> {2697self.02698}2699}27002701impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {2702type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;27032704type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;27052706fn into_iter(self) -> Self::IntoIter {2707self.0.into_iter()2708}2709}27102711impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {2712type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;27132714type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;27152716fn into_iter(self) -> Self::IntoIter {2717self.deref().into_iter()2718}2719}27202721impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a mut Populated<'w, 's, D, F> {2722type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;27232724type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;27252726fn into_iter(self) -> Self::IntoIter {2727self.deref_mut().into_iter()2728}2729}27302731#[cfg(test)]2732mod tests {2733use crate::{prelude::*, query::QueryEntityError};2734use alloc::vec::Vec;27352736#[test]2737fn get_many_uniqueness() {2738let mut world = World::new();27392740let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();27412742let mut query_state = world.query::<Entity>();27432744// It's best to test get_many_mut_inner directly, as it is shared2745// We don't care about aliased mutability for the read-only equivalent27462747// SAFETY: Query does not access world data.2748assert!(query_state2749.query_mut(&mut world)2750.get_many_mut_inner::<10>(entities.clone().try_into().unwrap())2751.is_ok());27522753assert_eq!(2754query_state2755.query_mut(&mut world)2756.get_many_mut_inner([entities[0], entities[0]])2757.unwrap_err(),2758QueryEntityError::AliasedMutability(entities[0])2759);27602761assert_eq!(2762query_state2763.query_mut(&mut world)2764.get_many_mut_inner([entities[0], entities[1], entities[0]])2765.unwrap_err(),2766QueryEntityError::AliasedMutability(entities[0])2767);27682769assert_eq!(2770query_state2771.query_mut(&mut world)2772.get_many_mut_inner([entities[9], entities[9]])2773.unwrap_err(),2774QueryEntityError::AliasedMutability(entities[9])2775);2776}2777}277827792780