refactor: fine-grained interior mutability for scenegraph

This commit is contained in:
Nova
2022-06-06 21:34:42 -04:00
parent bb26038030
commit 2c27e5728c
5 changed files with 55 additions and 76 deletions

View File

@@ -2,20 +2,20 @@ use super::scenegraph::Scenegraph;
use crate::nodes::spatial; use crate::nodes::spatial;
use libstardustxr::messenger::Messenger; use libstardustxr::messenger::Messenger;
use mio::net::UnixStream; use mio::net::UnixStream;
use rccell::{RcCell, WeakCell}; use std::rc::Rc;
pub struct Client<'a> { pub struct Client<'a> {
pub messenger: Messenger<'a>, messenger: Messenger<'a>,
scenegraph: Scenegraph<'a>, scenegraph: Scenegraph<'a>,
} }
impl<'a> Client<'a> { impl<'a> Client<'a> {
pub fn from_connection(connection: UnixStream) -> RcCell<Self> { pub fn from_connection(connection: UnixStream) -> Rc<Self> {
let client = RcCell::new(Client { let client = Rc::new(Client {
scenegraph: Default::default(),
messenger: Messenger::new(connection), messenger: Messenger::new(connection),
scenegraph: Default::default(),
}); });
client.borrow_mut().scenegraph.set_client(client.clone()); client.scenegraph.set_client(&client);
spatial::create_interface(client.clone()); spatial::create_interface(client.clone());
client client
} }
@@ -29,7 +29,4 @@ impl<'a> Client<'a> {
pub fn get_scenegraph(&self) -> &Scenegraph<'a> { pub fn get_scenegraph(&self) -> &Scenegraph<'a> {
&self.scenegraph &self.scenegraph
} }
pub fn get_scenegraph_mut(&mut self) -> &mut Scenegraph<'a> {
&mut self.scenegraph
}
} }

View File

