Make all nodes thread safe

This commit is contained in:
Nova
2022-06-14 19:34:27 -04:00
parent 651fa5f012
commit 3aa691475c
6 changed files with 182 additions and 207 deletions

View File

@@ -6,8 +6,8 @@ use mio::net::UnixStream;
use std::rc::Rc; use std::rc::Rc;
pub struct Client { pub struct Client {
messenger: Messenger, pub messenger: Messenger,
scenegraph: Scenegraph, pub scenegraph: Scenegraph,
} }
impl Client { impl Client {
@@ -24,11 +24,4 @@ impl Client {
pub fn dispatch(&self) -> Result<(), std::io::Error> { pub fn dispatch(&self) -> Result<(), std::io::Error> {
self.messenger.dispatch(&self.scenegraph) self.messenger.dispatch(&self.scenegraph)
} }
pub fn get_messenger(&self) -> &Messenger {
&self.messenger
}
pub fn get_scenegraph(&self) -> &Scenegraph {
&self.scenegraph
}
} }

View File

@@ -3,9 +3,9 @@ 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;
use std::cell::RefCell; use std::cell::RefCell;
use std::rc::{Rc, Weak}; use std::rc::{Rc, Weak};
use std::sync::Arc;
use core::hash::BuildHasherDefault; use core::hash::BuildHasherDefault;
use dashmap::DashMap; use dashmap::DashMap;
@@ -14,7 +14,7 @@ use rustc_hash::FxHasher;
#[derive(Default)] #[derive(Default)]
pub struct Scenegraph { pub struct Scenegraph {
client: RefCell<Weak<Client>>, client: RefCell<Weak<Client>>,
nodes: DashMap<String, RcCell<Node>, BuildHasherDefault<FxHasher>>, nodes: DashMap<String, Arc<Node>, BuildHasherDefault<FxHasher>>,
} }
impl Scenegraph { impl Scenegraph {
@@ -26,20 +26,20 @@ impl Scenegraph {
*self.client.borrow_mut() = Rc::downgrade(client); *self.client.borrow_mut() = Rc::downgrade(client);
} }
pub fn add_node(&self, node: Node) -> RcCell<Node> { pub fn add_node(&self, node: Node) -> Arc<Node> {
let mut node = node; let mut node = node;
node.client = Rc::downgrade(&self.get_client()); node.client = Rc::downgrade(&self.get_client());
let path = node.get_path().to_string(); let path = node.get_path().to_string();
let node_rc = RcCell::new(node); let node_arc = Arc::new(node);
self.nodes.insert(path, node_rc.clone()); self.nodes.insert(path, node_arc.clone());
node_rc node_arc
} }
pub fn get_node(&self, path: &str) -> Option<RcCell<Node>> { pub fn get_node(&self, path: &str) -> Option<Arc<Node>> {
Some(self.nodes.get(path)?.clone()) Some(self.nodes.get(path)?.clone())
} }
pub fn remove_node(&self, path: &str) -> Option<RcCell<Node>> { pub fn remove_node(&self, path: &str) -> Option<Arc<Node>> {
let (_, node) = self.nodes.remove(path)?; let (_, node) = self.nodes.remove(path)?;
Some(node) Some(node)
} }
@@ -49,7 +49,6 @@ impl scenegraph::Scenegraph for Scenegraph {
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.get_node(path) self.get_node(path)
.ok_or(ScenegraphError::NodeNotFound)? .ok_or(ScenegraphError::NodeNotFound)?
.borrow()
.send_local_signal(self.get_client(), method, data) .send_local_signal(self.get_client(), method, data)
} }
fn execute_method( fn execute_method(
@@ -60,7 +59,6 @@ impl scenegraph::Scenegraph for Scenegraph {
) -> Result<Vec<u8>, ScenegraphError> { ) -> Result<Vec<u8>, ScenegraphError> {
self.get_node(path) self.get_node(path)
.ok_or(ScenegraphError::NodeNotFound)? .ok_or(ScenegraphError::NodeNotFound)?
.borrow()
.execute_local_method(self.get_client(), method, data) .execute_local_method(self.get_client(), method, data)
} }
} }

View File

