Skip to content
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

Add DefaultQueryFilters #13120

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions crates/bevy_app/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use bevy_ecs::{
event::{event_update_system, ManualEventReader},
intern::Interned,
prelude::*,
query::DefaultQueryFilters,
schedule::{ScheduleBuildSettings, ScheduleLabel},
system::SystemId,
};
Expand Down Expand Up @@ -94,6 +95,7 @@ impl Default for App {
let mut app = App::empty();
app.sub_apps.main.update_schedule = Some(Main.intern());

app.init_resource::<DefaultQueryFilters>();
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(feature = "bevy_reflect")]
app.init_resource::<AppTypeRegistry>();
app.add_plugins(MainSchedulePlugin);
Expand Down
173 changes: 173 additions & 0 deletions crates/bevy_ecs/src/query/default_filters.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
use crate as bevy_ecs;
use crate::{component::ComponentId, query::FilteredAccess};
use bevy_ecs_macros::Resource;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum FilterKind {
With,
Without,
}

#[derive(PartialEq, Eq, Debug)]
struct DefaultFilter {
component_id: ComponentId,
kind: FilterKind,
}

/// A list of default query filters, these can be used to globally exclude entities from queries.
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
/// Each individual filter is only applied to queries that don't mention that component.
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
///
/// If for example we register a `Hidden` component using the `without` method, entities with this
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
/// component will only be visible to a [`Query`](crate::prelude::Query) containing something like
/// [`With<Hidden>`](crate::prelude::With) or [`Has<Hidden>`](crate::prelude::Has).
///
/// These filters are only applied to queries initialized after updating this resource,
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
/// it should most likely only be modified before the app starts.
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
#[derive(Resource, Default)]
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
pub struct DefaultQueryFilters(Vec<DefaultFilter>);
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved

impl DefaultQueryFilters {
/// Add a With filter to the default query filters.
/// Removes any Without filter for this component if present.
pub fn with(&mut self, component_id: ComponentId) {
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
self.set(component_id, FilterKind::With);
}

/// Add a Without filter to the default query filters.
/// Removes any With filter for this component if present.
pub fn without(&mut self, component_id: ComponentId) {
self.set(component_id, FilterKind::Without);
}

/// Remove a filter for the specified [`ComponentId`]
pub fn remove(&mut self, component_id: ComponentId) {
self.0.retain(|filter| filter.component_id != component_id);
}

fn set(&mut self, component_id: ComponentId, kind: FilterKind) {
if let Some(filter) = self
.0
.iter_mut()
.find(|filter| filter.component_id == component_id)
{
filter.kind = kind;
} else {
self.0.push(DefaultFilter { component_id, kind });
}
}

pub(super) fn apply(&self, component_access: &mut FilteredAccess<ComponentId>) {
for filter in self.0.iter() {
if !contains_component(component_access, filter.component_id) {
match filter.kind {
FilterKind::With => component_access.and_with(filter.component_id),
FilterKind::Without => component_access.and_without(filter.component_id),
}
}
}
}
}

fn contains_component(
NiseVoid marked this conversation as resolved.
Show resolved Hide resolved
component_access: &FilteredAccess<ComponentId>,
component_id: ComponentId,
) -> bool {
component_access.access().has_read(component_id)
|| component_access.access().has_archetypal(component_id)
|| component_access.filter_sets.iter().any(|f| {
f.with.contains(component_id.index()) || f.without.contains(component_id.index())
})
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_set_filters() {
let mut filters = DefaultQueryFilters::default();
filters.with(ComponentId::new(1));
filters.with(ComponentId::new(3));
filters.without(ComponentId::new(3));

assert_eq!(2, filters.0.len());
assert_eq!(
DefaultFilter {
component_id: ComponentId::new(1),
kind: FilterKind::With
},
filters.0[0]
);
assert_eq!(
DefaultFilter {
component_id: ComponentId::new(3),
kind: FilterKind::Without
},
filters.0[1]
);
}

#[test]
fn test_apply_filters() {
let mut filters = DefaultQueryFilters::default();
filters.with(ComponentId::new(1));
filters.without(ComponentId::new(3));

// A component access with an unrelated component
let mut component_access = FilteredAccess::<ComponentId>::default();
component_access.access_mut().add_read(ComponentId::new(2));

let mut applied_access = component_access.clone();
filters.apply(&mut applied_access);
assert_eq!(
vec![ComponentId::new(1)],
applied_access.with_filters().collect::<Vec<_>>()
);
assert_eq!(
vec![ComponentId::new(3)],
applied_access.without_filters().collect::<Vec<_>>()
);

// We add a with filter, now we expect to see both filters
component_access.and_with(ComponentId::new(4));

let mut applied_access = component_access.clone();
filters.apply(&mut applied_access);
assert_eq!(
vec![ComponentId::new(1), ComponentId::new(4)],
applied_access.with_filters().collect::<Vec<_>>()
);
assert_eq!(
vec![ComponentId::new(3)],
applied_access.without_filters().collect::<Vec<_>>()
);

// We add a rule targeting a default component, that filter should no longer be added
component_access.and_with(ComponentId::new(3));

let mut applied_access = component_access.clone();
filters.apply(&mut applied_access);
assert_eq!(
vec![
ComponentId::new(1),
ComponentId::new(3),
ComponentId::new(4)
],
applied_access.with_filters().collect::<Vec<_>>()
);
assert!(applied_access.without_filters().next().is_none());

// Archetypal access should also filter rules
component_access
.access_mut()
.add_archetypal(ComponentId::new(1));

let mut applied_access = component_access.clone();
filters.apply(&mut applied_access);
assert_eq!(
vec![ComponentId::new(3), ComponentId::new(4)],
applied_access.with_filters().collect::<Vec<_>>()
);
assert!(applied_access.without_filters().next().is_none());
}
}
2 changes: 2 additions & 0 deletions crates/bevy_ecs/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

