bevy_ecs/system/query.rs
1use crate::{
2 batching::BatchingStrategy,
3 component::Tick,
4 entity::Entity,
5 query::{
6 QueryCombinationIter, QueryData, QueryEntityError, QueryFilter, QueryIter, QueryManyIter,
7 QueryParIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,
8 },
9 world::unsafe_world_cell::UnsafeWorldCell,
10};
11use core::{
12 borrow::Borrow,
13 marker::PhantomData,
14 ops::{Deref, DerefMut},
15};
16
17/// [System parameter] that provides selective access to the [`Component`] data stored in a [`World`].
18///
19/// Enables access to [entity identifiers] and [components] from a system, without the need to directly access the world.
20/// Its iterators and getter methods return *query items*.
21/// Each query item is a type containing data relative to an entity.
22///
23/// `Query` is a generic data structure that accepts two type parameters:
24///
25/// - **`D` (query data).**
26/// The type of data contained in the query item.
27/// Only entities that match the requested data will generate an item.
28/// Must implement the [`QueryData`] trait.
29/// - **`F` (query filter).**
30/// A set of conditions that determines whether query items should be kept or discarded.
31/// Must implement the [`QueryFilter`] trait.
32/// This type parameter is optional.
33///
34/// [`World`]: crate::world::World
35///
36/// # Similar parameters
37///
38/// [`Query`] has few sibling [`SystemParam`](crate::system::system_param::SystemParam)s, which perform additional validation:
39/// - [`Single`] - Exactly one matching query item.
40/// - [`Option<Single>`] - Zero or one matching query item.
41/// - [`Populated`] - At least one matching query item.
42///
43/// Those parameters will prevent systems from running if their requirements aren't met.
44///
45/// # System parameter declaration
46///
47/// A query should always be declared as a system parameter.
48/// This section shows the most common idioms involving the declaration of `Query`.
49///
50/// ## Component access
51///
52/// A query defined with a reference to a component as the query fetch type parameter can be used to generate items that refer to the data of said component.
53///
54/// ```
55/// # use bevy_ecs::prelude::*;
56/// # #[derive(Component)]
57/// # struct ComponentA;
58/// # fn immutable_ref(
59/// // A component can be accessed by shared reference...
60/// query: Query<&ComponentA>
61/// # ) {}
62/// # bevy_ecs::system::assert_is_system(immutable_ref);
63///
64/// # fn mutable_ref(
65/// // ... or by mutable reference.
66/// query: Query<&mut ComponentA>
67/// # ) {}
68/// # bevy_ecs::system::assert_is_system(mutable_ref);
69/// ```
70///
71/// ## Query filtering
72///
73/// Setting the query filter type parameter will ensure that each query item satisfies the given condition.
74///
75/// ```
76/// # use bevy_ecs::prelude::*;
77/// # #[derive(Component)]
78/// # struct ComponentA;
79/// # #[derive(Component)]
80/// # struct ComponentB;
81/// # fn system(
82/// // Just `ComponentA` data will be accessed, but only for entities that also contain
83/// // `ComponentB`.
84/// query: Query<&ComponentA, With<ComponentB>>
85/// # ) {}
86/// # bevy_ecs::system::assert_is_system(system);
87/// ```
88///
89/// ## `QueryData` or `QueryFilter` tuples
90///
91/// Using tuples, each `Query` type parameter can contain multiple elements.
92///
93/// In the following example, two components are accessed simultaneously, and the query items are filtered on two conditions.
94///
95/// ```
96/// # use bevy_ecs::prelude::*;
97/// # #[derive(Component)]
98/// # struct ComponentA;
99/// # #[derive(Component)]
100/// # struct ComponentB;
101/// # #[derive(Component)]
102/// # struct ComponentC;
103/// # #[derive(Component)]
104/// # struct ComponentD;
105/// # fn immutable_ref(
106/// query: Query<(&ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
107/// # ) {}
108/// # bevy_ecs::system::assert_is_system(immutable_ref);
109/// ```
110///
111/// ## Entity identifier access
112///
113/// The identifier of an entity can be made available inside the query item by including [`Entity`] in the query fetch type parameter.
114///
115/// ```
116/// # use bevy_ecs::prelude::*;
117/// # #[derive(Component)]
118/// # struct ComponentA;
119/// # fn system(
120/// query: Query<(Entity, &ComponentA)>
121/// # ) {}
122/// # bevy_ecs::system::assert_is_system(system);
123/// ```
124///
125/// ## Optional component access
126///
127/// A component can be made optional in a query by wrapping it into an [`Option`].
128/// In this way, a query item can still be generated even if the queried entity does not contain the wrapped component.
129/// In this case, its corresponding value will be `None`.
130///
131/// ```
132/// # use bevy_ecs::prelude::*;
133/// # #[derive(Component)]
134/// # struct ComponentA;
135/// # #[derive(Component)]
136/// # struct ComponentB;
137/// # fn system(
138/// // Generates items for entities that contain `ComponentA`, and optionally `ComponentB`.
139/// query: Query<(&ComponentA, Option<&ComponentB>)>
140/// # ) {}
141/// # bevy_ecs::system::assert_is_system(system);
142/// ```
143///
144/// See the documentation for [`AnyOf`] to idiomatically declare many optional components.
145///
146/// See the [performance] section to learn more about the impact of optional components.
147///
148/// ## Disjoint queries
149///
150/// A system cannot contain two queries that break Rust's mutability rules.
151/// In this case, the [`Without`] filter can be used to disjoint them.
152///
153/// In the following example, two queries mutably access the same component.
154/// Executing this system will panic, since an entity could potentially match the two queries at the same time by having both `Player` and `Enemy` components.
155/// This would violate mutability rules.
156///
157/// ```should_panic
158/// # use bevy_ecs::prelude::*;
159/// # #[derive(Component)]
160/// # struct Health;
161/// # #[derive(Component)]
162/// # struct Player;
163/// # #[derive(Component)]
164/// # struct Enemy;
165/// #
166/// fn randomize_health(
167/// player_query: Query<&mut Health, With<Player>>,
168/// enemy_query: Query<&mut Health, With<Enemy>>,
169/// )
170/// # {}
171/// # let mut randomize_health_system = IntoSystem::into_system(randomize_health);
172/// # let mut world = World::new();
173/// # randomize_health_system.initialize(&mut world);
174/// # randomize_health_system.run((), &mut world);
175/// ```
176///
177/// Adding a `Without` filter will disjoint the queries.
178/// In this way, any entity that has both `Player` and `Enemy` components is excluded from both queries.
179///
180/// ```
181/// # use bevy_ecs::prelude::*;
182/// # #[derive(Component)]
183/// # struct Health;
184/// # #[derive(Component)]
185/// # struct Player;
186/// # #[derive(Component)]
187/// # struct Enemy;
188/// #
189/// fn randomize_health(
190/// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
191/// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
192/// )
193/// # {}
194/// # let mut randomize_health_system = IntoSystem::into_system(randomize_health);
195/// # let mut world = World::new();
196/// # randomize_health_system.initialize(&mut world);
197/// # randomize_health_system.run((), &mut world);
198/// ```
199///
200/// An alternative to this idiom is to wrap the conflicting queries into a [`ParamSet`](super::ParamSet).
201///
202/// ## Whole Entity Access
203///
204/// [`EntityRef`]s can be fetched from a query. This will give read-only access to any component on the entity,
205/// and can be use to dynamically fetch any component without baking it into the query type. Due to this global
206/// access to the entity, this will block any other system from parallelizing with it. As such these queries
207/// should be sparingly used.
208///
209/// ```
210/// # use bevy_ecs::prelude::*;
211/// # #[derive(Component)]
212/// # struct ComponentA;
213/// # fn system(
214/// query: Query<(EntityRef, &ComponentA)>
215/// # ) {}
216/// # bevy_ecs::system::assert_is_system(system);
217/// ```
218///
219/// As `EntityRef` can read any component on an entity, a query using it will conflict with *any* mutable
220/// access. It is strongly advised to couple `EntityRef` queries with the use of either `With`/`Without`
221/// filters or `ParamSets`. This also limits the scope of the query, which will improve iteration performance
222/// and also allows it to parallelize with other non-conflicting systems.
223///
224/// ```should_panic
225/// # use bevy_ecs::prelude::*;
226/// # #[derive(Component)]
227/// # struct ComponentA;
228/// # fn system(
229/// // This will panic!
230/// query: Query<(EntityRef, &mut ComponentA)>
231/// # ) {}
232/// # bevy_ecs::system::assert_system_does_not_conflict(system);
233/// ```
234/// ```
235/// # use bevy_ecs::prelude::*;
236/// # #[derive(Component)]
237/// # struct ComponentA;
238/// # #[derive(Component)]
239/// # struct ComponentB;
240/// # fn system(
241/// // This will not panic.
242/// query_a: Query<EntityRef, With<ComponentA>>,
243/// query_b: Query<&mut ComponentB, Without<ComponentA>>,
244/// # ) {}
245/// # bevy_ecs::system::assert_system_does_not_conflict(system);
246/// ```
247///
248/// # Accessing query items
249///
250/// The following table summarizes the behavior of the safe methods that can be used to get query items.
251///
252/// |Query methods|Effect|
253/// |:---:|---|
254/// |[`iter`]\[[`_mut`][`iter_mut`]]|Returns an iterator over all query items.|
255/// |[[`iter().for_each()`][`for_each`]\[[`iter_mut().for_each()`][`for_each`]],<br>[`par_iter`]\[[`_mut`][`par_iter_mut`]]|Runs a specified function for each query item.|
256/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]]|Iterates or runs a specified function over query items generated by a list of entities.|
257/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]]|Returns an iterator over all combinations of a specified number of query items.|
258/// |[`get`]\[[`_mut`][`get_mut`]]|Returns the query item for the specified entity.|
259/// |[`many`]\[[`_mut`][`many_mut`]],<br>[`get_many`]\[[`_mut`][`get_many_mut`]]|Returns the query items for the specified entities.|
260/// |[`single`]\[[`_mut`][`single_mut`]],<br>[`get_single`]\[[`_mut`][`get_single_mut`]]|Returns the query item while verifying that there aren't others.|
261///
262/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).
263/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.
264/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
265///
266/// # Performance
267///
268/// Creating a `Query` is a low-cost constant operation.
269/// Iterating it, on the other hand, fetches data from the world and generates items, which can have a significant computational cost.
270///
271/// [`Table`] component storage type is much more optimized for query iteration than [`SparseSet`].
272///
273/// Two systems cannot be executed in parallel if both access the same component type where at least one of the accesses is mutable.
274/// This happens unless the executor can verify that no entity could be found in both queries.
275///
276/// Optional components increase the number of entities a query has to match against.
277/// This can hurt iteration performance, especially if the query solely consists of only optional components, since the query would iterate over each entity in the world.
278///
279/// The following table compares the computational complexity of the various methods and operations, where:
280///
281/// - **n** is the number of entities that match the query,
282/// - **r** is the number of elements in a combination,
283/// - **k** is the number of involved entities in the operation,
284/// - **a** is the number of archetypes in the world,
285/// - **C** is the [binomial coefficient], used to count combinations.
286/// <sub>n</sub>C<sub>r</sub> is read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r* elements that can be taken from a set of *n* elements.
287///
288/// |Query operation|Computational complexity|
289/// |:---:|:---:|
290/// |[`iter`]\[[`_mut`][`iter_mut`]]|O(n)|
291/// |[[`iter().for_each()`][`for_each`]\[[`iter_mut().for_each()`][`for_each`]],<br>[`par_iter`]\[[`_mut`][`par_iter_mut`]]|O(n)|
292/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]]|O(k)|
293/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]]|O(<sub>n</sub>C<sub>r</sub>)|
294/// |[`get`]\[[`_mut`][`get_mut`]]|O(1)|
295/// |([`get_`][`get_many`])[`many`]|O(k)|
296/// |([`get_`][`get_many_mut`])[`many_mut`]|O(k<sup>2</sup>)|
297/// |[`single`]\[[`_mut`][`single_mut`]],<br>[`get_single`]\[[`_mut`][`get_single_mut`]]|O(a)|
298/// |Archetype based filtering ([`With`], [`Without`], [`Or`])|O(a)|
299/// |Change detection filtering ([`Added`], [`Changed`])|O(a + n)|
300///
301/// # `Iterator::for_each`
302///
303/// `for_each` methods are seen to be generally faster than directly iterating through `iter` on worlds with high archetype
304/// fragmentation, and may enable additional optimizations like [autovectorization]. It is strongly advised to only use
305/// [`Iterator::for_each`] if it tangibly improves performance. *Always* be sure profile or benchmark both before and
306/// after the change!
307///
308/// ```rust
309/// # use bevy_ecs::prelude::*;
310/// # #[derive(Component)]
311/// # struct ComponentA;
312/// # fn system(
313/// # query: Query<&ComponentA>,
314/// # ) {
315/// // This might be result in better performance...
316/// query.iter().for_each(|component| {
317/// // do things with the component
318/// });
319/// // ...than this. Always be sure to benchmark to validate the difference!
320/// for component in query.iter() {
321/// // do things with the component
322/// }
323/// # }
324/// # bevy_ecs::system::assert_system_does_not_conflict(system);
325/// ```
326///
327/// [`Component`]: crate::component::Component
328/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization
329/// [`Added`]: crate::query::Added
330/// [`AnyOf`]: crate::query::AnyOf
331/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient
332/// [`Changed`]: crate::query::Changed
333/// [components]: crate::component::Component
334/// [entity identifiers]: Entity
335/// [`EntityRef`]: crate::world::EntityRef
336/// [`for_each`]: #iterator-for-each
337/// [`get`]: Self::get
338/// [`get_many`]: Self::get_many
339/// [`get_many_mut`]: Self::get_many_mut
340/// [`get_mut`]: Self::get_mut
341/// [`get_single`]: Self::get_single
342/// [`get_single_mut`]: Self::get_single_mut
343/// [`iter`]: Self::iter
344/// [`iter_combinations`]: Self::iter_combinations
345/// [`iter_combinations_mut`]: Self::iter_combinations_mut
346/// [`iter_many`]: Self::iter_many
347/// [`iter_many_mut`]: Self::iter_many_mut
348/// [`iter_mut`]: Self::iter_mut
349/// [`many`]: Self::many
350/// [`many_mut`]: Self::many_mut
351/// [`Or`]: crate::query::Or
352/// [`par_iter`]: Self::par_iter
353/// [`par_iter_mut`]: Self::par_iter_mut
354/// [performance]: #performance
355/// [`Single`]: Single
356/// [`Option<Single>`]: Single
357/// [`single`]: Self::single
358/// [`single_mut`]: Self::single_mut
359/// [`SparseSet`]: crate::storage::SparseSet
360/// [System parameter]: crate::system::SystemParam
361/// [`Table`]: crate::storage::Table
362/// [`With`]: crate::query::With
363/// [`Without`]: crate::query::Without
364pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {
365 // SAFETY: Must have access to the components registered in `state`.
366 world: UnsafeWorldCell<'world>,
367 state: &'state QueryState<D, F>,
368 last_run: Tick,
369 this_run: Tick,
370}
371
372impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {
373 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
374 f.debug_struct("Query")
375 .field("matched_entities", &self.iter().count())
376 .field("state", &self.state)
377 .field("last_run", &self.last_run)
378 .field("this_run", &self.this_run)
379 .field("world", &self.world)
380 .finish()
381 }
382}
383
384impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
385 /// Creates a new query.
386 ///
387 /// # Panics
388 ///
389 /// This will panic if the world used to create `state` is not `world`.
390 ///
391 /// # Safety
392 ///
393 /// This will create a query that could violate memory safety rules. Make sure that this is only
394 /// called in ways that ensure the queries have unique mutable access.
395 #[inline]
396 pub(crate) unsafe fn new(
397 world: UnsafeWorldCell<'w>,
398 state: &'s QueryState<D, F>,
399 last_run: Tick,
400 this_run: Tick,
401 ) -> Self {
402 state.validate_world(world.id());
403
404 Self {
405 world,
406 state,
407 last_run,
408 this_run,
409 }
410 }
411
412 /// Returns another `Query` from this that fetches the read-only version of the query items.
413 ///
414 /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
415 /// This can be useful when working around the borrow checker,
416 /// or reusing functionality between systems via functions that accept query types.
417 pub fn to_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {
418 let new_state = self.state.as_readonly();
419 // SAFETY: This is memory safe because it turns the query immutable.
420 unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
421 }
422
423 /// Returns a new `Query` reborrowing the access from this one. The current query will be unusable
424 /// while the new one exists.
425 ///
426 /// # Example
427 ///
428 /// For example this allows to call other methods or other systems that require an owned `Query` without
429 /// completely giving up ownership of it.
430 ///
431 /// ```
432 /// # use bevy_ecs::prelude::*;
433 /// #
434 /// # #[derive(Component)]
435 /// # struct ComponentA;
436 ///
437 /// fn helper_system(query: Query<&ComponentA>) { /* ... */}
438 ///
439 /// fn system(mut query: Query<&ComponentA>) {
440 /// helper_system(query.reborrow());
441 /// // Can still use query here:
442 /// for component in &query {
443 /// // ...
444 /// }
445 /// }
446 /// ```
447 pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {
448 // SAFETY: this query is exclusively borrowed while the new one exists, so
449 // no overlapping access can occur.
450 unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }
451 }
452
453 /// Returns an [`Iterator`] over the read-only query items.
454 ///
455 /// This iterator is always guaranteed to return results from each matching entity once and only once.
456 /// Iteration order is not guaranteed.
457 ///
458 /// # Example
459 ///
460 /// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:
461 ///
462 /// ```
463 /// # use bevy_ecs::prelude::*;
464 /// #
465 /// # #[derive(Component)]
466 /// # struct Player { name: String }
467 /// #
468 /// fn report_names_system(query: Query<&Player>) {
469 /// for player in &query {
470 /// println!("Say hello to {}!", player.name);
471 /// }
472 /// }
473 /// # bevy_ecs::system::assert_is_system(report_names_system);
474 /// ```
475 ///
476 /// # See also
477 ///
478 /// [`iter_mut`](Self::iter_mut) for mutable query items.
479 #[inline]
480 pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {
481 // SAFETY:
482 // - `self.world` has permission to access the required components.
483 // - The query is read-only, so it can be aliased even if it was originally mutable.
484 unsafe {
485 self.state
486 .as_readonly()
487 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
488 }
489 }
490
491 /// Returns an [`Iterator`] over the query items.
492 ///
493 /// This iterator is always guaranteed to return results from each matching entity once and only once.
494 /// Iteration order is not guaranteed.
495 ///
496 /// # Example
497 ///
498 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
499 ///
500 /// ```
501 /// # use bevy_ecs::prelude::*;
502 /// #
503 /// # #[derive(Component)]
504 /// # struct Velocity { x: f32, y: f32, z: f32 }
505 /// fn gravity_system(mut query: Query<&mut Velocity>) {
506 /// const DELTA: f32 = 1.0 / 60.0;
507 /// for mut velocity in &mut query {
508 /// velocity.y -= 9.8 * DELTA;
509 /// }
510 /// }
511 /// # bevy_ecs::system::assert_is_system(gravity_system);
512 /// ```
513 ///
514 /// # See also
515 ///
516 /// [`iter`](Self::iter) for read-only query items.
517 #[inline]
518 pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {
519 // SAFETY: `self.world` has permission to access the required components.
520 unsafe {
521 self.state
522 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
523 }
524 }
525
526 /// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.
527 ///
528 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
529 /// Iteration order is not guaranteed.
530 ///
531 /// # Example
532 ///
533 /// ```
534 /// # use bevy_ecs::prelude::*;
535 /// # #[derive(Component)]
536 /// # struct ComponentA;
537 /// #
538 /// fn some_system(query: Query<&ComponentA>) {
539 /// for [a1, a2] in query.iter_combinations() {
540 /// // ...
541 /// }
542 /// }
543 /// ```
544 ///
545 /// # See also
546 ///
547 /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
548 #[inline]
549 pub fn iter_combinations<const K: usize>(
550 &self,
551 ) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {
552 // SAFETY:
553 // - `self.world` has permission to access the required components.
554 // - The query is read-only, so it can be aliased even if it was originally mutable.
555 unsafe {
556 self.state.as_readonly().iter_combinations_unchecked_manual(
557 self.world,
558 self.last_run,
559 self.this_run,
560 )
561 }
562 }
563
564 /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
565 ///
566 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
567 /// Iteration order is not guaranteed.
568 ///
569 /// # Example
570 ///
571 /// ```
572 /// # use bevy_ecs::prelude::*;
573 /// # #[derive(Component)]
574 /// # struct ComponentA;
575 /// fn some_system(mut query: Query<&mut ComponentA>) {
576 /// let mut combinations = query.iter_combinations_mut();
577 /// while let Some([mut a1, mut a2]) = combinations.fetch_next() {
578 /// // mutably access components data
579 /// }
580 /// }
581 /// ```
582 ///
583 /// # See also
584 ///
585 /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
586 #[inline]
587 pub fn iter_combinations_mut<const K: usize>(
588 &mut self,
589 ) -> QueryCombinationIter<'_, 's, D, F, K> {
590 // SAFETY: `self.world` has permission to access the required components.
591 unsafe {
592 self.state
593 .iter_combinations_unchecked_manual(self.world, self.last_run, self.this_run)
594 }
595 }
596
597 /// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
598 ///
599 /// Items are returned in the order of the list of entities, and may not be unique if the input
600 /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
601 ///
602 /// # Example
603 ///
604 /// ```
605 /// # use bevy_ecs::prelude::*;
606 /// # #[derive(Component)]
607 /// # struct Counter {
608 /// # value: i32
609 /// # }
610 /// #
611 /// // A component containing an entity list.
612 /// #[derive(Component)]
613 /// struct Friends {
614 /// list: Vec<Entity>,
615 /// }
616 ///
617 /// fn system(
618 /// friends_query: Query<&Friends>,
619 /// counter_query: Query<&Counter>,
620 /// ) {
621 /// for friends in &friends_query {
622 /// for counter in counter_query.iter_many(&friends.list) {
623 /// println!("Friend's counter: {:?}", counter.value);
624 /// }
625 /// }
626 /// }
627 /// # bevy_ecs::system::assert_is_system(system);
628 /// ```
629 ///
630 /// # See also
631 ///
632 /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
633 #[inline]
634 pub fn iter_many<EntityList: IntoIterator<Item: Borrow<Entity>>>(
635 &self,
636 entities: EntityList,
637 ) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
638 // SAFETY:
639 // - `self.world` has permission to access the required components.
640 // - The query is read-only, so it can be aliased even if it was originally mutable.
641 unsafe {
642 self.state.as_readonly().iter_many_unchecked_manual(
643 entities,
644 self.world,
645 self.last_run,
646 self.this_run,
647 )
648 }
649 }
650
651 /// Returns an iterator over the query items generated from an [`Entity`] list.
652 ///
653 /// Items are returned in the order of the list of entities, and may not be unique if the input
654 /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
655 ///
656 /// # Examples
657 ///
658 /// ```
659 /// # use bevy_ecs::prelude::*;
660 /// #[derive(Component)]
661 /// struct Counter {
662 /// value: i32
663 /// }
664 ///
665 /// #[derive(Component)]
666 /// struct Friends {
667 /// list: Vec<Entity>,
668 /// }
669 ///
670 /// fn system(
671 /// friends_query: Query<&Friends>,
672 /// mut counter_query: Query<&mut Counter>,
673 /// ) {
674 /// for friends in &friends_query {
675 /// let mut iter = counter_query.iter_many_mut(&friends.list);
676 /// while let Some(mut counter) = iter.fetch_next() {
677 /// println!("Friend's counter: {:?}", counter.value);
678 /// counter.value += 1;
679 /// }
680 /// }
681 /// }
682 /// # bevy_ecs::system::assert_is_system(system);
683 /// ```
684 #[inline]
685 pub fn iter_many_mut<EntityList: IntoIterator<Item: Borrow<Entity>>>(
686 &mut self,
687 entities: EntityList,
688 ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
689 // SAFETY: `self.world` has permission to access the required components.
690 unsafe {
691 self.state.iter_many_unchecked_manual(
692 entities,
693 self.world,
694 self.last_run,
695 self.this_run,
696 )
697 }
698 }
699
700 /// Returns an [`Iterator`] over the query items.
701 ///
702 /// This iterator is always guaranteed to return results from each matching entity once and only once.
703 /// Iteration order is not guaranteed.
704 ///
705 /// # Safety
706 ///
707 /// This function makes it possible to violate Rust's aliasing guarantees.
708 /// You must make sure this call does not result in multiple mutable references to the same component.
709 ///
710 /// # See also
711 ///
712 /// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.
713 #[inline]
714 pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {
715 // SAFETY:
716 // - `self.world` has permission to access the required components.
717 // - The caller ensures that this operation will not result in any aliased mutable accesses.
718 unsafe {
719 self.state
720 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
721 }
722 }
723
724 /// Iterates over all possible combinations of `K` query items without repetition.
725 ///
726 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
727 /// Iteration order is not guaranteed.
728 ///
729 /// # Safety
730 ///
731 /// This allows aliased mutability.
732 /// You must make sure this call does not result in multiple mutable references to the same component.
733 ///
734 /// # See also
735 ///
736 /// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.
737 #[inline]
738 pub unsafe fn iter_combinations_unsafe<const K: usize>(
739 &self,
740 ) -> QueryCombinationIter<'_, 's, D, F, K> {
741 // SAFETY:
742 // - `self.world` has permission to access the required components.
743 // - The caller ensures that this operation will not result in any aliased mutable accesses.
744 unsafe {
745 self.state
746 .iter_combinations_unchecked_manual(self.world, self.last_run, self.this_run)
747 }
748 }
749
750 /// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.
751 ///
752 /// Items are returned in the order of the list of entities, and may not be unique if the input
753 /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
754 ///
755 /// # Safety
756 ///
757 /// This allows aliased mutability and does not check for entity uniqueness.
758 /// You must make sure this call does not result in multiple mutable references to the same component.
759 /// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].
760 ///
761 /// # See also
762 ///
763 /// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.
764 pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: Borrow<Entity>>>(
765 &self,
766 entities: EntityList,
767 ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
768 // SAFETY:
769 // - `self.world` has permission to access the required components.
770 // - The caller ensures that this operation will not result in any aliased mutable accesses.
771 unsafe {
772 self.state.iter_many_unchecked_manual(
773 entities,
774 self.world,
775 self.last_run,
776 self.this_run,
777 )
778 }
779 }
780
781 /// Returns a parallel iterator over the query results for the given [`World`].
782 ///
783 /// This parallel iterator is always guaranteed to return results from each matching entity once and
784 /// only once. Iteration order and thread assignment is not guaranteed.
785 ///
786 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
787 /// on [`QueryIter`].
788 ///
789 /// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
790 ///
791 /// Note that you must use the `for_each` method to iterate over the
792 /// results, see [`par_iter_mut`] for an example.
793 ///
794 /// [`par_iter_mut`]: Self::par_iter_mut
795 /// [`World`]: crate::world::World
796 #[inline]
797 pub fn par_iter(&self) -> QueryParIter<'_, '_, D::ReadOnly, F> {
798 QueryParIter {
799 world: self.world,
800 state: self.state.as_readonly(),
801 last_run: self.last_run,
802 this_run: self.this_run,
803 batching_strategy: BatchingStrategy::new(),
804 }
805 }
806
807 /// Returns a parallel iterator over the query results for the given [`World`].
808 ///
809 /// This parallel iterator is always guaranteed to return results from each matching entity once and
810 /// only once. Iteration order and thread assignment is not guaranteed.
811 ///
812 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
813 /// on [`QueryIter`].
814 ///
815 /// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
816 ///
817 /// # Example
818 ///
819 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
820 ///
821 /// ```
822 /// # use bevy_ecs::prelude::*;
823 /// #
824 /// # #[derive(Component)]
825 /// # struct Velocity { x: f32, y: f32, z: f32 }
826 /// fn gravity_system(mut query: Query<&mut Velocity>) {
827 /// const DELTA: f32 = 1.0 / 60.0;
828 /// query.par_iter_mut().for_each(|mut velocity| {
829 /// velocity.y -= 9.8 * DELTA;
830 /// });
831 /// }
832 /// # bevy_ecs::system::assert_is_system(gravity_system);
833 /// ```
834 ///
835 /// [`par_iter`]: Self::par_iter
836 /// [`World`]: crate::world::World
837 #[inline]
838 pub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F> {
839 QueryParIter {
840 world: self.world,
841 state: self.state,
842 last_run: self.last_run,
843 this_run: self.this_run,
844 batching_strategy: BatchingStrategy::new(),
845 }
846 }
847
848 /// Returns the read-only query item for the given [`Entity`].
849 ///
850 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
851 ///
852 /// This is always guaranteed to run in `O(1)` time.
853 ///
854 /// # Example
855 ///
856 /// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.
857 ///
858 /// ```
859 /// # use bevy_ecs::prelude::*;
860 /// #
861 /// # #[derive(Resource)]
862 /// # struct SelectedCharacter { entity: Entity }
863 /// # #[derive(Component)]
864 /// # struct Character { name: String }
865 /// #
866 /// fn print_selected_character_name_system(
867 /// query: Query<&Character>,
868 /// selection: Res<SelectedCharacter>
869 /// )
870 /// {
871 /// if let Ok(selected_character) = query.get(selection.entity) {
872 /// println!("{}", selected_character.name);
873 /// }
874 /// }
875 /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
876 /// ```
877 ///
878 /// # See also
879 ///
880 /// - [`get_mut`](Self::get_mut) to get a mutable query item.
881 #[inline]
882 pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, D>, QueryEntityError> {
883 // SAFETY: system runs without conflicts with other systems.
884 // same-system queries have runtime borrow checks when they conflict
885 unsafe {
886 self.state.as_readonly().get_unchecked_manual(
887 self.world,
888 entity,
889 self.last_run,
890 self.this_run,
891 )
892 }
893 }
894
895 /// Returns the read-only query items for the given array of [`Entity`].
896 ///
897 /// The returned query items are in the same order as the input.
898 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
899 /// The elements of the array do not need to be unique, unlike `get_many_mut`.
900 ///
901 /// # See also
902 ///
903 /// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.
904 /// - [`many`](Self::many) for the panicking version.
905 #[inline]
906 pub fn get_many<const N: usize>(
907 &self,
908 entities: [Entity; N],
909 ) -> Result<[ROQueryItem<'_, D>; N], QueryEntityError> {
910 // SAFETY:
911 // - `&self` ensures there is no mutable access to any components accessible to this query.
912 // - `self.world` matches `self.state`.
913 unsafe {
914 self.state
915 .get_many_read_only_manual(self.world, entities, self.last_run, self.this_run)
916 }
917 }
918
919 /// Returns the read-only query items for the given array of [`Entity`].
920 ///
921 /// # Panics
922 ///
923 /// This method panics if there is a query mismatch or a non-existing entity.
924 ///
925 /// # Examples
926 /// ``` no_run
927 /// use bevy_ecs::prelude::*;
928 ///
929 /// #[derive(Component)]
930 /// struct Targets([Entity; 3]);
931 ///
932 /// #[derive(Component)]
933 /// struct Position{
934 /// x: i8,
935 /// y: i8
936 /// };
937 ///
938 /// impl Position {
939 /// fn distance(&self, other: &Position) -> i8 {
940 /// // Manhattan distance is way easier to compute!
941 /// (self.x - other.x).abs() + (self.y - other.y).abs()
942 /// }
943 /// }
944 ///
945 /// fn check_all_targets_in_range(targeting_query: Query<(Entity, &Targets, &Position)>, targets_query: Query<&Position>){
946 /// for (targeting_entity, targets, origin) in &targeting_query {
947 /// // We can use "destructuring" to unpack the results nicely
948 /// let [target_1, target_2, target_3] = targets_query.many(targets.0);
949 ///
950 /// assert!(target_1.distance(origin) <= 5);
951 /// assert!(target_2.distance(origin) <= 5);
952 /// assert!(target_3.distance(origin) <= 5);
953 /// }
954 /// }
955 /// ```
956 ///
957 /// # See also
958 ///
959 /// - [`get_many`](Self::get_many) for the non-panicking version.
960 #[inline]
961 #[track_caller]
962 pub fn many<const N: usize>(&self, entities: [Entity; N]) -> [ROQueryItem<'_, D>; N] {
963 match self.get_many(entities) {
964 Ok(items) => items,
965 Err(error) => panic!("Cannot get query results: {error}"),
966 }
967 }
968
969 /// Returns the query item for the given [`Entity`].
970 ///
971 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
972 ///
973 /// This is always guaranteed to run in `O(1)` time.
974 ///
975 /// # Example
976 ///
977 /// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.
978 ///
979 /// ```
980 /// # use bevy_ecs::prelude::*;
981 /// #
982 /// # #[derive(Resource)]
983 /// # struct PoisonedCharacter { character_id: Entity }
984 /// # #[derive(Component)]
985 /// # struct Health(u32);
986 /// #
987 /// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
988 /// if let Ok(mut health) = query.get_mut(poisoned.character_id) {
989 /// health.0 -= 1;
990 /// }
991 /// }
992 /// # bevy_ecs::system::assert_is_system(poison_system);
993 /// ```
994 ///
995 /// # See also
996 ///
997 /// - [`get`](Self::get) to get a read-only query item.
998 #[inline]
999 pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_>, QueryEntityError> {
1000 // SAFETY: system runs without conflicts with other systems.
1001 // same-system queries have runtime borrow checks when they conflict
1002 unsafe {
1003 self.state
1004 .get_unchecked_manual(self.world, entity, self.last_run, self.this_run)
1005 }
1006 }
1007
1008 /// Returns the query items for the given array of [`Entity`].
1009 ///
1010 /// The returned query items are in the same order as the input.
1011 /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1012 ///
1013 /// # See also
1014 ///
1015 /// - [`get_many`](Self::get_many) to get read-only query items.
1016 /// - [`many_mut`](Self::many_mut) for the panicking version.
1017 #[inline]
1018 pub fn get_many_mut<const N: usize>(
1019 &mut self,
1020 entities: [Entity; N],
1021 ) -> Result<[D::Item<'_>; N], QueryEntityError> {
1022 // SAFETY: scheduler ensures safe Query world access
1023 unsafe {
1024 self.state
1025 .get_many_unchecked_manual(self.world, entities, self.last_run, self.this_run)
1026 }
1027 }
1028
1029 /// Returns the query items for the given array of [`Entity`].
1030 ///
1031 /// # Panics
1032 ///
1033 /// This method panics if there is a query mismatch, a non-existing entity, or the same `Entity` is included more than once in the array.
1034 ///
1035 /// # Examples
1036 ///
1037 /// ``` no_run
1038 /// use bevy_ecs::prelude::*;
1039 ///
1040 /// #[derive(Component)]
1041 /// struct Spring{
1042 /// connected_entities: [Entity; 2],
1043 /// strength: f32,
1044 /// }
1045 ///
1046 /// #[derive(Component)]
1047 /// struct Position {
1048 /// x: f32,
1049 /// y: f32,
1050 /// }
1051 ///
1052 /// #[derive(Component)]
1053 /// struct Force {
1054 /// x: f32,
1055 /// y: f32,
1056 /// }
1057 ///
1058 /// fn spring_forces(spring_query: Query<&Spring>, mut mass_query: Query<(&Position, &mut Force)>){
1059 /// for spring in &spring_query {
1060 /// // We can use "destructuring" to unpack our query items nicely
1061 /// let [(position_1, mut force_1), (position_2, mut force_2)] = mass_query.many_mut(spring.connected_entities);
1062 ///
1063 /// force_1.x += spring.strength * (position_1.x - position_2.x);
1064 /// force_1.y += spring.strength * (position_1.y - position_2.y);
1065 ///
1066 /// // Silence borrow-checker: I have split your mutable borrow!
1067 /// force_2.x += spring.strength * (position_2.x - position_1.x);
1068 /// force_2.y += spring.strength * (position_2.y - position_1.y);
1069 /// }
1070 /// }
1071 /// ```
1072 ///
1073 /// # See also
1074 ///
1075 /// - [`get_many_mut`](Self::get_many_mut) for the non panicking version.
1076 /// - [`many`](Self::many) to get read-only query items.
1077 #[inline]
1078 #[track_caller]
1079 pub fn many_mut<const N: usize>(&mut self, entities: [Entity; N]) -> [D::Item<'_>; N] {
1080 match self.get_many_mut(entities) {
1081 Ok(items) => items,
1082 Err(error) => panic!("Cannot get query result: {error}"),
1083 }
1084 }
1085
1086 /// Returns the query item for the given [`Entity`].
1087 ///
1088 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1089 ///
1090 /// This is always guaranteed to run in `O(1)` time.
1091 ///
1092 /// # Safety
1093 ///
1094 /// This function makes it possible to violate Rust's aliasing guarantees.
1095 /// You must make sure this call does not result in multiple mutable references to the same component.
1096 ///
1097 /// # See also
1098 ///
1099 /// - [`get_mut`](Self::get_mut) for the safe version.
1100 #[inline]
1101 pub unsafe fn get_unchecked(&self, entity: Entity) -> Result<D::Item<'_>, QueryEntityError> {
1102 // SEMI-SAFETY: system runs without conflicts with other systems.
1103 // same-system queries have runtime borrow checks when they conflict
1104 unsafe {
1105 self.state
1106 .get_unchecked_manual(self.world, entity, self.last_run, self.this_run)
1107 }
1108 }
1109
1110 /// Returns a single read-only query item when there is exactly one entity matching the query.
1111 ///
1112 /// # Panics
1113 ///
1114 /// This method panics if the number of query items is **not** exactly one.
1115 ///
1116 /// # Example
1117 ///
1118 /// ```
1119 /// # use bevy_ecs::prelude::*;
1120 /// # #[derive(Component)]
1121 /// # struct Player;
1122 /// # #[derive(Component)]
1123 /// # struct Position(f32, f32);
1124 /// fn player_system(query: Query<&Position, With<Player>>) {
1125 /// let player_position = query.single();
1126 /// // do something with player_position
1127 /// }
1128 /// # bevy_ecs::system::assert_is_system(player_system);
1129 /// ```
1130 ///
1131 /// # See also
1132 ///
1133 /// - [`get_single`](Self::get_single) for the non-panicking version.
1134 /// - [`single_mut`](Self::single_mut) to get the mutable query item.
1135 #[track_caller]
1136 pub fn single(&self) -> ROQueryItem<'_, D> {
1137 self.get_single().unwrap()
1138 }
1139
1140 /// Returns a single read-only query item when there is exactly one entity matching the query.
1141 ///
1142 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1143 ///
1144 /// # Example
1145 ///
1146 /// ```
1147 /// # use bevy_ecs::prelude::*;
1148 /// # use bevy_ecs::query::QuerySingleError;
1149 /// # #[derive(Component)]
1150 /// # struct PlayerScore(i32);
1151 /// fn player_scoring_system(query: Query<&PlayerScore>) {
1152 /// match query.get_single() {
1153 /// Ok(PlayerScore(score)) => {
1154 /// println!("Score: {}", score);
1155 /// }
1156 /// Err(QuerySingleError::NoEntities(_)) => {
1157 /// println!("Error: There is no player!");
1158 /// }
1159 /// Err(QuerySingleError::MultipleEntities(_)) => {
1160 /// println!("Error: There is more than one player!");
1161 /// }
1162 /// }
1163 /// }
1164 /// # bevy_ecs::system::assert_is_system(player_scoring_system);
1165 /// ```
1166 ///
1167 /// # See also
1168 ///
1169 /// - [`get_single_mut`](Self::get_single_mut) to get the mutable query item.
1170 /// - [`single`](Self::single) for the panicking version.
1171 #[inline]
1172 pub fn get_single(&self) -> Result<ROQueryItem<'_, D>, QuerySingleError> {
1173 // SAFETY:
1174 // the query ensures that the components it accesses are not mutably accessible somewhere else
1175 // and the query is read only.
1176 unsafe {
1177 self.state.as_readonly().get_single_unchecked_manual(
1178 self.world,
1179 self.last_run,
1180 self.this_run,
1181 )
1182 }
1183 }
1184
1185 /// Returns a single query item when there is exactly one entity matching the query.
1186 ///
1187 /// # Panics
1188 ///
1189 /// This method panics if the number of query items is **not** exactly one.
1190 ///
1191 /// # Example
1192 ///
1193 /// ```
1194 /// # use bevy_ecs::prelude::*;
1195 /// #
1196 /// # #[derive(Component)]
1197 /// # struct Player;
1198 /// # #[derive(Component)]
1199 /// # struct Health(u32);
1200 /// #
1201 /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
1202 /// let mut health = query.single_mut();
1203 /// health.0 += 1;
1204 /// }
1205 /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1206 /// ```
1207 ///
1208 /// # See also
1209 ///
1210 /// - [`get_single_mut`](Self::get_single_mut) for the non-panicking version.
1211 /// - [`single`](Self::single) to get the read-only query item.
1212 #[track_caller]
1213 pub fn single_mut(&mut self) -> D::Item<'_> {
1214 self.get_single_mut().unwrap()
1215 }
1216
1217 /// Returns a single query item when there is exactly one entity matching the query.
1218 ///
1219 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1220 ///
1221 /// # Example
1222 ///
1223 /// ```
1224 /// # use bevy_ecs::prelude::*;
1225 /// #
1226 /// # #[derive(Component)]
1227 /// # struct Player;
1228 /// # #[derive(Component)]
1229 /// # struct Health(u32);
1230 /// #
1231 /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
1232 /// let mut health = query.get_single_mut().expect("Error: Could not find a single player.");
1233 /// health.0 += 1;
1234 /// }
1235 /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1236 /// ```
1237 ///
1238 /// # See also
1239 ///
1240 /// - [`get_single`](Self::get_single) to get the read-only query item.
1241 /// - [`single_mut`](Self::single_mut) for the panicking version.
1242 #[inline]
1243 pub fn get_single_mut(&mut self) -> Result<D::Item<'_>, QuerySingleError> {
1244 // SAFETY:
1245 // the query ensures mutable access to the components it accesses, and the query
1246 // is uniquely borrowed
1247 unsafe {
1248 self.state
1249 .get_single_unchecked_manual(self.world, self.last_run, self.this_run)
1250 }
1251 }
1252
1253 /// Returns `true` if there are no query items.
1254 ///
1255 /// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`
1256 /// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely
1257 /// on non-archetypal filters such as [`Added`] or [`Changed`] which must individually check each query
1258 /// result for a match.
1259 ///
1260 /// # Example
1261 ///
1262 /// Here, the score is increased only if an entity with a `Player` component is present in the world:
1263 ///
1264 /// ```
1265 /// # use bevy_ecs::prelude::*;
1266 /// #
1267 /// # #[derive(Component)]
1268 /// # struct Player;
1269 /// # #[derive(Resource)]
1270 /// # struct Score(u32);
1271 /// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
1272 /// if !query.is_empty() {
1273 /// score.0 += 1;
1274 /// }
1275 /// }
1276 /// # bevy_ecs::system::assert_is_system(update_score_system);
1277 /// ```
1278 ///
1279 /// [`Added`]: crate::query::Added
1280 /// [`Changed`]: crate::query::Changed
1281 #[inline]
1282 pub fn is_empty(&self) -> bool {
1283 // SAFETY:
1284 // - `self.world` has permission to read any data required by the WorldQuery.
1285 // - `&self` ensures that no one currently has write access.
1286 // - `self.world` matches `self.state`.
1287 unsafe {
1288 self.state
1289 .is_empty_unsafe_world_cell(self.world, self.last_run, self.this_run)
1290 }
1291 }
1292
1293 /// Returns `true` if the given [`Entity`] matches the query.
1294 ///
1295 /// This is always guaranteed to run in `O(1)` time.
1296 ///
1297 /// # Example
1298 ///
1299 /// ```
1300 /// # use bevy_ecs::prelude::*;
1301 /// #
1302 /// # #[derive(Component)]
1303 /// # struct InRange;
1304 /// #
1305 /// # #[derive(Resource)]
1306 /// # struct Target {
1307 /// # entity: Entity,
1308 /// # }
1309 /// #
1310 /// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
1311 /// if in_range_query.contains(target.entity) {
1312 /// println!("Bam!")
1313 /// }
1314 /// }
1315 /// # bevy_ecs::system::assert_is_system(targeting_system);
1316 /// ```
1317 #[inline]
1318 pub fn contains(&self, entity: Entity) -> bool {
1319 // SAFETY: NopFetch does not access any members while &self ensures no one has exclusive access
1320 unsafe {
1321 self.state
1322 .as_nop()
1323 .get_unchecked_manual(self.world, entity, self.last_run, self.this_run)
1324 .is_ok()
1325 }
1326 }
1327
1328 /// Returns a [`QueryLens`] that can be used to get a query with a more general fetch.
1329 ///
1330 /// For example, this can transform a `Query<(&A, &mut B)>` to a `Query<&B>`.
1331 /// This can be useful for passing the query to another function. Note that since
1332 /// filter terms are dropped, non-archetypal filters like [`Added`](crate::query::Added) and
1333 /// [`Changed`](crate::query::Changed) will not be respected. To maintain or change filter
1334 /// terms see [`Self::transmute_lens_filtered`]
1335 ///
1336 /// ## Panics
1337 ///
1338 /// This will panic if `NewD` is not a subset of the original fetch `Q`
1339 ///
1340 /// ## Example
1341 ///
1342 /// ```rust
1343 /// # use bevy_ecs::prelude::*;
1344 /// # use bevy_ecs::system::QueryLens;
1345 /// #
1346 /// # #[derive(Component)]
1347 /// # struct A(usize);
1348 /// #
1349 /// # #[derive(Component)]
1350 /// # struct B(usize);
1351 /// #
1352 /// # let mut world = World::new();
1353 /// #
1354 /// # world.spawn((A(10), B(5)));
1355 /// #
1356 /// fn reusable_function(lens: &mut QueryLens<&A>) {
1357 /// assert_eq!(lens.query().single().0, 10);
1358 /// }
1359 ///
1360 /// // We can use the function in a system that takes the exact query.
1361 /// fn system_1(mut query: Query<&A>) {
1362 /// reusable_function(&mut query.as_query_lens());
1363 /// }
1364 ///
1365 /// // We can also use it with a query that does not match exactly
1366 /// // by transmuting it.
1367 /// fn system_2(mut query: Query<(&mut A, &B)>) {
1368 /// let mut lens = query.transmute_lens::<&A>();
1369 /// reusable_function(&mut lens);
1370 /// }
1371 ///
1372 /// # let mut schedule = Schedule::default();
1373 /// # schedule.add_systems((system_1, system_2));
1374 /// # schedule.run(&mut world);
1375 /// ```
1376 ///
1377 /// ## Allowed Transmutes
1378 ///
1379 /// Besides removing parameters from the query, you can also
1380 /// make limited changes to the types of parameters.
1381 ///
1382 /// * Can always add/remove [`Entity`]
1383 /// * Can always add/remove [`EntityLocation`]
1384 /// * Can always add/remove [`&Archetype`]
1385 /// * `Ref<T>` <-> `&T`
1386 /// * `&mut T` -> `&T`
1387 /// * `&mut T` -> `Ref<T>`
1388 /// * [`EntityMut`](crate::world::EntityMut) -> [`EntityRef`](crate::world::EntityRef)
1389 ///
1390 /// [`EntityLocation`]: crate::entity::EntityLocation
1391 /// [`&Archetype`]: crate::archetype::Archetype
1392 #[track_caller]
1393 pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {
1394 self.transmute_lens_filtered::<NewD, ()>()
1395 }
1396
1397 /// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.
1398 ///
1399 /// Note that the lens will iterate the same tables and archetypes as the original query. This means that
1400 /// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
1401 /// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added) and
1402 /// [`Changed`](crate::query::Changed) will only be respected if they are in the type signature.
1403 #[track_caller]
1404 pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(
1405 &mut self,
1406 ) -> QueryLens<'_, NewD, NewF> {
1407 let state = self.state.transmute_filtered::<NewD, NewF>(self.world);
1408 QueryLens {
1409 world: self.world,
1410 state,
1411 last_run: self.last_run,
1412 this_run: self.this_run,
1413 }
1414 }
1415
1416 /// Gets a [`QueryLens`] with the same accesses as the existing query
1417 pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {
1418 self.transmute_lens()
1419 }
1420
1421 /// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
1422 ///
1423 /// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
1424 /// The returned query will only return items with both `A` and `B`. Note that since filters
1425 /// are dropped, non-archetypal filters like `Added` and `Changed` will not be respected.
1426 /// To maintain or change filter terms see `Self::join_filtered`.
1427 ///
1428 /// ## Example
1429 ///
1430 /// ```rust
1431 /// # use bevy_ecs::prelude::*;
1432 /// # use bevy_ecs::system::QueryLens;
1433 /// #
1434 /// # #[derive(Component)]
1435 /// # struct Transform;
1436 /// #
1437 /// # #[derive(Component)]
1438 /// # struct Player;
1439 /// #
1440 /// # #[derive(Component)]
1441 /// # struct Enemy;
1442 /// #
1443 /// # let mut world = World::default();
1444 /// # world.spawn((Transform, Player));
1445 /// # world.spawn((Transform, Enemy));
1446 ///
1447 /// fn system(
1448 /// mut transforms: Query<&Transform>,
1449 /// mut players: Query<&Player>,
1450 /// mut enemies: Query<&Enemy>
1451 /// ) {
1452 /// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);
1453 /// for (transform, player) in &players_transforms.query() {
1454 /// // do something with a and b
1455 /// }
1456 ///
1457 /// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);
1458 /// for (transform, enemy) in &enemies_transforms.query() {
1459 /// // do something with a and b
1460 /// }
1461 /// }
1462 ///
1463 /// # let mut schedule = Schedule::default();
1464 /// # schedule.add_systems(system);
1465 /// # schedule.run(&mut world);
1466 /// ```
1467 /// ## Panics
1468 ///
1469 /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
1470 ///
1471 /// ## Allowed Transmutes
1472 ///
1473 /// Like `transmute_lens` the query terms can be changed with some restrictions.
1474 /// See [`Self::transmute_lens`] for more details.
1475 pub fn join<OtherD: QueryData, NewD: QueryData>(
1476 &mut self,
1477 other: &mut Query<OtherD>,
1478 ) -> QueryLens<'_, NewD> {
1479 self.join_filtered(other)
1480 }
1481
1482 /// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.
1483 ///
1484 /// Note that the lens with iterate a subset of the original queries' tables
1485 /// and archetypes. This means that additional archetypal query terms like
1486 /// `With` and `Without` will not necessarily be respected and non-archetypal
1487 /// terms like `Added` and `Changed` will only be respected if they are in
1488 /// the type signature.
1489 pub fn join_filtered<
1490 OtherD: QueryData,
1491 OtherF: QueryFilter,
1492 NewD: QueryData,
1493 NewF: QueryFilter,
1494 >(
1495 &mut self,
1496 other: &mut Query<OtherD, OtherF>,
1497 ) -> QueryLens<'_, NewD, NewF> {
1498 let state = self
1499 .state
1500 .join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);
1501 QueryLens {
1502 world: self.world,
1503 state,
1504 last_run: self.last_run,
1505 this_run: self.this_run,
1506 }
1507 }
1508}
1509
1510impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {
1511 type Item = ROQueryItem<'w, D>;
1512 type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;
1513
1514 fn into_iter(self) -> Self::IntoIter {
1515 self.iter()
1516 }
1517}
1518
1519impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {
1520 type Item = D::Item<'w>;
1521 type IntoIter = QueryIter<'w, 's, D, F>;
1522
1523 fn into_iter(self) -> Self::IntoIter {
1524 self.iter_mut()
1525 }
1526}
1527
1528impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter> Query<'w, 's, D, F> {
1529 /// Returns the query item for the given [`Entity`], with the actual "inner" world lifetime.
1530 ///
1531 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is
1532 /// returned instead.
1533 ///
1534 /// This can only return immutable data (mutable data will be cast to an immutable form).
1535 /// See [`get_mut`](Self::get_mut) for queries that contain at least one mutable component.
1536 ///
1537 /// # Example
1538 ///
1539 /// Here, `get` is used to retrieve the exact query item of the entity specified by the
1540 /// `SelectedCharacter` resource.
1541 ///
1542 /// ```
1543 /// # use bevy_ecs::prelude::*;
1544 /// #
1545 /// # #[derive(Resource)]
1546 /// # struct SelectedCharacter { entity: Entity }
1547 /// # #[derive(Component)]
1548 /// # struct Character { name: String }
1549 /// #
1550 /// fn print_selected_character_name_system(
1551 /// query: Query<&Character>,
1552 /// selection: Res<SelectedCharacter>
1553 /// )
1554 /// {
1555 /// if let Ok(selected_character) = query.get(selection.entity) {
1556 /// println!("{}", selected_character.name);
1557 /// }
1558 /// }
1559 /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
1560 /// ```
1561 #[inline]
1562 pub fn get_inner(&self, entity: Entity) -> Result<ROQueryItem<'w, D>, QueryEntityError> {
1563 // SAFETY: system runs without conflicts with other systems.
1564 // same-system queries have runtime borrow checks when they conflict
1565 unsafe {
1566 self.state.as_readonly().get_unchecked_manual(
1567 self.world,
1568 entity,
1569 self.last_run,
1570 self.this_run,
1571 )
1572 }
1573 }
1574
1575 /// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.
1576 ///
1577 /// This can only return immutable data (mutable data will be cast to an immutable form).
1578 /// See [`Self::iter_mut`] for queries that contain at least one mutable component.
1579 ///
1580 /// # Example
1581 ///
1582 /// Here, the `report_names_system` iterates over the `Player` component of every entity
1583 /// that contains it:
1584 ///
1585 /// ```
1586 /// # use bevy_ecs::prelude::*;
1587 /// #
1588 /// # #[derive(Component)]
1589 /// # struct Player { name: String }
1590 /// #
1591 /// fn report_names_system(query: Query<&Player>) {
1592 /// for player in &query {
1593 /// println!("Say hello to {}!", player.name);
1594 /// }
1595 /// }
1596 /// # bevy_ecs::system::assert_is_system(report_names_system);
1597 /// ```
1598 #[inline]
1599 pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {
1600 // SAFETY: system runs without conflicts with other systems.
1601 // same-system queries have runtime borrow checks when they conflict
1602 unsafe {
1603 self.state
1604 .as_readonly()
1605 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
1606 }
1607 }
1608}
1609
1610/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].
1611///
1612/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]
1613pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {
1614 world: UnsafeWorldCell<'w>,
1615 state: QueryState<Q, F>,
1616 last_run: Tick,
1617 this_run: Tick,
1618}
1619
1620impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {
1621 /// Create a [`Query`] from the underlying [`QueryState`].
1622 pub fn query(&mut self) -> Query<'w, '_, Q, F> {
1623 Query {
1624 world: self.world,
1625 state: &self.state,
1626 last_run: self.last_run,
1627 this_run: self.this_run,
1628 }
1629 }
1630}
1631
1632impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>
1633 for Query<'w, 's, Q, F>
1634{
1635 fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'w, 's, Q, F> {
1636 value.query()
1637 }
1638}
1639
1640impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>
1641 for QueryLens<'q, Q, F>
1642{
1643 fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {
1644 value.transmute_lens_filtered()
1645 }
1646}
1647
1648/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].
1649///
1650/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.
1651/// /// This will cause a panic, but can be configured to do nothing or warn once.
1652///
1653/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.
1654///
1655/// See [`Query`] for more details.
1656///
1657/// [System parameter]: crate::system::SystemParam
1658pub struct Single<'w, D: QueryData, F: QueryFilter = ()> {
1659 pub(crate) item: D::Item<'w>,
1660 pub(crate) _filter: PhantomData<F>,
1661}
1662
1663impl<'w, D: QueryData, F: QueryFilter> Deref for Single<'w, D, F> {
1664 type Target = D::Item<'w>;
1665
1666 fn deref(&self) -> &Self::Target {
1667 &self.item
1668 }
1669}
1670
1671impl<'w, D: QueryData, F: QueryFilter> DerefMut for Single<'w, D, F> {
1672 fn deref_mut(&mut self) -> &mut Self::Target {
1673 &mut self.item
1674 }
1675}
1676
1677impl<'w, D: QueryData, F: QueryFilter> Single<'w, D, F> {
1678 /// Returns the inner item with ownership.
1679 pub fn into_inner(self) -> D::Item<'w> {
1680 self.item
1681 }
1682}
1683
1684/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.
1685///
1686/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.
1687/// /// This will cause a panic, but can be configured to do nothing or warn once.
1688///
1689/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.
1690/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added) or [`Changed`](crate::query::Changed)
1691/// which must individually check each query result for a match.
1692///
1693/// See [`Query`] for more details.
1694///
1695/// [System parameter]: crate::system::SystemParam
1696pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);
1697
1698impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {
1699 type Target = Query<'w, 's, D, F>;
1700
1701 fn deref(&self) -> &Self::Target {
1702 &self.0
1703 }
1704}
1705
1706impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {
1707 fn deref_mut(&mut self) -> &mut Self::Target {
1708 &mut self.0
1709 }
1710}
1711
1712impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {
1713 /// Returns the inner item with ownership.
1714 pub fn into_inner(self) -> Query<'w, 's, D, F> {
1715 self.0
1716 }
1717}