@@ -4,13 +4,15 @@ use super::spatial::Spatial;
use crate::core::client::Client; use crate::core::client::Client;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use libstardustxr::scenegraph::ScenegraphError; use libstardustxr::scenegraph::ScenegraphError;
use rccell::{RcCell, WeakCell}; use nanoid::nanoid;
use parking_lot::RwLock;
use std::rc::{Rc, Weak}; use std::rc::{Rc, Weak};
use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering};
use std::{collections::HashMap, vec::Vec}; use std::sync::{Arc, Weak as WeakArc};
use std::vec::Vec;
use core::hash::BuildHasherDefault; use core::hash::BuildHasherDefault;
use nanoid::nanoid; use dashmap::DashMap;
use rustc_hash::FxHasher; use rustc_hash::FxHasher;
pub type Signal = fn(&Node, Rc<Client>, &[u8]) -> Result<()>; pub type Signal = fn(&Node, Rc<Client>, &[u8]) -> Result<()>;
@@ -21,14 +23,14 @@ pub struct Node {
pub(crate) client: Weak<Client>, pub(crate) client: Weak<Client>,
path: String, path: String,
// trailing_slash_pos: usize, // trailing_slash_pos: usize,
local_signals: HashMap<String, Signal, BuildHasherDefault<FxHasher>>, local_signals: DashMap<String, Signal, BuildHasherDefault<FxHasher>>,
local_methods: HashMap<String, Method, BuildHasherDefault<FxHasher>>, local_methods: DashMap<String, Method, BuildHasherDefault<FxHasher>>,
destroyable: bool, destroyable: AtomicBool,
alias: Option<Alias>, alias: RwLock<Option<Alias>>,
pub spatial: Option<Arc<Spatial>>, pub spatial: RwLock<Option<Arc<Spatial>>>,
pub field: Option<Arc<Field>>, pub field: RwLock<Option<Arc<Field>>>,
pub pulse_sender: Option<Arc<PulseSender>>, pub pulse_sender: RwLock<Option<Arc<PulseSender>>>,
} }
impl Node { impl Node {
@@ -42,33 +44,33 @@ impl Node {
self.path.as_str() self.path.as_str()
} }
pub fn is_destroyable(&self) -> bool { pub fn is_destroyable(&self) -> bool {
self.destroyable self.destroyable.load(Ordering::Relaxed)
} }
pub fn create(parent: &str, name: &str, destroyable: bool) -> Self { pub fn create(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);
let mut node = Node { let node = Node {
uid: nanoid!(), uid: nanoid!(),
client: Weak::new(), client: Weak::new(),
path, path,
// trailing_slash_pos: parent.len(), // trailing_slash_pos: parent.len(),
local_signals: Default::default(), local_signals: Default::default(),
local_methods: Default::default(), local_methods: Default::default(),
destroyable, destroyable: AtomicBool::from(destroyable),
alias: None, alias: RwLock::new(None),
spatial: None, spatial: RwLock::new(None),
field: None, field: RwLock::new(None),
pulse_sender: None, pulse_sender: RwLock::new(None),
}; };
node.add_local_signal("destroy", Node::destroy_flex); node.add_local_signal("destroy", Node::destroy_flex);
node node
} }
pub fn destroy(&self) { pub fn destroy(&self) {
if let Some(client) = self.get_client() { if let Some(client) = self.get_client() {
let _ = client.get_scenegraph().remove_node(self.get_path()); let _ = client.scenegraph.remove_node(self.get_path());
} }
} }
@@ -79,10 +81,10 @@ impl Node {
Ok(()) Ok(())
} }
pub fn add_local_signal(&mut self, name: &str, signal: Signal) { pub fn add_local_signal(&self, name: &str, signal: Signal) {
self.local_signals.insert(name.to_string(), signal); self.local_signals.insert(name.to_string(), signal);
} }
pub fn add_local_method(&mut self, name: &str, method: Method) { pub fn add_local_method(&self, name: &str, method: Method) {
self.local_methods.insert(name.to_string(), method); self.local_methods.insert(name.to_string(), method);
} }
@@ -92,15 +94,14 @@ impl Node {
method: &str, method: &str,
data: &[u8], data: &[u8],
) -> Result<(), ScenegraphError> { ) -> Result<(), ScenegraphError> {
if let Some(alias) = self.alias.as_ref() { if let Some(alias) = self.alias.read().as_ref() {
if !alias.signals.contains(&method.to_string()) { if !alias.signals.contains(&method.to_string()) {
return Err(ScenegraphError::SignalNotFound); return Err(ScenegraphError::SignalNotFound);
} }
alias alias
.original .original
.upgrade() .upgrade()
.ok_or_else(|| ScenegraphError::BrokenAlias)? .ok_or(ScenegraphError::BrokenAlias)?
.borrow()
.send_local_signal(calling_client, method, data) .send_local_signal(calling_client, method, data)
} else { } else {
let signal = self let signal = self
@@ -117,15 +118,14 @@ impl Node {
method: &str, method: &str,
data: &[u8], data: &[u8],
) -> Result<Vec<u8>, ScenegraphError> { ) -> Result<Vec<u8>, ScenegraphError> {
if let Some(alias) = self.alias.as_ref() { if let Some(alias) = self.alias.read().as_ref() {
if !alias.methods.contains(&method.to_string()) { if !alias.methods.contains(&method.to_string()) {
return Err(ScenegraphError::MethodNotFound); return Err(ScenegraphError::MethodNotFound);
} }
alias alias
.original .original
.upgrade() .upgrade()
.ok_or_else(|| ScenegraphError::BrokenAlias)? .ok_or(ScenegraphError::BrokenAlias)?
.borrow()
.execute_local_method(calling_client, method, data) .execute_local_method(calling_client, method, data)
} else { } else {
let method = self let method = self
@@ -139,7 +139,7 @@ impl Node {
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_else(|| anyhow!("Node has no client, can't send remote signal!"))? .ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))?
.get_messenger() .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"))
} }
@@ -151,27 +151,27 @@ impl Node {
// ) -> Result<()> { // ) -> Result<()> {
// self.get_client() // self.get_client()
// .ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))? // .ok_or_else(|| anyhow!("Node has no client, can't send remote signal!"))?
// .get_messenger() // .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"))
// } // }
} }
struct Alias { struct Alias {
original: WeakCell<Node>, original: WeakArc<Node>,
signals: Vec<String>, signals: Vec<String>,
methods: Vec<String>, methods: Vec<String>,
} }
impl Alias { impl Alias {
pub fn add_to( pub fn add_to(
node: &RcCell<Node>, node: &Arc<Node>,
original: &RcCell<Node>, original: &Arc<Node>,
signals: Vec<String>, signals: Vec<String>,
methods: Vec<String>, methods: Vec<String>,
) { ) {
node.borrow_mut().alias = Some(Alias { *node.alias.write() = Some(Alias {
original: original.downgrade(), original: Arc::downgrade(original),
signals, signals,
methods, methods,
}); });

View File

@@ -2,7 +2,7 @@ use super::core::Node;
use crate::core::registry::Registry; use crate::core::registry::Registry;
use anyhow::{ensure, Result}; use anyhow::{ensure, Result};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use rccell::RcCell; use std::sync::Arc;
lazy_static! { lazy_static! {
static ref PULSE_SENDER_REGISTRY: Registry<PulseSender> = Default::default(); static ref PULSE_SENDER_REGISTRY: Registry<PulseSender> = Default::default();
@@ -11,15 +11,15 @@ lazy_static! {
pub struct PulseSender {} pub struct PulseSender {}
impl PulseSender { impl PulseSender {
pub fn add_to(node: &RcCell<Node>) -> Result<()> { pub fn add_to(node: &Arc<Node>) -> Result<()> {
ensure!( ensure!(
node.borrow().spatial.is_some(), node.spatial.read().is_some(),
"Internal: Node does not have a spatial attached!" "Internal: Node does not have a spatial attached!"
); );
let sender = PulseSender {}; let sender = PulseSender {};
let sender = PULSE_SENDER_REGISTRY.add(sender)?; let sender = PULSE_SENDER_REGISTRY.add(sender)?;
node.borrow_mut().pulse_sender = Some(sender); *node.pulse_sender.write() = Some(sender);
Ok(()) Ok(())
} }
} }

View File

@@ -7,7 +7,6 @@ use libstardustxr::fusion::flex::FlexBuffable;
use libstardustxr::{flex_to_quat, flex_to_vec3}; use libstardustxr::{flex_to_quat, flex_to_vec3};
use parking_lot::Mutex; use parking_lot::Mutex;
use portable_atomic::AtomicF32; use portable_atomic::AtomicF32;
use rccell::RcCell;
use std::ops::Deref; use std::ops::Deref;
use std::rc::Rc; use std::rc::Rc;
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
@@ -55,85 +54,87 @@ pub trait FieldTrait {
.transform_point3a(self.local_closest_point(local_p, r)) .transform_point3a(self.local_closest_point(local_p, r))
} }
fn add_field_methods(&self, node: &RcCell<Node>) { fn add_field_methods(&self, node: &Arc<Node>) {
node.borrow_mut() node.add_local_method("distance", field_distance_flex);
.add_local_method("distance", |node, calling_client, data| { node.add_local_method("normal", field_normal_flex);
let root = flexbuffers::Reader::get_root(data)?; node.add_local_method("closest_point", field_closest_point_flex);
let flex_vec = root.get_vector()?;
let reference_space_path = flex_vec.idx(0).as_str();
let reference_space = calling_client
.get_scenegraph()
.get_node(reference_space_path)
.ok_or_else(|| anyhow!("Reference space node does not exist"))?
.borrow()
.spatial
.as_ref()
.ok_or_else(|| anyhow!("Reference space node does not have a spatial"))?
.clone();
let point =
flex_to_vec3!(flex_vec.idx(1)).ok_or_else(|| anyhow!("Point is invalid"))?;
let field = node
.field
.as_ref()
.ok_or_else(|| anyhow!("Node does not have a field!"))?;
let distance = field.distance(reference_space.as_ref(), point.into());
Ok(FlexBuffable::from(distance).build_singleton())
});
node.borrow_mut()
.add_local_method("normal", |node, calling_client, data| {
let root = flexbuffers::Reader::get_root(data)?;
let flex_vec = root.get_vector()?;
let reference_space_path = flex_vec.idx(0).as_str();
let reference_space = calling_client
.get_scenegraph()
.get_node(reference_space_path)
.ok_or_else(|| anyhow!("Reference space node does not exist"))?
.borrow()
.spatial
.as_ref()
.ok_or_else(|| anyhow!("Reference space node does not have a spatial"))?
.clone();
let point =
flex_to_vec3!(flex_vec.idx(1)).ok_or_else(|| anyhow!("Point is invalid"))?;
let field = node
.field
.as_ref()
.ok_or_else(|| anyhow!("Node does not have a field!"))?;
let normal = field.normal(reference_space.as_ref(), point.into(), 0.001_f32);
Ok(FlexBuffable::from(mint::Vector3::from(normal)).build_singleton())
});
node.borrow_mut()
.add_local_method("closest_point", |node, calling_client, data| {
let root = flexbuffers::Reader::get_root(data)?;
let flex_vec = root.get_vector()?;
let reference_space_path = flex_vec.idx(0).as_str();
let reference_space = calling_client
.get_scenegraph()
.get_node(reference_space_path)
.ok_or_else(|| anyhow!("Reference space node does not exist"))?
.borrow()
.spatial
.as_ref()
.ok_or_else(|| anyhow!("Reference space node does not have a spatial"))?
.clone();
let point =
flex_to_vec3!(flex_vec.idx(1)).ok_or_else(|| anyhow!("Point is invalid"))?;
let field = node
.field
.as_ref()
.ok_or_else(|| anyhow!("Node does not have a field!"))?;
let closest_point =
field.closest_point(reference_space.as_ref(), point.into(), 0.001_f32);
Ok(FlexBuffable::from(mint::Vector3::from(closest_point)).build_singleton())
});
} }
fn spatial_ref(&self) -> &Spatial; fn spatial_ref(&self) -> &Spatial;
} }
fn field_distance_flex(node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<Vec<u8>> {
let root = flexbuffers::Reader::get_root(data)?;
let flex_vec = root.get_vector()?;
let reference_space_path = flex_vec.idx(0).as_str();
let reference_space = calling_client
.scenegraph
.get_node(reference_space_path)
.ok_or_else(|| anyhow!("Reference space node does not exist"))?
.spatial
.read()
.as_ref()
.ok_or_else(|| anyhow!("Reference space node does not have a spatial"))?
.clone();
let point = flex_to_vec3!(flex_vec.idx(1)).ok_or_else(|| anyhow!("Point is invalid"))?;
let distance = node
.field
.read()
.as_ref()
.unwrap()
.distance(reference_space.as_ref(), point.into());
Ok(FlexBuffable::from(distance).build_singleton())
}
fn field_normal_flex(node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<Vec<u8>> {
let root = flexbuffers::Reader::get_root(data)?;
let flex_vec = root.get_vector()?;
let reference_space_path = flex_vec.idx(0).as_str();
let reference_space = calling_client
.scenegraph
.get_node(reference_space_path)
.ok_or_else(|| anyhow!("Reference space node does not exist"))?
.spatial
.read()
.as_ref()
.ok_or_else(|| anyhow!("Reference space node does not have a spatial"))?
.clone();
let point = flex_to_vec3!(flex_vec.idx(1)).ok_or_else(|| anyhow!("Point is invalid"))?;
let normal = node.field.read().as_ref().unwrap().normal(
reference_space.as_ref(),
point.into(),
0.001_f32,
);
Ok(FlexBuffable::from(mint::Vector3::from(normal)).build_singleton())
}
fn field_closest_point_flex(
node: &Node,
calling_client: Rc<Client>,
data: &[u8],
) -> Result<Vec<u8>> {
let root = flexbuffers::Reader::get_root(data)?;
let flex_vec = root.get_vector()?;
let reference_space_path = flex_vec.idx(0).as_str();
let reference_space = calling_client
.scenegraph
.get_node(reference_space_path)
.ok_or_else(|| anyhow!("Reference space node does not exist"))?
.spatial
.read()
.as_ref()
.ok_or_else(|| anyhow!("Reference space node does not have a spatial"))?
.clone();
let point = flex_to_vec3!(flex_vec.idx(1)).ok_or_else(|| anyhow!("Point is invalid"))?;
let closest_point = node.field.read().as_ref().unwrap().closest_point(
reference_space.as_ref(),
point.into(),
0.001_f32,
);
Ok(FlexBuffable::from(mint::Vector3::from(closest_point)).build_singleton())
}
pub enum Field { pub enum Field {
Box(BoxField), Box(BoxField),
Cylinder(CylinderField), Cylinder(CylinderField),
@@ -157,23 +158,22 @@ pub struct BoxField {
} }
impl BoxField { impl BoxField {
pub fn add_to(node: &RcCell<Node>, size: Vec3) -> Result<()> { pub fn add_to(node: &Arc<Node>, size: Vec3) -> Result<()> {
ensure!( ensure!(
node.borrow().spatial.is_some(), node.spatial.read().is_some(),
"Internal: Node does not have a spatial attached!" "Internal: Node does not have a spatial attached!"
); );
ensure!( ensure!(
node.borrow().field.is_none(), node.field.read().is_none(),
"Internal: Node already has a field attached!" "Internal: Node already has a field attached!"
); );
let box_field = BoxField { let box_field = BoxField {
space: node.borrow().spatial.as_ref().unwrap().clone(), space: node.spatial.read().as_ref().unwrap().clone(),
size: Mutex::new(size), size: Mutex::new(size),
}; };
box_field.add_field_methods(node); box_field.add_field_methods(node);
node.borrow_mut() node.add_local_signal("setSize", BoxField::set_size_flex);
.add_local_signal("setSize", BoxField::set_size_flex); *node.field.write() = Some(Arc::new(Field::Box(box_field)));
node.borrow_mut().field = Some(Arc::new(Field::Box(box_field)));
Ok(()) Ok(())
} }
@@ -184,11 +184,7 @@ impl BoxField {
pub fn set_size_flex(node: &Node, _calling_client: Rc<Client>, data: &[u8]) -> Result<()> { pub fn set_size_flex(node: &Node, _calling_client: Rc<Client>, data: &[u8]) -> Result<()> {
let root = flexbuffers::Reader::get_root(data)?; let root = flexbuffers::Reader::get_root(data)?;
let size = flex_to_vec3!(root).ok_or_else(|| anyhow!("Size is invalid"))?; let size = flex_to_vec3!(root).ok_or_else(|| anyhow!("Size is invalid"))?;
let field = node if let Field::Box(box_field) = node.field.read().as_ref().unwrap().as_ref() {
.field
.as_ref()
.ok_or_else(|| anyhow!("Node does not have a field"))?;
if let Field::Box(box_field) = field.as_ref() {
box_field.set_size(size.into()); box_field.set_size(size.into());
} }
Ok(()) Ok(())
@@ -218,24 +214,23 @@ pub struct CylinderField {
} }
impl CylinderField { impl CylinderField {
pub fn add_to(node: &RcCell<Node>, length: f32, radius: f32) -> Result<()> { pub fn add_to(node: &Arc<Node>, length: f32, radius: f32) -> Result<()> {
ensure!( ensure!(
node.borrow().spatial.is_some(), node.spatial.read().is_some(),
"Internal: Node does not have a spatial attached!" "Internal: Node does not have a spatial attached!"
); );
ensure!( ensure!(
node.borrow().field.is_none(), node.field.read().is_none(),
"Internal: Node already has a field attached!" "Internal: Node already has a field attached!"
); );
let cylinder_field = CylinderField { let cylinder_field = CylinderField {
space: node.borrow().spatial.as_ref().unwrap().clone(), space: node.spatial.read().as_ref().unwrap().clone(),
length: AtomicF32::new(length), length: AtomicF32::new(length),
radius: AtomicF32::new(radius), radius: AtomicF32::new(radius),
}; };
cylinder_field.add_field_methods(node); cylinder_field.add_field_methods(node);
node.borrow_mut() node.add_local_signal("setSize", CylinderField::set_size_flex);
.add_local_signal("setSize", CylinderField::set_size_flex); *node.field.write() = Some(Arc::new(Field::Cylinder(cylinder_field)));
node.borrow_mut().field = Some(Arc::new(Field::Cylinder(cylinder_field)));
Ok(()) Ok(())
} }
@@ -249,11 +244,7 @@ impl CylinderField {
let flex_vec = root.get_vector()?; let flex_vec = root.get_vector()?;
let length = flex_vec.idx(0).as_f32(); let length = flex_vec.idx(0).as_f32();
let radius = flex_vec.idx(1).as_f32(); let radius = flex_vec.idx(1).as_f32();
let field = node if let Field::Cylinder(cylinder_field) = node.field.read().as_ref().unwrap().as_ref() {
.field
.as_ref()
.ok_or_else(|| anyhow!("Node does not have a field"))?;
if let Field::Cylinder(cylinder_field) = field.as_ref() {
cylinder_field.set_size(length, radius); cylinder_field.set_size(length, radius);
} }
Ok(()) Ok(())
@@ -283,23 +274,22 @@ pub struct SphereField {
} }
impl SphereField { impl SphereField {
pub fn add_to(node: &RcCell<Node>, radius: f32) -> Result<()> { pub fn add_to(node: &Arc<Node>, radius: f32) -> Result<()> {
ensure!( ensure!(
node.borrow().spatial.is_some(), node.spatial.read().is_some(),
"Internal: Node does not have a spatial attached!" "Internal: Node does not have a spatial attached!"
); );
ensure!( ensure!(
node.borrow().field.is_none(), node.field.read().is_none(),
"Internal: Node already has a field attached!" "Internal: Node already has a field attached!"
); );
let sphere_field = SphereField { let sphere_field = SphereField {
space: node.borrow().spatial.as_ref().unwrap().clone(), space: node.spatial.read().as_ref().unwrap().clone(),
radius: AtomicF32::new(radius), radius: AtomicF32::new(radius),
}; };
sphere_field.add_field_methods(node); sphere_field.add_field_methods(node);
node.borrow_mut() node.add_local_signal("setRadius", SphereField::set_radius_flex);
.add_local_signal("setRadius", SphereField::set_radius_flex); *node.field.write() = Some(Arc::new(Field::Sphere(sphere_field)));
node.borrow_mut().field = Some(Arc::new(Field::Sphere(sphere_field)));
Ok(()) Ok(())
} }
@@ -309,11 +299,7 @@ impl SphereField {
pub fn set_radius_flex(node: &Node, _calling_client: Rc<Client>, data: &[u8]) -> Result<()> { pub fn set_radius_flex(node: &Node, _calling_client: Rc<Client>, data: &[u8]) -> Result<()> {
let root = flexbuffers::Reader::get_root(data)?; let root = flexbuffers::Reader::get_root(data)?;
let field = node if let Field::Sphere(sphere_field) = node.field.read().as_ref().unwrap().as_ref() {
.field
.as_ref()
.ok_or_else(|| anyhow!("Node does not have a field"))?;
if let Field::Sphere(sphere_field) = field.as_ref() {
sphere_field.set_radius(root.as_f32()); sphere_field.set_radius(root.as_f32());
} }
Ok(()) Ok(())
@@ -336,11 +322,11 @@ impl FieldTrait for SphereField {
} }
pub fn create_interface(client: Rc<Client>) { pub fn create_interface(client: Rc<Client>) {
let mut node = Node::create("", "field", false); let node = Node::create("", "field", false);
node.add_local_signal("createBoxField", create_box_field_flex); node.add_local_signal("createBoxField", create_box_field_flex);
node.add_local_signal("createCylinderField", create_cylinder_field_flex); node.add_local_signal("createCylinderField", create_cylinder_field_flex);
node.add_local_signal("createSphereField", create_sphere_field_flex); node.add_local_signal("createSphereField", create_sphere_field_flex);
client.get_scenegraph().add_node(node); client.scenegraph.add_node(node);
} }
pub fn create_box_field_flex(_node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<()> { pub fn create_box_field_flex(_node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<()> {
@@ -348,9 +334,9 @@ pub fn create_box_field_flex(_node: &Node, calling_client: Rc<Client>, data: &[u
let flex_vec = root.get_vector()?; let flex_vec = root.get_vector()?;
let node = Node::create("/field", flex_vec.idx(0).get_str()?, true); let node = Node::create("/field", flex_vec.idx(0).get_str()?, true);
let parent = calling_client let parent = calling_client
.get_scenegraph() .scenegraph
.get_node(flex_vec.idx(1).as_str()) .get_node(flex_vec.idx(1).as_str())
.and_then(|node| node.borrow().spatial.clone()); .and_then(|node| node.spatial.read().clone());
let transform = Mat4::from_rotation_translation( let transform = Mat4::from_rotation_translation(
flex_to_quat!(flex_vec.idx(3)) flex_to_quat!(flex_vec.idx(3))
.ok_or_else(|| anyhow!("Rotation not found"))? .ok_or_else(|| anyhow!("Rotation not found"))?
@@ -360,7 +346,7 @@ pub fn create_box_field_flex(_node: &Node, calling_client: Rc<Client>, data: &[u
.into(), .into(),
); );
let size = flex_to_vec3!(flex_vec.idx(4)).ok_or_else(|| anyhow!("Size invalid"))?; let size = flex_to_vec3!(flex_vec.idx(4)).ok_or_else(|| anyhow!("Size invalid"))?;
let node_rc = calling_client.get_scenegraph().add_node(node); let node_rc = calling_client.scenegraph.add_node(node);
Spatial::add_to(&node_rc, parent, transform)?; Spatial::add_to(&node_rc, parent, transform)?;
BoxField::add_to(&node_rc, size.into())?; BoxField::add_to(&node_rc, size.into())?;
Ok(()) Ok(())
@@ -375,9 +361,9 @@ pub fn create_cylinder_field_flex(
let flex_vec = root.get_vector()?; let flex_vec = root.get_vector()?;
let node = Node::create("/field", flex_vec.idx(0).get_str()?, true); let node = Node::create("/field", flex_vec.idx(0).get_str()?, true);
let parent = calling_client let parent = calling_client
.get_scenegraph() .scenegraph
.get_node(flex_vec.idx(1).as_str()) .get_node(flex_vec.idx(1).as_str())
.and_then(|node| node.borrow().spatial.clone()); .and_then(|node| node.spatial.read().clone());
let transform = Mat4::from_rotation_translation( let transform = Mat4::from_rotation_translation(
flex_to_quat!(flex_vec.idx(3)) flex_to_quat!(flex_vec.idx(3))
.ok_or_else(|| anyhow!("Rotation not found"))? .ok_or_else(|| anyhow!("Rotation not found"))?
@@ -388,7 +374,7 @@ pub fn create_cylinder_field_flex(
); );
let length = flex_vec.idx(0).as_f32(); let length = flex_vec.idx(0).as_f32();
let radius = flex_vec.idx(1).as_f32(); let radius = flex_vec.idx(1).as_f32();
let node_rc = calling_client.get_scenegraph().add_node(node); let node_rc = calling_client.scenegraph.add_node(node);
Spatial::add_to(&node_rc, parent, transform)?; Spatial::add_to(&node_rc, parent, transform)?;
CylinderField::add_to(&node_rc, length, radius)?; CylinderField::add_to(&node_rc, length, radius)?;
Ok(()) Ok(())
@@ -403,15 +389,15 @@ pub fn create_sphere_field_flex(
let flex_vec = root.get_vector()?; let flex_vec = root.get_vector()?;
let node = Node::create("/field", flex_vec.idx(0).get_str()?, true); let node = Node::create("/field", flex_vec.idx(0).get_str()?, true);
let parent = calling_client let parent = calling_client
.get_scenegraph() .scenegraph
.get_node(flex_vec.idx(1).as_str()) .get_node(flex_vec.idx(1).as_str())
.and_then(|node| node.borrow().spatial.clone()); .and_then(|node| node.spatial.read().clone());
let transform = Mat4::from_translation( let transform = Mat4::from_translation(
flex_to_vec3!(flex_vec.idx(2)) flex_to_vec3!(flex_vec.idx(2))
.ok_or_else(|| anyhow!("Position not found"))? .ok_or_else(|| anyhow!("Position not found"))?
.into(), .into(),
); );
let node_rc = calling_client.get_scenegraph().add_node(node); let node_rc = calling_client.scenegraph.add_node(node);
Spatial::add_to(&node_rc, parent, transform)?; Spatial::add_to(&node_rc, parent, transform)?;
SphereField::add_to(&node_rc, flex_vec.idx(3).as_f32())?; SphereField::add_to(&node_rc, flex_vec.idx(3).as_f32())?;
Ok(()) Ok(())

View File

@@ -6,24 +6,23 @@ use libstardustxr::flex::flexbuffer_from_vector_arguments;
use libstardustxr::push_to_vec; use libstardustxr::push_to_vec;
use libstardustxr::{flex_to_quat, flex_to_vec3}; use libstardustxr::{flex_to_quat, flex_to_vec3};
use parking_lot::RwLock; use parking_lot::RwLock;
use rccell::RcCell;
use std::rc::Rc; use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
pub struct Spatial { pub struct Spatial {
// node: WeakCell<Node>, // node: Weak<Node>,
parent: RwLock<Option<Arc<Spatial>>>, parent: RwLock<Option<Arc<Spatial>>>,
transform: RwLock<Mat4>, transform: RwLock<Mat4>,
} }
impl Spatial { impl Spatial {
pub fn add_to( pub fn add_to(
node: &RcCell<Node>, node: &Arc<Node>,
parent: Option<Arc<Spatial>>, parent: Option<Arc<Spatial>>,
transform: Mat4, transform: Mat4,
) -> Result<Arc<Spatial>> { ) -> Result<Arc<Spatial>> {
ensure!( ensure!(
node.borrow_mut().spatial.is_none(), node.spatial.read().is_none(),
"Internal: Node already has a Spatial aspect!" "Internal: Node already has a Spatial aspect!"
); );
let spatial = Spatial { let spatial = Spatial {
@@ -31,12 +30,10 @@ impl Spatial {
parent: RwLock::new(parent), parent: RwLock::new(parent),
transform: RwLock::new(transform), transform: RwLock::new(transform),
}; };
node.borrow_mut() node.add_local_method("getTransform", Spatial::get_transform_flex);
.add_local_method("getTransform", Spatial::get_transform_flex); node.add_local_signal("setTransform", Spatial::set_transform_flex);
node.borrow_mut()
.add_local_signal("setTransform", Spatial::set_transform_flex);
let spatial_arc = Arc::new(spatial); let spatial_arc = Arc::new(spatial);
node.borrow_mut().spatial = Some(spatial_arc.clone()); *node.spatial.write() = Some(spatial_arc.clone());
Ok(spatial_arc) Ok(spatial_arc)
} }
@@ -100,12 +97,13 @@ impl Spatial {
let root = flexbuffers::Reader::get_root(data)?; let root = flexbuffers::Reader::get_root(data)?;
let this_spatial = node let this_spatial = node
.spatial .spatial
.read()
.clone() .clone()
.ok_or_else(|| anyhow!("Node doesn't have a spatial?"))?; .ok_or_else(|| anyhow!("Node doesn't have a spatial?"))?;
let relative_spatial = calling_client let relative_spatial = calling_client
.get_scenegraph() .scenegraph
.get_node(root.as_str()) .get_node(root.as_str())
.and_then(|node| node.borrow().spatial.clone()) .and_then(|node| node.spatial.read().clone())
.ok_or_else(|| anyhow!("Space not found"))?; .ok_or_else(|| anyhow!("Space not found"))?;
let (scale, rotation, position) = Spatial::space_to_space_matrix( let (scale, rotation, position) = Spatial::space_to_space_matrix(
@@ -126,40 +124,40 @@ impl Spatial {
pub fn set_transform_flex(node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<()> { pub fn set_transform_flex(node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<()> {
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 spatial = node
.spatial
.as_ref()
.ok_or_else(|| anyhow!("Node somehow is not spatial"))?;
let reference_space_path = flex_vec.idx(0).as_str(); let reference_space_path = flex_vec.idx(0).as_str();
let reference_space_transform = if reference_space_path.is_empty() { let reference_space_transform = if reference_space_path.is_empty() {
None None
} else { } else {
Some( Some(
calling_client calling_client
.get_scenegraph() .scenegraph
.get_node(reference_space_path) .get_node(reference_space_path)
.ok_or_else(|| anyhow!("Other spatial node not found"))? .ok_or_else(|| anyhow!("Other spatial node not found"))?
.borrow()
.spatial .spatial
.read()
.as_ref() .as_ref()
.ok_or_else(|| anyhow!("Node is not a Spatial!"))? .ok_or_else(|| anyhow!("Node is not a Spatial!"))?
.clone(), .clone(),
) )
}; };
spatial.set_local_transform_components( node.spatial
reference_space_transform.as_deref(), .read()
flex_to_vec3!(flex_vec.idx(1)).map(|v| v.into()), .as_ref()
flex_to_quat!(flex_vec.idx(2)).map(|v| v.into()), .unwrap()
flex_to_vec3!(flex_vec.idx(3)).map(|v| v.into()), .set_local_transform_components(
); reference_space_transform.as_deref(),
flex_to_vec3!(flex_vec.idx(1)).map(|v| v.into()),
flex_to_quat!(flex_vec.idx(2)).map(|v| v.into()),
flex_to_vec3!(flex_vec.idx(3)).map(|v| v.into()),
);
Ok(()) Ok(())
} }
} }
pub fn create_interface(client: Rc<Client>) { pub fn create_interface(client: Rc<Client>) {
let mut node = Node::create("", "spatial", false); let node = Node::create("", "spatial", false);
node.add_local_signal("createSpatial", create_spatial_flex); node.add_local_signal("createSpatial", create_spatial_flex);
client.get_scenegraph().add_node(node); client.scenegraph.add_node(node);
} }
pub fn create_spatial_flex(_node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<()> { pub fn create_spatial_flex(_node: &Node, calling_client: Rc<Client>, data: &[u8]) -> Result<()> {
@@ -167,9 +165,9 @@ pub fn create_spatial_flex(_node: &Node, calling_client: Rc<Client>, data: &[u8]
let flex_vec = root.get_vector()?; let flex_vec = root.get_vector()?;
let spatial = Node::create("/spatial/spatial", flex_vec.idx(0).get_str()?, true); let spatial = Node::create("/spatial/spatial", flex_vec.idx(0).get_str()?, true);
let parent = calling_client let parent = calling_client
.get_scenegraph() .scenegraph
.get_node(flex_vec.idx(1).as_str()) .get_node(flex_vec.idx(1).as_str())
.and_then(|node| node.borrow().spatial.clone()); .and_then(|node| node.spatial.read().clone());
let transform = Mat4::from_scale_rotation_translation( let transform = Mat4::from_scale_rotation_translation(
flex_to_vec3!(flex_vec.idx(4)) flex_to_vec3!(flex_vec.idx(4))
.ok_or_else(|| anyhow!("Scale not found"))? .ok_or_else(|| anyhow!("Scale not found"))?
@@ -181,7 +179,7 @@ pub fn create_spatial_flex(_node: &Node, calling_client: Rc<Client>, data: &[u8]
.ok_or_else(|| anyhow!("Position not found"))? .ok_or_else(|| anyhow!("Position not found"))?
.into(), .into(),
); );
let spatial_rc = calling_client.get_scenegraph().add_node(spatial); let spatial_rc = calling_client.scenegraph.add_node(spatial);
Spatial::add_to(&spatial_rc, parent, transform)?; Spatial::add_to(&spatial_rc, parent, transform)?;
Ok(()) Ok(())
} }