bevy-sequential-actions 0.15.0

A Bevy library for executing various actions in a sequence.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#![warn(missing_docs, rustdoc::all)]

/*!
<div align="center">

# Bevy Sequential Actions

[![crates.io](https://img.shields.io/crates/v/bevy-sequential-actions?style=flat-square)](https://crates.io/crates/bevy-sequential-actions)
[![github.com](https://img.shields.io/github/stars/hikikones/bevy-sequential-actions?logo=github&style=flat-square)](https://github.com/hikikones/bevy-sequential-actions)
[![MIT/Apache 2.0](https://img.shields.io/crates/l/bevy-sequential-actions?style=flat-square)](https://github.com/hikikones/bevy-sequential-actions#license)

A simple library for managing and sequencing various actions in [Bevy](https://bevyengine.org).

<figure>
    <img src="https://github.com/user-attachments/assets/66b5b15e-96af-47bd-9371-eee8809d1294"/>
    <p><em>An entity with a queue of repeating actions</em></p>
</figure>

</div>

## 📜 Getting Started

#### Plugin

The quickest way for getting started is adding the [`SequentialActionsPlugin`] to your [`App`].

```rust,no_run
# use bevy_ecs::prelude::*;
# use bevy_app::prelude::*;
use bevy_sequential_actions::*;
#
# struct DefaultPlugins;
# impl Plugin for DefaultPlugins { fn build(&self, _app: &mut App) {} }

fn main() {
    App::new()
        .add_plugins((DefaultPlugins, SequentialActionsPlugin))
        .run();
}
```

#### Implementing an Action

An action is anything that implements the [`Action`] trait.
The trait contains various methods that together defines the _lifecycle_ of an action.
From this, you can create any action that can last as long as you like,
and do as much as you like.

An entity with actions is referred to as an `agent`.

A simple wait action follows.

```rust,no_run
# use bevy_ecs::prelude::*;
# use bevy_sequential_actions::*;
#
# struct Time;
# impl Resource for Time {}
# impl Time { fn delta_seconds(&self) -> f32 { 0.0 } }
#
pub struct WaitAction {
    duration: f32, // Seconds
    remaining: Option<f32>, // None
}

impl Action for WaitAction {
    // By default, this method is called every frame in the Last schedule.
    fn is_finished(&self, agent: Entity, world: &World) -> bool {
        // Determine if wait timer has reached zero.
        world.get::<WaitTimer>(agent).unwrap().0 <= 0.0
    }

    // This method is called when an action is started.
    fn on_start(&mut self, agent: Entity, world: &mut World) -> bool {
        // Take remaining time (if paused), or use full duration.
        let duration = self.remaining.take().unwrap_or(self.duration);

        // Run the wait timer system on the agent.
        world.entity_mut(agent).insert(WaitTimer(duration));

        // Is action already finished?
        // Returning true here will immediately advance the action queue.
        self.is_finished(agent, world)
    }

    // This method is called when an action is stopped.
    fn on_stop(&mut self, agent: Option<Entity>, world: &mut World, reason: StopReason) {
        // Do nothing if agent has been despawned.
        let Some(agent) = agent else { return };

        // Take the wait timer component from the agent.
        let wait_timer = world.entity_mut(agent).take::<WaitTimer>();

        // Store remaining time when paused.
        if reason == StopReason::Paused {
            self.remaining = Some(wait_timer.unwrap().0);
        }
    }

    // Optional. This method is called when an action is added to the queue.
    fn on_add(&mut self, agent: Entity, world: &mut World) {}

    // Optional. This method is called when an action is removed from the queue.
    fn on_remove(&mut self, agent: Option<Entity>, world: &mut World) {}

    // Optional. The last method that is called with full ownership.
    fn on_drop(self: Box<Self>, agent: Option<Entity>, world: &mut World, reason: DropReason) {}
}

#[derive(Component)]
struct WaitTimer(f32);

fn wait_system(mut wait_timer_q: Query<&mut WaitTimer>, time: Res<Time>) {
    for mut wait_timer in &mut wait_timer_q {
        wait_timer.0 -= time.delta_seconds();
    }
}
```

#### Managing Actions

Actions can be added to any [`Entity`] with the [`SequentialActions`] marker component.
Adding and managing actions is done through the [`actions(agent)`](ActionsProxy::actions)
extension method implemented for both [`Commands`] and [`World`].
See the [`ManageActions`] trait for available methods.

```rust,no_run
# use bevy_app::AppExit;
# use bevy_ecs::prelude::*;
# use bevy_sequential_actions::*;
#
# struct EmptyAction;
# impl Action for EmptyAction {
#   fn is_finished(&self, _a: Entity, _w: &World) -> bool { true }
#   fn on_start(&mut self, _a: Entity, _w: &mut World) -> bool { true }
#   fn on_stop(&mut self, _a: Option<Entity>, _w: &mut World, _r: StopReason) {}
# }
#
fn setup(mut commands: Commands) {
#   let action_a = EmptyAction;
#   let action_b = EmptyAction;
#   let action_c = EmptyAction;
#   let action_d = EmptyAction;
#   let action_e = EmptyAction;
#   let action_f = EmptyAction;
#
    // Spawn entity with the marker component
    let agent = commands.spawn(SequentialActions).id();
    commands
        .actions(agent)
        // Add a single action
        .add(action_a)
        // Add more actions with a tuple
        .add((action_b, action_c))
        // Add a collection of actions
        .add(actions![action_d, action_e, action_f])
        // Add an anonymous action with a closure
        .add(|_agent, world: &mut World| -> bool {
            // on_start
            world.write_message(AppExit::Success);
            true
        });
}
```

#### ⚠️ Warning

Since you are given a mutable [`World`], you can in practice do _anything_.
Depending on what you do, the logic for advancing the action queue might not work properly.
There are a few things you should keep in mind:

* If you want to despawn an `agent` as an action, this should be done in [`on_start`](`Action::on_start`).
* The [`execute`](`ManageActions::execute`) and [`next`](`ManageActions::next`) methods should not be used,
  as that will immediately advance the action queue while inside any of the trait methods.
  Instead, you should return `true` in [`on_start`](`Action::on_start`).
* When adding new actions, you should set the [`start`](`ManageActions::start`) property to `false`.
  Otherwise, you will effectively call [`execute`](`ManageActions::execute`) which, again, should not be used.
  At worst, you will cause a **stack overflow** if the action adds itself.

    ```rust,no_run
    # use bevy_ecs::prelude::*;
    # use bevy_sequential_actions::*;
    # struct EmptyAction;
    # impl Action for EmptyAction {
    #   fn is_finished(&self, _a: Entity, _w: &World) -> bool { true }
    #   fn on_start(&mut self, _a: Entity, _w: &mut World) -> bool { true }
    #   fn on_stop(&mut self, _a: Option<Entity>, _w: &mut World, _r: StopReason) {}
    # }
    # struct TestAction;
    # impl Action for TestAction {
    #   fn is_finished(&self, _a: Entity, _w: &World) -> bool { true }
        fn on_start(&mut self, agent: Entity, world: &mut World) -> bool {
    #       let action_a = EmptyAction;
    #       let action_b = EmptyAction;
    #       let action_c = EmptyAction;
            world
                .actions(agent)
                .start(false) // Do not start next action
                .add((action_a, action_b, action_c));

            // Immediately advance the action queue
            true
        }
    #   fn on_stop(&mut self, _a: Option<Entity>, _w: &mut World, _r: StopReason) {}
    # }
    ```
*/

