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};
16
17use crate::ecs::Component;
18
19/// A component that describes an entity's position, rotation, and scale
20/// relative to its `Parent`. If the entity has no `Parent`, this is relative
21/// to the world origin.
22///
23/// This is the component that users and other systems should modify. A dedicated
24/// transform propagation system will use this component's value to calculate
25/// the final `GlobalTransform`.
26#[derive(Debug, Clone, Copy, PartialEq)]
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 Component for Transform {}
37
38impl Transform {
39 /// Creates a new `Transform` with a given translation, rotation, and scale.
40 pub fn new(translation: Vec3, rotation: Quaternion, scale: Vec3) -> Self {
41 Self {
42 translation,
43 rotation,
44 scale,
45 }
46 }
47
48 /// Creates a new identity `Transform`, with no translation, rotation, or scaling.
49 /// This represents the origin.
50 pub fn identity() -> Self {
51 Self {
52 translation: Vec3::ZERO,
53 rotation: Quaternion::IDENTITY,
54 scale: Vec3::ONE,
55 }
56 }
57
58 /// Calculates the `Mat4` transformation matrix from this component's
59 /// translation, rotation, and scale.
60 ///
61 /// The final matrix is calculated in the standard `Scale -> Rotate -> Translate` order.
62 pub fn to_mat4(&self) -> Mat4 {
63 // T * R * S
64 Mat4::from_translation(self.translation)
65 * Mat4::from_quat(self.rotation)
66 * Mat4::from_scale(self.scale)
67 }
68}
69
70impl Default for Transform {
71 /// Returns the identity `Transform`.
72 fn default() -> Self {
73 Self::identity()
74 }
75}