use std::ops::Add;
use crate::Mat4;
use crate::Vec2;
use crate::Vec3;
#[derive(Debug, Clone)]
pub struct Transform {
matrix: Mat4,
pub position: Vec3,
pub rotation: Vec3,
pub scale: Vec3,
}
impl Default for Transform {
fn default() -> Self {
Self {
matrix: Mat4::identity(),
position: Vec3::zeros(),
rotation: Vec3::zeros(),
scale: Vec3::from_element(1.0),
}
}
}
impl Transform {
pub fn new() -> Self {
Self::default()
}
pub fn new_with_position(position: Vec3) -> Self {
Self {
position,
matrix: Mat4::new_translation(&position),
..Self::default()
}
}
pub fn matrix(&self) -> Mat4 {
self.matrix
}
pub fn matrix_slice(&mut self) -> &[f32] {
self.matrix.as_slice()
}
fn recalculate_matrix(&mut self) {
self.matrix = Mat4::new_translation(&self.position)
* Mat4::new_rotation(self.rotation)
* Mat4::new_nonuniform_scaling(&self.scale);
}
pub fn set_position(&mut self, position: Vec3) {
self.position = position;
self.recalculate_matrix();
}
pub fn set_rotation(&mut self, rotation: f32) {
self.rotation = Vec3::z() * rotation;
self.recalculate_matrix();
}
pub fn set_scale(&mut self, scale: Vec3) {
self.scale = scale;
self.recalculate_matrix();
}
pub fn get_position(&self) -> &[f32] {
self.position.as_slice()
}
pub fn get_rotation(&self) -> f32 {
self.rotation.z
}
pub fn get_scale(&self) -> &[f32] {
self.scale.as_slice()
}
}
#[derive(Debug, Clone, Copy)]
pub struct Transform2D {
pub position: Vec2,
pub rotation: f32,
pub scale: Vec2,
}
impl Default for Transform2D {
fn default() -> Self {
Self {
position: Vec2::zeros(),
rotation: 0.0f32,
scale: Vec2::from_element(1.0),
}
}
}
impl Add for Transform2D {
type Output = Transform2D;
fn add(self, rhs: Self) -> Self::Output {
Transform2D {
position: self.position + rhs.position,
rotation: self.rotation + rhs.rotation,
..rhs
}
}
}
impl Transform2D {
pub fn new_with_position(pos_x: f32, pos_y: f32) -> Self {
Self {
position: Vec2::new(pos_x, pos_y),
..Default::default()
}
}
pub fn new_with_scale(scale_x: f32, scale_y: f32) -> Self {
Self {
scale: Vec2::new(scale_x, scale_y),
..Default::default()
}
}
pub fn translate(&mut self, delta_x: f32, delta_y: f32) {
self.position.x += delta_x;
self.position.y += delta_y;
}
pub fn matrix(&self) -> Mat4 {
Mat4::new_translation(&Vec3::new(self.position.x, self.position.y, 0.0))
}
}