|
| 1 | +//! Entities generally don't exist in isolation. Instead, they are related to other entities in various ways. |
| 2 | +//! While Bevy comes with a built-in [`ChildOf`]/[`Children`] relationship |
| 3 | +//! (which enables transform and visibility propagation), |
| 4 | +//! you can define your own relationships using components. |
| 5 | +//! |
| 6 | +//! We can define a custom relationship by creating two components: |
| 7 | +//! one to store the relationship itself, and another to keep track of the reverse relationship. |
| 8 | +//! Bevy's [`ChildOf`] component implements the [`Relationship`] trait, serving as the source of truth, |
| 9 | +//! while the [`Children`] component implements the [`RelationshipTarget`] trait and is used to accelerate traversals down the hierarchy. |
| 10 | +//! |
| 11 | +//! In this example we're creating a [`Targeting`]/[`TargetedBy`] relationship, |
| 12 | +//! demonstrating how you might model units which target a single unit in combat. |
| 13 | +
|
| 14 | +use bevy::ecs::entity::hash_set::EntityHashSet; |
| 15 | +use bevy::ecs::system::RunSystemOnce; |
| 16 | +use bevy::prelude::*; |
| 17 | + |
| 18 | +/// The entity that this entity is targeting. |
| 19 | +/// |
| 20 | +/// This is the source of truth for the relationship, |
| 21 | +/// and can be modified directly to change the target. |
| 22 | +#[derive(Component, Debug)] |
| 23 | +#[relationship(relationship_target = TargetedBy)] |
| 24 | +struct Targeting(Entity); |
| 25 | + |
| 26 | +/// All entities that are targeting this entity. |
| 27 | +/// |
| 28 | +/// This component is updated reactively using the component hooks introduced by deriving |
| 29 | +/// the [`Relationship`] trait. We should not modify this component directly, |
| 30 | +/// but can safely read its field. In a larger project, we could enforce this through the use of |
| 31 | +/// private fields and public getters. |
| 32 | +#[derive(Component, Debug)] |
| 33 | +#[relationship_target(relationship = Targeting)] |
| 34 | +struct TargetedBy(Vec<Entity>); |
| 35 | + |
| 36 | +fn main() { |
| 37 | + // Operating on a raw `World` and running systems one at a time |
| 38 | + // is great for writing tests and teaching abstract concepts! |
| 39 | + let mut world = World::new(); |
| 40 | + |
| 41 | + // We're going to spawn a few entities and relate them to each other in a complex way. |
| 42 | + // To start, Bob will target Alice, Charlie will target Bob, |
| 43 | + // and Alice will target Charlie. This creates a loop in the relationship graph. |
| 44 | + // |
| 45 | + // Then, we'll spawn Devon, who will target Charlie, |
| 46 | + // creating a more complex graph with a branching structure. |
| 47 | + fn spawning_entities_with_relationships(mut commands: Commands) { |
| 48 | + // Calling .id() after spawning an entity will return the `Entity` identifier of the spawned entity, |
| 49 | + // even though the entity itself is not yet instantiated in the world. |
| 50 | + // This works because Commands will reserve the entity ID before actually spawning the entity, |
| 51 | + // through the use of atomic counters. |
| 52 | + let alice = commands.spawn(Name::new("Alice")).id(); |
| 53 | + // Relations are just components, so we can add them into the bundle that we're spawning. |
| 54 | + let bob = commands.spawn((Name::new("Bob"), Targeting(alice))).id(); |
| 55 | + |
| 56 | + // The `with_related` helper method on `EntityCommands` can be used to add relations in a more ergonomic way. |
| 57 | + let charlie = commands |
| 58 | + .spawn((Name::new("Charlie"), Targeting(bob))) |
| 59 | + // The `with_related` method will automatically add the `Targeting` component to any entities spawned within the closure, |
| 60 | + // targeting the entity that we're calling `with_related` on. |
| 61 | + .with_related::<Targeting>(|related_spawner_commands| { |
| 62 | + // We could spawn multiple entities here, and they would all target `charlie`. |
| 63 | + related_spawner_commands.spawn(Name::new("Devon")); |
| 64 | + }) |
| 65 | + .id(); |
| 66 | + |
| 67 | + // Simply inserting the `Targeting` component will automatically create and update the `TargetedBy` component on the target entity. |
| 68 | + // We can do this at any point; not just when the entity is spawned. |
| 69 | + commands.entity(alice).insert(Targeting(charlie)); |
| 70 | + } |
| 71 | + |
| 72 | + world |
| 73 | + .run_system_once(spawning_entities_with_relationships) |
| 74 | + .unwrap(); |
| 75 | + |
| 76 | + fn debug_relationships( |
| 77 | + // Not all of our entities are targeted by something, so we use `Option` in our query to handle this case. |
| 78 | + relations_query: Query<(&Name, &Targeting, Option<&TargetedBy>)>, |
| 79 | + name_query: Query<&Name>, |
| 80 | + ) { |
| 81 | + let mut relationships = String::new(); |
| 82 | + |
| 83 | + for (name, targeting, maybe_targeted_by) in relations_query.iter() { |
| 84 | + let targeting_name = name_query.get(targeting.0).unwrap(); |
| 85 | + let targeted_by_string = if let Some(targeted_by) = maybe_targeted_by { |
| 86 | + let mut vec_of_names = Vec::<&Name>::new(); |
| 87 | + |
| 88 | + for entity in &targeted_by.0 { |
| 89 | + let name = name_query.get(*entity).unwrap(); |
| 90 | + vec_of_names.push(name); |
| 91 | + } |
| 92 | + |
| 93 | + // Convert this to a nice string for printing. |
| 94 | + let vec_of_str: Vec<&str> = vec_of_names.iter().map(|name| name.as_str()).collect(); |
| 95 | + vec_of_str.join(", ") |
| 96 | + } else { |
| 97 | + "nobody".to_string() |
| 98 | + }; |
| 99 | + |
| 100 | + relationships.push_str(&format!( |
| 101 | + "{name} is targeting {targeting_name}, and is targeted by {targeted_by_string}\n", |
| 102 | + )); |
| 103 | + } |
| 104 | + |
| 105 | + println!("{}", relationships); |
| 106 | + } |
| 107 | + |
| 108 | + world.run_system_once(debug_relationships).unwrap(); |
| 109 | + |
| 110 | + // Demonstrates how to correctly mutate relationships. |
| 111 | + // Relationship components are immutable! We can't query for the `Targeting` component mutably and modify it directly, |
| 112 | + // but we can insert a new `Targeting` component to replace the old one. |
| 113 | + // This allows the hooks on the `Targeting` component to update the `TargetedBy` component correctly. |
| 114 | + // The `TargetedBy` component will be updated automatically! |
| 115 | + fn mutate_relationships(name_query: Query<(Entity, &Name)>, mut commands: Commands) { |
| 116 | + // Let's find Devon by doing a linear scan of the entity names. |
| 117 | + let devon = name_query |
| 118 | + .iter() |
| 119 | + .find(|(_entity, name)| name.as_str() == "Devon") |
| 120 | + .unwrap() |
| 121 | + .0; |
| 122 | + |
| 123 | + let alice = name_query |
| 124 | + .iter() |
| 125 | + .find(|(_entity, name)| name.as_str() == "Alice") |
| 126 | + .unwrap() |
| 127 | + .0; |
| 128 | + |
| 129 | + println!("Making Devon target Alice.\n"); |
| 130 | + commands.entity(devon).insert(Targeting(alice)); |
| 131 | + } |
| 132 | + |
| 133 | + world.run_system_once(mutate_relationships).unwrap(); |
| 134 | + world.run_system_once(debug_relationships).unwrap(); |
| 135 | + |
| 136 | + // Systems can return errors, |
| 137 | + // which can be used to signal that something went wrong during the system's execution. |
| 138 | + #[derive(Debug)] |
| 139 | + #[expect( |
| 140 | + dead_code, |
| 141 | + reason = "Rust considers types that are only used by their debug trait as dead code." |
| 142 | + )] |
| 143 | + struct TargetingCycle { |
| 144 | + initial_entity: Entity, |
| 145 | + visited: EntityHashSet, |
| 146 | + } |
| 147 | + |
| 148 | + /// Bevy's relationships come with all sorts of useful methods for traversal. |
| 149 | + /// Here, we're going to look for cycles using a depth-first search. |
| 150 | + fn check_for_cycles( |
| 151 | + // We want to check every entity for cycles |
| 152 | + query_to_check: Query<Entity, With<Targeting>>, |
| 153 | + // Fetch the names for easier debugging. |
| 154 | + name_query: Query<&Name>, |
| 155 | + // The targeting_query allows us to traverse the relationship graph. |
| 156 | + targeting_query: Query<&Targeting>, |
| 157 | + ) -> Result<(), TargetingCycle> { |
| 158 | + for initial_entity in query_to_check.iter() { |
| 159 | + let mut visited = EntityHashSet::new(); |
| 160 | + let mut targeting_name = name_query.get(initial_entity).unwrap().clone(); |
| 161 | + println!("Checking for cycles starting at {targeting_name}",); |
| 162 | + |
| 163 | + // There's all sorts of methods like this; check the `Query` docs for more! |
| 164 | + // This would also be easy to do by just manually checking the `Targeting` component, |
| 165 | + // and calling `query.get(targeted_entity)` on the entity that it targets in a loop. |
| 166 | + for targeting in targeting_query.iter_ancestors(initial_entity) { |
| 167 | + let target_name = name_query.get(targeting).unwrap(); |
| 168 | + println!("{targeting_name} is targeting {target_name}",); |
| 169 | + targeting_name = target_name.clone(); |
| 170 | + |
| 171 | + if !visited.insert(targeting) { |
| 172 | + return Err(TargetingCycle { |
| 173 | + initial_entity, |
| 174 | + visited, |
| 175 | + }); |
| 176 | + } |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + // If we've checked all the entities and haven't found a cycle, we're good! |
| 181 | + Ok(()) |
| 182 | + } |
| 183 | + |
| 184 | + // Calling `world.run_system_once` on systems which return Results gives us two layers of errors: |
| 185 | + // the first checks if running the system failed, and the second checks if the system itself returned an error. |
| 186 | + // We're unwrapping the first, but checking the output of the system itself. |
| 187 | + let cycle_result = world.run_system_once(check_for_cycles).unwrap(); |
| 188 | + println!("{cycle_result:?} \n"); |
| 189 | + // We deliberately introduced a cycle during spawning! |
| 190 | + assert!(cycle_result.is_err()); |
| 191 | + |
| 192 | + // Now, let's demonstrate removing relationships and break the cycle. |
| 193 | + fn untarget(mut commands: Commands, name_query: Query<(Entity, &Name)>) { |
| 194 | + // Let's find Charlie by doing a linear scan of the entity names. |
| 195 | + let charlie = name_query |
| 196 | + .iter() |
| 197 | + .find(|(_entity, name)| name.as_str() == "Charlie") |
| 198 | + .unwrap() |
| 199 | + .0; |
| 200 | + |
| 201 | + // We can remove the `Targeting` component to remove the relationship |
| 202 | + // and break the cycle we saw earlier. |
| 203 | + println!("Removing Charlie's targeting relationship.\n"); |
| 204 | + commands.entity(charlie).remove::<Targeting>(); |
| 205 | + } |
| 206 | + |
| 207 | + world.run_system_once(untarget).unwrap(); |
| 208 | + world.run_system_once(debug_relationships).unwrap(); |
| 209 | + // Cycle free! |
| 210 | + let cycle_result = world.run_system_once(check_for_cycles).unwrap(); |
| 211 | + println!("{cycle_result:?} \n"); |
| 212 | + assert!(cycle_result.is_ok()); |
| 213 | +} |
0 commit comments