bevy_ecs/system/query.rs
1use bevy_utils::prelude::DebugName;
2
3use crate::{
4 batching::BatchingStrategy,
5 change_detection::Tick,
6 entity::{Entity, EntityEquivalent, EntitySet, UniqueEntityArray},
7 query::{
8 ArchetypeFilter, ContiguousQueryData, DebugCheckedUnwrap, IterQueryData, NopWorldQuery,
9 QueryCombinationIter, QueryContiguousIter, QueryContiguousParIter, QueryData,
10 QueryEntityError, QueryFilter, QueryIter, QueryManyIter, QueryManyUniqueIter,
11 QueryNotDenseError, QueryParIter, QueryParManyIter, QueryParManyUniqueIter,
12 QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData, SingleEntityQueryData,
13 },
14 world::unsafe_world_cell::UnsafeWorldCell,
15};
16use core::{
17 marker::PhantomData,
18 mem::MaybeUninit,
19 ops::{Deref, DerefMut},
20};
21
22/// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`].
23///
24/// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`].
25/// Its iterators and getter methods return *query items*, which are types containing data related to an entity.
26///
27/// `Query` is a generic data structure that accepts two type parameters:
28///
29/// - **`D` (query data)**:
30/// The type of data fetched by the query, which will be returned as the query item.
31/// Only entities that match the requested data will generate an item.
32/// Must implement the [`QueryData`] trait.
33/// - **`F` (query filter)**:
34/// An optional set of conditions that determine whether query items should be kept or discarded.
35/// This defaults to [`unit`], which means no additional filters will be applied.
36/// Must implement the [`QueryFilter`] trait.
37///
38/// [system parameter]: crate::system::SystemParam
39/// [`Component`]: crate::component::Component
40/// [`World`]: crate::world::World
41/// [entity identifiers]: Entity
42/// [components]: crate::component::Component
43///
44/// # Similar parameters
45///
46/// `Query` has few sibling [`SystemParam`]s, which perform additional validation:
47///
48/// - [`Single`] - Exactly one matching query item.
49/// - [`Option<Single>`] - Zero or one matching query item.
50/// - [`Populated`] - At least one matching query item.
51///
52/// These parameters will prevent systems from running if their requirements are not met.
53///
54/// [`SystemParam`]: crate::system::system_param::SystemParam
55/// [`Option<Single>`]: Single
56///
57/// # System parameter declaration
58///
59/// A query should always be declared as a system parameter.
60/// This section shows the most common idioms involving the declaration of `Query`.
61///
62/// ## Component access
63///
64/// You can fetch an entity's component by specifying a reference to that component in the query's data parameter:
65///
66/// ```
67/// # use bevy_ecs::prelude::*;
68/// #
69/// # #[derive(Component)]
70/// # struct ComponentA;
71/// #
72/// // A component can be accessed by a shared reference...
73/// fn immutable_query(query: Query<&ComponentA>) {
74/// // ...
75/// }
76///
77/// // ...or by a mutable reference.
78/// fn mutable_query(query: Query<&mut ComponentA>) {
79/// // ...
80/// }
81/// #
82/// # bevy_ecs::system::assert_is_system(immutable_query);
83/// # bevy_ecs::system::assert_is_system(mutable_query);
84/// ```
85///
86/// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile:
87///
88/// ```compile_fail,E0277
89/// # use bevy_ecs::prelude::*;
90/// #
91/// # #[derive(Component)]
92/// # struct ComponentA;
93/// #
94/// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile.
95/// fn invalid_query(query: Query<ComponentA>) {
96/// // ...
97/// }
98/// ```
99///
100/// ## Query filtering
101///
102/// Setting the query filter type parameter will ensure that each query item satisfies the given condition:
103///
104/// ```
105/// # use bevy_ecs::prelude::*;
106/// #
107/// # #[derive(Component)]
108/// # struct ComponentA;
109/// #
110/// # #[derive(Component)]
111/// # struct ComponentB;
112/// #
113/// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`.
114/// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) {
115/// // ...
116/// }
117/// #
118/// # bevy_ecs::system::assert_is_system(filtered_query);
119/// ```
120///
121/// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With`
122/// does not require components to be behind a reference.
123///
124/// ## `QueryData` or `QueryFilter` tuples
125///
126/// Using [`tuple`]s, each `Query` type parameter can contain multiple elements.
127///
128/// In the following example two components are accessed simultaneously, and the query items are
129/// filtered on two conditions:
130///
131/// ```
132/// # use bevy_ecs::prelude::*;
133/// #
134/// # #[derive(Component)]
135/// # struct ComponentA;
136/// #
137/// # #[derive(Component)]
138/// # struct ComponentB;
139/// #
140/// # #[derive(Component)]
141/// # struct ComponentC;
142/// #
143/// # #[derive(Component)]
144/// # struct ComponentD;
145/// #
146/// fn complex_query(
147/// query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
148/// ) {
149/// // ...
150/// }
151/// #
152/// # bevy_ecs::system::assert_is_system(complex_query);
153/// ```
154///
155/// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to
156/// get around this limit:
157///
158/// ```
159/// # use bevy_ecs::prelude::*;
160/// #
161/// # #[derive(Component)]
162/// # struct ComponentA;
163/// #
164/// # #[derive(Component)]
165/// # struct ComponentB;
166/// #
167/// # #[derive(Component)]
168/// # struct ComponentC;
169/// #
170/// # #[derive(Component)]
171/// # struct ComponentD;
172/// #
173/// fn nested_query(
174/// query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))>
175/// ) {
176/// // ...
177/// }
178/// #
179/// # bevy_ecs::system::assert_is_system(nested_query);
180/// ```
181///
182/// ## Entity identifier access
183///
184/// You can access [`Entity`], the entity identifier, by including it in the query data parameter:
185///
186/// ```
187/// # use bevy_ecs::prelude::*;
188/// #
189/// # #[derive(Component)]
190/// # struct ComponentA;
191/// #
192/// fn entity_id_query(query: Query<(Entity, &ComponentA)>) {
193/// // ...
194/// }
195/// #
196/// # bevy_ecs::system::assert_is_system(entity_id_query);
197/// ```
198///
199/// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference.
200///
201/// ## Optional component access
202///
203/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a
204/// query item will still be generated even if the queried entity does not contain `ComponentB`.
205/// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`.
206///
207/// ```
208/// # use bevy_ecs::prelude::*;
209/// #
210/// # #[derive(Component)]
211/// # struct ComponentA;
212/// #
213/// # #[derive(Component)]
214/// # struct ComponentB;
215/// #
216/// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will
217/// // be fetched as well.
218/// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) {
219/// // ...
220/// }
221/// #
222/// # bevy_ecs::system::assert_is_system(optional_component_query);
223/// ```
224///
225/// Optional components can hurt performance in some cases, so please read the [performance]
226/// section to learn more about them. Additionally, if you need to declare several optional
227/// components, you may be interested in using [`AnyOf`].
228///
229/// [performance]: #performance
230/// [`AnyOf`]: crate::query::AnyOf
231///
232/// ## Disjoint queries
233///
234/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic
235/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries
236/// disjoint.
237///
238/// In the following example, the two queries can mutably access the same `&mut Health` component
239/// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic,
240/// however, instead of breaking Rust's mutability rules:
241///
242/// ```should_panic
243/// # use bevy_ecs::prelude::*;
244/// #
245/// # #[derive(Component)]
246/// # struct Health;
247/// #
248/// # #[derive(Component)]
249/// # struct Player;
250/// #
251/// # #[derive(Component)]
252/// # struct Enemy;
253/// #
254/// fn randomize_health(
255/// player_query: Query<&mut Health, With<Player>>,
256/// enemy_query: Query<&mut Health, With<Enemy>>,
257/// ) {
258/// // ...
259/// }
260/// #
261/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
262/// ```
263///
264/// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity
265/// that has both the `Player` and `Enemy` components will be excluded from _both_ queries:
266///
267/// ```
268/// # use bevy_ecs::prelude::*;
269/// #
270/// # #[derive(Component)]
271/// # struct Health;
272/// #
273/// # #[derive(Component)]
274/// # struct Player;
275/// #
276/// # #[derive(Component)]
277/// # struct Enemy;
278/// #
279/// fn randomize_health(
280/// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
281/// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
282/// ) {
283/// // ...
284/// }
285/// #
286/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
287/// ```
288///
289/// An alternative solution to this problem would be to wrap the conflicting queries in
290/// [`ParamSet`].
291///
292/// [`Without`]: crate::query::Without
293/// [`ParamSet`]: crate::system::ParamSet
294///
295/// ## Whole Entity Access
296///
297/// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity.
298/// This is useful when dynamically fetching components instead of baking them into the query type.
299///
300/// ```
301/// # use bevy_ecs::prelude::*;
302/// #
303/// # #[derive(Component)]
304/// # struct ComponentA;
305/// #
306/// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) {
307/// // ...
308/// }
309/// #
310/// # bevy_ecs::system::assert_is_system(all_components_query);
311/// ```
312///
313/// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any*
314/// mutable component access.
315///
316/// ```should_panic
317/// # use bevy_ecs::prelude::*;
318/// #
319/// # #[derive(Component)]
320/// # struct ComponentA;
321/// #
322/// // `EntityRef` provides read access to *all* components on an entity. When combined with
323/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read
324/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing
325/// // rules.
326/// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) {
327/// // ...
328/// }
329/// #
330/// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query);
331/// ```
332///
333/// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] /
334/// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and
335/// parallelization of the system, but it enables systems to gain mutable access to other
336/// components:
337///
338/// ```
339/// # use bevy_ecs::prelude::*;
340/// #
341/// # #[derive(Component)]
342/// # struct ComponentA;
343/// #
344/// # #[derive(Component)]
345/// # struct ComponentB;
346/// #
347/// // The first query only reads entities that have `ComponentA`, while the second query only
348/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same
349/// // entity, this system does not conflict.
350/// fn disjoint_query(
351/// query_a: Query<EntityRef, With<ComponentA>>,
352/// query_b: Query<&mut ComponentB, Without<ComponentA>>,
353/// ) {
354/// // ...
355/// }
356/// #
357/// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query);
358/// ```
359///
360/// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never
361/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the
362/// queries on completely separate entities.
363///
364/// [`EntityRef`]: crate::world::EntityRef
365/// [`With`]: crate::query::With
366///
367/// # Accessing query items
368///
369/// The following table summarizes the behavior of safe methods that can be used to get query
370/// items:
371///
372/// |Query methods|Effect|
373/// |-|-|
374/// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.|
375/// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.|
376/// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.|
377/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.|
378/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.|
379/// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.|
380/// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.|
381///
382/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).
383/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.
384/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
385///
386/// [`iter`]: Self::iter
387/// [`iter_mut`]: Self::iter_mut
388/// [`for_each`]: #iteratorfor_each
389/// [`par_iter`]: Self::par_iter
390/// [`par_iter_mut`]: Self::par_iter_mut
391/// [`iter_many`]: Self::iter_many
392/// [`iter_many_unique`]: Self::iter_many_unique
393/// [`iter_many_mut`]: Self::iter_many_mut
394/// [`iter_combinations`]: Self::iter_combinations
395/// [`iter_combinations_mut`]: Self::iter_combinations_mut
396/// [`single_mut`]: Self::single_mut
397/// [`get`]: Self::get
398/// [`get_mut`]: Self::get_mut
399/// [`get_many`]: Self::get_many
400/// [`get_many_unique`]: Self::get_many_unique
401/// [`get_many_mut`]: Self::get_many_mut
402///
403/// # Performance
404///
405/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches
406/// data from the world and generates items, which can have a significant computational cost.
407///
408/// Two systems cannot be executed in parallel if both access the same component type where at
409/// least one of the accesses is mutable. Because of this, it is recommended for queries to only
410/// fetch mutable access to components when necessary, since immutable access can be parallelized.
411///
412/// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of
413/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be
414/// parallelized by the scheduler.
415///
416/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and
417/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is
418/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the
419/// query would iterate over all entities in the world.
420///
421/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers
422/// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite:
423/// it offers fast component insertion and removal speeds, but slower iteration speeds.
424///
425/// The following table compares the computational complexity of the various methods and
426/// operations, where:
427///
428/// - **n** is the number of entities that match the query.
429/// - **r** is the number of elements in a combination.
430/// - **k** is the number of involved entities in the operation.
431/// - **a** is the number of archetypes in the world.
432/// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is
433/// read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r*
434/// elements that can be taken from a set of *n* elements.
435///
436/// |Query operation|Computational complexity|
437/// |-|-|
438/// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)|
439/// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)|
440/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)|
441/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)|
442/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)|
443/// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)|
444/// |[`get_many`]|O(k)|
445/// |[`get_many_mut`]|O(k<sup>2</sup>)|
446/// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)|
447/// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)|
448///
449/// [component storage types]: crate::component::StorageType
450/// [`Table`]: crate::storage::Table
451/// [`SparseSet`]: crate::storage::SparseSet
452/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient
453/// [`Or`]: crate::query::Or
454/// [`Added`]: crate::query::Added
455/// [`Changed`]: crate::query::Changed
456/// [`Spawned`]: crate::query::Spawned
457///
458/// # `Iterator::for_each`
459///
460/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with
461/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It
462/// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance.
463/// *Always* profile or benchmark before and after the change!
464///
465/// ```rust
466/// # use bevy_ecs::prelude::*;
467/// #
468/// # #[derive(Component)]
469/// # struct ComponentA;
470/// #
471/// fn system(query: Query<&ComponentA>) {
472/// // This may result in better performance...
473/// query.iter().for_each(|component| {
474/// // ...
475/// });
476///
477/// // ...than this. Always benchmark to validate the difference!
478/// for component in query.iter() {
479/// // ...
480/// }
481/// }
482/// #
483/// # bevy_ecs::system::assert_is_system(system);
484/// ```
485///
486/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization
487pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {
488 // SAFETY: Must have access to the components registered in `state`.
489 world: UnsafeWorldCell<'world>,
490 state: &'state QueryState<D, F>,
491 last_run: Tick,
492 this_run: Tick,
493}
494
495impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {
496 fn clone(&self) -> Self {
497 *self
498 }
499}
500
501impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}
502
503impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {
504 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
505 f.debug_struct("Query")
506 .field("matched_entities", &self.iter().count())
507 .field("state", &self.state)
508 .field("last_run", &self.last_run)
509 .field("this_run", &self.this_run)
510 .field("world", &self.world)
511 .finish()
512 }
513}
514
515impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
516 /// Creates a new query.
517 ///
518 /// # Safety
519 ///
520 /// * This will create a query that could violate memory safety rules. Make sure that this is only
521 /// called in ways that ensure the queries have unique mutable access.
522 /// * `world` must be the world used to create `state`.
523 #[inline]
524 pub(crate) unsafe fn new(
525 world: UnsafeWorldCell<'w>,
526 state: &'s QueryState<D, F>,
527 last_run: Tick,
528 this_run: Tick,
529 ) -> Self {
530 Self {
531 world,
532 state,
533 last_run,
534 this_run,
535 }
536 }
537
538 /// Returns another `Query` from this that fetches the read-only version of the query items.
539 ///
540 /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
541 /// This can be useful when working around the borrow checker,
542 /// or reusing functionality between systems via functions that accept query types.
543 ///
544 /// # See also
545 ///
546 /// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.
547 pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {
548 // SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access,
549 // and the original query is held with a shared borrow, so it cannot perform mutable access either.
550 unsafe { self.reborrow_unsafe() }.into_readonly()
551 }
552
553 /// Returns another `Query` from this does not return any data, which can be faster.
554 ///
555 /// The resulting query will ignore any non-archetypal filters in `D`,
556 /// so this is only equivalent if `D::IS_ARCHETYPAL` is `true`.
557 fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {
558 let new_state = self.state.as_nop();
559 // SAFETY:
560 // - The reborrowed query is converted to read-only, so it cannot perform mutable access,
561 // and the original query is held with a shared borrow, so it cannot perform mutable access either.
562 // Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query,
563 // it has the original `QueryState::component_access` and could be `transmute`d to a read-only query.
564 // - The world matches because it was the same one used to construct self.
565 unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
566 }
567
568 /// Returns another `Query` from this that fetches the read-only version of the query items.
569 ///
570 /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
571 /// This can be useful when working around the borrow checker,
572 /// or reusing functionality between systems via functions that accept query types.
573 ///
574 /// # See also
575 ///
576 /// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.
577 pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {
578 let new_state = self.state.as_readonly();
579 // SAFETY:
580 // - This is memory safe because it turns the query immutable.
581 // - The world matches because it was the same one used to construct self.
582 unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
583 }
584
585 /// Returns a new `Query` reborrowing the access from this one. The current query will be unusable
586 /// while the new one exists.
587 ///
588 /// # Example
589 ///
590 /// For example this allows to call other methods or other systems that require an owned `Query` without
591 /// completely giving up ownership of it.
592 ///
593 /// ```
594 /// # use bevy_ecs::prelude::*;
595 /// #
596 /// # #[derive(Component)]
597 /// # struct ComponentA;
598 ///
599 /// fn helper_system(query: Query<&ComponentA>) { /* ... */}
600 ///
601 /// fn system(mut query: Query<&ComponentA>) {
602 /// helper_system(query.reborrow());
603 /// // Can still use query here:
604 /// for component in &query {
605 /// // ...
606 /// }
607 /// }
608 /// ```
609 pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {
610 // SAFETY: this query is exclusively borrowed while the new one exists, so
611 // no overlapping access can occur.
612 unsafe { self.reborrow_unsafe() }
613 }
614
615 /// Returns a new `Query` reborrowing the access from this one.
616 /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
617 ///
618 /// # Safety
619 ///
620 /// This function makes it possible to violate Rust's aliasing guarantees.
621 /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
622 ///
623 /// # See also
624 ///
625 /// - [`reborrow`](Self::reborrow) for the safe versions.
626 pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> {
627 // SAFETY:
628 // - This is memory safe because the caller ensures that there are no conflicting references.
629 // - The world matches because it was the same one used to construct self.
630 unsafe { self.copy_unsafe() }
631 }
632
633 /// Returns a new `Query` copying the access from this one.
634 /// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
635 ///
636 /// # Safety
637 ///
638 /// This function makes it possible to violate Rust's aliasing guarantees.
639 /// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
640 ///
641 /// # See also
642 ///
643 /// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.
644 unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> {
645 // SAFETY:
646 // - This is memory safe because the caller ensures that there are no conflicting references.
647 // - The world matches because it was the same one used to construct self.
648 unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }
649 }
650
651 /// Returns an [`Iterator`] over the read-only query items.
652 ///
653 /// This iterator is always guaranteed to return results from each matching entity once and only once.
654 /// Iteration order is not guaranteed.
655 ///
656 /// # Example
657 ///
658 /// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:
659 ///
660 /// ```
661 /// # use bevy_ecs::prelude::*;
662 /// #
663 /// # #[derive(Component)]
664 /// # struct Player { name: String }
665 /// #
666 /// fn report_names_system(query: Query<&Player>) {
667 /// for player in &query {
668 /// println!("Say hello to {}!", player.name);
669 /// }
670 /// }
671 /// # bevy_ecs::system::assert_is_system(report_names_system);
672 /// ```
673 ///
674 /// # See also
675 ///
676 /// [`iter_mut`](Self::iter_mut) for mutable query items.
677 #[inline]
678 pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {
679 self.as_readonly().into_iter()
680 }
681
682 /// Returns an [`Iterator`] over the query items.
683 ///
684 /// This iterator is always guaranteed to return results from each matching entity once and only once.
685 /// Iteration order is not guaranteed.
686 ///
687 /// If the [`QueryData`] does not implement [`IterQueryData`],
688 /// then it is not sound to yield multiple items concurrently
689 /// and the resulting [`QueryIter`] will not implement [`Iterator`].
690 /// To iterate over the items in that case,
691 /// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method,
692 /// which ensures only one item is alive at a time.
693 ///
694 /// # Example
695 ///
696 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
697 ///
698 /// ```
699 /// # use bevy_ecs::prelude::*;
700 /// #
701 /// # #[derive(Component)]
702 /// # struct Velocity { x: f32, y: f32, z: f32 }
703 /// fn gravity_system(mut query: Query<&mut Velocity>) {
704 /// const DELTA: f32 = 1.0 / 60.0;
705 /// for mut velocity in &mut query {
706 /// velocity.y -= 9.8 * DELTA;
707 /// }
708 /// }
709 /// # bevy_ecs::system::assert_is_system(gravity_system);
710 /// ```
711 ///
712 /// # See also
713 ///
714 /// [`iter`](Self::iter) for read-only query items.
715 #[inline]
716 pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {
717 self.reborrow().iter_inner()
718 }
719
720 /// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.
721 ///
722 /// This iterator is always guaranteed to return results from each matching entity once and only once.
723 /// Iteration order is not guaranteed.
724 ///
725 /// If the [`QueryData`] does not implement [`IterQueryData`],
726 /// then it is not sound to yield multiple items concurrently
727 /// and the resulting [`QueryIter`] will not implement [`Iterator`].
728 /// To iterate over the items in that case,
729 /// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method,
730 /// which ensures only one item is alive at a time.
731 ///
732 /// # Example
733 ///
734 /// Here, the `report_names_system` iterates over the `Player` component of every entity
735 /// that contains it:
736 ///
737 /// ```
738 /// # use bevy_ecs::prelude::*;
739 /// #
740 /// # #[derive(Component)]
741 /// # struct Player { name: String }
742 /// #
743 /// fn report_names_system(query: Query<&Player>) {
744 /// for player in &query {
745 /// println!("Say hello to {}!", player.name);
746 /// }
747 /// }
748 /// # bevy_ecs::system::assert_is_system(report_names_system);
749 /// ```
750 #[inline]
751 pub fn iter_inner(self) -> QueryIter<'w, 's, D, F> {
752 // SAFETY:
753 // - `self.world` has permission to access the required components.
754 // - We consume the query, so mutable queries cannot alias.
755 // Read-only queries are `Copy`, but may alias themselves.
756 unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }
757 }
758
759 /// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.
760 ///
761 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
762 /// Iteration order is not guaranteed.
763 ///
764 /// # Example
765 ///
766 /// ```
767 /// # use bevy_ecs::prelude::*;
768 /// # #[derive(Component)]
769 /// # struct ComponentA;
770 /// #
771 /// fn some_system(query: Query<&ComponentA>) {
772 /// for [a1, a2] in query.iter_combinations() {
773 /// // ...
774 /// }
775 /// }
776 /// ```
777 ///
778 /// # See also
779 ///
780 /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
781 /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
782 #[inline]
783 pub fn iter_combinations<const K: usize>(
784 &self,
785 ) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {
786 self.as_readonly().iter_combinations_inner()
787 }
788
789 /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
790 ///
791 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
792 /// Iteration order is not guaranteed.
793 ///
794 /// # Example
795 ///
796 /// ```
797 /// # use bevy_ecs::prelude::*;
798 /// # #[derive(Component)]
799 /// # struct ComponentA;
800 /// fn some_system(mut query: Query<&mut ComponentA>) {
801 /// let mut combinations = query.iter_combinations_mut();
802 /// while let Some([mut a1, mut a2]) = combinations.fetch_next() {
803 /// // mutably access components data
804 /// }
805 /// }
806 /// ```
807 ///
808 /// # See also
809 ///
810 /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
811 /// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
812 #[inline]
813 pub fn iter_combinations_mut<const K: usize>(&mut self) -> QueryCombinationIter<'_, 's, D, F, K>
814 where
815 D: IterQueryData,
816 {
817 self.reborrow().iter_combinations_inner()
818 }
819
820 /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
821 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
822 ///
823 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
824 /// Iteration order is not guaranteed.
825 ///
826 /// # Example
827 ///
828 /// ```
829 /// # use bevy_ecs::prelude::*;
830 /// # #[derive(Component)]
831 /// # struct ComponentA;
832 /// fn some_system(query: Query<&mut ComponentA>) {
833 /// let mut combinations = query.iter_combinations_inner();
834 /// while let Some([mut a1, mut a2]) = combinations.fetch_next() {
835 /// // mutably access components data
836 /// }
837 /// }
838 /// ```
839 ///
840 /// # See also
841 ///
842 /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
843 /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
844 #[inline]
845 pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K>
846 where
847 D: IterQueryData,
848 {
849 // SAFETY: `self.world` has permission to access the required components.
850 unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }
851 }
852
853 /// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
854 ///
855 /// Items are returned in the order of the list of entities, and may not be unique if the input
856 /// doesn't guarantee uniqueness.
857 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
858 ///
859 /// # Examples
860 ///
861 /// ```
862 /// # use bevy_ecs::prelude::*;
863 /// # #[derive(Component)]
864 /// # struct Counter {
865 /// # value: i32
866 /// # }
867 /// #
868 /// // A component containing an entity list.
869 /// #[derive(Component)]
870 /// struct Friends {
871 /// list: Vec<Entity>,
872 /// }
873 ///
874 /// fn matching_system(
875 /// friends_query: Query<&Friends>,
876 /// counter_query: Query<&Counter>,
877 /// ) {
878 /// for friends in &friends_query {
879 /// for counter in counter_query.iter_many(&friends.list).matched() {
880 /// println!("Friend's counter: {}", counter.value);
881 /// }
882 /// }
883 /// }
884 ///
885 /// fn unwrapping_system(
886 /// friends_query: Query<&Friends>,
887 /// counter_query: Query<&Counter>,
888 /// ) {
889 /// for friends in &friends_query {
890 /// for counter in counter_query.iter_many(&friends.list).unwrapped() {
891 /// println!("Friend's counter: {}", counter.value);
892 /// }
893 /// }
894 /// }
895 ///
896 /// fn error_system(
897 /// friends_query: Query<&Friends>,
898 /// counter_query: Query<&Counter>,
899 /// ) -> Result<(), BevyError> {
900 /// for friends in &friends_query {
901 /// for counter_result in counter_query.iter_many(&friends.list) {
902 /// let counter = counter_result?;
903 /// println!("Friend's counter: {}", counter.value);
904 /// }
905 /// }
906 /// Ok(())
907 /// }
908 /// # bevy_ecs::system::assert_is_system(matching_system);
909 /// # bevy_ecs::system::assert_is_system(unwrapping_system);
910 /// # bevy_ecs::system::assert_is_system::<(), Result<(), BevyError>, _>(error_system);
911 /// ```
912 ///
913 /// # See also
914 ///
915 /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
916 /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
917 #[inline]
918 pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
919 &self,
920 entities: EntityList,
921 ) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
922 self.as_readonly().iter_many_inner(entities)
923 }
924
925 /// Returns an iterator over the query items generated from an [`Entity`] list.
926 ///
927 /// Items are returned in the order of the list of entities, and may not be unique if the input
928 /// doesn't guarantee uniqueness.
929 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
930 ///
931 /// # Examples
932 ///
933 /// ```
934 /// # use bevy_ecs::prelude::*;
935 /// #[derive(Component)]
936 /// struct Counter {
937 /// value: i32
938 /// }
939 ///
940 /// #[derive(Component)]
941 /// struct Friends {
942 /// list: Vec<Entity>,
943 /// }
944 ///
945 /// fn system(
946 /// friends_query: Query<&Friends>,
947 /// mut counter_query: Query<&mut Counter>,
948 /// ) {
949 /// for friends in &friends_query {
950 /// let mut iter = counter_query.iter_many_mut(&friends.list).matched();
951 /// while let Some(mut counter) = iter.fetch_next() {
952 /// println!("Friend's counter: {}", counter.value);
953 /// counter.value += 1;
954 /// }
955 /// }
956 /// }
957 /// # bevy_ecs::system::assert_is_system(system);
958 /// ```
959 /// # See also
960 ///
961 /// - [`iter_many`](Self::iter_many) to get read-only query items.
962 /// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
963 #[inline]
964 pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(
965 &mut self,
966 entities: EntityList,
967 ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
968 self.reborrow().iter_many_inner(entities)
969 }
970
971 /// Returns an iterator over the query items generated from an [`Entity`] list.
972 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
973 ///
974 /// Items are returned in the order of the list of entities, and may not be unique if the input
975 /// doesn't guarantee uniqueness.
976 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
977 ///
978 /// # See also
979 ///
980 /// - [`iter_many`](Self::iter_many) to get read-only query items.
981 /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
982 #[inline]
983 pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(
984 self,
985 entities: EntityList,
986 ) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {
987 // SAFETY: `self.world` has permission to access the required components.
988 unsafe {
989 QueryManyIter::new(
990 self.world,
991 self.state,
992 entities,
993 self.last_run,
994 self.this_run,
995 )
996 }
997 }
998
999 /// Returns an [`Iterator`] over the unique read-only query items generated from an [`EntitySet`].
1000 ///
1001 /// Items are returned in the order of the list of entities.
1002 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1003 ///
1004 /// # Example
1005 ///
1006 /// ```
1007 /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1008 /// # use core::slice;
1009 /// # #[derive(Component)]
1010 /// # struct Counter {
1011 /// # value: i32
1012 /// # }
1013 /// #
1014 /// // `Friends` ensures that it only lists unique entities.
1015 /// #[derive(Component)]
1016 /// struct Friends {
1017 /// unique_list: Vec<Entity>,
1018 /// }
1019 ///
1020 /// impl<'a> IntoIterator for &'a Friends {
1021 ///
1022 /// type Item = &'a Entity;
1023 /// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1024 ///
1025 /// fn into_iter(self) -> Self::IntoIter {
1026 /// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1027 /// unsafe { UniqueEntityIter::from_iter_unchecked(self.unique_list.iter()) }
1028 /// }
1029 /// }
1030 ///
1031 /// fn system(
1032 /// friends_query: Query<&Friends>,
1033 /// counter_query: Query<&Counter>,
1034 /// ) {
1035 /// for friends in &friends_query {
1036 /// for counter in counter_query.iter_many_unique(friends).matched() {
1037 /// println!("Friend's counter: {:?}", counter.value);
1038 /// }
1039 /// }
1040 /// }
1041 /// # bevy_ecs::system::assert_is_system(system);
1042 /// ```
1043 ///
1044 /// # See also
1045 ///
1046 /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1047 /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1048 #[inline]
1049 pub fn iter_many_unique<EntityList: EntitySet>(
1050 &self,
1051 entities: EntityList,
1052 ) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
1053 self.as_readonly().iter_many_unique_inner(entities)
1054 }
1055
1056 /// Returns an iterator over the unique query items generated from an [`EntitySet`].
1057 ///
1058 /// Items are returned in the order of the list of entities.
1059 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1060 ///
1061 /// # Examples
1062 ///
1063 /// ```
1064 /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1065 /// # use core::slice;
1066 /// #[derive(Component)]
1067 /// struct Counter {
1068 /// value: i32
1069 /// }
1070 ///
1071 /// // `Friends` ensures that it only lists unique entities.
1072 /// #[derive(Component)]
1073 /// struct Friends {
1074 /// unique_list: Vec<Entity>,
1075 /// }
1076 ///
1077 /// impl<'a> IntoIterator for &'a Friends {
1078 /// type Item = &'a Entity;
1079 /// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1080 ///
1081 /// fn into_iter(self) -> Self::IntoIter {
1082 /// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1083 /// unsafe { UniqueEntityIter::from_iter_unchecked(self.unique_list.iter()) }
1084 /// }
1085 /// }
1086 ///
1087 /// fn system(
1088 /// friends_query: Query<&Friends>,
1089 /// mut counter_query: Query<&mut Counter>,
1090 /// ) {
1091 /// for friends in &friends_query {
1092 /// for mut counter in counter_query.iter_many_unique_mut(friends).matched() {
1093 /// println!("Friend's counter: {:?}", counter.value);
1094 /// counter.value += 1;
1095 /// }
1096 /// }
1097 /// }
1098 /// # bevy_ecs::system::assert_is_system(system);
1099 /// ```
1100 /// # See also
1101 ///
1102 /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1103 /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1104 #[inline]
1105 pub fn iter_many_unique_mut<EntityList: EntitySet>(
1106 &mut self,
1107 entities: EntityList,
1108 ) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter>
1109 where
1110 D: IterQueryData,
1111 {
1112 self.reborrow().iter_many_unique_inner(entities)
1113 }
1114
1115 /// Returns an iterator over the unique query items generated from an [`EntitySet`].
1116 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1117 ///
1118 /// Items are returned in the order of the list of entities.
1119 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1120 ///
1121 /// # Examples
1122 ///
1123 /// ```
1124 /// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1125 /// # use core::slice;
1126 /// #[derive(Component)]
1127 /// struct Counter {
1128 /// value: i32
1129 /// }
1130 ///
1131 /// // `Friends` ensures that it only lists unique entities.
1132 /// #[derive(Component)]
1133 /// struct Friends {
1134 /// unique_list: Vec<Entity>,
1135 /// }
1136 ///
1137 /// impl<'a> IntoIterator for &'a Friends {
1138 /// type Item = &'a Entity;
1139 /// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1140 ///
1141 /// fn into_iter(self) -> Self::IntoIter {
1142 /// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1143 /// unsafe { UniqueEntityIter::from_iter_unchecked(self.unique_list.iter()) }
1144 /// }
1145 /// }
1146 ///
1147 /// fn system(
1148 /// friends_query: Query<&Friends>,
1149 /// mut counter_query: Query<&mut Counter>,
1150 /// ) {
1151 /// let friends = friends_query.single().unwrap();
1152 /// for mut counter in counter_query.iter_many_unique_inner(friends).matched() {
1153 /// println!("Friend's counter: {:?}", counter.value);
1154 /// counter.value += 1;
1155 /// }
1156 /// }
1157 /// # bevy_ecs::system::assert_is_system(system);
1158 /// ```
1159 /// # See also
1160 ///
1161 /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1162 /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1163 #[inline]
1164 pub fn iter_many_unique_inner<EntityList: EntitySet>(
1165 self,
1166 entities: EntityList,
1167 ) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter>
1168 where
1169 D: IterQueryData,
1170 {
1171 // SAFETY: `self.world` has permission to access the required components.
1172 unsafe {
1173 QueryManyUniqueIter::new(
1174 self.world,
1175 self.state,
1176 entities,
1177 self.last_run,
1178 self.this_run,
1179 )
1180 }
1181 }
1182
1183 /// Returns an [`Iterator`] over the query items.
1184 ///
1185 /// This iterator is always guaranteed to return results from each matching entity once and only once.
1186 /// Iteration order is not guaranteed.
1187 ///
1188 /// If the [`QueryData`] does not implement [`IterQueryData`],
1189 /// then it is not sound to yield multiple items concurrently
1190 /// and the resulting [`QueryIter`] will not implement [`Iterator`].
1191 /// To iterate over the items in that case,
1192 /// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method,
1193 /// which ensures only one item is alive at a time.
1194 ///
1195 /// # Safety
1196 ///
1197 /// This function makes it possible to violate Rust's aliasing guarantees.
1198 /// You must make sure this call does not result in multiple mutable references to the same component.
1199 ///
1200 /// # See also
1201 ///
1202 /// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.
1203 #[inline]
1204 pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F>
1205 where
1206 D: IterQueryData,
1207 {
1208 // SAFETY: The caller promises that this will not result in multiple mutable references.
1209 unsafe { self.reborrow_unsafe() }.into_iter()
1210 }
1211
1212 /// Iterates over all possible combinations of `K` query items without repetition.
1213 ///
1214 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
1215 /// Iteration order is not guaranteed.
1216 ///
1217 /// # Safety
1218 ///
1219 /// This allows aliased mutability.
1220 /// You must make sure this call does not result in multiple mutable references to the same component.
1221 ///
1222 /// # See also
1223 ///
1224 /// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.
1225 #[inline]
1226 pub unsafe fn iter_combinations_unsafe<const K: usize>(
1227 &self,
1228 ) -> QueryCombinationIter<'_, 's, D, F, K>
1229 where
1230 D: IterQueryData,
1231 {
1232 // SAFETY: The caller promises that this will not result in multiple mutable references.
1233 unsafe { self.reborrow_unsafe() }.iter_combinations_inner()
1234 }
1235
1236 /// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.
1237 ///
1238 /// Items are returned in the order of the list of entities, and may not be unique if the input
1239 /// doesnn't guarantee uniqueness.
1240 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1241 ///
1242 /// # Safety
1243 ///
1244 /// This allows aliased mutability and does not check for entity uniqueness.
1245 /// You must make sure this call does not result in multiple mutable references to the same component.
1246 /// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].
1247 ///
1248 /// # See also
1249 ///
1250 /// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.
1251 pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(
1252 &self,
1253 entities: EntityList,
1254 ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
1255 // SAFETY: The caller promises that this will not result in multiple mutable references.
1256 unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)
1257 }
1258
1259 /// Returns an [`Iterator`] over the unique query items generated from an [`Entity`] list.
1260 ///
1261 /// Items are returned in the order of the list of entities.
1262 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1263 ///
1264 /// # Safety
1265 ///
1266 /// This allows aliased mutability.
1267 /// You must make sure this call does not result in multiple mutable references to the same component.
1268 ///
1269 /// # See also
1270 ///
1271 /// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1272 /// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1273 /// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1274 pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(
1275 &self,
1276 entities: EntityList,
1277 ) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter>
1278 where
1279 D: IterQueryData,
1280 {
1281 // SAFETY: The caller promises that this will not result in multiple mutable references.
1282 unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)
1283 }
1284
1285 /// Returns a parallel iterator over the query results for the given [`World`].
1286 ///
1287 /// This parallel iterator is always guaranteed to return results from each matching entity once and
1288 /// only once. Iteration order and thread assignment is not guaranteed.
1289 ///
1290 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1291 /// on [`QueryIter`].
1292 ///
1293 /// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
1294 ///
1295 /// Note that you must use the `for_each` method to iterate over the
1296 /// results, see [`par_iter_mut`] for an example.
1297 ///
1298 /// [`par_iter_mut`]: Self::par_iter_mut
1299 /// [`World`]: crate::world::World
1300 #[inline]
1301 pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {
1302 self.as_readonly().par_iter_inner()
1303 }
1304
1305 /// Returns a parallel iterator over the query results for the given [`World`].
1306 ///
1307 /// This parallel iterator is always guaranteed to return results from each matching entity once and
1308 /// only once. Iteration order and thread assignment is not guaranteed.
1309 ///
1310 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1311 /// on [`QueryIter`].
1312 ///
1313 /// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
1314 ///
1315 /// # Example
1316 ///
1317 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1318 ///
1319 /// ```
1320 /// # use bevy_ecs::prelude::*;
1321 /// #
1322 /// # #[derive(Component)]
1323 /// # struct Velocity { x: f32, y: f32, z: f32 }
1324 /// fn gravity_system(mut query: Query<&mut Velocity>) {
1325 /// const DELTA: f32 = 1.0 / 60.0;
1326 /// query.par_iter_mut().for_each(|mut velocity| {
1327 /// velocity.y -= 9.8 * DELTA;
1328 /// });
1329 /// }
1330 /// # bevy_ecs::system::assert_is_system(gravity_system);
1331 /// ```
1332 ///
1333 /// [`par_iter`]: Self::par_iter
1334 /// [`World`]: crate::world::World
1335 #[inline]
1336 pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F>
1337 where
1338 D: IterQueryData,
1339 {
1340 self.reborrow().par_iter_inner()
1341 }
1342
1343 /// Returns a parallel iterator over the query results for the given [`World`](crate::world::World).
1344 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1345 ///
1346 /// This parallel iterator is always guaranteed to return results from each matching entity once and
1347 /// only once. Iteration order and thread assignment is not guaranteed.
1348 ///
1349 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1350 /// on [`QueryIter`].
1351 ///
1352 /// # Example
1353 ///
1354 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1355 ///
1356 /// ```
1357 /// # use bevy_ecs::prelude::*;
1358 /// #
1359 /// # #[derive(Component)]
1360 /// # struct Velocity { x: f32, y: f32, z: f32 }
1361 /// fn gravity_system(query: Query<&mut Velocity>) {
1362 /// const DELTA: f32 = 1.0 / 60.0;
1363 /// query.par_iter_inner().for_each(|mut velocity| {
1364 /// velocity.y -= 9.8 * DELTA;
1365 /// });
1366 /// }
1367 /// # bevy_ecs::system::assert_is_system(gravity_system);
1368 /// ```
1369 #[inline]
1370 pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F>
1371 where
1372 D: IterQueryData,
1373 {
1374 QueryParIter {
1375 world: self.world,
1376 state: self.state,
1377 last_run: self.last_run,
1378 this_run: self.this_run,
1379 batching_strategy: BatchingStrategy::new(),
1380 }
1381 }
1382
1383 /// Returns a parallel iterator over the read-only query items generated from an [`Entity`] list.
1384 ///
1385 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1386 /// Iteration order and thread assignment is not guaranteed.
1387 ///
1388 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1389 /// on [`QueryManyIter`].
1390 ///
1391 /// This can only be called for read-only queries. To avoid potential aliasing, there is no `par_iter_many_mut` equivalent.
1392 /// See [`par_iter_many_unique_mut`] for an alternative using [`EntitySet`].
1393 ///
1394 /// Note that you must use the `for_each` method to iterate over the
1395 /// results, see [`par_iter_mut`] for an example.
1396 ///
1397 /// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1398 /// [`par_iter_mut`]: Self::par_iter_mut
1399 #[inline]
1400 pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
1401 &self,
1402 entities: EntityList,
1403 ) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1404 QueryParManyIter {
1405 world: self.world,
1406 state: self.state.as_readonly(),
1407 entity_list: entities.into_iter().collect(),
1408 last_run: self.last_run,
1409 this_run: self.this_run,
1410 batching_strategy: BatchingStrategy::new(),
1411 }
1412 }
1413
1414 /// Returns a parallel iterator over the unique read-only query items generated from an [`EntitySet`].
1415 ///
1416 /// Iteration order and thread assignment is not guaranteed.
1417 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1418 ///
1419 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1420 /// on [`QueryManyUniqueIter`].
1421 ///
1422 /// This can only be called for read-only queries, see [`par_iter_many_unique_mut`] for write-queries.
1423 ///
1424 /// Note that you must use the `for_each` method to iterate over the
1425 /// results, see [`par_iter_mut`] for an example.
1426 ///
1427 /// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1428 /// [`par_iter_mut`]: Self::par_iter_mut
1429 #[inline]
1430 pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(
1431 &self,
1432 entities: EntityList,
1433 ) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1434 QueryParManyUniqueIter {
1435 world: self.world,
1436 state: self.state.as_readonly(),
1437 entity_list: entities.into_iter().collect(),
1438 last_run: self.last_run,
1439 this_run: self.this_run,
1440 batching_strategy: BatchingStrategy::new(),
1441 }
1442 }
1443
1444 /// Returns a parallel iterator over the unique query items generated from an [`EntitySet`].
1445 ///
1446 /// Iteration order and thread assignment is not guaranteed.
1447 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is generated instead.
1448 ///
1449 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1450 /// on [`QueryManyUniqueIter`].
1451 ///
1452 /// This can only be called for mutable queries, see [`par_iter_many_unique`] for read-only-queries.
1453 ///
1454 /// Note that you must use the `for_each` method to iterate over the
1455 /// results, see [`par_iter_mut`] for an example.
1456 ///
1457 /// [`par_iter_many_unique`]: Self::par_iter_many_unique
1458 /// [`par_iter_mut`]: Self::par_iter_mut
1459 #[inline]
1460 pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(
1461 &mut self,
1462 entities: EntityList,
1463 ) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item>
1464 where
1465 D: IterQueryData,
1466 {
1467 QueryParManyUniqueIter {
1468 world: self.world,
1469 state: self.state,
1470 entity_list: entities.into_iter().collect(),
1471 last_run: self.last_run,
1472 this_run: self.this_run,
1473 batching_strategy: BatchingStrategy::new(),
1474 }
1475 }
1476
1477 /// Returns a contiguous iterator over the query results for the given
1478 /// [`World`](crate::world::World) or [`Err`] with [`QueryNotDenseError`] if the query is not dense hence not contiguously
1479 /// iterable.
1480 ///
1481 /// Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example
1482 /// may be used for simd-operations, which may accelerate an algorithm.
1483 ///
1484 /// # Example
1485 ///
1486 /// The following system despawns all entities which health is negative.
1487 ///
1488 /// ```
1489 /// # use bevy_ecs::prelude::*;
1490 /// #
1491 /// # #[derive(Component)]
1492 /// # struct Health(pub f32);
1493 ///
1494 /// fn despawn_all_dead_entities(mut commands: Commands, query: Query<(Entity, &Health)>) {
1495 /// for (entities, health) in query.contiguous_iter().unwrap() {
1496 /// // For each entity there is one component, hence it always holds true
1497 /// assert!(entities.len() == health.len());
1498 /// for (entity, health) in entities.iter().zip(health.iter()) {
1499 /// if health.0 < 0.0 {
1500 /// commands.entity(*entity).despawn();
1501 /// }
1502 /// }
1503 /// }
1504 /// }
1505 ///
1506 /// ```
1507 ///
1508 /// A mutable version: [`Self::contiguous_iter_mut`]
1509 pub fn contiguous_iter(
1510 &self,
1511 ) -> Result<QueryContiguousIter<'_, 's, D::ReadOnly, F>, QueryNotDenseError>
1512 where
1513 D::ReadOnly: ContiguousQueryData,
1514 F: ArchetypeFilter,
1515 {
1516 self.as_readonly().contiguous_iter_inner()
1517 }
1518
1519 /// Returns a mutable contiguous iterator over the query results for the given
1520 /// [`World`](crate::world::World) or [`Err`] with [`QueryNotDenseError`] if the query is not dense hence not contiguously
1521 /// iterable.
1522 ///
1523 /// Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example
1524 /// may be used for simd-operations, which may accelerate an algorithm.
1525 ///
1526 /// # Example
1527 ///
1528 /// The following system applies a "health decay" effect on all entities, which reduces their
1529 /// health by some fraction.
1530 ///
1531 /// ```
1532 /// # use bevy_ecs::prelude::*;
1533 /// #
1534 /// # #[derive(Component)]
1535 /// # struct Health(pub f32);
1536 /// #
1537 /// # #[derive(Component)]
1538 /// # struct HealthDecay(pub f32);
1539 ///
1540 /// fn apply_health_decay(mut query: Query<(&mut Health, &HealthDecay)>) {
1541 /// for (mut health, decay) in query.contiguous_iter_mut().unwrap() {
1542 /// // all data slices returned by component queries are the same size
1543 /// assert!(health.len() == decay.len());
1544 /// // we could have used health.bypass_change_detection() to do less work.
1545 /// for (health, decay) in health.iter_mut().zip(decay) {
1546 /// health.0 *= decay.0;
1547 /// }
1548 /// }
1549 /// }
1550 /// ```
1551 /// An immutable version: [`Self::contiguous_iter`]
1552 pub fn contiguous_iter_mut(
1553 &mut self,
1554 ) -> Result<QueryContiguousIter<'_, 's, D, F>, QueryNotDenseError>
1555 where
1556 D: ContiguousQueryData,
1557 F: ArchetypeFilter,
1558 {
1559 self.reborrow().contiguous_iter_inner()
1560 }
1561
1562 /// Returns a contiguous iterator over the query results for the given
1563 /// [`World`](crate::world::World) or [`Err`] with [`QueryNotDenseError`] if the query is not dense hence not contiguously
1564 /// iterable.
1565 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1566 pub fn contiguous_iter_inner(
1567 self,
1568 ) -> Result<QueryContiguousIter<'w, 's, D, F>, QueryNotDenseError>
1569 where
1570 D: ContiguousQueryData,
1571 F: ArchetypeFilter,
1572 {
1573 // SAFETY:
1574 // - `self.world` has permission to access the required components
1575 // - `self.world` was used to initialize `self.state`
1576 unsafe { QueryContiguousIter::new(self.world, self.state, self.last_run, self.this_run) }
1577 .ok_or(QueryNotDenseError(DebugName::type_name::<Self>()))
1578 }
1579
1580 /// Returns a parallel iterator over contiguous query results for the given
1581 /// [`World`].
1582 ///
1583 /// Contiguous iteration enables getting slices of contiguously laid out
1584 /// components that reside in the same table. These slices may for example
1585 /// be used for SIMD operations.
1586 ///
1587 /// This parallel iterator is always guaranteed to return results from each
1588 /// matching entity once and only once. Iteration order and thread
1589 /// assignment is not guaranteed.
1590 ///
1591 /// If the query isn't contiguously iterable because it isn't dense, this
1592 /// method returns a [`QueryNotDenseError`].
1593 ///
1594 /// If the `multithreaded` feature is disabled, iterating with this operates
1595 /// identically to [`Iterator::for_each`] on [`QueryContiguousIter`].
1596 ///
1597 /// This can only be called for read-only queries. For queries that may
1598 /// write to the components they query, see [`Self::par_iter_mut`].
1599 ///
1600 /// Note that you must use the `for_each` method to iterate over the
1601 /// results. See [`Self::contiguous_par_iter_mut`] for an example.
1602 ///
1603 /// [`World`]: crate::world::World
1604 pub fn contiguous_par_iter(
1605 &self,
1606 ) -> Result<QueryContiguousParIter<'_, 's, D::ReadOnly, F>, QueryNotDenseError>
1607 where
1608 D::ReadOnly: ContiguousQueryData,
1609 F: ArchetypeFilter,
1610 {
1611 self.as_readonly().contiguous_par_iter_inner()
1612 }
1613
1614 /// Returns a parallel iterator over contiguous query results for the given
1615 /// [`World`].
1616 ///
1617 /// Contiguous iteration enables getting slices of contiguously laid out
1618 /// components that reside in the same table. These slices may for example
1619 /// be used for SIMD operations.
1620 ///
1621 /// This parallel contiguous iterator is always guaranteed to return results
1622 /// from each matching entity once and only once. Iteration order and thread
1623 /// assignment is not guaranteed.
1624 ///
1625 /// If the `multithreaded` feature is disabled, iterating with this operates
1626 /// identically to [`Iterator::for_each`] on [`QueryContiguousIter`].
1627 ///
1628 /// This can only be called for mutable queries. See [`par_iter`] for
1629 /// read-only queries.
1630 ///
1631 /// # Example
1632 ///
1633 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1634 ///
1635 /// ```
1636 /// # use bevy_ecs::prelude::*;
1637 /// #
1638 /// # #[derive(Component)]
1639 /// # struct Velocity { x: f32, y: f32, z: f32 }
1640 /// fn gravity_system(mut query: Query<&mut Velocity>) {
1641 /// const DELTA: f32 = 1.0 / 60.0;
1642 /// query.contiguous_par_iter_mut().unwrap().for_each(|mut velocities| {
1643 /// for mut velocity in velocities {
1644 /// velocity.y -= 9.8 * DELTA;
1645 /// }
1646 /// });
1647 /// }
1648 /// # bevy_ecs::system::assert_is_system(gravity_system);
1649 /// ```
1650 ///
1651 /// [`par_iter`]: Self::par_iter
1652 /// [`World`]: crate::world::World
1653 pub fn contiguous_par_iter_mut(
1654 &mut self,
1655 ) -> Result<QueryContiguousParIter<'_, 's, D, F>, QueryNotDenseError>
1656 where
1657 D: ContiguousQueryData,
1658 F: ArchetypeFilter,
1659 {
1660 self.reborrow().contiguous_par_iter_inner()
1661 }
1662
1663 /// Returns a parallel iterator over contiguous query results for the given
1664 /// [`World`](crate::world::World). This consumes the [`Query`] to return
1665 /// results with the actual "inner" world lifetime.
1666 ///
1667 /// Contiguous iteration enables getting slices of contiguously laid out
1668 /// components that reside in the same table. These slices may for example
1669 /// be used for SIMD operations.
1670 ///
1671 /// This parallel iterator is always guaranteed to return results from each
1672 /// matching entity once and only once. Iteration order and thread
1673 /// assignment is not guaranteed.
1674 ///
1675 /// If the `multithreaded` feature is disabled, iterating with this operates
1676 /// identically to [`Iterator::for_each`] on [`QueryContiguousIter`].
1677 pub fn contiguous_par_iter_inner(
1678 self,
1679 ) -> Result<QueryContiguousParIter<'w, 's, D, F>, QueryNotDenseError>
1680 where
1681 D: ContiguousQueryData,
1682 F: ArchetypeFilter,
1683 {
1684 QueryContiguousParIter::new(self.world, self.state, self.last_run, self.this_run)
1685 .ok_or(QueryNotDenseError(DebugName::type_name::<Self>()))
1686 }
1687
1688 /// Returns the read-only query item for the given [`Entity`].
1689 ///
1690 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1691 ///
1692 /// This is always guaranteed to run in `O(1)` time.
1693 ///
1694 /// # Example
1695 ///
1696 /// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.
1697 ///
1698 /// ```
1699 /// # use bevy_ecs::prelude::*;
1700 /// #
1701 /// # #[derive(Resource)]
1702 /// # struct SelectedCharacter { entity: Entity }
1703 /// # #[derive(Component)]
1704 /// # struct Character { name: String }
1705 /// #
1706 /// fn print_selected_character_name_system(
1707 /// query: Query<&Character>,
1708 /// selection: Res<SelectedCharacter>
1709 /// )
1710 /// {
1711 /// if let Ok(selected_character) = query.get(selection.entity) {
1712 /// println!("{}", selected_character.name);
1713 /// }
1714 /// }
1715 /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
1716 /// ```
1717 ///
1718 /// # See also
1719 ///
1720 /// - [`get_mut`](Self::get_mut) to get a mutable query item.
1721 #[inline]
1722 pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {
1723 self.as_readonly().get_inner(entity)
1724 }
1725
1726 /// Returns the read-only query items for the given array of [`Entity`].
1727 ///
1728 /// The returned query items are in the same order as the input.
1729 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1730 /// The elements of the array do not need to be unique, unlike `get_many_mut`.
1731 ///
1732 /// # Examples
1733 ///
1734 /// ```
1735 /// use bevy_ecs::prelude::*;
1736 /// use bevy_ecs::query::QueryEntityError;
1737 ///
1738 /// #[derive(Component, PartialEq, Debug)]
1739 /// struct A(usize);
1740 ///
1741 /// let mut world = World::new();
1742 /// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1743 /// let entities: [Entity; 3] = entity_vec.try_into().unwrap();
1744 ///
1745 /// world.spawn(A(73));
1746 ///
1747 /// let mut query_state = world.query::<&A>();
1748 /// let query = query_state.query(&world);
1749 ///
1750 /// let component_values = query.get_many(entities).unwrap();
1751 ///
1752 /// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1753 ///
1754 /// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1755 ///
1756 /// assert_eq!(
1757 /// match query.get_many([wrong_entity]).unwrap_err() {
1758 /// QueryEntityError::NotSpawned(error) => error.entity(),
1759 /// _ => panic!(),
1760 /// },
1761 /// wrong_entity
1762 /// );
1763 /// ```
1764 ///
1765 /// # See also
1766 ///
1767 /// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.
1768 /// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.
1769 #[inline]
1770 pub fn get_many<const N: usize>(
1771 &self,
1772 entities: [Entity; N],
1773 ) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1774 // Note that we call a separate `*_inner` method from `get_many_mut`
1775 // because we don't need to check for duplicates.
1776 self.as_readonly().get_many_inner(entities)
1777 }
1778
1779 /// Returns the read-only query items for the given [`UniqueEntityArray`].
1780 ///
1781 /// The returned query items are in the same order as the input.
1782 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1783 ///
1784 /// # Examples
1785 ///
1786 /// ```
1787 /// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1788 ///
1789 /// #[derive(Component, PartialEq, Debug)]
1790 /// struct A(usize);
1791 ///
1792 /// let mut world = World::new();
1793 /// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1794 /// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1795 ///
1796 /// world.spawn(A(73));
1797 ///
1798 /// let mut query_state = world.query::<&A>();
1799 /// let query = query_state.query(&world);
1800 ///
1801 /// let component_values = query.get_many_unique(entity_set).unwrap();
1802 ///
1803 /// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1804 ///
1805 /// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1806 ///
1807 /// assert_eq!(
1808 /// match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {
1809 /// QueryEntityError::NotSpawned(error) => error.entity(),
1810 /// _ => panic!(),
1811 /// },
1812 /// wrong_entity
1813 /// );
1814 /// ```
1815 ///
1816 /// # See also
1817 ///
1818 /// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.
1819 /// - [`get_many`](Self::get_many) to handle inputs with duplicates.
1820 #[inline]
1821 pub fn get_many_unique<const N: usize>(
1822 &self,
1823 entities: UniqueEntityArray<N>,
1824 ) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1825 self.as_readonly().get_many_unique_inner(entities)
1826 }
1827
1828 /// Returns the query item for the given [`Entity`].
1829 ///
1830 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1831 ///
1832 /// This is always guaranteed to run in `O(1)` time.
1833 ///
1834 /// # Example
1835 ///
1836 /// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.
1837 ///
1838 /// ```
1839 /// # use bevy_ecs::prelude::*;
1840 /// #
1841 /// # #[derive(Resource)]
1842 /// # struct PoisonedCharacter { character_id: Entity }
1843 /// # #[derive(Component)]
1844 /// # struct Health(u32);
1845 /// #
1846 /// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
1847 /// if let Ok(mut health) = query.get_mut(poisoned.character_id) {
1848 /// health.0 -= 1;
1849 /// }
1850 /// }
1851 /// # bevy_ecs::system::assert_is_system(poison_system);
1852 /// ```
1853 ///
1854 /// # See also
1855 ///
1856 /// - [`get`](Self::get) to get a read-only query item.
1857 #[inline]
1858 pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {
1859 self.reborrow().get_inner(entity)
1860 }
1861
1862 /// Returns the query item for the given [`Entity`].
1863 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1864 ///
1865 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1866 ///
1867 /// This is always guaranteed to run in `O(1)` time.
1868 ///
1869 /// # See also
1870 ///
1871 /// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].
1872 #[inline]
1873 pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {
1874 // SAFETY: system runs without conflicts with other systems.
1875 // same-system queries have runtime borrow checks when they conflict
1876 unsafe {
1877 let location = self.world.entities().get_spawned(entity)?;
1878 if !self
1879 .state
1880 .matched_archetypes
1881 .contains(location.archetype_id.index())
1882 {
1883 return Err(QueryEntityError::QueryDoesNotMatch(
1884 entity,
1885 location.archetype_id,
1886 ));
1887 }
1888 let archetype = self
1889 .world
1890 .archetypes()
1891 .get(location.archetype_id)
1892 .debug_checked_unwrap();
1893 let mut fetch = D::init_fetch(
1894 self.world,
1895 &self.state.fetch_state,
1896 self.last_run,
1897 self.this_run,
1898 );
1899 let mut filter = F::init_fetch(
1900 self.world,
1901 &self.state.filter_state,
1902 self.last_run,
1903 self.this_run,
1904 );
1905
1906 let table = self
1907 .world
1908 .storages()
1909 .tables
1910 .get(location.table_id)
1911 .debug_checked_unwrap();
1912 D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);
1913 F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);
1914
1915 if F::filter_fetch(
1916 &self.state.filter_state,
1917 &mut filter,
1918 entity,
1919 location.table_row,
1920 ) && let Some(item) = D::fetch(
1921 &self.state.fetch_state,
1922 &mut fetch,
1923 entity,
1924 location.table_row,
1925 ) {
1926 Ok(item)
1927 } else {
1928 Err(QueryEntityError::QueryDoesNotMatch(
1929 entity,
1930 location.archetype_id,
1931 ))
1932 }
1933 }
1934 }
1935
1936 /// Returns the query items for the given array of [`Entity`].
1937 ///
1938 /// The returned query items are in the same order as the input.
1939 /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1940 ///
1941 /// # Examples
1942 ///
1943 /// ```
1944 /// use bevy_ecs::prelude::*;
1945 /// use bevy_ecs::query::QueryEntityError;
1946 ///
1947 /// #[derive(Component, PartialEq, Debug)]
1948 /// struct A(usize);
1949 ///
1950 /// let mut world = World::new();
1951 ///
1952 /// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1953 /// let entities: [Entity; 3] = entities.try_into().unwrap();
1954 ///
1955 /// world.spawn(A(73));
1956 /// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1957 /// let invalid_entity = world.spawn_empty().id();
1958 ///
1959 ///
1960 /// let mut query_state = world.query::<&mut A>();
1961 /// let mut query = query_state.query_mut(&mut world);
1962 ///
1963 /// let mut mutable_component_values = query.get_many_mut(entities).unwrap();
1964 ///
1965 /// for mut a in &mut mutable_component_values {
1966 /// a.0 += 5;
1967 /// }
1968 ///
1969 /// let component_values = query.get_many(entities).unwrap();
1970 ///
1971 /// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1972 ///
1973 /// assert_eq!(
1974 /// match query
1975 /// .get_many_mut([wrong_entity])
1976 /// .unwrap_err()
1977 /// {
1978 /// QueryEntityError::NotSpawned(error) => error.entity(),
1979 /// _ => panic!(),
1980 /// },
1981 /// wrong_entity
1982 /// );
1983 /// assert_eq!(
1984 /// match query
1985 /// .get_many_mut([invalid_entity])
1986 /// .unwrap_err()
1987 /// {
1988 /// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1989 /// _ => panic!(),
1990 /// },
1991 /// invalid_entity
1992 /// );
1993 /// assert_eq!(
1994 /// query
1995 /// .get_many_mut([entities[0], entities[0]])
1996 /// .unwrap_err(),
1997 /// QueryEntityError::AliasedMutability(entities[0])
1998 /// );
1999 /// ```
2000 /// # See also
2001 ///
2002 /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
2003 #[inline]
2004 pub fn get_many_mut<const N: usize>(
2005 &mut self,
2006 entities: [Entity; N],
2007 ) -> Result<[D::Item<'_, 's>; N], QueryEntityError>
2008 where
2009 D: IterQueryData,
2010 {
2011 self.reborrow().get_many_mut_inner(entities)
2012 }
2013
2014 /// Returns the query items for the given [`UniqueEntityArray`].
2015 ///
2016 /// The returned query items are in the same order as the input.
2017 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
2018 ///
2019 /// # Examples
2020 ///
2021 /// ```
2022 /// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
2023 ///
2024 /// #[derive(Component, PartialEq, Debug)]
2025 /// struct A(usize);
2026 ///
2027 /// let mut world = World::new();
2028 ///
2029 /// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
2030 /// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
2031 ///
2032 /// world.spawn(A(73));
2033 /// let wrong_entity = Entity::from_raw_u32(57).unwrap();
2034 /// let invalid_entity = world.spawn_empty().id();
2035 ///
2036 ///
2037 /// let mut query_state = world.query::<&mut A>();
2038 /// let mut query = query_state.query_mut(&mut world);
2039 ///
2040 /// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();
2041 ///
2042 /// for mut a in &mut mutable_component_values {
2043 /// a.0 += 5;
2044 /// }
2045 ///
2046 /// let component_values = query.get_many_unique(entity_set).unwrap();
2047 ///
2048 /// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
2049 ///
2050 /// assert_eq!(
2051 /// match query
2052 /// .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))
2053 /// .unwrap_err()
2054 /// {
2055 /// QueryEntityError::NotSpawned(error) => error.entity(),
2056 /// _ => panic!(),
2057 /// },
2058 /// wrong_entity
2059 /// );
2060 /// assert_eq!(
2061 /// match query
2062 /// .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))
2063 /// .unwrap_err()
2064 /// {
2065 /// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
2066 /// _ => panic!(),
2067 /// },
2068 /// invalid_entity
2069 /// );
2070 /// ```
2071 /// # See also
2072 ///
2073 /// - [`get_many_unique`](Self::get_many) to get read-only query items.
2074 #[inline]
2075 pub fn get_many_unique_mut<const N: usize>(
2076 &mut self,
2077 entities: UniqueEntityArray<N>,
2078 ) -> Result<[D::Item<'_, 's>; N], QueryEntityError>
2079 where
2080 D: IterQueryData,
2081 {
2082 self.reborrow().get_many_unique_inner(entities)
2083 }
2084
2085 /// Returns the query items for the given array of [`Entity`].
2086 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2087 ///
2088 /// The returned query items are in the same order as the input.
2089 /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
2090 ///
2091 /// # See also
2092 ///
2093 /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
2094 /// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
2095 /// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.
2096 #[inline]
2097 pub fn get_many_mut_inner<const N: usize>(
2098 self,
2099 entities: [Entity; N],
2100 ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
2101 where
2102 D: IterQueryData,
2103 {
2104 // Verify that all entities are unique
2105 for i in 0..N {
2106 for j in 0..i {
2107 if entities[i] == entities[j] {
2108 return Err(QueryEntityError::AliasedMutability(entities[i]));
2109 }
2110 }
2111 }
2112 // SAFETY: All entities are unique, so the results don't alias.
2113 unsafe { self.get_many_impl(entities) }
2114 }
2115
2116 /// Returns the query items for the given array of [`Entity`].
2117 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2118 ///
2119 /// The returned query items are in the same order as the input.
2120 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
2121 ///
2122 /// # See also
2123 ///
2124 /// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
2125 /// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
2126 /// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.
2127 #[inline]
2128 pub fn get_many_inner<const N: usize>(
2129 self,
2130 entities: [Entity; N],
2131 ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
2132 where
2133 D: ReadOnlyQueryData,
2134 {
2135 // SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.
2136 unsafe { self.get_many_impl(entities) }
2137 }
2138
2139 /// Returns the query items for the given [`UniqueEntityArray`].
2140 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2141 ///
2142 /// The returned query items are in the same order as the input.
2143 /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
2144 ///
2145 /// # See also
2146 ///
2147 /// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.
2148 /// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.
2149 #[inline]
2150 pub fn get_many_unique_inner<const N: usize>(
2151 self,
2152 entities: UniqueEntityArray<N>,
2153 ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
2154 where
2155 D: IterQueryData,
2156 {
2157 // SAFETY: All entities are unique, so the results don't alias.
2158 unsafe { self.get_many_impl(entities.into_inner()) }
2159 }
2160
2161 /// Returns the query items for the given array of [`Entity`].
2162 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2163 ///
2164 /// # Safety
2165 ///
2166 /// The caller must ensure that the query data returned for the entities does not conflict,
2167 /// either because they are all unique or because the data is read-only.
2168 unsafe fn get_many_impl<const N: usize>(
2169 self,
2170 entities: [Entity; N],
2171 ) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
2172 where
2173 D: IterQueryData,
2174 {
2175 let mut values = [(); N].map(|_| MaybeUninit::uninit());
2176
2177 for (value, entity) in core::iter::zip(&mut values, entities) {
2178 // SAFETY: The caller asserts that the results don't alias,
2179 // and `D: IterQueryData` so its valid to have items alive for different entitiess
2180 let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;
2181 *value = MaybeUninit::new(item);
2182 }
2183
2184 // SAFETY: Each value has been fully initialized.
2185 Ok(values.map(|x| unsafe { x.assume_init() }))
2186 }
2187
2188 /// Returns the query item for the given [`Entity`].
2189 ///
2190 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
2191 ///
2192 /// This is always guaranteed to run in `O(1)` time.
2193 ///
2194 /// # Safety
2195 ///
2196 /// This function makes it possible to violate Rust's aliasing guarantees.
2197 /// You must make sure this call does not result in multiple mutable references to the same component.
2198 ///
2199 /// # See also
2200 ///
2201 /// - [`get_mut`](Self::get_mut) for the safe version.
2202 #[inline]
2203 pub unsafe fn get_unchecked(
2204 &self,
2205 entity: Entity,
2206 ) -> Result<D::Item<'_, 's>, QueryEntityError> {
2207 // SAFETY: The caller promises that this will not result in multiple mutable references.
2208 unsafe { self.reborrow_unsafe() }.get_inner(entity)
2209 }
2210
2211 /// Returns a single read-only query item when there is exactly one entity matching the query.
2212 ///
2213 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
2214 ///
2215 /// # Example
2216 ///
2217 /// ```
2218 /// # use bevy_ecs::prelude::*;
2219 /// # use bevy_ecs::query::QuerySingleError;
2220 /// # #[derive(Component)]
2221 /// # struct PlayerScore(i32);
2222 /// fn player_scoring_system(query: Query<&PlayerScore>) {
2223 /// match query.single() {
2224 /// Ok(PlayerScore(score)) => {
2225 /// println!("Score: {}", score);
2226 /// }
2227 /// Err(QuerySingleError::NoEntities(_)) => {
2228 /// println!("Error: There is no player!");
2229 /// }
2230 /// Err(QuerySingleError::MultipleEntities(_)) => {
2231 /// println!("Error: There is more than one player!");
2232 /// }
2233 /// }
2234 /// }
2235 /// # bevy_ecs::system::assert_is_system(player_scoring_system);
2236 /// ```
2237 ///
2238 /// # See also
2239 ///
2240 /// - [`single_mut`](Self::single_mut) to get the mutable query item.
2241 #[inline]
2242 pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {
2243 self.as_readonly().single_inner()
2244 }
2245
2246 /// Returns a single query item when there is exactly one entity matching the query.
2247 ///
2248 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
2249 ///
2250 /// # Example
2251 ///
2252 /// ```
2253 /// # use bevy_ecs::prelude::*;
2254 /// #
2255 /// # #[derive(Component)]
2256 /// # struct Player;
2257 /// # #[derive(Component)]
2258 /// # struct Health(u32);
2259 /// #
2260 /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
2261 /// let mut health = query.single_mut().expect("Error: Could not find a single player.");
2262 /// health.0 += 1;
2263 /// }
2264 /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
2265 /// ```
2266 ///
2267 /// # See also
2268 ///
2269 /// - [`single`](Self::single) to get the read-only query item.
2270 #[inline]
2271 pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError>
2272 where
2273 D: IterQueryData,
2274 {
2275 self.reborrow().single_inner()
2276 }
2277
2278 /// Returns a single query item when there is exactly one entity matching the query.
2279 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2280 ///
2281 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
2282 ///
2283 /// # Example
2284 ///
2285 /// ```
2286 /// # use bevy_ecs::prelude::*;
2287 /// #
2288 /// # #[derive(Component)]
2289 /// # struct Player;
2290 /// # #[derive(Component)]
2291 /// # struct Health(u32);
2292 /// #
2293 /// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {
2294 /// let mut health = query.single_inner().expect("Error: Could not find a single player.");
2295 /// health.0 += 1;
2296 /// }
2297 /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
2298 /// ```
2299 ///
2300 /// # See also
2301 ///
2302 /// - [`single`](Self::single) to get the read-only query item.
2303 /// - [`single_mut`](Self::single_mut) to get the mutable query item.
2304 #[inline]
2305 pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError>
2306 where
2307 D: IterQueryData,
2308 {
2309 let mut query = self.into_iter();
2310 let first = query.next();
2311 let extra = query.next().is_some();
2312
2313 match (first, extra) {
2314 (Some(r), false) => Ok(r),
2315 (None, _) => Err(QuerySingleError::NoEntities(DebugName::type_name::<Self>())),
2316 (Some(_), _) => Err(QuerySingleError::MultipleEntities(DebugName::type_name::<
2317 Self,
2318 >())),
2319 }
2320 }
2321
2322 /// Returns `true` if there are no query items.
2323 ///
2324 /// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`
2325 /// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely
2326 /// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check
2327 /// each query result for a match.
2328 ///
2329 /// # Example
2330 ///
2331 /// Here, the score is increased only if an entity with a `Player` component is present in the world:
2332 ///
2333 /// ```
2334 /// # use bevy_ecs::prelude::*;
2335 /// #
2336 /// # #[derive(Component)]
2337 /// # struct Player;
2338 /// # #[derive(Resource)]
2339 /// # struct Score(u32);
2340 /// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
2341 /// if !query.is_empty() {
2342 /// score.0 += 1;
2343 /// }
2344 /// }
2345 /// # bevy_ecs::system::assert_is_system(update_score_system);
2346 /// ```
2347 ///
2348 /// [`Added`]: crate::query::Added
2349 /// [`Changed`]: crate::query::Changed
2350 /// [`Spawned`]: crate::query::Spawned
2351 #[inline]
2352 pub fn is_empty(&self) -> bool {
2353 // If the query data matches every entity, then `as_nop()` can safely
2354 // skip the cost of initializing the fetch for data that won't be used.
2355 if D::IS_ARCHETYPAL {
2356 self.as_nop().iter().next().is_none()
2357 } else {
2358 self.iter().next().is_none()
2359 }
2360 }
2361
2362 /// Returns `true` if the given [`Entity`] matches the query.
2363 ///
2364 /// This is always guaranteed to run in `O(1)` time.
2365 ///
2366 /// # Example
2367 ///
2368 /// ```
2369 /// # use bevy_ecs::prelude::*;
2370 /// #
2371 /// # #[derive(Component)]
2372 /// # struct InRange;
2373 /// #
2374 /// # #[derive(Resource)]
2375 /// # struct Target {
2376 /// # entity: Entity,
2377 /// # }
2378 /// #
2379 /// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
2380 /// if in_range_query.contains(target.entity) {
2381 /// println!("Bam!")
2382 /// }
2383 /// }
2384 /// # bevy_ecs::system::assert_is_system(targeting_system);
2385 /// ```
2386 #[inline]
2387 pub fn contains(&self, entity: Entity) -> bool {
2388 // If the query data matches every entity, then `as_nop()` can safely
2389 // skip the cost of initializing the fetch for data that won't be used.
2390 if D::IS_ARCHETYPAL {
2391 self.as_nop().get(entity).is_ok()
2392 } else {
2393 self.get(entity).is_ok()
2394 }
2395 }
2396
2397 /// Counts the number of entities that match the query.
2398 ///
2399 /// This is equivalent to `self.iter().count()` but may be more efficient in some cases.
2400 ///
2401 /// If [`D::IS_ARCHETYPAL`](QueryData::IS_ARCHETYPAL) && [`F::IS_ARCHETYPAL`](QueryFilter::IS_ARCHETYPAL) is `true`,
2402 /// this will do work proportional to the number of matched archetypes or tables, but will not iterate each entity.
2403 /// If it is `false`, it will have to do work for each entity.
2404 ///
2405 /// # Example
2406 ///
2407 /// ```
2408 /// # use bevy_ecs::prelude::*;
2409 /// #
2410 /// # #[derive(Component)]
2411 /// # struct InRange;
2412 /// #
2413 /// fn targeting_system(in_range_query: Query<&InRange>) {
2414 /// let count = in_range_query.count();
2415 /// println!("{count} targets in range!");
2416 /// }
2417 /// # bevy_ecs::system::assert_is_system(targeting_system);
2418 /// ```
2419 pub fn count(&self) -> usize {
2420 // If the query data matches every entity, then `as_nop()` can safely
2421 // skip the cost of initializing the fetch for data that won't be used.
2422 if !D::IS_ARCHETYPAL {
2423 self.into_iter().count()
2424 } else if !F::IS_ARCHETYPAL {
2425 // If we have non-archetypal filters, we have to check each entity.
2426 self.as_nop().into_iter().count()
2427 } else {
2428 // For archetypal queries, the `size_hint()` is exact,
2429 // and we can get the count from the archetype and table counts.
2430 self.as_nop().into_iter().size_hint().0
2431 }
2432 }
2433
2434 /// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more
2435 /// restrictive access to the entities matched by the current query.
2436 ///
2437 /// A transmute is valid only if `NewD` has a subset of the read, write, and required access
2438 /// of the current query. A precise description of the access required by each parameter
2439 /// type is given in the table below, but typical uses are to:
2440 /// * Remove components, e.g. `Query<(&A, &B)>` to `Query<&A>`.
2441 /// * Retrieve an existing component with reduced or equal access, e.g. `Query<&mut A>` to `Query<&A>`
2442 /// or `Query<&T>` to `Query<Ref<T>>`.
2443 /// * Add parameters with no new access, for example adding an `Entity` parameter.
2444 ///
2445 /// Note that since filter terms are dropped, non-archetypal filters like
2446 /// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter
2447 /// terms see [`Self::transmute_lens_filtered`].
2448 ///
2449 /// |`QueryData` parameter type|Access required|
2450 /// |----|----|
2451 /// |[`Entity`], [`EntityLocation`], [`SpawnDetails`], [`&Archetype`], [`Has<T>`], [`PhantomData<T>`]|No access|
2452 /// |[`EntityMut`]|Read and write access to all components, but no required access|
2453 /// |[`EntityRef`]|Read access to all components, but no required access|
2454 /// |`&T`, [`Ref<T>`]|Read and required access to `T`|
2455 /// |`&mut T`, [`Mut<T>`]|Read, write and required access to `T`|
2456 /// |[`Option<T>`], [`AnyOf<(D, ...)>`]|Read and write access to `T`, but no required access|
2457 /// |Tuples of query data and<br/>`#[derive(QueryData)]` structs|The union of the access of their subqueries|
2458 /// |[`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|
2459 ///
2460 /// `transmute_lens` drops filter terms, but [`Self::transmute_lens_filtered`] supports returning a [`QueryLens`] with a new
2461 /// filter type - the access required by filter parameters are as follows.
2462 ///
2463 /// |`QueryFilter` parameter type|Access required|
2464 /// |----|----|
2465 /// |[`Added<T>`], [`Changed<T>`]|Read and required access to `T`|
2466 /// |[`With<T>`], [`Without<T>`]|No access|
2467 /// |[`Or<(T, ...)>`]|Read access of the subqueries, but no required access|
2468 /// |Tuples of query filters and `#[derive(QueryFilter)]` structs|The union of the access of their subqueries|
2469 ///
2470 /// [`Added`]: crate::query::Added
2471 /// [`Added<T>`]: crate::query::Added
2472 /// [`AnyOf<(D, ...)>`]: crate::query::AnyOf
2473 /// [`&Archetype`]: crate::archetype::Archetype
2474 /// [`Changed`]: crate::query::Changed
2475 /// [`Changed<T>`]: crate::query::Changed
2476 /// [`EntityMut`]: crate::world::EntityMut
2477 /// [`EntityLocation`]: crate::entity::EntityLocation
2478 /// [`EntityRef`]: crate::world::EntityRef
2479 /// [`FilteredEntityRef`]: crate::world::FilteredEntityRef
2480 /// [`FilteredEntityMut`]: crate::world::FilteredEntityMut
2481 /// [`Has<T>`]: crate::query::Has
2482 /// [`Mut<T>`]: crate::world::Mut
2483 /// [`Or<(T, ...)>`]: crate::query::Or
2484 /// [`QueryBuilder`]: crate::query::QueryBuilder
2485 /// [`Ref<T>`]: crate::world::Ref
2486 /// [`SpawnDetails`]: crate::query::SpawnDetails
2487 /// [`Spawned`]: crate::query::Spawned
2488 /// [`With<T>`]: crate::query::With
2489 /// [`Without<T>`]: crate::query::Without
2490 ///
2491 /// ## Panics
2492 ///
2493 /// This will panic if the access required by `NewD` is not a subset of that required by
2494 /// the original fetch `D`.
2495 ///
2496 /// ## Example
2497 ///
2498 /// ```rust
2499 /// # use bevy_ecs::prelude::*;
2500 /// # use bevy_ecs::system::QueryLens;
2501 /// #
2502 /// # #[derive(Component)]
2503 /// # struct A(usize);
2504 /// #
2505 /// # #[derive(Component)]
2506 /// # struct B(usize);
2507 /// #
2508 /// # let mut world = World::new();
2509 /// #
2510 /// # world.spawn((A(10), B(5)));
2511 /// #
2512 /// fn reusable_function(lens: &mut QueryLens<&A>) {
2513 /// assert_eq!(lens.query().single().unwrap().0, 10);
2514 /// }
2515 ///
2516 /// // We can use the function in a system that takes the exact query.
2517 /// fn system_1(mut query: Query<&A>) {
2518 /// reusable_function(&mut query.as_query_lens());
2519 /// }
2520 ///
2521 /// // We can also use it with a query that does not match exactly
2522 /// // by transmuting it.
2523 /// fn system_2(mut query: Query<(&mut A, &B)>) {
2524 /// let mut lens = query.transmute_lens::<&A>();
2525 /// reusable_function(&mut lens);
2526 /// }
2527 ///
2528 /// # let mut schedule = Schedule::default();
2529 /// # schedule.add_systems((system_1, system_2));
2530 /// # schedule.run(&mut world);
2531 /// ```
2532 ///
2533 /// ### Examples of valid transmutes
2534 ///
2535 /// ```rust
2536 /// # use bevy_ecs::{
2537 /// # prelude::*,
2538 /// # archetype::Archetype,
2539 /// # entity::EntityLocation,
2540 /// # query::{QueryData, QueryFilter, SingleEntityQueryData},
2541 /// # world::{FilteredEntityMut, FilteredEntityRef},
2542 /// # };
2543 /// # use std::marker::PhantomData;
2544 /// #
2545 /// # fn assert_valid_transmute<OldD: QueryData, NewD: SingleEntityQueryData>() {
2546 /// # assert_valid_transmute_filtered::<OldD, (), NewD, ()>();
2547 /// # }
2548 /// #
2549 /// # fn assert_valid_transmute_filtered<OldD: QueryData, OldF: QueryFilter, NewD: SingleEntityQueryData, NewF: QueryFilter>() {
2550 /// # let mut world = World::new();
2551 /// # // Make sure all components in the new query are initialized
2552 /// # let state = world.query_filtered::<NewD, NewF>();
2553 /// # let state = world.query_filtered::<OldD, OldF>();
2554 /// # state.transmute_filtered::<NewD, NewF>(&world);
2555 /// # }
2556 /// #
2557 /// # #[derive(Component)]
2558 /// # struct T;
2559 /// #
2560 /// # #[derive(Component)]
2561 /// # struct U;
2562 /// #
2563 /// # #[derive(Component)]
2564 /// # struct V;
2565 /// #
2566 /// // `&mut T` and `Mut<T>` access the same data and can be transmuted to each other,
2567 /// // `&T` and `Ref<T>` access the same data and can be transmuted to each other,
2568 /// // and mutable versions can be transmuted to read-only versions
2569 /// assert_valid_transmute::<&mut T, &T>();
2570 /// assert_valid_transmute::<&mut T, Mut<T>>();
2571 /// assert_valid_transmute::<Mut<T>, &mut T>();
2572 /// assert_valid_transmute::<&T, Ref<T>>();
2573 /// assert_valid_transmute::<Ref<T>, &T>();
2574 ///
2575 /// // The structure can be rearranged, or subqueries dropped
2576 /// assert_valid_transmute::<(&T, &U), &T>();
2577 /// assert_valid_transmute::<((&T, &U), &V), (&T, (&U, &V))>();
2578 /// assert_valid_transmute::<Option<(&T, &U)>, (Option<&T>, Option<&U>)>();
2579 ///
2580 /// // Queries with no access can be freely added
2581 /// assert_valid_transmute::<
2582 /// &T,
2583 /// (&T, Entity, EntityLocation, &Archetype, Has<U>, PhantomData<T>),
2584 /// >();
2585 ///
2586 /// // Required access can be transmuted to optional,
2587 /// // and optional access can be transmuted to other optional access
2588 /// assert_valid_transmute::<&T, Option<&T>>();
2589 /// assert_valid_transmute::<AnyOf<(&mut T, &mut U)>, Option<&T>>();
2590 /// // Note that removing subqueries from `AnyOf` will result
2591 /// // in an `AnyOf` where all subqueries can yield `None`!
2592 /// assert_valid_transmute::<AnyOf<(&T, &U, &V)>, AnyOf<(&T, &U)>>();
2593 /// assert_valid_transmute::<EntityMut, Option<&mut T>>();
2594 ///
2595 /// // Anything can be transmuted to `FilteredEntityRef` or `FilteredEntityMut`
2596 /// // This will create a `FilteredEntityMut` that only has read access to `T`
2597 /// assert_valid_transmute::<&T, FilteredEntityMut>();
2598 /// // This will create a `FilteredEntityMut` that has no access to `T`,
2599 /// // read access to `U`, and write access to `V`.
2600 /// assert_valid_transmute::<(&mut T, &mut U, &mut V), (&mut T, &U, FilteredEntityMut)>();
2601 ///
2602 /// // `Added<T>` and `Changed<T>` filters have the same access as `&T` data
2603 /// // Remember that they are only evaluated on the transmuted query, not the original query!
2604 /// assert_valid_transmute_filtered::<Entity, Changed<T>, &T, ()>();
2605 /// assert_valid_transmute_filtered::<&mut T, (), &T, Added<T>>();
2606 /// // Nested inside of an `Or` filter, they have the same access as `Option<&T>`.
2607 /// assert_valid_transmute_filtered::<Option<&T>, (), Entity, Or<(Changed<T>, With<U>)>>();
2608 /// ```
2609 #[track_caller]
2610 pub fn transmute_lens<NewD: SingleEntityQueryData>(&mut self) -> QueryLens<'_, NewD> {
2611 self.transmute_lens_filtered::<NewD, ()>()
2612 }
2613
2614 /// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive
2615 /// access to the entities matched by the current query.
2616 ///
2617 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2618 ///
2619 /// See [`Self::transmute_lens`] for a description of allowed transmutes.
2620 ///
2621 /// ## Panics
2622 ///
2623 /// This will panic if `NewD` is not a subset of the original fetch `D`
2624 ///
2625 /// ## Example
2626 ///
2627 /// ```rust
2628 /// # use bevy_ecs::prelude::*;
2629 /// # use bevy_ecs::system::QueryLens;
2630 /// #
2631 /// # #[derive(Component)]
2632 /// # struct A(usize);
2633 /// #
2634 /// # #[derive(Component)]
2635 /// # struct B(usize);
2636 /// #
2637 /// # let mut world = World::new();
2638 /// #
2639 /// # world.spawn((A(10), B(5)));
2640 /// #
2641 /// fn reusable_function(mut lens: QueryLens<&A>) {
2642 /// assert_eq!(lens.query().single().unwrap().0, 10);
2643 /// }
2644 ///
2645 /// // We can use the function in a system that takes the exact query.
2646 /// fn system_1(query: Query<&A>) {
2647 /// reusable_function(query.into_query_lens());
2648 /// }
2649 ///
2650 /// // We can also use it with a query that does not match exactly
2651 /// // by transmuting it.
2652 /// fn system_2(query: Query<(&mut A, &B)>) {
2653 /// let mut lens = query.transmute_lens_inner::<&A>();
2654 /// reusable_function(lens);
2655 /// }
2656 ///
2657 /// # let mut schedule = Schedule::default();
2658 /// # schedule.add_systems((system_1, system_2));
2659 /// # schedule.run(&mut world);
2660 /// ```
2661 ///
2662 /// # See also
2663 ///
2664 /// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].
2665 #[track_caller]
2666 pub fn transmute_lens_inner<NewD: SingleEntityQueryData>(self) -> QueryLens<'w, NewD> {
2667 self.transmute_lens_filtered_inner::<NewD, ()>()
2668 }
2669
2670 /// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.
2671 ///
2672 /// See [`Self::transmute_lens`] for a description of allowed transmutes.
2673 ///
2674 /// Note that the lens will iterate the same tables and archetypes as the original query. This means that
2675 /// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
2676 /// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),
2677 /// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they
2678 /// are in the type signature.
2679 #[track_caller]
2680 pub fn transmute_lens_filtered<NewD: SingleEntityQueryData, NewF: QueryFilter>(
2681 &mut self,
2682 ) -> QueryLens<'_, NewD, NewF> {
2683 self.reborrow().transmute_lens_filtered_inner()
2684 }
2685
2686 /// Equivalent to [`Self::transmute_lens_inner`] but also includes a [`QueryFilter`] type.
2687 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2688 ///
2689 /// See [`Self::transmute_lens`] for a description of allowed transmutes.
2690 ///
2691 /// Note that the lens will iterate the same tables and archetypes as the original query. This means that
2692 /// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
2693 /// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),
2694 /// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they
2695 /// are in the type signature.
2696 ///
2697 /// # See also
2698 ///
2699 /// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].
2700 #[track_caller]
2701 pub fn transmute_lens_filtered_inner<NewD: SingleEntityQueryData, NewF: QueryFilter>(
2702 self,
2703 ) -> QueryLens<'w, NewD, NewF> {
2704 let state = self.state.transmute_filtered::<NewD, NewF>(self.world);
2705 QueryLens {
2706 world: self.world,
2707 state,
2708 last_run: self.last_run,
2709 this_run: self.this_run,
2710 }
2711 }
2712
2713 /// Gets a [`QueryLens`] with the same accesses as the existing query
2714 pub fn as_query_lens(&mut self) -> QueryLens<'_, D>
2715 where
2716 D: SingleEntityQueryData,
2717 {
2718 self.transmute_lens()
2719 }
2720
2721 /// Gets a [`QueryLens`] with the same accesses as the existing query
2722 ///
2723 /// # See also
2724 ///
2725 /// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].
2726 pub fn into_query_lens(self) -> QueryLens<'w, D>
2727 where
2728 D: SingleEntityQueryData,
2729 {
2730 self.transmute_lens_inner()
2731 }
2732
2733 /// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
2734 ///
2735 /// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
2736 /// The returned query will only return items with both `A` and `B`. Note that since filters
2737 /// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.
2738 /// To maintain or change filter terms see `Self::join_filtered`.
2739 ///
2740 /// ## Example
2741 ///
2742 /// ```rust
2743 /// # use bevy_ecs::prelude::*;
2744 /// # use bevy_ecs::system::QueryLens;
2745 /// #
2746 /// # #[derive(Component)]
2747 /// # struct Transform;
2748 /// #
2749 /// # #[derive(Component)]
2750 /// # struct Player;
2751 /// #
2752 /// # #[derive(Component)]
2753 /// # struct Enemy;
2754 /// #
2755 /// # let mut world = World::default();
2756 /// # world.spawn((Transform, Player));
2757 /// # world.spawn((Transform, Enemy));
2758 ///
2759 /// fn system(
2760 /// mut transforms: Query<&Transform>,
2761 /// mut players: Query<&Player>,
2762 /// mut enemies: Query<&Enemy>
2763 /// ) {
2764 /// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);
2765 /// for (transform, player) in &players_transforms.query() {
2766 /// // do something with a and b
2767 /// }
2768 ///
2769 /// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);
2770 /// for (transform, enemy) in &enemies_transforms.query() {
2771 /// // do something with a and b
2772 /// }
2773 /// }
2774 ///
2775 /// # let mut schedule = Schedule::default();
2776 /// # schedule.add_systems(system);
2777 /// # schedule.run(&mut world);
2778 /// ```
2779 /// ## Panics
2780 ///
2781 /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2782 ///
2783 /// ## Allowed Transmutes
2784 ///
2785 /// Like `transmute_lens` the query terms can be changed with some restrictions.
2786 /// See [`Self::transmute_lens`] for more details.
2787 pub fn join<'a, OtherD: QueryData, NewD: SingleEntityQueryData>(
2788 &'a mut self,
2789 other: &'a mut Query<OtherD>,
2790 ) -> QueryLens<'a, NewD> {
2791 self.join_filtered(other)
2792 }
2793
2794 /// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
2795 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2796 ///
2797 /// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
2798 /// The returned query will only return items with both `A` and `B`. Note that since filters
2799 /// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.
2800 /// To maintain or change filter terms see `Self::join_filtered`.
2801 ///
2802 /// ## Panics
2803 ///
2804 /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2805 ///
2806 /// ## Allowed Transmutes
2807 ///
2808 /// Like `transmute_lens` the query terms can be changed with some restrictions.
2809 /// See [`Self::transmute_lens`] for more details.
2810 ///
2811 /// # See also
2812 ///
2813 /// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].
2814 pub fn join_inner<OtherD: QueryData, NewD: SingleEntityQueryData>(
2815 self,
2816 other: Query<'w, '_, OtherD>,
2817 ) -> QueryLens<'w, NewD> {
2818 self.join_filtered_inner(other)
2819 }
2820
2821 /// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.
2822 ///
2823 /// Note that the lens with iterate a subset of the original queries' tables
2824 /// and archetypes. This means that additional archetypal query terms like
2825 /// `With` and `Without` will not necessarily be respected and non-archetypal
2826 /// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2827 /// are in the type signature.
2828 pub fn join_filtered<
2829 'a,
2830 OtherD: QueryData,
2831 OtherF: QueryFilter,
2832 NewD: SingleEntityQueryData,
2833 NewF: QueryFilter,
2834 >(
2835 &'a mut self,
2836 other: &'a mut Query<OtherD, OtherF>,
2837 ) -> QueryLens<'a, NewD, NewF> {
2838 self.reborrow().join_filtered_inner(other.reborrow())
2839 }
2840
2841 /// Equivalent to [`Self::join_inner`] but also includes a [`QueryFilter`] type.
2842 /// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2843 ///
2844 /// Note that the lens with iterate a subset of the original queries' tables
2845 /// and archetypes. This means that additional archetypal query terms like
2846 /// `With` and `Without` will not necessarily be respected and non-archetypal
2847 /// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2848 /// are in the type signature.
2849 ///
2850 /// # See also
2851 ///
2852 /// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].
2853 pub fn join_filtered_inner<
2854 OtherD: QueryData,
2855 OtherF: QueryFilter,
2856 NewD: SingleEntityQueryData,
2857 NewF: QueryFilter,
2858 >(
2859 self,
2860 other: Query<'w, '_, OtherD, OtherF>,
2861 ) -> QueryLens<'w, NewD, NewF> {
2862 let state = self
2863 .state
2864 .join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);
2865 QueryLens {
2866 world: self.world,
2867 state,
2868 last_run: self.last_run,
2869 this_run: self.this_run,
2870 }
2871 }
2872}
2873
2874impl<'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {
2875 type Item = D::Item<'w, 's>;
2876 type IntoIter = QueryIter<'w, 's, D, F>;
2877
2878 fn into_iter(self) -> Self::IntoIter {
2879 self.iter_inner()
2880 }
2881}
2882
2883impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {
2884 type Item = ROQueryItem<'w, 's, D>;
2885 type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;
2886
2887 fn into_iter(self) -> Self::IntoIter {
2888 self.iter()
2889 }
2890}
2891
2892impl<'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {
2893 type Item = D::Item<'w, 's>;
2894 type IntoIter = QueryIter<'w, 's, D, F>;
2895
2896 fn into_iter(self) -> Self::IntoIter {
2897 self.iter_mut()
2898 }
2899}
2900
2901/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].
2902///
2903/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]
2904pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {
2905 world: UnsafeWorldCell<'w>,
2906 state: QueryState<Q, F>,
2907 last_run: Tick,
2908 this_run: Tick,
2909}
2910
2911impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2912 /// Create a [`Query`] from the underlying [`QueryState`].
2913 pub fn query(&mut self) -> Query<'_, '_, Q, F> {
2914 Query {
2915 world: self.world,
2916 state: &self.state,
2917 last_run: self.last_run,
2918 this_run: self.this_run,
2919 }
2920 }
2921}
2922
2923impl<'w, Q: ReadOnlyQueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2924 /// Create a [`Query`] from the underlying [`QueryState`].
2925 /// This returns results with the actual "inner" world lifetime,
2926 /// so it may only be used with read-only queries to prevent mutable aliasing.
2927 pub fn query_inner(&self) -> Query<'w, '_, Q, F> {
2928 Query {
2929 world: self.world,
2930 state: &self.state,
2931 last_run: self.last_run,
2932 this_run: self.this_run,
2933 }
2934 }
2935}
2936
2937impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>
2938 for Query<'s, 's, Q, F>
2939{
2940 fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {
2941 value.query()
2942 }
2943}
2944
2945impl<'w, 'q, Q: SingleEntityQueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>
2946 for QueryLens<'q, Q, F>
2947{
2948 fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {
2949 value.transmute_lens_filtered()
2950 }
2951}
2952
2953/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].
2954///
2955/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.
2956/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).
2957///
2958/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.
2959///
2960/// Note that [`Single`] is not used as a search optimization. It is used as a validation with slight overhead compared to [`Query`].
2961///
2962/// See [`Query`] for more details.
2963///
2964/// [System parameter]: crate::system::SystemParam
2965///
2966/// # Example
2967/// ```
2968/// # use bevy_ecs::prelude::*;
2969/// #[derive(Component)]
2970/// struct Hiding;
2971///
2972/// #[derive(Component)]
2973/// struct Boss {
2974/// health: f32
2975/// };
2976///
2977/// #[derive(Component)]
2978/// struct EnemySize {
2979/// height: f32
2980/// };
2981///
2982/// fn hurt_boss(mut boss: Single<&mut Boss, Without<Hiding>>) {
2983/// boss.health -= 4.0;
2984/// }
2985///
2986/// fn hurt_and_shrink_boss(mut boss_and_size: Single<(&mut Boss, &mut EnemySize)>) {
2987/// let (mut boss, mut size) = boss_and_size.into_inner();
2988/// boss.health -= 4.0;
2989/// size.height *= 0.5;
2990/// }
2991/// ```
2992/// Note that because [`Single`] implements [`Deref`] and [`DerefMut`], methods and fields like `health` can be accessed directly.
2993/// You can also access the underlying data manually, by calling `.deref`/`.deref_mut`, or by using the `*` operator.
2994/// When mutable elements appear in [`Single`], use `.into_inner` to extract the tuple elements to mutate them.
2995pub struct Single<'w, 's, D: IterQueryData, F: QueryFilter = ()> {
2996 pub(crate) item: D::Item<'w, 's>,
2997 pub(crate) _filter: PhantomData<F>,
2998}
2999
3000impl<'w, 's, D: IterQueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {
3001 type Target = D::Item<'w, 's>;
3002
3003 fn deref(&self) -> &Self::Target {
3004 &self.item
3005 }
3006}
3007
3008impl<'w, 's, D: IterQueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {
3009 fn deref_mut(&mut self) -> &mut Self::Target {
3010 &mut self.item
3011 }
3012}
3013
3014impl<'w, 's, D: IterQueryData, F: QueryFilter> Single<'w, 's, D, F> {
3015 /// Returns the inner item with ownership.
3016 pub fn into_inner(self) -> D::Item<'w, 's> {
3017 self.item
3018 }
3019}
3020
3021/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.
3022///
3023/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.
3024/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).
3025///
3026/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.
3027/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added),
3028/// [`Changed`](crate::query::Changed) of [`Spawned`](crate::query::Spawned) which must individually check each query
3029/// result for a match.
3030///
3031/// See [`Query`] for more details.
3032///
3033/// If the system doesn't need to perform the query but should still be skipped if it is empty,
3034/// you may use the [`any_with_component`](crate::schedule::common_conditions::any_with_component) or [`any_match_filter`](crate::schedule::common_conditions::any_match_filter) run conditions.
3035///
3036/// [System parameter]: crate::system::SystemParam
3037pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);
3038
3039impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {
3040 type Target = Query<'w, 's, D, F>;
3041
3042 fn deref(&self) -> &Self::Target {
3043 &self.0
3044 }
3045}
3046
3047impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {
3048 fn deref_mut(&mut self) -> &mut Self::Target {
3049 &mut self.0
3050 }
3051}
3052
3053impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {
3054 /// Returns the inner item with ownership.
3055 pub fn into_inner(self) -> Query<'w, 's, D, F> {
3056 self.0
3057 }
3058}
3059
3060impl<'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {
3061 type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;
3062
3063 type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;
3064
3065 fn into_iter(self) -> Self::IntoIter {
3066 self.0.into_iter()
3067 }
3068}
3069
3070impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {
3071 type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;
3072
3073 type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;
3074
3075 fn into_iter(self) -> Self::IntoIter {
3076 self.deref().into_iter()
3077 }
3078}
3079
3080impl<'a, 'w, 's, D: IterQueryData, F: QueryFilter> IntoIterator
3081 for &'a mut Populated<'w, 's, D, F>
3082{
3083 type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;
3084
3085 type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;
3086
3087 fn into_iter(self) -> Self::IntoIter {
3088 self.deref_mut().into_iter()
3089 }
3090}
3091
3092#[cfg(test)]
3093mod tests {
3094 use crate::{prelude::*, query::QueryEntityError};
3095 use alloc::vec::Vec;
3096
3097 #[test]
3098 fn get_many_uniqueness() {
3099 let mut world = World::new();
3100
3101 let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();
3102
3103 let mut query_state = world.query::<Entity>();
3104
3105 // It's best to test get_many_mut_inner directly, as it is shared
3106 // We don't care about aliased mutability for the read-only equivalent
3107
3108 // SAFETY: Query does not access world data.
3109 assert!(query_state
3110 .query_mut(&mut world)
3111 .get_many_mut_inner::<10>(entities.clone().try_into().unwrap())
3112 .is_ok());
3113
3114 assert_eq!(
3115 query_state
3116 .query_mut(&mut world)
3117 .get_many_mut_inner([entities[0], entities[0]])
3118 .unwrap_err(),
3119 QueryEntityError::AliasedMutability(entities[0])
3120 );
3121
3122 assert_eq!(
3123 query_state
3124 .query_mut(&mut world)
3125 .get_many_mut_inner([entities[0], entities[1], entities[0]])
3126 .unwrap_err(),
3127 QueryEntityError::AliasedMutability(entities[0])
3128 );
3129
3130 assert_eq!(
3131 query_state
3132 .query_mut(&mut world)
3133 .get_many_mut_inner([entities[9], entities[9]])
3134 .unwrap_err(),
3135 QueryEntityError::AliasedMutability(entities[9])
3136 );
3137 }
3138}