strafe-client/src/context.rs
2024-10-03 18:01:42 -07:00

47 lines
1.5 KiB
Rust

use rbx_dom_weak::{types::Ref,InstanceBuilder,WeakDom};
pub fn class_is_a(class:&str,superclass:&str)->bool{
class==superclass
||rbx_reflection_database::get().classes.get(class)
.is_some_and(|descriptor|
descriptor.superclass.as_ref().is_some_and(|class_super|
class_is_a(class_super,superclass)
)
)
}
#[repr(transparent)]
pub struct Context{
pub(crate)dom:WeakDom,
}
impl Context{
pub const fn new(dom:WeakDom)->Self{
Self{dom}
}
pub fn script_singleton(source:String)->(Context,crate::runner::instance::Script,crate::place::Services){
let script=InstanceBuilder::new("Script")
.with_property("Source",rbx_types::Variant::String(source));
let script_ref=script.referent();
let (dom,services)=crate::place::new_place_with_instances_in_workspace(
WeakDom::new(
InstanceBuilder::new("DataModel")
.with_child(script)
)
);
(Context{dom},crate::runner::instance::Script::new(script_ref),services)
}
pub fn from_mut(dom:&mut WeakDom)->&mut Context{
unsafe{&mut *(dom as *mut WeakDom as *mut Context)}
}
/// Creates an iterator over all items of a particular class.
pub fn superclass_iter<'a>(&'a self,superclass:&'a str)->impl Iterator<Item=Ref>+'a{
self.dom.descendants().filter(|&instance|
class_is_a(instance.class.as_ref(),superclass)
).map(|instance|instance.referent())
}
pub fn scripts(&self)->Vec<crate::runner::instance::Script>{
self.superclass_iter("LuaSourceContainer").map(crate::runner::instance::Script::new).collect()
}
}