Skip to main content

NestedQuery

Struct NestedQuery 

Source
pub struct NestedQuery<D, F = ()>(/* private fields */)
where
    D: QueryData + 'static,
    F: QueryFilter + 'static;
Expand description

A helper type for accessing a Query within a QueryData.

This is intended to be used inside other implementations of QueryData, either for manual implementations or #[derive(QueryData)]. It is not normally useful to query directly, since it’s equivalent to adding another Query parameter to a system.

Note that this requires the inner query to be a ReadOnlyQueryData to prevent mutable aliasing.

fn system(mut query: Query<NestedQuery<&A>>) {
    // This works, because it performs read-only iteration
    for a in &query {
        let a: Query<&A> = a;
    }
}
fn system(mut query: Query<NestedQuery<&mut A>>) {
    // This fails, because it would allow mutable aliasing of `&mut A`
    for a in &mut query {
        let a: Query<&mut A> = a;
    }
}

§Example

The simplest way to use a NestedQuery is with a #[derive(QueryData)] struct. The Query will be available on the generated Item struct, and we can use the query in methods on that struct.

// We want to create a relational query data
// that lets us query components on an entity's parent,
// like this:
let root = world.spawn(Data(3)).id();
let child = world.spawn(ChildOf(root)).id();

let mut query = world.query::<Parent<&Data>>();
let &Data(data) = query.query(&mut world).get(child).unwrap().data().unwrap();
assert_eq!(data, 3);

// We derive a query data struct that contains the relation plus a `NestedQuery`
#[derive(QueryData)]
struct Parent<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static = ()> {
    // This will query `ChildOf` on the entity itself,
    // so we can find the parent entity
    parent: &'static ChildOf,
    // This will provide a `Query` that we can use to
    // query data on the parent entity
    nested_query: NestedQuery<D, F>,
}

// And add a method on the generated item struct to invoke the nested query.
impl<'w, 's, D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ParentItem<'w, 's, D, F> {
    fn data(&self) -> Option<D::Item<'w, 's>> {
        // We need to use `_inner` methods to return the full `'w` lifetime.
        self.nested_query.get_inner(self.parent.parent()).ok()
    }
}

In order to make a query that returns the inner query data directly, instead of through an intermediate Item struct, you can implement QueryData manually by delegating to NestedQuery.

// We want to create a relational query data
// that lets us query components on an entity's parent,
// like this:
let root = world.spawn(Data(3)).id();
let child = world.spawn(ChildOf(root)).id();

let mut query = world.query::<Parent<&Data>>();
let &Data(data) = query.query(&mut world).get(child).unwrap();
assert_eq!(data, 3);

// This is the relational query data.
// This will never actually be constructed,
// and is only used as a `QueryData` type.
pub struct Parent<D: ReadOnlyQueryData, F: QueryFilter = ()>(D, F);

// A type alias to delegate the `QueryData` impls to.
// We need to refer to this type a lot, so the alias will help.
// This could also be a `#[derive(QueryData)]` type.
type ParentInner<D, F> = (
    // This will query `ChildOf` on the entity itself,
    // so we can find the parent entity
    &'static ChildOf,
    // This will provide a `Query` that we can use to
    // query data on the parent entity
    NestedQuery<D, F>,
);

unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> QueryData for Parent<D, F> {
    // Set `Item` to what we need for this relational query.
    // Here we use the output of `D`.
    type Item<'w, 's> = D::Item<'w, 's>;

    unsafe fn fetch<'w, 's>(state: &'s Self::State, fetch: &mut Self::Fetch<'w>, entity: Entity, table_row: TableRow) -> Option<Self::Item<'w, 's>> {
        // In `fetch`, first delegate to the type alias to get the parts:
        let (&ChildOf(parent), nested_query) =
            <ParentInner<D, F> as QueryData>::fetch(state, fetch, entity, table_row)?;
        // Then use the `NestedQuery` to get the data we need.
        // We need to use `_inner` methods to return the full `'w` lifetime.
        nested_query.get_inner(parent).ok()
    }

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

    // Set `ReadOnly` to `Self`,
    // as `NestedQuery` does not yet support mutable queries.
    type ReadOnly = Self;

    // Delegate everything else on `QueryData` and `WorldQuery` to the type alias.
    // This is sound for `unsafe` items because they delegate to the
    // sound implementations on the type alias.
    const IS_READ_ONLY: bool = <ParentInner<D, F> as QueryData>::IS_READ_ONLY;
    const IS_ARCHETYPAL: bool = <ParentInner<D, F> as QueryData>::IS_ARCHETYPAL;

    fn iter_access(state: &Self::State) -> impl Iterator<Item = EcsAccessType<'_>> {
        <ParentInner<D, F> as QueryData>::iter_access(state)
    }
}

unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> WorldQuery for Parent<D, F> {
    type Fetch<'w> = <ParentInner<D, F> as WorldQuery>::Fetch<'w>;
    type State = <ParentInner<D, F> as WorldQuery>::State;

    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
        <ParentInner<D, F> as WorldQuery>::shrink_fetch(fetch)
    }

    unsafe fn init_fetch<'w, 's>(world: UnsafeWorldCell<'w>, state: &'s Self::State, last_run: Tick, this_run: Tick) -> Self::Fetch<'w> {
        <ParentInner<D, F> as WorldQuery>::init_fetch(world, state, last_run, this_run)
    }

    const IS_DENSE: bool = <ParentInner<D, F> as WorldQuery>::IS_DENSE;

    unsafe fn set_archetype<'w, 's>(fetch: &mut Self::Fetch<'w>, state: &'s Self::State, archetype: &'w Archetype, table: &'w Table) {
        <ParentInner<D, F> as WorldQuery>::set_archetype(fetch, state, archetype, table)
    }

    unsafe fn set_table<'w, 's>(fetch: &mut Self::Fetch<'w>, state: &'s Self::State, table: &'w Table) {
        <ParentInner<D, F> as WorldQuery>::set_table(fetch, state, table)
    }

    fn update_component_access(state: &Self::State, access: &mut FilteredAccess) {
        <ParentInner<D, F> as WorldQuery>::update_component_access(state, access)
    }

    fn init_state(world: &mut World) -> Self::State {
        <ParentInner<D, F> as WorldQuery>::init_state(world)
    }

    fn get_state(components: &Components) -> Option<Self::State> {
        <ParentInner<D, F> as WorldQuery>::get_state(components)
    }

    fn matches_component_set(state: &Self::State, set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
        <ParentInner<D, F> as WorldQuery>::matches_component_set(state, set_contains_id)
    }
}

// Also impl `ReadOnlyQueryData`, `IterQueryData`, and `ReleaseStateQueryData`
// These are safe because they delegate to the type alias, which is also read-only.
// Do *not* impl `ArchetypeQueryData`, because `fetch` sometimes returns `None`,
// and do *not* impl `SingleEntityQueryData`, because `NestedQuery` accesses other entities.
unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> ReadOnlyQueryData for Parent<D, F> {}

unsafe impl<D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static> IterQueryData for Parent<D, F> {}

impl<D: ReadOnlyQueryData + ReleaseStateQueryData + 'static, F: QueryFilter + 'static>
    ReleaseStateQueryData for Parent<D, F>
{
    fn release_state<'w>(item: Self::Item<'w, '_>) -> Self::Item<'w, 'static> {
        D::release_state(item)
    }
}

Trait Implementations§

Source§

impl<D, F> QueryData for NestedQuery<D, F>
where D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static,

Source§

const IS_READ_ONLY: bool = D::IS_READ_ONLY

True if this query is read-only and may not perform mutable access.
Source§

const IS_ARCHETYPAL: bool = true

Returns true if (and only if) this query data relies strictly on archetypes to limit which entities are accessed by the Query. Read more
Source§

type ReadOnly = NestedQuery<D, F>

The read-only variant of this QueryData, which satisfies the ReadOnlyQueryData trait.
Source§

type Item<'w, 's> = Query<'w, 's, D, F>

The item returned by this WorldQuery This will be the data retrieved by the query, and is visible to the end user when calling e.g. Query<Self>::get.
Source§

fn shrink<'wlong, 'wshort, 's>( item: <NestedQuery<D, F> as QueryData>::Item<'wlong, 's>, ) -> <NestedQuery<D, F> as QueryData>::Item<'wshort, 's>
where 'wlong: 'wshort,

This function manually implements subtyping for the query items.
Source§

unsafe fn fetch<'w, 's>( state: &'s <NestedQuery<D, F> as WorldQuery>::State, fetch: &mut <NestedQuery<D, F> as WorldQuery>::Fetch<'w>, _entity: Entity, _table_row: TableRow, ) -> Option<<NestedQuery<D, F> as QueryData>::Item<'w, 's>>

Fetch Self::Item for either the given entity in the current Table, or for the given entity in the current Archetype. This must always be called after WorldQuery::set_table with a table_row in the range of the current Table or after WorldQuery::set_archetype with an entity in the current archetype. Accesses components registered in WorldQuery::update_component_access. Read more
Source§

fn iter_access( _state: &<NestedQuery<D, F> as WorldQuery>::State, ) -> impl Iterator<Item = EcsAccessType<'_>>

