Theoretically can add children from script

This commit is contained in:
Dane Johnson 2022-04-15 20:31:13 -05:00
parent d22584c44e
commit 2d5ce7ae98
3 changed files with 17 additions and 29 deletions

View File

@ -17,25 +17,6 @@ pub trait Childbearing<T> { // TODO remove this
fn add_child(&mut self, name: &str, child: T);
}
impl Node {
pub fn find_node(&self, name: &str) -> Option<NodeRef> {
self.children
.iter()
.find(|node| node.borrow().name == name)
.map(Rc::clone)
}
}
macro_rules! impl_childbearing {
($t:ty, $e:path) => {
impl Childbearing<$t> for Node {
fn add_child(&mut self, name: &str, child: $t) {
self.children.push(Rc::new(RefCell::new(Node::new(name.to_string(), $e(Box::new(child))))));
}
}
}
}
impl Node {
pub fn new(name: String, gameobject: GameObject) -> Self {
Node {
@ -44,6 +25,15 @@ impl Node {
children: Vec::new(),
}
}
pub fn find_node(&self, name: &str) -> Option<NodeRef> {
self.children
.iter()
.find(|node| node.borrow().name == name)
.map(Rc::clone)
}
pub fn add_child(&mut self, child: NodeRef) {
self.children.push(child)
}
}
pub enum GameObject {
@ -114,8 +104,6 @@ impl Spatial for Camera {
}
}
impl_childbearing!(Camera, GameObject::Camera);
pub struct Mesh {
pub model: Model,
transform: Transform,
@ -138,5 +126,3 @@ impl Spatial for Mesh {
self.transform = transform;
}
}
impl_childbearing!(Mesh, GameObject::Mesh);

View File

@ -33,15 +33,14 @@ fn main() {
{
// Initial scene setup
let mut root = root.borrow_mut();
root.add_child("camera", Camera::new());
let mut cube = Mesh::new(Model::new(&display, "Box.glb"));
cube.set_transform(gameobject::Transform {
position: glm::vec3(0.0, 0.0, -10.0),
rotation: glm::vec3(0.0, 15.0_f32.to_radians(), 0.0),
scale: glm::vec3(1.0, 1.0, 1.0),
});
root.add_child("cube", cube);
root.add_child(Rc::new(RefCell::new(Node::new("cube".to_string(), GameObject::Mesh(Box::new(cube))))));
}
let mut script_lang = Lua::new(Rc::clone(&root));

View File

@ -1,8 +1,7 @@
use super::*;
use crate::gameobject::{ Node, Transform };
use crate::gameobject::{ Node, NodeRef, Transform };
extern crate mlua;
use mlua::Lua as LuaContext;
use mlua::Error::RuntimeError as LuaError;
use mlua::chunk;
@ -61,13 +60,17 @@ impl ScriptLang for Lua {
impl mlua::UserData for Node {
fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
methods.add_method_mut("find_node", |_, this, name: String| {
methods.add_method("find_node", |_, this, name: String| {
let child = this.find_node(&name);
match child {
Some(child) => Ok(child),
None => Err(mlua::Error::RuntimeError("Could not find child".to_string())),
}
});
methods.add_method_mut("add_child", |_, this, child: NodeRef| {
this.add_child(child);
Ok(())
});
methods.add_method("get_transform", |_, this, _: ()| {
match this.gameobject.get_transform() {
Ok(transform) => Ok(transform),