use std::{collections::VecDeque, fmt::Debug};

use bevy_app::prelude::*;
use bevy_derive::{Deref, DerefMut};
use bevy_ecs::{lifecycle::HookContext, prelude::*, query::QueryFilter, world::DeferredWorld};
use bevy_log::{debug, warn};

mod commands;
mod macros;
mod plugin;
mod traits;
mod world;

pub use commands::*;
pub use plugin::*;
pub use traits::*;
pub use world::*;

/// A boxed [`Action`].
pub type BoxedAction = Box<dyn Action>;

/// Marker component for entities with actions.
///
/// This component is all that is needed for spawning an agent that you can add actions to.
/// Required components will bring in the necessary components,
/// namely [CurrentAction] and [ActionQueue].
///
/// If you do not care for the marker,
/// or perhaps don't want to use required components,
/// there is still the [ActionsBundle] for spawning an agent as before.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Component)]
#[require(CurrentAction, ActionQueue)]
pub struct SequentialActions;

/// The component bundle that all entities with actions must have.
#[derive(Default, Bundle)]
pub struct ActionsBundle {
    current: CurrentAction,
    queue: ActionQueue,
}

impl ActionsBundle {
    /// Creates a new [`Bundle`] that contains the necessary components
    /// that all entities with actions must have.
    pub const fn new() -> Self {
        Self {
            current: CurrentAction(None),
            queue: ActionQueue(VecDeque::new()),
        }
    }

