Compare commits

...

7 Commits

5 changed files with 169 additions and 161 deletions

49
Cargo.lock generated
View File

@ -183,6 +183,48 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "phf"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc"
dependencies = [
"phf_macros",
"phf_shared",
]
[[package]]
name = "phf_generator"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0"
dependencies = [
"phf_shared",
"rand",
]
[[package]]
name = "phf_macros"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b"
dependencies = [
"phf_generator",
"phf_shared",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "phf_shared"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b"
dependencies = [
"siphasher",
]
[[package]]
name = "pkg-config"
version = "0.3.30"
@ -322,6 +364,7 @@ version = "0.4.1"
dependencies = [
"glam",
"mlua",
"phf",
"rbx_dom_weak",
"rbx_reflection",
"rbx_reflection_database",
@ -360,6 +403,12 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "siphasher"
version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
[[package]]
name = "syn"
version = "2.0.77"

View File

@ -10,6 +10,7 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
[dependencies]
glam = "0.29.0"
mlua = { version = "0.9.9", features = ["luau"] }
phf = { version = "0.11.2", features = ["macros"] }
rbx_dom_weak = { version = "2.7.0", registry = "strafesnet" }
rbx_reflection = { version = "4.7.0", registry = "strafesnet" }
rbx_reflection_database = { version = "0.2.10", registry = "strafesnet" }

View File

@ -19,7 +19,7 @@ impl Context{
pub const fn new(dom:WeakDom)->Self{
Self{dom}
}
pub fn script_singleton(source:String)->(Context,crate::runner::instance::Script,Services){
pub fn script_singleton(source:String)->(Context,crate::runner::instance::Instance,Services){
let script=InstanceBuilder::new("Script")
.with_property("Source",rbx_types::Variant::String(source));
let script_ref=script.referent();
@ -28,7 +28,7 @@ impl Context{
.with_child(script)
));
let services=context.convert_into_place();
(context,crate::runner::instance::Script::new(script_ref),services)
(context,crate::runner::instance::Instance::new(script_ref),services)
}
pub fn from_ref(dom:&WeakDom)->&Context{
unsafe{&*(dom as *const WeakDom as *const Context)}
@ -42,8 +42,8 @@ impl Context{
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()
pub fn scripts(&self)->Vec<crate::runner::instance::Instance>{
self.superclass_iter("LuaSourceContainer").map(crate::runner::instance::Instance::new).collect()
}
pub fn find_services(&self)->Option<Services>{

View File

@ -1,10 +1,36 @@
use mlua::IntoLua;
use std::collections::{hash_map::Entry,HashMap};
use mlua::{IntoLua,IntoLuaMulti};
use rbx_types::Ref;
use rbx_dom_weak::{InstanceBuilder,WeakDom};
use super::vector3::Vector3;
/// A store of created functions for each Roblox class.
/// Functions are created the first time they are accessed and stored in this data structure.
#[derive(Default)]
struct ClassFunctions<'a>{
classes:HashMap<&'static str,//ClassName
HashMap<&'static str,//Function name
mlua::Function<'a>
>
>
}
fn place_id<'lua>(lua:&'lua mlua::Lua,tuple:mlua::MultiValue<'lua>)->mlua::Result<mlua::MultiValue<'lua>>{
0.into_lua_multi(lua)
}
type FPointer=for<'lua> fn(&'lua mlua::Lua,mlua::MultiValue<'lua>)->mlua::Result<mlua::MultiValue<'lua>>;
static CLASS_FUNCTION_DATABASE:phf::Map<&str,phf::Map<&str,FPointer>>=phf::phf_map!{
"DataModel"=>phf::phf_map!{
"GetService"=>place_id as FPointer,
}
};
pub fn set_globals(lua:&mlua::Lua,globals:&mlua::Table<'_>)->Result<(),mlua::Error>{
//class functions store
lua.set_app_data::<ClassFunctions<'static>>(ClassFunctions::default());
let instance_table=lua.create_table()?;
//Instance.new
@ -29,6 +55,10 @@ fn dom_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut WeakDom)->mlua::Result<T>)->m
let mut dom=lua.app_data_mut::<&'static mut WeakDom>().ok_or(mlua::Error::runtime("DataModel missing"))?;
f(&mut *dom)
}
fn class_functions_mut<T>(lua:&mlua::Lua,mut f:impl FnMut(&mut ClassFunctions<'_>)->mlua::Result<T>)->mlua::Result<T>{
let mut dom=lua.app_data_mut::<ClassFunctions<'static>>().ok_or(mlua::Error::runtime("ClassFunctions missing"))?;
f(&mut *dom)
}
fn coerce_float32(value:&mlua::Value)->Option<f32>{
match value{
@ -48,6 +78,17 @@ fn get_full_name(dom:&rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance)->S
}
full_name
}
//helper function for script
pub fn get_name_source(lua:&mlua::Lua,script:Instance)->Result<(String,String),mlua::Error>{
dom_mut(lua,|dom|{
let instance=script.get(dom)?;
let source=match instance.properties.get("Source"){
Some(rbx_dom_weak::types::Variant::String(s))=>s.clone(),
_=>Err(mlua::Error::external("Missing script.Source"))?,
};
Ok((get_full_name(dom,instance),source))
})
}
pub fn find_first_child<'a>(dom:&'a rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance,name:&str)->Option<&'a rbx_dom_weak::Instance>{
instance.children().iter().filter_map(|&r|dom.get_by_ref(r)).find(|inst|inst.name==name)
@ -63,63 +104,22 @@ pub fn find_first_descendant_of_class<'a>(dom:&'a rbx_dom_weak::WeakDom,instance
dom.descendants_of(instance.referent()).find(|&inst|inst.class==class)
}
//workaround until I have an enum of classes
struct Dereferent(Ref);
impl mlua::UserData for Dereferent{}
type_from_lua_userdata!(Dereferent);
impl Referent for Dereferent{
fn referent(&self)->Ref{
self.0
}
}
trait Referent{
fn referent(&self)->Ref;
fn get<'a>(&self,dom:&'a WeakDom)->mlua::Result<&'a rbx_dom_weak::Instance>{
dom.get_by_ref(self.referent()).ok_or(mlua::Error::runtime("Instance missing"))
}
fn get_mut<'a>(&self,dom:&'a mut WeakDom)->mlua::Result<&'a mut rbx_dom_weak::Instance>{
dom.get_by_ref_mut(self.referent()).ok_or(mlua::Error::runtime("Instance missing"))
}
}
macro_rules! class{
($class:ident)=>{
pub struct $class{
#[derive(Clone,Copy)]
pub struct Instance{
referent:Ref,
}
impl $class{
}
impl Instance{
pub const fn new(referent:Ref)->Self{
Self{referent}
}
pub fn get<'a>(&self,dom:&'a WeakDom)->mlua::Result<&'a rbx_dom_weak::Instance>{
dom.get_by_ref(self.referent).ok_or(mlua::Error::runtime("Instance missing"))
}
impl Referent for $class{
fn referent(&self)->Ref{
self.referent
pub fn get_mut<'a>(&self,dom:&'a mut WeakDom)->mlua::Result<&'a mut rbx_dom_weak::Instance>{
dom.get_by_ref_mut(self.referent).ok_or(mlua::Error::runtime("Instance missing"))
}
}
type_from_lua_userdata!($class);
};
}
macro_rules! class_composition{
($class:ident,($($superclass:ident),*))=>{
impl mlua::UserData for $class{
fn add_fields<'lua,F:mlua::UserDataFields<'lua,Self>>(fields:&mut F){
fields.add_field_method_get("Referent",|_,this|{
Ok(Dereferent(this.referent()))
});
$(
$superclass::composition_add_fields(fields);
)*
}
fn add_methods<'lua,M:mlua::UserDataMethods<'lua,Self>>(methods:&mut M){
$(
$superclass::composition_add_methods(methods);
)*
}
}
};
}
type_from_lua_userdata!(Instance);
//TODO: update rbx_reflection and use dom.superclasses_iter
pub struct SuperClassIter<'a> {
@ -140,21 +140,18 @@ impl<'a> Iterator for SuperClassIter<'a> {
}
}
class!(Instance);
class_composition!(Instance,(Instance));
impl Instance{
fn composition_add_fields<'lua,T:Referent,F:mlua::UserDataFields<'lua,T>>(fields:&mut F){
impl mlua::UserData for Instance{
fn add_fields<'lua,F:mlua::UserDataFields<'lua,Self>>(fields:&mut F){
fields.add_field_method_get("Parent",|lua,this|{
dom_mut(lua,|dom|{
let instance=this.get(dom)?;
Ok(Instance::new(instance.parent()))
})
});
fields.add_field_method_set("Parent",|lua,this,val:mlua::AnyUserData|{
let Dereferent(referent)=mlua::AnyUserDataExt::get(&val,"Referent")?;
fields.add_field_method_set("Parent",|lua,this,val:Option<Instance>|{
let parent=val.ok_or(mlua::Error::runtime("Nil Parent not yet supported"))?;
dom_mut(lua,|dom|{
dom.transfer_within(this.referent(),referent);
dom.transfer_within(this.referent,parent.referent);
Ok(())
})
});
@ -179,7 +176,7 @@ impl Instance{
})
});
}
fn composition_add_methods<'lua,T:Referent,M:mlua::UserDataMethods<'lua,T>>(methods:&mut M){
fn add_methods<'lua,M:mlua::UserDataMethods<'lua,Self>>(methods:&mut M){
methods.add_method("GetChildren",|lua,this,_:()|
dom_mut(lua,|dom|{
let instance=this.get(dom)?;
@ -192,7 +189,7 @@ impl Instance{
Ok(children)
})
);
let ffc=|lua,this:&T,(name,search_descendants):(mlua::String,Option<bool>)|{
let ffc=|lua,this:&Self,(name,search_descendants):(mlua::String,Option<bool>)|{
let name_str=name.to_str()?;
dom_mut(lua,|dom|{
let instance=this.get(dom)?;
@ -226,7 +223,7 @@ impl Instance{
methods.add_method("GetDescendants",|lua,this,_:()|
dom_mut(lua,|dom|{
let children:Vec<_>=dom
.descendants_of(this.referent())
.descendants_of(this.referent)
.map(|instance|
Instance::new(instance.referent())
)
@ -242,15 +239,14 @@ impl Instance{
);
methods.add_method("Destroy",|lua,this,()|
dom_mut(lua,|dom|{
dom.destroy(this.referent());
dom.destroy(this.referent);
Ok(())
})
);
methods.add_meta_function(mlua::MetaMethod::Index,|lua,(this,index):(mlua::AnyUserData,mlua::String)|{
methods.add_meta_function(mlua::MetaMethod::Index,|lua,(this,index):(Instance,mlua::String)|{
let index_str=index.to_str()?;
let dereferent:Dereferent=mlua::AnyUserDataExt::get(&this,"Referent")?;
dom_mut(lua,|dom|{
let instance=dereferent.get(dom)?;
let instance=this.get(dom)?;
//Find existing property
match instance.properties.get(index_str)
//Find default value
@ -265,6 +261,48 @@ impl Instance{
Some(&rbx_types::Variant::Vector3(v))=>return Ok(Into::<super::vector3::Vector3>::into(v).into_lua(lua)),
_=>(),
}
//find a function with a matching name
if let Some(ret)=class_functions_mut(lua,|cf|{
let class_str=instance.class.as_str();
let f=match CLASS_FUNCTION_DATABASE.get_entry(class_str){
Some((&static_class_str,class_functions))=>{
match cf.classes.entry(static_class_str){
Entry::Occupied(mut occupied_entry)=>{
match class_functions.get_entry(index_str){
Some((&static_index_str,function_pointer))=>{
match occupied_entry.get_mut().entry(static_index_str){
Entry::Occupied(occupied_entry)=>{
Some(occupied_entry.get().clone())
},
Entry::Vacant(vacant_entry)=>{
Some(vacant_entry.insert(unsafe{core::mem::transmute(lua.create_function(function_pointer)?)}).clone())
},
}
},
None=>None,
}
},
Entry::Vacant(vacant_entry)=>{
match class_functions.get_entry(index_str){
Some((&static_index_str,function_pointer))=>{
let mut h=HashMap::new();
h.entry(static_index_str).or_insert(unsafe{core::mem::transmute(lua.create_function(function_pointer)?)});
vacant_entry.insert(h).get(static_index_str).map(|f|f.clone())
},
None=>None,
}
},
}
},
None=>None,
};
Ok(f.map(|f|{
let f_static:mlua::Function::<'static>=unsafe{core::mem::transmute(f)};
f_static
}))
})?{
return Ok(ret.into_lua(lua));
}
//find a child with a matching name
Ok(
find_first_child(dom,instance,index_str)
@ -273,10 +311,9 @@ impl Instance{
)
})
});
methods.add_meta_function(mlua::MetaMethod::NewIndex,|lua,(this,index,value):(mlua::AnyUserData,mlua::String,mlua::Value)|{
let dereferent:Dereferent=mlua::AnyUserDataExt::get(&this,"Referent")?;
methods.add_meta_function(mlua::MetaMethod::NewIndex,|lua,(this,index,value):(Instance,mlua::String,mlua::Value)|{
dom_mut(lua,|dom|{
let instance=dereferent.get_mut(dom)?;
let instance=this.get_mut(dom)?;
//println!("__newindex t={} i={index:?} v={value:?}",instance.name);
let index_str=index.to_str()?;
let db=rbx_reflection_database::get();
@ -330,82 +367,3 @@ impl Instance{
});
}
}
class!(DataModel);
class_composition!(DataModel,(Instance,DataModel));
impl DataModel{
fn composition_add_fields<'lua,T:Referent,F:mlua::UserDataFields<'lua,T>>(fields:&mut F){
fields.add_field_method_get("workspace",|lua,this|{
dom_mut(lua,|dom|{
Ok(find_first_child_of_class(dom,this.get(dom)?,"Workspace")
.map(|inst|Workspace::new(inst.referent()))
)
})
});
fields.add_field_method_get("PlaceId",|lua,this|{
Ok(mlua::Value::Integer(0))
});
}
fn composition_add_methods<'lua,T,M:mlua::UserDataMethods<'lua,T>>(methods:&mut M){
methods.add_method("GetService",|lua,this,service:String|
dom_mut(lua,|dom|{
match service.as_str(){
"Lighting"=>{
let referent=find_first_child_of_class(dom,dom.root(),"Lighting")
.map(|instance|instance.referent())
.unwrap_or_else(||
dom.insert(dom.root_ref(),InstanceBuilder::new("Lighting"))
);
Lighting::new(referent).into_lua(lua)
},
other=>Err::<mlua::Value,_>(mlua::Error::runtime(format!("Service '{other}' not supported"))),
}
})
);
}
}
class!(Workspace);
class_composition!(Workspace,(Instance,Workspace));
impl Workspace{
fn composition_add_fields<'lua,T:Referent,F:mlua::UserDataFields<'lua,T>>(fields:&mut F){
fields.add_field_method_get("Terrain",|lua,this|{
dom_mut(lua,|dom|{
Ok(find_first_child_of_class(dom,this.get(dom)?,"Terrain")
.map(|inst|Terrain::new(inst.referent()))
)
})
});
}
fn composition_add_methods<'lua,T,M:mlua::UserDataMethods<'lua,T>>(_methods:&mut M){
}
}
class!(Lighting);
class_composition!(Lighting,(Instance));
class!(Script);
class_composition!(Script,(Instance));
impl Script{
pub fn get_name_source(&self,lua:&mlua::Lua)->Result<(String,String),mlua::Error>{
dom_mut(lua,|dom|{
let instance=self.get(dom)?;
let source=match instance.properties.get("Source"){
Some(rbx_dom_weak::types::Variant::String(s))=>s.clone(),
_=>Err(mlua::Error::external("Missing script.Source"))?,
};
Ok((get_full_name(dom,instance),source))
})
}
}
class!(Terrain);
class_composition!(Terrain,(Instance,Terrain));
impl Terrain{
fn composition_add_fields<'lua,T:Referent,F:mlua::UserDataFields<'lua,T>>(fields:&mut F){
}
fn composition_add_methods<'lua,T,M:mlua::UserDataMethods<'lua,T>>(methods:&mut M){
methods.add_method("FillBlock",|lua,this,_:(super::cframe::CFrame,Vector3,super::r#enum::Enum)|
Ok(())//Ok(mlua::Value::Nil)
)
}
}

View File

@ -53,8 +53,8 @@ impl Runner{
pub fn runnable_context_with_services<'a>(self,context:&'a mut Context,services:&crate::context::Services)->Result<Runnable<'a>,Error>{
{
let globals=self.lua.globals();
globals.set("game",super::instance::DataModel::new(services.game)).map_err(Error::RustLua)?;
globals.set("workspace",super::instance::Workspace::new(services.workspace)).map_err(Error::RustLua)?;
globals.set("game",super::instance::Instance::new(services.game)).map_err(Error::RustLua)?;
globals.set("workspace",super::instance::Instance::new(services.workspace)).map_err(Error::RustLua)?;
}
//this makes set_app_data shut up about the lifetime
self.lua.set_app_data::<&'static mut rbx_dom_weak::WeakDom>(unsafe{core::mem::transmute(&mut context.dom)});
@ -77,8 +77,8 @@ impl Runnable<'_>{
lua:self.lua,
}
}
pub fn run_script(&self,script:super::instance::Script)->Result<(),Error>{
let (name,source)=script.get_name_source(&self.lua).map_err(Error::RustLua)?;
pub fn run_script(&self,script:super::instance::Instance)->Result<(),Error>{
let (name,source)=super::instance::get_name_source(&self.lua,script).map_err(Error::RustLua)?;
self.lua.globals().set("script",script).map_err(Error::RustLua)?;
self.lua.load(source.as_str())
.set_name(name)