Grindstone Game Engine v0.2.0
An open source game engine and toolkit.
Loading...
Searching...
No Matches
TransformComponent.hpp
1#pragma once
2
3#include <glm/gtx/transform.hpp>
4#include <glm/gtx/quaternion.hpp>
5#include "EngineCore/Reflection/ComponentReflection.hpp"
6#include "Common/Math.hpp"
7
8#include <EngineCore/ECS/Entity.hpp>
9#include <EngineCore/CoreComponents/Parent/ParentComponent.hpp>
10
11namespace Grindstone {
13 Math::Quaternion rotation = Math::Quaternion(0.0f, 0.0f, 0.0f, 1.0f);
14 Math::Float3 position = Math::Float3(0.0f, 0.0f, 0.0f);
15 Math::Float3 scale = Math::Float3(1.f, 1.f, 1.f);
16
17 static Math::Matrix4 GetWorldTransformMatrix(ECS::Entity entity) {
18 return GetWorldTransformMatrix(entity.GetHandle(), entity.GetSceneEntityRegistry());
19 }
20
21 static Math::Matrix4 GetWorldTransformMatrix(entt::entity entity, const entt::registry& registry) {
22 Math::Matrix4 matrix = Math::Matrix4(1.0f);
23 entt::entity currentEntity = entity;
24 while (currentEntity != entt::null) {
25 const TransformComponent* transformComp = registry.try_get<TransformComponent>(currentEntity);
26 if (transformComp == nullptr) {
27 break;
28 }
29
30 matrix = transformComp->GetTransformMatrix() * matrix;
31
32 const ParentComponent* parentComp = registry.try_get<ParentComponent>(currentEntity);
33 if (parentComp == nullptr) {
34 break;
35 }
36
37 currentEntity = parentComp->parentEntity;
38 }
39
40 return matrix;
41 }
42
43 static Math::Float3 GetWorldPosition(const ECS::Entity entity) {
44 return GetWorldPosition(entity.GetHandle(), entity.GetSceneEntityRegistry());
45 }
46
47 static Math::Float3 GetWorldPosition(const entt::entity entity, const entt::registry& registry) {
48 Math::Matrix4 worldMatrix = GetWorldTransformMatrix(entity, registry);
49
50 return Math::Float3(worldMatrix[3][0], worldMatrix[3][1], worldMatrix[3][2]);
51 }
52
53 void SetLocalMatrix(Math::Matrix4 localMatrix) {
54 rotation = Math::Quaternion(localMatrix);
55
56 for (int i = 0; i < 3; i++) {
57 position[i] = localMatrix[3][i];
58
59 scale[i] = glm::sqrt(
60 localMatrix[i][0] * localMatrix[i][0]
61 + localMatrix[i][1] * localMatrix[i][1]
62 + localMatrix[i][2] * localMatrix[i][2]);
63 }
64 }
65
66 void SetWorldMatrixRelativeTo(Math::Matrix4 newWorldMatrix, Math::Matrix4 parentMatrix) {
67 Math::Matrix4 localMatrix = glm::inverse(parentMatrix) * newWorldMatrix;
68 SetLocalMatrix(localMatrix);
69 }
70
71 Math::Matrix4 GetTransformMatrix() const {
72 return glm::translate(position) *
73 glm::toMat4(rotation) *
74 glm::scale(scale);
75 }
76
77 Math::Float3 GetForward() const {
78 return rotation * Math::Float3(0.0f, 0.0f, 1.0f);
79 }
80
81 Math::Float3 GetRight() const {
82 return rotation * Math::Float3(1.0f, 0.0f, 0.0f);
83 }
84
85 Math::Float3 GetUp() const {
86 return rotation * Math::Float3(0.0f, 1.0f, 0.0f);
87 }
88
89 REFLECT("Transform")
90 };
91}
Definition Entity.hpp:15
Definition ParentComponent.hpp:8
Definition TransformComponent.hpp:12