bevy_ecs/entity_disabling.rs
1//! Disabled entities do not show up in queries unless the query explicitly mentions them.
2//!
3//! Entities which are disabled in this way are not removed from the [`World`],
4//! and their relationships remain intact.
5//! In many cases, you may want to disable entire trees of entities at once,
6//! using [`EntityCommands::insert_recursive`](crate::prelude::EntityCommands::insert_recursive).
7//!
8//! While Bevy ships with a built-in [`Disabled`] component, you can also create your own
9//! disabling components, which will operate in the same way but can have distinct semantics.
10//!
11//! ```
12//! use bevy_ecs::prelude::*;
13//!
14//! // Our custom disabling component!
15//! #[derive(Component, Clone)]
16//! struct Prefab;
17//!
18//! #[derive(Component)]
19//! struct A;
20//!
21//! let mut world = World::new();
22//! world.register_disabling_component::<Prefab>();
23//! world.spawn((A, Prefab));
24//! world.spawn((A,));
25//! world.spawn((A,));
26//!
27//! let mut normal_query = world.query::<&A>();
28//! assert_eq!(2, normal_query.iter(&world).count());
29//!
30//! let mut prefab_query = world.query_filtered::<&A, With<Prefab>>();
31//! assert_eq!(1, prefab_query.iter(&world).count());
32//!
33//! let mut maybe_prefab_query = world.query::<(&A, Has<Prefab>)>();
34//! assert_eq!(3, maybe_prefab_query.iter(&world).count());
35//! ```
36//!
37//! ## Default query filters
38//!
39//! In Bevy, entity disabling is implemented through the construction of a global "default query filter" resource.
40//! Queries which do not explicitly mention the disabled component will not include entities with that component.
41//! If an entity has multiple disabling components, it will only be included in queries that mention all of them.
42//!
43//! For example, `Query<&Position>` will not include entities with the [`Disabled`] component,
44//! even if they have a `Position` component,
45//! but `Query<&Position, With<Disabled>>` or `Query<(&Position, Has<Disabled>)>` will see them.
46//!
47//! The [`Allow`](crate::query::Allow) query filter is designed to be used with default query filters,
48//! and ensures that the query will include entities both with and without the specified disabling component.
49//!
50//! Entities with disabling components are still present in the [`World`] and can be accessed directly,
51//! using methods on [`World`] or [`Commands`](crate::prelude::Commands).
52//!
53//! As default query filters are implemented through a resource,
54//! it's possible to temporarily ignore any default filters by using [`World::resource_scope`](crate::prelude::World).
55//!
56//! ```
57//! use bevy_ecs::prelude::*;
58//! use bevy_ecs::entity_disabling::{DefaultQueryFilters, Disabled};
59//!
60//! let mut world = World::default();
61//!
62//! #[derive(Component)]
63//! struct CustomDisabled;
64//!
65//! world.register_disabling_component::<CustomDisabled>();
66//!
67//! world.spawn(Disabled);
68//! world.spawn(CustomDisabled);
69//!
70//! // resource_scope removes DefaultQueryFilters temporarily before re-inserting into the world.
71//! world.resource_scope(|world: &mut World, _: Mut<DefaultQueryFilters>| {
72//! // within this scope, we can query like no components are disabled.
73//! assert_eq!(world.query::<&Disabled>().query(&world).count(), 1);
74//! assert_eq!(world.query::<&CustomDisabled>().query(&world).count(), 1);
75//! assert_eq!(world.query::<()>().query(&world).count(), world.entities().count_spawned() as usize);
76//! })
77//! ```
78//!
79//! ### Warnings
80//!
81//! Currently, only queries for which the cache is built after enabling a default query filter will have entities
82//! with those components filtered. As a result, they should generally only be modified before the
83//! app starts.
84//!
85//! Because filters are applied to all queries they can have performance implication for
86//! the entire [`World`], especially when they cause queries to mix sparse and table components.
87//! See [`Query` performance] for more info.
88//!
89//! Custom disabling components can cause significant interoperability issues within the ecosystem,
90//! as users must be aware of each disabling component in use.
91//! Libraries should think carefully about whether they need to use a new disabling component,
92//! and clearly communicate their presence to their users to avoid the new for library compatibility flags.
93//!
94//! [`With`]: crate::prelude::With
95//! [`Has`]: crate::prelude::Has
96//! [`World`]: crate::prelude::World
97//! [`Query` performance]: crate::prelude::Query#performance
98
99use crate::{
100 component::{ComponentId, Components, StorageType},
101 query::FilteredAccess,
102 world::{FromWorld, World},
103};
104use bevy_ecs_macros::{Component, Resource};
105use smallvec::SmallVec;
106
107#[cfg(feature = "bevy_reflect")]
108use {
109 crate::reflect::ReflectComponent, bevy_reflect::std_traits::ReflectDefault,
110 bevy_reflect::Reflect,
111};
112
113/// A marker component for disabled entities.
114///
115/// Semantically, this component is used to mark entities that are temporarily disabled (typically for gameplay reasons),
116/// but will likely be re-enabled at some point.
117///
118/// Like all disabling components, this only disables the entity itself,
119/// not its children or other entities that reference it.
120/// To disable an entire tree of entities, use [`EntityCommands::insert_recursive`](crate::prelude::EntityCommands::insert_recursive).
121///
122/// Every [`World`] has a default query filter that excludes entities with this component,
123/// registered in the [`DefaultQueryFilters`] resource.
124/// See [the module docs] for more info.
125///
126/// [the module docs]: crate::entity_disabling
127#[derive(Component, Clone, Debug, Default)]
128#[cfg_attr(
129 feature = "bevy_reflect",
130 derive(Reflect),
131 reflect(Component),
132 reflect(Debug, Clone, Default)
133)]
134// This component is registered as a disabling component during World::bootstrap
135pub struct Disabled;
136
137/// Default query filters work by excluding entities with certain components from most queries.
138///
139/// If a query does not explicitly mention a given disabling component, it will not include entities with that component.
140/// To be more precise, this checks if the query's [`FilteredAccess`] contains the component,
141/// and if it does not, adds a [`Without`](crate::prelude::Without) filter for that component to the query.
142///
143/// [`Allow`](crate::query::Allow) and [`Has`](crate::prelude::Has) can be used to include entities
144/// with and without the disabling component.
145/// [`Allow`](crate::query::Allow) is a [`QueryFilter`](crate::query::QueryFilter) and will simply change
146/// the list of shown entities, while [`Has`](crate::prelude::Has) is a [`QueryData`](crate::query::QueryData)
147/// and will allow you to see if each entity has the disabling component or not.
148///
149/// This resource is initialized in the [`World`] whenever a new world is created,
150/// with the [`Disabled`] component as a disabling component.
151///
152/// Note that you can remove default query filters by overwriting the [`DefaultQueryFilters`] resource.
153/// This can be useful as a last resort escape hatch, but is liable to break compatibility with other libraries.
154///
155/// See the [module docs](crate::entity_disabling) for more info.
156///
157///
158/// # Warning
159///
160/// Default query filters are a global setting that affects all queries in the [`World`],
161/// and incur a small performance cost for each query.
162///
163/// They can cause significant interoperability issues within the ecosystem,
164/// as users must be aware of each disabling component in use.
165///
166/// Think carefully about whether you need to use a new disabling component,
167/// and clearly communicate their presence in any libraries you publish.
168#[derive(Resource, Debug)]
169#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
170pub struct DefaultQueryFilters {
171 // We only expect a few components per application to act as disabling components, so we use a SmallVec here
172 // to avoid heap allocation in most cases.
173 disabling: SmallVec<[ComponentId; 4]>,
174}
175
176impl FromWorld for DefaultQueryFilters {
177 fn from_world(world: &mut World) -> Self {
178 let mut filters = DefaultQueryFilters::empty();
179 let disabled_component_id = world.register_component::<Disabled>();
180 filters.register_disabling_component(disabled_component_id);
181 filters
182 }
183}
184
185impl DefaultQueryFilters {
186 /// Creates a new, completely empty [`DefaultQueryFilters`].
187 ///
188 /// This is provided as an escape hatch; in most cases you should initialize this using [`FromWorld`],
189 /// which is automatically called when creating a new [`World`].
190 #[must_use]
191 pub fn empty() -> Self {
192 DefaultQueryFilters {
193 disabling: SmallVec::new(),
194 }
195 }
196
197 /// Adds this [`ComponentId`] to the set of [`DefaultQueryFilters`],
198 /// causing entities with this component to be excluded from queries.
199 ///
200 /// This method is idempotent, and will not add the same component multiple times.
201 ///
202 /// # Warning
203 ///
204 /// This method should only be called before the app starts, as it will not affect queries
205 /// initialized before it is called.
206 ///
207 /// As discussed in the [module docs](crate::entity_disabling), this can have performance implications,
208 /// as well as create interoperability issues, and should be used with caution.
209 pub fn register_disabling_component(&mut self, component_id: ComponentId) {
210 if !self.disabling.contains(&component_id) {
211 self.disabling.push(component_id);
212 }
213 }
214
215 /// Get an iterator over all of the components which disable entities when present.
216 pub fn disabling_ids(&self) -> impl Iterator<Item = ComponentId> {
217 self.disabling.iter().copied()
218 }
219
220 /// Modifies the provided [`FilteredAccess`] to include the filters from this [`DefaultQueryFilters`].
221 pub(super) fn modify_access(&self, component_access: &mut FilteredAccess) {
222 for component_id in self.disabling_ids() {
223 if !component_access.contains(component_id) {
224 component_access.and_without(component_id);
225 }
226 }
227 }
228
229 pub(super) fn is_dense(&self, components: &Components) -> bool {
230 self.disabling_ids().all(|component_id| {
231 components
232 .get_info(component_id)
233 .is_some_and(|info| info.storage_type() == StorageType::Table)
234 })
235 }
236}
237
238#[cfg(test)]
239mod tests {
240
241 use super::*;
242 use crate::{
243 prelude::{EntityMut, EntityRef, World},
244 query::{Has, With},
245 };
246 use alloc::{vec, vec::Vec};
247
248 #[test]
249 fn filters_modify_access() {
250 let mut filters = DefaultQueryFilters::empty();
251 filters.register_disabling_component(ComponentId::new(1));
252
253 // A component access with an unrelated component
254 let mut component_access = FilteredAccess::default();
255 component_access
256 .access_mut()
257 .add_component_read(ComponentId::new(2));
258
259 let mut applied_access = component_access.clone();
260 filters.modify_access(&mut applied_access);
261 assert_eq!(0, applied_access.with_filters().count());
262 assert_eq!(
263 vec![ComponentId::new(1)],
264 applied_access.without_filters().collect::<Vec<_>>()
265 );
266
267 // We add a with filter, now we expect to see both filters
268 component_access.and_with(ComponentId::new(4));
269
270 let mut applied_access = component_access.clone();
271 filters.modify_access(&mut applied_access);
272 assert_eq!(
273 vec![ComponentId::new(4)],
274 applied_access.with_filters().collect::<Vec<_>>()
275 );
276 assert_eq!(
277 vec![ComponentId::new(1)],
278 applied_access.without_filters().collect::<Vec<_>>()
279 );
280
281 let copy = component_access.clone();
282 // We add a rule targeting a default component, that filter should no longer be added
283 component_access.and_with(ComponentId::new(1));
284
285 let mut applied_access = component_access.clone();
286 filters.modify_access(&mut applied_access);
287 assert_eq!(
288 vec![ComponentId::new(1), ComponentId::new(4)],
289 applied_access.with_filters().collect::<Vec<_>>()
290 );
291 assert_eq!(0, applied_access.without_filters().count());
292
293 // Archetypal access should also filter rules
294 component_access = copy.clone();
295 component_access
296 .access_mut()
297 .add_archetypal(ComponentId::new(1));
298
299 let mut applied_access = component_access.clone();
300 filters.modify_access(&mut applied_access);
301 assert_eq!(
302 vec![ComponentId::new(4)],
303 applied_access.with_filters().collect::<Vec<_>>()
304 );
305 assert_eq!(0, applied_access.without_filters().count());
306 }
307
308 #[derive(Component)]
309 struct CustomDisabled;
310
311 #[derive(Component)]
312 struct Dummy;
313
314 #[test]
315 fn multiple_disabling_components() {
316 let mut world = World::new();
317 world.register_disabling_component::<CustomDisabled>();
318
319 // Use powers of two so we can uniquely identify the set of matching archetypes from the count.
320 world.spawn(Dummy);
321 world.spawn_batch((0..2).map(|_| (Dummy, Disabled)));
322 world.spawn_batch((0..4).map(|_| (Dummy, CustomDisabled)));
323 world.spawn_batch((0..8).map(|_| (Dummy, Disabled, CustomDisabled)));
324
325 let mut query = world.query::<&Dummy>();
326 assert_eq!(1, query.iter(&world).count());
327
328 let mut query = world.query_filtered::<EntityRef, With<Dummy>>();
329 assert_eq!(1, query.iter(&world).count());
330
331 let mut query = world.query_filtered::<EntityMut, With<Dummy>>();
332 assert_eq!(1, query.iter(&world).count());
333
334 let mut query = world.query_filtered::<&Dummy, With<Disabled>>();
335 assert_eq!(2, query.iter(&world).count());
336
337 let mut query = world.query_filtered::<Has<Disabled>, With<Dummy>>();
338 assert_eq!(3, query.iter(&world).count());
339
340 let mut query = world.query_filtered::<&Dummy, With<CustomDisabled>>();
341 assert_eq!(4, query.iter(&world).count());
342
343 let mut query = world.query_filtered::<Has<CustomDisabled>, With<Dummy>>();
344 assert_eq!(5, query.iter(&world).count());
345
346 let mut query = world.query_filtered::<&Dummy, (With<Disabled>, With<CustomDisabled>)>();
347 assert_eq!(8, query.iter(&world).count());
348
349 let mut query = world.query_filtered::<(Has<Disabled>, Has<CustomDisabled>), With<Dummy>>();
350 assert_eq!(15, query.iter(&world).count());
351
352 // This seems like it ought to count as a mention of `Disabled`, but it does not.
353 // We don't consider read access, since that would count `EntityRef` as a mention of *all* components.
354 let mut query = world.query_filtered::<Option<&Disabled>, With<Dummy>>();
355 assert_eq!(1, query.iter(&world).count());
356 }
357}