mod access;
mod builder;
mod default_filters;
mod error;
mod fetch;
mod filter;
Expand All @@ -13,6 +14,7 @@ mod world_query;
pub use access::*;
pub use bevy_ecs_macros::{QueryData, QueryFilter};
pub use builder::*;
pub use default_filters::DefaultQueryFilters;
pub use error::*;
pub use fetch::*;
pub use filter::*;
Expand Down
51 changes: 47 additions & 4 deletions crates/bevy_ecs/src/query/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use crate::{
entity::Entity,
prelude::FromWorld,
query::{
Access, DebugCheckedUnwrap, FilteredAccess, QueryCombinationIter, QueryIter, QueryParIter,
default_filters::DefaultQueryFilters, Access, DebugCheckedUnwrap, FilteredAccess,
QueryCombinationIter, QueryIter, QueryParIter,
},
storage::{SparseSetIndex, TableId},
world::{unsafe_world_cell::UnsafeWorldCell, World, WorldId},
Expand Down Expand Up @@ -194,6 +195,10 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
// properly considered in a global "cross-query" context (both within systems and across systems).
component_access.extend(&filter_component_access);

if let Some(default_filters) = world.get_resource::<DefaultQueryFilters>() {
default_filters.apply(&mut component_access);
}

Self {
world_id: world.id(),
archetype_generation: ArchetypeGeneration::initial(),
Expand All @@ -218,13 +223,19 @@ impl<D: QueryData, F: QueryFilter> QueryState<D, F> {
let filter_state = F::init_state(builder.world_mut());
D::set_access(&mut fetch_state, builder.access());

let mut component_access = builder.access().clone();

if let Some(default_filters) = builder.world().get_resource::<DefaultQueryFilters>() {
default_filters.apply(&mut component_access);
}

let mut state = Self {
world_id: builder.world().id(),
archetype_generation: ArchetypeGeneration::initial(),
matched_storage_ids: Vec::new(),
fetch_state,
filter_state,
component_access: builder.access().clone(),
component_access,
matched_tables: Default::default(),
matched_archetypes: Default::default(),
#[cfg(feature = "trace")]
Expand Down Expand Up @@ -1657,8 +1668,12 @@ impl<D: QueryData, F: QueryFilter> From<QueryBuilder<'_, D, F>> for QueryState<D
#[cfg(test)]
mod tests {
use crate as bevy_ecs;
use crate::world::FilteredEntityRef;
use crate::{component::Component, prelude::*, query::QueryEntityError};
use crate::{
component::Component,
prelude::*,
query::{DefaultQueryFilters, QueryEntityError},
world::FilteredEntityRef,
};

#[test]
fn get_many_unchecked_manual_uniqueness() {
Expand Down Expand Up @@ -2030,4 +2045,32 @@ mod tests {
let query_2 = QueryState::<&B, Without<C>>::new(&mut world);
let _: QueryState<Entity, Changed<C>> = query_1.join_filtered(&world, &query_2);
}

#[test]
fn query_respects_default_filters() {
let mut world = World::new();
world.spawn((A(0), B(0)));
world.spawn((B(0), C(0)));
world.spawn(C(0));

let b = world.component_id::<B>().unwrap();
let c = world.component_id::<C>().unwrap();

let mut default_filters = DefaultQueryFilters::default();
default_filters.with(b);
default_filters.without(c);
world.insert_resource(default_filters);

// With<B>, Without<C> only matches the first entity
let mut query = QueryState::<()>::new(&mut world);
assert_eq!(1, query.iter(&world).count());
alice-i-cecile marked this conversation as resolved.
Show resolved Hide resolved

// With<B>, With<C> only matches the second entity
let mut query = QueryState::<(), With<C>>::new(&mut world);
assert_eq!(1, query.iter(&world).count());

// Without<B> only matches the last entity
let mut query = QueryState::<Has<C>, Without<B>>::new(&mut world);
assert_eq!(1, query.iter(&world).count());
}
}