cranium_core/
context_fetchers.rs1use bevy::prelude::*;
10use bevy::platform::prelude::{String, ToOwned};
11use bevy::platform::sync::Arc;
12use crate::types::{self, ActionContext, AiEntity, CraniumKvMap, CraniumRwLock, PawnEntityRef};
13use crate::identifiers::ContextFetcherIdentifier;
14
15
16pub type ContextFetcherInputs = bevy::prelude::In<(
37 AiEntity,
38 PawnEntityRef,
39)>;
40
41pub type ContextFetcherOutputs = crate::types::CraniumList<ActionContext>;
43
44pub trait ContextFetcherSystem: bevy::ecs::system::ReadOnlySystem<
51 In = ContextFetcherInputs,
52 Out = ContextFetcherOutputs,
53> {}
54
55impl<
56 ROS: bevy::ecs::system::ReadOnlySystem<
57 In = ContextFetcherInputs,
58 Out = ContextFetcherOutputs,
59 >
60> ContextFetcherSystem for ROS {}
61
62
63pub trait IntoContextFetcherSystem<Marker>: IntoSystem<
66 ContextFetcherInputs,
67 ContextFetcherOutputs,
68 Marker,
69> {}
70
71impl<
72 CS: ContextFetcherSystem,
73 Marker,
74 IS: IntoSystem<
75 ContextFetcherInputs,
76 ContextFetcherOutputs,
77 Marker,
78 System = CS
79 >
80> IntoContextFetcherSystem<Marker> for IS {}
81
82
83#[derive(Clone)]
84pub struct ContextFetcherMappedToSystem {
85 pub context_fetcher_system: Result<Arc<CraniumRwLock<dyn ContextFetcherSystem>>, ()>,
86}
87
88#[derive(Resource, Default)]
89pub struct ContextFetcherKeyToSystemMap {
90 pub mapping: CraniumKvMap<
91 types::ContextFetcherKey,
92 Arc<CraniumRwLock<dyn ContextFetcherSystem>>
93 >
94}
95
96
97pub trait AcceptsContextFetcherRegistrations {
104 fn register_context_fetcher<
105 CS: ContextFetcherSystem,
106 Marker,
107 F: IntoContextFetcherSystem<Marker, System = CS> + 'static,
108 IS: Into<String>,
109 >(
110 &mut self,
111 context_fetcher: F,
112 key: IS,
113 ) -> &mut Self;
114}
115
116impl AcceptsContextFetcherRegistrations for App {
117 fn register_context_fetcher<
118 CS: ContextFetcherSystem,
119 Marker,
120 F: IntoContextFetcherSystem<Marker, System = CS> + 'static,
121 IS: Into<String>,
122 >(
123 &mut self,
124 context_fetcher: F,
125 key: IS,
126 ) -> &mut Self {
127 self.world_mut().register_context_fetcher(context_fetcher, key);
128 self
129 }
130}
131
132impl AcceptsContextFetcherRegistrations for World {
133 fn register_context_fetcher<
134 CS: ContextFetcherSystem,
135 Marker,
136 F: IntoContextFetcherSystem<Marker, System = CS> + 'static,
137 IS: Into<String>,
138 >(
139 &mut self,
140 context_fetcher: F,
141 key: IS,
142 ) -> &mut Self {
143 let system = F::into_system(context_fetcher);
144 let system_key = ContextFetcherIdentifier::from(key);
145 let mut system_registry = self.get_resource_or_init::<ContextFetcherKeyToSystemMap>();
146
147 let old = system_registry.mapping.insert(
148 system_key.to_owned(),
149 Arc::new(CraniumRwLock::new(
150 system
151 )));
152
153 match old {
154 None => {},
155 Some(_) => {
156 #[cfg(feature = "logging")]
157 bevy::log::warn!(
158 "Detected a key collision for key {:?}. Ejecting previous registration...",
159 system_key
160 );
161 }
162 }
163 self
164 }
165}
166
167#[derive(Resource, Debug)]
168pub struct ShouldReinitCfQueries(bool);
169
170impl ShouldReinitCfQueries {
171 pub fn get(&self) -> bool {
172 self.0
173 }
174
175 pub fn set(&mut self, val: bool) {
176 self.0 = val;
177 }
178}
179
180impl Default for ShouldReinitCfQueries {
181 fn default() -> Self {
182 Self(true)
183 }
184}
185
186pub fn reinit_cf_queries(world: &mut World) {
187 let world_cell = world.as_unsafe_world_cell();
188
189 let should_reinit_res = unsafe {
192 world_cell.get_resource::<ShouldReinitCfQueries>()
193 };
194
195 let should_reinit = match should_reinit_res {
196 None => true,
197 Some(reinit_mark) => reinit_mark.get()
198 };
199
200 if !should_reinit {
201 return
202 };
203
204 let registry = unsafe {
208 world_cell.get_resource_mut::<ContextFetcherKeyToSystemMap>()
209 };
210
211 let mut registry = match registry {
212 None => return,
213 Some(r) => r,
214 };
215
216 registry.mapping.iter_mut().for_each(|(_key, system_lock)| {
217 let write_state = system_lock.write();
218 {
219 match write_state {
220 Ok(mut system) => {
221 #[cfg(feature = "logging")]
225 bevy::log::debug!("reinit_consideration_queries: Reinitializing System {:?}", _key);
226 system.initialize(unsafe { world_cell.world_mut() });
227 },
228 Err(e) => panic!("{:?}", e)
229 }
230 }
231 });
232}
233
234pub struct ContextFetcherPlugin;
235
236impl Plugin for ContextFetcherPlugin {
237 fn build(&self, app: &mut App) {
238 app
239 .init_resource::<ShouldReinitCfQueries>()
241 .init_resource::<ContextFetcherKeyToSystemMap>()
242 .add_systems(Startup, reinit_cf_queries)
243 .add_systems(FixedFirst, reinit_cf_queries)
244 .add_observer(crate::decision_loop::disable_cf_reinit)
245 ;
246 }
247}