custom_query_param/
custom_query_param.rs

1//! This example illustrates the usage of the [`QueryData`] derive macro, which allows
2//! defining custom query and filter types.
3//!
4//! While regular tuple queries work great in most of simple scenarios, using custom queries
5//! declared as named structs can bring the following advantages:
6//! - They help to avoid destructuring or using `q.0, q.1, ...` access pattern.
7//! - Adding, removing components or changing items order with structs greatly reduces maintenance
8//!   burden, as you don't need to update statements that destructure tuples, care about order
9//!   of elements, etc. Instead, you can just add or remove places where a certain element is used.
10//! - Named structs enable the composition pattern, that makes query types easier to re-use.
11//! - You can bypass the limit of 15 components that exists for query tuples.
12//!
13//! For more details on the [`QueryData`] derive macro, see the trait documentation.
14
15use bevy::{
16    ecs::query::{QueryData, QueryFilter},
17    prelude::*,
18};
19use std::fmt::Debug;
20
21fn main() {
22    App::new()
23        .add_systems(Startup, spawn)
24        .add_systems(
25            Update,
26            (
27                print_components_read_only,
28                print_components_iter_mut,
29                print_components_iter,
30                print_components_tuple,
31            )
32                .chain(),
33        )
34        .run();
35}
36
37#[derive(Component, Debug)]
38struct ComponentA;
39#[derive(Component, Debug)]
40struct ComponentB;
41#[derive(Component, Debug)]
42struct ComponentC;
43#[derive(Component, Debug)]
44struct ComponentD;
45#[derive(Component, Debug)]
46struct ComponentZ;
47
48#[derive(QueryData)]
49#[query_data(derive(Debug))]
50struct ReadOnlyCustomQuery<T: Component + Debug, P: Component + Debug> {
51    entity: Entity,
52    a: &'static ComponentA,
53    b: Option<&'static ComponentB>,
54    nested: NestedQuery,
55    optional_nested: Option<NestedQuery>,
56    optional_tuple: Option<(&'static ComponentB, &'static ComponentZ)>,
57    generic: GenericQuery<T, P>,
58    empty: EmptyQuery,
59}
60
61fn print_components_read_only(
62    query: Query<
63        ReadOnlyCustomQuery<ComponentC, ComponentD>,
64        CustomQueryFilter<ComponentC, ComponentD>,
65    >,
66) {
67    println!("Print components (read_only):");
68    for e in &query {
69        println!("Entity: {}", e.entity);
70        println!("A: {:?}", e.a);
71        println!("B: {:?}", e.b);
72        println!("Nested: {:?}", e.nested);
73        println!("Optional nested: {:?}", e.optional_nested);
74        println!("Optional tuple: {:?}", e.optional_tuple);
75        println!("Generic: {:?}", e.generic);
76    }
77    println!();
78}
79
80/// If you are going to mutate the data in a query, you must mark it with the `mutable` attribute.
81///
82/// The [`QueryData`] derive macro will still create a read-only version, which will be have `ReadOnly`
83/// suffix.
84/// Note: if you want to use derive macros with read-only query variants, you need to pass them with
85/// using the `derive` attribute.
86#[derive(QueryData)]
87#[query_data(mutable, derive(Debug))]
88struct CustomQuery<T: Component + Debug, P: Component + Debug> {
89    entity: Entity,
90    a: &'static mut ComponentA,
91    b: Option<&'static mut ComponentB>,
92    nested: NestedQuery,
93    optional_nested: Option<NestedQuery>,
94    optional_tuple: Option<(NestedQuery, &'static mut ComponentZ)>,
95    generic: GenericQuery<T, P>,
96    empty: EmptyQuery,
97}
98
99// This is a valid query as well, which would iterate over every entity.
100#[derive(QueryData)]
101#[query_data(derive(Debug))]
102struct EmptyQuery {
103    empty: (),
104}
105
106#[derive(QueryData)]
107#[query_data(derive(Debug))]
108struct NestedQuery {
109    c: &'static ComponentC,
110    d: Option<&'static ComponentD>,
111}
112
113#[derive(QueryData)]
114#[query_data(derive(Debug))]
115struct GenericQuery<T: Component, P: Component> {
116    generic: (&'static T, &'static P),
117}
118
119#[derive(QueryFilter)]
120struct CustomQueryFilter<T: Component, P: Component> {
121    _c: With<ComponentC>,
122    _d: With<ComponentD>,
123    _or: Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
124    _generic_tuple: (With<T>, With<P>),
125}
126
127fn spawn(mut commands: Commands) {
128    commands.spawn((ComponentA, ComponentB, ComponentC, ComponentD));
129}
130
131fn print_components_iter_mut(
132    mut query: Query<
133        CustomQuery<ComponentC, ComponentD>,
134        CustomQueryFilter<ComponentC, ComponentD>,
135    >,
136) {
137    println!("Print components (iter_mut):");
138    for e in &mut query {
139        // Re-declaring the variable to illustrate the type of the actual iterator item.
140        let e: CustomQueryItem<'_, _, _> = e;
141        println!("Entity: {}", e.entity);
142        println!("A: {:?}", e.a);
143        println!("B: {:?}", e.b);
144        println!("Optional nested: {:?}", e.optional_nested);
145        println!("Optional tuple: {:?}", e.optional_tuple);
146        println!("Nested: {:?}", e.nested);
147        println!("Generic: {:?}", e.generic);
148    }
149    println!();
150}
151
152fn print_components_iter(
153    query: Query<CustomQuery<ComponentC, ComponentD>, CustomQueryFilter<ComponentC, ComponentD>>,
154) {
155    println!("Print components (iter):");
156    for e in &query {
157        // Re-declaring the variable to illustrate the type of the actual iterator item.
158        let e: CustomQueryReadOnlyItem<'_, _, _> = e;
159        println!("Entity: {}", e.entity);
160        println!("A: {:?}", e.a);
161        println!("B: {:?}", e.b);
162        println!("Nested: {:?}", e.nested);
163        println!("Generic: {:?}", e.generic);
164    }
165    println!();
166}
167
168type NestedTupleQuery<'w> = (&'w ComponentC, &'w ComponentD);
169type GenericTupleQuery<'w, T, P> = (&'w T, &'w P);
170
171fn print_components_tuple(
172    query: Query<
173        (
174            Entity,
175            &ComponentA,
176            &ComponentB,
177            NestedTupleQuery,
178            GenericTupleQuery<ComponentC, ComponentD>,
179        ),
180        (
181            With<ComponentC>,
182            With<ComponentD>,
183            Or<(Added<ComponentC>, Changed<ComponentD>, Without<ComponentZ>)>,
184        ),
185    >,
186) {
187    println!("Print components (tuple):");
188    for (entity, a, b, nested, (generic_c, generic_d)) in &query {
189        println!("Entity: {entity}");
190        println!("A: {a:?}");
191        println!("B: {b:?}");
192        println!("Nested: {:?} {:?}", nested.0, nested.1);
193        println!("Generic: {generic_c:?} {generic_d:?}");
194    }
195}