Skip to content

Add simple Disabled marker #17514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions crates/bevy_ecs/src/entity_disabling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,17 @@ use crate::{
component::{ComponentId, Components, StorageType},
query::FilteredAccess,
};
use bevy_ecs_macros::Resource;
use bevy_ecs_macros::{Component, Resource};

#[cfg(feature = "bevy_reflect")]
use {crate::reflect::ReflectComponent, bevy_reflect::Reflect};

/// A marker component for disabled entities. See [the module docs] for more info.
///
/// [the module docs]: crate::entity_disabling
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we update the module docs to mention that the Disabled component is disabled in the default DefaultQueryFilters? Right now they talk about it as a hypothetical.

#[derive(Component)]
#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Component))]
pub struct Disabled;

/// The default filters for all queries, these are used to globally exclude entities from queries.
/// See the [module docs](crate::entity_disabling) for more info.
Expand All @@ -37,10 +47,6 @@ pub struct DefaultQueryFilters {
}

impl DefaultQueryFilters {
#[cfg_attr(
not(test),
expect(dead_code, reason = "No Disabled component exist yet")
)]
/// Set the [`ComponentId`] for the entity disabling marker
pub(crate) fn set_disabled(&mut self, component_id: ComponentId) -> Option<()> {
if self.disabled.is_some() {
Expand Down
3 changes: 3 additions & 0 deletions crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ mod tests {
change_detection::Ref,
component::{require, Component, ComponentId, RequiredComponents, RequiredComponentsError},
entity::Entity,
entity_disabling::DefaultQueryFilters,
prelude::Or,
query::{Added, Changed, FilteredAccess, QueryFilter, With, Without},
resource::Resource,
Expand Down Expand Up @@ -1530,6 +1531,8 @@ mod tests {
#[test]
fn filtered_query_access() {
let mut world = World::new();
// We remove entity disabling so it doesn't affect our query filters
world.remove_resource::<DefaultQueryFilters>();
let query = world.query_filtered::<&mut A, Changed<B>>();

let mut expected = FilteredAccess::<ComponentId>::default();
Expand Down
6 changes: 3 additions & 3 deletions crates/bevy_ecs/src/system/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2516,15 +2516,15 @@ mod tests {

fn nothing() {}

assert!(world.iter_resources().count() == 0);
let resources = world.iter_resources().count();
let id = world.register_system_cached(nothing);
assert!(world.iter_resources().count() == 1);
assert_eq!(world.iter_resources().count(), resources + 1);
assert!(world.get_entity(id.entity).is_ok());

let mut commands = Commands::new(&mut queue, &world);
commands.unregister_system_cached(nothing);
queue.apply(&mut world);
assert!(world.iter_resources().count() == 0);
assert_eq!(world.iter_resources().count(), resources);
assert!(world.get_entity(id.entity).is_err());
}

Expand Down
24 changes: 24 additions & 0 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ use crate::{
RequiredComponentsError, Tick,
},
entity::{AllocAtWithoutReplacement, Entities, Entity, EntityLocation},
entity_disabling::{DefaultQueryFilters, Disabled},
event::{Event, EventId, Events, SendBatchIds},
observer::Observers,
query::{DebugCheckedUnwrap, QueryData, QueryFilter, QueryState},
Expand Down Expand Up @@ -159,6 +160,11 @@ impl World {

let on_despawn = OnDespawn::register_component_id(self);
assert_eq!(ON_DESPAWN, on_despawn);

let disabled = self.register_component::<Disabled>();
let mut filters = DefaultQueryFilters::default();
filters.set_disabled(disabled);
Copy link
Contributor

@cBournhonesque cBournhonesque Jan 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit worried that users might do a
app.init_resource::<DefaultQueryFilters>()

and lose the Disabled functionality inadvertently..

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

init_resource doesn't overwrite existing resources. You'd have to explicitly call .insert_resource(DefaultQueryFilters::default()) which is probably verbose enough to make it obvious what will happen. Currently it is intended that you can opt-out of entity disabling, but as the feature matures we could consider making it so that it is always there.

self.insert_resource(filters);
}
/// Creates a new empty [`World`].
///
Expand Down Expand Up @@ -3268,6 +3274,7 @@ impl World {
/// # struct B(u32);
/// #
/// # let mut world = World::new();
/// # world.remove_resource::<bevy_ecs::entity_disabling::DefaultQueryFilters>();
/// # world.insert_resource(A(1));
/// # world.insert_resource(B(2));
/// let mut total = 0;
Expand Down Expand Up @@ -3766,6 +3773,7 @@ mod tests {
change_detection::DetectChangesMut,
component::{ComponentDescriptor, ComponentInfo, StorageType},
entity::hash_set::EntityHashSet,
entity_disabling::{DefaultQueryFilters, Disabled},
ptr::OwningPtr,
resource::Resource,
world::error::EntityFetchError,
Expand Down Expand Up @@ -3955,6 +3963,8 @@ mod tests {
#[test]
fn iter_resources() {
let mut world = World::new();
// Remove DefaultQueryFilters so it doesn't show up in the iterator
world.remove_resource::<DefaultQueryFilters>();
world.insert_resource(TestResource(42));
world.insert_resource(TestResource2("Hello, world!".to_string()));
world.insert_resource(TestResource3);
Expand All @@ -3981,6 +3991,8 @@ mod tests {
#[test]
fn iter_resources_mut() {
let mut world = World::new();
// Remove DefaultQueryFilters so it doesn't show up in the iterator
world.remove_resource::<DefaultQueryFilters>();
world.insert_resource(TestResource(42));
world.insert_resource(TestResource2("Hello, world!".to_string()));
world.insert_resource(TestResource3);
Expand Down Expand Up @@ -4447,4 +4459,16 @@ mod tests {
None
);
}

#[test]
fn new_world_has_disabling() {
let mut world = World::new();
world.spawn(Foo);
world.spawn((Foo, Disabled));
assert_eq!(1, world.query::<&Foo>().iter(&world).count());

// If we explicitly remove the resource, no entities should be filtered anymore
world.remove_resource::<DefaultQueryFilters>();
assert_eq!(2, world.query::<&Foo>().iter(&world).count());
}
}
11 changes: 11 additions & 0 deletions crates/bevy_scene/src/dynamic_scene_builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use core::any::TypeId;

use crate::{DynamicEntity, DynamicScene, SceneFilter};
use alloc::collections::BTreeMap;
use bevy_ecs::{
component::{Component, ComponentId},
entity_disabling::DefaultQueryFilters,
prelude::Entity,
reflect::{AppTypeRegistry, ReflectComponent, ReflectResource},
resource::Resource,
Expand Down Expand Up @@ -348,9 +351,17 @@ impl<'w> DynamicSceneBuilder<'w> {
/// [`deny_resource`]: Self::deny_resource
#[must_use]
pub fn extract_resources(mut self) -> Self {
let original_world_dqf_id = self
.original_world
.components()
.get_resource_id(TypeId::of::<DefaultQueryFilters>());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It will be nice when resources-as-components lets us use default query filters to exclude the default query filters resource from our resource query :).


let type_registry = self.original_world.resource::<AppTypeRegistry>().read();

for (component_id, _) in self.original_world.storages().resources.iter() {
if Some(component_id) == original_world_dqf_id {
continue;
}
let mut extract_and_push = || {
let type_id = self
.original_world
Expand Down
11 changes: 11 additions & 0 deletions crates/bevy_scene/src/scene.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use core::any::TypeId;

use crate::{DynamicScene, SceneSpawnError};
use bevy_asset::Asset;
use bevy_ecs::{
entity::{hash_map::EntityHashMap, Entity, SceneEntityMapper},
entity_disabling::DefaultQueryFilters,
reflect::{AppTypeRegistry, ReflectComponent, ReflectMapEntities, ReflectResource},
world::World,
};
Expand Down Expand Up @@ -59,8 +62,16 @@ impl Scene {
) -> Result<(), SceneSpawnError> {
let type_registry = type_registry.read();

let self_dqf_id = self
.world
.components()
.get_resource_id(TypeId::of::<DefaultQueryFilters>());

// Resources archetype
for (component_id, resource_data) in self.world.storages().resources.iter() {
if Some(component_id) == self_dqf_id {
continue;
}
if !resource_data.is_present() {
continue;
}
Expand Down
Loading