Queries
Read and change the components of matching entities with Query, look up single entities, iterate in parallel and define your own query types.
On this page
A Query is how a system reaches components. Query<D, F> has two parts: D, the data you want from each entity, and F, an optional filter that narrows which entities match. The query yields every entity that has all the components in D and passes F.
use neo::prelude::*;
#[derive(Component)]
struct Velocity(Vec3);
#[derive(Component)]
struct Enemy;
// every entity with both a Transform and a Velocity
fn movement(time: Res<Time>, mut query: Query<(&mut Transform, &Velocity)>) {
for (mut transform, velocity) in &mut query {
transform.translation += velocity.0 * time.delta_secs();
}
}
// only enemies, read-only
fn count_enemies(query: Query<&Transform, With<Enemy>>) {
info!("{} enemies", query.iter().len());
}What you can ask for#
In D | You get |
|---|---|
&T | A shared reference to component T. |
&mut T | A mutable reference (Mut<T>). Writing through it marks the component changed. |
Entity | The entity's id. |
Option<&T> | Some if the entity has T, None otherwise. The entity matches either way. |
Has<T> | true or false: whether the entity has T, without fetching it. |
AnyOf<(&A, &B)> | Entities with at least one of the components, each as an Option. |
Ref<T> | &T plus its change ticks: is_added(), is_changed(). |
NameOrEntity | The entity's Name, or its id when it has none. |
EntityRef, EntityMut | Every component of the entity. |
| A tuple | Several of the above: (Entity, &Transform, Option<&Name>). |
Iterate#
| Method | What it does |
|---|---|
for item in &query / query.iter() | Every match, read-only. |
for item in &mut query / query.iter_mut() | Every match, mutable. |
query.iter().len(), query.count() | How many entities match. |
query.is_empty() | Whether nothing matches. |
query.iter().sort::<&Name>() | Every match in a sorted order (iteration order is otherwise unspecified). |
query.iter_many(ids) | The matches among a list of ids, in that order. |
query.iter_combinations::<K>() | Every combination of K distinct matches, for pairwise checks. |
The order of a plain iter isn't defined and can change as entities are added and removed. Sort, or keep your own list, when order matters.
Look up a specific entity#
fn damage_target(target: Res<Target>, mut health: Query<&mut Health>) {
if let Ok(mut health) = health.get_mut(target.0) {
health.0 = health.0.saturating_sub(10);
}
}
#[derive(Resource)]
struct Target(Entity);
#[derive(Component)]
struct Health(u32);| Method | Returns |
|---|---|
query.get(entity), query.get_mut(entity) | Result: the entity's item, or an error if it doesn't exist or doesn't match. |
query.contains(entity) | Whether the entity matches. |
query.get_many([a, b]), query.get_many_mut([a, b]) | Several entities at once. get_many_mut errors if an id repeats. |
query.single(), query.single_mut() | Result: the only match, or an error if there are none or several. |
Single and Populated#
When a system only makes sense with exactly one matching entity, take Single instead of a query. The system is skipped, without an error, when there isn't exactly one match:
#[derive(Component)]
struct Player;
fn follow_player(
player: Single<&Transform, With<Player>>,
mut camera: Single<&mut Transform, (With<Camera3d>, Without<Player>)>,
) {
camera.translation = player.translation + Vec3::new(0.0, 5.0, 10.0);
}| Parameter | The system runs when |
|---|---|
Single<D, F> | Exactly one entity matches. |
Option<Single<D, F>> | Zero or one entity matches (None for zero). |
Populated<D, F> | At least one entity matches. Use it like a Query. |
Query<D, F> | Always, even with no matches. |
Two queries over the same component#
Two queries in one system can't both have mutable access to the same component on the same entities, because Rust can't allow two &mut to one value. The engine checks this when the system starts and reports the conflict. Make the queries disjoint with filters, for example With<Player> and Without<Player> as above, or use a ParamSet.
Iterate in parallel#
par_iter and par_iter_mut split the work across the engine's thread pool:
fn move_particles(time: Res<Time>, mut query: Query<(&mut Transform, &Velocity)>) {
let dt = time.delta_secs();
query.par_iter_mut().for_each(|(mut transform, velocity)| {
transform.translation += velocity.0 * dt;
});
}This helps when there are many entities and real work per entity. For a few hundred cheap updates, a plain loop is usually as fast. In a browser build everything runs on one thread, so a parallel iteration runs one item after another; see Web builds.
Pairs of entities#
iter_combinations_mut visits each pair once, which suits gravity, collisions and flocking:
fn attract(mut query: Query<(&Transform, &mut Velocity)>) {
let mut pairs = query.iter_combinations_mut();
while let Some([(a, mut va), (b, mut vb)]) = pairs.fetch_next() {
let d = b.translation - a.translation;
va.0 += d * 0.001;
vb.0 -= d * 0.001;
}
}Custom query types#
For queries with many parts, derive QueryData on a struct to name the fields:
use neo::ecs::query::QueryData;
#[derive(QueryData)]
#[query_data(mutable)]
struct EnemyQuery {
entity: Entity,
transform: &'static mut Transform,
health: &'static mut Health,
name: Option<&'static Name>,
}
fn tick(mut enemies: Query<EnemyQuery, With<Enemy>>) {
for mut enemy in &mut enemies {
enemy.transform.translation.y += 0.1;
enemy.health.0 += 1;
}
}Leave out mutable for a read-only query type. You can derive QueryFilter the same way for reusable filters.
Examples#
Run these from the engine core's workspace:
| Example | What it shows |
|---|---|
cargo run --example custom_query_param | QueryData and QueryFilter structs. |
cargo run --example iter_combinations | An n-body simulation over pairs of entities. |
cargo run --example parallel_query | par_iter_mut and batch sizes. |
cargo run --example fallible_params | Single, Option<Single> and Populated. |
cargo run --example contiguous_query | Reading components as contiguous slices. |