Skip to main content

rayengine_core/
transform.rs

1//! Local and global transforms for typed 2D and 3D entities.
2
3use glam::{Mat3, Mat4, Quat, Vec2, Vec3};
4use hecs::Entity;
5
6/// Optional scene parent. Prefer [`crate::scene::Scene::set_parent`] to validate edits.
7#[derive(Clone, Copy, Debug)]
8pub struct Parent(pub Entity);
9
10/// A 2D local transform. Positive Y points down; rotation is in radians.
11#[derive(Clone, Copy, Debug)]
12pub struct Transform2D {
13    /// Local position.
14    pub position: Vec2,
15    /// Local rotation in radians.
16    pub rotation: f32,
17    /// Local scale.
18    pub scale: Vec2,
19}
20
21impl Default for Transform2D {
22    fn default() -> Self {
23        Self {
24            position: Vec2::ZERO,
25            rotation: 0.0,
26            scale: Vec2::ONE,
27        }
28    }
29}
30
31impl Transform2D {
32    /// Translation with identity rotation and scale.
33    pub fn at(position: Vec2) -> Self {
34        Self {
35            position,
36            ..Self::default()
37        }
38    }
39
40    /// Local affine matrix.
41    pub fn matrix(self) -> Mat3 {
42        Mat3::from_scale_angle_translation(self.scale, self.rotation, self.position)
43    }
44}
45
46/// A 3D local transform. Positive Y points up, using right-handed coordinates.
47#[derive(Clone, Copy, Debug)]
48pub struct Transform3D {
49    /// Local position.
50    pub position: Vec3,
51    /// Local rotation.
52    pub rotation: Quat,
53    /// Local scale.
54    pub scale: Vec3,
55}
56
57impl Default for Transform3D {
58    fn default() -> Self {
59        Self {
60            position: Vec3::ZERO,
61            rotation: Quat::IDENTITY,
62            scale: Vec3::ONE,
63        }
64    }
65}
66
67impl Transform3D {
68    /// Translation with identity rotation and scale.
69    pub fn at(position: Vec3) -> Self {
70        Self {
71            position,
72            ..Self::default()
73        }
74    }
75
76    /// Local affine matrix.
77    pub fn matrix(self) -> Mat4 {
78        Mat4::from_scale_rotation_translation(self.scale, self.rotation, self.position)
79    }
80}
81
82/// Computed 2D transform including every scene ancestor.
83#[derive(Clone, Copy, Debug)]
84pub struct GlobalTransform2D(pub Mat3);
85
86impl Default for GlobalTransform2D {
87    fn default() -> Self {
88        Self(Mat3::IDENTITY)
89    }
90}
91
92/// Computed 3D transform including every scene ancestor.
93#[derive(Clone, Copy, Debug)]
94pub struct GlobalTransform3D(pub Mat4);
95
96impl Default for GlobalTransform3D {
97    fn default() -> Self {
98        Self(Mat4::IDENTITY)
99    }
100}