Thanks to visit codestin.com
Credit goes to docs.rs

bevy_ecs/system/
query.rs

1use bevy_utils::prelude::DebugName;
2
3use crate::{
4    batching::BatchingStrategy,
5    component::Tick,
6    entity::{Entity, EntityDoesNotExistError, EntityEquivalent, EntitySet, UniqueEntityArray},
7    query::{
8        DebugCheckedUnwrap, NopWorldQuery, QueryCombinationIter, QueryData, QueryEntityError,
9        QueryFilter, QueryIter, QueryManyIter, QueryManyUniqueIter, QueryParIter, QueryParManyIter,
10        QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,
11    },
12    world::unsafe_world_cell::UnsafeWorldCell,
13};
14use core::{
15    marker::PhantomData,
16    mem::MaybeUninit,
17    ops::{Deref, DerefMut},
18};
19
20/// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`].
21///
22/// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`].
23/// Its iterators and getter methods return *query items*, which are types containing data related to an entity.
24///
25/// `Query` is a generic data structure that accepts two type parameters:
26///
27/// - **`D` (query data)**:
28///   The type of data fetched by the query, which will be returned as the query item.
29///   Only entities that match the requested data will generate an item.
30///   Must implement the [`QueryData`] trait.
31/// - **`F` (query filter)**:
32///   An optional set of conditions that determine whether query items should be kept or discarded.
33///   This defaults to [`unit`], which means no additional filters will be applied.
34///   Must implement the [`QueryFilter`] trait.
35///
36/// [system parameter]: crate::system::SystemParam
37/// [`Component`]: crate::component::Component
38/// [`World`]: crate::world::World
39/// [entity identifiers]: Entity
40/// [components]: crate::component::Component
41///
42/// # Similar parameters
43///
44/// `Query` has few sibling [`SystemParam`]s, which perform additional validation:
45///
46/// - [`Single`] - Exactly one matching query item.
47/// - [`Option<Single>`] - Zero or one matching query item.
48/// - [`Populated`] - At least one matching query item.
49///
50/// These parameters will prevent systems from running if their requirements are not met.
51///
52/// [`SystemParam`]: crate::system::system_param::SystemParam
53/// [`Option<Single>`]: Single
54///
55/// # System parameter declaration
56///
57/// A query should always be declared as a system parameter.
58/// This section shows the most common idioms involving the declaration of `Query`.
59///
60/// ## Component access
61///
62/// You can fetch an entity's component by specifying a reference to that component in the query's data parameter:
63///
64/// ```
65/// # use bevy_ecs::prelude::*;
66/// #
67/// # #[derive(Component)]
68/// # struct ComponentA;
69/// #
70/// // A component can be accessed by a shared reference...
71/// fn immutable_query(query: Query<&ComponentA>) {
72///     // ...
73/// }
74///
75/// // ...or by a mutable reference.
76/// fn mutable_query(query: Query<&mut ComponentA>) {
77///     // ...
78/// }
79/// #
80/// # bevy_ecs::system::assert_is_system(immutable_query);
81/// # bevy_ecs::system::assert_is_system(mutable_query);
82/// ```
83///
84/// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile:
85///
86/// ```compile_fail,E0277
87/// # use bevy_ecs::prelude::*;
88/// #
89/// # #[derive(Component)]
90/// # struct ComponentA;
91/// #
92/// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile.
93/// fn invalid_query(query: Query<ComponentA>) {
94///     // ...
95/// }
96/// ```
97///
98/// ## Query filtering
99///
100/// Setting the query filter type parameter will ensure that each query item satisfies the given condition:
101///
102/// ```
103/// # use bevy_ecs::prelude::*;
104/// #
105/// # #[derive(Component)]
106/// # struct ComponentA;
107/// #
108/// # #[derive(Component)]
109/// # struct ComponentB;
110/// #
111/// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`.
112/// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) {
113///     // ...
114/// }
115/// #
116/// # bevy_ecs::system::assert_is_system(filtered_query);
117/// ```
118///
119/// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With`
120/// does not require components to be behind a reference.
121///
122/// ## `QueryData` or `QueryFilter` tuples
123///
124/// Using [`tuple`]s, each `Query` type parameter can contain multiple elements.
125///
126/// In the following example two components are accessed simultaneously, and the query items are
127/// filtered on two conditions:
128///
129/// ```
130/// # use bevy_ecs::prelude::*;
131/// #
132/// # #[derive(Component)]
133/// # struct ComponentA;
134/// #
135/// # #[derive(Component)]
136/// # struct ComponentB;
137/// #
138/// # #[derive(Component)]
139/// # struct ComponentC;
140/// #
141/// # #[derive(Component)]
142/// # struct ComponentD;
143/// #
144/// fn complex_query(
145///     query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
146/// ) {
147///     // ...
148/// }
149/// #
150/// # bevy_ecs::system::assert_is_system(complex_query);
151/// ```
152///
153/// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to
154/// get around this limit:
155///
156/// ```
157/// # use bevy_ecs::prelude::*;
158/// #
159/// # #[derive(Component)]
160/// # struct ComponentA;
161/// #
162/// # #[derive(Component)]
163/// # struct ComponentB;
164/// #
165/// # #[derive(Component)]
166/// # struct ComponentC;
167/// #
168/// # #[derive(Component)]
169/// # struct ComponentD;
170/// #
171/// fn nested_query(
172///     query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))>
173/// ) {
174///     // ...
175/// }
176/// #
177/// # bevy_ecs::system::assert_is_system(nested_query);
178/// ```
179///
180/// ## Entity identifier access
181///
182/// You can access [`Entity`], the entity identifier, by including it in the query data parameter:
183///
184/// ```
185/// # use bevy_ecs::prelude::*;
186/// #
187/// # #[derive(Component)]
188/// # struct ComponentA;
189/// #
190/// fn entity_id_query(query: Query<(Entity, &ComponentA)>) {
191///     // ...
192/// }
193/// #
194/// # bevy_ecs::system::assert_is_system(entity_id_query);
195/// ```
196///
197/// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference.
198///
199/// ## Optional component access
200///
201/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a
202/// query item will still be generated even if the queried entity does not contain `ComponentB`.
203/// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`.
204///
205/// ```
206/// # use bevy_ecs::prelude::*;
207/// #
208/// # #[derive(Component)]
209/// # struct ComponentA;
210/// #
211/// # #[derive(Component)]
212/// # struct ComponentB;
213/// #
214/// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will
215/// // be fetched as well.
216/// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) {
217///     // ...
218/// }
219/// #
220/// # bevy_ecs::system::assert_is_system(optional_component_query);
221/// ```
222///
223/// Optional components can hurt performance in some cases, so please read the [performance]
224/// section to learn more about them. Additionally, if you need to declare several optional
225/// components, you may be interested in using [`AnyOf`].
226///
227/// [performance]: #performance
228/// [`AnyOf`]: crate::query::AnyOf
229///
230/// ## Disjoint queries
231///
232/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic
233/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries
234/// disjoint.
235///
236/// In the following example, the two queries can mutably access the same `&mut Health` component
237/// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic,
238/// however, instead of breaking Rust's mutability rules:
239///
240/// ```should_panic
241/// # use bevy_ecs::prelude::*;
242/// #
243/// # #[derive(Component)]
244/// # struct Health;
245/// #
246/// # #[derive(Component)]
247/// # struct Player;
248/// #
249/// # #[derive(Component)]
250/// # struct Enemy;
251/// #
252/// fn randomize_health(
253///     player_query: Query<&mut Health, With<Player>>,
254///     enemy_query: Query<&mut Health, With<Enemy>>,
255/// ) {
256///     // ...
257/// }
258/// #
259/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
260/// ```
261///
262/// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity
263/// that has both the `Player` and `Enemy` components will be excluded from _both_ queries:
264///
265/// ```
266/// # use bevy_ecs::prelude::*;
267/// #
268/// # #[derive(Component)]
269/// # struct Health;
270/// #
271/// # #[derive(Component)]
272/// # struct Player;
273/// #
274/// # #[derive(Component)]
275/// # struct Enemy;
276/// #
277/// fn randomize_health(
278///     player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
279///     enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
280/// ) {
281///     // ...
282/// }
283/// #
284/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
285/// ```
286///
287/// An alternative solution to this problem would be to wrap the conflicting queries in
288/// [`ParamSet`].
289///
290/// [`Without`]: crate::query::Without
291/// [`ParamSet`]: crate::system::ParamSet
292///
293/// ## Whole Entity Access
294///
295/// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity.
296/// This is useful when dynamically fetching components instead of baking them into the query type.
297///
298/// ```
299/// # use bevy_ecs::prelude::*;
300/// #
301/// # #[derive(Component)]
302/// # struct ComponentA;
303/// #
304/// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) {
305///     // ...
306/// }
307/// #
308/// # bevy_ecs::system::assert_is_system(all_components_query);
309/// ```
310///
311/// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any*
312/// mutable component access.
313///
314/// ```should_panic
315/// # use bevy_ecs::prelude::*;
316/// #
317/// # #[derive(Component)]
318/// # struct ComponentA;
319/// #
320/// // `EntityRef` provides read access to *all* components on an entity. When combined with
321/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read
322/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing
323/// // rules.
324/// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) {
325///     // ...
326/// }
327/// #
328/// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query);
329/// ```
330///
331/// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] /
332/// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and
333/// parallelization of the system, but it enables systems to gain mutable access to other
334/// components:
335///
336/// ```
337/// # use bevy_ecs::prelude::*;
338/// #
339/// # #[derive(Component)]
340/// # struct ComponentA;
341/// #
342/// # #[derive(Component)]
343/// # struct ComponentB;
344/// #
345/// // The first query only reads entities that have `ComponentA`, while the second query only
346/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same
347/// // entity, this system does not conflict.
348/// fn disjoint_query(
349///     query_a: Query<EntityRef, With<ComponentA>>,
350///     query_b: Query<&mut ComponentB, Without<ComponentA>>,
351/// ) {
352///     // ...
353/// }
354/// #
355/// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query);
356/// ```
357///
358/// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never
359/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the
360/// queries on completely separate entities.
361///
362/// [`EntityRef`]: crate::world::EntityRef
363/// [`With`]: crate::query::With
364///
365/// # Accessing query items
366///
367/// The following table summarizes the behavior of safe methods that can be used to get query
368/// items:
369///
370/// |Query methods|Effect|
371/// |-|-|
372/// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.|
373/// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.|
374/// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.|
375/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.|
376/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.|
377/// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.|
378/// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.|
379///
380/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).
381/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.
382/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
383///
384/// [`iter`]: Self::iter
385/// [`iter_mut`]: Self::iter_mut
386/// [`for_each`]: #iteratorfor_each
387/// [`par_iter`]: Self::par_iter
388/// [`par_iter_mut`]: Self::par_iter_mut
389/// [`iter_many`]: Self::iter_many
390/// [`iter_many_unique`]: Self::iter_many_unique
391/// [`iter_many_mut`]: Self::iter_many_mut
392/// [`iter_combinations`]: Self::iter_combinations
393/// [`iter_combinations_mut`]: Self::iter_combinations_mut
394/// [`single_mut`]: Self::single_mut
395/// [`get`]: Self::get
396/// [`get_mut`]: Self::get_mut
397/// [`get_many`]: Self::get_many
398/// [`get_many_unique`]: Self::get_many_unique
399/// [`get_many_mut`]: Self::get_many_mut
400///
401/// # Performance
402///
403/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches
404/// data from the world and generates items, which can have a significant computational cost.
405///
406/// Two systems cannot be executed in parallel if both access the same component type where at
407/// least one of the accesses is mutable. Because of this, it is recommended for queries to only
408/// fetch mutable access to components when necessary, since immutable access can be parallelized.
409///
410/// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of
411/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be
412/// parallelized by the scheduler.
413///
414/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and
415/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is
416/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the
417/// query would iterate over all entities in the world.
418///
419/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers
420/// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite:
421/// it offers fast component insertion and removal speeds, but slower iteration speeds.
422///
423/// The following table compares the computational complexity of the various methods and
424/// operations, where:
425///
426/// - **n** is the number of entities that match the query.
427/// - **r** is the number of elements in a combination.
428/// - **k** is the number of involved entities in the operation.
429/// - **a** is the number of archetypes in the world.
430/// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is
431///   read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r*
432///   elements that can be taken from a set of *n* elements.
433///
434/// |Query operation|Computational complexity|
435/// |-|-|
436/// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)|
437/// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)|
438/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)|
439/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)|
440/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)|
441/// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)|
442/// |[`get_many`]|O(k)|
443/// |[`get_many_mut`]|O(k<sup>2</sup>)|
444/// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)|
445/// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)|
446///
447/// [component storage types]: crate::component::StorageType
448/// [`Table`]: crate::storage::Table
449/// [`SparseSet`]: crate::storage::SparseSet
450/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient
451/// [`Or`]: crate::query::Or
452/// [`Added`]: crate::query::Added
453/// [`Changed`]: crate::query::Changed
454/// [`Spawned`]: crate::query::Spawned
455///
456/// # `Iterator::for_each`
457///
458/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with
459/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It
460/// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance.
461/// *Always* profile or benchmark before and after the change!
462///
463/// ```rust
464/// # use bevy_ecs::prelude::*;
465/// #
466/// # #[derive(Component)]
467/// # struct ComponentA;
468/// #
469/// fn system(query: Query<&ComponentA>) {
470///     // This may result in better performance...
471///     query.iter().for_each(|component| {
472///         // ...
473///     });
474///
475///     // ...than this. Always benchmark to validate the difference!
476///     for component in query.iter() {
477///         // ...
478///     }
479/// }
480/// #
481/// # bevy_ecs::system::assert_is_system(system);
482/// ```
483///
484/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization
485pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {
486    // SAFETY: Must have access to the components registered in `state`.
487    world: UnsafeWorldCell<'world>,
488    state: &'state QueryState<D, F>,
489    last_run: Tick,
490    this_run: Tick,
491}
492
493impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {
494    fn clone(&self) -> Self {
495        *self
496    }
497}
498
499impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}
500
501impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {
502    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
503        f.debug_struct("Query")
504            .field("matched_entities", &self.iter().count())
505            .field("state", &self.state)
506            .field("last_run", &self.last_run)
507            .field("this_run", &self.this_run)
508            .field("world", &self.world)
509            .finish()
510    }
511}
512
513impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
514    /// Creates a new query.
515    ///
516    /// # Safety
517    ///
518    /// * This will create a query that could violate memory safety rules. Make sure that this is only
519    ///   called in ways that ensure the queries have unique mutable access.
520    /// * `world` must be the world used to create `state`.
521    #[inline]
522    pub(crate) unsafe fn new(
523        world: UnsafeWorldCell<'w>,
524        state: &'s QueryState<D, F>,
525        last_run: Tick,
526        this_run: Tick,
527    ) -> Self {
528        Self {
529            world,
530            state,
531            last_run,
532            this_run,
533        }
534    }
535
536    /// Returns another `Query` from this that fetches the read-only version of the query items.
537    ///
538    /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
539    /// This can be useful when working around the borrow checker,
540    /// or reusing functionality between systems via functions that accept query types.
541    ///
542    /// # See also
543    ///
544    /// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.
545    pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {
546        // SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access,
547        // and the original query is held with a shared borrow, so it cannot perform mutable access either.
548        unsafe { self.reborrow_unsafe() }.into_readonly()
549    }
550
551    /// Returns another `Query` from this does not return any data, which can be faster.
552    fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {
553        let new_state = self.state.as_nop();
554        // SAFETY:
555        // - The reborrowed query is converted to read-only, so it cannot perform mutable access,
556        //   and the original query is held with a shared borrow, so it cannot perform mutable access either.
557        //   Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query,
558        //   it has the original `QueryState::component_access` and could be `transmute`d to a read-only query.
559        // - The world matches because it was the same one used to construct self.
560        unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
561    }
562
563    /// Returns another `Query` from this that fetches the read-only version of the query items.
564    ///
565    /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
566    /// This can be useful when working around the borrow checker,
567    /// or reusing functionality between systems via functions that accept query types.
568    ///
569    /// # See also
570    ///
571    /// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.
572    pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {
573        let new_state = self.state.as_readonly();
574        // SAFETY:
575        // - This is memory safe because it turns the query immutable.
576        // - The world matches because it was the same one used to construct self.
577        unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
578    }
579
580    /// Returns a new `Query` reborrowing the access from this one. The current query will be unusable
581    /// while the new one exists.
582    ///
583    /// # Example
584    ///
585    /// For example this allows to call other methods or other systems that require an owned `Query` without
586    /// completely giving up ownership of it.
587    ///
588    /// ```
589    /// # use bevy_ecs::prelude::*;
590    /// #
591    /// # #[derive(Component)]
592    /// # struct ComponentA;
593    ///
594    /// fn helper_system(query: Query<&ComponentA>) { /* ... */}
595    ///
596    /// fn system(mut query: Query<&ComponentA>) {
597    ///     helper_system(query.reborrow());
598    ///     // Can still use query here:
599    ///     for component in &query {
600    ///         // ...
601    ///     }
602    /// }
603    /// ```
604    pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {
605        // SAFETY: this query is exclusively borrowed while the new one exists, so
606        // no overlapping access can occur.
607        unsafe { self.reborrow_unsafe() }
608    }
609
610    /// Returns a new `Query` reborrowing the access from this one.
611    /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
612    ///
613    /// # Safety
614    ///
615    /// This function makes it possible to violate Rust's aliasing guarantees.
616    /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
617    ///
618    /// # See also
619    ///
620    /// - [`reborrow`](Self::reborrow) for the safe versions.
621    pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> {
622        // SAFETY:
623        // - This is memory safe because the caller ensures that there are no conflicting references.
624        // - The world matches because it was the same one used to construct self.
625        unsafe { self.copy_unsafe() }
626    }
627
628    /// Returns a new `Query` copying the access from this one.
629    /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
630    ///
631    /// # Safety
632    ///
633    /// This function makes it possible to violate Rust's aliasing guarantees.
634    /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
635    ///
636    /// # See also
637    ///
638    /// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.
639    unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> {
640        // SAFETY:
641        // - This is memory safe because the caller ensures that there are no conflicting references.
642        // - The world matches because it was the same one used to construct self.
643        unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }
644    }
645
646    /// Returns an [`Iterator`] over the read-only query items.
647    ///
648    /// This iterator is always guaranteed to return results from each matching entity once and only once.
649    /// Iteration order is not guaranteed.
650    ///
651    /// # Example
652    ///
653    /// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:
654    ///
655    /// ```
656    /// # use bevy_ecs::prelude::*;
657    /// #
658    /// # #[derive(Component)]
659    /// # struct Player { name: String }
660    /// #
661    /// fn report_names_system(query: Query<&Player>) {
662    ///     for player in &query {
663    ///         println!("Say hello to {}!", player.name);
664    ///     }
665    /// }
666    /// # bevy_ecs::system::assert_is_system(report_names_system);
667    /// ```
668    ///
669    /// # See also
670    ///
671    /// [`iter_mut`](Self::iter_mut) for mutable query items.
672    #[inline]
673    pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {
674        self.as_readonly().into_iter()
675    }
676
677    /// Returns an [`Iterator`] over the query items.
678    ///
679    /// This iterator is always guaranteed to return results from each matching entity once and only once.
680    /// Iteration order is not guaranteed.
681    ///
682    /// # Example
683    ///
684    /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
685    ///
686    /// ```
687    /// # use bevy_ecs::prelude::*;
688    /// #
689    /// # #[derive(Component)]
690    /// # struct Velocity { x: f32, y: f32, z: f32 }
691    /// fn gravity_system(mut query: Query<&mut Velocity>) {
692    ///     const DELTA: f32 = 1.0 / 60.0;
693    ///     for mut velocity in &mut query {
694    ///         velocity.y -= 9.8 * DELTA;
695    ///     }
696    /// }
697    /// # bevy_ecs::system::assert_is_system(gravity_system);
698    /// ```
699    ///
700    /// # See also
701    ///
702    /// [`iter`](Self::iter) for read-only query items.
703    #[inline]
704    pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {
705        self.reborrow().into_iter()
706    }
707
708    /// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.
709    ///
710    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
711    /// Iteration order is not guaranteed.
712    ///
713    /// # Example
714    ///
715    /// ```
716    /// # use bevy_ecs::prelude::*;
717    /// # #[derive(Component)]
718    /// # struct ComponentA;
719    /// #
720    /// fn some_system(query: Query<&ComponentA>) {
721    ///     for [a1, a2] in query.iter_combinations() {
722    ///         // ...
723    ///     }
724    /// }
725    /// ```
726    ///
727    /// # See also
728    ///
729    /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
730    /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
731    #[inline]
732    pub fn iter_combinations<const K: usize>(
733        &self,
734    ) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {
735        self.as_readonly().iter_combinations_inner()
736    }
737
738    /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
739    ///
740    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
741    /// Iteration order is not guaranteed.
742    ///
743    /// # Example
744    ///
745    /// ```
746    /// # use bevy_ecs::prelude::*;
747    /// # #[derive(Component)]
748    /// # struct ComponentA;
749    /// fn some_system(mut query: Query<&mut ComponentA>) {
750    ///     let mut combinations = query.iter_combinations_mut();
751    ///     while let Some([mut a1, mut a2]) = combinations.fetch_next() {
752    ///         // mutably access components data
753    ///     }
754    /// }
755    /// ```
756    ///
757    /// # See also
758    ///
759    /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
760    /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
761    #[inline]
762    pub fn iter_combinations_mut<const K: usize>(
763        &mut self,
764    ) -> QueryCombinationIter<'_, 's, D, F, K> {
765        self.reborrow().iter_combinations_inner()
766    }
767
768    /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
769    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
770    ///
771    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
772    /// Iteration order is not guaranteed.
773    ///
774    /// # Example
775    ///
776    /// ```
777    /// # use bevy_ecs::prelude::*;
778    /// # #[derive(Component)]
779    /// # struct ComponentA;
780    /// fn some_system(query: Query<&mut ComponentA>) {
781    ///     let mut combinations = query.iter_combinations_inner();
782    ///     while let Some([mut a1, mut a2]) = combinations.fetch_next() {
783    ///         // mutably access components data
784    ///     }
785    /// }
786    /// ```
787    ///
788    /// # See also
789    ///
790    /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
791    /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
792    #[inline]
793    pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K> {
794        // SAFETY: `self.world` has permission to access the required components.
795        unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }
796    }
797
798    /// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
799    ///
800    /// Items are returned in the order of the list of entities, and may not be unique if the input
801    /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
802    ///
803    /// # Example
804    ///
805    /// ```
806    /// # use bevy_ecs::prelude::*;
807    /// # #[derive(Component)]
808    /// # struct Counter {
809    /// #     value: i32
810    /// # }
811    /// #
812    /// // A component containing an entity list.
813    /// #[derive(Component)]
814    /// struct Friends {
815    ///     list: Vec<Entity>,
816    /// }
817    ///
818    /// fn system(
819    ///     friends_query: Query<&Friends>,
820    ///     counter_query: Query<&Counter>,
821    /// ) {
822    ///     for friends in &friends_query {
823    ///         for counter in counter_query.iter_many(&friends.list) {
824    ///             println!("Friend's counter: {}", counter.value);
825    ///         }
826    ///     }
827    /// }
828    /// # bevy_ecs::system::assert_is_system(system);
829    /// ```
830    ///
831    /// # See also
832    ///
833    /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
834    /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
835    #[inline]
836    pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
837        &self,
838        entities: EntityList,
839    ) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
840        self.as_readonly().iter_many_inner(entities)
841    }
842
843    /// Returns an iterator over the query items generated from an [`Entity`] list.
844    ///
845    /// Items are returned in the order of the list of entities, and may not be unique if the input
846    /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
847    ///
848    /// # Examples
849    ///
850    /// ```
851    /// # use bevy_ecs::prelude::*;
852    /// #[derive(Component)]
853    /// struct Counter {
854    ///     value: i32
855    /// }
856    ///
857    /// #[derive(Component)]
858    /// struct Friends {
859    ///     list: Vec<Entity>,
860    /// }
861    ///
862    /// fn system(
863    ///     friends_query: Query<&Friends>,
864    ///     mut counter_query: Query<&mut Counter>,
865    /// ) {
866    ///     for friends in &friends_query {
867    ///         let mut iter = counter_query.iter_many_mut(&friends.list);
868    ///         while let Some(mut counter) = iter.fetch_next() {
869    ///             println!("Friend's counter: {}", counter.value);
870    ///             counter.value += 1;
871    ///         }
872    ///     }
873    /// }
874    /// # bevy_ecs::system::assert_is_system(system);
875    /// ```
876    /// # See also
877    ///
878    /// - [`iter_many`](Self::iter_many) to get read-only query items.
879    /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
880    #[inline]
881    pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(
882        &mut self,
883        entities: EntityList,
884    ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
885        self.reborrow().iter_many_inner(entities)
886    }
887
888    /// Returns an iterator over the query items generated from an [`Entity`] list.
889    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
890    ///
891    /// Items are returned in the order of the list of entities, and may not be unique if the input
892    /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
893    ///
894    /// # See also
895    ///
896    /// - [`iter_many`](Self::iter_many) to get read-only query items.
897    /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
898    #[inline]
899    pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(
900        self,
901        entities: EntityList,
902    ) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {
903        // SAFETY: `self.world` has permission to access the required components.
904        unsafe {
905            QueryManyIter::new(
906                self.world,
907                self.state,
908                entities,
909                self.last_run,
910                self.this_run,
911            )
912        }
913    }
914
915    /// Returns an [`Iterator`] over the unique read-only query items generated from an [`EntitySet`].
916    ///
917    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
918    ///
919    /// # Example
920    ///
921    /// ```
922    /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
923    /// # use core::slice;
924    /// # #[derive(Component)]
925    /// # struct Counter {
926    /// #     value: i32
927    /// # }
928    /// #
929    /// // `Friends` ensures that it only lists unique entities.
930    /// #[derive(Component)]
931    /// struct Friends {
932    ///     unique_list: Vec<Entity>,
933    /// }
934    ///
935    /// impl<'a> IntoIterator for &'a Friends {
936    ///
937    ///     type Item = &'a Entity;
938    ///     type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
939    ///
940    ///     fn into_iter(self) -> Self::IntoIter {
941    ///         // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
942    ///        unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }
943    ///     }
944    /// }
945    ///
946    /// fn system(
947    ///     friends_query: Query<&Friends>,
948    ///     counter_query: Query<&Counter>,
949    /// ) {
950    ///     for friends in &friends_query {
951    ///         for counter in counter_query.iter_many_unique(friends) {
952    ///             println!("Friend's counter: {:?}", counter.value);
953    ///         }
954    ///     }
955    /// }
956    /// # bevy_ecs::system::assert_is_system(system);
957    /// ```
958    ///
959    /// # See also
960    ///
961    /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
962    /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
963    #[inline]
964    pub fn iter_many_unique<EntityList: EntitySet>(
965        &self,
966        entities: EntityList,
967    ) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
968        self.as_readonly().iter_many_unique_inner(entities)
969    }
970
971    /// Returns an iterator over the unique query items generated from an [`EntitySet`].
972    ///
973    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
974    ///
975    /// # Examples
976    ///
977    /// ```
978    /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
979    /// # use core::slice;
980    /// #[derive(Component)]
981    /// struct Counter {
982    ///     value: i32
983    /// }
984    ///
985    /// // `Friends` ensures that it only lists unique entities.
986    /// #[derive(Component)]
987    /// struct Friends {
988    ///     unique_list: Vec<Entity>,
989    /// }
990    ///
991    /// impl<'a> IntoIterator for &'a Friends {
992    ///     type Item = &'a Entity;
993    ///     type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
994    ///
995    ///     fn into_iter(self) -> Self::IntoIter {
996    ///         // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
997    ///         unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }
998    ///     }
999    /// }
1000    ///
1001    /// fn system(
1002    ///     friends_query: Query<&Friends>,
1003    ///     mut counter_query: Query<&mut Counter>,
1004    /// ) {
1005    ///     for friends in &friends_query {
1006    ///         for mut counter in counter_query.iter_many_unique_mut(friends) {
1007    ///             println!("Friend's counter: {:?}", counter.value);
1008    ///             counter.value += 1;
1009    ///         }
1010    ///     }
1011    /// }
1012    /// # bevy_ecs::system::assert_is_system(system);
1013    /// ```
1014    /// # See also
1015    ///
1016    /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1017    /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1018    #[inline]
1019    pub fn iter_many_unique_mut<EntityList: EntitySet>(
1020        &mut self,
1021        entities: EntityList,
1022    ) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {
1023        self.reborrow().iter_many_unique_inner(entities)
1024    }
1025
1026    /// Returns an iterator over the unique query items generated from an [`EntitySet`].
1027    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1028    ///
1029    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1030    ///
1031    /// # Examples
1032    ///
1033    /// ```
1034    /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1035    /// # use core::slice;
1036    /// #[derive(Component)]
1037    /// struct Counter {
1038    ///     value: i32
1039    /// }
1040    ///
1041    /// // `Friends` ensures that it only lists unique entities.
1042    /// #[derive(Component)]
1043    /// struct Friends {
1044    ///     unique_list: Vec<Entity>,
1045    /// }
1046    ///
1047    /// impl<'a> IntoIterator for &'a Friends {
1048    ///     type Item = &'a Entity;
1049    ///     type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1050    ///
1051    ///     fn into_iter(self) -> Self::IntoIter {
1052    ///         // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1053    ///         unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }
1054    ///     }
1055    /// }
1056    ///
1057    /// fn system(
1058    ///     friends_query: Query<&Friends>,
1059    ///     mut counter_query: Query<&mut Counter>,
1060    /// ) {
1061    ///     let friends = friends_query.single().unwrap();
1062    ///     for mut counter in counter_query.iter_many_unique_inner(friends) {
1063    ///         println!("Friend's counter: {:?}", counter.value);
1064    ///         counter.value += 1;
1065    ///     }
1066    /// }
1067    /// # bevy_ecs::system::assert_is_system(system);
1068    /// ```
1069    /// # See also
1070    ///
1071    /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1072    /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1073    #[inline]
1074    pub fn iter_many_unique_inner<EntityList: EntitySet>(
1075        self,
1076        entities: EntityList,
1077    ) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter> {
1078        // SAFETY: `self.world` has permission to access the required components.
1079        unsafe {
1080            QueryManyUniqueIter::new(
1081                self.world,
1082                self.state,
1083                entities,
1084                self.last_run,
1085                self.this_run,
1086            )
1087        }
1088    }
1089
1090    /// Returns an [`Iterator`] over the query items.
1091    ///
1092    /// This iterator is always guaranteed to return results from each matching entity once and only once.
1093    /// Iteration order is not guaranteed.
1094    ///
1095    /// # Safety
1096    ///
1097    /// This function makes it possible to violate Rust's aliasing guarantees.
1098    /// You must make sure this call does not result in multiple mutable references to the same component.
1099    ///
1100    /// # See also
1101    ///
1102    /// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.
1103    #[inline]
1104    pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {
1105        // SAFETY: The caller promises that this will not result in multiple mutable references.
1106        unsafe { self.reborrow_unsafe() }.into_iter()
1107    }
1108
1109    /// Iterates over all possible combinations of `K` query items without repetition.
1110    ///
1111    /// This iterator is always guaranteed to return results from each unique pair of matching entities.
1112    /// Iteration order is not guaranteed.
1113    ///
1114    /// # Safety
1115    ///
1116    /// This allows aliased mutability.
1117    /// You must make sure this call does not result in multiple mutable references to the same component.
1118    ///
1119    /// # See also
1120    ///
1121    /// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.
1122    #[inline]
1123    pub unsafe fn iter_combinations_unsafe<const K: usize>(
1124        &self,
1125    ) -> QueryCombinationIter<'_, 's, D, F, K> {
1126        // SAFETY: The caller promises that this will not result in multiple mutable references.
1127        unsafe { self.reborrow_unsafe() }.iter_combinations_inner()
1128    }
1129
1130    /// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.
1131    ///
1132    /// Items are returned in the order of the list of entities, and may not be unique if the input
1133    /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
1134    ///
1135    /// # Safety
1136    ///
1137    /// This allows aliased mutability and does not check for entity uniqueness.
1138    /// You must make sure this call does not result in multiple mutable references to the same component.
1139    /// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].
1140    ///
1141    /// # See also
1142    ///
1143    /// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.
1144    pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(
1145        &self,
1146        entities: EntityList,
1147    ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
1148        // SAFETY: The caller promises that this will not result in multiple mutable references.
1149        unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)
1150    }
1151
1152    /// Returns an [`Iterator`] over the unique query items generated from an [`Entity`] list.
1153    ///
1154    /// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1155    ///
1156    /// # Safety
1157    ///
1158    /// This allows aliased mutability.
1159    /// You must make sure this call does not result in multiple mutable references to the same component.
1160    ///
1161    /// # See also
1162    ///
1163    /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1164    /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1165    /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1166    pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(
1167        &self,
1168        entities: EntityList,
1169    ) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {
1170        // SAFETY: The caller promises that this will not result in multiple mutable references.
1171        unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)
1172    }
1173
1174    /// Returns a parallel iterator over the query results for the given [`World`].
1175    ///
1176    /// This parallel iterator is always guaranteed to return results from each matching entity once and
1177    /// only once.  Iteration order and thread assignment is not guaranteed.
1178    ///
1179    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1180    /// on [`QueryIter`].
1181    ///
1182    /// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
1183    ///
1184    /// Note that you must use the `for_each` method to iterate over the
1185    /// results, see [`par_iter_mut`] for an example.
1186    ///
1187    /// [`par_iter_mut`]: Self::par_iter_mut
1188    /// [`World`]: crate::world::World
1189    #[inline]
1190    pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {
1191        self.as_readonly().par_iter_inner()
1192    }
1193
1194    /// Returns a parallel iterator over the query results for the given [`World`].
1195    ///
1196    /// This parallel iterator is always guaranteed to return results from each matching entity once and
1197    /// only once.  Iteration order and thread assignment is not guaranteed.
1198    ///
1199    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1200    /// on [`QueryIter`].
1201    ///
1202    /// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
1203    ///
1204    /// # Example
1205    ///
1206    /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1207    ///
1208    /// ```
1209    /// # use bevy_ecs::prelude::*;
1210    /// #
1211    /// # #[derive(Component)]
1212    /// # struct Velocity { x: f32, y: f32, z: f32 }
1213    /// fn gravity_system(mut query: Query<&mut Velocity>) {
1214    ///     const DELTA: f32 = 1.0 / 60.0;
1215    ///     query.par_iter_mut().for_each(|mut velocity| {
1216    ///         velocity.y -= 9.8 * DELTA;
1217    ///     });
1218    /// }
1219    /// # bevy_ecs::system::assert_is_system(gravity_system);
1220    /// ```
1221    ///
1222    /// [`par_iter`]: Self::par_iter
1223    /// [`World`]: crate::world::World
1224    #[inline]
1225    pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F> {
1226        self.reborrow().par_iter_inner()
1227    }
1228
1229    /// Returns a parallel iterator over the query results for the given [`World`](crate::world::World).
1230    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1231    ///
1232    /// This parallel iterator is always guaranteed to return results from each matching entity once and
1233    /// only once.  Iteration order and thread assignment is not guaranteed.
1234    ///
1235    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1236    /// on [`QueryIter`].
1237    ///
1238    /// # Example
1239    ///
1240    /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1241    ///
1242    /// ```
1243    /// # use bevy_ecs::prelude::*;
1244    /// #
1245    /// # #[derive(Component)]
1246    /// # struct Velocity { x: f32, y: f32, z: f32 }
1247    /// fn gravity_system(query: Query<&mut Velocity>) {
1248    ///     const DELTA: f32 = 1.0 / 60.0;
1249    ///     query.par_iter_inner().for_each(|mut velocity| {
1250    ///         velocity.y -= 9.8 * DELTA;
1251    ///     });
1252    /// }
1253    /// # bevy_ecs::system::assert_is_system(gravity_system);
1254    /// ```
1255    #[inline]
1256    pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F> {
1257        QueryParIter {
1258            world: self.world,
1259            state: self.state,
1260            last_run: self.last_run,
1261            this_run: self.this_run,
1262            batching_strategy: BatchingStrategy::new(),
1263        }
1264    }
1265
1266    /// Returns a parallel iterator over the read-only query items generated from an [`Entity`] list.
1267    ///
1268    /// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1269    ///
1270    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1271    /// on [`QueryManyIter`].
1272    ///
1273    /// This can only be called for read-only queries. To avoid potential aliasing, there is no `par_iter_many_mut` equivalent.
1274    /// See [`par_iter_many_unique_mut`] for an alternative using [`EntitySet`].
1275    ///
1276    /// Note that you must use the `for_each` method to iterate over the
1277    /// results, see [`par_iter_mut`] for an example.
1278    ///
1279    /// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1280    /// [`par_iter_mut`]: Self::par_iter_mut
1281    #[inline]
1282    pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
1283        &self,
1284        entities: EntityList,
1285    ) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1286        QueryParManyIter {
1287            world: self.world,
1288            state: self.state.as_readonly(),
1289            entity_list: entities.into_iter().collect(),
1290            last_run: self.last_run,
1291            this_run: self.this_run,
1292            batching_strategy: BatchingStrategy::new(),
1293        }
1294    }
1295
1296    /// Returns a parallel iterator over the unique read-only query items generated from an [`EntitySet`].
1297    ///
1298    /// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1299    ///
1300    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1301    /// on [`QueryManyUniqueIter`].
1302    ///
1303    /// This can only be called for read-only queries, see [`par_iter_many_unique_mut`] for write-queries.
1304    ///
1305    /// Note that you must use the `for_each` method to iterate over the
1306    /// results, see [`par_iter_mut`] for an example.
1307    ///
1308    /// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1309    /// [`par_iter_mut`]: Self::par_iter_mut
1310    #[inline]
1311    pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(
1312        &self,
1313        entities: EntityList,
1314    ) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1315        QueryParManyUniqueIter {
1316            world: self.world,
1317            state: self.state.as_readonly(),
1318            entity_list: entities.into_iter().collect(),
1319            last_run: self.last_run,
1320            this_run: self.this_run,
1321            batching_strategy: BatchingStrategy::new(),
1322        }
1323    }
1324
1325    /// Returns a parallel iterator over the unique query items generated from an [`EntitySet`].
1326    ///
1327    /// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1328    ///
1329    /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1330    /// on [`QueryManyUniqueIter`].
1331    ///
1332    /// This can only be called for mutable queries, see [`par_iter_many_unique`] for read-only-queries.
1333    ///
1334    /// Note that you must use the `for_each` method to iterate over the
1335    /// results, see [`par_iter_mut`] for an example.
1336    ///
1337    /// [`par_iter_many_unique`]: Self::par_iter_many_unique
1338    /// [`par_iter_mut`]: Self::par_iter_mut
1339    #[inline]
1340    pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(
1341        &mut self,
1342        entities: EntityList,
1343    ) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item> {
1344        QueryParManyUniqueIter {
1345            world: self.world,
1346            state: self.state,
1347            entity_list: entities.into_iter().collect(),
1348            last_run: self.last_run,
1349            this_run: self.this_run,
1350            batching_strategy: BatchingStrategy::new(),
1351        }
1352    }
1353
1354    /// Returns the read-only query item for the given [`Entity`].
1355    ///
1356    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1357    ///
1358    /// This is always guaranteed to run in `O(1)` time.
1359    ///
1360    /// # Example
1361    ///
1362    /// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.
1363    ///
1364    /// ```
1365    /// # use bevy_ecs::prelude::*;
1366    /// #
1367    /// # #[derive(Resource)]
1368    /// # struct SelectedCharacter { entity: Entity }
1369    /// # #[derive(Component)]
1370    /// # struct Character { name: String }
1371    /// #
1372    /// fn print_selected_character_name_system(
1373    ///        query: Query<&Character>,
1374    ///        selection: Res<SelectedCharacter>
1375    /// )
1376    /// {
1377    ///     if let Ok(selected_character) = query.get(selection.entity) {
1378    ///         println!("{}", selected_character.name);
1379    ///     }
1380    /// }
1381    /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
1382    /// ```
1383    ///
1384    /// # See also
1385    ///
1386    /// - [`get_mut`](Self::get_mut) to get a mutable query item.
1387    #[inline]
1388    pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {
1389        self.as_readonly().get_inner(entity)
1390    }
1391
1392    /// Returns the read-only query items for the given array of [`Entity`].
1393    ///
1394    /// The returned query items are in the same order as the input.
1395    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1396    /// The elements of the array do not need to be unique, unlike `get_many_mut`.
1397    ///
1398    /// # Examples
1399    ///
1400    /// ```
1401    /// use bevy_ecs::prelude::*;
1402    /// use bevy_ecs::query::QueryEntityError;
1403    ///
1404    /// #[derive(Component, PartialEq, Debug)]
1405    /// struct A(usize);
1406    ///
1407    /// let mut world = World::new();
1408    /// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1409    /// let entities: [Entity; 3] = entity_vec.try_into().unwrap();
1410    ///
1411    /// world.spawn(A(73));
1412    ///
1413    /// let mut query_state = world.query::<&A>();
1414    /// let query = query_state.query(&world);
1415    ///
1416    /// let component_values = query.get_many(entities).unwrap();
1417    ///
1418    /// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1419    ///
1420    /// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1421    ///
1422    /// assert_eq!(
1423    ///     match query.get_many([wrong_entity]).unwrap_err() {
1424    ///         QueryEntityError::EntityDoesNotExist(error) => error.entity,
1425    ///         _ => panic!(),
1426    ///     },
1427    ///     wrong_entity
1428    /// );
1429    /// ```
1430    ///
1431    /// # See also
1432    ///
1433    /// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.
1434    /// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.
1435    #[inline]
1436    pub fn get_many<const N: usize>(
1437        &self,
1438        entities: [Entity; N],
1439    ) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1440        // Note that we call a separate `*_inner` method from `get_many_mut`
1441        // because we don't need to check for duplicates.
1442        self.as_readonly().get_many_inner(entities)
1443    }
1444
1445    /// Returns the read-only query items for the given [`UniqueEntityArray`].
1446    ///
1447    /// The returned query items are in the same order as the input.
1448    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1449    ///
1450    /// # Examples
1451    ///
1452    /// ```
1453    /// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1454    ///
1455    /// #[derive(Component, PartialEq, Debug)]
1456    /// struct A(usize);
1457    ///
1458    /// let mut world = World::new();
1459    /// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1460    /// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1461    ///
1462    /// world.spawn(A(73));
1463    ///
1464    /// let mut query_state = world.query::<&A>();
1465    /// let query = query_state.query(&world);
1466    ///
1467    /// let component_values = query.get_many_unique(entity_set).unwrap();
1468    ///
1469    /// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1470    ///
1471    /// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1472    ///
1473    /// assert_eq!(
1474    ///     match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {
1475    ///         QueryEntityError::EntityDoesNotExist(error) => error.entity,
1476    ///         _ => panic!(),
1477    ///     },
1478    ///     wrong_entity
1479    /// );
1480    /// ```
1481    ///
1482    /// # See also
1483    ///
1484    /// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.
1485    /// - [`get_many`](Self::get_many) to handle inputs with duplicates.
1486    #[inline]
1487    pub fn get_many_unique<const N: usize>(
1488        &self,
1489        entities: UniqueEntityArray<N>,
1490    ) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1491        self.as_readonly().get_many_unique_inner(entities)
1492    }
1493
1494    /// Returns the query item for the given [`Entity`].
1495    ///
1496    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1497    ///
1498    /// This is always guaranteed to run in `O(1)` time.
1499    ///
1500    /// # Example
1501    ///
1502    /// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.
1503    ///
1504    /// ```
1505    /// # use bevy_ecs::prelude::*;
1506    /// #
1507    /// # #[derive(Resource)]
1508    /// # struct PoisonedCharacter { character_id: Entity }
1509    /// # #[derive(Component)]
1510    /// # struct Health(u32);
1511    /// #
1512    /// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
1513    ///     if let Ok(mut health) = query.get_mut(poisoned.character_id) {
1514    ///         health.0 -= 1;
1515    ///     }
1516    /// }
1517    /// # bevy_ecs::system::assert_is_system(poison_system);
1518    /// ```
1519    ///
1520    /// # See also
1521    ///
1522    /// - [`get`](Self::get) to get a read-only query item.
1523    #[inline]
1524    pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {
1525        self.reborrow().get_inner(entity)
1526    }
1527
1528    /// Returns the query item for the given [`Entity`].
1529    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1530    ///
1531    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1532    ///
1533    /// This is always guaranteed to run in `O(1)` time.
1534    ///
1535    /// # See also
1536    ///
1537    /// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].
1538    #[inline]
1539    pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {
1540        // SAFETY: system runs without conflicts with other systems.
1541        // same-system queries have runtime borrow checks when they conflict
1542        unsafe {
1543            let location = self
1544                .world
1545                .entities()
1546                .get(entity)
1547                .ok_or(EntityDoesNotExistError::new(entity, self.world.entities()))?;
1548            if !self
1549                .state
1550                .matched_archetypes
1551                .contains(location.archetype_id.index())
1552            {
1553                return Err(QueryEntityError::QueryDoesNotMatch(
1554                    entity,
1555                    location.archetype_id,
1556                ));
1557            }
1558            let archetype = self
1559                .world
1560                .archetypes()
1561                .get(location.archetype_id)
1562                .debug_checked_unwrap();
1563            let mut fetch = D::init_fetch(
1564                self.world,
1565                &self.state.fetch_state,
1566                self.last_run,
1567                self.this_run,
1568            );
1569            let mut filter = F::init_fetch(
1570                self.world,
1571                &self.state.filter_state,
1572                self.last_run,
1573                self.this_run,
1574            );
1575
1576            let table = self
1577                .world
1578                .storages()
1579                .tables
1580                .get(location.table_id)
1581                .debug_checked_unwrap();
1582            D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);
1583            F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);
1584
1585            if F::filter_fetch(
1586                &self.state.filter_state,
1587                &mut filter,
1588                entity,
1589                location.table_row,
1590            ) {
1591                Ok(D::fetch(
1592                    &self.state.fetch_state,
1593                    &mut fetch,
1594                    entity,
1595                    location.table_row,
1596                ))
1597            } else {
1598                Err(QueryEntityError::QueryDoesNotMatch(
1599                    entity,
1600                    location.archetype_id,
1601                ))
1602            }
1603        }
1604    }
1605
1606    /// Returns the query items for the given array of [`Entity`].
1607    ///
1608    /// The returned query items are in the same order as the input.
1609    /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1610    ///
1611    /// # Examples
1612    ///
1613    /// ```
1614    /// use bevy_ecs::prelude::*;
1615    /// use bevy_ecs::query::QueryEntityError;
1616    ///
1617    /// #[derive(Component, PartialEq, Debug)]
1618    /// struct A(usize);
1619    ///
1620    /// let mut world = World::new();
1621    ///
1622    /// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1623    /// let entities: [Entity; 3] = entities.try_into().unwrap();
1624    ///
1625    /// world.spawn(A(73));
1626    /// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1627    /// let invalid_entity = world.spawn_empty().id();
1628    ///
1629    ///
1630    /// let mut query_state = world.query::<&mut A>();
1631    /// let mut query = query_state.query_mut(&mut world);
1632    ///
1633    /// let mut mutable_component_values = query.get_many_mut(entities).unwrap();
1634    ///
1635    /// for mut a in &mut mutable_component_values {
1636    ///     a.0 += 5;
1637    /// }
1638    ///
1639    /// let component_values = query.get_many(entities).unwrap();
1640    ///
1641    /// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1642    ///
1643    /// assert_eq!(
1644    ///     match query
1645    ///         .get_many_mut([wrong_entity])
1646    ///         .unwrap_err()
1647    ///     {
1648    ///         QueryEntityError::EntityDoesNotExist(error) => error.entity,
1649    ///         _ => panic!(),
1650    ///     },
1651    ///     wrong_entity
1652    /// );
1653    /// assert_eq!(
1654    ///     match query
1655    ///         .get_many_mut([invalid_entity])
1656    ///         .unwrap_err()
1657    ///     {
1658    ///         QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1659    ///         _ => panic!(),
1660    ///     },
1661    ///     invalid_entity
1662    /// );
1663    /// assert_eq!(
1664    ///     query
1665    ///         .get_many_mut([entities[0], entities[0]])
1666    ///         .unwrap_err(),
1667    ///     QueryEntityError::AliasedMutability(entities[0])
1668    /// );
1669    /// ```
1670    /// # See also
1671    ///
1672    /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1673    #[inline]
1674    pub fn get_many_mut<const N: usize>(
1675        &mut self,
1676        entities: [Entity; N],
1677    ) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {
1678        self.reborrow().get_many_mut_inner(entities)
1679    }
1680
1681    /// Returns the query items for the given [`UniqueEntityArray`].
1682    ///
1683    /// The returned query items are in the same order as the input.
1684    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1685    ///
1686    /// # Examples
1687    ///
1688    /// ```
1689    /// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1690    ///
1691    /// #[derive(Component, PartialEq, Debug)]
1692    /// struct A(usize);
1693    ///
1694    /// let mut world = World::new();
1695    ///
1696    /// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1697    /// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1698    ///
1699    /// world.spawn(A(73));
1700    /// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1701    /// let invalid_entity = world.spawn_empty().id();
1702    ///
1703    ///
1704    /// let mut query_state = world.query::<&mut A>();
1705    /// let mut query = query_state.query_mut(&mut world);
1706    ///
1707    /// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();
1708    ///
1709    /// for mut a in &mut mutable_component_values {
1710    ///     a.0 += 5;
1711    /// }
1712    ///
1713    /// let component_values = query.get_many_unique(entity_set).unwrap();
1714    ///
1715    /// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1716    ///
1717    /// assert_eq!(
1718    ///     match query
1719    ///         .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))
1720    ///         .unwrap_err()
1721    ///     {
1722    ///         QueryEntityError::EntityDoesNotExist(error) => error.entity,
1723    ///         _ => panic!(),
1724    ///     },
1725    ///     wrong_entity
1726    /// );
1727    /// assert_eq!(
1728    ///     match query
1729    ///         .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))
1730    ///         .unwrap_err()
1731    ///     {
1732    ///         QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1733    ///         _ => panic!(),
1734    ///     },
1735    ///     invalid_entity
1736    /// );
1737    /// ```
1738    /// # See also
1739    ///
1740    /// - [`get_many_unique`](Self::get_many) to get read-only query items.
1741    #[inline]
1742    pub fn get_many_unique_mut<const N: usize>(
1743        &mut self,
1744        entities: UniqueEntityArray<N>,
1745    ) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {
1746        self.reborrow().get_many_unique_inner(entities)
1747    }
1748
1749    /// Returns the query items for the given array of [`Entity`].
1750    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1751    ///
1752    /// The returned query items are in the same order as the input.
1753    /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1754    ///
1755    /// # See also
1756    ///
1757    /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1758    /// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
1759    /// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.
1760    #[inline]
1761    pub fn get_many_mut_inner<const N: usize>(
1762        self,
1763        entities: [Entity; N],
1764    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {
1765        // Verify that all entities are unique
1766        for i in 0..N {
1767            for j in 0..i {
1768                if entities[i] == entities[j] {
1769                    return Err(QueryEntityError::AliasedMutability(entities[i]));
1770                }
1771            }
1772        }
1773        // SAFETY: All entities are unique, so the results don't alias.
1774        unsafe { self.get_many_impl(entities) }
1775    }
1776
1777    /// Returns the query items for the given array of [`Entity`].
1778    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1779    ///
1780    /// The returned query items are in the same order as the input.
1781    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1782    ///
1783    /// # See also
1784    ///
1785    /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1786    /// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
1787    /// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.
1788    #[inline]
1789    pub fn get_many_inner<const N: usize>(
1790        self,
1791        entities: [Entity; N],
1792    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
1793    where
1794        D: ReadOnlyQueryData,
1795    {
1796        // SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.
1797        unsafe { self.get_many_impl(entities) }
1798    }
1799
1800    /// Returns the query items for the given [`UniqueEntityArray`].
1801    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1802    ///
1803    /// The returned query items are in the same order as the input.
1804    /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1805    ///
1806    /// # See also
1807    ///
1808    /// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.
1809    /// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.
1810    #[inline]
1811    pub fn get_many_unique_inner<const N: usize>(
1812        self,
1813        entities: UniqueEntityArray<N>,
1814    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {
1815        // SAFETY: All entities are unique, so the results don't alias.
1816        unsafe { self.get_many_impl(entities.into_inner()) }
1817    }
1818
1819    /// Returns the query items for the given array of [`Entity`].
1820    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1821    ///
1822    /// # Safety
1823    ///
1824    /// The caller must ensure that the query data returned for the entities does not conflict,
1825    /// either because they are all unique or because the data is read-only.
1826    unsafe fn get_many_impl<const N: usize>(
1827        self,
1828        entities: [Entity; N],
1829    ) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {
1830        let mut values = [(); N].map(|_| MaybeUninit::uninit());
1831
1832        for (value, entity) in core::iter::zip(&mut values, entities) {
1833            // SAFETY: The caller asserts that the results don't alias
1834            let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;
1835            *value = MaybeUninit::new(item);
1836        }
1837
1838        // SAFETY: Each value has been fully initialized.
1839        Ok(values.map(|x| unsafe { x.assume_init() }))
1840    }
1841
1842    /// Returns the query item for the given [`Entity`].
1843    ///
1844    /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1845    ///
1846    /// This is always guaranteed to run in `O(1)` time.
1847    ///
1848    /// # Safety
1849    ///
1850    /// This function makes it possible to violate Rust's aliasing guarantees.
1851    /// You must make sure this call does not result in multiple mutable references to the same component.
1852    ///
1853    /// # See also
1854    ///
1855    /// - [`get_mut`](Self::get_mut) for the safe version.
1856    #[inline]
1857    pub unsafe fn get_unchecked(
1858        &self,
1859        entity: Entity,
1860    ) -> Result<D::Item<'_, 's>, QueryEntityError> {
1861        // SAFETY: The caller promises that this will not result in multiple mutable references.
1862        unsafe { self.reborrow_unsafe() }.get_inner(entity)
1863    }
1864
1865    /// Returns a single read-only query item when there is exactly one entity matching the query.
1866    ///
1867    /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1868    ///
1869    /// # Example
1870    ///
1871    /// ```
1872    /// # use bevy_ecs::prelude::*;
1873    /// # use bevy_ecs::query::QuerySingleError;
1874    /// # #[derive(Component)]
1875    /// # struct PlayerScore(i32);
1876    /// fn player_scoring_system(query: Query<&PlayerScore>) {
1877    ///     match query.single() {
1878    ///         Ok(PlayerScore(score)) => {
1879    ///             println!("Score: {}", score);
1880    ///         }
1881    ///         Err(QuerySingleError::NoEntities(_)) => {
1882    ///             println!("Error: There is no player!");
1883    ///         }
1884    ///         Err(QuerySingleError::MultipleEntities(_)) => {
1885    ///             println!("Error: There is more than one player!");
1886    ///         }
1887    ///     }
1888    /// }
1889    /// # bevy_ecs::system::assert_is_system(player_scoring_system);
1890    /// ```
1891    ///
1892    /// # See also
1893    ///
1894    /// - [`single_mut`](Self::single_mut) to get the mutable query item.
1895    #[inline]
1896    pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {
1897        self.as_readonly().single_inner()
1898    }
1899
1900    /// Returns a single query item when there is exactly one entity matching the query.
1901    ///
1902    /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1903    ///
1904    /// # Example
1905    ///
1906    /// ```
1907    /// # use bevy_ecs::prelude::*;
1908    /// #
1909    /// # #[derive(Component)]
1910    /// # struct Player;
1911    /// # #[derive(Component)]
1912    /// # struct Health(u32);
1913    /// #
1914    /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
1915    ///     let mut health = query.single_mut().expect("Error: Could not find a single player.");
1916    ///     health.0 += 1;
1917    /// }
1918    /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1919    /// ```
1920    ///
1921    /// # See also
1922    ///
1923    /// - [`single`](Self::single) to get the read-only query item.
1924    #[inline]
1925    pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError> {
1926        self.reborrow().single_inner()
1927    }
1928
1929    /// Returns a single query item when there is exactly one entity matching the query.
1930    /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1931    ///
1932    /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1933    ///
1934    /// # Example
1935    ///
1936    /// ```
1937    /// # use bevy_ecs::prelude::*;
1938    /// #
1939    /// # #[derive(Component)]
1940    /// # struct Player;
1941    /// # #[derive(Component)]
1942    /// # struct Health(u32);
1943    /// #
1944    /// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {
1945    ///     let mut health = query.single_inner().expect("Error: Could not find a single player.");
1946    ///     health.0 += 1;
1947    /// }
1948    /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1949    /// ```
1950    ///
1951    /// # See also
1952    ///
1953    /// - [`single`](Self::single) to get the read-only query item.
1954    /// - [`single_mut`](Self::single_mut) to get the mutable query item.
1955    #[inline]
1956    pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError> {
1957        let mut query = self.into_iter();
1958        let first = query.next();
1959        let extra = query.next().is_some();
1960
1961        match (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::<
1965                Self,
1966            >())),
1967        }
1968    }
1969
1970    /// 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 rely
1974    /// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check
1975    /// each query result for a match.
1976    ///
1977    /// # Example
1978    ///
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::Added
1997    /// [`Changed`]: crate::query::Changed
1998    /// [`Spawned`]: crate::query::Spawned
1999    #[inline]
2000    pub fn is_empty(&self) -> bool {
2001        self.as_nop().iter().next().is_none()
2002    }
2003
2004    /// Returns `true` if the given [`Entity`] matches the query.
2005    ///
2006    /// This is always guaranteed to run in `O(1)` time.
2007    ///
2008    /// # Example
2009    ///
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]
2029    pub fn contains(&self, entity: Entity) -> bool {
2030        self.as_nop().get(entity).is_ok()
2031    }
2032
2033    /// 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    /// # Example
2042    ///
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    /// ```
2055    pub fn count(&self) -> usize {
2056        let iter = self.as_nop().into_iter();
2057        if 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.
2060            iter.size_hint().0
2061        } else {
2062            // If we have non-archetypal filters, we have to check each entity.
2063            iter.count()
2064        }
2065    }
2066
2067    /// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more
2068    /// 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 access
2071    /// of the current query. A precise description of the access required by each parameter
2072    /// 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 like
2079    /// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter
2080    /// 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 new
2094    /// 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::Added
2104    /// [`Added<T>`]: crate::query::Added
2105    /// [`AnyOf<(D, ...)>`]: crate::query::AnyOf
2106    /// [`&Archetype`]: crate::archetype::Archetype
2107    /// [`Changed`]: crate::query::Changed
2108    /// [`Changed<T>`]: crate::query::Changed
2109    /// [`EntityMut`]: crate::world::EntityMut
2110    /// [`EntityLocation`]: crate::entity::EntityLocation
2111    /// [`EntityRef`]: crate::world::EntityRef
2112    /// [`FilteredEntityRef`]: crate::world::FilteredEntityRef
2113    /// [`FilteredEntityMut`]: crate::world::FilteredEntityMut
2114    /// [`Has<T>`]: crate::query::Has
2115    /// [`Mut<T>`]: crate::world::Mut
2116    /// [`Or<(T, ...)>`]: crate::query::Or
2117    /// [`QueryBuilder`]: crate::query::QueryBuilder
2118    /// [`Ref<T>`]: crate::world::Ref
2119    /// [`SpawnDetails`]: crate::query::SpawnDetails
2120    /// [`Spawned`]: crate::query::Spawned
2121    /// [`With<T>`]: crate::query::With
2122    /// [`Without<T>`]: crate::query::Without
2123    ///
2124    /// ## Panics
2125    ///
2126    /// This will panic if the access required by `NewD` is not a subset of that required by
2127    /// the original fetch `D`.
2128    ///
2129    /// ## Example
2130    ///
2131    /// ```rust
2132    /// # 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 exactly
2155    /// // 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 transmutes
2167    ///
2168    /// ```rust
2169    /// # 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 initialized
2185    /// #     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 versions
2202    /// 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 dropped
2209    /// 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 added
2214    /// 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 access
2221    /// 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 result
2224    /// // 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` data
2236    /// // 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]
2243    pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {
2244        self.transmute_lens_filtered::<NewD, ()>()
2245    }
2246
2247    /// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive
2248    /// 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    /// ## Panics
2255    ///
2256    /// This will panic if `NewD` is not a subset of the original fetch `D`
2257    ///
2258    /// ## Example
2259    ///
2260    /// ```rust
2261    /// # 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 exactly
2284    /// // 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 also
2296    ///
2297    /// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].
2298    #[track_caller]
2299    pub fn transmute_lens_inner<NewD: QueryData>(self) -> QueryLens<'w, NewD> {
2300        self.transmute_lens_filtered_inner::<NewD, ()>()
2301    }
2302
2303    /// 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 that
2308    /// 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 they
2311    /// are in the type signature.
2312    #[track_caller]
2313    pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(
2314        &mut self,
2315    ) -> QueryLens<'_, NewD, NewF> {
2316        self.reborrow().transmute_lens_filtered_inner()
2317    }
2318
2319    /// 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 that
2325    /// 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 they
2328    /// are in the type signature.
2329    ///
2330    /// # See also
2331    ///
2332    /// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].
2333    #[track_caller]
2334    pub fn transmute_lens_filtered_inner<NewD: QueryData, NewF: QueryFilter>(
2335        self,
2336    ) -> QueryLens<'w, NewD, NewF> {
2337        let state = self.state.transmute_filtered::<NewD, NewF>(self.world);
2338        QueryLens {
2339            world: self.world,
2340            state,
2341            last_run: self.last_run,
2342            this_run: self.this_run,
2343        }
2344    }
2345
2346    /// Gets a [`QueryLens`] with the same accesses as the existing query
2347    pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {
2348        self.transmute_lens()
2349    }
2350
2351    /// Gets a [`QueryLens`] with the same accesses as the existing query
2352    ///
2353    /// # See also
2354    ///
2355    /// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].
2356    pub fn into_query_lens(self) -> QueryLens<'w, D> {
2357        self.transmute_lens_inner()
2358    }
2359
2360    /// 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 filters
2364    /// 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    /// ## Example
2368    ///
2369    /// ```rust
2370    /// # 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 b
2394    ///     }
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 b
2399    ///     }
2400    /// }
2401    ///
2402    /// # let mut schedule = Schedule::default();
2403    /// # schedule.add_systems(system);
2404    /// # schedule.run(&mut world);
2405    /// ```
2406    /// ## Panics
2407    ///
2408    /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2409    ///
2410    /// ## Allowed Transmutes
2411    ///
2412    /// Like `transmute_lens` the query terms can be changed with some restrictions.
2413    /// See [`Self::transmute_lens`] for more details.
2414    pub fn join<'a, OtherD: QueryData, NewD: QueryData>(
2415        &'a mut self,
2416        other: &'a mut Query<OtherD>,
2417    ) -> QueryLens<'a, NewD> {
2418        self.join_filtered(other)
2419    }
2420
2421    /// 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 filters
2426    /// 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    /// ## Panics
2430    ///
2431    /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2432    ///
2433    /// ## Allowed Transmutes
2434    ///
2435    /// Like `transmute_lens` the query terms can be changed with some restrictions.
2436    /// See [`Self::transmute_lens`] for more details.
2437    ///
2438    /// # See also
2439    ///
2440    /// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].
2441    pub fn join_inner<OtherD: QueryData, NewD: QueryData>(
2442        self,
2443        other: Query<'w, '_, OtherD>,
2444    ) -> QueryLens<'w, NewD> {
2445        self.join_filtered_inner(other)
2446    }
2447
2448    /// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.
2449    ///
2450    /// Note that the lens with iterate a subset of the original queries' tables
2451    /// and archetypes. This means that additional archetypal query terms like
2452    /// `With` and `Without` will not necessarily be respected and non-archetypal
2453    /// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2454    /// are in the type signature.
2455    pub fn join_filtered<
2456        'a,
2457        OtherD: QueryData,
2458        OtherF: QueryFilter,
2459        NewD: QueryData,
2460        NewF: QueryFilter,
2461    >(
2462        &'a mut self,
2463        other: &'a mut Query<OtherD, OtherF>,
2464    ) -> QueryLens<'a, NewD, NewF> {
2465        self.reborrow().join_filtered_inner(other.reborrow())
2466    }
2467
2468    /// 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' tables
2472    /// and archetypes. This means that additional archetypal query terms like
2473    /// `With` and `Without` will not necessarily be respected and non-archetypal
2474    /// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2475    /// are in the type signature.
2476    ///
2477    /// # See also
2478    ///
2479    /// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].
2480    pub fn join_filtered_inner<
2481        OtherD: QueryData,
2482        OtherF: QueryFilter,
2483        NewD: QueryData,
2484        NewF: QueryFilter,
2485    >(
2486        self,
2487        other: Query<'w, '_, OtherD, OtherF>,
2488    ) -> QueryLens<'w, NewD, NewF> {
2489        let state = self
2490            .state
2491            .join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);
2492        QueryLens {
2493            world: self.world,
2494            state,
2495            last_run: self.last_run,
2496            this_run: self.this_run,
2497        }
2498    }
2499}
2500
2501impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {
2502    type Item = D::Item<'w, 's>;
2503    type IntoIter = QueryIter<'w, 's, D, F>;
2504
2505    fn 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.
2510        unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }
2511    }
2512}
2513
2514impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {
2515    type Item = ROQueryItem<'w, 's, D>;
2516    type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;
2517
2518    fn into_iter(self) -> Self::IntoIter {
2519        self.iter()
2520    }
2521}
2522
2523impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {
2524    type Item = D::Item<'w, 's>;
2525    type IntoIter = QueryIter<'w, 's, D, F>;
2526
2527    fn into_iter(self) -> Self::IntoIter {
2528        self.iter_mut()
2529    }
2530}
2531
2532impl<'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    /// # Example
2539    ///
2540    /// Here, the `report_names_system` iterates over the `Player` component of every entity
2541    /// 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]
2557    pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {
2558        (*self).into_iter()
2559    }
2560}
2561
2562/// 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 = ()> {
2566    world: UnsafeWorldCell<'w>,
2567    state: QueryState<Q, F>,
2568    last_run: Tick,
2569    this_run: Tick,
2570}
2571
2572impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2573    /// Create a [`Query`] from the underlying [`QueryState`].
2574    pub fn query(&mut self) -> Query<'_, '_, Q, F> {
2575        Query {
2576            world: self.world,
2577            state: &self.state,
2578            last_run: self.last_run,
2579            this_run: self.this_run,
2580        }
2581    }
2582}
2583
2584impl<'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.
2588    pub fn query_inner(&self) -> Query<'w, '_, Q, F> {
2589        Query {
2590            world: self.world,
2591            state: &self.state,
2592            last_run: self.last_run,
2593            this_run: self.this_run,
2594        }
2595    }
2596}
2597
2598impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>
2599    for Query<'s, 's, Q, F>
2600{
2601    fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {
2602        value.query()
2603    }
2604}
2605
2606impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>
2607    for QueryLens<'q, Q, F>
2608{
2609    fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {
2610        value.transmute_lens_filtered()
2611    }
2612}
2613
2614/// [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::SystemParam
2624///
2625/// # Example
2626/// ```
2627/// # use bevy_ecs::prelude::*;
2628/// #[derive(Component)]
2629/// struct Boss {
2630///    health: f32
2631/// };
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 = ()> {
2640    pub(crate) item: D::Item<'w, 's>,
2641    pub(crate) _filter: PhantomData<F>,
2642}
2643
2644impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {
2645    type Target = D::Item<'w, 's>;
2646
2647    fn deref(&self) -> &Self::Target {
2648        &self.item
2649    }
2650}
2651
2652impl<'w, 's, D: QueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {
2653    fn deref_mut(&mut self) -> &mut Self::Target {
2654        &mut self.item
2655    }
2656}
2657
2658impl<'w, 's, D: QueryData, F: QueryFilter> Single<'w, 's, D, F> {
2659    /// Returns the inner item with ownership.
2660    pub fn into_inner(self) -> D::Item<'w, 's> {
2661        self.item
2662    }
2663}
2664
2665/// [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 query
2673/// result for a match.
2674///
2675/// See [`Query`] for more details.
2676///
2677/// [System parameter]: crate::system::SystemParam
2678pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);
2679
2680impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {
2681    type Target = Query<'w, 's, D, F>;
2682
2683    fn deref(&self) -> &Self::Target {
2684        &self.0
2685    }
2686}
2687
2688impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {
2689    fn deref_mut(&mut self) -> &mut Self::Target {
2690        &mut self.0
2691    }
2692}
2693
2694impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {
2695    /// Returns the inner item with ownership.
2696    pub fn into_inner(self) -> Query<'w, 's, D, F> {
2697        self.0
2698    }
2699}
2700
2701impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {
2702    type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;
2703
2704    type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2705
2706    fn into_iter(self) -> Self::IntoIter {
2707        self.0.into_iter()
2708    }
2709}
2710
2711impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {
2712    type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;
2713
2714    type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2715
2716    fn into_iter(self) -> Self::IntoIter {
2717        self.deref().into_iter()
2718    }
2719}
2720
2721impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a mut Populated<'w, 's, D, F> {
2722    type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;
2723
2724    type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2725
2726    fn into_iter(self) -> Self::IntoIter {
2727        self.deref_mut().into_iter()
2728    }
2729}
2730
2731#[cfg(test)]
2732mod tests {
2733    use crate::{prelude::*, query::QueryEntityError};
2734    use alloc::vec::Vec;
2735
2736    #[test]
2737    fn get_many_uniqueness() {
2738        let mut world = World::new();
2739
2740        let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();
2741
2742        let mut query_state = world.query::<Entity>();
2743
2744        // It's best to test get_many_mut_inner directly, as it is shared
2745        // We don't care about aliased mutability for the read-only equivalent
2746
2747        // SAFETY: Query does not access world data.
2748        assert!(query_state
2749            .query_mut(&mut world)
2750            .get_many_mut_inner::<10>(entities.clone().try_into().unwrap())
2751            .is_ok());
2752
2753        assert_eq!(
2754            query_state
2755                .query_mut(&mut world)
2756                .get_many_mut_inner([entities[0], entities[0]])
2757                .unwrap_err(),
2758            QueryEntityError::AliasedMutability(entities[0])
2759        );
2760
2761        assert_eq!(
2762            query_state
2763                .query_mut(&mut world)
2764                .get_many_mut_inner([entities[0], entities[1], entities[0]])
2765                .unwrap_err(),
2766            QueryEntityError::AliasedMutability(entities[0])
2767        );
2768
2769        assert_eq!(
2770            query_state
2771                .query_mut(&mut world)
2772                .get_many_mut_inner([entities[9], entities[9]])
2773                .unwrap_err(),
2774            QueryEntityError::AliasedMutability(entities[9])
2775        );
2776    }
2777}