    /// Creates a new [`Bundle`] with specified `capacity` for the action queue.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            current: CurrentAction(None),
            queue: ActionQueue(VecDeque::with_capacity(capacity)),
        }
    }
}

/// The current action for an `agent`.
#[derive(Debug, Default, Component, Deref, DerefMut)]
pub struct CurrentAction(Option<BoxedAction>);

impl CurrentAction {
    /// The [`on_remove`](bevy_ecs::lifecycle::ComponentHooks::on_remove) component lifecycle hook
    /// used by [`SequentialActionsPlugin`] for cleaning up the current action when an `agent` is despawned.
    pub fn on_remove_hook(mut world: DeferredWorld, ctx: HookContext) {
        let agent = ctx.entity;
        let mut current_action = world.get_mut::<Self>(agent).unwrap();
        if let Some(mut action) = current_action.take() {
            world.commands().queue(move |world: &mut World| {
                action.on_stop(None, world, StopReason::Canceled);
                action.on_remove(None, world);
                action.on_drop(None, world, DropReason::Done);
            });
        }
    }

    /// [`Observer`] for cleaning up the current action when an `agent` is despawned.
    pub fn on_remove_trigger<F: QueryFilter>(
        remove: On<Remove, Self>,
        mut query: Query<&mut Self, F>,
        mut commands: Commands,
    ) {
        let agent = remove.entity;
        if let Ok(mut current_action) = query.get_mut(agent)
            && let Some(mut action) = current_action.take()
        {
            commands.queue(move |world: &mut World| {
                action.on_stop(None, world, StopReason::Canceled);
                action.on_remove(None, world);
                action.on_drop(None, world, DropReason::Done);
            });
        }
    }
}

/// The action queue for an `agent`.
#[derive(Debug, Default, Component, Deref, DerefMut)]
pub struct ActionQueue(VecDeque<BoxedAction>);

impl ActionQueue {
    /// The [`on_remove`](bevy_ecs::lifecycle::ComponentHooks::on_remove) component lifecycle hook
    /// used by [`SequentialActionsPlugin`] for cleaning up the action queue when an `agent` is despawned.
    pub fn on_remove_hook(mut world: DeferredWorld, ctx: HookContext) {
        let agent = ctx.entity;
        let mut action_queue = world.get_mut::<Self>(agent).unwrap();
        if !action_queue.is_empty() {
            let actions = std::mem::take(&mut action_queue.0);
            world.commands().queue(move |world: &mut World| {
                for mut action in actions {
                    action.on_remove(None, world);
                    action.on_drop(None, world, DropReason::Cleared);
                }
            });
        }
    }

    /// [`Observer`] for cleaning up the action queue when an `agent` is despawned.
    pub fn on_remove_trigger<F: QueryFilter>(
        remove: On<Remove, Self>,
        mut query: Query<&mut Self, F>,
        mut commands: Commands,
    ) {
        let agent = remove.entity;
        if let Ok(mut action_queue) = query.get_mut(agent)
            && !action_queue.is_empty()
        {
            let actions = std::mem::take(&mut action_queue.0);
            commands.queue(move |world: &mut World| {
                for mut action in actions {
                    action.on_remove(None, world);
                    action.on_drop(None, world, DropReason::Cleared);
                }
            });
        }
    }
}

/// Configuration for actions to be added.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AddConfig {
    /// Start the next action in the queue if nothing is currently running.
    pub start: bool,
    /// The queue order for actions to be added.
    pub order: AddOrder,
}

impl AddConfig {
    /// Returns a new configuration for actions to be added.
    pub const fn new(start: bool, order: AddOrder) -> Self {
        Self { start, order }
    }
}

impl Default for AddConfig {
    fn default() -> Self {
        Self::new(true, AddOrder::Back)
    }
}

/// The queue order for actions to be added.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum AddOrder {
    /// An action is added to the back of the queue.
    #[default]
    Back,
    /// An action is added to the front of the queue.
    Front,
}

/// The reason why an [`Action`] was stopped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopReason {
    /// The action was finished.
    Finished,
    /// The action was canceled.
    Canceled,
    /// The action was paused.
    Paused,
}

/// The reason why an [`Action`] was dropped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DropReason {
    /// The action is considered done as it was either finished or canceled
    /// without being skipped or cleared from the action queue.
    Done,
    /// The action was skipped. This happens either deliberately,
    /// or because an action was added to an `agent` that does not exist or is missing a component.
    Skipped,
    /// The action queue was cleared. This happens either deliberately,
    /// or because an `agent` was despawned.
    Cleared,
}