Skip to main content

cranium_core/
context_fetchers.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//! ContextFetchers - registerable Systems that find inputs (Contexts) for ActionTemplates.
8
9use 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
16/// Convenience type-alias for generic inputs piped into each ContextFetcher. 
17/// 
18/// You can use it to simply write `fn your_context_fetcher(params: ContextFetcherInputs, your_query:...`
19/// instead of having to memorize the specific interface required by the library.
20/// 
21/// This currently comprises:
22/// - Requesting AI - as Entity
23/// - Requesting AI's Pawn (controlled Entity) - as Entity
24/// 
25/// Changes to this interface will be considered semver-breaking once the core lib stabilizes.
26/// 
27/// Note that ContextFetchers are Plain Old (Read-Only!) Systems, so you can use `Queries`, 
28/// `Resources` and all the other Bevy goodness to write your ContextFetcher logic - but you 
29/// must also include these inputs as a parameter.
30/// 
31/// The point of those inputs is to let the World inject metadata about the AI query 
32/// into your ContextFetchers so that you can use them in your own logic. 
33/// 
34/// The key Entities in play in particular are included to enable no-fuss fast 
35/// retrieval of data about them in your custom Queries (using `Query::get()`). 
36pub type ContextFetcherInputs = bevy::prelude::In<(
37    AiEntity, 
38    PawnEntityRef,
39)>;
40
41/// Convenience type-alias for the output type required from a ContextFetcher System. 
42pub type ContextFetcherOutputs = crate::types::CraniumList<ActionContext>;
43
44/// A specialization of Bevy's `System` trait (or more precisely, `ReadOnlySystem`) 
45/// that can be used as a Cranium ContextFetcher.
46/// 
47/// Note that the associated `In` type only adds the restriction that your custom 
48/// functions must *at least* accept the metadata piped into them; you can add any 
49/// number of Queries, Resource accesses, etc. - as long as they are read-only.
50pub 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
63/// A specialization of Bevy's `IntoSystem` trait that defines any function 
64/// that can be turned into a valid Cranium ContextFetcher System.
65pub 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
97/// Something that allows us to register a ContextFetcher to the World. 
98/// 
99/// Note that for convenience, the first registration attempt 
100/// will initialize *an empty registry* if one does not exist yet, so
101/// you don't need to use `app.initialize_resource::<UtilityCurveRegistry>()` 
102/// unless you want to be explicit about it.
103pub 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    // SAFETY: This is an Exclusive System, so we are the only one with World access.
190    //         We only really need this to bypass a silly borrow-check on the reference.
191    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    // SAFETY: This is an Exclusive System, so we are the only one with World access, 
205    //         and we are the only ones with a lock on the initialized System.
206    //         We only really need this to bypass a silly borrow-check on the reference.
207    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                    // SAFETY: This is an Exclusive System, so we are the only one with World access, 
222                    //         and we are the only ones with a lock on the initialized System.
223                    //         We only really need this to bypass a silly borrow-check on &muts.
224                    #[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            // Technically unnecessary, but will give users saner error messages if we pre-initialize:
240            .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}