bevy/examples/ecs/generic_system.rs

92 lines
3.1 KiB
Rust
Raw Normal View History

use bevy::{ecs::component::Component, prelude::*};
/// Generic types allow us to reuse logic across many related systems,
/// allowing us to specialize our function's behavior based on which type (or types) are passed in.
///
/// This is commonly useful for working on related components or resources,
/// where we want to have unique types for querying purposes but want them all to work the same way.
/// This is particularly powerful when combined with user-defined traits to add more functionality to these related types.
/// Remember to insert a specialized copy of the system into the schedule for each type that you want to operate on!
///
/// For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html>
/// or <https://doc.rust-lang.org/rust-by-example/generics.html>
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum AppState {
MainMenu,
InGame,
}
#[derive(Component)]
struct TextToPrint(String);
bevy_derive: Add derives for `Deref` and `DerefMut` (#4328) # Objective A common pattern in Rust is the [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html). This is an especially useful pattern in Bevy as it allows us to give common/foreign types different semantics (such as allowing it to implement `Component` or `FromWorld`) or to simply treat them as a "new type" (clever). For example, it allows us to wrap a common `Vec<String>` and do things like: ```rust #[derive(Component)] struct Items(Vec<String>); fn give_sword(query: Query<&mut Items>) { query.single_mut().0.push(String::from("Flaming Poisoning Raging Sword of Doom")); } ``` > We could then define another struct that wraps `Vec<String>` without anything clashing in the query. However, one of the worst parts of this pattern is the ugly `.0` we have to write in order to access the type we actually care about. This is why people often implement `Deref` and `DerefMut` in order to get around this. Since it's such a common pattern, especially for Bevy, it makes sense to add a derive macro to automatically add those implementations. ## Solution Added a derive macro for `Deref` and another for `DerefMut` (both exported into the prelude). This works on all structs (including tuple structs) as long as they only contain a single field: ```rust #[derive(Deref)] struct Foo(String); #[derive(Deref, DerefMut)] struct Bar { name: String, } ``` This allows us to then remove that pesky `.0`: ```rust #[derive(Component, Deref, DerefMut)] struct Items(Vec<String>); fn give_sword(query: Query<&mut Items>) { query.single_mut().push(String::from("Flaming Poisoning Raging Sword of Doom")); } ``` ### Alternatives There are other alternatives to this such as by using the [`derive_more`](https://crates.io/crates/derive_more) crate. However, it doesn't seem like we need an entire crate just yet since we only need `Deref` and `DerefMut` (for now). ### Considerations One thing to consider is that the Rust std library recommends _not_ using `Deref` and `DerefMut` for things like this: "`Deref` should only be implemented for smart pointers to avoid confusion" ([reference](https://doc.rust-lang.org/std/ops/trait.Deref.html)). Personally, I believe it makes sense to use it in the way described above, but others may disagree. ### Additional Context Discord: https://discord.com/channels/691052431525675048/692572690833473578/956648422163746827 (controversiality discussed [here](https://discord.com/channels/691052431525675048/692572690833473578/956711911481835630)) --- ## Changelog - Add `Deref` derive macro (exported to prelude) - Add `DerefMut` derive macro (exported to prelude) - Updated most newtypes in examples to use one or both derives Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-03-29 02:10:06 +00:00
#[derive(Component, Deref, DerefMut)]
struct PrinterTick(bevy::prelude::Timer);
#[derive(Component)]
struct MenuClose;
#[derive(Component)]
struct LevelUnload;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_state(AppState::MainMenu)
.add_startup_system(setup_system)
.add_system(print_text_system)
.add_system_set(
SystemSet::on_update(AppState::MainMenu).with_system(transition_to_in_game_system),
)
// add the cleanup systems
.add_system_set(
// Pass in the types your system should operate on using the ::<T> (turbofish) syntax
SystemSet::on_exit(AppState::MainMenu).with_system(cleanup_system::<MenuClose>),
)
.add_system_set(
SystemSet::on_exit(AppState::InGame).with_system(cleanup_system::<LevelUnload>),
)
.run();
}
fn setup_system(mut commands: Commands) {
commands
.spawn()
.insert(PrinterTick(bevy::prelude::Timer::from_seconds(1.0, true)))
.insert(TextToPrint(
"I will print until you press space.".to_string(),
))
.insert(MenuClose);
commands
.spawn()
.insert(PrinterTick(bevy::prelude::Timer::from_seconds(1.0, true)))
.insert(TextToPrint("I will always print".to_string()))
.insert(LevelUnload);
}
fn print_text_system(time: Res<Time>, mut query: Query<(&mut PrinterTick, &TextToPrint)>) {
for (mut timer, text) in query.iter_mut() {
bevy_derive: Add derives for `Deref` and `DerefMut` (#4328) # Objective A common pattern in Rust is the [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html). This is an especially useful pattern in Bevy as it allows us to give common/foreign types different semantics (such as allowing it to implement `Component` or `FromWorld`) or to simply treat them as a "new type" (clever). For example, it allows us to wrap a common `Vec<String>` and do things like: ```rust #[derive(Component)] struct Items(Vec<String>); fn give_sword(query: Query<&mut Items>) { query.single_mut().0.push(String::from("Flaming Poisoning Raging Sword of Doom")); } ``` > We could then define another struct that wraps `Vec<String>` without anything clashing in the query. However, one of the worst parts of this pattern is the ugly `.0` we have to write in order to access the type we actually care about. This is why people often implement `Deref` and `DerefMut` in order to get around this. Since it's such a common pattern, especially for Bevy, it makes sense to add a derive macro to automatically add those implementations. ## Solution Added a derive macro for `Deref` and another for `DerefMut` (both exported into the prelude). This works on all structs (including tuple structs) as long as they only contain a single field: ```rust #[derive(Deref)] struct Foo(String); #[derive(Deref, DerefMut)] struct Bar { name: String, } ``` This allows us to then remove that pesky `.0`: ```rust #[derive(Component, Deref, DerefMut)] struct Items(Vec<String>); fn give_sword(query: Query<&mut Items>) { query.single_mut().push(String::from("Flaming Poisoning Raging Sword of Doom")); } ``` ### Alternatives There are other alternatives to this such as by using the [`derive_more`](https://crates.io/crates/derive_more) crate. However, it doesn't seem like we need an entire crate just yet since we only need `Deref` and `DerefMut` (for now). ### Considerations One thing to consider is that the Rust std library recommends _not_ using `Deref` and `DerefMut` for things like this: "`Deref` should only be implemented for smart pointers to avoid confusion" ([reference](https://doc.rust-lang.org/std/ops/trait.Deref.html)). Personally, I believe it makes sense to use it in the way described above, but others may disagree. ### Additional Context Discord: https://discord.com/channels/691052431525675048/692572690833473578/956648422163746827 (controversiality discussed [here](https://discord.com/channels/691052431525675048/692572690833473578/956711911481835630)) --- ## Changelog - Add `Deref` derive macro (exported to prelude) - Add `DerefMut` derive macro (exported to prelude) - Updated most newtypes in examples to use one or both derives Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-03-29 02:10:06 +00:00
if timer.tick(time.delta()).just_finished() {
info!("{}", text.0);
}
}
}
fn transition_to_in_game_system(
mut state: ResMut<State<AppState>>,
keyboard_input: Res<Input<KeyCode>>,
) {
if keyboard_input.pressed(KeyCode::Space) {
state.set(AppState::InGame).unwrap();
}
}
// Type arguments on functions come after the function name, but before ordinary arguments.
// Here, the `Component` trait is a trait bound on T, our generic type
fn cleanup_system<T: Component>(mut commands: Commands, query: Query<Entity, With<T>>) {
for e in query.iter() {
commands.entity(e).despawn_recursive();
}
}