Skip to main content

cranium_core/
events.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//! Assorted Event types used by Cranium.
8
9use bevy::prelude::*;
10use crate::{actions::ActionContext, types::{self, RequestKey}};
11
12/// An Event that signals the decision engine picked the new best Action
13/// for a specific AI Entity and provides details about it (abstract ID, 
14/// context, etc.).
15/// 
16/// Primarily expected to be raised by the decision_process() System 
17/// and listened to by consumers for remapping into more Action-specific logic
18/// (e.g. raising an Event for a *specific* Action implementation).
19#[derive(EntityEvent, Debug)]
20pub struct AiActionPicked {
21    /// The AI that picked this Action for execution. 
22    pub entity: Entity,
23
24    /// Identifier for the handling event (e.g. "GoTo"). 
25    /// This is effectively a link to the *implementation* of the action. 
26    pub action_key: crate::types::ActionKey,
27
28    /// Human-readable primary identifier; one action_key may handle distinct action_names 
29    /// (e.g. action_key "GoTo" may cover action_names "Walk", "Run", "Flee", etc.).
30    /// In other words, this is what this action represents *semantically*, and is less likely
31    /// to change for technical purposes.
32    pub action_name: String,
33
34    /// The Context of the Action, i.e. the static input(s) we scored against.
35    pub action_context: crate::types::ActionContextRef,
36
37    /// The Utility score; this is so that we can decide whether to possibly 
38    /// override this with a higher-priority Action later on.
39    pub action_score: crate::types::ActionScore,
40
41    /// Identifier of the request that has originally triggered this decision. 
42    /// Used to tie the reponse back to the request that led to it.
43    pub request_key: Option<RequestKey>,
44}
45
46impl AiActionPicked {
47    pub fn new(
48        ai_owner: Entity,
49        action_key: crate::types::ActionKey,
50        action_name: String,
51        action_context: ActionContext,
52        action_score: crate::types::ActionScore,
53        request_key: Option<RequestKey>,
54    ) -> Self {
55        
56        #[cfg(feature = "logging")]
57        bevy::log::debug!(
58            "Creating a new AiActionPicked event for {:?} with key {:?} ({:?})",
59            ai_owner,
60            action_key,
61            action_name
62        );
63
64        let wrapped_ctx = action_context;
65
66        Self {
67            entity: ai_owner,
68            action_key: action_key,
69            action_name: action_name,
70            action_context: wrapped_ctx,
71            action_score: action_score,
72            request_key: request_key,
73        }
74    }
75}
76
77/// A more general signal than AiActionPicked - simply signals that SOME AI has 
78/// done some processing. This is used to optimize query reinitializations - as 
79/// they are currently all-or-nothing, if one AI handled the reinit, they all did.
80#[derive(Event, Debug)]
81pub struct SomeAiDecisionProcessed;
82
83
84/// Supporting Event for triggering a decision_process() for an AI.
85/// Raised whenever an active AI starts a tick without an Action.
86/// 
87/// Should generally NOT be raised more than once per Entity per tick 
88/// or you are likely running the same calculation multiple times.
89#[derive(EntityEvent)]
90pub struct AiDecisionRequested {
91    pub entity: types::AiEntity,
92    pub request_key: Option<RequestKey>,
93    pub smart_objects: Option<crate::types::SmartObjects>,
94}
95
96
97/// Supporting Event for triggering a decision_process() for an AI.
98/// Raised when AiDecisionRequested has finished preparing the AI.
99/// 
100/// Should generally NOT be raised more than once per Entity per tick 
101/// or you are likely running the same calculation multiple times.
102#[derive(EntityEvent)]
103pub struct AiDecisionInitiated {
104    pub entity: types::AiEntity,
105    pub request_key: Option<RequestKey>,
106    pub smart_objects: Option<crate::types::SmartObjects>,
107}
108
109
110/// An Event that signals that Cranium is handing off to the user code by running 
111/// any registered ActionHandlers.
112/// 
113/// Primarily used as a trigger to kick off a System that handles calling an appropriate 
114/// user function from the registry - the registry is NonSend, so we are doing this in 
115/// a separate System to not force the main decision logic to run on the main thread.
116#[derive(Message, Debug)]
117pub struct AiActionDispatchToUserCode {
118    /// The AI that picked this Action for execution. 
119    pub entity: Entity,
120
121    /// Identifier for the handling event (e.g. "GoTo"). 
122    /// This is effectively a link to the *implementation* of the action. 
123    pub action_key: crate::types::ActionKey,
124
125    /// Human-readable primary identifier; one action_key may handle distinct action_names 
126    /// (e.g. action_key "GoTo" may cover action_names "Walk", "Run", "Flee", etc.).
127    /// In other words, this is what this action represents *semantically*, and is less likely
128    /// to change for technical purposes.
129    pub action_name: String,
130
131    /// The Context of the Action, i.e. the static input(s) we scored against.
132    pub action_context: crate::types::ActionContextRef,
133
134    /// The Utility score; this is so that we can decide whether to possibly 
135    /// override this with a higher-priority Action later on.
136    pub action_score: crate::types::ActionScore,
137}
138
139impl AiActionDispatchToUserCode {
140    pub fn new(
141        ai_owner: Entity,
142        action_key: crate::types::ActionKey,
143        action_name: String,
144        action_context: ActionContext,
145        action_score: crate::types::ActionScore,
146    ) -> Self {
147        
148        #[cfg(feature = "logging")]
149        bevy::log::debug!(
150            "Creating a new AiActionDispatchToUserCode event for {:?} with key {:?} ({:?})",
151            ai_owner,
152            action_key,
153            action_name
154        );
155
156        let wrapped_ctx = action_context;
157
158        Self {
159            entity: ai_owner,
160            action_key: action_key,
161            action_name: action_name,
162            action_context: wrapped_ctx,
163            action_score: action_score,
164        }
165    }
166}
167
168
169#[derive(Message)]
170pub struct NoDecisionMessage {
171    pub entity: Option<Entity>,
172    pub request_key: Option<RequestKey>,
173    /// IMPORTANT: If used, comments are meant to be hardcoded, NUL-TERMINATED strings. 
174    /// The nul at the end is critical for FFI-safety - failure to include may cause panics. 
175    pub comment: Option<&'static str>,
176}
177
178
179#[cfg(test)]
180mod tests {
181    #[cfg(feature = "logging")]
182    use bevy::log::LogPlugin;
183    use bevy::{app::ScheduleRunnerPlugin, prelude::*};
184    use super::*;
185    use crate::ai::AIController;
186
187    #[derive(Component)]
188    struct TestContextData {
189        _foo: u8,
190        _bar: i8,
191    }
192
193    #[derive(Debug, Default, Event)]
194    struct TestActionEvent;
195
196    fn setup_test_entity(
197        mut commands: Commands,
198    ) {
199        let entity_cmds = commands.spawn(
200            AIController::default()
201        );
202
203        let entity = entity_cmds.id();
204
205        let ctx2 = commands.spawn(
206            TestContextData {
207                _foo: 1,
208                _bar: 2,
209            }
210        ).id();
211
212        commands.trigger(AiActionPicked {
213            action_name: "TestAction".into(),
214            action_key: "TestActionEvent".into(),
215            action_context: ctx2,
216            action_score: 1.,
217            entity: entity.into(),
218            request_key: None,
219        });
220    }
221
222    fn dispatch_events(
223        trigger: On<AiActionPicked>,
224        mut commands: Commands,
225    ) {
226        let evt = trigger.event();
227        let actionkey = evt.action_key.as_str();
228
229        match actionkey {
230            "TestActionEvent" => { commands.trigger(TestActionEvent) }
231            _ => { panic!("Unrecognized Action Key: {}", actionkey) }
232        };
233    }
234
235    fn handle_event(
236        trigger: On<TestActionEvent>
237    ) {
238        let evt = trigger.event();
239        #[cfg(feature = "logging")]
240        bevy::log::debug!("Processing event {:?}", evt);
241    }
242
243    #[test]
244    fn test_run_action() {
245        let mut app = App::new();
246
247        app
248        .add_plugins((
249            MinimalPlugins.set(ScheduleRunnerPlugin::run_once()),
250            #[cfg(feature = "logging")]
251            LogPlugin { 
252                level: bevy::log::Level::DEBUG, 
253                custom_layer: |_| None, 
254                filter: "wgpu=error,bevy_render=info,bevy_ecs=info".to_string(),
255                fmt_layer: |_| None,
256            }
257        ))
258        .add_systems(Startup, setup_test_entity)
259        .add_observer(dispatch_events)
260        .add_observer(handle_event)
261        ;
262
263        app.run();
264    }
265}