Skip to main content

contiguous_query/
contiguous_query.rs

1//! Demonstrates how contiguous queries work.
2//!
3//! Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example
4//! may be used for simd-operations, which may accelerate an algorithm.
5//!
6//! Contiguous iteration may be used for example via [`Query::contiguous_iter`], [`Query::contiguous_iter_mut`],
7//! both of which return an option which is only [`None`] when the query doesn't support contiguous
8//! iteration due to it not being dense (iteration happens on archetypes, not tables) or filters not being archetypal.
9//!
10//! For further documentation refer to:
11//! - [`Query::contiguous_iter`]
12//! - [`ContiguousQueryData`](`bevy::ecs::query::ContiguousQueryData`)
13//! - [`ArchetypeFilter`](`bevy::ecs::query::ArchetypeFilter`)
14
15use bevy::prelude::*;
16
17#[derive(Component)]
18/// When the value reaches 0.0 the entity dies
19pub struct Health(pub f32);
20
21#[derive(Component)]
22/// Each tick an entity will have it's health multiplied by the factor, which
23/// for a big amount of entities can be accelerated using contiguous queries
24pub struct HealthDecay(pub f32);
25
26fn apply_health_decay(mut query: Query<(&mut Health, &HealthDecay)>) {
27    // contiguous_iter_mut() would return None if query couldn't be iterated contiguously
28    for (mut health, decay) in query.contiguous_iter_mut().unwrap() {
29        // all data slices returned by component queries are the same size
30        assert!(health.len() == decay.len());
31        // we could also bypass change detection via bypass_change_detection() because we do not
32        // use it anyways.
33        for (health, decay) in health.iter_mut().zip(decay) {
34            health.0 *= decay.0;
35        }
36    }
37}
38
39fn finish_off_first(mut commands: Commands, mut query: Query<(Entity, &mut Health)>) {
40    if let Some((entity, mut health)) = query.iter_mut().next() {
41        health.0 -= 1.0;
42        if health.0 <= 0.0 {
43            commands.entity(entity).despawn();
44            println!("Finishing off {entity:?}");
45        }
46    }
47}
48
49fn main() {
50    App::new()
51        .add_plugins(DefaultPlugins)
52        .add_systems(Update, (apply_health_decay, finish_off_first).chain())
53        .add_systems(Startup, setup)
54        .run();
55}
56
57fn setup(mut commands: Commands) {
58    let mut i = 0;
59    commands.spawn_batch(std::iter::from_fn(move || {
60        i += 1;
61        if i == 10_000 {
62            None
63        } else {
64            Some((Health(i as f32 * 5.0), HealthDecay(0.9)))
65        }
66    }));
67}