1use bevy::platform::prelude::{String, ToOwned};
10
11use bevy::prelude::*;
12use bevy::platform::sync::Arc;
13
14use crate::types::{self, ActionContextRef, AiEntity, CraniumKvMap, CraniumRwLock, PawnEntityRef};
15use crate::identifiers::{ConsiderationIdentifier, CurveIdentifier};
16
17#[cfg(any(feature = "actionset_loader"))]
18use serde::{Serialize, Deserialize};
19
20#[derive(Clone, Debug, Reflect)]
21#[cfg_attr(feature = "actionset_loader", derive(Serialize, Deserialize))]
22pub struct ConsiderationData {
23 #[cfg_attr(any(feature = "actionset_loader"), serde(rename="consideration"))]
24 pub consideration_name: ConsiderationIdentifier,
25
26 #[cfg_attr(any(feature = "actionset_loader"), serde(rename="curve"))]
27 pub curve_name: CurveIdentifier,
28
29 pub min: types::ActionScore,
30 pub max: types::ActionScore,
31}
32
33impl ConsiderationData {
34 pub fn new<CNN: Into<ConsiderationIdentifier>, CRN: Into<CurveIdentifier>>(
35 consideration_name: CNN,
36 curve_name: CRN,
37 min: types::ActionScore,
38 max: types::ActionScore,
39 ) -> Self {
40 Self {
41 consideration_name: consideration_name.into(),
42 curve_name: curve_name.into(),
43 min: min,
44 max: max,
45 }
46 }
47}
48
49pub type ConsiderationInputs = bevy::prelude::In<(
71 AiEntity,
72 PawnEntityRef,
73 ActionContextRef,
74)>;
75
76pub type ConsiderationOutputs = Option<f32>;
78
79
80pub trait ConsiderationSystem: bevy::ecs::system::ReadOnlySystem<
87 In = ConsiderationInputs,
88 Out = ConsiderationOutputs
89> {}
90
91impl<
92 ROS: bevy::ecs::system::ReadOnlySystem<
93 In = ConsiderationInputs,
94 Out = ConsiderationOutputs
95 >
96> ConsiderationSystem for ROS {}
97
98
99pub trait IntoConsiderationSystem<Marker>: IntoSystem<
102 ConsiderationInputs,
103 ConsiderationOutputs,
104 Marker,
105> {}
106
107impl<
108 Marker,
109 CS: ConsiderationSystem,
110 IS: IntoSystem<
111 ConsiderationInputs,
112 ConsiderationOutputs,
113 Marker,
114 System = CS
115 >
116> IntoConsiderationSystem<Marker> for IS {}
117
118
119#[derive(Clone)]
120pub struct ConsiderationMappedToSystem {
121 pub func_name: ConsiderationIdentifier,
122
123 pub consideration_system: Result<Arc<CraniumRwLock<dyn ConsiderationSystem>>, ()>,
127 pub curve_name: CurveIdentifier,
128
129 pub min: types::ActionScore,
130 pub max: types::ActionScore,
131}
132
133
134#[derive(Resource, Default)]
135pub struct ConsiderationKeyToSystemMap {
136 pub mapping: CraniumKvMap<
137 ConsiderationIdentifier,
138 Arc<CraniumRwLock<dyn ConsiderationSystem>>
139 >
140}
141
142
143pub trait AcceptsConsiderationRegistrations {
150 fn register_consideration<
151 CS: ConsiderationSystem,
152 Marker,
153 F: IntoConsiderationSystem<Marker, System = CS> + 'static,
154 IS: Into<String>,
155 >(
156 &mut self,
157 consideration: F,
158 key: IS,
159 ) -> &mut Self;
160}
161
162impl AcceptsConsiderationRegistrations for App {
163 fn register_consideration<
164 CS: ConsiderationSystem,
165 Marker,
166 F: IntoConsiderationSystem<Marker, System = CS> + 'static,
167 IS: Into<String>,
168 >(
169 &mut self,
170 consideration: F,
171 key: IS
172 ) -> &mut Self {
173 self.world_mut().register_consideration(consideration, key);
174 self
175 }
176}
177
178impl AcceptsConsiderationRegistrations for &mut App {
179 fn register_consideration<
180 CS: ConsiderationSystem,
181 Marker,
182 F: IntoConsiderationSystem<Marker, System = CS> + 'static,
183 IS: Into<String>,
184 >(
185 &mut self,
186 consideration: F,
187 key: IS
188 ) -> &mut Self {
189 self.world_mut().register_consideration(consideration, key);
190 self
191 }
192}
193
194impl AcceptsConsiderationRegistrations for World {
195 fn register_consideration<
196 CS: ConsiderationSystem,
197 Marker,
198 F: IntoConsiderationSystem<Marker, System = CS> + 'static,
199 IS: Into<String>,
200 >(
201 &mut self,
202 consideration: F,
203 key: IS
204 ) -> &mut Self {
205 let system = F::into_system(consideration);
206 let system_key = ConsiderationIdentifier::from(key);
207 let mut system_registry = self.get_resource_or_init::<ConsiderationKeyToSystemMap>();
208 let old = system_registry.mapping.insert(
209 system_key.to_owned(),
210 Arc::new(CraniumRwLock::new(
211 system
212 )));
213 match old {
214 None => {},
215 Some(_) => {
216 #[cfg(feature = "logging")]
217 bevy::log::warn!(
218 "Detected a key collision for key {:?}. Ejecting previous registration...",
219 system_key
220 );
221 }
222 }
223 self
224 }
225}
226
227#[derive(Resource, Debug)]
228pub struct ShouldReinitConsiderationQueries(bool);
229
230impl ShouldReinitConsiderationQueries {
231 pub fn get(&self) -> bool {
232 self.0
233 }
234
235 pub fn set(&mut self, val: bool) {
236 self.0 = val;
237 }
238}
239
240impl Default for ShouldReinitConsiderationQueries {
241 fn default() -> Self {
242 Self(true)
243 }
244}
245
246pub fn reinit_consideration_queries(world: &mut World) {
247 let world_cell = world.as_unsafe_world_cell();
248
249 let should_reinit_res = unsafe {
252 world_cell.get_resource::<ShouldReinitConsiderationQueries>()
253 };
254
255 let should_reinit = match should_reinit_res {
256 None => true,
257 Some(reinit_mark) => reinit_mark.get()
258 };
259
260 if !should_reinit {
261 return
262 };
263
264 let registry = unsafe {
268 world_cell.get_resource_mut::<ConsiderationKeyToSystemMap>()
269 };
270
271 let mut registry = match registry {
272 None => return,
273 Some(r) => r,
274 };
275
276 registry.mapping.iter_mut().for_each(|(_key, system_lock)| {
277 let write_state = system_lock.write();
278 {
279 match write_state {
280 Ok(mut system) => {
281 #[cfg(feature = "logging")]
285 bevy::log::debug!("reinit_consideration_queries: Reinitializing System {:?}", _key);
286 system.initialize(unsafe { world_cell.world_mut() });
287 },
288 Err(e) => panic!("{:?}", e)
289 }
290 }
291 });
292}
293
294pub struct ConsiderationPlugin;
295
296impl Plugin for ConsiderationPlugin {
297 fn build(&self, app: &mut App) {
298 app
299 .init_resource::<ShouldReinitConsiderationQueries>()
301 .init_resource::<ConsiderationKeyToSystemMap>()
302 .add_systems(Startup, reinit_consideration_queries)
303 .add_systems(FixedFirst, reinit_consideration_queries)
304 .add_observer(crate::decision_loop::disable_consideration_reinit)
305 ;
306 }
307}