use super::{InstancedMesh, Layers, LineSegments, Mesh, Points, SkinnedMesh, Sprite};
use crate::lights::Light;
use crate::math::{Euler, EulerOrder, Matrix4, Quaternion, Vector3};
use slotmap::{new_key_type, SlotMap};
new_key_type! {
pub struct ObjectId;
}
#[derive(Debug, Clone)]
pub enum ObjectKind {
Group,
Mesh(Mesh),
Light(Light),
LineSegments(LineSegments),
Points(Points),
Sprite(Sprite),
InstancedMesh(InstancedMesh),
SkinnedMesh(SkinnedMesh),
#[cfg(feature = "audio")]
Audio(Box<crate::audio::PositionalAudio>),
}
#[derive(Debug, Clone)]
pub struct Object3D {
pub name: String,
pub position: Vector3,
pub quaternion: Quaternion,
pub scale: Vector3,
pub up: Vector3,
pub visible: bool,
pub layers: Layers,
pub cast_shadow: bool,
pub receive_shadow: bool,
pub render_order: i32,
pub refract_capture: bool,
pub clip_plane: Option<crate::math::Plane>,
pub kind: ObjectKind,
pub is_group: bool,
pub matrix: Matrix4,
pub matrix_world: Matrix4,
pub matrix_auto_update: bool,
pub matrix_world_auto_update: bool,
pub rotation_order: EulerOrder,
pub parent: Option<ObjectId>,
pub children: Vec<ObjectId>,
}
impl Object3D {
pub fn group() -> Self {
Self::with_kind(ObjectKind::Group)
}
pub fn mesh(mesh: Mesh) -> Self {
Self::with_kind(ObjectKind::Mesh(mesh))
}
pub fn light(light: impl Into<Light>) -> Self {
Self::with_kind(ObjectKind::Light(light.into()))
}
#[cfg(feature = "audio")]
pub fn audio(audio: crate::audio::PositionalAudio) -> Self {
Self::with_kind(ObjectKind::Audio(Box::new(audio)))
}
pub fn line_segments(ls: LineSegments) -> Self {
Self::with_kind(ObjectKind::LineSegments(ls))
}
pub fn points(p: Points) -> Self {
Self::with_kind(ObjectKind::Points(p))
}
pub fn sprite(s: Sprite) -> Self {
Self::with_kind(ObjectKind::Sprite(s))
}
pub fn instanced_mesh(im: InstancedMesh) -> Self {
Self::with_kind(ObjectKind::InstancedMesh(im))
}
pub fn skinned_mesh(sm: SkinnedMesh) -> Self {
Self::with_kind(ObjectKind::SkinnedMesh(sm))
}
fn with_kind(kind: ObjectKind) -> Self {
Self {
name: String::new(),
position: Vector3::ZERO,
quaternion: Quaternion::identity(),
scale: Vector3::ONE,
up: Vector3::UP,
visible: true,
layers: Layers::default(),
cast_shadow: false,
receive_shadow: false,
render_order: 0,
clip_plane: None,
refract_capture: true,
kind,
is_group: false,
matrix: Matrix4::identity(),
matrix_world: Matrix4::identity(),
matrix_auto_update: true,
matrix_world_auto_update: true,
rotation_order: EulerOrder::XYZ,
parent: None,
children: Vec::new(),
}
}
pub fn update_matrix(&mut self) {
self.matrix = Matrix4::compose(self.position, self.quaternion, self.scale);
}
pub fn set_matrix(&mut self, m: Matrix4) -> &mut Self {
self.matrix = m;
self.matrix_auto_update = false;
let (p, q, s) = m.decompose();
self.position = p;
self.quaternion = q;
self.scale = s;
self
}
pub fn rotation(&self) -> Euler {
Euler::from_quaternion(self.quaternion, self.rotation_order)
}
pub fn set_rotation(&mut self, e: Euler) -> &mut Self {
self.quaternion = Quaternion::from_euler(e);
self.rotation_order = e.order;
self
}
pub fn set_rotation_from_axis_angle(&mut self, axis: Vector3, angle: f32) -> &mut Self {
self.quaternion = Quaternion::from_axis_angle(axis, angle);
self
}
pub fn set_rotation_from_matrix(&mut self, m: &Matrix4) -> &mut Self {
self.quaternion = Quaternion::from_rotation_matrix(m);
self
}
pub fn set_rotation_from_quaternion(&mut self, q: Quaternion) -> &mut Self {
self.quaternion = q;
self
}
fn looks_down_negative_z(&self) -> bool {
matches!(self.kind, ObjectKind::Light(_))
}
fn look_rotation(&self, eye: Vector3, target: Vector3) -> Quaternion {
let m = if self.looks_down_negative_z() {
Matrix4::target_look_at(eye, target, self.up)
} else {
Matrix4::target_look_at(target, eye, self.up)
};
Quaternion::from_rotation_matrix(&m)
}
pub fn translate_on_axis(&mut self, axis: Vector3, distance: f32) -> &mut Self {
let world_axis = axis.apply_quaternion(self.quaternion);
self.position = self.position + world_axis * distance;
self
}
pub fn translate_x(&mut self, d: f32) -> &mut Self {
self.translate_on_axis(Vector3::new(1.0, 0.0, 0.0), d)
}
pub fn translate_y(&mut self, d: f32) -> &mut Self {
self.translate_on_axis(Vector3::new(0.0, 1.0, 0.0), d)
}
pub fn translate_z(&mut self, d: f32) -> &mut Self {
self.translate_on_axis(Vector3::new(0.0, 0.0, 1.0), d)
}
pub fn rotate_on_axis(&mut self, axis: Vector3, angle: f32) -> &mut Self {
let q = Quaternion::from_axis_angle(axis, angle);
self.quaternion = self.quaternion.multiply(q);
self
}
pub fn rotate_on_world_axis(&mut self, axis: Vector3, angle: f32) -> &mut Self {
let q = Quaternion::from_axis_angle(axis, angle);
self.quaternion = self.quaternion.premultiply(q);
self
}
pub fn rotate_x(&mut self, angle: f32) -> &mut Self {
self.rotate_on_axis(Vector3::new(1.0, 0.0, 0.0), angle)
}
pub fn rotate_y(&mut self, angle: f32) -> &mut Self {
self.rotate_on_axis(Vector3::new(0.0, 1.0, 0.0), angle)
}
pub fn rotate_z(&mut self, angle: f32) -> &mut Self {
self.rotate_on_axis(Vector3::new(0.0, 0.0, 1.0), angle)
}
pub fn apply_matrix4(&mut self, m: &Matrix4) -> &mut Self {
if self.matrix_auto_update {
self.update_matrix();
}
self.matrix = m.multiply(&self.matrix);
let (p, q, s) = self.matrix.decompose();
self.position = p;
self.quaternion = q;
self.scale = s;
self
}
pub fn apply_quaternion(&mut self, q: Quaternion) -> &mut Self {
self.quaternion = q.multiply(self.quaternion);
self
}
pub fn look_at(&mut self, target: Vector3) -> &mut Self {
self.quaternion = self.look_rotation(self.position, target);
self
}
pub fn world_position(&self) -> Vector3 {
let e = &self.matrix_world.elements;
Vector3::new(e[12], e[13], e[14])
}
pub fn world_quaternion(&self) -> Quaternion {
let (_, q, _) = self.matrix_world.decompose();
q
}
pub fn world_scale(&self) -> Vector3 {
let (_, _, s) = self.matrix_world.decompose();
s
}
}
#[derive(Debug, Default)]
pub struct ObjectArena {
pub nodes: SlotMap<ObjectId, Object3D>,
}
impl ObjectArena {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, obj: Object3D) -> ObjectId {
self.nodes.insert(obj)
}
pub fn get(&self, id: ObjectId) -> Option<&Object3D> {
self.nodes.get(id)
}
pub fn get_mut(&mut self, id: ObjectId) -> Option<&mut Object3D> {
self.nodes.get_mut(id)
}
pub fn add_child(&mut self, parent: ObjectId, child: ObjectId) {
if let Some(old_parent) = self.nodes.get(child).and_then(|c| c.parent)
&& let Some(p) = self.nodes.get_mut(old_parent)
{
p.children.retain(|c| *c != child);
}
if let Some(c) = self.nodes.get_mut(child) {
c.parent = Some(parent);
}
if let Some(p) = self.nodes.get_mut(parent) {
p.children.push(child);
}
}
pub fn remove_subtree(&mut self, id: ObjectId) -> usize {
self.remove_child(id);
let mut stack = vec![id];
let mut n = 0;
while let Some(i) = stack.pop() {
if let Some(obj) = self.nodes.remove(i) {
stack.extend(obj.children);
n += 1;
}
}
n
}
pub fn remove_child(&mut self, child: ObjectId) {
let parent = self.nodes.get(child).and_then(|c| c.parent);
if let Some(p) = parent
&& let Some(parent_obj) = self.nodes.get_mut(p)
{
parent_obj.children.retain(|c| *c != child);
}
if let Some(c) = self.nodes.get_mut(child) {
c.parent = None;
}
}
pub fn delete(&mut self, id: ObjectId) {
self.remove_child(id);
if let Some(node) = self.nodes.remove(id) {
for c in node.children {
if let Some(child) = self.nodes.get_mut(c)
&& child.parent == Some(id)
{
child.parent = None;
}
}
}
}
pub fn delete_subtrees(&mut self, ids: &[ObjectId]) -> Vec<ObjectId> {
let tops: std::collections::HashSet<ObjectId> = ids
.iter()
.copied()
.filter(|&id| self.nodes.contains_key(id))
.collect();
let parents: std::collections::HashSet<ObjectId> = tops
.iter()
.filter_map(|&id| self.nodes[id].parent)
.filter(|parent| !tops.contains(parent))
.collect();
for parent in parents {
if let Some(node) = self.nodes.get_mut(parent) {
node.children.retain(|child| !tops.contains(child));
}
}
let mut pending: Vec<ObjectId> = tops.into_iter().collect();
let mut removed = Vec::with_capacity(pending.len());
while let Some(id) = pending.pop() {
if let Some(node) = self.nodes.remove(id) {
pending.extend_from_slice(&node.children);
removed.push(id);
}
}
removed
}
pub fn set_children(&mut self, parent: ObjectId, children: &[ObjectId]) {
if !self.nodes.contains_key(parent) {
return;
}
let mut ancestors = vec![parent];
let mut cur = self.nodes[parent].parent;
while let Some(p) = cur {
ancestors.push(p);
cur = self.nodes.get(p).and_then(|n| n.parent);
}
let keep: Vec<ObjectId> = children
.iter()
.copied()
.filter(|c| self.nodes.contains_key(*c) && !ancestors.contains(c))
.collect();
let old = std::mem::take(&mut self.nodes[parent].children);
for c in old {
if !keep.contains(&c)
&& let Some(n) = self.nodes.get_mut(c)
{
n.parent = None;
}
}
for &c in &keep {
if let Some(prev) = self.nodes[c].parent.filter(|p| *p != parent)
&& let Some(p) = self.nodes.get_mut(prev)
{
p.children.retain(|x| *x != c);
}
self.nodes[c].parent = Some(parent);
}
self.nodes[parent].children = keep;
}
pub fn update_world_matrices(&mut self, id: ObjectId, parent_world: Matrix4) {
let world = {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.matrix_auto_update {
node.update_matrix();
}
node.matrix_world = parent_world.multiply(&node.matrix);
node.matrix_world
};
let children = self.nodes[id].children.clone();
for c in children {
self.update_world_matrices(c, world);
}
}
pub fn parent_world_matrix(&mut self, id: ObjectId) -> Matrix4 {
let mut chain = Vec::new();
let mut cur = self.nodes.get(id).and_then(|n| n.parent);
while let Some(p) = cur {
chain.push(p);
cur = self.nodes.get(p).and_then(|n| n.parent);
}
let mut world = Matrix4::identity();
for &n in chain.iter().rev() {
let node = &mut self.nodes[n];
if node.matrix_auto_update {
node.update_matrix();
}
node.matrix_world = world.multiply(&node.matrix);
world = node.matrix_world;
}
world
}
pub fn look_at(&mut self, id: ObjectId, target: Vector3) {
let parent_world = self.parent_world_matrix(id);
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.matrix_auto_update {
node.update_matrix();
}
let world = parent_world.multiply(&node.matrix);
let eye = Vector3::new(world.elements[12], world.elements[13], world.elements[14]);
let mut q = node.look_rotation(eye, target);
if node.parent.is_some() {
let pq = Quaternion::from_rotation_matrix(&parent_world.extract_rotation());
q = pq.invert().multiply(q);
}
node.quaternion = q;
}
pub fn attach(&mut self, parent: ObjectId, child: ObjectId) {
let parent_world = {
let pw = self.parent_world_matrix(parent);
let Some(p) = self.nodes.get_mut(parent) else {
return;
};
if p.matrix_auto_update {
p.update_matrix();
}
pw.multiply(&p.matrix)
};
let child_world = {
let cw = self.parent_world_matrix(child);
let Some(c) = self.nodes.get_mut(child) else {
return;
};
if c.matrix_auto_update {
c.update_matrix();
}
cw.multiply(&c.matrix)
};
let local = parent_world.invert().multiply(&child_world);
self.add_child(parent, child);
if let Some(c) = self.nodes.get_mut(child) {
c.matrix = local;
let (p, q, s) = local.decompose();
c.position = p;
c.quaternion = q;
c.scale = s;
}
}
pub fn traverse(&self, id: ObjectId, f: &mut impl FnMut(ObjectId, &Object3D)) {
if let Some(node) = self.nodes.get(id) {
f(id, node);
for c in node.children.clone() {
self.traverse(c, f);
}
}
}
pub fn traverse_visible(&self, id: ObjectId, f: &mut impl FnMut(ObjectId, &Object3D)) {
if let Some(node) = self.nodes.get(id) {
if !node.visible {
return;
}
f(id, node);
for c in node.children.clone() {
self.traverse_visible(c, f);
}
}
}
pub fn traverse_ancestors(&self, id: ObjectId, f: &mut impl FnMut(ObjectId, &Object3D)) {
let mut cur = self.nodes.get(id).and_then(|n| n.parent);
while let Some(p) = cur {
if let Some(n) = self.nodes.get(p) {
f(p, n);
cur = n.parent;
} else {
break;
}
}
}
pub fn get_object_by_name(&self, root: ObjectId, name: &str) -> Option<ObjectId> {
let mut found = None;
self.traverse(root, &mut |id, obj| {
if found.is_none() && obj.name == name {
found = Some(id);
}
});
found
}
pub fn get_objects_by_name(&self, root: ObjectId, name: &str) -> Vec<ObjectId> {
let mut out = Vec::new();
self.traverse(root, &mut |id, obj| {
if obj.name == name {
out.push(id);
}
});
out
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ids(arena: &ObjectArena, id: ObjectId) -> Vec<ObjectId> {
arena.get(id).unwrap().children.clone()
}
#[test]
fn set_children_mirrors_a_child_list() {
let mut arena = ObjectArena::new();
let [a, b, c, d] = [(); 4].map(|_| arena.insert(Object3D::group()));
arena.add_child(a, b);
arena.add_child(a, c);
arena.add_child(d, c); arena.set_children(a, &[c, b]);
assert_eq!(ids(&arena, a), vec![c, b], "the given order");
assert!(ids(&arena, d).is_empty(), "moved out of its old parent");
assert_eq!(arena.get(c).unwrap().parent, Some(a));
arena.set_children(a, &[b]);
assert_eq!(arena.get(c).unwrap().parent, None, "left out: detached");
arena.set_children(b, &[a]);
assert!(
ids(&arena, b).is_empty(),
"an ancestor is never made a child"
);
}
#[test]
fn delete_orphans_children() {
let mut arena = ObjectArena::new();
let [a, b, c] = [(); 3].map(|_| arena.insert(Object3D::group()));
arena.add_child(a, b);
arena.add_child(b, c);
arena.delete(b);
assert!(arena.get(b).is_none());
assert!(ids(&arena, a).is_empty());
assert_eq!(arena.get(c).unwrap().parent, None);
}
}