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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use super::*;

/// The [`Plugin`] for this library that you can add to your [`App`].
///
/// This plugin adds the [`check_actions`](Self::check_actions) system to the [`Last`] schedule
/// for action queue advancement, and also two [`hooks`](bevy_ecs::lifecycle::ComponentHooks)
/// for cleaning up actions from despawned agents.
///
/// Finally, it also contains various static methods for managing the action queue.
pub struct SequentialActionsPlugin;

impl Plugin for SequentialActionsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Last, Self::check_actions::<()>);
        app.world_mut()
            .register_component_hooks::<CurrentAction>()
            .on_remove(CurrentAction::on_remove_hook);
        app.world_mut()
            .register_component_hooks::<ActionQueue>()
            .on_remove(ActionQueue::on_remove_hook);
    }
}

impl SequentialActionsPlugin {
    /// The [`System`] used by [`SequentialActionsPlugin`].
    /// It is responsible for checking all agents for finished actions
    /// and advancing the action queue.
    ///
    /// The query filter `F` is used for filtering agents.
    /// Use the unit type `()` for no filtering.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bevy_ecs::prelude::*;
    /// # use bevy_app::prelude::*;
    /// # use bevy_sequential_actions::*;
    /// #
    /// # fn main() {
    /// App::new()
    ///     .add_systems(Last, SequentialActionsPlugin::check_actions::<()>)
    ///     .run();
    /// # }
    /// ```
    pub fn check_actions<F: QueryFilter>(
        action_q: Query<(Entity, &CurrentAction), F>,
        world: &World,
        mut commands: Commands,
    ) {
        action_q
            .iter()
            .filter_map(|(agent, current_action)| {
                current_action
                    .as_ref()
                    .and_then(|action| action.is_finished(agent, world).then_some(agent))
            })
            .for_each(|agent| {
                commands.queue(move |world: &mut World| {
                    Self::stop_current_action(agent, StopReason::Finished, world);
                    Self::start_next_action(agent, world);
                });
            });
    }

    /// Adds a single [`action`](Action) to `agent` with specified `config`.
    pub fn add_action(
        agent: Entity,
        config: AddConfig,
        action: impl IntoBoxedAction,
        world: &mut World,
    ) {
        let mut action = action.into_boxed_action();

        if world.get_entity(agent).is_err() {
            warn!("Cannot add action {action:?} to non-existent agent {agent}.");
            return;
        }

        debug!("Adding action {action:?} for agent {agent} with {config:?}.");
        action.on_add(agent, world);

        let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
            warn!(
                "Cannot enqueue action {action:?} to non-existent agent {agent}. \
                Action is therefore dropped immediately."
            );
            action.on_remove(None, world);
            action.on_drop(None, world, DropReason::Skipped);
            return;
        };

