Skip to main content

bevy_mod_scripting_bindings/
script_component.rs

1//! Everything necessary to support scripts registering their own components
2
3use super::{InteropError, ScriptComponentRegistration, ScriptEventRegistration, ScriptValue};
4use crate::ScriptNamespaceAppExt;
5use ::{
6    bevy_app::{App, Plugin},
7    bevy_ecs::component::{Component, Mutable, StorageType},
8};
9use bevy_ecs::{entity::Entity, resource::Resource, world::World};
10use bevy_mod_scripting_script::ScriptAttachment;
11use bevy_platform::collections::HashMap;
12use bevy_reflect::{Reflect, std_traits::ReflectDefault};
13use parking_lot::RwLock;
14use std::sync::Arc;
15
16/// A dynamic script component
17#[derive(Reflect, Clone, Default, Debug)]
18#[reflect(Default)]
19pub struct DynamicComponent {
20    data: ScriptValue,
21}
22
23impl DynamicComponent {
24    /// Creates a new dynamic component holding the given data
25    pub fn new(data: ScriptValue) -> Self {
26        Self { data }
27    }
28
29    /// Returns the data held by this component
30    pub fn data(&self) -> &ScriptValue {
31        &self.data
32    }
33}
34
35/// The prefix all namespaces defined by scripts must start with.
36pub const SCRIPT_NAMESPACE_PREFIX: &str = "script.";
37
38/// Joins a script namespace and a name into the full path types are registered under, i.e. `script.game.Enemy`.
39pub fn script_path(namespace: &str, name: &str) -> String {
40    format!("{namespace}.{name}")
41}
42
43/// Checks that a namespace and name given by a script to register something are valid.
44///
45/// Namespaces defined by scripts must start with `script.` followed by at least one segment, segments are separated by dots and
46/// made up of letters, digits and underscores. Names cannot contain dots.
47pub fn validate_script_namespace_and_name(namespace: &str, name: &str) -> Result<(), InteropError> {
48    let invalid_segment = |segment: &str| {
49        segment.is_empty() || !segment.chars().all(|c| c.is_alphanumeric() || c == '_')
50    };
51    let Some(rest) = namespace.strip_prefix(SCRIPT_NAMESPACE_PREFIX) else {
52        return Err(InteropError::string(format!(
53            "script namespaces must start with `{SCRIPT_NAMESPACE_PREFIX}` (i.e. `{SCRIPT_NAMESPACE_PREFIX}my_game`), got `{namespace}`. \
54            Other namespaces are the names of crates, which scripts cannot add to."
55        )));
56    };
57    if rest.split('.').any(invalid_segment) {
58        return Err(InteropError::string(format!(
59            "invalid script namespace `{namespace}`: after `{SCRIPT_NAMESPACE_PREFIX}` it must be made up of non empty segments \
60            of letters, digits and underscores separated by dots"
61        )));
62    }
63    if name.is_empty() || name.contains('.') {
64        return Err(InteropError::string(format!(
65            "invalid name `{name}` for something registered in `{namespace}`: it cannot be empty or contain dots"
66        )));
67    }
68    Ok(())
69}
70
71/// A function exported by a script, see [`ScriptComponentRegistry::register_export`].
72///
73/// The function itself stays in the script that exports it: it is a callback of that script, and calls to it run through the callback runners.
74#[derive(Clone, Debug)]
75pub struct ScriptExport {
76    /// The name of the export within its namespace
77    pub name: String,
78    /// The script namespace the function was exported into
79    pub namespace: String,
80    /// The script that exported the function, and which runs it
81    pub owner: ScriptAttachment,
82    /// The label of the callback of the owner that is the exported function
83    pub label: String,
84}
85
86impl ScriptExport {
87    /// The full path of the export, which is unique, i.e. `script.game.spawn_enemy`
88    pub fn path(&self) -> String {
89        script_path(&self.namespace, &self.name)
90    }
91}
92
93/// Marks the entity of an observer added by a script, which is removed when the script is unloaded.
94#[derive(Component, Clone, Debug)]
95pub struct ScriptObserverOwner(pub ScriptAttachment);
96
97/// Removes everything a script registered which is tied to the script running: its exports, system sets and observers.
98///
99/// Called when the script is unloaded (also when it is about to be reloaded, the script registers them again when it runs).
100/// Components, bundles and events stay registered, as Bevy can not unregister components, scripts re-registering them
101/// on reload use `allow_existing`. System sets are only removed from their namespace, they stay in the schedules.
102pub fn remove_script_registrations(world: &mut World, attachment: &ScriptAttachment) {
103    if let Some(registry) = world.get_resource::<AppScriptComponentRegistry>() {
104        let mut registry = registry.write();
105        registry.remove_exports_of(attachment);
106        registry.remove_system_sets_of(attachment);
107    }
108    let observers = world
109        .query::<(Entity, &ScriptObserverOwner)>()
110        .iter(world)
111        .filter(|(_, owner)| owner.0 == *attachment)
112        .map(|(entity, _)| entity)
113        .collect::<Vec<_>>();
114    for observer in observers {
115        world.despawn(observer);
116    }
117}
118
119/// Some metadata about dynamic script components
120pub struct DynamicComponentInfo {
121    /// The name of the component within its namespace
122    pub name: String,
123    /// The script namespace the component was registered in
124    pub namespace: String,
125    /// The type registration for the component
126    pub registration: ScriptComponentRegistration,
127}
128
129impl DynamicComponentInfo {
130    /// The full path of the component, which is unique, i.e. `script.game.Enemy`
131    pub fn path(&self) -> String {
132        script_path(&self.namespace, &self.name)
133    }
134}
135
136impl Component for DynamicComponent {
137    const STORAGE_TYPE: StorageType = StorageType::Table;
138    type Mutability = Mutable;
139}
140
141/// A registry of dynamically registered script components
142#[derive(Clone, Resource, Default)]
143pub struct AppScriptComponentRegistry(pub Arc<RwLock<ScriptComponentRegistry>>);
144
145#[profiling::all_functions]
146impl AppScriptComponentRegistry {
147    /// Reads the underlying registry
148    pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, ScriptComponentRegistry> {
149        self.0.read()
150    }
151
152    /// Writes to the underlying registry
153    pub fn write(&self) -> parking_lot::RwLockWriteGuard<'_, ScriptComponentRegistry> {
154        self.0.write()
155    }
156}
157
158#[derive(Default)]
159/// A registry of dynamically registered script components, events, exports and system sets
160pub struct ScriptComponentRegistry {
161    components: HashMap<String, DynamicComponentInfo>,
162    events: HashMap<String, ScriptEventRegistration>,
163    exports: HashMap<String, ScriptExport>,
164    /// The scripts which registered each system set, by its full path, see [`crate::ScriptNamedSet`]
165    system_sets: HashMap<String, ScriptAttachment>,
166    generation: u64,
167}
168
169#[profiling::all_functions]
170impl ScriptComponentRegistry {
171    /// Registers a dynamic script component, possibly overwriting an existing one
172    pub fn register(&mut self, info: DynamicComponentInfo) {
173        self.components.insert(info.path(), info);
174        self.generation += 1;
175    }
176
177    /// Gets a dynamic script component by its full path, i.e. `script.game.Enemy`
178    pub fn get(&self, path: &str) -> Option<&DynamicComponentInfo> {
179        self.components.get(path)
180    }
181
182    /// Gets a dynamic script component by its full path (i.e. `script.game.Enemy`).
183    pub fn find(&self, path: &str) -> Option<&DynamicComponentInfo> {
184        self.components.get(path)
185    }
186
187    /// A counter which changes whenever a component is registered.
188    ///
189    /// Lookups of existing registrations do not change it.
190    pub fn generation(&self) -> u64 {
191        self.generation
192    }
193
194    /// Iterates over all registered script components
195    pub fn iter_components(&self) -> impl Iterator<Item = &DynamicComponentInfo> {
196        self.components.values()
197    }
198
199    /// Registers a script event, possibly overwriting an existing one
200    pub fn register_event(&mut self, registration: ScriptEventRegistration) {
201        self.events
202            .insert(registration.name.to_string(), registration);
203    }
204
205    /// Gets a script event by its full path
206    pub fn get_event(&self, name: &str) -> Option<&ScriptEventRegistration> {
207        self.events.get(name)
208    }
209
210    /// Registers a function exported by a script.
211    ///
212    /// Exporting the same path again from the same script replaces the export (i.e. when a script runs again),
213    /// exporting a path another script exported, or one used by a component or event, is an error.
214    pub fn register_export(&mut self, export: ScriptExport) -> Result<(), InteropError> {
215        let path = export.path();
216        if let Some(existing) = self.exports.get(&path)
217            && existing.owner != export.owner
218        {
219            return Err(InteropError::string(format!(
220                "`{path}` is already exported by script {}, exports have to be unique",
221                existing.owner
222            )));
223        }
224        if self.components.contains_key(&path)
225            || self.events.contains_key(&path)
226            || self.system_sets.contains_key(&path)
227        {
228            return Err(InteropError::string(format!(
229                "cannot export `{path}`: a script registered component, event or system set has that path"
230            )));
231        }
232        self.exports.insert(path, export);
233        Ok(())
234    }
235
236    /// Removes all exports of the given script, returns how many there were
237    pub fn remove_exports_of(&mut self, owner: &ScriptAttachment) -> usize {
238        let before = self.exports.len();
239        self.exports.retain(|_, export| export.owner != *owner);
240        before - self.exports.len()
241    }
242
243    /// Gets an export by its full path
244    pub fn get_export(&self, path: &str) -> Option<&ScriptExport> {
245        self.exports.get(path)
246    }
247
248    /// Iterates over the exports of the given namespace
249    pub fn iter_exports_in<'a>(
250        &'a self,
251        namespace: &'a str,
252    ) -> impl Iterator<Item = &'a ScriptExport> {
253        self.exports
254            .values()
255            .filter(move |e| e.namespace == namespace)
256    }
257
258    /// Iterates over the script events of the given namespace, with their names within it
259    pub fn iter_events_in<'a>(
260        &'a self,
261        namespace: &'a str,
262    ) -> impl Iterator<Item = (&'a str, &'a ScriptEventRegistration)> {
263        self.events.iter().filter_map(move |(path, event)| {
264            // names cannot contain dots, so the namespace is everything before the last one
265            let (event_namespace, name) = path.rsplit_once('.')?;
266            (event_namespace == namespace).then_some((name, event))
267        })
268    }
269
270    /// The namespaces with at least one export, event or system set, in no particular order, possibly repeated
271    pub fn export_and_event_namespaces(&self) -> impl Iterator<Item = &str> {
272        self.exports.values().map(|e| e.namespace.as_str()).chain(
273            self.events
274                .keys()
275                .chain(self.system_sets.keys())
276                .filter_map(|p| Some(p.rsplit_once('.')?.0)),
277        )
278    }
279
280    /// Registers a system set of a script by its full path, i.e. `script.game.ai`, possibly replacing its owner
281    pub fn register_system_set(&mut self, path: String, owner: ScriptAttachment) {
282        self.system_sets.insert(path, owner);
283    }
284
285    /// The script which registered the system set with the given full path
286    pub fn get_system_set_owner(&self, path: &str) -> Option<&ScriptAttachment> {
287        self.system_sets.get(path)
288    }
289
290    /// Removes all system sets registered by the given script, returns how many there were.
291    ///
292    /// The sets stay in the schedules, systems can still be in and ordered against them.
293    pub fn remove_system_sets_of(&mut self, owner: &ScriptAttachment) -> usize {
294        let before = self.system_sets.len();
295        self.system_sets.retain(|_, set_owner| set_owner != owner);
296        before - self.system_sets.len()
297    }
298
299    /// Iterates over the full paths and names of the system sets registered into the given namespace
300    pub fn iter_system_sets_in<'a>(
301        &'a self,
302        namespace: &'a str,
303    ) -> impl Iterator<Item = (&'a str, &'a str)> {
304        self.system_sets.keys().filter_map(move |path| {
305            let (set_namespace, name) = path.rsplit_once('.')?;
306            (set_namespace == namespace).then_some((path.as_str(), name))
307        })
308    }
309}
310
311/// A plugin to support dynamic script components
312pub struct DynamicScriptComponentPlugin;
313
314impl Plugin for DynamicScriptComponentPlugin {
315    fn build(&self, app: &mut App) {
316        app.init_resource::<AppScriptComponentRegistry>()
317            .register_type::<DynamicComponent>()
318            .override_script_namespace::<DynamicComponent>("bms");
319    }
320}
321
322#[cfg(test)]
323mod test {
324    use bevy_ecs::world::World;
325    use bevy_mod_scripting_world::{WorldAccessGuard, WorldGuard};
326
327    use crate::{CurrentScriptAttachment, WorldExtensions};
328
329    use super::*;
330
331    #[test]
332    fn test_script_component() {
333        let mut world = World::new();
334        world.init_resource::<AppScriptComponentRegistry>();
335        let cache = WorldGuard::setup_cache(&world, CurrentScriptAttachment::empty());
336        let registration = {
337            let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
338
339            guard
340                .register_script_component("script.test", "ScriptTest", false)
341                .unwrap()
342        };
343
344        let registry = world.get_resource::<AppScriptComponentRegistry>().unwrap();
345
346        let registry = registry.read();
347        let info = registry.get("script.test.ScriptTest").unwrap();
348        assert_eq!(info.registration.component_id, registration.component_id);
349        assert_eq!(info.name, "ScriptTest");
350        assert_eq!(info.registration.namespace(), "script.test");
351
352        // can get the component through the world
353        let component = world
354            .components()
355            .get_info(info.registration.component_id)
356            .unwrap();
357
358        assert_eq!(component.name(), "script.test.ScriptTest".into());
359    }
360}