Skip to main content

naia_bevy_shared/
world_op_command.rs

1//! Generic `WorldOpCommand<F>` — collapses the boilerplate of "queue a
2//! Bevy `Command` that runs with `&mut World`" used by every naia bevy
3//! adapter Commands extension.
4//!
5//! Before this helper, every world-mutating Commands extension method
6//! defined its own one-shot `Command` struct (e.g.
7//! `ConfigureReplicationCommand`, `ReplicateResourceCommand`,
8//! `RemoveReplicatedResourceCommand`, etc.) with the same shape:
9//!
10//! ```ignore
11//! struct FooCommand { ... }
12//! impl Command for FooCommand {
13//!     fn apply(self, world: &mut World) {
14//!         world.resource_scope(|world, mut server| { ... });
15//!     }
16//! }
17//! ```
18//!
19//! That's a lot of repeated structure for what is, in essence, "queue
20//! this closure to run with `&mut World`." With `WorldOpCommand`:
21//!
22//! ```ignore
23//! commands.queue(WorldOpCommand::new(move |world| {
24//!     world.resource_scope::<ServerImpl, _>(|world, mut server| { ... });
25//! }));
26//! ```
27//!
28//! Trade-off: the generic over `F` means each call site instantiates
29//! its own concrete type. Small compile-time cost, big readability win
30//! (no more per-operation Command struct + Command impl).
31
32use bevy_ecs::system::Command;
33use bevy_ecs::world::World;
34
35/// A Bevy `Command` whose `apply` body is an arbitrary `FnOnce(&mut World)`.
36///
37/// Use this when you need to run code with `&mut World` deferred to the
38/// next `apply_deferred` boundary. Saves the boilerplate of defining a
39/// dedicated `Command` struct + impl per operation.
40pub struct WorldOpCommand<F: FnOnce(&mut World) + Send + 'static> {
41    op: F,
42}
43
44impl<F: FnOnce(&mut World) + Send + 'static> WorldOpCommand<F> {
45    /// Wrap a closure as a Bevy `Command`. Queue with
46    /// `commands.queue(WorldOpCommand::new(|world| ...))`.
47    #[inline]
48    pub fn new(op: F) -> Self {
49        Self { op }
50    }
51}
52
53impl<F: FnOnce(&mut World) + Send + 'static> Command for WorldOpCommand<F> {
54    #[inline]
55    fn apply(self, world: &mut World) {
56        (self.op)(world);
57    }
58}