Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

run a system from a command #2234

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,10 @@ path = "examples/ecs/state.rs"
name = "system_chaining"
path = "examples/ecs/system_chaining.rs"

[[example]]
name = "system_command"
path = "examples/ecs/system_command.rs"

[[example]]
name = "system_param"
path = "examples/ecs/system_param.rs"
Expand Down
38 changes: 38 additions & 0 deletions crates/bevy_ecs/src/system/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use bevy_utils::tracing::debug;
pub use command_queue::CommandQueue;
use std::marker::PhantomData;

use super::{IntoSystem, System};

/// A [`World`] mutation.
pub trait Command: Send + Sync + 'static {
fn write(self, world: &mut World);
Expand Down Expand Up @@ -152,6 +154,30 @@ impl<'a> Commands<'a> {
});
}

/// Run a one-off [`System`].
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # struct MyComponent;
///
/// # fn my_system(_components: Query<&MyComponent>) {}
///
/// # fn main_system(mut commands: Commands) {
/// // Can take a standard system function
/// commands.run_system(my_system);
/// // Can take a closure system
/// commands.run_system(|query: Query<&MyComponent>| {
/// println!("count: {}", query.iter().len());
/// });
/// # }
/// # main_system.system();
/// ```
pub fn run_system<Params>(&mut self, system: impl IntoSystem<(), (), Params>) {
self.queue.push(RunSystem {
system: Box::new(system.system()),
});
}

/// Adds a command directly to the command list.
pub fn add<C: Command>(&mut self, command: C) {
self.queue.push(command);
Expand Down Expand Up @@ -387,6 +413,18 @@ impl<T: Component> Command for RemoveResource<T> {
}
}

pub struct RunSystem {
pub system: Box<dyn System<In = (), Out = ()>>,
}

impl Command for RunSystem {
fn write(mut self, world: &mut World) {
self.system.initialize(world);
self.system.run((), world);
self.system.apply_buffers(world);
}
}

#[cfg(test)]
#[allow(clippy::float_cmp, clippy::approx_constant)]
mod tests {
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ Example | File | Description
`startup_system` | [`ecs/startup_system.rs`](./ecs/startup_system.rs) | Demonstrates a startup system (one that runs once when the app starts up)
`state` | [`ecs/state.rs`](./ecs/state.rs) | Illustrates how to use States to control transitioning from a Menu state to an InGame state
`system_chaining` | [`ecs/system_chaining.rs`](./ecs/system_chaining.rs) | Chain two systems together, specifying a return type in a system (such as `Result`)
`system_command` | [`ecs/system_command.rs`](./ecs/system_command.rs) | Run a system from a command
`system_param` | [`ecs/system_param.rs`](./ecs/system_param.rs) | Illustrates creating custom system parameters with `SystemParam`
`system_sets` | [`ecs/system_sets.rs`](./ecs/system_sets.rs) | Shows `SystemSet` use along with run criterion
`timers` | [`ecs/timers.rs`](./ecs/timers.rs) | Illustrates ticking `Timer` resources inside systems and handling their state
Expand Down
38 changes: 38 additions & 0 deletions examples/ecs/system_command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use bevy::{prelude::*, utils::Duration};

/// This example triggers a system from a command
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(spawn)
.add_system(trigger_sync)
.run();
}

pub struct Player;

/// Spawn some players to sync
fn spawn(mut commands: Commands) {
commands.spawn().insert(Player);
commands.spawn().insert(Player);
Comment on lines +16 to +17
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at this makes it seem like a copy paste error in my head haha 😅
Could we change this to be like for _ in 0..5 or something similar?

Copy link
Member Author

@mockersf mockersf May 22, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a copy paste! from

commands.spawn().insert(Player);
commands.spawn().insert(Player);
commands.spawn().insert(Player);

But I removed one just to be different

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still prefer the for - in syntax, but I guess I'm ok with how it is.

}

fn trigger_sync(mut commands: Commands, mut last_sync: Local<f64>, time: Res<Time>) {
if time.seconds_since_startup() - *last_sync > 5.0 {
commands
.run_system(sync_system.config(|config| config.1 = Some(time.time_since_startup())));
*last_sync = time.seconds_since_startup();
}
}

/// As this system is run through a command, it will run at the end of the current stage.
fn sync_system(players: Query<&Player>, since_startup: Local<Duration>) {
for _player in players.iter() {
// do the sync
}
info!(
"synced: {} players ({:?})",
players.iter().len(),
*since_startup
);
}