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

Added Has<T> WorldQuery type #8844

Merged
merged 14 commits into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
128 changes: 128 additions & 0 deletions crates/bevy_ecs/src/query/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,6 +1096,134 @@ unsafe impl<T: WorldQuery> WorldQuery for Option<T> {
/// SAFETY: [`OptionFetch`] is read only because `T` is read only
unsafe impl<T: ReadOnlyWorldQuery> ReadOnlyWorldQuery for Option<T> {}

/// Returns whether each entity has component `T`.
wainwrightmark marked this conversation as resolved.
Show resolved Hide resolved
///
/// This can be used in a [`Query`](crate::system::Query) if you want to know whether or not entities
/// have the component `T` but don't actually care about the component's value.
///
/// # Examples
///
/// ```
/// # use bevy_ecs::component::Component;
/// # use bevy_ecs::query::Has;
/// # use bevy_ecs::system::IntoSystem;
/// # use bevy_ecs::system::Query;
/// #
/// # #[derive(Component)]
/// # struct IsHungry;
/// # #[derive(Component)]
/// # struct Name { name: &'static str };
/// #
/// fn compliment_entity_system(query: Query<(&Name, Has<IsHungry>) >) {
/// for (name, is_hungry) in &query {
/// if is_hungry{
/// println!("{} would like some food.", name.name);
/// } else {
/// println!("{} has had sufficient.", name.name);
/// }
/// }
/// }
/// # bevy_ecs::system::assert_is_system(compliment_entity_system);
/// ```
pub struct Has<T>(PhantomData<T>);

#[doc(hidden)]
pub struct HasFetch<T: Component> {
phantom: PhantomData<T>,
matches: bool,
}

// SAFETY: `Self::ReadOnly` is the same as `Self`
unsafe impl<T: Component> WorldQuery for Has<T> {
type Fetch<'w> = HasFetch<T>;
wainwrightmark marked this conversation as resolved.
Show resolved Hide resolved
type Item<'w> = bool;
type ReadOnly = Self;
type State = ComponentId;

fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
item
}

const IS_DENSE: bool = {
match T::Storage::STORAGE_TYPE {
StorageType::Table => true,
StorageType::SparseSet => false,
}
};

const IS_ARCHETYPAL: bool = true;

#[inline]
unsafe fn init_fetch(
_world: &World,
_state: &ComponentId,
_last_run: Tick,
_this_run: Tick,
) -> HasFetch<T> {
HasFetch {
phantom: Default::default(),
matches: false,
}
}

unsafe fn clone_fetch<'w>(fetch: &Self::Fetch<'w>) -> Self::Fetch<'w> {
HasFetch {
phantom: Default::default(),
matches: fetch.matches,
}
}

#[inline]
unsafe fn set_archetype(
fetch: &mut HasFetch<T>,
state: &ComponentId,
archetype: &Archetype,
_table: &Table,
) {
fetch.matches = archetype.contains(*state);
}

#[inline]
unsafe fn set_table(_fetch: &mut HasFetch<T>, _state: &ComponentId, _table: &Table) {
_fetch.matches = _table.has_column(*_state);
alice-i-cecile marked this conversation as resolved.
Show resolved Hide resolved
}

#[inline(always)]
unsafe fn fetch<'w>(
fetch: &mut Self::Fetch<'w>,
_entity: Entity,
_table_row: TableRow,
) -> Self::Item<'w> {
fetch.matches
}

fn update_component_access(_state: &ComponentId, _access: &mut FilteredAccess<ComponentId>) {
// Do nothing as presence of `Has<T>` never affects whether two queries are disjoint
}

fn update_archetype_component_access(
_state: &ComponentId,
_archetype: &Archetype,
_access: &mut Access<ArchetypeComponentId>,
) {
}

fn init_state(world: &mut World) -> ComponentId {
world.init_component::<T>()
}

fn matches_component_set(
_state: &ComponentId,
_set_contains_id: &impl Fn(ComponentId) -> bool,
) -> bool {
// `Has<T>` always matches
true
}
}

/// SAFETY: [`Has`] is read only
unsafe impl<T: Component> ReadOnlyWorldQuery for Has<T> {}

macro_rules! impl_tuple_fetch {
($(($name: ident, $state: ident)),*) => {
#[allow(non_snake_case)]
Expand Down
5 changes: 3 additions & 2 deletions crates/bevy_ecs/src/query/filter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{
archetype::{Archetype, ArchetypeComponentId},
component::{Component, ComponentId, ComponentStorage, StorageType, Tick},
entity::Entity,
query::{Access, DebugCheckedUnwrap, FilteredAccess, WorldQuery},
query::{Access, DebugCheckedUnwrap, FilteredAccess, Has, WorldQuery},
storage::{Column, ComponentSparseSet, Table, TableRow},
world::World,
};
Expand Down Expand Up @@ -623,7 +623,7 @@ impl_tick_filter!(
/// [`QueryIter`](crate::query::QueryIter) that contains archetype-level filters.
///
/// The trait must only be implement for filters where its corresponding [`WorldQuery::IS_ARCHETYPAL`](crate::query::WorldQuery::IS_ARCHETYPAL)
/// is [`prim@true`]. As such, only the [`With`] and [`Without`] filters can implement the trait.
/// is [`prim@true`]. As such, only the [`With`], [`Without`], and [`Has`] filters can implement the trait.
/// [Tuples](prim@tuple) and [`Or`] filters are automatically implemented with the trait only if its containing types
/// also implement the same trait.
///
Expand All @@ -633,6 +633,7 @@ pub trait ArchetypeFilter {}

impl<T> ArchetypeFilter for With<T> {}
impl<T> ArchetypeFilter for Without<T> {}
impl<T> ArchetypeFilter for Has<T> {}

macro_rules! impl_archetype_filter_tuple {
($($filter: ident),*) => {
Expand Down
20 changes: 19 additions & 1 deletion crates/bevy_ecs/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl<T> DebugCheckedUnwrap for Option<T> {
mod tests {
use super::{ReadOnlyWorldQuery, WorldQuery};
use crate::prelude::{AnyOf, Changed, Entity, Or, QueryState, With, Without};
use crate::query::{ArchetypeFilter, QueryCombinationIter};
use crate::query::{ArchetypeFilter, Has, QueryCombinationIter};
use crate::schedule::{IntoSystemConfigs, Schedule};
use crate::system::{IntoSystem, Query, System, SystemState};
use crate::{self as bevy_ecs, component::Component, world::World};
Expand Down Expand Up @@ -476,6 +476,24 @@ mod tests {
);
}

#[test]
fn has_query() {
let mut world = World::new();

world.spawn((A(1), B(1)));
world.spawn(A(2));
world.spawn((A(3), B(1)));
world.spawn(A(4));

let values: Vec<(&A, bool)> = world.query::<(&A, Has<B>)>().iter(&world).collect();

// The query seems to put the components with B first
assert_eq!(
values,
vec![(&A(1), true), (&A(3), true), (&A(2), false), (&A(4), false),]
);
}

#[test]
#[should_panic = "&mut bevy_ecs::query::tests::A conflicts with a previous access in this query."]
fn self_conflicting_worldquery() {
Expand Down