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)]
26pub struct Transform {
27 /// The translation (position) of the entity.
28 pub translation: Vec3,
29 /// The rotation of the entity, represented as a quaternion.
30 pub rotation: Quaternion,
31 /// The scale of the entity.
32 pub scale: Vec3,
33}
34
35impl Transform {
36 /// Creates a new `Transform` with a given translation, rotation, and scale.
37 pub fn new(translation: Vec3, rotation: Quaternion, scale: Vec3) -> Self {
38 Self {
39 translation,
40 rotation,
41 scale,
42 }
43 }
44
45 /// Creates a new identity `Transform`, with no translation, rotation, or scaling.
46 /// This represents the origin.
47 pub fn identity() -> Self {
48 Self {
49 translation: Vec3::ZERO,
50 rotation: Quaternion::IDENTITY,
51 scale: Vec3::ONE,
52 }
53 }
54
55 /// Calculates the `Mat4` transformation matrix from this component's
56 /// translation, rotation, and scale.
57 ///
58 /// The final matrix is calculated in the standard `Scale -> Rotate -> Translate` order.
59 pub fn to_mat4(&self) -> Mat4 {
60 // T * R * S
61 Mat4::from_translation(self.translation)
62 * Mat4::from_quat(self.rotation)
63 * Mat4::from_scale(self.scale)
64 }
65}
66
67impl Default for Transform {
68 /// Returns the identity `Transform`.
69 fn default() -> Self {
70 Self::identity()
71 }
72}