        let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
            warn!(
                "Cannot enqueue action {action:?} to agent {agent} due to missing component {}. \
                Action is therefore dropped immediately.",
                std::any::type_name::<ActionQueue>()
            );
            action.on_remove(agent.into(), world);
            action.on_drop(agent.into(), world, DropReason::Skipped);
            return;
        };

        match config.order {
            AddOrder::Back => action_queue.push_back(action),
            AddOrder::Front => action_queue.push_front(action),
        }

        if config.start {
            let Some(current_action) = agent_ref.get::<CurrentAction>() else {
                warn!(
                    "Could not start next action for agent {agent} due to missing component {}.",
                    std::any::type_name::<CurrentAction>()
                );
                return;
            };

            if current_action.is_none() {
                Self::start_next_action(agent, world);
            }
        }
    }

    /// Adds a collection of actions to `agent` with specified `config`.
    /// An empty collection does nothing.
    pub fn add_actions<I>(agent: Entity, config: AddConfig, actions: I, world: &mut World)
    where
        I: DoubleEndedIterator<Item = BoxedAction> + ExactSizeIterator + Debug,
    {
        let actions = actions.into_iter();
        let len = actions.len();

        if len == 0 {
            return;
        }

        let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
            warn!("Cannot add actions {actions:?} to non-existent agent {agent}.");
            return;
        };

        let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
            warn!(
                "Cannot add actions {actions:?} to agent {agent} due to missing component {}.",
                std::any::type_name::<ActionQueue>()
            );
            return;
        };

        debug!("Adding actions {actions:?} for agent {agent} with {config:?}.");
        action_queue.reserve(len);

        match config.order {
            AddOrder::Back => {
                for mut action in actions {
                    action.on_add(agent, world);

                    let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
                        warn!(
                            "Cannot enqueue action {action:?} to non-existent agent {agent}. \
                            Action is therefore dropped immediately."
                        );
                        action.on_remove(None, world);
                        action.on_drop(None, world, DropReason::Skipped);
                        return;
                    };

                    let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
                        warn!(
                            "Cannot enqueue action {action:?} to agent {agent} due to missing component {}. \
                            Action is therefore dropped immediately.",
                            std::any::type_name::<ActionQueue>()
                        );
                        action.on_remove(agent.into(), world);
                        action.on_drop(agent.into(), world, DropReason::Skipped);
                        return;
                    };

                    action_queue.push_back(action);
                }
            }
            AddOrder::Front => {
                for mut action in actions.rev() {
                    action.on_add(agent, world);

                    let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
                        warn!(
                            "Cannot enqueue action {action:?} to non-existent agent {agent}. \
                            Action is therefore dropped immediately."
                        );
                        action.on_remove(None, world);
                        action.on_drop(None, world, DropReason::Skipped);
                        return;
                    };

                    let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
                        warn!(
                            "Cannot enqueue action {action:?} to agent {agent} due to missing component {}. \
                            Action is therefore dropped immediately.",
                            std::any::type_name::<ActionQueue>()
                        );
                        action.on_remove(agent.into(), world);
                        action.on_drop(agent.into(), world, DropReason::Skipped);
                        return;
                    };

                    action_queue.push_front(action);
                }
            }
        }

        if config.start {
            let Some(current_action) = world.get::<CurrentAction>(agent) else {
                warn!(
                    "Could not start next action for agent {agent} due to missing component {}.",
                    std::any::type_name::<CurrentAction>()
                );
                return;
            };

            if current_action.is_none() {
                Self::start_next_action(agent, world);
            }
        }
    }

    /// [`Starts`](Action::on_start) the next [`action`](Action) in the queue for `agent`,
    /// but only if there is no current action.
    pub fn execute_actions(agent: Entity, world: &mut World) {
        let Ok(agent_ref) = world.get_entity(agent) else {
            warn!("Cannot execute actions for non-existent agent {agent}.");
            return;
        };

        let Some(current_action) = agent_ref.get::<CurrentAction>() else {
            warn!(
                "Cannot execute actions for agent {agent} due to missing component {}.",
                std::any::type_name::<CurrentAction>()
            );
            return;
        };

        if current_action.is_none() {
            debug!("Executing actions for agent {agent}.");
            Self::start_next_action(agent, world);
        }
    }

    /// [`Stops`](Action::on_stop) the current [`action`](Action) for `agent` with specified `reason`.
    pub fn stop_current_action(agent: Entity, reason: StopReason, world: &mut World) {
        let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
            warn!(
                "Cannot stop current action for non-existent agent {agent} with reason {reason:?}."
            );
            return;
        };

        let Some(mut current_action) = agent_ref.get_mut::<CurrentAction>() else {
            warn!(
                "Cannot stop current action for agent {agent} with reason {reason:?} \
                due to missing component {}.",
                std::any::type_name::<CurrentAction>()
            );
            return;
        };

        if let Some(mut action) = current_action.take() {
            debug!("Stopping current action {action:?} for agent {agent} with reason {reason:?}.");
            action.on_stop(agent.into(), world, reason);

            match reason {
                StopReason::Finished | StopReason::Canceled => {
                    action.on_remove(agent.into(), world);
                    action.on_drop(agent.into(), world, DropReason::Done);
                }
                StopReason::Paused => {
                    let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
                        warn!(
                            "Cannot enqueue paused action {action:?} to non-existent agent {agent}. \
                            Action is therefore dropped immediately."
                        );
                        action.on_remove(None, world);
                        action.on_drop(None, world, DropReason::Skipped);
                        return;
                    };

                    let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
                        warn!(
                            "Cannot enqueue paused action {action:?} to agent {agent} due to missing component {}. \
                            Action is therefore dropped immediately.",
                            std::any::type_name::<ActionQueue>()
                        );
                        action.on_remove(agent.into(), world);
                        action.on_drop(agent.into(), world, DropReason::Skipped);
                        return;
                    };

                    action_queue.push_front(action);
                }
            }
        }
    }

    /// [`Starts`](Action::on_start) the next [`action`](Action) in the queue for `agent`.
    ///
    /// This will loop until any next action is not immediately finished or the queue is empty.
    /// Since this may trigger an infinite loop, a counter is used in debug build
    /// that panics when reaching a sufficient target.
    ///
    /// The loop will also break if `agent` already has a current action.
    /// This is likely a user error, and so a warning will be emitted.
    pub fn start_next_action(agent: Entity, world: &mut World) {
        #[cfg(debug_assertions)]
        let mut counter: u16 = 0;

        loop {
            let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
                warn!("Cannot start next action for non-existent agent {agent}.");
                break;
            };

            let Some(current_action) = agent_ref.get::<CurrentAction>() else {
                warn!(
                    "Cannot start next action for agent {agent} due to missing component {}.",
                    std::any::type_name::<CurrentAction>()
                );
                break;
            };

            if let Some(action) = current_action.0.as_ref() {
                warn!(
                    "Cannot start next action for agent {agent} \
                    as it already has current action {action:?}."
                );
                break;
            }

            let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
                warn!(
                    "Cannot start next action for agent {agent} due to missing component {}.",
                    std::any::type_name::<ActionQueue>()
                );
                break;
            };

            let Some(mut action) = action_queue.pop_front() else {
                break;
            };

            debug!("Starting action {action:?} for agent {agent}.");
            if !action.on_start(agent, world) {
                match world.get_mut::<CurrentAction>(agent) {
                    Some(mut current_action) => {
                        current_action.0 = Some(action);
                    }
                    None => {
                        debug!("Canceling action {action:?} due to missing agent {agent}.");
                        action.on_stop(None, world, StopReason::Canceled);
                        action.on_remove(None, world);
                        action.on_drop(None, world, DropReason::Done);
                    }
                }
                break;
            };

            debug!("Finishing action {action:?} for agent {agent}.");
            let agent = world.get_entity(agent).map(|_| agent).ok();
            action.on_stop(agent, world, StopReason::Finished);
            action.on_remove(agent, world);
            action.on_drop(agent, world, DropReason::Done);

            if agent.is_none() {
                break;
            }

            #[cfg(debug_assertions)]
            {
                counter += 1;
                if counter == u16::MAX {
                    panic!("infinite loop detected in starting next action");
                }
            }
        }
    }

    /// Skips the next `n` actions in the queue for `agent`.
    pub fn skip_actions(agent: Entity, mut n: usize, world: &mut World) {
        loop {
            if n == 0 {
                break;
            }

            let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
                warn!("Cannot skip next action for non-existent agent {agent}.");
                break;
            };

            let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
                warn!(
                    "Cannot skip next action for agent {agent} due to missing component {}.",
                    std::any::type_name::<ActionQueue>()
                );
                break;
            };

            let Some(mut action) = action_queue.pop_front() else {
                break;
            };

            debug!("Skipping action {action:?} for agent {agent}.");
            action.on_remove(agent.into(), world);
            action.on_drop(agent.into(), world, DropReason::Skipped);

            n -= 1;
        }
    }

    /// Clears the action queue for `agent`.
    ///
    /// Current action is [`stopped`](Action::on_stop) as [`canceled`](StopReason::Canceled).
    pub fn clear_actions(agent: Entity, world: &mut World) {
        let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
            warn!("Cannot clear actions for non-existent agent {agent}.");
            return;
        };

        let Some(mut current_action) = agent_ref.get_mut::<CurrentAction>() else {
            warn!(
                "Cannot clear current action for agent {agent} due to missing component {}.",
                std::any::type_name::<CurrentAction>()
            );
            return;
        };

        if let Some(mut action) = current_action.take() {
            debug!("Clearing current action {action:?} for agent {agent}.");
            action.on_stop(agent.into(), world, StopReason::Canceled);
            action.on_remove(agent.into(), world);
            action.on_drop(agent.into(), world, DropReason::Cleared);
        }

        let Ok(mut agent_ref) = world.get_entity_mut(agent) else {
            warn!("Cannot clear action queue for non-existent agent {agent}.");
            return;
        };

        let Some(mut action_queue) = agent_ref.get_mut::<ActionQueue>() else {
            warn!(
                "Cannot clear action queue for agent {agent} due to missing component {}.",
                std::any::type_name::<ActionQueue>()
            );
            return;
        };

        if action_queue.is_empty() {
            return;
        }

        debug!("Clearing action queue {:?} for {agent}.", **action_queue);
        let actions = std::mem::take(&mut action_queue.0);
        for mut action in actions {
            action.on_remove(agent.into(), world);
            action.on_drop(agent.into(), world, DropReason::Cleared);
        }
    }
}