Skip to main content

bevy_ecs/query/
fetch.rs

1use crate::{
2    archetype::{Archetype, Archetypes},
3    bundle::Bundle,
4    change_detection::{
5        ComponentTicksMut, ComponentTicksRef, ContiguousComponentTicksMut,
6        ContiguousComponentTicksRef, ContiguousMut, ContiguousRef, MaybeLocation, Tick,
7    },
8    component::{Component, ComponentId, Components, Mutable, StorageType},
9    entity::{Entities, Entity, EntityLocation},
10    query::{
11        access_iter::{EcsAccessLevel, EcsAccessType},
12        Access, DebugCheckedUnwrap, FilteredAccess, FilteredAccessSet, QueryFilter, QueryState,
13        WorldQuery,
14    },
15    storage::{ComponentSparseSet, Table, TableRow},
16    system::Query,
17    world::{
18        unsafe_world_cell::UnsafeWorldCell, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept,
19        FilteredEntityMut, FilteredEntityRef, Mut, Ref, World,
20    },
21};
22use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref};
23use bevy_utils::prelude::DebugName;
24use core::{cell::UnsafeCell, iter, marker::PhantomData, panic::Location};
25use variadics_please::all_tuples;
26
27/// Types that can be fetched from a [`World`] using a [`Query`].
28///
29/// There are many types that natively implement this trait:
30///
31/// - **Component references. (&T and &mut T)**
32///   Fetches a component by reference (immutably or mutably).
33/// - **`QueryData` tuples.**
34///   If every element of a tuple implements `QueryData`, then the tuple itself also implements the same trait.
35///   This enables a single `Query` to access multiple components.
36///   Due to the current lack of variadic generics in Rust, the trait has been implemented for tuples from 0 to 15 elements,
37///   but nesting of tuples allows infinite `WorldQuery`s.
38/// - **[`Entity`].**
39///   Gets the identifier of the queried entity.
40/// - **[`EntityLocation`].**
41///   Gets the location metadata of the queried entity.
42/// - **[`SpawnDetails`].**
43///   Gets the tick the entity was spawned at.
44/// - **[`EntityRef`].**
45///   Read-only access to arbitrary components on the queried entity.
46/// - **[`EntityMut`].**
47///   Mutable access to arbitrary components on the queried entity.
48/// - **[`&Archetype`](Archetype).**
49///   Read-only access to the archetype-level metadata of the queried entity.
50/// - **[`Option`].**
51///   By default, a world query only tests entities that have the matching component types.
52///   Wrapping it into an `Option` will increase the query search space, and it will return `None` if an entity doesn't satisfy the `WorldQuery`.
53/// - **[`AnyOf`].**
54///   Equivalent to wrapping each world query inside it into an `Option`.
55/// - **[`Ref`].**
56///   Similar to change detection filters but it is used as a query fetch parameter.
57///   It exposes methods to check for changes to the wrapped component.
58/// - **[`Mut`].**
59///   Mutable component access, with change detection data.
60/// - **[`Has`].**
61///   Returns a bool indicating whether the entity has the specified component.
62///
63/// Implementing the trait manually can allow for a fundamentally new type of behavior.
64///
65/// # Trait derivation
66///
67/// Query design can be easily structured by deriving `QueryData` for custom types.
68/// Despite the added complexity, this approach has several advantages over using `QueryData` tuples.
69/// The most relevant improvements are:
70///
71/// - Reusability across multiple systems.
72/// - There is no need to destructure a tuple since all fields are named.
73/// - Subqueries can be composed together to create a more complex query.
74/// - Methods can be implemented for the query items.
75/// - There is no hardcoded limit on the number of elements.
76///
77/// This trait can only be derived for structs, if each field also implements `QueryData`.
78///
79/// ```
80/// # use bevy_ecs::prelude::*;
81/// use bevy_ecs::query::QueryData;
82/// #
83/// # #[derive(Component)]
84/// # struct ComponentA;
85/// # #[derive(Component)]
86/// # struct ComponentB;
87///
88/// #[derive(QueryData)]
89/// struct MyQuery {
90///     entity: Entity,
91///     // It is required that all reference lifetimes are explicitly annotated, just like in any
92///     // struct. Each lifetime should be 'static.
93///     component_a: &'static ComponentA,
94///     component_b: &'static ComponentB,
95/// }
96///
97/// fn my_system(query: Query<MyQuery>) {
98///     for q in &query {
99///         q.component_a;
100///     }
101/// }
102/// # bevy_ecs::system::assert_is_system(my_system);
103/// ```
104///
105/// ## Macro expansion
106///
107/// Expanding the macro will declare one to five additional structs, depending on whether or not the struct is marked as mutable or as contiguous.
108/// For a struct named `X`, the additional structs will be:
109///
110/// |Struct name|`mutable` only|`contiguous` target|Description|
111/// |:---:|:---:|:---:|---|
112/// |`XItem`|---|---|The type of the query item for `X`|
113/// |`XReadOnlyItem`|✓|---|The type of the query item for `XReadOnly`|
114/// |`XReadOnly`|✓|---|[`ReadOnly`] variant of `X`|
115/// |`XContiguousItem`|---|`mutable` or `all`|The type of the contiguous query item for `X`|
116/// |`XReadOnlyContiguousItem`|✓|`immutable` or `all`|The type of the contiguous query item for `XReadOnly`|
117///
118/// ## Adding mutable references
119///
120/// Simply adding mutable references to a derived `QueryData` will result in a compilation error:
121///
122/// ```compile_fail
123/// # use bevy_ecs::prelude::*;
124/// # use bevy_ecs::query::QueryData;
125/// #
126/// # #[derive(Component)]
127/// # struct ComponentA;
128/// #
129/// #[derive(QueryData)]
130/// struct CustomQuery {
131///     component_a: &'static mut ComponentA,
132/// }
133/// ```
134///
135/// To grant mutable access to components, the struct must be marked with the `#[query_data(mutable)]` attribute.
136/// This will also create three more structs that will be used for accessing the query immutably (see table above).
137///
138/// ```
139/// # use bevy_ecs::prelude::*;
140/// # use bevy_ecs::query::QueryData;
141/// #
142/// # #[derive(Component)]
143/// # struct ComponentA;
144/// #
145/// #[derive(QueryData)]
146/// #[query_data(mutable)]
147/// struct CustomQuery {
148///     component_a: &'static mut ComponentA,
149/// }
150/// ```
151///
152/// ## Supporting contiguous iteration
153///
154/// To create contiguous items additionally (to support contiguous iteration), the struct must be marked with the `#[query_data(contiguous(target))]` attribute,
155/// where the target may be `all`, `mutable` or `immutable` (see the table above).
156///
157/// For mutable queries it may be done like this:
158/// ```
159/// # use bevy_ecs::prelude::*;
160/// # use bevy_ecs::query::QueryData;
161/// #
162/// # #[derive(Component)]
163/// # struct ComponentA;
164/// #
165/// #[derive(QueryData)]
166/// /// - contiguous(all) will create contiguous items for both read and mutable versions
167/// /// - contiguous(mutable) will only create a contiguous item for the mutable version
168/// /// - contiguous(immutable) will only create a contiguous item for the read only version
169/// #[query_data(mutable, contiguous(all))]
170/// struct CustomQuery {
171///     component_a: &'static mut ComponentA,
172/// }
173/// ```
174///
175/// For immutable queries `contiguous(immutable)` attribute will be **ignored**, meanwhile `contiguous(mutable)` and `contiguous(all)`
176/// will only generate a contiguous item for the (original) read only version.
177///
178/// To understand contiguous iteration refer to
179/// [`Query::contiguous_iter`](`crate::system::Query::contiguous_iter`)
180///
181/// ## Adding methods to query items
182///
183/// It is possible to add methods to query items in order to write reusable logic about related components.
184/// This will often make systems more readable because low level logic is moved out from them.
185/// It is done by adding `impl` blocks with methods for the `-Item`, `-ReadOnlyItem`, `-ContiguousItem` or `ContiguousReadOnlyItem`
186/// generated structs.
187///
188/// ```
189/// # use bevy_ecs::prelude::*;
190/// # use bevy_ecs::query::QueryData;
191/// #
192/// #[derive(Component)]
193/// struct Health(f32);
194///
195/// #[derive(Component)]
196/// struct Buff(f32);
197///
198/// #[derive(QueryData)]
199/// #[query_data(mutable)]
200/// struct HealthQuery {
201///     health: &'static mut Health,
202///     buff: Option<&'static mut Buff>,
203/// }
204///
205/// // `HealthQueryItem` is only available when accessing the query with mutable methods.
206/// impl<'w, 's> HealthQueryItem<'w, 's> {
207///     fn damage(&mut self, value: f32) {
208///         self.health.0 -= value;
209///     }
210///
211///     fn total(&self) -> f32 {
212///         self.health.0 + self.buff.as_deref().map_or(0.0, |Buff(buff)| *buff)
213///     }
214/// }
215///
216/// // `HealthQueryReadOnlyItem` is only available when accessing the query with immutable methods.
217/// impl<'w, 's> HealthQueryReadOnlyItem<'w, 's> {
218///     fn total(&self) -> f32 {
219///         self.health.0 + self.buff.map_or(0.0, |Buff(buff)| *buff)
220///     }
221/// }
222///
223/// fn my_system(mut health_query: Query<HealthQuery>) {
224///     // The item returned by the iterator is of type `HealthQueryReadOnlyItem`.
225///     for health in health_query.iter() {
226///         println!("Total: {}", health.total());
227///     }
228///     // The item returned by the iterator is of type `HealthQueryItem`.
229///     for mut health in &mut health_query {
230///         health.damage(1.0);
231///         println!("Total (mut): {}", health.total());
232///     }
233/// }
234/// # bevy_ecs::system::assert_is_system(my_system);
235/// ```
236///
237/// ## Deriving traits for query items
238///
239/// The `QueryData` derive macro does not automatically implement the traits of the struct to the query item types.
240/// Something similar can be done by using the `#[query_data(derive(...))]` attribute.
241/// This will apply the listed derivable traits to the query item structs.
242///
243/// ```
244/// # use bevy_ecs::prelude::*;
245/// # use bevy_ecs::query::QueryData;
246/// #
247/// # #[derive(Component, Debug)]
248/// # struct ComponentA;
249/// #
250/// #[derive(QueryData)]
251/// #[query_data(mutable, derive(Debug), contiguous(all))]
252/// struct CustomQuery {
253///     component_a: &'static ComponentA,
254/// }
255///
256/// // This function statically checks that `T` implements `Debug`.
257/// fn assert_debug<T: std::fmt::Debug>() {}
258///
259/// assert_debug::<CustomQueryItem>();
260/// assert_debug::<CustomQueryReadOnlyItem>();
261/// assert_debug::<CustomQueryContiguousItem>();
262/// assert_debug::<CustomQueryReadOnlyContiguousItem>();
263/// ```
264///
265/// ## Query composition
266///
267/// It is possible to use any `QueryData` as a field of another one.
268/// This means that a `QueryData` can also be used as a subquery, potentially in multiple places.
269///
270/// ```
271/// # use bevy_ecs::prelude::*;
272/// # use bevy_ecs::query::QueryData;
273/// #
274/// # #[derive(Component)]
275/// # struct ComponentA;
276/// # #[derive(Component)]
277/// # struct ComponentB;
278/// # #[derive(Component)]
279/// # struct ComponentC;
280/// #
281/// #[derive(QueryData)]
282/// struct SubQuery {
283///     component_a: &'static ComponentA,
284///     component_b: &'static ComponentB,
285/// }
286///
287/// #[derive(QueryData)]
288/// struct MyQuery {
289///     subquery: SubQuery,
290///     component_c: &'static ComponentC,
291/// }
292/// ```
293///
294/// # Generic Queries
295///
296/// When writing generic code, it is often necessary to use [`PhantomData`]
297/// to constrain type parameters. Since `QueryData` is implemented for all
298/// `PhantomData<T>` types, this pattern can be used with this macro.
299///
300/// ```
301/// # use bevy_ecs::{prelude::*, query::QueryData};
302/// # use std::marker::PhantomData;
303/// #[derive(QueryData)]
304/// pub struct GenericQuery<T> {
305///     id: Entity,
306///     marker: PhantomData<T>,
307/// }
308/// # fn my_system(q: Query<GenericQuery<()>>) {}
309/// # bevy_ecs::system::assert_is_system(my_system);
310/// ```
311///
312/// # Safety
313///
314/// - Component access of `Self::ReadOnly` must be a subset of `Self`
315///   and `Self::ReadOnly` must match exactly the same archetypes/tables as `Self`
316/// - `IS_READ_ONLY` must be `true` if and only if `Self: ReadOnlyQueryData`
317///
318/// [`ReadOnly`]: Self::ReadOnly
319#[diagnostic::on_unimplemented(
320    message = "`{Self}` is not valid to request as data in a `Query`",
321    label = "invalid `Query` data",
322    note = "if `{Self}` is a component type, try using `&{Self}` or `&mut {Self}`"
323)]
324pub unsafe trait QueryData: WorldQuery {
325    /// True if this query is read-only and may not perform mutable access.
326    const IS_READ_ONLY: bool;
327
328    /// Returns true if (and only if) this query data relies strictly on archetypes to limit which
329    /// entities are accessed by the Query.
330    ///
331    /// This enables optimizations for [`QueryIter`](`crate::query::QueryIter`) that rely on knowing exactly how
332    /// many elements are being iterated (such as `Iterator::collect()`).
333    ///
334    /// If this is `true`, then [`QueryData::fetch`] must always return `Some`.
335    const IS_ARCHETYPAL: bool;
336
337    /// The read-only variant of this [`QueryData`], which satisfies the [`ReadOnlyQueryData`] trait.
338    type ReadOnly: ReadOnlyQueryData<State = <Self as WorldQuery>::State>;
339
340    /// The item returned by this [`WorldQuery`]
341    /// This will be the data retrieved by the query,
342    /// and is visible to the end user when calling e.g. `Query<Self>::get`.
343    type Item<'w, 's>;
344
345    /// This function manually implements subtyping for the query items.
346    fn shrink<'wlong: 'wshort, 'wshort, 's>(
347        item: Self::Item<'wlong, 's>,
348    ) -> Self::Item<'wshort, 's>;
349
350    /// Offers additional access above what we requested in `update_component_access`.
351    /// Implementations may add additional access that is a subset of `available_access`
352    /// and does not conflict with anything in `access`,
353    /// and must update `access` to include that access.
354    ///
355    /// This is used by [`WorldQuery`] types like [`FilteredEntityRef`]
356    /// and [`FilteredEntityMut`] to support dynamic access.
357    ///
358    /// Called when constructing a [`QueryLens`](crate::system::QueryLens) or calling [`QueryState::from_builder`](super::QueryState::from_builder)
359    fn provide_extra_access(
360        _state: &mut Self::State,
361        _access: &mut Access,
362        _available_access: &Access,
363    ) {
364    }
365
366    /// Fetch [`Self::Item`](`QueryData::Item`) for either the given `entity` in the current [`Table`],
367    /// or for the given `entity` in the current [`Archetype`]. This must always be called after
368    /// [`WorldQuery::set_table`] with a `table_row` in the range of the current [`Table`] or after
369    /// [`WorldQuery::set_archetype`]  with an `entity` in the current archetype.
370    /// Accesses components registered in [`WorldQuery::update_component_access`].
371    ///
372    /// This method returns `None` if the entity does not match the query.
373    /// If `Self` implements [`ArchetypeQueryData`], this must always return `Some`.
374    ///
375    /// # Safety
376    ///
377    /// - Must always be called _after_ [`WorldQuery::set_table`] or [`WorldQuery::set_archetype`]. `entity` and
378    ///   `table_row` must be in the range of the current table and archetype.
379    /// - There must not be simultaneous conflicting component access registered in `update_component_access`.
380    /// - If `Self` does not impl `ReadOnlyQueryData`, then there must not be any other `Item`s alive for the current entity
381    /// - If `Self` does not impl `IterQueryData`, then there must not be any other `Item`s alive for *any* entity
382    unsafe fn fetch<'w, 's>(
383        state: &'s Self::State,
384        fetch: &mut Self::Fetch<'w>,
385        entity: Entity,
386        table_row: TableRow,
387    ) -> Option<Self::Item<'w, 's>>;
388
389    /// Returns an iterator over the access needed by [`QueryData::fetch`]. Access conflicts are usually
390    /// checked in [`WorldQuery::update_component_access`], but in certain cases this method can be useful to implement
391    /// a way of checking for access conflicts in a non-allocating way.
392    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>>;
393}
394
395/// A [`QueryData`] which allows getting a direct access to contiguous chunks of components'
396/// values, which may be used to apply simd-operations.
397///
398/// Contiguous iteration may be done via:
399/// - [`Query::contiguous_iter`](crate::system::Query::contiguous_iter),
400/// - [`Query::contiguous_iter_mut`](crate::system::Query::contiguous_iter_mut),
401///
402// NOTE: Even though all component references (&T, &mut T) implement this trait, it won't be executed for
403// SparseSet components because in that case the query is not dense.
404#[diagnostic::on_unimplemented(
405    message = "`{Self}` cannot be iterated contiguously",
406    label = "invalid contiguous `Query` data",
407    note = "if `{Self}` is a custom query type, using `QueryData` derive macro, ensure that the `#[query_data(contiguous(target))]` attribute is added"
408)]
409pub trait ContiguousQueryData: ArchetypeQueryData + IterQueryData {
410    /// Item returned by [`ContiguousQueryData::fetch_contiguous`].
411    /// Represents a contiguous chunk of memory.
412    type Contiguous<'w, 's>;
413
414    /// Fetch [`ContiguousQueryData::Contiguous`] which represents a contiguous chunk of memory (e.g., an array) in the current [`Table`].
415    /// This must always be called after [`WorldQuery::set_table`].
416    ///
417    /// # Safety
418    ///
419    /// - Must always be called _after_ [`WorldQuery::set_table`].
420    /// - `entities`'s length must match the length of the set table.
421    /// - `entities` must match the entities of the set table.
422    /// - There must not be simultaneous conflicting component access registered in `update_component_access`.
423    unsafe fn fetch_contiguous<'w, 's>(
424        state: &'s Self::State,
425        fetch: &mut Self::Fetch<'w>,
426        entities: &'w [Entity],
427    ) -> Self::Contiguous<'w, 's>;
428}
429
430/// A [`QueryData`] for which instances may be alive for different entities concurrently.
431///
432/// Rust [`Iterator`]s don't connect the lifetime in [`Iterator::next`] to anything in [`Iterator::Item`],
433/// so later calls don't invalidate earlier items.
434/// This is how methods like [`Iterator::collect`] work.
435/// It is therefore unsound to offer an [`Iterator`] for a [`QueryData`] for which only one instance may be alive concurrently.
436///
437/// To iterate over a [`QueryData`] that does not implement [`IterQueryData`],
438/// use the [`QueryIter::fetch_next()`](crate::query::QueryIter::fetch_next) method.
439///
440/// For `QueryData` that implement this trait, [`QueryData::fetch`] may be called for one entity while an item is still alive for a different entity.
441///
442/// All [`SingleEntityQueryData`] types are [`IterQueryData`].
443/// They only access data on the current entity, the one passed to [`QueryData::fetch`],
444/// so the access for different entities will always be disjoint.
445///
446/// All [`ReadOnlyQueryData`] types are [`IterQueryData`].
447/// Even if they access data on entities other than the current one,
448/// that access is read-only and it's sound for it to alias.
449///
450/// Queries with a nested query that performs mutable access should generally *not* be [`IterQueryData`],
451/// although they can be if they have a way to prove that all accesses through the nested query are disjoint.
452///
453/// # Safety
454///
455/// This [`QueryData`] must not perform conflicting access when fetched for different entities.
456pub unsafe trait IterQueryData: QueryData {}
457
458/// A [`QueryData`] that is read only.
459///
460/// # Safety
461///
462/// This must only be implemented for read-only [`QueryData`]'s.
463pub unsafe trait ReadOnlyQueryData: IterQueryData<ReadOnly = Self> {}
464
465/// A [`QueryData`] that only accesses data from the current entity, the one passed to [`QueryData::fetch`].
466///
467/// This is used as a bound in [`EntityRef::get_components`] and related APIs,
468/// since they only have access to a single entity.
469///
470/// # Safety
471///
472/// This [`QueryData`] must only access data from the current entity, and not any other entities.
473pub unsafe trait SingleEntityQueryData: IterQueryData {}
474
475/// The item type returned when a [`WorldQuery`] is iterated over
476pub type QueryItem<'w, 's, Q> = <Q as QueryData>::Item<'w, 's>;
477/// The read-only variant of the item type returned when a [`QueryData`] is iterated over immutably
478pub type ROQueryItem<'w, 's, D> = QueryItem<'w, 's, <D as QueryData>::ReadOnly>;
479
480/// A [`QueryData`] that does not borrow from its [`QueryState`].
481///
482/// This is implemented by most `QueryData` types.
483/// The main exceptions are [`FilteredEntityRef`], [`FilteredEntityMut`], [`EntityRefExcept`], and [`EntityMutExcept`],
484/// which borrow an access list from their query state.
485/// Consider using a full [`EntityRef`] or [`EntityMut`] if you would need those.
486pub trait ReleaseStateQueryData: QueryData {
487    /// Releases the borrow from the query state by converting an item to have a `'static` state lifetime.
488    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static>;
489}
490
491/// A marker trait to indicate that the query data filters at an archetype level.
492///
493/// This is needed to implement [`ExactSizeIterator`] for
494/// [`QueryIter`](crate::query::QueryIter) that contains archetype-level filters.
495///
496/// The trait must only be implemented for query data where its corresponding [`QueryData::IS_ARCHETYPAL`] is [`prim@true`].
497pub trait ArchetypeQueryData: QueryData {}
498
499// SAFETY:
500// `update_component_access` does nothing.
501// This is sound because `fetch` does not access components.
502unsafe impl WorldQuery for Entity {
503    type Fetch<'w> = ();
504    type State = ();
505
506    fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {}
507
508    unsafe fn init_fetch<'w, 's>(
509        _world: UnsafeWorldCell<'w>,
510        _state: &'s Self::State,
511        _last_run: Tick,
512        _this_run: Tick,
513    ) -> Self::Fetch<'w> {
514    }
515
516    const IS_DENSE: bool = true;
517
518    #[inline]
519    unsafe fn set_archetype<'w, 's>(
520        _fetch: &mut Self::Fetch<'w>,
521        _state: &'s Self::State,
522        _archetype: &'w Archetype,
523        _table: &Table,
524    ) {
525    }
526
527    #[inline]
528    unsafe fn set_table<'w, 's>(
529        _fetch: &mut Self::Fetch<'w>,
530        _state: &'s Self::State,
531        _table: &'w Table,
532    ) {
533    }
534
535    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {}
536
537    fn init_state(_world: &mut World) {}
538
539    fn get_state(_components: &Components) -> Option<()> {
540        Some(())
541    }
542
543    fn matches_component_set(
544        _state: &Self::State,
545        _set_contains_id: &impl Fn(ComponentId) -> bool,
546    ) -> bool {
547        true
548    }
549}
550
551// SAFETY: `Self` is the same as `Self::ReadOnly`
552unsafe impl QueryData for Entity {
553    const IS_READ_ONLY: bool = true;
554    const IS_ARCHETYPAL: bool = true;
555    type ReadOnly = Self;
556
557    type Item<'w, 's> = Entity;
558
559    fn shrink<'wlong: 'wshort, 'wshort, 's>(
560        item: Self::Item<'wlong, 's>,
561    ) -> Self::Item<'wshort, 's> {
562        item
563    }
564
565    #[inline(always)]
566    unsafe fn fetch<'w, 's>(
567        _state: &'s Self::State,
568        _fetch: &mut Self::Fetch<'w>,
569        entity: Entity,
570        _table_row: TableRow,
571    ) -> Option<Self::Item<'w, 's>> {
572        Some(entity)
573    }
574
575    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
576        iter::empty()
577    }
578}
579
580// SAFETY: access is read only and only on the current entity
581unsafe impl IterQueryData for Entity {}
582
583// SAFETY: access is read only
584unsafe impl ReadOnlyQueryData for Entity {}
585
586// SAFETY: access is only on the current entity
587unsafe impl SingleEntityQueryData for Entity {}
588
589impl ReleaseStateQueryData for Entity {
590    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
591        item
592    }
593}
594
595impl ArchetypeQueryData for Entity {}
596
597impl ContiguousQueryData for Entity {
598    type Contiguous<'w, 's> = &'w [Entity];
599
600    unsafe fn fetch_contiguous<'w, 's>(
601        _state: &'s Self::State,
602        _fetch: &mut Self::Fetch<'w>,
603        entities: &'w [Entity],
604    ) -> Self::Contiguous<'w, 's> {
605        entities
606    }
607}
608
609// SAFETY:
610// `update_component_access` does nothing.
611// This is sound because `fetch` does not access components.
612unsafe impl WorldQuery for EntityLocation {
613    type Fetch<'w> = &'w Entities;
614    type State = ();
615
616    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
617        fetch
618    }
619
620    unsafe fn init_fetch<'w, 's>(
621        world: UnsafeWorldCell<'w>,
622        _state: &'s Self::State,
623        _last_run: Tick,
624        _this_run: Tick,
625    ) -> Self::Fetch<'w> {
626        world.entities()
627    }
628
629    // This is set to true to avoid forcing archetypal iteration in compound queries, is likely to be slower
630    // in most practical use case.
631    const IS_DENSE: bool = true;
632
633    #[inline]
634    unsafe fn set_archetype<'w, 's>(
635        _fetch: &mut Self::Fetch<'w>,
636        _state: &'s Self::State,
637        _archetype: &'w Archetype,
638        _table: &Table,
639    ) {
640    }
641
642    #[inline]
643    unsafe fn set_table<'w, 's>(
644        _fetch: &mut Self::Fetch<'w>,
645        _state: &'s Self::State,
646        _table: &'w Table,
647    ) {
648    }
649
650    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {}
651
652    fn init_state(_world: &mut World) {}
653
654    fn get_state(_components: &Components) -> Option<()> {
655        Some(())
656    }
657
658    fn matches_component_set(
659        _state: &Self::State,
660        _set_contains_id: &impl Fn(ComponentId) -> bool,
661    ) -> bool {
662        true
663    }
664}
665
666// SAFETY: `Self` is the same as `Self::ReadOnly`
667unsafe impl QueryData for EntityLocation {
668    const IS_READ_ONLY: bool = true;
669    const IS_ARCHETYPAL: bool = true;
670    type ReadOnly = Self;
671    type Item<'w, 's> = EntityLocation;
672
673    fn shrink<'wlong: 'wshort, 'wshort, 's>(
674        item: Self::Item<'wlong, 's>,
675    ) -> Self::Item<'wshort, 's> {
676        item
677    }
678
679    #[inline(always)]
680    unsafe fn fetch<'w, 's>(
681        _state: &'s Self::State,
682        fetch: &mut Self::Fetch<'w>,
683        entity: Entity,
684        _table_row: TableRow,
685    ) -> Option<Self::Item<'w, 's>> {
686        // SAFETY: `fetch` must be called with an entity that exists in the world
687        Some(unsafe { fetch.get_spawned(entity).debug_checked_unwrap() })
688    }
689
690    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
691        iter::empty()
692    }
693}
694
695// SAFETY: access is read only and only on the current entity
696unsafe impl IterQueryData for EntityLocation {}
697
698// SAFETY: access is read only
699unsafe impl ReadOnlyQueryData for EntityLocation {}
700
701// SAFETY: access is only on the current entity
702unsafe impl SingleEntityQueryData for EntityLocation {}
703
704impl ReleaseStateQueryData for EntityLocation {
705    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
706        item
707    }
708}
709
710impl ArchetypeQueryData for EntityLocation {}
711
712/// The `SpawnDetails` query parameter fetches the [`Tick`] the entity was spawned at.
713///
714/// To evaluate whether the spawn happened since the last time the system ran, the system
715/// param [`SystemChangeTick`](bevy_ecs::system::SystemChangeTick) needs to be used.
716///
717/// If the query should filter for spawned entities instead, use the
718/// [`Spawned`](bevy_ecs::query::Spawned) query filter instead.
719///
720/// # Examples
721///
722/// ```
723/// # use bevy_ecs::component::Component;
724/// # use bevy_ecs::entity::Entity;
725/// # use bevy_ecs::system::Query;
726/// # use bevy_ecs::query::Spawned;
727/// # use bevy_ecs::query::SpawnDetails;
728///
729/// fn print_spawn_details(query: Query<(Entity, SpawnDetails)>) {
730///     for (entity, spawn_details) in &query {
731///         if spawn_details.is_spawned() {
732///             print!("new ");
733///         }
734///         print!(
735///             "entity {:?} spawned at {:?}",
736///             entity,
737///             spawn_details.spawn_tick()
738///         );
739///         match spawn_details.spawned_by().into_option() {
740///             Some(location) => println!(" by {:?}", location),
741///             None => println!()
742///         }
743///     }
744/// }
745///
746/// # bevy_ecs::system::assert_is_system(print_spawn_details);
747/// ```
748#[derive(#[automatically_derived]
impl ::core::clone::Clone for SpawnDetails {
    #[inline]
    fn clone(&self) -> SpawnDetails {
        let _: ::core::clone::AssertParamIsClone<MaybeLocation>;
        let _: ::core::clone::AssertParamIsClone<Tick>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for SpawnDetails { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for SpawnDetails {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f, "SpawnDetails",
            "spawned_by", &self.spawned_by, "spawn_tick", &self.spawn_tick,
            "last_run", &self.last_run, "this_run", &&self.this_run)
    }
}Debug)]
749pub struct SpawnDetails {
750    spawned_by: MaybeLocation,
751    spawn_tick: Tick,
752    last_run: Tick,
753    this_run: Tick,
754}
755
756impl SpawnDetails {
757    /// Returns `true` if the entity spawned since the last time this system ran.
758    /// Otherwise, returns `false`.
759    pub fn is_spawned(self) -> bool {
760        self.is_spawned_after(self.last_run)
761    }
762
763    /// Returns `true` if the entity spawned after the `other` tick.
764    /// Otherwise, returns `false`.
765    #[inline]
766    pub fn is_spawned_after(self, other: Tick) -> bool {
767        self.spawn_tick.is_newer_than(other, self.this_run)
768    }
769
770    /// Returns the `Tick` this entity spawned at.
771    pub fn spawn_tick(self) -> Tick {
772        self.spawn_tick
773    }
774
775    /// Returns the source code location from which this entity has been spawned.
776    pub fn spawned_by(self) -> MaybeLocation {
777        self.spawned_by
778    }
779}
780
781#[doc(hidden)]
782#[derive(#[automatically_derived]
impl<'w> ::core::clone::Clone for SpawnDetailsFetch<'w> {
    #[inline]
    fn clone(&self) -> SpawnDetailsFetch<'w> {
        SpawnDetailsFetch {
            entities: ::core::clone::Clone::clone(&self.entities),
            last_run: ::core::clone::Clone::clone(&self.last_run),
            this_run: ::core::clone::Clone::clone(&self.this_run),
        }
    }
}Clone)]
783pub struct SpawnDetailsFetch<'w> {
784    entities: &'w Entities,
785    last_run: Tick,
786    this_run: Tick,
787}
788
789// SAFETY:
790// No components are accessed.
791unsafe impl WorldQuery for SpawnDetails {
792    type Fetch<'w> = SpawnDetailsFetch<'w>;
793    type State = ();
794
795    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
796        fetch
797    }
798
799    unsafe fn init_fetch<'w, 's>(
800        world: UnsafeWorldCell<'w>,
801        _state: &'s Self::State,
802        last_run: Tick,
803        this_run: Tick,
804    ) -> Self::Fetch<'w> {
805        SpawnDetailsFetch {
806            entities: world.entities(),
807            last_run,
808            this_run,
809        }
810    }
811
812    const IS_DENSE: bool = true;
813
814    #[inline]
815    unsafe fn set_archetype<'w, 's>(
816        _fetch: &mut Self::Fetch<'w>,
817        _state: &'s Self::State,
818        _archetype: &'w Archetype,
819        _table: &'w Table,
820    ) {
821    }
822
823    #[inline]
824    unsafe fn set_table<'w, 's>(
825        _fetch: &mut Self::Fetch<'w>,
826        _state: &'s Self::State,
827        _table: &'w Table,
828    ) {
829    }
830
831    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {}
832
833    fn init_state(_world: &mut World) {}
834
835    fn get_state(_components: &Components) -> Option<()> {
836        Some(())
837    }
838
839    fn matches_component_set(
840        _state: &Self::State,
841        _set_contains_id: &impl Fn(ComponentId) -> bool,
842    ) -> bool {
843        true
844    }
845}
846
847// SAFETY:
848// No components are accessed.
849// Is its own ReadOnlyQueryData.
850unsafe impl QueryData for SpawnDetails {
851    const IS_READ_ONLY: bool = true;
852    const IS_ARCHETYPAL: bool = true;
853    type ReadOnly = Self;
854    type Item<'w, 's> = Self;
855
856    fn shrink<'wlong: 'wshort, 'wshort, 's>(
857        item: Self::Item<'wlong, 's>,
858    ) -> Self::Item<'wshort, 's> {
859        item
860    }
861
862    #[inline(always)]
863    unsafe fn fetch<'w, 's>(
864        _state: &'s Self::State,
865        fetch: &mut Self::Fetch<'w>,
866        entity: Entity,
867        _table_row: TableRow,
868    ) -> Option<Self::Item<'w, 's>> {
869        // SAFETY: only living entities are queried
870        let (spawned_by, spawn_tick) = unsafe {
871            fetch
872                .entities
873                .entity_get_spawned_or_despawned_unchecked(entity)
874        };
875        Some(Self {
876            spawned_by,
877            spawn_tick,
878            last_run: fetch.last_run,
879            this_run: fetch.this_run,
880        })
881    }
882
883    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
884        iter::empty()
885    }
886}
887
888// SAFETY: access is read only and only on the current entity
889unsafe impl IterQueryData for SpawnDetails {}
890
891// SAFETY: access is read only
892unsafe impl ReadOnlyQueryData for SpawnDetails {}
893
894// SAFETY: access is only on the current entity
895unsafe impl SingleEntityQueryData for SpawnDetails {}
896
897impl ReleaseStateQueryData for SpawnDetails {
898    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
899        item
900    }
901}
902
903impl ArchetypeQueryData for SpawnDetails {}
904
905/// The [`WorldQuery::Fetch`] type for WorldQueries that can fetch multiple components from an entity
906/// ([`EntityRef`], [`EntityMut`], etc.)
907#[derive(#[automatically_derived]
impl<'w> ::core::marker::Copy for EntityFetch<'w> { }Copy, #[automatically_derived]
impl<'w> ::core::clone::Clone for EntityFetch<'w> {
    #[inline]
    fn clone(&self) -> EntityFetch<'w> {
        let _: ::core::clone::AssertParamIsClone<UnsafeWorldCell<'w>>;
        let _: ::core::clone::AssertParamIsClone<Tick>;
        *self
    }
}Clone)]
908#[doc(hidden)]
909pub struct EntityFetch<'w> {
910    world: UnsafeWorldCell<'w>,
911    last_run: Tick,
912    this_run: Tick,
913}
914
915// SAFETY:
916// `fetch` accesses all components in a readonly way.
917// This is sound because `update_component_access` sets read access for all components and panic when appropriate.
918// Filters are unchanged.
919unsafe impl<'a> WorldQuery for EntityRef<'a> {
920    type Fetch<'w> = EntityFetch<'w>;
921    type State = ();
922
923    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
924        fetch
925    }
926
927    unsafe fn init_fetch<'w, 's>(
928        world: UnsafeWorldCell<'w>,
929        _state: &'s Self::State,
930        last_run: Tick,
931        this_run: Tick,
932    ) -> Self::Fetch<'w> {
933        EntityFetch {
934            world,
935            last_run,
936            this_run,
937        }
938    }
939
940    const IS_DENSE: bool = true;
941
942    #[inline]
943    unsafe fn set_archetype<'w, 's>(
944        _fetch: &mut Self::Fetch<'w>,
945        _state: &'s Self::State,
946        _archetype: &'w Archetype,
947        _table: &Table,
948    ) {
949    }
950
951    #[inline]
952    unsafe fn set_table<'w, 's>(
953        _fetch: &mut Self::Fetch<'w>,
954        _state: &'s Self::State,
955        _table: &'w Table,
956    ) {
957    }
958
959    fn update_component_access(_state: &Self::State, access: &mut FilteredAccess) {
960        if !!access.access().has_any_write() {
    {
        ::core::panicking::panic_fmt(format_args!("EntityRef conflicts with a previous access in this query. Shared access cannot coincide with exclusive access."));
    }
};assert!(
961            !access.access().has_any_write(),
962            "EntityRef conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
963        );
964        access.read_all();
965    }
966
967    fn init_state(_world: &mut World) {}
968
969    fn get_state(_components: &Components) -> Option<()> {
970        Some(())
971    }
972
973    fn matches_component_set(
974        _state: &Self::State,
975        _set_contains_id: &impl Fn(ComponentId) -> bool,
976    ) -> bool {
977        true
978    }
979}
980
981// SAFETY: `Self` is the same as `Self::ReadOnly`
982unsafe impl<'a> QueryData for EntityRef<'a> {
983    const IS_READ_ONLY: bool = true;
984    const IS_ARCHETYPAL: bool = true;
985    type ReadOnly = Self;
986    type Item<'w, 's> = EntityRef<'w>;
987
988    fn shrink<'wlong: 'wshort, 'wshort, 's>(
989        item: Self::Item<'wlong, 's>,
990    ) -> Self::Item<'wshort, 's> {
991        item
992    }
993
994    #[inline(always)]
995    unsafe fn fetch<'w, 's>(
996        _state: &'s Self::State,
997        fetch: &mut Self::Fetch<'w>,
998        entity: Entity,
999        _table_row: TableRow,
1000    ) -> Option<Self::Item<'w, 's>> {
1001        // SAFETY: `fetch` must be called with an entity that exists in the world
1002        let cell = unsafe {
1003            fetch
1004                .world
1005                .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run)
1006                .debug_checked_unwrap()
1007        };
1008        // SAFETY: Read-only access to every component has been registered.
1009        Some(unsafe { EntityRef::new(cell) })
1010    }
1011
1012    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1013        iter::once(EcsAccessType::Component(EcsAccessLevel::ReadAll))
1014    }
1015}
1016
1017// SAFETY: access is read only and only on the current entity
1018unsafe impl IterQueryData for EntityRef<'_> {}
1019
1020// SAFETY: access is read only
1021unsafe impl ReadOnlyQueryData for EntityRef<'_> {}
1022
1023// SAFETY: access is only on the current entity
1024unsafe impl SingleEntityQueryData for EntityRef<'_> {}
1025
1026impl ReleaseStateQueryData for EntityRef<'_> {
1027    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
1028        item
1029    }
1030}
1031
1032impl ArchetypeQueryData for EntityRef<'_> {}
1033
1034// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self`
1035unsafe impl<'a> WorldQuery for EntityMut<'a> {
1036    type Fetch<'w> = EntityFetch<'w>;
1037    type State = ();
1038
1039    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1040        fetch
1041    }
1042
1043    unsafe fn init_fetch<'w, 's>(
1044        world: UnsafeWorldCell<'w>,
1045        _state: &'s Self::State,
1046        last_run: Tick,
1047        this_run: Tick,
1048    ) -> Self::Fetch<'w> {
1049        EntityFetch {
1050            world,
1051            last_run,
1052            this_run,
1053        }
1054    }
1055
1056    const IS_DENSE: bool = true;
1057
1058    #[inline]
1059    unsafe fn set_archetype<'w, 's>(
1060        _fetch: &mut Self::Fetch<'w>,
1061        _state: &'s Self::State,
1062        _archetype: &'w Archetype,
1063        _table: &Table,
1064    ) {
1065    }
1066
1067    #[inline]
1068    unsafe fn set_table<'w, 's>(
1069        _fetch: &mut Self::Fetch<'w>,
1070        _state: &'s Self::State,
1071        _table: &'w Table,
1072    ) {
1073    }
1074
1075    fn update_component_access(_state: &Self::State, access: &mut FilteredAccess) {
1076        if !!access.access().has_any_read() {
    {
        ::core::panicking::panic_fmt(format_args!("EntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses."));
    }
};assert!(
1077            !access.access().has_any_read(),
1078            "EntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",
1079        );
1080        access.write_all();
1081    }
1082
1083    fn init_state(_world: &mut World) {}
1084
1085    fn get_state(_components: &Components) -> Option<()> {
1086        Some(())
1087    }
1088
1089    fn matches_component_set(
1090        _state: &Self::State,
1091        _set_contains_id: &impl Fn(ComponentId) -> bool,
1092    ) -> bool {
1093        true
1094    }
1095}
1096
1097// SAFETY: access of `EntityRef` is a subset of `EntityMut`
1098unsafe impl<'a> QueryData for EntityMut<'a> {
1099    const IS_READ_ONLY: bool = false;
1100    const IS_ARCHETYPAL: bool = true;
1101    type ReadOnly = EntityRef<'a>;
1102    type Item<'w, 's> = EntityMut<'w>;
1103
1104    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1105        item: Self::Item<'wlong, 's>,
1106    ) -> Self::Item<'wshort, 's> {
1107        item
1108    }
1109
1110    #[inline(always)]
1111    unsafe fn fetch<'w, 's>(
1112        _state: &'s Self::State,
1113        fetch: &mut Self::Fetch<'w>,
1114        entity: Entity,
1115        _table_row: TableRow,
1116    ) -> Option<Self::Item<'w, 's>> {
1117        // SAFETY: `fetch` must be called with an entity that exists in the world
1118        let cell = unsafe {
1119            fetch
1120                .world
1121                .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run)
1122                .debug_checked_unwrap()
1123        };
1124        // SAFETY: mutable access to every component has been registered.
1125        Some(unsafe { EntityMut::new(cell) })
1126    }
1127
1128    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1129        iter::once(EcsAccessType::Component(EcsAccessLevel::WriteAll))
1130    }
1131}
1132
1133// SAFETY: access is only on the current entity
1134unsafe impl IterQueryData for EntityMut<'_> {}
1135
1136// SAFETY: access is only on the current entity
1137unsafe impl SingleEntityQueryData for EntityMut<'_> {}
1138
1139impl ReleaseStateQueryData for EntityMut<'_> {
1140    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
1141        item
1142    }
1143}
1144
1145impl ArchetypeQueryData for EntityMut<'_> {}
1146
1147// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self`
1148unsafe impl WorldQuery for FilteredEntityRef<'_, '_> {
1149    type Fetch<'w> = EntityFetch<'w>;
1150    type State = Access;
1151
1152    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1153        fetch
1154    }
1155
1156    const IS_DENSE: bool = true;
1157
1158    unsafe fn init_fetch<'w, 's>(
1159        world: UnsafeWorldCell<'w>,
1160        _state: &'s Self::State,
1161        last_run: Tick,
1162        this_run: Tick,
1163    ) -> Self::Fetch<'w> {
1164        EntityFetch {
1165            world,
1166            last_run,
1167            this_run,
1168        }
1169    }
1170
1171    #[inline]
1172    unsafe fn set_archetype<'w, 's>(
1173        _fetch: &mut Self::Fetch<'w>,
1174        _state: &'s Self::State,
1175        _: &'w Archetype,
1176        _table: &Table,
1177    ) {
1178    }
1179
1180    #[inline]
1181    unsafe fn set_table<'w, 's>(
1182        _fetch: &mut Self::Fetch<'w>,
1183        _state: &'s Self::State,
1184        _: &'w Table,
1185    ) {
1186    }
1187
1188    fn update_component_access(state: &Self::State, filtered_access: &mut FilteredAccess) {
1189        if !filtered_access.access().is_compatible(state) {
    {
        ::core::panicking::panic_fmt(format_args!("FilteredEntityRef conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses."));
    }
};assert!(
1190            filtered_access.access().is_compatible(state),
1191            "FilteredEntityRef conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",
1192        );
1193        filtered_access.access.extend(state);
1194    }
1195
1196    fn init_state(_world: &mut World) -> Self::State {
1197        Access::default()
1198    }
1199
1200    fn get_state(_components: &Components) -> Option<Self::State> {
1201        Some(Access::default())
1202    }
1203
1204    fn matches_component_set(
1205        _state: &Self::State,
1206        _set_contains_id: &impl Fn(ComponentId) -> bool,
1207    ) -> bool {
1208        true
1209    }
1210}
1211
1212// SAFETY: `Self` is the same as `Self::ReadOnly`
1213unsafe impl<'a, 'b> QueryData for FilteredEntityRef<'a, 'b> {
1214    const IS_READ_ONLY: bool = true;
1215    const IS_ARCHETYPAL: bool = true;
1216    type ReadOnly = Self;
1217    type Item<'w, 's> = FilteredEntityRef<'w, 's>;
1218
1219    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1220        item: Self::Item<'wlong, 's>,
1221    ) -> Self::Item<'wshort, 's> {
1222        item
1223    }
1224
1225    #[inline]
1226    fn provide_extra_access(
1227        state: &mut Self::State,
1228        access: &mut Access,
1229        available_access: &Access,
1230    ) {
1231        // Claim any extra access that doesn't conflict with other subqueries
1232        // This is used when constructing a `QueryLens` or creating a query from a `QueryBuilder`
1233        // Start with the entire available access, since that is the most we can possibly access
1234        state.clone_from(available_access);
1235        // Prevent all writes, since `FilteredEntityRef` only performs read access
1236        state.clear_writes();
1237        // Prevent any access that would conflict with other accesses in the current query
1238        state.remove_conflicting_access(access);
1239        // Finally, add the resulting access to the query access
1240        // to make sure a later `FilteredEntityMut` won't conflict with this.
1241        access.extend(state);
1242    }
1243
1244    #[inline(always)]
1245    unsafe fn fetch<'w, 's>(
1246        access: &'s Self::State,
1247        fetch: &mut Self::Fetch<'w>,
1248        entity: Entity,
1249        _table_row: TableRow,
1250    ) -> Option<Self::Item<'w, 's>> {
1251        // SAFETY: `fetch` must be called with an entity that exists in the world
1252        let cell = unsafe {
1253            fetch
1254                .world
1255                .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run)
1256                .debug_checked_unwrap()
1257        };
1258        // SAFETY: mutable access to every component has been registered.
1259        Some(unsafe { FilteredEntityRef::new(cell, access) })
1260    }
1261
1262    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1263        iter::once(EcsAccessType::Access(state))
1264    }
1265}
1266
1267// SAFETY: access is read only and only on the current entity
1268unsafe impl IterQueryData for FilteredEntityRef<'_, '_> {}
1269
1270// SAFETY: access is read only
1271unsafe impl ReadOnlyQueryData for FilteredEntityRef<'_, '_> {}
1272
1273// SAFETY: access is only on the current entity
1274unsafe impl SingleEntityQueryData for FilteredEntityRef<'_, '_> {}
1275
1276impl ArchetypeQueryData for FilteredEntityRef<'_, '_> {}
1277
1278// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self`
1279unsafe impl WorldQuery for FilteredEntityMut<'_, '_> {
1280    type Fetch<'w> = EntityFetch<'w>;
1281    type State = Access;
1282
1283    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1284        fetch
1285    }
1286
1287    const IS_DENSE: bool = true;
1288
1289    unsafe fn init_fetch<'w, 's>(
1290        world: UnsafeWorldCell<'w>,
1291        _state: &'s Self::State,
1292        last_run: Tick,
1293        this_run: Tick,
1294    ) -> Self::Fetch<'w> {
1295        EntityFetch {
1296            world,
1297            last_run,
1298            this_run,
1299        }
1300    }
1301
1302    #[inline]
1303    unsafe fn set_archetype<'w, 's>(
1304        _fetch: &mut Self::Fetch<'w>,
1305        _state: &'s Self::State,
1306        _: &'w Archetype,
1307        _table: &Table,
1308    ) {
1309    }
1310
1311    #[inline]
1312    unsafe fn set_table<'w, 's>(
1313        _fetch: &mut Self::Fetch<'w>,
1314        _state: &'s Self::State,
1315        _: &'w Table,
1316    ) {
1317    }
1318
1319    fn update_component_access(state: &Self::State, filtered_access: &mut FilteredAccess) {
1320        if !filtered_access.access().is_compatible(state) {
    {
        ::core::panicking::panic_fmt(format_args!("FilteredEntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses."));
    }
};assert!(
1321            filtered_access.access().is_compatible(state),
1322            "FilteredEntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",
1323        );
1324        filtered_access.access.extend(state);
1325    }
1326
1327    fn init_state(_world: &mut World) -> Self::State {
1328        Access::default()
1329    }
1330
1331    fn get_state(_components: &Components) -> Option<Self::State> {
1332        Some(Access::default())
1333    }
1334
1335    fn matches_component_set(
1336        _state: &Self::State,
1337        _set_contains_id: &impl Fn(ComponentId) -> bool,
1338    ) -> bool {
1339        true
1340    }
1341}
1342
1343// SAFETY: access of `FilteredEntityRef` is a subset of `FilteredEntityMut`
1344unsafe impl<'a, 'b> QueryData for FilteredEntityMut<'a, 'b> {
1345    const IS_READ_ONLY: bool = false;
1346    const IS_ARCHETYPAL: bool = true;
1347    type ReadOnly = FilteredEntityRef<'a, 'b>;
1348    type Item<'w, 's> = FilteredEntityMut<'w, 's>;
1349
1350    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1351        item: Self::Item<'wlong, 's>,
1352    ) -> Self::Item<'wshort, 's> {
1353        item
1354    }
1355
1356    #[inline]
1357    fn provide_extra_access(
1358        state: &mut Self::State,
1359        access: &mut Access,
1360        available_access: &Access,
1361    ) {
1362        // Claim any extra access that doesn't conflict with other subqueries
1363        // This is used when constructing a `QueryLens` or creating a query from a `QueryBuilder`
1364        // Start with the entire available access, since that is the most we can possibly access
1365        state.clone_from(available_access);
1366        // Prevent any access that would conflict with other accesses in the current query
1367        state.remove_conflicting_access(access);
1368        // Finally, add the resulting access to the query access
1369        // to make sure a later `FilteredEntityRef` or `FilteredEntityMut` won't conflict with this.
1370        access.extend(state);
1371    }
1372
1373    #[inline(always)]
1374    unsafe fn fetch<'w, 's>(
1375        access: &'s Self::State,
1376        fetch: &mut Self::Fetch<'w>,
1377        entity: Entity,
1378        _table_row: TableRow,
1379    ) -> Option<Self::Item<'w, 's>> {
1380        // SAFETY: `fetch` must be called with an entity that exists in the world
1381        let cell = unsafe {
1382            fetch
1383                .world
1384                .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run)
1385                .debug_checked_unwrap()
1386        };
1387        // SAFETY: mutable access to every component has been registered.
1388        Some(unsafe { FilteredEntityMut::new(cell, access) })
1389    }
1390
1391    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1392        iter::once(EcsAccessType::Access(state))
1393    }
1394}
1395
1396// SAFETY: access is only on the current entity
1397unsafe impl IterQueryData for FilteredEntityMut<'_, '_> {}
1398
1399// SAFETY: access is only on the current entity
1400unsafe impl SingleEntityQueryData for FilteredEntityMut<'_, '_> {}
1401
1402impl ArchetypeQueryData for FilteredEntityMut<'_, '_> {}
1403
1404// SAFETY: `EntityRefExcept` guards access to all components in the bundle `B`
1405// and populates `Access` values so that queries that conflict with this access
1406// are rejected.
1407unsafe impl<'a, 'b, B> WorldQuery for EntityRefExcept<'a, 'b, B>
1408where
1409    B: Bundle,
1410{
1411    type Fetch<'w> = EntityFetch<'w>;
1412    type State = Access;
1413
1414    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1415        fetch
1416    }
1417
1418    unsafe fn init_fetch<'w, 's>(
1419        world: UnsafeWorldCell<'w>,
1420        _: &'s Self::State,
1421        last_run: Tick,
1422        this_run: Tick,
1423    ) -> Self::Fetch<'w> {
1424        EntityFetch {
1425            world,
1426            last_run,
1427            this_run,
1428        }
1429    }
1430
1431    const IS_DENSE: bool = true;
1432
1433    unsafe fn set_archetype<'w, 's>(
1434        _: &mut Self::Fetch<'w>,
1435        _: &'s Self::State,
1436        _: &'w Archetype,
1437        _: &'w Table,
1438    ) {
1439    }
1440
1441    unsafe fn set_table<'w, 's>(_: &mut Self::Fetch<'w>, _: &'s Self::State, _: &'w Table) {}
1442
1443    fn update_component_access(state: &Self::State, filtered_access: &mut FilteredAccess) {
1444        let access = filtered_access.access_mut();
1445        if !access.is_compatible(state) {
    {
        ::core::panicking::panic_fmt(format_args!("`EntityRefExcept<{0}>` conflicts with a previous access in this query.",
                DebugName::type_name::<B>()));
    }
};assert!(
1446            access.is_compatible(state),
1447            "`EntityRefExcept<{}>` conflicts with a previous access in this query.",
1448            DebugName::type_name::<B>(),
1449        );
1450        access.extend(state);
1451    }
1452
1453    fn init_state(world: &mut World) -> Self::State {
1454        let mut access = Access::new();
1455        access.read_all();
1456        for id in B::component_ids(&mut world.components_registrator()) {
1457            access.remove_read(id);
1458        }
1459        access
1460    }
1461
1462    fn get_state(components: &Components) -> Option<Self::State> {
1463        let mut access = Access::new();
1464        access.read_all();
1465        // If the component isn't registered, we don't have a `ComponentId`
1466        // to use to exclude its access.
1467        // Rather than fail, just try to take additional access.
1468        // This is sound because access checks will run on the resulting access.
1469        // Since the component isn't registered, there are no entities with that
1470        // component, and the extra access will usually have no effect.
1471        for id in B::get_component_ids(components).flatten() {
1472            access.remove_read(id);
1473        }
1474        Some(access)
1475    }
1476
1477    fn matches_component_set(_: &Self::State, _: &impl Fn(ComponentId) -> bool) -> bool {
1478        true
1479    }
1480}
1481
1482// SAFETY: `Self` is the same as `Self::ReadOnly`.
1483unsafe impl<'a, 'b, B> QueryData for EntityRefExcept<'a, 'b, B>
1484where
1485    B: Bundle,
1486{
1487    const IS_READ_ONLY: bool = true;
1488    const IS_ARCHETYPAL: bool = true;
1489    type ReadOnly = Self;
1490    type Item<'w, 's> = EntityRefExcept<'w, 's, B>;
1491
1492    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1493        item: Self::Item<'wlong, 's>,
1494    ) -> Self::Item<'wshort, 's> {
1495        item
1496    }
1497
1498    unsafe fn fetch<'w, 's>(
1499        access: &'s Self::State,
1500        fetch: &mut Self::Fetch<'w>,
1501        entity: Entity,
1502        _: TableRow,
1503    ) -> Option<Self::Item<'w, 's>> {
1504        let cell = fetch
1505            .world
1506            .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run)
1507            .unwrap();
1508        Some(EntityRefExcept::new(cell, access))
1509    }
1510
1511    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1512        iter::once(EcsAccessType::Access(state))
1513    }
1514}
1515
1516// SAFETY: access is read only and only on the current entity
1517unsafe impl<B> IterQueryData for EntityRefExcept<'_, '_, B> where B: Bundle {}
1518
1519// SAFETY: access is read only
1520unsafe impl<B> ReadOnlyQueryData for EntityRefExcept<'_, '_, B> where B: Bundle {}
1521
1522// SAFETY: access is only on the current entity
1523unsafe impl<B> SingleEntityQueryData for EntityRefExcept<'_, '_, B> where B: Bundle {}
1524
1525impl<B: Bundle> ArchetypeQueryData for EntityRefExcept<'_, '_, B> {}
1526
1527// SAFETY: `EntityMutExcept` guards access to all components in the bundle `B`
1528// and populates `Access` values so that queries that conflict with this access
1529// are rejected.
1530unsafe impl<'a, 'b, B> WorldQuery for EntityMutExcept<'a, 'b, B>
1531where
1532    B: Bundle,
1533{
1534    type Fetch<'w> = EntityFetch<'w>;
1535    type State = Access;
1536
1537    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1538        fetch
1539    }
1540
1541    unsafe fn init_fetch<'w, 's>(
1542        world: UnsafeWorldCell<'w>,
1543        _: &'s Self::State,
1544        last_run: Tick,
1545        this_run: Tick,
1546    ) -> Self::Fetch<'w> {
1547        EntityFetch {
1548            world,
1549            last_run,
1550            this_run,
1551        }
1552    }
1553
1554    const IS_DENSE: bool = true;
1555
1556    unsafe fn set_archetype<'w, 's>(
1557        _: &mut Self::Fetch<'w>,
1558        _: &'s Self::State,
1559        _: &'w Archetype,
1560        _: &'w Table,
1561    ) {
1562    }
1563
1564    unsafe fn set_table<'w, 's>(_: &mut Self::Fetch<'w>, _: &'s Self::State, _: &'w Table) {}
1565
1566    fn update_component_access(state: &Self::State, filtered_access: &mut FilteredAccess) {
1567        let access = filtered_access.access_mut();
1568        if !access.is_compatible(state) {
    {
        ::core::panicking::panic_fmt(format_args!("`EntityMutExcept<{0}>` conflicts with a previous access in this query.",
                DebugName::type_name::<B>()));
    }
};assert!(
1569            access.is_compatible(state),
1570            "`EntityMutExcept<{}>` conflicts with a previous access in this query.",
1571            DebugName::type_name::<B>()
1572        );
1573        access.extend(state);
1574    }
1575
1576    fn init_state(world: &mut World) -> Self::State {
1577        let mut access = Access::new();
1578        access.write_all();
1579        for id in B::component_ids(&mut world.components_registrator()) {
1580            access.remove_read(id);
1581        }
1582        access
1583    }
1584
1585    fn get_state(components: &Components) -> Option<Self::State> {
1586        let mut access = Access::new();
1587        access.write_all();
1588        // If the component isn't registered, we don't have a `ComponentId`
1589        // to use to exclude its access.
1590        // Rather than fail, just try to take additional access.
1591        // This is sound because access checks will run on the resulting access.
1592        // Since the component isn't registered, there are no entities with that
1593        // component, and the extra access will usually have no effect.
1594        for id in B::get_component_ids(components).flatten() {
1595            access.remove_read(id);
1596        }
1597        Some(access)
1598    }
1599
1600    fn matches_component_set(_: &Self::State, _: &impl Fn(ComponentId) -> bool) -> bool {
1601        true
1602    }
1603}
1604
1605// SAFETY: All accesses that `EntityRefExcept` provides are also accesses that
1606// `EntityMutExcept` provides.
1607unsafe impl<'a, 'b, B> QueryData for EntityMutExcept<'a, 'b, B>
1608where
1609    B: Bundle,
1610{
1611    const IS_READ_ONLY: bool = false;
1612    const IS_ARCHETYPAL: bool = true;
1613    type ReadOnly = EntityRefExcept<'a, 'b, B>;
1614    type Item<'w, 's> = EntityMutExcept<'w, 's, B>;
1615
1616    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1617        item: Self::Item<'wlong, 's>,
1618    ) -> Self::Item<'wshort, 's> {
1619        item
1620    }
1621
1622    unsafe fn fetch<'w, 's>(
1623        access: &'s Self::State,
1624        fetch: &mut Self::Fetch<'w>,
1625        entity: Entity,
1626        _: TableRow,
1627    ) -> Option<Self::Item<'w, 's>> {
1628        let cell = fetch
1629            .world
1630            .get_entity_with_ticks(entity, fetch.last_run, fetch.this_run)
1631            .unwrap();
1632        Some(EntityMutExcept::new(cell, access))
1633    }
1634
1635    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1636        iter::once(EcsAccessType::Access(state))
1637    }
1638}
1639
1640// SAFETY: access is only on the current entity
1641unsafe impl<B> IterQueryData for EntityMutExcept<'_, '_, B> where B: Bundle {}
1642
1643// SAFETY: access is only on the current entity
1644unsafe impl<B> SingleEntityQueryData for EntityMutExcept<'_, '_, B> where B: Bundle {}
1645
1646impl<B: Bundle> ArchetypeQueryData for EntityMutExcept<'_, '_, B> {}
1647
1648// SAFETY:
1649// `update_component_access` does nothing.
1650// This is sound because `fetch` does not access components.
1651unsafe impl WorldQuery for &Archetype {
1652    type Fetch<'w> = (&'w Entities, &'w Archetypes);
1653    type State = ();
1654
1655    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1656        fetch
1657    }
1658
1659    unsafe fn init_fetch<'w, 's>(
1660        world: UnsafeWorldCell<'w>,
1661        _state: &'s Self::State,
1662        _last_run: Tick,
1663        _this_run: Tick,
1664    ) -> Self::Fetch<'w> {
1665        (world.entities(), world.archetypes())
1666    }
1667
1668    // This could probably be a non-dense query and just set a Option<&Archetype> fetch value in
1669    // set_archetypes, but forcing archetypal iteration is likely to be slower in any compound query.
1670    const IS_DENSE: bool = true;
1671
1672    #[inline]
1673    unsafe fn set_archetype<'w, 's>(
1674        _fetch: &mut Self::Fetch<'w>,
1675        _state: &'s Self::State,
1676        _archetype: &'w Archetype,
1677        _table: &Table,
1678    ) {
1679    }
1680
1681    #[inline]
1682    unsafe fn set_table<'w, 's>(
1683        _fetch: &mut Self::Fetch<'w>,
1684        _state: &'s Self::State,
1685        _table: &'w Table,
1686    ) {
1687    }
1688
1689    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {}
1690
1691    fn init_state(_world: &mut World) {}
1692
1693    fn get_state(_components: &Components) -> Option<()> {
1694        Some(())
1695    }
1696
1697    fn matches_component_set(
1698        _state: &Self::State,
1699        _set_contains_id: &impl Fn(ComponentId) -> bool,
1700    ) -> bool {
1701        true
1702    }
1703}
1704
1705// SAFETY: `Self` is the same as `Self::ReadOnly`
1706unsafe impl QueryData for &Archetype {
1707    const IS_READ_ONLY: bool = true;
1708    const IS_ARCHETYPAL: bool = true;
1709    type ReadOnly = Self;
1710    type Item<'w, 's> = &'w Archetype;
1711
1712    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1713        item: Self::Item<'wlong, 's>,
1714    ) -> Self::Item<'wshort, 's> {
1715        item
1716    }
1717
1718    #[inline(always)]
1719    unsafe fn fetch<'w, 's>(
1720        _state: &'s Self::State,
1721        fetch: &mut Self::Fetch<'w>,
1722        entity: Entity,
1723        _table_row: TableRow,
1724    ) -> Option<Self::Item<'w, 's>> {
1725        let (entities, archetypes) = *fetch;
1726        // SAFETY: `fetch` must be called with an entity that exists in the world
1727        let location = unsafe { entities.get_spawned(entity).debug_checked_unwrap() };
1728        // SAFETY: The assigned archetype for a living entity must always be valid.
1729        Some(unsafe { archetypes.get(location.archetype_id).debug_checked_unwrap() })
1730    }
1731
1732    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1733        iter::empty()
1734    }
1735}
1736
1737// SAFETY: access is read only and only on the current entity
1738unsafe impl IterQueryData for &Archetype {}
1739
1740// SAFETY: access is read only
1741unsafe impl ReadOnlyQueryData for &Archetype {}
1742
1743// SAFETY: access is only on the current entity
1744unsafe impl SingleEntityQueryData for &Archetype {}
1745
1746impl ReleaseStateQueryData for &Archetype {
1747    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
1748        item
1749    }
1750}
1751
1752impl ArchetypeQueryData for &Archetype {}
1753
1754/// The [`WorldQuery::Fetch`] type for `& T`.
1755pub struct ReadFetch<'w, T: Component> {
1756    components: StorageSwitch<
1757        T,
1758        // T::STORAGE_TYPE = StorageType::Table
1759        Option<ThinSlicePtr<'w, UnsafeCell<T>>>,
1760        // T::STORAGE_TYPE = StorageType::SparseSet
1761        Option<&'w ComponentSparseSet>,
1762    >,
1763}
1764
1765impl<T: Component> Clone for ReadFetch<'_, T> {
1766    fn clone(&self) -> Self {
1767        *self
1768    }
1769}
1770
1771impl<T: Component> Copy for ReadFetch<'_, T> {}
1772
1773// SAFETY:
1774// `fetch` accesses a single component in a readonly way.
1775// This is sound because `update_component_access` adds read access for that component and panic when appropriate.
1776// `update_component_access` adds a `With` filter for a component.
1777// This is sound because `matches_component_set` returns whether the set contains that component.
1778unsafe impl<T: Component> WorldQuery for &T {
1779    type Fetch<'w> = ReadFetch<'w, T>;
1780    type State = ComponentId;
1781
1782    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1783        fetch
1784    }
1785
1786    #[inline]
1787    unsafe fn init_fetch<'w, 's>(
1788        world: UnsafeWorldCell<'w>,
1789        &component_id: &ComponentId,
1790        _last_run: Tick,
1791        _this_run: Tick,
1792    ) -> ReadFetch<'w, T> {
1793        ReadFetch {
1794            components: StorageSwitch::new(
1795                || None,
1796                || {
1797                    // SAFETY: The underlying type associated with `component_id` is `T`,
1798                    // which we are allowed to access since we registered it in `update_component_access`.
1799                    // Note that we do not actually access any components in this function, we just get a shared
1800                    // reference to the sparse set, which is used to access the components in `Self::fetch`.
1801                    unsafe { world.storages().sparse_sets.get(component_id) }
1802                },
1803            ),
1804        }
1805    }
1806
1807    const IS_DENSE: bool = {
1808        match T::STORAGE_TYPE {
1809            StorageType::Table => true,
1810            StorageType::SparseSet => false,
1811        }
1812    };
1813
1814    #[inline]
1815    unsafe fn set_archetype<'w>(
1816        fetch: &mut ReadFetch<'w, T>,
1817        component_id: &ComponentId,
1818        _archetype: &'w Archetype,
1819        table: &'w Table,
1820    ) {
1821        if Self::IS_DENSE {
1822            // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones.
1823            unsafe {
1824                Self::set_table(fetch, component_id, table);
1825            }
1826        }
1827    }
1828
1829    #[inline]
1830    unsafe fn set_table<'w>(
1831        fetch: &mut ReadFetch<'w, T>,
1832        &component_id: &ComponentId,
1833        table: &'w Table,
1834    ) {
1835        let table_data = Some(
1836            table
1837                .get_data_slice_for(component_id)
1838                .debug_checked_unwrap()
1839                .into(),
1840        );
1841        // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table
1842        unsafe { fetch.components.set_table(table_data) };
1843    }
1844
1845    fn update_component_access(&component_id: &ComponentId, access: &mut FilteredAccess) {
1846        if !!access.access().has_write(component_id) {
    {
        ::core::panicking::panic_fmt(format_args!("&{0} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
                DebugName::type_name::<T>()));
    }
};assert!(
1847            !access.access().has_write(component_id),
1848            "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
1849            DebugName::type_name::<T>(),
1850        );
1851        access.add_read(component_id);
1852    }
1853
1854    fn init_state(world: &mut World) -> ComponentId {
1855        world.register_component::<T>()
1856    }
1857
1858    fn get_state(components: &Components) -> Option<Self::State> {
1859        components.component_id::<T>()
1860    }
1861
1862    fn matches_component_set(
1863        &state: &ComponentId,
1864        set_contains_id: &impl Fn(ComponentId) -> bool,
1865    ) -> bool {
1866        set_contains_id(state)
1867    }
1868}
1869
1870// SAFETY: `Self` is the same as `Self::ReadOnly`
1871unsafe impl<T: Component> QueryData for &T {
1872    const IS_READ_ONLY: bool = true;
1873    const IS_ARCHETYPAL: bool = true;
1874    type ReadOnly = Self;
1875    type Item<'w, 's> = &'w T;
1876
1877    fn shrink<'wlong: 'wshort, 'wshort, 's>(
1878        item: Self::Item<'wlong, 's>,
1879    ) -> Self::Item<'wshort, 's> {
1880        item
1881    }
1882
1883    #[inline(always)]
1884    unsafe fn fetch<'w, 's>(
1885        _state: &'s Self::State,
1886        fetch: &mut Self::Fetch<'w>,
1887        entity: Entity,
1888        table_row: TableRow,
1889    ) -> Option<Self::Item<'w, 's>> {
1890        Some(fetch.components.extract(
1891            |table| {
1892                // SAFETY: set_table was previously called
1893                let table = unsafe { table.debug_checked_unwrap() };
1894                // SAFETY: Caller ensures `table_row` is in range.
1895                let item = unsafe { table.get_unchecked(table_row.index()) };
1896                item.deref()
1897            },
1898            |sparse_set| {
1899                // SAFETY: Caller ensures `entity` is in range.
1900                let item = unsafe {
1901                    sparse_set
1902                        .debug_checked_unwrap()
1903                        .get(entity)
1904                        .debug_checked_unwrap()
1905                };
1906                item.deref()
1907            },
1908        ))
1909    }
1910
1911    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
1912        iter::once(EcsAccessType::Component(EcsAccessLevel::Read(*state)))
1913    }
1914}
1915
1916impl<T: Component> ContiguousQueryData for &T {
1917    type Contiguous<'w, 's> = &'w [T];
1918
1919    unsafe fn fetch_contiguous<'w, 's>(
1920        _state: &'s Self::State,
1921        fetch: &mut Self::Fetch<'w>,
1922        entities: &'w [Entity],
1923    ) -> Self::Contiguous<'w, 's> {
1924        fetch.components.extract(
1925            |table| {
1926                // SAFETY: The caller ensures `set_table` was previously called
1927                let table = unsafe { table.debug_checked_unwrap() };
1928                // SAFETY:
1929                // - `table` is `entities.len()` long
1930                // - `UnsafeCell<T>` has the same layout as `T`
1931                unsafe { table.cast().as_slice_unchecked(entities.len()) }
1932            },
1933            |_| {
1934                #[cfg(debug_assertions)]
1935                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1936                // SAFETY: The caller ensures query is dense
1937                #[cfg(not(debug_assertions))]
1938                core::hint::unreachable_unchecked();
1939            },
1940        )
1941    }
1942}
1943
1944// SAFETY: access is read only and only on the current entity
1945unsafe impl<T: Component> IterQueryData for &T {}
1946
1947// SAFETY: access is read only
1948unsafe impl<T: Component> ReadOnlyQueryData for &T {}
1949
1950// SAFETY: access is only on the current entity
1951unsafe impl<T: Component> SingleEntityQueryData for &T {}
1952
1953impl<T: Component> ReleaseStateQueryData for &T {
1954    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
1955        item
1956    }
1957}
1958
1959impl<T: Component> ArchetypeQueryData for &T {}
1960
1961#[doc(hidden)]
1962pub struct RefFetch<'w, T: Component> {
1963    components: StorageSwitch<
1964        T,
1965        // T::STORAGE_TYPE = StorageType::Table
1966        Option<(
1967            ThinSlicePtr<'w, UnsafeCell<T>>,
1968            ThinSlicePtr<'w, UnsafeCell<Tick>>,
1969            ThinSlicePtr<'w, UnsafeCell<Tick>>,
1970            MaybeLocation<ThinSlicePtr<'w, UnsafeCell<&'static Location<'static>>>>,
1971        )>,
1972        // T::STORAGE_TYPE = StorageType::SparseSet
1973        // Can be `None` when the component has never been inserted
1974        Option<&'w ComponentSparseSet>,
1975    >,
1976    last_run: Tick,
1977    this_run: Tick,
1978}
1979
1980impl<T: Component> Clone for RefFetch<'_, T> {
1981    fn clone(&self) -> Self {
1982        *self
1983    }
1984}
1985
1986impl<T: Component> Copy for RefFetch<'_, T> {}
1987
1988// SAFETY:
1989// `fetch` accesses a single component in a readonly way.
1990// This is sound because `update_component_access` adds read access for that component and panic when appropriate.
1991// `update_component_access` adds a `With` filter for a component.
1992// This is sound because `matches_component_set` returns whether the set contains that component.
1993unsafe impl<'__w, T: Component> WorldQuery for Ref<'__w, T> {
1994    type Fetch<'w> = RefFetch<'w, T>;
1995    type State = ComponentId;
1996
1997    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1998        fetch
1999    }
2000
2001    #[inline]
2002    unsafe fn init_fetch<'w, 's>(
2003        world: UnsafeWorldCell<'w>,
2004        &component_id: &ComponentId,
2005        last_run: Tick,
2006        this_run: Tick,
2007    ) -> RefFetch<'w, T> {
2008        RefFetch {
2009            components: StorageSwitch::new(
2010                || None,
2011                || {
2012                    // SAFETY: The underlying type associated with `component_id` is `T`,
2013                    // which we are allowed to access since we registered it in `update_component_access`.
2014                    // Note that we do not actually access any components in this function, we just get a shared
2015                    // reference to the sparse set, which is used to access the components in `Self::fetch`.
2016                    unsafe { world.storages().sparse_sets.get(component_id) }
2017                },
2018            ),
2019            last_run,
2020            this_run,
2021        }
2022    }
2023
2024    const IS_DENSE: bool = {
2025        match T::STORAGE_TYPE {
2026            StorageType::Table => true,
2027            StorageType::SparseSet => false,
2028        }
2029    };
2030
2031    #[inline]
2032    unsafe fn set_archetype<'w>(
2033        fetch: &mut RefFetch<'w, T>,
2034        component_id: &ComponentId,
2035        _archetype: &'w Archetype,
2036        table: &'w Table,
2037    ) {
2038        if Self::IS_DENSE {
2039            // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones.
2040            unsafe {
2041                Self::set_table(fetch, component_id, table);
2042            }
2043        }
2044    }
2045
2046    #[inline]
2047    unsafe fn set_table<'w>(
2048        fetch: &mut RefFetch<'w, T>,
2049        &component_id: &ComponentId,
2050        table: &'w Table,
2051    ) {
2052        let column = table.get_column(component_id).debug_checked_unwrap();
2053        let table_data = Some((
2054            column.get_data_slice(table.entity_count() as usize).into(),
2055            column
2056                .get_added_ticks_slice(table.entity_count() as usize)
2057                .into(),
2058            column
2059                .get_changed_ticks_slice(table.entity_count() as usize)
2060                .into(),
2061            column
2062                .get_changed_by_slice(table.entity_count() as usize)
2063                .map(Into::into),
2064        ));
2065        // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table
2066        unsafe { fetch.components.set_table(table_data) };
2067    }
2068
2069    fn update_component_access(&component_id: &ComponentId, access: &mut FilteredAccess) {
2070        if !!access.access().has_write(component_id) {
    {
        ::core::panicking::panic_fmt(format_args!("&{0} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
                DebugName::type_name::<T>()));
    }
};assert!(
2071            !access.access().has_write(component_id),
2072            "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
2073            DebugName::type_name::<T>(),
2074        );
2075        access.add_read(component_id);
2076    }
2077
2078    fn init_state(world: &mut World) -> ComponentId {
2079        world.register_component::<T>()
2080    }
2081
2082    fn get_state(components: &Components) -> Option<Self::State> {
2083        components.component_id::<T>()
2084    }
2085
2086    fn matches_component_set(
2087        &state: &ComponentId,
2088        set_contains_id: &impl Fn(ComponentId) -> bool,
2089    ) -> bool {
2090        set_contains_id(state)
2091    }
2092}
2093
2094// SAFETY: `Self` is the same as `Self::ReadOnly`
2095unsafe impl<'__w, T: Component> QueryData for Ref<'__w, T> {
2096    const IS_READ_ONLY: bool = true;
2097    const IS_ARCHETYPAL: bool = true;
2098    type ReadOnly = Self;
2099    type Item<'w, 's> = Ref<'w, T>;
2100
2101    fn shrink<'wlong: 'wshort, 'wshort, 's>(
2102        item: Self::Item<'wlong, 's>,
2103    ) -> Self::Item<'wshort, 's> {
2104        item
2105    }
2106
2107    #[inline(always)]
2108    unsafe fn fetch<'w, 's>(
2109        _state: &'s Self::State,
2110        fetch: &mut Self::Fetch<'w>,
2111        entity: Entity,
2112        table_row: TableRow,
2113    ) -> Option<Self::Item<'w, 's>> {
2114        Some(fetch.components.extract(
2115            |table| {
2116                // SAFETY: set_table was previously called
2117                let (table_components, added_ticks, changed_ticks, callers) =
2118                    unsafe { table.debug_checked_unwrap() };
2119
2120                // SAFETY: The caller ensures `table_row` is in range.
2121                let component = unsafe { table_components.get_unchecked(table_row.index()) };
2122                // SAFETY: The caller ensures `table_row` is in range.
2123                let added = unsafe { added_ticks.get_unchecked(table_row.index()) };
2124                // SAFETY: The caller ensures `table_row` is in range.
2125                let changed = unsafe { changed_ticks.get_unchecked(table_row.index()) };
2126                // SAFETY: The caller ensures `table_row` is in range.
2127                let caller =
2128                    callers.map(|callers| unsafe { callers.get_unchecked(table_row.index()) });
2129
2130                Ref {
2131                    value: component.deref(),
2132                    ticks: ComponentTicksRef {
2133                        added: added.deref(),
2134                        changed: changed.deref(),
2135                        changed_by: caller.map(|caller| caller.deref()),
2136                        this_run: fetch.this_run,
2137                        last_run: fetch.last_run,
2138                    },
2139                }
2140            },
2141            |sparse_set| {
2142                // SAFETY: The caller ensures `entity` is in range and has the component.
2143                let (component, ticks) = unsafe {
2144                    sparse_set
2145                        .debug_checked_unwrap()
2146                        .get_with_ticks(entity)
2147                        .debug_checked_unwrap()
2148                };
2149
2150                Ref {
2151                    value: component.deref(),
2152                    ticks: ComponentTicksRef::from_tick_cells(
2153                        ticks,
2154                        fetch.last_run,
2155                        fetch.this_run,
2156                    ),
2157                }
2158            },
2159        ))
2160    }
2161
2162    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
2163        iter::once(EcsAccessType::Component(EcsAccessLevel::Read(*state)))
2164    }
2165}
2166
2167// SAFETY: access is read only and only on the current entity
2168unsafe impl<'__w, T: Component> IterQueryData for Ref<'__w, T> {}
2169
2170// SAFETY: access is read only
2171unsafe impl<'__w, T: Component> ReadOnlyQueryData for Ref<'__w, T> {}
2172
2173// SAFETY: access is only on the current entity
2174unsafe impl<'__w, T: Component> SingleEntityQueryData for Ref<'__w, T> {}
2175
2176impl<T: Component> ReleaseStateQueryData for Ref<'_, T> {
2177    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
2178        item
2179    }
2180}
2181
2182impl<T: Component> ArchetypeQueryData for Ref<'_, T> {}
2183
2184impl<T: Component> ContiguousQueryData for Ref<'_, T> {
2185    type Contiguous<'w, 's> = ContiguousRef<'w, T>;
2186
2187    unsafe fn fetch_contiguous<'w, 's>(
2188        _state: &'s Self::State,
2189        fetch: &mut Self::Fetch<'w>,
2190        entities: &'w [Entity],
2191    ) -> Self::Contiguous<'w, 's> {
2192        fetch.components.extract(
2193            |table| {
2194                // SAFETY: set_table was previously called
2195                let (table_components, added_ticks, changed_ticks, callers) =
2196                    unsafe { table.debug_checked_unwrap() };
2197
2198                ContiguousRef {
2199                    // SAFETY: `entities` has the same length as the rows in the set table.
2200                    value: unsafe { table_components.cast().as_slice_unchecked(entities.len()) },
2201                    // SAFETY:
2202                    // - The caller ensures the permission to access ticks.
2203                    // - `entities` has the same length as the rows in the set table hence the
2204                    // ticks.
2205                    ticks: unsafe {
2206                        ContiguousComponentTicksRef::from_slice_ptrs(
2207                            added_ticks,
2208                            changed_ticks,
2209                            callers,
2210                            entities.len(),
2211                            fetch.this_run,
2212                            fetch.last_run,
2213                        )
2214                    },
2215                }
2216            },
2217            |_| {
2218                #[cfg(debug_assertions)]
2219                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
2220                // SAFETY: the caller ensures that [`Self::set_table`] was called beforehand.
2221                #[cfg(not(debug_assertions))]
2222                core::hint::unreachable_unchecked();
2223            },
2224        )
2225    }
2226}
2227
2228/// The [`WorldQuery::Fetch`] type for `&mut T`.
2229pub struct WriteFetch<'w, T: Component> {
2230    components: StorageSwitch<
2231        T,
2232        // T::STORAGE_TYPE = StorageType::Table
2233        Option<(
2234            ThinSlicePtr<'w, UnsafeCell<T>>,
2235            ThinSlicePtr<'w, UnsafeCell<Tick>>,
2236            ThinSlicePtr<'w, UnsafeCell<Tick>>,
2237            MaybeLocation<ThinSlicePtr<'w, UnsafeCell<&'static Location<'static>>>>,
2238        )>,
2239        // T::STORAGE_TYPE = StorageType::SparseSet
2240        // Can be `None` when the component has never been inserted
2241        Option<&'w ComponentSparseSet>,
2242    >,
2243    last_run: Tick,
2244    this_run: Tick,
2245}
2246
2247impl<T: Component> Clone for WriteFetch<'_, T> {
2248    fn clone(&self) -> Self {
2249        *self
2250    }
2251}
2252
2253impl<T: Component> Copy for WriteFetch<'_, T> {}
2254
2255// SAFETY:
2256// `fetch` accesses a single component mutably.
2257// This is sound because `update_component_access` adds write access for that component and panic when appropriate.
2258// `update_component_access` adds a `With` filter for a component.
2259// This is sound because `matches_component_set` returns whether the set contains that component.
2260unsafe impl<'__w, T: Component> WorldQuery for &'__w mut T {
2261    type Fetch<'w> = WriteFetch<'w, T>;
2262    type State = ComponentId;
2263
2264    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
2265        fetch
2266    }
2267
2268    #[inline]
2269    unsafe fn init_fetch<'w, 's>(
2270        world: UnsafeWorldCell<'w>,
2271        &component_id: &ComponentId,
2272        last_run: Tick,
2273        this_run: Tick,
2274    ) -> WriteFetch<'w, T> {
2275        WriteFetch {
2276            components: StorageSwitch::new(
2277                || None,
2278                || {
2279                    // SAFETY: The underlying type associated with `component_id` is `T`,
2280                    // which we are allowed to access since we registered it in `update_component_access`.
2281                    // Note that we do not actually access any components in this function, we just get a shared
2282                    // reference to the sparse set, which is used to access the components in `Self::fetch`.
2283                    unsafe { world.storages().sparse_sets.get(component_id) }
2284                },
2285            ),
2286            last_run,
2287            this_run,
2288        }
2289    }
2290
2291    const IS_DENSE: bool = {
2292        match T::STORAGE_TYPE {
2293            StorageType::Table => true,
2294            StorageType::SparseSet => false,
2295        }
2296    };
2297
2298    #[inline]
2299    unsafe fn set_archetype<'w>(
2300        fetch: &mut WriteFetch<'w, T>,
2301        component_id: &ComponentId,
2302        _archetype: &'w Archetype,
2303        table: &'w Table,
2304    ) {
2305        if Self::IS_DENSE {
2306            // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones.
2307            unsafe {
2308                Self::set_table(fetch, component_id, table);
2309            }
2310        }
2311    }
2312
2313    #[inline]
2314    unsafe fn set_table<'w>(
2315        fetch: &mut WriteFetch<'w, T>,
2316        &component_id: &ComponentId,
2317        table: &'w Table,
2318    ) {
2319        let column = table.get_column(component_id).debug_checked_unwrap();
2320        let table_data = Some((
2321            column.get_data_slice(table.entity_count() as usize).into(),
2322            column
2323                .get_added_ticks_slice(table.entity_count() as usize)
2324                .into(),
2325            column
2326                .get_changed_ticks_slice(table.entity_count() as usize)
2327                .into(),
2328            column
2329                .get_changed_by_slice(table.entity_count() as usize)
2330                .map(Into::into),
2331        ));
2332        // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table
2333        unsafe { fetch.components.set_table(table_data) };
2334    }
2335
2336    fn update_component_access(&component_id: &ComponentId, access: &mut FilteredAccess) {
2337        if !!access.access().has_read(component_id) {
    {
        ::core::panicking::panic_fmt(format_args!("&mut {0} conflicts with a previous access in this query. Mutable component access must be unique.",
                DebugName::type_name::<T>()));
    }
};assert!(
2338            !access.access().has_read(component_id),
2339            "&mut {} conflicts with a previous access in this query. Mutable component access must be unique.",
2340            DebugName::type_name::<T>(),
2341        );
2342        access.add_write(component_id);
2343    }
2344
2345    fn init_state(world: &mut World) -> ComponentId {
2346        world.register_component::<T>()
2347    }
2348
2349    fn get_state(components: &Components) -> Option<Self::State> {
2350        components.component_id::<T>()
2351    }
2352
2353    fn matches_component_set(
2354        &state: &ComponentId,
2355        set_contains_id: &impl Fn(ComponentId) -> bool,
2356    ) -> bool {
2357        set_contains_id(state)
2358    }
2359}
2360
2361// SAFETY: access of `&T` is a subset of `&mut T`
2362unsafe impl<'__w, T: Component<Mutability = Mutable>> QueryData for &'__w mut T {
2363    const IS_READ_ONLY: bool = false;
2364    const IS_ARCHETYPAL: bool = true;
2365    type ReadOnly = &'__w T;
2366    type Item<'w, 's> = Mut<'w, T>;
2367
2368    fn shrink<'wlong: 'wshort, 'wshort, 's>(
2369        item: Self::Item<'wlong, 's>,
2370    ) -> Self::Item<'wshort, 's> {
2371        item
2372    }
2373
2374    #[inline(always)]
2375    unsafe fn fetch<'w, 's>(
2376        _state: &'s Self::State,
2377        fetch: &mut Self::Fetch<'w>,
2378        entity: Entity,
2379        table_row: TableRow,
2380    ) -> Option<Self::Item<'w, 's>> {
2381        Some(fetch.components.extract(
2382            |table| {
2383                // SAFETY: set_table was previously called
2384                let (table_components, added_ticks, changed_ticks, callers) =
2385                    unsafe { table.debug_checked_unwrap() };
2386
2387                // SAFETY: The caller ensures `table_row` is in range.
2388                let component = unsafe { table_components.get_unchecked(table_row.index()) };
2389                // SAFETY: The caller ensures `table_row` is in range.
2390                let added = unsafe { added_ticks.get_unchecked(table_row.index()) };
2391                // SAFETY: The caller ensures `table_row` is in range.
2392                let changed = unsafe { changed_ticks.get_unchecked(table_row.index()) };
2393                // SAFETY: The caller ensures `table_row` is in range.
2394                let caller =
2395                    callers.map(|callers| unsafe { callers.get_unchecked(table_row.index()) });
2396
2397                Mut {
2398                    value: component.deref_mut(),
2399                    ticks: ComponentTicksMut {
2400                        added: added.deref_mut(),
2401                        changed: changed.deref_mut(),
2402                        changed_by: caller.map(|caller| caller.deref_mut()),
2403                        this_run: fetch.this_run,
2404                        last_run: fetch.last_run,
2405                    },
2406                }
2407            },
2408            |sparse_set| {
2409                // SAFETY: The caller ensures `entity` is in range and has the component.
2410                let (component, ticks) = unsafe {
2411                    sparse_set
2412                        .debug_checked_unwrap()
2413                        .get_with_ticks(entity)
2414                        .debug_checked_unwrap()
2415                };
2416
2417                Mut {
2418                    value: component.assert_unique().deref_mut(),
2419                    ticks: ComponentTicksMut::from_tick_cells(
2420                        ticks,
2421                        fetch.last_run,
2422                        fetch.this_run,
2423                    ),
2424                }
2425            },
2426        ))
2427    }
2428
2429    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
2430        iter::once(EcsAccessType::Component(EcsAccessLevel::Write(*state)))
2431    }
2432}
2433
2434// SAFETY: access is only on the current entity
2435unsafe impl<T: Component<Mutability = Mutable>> IterQueryData for &mut T {}
2436
2437// SAFETY: access is only on the current entity
2438unsafe impl<T: Component<Mutability = Mutable>> SingleEntityQueryData for &mut T {}
2439
2440impl<T: Component<Mutability = Mutable>> ReleaseStateQueryData for &mut T {
2441    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
2442        item
2443    }
2444}
2445
2446impl<T: Component<Mutability = Mutable>> ArchetypeQueryData for &mut T {}
2447
2448impl<T: Component<Mutability = Mutable>> ContiguousQueryData for &mut T {
2449    type Contiguous<'w, 's> = ContiguousMut<'w, T>;
2450
2451    unsafe fn fetch_contiguous<'w, 's>(
2452        _state: &'s Self::State,
2453        fetch: &mut Self::Fetch<'w>,
2454        entities: &'w [Entity],
2455    ) -> Self::Contiguous<'w, 's> {
2456        fetch.components.extract(
2457            |table| {
2458                // SAFETY: set_table was previously called
2459                let (table_components, added_ticks, changed_ticks, callers) =
2460                    unsafe { table.debug_checked_unwrap() };
2461
2462                ContiguousMut {
2463                    // SAFETY: `entities` has the same length as the rows in the set table.
2464                    value: unsafe { table_components.as_mut_slice_unchecked(entities.len()) },
2465                    // SAFETY:
2466                    // - The caller ensures the permission to access ticks.
2467                    // - `entities` has the same length as the rows in the set table hence the
2468                    // ticks.
2469                    ticks: unsafe {
2470                        ContiguousComponentTicksMut::from_slice_ptrs(
2471                            added_ticks,
2472                            changed_ticks,
2473                            callers,
2474                            entities.len(),
2475                            fetch.this_run,
2476                            fetch.last_run,
2477                        )
2478                    },
2479                }
2480            },
2481            |_| {
2482                #[cfg(debug_assertions)]
2483                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
2484                // SAFETY: the caller ensures that [`Self::set_table`] was called beforehand.
2485                #[cfg(not(debug_assertions))]
2486                core::hint::unreachable_unchecked();
2487            },
2488        )
2489    }
2490}
2491
2492/// When `Mut<T>` is used in a query, it will be converted to `Ref<T>` when transformed into its read-only form, providing access to change detection methods.
2493///
2494/// By contrast `&mut T` will result in a `Mut<T>` item in mutable form to record mutations, but result in a bare `&T` in read-only form.
2495//
2496// SAFETY:
2497// `fetch` accesses a single component mutably.
2498// This is sound because `update_component_access` adds write access for that component and panic when appropriate.
2499// `update_component_access` adds a `With` filter for a component.
2500// This is sound because `matches_component_set` returns whether the set contains that component.
2501unsafe impl<'__w, T: Component> WorldQuery for Mut<'__w, T> {
2502    type Fetch<'w> = WriteFetch<'w, T>;
2503    type State = ComponentId;
2504
2505    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
2506        fetch
2507    }
2508
2509    #[inline]
2510    // Forwarded to `&mut T`
2511    unsafe fn init_fetch<'w, 's>(
2512        world: UnsafeWorldCell<'w>,
2513        state: &ComponentId,
2514        last_run: Tick,
2515        this_run: Tick,
2516    ) -> WriteFetch<'w, T> {
2517        <&mut T as WorldQuery>::init_fetch(world, state, last_run, this_run)
2518    }
2519
2520    // Forwarded to `&mut T`
2521    const IS_DENSE: bool = <&mut T as WorldQuery>::IS_DENSE;
2522
2523    #[inline]
2524    // Forwarded to `&mut T`
2525    unsafe fn set_archetype<'w>(
2526        fetch: &mut WriteFetch<'w, T>,
2527        state: &ComponentId,
2528        archetype: &'w Archetype,
2529        table: &'w Table,
2530    ) {
2531        <&mut T as WorldQuery>::set_archetype(fetch, state, archetype, table);
2532    }
2533
2534    #[inline]
2535    // Forwarded to `&mut T`
2536    unsafe fn set_table<'w>(fetch: &mut WriteFetch<'w, T>, state: &ComponentId, table: &'w Table) {
2537        <&mut T as WorldQuery>::set_table(fetch, state, table);
2538    }
2539
2540    // NOT forwarded to `&mut T`
2541    fn update_component_access(&component_id: &ComponentId, access: &mut FilteredAccess) {
2542        // Update component access here instead of in `<&mut T as WorldQuery>` to avoid erroneously referencing
2543        // `&mut T` in error message.
2544        if !!access.access().has_read(component_id) {
    {
        ::core::panicking::panic_fmt(format_args!("Mut<{0}> conflicts with a previous access in this query. Mutable component access mut be unique.",
                DebugName::type_name::<T>()));
    }
};assert!(
2545            !access.access().has_read(component_id),
2546            "Mut<{}> conflicts with a previous access in this query. Mutable component access mut be unique.",
2547            DebugName::type_name::<T>(),
2548        );
2549        access.add_write(component_id);
2550    }
2551
2552    // Forwarded to `&mut T`
2553    fn init_state(world: &mut World) -> ComponentId {
2554        <&mut T as WorldQuery>::init_state(world)
2555    }
2556
2557    // Forwarded to `&mut T`
2558    fn get_state(components: &Components) -> Option<ComponentId> {
2559        <&mut T as WorldQuery>::get_state(components)
2560    }
2561
2562    // Forwarded to `&mut T`
2563    fn matches_component_set(
2564        state: &ComponentId,
2565        set_contains_id: &impl Fn(ComponentId) -> bool,
2566    ) -> bool {
2567        <&mut T as WorldQuery>::matches_component_set(state, set_contains_id)
2568    }
2569}
2570
2571// SAFETY: access of `Ref<T>` is a subset of `Mut<T>`
2572unsafe impl<'__w, T: Component<Mutability = Mutable>> QueryData for Mut<'__w, T> {
2573    const IS_READ_ONLY: bool = false;
2574    const IS_ARCHETYPAL: bool = true;
2575    type ReadOnly = Ref<'__w, T>;
2576    type Item<'w, 's> = Mut<'w, T>;
2577
2578    // Forwarded to `&mut T`
2579    fn shrink<'wlong: 'wshort, 'wshort, 's>(
2580        item: Self::Item<'wlong, 's>,
2581    ) -> Self::Item<'wshort, 's> {
2582        <&mut T as QueryData>::shrink(item)
2583    }
2584
2585    #[inline(always)]
2586    // Forwarded to `&mut T`
2587    unsafe fn fetch<'w, 's>(
2588        state: &'s Self::State,
2589        // Rust complains about lifetime bounds not matching the trait if I directly use `WriteFetch<'w, T>` right here.
2590        // But it complains nowhere else in the entire trait implementation.
2591        fetch: &mut Self::Fetch<'w>,
2592        entity: Entity,
2593        table_row: TableRow,
2594    ) -> Option<Self::Item<'w, 's>> {
2595        <&mut T as QueryData>::fetch(state, fetch, entity, table_row)
2596    }
2597
2598    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
2599        iter::once(EcsAccessType::Component(EcsAccessLevel::Write(*state)))
2600    }
2601}
2602
2603// SAFETY: access is only on the current entity
2604unsafe impl<T: Component<Mutability = Mutable>> IterQueryData for Mut<'_, T> {}
2605
2606// SAFETY: access is only on the current entity
2607unsafe impl<T: Component<Mutability = Mutable>> SingleEntityQueryData for Mut<'_, T> {}
2608
2609impl<T: Component<Mutability = Mutable>> ReleaseStateQueryData for Mut<'_, T> {
2610    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
2611        item
2612    }
2613}
2614
2615impl<T: Component<Mutability = Mutable>> ArchetypeQueryData for Mut<'_, T> {}
2616
2617impl<'__w, T: Component<Mutability = Mutable>> ContiguousQueryData for Mut<'__w, T> {
2618    type Contiguous<'w, 's> = ContiguousMut<'w, T>;
2619
2620    unsafe fn fetch_contiguous<'w, 's>(
2621        state: &'s Self::State,
2622        fetch: &mut Self::Fetch<'w>,
2623        entities: &'w [Entity],
2624    ) -> Self::Contiguous<'w, 's> {
2625        <&mut T as ContiguousQueryData>::fetch_contiguous(state, fetch, entities)
2626    }
2627}
2628
2629/// A helper type for accessing a [`Query`] within a [`QueryData`].
2630///
2631/// This is intended to be used inside other implementations of [`QueryData`],
2632/// either for manual implementations or `#[derive(QueryData)]`.
2633/// It is not normally useful to query directly,
2634/// since it's equivalent to adding another [`Query`] parameter to a system.
2635///
2636/// Note that this requires the inner query to be a [`ReadOnlyQueryData`]
2637/// to prevent mutable aliasing.
2638///
2639/// ```
2640/// # use bevy_ecs::prelude::*;
2641/// # use bevy_ecs::query::NestedQuery;
2642/// #
2643/// # #[derive(Component)]
2644/// # struct A;
2645/// fn system(mut query: Query<NestedQuery<&A>>) {
2646///     // This works, because it performs read-only iteration
2647///     for a in &query {
2648///         let a: Query<&A> = a;
2649///     }
2650/// }
2651/// ```
2652///
2653/// ```compile_fail
2654/// # use bevy_ecs::prelude::*;
2655/// # use bevy_ecs::query::NestedQuery;
2656/// #
2657/// # #[derive(Component)]
2658/// # struct A;
2659/// fn system(mut query: Query<NestedQuery<&mut A>>) {
2660///     // This fails, because it would allow mutable aliasing of `&mut A`
2661///     for a in &mut query {
2662///         let a: Query<&mut A> = a;
2663///     }
2664/// }
2665/// ```
2666///
2667/// # Example
2668///
2669/// The simplest way to use a `NestedQuery` is with a `#[derive(QueryData)]` struct.
2670/// The `Query` will be available on the generated `Item` struct,
2671/// and we can use the query in methods on that struct.
2672///
2673/// ```
2674/// # use bevy_ecs::prelude::*;
2675/// # use bevy_ecs::query::{NestedQuery, QueryData, QueryFilter, ReadOnlyQueryData};
2676/// #
2677/// # #[derive(Component)]
2678/// # struct Data(usize);
2679/// #
2680/// # let mut world = World::new();
2681/// #
2682/// // We want to create a relational query data
2683/// // that lets us query components on an entity's parent,
2684/// // like this:
2685/// let root = world.spawn(Data(3)).id();
2686/// let child = world.spawn(ChildOf(root)).id();
2687///
2688/// let mut query = world.query::<Parent<&Data>>();
2689/// let &Data(data) = query.query(&mut world).get(child).unwrap().data().unwrap();
2690/// assert_eq!(data, 3);
2691///
2692/// // We derive a query data struct that contains the relation plus a `NestedQuery`
2693/// #[derive(QueryData)]
2694/// struct Parent<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static = ()> {
2695///     // This will query `ChildOf` on the entity itself,
2696///     // so we can find the parent entity
2697///     parent: &'static ChildOf,
2698///     // This will provide a `Query` that we can use to
2699///     // query data on the parent entity
2700///     nested_query: NestedQuery<D, F>,
2701/// }
2702///
2703/// // And add a method on the generated item struct to invoke the nested query.
2704/// impl<'w, 's, D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ParentItem<'w, 's, D, F> {
2705///     fn data(&self) -> Option<D::Item<'w, 's>> {
2706///         // We need to use `_inner` methods to return the full `'w` lifetime.
2707///         self.nested_query.get_inner(self.parent.parent()).ok()
2708///     }
2709/// }
2710/// ```
2711///
2712/// In order to make a query that returns the inner query data directly,
2713/// instead of through an intermediate `Item` struct,
2714/// you can implement `QueryData` manually by delegating to `NestedQuery`.
2715///
2716/// ```
2717/// # use bevy_ecs::{
2718/// #     archetype::Archetype,
2719/// #     change_detection::Tick,
2720/// #     component::{ComponentId, Components},
2721/// #     prelude::*,
2722/// #     query::{
2723/// #         EcsAccessType, FilteredAccess, IterQueryData, NestedQuery, QueryData, QueryFilter,
2724/// #         ReadOnlyQueryData, ReleaseStateQueryData, WorldQuery,
2725/// #     },
2726/// #     storage::{Table, TableRow},
2727/// #     world::unsafe_world_cell::UnsafeWorldCell,
2728/// # };
2729/// #
2730/// # #[derive(Component)]
2731/// # struct Data(usize);
2732/// #
2733/// # let mut world = World::new();
2734/// #
2735/// // We want to create a relational query data
2736/// // that lets us query components on an entity's parent,
2737/// // like this:
2738/// let root = world.spawn(Data(3)).id();
2739/// let child = world.spawn(ChildOf(root)).id();
2740///
2741/// let mut query = world.query::<Parent<&Data>>();
2742/// let &Data(data) = query.query(&mut world).get(child).unwrap();
2743/// assert_eq!(data, 3);
2744///
2745/// // This is the relational query data.
2746/// // This will never actually be constructed,
2747/// // and is only used as a `QueryData` type.
2748/// pub struct Parent<D: ReadOnlyQueryData, F: QueryFilter = ()>(D, F);
2749///
2750/// // A type alias to delegate the `QueryData` impls to.
2751/// // We need to refer to this type a lot, so the alias will help.
2752/// // This could also be a `#[derive(QueryData)]` type.
2753/// type ParentInner<D, F> = (
2754///     // This will query `ChildOf` on the entity itself,
2755///     // so we can find the parent entity
2756///     &'static ChildOf,
2757///     // This will provide a `Query` that we can use to
2758///     // query data on the parent entity
2759///     NestedQuery<D, F>,
2760/// );
2761///
2762/// unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> QueryData for Parent<D, F> {
2763///     // Set `Item` to what we need for this relational query.
2764///     // Here we use the output of `D`.
2765///     type Item<'w, 's> = D::Item<'w, 's>;
2766///
2767///     unsafe fn fetch<'w, 's>(state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, table_row: TableRow) -> Option<Self::Item<'w, 's>> {
2768///         // In `fetch`, first delegate to the type alias to get the parts:
2769///         let (&ChildOf(parent), nested_query) =
2770///             <ParentInner<D, F> as QueryData>::fetch(state, fetch, entity, table_row)?;
2771///         // Then use the `NestedQuery` to get the data we need.
2772///         // We need to use `_inner` methods to return the full `'w` lifetime.
2773///         nested_query.get_inner(parent).ok()
2774///     }
2775///
2776///     fn shrink<'wlong: 'wshort, 'wshort, 's>(item: Self::Item<'wlong, 's>) -> Self::Item<'wshort, 's> {
2777///         D::shrink(item)
2778///     }
2779///
2780///     // Set `ReadOnly` to `Self`,
2781///     // as `NestedQuery` does not yet support mutable queries.
2782///     type ReadOnly = Self;
2783///
2784///     // Delegate everything else on `QueryData` and `WorldQuery` to the type alias.
2785///     // This is sound for `unsafe` items because they delegate to the
2786///     // sound implementations on the type alias.
2787///     const IS_READ_ONLY: bool = <ParentInner<D, F> as QueryData>::IS_READ_ONLY;
2788///     const IS_ARCHETYPAL: bool = <ParentInner<D, F> as QueryData>::IS_ARCHETYPAL;
2789///
2790///     fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
2791///         <ParentInner<D, F> as QueryData>::iter_access(state)
2792///     }
2793/// }
2794///
2795/// unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> WorldQuery for Parent<D, F> {
2796///     type Fetch<'w> = <ParentInner<D, F> as WorldQuery>::Fetch<'w>;
2797///     type State = <ParentInner<D, F> as WorldQuery>::State;
2798///
2799///     fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
2800///         <ParentInner<D, F> as WorldQuery>::shrink_fetch(fetch)
2801///     }
2802///
2803///     unsafe fn init_fetch<'w, 's>(world: UnsafeWorldCell<'w>, state: &'s Self::State, last_run: Tick, this_run: Tick) -> Self::Fetch<'w> {
2804///         <ParentInner<D, F> as WorldQuery>::init_fetch(world, state, last_run, this_run)
2805///     }
2806///
2807///     const IS_DENSE: bool = <ParentInner<D, F> as WorldQuery>::IS_DENSE;
2808///
2809///     unsafe fn set_archetype<'w, 's>(fetch: &mut Self::Fetch<'w>, state: &'s Self::State, archetype: &'w Archetype, table: &'w Table) {
2810///         <ParentInner<D, F> as WorldQuery>::set_archetype(fetch, state, archetype, table)
2811///     }
2812///
2813///     unsafe fn set_table<'w, 's>(fetch: &mut Self::Fetch<'w>, state: &'s Self::State, table: &'w Table) {
2814///         <ParentInner<D, F> as WorldQuery>::set_table(fetch, state, table)
2815///     }
2816///
2817///     fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
2818///         <ParentInner<D, F> as WorldQuery>::update_component_access(state, access)
2819///     }
2820///
2821///     fn init_state(world: &mut World) -> Self::State {
2822///         <ParentInner<D, F> as WorldQuery>::init_state(world)
2823///     }
2824///
2825///     fn get_state(components: &Components) -> Option<Self::State> {
2826///         <ParentInner<D, F> as WorldQuery>::get_state(components)
2827///     }
2828///
2829///     fn matches_component_set(state: &Self::State, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
2830///         <ParentInner<D, F> as WorldQuery>::matches_component_set(state, set_contains_id)
2831///     }
2832/// }
2833///
2834/// // Also impl `ReadOnlyQueryData`, `IterQueryData`, and `ReleaseStateQueryData`
2835/// // These are safe because they delegate to the type alias, which is also read-only.
2836/// // Do *not* impl `ArchetypeQueryData`, because `fetch` sometimes returns `None`,
2837/// // and do *not* impl `SingleEntityQueryData`, because `NestedQuery` accesses other entities.
2838/// unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ReadOnlyQueryData for Parent<D, F> {}
2839///
2840/// unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> IterQueryData for Parent<D, F> {}
2841///
2842/// impl<D: ReadOnlyQueryData + ReleaseStateQueryData + 'static, F: QueryFilter + 'static>
2843///     ReleaseStateQueryData for Parent<D, F>
2844/// {
2845///     fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
2846///         D::release_state(item)
2847///     }
2848/// }
2849/// ```
2850pub struct NestedQuery<D: QueryData + 'static, F: QueryFilter + 'static = ()>(
2851    PhantomData<Query<'static, 'static, D, F>>,
2852);
2853
2854#[doc(hidden)]
2855#[derive(#[automatically_derived]
impl<'w> ::core::clone::Clone for NestedQueryFetch<'w> {
    #[inline]
    fn clone(&self) -> NestedQueryFetch<'w> {
        NestedQueryFetch {
            world: ::core::clone::Clone::clone(&self.world),
            last_run: ::core::clone::Clone::clone(&self.last_run),
            this_run: ::core::clone::Clone::clone(&self.this_run),
        }
    }
}Clone)]
2856pub struct NestedQueryFetch<'w> {
2857    world: UnsafeWorldCell<'w>,
2858    last_run: Tick,
2859    this_run: Tick,
2860}
2861
2862// SAFETY:
2863// Does not access any components on the current entity
2864// Accesses through the nested query are registered in `init_nested_access`
2865unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> WorldQuery
2866    for NestedQuery<D, F>
2867{
2868    type Fetch<'w> = NestedQueryFetch<'w>;
2869    type State = QueryState<D, F>;
2870
2871    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
2872        fetch
2873    }
2874
2875    #[inline]
2876    unsafe fn init_fetch<'w, 's>(
2877        world: UnsafeWorldCell<'w>,
2878        _state: &'s Self::State,
2879        last_run: Tick,
2880        this_run: Tick,
2881    ) -> Self::Fetch<'w> {
2882        NestedQueryFetch {
2883            world,
2884            last_run,
2885            this_run,
2886        }
2887    }
2888
2889    const IS_DENSE: bool = true;
2890
2891    #[inline]
2892    unsafe fn set_archetype<'w>(
2893        _fetch: &mut Self::Fetch<'w>,
2894        _state: &Self::State,
2895        _archetype: &'w Archetype,
2896        _table: &'w Table,
2897    ) {
2898    }
2899
2900    #[inline]
2901    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
2902    }
2903
2904    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {
2905        // This performs no access on the current entity
2906        // Access to the nested query is checked through `init_nested_access`
2907    }
2908
2909    fn init_nested_access(
2910        state: &Self::State,
2911        system_name: Option<&str>,
2912        component_access_set: &mut FilteredAccessSet,
2913        world: UnsafeWorldCell,
2914    ) {
2915        state.init_access(system_name, component_access_set, world);
2916    }
2917
2918    fn init_state(world: &mut World) -> Self::State {
2919        // SAFETY: `WorldQuery::init_nested_access` calls `QueryState::init_access`,
2920        // `WorldQuery::init_nested_access` must be called before `WorldQuery::init_fetch,
2921        // which must be called before `QueryData::fetch`,
2922        // and we only call methods on the `QueryState` in `fetch`.
2923        unsafe { QueryState::<D, F>::new_unchecked(world) }
2924    }
2925
2926    fn get_state(_components: &Components) -> Option<Self::State> {
2927        // This is not currently possible.
2928        // `QueryState::new` requires read access to the `DefaultQueryFilters` resource,
2929        // but this method may be called during `transmute` or `join`
2930        // when we have no such access.
2931        None
2932    }
2933
2934    fn matches_component_set(
2935        _state: &Self::State,
2936        _set_contains_id: &impl Fn(ComponentId) -> bool,
2937    ) -> bool {
2938        true
2939    }
2940
2941    fn update_archetypes(state: &mut Self::State, world: UnsafeWorldCell) {
2942        state.update_archetypes_unsafe_world_cell(world);
2943    }
2944}
2945
2946// SAFETY:
2947// `Self::ReadOnly` accesses `D::ReadOnly`, which is a subset of the data accessed by `D`
2948// `IS_READ_ONLY` iff `D::IS_READ_ONLY` iff `D: ReadOnlyQueryData` iff `Self: ReadOnlyQueryData`
2949unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> QueryData
2950    for NestedQuery<D, F>
2951{
2952    const IS_READ_ONLY: bool = D::IS_READ_ONLY;
2953    // Nested queries are always archetypal because `fetch` always returns `Some`.
2954    // If `D::IS_ARCHETYPAL == false` or `F::IS_ARCHETYPAL == false`,
2955    // then the nested query may filter out some entities that *it* matches,
2956    // but it will not filter the outer query.
2957    const IS_ARCHETYPAL: bool = true;
2958    type ReadOnly = NestedQuery<D, F>;
2959    type Item<'w, 's> = Query<'w, 's, D, F>;
2960
2961    fn shrink<'wlong: 'wshort, 'wshort, 's>(
2962        item: Self::Item<'wlong, 's>,
2963    ) -> Self::Item<'wshort, 's> {
2964        item
2965    }
2966
2967    #[inline(always)]
2968    unsafe fn fetch<'w, 's>(
2969        state: &'s Self::State,
2970        fetch: &mut Self::Fetch<'w>,
2971        _entity: Entity,
2972        _table_row: TableRow,
2973    ) -> Option<Self::Item<'w, 's>> {
2974        // SAFETY:
2975        // - We registered the required access in `init_nested_access`, so it's available.
2976        // - If we are fetching multiple entities concurrently,
2977        //   then `Self: IterQueryData`, so `D: ReadOnlyQueryData`,
2978        //   so it's safe to alias the queries.
2979        unsafe {
2980            Some(state.query_unchecked_manual_with_ticks(
2981                fetch.world,
2982                fetch.last_run,
2983                fetch.this_run,
2984            ))
2985        }
2986    }
2987
2988    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
2989        // This performs no access on the current entity
2990        // Access to the nested query is checked through `init_nested_access`
2991        iter::empty()
2992    }
2993}
2994
2995// SAFETY: All access is through `D`, which is read-only
2996unsafe impl<D: ReadOnlyQueryData, F: QueryFilter> ReadOnlyQueryData for NestedQuery<D, F> {}
2997
2998// SAFETY: All access to other entities is through `D`, which is read-only and does not conflict.
2999// Note that we must not impl IterQueryData for queries with mutable access,
3000// since the nested query must only be live for one entity at a time.
3001unsafe impl<D: ReadOnlyQueryData, F: QueryFilter> IterQueryData for NestedQuery<D, F> {}
3002
3003// Nested queries are always archetypal because `fetch` always returns `Some`.
3004// If `D::IS_ARCHETYPAL == false` or `F::IS_ARCHETYPAL == false`,
3005// then the nested query may filter out some entities that *it* matches,
3006// but it will never filter the outer query.
3007impl<D: ReadOnlyQueryData, F: QueryFilter> ArchetypeQueryData for NestedQuery<D, F> {}
3008
3009#[doc(hidden)]
3010pub struct OptionFetch<'w, T: WorldQuery> {
3011    fetch: T::Fetch<'w>,
3012    matches: bool,
3013}
3014
3015impl<T: WorldQuery> Clone for OptionFetch<'_, T> {
3016    fn clone(&self) -> Self {
3017        Self {
3018            fetch: self.fetch.clone(),
3019            matches: self.matches,
3020        }
3021    }
3022}
3023
3024// SAFETY:
3025// `fetch` might access any components that `T` accesses.
3026// This is sound because `update_component_access` adds the same accesses as `T`.
3027// Filters are unchanged.
3028unsafe impl<T: WorldQuery> WorldQuery for Option<T> {
3029    type Fetch<'w> = OptionFetch<'w, T>;
3030    type State = T::State;
3031
3032    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
3033        OptionFetch {
3034            fetch: T::shrink_fetch(fetch.fetch),
3035            matches: fetch.matches,
3036        }
3037    }
3038
3039    #[inline]
3040    unsafe fn init_fetch<'w, 's>(
3041        world: UnsafeWorldCell<'w>,
3042        state: &'s T::State,
3043        last_run: Tick,
3044        this_run: Tick,
3045    ) -> OptionFetch<'w, T> {
3046        OptionFetch {
3047            // SAFETY: The invariants are upheld by the caller.
3048            fetch: unsafe { T::init_fetch(world, state, last_run, this_run) },
3049            matches: false,
3050        }
3051    }
3052
3053    const IS_DENSE: bool = T::IS_DENSE;
3054
3055    #[inline]
3056    unsafe fn set_archetype<'w, 's>(
3057        fetch: &mut OptionFetch<'w, T>,
3058        state: &'s T::State,
3059        archetype: &'w Archetype,
3060        table: &'w Table,
3061    ) {
3062        fetch.matches = T::matches_component_set(state, &|id| archetype.contains(id));
3063        if fetch.matches {
3064            // SAFETY: The invariants are upheld by the caller.
3065            unsafe {
3066                T::set_archetype(&mut fetch.fetch, state, archetype, table);
3067            }
3068        }
3069    }
3070
3071    #[inline]
3072    unsafe fn set_table<'w, 's>(
3073        fetch: &mut OptionFetch<'w, T>,
3074        state: &'s T::State,
3075        table: &'w Table,
3076    ) {
3077        fetch.matches = T::matches_component_set(state, &|id| table.has_column(id));
3078        if fetch.matches {
3079            // SAFETY: The invariants are upheld by the caller.
3080            unsafe {
3081                T::set_table(&mut fetch.fetch, state, table);
3082            }
3083        }
3084    }
3085
3086    fn update_component_access(state: &T::State, access: &mut FilteredAccess) {
3087        // FilteredAccess::add_[write,read] adds the component to the `with` filter.
3088        // Those methods are called on `access` in `T::update_component_access`.
3089        // But in `Option<T>`, we specifically don't filter on `T`,
3090        // since `(Option<T>, &OtherComponent)` should be a valid item, even
3091        // if `Option<T>` is `None`.
3092        //
3093        // We pass a clone of the `FilteredAccess` to `T`, and only update the `Access`
3094        // using `extend_access` so that we can apply `T`'s component_access
3095        // without updating the `with` filters of `access`.
3096        let mut intermediate = access.clone();
3097        T::update_component_access(state, &mut intermediate);
3098        access.extend_access(&intermediate);
3099    }
3100
3101    fn init_nested_access(
3102        state: &Self::State,
3103        system_name: Option<&str>,
3104        component_access_set: &mut FilteredAccessSet,
3105        world: UnsafeWorldCell,
3106    ) {
3107        T::init_nested_access(state, system_name, component_access_set, world);
3108    }
3109
3110    fn init_state(world: &mut World) -> T::State {
3111        T::init_state(world)
3112    }
3113
3114    fn get_state(components: &Components) -> Option<Self::State> {
3115        T::get_state(components)
3116    }
3117
3118    fn matches_component_set(
3119        _state: &T::State,
3120        _set_contains_id: &impl Fn(ComponentId) -> bool,
3121    ) -> bool {
3122        true
3123    }
3124
3125    fn update_archetypes(state: &mut Self::State, world: UnsafeWorldCell) {
3126        T::update_archetypes(state, world);
3127    }
3128}
3129
3130// SAFETY: defers to soundness of `T: WorldQuery` impl
3131unsafe impl<T: QueryData> QueryData for Option<T> {
3132    const IS_READ_ONLY: bool = T::IS_READ_ONLY;
3133    // `Option` matches all entities, even if `T` does not,
3134    // so it's always an `ArchetypeQueryData`, even for non-archetypal `T`.
3135    const IS_ARCHETYPAL: bool = true;
3136    type ReadOnly = Option<T::ReadOnly>;
3137    type Item<'w, 's> = Option<T::Item<'w, 's>>;
3138
3139    fn shrink<'wlong: 'wshort, 'wshort, 's>(
3140        item: Self::Item<'wlong, 's>,
3141    ) -> Self::Item<'wshort, 's> {
3142        item.map(T::shrink)
3143    }
3144
3145    #[inline(always)]
3146    unsafe fn fetch<'w, 's>(
3147        state: &'s Self::State,
3148        fetch: &mut Self::Fetch<'w>,
3149        entity: Entity,
3150        table_row: TableRow,
3151    ) -> Option<Self::Item<'w, 's>> {
3152        Some(
3153            fetch
3154                .matches
3155                // SAFETY: The invariants are upheld by the caller.
3156                .then(|| unsafe { T::fetch(state, &mut fetch.fetch, entity, table_row) })
3157                .flatten(),
3158        )
3159    }
3160
3161    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
3162        T::iter_access(state)
3163    }
3164}
3165
3166// SAFETY: `Option<T>` is iterable because `T` is iterable
3167unsafe impl<T: IterQueryData> IterQueryData for Option<T> {}
3168
3169// SAFETY: `Option<T>` is read only because `T` is read only
3170unsafe impl<T: ReadOnlyQueryData> ReadOnlyQueryData for Option<T> {}
3171
3172// SAFETY: `Option<T>` only accesses the current entity because `T` only accesses the current entity
3173unsafe impl<T: SingleEntityQueryData> SingleEntityQueryData for Option<T> {}
3174
3175impl<T: ReleaseStateQueryData> ReleaseStateQueryData for Option<T> {
3176    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
3177        item.map(T::release_state)
3178    }
3179}
3180
3181// `Option` matches all entities, even if `T` does not,
3182// so it's always an `ArchetypeQueryData`, even for non-archetypal `T`.
3183impl<T: QueryData> ArchetypeQueryData for Option<T> {}
3184
3185impl<T: ContiguousQueryData> ContiguousQueryData for Option<T> {
3186    type Contiguous<'w, 's> = Option<T::Contiguous<'w, 's>>;
3187
3188    unsafe fn fetch_contiguous<'w, 's>(
3189        state: &'s Self::State,
3190        fetch: &mut Self::Fetch<'w>,
3191        entities: &'w [Entity],
3192    ) -> Self::Contiguous<'w, 's> {
3193        fetch
3194            .matches
3195            // SAFETY: The invariants are upheld by the caller
3196            .then(|| unsafe { T::fetch_contiguous(state, &mut fetch.fetch, entities) })
3197    }
3198}
3199
3200/// Returns a bool that describes if an entity has the component `T`.
3201///
3202/// This can be used in a [`Query`] if you want to know whether or not entities
3203/// have the component `T`  but don't actually care about the component's value.
3204///
3205/// # Footguns
3206///
3207/// Note that a `Query<Has<T>>` will match all existing entities.
3208/// Beware! Even if it matches all entities, it doesn't mean that `query.get(entity)`
3209/// will always return `Ok(bool)`.
3210///
3211/// In the case of a non-existent entity, such as a despawned one, it will return `Err`.
3212/// A workaround is to replace `query.get(entity).unwrap()` by
3213/// `query.get(entity).unwrap_or_default()`.
3214///
3215/// # Examples
3216///
3217/// ```
3218/// # use bevy_ecs::component::Component;
3219/// # use bevy_ecs::query::Has;
3220/// # use bevy_ecs::system::IntoSystem;
3221/// # use bevy_ecs::system::Query;
3222/// #
3223/// # #[derive(Component)]
3224/// # struct IsHungry;
3225/// # #[derive(Component)]
3226/// # struct Name { name: &'static str };
3227/// #
3228/// fn food_entity_system(query: Query<(&Name, Has<IsHungry>) >) {
3229///     for (name, is_hungry) in &query {
3230///         if is_hungry{
3231///             println!("{} would like some food.", name.name);
3232///         } else {
3233///             println!("{} has had sufficient.", name.name);
3234///         }
3235///     }
3236/// }
3237/// # bevy_ecs::system::assert_is_system(food_entity_system);
3238/// ```
3239///
3240/// ```
3241/// # use bevy_ecs::component::Component;
3242/// # use bevy_ecs::query::Has;
3243/// # use bevy_ecs::system::IntoSystem;
3244/// # use bevy_ecs::system::Query;
3245/// #
3246/// # #[derive(Component)]
3247/// # struct Alpha{has_beta: bool};
3248/// # #[derive(Component)]
3249/// # struct Beta { has_alpha: bool };
3250/// #
3251/// // Unlike `Option<&T>`, `Has<T>` is compatible with `&mut T`
3252/// // as it does not actually access any data.
3253/// fn alphabet_entity_system(mut alphas: Query<(&mut Alpha, Has<Beta>)>, mut betas: Query<(&mut Beta, Has<Alpha>)>) {
3254///     for (mut alpha, has_beta) in alphas.iter_mut() {
3255///         alpha.has_beta = has_beta;
3256///     }
3257///     for (mut beta, has_alpha) in betas.iter_mut() {
3258///         beta.has_alpha = has_alpha;
3259///     }
3260/// }
3261/// # bevy_ecs::system::assert_is_system(alphabet_entity_system);
3262/// ```
3263pub struct Has<T>(PhantomData<T>);
3264
3265impl<T> core::fmt::Debug for Has<T> {
3266    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
3267        f.write_fmt(format_args!("Has<{0}>", DebugName::type_name::<T>()))write!(f, "Has<{}>", DebugName::type_name::<T>())
3268    }
3269}
3270
3271// SAFETY:
3272// `update_component_access` does nothing.
3273// This is sound because `fetch` does not access components.
3274unsafe impl<T: Component> WorldQuery for Has<T> {
3275    type Fetch<'w> = bool;
3276    type State = ComponentId;
3277
3278    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
3279        fetch
3280    }
3281
3282    #[inline]
3283    unsafe fn init_fetch<'w, 's>(
3284        _world: UnsafeWorldCell<'w>,
3285        _state: &'s Self::State,
3286        _last_run: Tick,
3287        _this_run: Tick,
3288    ) -> Self::Fetch<'w> {
3289        false
3290    }
3291
3292    const IS_DENSE: bool = {
3293        match T::STORAGE_TYPE {
3294            StorageType::Table => true,
3295            StorageType::SparseSet => false,
3296        }
3297    };
3298
3299    #[inline]
3300    unsafe fn set_archetype<'w, 's>(
3301        fetch: &mut Self::Fetch<'w>,
3302        state: &'s Self::State,
3303        archetype: &'w Archetype,
3304        _table: &Table,
3305    ) {
3306        *fetch = archetype.contains(*state);
3307    }
3308
3309    #[inline]
3310    unsafe fn set_table<'w, 's>(
3311        fetch: &mut Self::Fetch<'w>,
3312        state: &'s Self::State,
3313        table: &'w Table,
3314    ) {
3315        *fetch = table.has_column(*state);
3316    }
3317
3318    fn update_component_access(&component_id: &Self::State, access: &mut FilteredAccess) {
3319        access.access_mut().add_archetypal(component_id);
3320    }
3321
3322    fn init_state(world: &mut World) -> ComponentId {
3323        world.register_component::<T>()
3324    }
3325
3326    fn get_state(components: &Components) -> Option<Self::State> {
3327        components.component_id::<T>()
3328    }
3329
3330    fn matches_component_set(
3331        _state: &Self::State,
3332        _set_contains_id: &impl Fn(ComponentId) -> bool,
3333    ) -> bool {
3334        // `Has<T>` always matches
3335        true
3336    }
3337}
3338
3339// SAFETY: `Self` is the same as `Self::ReadOnly`
3340unsafe impl<T: Component> QueryData for Has<T> {
3341    const IS_READ_ONLY: bool = true;
3342    const IS_ARCHETYPAL: bool = true;
3343    type ReadOnly = Self;
3344    type Item<'w, 's> = bool;
3345
3346    fn shrink<'wlong: 'wshort, 'wshort, 's>(
3347        item: Self::Item<'wlong, 's>,
3348    ) -> Self::Item<'wshort, 's> {
3349        item
3350    }
3351
3352    #[inline(always)]
3353    unsafe fn fetch<'w, 's>(
3354        _state: &'s Self::State,
3355        fetch: &mut Self::Fetch<'w>,
3356        _entity: Entity,
3357        _table_row: TableRow,
3358    ) -> Option<Self::Item<'w, 's>> {
3359        Some(*fetch)
3360    }
3361
3362    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
3363        iter::empty()
3364    }
3365}
3366
3367// SAFETY: access is read only and only on the current entity
3368unsafe impl<T: Component> IterQueryData for Has<T> {}
3369
3370// SAFETY: access is read only
3371unsafe impl<T: Component> ReadOnlyQueryData for Has<T> {}
3372
3373// SAFETY: access is only on the current entity
3374unsafe impl<T: Component> SingleEntityQueryData for Has<T> {}
3375
3376impl<T: Component> ReleaseStateQueryData for Has<T> {
3377    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
3378        item
3379    }
3380}
3381
3382impl<T: Component> ArchetypeQueryData for Has<T> {}
3383
3384impl<T: Component> ContiguousQueryData for Has<T> {
3385    type Contiguous<'w, 's> = bool;
3386
3387    unsafe fn fetch_contiguous<'w, 's>(
3388        _state: &'s Self::State,
3389        fetch: &mut Self::Fetch<'w>,
3390        _entities: &'w [Entity],
3391    ) -> Self::Contiguous<'w, 's> {
3392        *fetch
3393    }
3394}
3395
3396/// The `AnyOf` query parameter fetches entities with any of the component types included in T.
3397///
3398/// `Query<AnyOf<(&A, &B, &mut C)>>` is equivalent to `Query<(Option<&A>, Option<&B>, Option<&mut C>), Or<(With<A>, With<B>, With<C>)>>`.
3399/// Each of the components in `T` is returned as an `Option`, as with `Option<A>` queries.
3400/// Entities are guaranteed to have at least one of the components in `T`.
3401pub struct AnyOf<T>(PhantomData<T>);
3402
3403macro_rules! impl_tuple_query_data {
3404    ($(#[$meta:meta])* $(($name: ident, $item: ident, $state: ident)),*) => {
3405        #[expect(
3406            clippy::allow_attributes,
3407            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3408        )]
3409        #[allow(
3410            non_snake_case,
3411            reason = "The names of some variables are provided by the macro's caller, not by us."
3412        )]
3413        #[allow(
3414            unused_variables,
3415            reason = "Zero-length tuples won't use any of the parameters."
3416        )]
3417        #[allow(
3418            clippy::unused_unit,
3419            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3420        )]
3421        $(#[$meta])*
3422        // SAFETY: defers to soundness `$name: WorldQuery` impl
3423        unsafe impl<$($name: QueryData),*> QueryData for ($($name,)*) {
3424            const IS_READ_ONLY: bool = true $(&& $name::IS_READ_ONLY)*;
3425            const IS_ARCHETYPAL: bool = true $(&& $name::IS_ARCHETYPAL)*;
3426            type ReadOnly = ($($name::ReadOnly,)*);
3427            type Item<'w, 's> = ($($name::Item<'w, 's>,)*);
3428
3429            fn shrink<'wlong: 'wshort, 'wshort, 's>(item: Self::Item<'wlong, 's>) -> Self::Item<'wshort, 's> {
3430                let ($($name,)*) = item;
3431                ($(
3432                    $name::shrink($name),
3433                )*)
3434            }
3435
3436            #[inline]
3437            fn provide_extra_access(
3438                state: &mut Self::State,
3439                access: &mut Access,
3440                available_access: &Access,
3441            ) {
3442                let ($($name,)*) = state;
3443                $($name::provide_extra_access($name, access, available_access);)*
3444            }
3445
3446            #[inline(always)]
3447            unsafe fn fetch<'w, 's>(
3448                state: &'s Self::State,
3449                fetch: &mut Self::Fetch<'w>,
3450                entity: Entity,
3451                table_row: TableRow
3452            ) -> Option<Self::Item<'w, 's>> {
3453                let ($($state,)*) = state;
3454                let ($($name,)*) = fetch;
3455                // SAFETY: The invariants are upheld by the caller.
3456                Some(($(unsafe { $name::fetch($state, $name, entity, table_row) }?,)*))
3457            }
3458
3459            fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
3460                let ($($name,)*) = state;
3461                iter::empty()$(.chain($name::iter_access($name)))*
3462            }
3463        }
3464
3465        $(#[$meta])*
3466        // SAFETY: each item in the tuple is iterable
3467        unsafe impl<$($name: IterQueryData),*> IterQueryData for ($($name,)*) {}
3468
3469        $(#[$meta])*
3470        // SAFETY: each item in the tuple is read only
3471        unsafe impl<$($name: ReadOnlyQueryData),*> ReadOnlyQueryData for ($($name,)*) {}
3472
3473        $(#[$meta])*
3474        // SAFETY: each item in the tuple only accesses the current entity
3475        unsafe impl<$($name: SingleEntityQueryData),*> SingleEntityQueryData for ($($name,)*) {}
3476
3477        #[expect(
3478            clippy::allow_attributes,
3479            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3480        )]
3481        #[allow(
3482            clippy::unused_unit,
3483            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3484        )]
3485        $(#[$meta])*
3486        impl<$($name: ReleaseStateQueryData),*> ReleaseStateQueryData for ($($name,)*) {
3487            fn release_state<'w>(($($item,)*): Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
3488                ($($name::release_state($item),)*)
3489            }
3490        }
3491
3492        $(#[$meta])*
3493        impl<$($name: ArchetypeQueryData),*> ArchetypeQueryData for ($($name,)*) {}
3494
3495        #[expect(
3496            clippy::allow_attributes,
3497            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3498        )]
3499        #[allow(
3500            non_snake_case,
3501            reason = "The names of some variables are provided by the macro's caller, not by us."
3502        )]
3503        #[allow(
3504            unused_variables,
3505            reason = "Zero-length tuples won't use any of the parameters."
3506        )]
3507        #[allow(
3508            clippy::unused_unit,
3509            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3510        )]
3511        $(#[$meta])*
3512        impl<$($name: ContiguousQueryData),*> ContiguousQueryData for ($($name,)*) {
3513            type Contiguous<'w, 's> = ($($name::Contiguous::<'w, 's>,)*);
3514
3515            unsafe fn fetch_contiguous<'w, 's>(
3516                state: &'s Self::State,
3517                fetch: &mut Self::Fetch<'w>,
3518                entities: &'w [Entity],
3519            ) -> Self::Contiguous<'w, 's> {
3520                let ($($state,)*) = state;
3521                let ($($name,)*) = fetch;
3522                // SAFETY: The invariants are upheld by the caller.
3523                ($(unsafe {$name::fetch_contiguous($state, $name, entities)},)*)
3524            }
3525        }
3526    };
3527}
3528
3529macro_rules! impl_anytuple_fetch {
3530    ($(#[$meta:meta])* $(($name: ident, $state: ident, $item: ident)),*) => {
3531        $(#[$meta])*
3532        #[expect(
3533            clippy::allow_attributes,
3534            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3535        )]
3536        #[allow(
3537            non_snake_case,
3538            reason = "The names of some variables are provided by the macro's caller, not by us."
3539        )]
3540        #[allow(
3541            unused_variables,
3542            reason = "Zero-length tuples won't use any of the parameters."
3543        )]
3544        #[allow(
3545            clippy::unused_unit,
3546            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3547        )]
3548        // SAFETY:
3549        // `fetch` accesses are a subset of the subqueries' accesses
3550        // This is sound because `update_component_access` adds accesses according to the implementations of all the subqueries.
3551        // `update_component_access` replaces the filters with a disjunction where every element is a conjunction of the previous filters and the filters of one of the subqueries.
3552        // This is sound because `matches_component_set` returns a disjunction of the results of the subqueries' implementations.
3553        unsafe impl<$($name: WorldQuery),*> WorldQuery for AnyOf<($($name,)*)> {
3554            type Fetch<'w> = ($(($name::Fetch<'w>, bool),)*);
3555            type State = ($($name::State,)*);
3556
3557            fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
3558                let ($($name,)*) = fetch;
3559                ($(
3560                    ($name::shrink_fetch($name.0), $name.1),
3561                )*)
3562            }
3563
3564            #[inline]
3565            unsafe fn init_fetch<'w, 's>(_world: UnsafeWorldCell<'w>, state: &'s Self::State, _last_run: Tick, _this_run: Tick) -> Self::Fetch<'w> {
3566                let ($($name,)*) = state;
3567                // SAFETY: The invariants are upheld by the caller.
3568                ($(( unsafe { $name::init_fetch(_world, $name, _last_run, _this_run) }, false),)*)
3569            }
3570
3571            const IS_DENSE: bool = true $(&& $name::IS_DENSE)*;
3572
3573            #[inline]
3574            unsafe fn set_archetype<'w, 's>(
3575                _fetch: &mut Self::Fetch<'w>,
3576                _state: &'s Self::State,
3577                _archetype: &'w Archetype,
3578                _table: &'w Table
3579            ) {
3580                let ($($name,)*) = _fetch;
3581                let ($($state,)*) = _state;
3582                $(
3583                    $name.1 = $name::matches_component_set($state, &|id| _archetype.contains(id));
3584                    if $name.1 {
3585                        // SAFETY: The invariants are upheld by the caller.
3586                        unsafe { $name::set_archetype(&mut $name.0, $state, _archetype, _table); }
3587                    }
3588                )*
3589            }
3590
3591            #[inline]
3592            unsafe fn set_table<'w, 's>(_fetch: &mut Self::Fetch<'w>, _state: &'s Self::State, _table: &'w Table) {
3593                let ($($name,)*) = _fetch;
3594                let ($($state,)*) = _state;
3595                $(
3596                    $name.1 = $name::matches_component_set($state, &|id| _table.has_column(id));
3597                    if $name.1 {
3598                        // SAFETY: The invariants are required to be upheld by the caller.
3599                        unsafe { $name::set_table(&mut $name.0, $state, _table); }
3600                    }
3601                )*
3602            }
3603
3604            fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
3605                // update the filters (Or<(With<$name>,)>)
3606                let ($($name,)*) = state;
3607
3608                let mut _new_access = FilteredAccess::matches_nothing();
3609
3610                $(
3611                    // Create an intermediate because `access`'s value needs to be preserved
3612                    // for the next query data, and `_new_access` has to be modified only by `append_or` to it,
3613                    // which only updates the `filter_sets`, not the `access`.
3614                    let mut intermediate = access.clone();
3615                    $name::update_component_access($name, &mut intermediate);
3616                    _new_access.append_or(&intermediate);
3617                )*
3618
3619                // Of the accumulated `_new_access` we only care about the filter sets, not the access.
3620                access.filter_sets = _new_access.filter_sets;
3621
3622                // For the access we instead delegate to a tuple of `Option`s.
3623                // This has essentially the same semantics of `AnyOf`, except that it doesn't
3624                // require at least one of them to be `Some`.
3625                // We however solve this by setting explicitly the `filter_sets` above.
3626                // Also note that Option<T> updates the `access` but not the `filter_sets`.
3627                <($(Option<$name>,)*)>::update_component_access(state, access);
3628
3629            }
3630
3631            fn init_nested_access(
3632                state: &Self::State,
3633                system_name: Option<&str>,
3634                component_access_set: &mut FilteredAccessSet,
3635                world: UnsafeWorldCell,
3636            ) {
3637                <($(Option<$name>,)*)>::init_nested_access(state, system_name, component_access_set, world);
3638            }
3639
3640            fn init_state(world: &mut World) -> Self::State {
3641                ($($name::init_state(world),)*)
3642            }
3643            fn get_state(components: &Components) -> Option<Self::State> {
3644                Some(($($name::get_state(components)?,)*))
3645            }
3646
3647            fn matches_component_set(_state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
3648                let ($($name,)*) = _state;
3649                false $(|| $name::matches_component_set($name, _set_contains_id))*
3650            }
3651
3652            fn update_archetypes(state: &mut Self::State, world: UnsafeWorldCell) {
3653                <($(Option<$name>,)*)>::update_archetypes(state, world);
3654            }
3655        }
3656
3657        #[expect(
3658            clippy::allow_attributes,
3659            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3660        )]
3661        #[allow(
3662            non_snake_case,
3663            reason = "The names of some variables are provided by the macro's caller, not by us."
3664        )]
3665        #[allow(
3666            unused_variables,
3667            reason = "Zero-length tuples won't use any of the parameters."
3668        )]
3669        #[allow(
3670            clippy::unused_unit,
3671            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3672        )]
3673        $(#[$meta])*
3674        // SAFETY: defers to soundness of `$name: WorldQuery` impl
3675        unsafe impl<$($name: QueryData),*> QueryData for AnyOf<($($name,)*)> {
3676            const IS_READ_ONLY: bool = true $(&& $name::IS_READ_ONLY)*;
3677            const IS_ARCHETYPAL: bool = true $(&& $name::IS_ARCHETYPAL)*;
3678            type ReadOnly = AnyOf<($($name::ReadOnly,)*)>;
3679            type Item<'w, 's> = ($(Option<$name::Item<'w, 's>>,)*);
3680
3681            fn shrink<'wlong: 'wshort, 'wshort, 's>(item: Self::Item<'wlong, 's>) -> Self::Item<'wshort, 's> {
3682                let ($($name,)*) = item;
3683                ($(
3684                    $name.map($name::shrink),
3685                )*)
3686            }
3687
3688            #[inline(always)]
3689            unsafe fn fetch<'w, 's>(
3690                _state: &'s Self::State,
3691                _fetch: &mut Self::Fetch<'w>,
3692                _entity: Entity,
3693                _table_row: TableRow
3694            ) -> Option<Self::Item<'w, 's>> {
3695                let ($($name,)*) = _fetch;
3696                let ($($state,)*) = _state;
3697                let result = ($(
3698                    // SAFETY: The invariants are required to be upheld by the caller.
3699                    $name.1.then(|| unsafe { $name::fetch($state, &mut $name.0, _entity, _table_row) }).flatten(),
3700                )*);
3701                // If this is an archetypal query, then it is guaranteed to return `Some`,
3702                // and we can help the compiler remove branches by checking the const `IS_ARCHETYPAL` first.
3703                (Self::IS_ARCHETYPAL
3704                    // We want to return `Some` if the query matches this entity,
3705                    // which happens if at least one subquery returns `Some`.
3706                    // So, fetch everything as usual, but if all the subqueries return `None` then return `None` instead.
3707                    || !matches!(result, ($(Option::<QueryItem<$name>>::None,)*))
3708                    // If *none* of the subqueries matched the archetype, then this archetype was added in a transmute.
3709                    // We must treat those as matching in order to be consistent with `size_hint` for archetypal queries,
3710                    // so we treat them as matching for non-archetypal queries, as well.
3711                    || !(false $(|| $name.1)*))
3712                .then_some(result)
3713            }
3714
3715            fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
3716                let ($($name,)*) = state;
3717                iter::empty()$(.chain($name::iter_access($name)))*
3718            }
3719        }
3720
3721        $(#[$meta])*
3722        // SAFETY: each item in the tuple is iterable
3723        unsafe impl<$($name: IterQueryData),*> IterQueryData for AnyOf<($($name,)*)> {}
3724
3725        $(#[$meta])*
3726        // SAFETY: each item in the tuple is read only
3727        unsafe impl<$($name: ReadOnlyQueryData),*> ReadOnlyQueryData for AnyOf<($($name,)*)> {}
3728
3729        $(#[$meta])*
3730        // SAFETY: each item in the tuple only accesses the current entity
3731        unsafe impl<$($name: SingleEntityQueryData),*> SingleEntityQueryData for AnyOf<($($name,)*)> {}
3732
3733        #[expect(
3734            clippy::allow_attributes,
3735            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3736        )]
3737        #[allow(
3738            clippy::unused_unit,
3739            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3740        )]
3741        impl<$($name: ReleaseStateQueryData),*> ReleaseStateQueryData for AnyOf<($($name,)*)> {
3742            fn release_state<'w>(($($item,)*): Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
3743                ($($item.map(|$item| $name::release_state($item)),)*)
3744            }
3745        }
3746
3747        $(#[$meta])*
3748        impl<$($name: ArchetypeQueryData),*> ArchetypeQueryData for AnyOf<($($name,)*)> {}
3749
3750
3751        #[expect(
3752            clippy::allow_attributes,
3753            reason = "This is a tuple-related macro; as such the lints below may not always apply."
3754        )]
3755        #[allow(
3756            non_snake_case,
3757            reason = "The names of some variables are provided by the macro's caller, not by us."
3758        )]
3759        #[allow(
3760            unused_variables,
3761            reason = "Zero-length tuples won't use any of the parameters."
3762        )]
3763        #[allow(
3764            clippy::unused_unit,
3765            reason = "Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case."
3766        )]
3767        $(#[$meta])*
3768        impl<$($name: ContiguousQueryData),*> ContiguousQueryData for AnyOf<($($name,)*)> {
3769            type Contiguous<'w, 's> = ($(Option<$name::Contiguous<'w,'s>>,)*);
3770
3771            unsafe fn fetch_contiguous<'w, 's>(
3772                state: &'s Self::State,
3773                fetch: &mut Self::Fetch<'w>,
3774                entities: &'w [Entity],
3775            ) -> Self::Contiguous<'w, 's> {
3776                let ($($name,)*) = fetch;
3777                let ($($state,)*) = state;
3778                // Matches the [`QueryData::fetch`] except it always returns Some
3779                ($(
3780                    // SAFETY: The invariants are upheld by the caller
3781                    $name.1.then(|| unsafe { $name::fetch_contiguous($state, &mut $name.0, entities) }),
3782                )*)
3783            }
3784        }
3785    };
3786}
3787
3788#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(non_snake_case, reason =
"The names of some variables are provided by the macro's caller, not by us.")]
#[allow(unused_variables, reason =
"Zero-length tuples won't use any of the parameters.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
#[doc(hidden)]
unsafe impl<F0: QueryData, F1: QueryData, F2: QueryData, F3: QueryData,
    F4: QueryData, F5: QueryData, F6: QueryData, F7: QueryData, F8: QueryData,
    F9: QueryData, F10: QueryData, F11: QueryData, F12: QueryData,
    F13: QueryData, F14: QueryData> QueryData for
    (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
    const IS_READ_ONLY: bool =
        true && F0::IS_READ_ONLY && F1::IS_READ_ONLY && F2::IS_READ_ONLY &&
                                                        F3::IS_READ_ONLY && F4::IS_READ_ONLY && F5::IS_READ_ONLY &&
                                            F6::IS_READ_ONLY && F7::IS_READ_ONLY && F8::IS_READ_ONLY &&
                                F9::IS_READ_ONLY && F10::IS_READ_ONLY && F11::IS_READ_ONLY
                    && F12::IS_READ_ONLY && F13::IS_READ_ONLY &&
            F14::IS_READ_ONLY;
    const IS_ARCHETYPAL: bool =
        true && F0::IS_ARCHETYPAL && F1::IS_ARCHETYPAL && F2::IS_ARCHETYPAL &&
                                                        F3::IS_ARCHETYPAL && F4::IS_ARCHETYPAL && F5::IS_ARCHETYPAL
                                            && F6::IS_ARCHETYPAL && F7::IS_ARCHETYPAL &&
                                    F8::IS_ARCHETYPAL && F9::IS_ARCHETYPAL && F10::IS_ARCHETYPAL
                        && F11::IS_ARCHETYPAL && F12::IS_ARCHETYPAL &&
                F13::IS_ARCHETYPAL && F14::IS_ARCHETYPAL;
    type ReadOnly =
        (F0::ReadOnly, F1::ReadOnly, F2::ReadOnly, F3::ReadOnly, F4::ReadOnly,
        F5::ReadOnly, F6::ReadOnly, F7::ReadOnly, F8::ReadOnly, F9::ReadOnly,
        F10::ReadOnly, F11::ReadOnly, F12::ReadOnly, F13::ReadOnly,
        F14::ReadOnly);
    type Item<'w, 's> =
        (F0::Item<'w, 's>, F1::Item<'w, 's>, F2::Item<'w, 's>,
        F3::Item<'w, 's>, F4::Item<'w, 's>, F5::Item<'w, 's>,
        F6::Item<'w, 's>, F7::Item<'w, 's>, F8::Item<'w, 's>,
        F9::Item<'w, 's>, F10::Item<'w, 's>, F11::Item<'w, 's>,
        F12::Item<'w, 's>, F13::Item<'w, 's>, F14::Item<'w, 's>);
    fn shrink<'wlong: 'wshort, 'wshort, 's>(item: Self::Item<'wlong, 's>)
        -> Self::Item<'wshort, 's> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = item;
        (F0::shrink(F0), F1::shrink(F1), F2::shrink(F2), F3::shrink(F3),
            F4::shrink(F4), F5::shrink(F5), F6::shrink(F6), F7::shrink(F7),
            F8::shrink(F8), F9::shrink(F9), F10::shrink(F10),
            F11::shrink(F11), F12::shrink(F12), F13::shrink(F13),
            F14::shrink(F14))
    }
    #[inline]
    fn provide_extra_access(state: &mut Self::State, access: &mut Access,
        available_access: &Access) {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = state;
        F0::provide_extra_access(F0, access, available_access);
        F1::provide_extra_access(F1, access, available_access);
        F2::provide_extra_access(F2, access, available_access);
        F3::provide_extra_access(F3, access, available_access);
        F4::provide_extra_access(F4, access, available_access);
        F5::provide_extra_access(F5, access, available_access);
        F6::provide_extra_access(F6, access, available_access);
        F7::provide_extra_access(F7, access, available_access);
        F8::provide_extra_access(F8, access, available_access);
        F9::provide_extra_access(F9, access, available_access);
        F10::provide_extra_access(F10, access, available_access);
        F11::provide_extra_access(F11, access, available_access);
        F12::provide_extra_access(F12, access, available_access);
        F13::provide_extra_access(F13, access, available_access);
        F14::provide_extra_access(F14, access, available_access);
    }
    #[inline(always)]
    unsafe fn fetch<'w,
        's>(state: &'s Self::State, fetch: &mut Self::Fetch<'w>,
        entity: Entity, table_row: TableRow) -> Option<Self::Item<'w, 's>> {
        let (s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13,
                s14) = state;
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = fetch;
        Some((unsafe { F0::fetch(s0, F0, entity, table_row) }?,
                unsafe { F1::fetch(s1, F1, entity, table_row) }?,
                unsafe { F2::fetch(s2, F2, entity, table_row) }?,
                unsafe { F3::fetch(s3, F3, entity, table_row) }?,
                unsafe { F4::fetch(s4, F4, entity, table_row) }?,
                unsafe { F5::fetch(s5, F5, entity, table_row) }?,
                unsafe { F6::fetch(s6, F6, entity, table_row) }?,
                unsafe { F7::fetch(s7, F7, entity, table_row) }?,
                unsafe { F8::fetch(s8, F8, entity, table_row) }?,
                unsafe { F9::fetch(s9, F9, entity, table_row) }?,
                unsafe { F10::fetch(s10, F10, entity, table_row) }?,
                unsafe { F11::fetch(s11, F11, entity, table_row) }?,
                unsafe { F12::fetch(s12, F12, entity, table_row) }?,
                unsafe { F13::fetch(s13, F13, entity, table_row) }?,
                unsafe { F14::fetch(s14, F14, entity, table_row) }?))
    }
    fn iter_access(state: &Self::State)
        -> impl Iterator<Item = EcsAccessType<'_>> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = state;
        iter::empty().chain(F0::iter_access(F0)).chain(F1::iter_access(F1)).chain(F2::iter_access(F2)).chain(F3::iter_access(F3)).chain(F4::iter_access(F4)).chain(F5::iter_access(F5)).chain(F6::iter_access(F6)).chain(F7::iter_access(F7)).chain(F8::iter_access(F8)).chain(F9::iter_access(F9)).chain(F10::iter_access(F10)).chain(F11::iter_access(F11)).chain(F12::iter_access(F12)).chain(F13::iter_access(F13)).chain(F14::iter_access(F14))
    }
}
#[doc(hidden)]
unsafe impl<F0: IterQueryData, F1: IterQueryData, F2: IterQueryData,
    F3: IterQueryData, F4: IterQueryData, F5: IterQueryData,
    F6: IterQueryData, F7: IterQueryData, F8: IterQueryData,
    F9: IterQueryData, F10: IterQueryData, F11: IterQueryData,
    F12: IterQueryData, F13: IterQueryData, F14: IterQueryData> IterQueryData
    for (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
}
#[doc(hidden)]
unsafe impl<F0: ReadOnlyQueryData, F1: ReadOnlyQueryData,
    F2: ReadOnlyQueryData, F3: ReadOnlyQueryData, F4: ReadOnlyQueryData,
    F5: ReadOnlyQueryData, F6: ReadOnlyQueryData, F7: ReadOnlyQueryData,
    F8: ReadOnlyQueryData, F9: ReadOnlyQueryData, F10: ReadOnlyQueryData,
    F11: ReadOnlyQueryData, F12: ReadOnlyQueryData, F13: ReadOnlyQueryData,
    F14: ReadOnlyQueryData> ReadOnlyQueryData for
    (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
}
#[doc(hidden)]
unsafe impl<F0: SingleEntityQueryData, F1: SingleEntityQueryData,
    F2: SingleEntityQueryData, F3: SingleEntityQueryData,
    F4: SingleEntityQueryData, F5: SingleEntityQueryData,
    F6: SingleEntityQueryData, F7: SingleEntityQueryData,
    F8: SingleEntityQueryData, F9: SingleEntityQueryData,
    F10: SingleEntityQueryData, F11: SingleEntityQueryData,
    F12: SingleEntityQueryData, F13: SingleEntityQueryData,
    F14: SingleEntityQueryData> SingleEntityQueryData for
    (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
}
#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
#[doc(hidden)]
impl<F0: ReleaseStateQueryData, F1: ReleaseStateQueryData,
    F2: ReleaseStateQueryData, F3: ReleaseStateQueryData,
    F4: ReleaseStateQueryData, F5: ReleaseStateQueryData,
    F6: ReleaseStateQueryData, F7: ReleaseStateQueryData,
    F8: ReleaseStateQueryData, F9: ReleaseStateQueryData,
    F10: ReleaseStateQueryData, F11: ReleaseStateQueryData,
    F12: ReleaseStateQueryData, F13: ReleaseStateQueryData,
    F14: ReleaseStateQueryData> ReleaseStateQueryData for
    (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
    fn release_state<'w>((i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11,
            i12, i13, i14): Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
        (F0::release_state(i0), F1::release_state(i1), F2::release_state(i2),
            F3::release_state(i3), F4::release_state(i4),
            F5::release_state(i5), F6::release_state(i6),
            F7::release_state(i7), F8::release_state(i8),
            F9::release_state(i9), F10::release_state(i10),
            F11::release_state(i11), F12::release_state(i12),
            F13::release_state(i13), F14::release_state(i14))
    }
}
#[doc(hidden)]
impl<F0: ArchetypeQueryData, F1: ArchetypeQueryData, F2: ArchetypeQueryData,
    F3: ArchetypeQueryData, F4: ArchetypeQueryData, F5: ArchetypeQueryData,
    F6: ArchetypeQueryData, F7: ArchetypeQueryData, F8: ArchetypeQueryData,
    F9: ArchetypeQueryData, F10: ArchetypeQueryData, F11: ArchetypeQueryData,
    F12: ArchetypeQueryData, F13: ArchetypeQueryData, F14: ArchetypeQueryData>
    ArchetypeQueryData for
    (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
}
#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(non_snake_case, reason =
"The names of some variables are provided by the macro's caller, not by us.")]
#[allow(unused_variables, reason =
"Zero-length tuples won't use any of the parameters.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
#[doc(hidden)]
impl<F0: ContiguousQueryData, F1: ContiguousQueryData,
    F2: ContiguousQueryData, F3: ContiguousQueryData, F4: ContiguousQueryData,
    F5: ContiguousQueryData, F6: ContiguousQueryData, F7: ContiguousQueryData,
    F8: ContiguousQueryData, F9: ContiguousQueryData,
    F10: ContiguousQueryData, F11: ContiguousQueryData,
    F12: ContiguousQueryData, F13: ContiguousQueryData,
    F14: ContiguousQueryData> ContiguousQueryData for
    (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14) {
    type Contiguous<'w, 's> =
        (F0::Contiguous<'w, 's>, F1::Contiguous<'w, 's>,
        F2::Contiguous<'w, 's>, F3::Contiguous<'w, 's>,
        F4::Contiguous<'w, 's>, F5::Contiguous<'w, 's>,
        F6::Contiguous<'w, 's>, F7::Contiguous<'w, 's>,
        F8::Contiguous<'w, 's>, F9::Contiguous<'w, 's>,
        F10::Contiguous<'w, 's>, F11::Contiguous<'w, 's>,
        F12::Contiguous<'w, 's>, F13::Contiguous<'w, 's>,
        F14::Contiguous<'w, 's>);
    unsafe fn fetch_contiguous<'w,
        's>(state: &'s Self::State, fetch: &mut Self::Fetch<'w>,
        entities: &'w [Entity]) -> Self::Contiguous<'w, 's> {
        let (s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13,
                s14) = state;
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = fetch;
        (unsafe { F0::fetch_contiguous(s0, F0, entities) },
            unsafe { F1::fetch_contiguous(s1, F1, entities) },
            unsafe { F2::fetch_contiguous(s2, F2, entities) },
            unsafe { F3::fetch_contiguous(s3, F3, entities) },
            unsafe { F4::fetch_contiguous(s4, F4, entities) },
            unsafe { F5::fetch_contiguous(s5, F5, entities) },
            unsafe { F6::fetch_contiguous(s6, F6, entities) },
            unsafe { F7::fetch_contiguous(s7, F7, entities) },
            unsafe { F8::fetch_contiguous(s8, F8, entities) },
            unsafe { F9::fetch_contiguous(s9, F9, entities) },
            unsafe { F10::fetch_contiguous(s10, F10, entities) },
            unsafe { F11::fetch_contiguous(s11, F11, entities) },
            unsafe { F12::fetch_contiguous(s12, F12, entities) },
            unsafe { F13::fetch_contiguous(s13, F13, entities) },
            unsafe { F14::fetch_contiguous(s14, F14, entities) })
    }
}all_tuples!(
3789    #[doc(fake_variadic)]
3790    impl_tuple_query_data,
3791    0,
3792    15,
3793    F,
3794    i,
3795    s
3796);
3797#[doc(hidden)]
#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(non_snake_case, reason =
"The names of some variables are provided by the macro's caller, not by us.")]
#[allow(unused_variables, reason =
"Zero-length tuples won't use any of the parameters.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
unsafe impl<F0: WorldQuery, F1: WorldQuery, F2: WorldQuery, F3: WorldQuery,
    F4: WorldQuery, F5: WorldQuery, F6: WorldQuery, F7: WorldQuery,
    F8: WorldQuery, F9: WorldQuery, F10: WorldQuery, F11: WorldQuery,
    F12: WorldQuery, F13: WorldQuery, F14: WorldQuery> WorldQuery for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
    type Fetch<'w> =
        ((F0::Fetch<'w>, bool), (F1::Fetch<'w>, bool), (F2::Fetch<'w>, bool),
        (F3::Fetch<'w>, bool), (F4::Fetch<'w>, bool), (F5::Fetch<'w>, bool),
        (F6::Fetch<'w>, bool), (F7::Fetch<'w>, bool), (F8::Fetch<'w>, bool),
        (F9::Fetch<'w>, bool), (F10::Fetch<'w>, bool), (F11::Fetch<'w>, bool),
        (F12::Fetch<'w>, bool), (F13::Fetch<'w>, bool),
        (F14::Fetch<'w>, bool));
    type State =
        (F0::State, F1::State, F2::State, F3::State, F4::State, F5::State,
        F6::State, F7::State, F8::State, F9::State, F10::State, F11::State,
        F12::State, F13::State, F14::State);
    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>)
        -> Self::Fetch<'wshort> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = fetch;
        ((F0::shrink_fetch(F0.0), F0.1), (F1::shrink_fetch(F1.0), F1.1),
            (F2::shrink_fetch(F2.0), F2.1), (F3::shrink_fetch(F3.0), F3.1),
            (F4::shrink_fetch(F4.0), F4.1), (F5::shrink_fetch(F5.0), F5.1),
            (F6::shrink_fetch(F6.0), F6.1), (F7::shrink_fetch(F7.0), F7.1),
            (F8::shrink_fetch(F8.0), F8.1), (F9::shrink_fetch(F9.0), F9.1),
            (F10::shrink_fetch(F10.0), F10.1),
            (F11::shrink_fetch(F11.0), F11.1),
            (F12::shrink_fetch(F12.0), F12.1),
            (F13::shrink_fetch(F13.0), F13.1),
            (F14::shrink_fetch(F14.0), F14.1))
    }
    #[inline]
    unsafe fn init_fetch<'w,
        's>(_world: UnsafeWorldCell<'w>, state: &'s Self::State,
        _last_run: Tick, _this_run: Tick) -> Self::Fetch<'w> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = state;
        ((unsafe { F0::init_fetch(_world, F0, _last_run, _this_run) }, false),
            (unsafe { F1::init_fetch(_world, F1, _last_run, _this_run) },
                false),
            (unsafe { F2::init_fetch(_world, F2, _last_run, _this_run) },
                false),
            (unsafe { F3::init_fetch(_world, F3, _last_run, _this_run) },
                false),
            (unsafe { F4::init_fetch(_world, F4, _last_run, _this_run) },
                false),
            (unsafe { F5::init_fetch(_world, F5, _last_run, _this_run) },
                false),
            (unsafe { F6::init_fetch(_world, F6, _last_run, _this_run) },
                false),
            (unsafe { F7::init_fetch(_world, F7, _last_run, _this_run) },
                false),
            (unsafe { F8::init_fetch(_world, F8, _last_run, _this_run) },
                false),
            (unsafe { F9::init_fetch(_world, F9, _last_run, _this_run) },
                false),
            (unsafe { F10::init_fetch(_world, F10, _last_run, _this_run) },
                false),
            (unsafe { F11::init_fetch(_world, F11, _last_run, _this_run) },
                false),
            (unsafe { F12::init_fetch(_world, F12, _last_run, _this_run) },
                false),
            (unsafe { F13::init_fetch(_world, F13, _last_run, _this_run) },
                false),
            (unsafe { F14::init_fetch(_world, F14, _last_run, _this_run) },
                false))
    }
    const IS_DENSE: bool =
        true && F0::IS_DENSE && F1::IS_DENSE && F2::IS_DENSE && F3::IS_DENSE
                                                    && F4::IS_DENSE && F5::IS_DENSE && F6::IS_DENSE &&
                                        F7::IS_DENSE && F8::IS_DENSE && F9::IS_DENSE &&
                            F10::IS_DENSE && F11::IS_DENSE && F12::IS_DENSE &&
                F13::IS_DENSE && F14::IS_DENSE;
    #[inline]
    unsafe fn set_archetype<'w,
        's>(_fetch: &mut Self::Fetch<'w>, _state: &'s Self::State,
        _archetype: &'w Archetype, _table: &'w Table) {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = _fetch;
        let (S0, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13,
                S14) = _state;
        F0.1 = F0::matches_component_set(S0, &|id| _archetype.contains(id));
        if F0.1 {
            unsafe { F0::set_archetype(&mut F0.0, S0, _archetype, _table); }
        }
        F1.1 = F1::matches_component_set(S1, &|id| _archetype.contains(id));
        if F1.1 {
            unsafe { F1::set_archetype(&mut F1.0, S1, _archetype, _table); }
        }
        F2.1 = F2::matches_component_set(S2, &|id| _archetype.contains(id));
        if F2.1 {
            unsafe { F2::set_archetype(&mut F2.0, S2, _archetype, _table); }
        }
        F3.1 = F3::matches_component_set(S3, &|id| _archetype.contains(id));
        if F3.1 {
            unsafe { F3::set_archetype(&mut F3.0, S3, _archetype, _table); }
        }
        F4.1 = F4::matches_component_set(S4, &|id| _archetype.contains(id));
        if F4.1 {
            unsafe { F4::set_archetype(&mut F4.0, S4, _archetype, _table); }
        }
        F5.1 = F5::matches_component_set(S5, &|id| _archetype.contains(id));
        if F5.1 {
            unsafe { F5::set_archetype(&mut F5.0, S5, _archetype, _table); }
        }
        F6.1 = F6::matches_component_set(S6, &|id| _archetype.contains(id));
        if F6.1 {
            unsafe { F6::set_archetype(&mut F6.0, S6, _archetype, _table); }
        }
        F7.1 = F7::matches_component_set(S7, &|id| _archetype.contains(id));
        if F7.1 {
            unsafe { F7::set_archetype(&mut F7.0, S7, _archetype, _table); }
        }
        F8.1 = F8::matches_component_set(S8, &|id| _archetype.contains(id));
        if F8.1 {
            unsafe { F8::set_archetype(&mut F8.0, S8, _archetype, _table); }
        }
        F9.1 = F9::matches_component_set(S9, &|id| _archetype.contains(id));
        if F9.1 {
            unsafe { F9::set_archetype(&mut F9.0, S9, _archetype, _table); }
        }
        F10.1 =
            F10::matches_component_set(S10, &|id| _archetype.contains(id));
        if F10.1 {
            unsafe {
                F10::set_archetype(&mut F10.0, S10, _archetype, _table);
            }
        }
        F11.1 =
            F11::matches_component_set(S11, &|id| _archetype.contains(id));
        if F11.1 {
            unsafe {
                F11::set_archetype(&mut F11.0, S11, _archetype, _table);
            }
        }
        F12.1 =
            F12::matches_component_set(S12, &|id| _archetype.contains(id));
        if F12.1 {
            unsafe {
                F12::set_archetype(&mut F12.0, S12, _archetype, _table);
            }
        }
        F13.1 =
            F13::matches_component_set(S13, &|id| _archetype.contains(id));
        if F13.1 {
            unsafe {
                F13::set_archetype(&mut F13.0, S13, _archetype, _table);
            }
        }
        F14.1 =
            F14::matches_component_set(S14, &|id| _archetype.contains(id));
        if F14.1 {
            unsafe {
                F14::set_archetype(&mut F14.0, S14, _archetype, _table);
            }
        }
    }
    #[inline]
    unsafe fn set_table<'w,
        's>(_fetch: &mut Self::Fetch<'w>, _state: &'s Self::State,
        _table: &'w Table) {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = _fetch;
        let (S0, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13,
                S14) = _state;
        F0.1 = F0::matches_component_set(S0, &|id| _table.has_column(id));
        if F0.1 { unsafe { F0::set_table(&mut F0.0, S0, _table); } }
        F1.1 = F1::matches_component_set(S1, &|id| _table.has_column(id));
        if F1.1 { unsafe { F1::set_table(&mut F1.0, S1, _table); } }
        F2.1 = F2::matches_component_set(S2, &|id| _table.has_column(id));
        if F2.1 { unsafe { F2::set_table(&mut F2.0, S2, _table); } }
        F3.1 = F3::matches_component_set(S3, &|id| _table.has_column(id));
        if F3.1 { unsafe { F3::set_table(&mut F3.0, S3, _table); } }
        F4.1 = F4::matches_component_set(S4, &|id| _table.has_column(id));
        if F4.1 { unsafe { F4::set_table(&mut F4.0, S4, _table); } }
        F5.1 = F5::matches_component_set(S5, &|id| _table.has_column(id));
        if F5.1 { unsafe { F5::set_table(&mut F5.0, S5, _table); } }
        F6.1 = F6::matches_component_set(S6, &|id| _table.has_column(id));
        if F6.1 { unsafe { F6::set_table(&mut F6.0, S6, _table); } }
        F7.1 = F7::matches_component_set(S7, &|id| _table.has_column(id));
        if F7.1 { unsafe { F7::set_table(&mut F7.0, S7, _table); } }
        F8.1 = F8::matches_component_set(S8, &|id| _table.has_column(id));
        if F8.1 { unsafe { F8::set_table(&mut F8.0, S8, _table); } }
        F9.1 = F9::matches_component_set(S9, &|id| _table.has_column(id));
        if F9.1 { unsafe { F9::set_table(&mut F9.0, S9, _table); } }
        F10.1 = F10::matches_component_set(S10, &|id| _table.has_column(id));
        if F10.1 { unsafe { F10::set_table(&mut F10.0, S10, _table); } }
        F11.1 = F11::matches_component_set(S11, &|id| _table.has_column(id));
        if F11.1 { unsafe { F11::set_table(&mut F11.0, S11, _table); } }
        F12.1 = F12::matches_component_set(S12, &|id| _table.has_column(id));
        if F12.1 { unsafe { F12::set_table(&mut F12.0, S12, _table); } }
        F13.1 = F13::matches_component_set(S13, &|id| _table.has_column(id));
        if F13.1 { unsafe { F13::set_table(&mut F13.0, S13, _table); } }
        F14.1 = F14::matches_component_set(S14, &|id| _table.has_column(id));
        if F14.1 { unsafe { F14::set_table(&mut F14.0, S14, _table); } }
    }
    fn update_component_access(state: &Self::State,
        access: &mut FilteredAccess) {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = state;
        let mut _new_access = FilteredAccess::matches_nothing();
        let mut intermediate = access.clone();
        F0::update_component_access(F0, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F1::update_component_access(F1, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F2::update_component_access(F2, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F3::update_component_access(F3, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F4::update_component_access(F4, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F5::update_component_access(F5, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F6::update_component_access(F6, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F7::update_component_access(F7, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F8::update_component_access(F8, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F9::update_component_access(F9, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F10::update_component_access(F10, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F11::update_component_access(F11, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F12::update_component_access(F12, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F13::update_component_access(F13, &mut intermediate);
        _new_access.append_or(&intermediate);
        let mut intermediate = access.clone();
        F14::update_component_access(F14, &mut intermediate);
        _new_access.append_or(&intermediate);
        access.filter_sets = _new_access.filter_sets;
        <(Option<F0>, Option<F1>, Option<F2>, Option<F3>, Option<F4>,
                Option<F5>, Option<F6>, Option<F7>, Option<F8>, Option<F9>,
                Option<F10>, Option<F11>, Option<F12>, Option<F13>,
                Option<F14>)>::update_component_access(state, access);
    }
    fn init_nested_access(state: &Self::State, system_name: Option<&str>,
        component_access_set: &mut FilteredAccessSet,
        world: UnsafeWorldCell) {
        <(Option<F0>, Option<F1>, Option<F2>, Option<F3>, Option<F4>,
                Option<F5>, Option<F6>, Option<F7>, Option<F8>, Option<F9>,
                Option<F10>, Option<F11>, Option<F12>, Option<F13>,
                Option<F14>)>::init_nested_access(state, system_name,
            component_access_set, world);
    }
    fn init_state(world: &mut World) -> Self::State {
        (F0::init_state(world), F1::init_state(world), F2::init_state(world),
            F3::init_state(world), F4::init_state(world),
            F5::init_state(world), F6::init_state(world),
            F7::init_state(world), F8::init_state(world),
            F9::init_state(world), F10::init_state(world),
            F11::init_state(world), F12::init_state(world),
            F13::init_state(world), F14::init_state(world))
    }
    fn get_state(components: &Components) -> Option<Self::State> {
        Some((F0::get_state(components)?, F1::get_state(components)?,
                F2::get_state(components)?, F3::get_state(components)?,
                F4::get_state(components)?, F5::get_state(components)?,
                F6::get_state(components)?, F7::get_state(components)?,
                F8::get_state(components)?, F9::get_state(components)?,
                F10::get_state(components)?, F11::get_state(components)?,
                F12::get_state(components)?, F13::get_state(components)?,
                F14::get_state(components)?))
    }
    fn matches_component_set(_state: &Self::State,
        _set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = _state;
        false || F0::matches_component_set(F0, _set_contains_id) ||
                                                                F1::matches_component_set(F1, _set_contains_id) ||
                                                            F2::matches_component_set(F2, _set_contains_id) ||
                                                        F3::matches_component_set(F3, _set_contains_id) ||
                                                    F4::matches_component_set(F4, _set_contains_id) ||
                                                F5::matches_component_set(F5, _set_contains_id) ||
                                            F6::matches_component_set(F6, _set_contains_id) ||
                                        F7::matches_component_set(F7, _set_contains_id) ||
                                    F8::matches_component_set(F8, _set_contains_id) ||
                                F9::matches_component_set(F9, _set_contains_id) ||
                            F10::matches_component_set(F10, _set_contains_id) ||
                        F11::matches_component_set(F11, _set_contains_id) ||
                    F12::matches_component_set(F12, _set_contains_id) ||
                F13::matches_component_set(F13, _set_contains_id) ||
            F14::matches_component_set(F14, _set_contains_id)
    }
    fn update_archetypes(state: &mut Self::State, world: UnsafeWorldCell) {
        <(Option<F0>, Option<F1>, Option<F2>, Option<F3>, Option<F4>,
                Option<F5>, Option<F6>, Option<F7>, Option<F8>, Option<F9>,
                Option<F10>, Option<F11>, Option<F12>, Option<F13>,
                Option<F14>)>::update_archetypes(state, world);
    }
}
#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(non_snake_case, reason =
"The names of some variables are provided by the macro's caller, not by us.")]
#[allow(unused_variables, reason =
"Zero-length tuples won't use any of the parameters.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
#[doc(hidden)]
unsafe impl<F0: QueryData, F1: QueryData, F2: QueryData, F3: QueryData,
    F4: QueryData, F5: QueryData, F6: QueryData, F7: QueryData, F8: QueryData,
    F9: QueryData, F10: QueryData, F11: QueryData, F12: QueryData,
    F13: QueryData, F14: QueryData> QueryData for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
    const IS_READ_ONLY: bool =
        true && F0::IS_READ_ONLY && F1::IS_READ_ONLY && F2::IS_READ_ONLY &&
                                                        F3::IS_READ_ONLY && F4::IS_READ_ONLY && F5::IS_READ_ONLY &&
                                            F6::IS_READ_ONLY && F7::IS_READ_ONLY && F8::IS_READ_ONLY &&
                                F9::IS_READ_ONLY && F10::IS_READ_ONLY && F11::IS_READ_ONLY
                    && F12::IS_READ_ONLY && F13::IS_READ_ONLY &&
            F14::IS_READ_ONLY;
    const IS_ARCHETYPAL: bool =
        true && F0::IS_ARCHETYPAL && F1::IS_ARCHETYPAL && F2::IS_ARCHETYPAL &&
                                                        F3::IS_ARCHETYPAL && F4::IS_ARCHETYPAL && F5::IS_ARCHETYPAL
                                            && F6::IS_ARCHETYPAL && F7::IS_ARCHETYPAL &&
                                    F8::IS_ARCHETYPAL && F9::IS_ARCHETYPAL && F10::IS_ARCHETYPAL
                        && F11::IS_ARCHETYPAL && F12::IS_ARCHETYPAL &&
                F13::IS_ARCHETYPAL && F14::IS_ARCHETYPAL;
    type ReadOnly =
        AnyOf<(F0::ReadOnly, F1::ReadOnly, F2::ReadOnly, F3::ReadOnly,
        F4::ReadOnly, F5::ReadOnly, F6::ReadOnly, F7::ReadOnly, F8::ReadOnly,
        F9::ReadOnly, F10::ReadOnly, F11::ReadOnly, F12::ReadOnly,
        F13::ReadOnly, F14::ReadOnly)>;
    type Item<'w, 's> =
        (Option<F0::Item<'w, 's>>, Option<F1::Item<'w, 's>>,
        Option<F2::Item<'w, 's>>, Option<F3::Item<'w, 's>>,
        Option<F4::Item<'w, 's>>, Option<F5::Item<'w, 's>>,
        Option<F6::Item<'w, 's>>, Option<F7::Item<'w, 's>>,
        Option<F8::Item<'w, 's>>, Option<F9::Item<'w, 's>>,
        Option<F10::Item<'w, 's>>, Option<F11::Item<'w, 's>>,
        Option<F12::Item<'w, 's>>, Option<F13::Item<'w, 's>>,
        Option<F14::Item<'w, 's>>);
    fn shrink<'wlong: 'wshort, 'wshort, 's>(item: Self::Item<'wlong, 's>)
        -> Self::Item<'wshort, 's> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = item;
        (F0.map(F0::shrink), F1.map(F1::shrink), F2.map(F2::shrink),
            F3.map(F3::shrink), F4.map(F4::shrink), F5.map(F5::shrink),
            F6.map(F6::shrink), F7.map(F7::shrink), F8.map(F8::shrink),
            F9.map(F9::shrink), F10.map(F10::shrink), F11.map(F11::shrink),
            F12.map(F12::shrink), F13.map(F13::shrink), F14.map(F14::shrink))
    }
    #[inline(always)]
    unsafe fn fetch<'w,
        's>(_state: &'s Self::State, _fetch: &mut Self::Fetch<'w>,
        _entity: Entity, _table_row: TableRow) -> Option<Self::Item<'w, 's>> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = _fetch;
        let (S0, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13,
                S14) = _state;
        let result =
            (F0.1.then(||
                            unsafe {
                                F0::fetch(S0, &mut F0.0, _entity, _table_row)
                            }).flatten(),
                F1.1.then(||
                            unsafe {
                                F1::fetch(S1, &mut F1.0, _entity, _table_row)
                            }).flatten(),
                F2.1.then(||
                            unsafe {
                                F2::fetch(S2, &mut F2.0, _entity, _table_row)
                            }).flatten(),
                F3.1.then(||
                            unsafe {
                                F3::fetch(S3, &mut F3.0, _entity, _table_row)
                            }).flatten(),
                F4.1.then(||
                            unsafe {
                                F4::fetch(S4, &mut F4.0, _entity, _table_row)
                            }).flatten(),
                F5.1.then(||
                            unsafe {
                                F5::fetch(S5, &mut F5.0, _entity, _table_row)
                            }).flatten(),
                F6.1.then(||
                            unsafe {
                                F6::fetch(S6, &mut F6.0, _entity, _table_row)
                            }).flatten(),
                F7.1.then(||
                            unsafe {
                                F7::fetch(S7, &mut F7.0, _entity, _table_row)
                            }).flatten(),
                F8.1.then(||
                            unsafe {
                                F8::fetch(S8, &mut F8.0, _entity, _table_row)
                            }).flatten(),
                F9.1.then(||
                            unsafe {
                                F9::fetch(S9, &mut F9.0, _entity, _table_row)
                            }).flatten(),
                F10.1.then(||
                            unsafe {
                                F10::fetch(S10, &mut F10.0, _entity, _table_row)
                            }).flatten(),
                F11.1.then(||
                            unsafe {
                                F11::fetch(S11, &mut F11.0, _entity, _table_row)
                            }).flatten(),
                F12.1.then(||
                            unsafe {
                                F12::fetch(S12, &mut F12.0, _entity, _table_row)
                            }).flatten(),
                F13.1.then(||
                            unsafe {
                                F13::fetch(S13, &mut F13.0, _entity, _table_row)
                            }).flatten(),
                F14.1.then(||
                            unsafe {
                                F14::fetch(S14, &mut F14.0, _entity, _table_row)
                            }).flatten());
        (Self::IS_ARCHETYPAL ||
                        !#[allow(non_exhaustive_omitted_patterns)] match result {
                                (Option::<QueryItem<F0>>::None,
                                    Option::<QueryItem<F1>>::None,
                                    Option::<QueryItem<F2>>::None,
                                    Option::<QueryItem<F3>>::None,
                                    Option::<QueryItem<F4>>::None,
                                    Option::<QueryItem<F5>>::None,
                                    Option::<QueryItem<F6>>::None,
                                    Option::<QueryItem<F7>>::None,
                                    Option::<QueryItem<F8>>::None,
                                    Option::<QueryItem<F9>>::None,
                                    Option::<QueryItem<F10>>::None,
                                    Option::<QueryItem<F11>>::None,
                                    Option::<QueryItem<F12>>::None,
                                    Option::<QueryItem<F13>>::None,
                                    Option::<QueryItem<F14>>::None) => true,
                                _ => false,
                            } ||
                    !(false || F0.1 || F1.1 || F2.1 || F3.1 || F4.1 || F5.1 ||
                                                                F6.1 || F7.1 || F8.1 || F9.1 || F10.1 || F11.1 || F12.1 ||
                                    F13.1 || F14.1)).then_some(result)
    }
    fn iter_access(state: &Self::State)
        -> impl Iterator<Item = EcsAccessType<'_>> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = state;
        iter::empty().chain(F0::iter_access(F0)).chain(F1::iter_access(F1)).chain(F2::iter_access(F2)).chain(F3::iter_access(F3)).chain(F4::iter_access(F4)).chain(F5::iter_access(F5)).chain(F6::iter_access(F6)).chain(F7::iter_access(F7)).chain(F8::iter_access(F8)).chain(F9::iter_access(F9)).chain(F10::iter_access(F10)).chain(F11::iter_access(F11)).chain(F12::iter_access(F12)).chain(F13::iter_access(F13)).chain(F14::iter_access(F14))
    }
}
#[doc(hidden)]
unsafe impl<F0: IterQueryData, F1: IterQueryData, F2: IterQueryData,
    F3: IterQueryData, F4: IterQueryData, F5: IterQueryData,
    F6: IterQueryData, F7: IterQueryData, F8: IterQueryData,
    F9: IterQueryData, F10: IterQueryData, F11: IterQueryData,
    F12: IterQueryData, F13: IterQueryData, F14: IterQueryData> IterQueryData
    for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
}
#[doc(hidden)]
unsafe impl<F0: ReadOnlyQueryData, F1: ReadOnlyQueryData,
    F2: ReadOnlyQueryData, F3: ReadOnlyQueryData, F4: ReadOnlyQueryData,
    F5: ReadOnlyQueryData, F6: ReadOnlyQueryData, F7: ReadOnlyQueryData,
    F8: ReadOnlyQueryData, F9: ReadOnlyQueryData, F10: ReadOnlyQueryData,
    F11: ReadOnlyQueryData, F12: ReadOnlyQueryData, F13: ReadOnlyQueryData,
    F14: ReadOnlyQueryData> ReadOnlyQueryData for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
}
#[doc(hidden)]
unsafe impl<F0: SingleEntityQueryData, F1: SingleEntityQueryData,
    F2: SingleEntityQueryData, F3: SingleEntityQueryData,
    F4: SingleEntityQueryData, F5: SingleEntityQueryData,
    F6: SingleEntityQueryData, F7: SingleEntityQueryData,
    F8: SingleEntityQueryData, F9: SingleEntityQueryData,
    F10: SingleEntityQueryData, F11: SingleEntityQueryData,
    F12: SingleEntityQueryData, F13: SingleEntityQueryData,
    F14: SingleEntityQueryData> SingleEntityQueryData for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
}
#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
impl<F0: ReleaseStateQueryData, F1: ReleaseStateQueryData,
    F2: ReleaseStateQueryData, F3: ReleaseStateQueryData,
    F4: ReleaseStateQueryData, F5: ReleaseStateQueryData,
    F6: ReleaseStateQueryData, F7: ReleaseStateQueryData,
    F8: ReleaseStateQueryData, F9: ReleaseStateQueryData,
    F10: ReleaseStateQueryData, F11: ReleaseStateQueryData,
    F12: ReleaseStateQueryData, F13: ReleaseStateQueryData,
    F14: ReleaseStateQueryData> ReleaseStateQueryData for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
    fn release_state<'w>((i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11,
            i12, i13, i14): Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
        (i0.map(|i0| F0::release_state(i0)),
            i1.map(|i1| F1::release_state(i1)),
            i2.map(|i2| F2::release_state(i2)),
            i3.map(|i3| F3::release_state(i3)),
            i4.map(|i4| F4::release_state(i4)),
            i5.map(|i5| F5::release_state(i5)),
            i6.map(|i6| F6::release_state(i6)),
            i7.map(|i7| F7::release_state(i7)),
            i8.map(|i8| F8::release_state(i8)),
            i9.map(|i9| F9::release_state(i9)),
            i10.map(|i10| F10::release_state(i10)),
            i11.map(|i11| F11::release_state(i11)),
            i12.map(|i12| F12::release_state(i12)),
            i13.map(|i13| F13::release_state(i13)),
            i14.map(|i14| F14::release_state(i14)))
    }
}
#[doc(hidden)]
impl<F0: ArchetypeQueryData, F1: ArchetypeQueryData, F2: ArchetypeQueryData,
    F3: ArchetypeQueryData, F4: ArchetypeQueryData, F5: ArchetypeQueryData,
    F6: ArchetypeQueryData, F7: ArchetypeQueryData, F8: ArchetypeQueryData,
    F9: ArchetypeQueryData, F10: ArchetypeQueryData, F11: ArchetypeQueryData,
    F12: ArchetypeQueryData, F13: ArchetypeQueryData, F14: ArchetypeQueryData>
    ArchetypeQueryData for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
}
#[expect(clippy :: allow_attributes, reason =
"This is a tuple-related macro; as such the lints below may not always apply.")]
#[allow(non_snake_case, reason =
"The names of some variables are provided by the macro's caller, not by us.")]
#[allow(unused_variables, reason =
"Zero-length tuples won't use any of the parameters.")]
#[allow(clippy :: unused_unit, reason =
"Zero-length tuples will generate some function bodies equivalent to `()`; however, this macro is meant for all applicable tuples, and as such it makes no sense to rewrite it just for that case.")]
#[doc(hidden)]
impl<F0: ContiguousQueryData, F1: ContiguousQueryData,
    F2: ContiguousQueryData, F3: ContiguousQueryData, F4: ContiguousQueryData,
    F5: ContiguousQueryData, F6: ContiguousQueryData, F7: ContiguousQueryData,
    F8: ContiguousQueryData, F9: ContiguousQueryData,
    F10: ContiguousQueryData, F11: ContiguousQueryData,
    F12: ContiguousQueryData, F13: ContiguousQueryData,
    F14: ContiguousQueryData> ContiguousQueryData for
    AnyOf<(F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13, F14)> {
    type Contiguous<'w, 's> =
        (Option<F0::Contiguous<'w, 's>>, Option<F1::Contiguous<'w, 's>>,
        Option<F2::Contiguous<'w, 's>>, Option<F3::Contiguous<'w, 's>>,
        Option<F4::Contiguous<'w, 's>>, Option<F5::Contiguous<'w, 's>>,
        Option<F6::Contiguous<'w, 's>>, Option<F7::Contiguous<'w, 's>>,
        Option<F8::Contiguous<'w, 's>>, Option<F9::Contiguous<'w, 's>>,
        Option<F10::Contiguous<'w, 's>>, Option<F11::Contiguous<'w, 's>>,
        Option<F12::Contiguous<'w, 's>>, Option<F13::Contiguous<'w, 's>>,
        Option<F14::Contiguous<'w, 's>>);
    unsafe fn fetch_contiguous<'w,
        's>(state: &'s Self::State, fetch: &mut Self::Fetch<'w>,
        entities: &'w [Entity]) -> Self::Contiguous<'w, 's> {
        let (F0, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F13,
                F14) = fetch;
        let (S0, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13,
                S14) = state;
        (F0.1.then(||
                    unsafe { F0::fetch_contiguous(S0, &mut F0.0, entities) }),
            F1.1.then(||
                    unsafe { F1::fetch_contiguous(S1, &mut F1.0, entities) }),
            F2.1.then(||
                    unsafe { F2::fetch_contiguous(S2, &mut F2.0, entities) }),
            F3.1.then(||
                    unsafe { F3::fetch_contiguous(S3, &mut F3.0, entities) }),
            F4.1.then(||
                    unsafe { F4::fetch_contiguous(S4, &mut F4.0, entities) }),
            F5.1.then(||
                    unsafe { F5::fetch_contiguous(S5, &mut F5.0, entities) }),
            F6.1.then(||
                    unsafe { F6::fetch_contiguous(S6, &mut F6.0, entities) }),
            F7.1.then(||
                    unsafe { F7::fetch_contiguous(S7, &mut F7.0, entities) }),
            F8.1.then(||
                    unsafe { F8::fetch_contiguous(S8, &mut F8.0, entities) }),
            F9.1.then(||
                    unsafe { F9::fetch_contiguous(S9, &mut F9.0, entities) }),
            F10.1.then(||
                    unsafe {
                        F10::fetch_contiguous(S10, &mut F10.0, entities)
                    }),
            F11.1.then(||
                    unsafe {
                        F11::fetch_contiguous(S11, &mut F11.0, entities)
                    }),
            F12.1.then(||
                    unsafe {
                        F12::fetch_contiguous(S12, &mut F12.0, entities)
                    }),
            F13.1.then(||
                    unsafe {
                        F13::fetch_contiguous(S13, &mut F13.0, entities)
                    }),
            F14.1.then(||
                    unsafe {
                        F14::fetch_contiguous(S14, &mut F14.0, entities)
                    }))
    }
}all_tuples!(
3798    #[doc(fake_variadic)]
3799    impl_anytuple_fetch,
3800    0,
3801    15,
3802    F,
3803    S,
3804    i
3805);
3806
3807/// [`WorldQuery`] used to nullify queries by turning `Query<D>` into `Query<NopWorldQuery<D>>`
3808///
3809/// This will rarely be useful to consumers of `bevy_ecs`.
3810pub(crate) struct NopWorldQuery<D: QueryData>(PhantomData<D>);
3811
3812// SAFETY:
3813// `update_component_access` does nothing.
3814// This is sound because `fetch` does not access components.
3815unsafe impl<D: QueryData> WorldQuery for NopWorldQuery<D> {
3816    type Fetch<'w> = ();
3817    type State = D::State;
3818
3819    fn shrink_fetch<'wlong: 'wshort, 'wshort>(_fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
3820    }
3821
3822    #[inline(always)]
3823    unsafe fn init_fetch(
3824        _world: UnsafeWorldCell,
3825        _state: &D::State,
3826        _last_run: Tick,
3827        _this_run: Tick,
3828    ) {
3829    }
3830
3831    const IS_DENSE: bool = D::IS_DENSE;
3832
3833    #[inline(always)]
3834    unsafe fn set_archetype(
3835        _fetch: &mut (),
3836        _state: &D::State,
3837        _archetype: &Archetype,
3838        _tables: &Table,
3839    ) {
3840    }
3841
3842    #[inline(always)]
3843    unsafe fn set_table<'w>(_fetch: &mut (), _state: &D::State, _table: &Table) {}
3844
3845    fn update_component_access(_state: &D::State, _access: &mut FilteredAccess) {}
3846
3847    fn init_state(world: &mut World) -> Self::State {
3848        D::init_state(world)
3849    }
3850
3851    fn get_state(components: &Components) -> Option<Self::State> {
3852        D::get_state(components)
3853    }
3854
3855    fn matches_component_set(
3856        state: &Self::State,
3857        set_contains_id: &impl Fn(ComponentId) -> bool,
3858    ) -> bool {
3859        D::matches_component_set(state, set_contains_id)
3860    }
3861
3862    fn update_archetypes(state: &mut Self::State, world: UnsafeWorldCell) {
3863        D::update_archetypes(state, world);
3864    }
3865}
3866
3867// SAFETY: `Self::ReadOnly` is `Self`
3868unsafe impl<D: QueryData> QueryData for NopWorldQuery<D> {
3869    const IS_READ_ONLY: bool = true;
3870    const IS_ARCHETYPAL: bool = true;
3871    type ReadOnly = Self;
3872    type Item<'w, 's> = ();
3873
3874    fn shrink<'wlong: 'wshort, 'wshort, 's>(
3875        _item: Self::Item<'wlong, 's>,
3876    ) -> Self::Item<'wshort, 's> {
3877    }
3878
3879    #[inline(always)]
3880    unsafe fn fetch<'w, 's>(
3881        _state: &'s Self::State,
3882        _fetch: &mut Self::Fetch<'w>,
3883        _entity: Entity,
3884        _table_row: TableRow,
3885    ) -> Option<Self::Item<'w, 's>> {
3886        Some(())
3887    }
3888
3889    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
3890        iter::empty()
3891    }
3892}
3893
3894// SAFETY: `NopFetch` never accesses any data
3895unsafe impl<D: QueryData> IterQueryData for NopWorldQuery<D> {}
3896
3897// SAFETY: `NopFetch` never accesses any data
3898unsafe impl<D: QueryData> ReadOnlyQueryData for NopWorldQuery<D> {}
3899
3900// SAFETY: `NopFetch` never accesses any data
3901unsafe impl<D: QueryData> SingleEntityQueryData for NopWorldQuery<D> {}
3902
3903impl<D: QueryData> ReleaseStateQueryData for NopWorldQuery<D> {
3904    fn release_state<'w>(_item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {}
3905}
3906
3907impl<D: QueryData> ArchetypeQueryData for NopWorldQuery<D> {}
3908
3909// SAFETY:
3910// `update_component_access` does nothing.
3911// This is sound because `fetch` does not access components.
3912unsafe impl<T: ?Sized> WorldQuery for PhantomData<T> {
3913    type Fetch<'w> = ();
3914
3915    type State = ();
3916
3917    fn shrink_fetch<'wlong: 'wshort, 'wshort>(_fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
3918    }
3919
3920    unsafe fn init_fetch<'w, 's>(
3921        _world: UnsafeWorldCell<'w>,
3922        _state: &'s Self::State,
3923        _last_run: Tick,
3924        _this_run: Tick,
3925    ) -> Self::Fetch<'w> {
3926    }
3927
3928    // `PhantomData` does not match any components, so all components it matches
3929    // are stored in a Table (vacuous truth).
3930    const IS_DENSE: bool = true;
3931
3932    unsafe fn set_archetype<'w, 's>(
3933        _fetch: &mut Self::Fetch<'w>,
3934        _state: &'s Self::State,
3935        _archetype: &'w Archetype,
3936        _table: &'w Table,
3937    ) {
3938    }
3939
3940    unsafe fn set_table<'w, 's>(
3941        _fetch: &mut Self::Fetch<'w>,
3942        _state: &'s Self::State,
3943        _table: &'w Table,
3944    ) {
3945    }
3946
3947    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {}
3948
3949    fn init_state(_world: &mut World) -> Self::State {}
3950
3951    fn get_state(_components: &Components) -> Option<Self::State> {
3952        Some(())
3953    }
3954
3955    fn matches_component_set(
3956        _state: &Self::State,
3957        _set_contains_id: &impl Fn(ComponentId) -> bool,
3958    ) -> bool {
3959        true
3960    }
3961}
3962
3963// SAFETY: `Self::ReadOnly` is `Self`
3964unsafe impl<T: ?Sized> QueryData for PhantomData<T> {
3965    const IS_READ_ONLY: bool = true;
3966    const IS_ARCHETYPAL: bool = true;
3967    type ReadOnly = Self;
3968    type Item<'w, 's> = ();
3969
3970    fn shrink<'wlong: 'wshort, 'wshort, 's>(
3971        _item: Self::Item<'wlong, 's>,
3972    ) -> Self::Item<'wshort, 's> {
3973    }
3974
3975    unsafe fn fetch<'w, 's>(
3976        _state: &'s Self::State,
3977        _fetch: &mut Self::Fetch<'w>,
3978        _entity: Entity,
3979        _table_row: TableRow,
3980    ) -> Option<Self::Item<'w, 's>> {
3981        Some(())
3982    }
3983
3984    fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
3985        iter::empty()
3986    }
3987}
3988
3989// SAFETY: `PhantomData` never accesses any data
3990unsafe impl<T: ?Sized> IterQueryData for PhantomData<T> {}
3991
3992// SAFETY: `PhantomData` never accesses any data
3993unsafe impl<T: ?Sized> ReadOnlyQueryData for PhantomData<T> {}
3994
3995// SAFETY: `PhantomData` never accesses any data
3996unsafe impl<T: ?Sized> SingleEntityQueryData for PhantomData<T> {}
3997
3998impl<T: ?Sized> ReleaseStateQueryData for PhantomData<T> {
3999    fn release_state<'w>(_item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {}
4000}
4001
4002impl<T: ?Sized> ArchetypeQueryData for PhantomData<T> {}
4003
4004/// A compile-time checked union of two different types that differs based on the
4005/// [`StorageType`] of a given component.
4006pub(super) union StorageSwitch<C: Component, T: Copy, S: Copy> {
4007    /// The table variant. Requires the component to be a table component.
4008    table: T,
4009    /// The sparse set variant. Requires the component to be a sparse set component.
4010    sparse_set: S,
4011    _marker: PhantomData<C>,
4012}
4013
4014impl<C: Component, T: Copy, S: Copy> StorageSwitch<C, T, S> {
4015    /// Creates a new [`StorageSwitch`] using the given closures to initialize
4016    /// the variant corresponding to the component's [`StorageType`].
4017    pub fn new(table: impl FnOnce() -> T, sparse_set: impl FnOnce() -> S) -> Self {
4018        match C::STORAGE_TYPE {
4019            StorageType::Table => Self { table: table() },
4020            StorageType::SparseSet => Self {
4021                sparse_set: sparse_set(),
4022            },
4023        }
4024    }
4025
4026    /// Creates a new [`StorageSwitch`] using a table variant.
4027    ///
4028    /// # Panics
4029    ///
4030    /// This will panic on debug builds if `C` is not a table component.
4031    ///
4032    /// # Safety
4033    ///
4034    /// `C` must be a table component.
4035    #[inline]
4036    pub unsafe fn set_table(&mut self, table: T) {
4037        match C::STORAGE_TYPE {
4038            StorageType::Table => self.table = table,
4039            _ => {
4040                #[cfg(debug_assertions)]
4041                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
4042                #[cfg(not(debug_assertions))]
4043                core::hint::unreachable_unchecked()
4044            }
4045        }
4046    }
4047
4048    /// Fetches the internal value from the variant that corresponds to the
4049    /// component's [`StorageType`].
4050    pub fn extract<R>(&self, table: impl FnOnce(T) -> R, sparse_set: impl FnOnce(S) -> R) -> R {
4051        match C::STORAGE_TYPE {
4052            StorageType::Table => table(
4053                // SAFETY: C::STORAGE_TYPE == StorageType::Table
4054                unsafe { self.table },
4055            ),
4056            StorageType::SparseSet => sparse_set(
4057                // SAFETY: C::STORAGE_TYPE == StorageType::SparseSet
4058                unsafe { self.sparse_set },
4059            ),
4060        }
4061    }
4062}
4063
4064impl<C: Component, T: Copy, S: Copy> Clone for StorageSwitch<C, T, S> {
4065    fn clone(&self) -> Self {
4066        *self
4067    }
4068}
4069
4070impl<C: Component, T: Copy, S: Copy> Copy for StorageSwitch<C, T, S> {}
4071
4072#[cfg(test)]
4073mod tests {
4074    use super::*;
4075    use crate::change_detection::DetectChanges;
4076    use crate::query::Without;
4077    use crate::system::{assert_is_system, Query};
4078    use bevy_ecs::prelude::Schedule;
4079    use bevy_ecs_macros::QueryData;
4080
4081    #[derive(Component)]
4082    pub struct A;
4083
4084    #[derive(Component)]
4085    pub struct B;
4086
4087    // Tests that each variant of struct can be used as a `WorldQuery`.
4088    #[test]
4089    fn world_query_struct_variants() {
4090        #[derive(QueryData)]
4091        pub struct NamedQuery {
4092            id: Entity,
4093            a: &'static A,
4094        }
4095
4096        #[derive(QueryData)]
4097        pub struct TupleQuery(&'static A, &'static B);
4098
4099        #[derive(QueryData)]
4100        pub struct UnitQuery;
4101
4102        fn my_system(_: Query<(NamedQuery, TupleQuery, UnitQuery)>) {}
4103
4104        assert_is_system(my_system);
4105    }
4106
4107    // Compile test for https://github.com/bevyengine/bevy/pull/8030.
4108    #[test]
4109    fn world_query_phantom_data() {
4110        #[derive(QueryData)]
4111        pub struct IgnoredQuery<Marker> {
4112            id: Entity,
4113            _marker: PhantomData<Marker>,
4114        }
4115
4116        fn ignored_system(_: Query<IgnoredQuery<()>>) {}
4117
4118        assert_is_system(ignored_system);
4119    }
4120
4121    #[test]
4122    fn derive_release_state() {
4123        struct NonReleaseQueryData;
4124
4125        // SAFETY:
4126        // `update_component_access` do nothing.
4127        // This is sound because `fetch` does not access components.
4128        unsafe impl WorldQuery for NonReleaseQueryData {
4129            type Fetch<'w> = ();
4130            type State = ();
4131
4132            fn shrink_fetch<'wlong: 'wshort, 'wshort>(
4133                _: Self::Fetch<'wlong>,
4134            ) -> Self::Fetch<'wshort> {
4135            }
4136
4137            unsafe fn init_fetch<'w, 's>(
4138                _world: UnsafeWorldCell<'w>,
4139                _state: &'s Self::State,
4140                _last_run: Tick,
4141                _this_run: Tick,
4142            ) -> Self::Fetch<'w> {
4143            }
4144
4145            const IS_DENSE: bool = true;
4146
4147            #[inline]
4148            unsafe fn set_archetype<'w, 's>(
4149                _fetch: &mut Self::Fetch<'w>,
4150                _state: &'s Self::State,
4151                _archetype: &'w Archetype,
4152                _table: &Table,
4153            ) {
4154            }
4155
4156            #[inline]
4157            unsafe fn set_table<'w, 's>(
4158                _fetch: &mut Self::Fetch<'w>,
4159                _state: &'s Self::State,
4160                _table: &'w Table,
4161            ) {
4162            }
4163
4164            fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess) {}
4165
4166            fn init_state(_world: &mut World) {}
4167
4168            fn get_state(_components: &Components) -> Option<()> {
4169                Some(())
4170            }
4171
4172            fn matches_component_set(
4173                _state: &Self::State,
4174                _set_contains_id: &impl Fn(ComponentId) -> bool,
4175            ) -> bool {
4176                true
4177            }
4178        }
4179
4180        // SAFETY: `Self` is the same as `Self::ReadOnly`
4181        unsafe impl QueryData for NonReleaseQueryData {
4182            type ReadOnly = Self;
4183            const IS_READ_ONLY: bool = true;
4184            const IS_ARCHETYPAL: bool = true;
4185
4186            type Item<'w, 's> = ();
4187
4188            fn shrink<'wlong: 'wshort, 'wshort, 's>(
4189                _item: Self::Item<'wlong, 's>,
4190            ) -> Self::Item<'wshort, 's> {
4191            }
4192
4193            #[inline(always)]
4194            unsafe fn fetch<'w, 's>(
4195                _state: &'s Self::State,
4196                _fetch: &mut Self::Fetch<'w>,
4197                _entity: Entity,
4198                _table_row: TableRow,
4199            ) -> Option<Self::Item<'w, 's>> {
4200                Some(())
4201            }
4202
4203            fn iter_access(_state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
4204                iter::empty()
4205            }
4206        }
4207
4208        // SAFETY: access is read only
4209        unsafe impl ReadOnlyQueryData for NonReleaseQueryData {}
4210
4211        // SAFETY: access is read only
4212        unsafe impl IterQueryData for NonReleaseQueryData {}
4213
4214        impl ArchetypeQueryData for NonReleaseQueryData {}
4215
4216        #[derive(QueryData)]
4217        pub struct DerivedNonReleaseRead {
4218            non_release: NonReleaseQueryData,
4219            a: &'static A,
4220        }
4221
4222        #[derive(QueryData)]
4223        #[query_data(mutable)]
4224        pub struct DerivedNonReleaseMutable {
4225            non_release: NonReleaseQueryData,
4226            a: &'static mut A,
4227        }
4228
4229        #[derive(QueryData)]
4230        pub struct DerivedReleaseRead {
4231            a: &'static A,
4232        }
4233
4234        #[derive(QueryData)]
4235        #[query_data(mutable)]
4236        pub struct DerivedReleaseMutable {
4237            a: &'static mut A,
4238        }
4239
4240        fn assert_is_release_state<Q: ReleaseStateQueryData>() {}
4241
4242        assert_is_release_state::<DerivedReleaseRead>();
4243        assert_is_release_state::<DerivedReleaseMutable>();
4244    }
4245
4246    // Ensures that each field of a `WorldQuery` struct's read-only variant
4247    // has the same visibility as its corresponding mutable field.
4248    #[test]
4249    fn read_only_field_visibility() {
4250        mod private {
4251            use super::*;
4252
4253            #[derive(QueryData)]
4254            #[query_data(mutable)]
4255            pub struct D {
4256                pub a: &'static mut A,
4257            }
4258        }
4259
4260        let _ = private::DReadOnly { a: &A };
4261
4262        fn my_system(query: Query<private::D>) {
4263            for q in &query {
4264                let _ = &q.a;
4265            }
4266        }
4267
4268        assert_is_system(my_system);
4269    }
4270
4271    // Ensures that metadata types generated by the WorldQuery macro
4272    // do not conflict with user-defined types.
4273    // Regression test for https://github.com/bevyengine/bevy/issues/8010.
4274    #[test]
4275    fn world_query_metadata_collision() {
4276        // The metadata types generated would be named `ClientState` and `ClientFetch`,
4277        // but they should rename themselves to avoid conflicts.
4278        #[derive(QueryData)]
4279        pub struct Client<S: ClientState> {
4280            pub state: &'static S,
4281            pub fetch: &'static ClientFetch,
4282        }
4283
4284        pub trait ClientState: Component {}
4285
4286        #[derive(Component)]
4287        pub struct ClientFetch;
4288
4289        #[derive(Component)]
4290        pub struct C;
4291
4292        impl ClientState for C {}
4293
4294        fn client_system(_: Query<Client<C>>) {}
4295
4296        assert_is_system(client_system);
4297    }
4298
4299    // Test that EntityRef::get_ref::<T>() returns a Ref<T> value with the correct
4300    // ticks when the EntityRef was retrieved from a Query.
4301    // See: https://github.com/bevyengine/bevy/issues/13735
4302    #[test]
4303    fn test_entity_ref_query_with_ticks() {
4304        #[derive(Component)]
4305        pub struct C;
4306
4307        fn system(query: Query<EntityRef>) {
4308            for entity_ref in &query {
4309                if let Some(c) = entity_ref.get_ref::<C>()
4310                    && !c.is_added()
4311                {
4312                    panic!("Expected C to be added");
4313                }
4314            }
4315        }
4316
4317        let mut world = World::new();
4318        let mut schedule = Schedule::default();
4319        schedule.add_systems(system);
4320        world.spawn(C);
4321
4322        // reset the change ticks
4323        world.clear_trackers();
4324
4325        // we want EntityRef to use the change ticks of the system
4326        schedule.run(&mut world);
4327    }
4328
4329    #[test]
4330    fn test_contiguous_query_data() {
4331        #[derive(Component, PartialEq, Eq, Debug)]
4332        pub struct C(i32);
4333
4334        #[derive(Component, PartialEq, Eq, Debug)]
4335        pub struct D(bool);
4336
4337        let mut world = World::new();
4338        world.spawn((C(0), D(true)));
4339        world.spawn((C(1), D(false)));
4340        world.spawn(C(2));
4341
4342        let mut query = world.query::<(&C, &D)>();
4343        let mut iter = query.contiguous_iter(&world).unwrap();
4344        let c = iter.next().unwrap();
4345        assert_eq!(c.0, [C(0), C(1)].as_slice());
4346        assert_eq!(c.1, [D(true), D(false)].as_slice());
4347        assert!(iter.next().is_none());
4348
4349        let mut query = world.query::<&C>();
4350        let mut iter = query.contiguous_iter(&world).unwrap();
4351        let mut present = [false; 3];
4352        let mut len = 0;
4353        for _ in 0..2 {
4354            let c = iter.next().unwrap();
4355            for c in c {
4356                present[c.0 as usize] = true;
4357                len += 1;
4358            }
4359        }
4360        assert!(iter.next().is_none());
4361        assert_eq!(len, 3);
4362        assert_eq!(present, [true; 3]);
4363
4364        let mut query = world.query::<&mut C>();
4365        let mut iter = query.contiguous_iter_mut(&mut world).unwrap();
4366        for _ in 0..2 {
4367            let c = iter.next().unwrap();
4368            for c in c {
4369                c.0 *= 2;
4370            }
4371        }
4372        assert!(iter.next().is_none());
4373        let mut iter = query.contiguous_iter(&world).unwrap();
4374        let mut present = [false; 6];
4375        let mut len = 0;
4376        for _ in 0..2 {
4377            let c = iter.next().unwrap();
4378            for c in c {
4379                present[c.0 as usize] = true;
4380                len += 1;
4381            }
4382        }
4383        assert_eq!(present, [true, false, true, false, true, false]);
4384        assert_eq!(len, 3);
4385
4386        let mut query = world.query_filtered::<&C, Without<D>>();
4387        let mut iter = query.contiguous_iter(&world).unwrap();
4388        assert_eq!(iter.next().unwrap(), &[C(4)]);
4389        assert!(iter.next().is_none());
4390    }
4391
4392    #[test]
4393    fn sparse_set_contiguous_query() {
4394        #[derive(Component, Debug, PartialEq, Eq)]
4395        #[component(storage = "SparseSet")]
4396        pub struct S(i32);
4397
4398        let mut world = World::new();
4399        world.spawn(S(0));
4400
4401        let mut query = world.query::<&mut S>();
4402        let iter = query.contiguous_iter_mut(&mut world);
4403        assert!(iter.is_err());
4404    }
4405
4406    #[test]
4407    fn any_of_contiguous_test() {
4408        #[derive(Component, Debug, Clone, Copy)]
4409        pub struct C(i32);
4410
4411        #[derive(Component, Debug, Clone, Copy)]
4412        pub struct D(i32);
4413
4414        let mut world = World::new();
4415        world.spawn((C(0), D(1)));
4416        world.spawn(C(2));
4417        world.spawn(D(3));
4418        world.spawn(());
4419
4420        let mut query = world.query::<AnyOf<(&C, &D)>>();
4421        let iter = query.contiguous_iter(&world).unwrap();
4422        let mut present = [false; 4];
4423
4424        for (c, d) in iter {
4425            assert!(c.is_some() || d.is_some());
4426            let c = c.unwrap_or_default();
4427            let d = d.unwrap_or_default();
4428            for i in 0..c.len().max(d.len()) {
4429                let c = c.get(i).cloned();
4430                let d = d.get(i).cloned();
4431                if let Some(C(c)) = c {
4432                    assert!(!present[c as usize]);
4433                    present[c as usize] = true;
4434                }
4435                if let Some(D(d)) = d {
4436                    assert!(!present[d as usize]);
4437                    present[d as usize] = true;
4438                }
4439            }
4440        }
4441
4442        assert_eq!(present, [true; 4]);
4443    }
4444
4445    #[test]
4446    fn option_contiguous_test() {
4447        #[derive(Component, Clone, Copy)]
4448        struct C(i32);
4449
4450        #[derive(Component, Clone, Copy)]
4451        struct D(i32);
4452
4453        let mut world = World::new();
4454        world.spawn((C(0), D(1)));
4455        world.spawn(D(2));
4456        world.spawn(C(3));
4457
4458        let mut query = world.query::<(Option<&C>, &D)>();
4459        let iter = query.contiguous_iter(&world).unwrap();
4460        let mut present = [false; 3];
4461
4462        for (c, d) in iter {
4463            let c = c.unwrap_or_default();
4464            for i in 0..d.len() {
4465                let c = c.get(i).cloned();
4466                let D(d) = d[i];
4467                if let Some(C(c)) = c {
4468                    assert!(!present[c as usize]);
4469                    present[c as usize] = true;
4470                }
4471                assert!(!present[d as usize]);
4472                present[d as usize] = true;
4473            }
4474        }
4475
4476        assert_eq!(present, [true; 3]);
4477    }
4478}