Skip to main content

cranium_core/
action_state.rs

1/* 
2This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. 
3If a copy of the MPL was not distributed with this file, 
4You can obtain one at https://mozilla.org/MPL/2.0/. 
5*/
6
7//! The values used by the Action Runtime to track the state of AI Actions.
8
9use bevy::prelude::*;
10use bevy::{platform::collections::Equivalent, reflect::Reflect};
11
12use crate::{types, action_runtime::ActionTrackerState};
13
14#[cfg(any(feature = "actionset_loader"))]
15use serde::{Deserialize, Serialize};
16
17/// A lifecycle marker for ActionTrackers to indicate what the status of the tracked Action is. 
18/// 
19/// This is a state machine, more or less, with three layers:
20/// 1) Initial
21/// 2) Progressed
22/// 3) Terminal
23/// 
24/// *As a general rule*, the progression through those layers should be non-increasing, i.e.:
25/// - Terminal States should never change at all once reached, 
26/// - Progressed states should only become Terminal or different Progressed States, and
27/// - Initial states can become any other State.
28#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Reflect)]
29#[cfg_attr(any(feature = "actionset_loader"), derive(Serialize, Deserialize))]
30pub enum ActionState {
31    // Note that we are NOT implementing Default for this on purpose; 
32    // the default state is domain-specific (though probably just Ready most of the time).
33
34    /// Initial state. Planned but not started and cannot start yet - waiting on something (likely other Actions).
35    Queued, 
36    /// Initial state. Can start now, hadn't done literally anything yet though.
37    Ready, 
38    
39    /// Progressed state. Started but didn't finish yet, will continue.
40    Running, 
41    /// Progressed state. Started and can continue, but has been put on hold for now.
42    Paused, 
43    
44    /// Terminal state. Did all it was supposed to and is no longer needed, yaaay.
45    Succeeded, 
46    
47    /// Terminal state. 
48    /// We gave up due to getting stuck/timeout/etc., naaay. 
49    /// Generally implies the action should not be retried as-is 
50    /// and may trigger failure callbacks.
51    Failed, 
52    
53    /// Terminal state. 
54    /// We gave up because of an 'external' decision that we should, 
55    /// and NOT because something was wrong with the execution. 
56    /// The Action may well be still valid, we just stopped pursuing it. 
57    /// You can think of it as 'Paused, but forever'. 
58    Cancelled, 
59}
60
61impl ActionState {
62    /// A shorthand for checking if an Action is in one of the Initial states (e.g. Ready).
63    pub fn is_initial(&self) -> bool {
64        match self {
65            Self::Queued => true,
66            Self::Ready => true,
67            _ => false,
68        }
69    }
70
71    /// A shorthand for checking if an Action is in one of the Progressed states (e.g. Running).
72    pub fn is_progressed(&self) -> bool {
73        match self {
74            Self::Running => true,
75            Self::Paused => true,
76            _ => false,
77        }
78    }
79
80    /// A shorthand for checking if an Action is in one of the Terminal states (e.g. Succeeded).
81    pub fn is_terminal(&self) -> bool {
82        match self {
83            Self::Succeeded => true,
84            Self::Failed => true,
85            Self::Cancelled => true,
86            _ => false,
87        }
88    }
89
90    /// A shorthand for checking if an Action should be processed/'ticked'. If false, we can skip it.
91    pub fn should_process(&self) -> bool {
92        match self {
93            Self::Ready => true,
94            Self::Running => true,
95            _ => false,
96        }
97    }
98}
99
100impl Equivalent<ActionState> for &ActionState {
101    fn equivalent(&self, key: &ActionState) -> bool {
102        self == &key
103    }
104}
105
106
107/// 
108#[derive(Message)]
109pub struct AiActionStateChangeRequest {
110    pub entity: Entity,
111    pub action: types::ActionKey,
112    pub to_state: crate::action_state::ActionState,
113}
114
115
116/// Signals that an Action has transitioned between two states: from_state -> to_state.
117#[derive(EntityEvent)]
118pub struct AiActionStateChange {
119    pub entity: Entity,
120    pub action: types::ActionKey,
121    pub from_state: Option<crate::action_state::ActionState>,
122    pub to_state: crate::action_state::ActionState,
123}
124
125/// A System that processes all pending AiActionStateChangeRequest and applies them. 
126/// Can be scheduled as a System or (via `action_state_update_handler_observer()`) as an Observer.
127pub fn action_state_update_handler(
128    mut request_reader: MessageReader<AiActionStateChangeRequest>,
129    mut tracker_state_qry: Query<&mut ActionTrackerState>,
130    mut commands: Commands,
131) {
132    request_reader.read().for_each(|msg| {
133        let maybe_tracker_state = tracker_state_qry.get_mut(msg.entity);
134
135        match maybe_tracker_state {
136            Err(err) => {
137                #[cfg(feature = "logging")]
138                bevy::log::debug!("{:?}: ActionTracker does not exist: {:?}", &msg.action, err);
139                match commands.get_entity(msg.entity) {
140                    Err(err) => {
141                        #[cfg(feature = "logging")]
142                        bevy::log::error!("{:?}: AI {:?} does not exist??? - {:?}", &msg.action, msg.entity, err);
143                    }
144                    Ok(mut cmds) => {
145                        #[cfg(feature = "logging")]
146                        bevy::log::debug!("{:?}: Inserting new ActionState for AI {:?} - {:?}", &msg.action, msg.entity, &msg.to_state);
147                        cmds.trigger(|ent| AiActionStateChange {
148                            action: msg.action.clone(),
149                            entity: ent,
150                            from_state: None, 
151                            to_state: msg.to_state.clone(),
152                        });
153                        cmds.insert(ActionTrackerState(msg.to_state));
154                    }
155                }
156            }
157            Ok(mut state) => { 
158                #[cfg(feature = "logging")]
159                bevy::log::debug!("example_action for AI {:?}: Updating the state to new value {:?}", msg.entity, msg.to_state);
160                let current = state.get_state().clone();
161                commands.trigger(AiActionStateChange {
162                    action: msg.action.clone(),
163                    entity: msg.entity,
164                    from_state: Some(current), 
165                    to_state: msg.to_state.clone(),
166                });
167                state.set_state(msg.to_state);
168            },
169        }
170    });
171}
172
173
174/// An event that 
175#[derive(Event)]
176pub struct ProcessActionStateUpdatesSignal;
177
178
179/// An Observer wrapper for `action_state_update_handler()`, triggered by ProcessActionStateUpdatesSignal. 
180/// Can be used as a 'sparse' replacement for normal Schedule-based processing or in parallel to it as a 
181/// way to force a flush of the buffered AiActionStateChangeRequests.
182pub fn action_state_update_handler_observer(
183    _trigger: On<ProcessActionStateUpdatesSignal>,
184    request_reader: MessageReader<AiActionStateChangeRequest>,
185    tracker_state_qry: Query<&mut ActionTrackerState>,
186    commands: Commands,
187) {
188    action_state_update_handler(request_reader, tracker_state_qry, commands);
189}
190
191
192pub struct ActionStateUpdatesPlugin;
193
194impl Plugin for ActionStateUpdatesPlugin {
195    fn build(&self, app: &mut App) {
196        app
197        .add_message::<AiActionStateChangeRequest>()
198        .add_observer(action_state_update_handler_observer)
199        .add_systems(FixedUpdate, crate::action_state::action_state_update_handler)
200        ;
201    }
202}