use std::sync::Arc;
use bevy_app::App;
use bevy_ecs::{
resource::Resource,
schedule::{InternedSystemSet, SystemSet},
};
use bevy_log::warn;
use bevy_platform::collections::HashMap;
use bevy_system_reflection::ReflectSystemSet;
use crate::{
AppScriptNamespaceMembers, IntoScript, NamespaceValue, SCRIPT_NAMESPACE_PREFIX,
docgen::typed_through::TypedThrough, function::from::V, script_path,
};
#[derive(SystemSet, Clone, Hash, PartialEq, Eq, Debug)]
pub struct ScriptNamedSet(pub String);
#[derive(Resource, Default)]
pub struct ScriptSystemSetRegistry {
sets: HashMap<String, InternedSystemSet>,
}
impl ScriptSystemSetRegistry {
pub fn register(&mut self, path: String, set: InternedSystemSet) {
self.sets.insert(path, set);
}
pub fn get(&self, path: &str) -> Option<InternedSystemSet> {
self.sets.get(path).copied()
}
}
pub trait ScriptSystemSetAppExt {
fn register_script_system_set(
&mut self,
namespace: &'static str,
name: &'static str,
set: impl SystemSet,
) -> &mut Self;
}
impl ScriptSystemSetAppExt for App {
fn register_script_system_set(
&mut self,
namespace: &'static str,
name: &'static str,
set: impl SystemSet,
) -> &mut Self {
if namespace.starts_with(SCRIPT_NAMESPACE_PREFIX) {
warn!(
"Cannot register the system set `{set:?}` into the script namespace `{namespace}`, script namespaces are reserved for sets registered by scripts"
);
return self;
}
let set = set.intern();
let world = self.world_mut();
world
.get_resource_or_init::<ScriptSystemSetRegistry>()
.register(script_path(namespace, name), set);
world
.get_resource_or_init::<AppScriptNamespaceMembers>()
.write()
.register_value(
namespace,
name,
NamespaceValue {
maker: Arc::new(move |world| {
V(ReflectSystemSet::from_interned(set)).into_script(world)
}),
type_information: <V<ReflectSystemSet> as TypedThrough>::through_type_info(),
documentation: Some(format!("The `{set:?}` system set.").into()),
},
);
self
}
}