Skip to content

Commit

Permalink
Add recursive transformations
Browse files Browse the repository at this point in the history
  • Loading branch information
Ciubix8513 committed Jul 1, 2024
1 parent cd82ddd commit e5195e0
Showing 1 changed file with 50 additions and 14 deletions.
64 changes: 50 additions & 14 deletions src/components/transform.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use crate::math::{mat4x4::Mat4x4, vec3::Vec3};

use crate::ecs::Component;
use crate::ecs::{Component, ComponentReference};

///Transform component contains function and data to determine the position of the entity
///
///Note: rotation is represented as Euler angles using degrees
#[derive(Debug)]
pub struct Transform {
pub position: Vec3,
pub rotation: Vec3,
pub scale: Vec3,
parent: Option<ComponentReference<Self>>,
}

impl Default for Transform {
Expand All @@ -20,18 +23,7 @@ impl Default for Transform {
y: 1.0,
z: 1.0,
},
}
}
}

impl Transform {
///Create a new transform instance
#[must_use]
pub const fn new(position: Vec3, rotation: Vec3, scale: Vec3) -> Self {
Self {
position,
rotation,
scale,
parent: None,
}
}
}
Expand All @@ -45,6 +37,7 @@ impl Component for Transform {
rotation: Vec3::default(),
scale: Vec3::new(1.0, 1.0, 1.0),
position: Vec3::default(),
parent: None,
}
}
fn as_any(&self) -> &dyn std::any::Any {
Expand All @@ -56,9 +49,52 @@ impl Component for Transform {
}

impl Transform {
///Returns transformation of the entity
///Create a new transform instance
#[must_use]
pub const fn new(position: Vec3, rotation: Vec3, scale: Vec3) -> Self {
Self {
position,
rotation,
scale,
parent: None,
}
}

///Creates a new transform instance, with a parent
pub fn with_parent(
position: Vec3,
rotation: Vec3,
scale: Vec3,
parent: ComponentReference<Transform>,
) -> Self {
Self {
position,
rotation,
scale,
parent: Some(parent),
}
}

///Returns transformation of the entity taking transform of the parent into account
#[must_use]
pub fn matrix(&self) -> Mat4x4 {
if let Some(p) = &self.parent {
let parent_mat = p.borrow().matrix();
parent_mat * Mat4x4::transform_matrix_euler(&self.position, &self.scale, &self.rotation)
} else {
Mat4x4::transform_matrix_euler(&self.position, &self.scale, &self.rotation)
}
}

//Returns transformation matrix of the entity, without taking the parent transformation into
//account
#[must_use]
pub fn matrix_local(&self) -> Mat4x4 {
Mat4x4::transform_matrix_euler(&self.position, &self.scale, &self.rotation)
}

///Sets the parent of the entity, applying all parent transformations to this entity
pub fn set_parent(mut self, p: ComponentReference<Transform>) {
self.parent = Some(p);
}
}

0 comments on commit e5195e0

Please sign in to comment.