bevy_ecs/query/world_query.rs
1use crate::{
2 archetype::Archetype,
3 component::{ComponentId, Components, Tick},
4 entity::Entity,
5 query::FilteredAccess,
6 storage::{Table, TableRow},
7 world::{unsafe_world_cell::UnsafeWorldCell, World},
8};
9use bevy_utils::all_tuples;
10
11/// Types that can be used as parameters in a [`Query`].
12/// Types that implement this should also implement either [`QueryData`] or [`QueryFilter`]
13///
14/// # Safety
15///
16/// Implementor must ensure that
17/// [`update_component_access`], [`matches_component_set`], and [`fetch`]
18/// obey the following:
19///
20/// - For each component mutably accessed by [`fetch`], [`update_component_access`] should add write access unless read or write access has already been added, in which case it should panic.
21/// - For each component readonly accessed by [`fetch`], [`update_component_access`] should add read access unless write access has already been added, in which case it should panic.
22/// - If `fetch` mutably accesses the same component twice, [`update_component_access`] should panic.
23/// - [`update_component_access`] may not add a `Without` filter for a component unless [`matches_component_set`] always returns `false` when the component set contains that component.
24/// - [`update_component_access`] may not add a `With` filter for a component unless [`matches_component_set`] always returns `false` when the component set doesn't contain that component.
25/// - In cases where the query represents a disjunction (such as an `Or` filter) where each element is a valid [`WorldQuery`], the following rules must be obeyed:
26/// - [`matches_component_set`] must be a disjunction of the element's implementations
27/// - [`update_component_access`] must replace the filters with a disjunction of filters
28/// - Each filter in that disjunction must be a conjunction of the corresponding element's filter with the previous `access`
29///
30/// When implementing [`update_component_access`], note that `add_read` and `add_write` both also add a `With` filter, whereas `extend_access` does not change the filters.
31///
32/// [`fetch`]: Self::fetch
33/// [`matches_component_set`]: Self::matches_component_set
34/// [`Query`]: crate::system::Query
35/// [`update_component_access`]: Self::update_component_access
36/// [`QueryData`]: crate::query::QueryData
37/// [`QueryFilter`]: crate::query::QueryFilter
38pub unsafe trait WorldQuery {
39 /// The item returned by this [`WorldQuery`]
40 /// For `QueryData` this will be the item returned by the query.
41 /// For `QueryFilter` this will be either `()`, or a `bool` indicating whether the entity should be included
42 /// or a tuple of such things.
43 type Item<'a>;
44
45 /// Per archetype/table state used by this [`WorldQuery`] to fetch [`Self::Item`](WorldQuery::Item)
46 type Fetch<'a>: Clone;
47
48 /// State used to construct a [`Self::Fetch`](WorldQuery::Fetch). This will be cached inside [`QueryState`](crate::query::QueryState),
49 /// so it is best to move as much data / computation here as possible to reduce the cost of
50 /// constructing [`Self::Fetch`](WorldQuery::Fetch).
51 type State: Send + Sync + Sized;
52
53 /// This function manually implements subtyping for the query items.
54 fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort>;
55
56 /// Creates a new instance of this fetch.
57 ///
58 /// # Safety
59 ///
60 /// - `state` must have been initialized (via [`WorldQuery::init_state`]) using the same `world` passed
61 /// in to this function.
62 unsafe fn init_fetch<'w>(
63 world: UnsafeWorldCell<'w>,
64 state: &Self::State,
65 last_run: Tick,
66 this_run: Tick,
67 ) -> Self::Fetch<'w>;
68
69 /// Returns true if (and only if) every table of every archetype matched by this fetch contains
70 /// all of the matched components. This is used to select a more efficient "table iterator"
71 /// for "dense" queries. If this returns true, [`WorldQuery::set_table`] must be used before
72 /// [`WorldQuery::fetch`] can be called for iterators. If this returns false,
73 /// [`WorldQuery::set_archetype`] must be used before [`WorldQuery::fetch`] can be called for
74 /// iterators.
75 const IS_DENSE: bool;
76
77 /// Adjusts internal state to account for the next [`Archetype`]. This will always be called on
78 /// archetypes that match this [`WorldQuery`].
79 ///
80 /// # Safety
81 ///
82 /// - `archetype` and `tables` must be from the same [`World`] that [`WorldQuery::init_state`] was called on.
83 /// - `table` must correspond to `archetype`.
84 /// - `state` must be the [`State`](Self::State) that `fetch` was initialized with.
85 unsafe fn set_archetype<'w>(
86 fetch: &mut Self::Fetch<'w>,
87 state: &Self::State,
88 archetype: &'w Archetype,
89 table: &'w Table,
90 );
91
92 /// Adjusts internal state to account for the next [`Table`]. This will always be called on tables
93 /// that match this [`WorldQuery`].
94 ///
95 /// # Safety
96 ///
97 /// - `table` must be from the same [`World`] that [`WorldQuery::init_state`] was called on.
98 /// - `state` must be the [`State`](Self::State) that `fetch` was initialized with.
99 unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table);
100
101 /// Sets available accesses for implementors with dynamic access such as [`FilteredEntityRef`](crate::world::FilteredEntityRef)
102 /// or [`FilteredEntityMut`](crate::world::FilteredEntityMut).
103 ///
104 /// Called when constructing a [`QueryLens`](crate::system::QueryLens) or calling [`QueryState::from_builder`](super::QueryState::from_builder)
105 fn set_access(_state: &mut Self::State, _access: &FilteredAccess<ComponentId>) {}
106
107 /// Fetch [`Self::Item`](`WorldQuery::Item`) for either the given `entity` in the current [`Table`],
108 /// or for the given `entity` in the current [`Archetype`]. This must always be called after
109 /// [`WorldQuery::set_table`] with a `table_row` in the range of the current [`Table`] or after
110 /// [`WorldQuery::set_archetype`] with a `entity` in the current archetype.
111 ///
112 /// # Safety
113 ///
114 /// Must always be called _after_ [`WorldQuery::set_table`] or [`WorldQuery::set_archetype`]. `entity` and
115 /// `table_row` must be in the range of the current table and archetype.
116 unsafe fn fetch<'w>(
117 fetch: &mut Self::Fetch<'w>,
118 entity: Entity,
119 table_row: TableRow,
120 ) -> Self::Item<'w>;
121
122 /// Adds any component accesses used by this [`WorldQuery`] to `access`.
123 ///
124 /// Used to check which queries are disjoint and can run in parallel
125 // This does not have a default body of `{}` because 99% of cases need to add accesses
126 // and forgetting to do so would be unsound.
127 fn update_component_access(state: &Self::State, access: &mut FilteredAccess<ComponentId>);
128
129 /// Creates and initializes a [`State`](WorldQuery::State) for this [`WorldQuery`] type.
130 fn init_state(world: &mut World) -> Self::State;
131
132 /// Attempts to initialize a [`State`](WorldQuery::State) for this [`WorldQuery`] type using read-only
133 /// access to [`Components`].
134 fn get_state(components: &Components) -> Option<Self::State>;
135
136 /// Returns `true` if this query matches a set of components. Otherwise, returns `false`.
137 ///
138 /// Used to check which [`Archetype`]s can be skipped by the query
139 /// (if none of the [`Component`](crate::component::Component)s match)
140 fn matches_component_set(
141 state: &Self::State,
142 set_contains_id: &impl Fn(ComponentId) -> bool,
143 ) -> bool;
144}
145
146macro_rules! impl_tuple_world_query {
147 ($(($name: ident, $state: ident)),*) => {
148
149 #[allow(non_snake_case)]
150 #[allow(clippy::unused_unit)]
151 /// SAFETY:
152 /// `fetch` accesses are the conjunction of the subqueries' accesses
153 /// This is sound because `update_component_access` adds accesses according to the implementations of all the subqueries.
154 /// `update_component_access` adds all `With` and `Without` filters from the subqueries.
155 /// This is sound because `matches_component_set` always returns `false` if any the subqueries' implementations return `false`.
156 unsafe impl<$($name: WorldQuery),*> WorldQuery for ($($name,)*) {
157 type Fetch<'w> = ($($name::Fetch<'w>,)*);
158 type Item<'w> = ($($name::Item<'w>,)*);
159 type State = ($($name::State,)*);
160
161 fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
162 let ($($name,)*) = item;
163 ($(
164 $name::shrink($name),
165 )*)
166 }
167
168 #[inline]
169 #[allow(clippy::unused_unit)]
170 unsafe fn init_fetch<'w>(_world: UnsafeWorldCell<'w>, state: &Self::State, _last_run: Tick, _this_run: Tick) -> Self::Fetch<'w> {
171 let ($($name,)*) = state;
172 // SAFETY: The invariants are uphold by the caller.
173 ($(unsafe { $name::init_fetch(_world, $name, _last_run, _this_run) },)*)
174 }
175
176 const IS_DENSE: bool = true $(&& $name::IS_DENSE)*;
177
178 #[inline]
179 unsafe fn set_archetype<'w>(
180 _fetch: &mut Self::Fetch<'w>,
181 _state: &Self::State,
182 _archetype: &'w Archetype,
183 _table: &'w Table
184 ) {
185 let ($($name,)*) = _fetch;
186 let ($($state,)*) = _state;
187 // SAFETY: The invariants are uphold by the caller.
188 $(unsafe { $name::set_archetype($name, $state, _archetype, _table); })*
189 }
190
191 #[inline]
192 unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
193 let ($($name,)*) = _fetch;
194 let ($($state,)*) = _state;
195 // SAFETY: The invariants are uphold by the caller.
196 $(unsafe { $name::set_table($name, $state, _table); })*
197 }
198
199 #[inline(always)]
200 #[allow(clippy::unused_unit)]
201 unsafe fn fetch<'w>(
202 _fetch: &mut Self::Fetch<'w>,
203 _entity: Entity,
204 _table_row: TableRow
205 ) -> Self::Item<'w> {
206 let ($($name,)*) = _fetch;
207 // SAFETY: The invariants are uphold by the caller.
208 ($(unsafe { $name::fetch($name, _entity, _table_row) },)*)
209 }
210
211 fn update_component_access(state: &Self::State, _access: &mut FilteredAccess<ComponentId>) {
212 let ($($name,)*) = state;
213 $($name::update_component_access($name, _access);)*
214 }
215 #[allow(unused_variables)]
216 fn init_state(world: &mut World) -> Self::State {
217 ($($name::init_state(world),)*)
218 }
219 #[allow(unused_variables)]
220 fn get_state(components: &Components) -> Option<Self::State> {
221 Some(($($name::get_state(components)?,)*))
222 }
223
224 fn matches_component_set(state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
225 let ($($name,)*) = state;
226 true $(&& $name::matches_component_set($name, _set_contains_id))*
227 }
228 }
229 };
230}
231
232all_tuples!(impl_tuple_world_query, 0, 15, F, S);