Skip to main content

khora_data/ecs/components/
transform.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use khora_core::math::{Mat4, Quaternion, Vec3};
16use khora_macros::Component;
17
18/// A component that describes an entity's position, rotation, and scale
19/// relative to its `Parent`. If the entity has no `Parent`, this is relative
20/// to the world origin.
21///
22/// This is the component that users and other systems should modify. A dedicated
23/// transform propagation system will use this component's value to calculate
24/// the final `GlobalTransform`.
25#[derive(Debug, Clone, Copy, PartialEq, Component)]
26#[component(domain = Spatial)]
27pub struct Transform {
28    /// The translation (position) of the entity.
29    pub translation: Vec3,
30    /// The rotation of the entity, represented as a quaternion.
31    pub rotation: Quaternion,
32    /// The scale of the entity.
33    pub scale: Vec3,
34}
35
36impl Transform {
37    /// Creates a new `Transform` with a given translation, rotation, and scale.
38    pub fn new(translation: Vec3, rotation: Quaternion, scale: Vec3) -> Self {
39        Self {
40            translation,
41            rotation,
42            scale,
43        }
44    }
45
46    /// Creates a new `Transform` with a given translation, and identity rotation/scale.
47    pub fn from_translation(translation: Vec3) -> Self {
48        Self {
49            translation,
50            rotation: Quaternion::IDENTITY,
51            scale: Vec3::ONE,
52        }
53    }
54
55    /// Creates a new identity `Transform`, with no translation, rotation, or scaling.
56    /// This represents the origin.
57    pub fn identity() -> Self {
58        Self {
59            translation: Vec3::ZERO,
60            rotation: Quaternion::IDENTITY,
61            scale: Vec3::ONE,
62        }
63    }
64
65    /// Calculates the `Mat4` transformation matrix from this component's
66    /// translation, rotation, and scale.
67    ///
68    /// The final matrix is calculated in the standard `Scale -> Rotate -> Translate` order.
69    pub fn to_mat4(&self) -> Mat4 {
70        // T * R * S
71        Mat4::from_translation(self.translation)
72            * Mat4::from_quat(self.rotation)
73            * Mat4::from_scale(self.scale)
74    }
75}
76
77impl Default for Transform {
78    /// Returns the identity `Transform`.
79    fn default() -> Self {
80        Self::identity()
81    }
82}