@@ -1,12 +1,12 @@
use super::client::Client; use super::client::Client;
use anyhow::{anyhow, Result}; use anyhow::Result;
use libstardustxr::server; use libstardustxr::server;
use mio::net::UnixListener; use mio::net::UnixListener;
use mio::unix::pipe; use mio::unix::pipe;
use mio::{Events, Interest, Poll, Token}; use mio::{Events, Interest, Poll, Token};
use rccell::RcCell;
use slab::Slab; use slab::Slab;
use std::io::Write; use std::io::Write;
use std::rc::Rc;
use std::thread::{self, JoinHandle}; use std::thread::{self, JoinHandle};
pub struct EventLoop { pub struct EventLoop {
@@ -24,7 +24,7 @@ impl EventLoop {
let join_handle = thread::Builder::new() let join_handle = thread::Builder::new()
.name("event_loop".to_owned()) .name("event_loop".to_owned())
.spawn(move || -> Result<()> { .spawn(move || -> Result<()> {
let mut clients: Slab<Option<RcCell<Client>>> = Slab::new(); let mut clients: Slab<Option<Rc<Client>>> = Slab::new();
let mut poll = Poll::new()?; let mut poll = Poll::new()?;
let mut events = Events::with_capacity(1024); let mut events = Events::with_capacity(1024);
const LISTENER: Token = Token(usize::MAX - 1); const LISTENER: Token = Token(usize::MAX - 1);
@@ -59,14 +59,7 @@ impl EventLoop {
}, },
STOP => return Ok(()), STOP => return Ok(()),
token => loop { token => loop {
match clients match clients.get(token.0).unwrap().as_ref().unwrap().dispatch() {
.get(token.0)
.unwrap()
.as_ref()
.unwrap()
.borrow()
.dispatch()
{
Ok(_) => continue, Ok(_) => continue,
Err(e) => { Err(e) => {
if e.kind() == std::io::ErrorKind::WouldBlock { if e.kind() == std::io::ErrorKind::WouldBlock {

View File

@@ -3,43 +3,45 @@ use crate::nodes::core::Node;
use anyhow::Result; use anyhow::Result;
use libstardustxr::scenegraph; use libstardustxr::scenegraph;
use libstardustxr::scenegraph::ScenegraphError; use libstardustxr::scenegraph::ScenegraphError;
use rccell::{RcCell, WeakCell}; use rccell::RcCell;
use std::cell::RefCell;
use std::collections::HashMap; use std::collections::HashMap;
use std::rc::{Rc, Weak};
use std::sync::RwLock;
#[derive(Default)]
pub struct Scenegraph<'a> { pub struct Scenegraph<'a> {
client: WeakCell<Client<'a>>, client: RefCell<Weak<Client<'a>>>,
pub nodes: HashMap<String, RcCell<Node<'a>>>, pub nodes: RwLock<HashMap<String, RcCell<Node<'a>>>>,
} }
impl<'a> Scenegraph<'a> { impl<'a> Scenegraph<'a> {
pub fn set_client(&mut self, client: RcCell<Client<'a>>) { pub fn get_client(&self) -> Rc<Client<'a>> {
self.client = client.downgrade(); self.client.borrow().upgrade().unwrap()
} }
pub fn add_node(&mut self, node: Node<'a>) -> RcCell<Node<'a>> { pub fn set_client(&self, client: &Rc<Client<'a>>) {
*self.client.borrow_mut() = Rc::downgrade(client);
}
pub fn add_node(&self, node: Node<'a>) -> RcCell<Node<'a>> {
let path = node.get_path().to_string(); let path = node.get_path().to_string();
let node_rc = RcCell::new(node); let node_rc = RcCell::new(node);
self.nodes.insert(path, node_rc.clone()); self.nodes.write().unwrap().insert(path, node_rc.clone());
node_rc node_rc
} }
}
impl<'a> Default for Scenegraph<'a> { pub fn get_node(&self, path: &str) -> Option<RcCell<Node<'a>>> {
fn default() -> Self { Some(self.nodes.read().ok()?.get(path)?.clone())
Scenegraph {
client: WeakCell::new(),
nodes: HashMap::new(),
}
} }
} }
impl<'a> scenegraph::Scenegraph for Scenegraph<'a> { impl<'a> scenegraph::Scenegraph for Scenegraph<'a> {
fn send_signal(&self, path: &str, method: &str, data: &[u8]) -> Result<(), ScenegraphError> { fn send_signal(&self, path: &str, method: &str, data: &[u8]) -> Result<(), ScenegraphError> {
self.nodes self.get_node(path)
.get(path)
.ok_or(ScenegraphError::NodeNotFound)? .ok_or(ScenegraphError::NodeNotFound)?
.borrow() .borrow()
.send_local_signal(self.client.upgrade().unwrap(), method, data) .send_local_signal(self.get_client(), method, data)
.map_err(|_| ScenegraphError::MethodNotFound) .map_err(|_| ScenegraphError::MethodNotFound)
} }
fn execute_method( fn execute_method(
@@ -48,11 +50,10 @@ impl<'a> scenegraph::Scenegraph for Scenegraph<'a> {
method: &str, method: &str,
data: &[u8], data: &[u8],
) -> Result<Vec<u8>, ScenegraphError> { ) -> Result<Vec<u8>, ScenegraphError> {
self.nodes self.get_node(path)
.get(path)
.ok_or(ScenegraphError::NodeNotFound)? .ok_or(ScenegraphError::NodeNotFound)?
.borrow() .borrow()
.execute_local_method(self.client.upgrade().unwrap(), method, data) .execute_local_method(self.get_client(), method, data)
.map_err(|_| ScenegraphError::MethodNotFound) .map_err(|_| ScenegraphError::MethodNotFound)
} }
} }

View File

@@ -1,14 +1,14 @@
use crate::core::client::Client; use crate::core::client::Client;
use crate::nodes::spatial::Spatial; use crate::nodes::spatial::Spatial;
use anyhow::{anyhow, ensure, Result}; use anyhow::{anyhow, Result};
use rccell::{RcCell, WeakCell}; use std::rc::{Rc, Weak};
use std::{collections::HashMap, vec::Vec}; use std::{collections::HashMap, vec::Vec};
pub type Signal<'a> = Box<dyn Fn(RcCell<Client>, &[u8]) -> Result<()> + 'a>; pub type Signal<'a> = Box<dyn Fn(Rc<Client>, &[u8]) -> Result<()> + 'a>;
pub type Method<'a> = Box<dyn Fn(RcCell<Client>, &[u8]) -> Result<Vec<u8>> + 'a>; pub type Method<'a> = Box<dyn Fn(Rc<Client>, &[u8]) -> Result<Vec<u8>> + 'a>;
pub struct Node<'a> { pub struct Node<'a> {
client: WeakCell<Client<'a>>, client: Weak<Client<'a>>,
path: String, path: String,
trailing_slash_pos: usize, trailing_slash_pos: usize,
local_signals: HashMap<String, Signal<'a>>, local_signals: HashMap<String, Signal<'a>>,
@@ -19,7 +19,7 @@ pub struct Node<'a> {
} }
impl<'a> Node<'a> { impl<'a> Node<'a> {
pub fn get_client(&self) -> Option<RcCell<Client<'a>>> { pub fn get_client(&self) -> Option<Rc<Client<'a>>> {
self.client.clone().upgrade() self.client.clone().upgrade()
} }
pub fn get_name(&self) -> &str { pub fn get_name(&self) -> &str {
@@ -29,18 +29,13 @@ impl<'a> Node<'a> {
self.path.as_str() self.path.as_str()
} }
pub fn create( pub fn create(client: Weak<Client<'a>>, parent: &str, name: &str, destroyable: bool) -> Self {
client: WeakCell<Client<'a>>,
parent: &str,
name: &str,
destroyable: bool,
) -> Self {
let mut path = parent.to_string(); let mut path = parent.to_string();
path.push('/'); path.push('/');
path.push_str(name); path.push_str(name);
Node { Node {
client, client,
path: path, path,
trailing_slash_pos: parent.len(), trailing_slash_pos: parent.len(),
local_signals: HashMap::new(), local_signals: HashMap::new(),
local_methods: HashMap::new(), local_methods: HashMap::new(),
@@ -55,7 +50,7 @@ impl<'a> Node<'a> {
pub fn send_local_signal( pub fn send_local_signal(
&self, &self,
calling_client: RcCell<Client>, calling_client: Rc<Client>,
method: &str, method: &str,
data: &[u8], data: &[u8],
) -> Result<()> { ) -> Result<()> {
@@ -67,7 +62,7 @@ impl<'a> Node<'a> {
} }
pub fn execute_local_method( pub fn execute_local_method(
&self, &self,
calling_client: RcCell<Client>, calling_client: Rc<Client>,
method: &str, method: &str,
data: &[u8], data: &[u8],
) -> Result<Vec<u8>> { ) -> Result<Vec<u8>> {
@@ -77,8 +72,7 @@ impl<'a> Node<'a> {
} }
pub fn send_remote_signal(&self, method: &str, data: &[u8]) -> Result<()> { pub fn send_remote_signal(&self, method: &str, data: &[u8]) -> Result<()> {
self.get_client() self.get_client()
.ok_or(anyhow!("Node has no client, can't send remote signal!"))? .ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))?
.borrow()
.get_messenger() .get_messenger()
.send_remote_signal(self.path.as_str(), method, data) .send_remote_signal(self.path.as_str(), method, data)
.map_err(|_| anyhow!("Unable to write in messenger")) .map_err(|_| anyhow!("Unable to write in messenger"))
@@ -90,8 +84,7 @@ impl<'a> Node<'a> {
callback: Box<dyn Fn(&[u8]) + 'a>, callback: Box<dyn Fn(&[u8]) + 'a>,
) -> Result<()> { ) -> Result<()> {
self.get_client() self.get_client()
.ok_or(anyhow!("Node has no client, can't send remote signal!"))? .ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))?
.borrow()
.get_messenger() .get_messenger()
.execute_remote_method(self.path.as_str(), method, data, callback) .execute_remote_method(self.path.as_str(), method, data, callback)
.map_err(|_| anyhow!("Unable to write in messenger")) .map_err(|_| anyhow!("Unable to write in messenger"))

View File

@@ -1,9 +1,10 @@
use super::core::Node; use super::core::Node;
use crate::core::client::Client; use crate::core::client::Client;
use anyhow::{anyhow, bail, ensure, Result}; use anyhow::{anyhow, bail, ensure, Result};
use glam::{Mat4, Quat, Vec3}; use glam::Mat4;
use libstardustxr::{flex_to_quat, flex_to_vec3}; use libstardustxr::{flex_to_quat, flex_to_vec3};
use rccell::{RcCell, WeakCell}; use rccell::{RcCell, WeakCell};
use std::rc::Rc;
pub struct Spatial<'a> { pub struct Spatial<'a> {
node: WeakCell<Node<'a>>, node: WeakCell<Node<'a>>,
@@ -34,14 +35,11 @@ impl<'a> Spatial<'a> {
let client = node_captured let client = node_captured
.borrow() .borrow()
.get_client() .get_client()
.ok_or(anyhow!("Node somehow has no client!"))?; .ok_or_else(|| anyhow!("Node somehow has no client"))?;
let other_spatial = calling_client let other_spatial = calling_client
.borrow()
.get_scenegraph() .get_scenegraph()
.nodes .get_node(flex_vec.idx(0).as_str())
.get(flex_vec.idx(0).as_str()) .ok_or_else(|| anyhow!("Other spatial node not found"))?;
.ok_or(anyhow!("Spatial node not found"))?
.clone();
ensure!( ensure!(
other_spatial.borrow().spatial.is_some(), other_spatial.borrow().spatial.is_some(),
"Node is not a Spatial!" "Node is not a Spatial!"
@@ -54,7 +52,7 @@ impl<'a> Spatial<'a> {
.spatial .spatial
.as_mut() .as_mut()
.unwrap() .unwrap()
.set_transform_components(client, other_spatial, pos.into(), rot, scl); .set_transform_components(client, other_spatial, pos, rot, scl);
Ok(()) Ok(())
}), }),
); );
@@ -76,7 +74,7 @@ impl<'a> Spatial<'a> {
pub fn set_transform_components( pub fn set_transform_components(
&mut self, &mut self,
calling_client: RcCell<Client>, calling_client: Rc<Client>,
relative_space: RcCell<Node>, relative_space: RcCell<Node>,
pos: Option<mint::Vector3<f32>>, pos: Option<mint::Vector3<f32>>,
rot: Option<mint::Quaternion<f32>>, rot: Option<mint::Quaternion<f32>>,
@@ -88,15 +86,15 @@ impl<'a> Spatial<'a> {
// pub fn relative_transform(&self, space: WeakCell<Spatial>) {} // pub fn relative_transform(&self, space: WeakCell<Spatial>) {}
} }
pub fn create_interface(client: RcCell<Client>) { pub fn create_interface(client: Rc<Client>) {
let mut node = Node::create(client.downgrade(), "", "spatial", false); let mut node = Node::create(Rc::downgrade(&client), "", "spatial", false);
node.add_local_signal( node.add_local_signal(
"createSpatial", "createSpatial",
Box::new(move |calling_client, data| { Box::new(move |calling_client, data| {
let root = flexbuffers::Reader::get_root(data)?; let root = flexbuffers::Reader::get_root(data)?;
let flex_vec = root.get_vector()?; let flex_vec = root.get_vector()?;
let node = Node::create( let node = Node::create(
calling_client.downgrade(), Rc::downgrade(&calling_client),
"/spatial", "/spatial",
flex_vec.idx(0).get_str()?, flex_vec.idx(0).get_str()?,
true, true,
@@ -112,13 +110,10 @@ pub fn create_interface(client: RcCell<Client>) {
.ok_or_else(|| anyhow!("Position not found"))? .ok_or_else(|| anyhow!("Position not found"))?
.into(), .into(),
); );
let node_rc = calling_client let node_rc = calling_client.get_scenegraph().add_node(node);
.borrow_mut()
.get_scenegraph_mut()
.add_node(node);
Spatial::add_to(node_rc, WeakCell::new(), transform)?; Spatial::add_to(node_rc, WeakCell::new(), transform)?;
Ok(()) Ok(())
}), }),
); );
client.borrow_mut().get_scenegraph_mut().add_node(node); client.get_scenegraph().add_node(node);
} }