Returns an iterator over the access needed by QueryData::fetch. Access conflicts are usually checked in WorldQuery::update_component_access, but in certain cases this method can be useful to implement a way of checking for access conflicts in a non-allocating way.
Source§

fn provide_extra_access( _state: &mut Self::State, _access: &mut Access, _available_access: &Access, )

Offers additional access above what we requested in update_component_access. Implementations may add additional access that is a subset of available_access and does not conflict with anything in access, and must update access to include that access. Read more
Source§

impl<D, F> WorldQuery for NestedQuery<D, F>
where D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static,

Source§

const IS_DENSE: bool = true

Returns true if (and only if) every table of every archetype matched by this fetch contains all of the matched components. Read more
Source§

type Fetch<'w> = NestedQueryFetch<'w>

Per archetype/table state retrieved by this WorldQuery to compute Self::Item for each entity.
Source§

type State = QueryState<D, F>

State used to construct a Self::Fetch. This will be cached inside QueryState, so it is best to move as much data / computation here as possible to reduce the cost of constructing Self::Fetch.
Source§

fn shrink_fetch<'wlong, 'wshort>( fetch: <NestedQuery<D, F> as WorldQuery>::Fetch<'wlong>, ) -> <NestedQuery<D, F> as WorldQuery>::Fetch<'wshort>
where 'wlong: 'wshort,

This function manually implements subtyping for the query fetches.
Source§

unsafe fn init_fetch<'w, 's>( world: UnsafeWorldCell<'w>, _state: &'s <NestedQuery<D, F> as WorldQuery>::State, last_run: Tick, this_run: Tick, ) -> <NestedQuery<D, F> as WorldQuery>::Fetch<'w>

Creates a new instance of Self::Fetch, by combining data from the World with the cached Self::State. Readonly accesses resources registered in WorldQuery::update_component_access. Read more
Source§

unsafe fn set_archetype<'w>( _fetch: &mut <NestedQuery<D, F> as WorldQuery>::Fetch<'w>, _state: &<NestedQuery<D, F> as WorldQuery>::State, _archetype: &'w Archetype, _table: &'w Table, )

Adjusts internal state to account for the next Archetype. This will always be called on archetypes that match this WorldQuery. Read more
Source§

unsafe fn set_table<'w>( _fetch: &mut <NestedQuery<D, F> as WorldQuery>::Fetch<'w>, _state: &<NestedQuery<D, F> as WorldQuery>::State, _table: &'w Table, )

Adjusts internal state to account for the next Table. This will always be called on tables that match this WorldQuery. Read more
Source§

fn update_component_access( _state: &<NestedQuery<D, F> as WorldQuery>::State, _access: &mut FilteredAccess, )

Adds any component accesses to the current entity used by this WorldQuery to access. Read more
Source§

fn init_nested_access( state: &<NestedQuery<D, F> as WorldQuery>::State, system_name: Option<&str>, component_access_set: &mut FilteredAccessSet, world: UnsafeWorldCell<'_>, )

Adds any component accesses to other entities used by this WorldQuery. Read more
Source§

fn init_state(world: &mut World) -> <NestedQuery<D, F> as WorldQuery>::State

Creates and initializes a State for this WorldQuery type.
Source§

fn get_state( _components: &Components, ) -> Option<<NestedQuery<D, F> as WorldQuery>::State>

Attempts to initialize a State for this WorldQuery type using read-only access to Components.
Source§

fn matches_component_set( _state: &<NestedQuery<D, F> as WorldQuery>::State, _set_contains_id: &impl Fn(ComponentId) -> bool, ) -> bool

Returns true if this query matches a set of components. Otherwise, returns false. Read more
Source§

fn update_archetypes( state: &mut <NestedQuery<D, F> as WorldQuery>::State, world: UnsafeWorldCell<'_>, )

Called when the query state is updating its archetype cache. This can be used by nested queries to update their internal archetype caches.
Source§

impl<D, F> ArchetypeQueryData for NestedQuery<D, F>

Source§

impl<D, F> IterQueryData for NestedQuery<D, F>

Source§

impl<D, F> ReadOnlyQueryData for NestedQuery<D, F>

Auto Trait Implementations§

§

impl<D, F> Freeze for NestedQuery<D, F>

§

impl<D, F = ()> !RefUnwindSafe for NestedQuery<D, F>

§

impl<D, F> Send for NestedQuery<D, F>

§

impl<D, F> Sync for NestedQuery<D, F>

§

impl<D, F> Unpin for NestedQuery<D, F>

§

impl<D, F> UnsafeUnpin for NestedQuery<D, F>

§

impl<D, F = ()> !UnwindSafe for NestedQuery<D, F>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,