bevy/crates/bevy_ecs/examples/change_detection.rs

119 lines
4.5 KiB
Rust
Raw Normal View History

use bevy_ecs::prelude::*;
use rand::Rng;
use std::ops::Deref;
// In this example we will simulate a population of entities. In every tick we will:
// 1. spawn a new entity with a certain possibility
// 2. age all entities
// 3. despawn entities with age > 2
//
// To demonstrate change detection, there are some console outputs based on changes in
// the EntityCounter resource and updated Age components
fn main() {
// Create a new empty World to hold our Entities, Components and Resources
let mut world = World::new();
// Add the counter resource to remember how many entities where spawned
world.insert_resource(EntityCounter { value: 0 });
// Create a new Schedule, which defines an execution strategy for Systems
let mut schedule = Schedule::default();
// Create a Stage to add to our Schedule. Each Stage in a schedule runs all of its systems
// before moving on to the next Stage
let mut update = SystemStage::parallel();
// Add systems to the Stage to execute our app logic
// We can label our systems to force a specific run-order between some of them
update.add_system(spawn_entities.label(SimulationSystem::Spawn));
update.add_system(print_counter_when_changed.after(SimulationSystem::Spawn));
update.add_system(age_all_entities.label(SimulationSystem::Age));
update.add_system(remove_old_entities.after(SimulationSystem::Age));
update.add_system(print_changed_entities.after(SimulationSystem::Age));
// Add the Stage with our systems to the Schedule
#[derive(StageLabel)]
struct Update;
schedule.add_stage(Update, update);
// Simulate 10 frames in our world
for iteration in 1..=10 {
println!("Simulating frame {}/10", iteration);
schedule.run(&mut world);
}
}
// This struct will be used as a Resource keeping track of the total amount of spawned entities
Make `Resource` trait opt-in, requiring `#[derive(Resource)]` V2 (#5577) *This PR description is an edited copy of #5007, written by @alice-i-cecile.* # Objective Follow-up to https://github.com/bevyengine/bevy/pull/2254. The `Resource` trait currently has a blanket implementation for all types that meet its bounds. While ergonomic, this results in several drawbacks: * it is possible to make confusing, silent mistakes such as inserting a function pointer (Foo) rather than a value (Foo::Bar) as a resource * it is challenging to discover if a type is intended to be used as a resource * we cannot later add customization options (see the [RFC](https://github.com/bevyengine/rfcs/blob/main/rfcs/27-derive-component.md) for the equivalent choice for Component). * dependencies can use the same Rust type as a resource in invisibly conflicting ways * raw Rust types used as resources cannot preserve privacy appropriately, as anyone able to access that type can read and write to internal values * we cannot capture a definitive list of possible resources to display to users in an editor ## Notes to reviewers * Review this commit-by-commit; there's effectively no back-tracking and there's a lot of churn in some of these commits. *ira: My commits are not as well organized :')* * I've relaxed the bound on Local to Send + Sync + 'static: I don't think these concerns apply there, so this can keep things simple. Storing e.g. a u32 in a Local is fine, because there's a variable name attached explaining what it does. * I think this is a bad place for the Resource trait to live, but I've left it in place to make reviewing easier. IMO that's best tackled with https://github.com/bevyengine/bevy/issues/4981. ## Changelog `Resource` is no longer automatically implemented for all matching types. Instead, use the new `#[derive(Resource)]` macro. ## Migration Guide Add `#[derive(Resource)]` to all types you are using as a resource. If you are using a third party type as a resource, wrap it in a tuple struct to bypass orphan rules. Consider deriving `Deref` and `DerefMut` to improve ergonomics. `ClearColor` no longer implements `Component`. Using `ClearColor` as a component in 0.8 did nothing. Use the `ClearColorConfig` in the `Camera3d` and `Camera2d` components instead. Co-authored-by: Alice <alice.i.cecile@gmail.com> Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com> Co-authored-by: devil-ira <justthecooldude@gmail.com> Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-08 21:36:35 +00:00
#[derive(Debug, Resource)]
struct EntityCounter {
pub value: i32,
}
// This struct represents a Component and holds the age in frames of the entity it gets assigned to
#[derive(Component, Default, Debug)]
struct Age {
frames: i32,
}
// System labels to enforce a run order of our systems
#[derive(SystemLabel, Debug, Clone, PartialEq, Eq, Hash)]
enum SimulationSystem {
Spawn,
Age,
}
// This system randomly spawns a new entity in 60% of all frames
// The entity will start with an age of 0 frames
// If an entity gets spawned, we increase the counter in the EntityCounter resource
fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {
if rand::thread_rng().gen_bool(0.6) {
Accept Bundles for insert and remove. Deprecate insert/remove_bundle (#6039) # Objective Take advantage of the "impl Bundle for Component" changes in #2975 / add the follow up changes discussed there. ## Solution - Change `insert` and `remove` to accept a Bundle instead of a Component (for both Commands and World) - Deprecate `insert_bundle`, `remove_bundle`, and `remove_bundle_intersection` - Add `remove_intersection` --- ## Changelog - Change `insert` and `remove` now accept a Bundle instead of a Component (for both Commands and World) - `insert_bundle` and `remove_bundle` are deprecated ## Migration Guide Replace `insert_bundle` with `insert`: ```rust // Old (0.8) commands.spawn().insert_bundle(SomeBundle::default()); // New (0.9) commands.spawn().insert(SomeBundle::default()); ``` Replace `remove_bundle` with `remove`: ```rust // Old (0.8) commands.entity(some_entity).remove_bundle::<SomeBundle>(); // New (0.9) commands.entity(some_entity).remove::<SomeBundle>(); ``` Replace `remove_bundle_intersection` with `remove_intersection`: ```rust // Old (0.8) world.entity_mut(some_entity).remove_bundle_intersection::<SomeBundle>(); // New (0.9) world.entity_mut(some_entity).remove_intersection::<SomeBundle>(); ``` Consider consolidating as many operations as possible to improve ergonomics and cut down on archetype moves: ```rust // Old (0.8) commands.spawn() .insert_bundle(SomeBundle::default()) .insert(SomeComponent); // New (0.9) - Option 1 commands.spawn().insert(( SomeBundle::default(), SomeComponent, )) // New (0.9) - Option 2 commands.spawn_bundle(( SomeBundle::default(), SomeComponent, )) ``` ## Next Steps Consider changing `spawn` to accept a bundle and deprecate `spawn_bundle`.
2022-09-21 21:47:53 +00:00
let entity_id = commands.spawn_bundle(Age::default()).id();
println!(" spawning {:?}", entity_id);
entity_counter.value += 1;
}
}
// This system prints out changes in our entity collection
// For every entity that just got the Age component added we will print that it's the
// entities first birthday. These entities where spawned in the previous frame.
// For every entity with a changed Age component we will print the new value.
// In this example the Age component is changed in every frame, so we don't actually
// need the `Changed` here, but it is still used for the purpose of demonstration.
fn print_changed_entities(
entity_with_added_component: Query<Entity, Added<Age>>,
entity_with_mutated_component: Query<(Entity, &Age), Changed<Age>>,
) {
for entity in &entity_with_added_component {
println!(" {:?} has it's first birthday!", entity);
}
for (entity, value) in &entity_with_mutated_component {
println!(" {:?} is now {:?} frames old", entity, value);
}
}
// This system iterates over all entities and increases their age in every frame
fn age_all_entities(mut entities: Query<&mut Age>) {
for mut age in &mut entities {
age.frames += 1;
}
}
// This system iterates over all entities in every frame and despawns entities older than 2 frames
fn remove_old_entities(mut commands: Commands, entities: Query<(Entity, &Age)>) {
for (entity, age) in &entities {
if age.frames > 2 {
println!(" despawning {:?} due to age > 2", entity);
commands.entity(entity).despawn();
}
}
}
// This system will print the new counter value everytime it was changed since
// the last execution of the system.
fn print_counter_when_changed(entity_counter: Res<EntityCounter>) {
if entity_counter.is_changed() {
println!(
" total number of entities spawned: {}",
entity_counter.deref().value
);
}
}