SleakEngine
0.1.0
C++23 multi-backend game engine
Toggle main menu visibility
Loading...
Searching...
No Matches
GameObject.hpp
Go to the documentation of this file.
1
#ifndef _GAMEOBJECT_H_
2
#define _GAMEOBJECT_H_
3
4
#include "
Object.hpp
"
5
#include <
Core/Logger.hpp
>
6
#include <
ECS/Component.hpp
>
7
#include <
Utility/Container/List.hpp
>
8
#include <
Memory/RefPtr.hpp
>
9
#include <type_traits>
10
#include <string>
11
12
namespace
Sleak
{
13
namespace
Math
{
class
Vector3D
;};
14
class
SceneBase
;
15
class
TransformComponent
;
16
class
MaterialComponent
;
17
class
MeshComponent
;
18
/// Scene entity holding components and an optional parent/child transform
19
/// hierarchy. Scene owns the instance; destroy via Scene::DestroyObject().
20
///
21
/// A GameObject on its own does nothing. Behavior comes from the
22
/// components attached to it: a TransformComponent for placement, a
23
/// MeshComponent and MaterialComponent to be drawn, a ColliderComponent
24
/// and RigidbodyComponent to be simulated, and your own Component
25
/// subclasses for gameplay.
26
///
27
/// AddComponent<T>() constructs the component in place, forwarding
28
/// extra arguments to its constructor after the owner pointer. Only one
29
/// component of a given type is allowed per object: a second
30
/// AddComponent<T>() logs a warning and does nothing. GetComponent<T>()
31
/// resolves through `dynamic_cast`, so it also matches subclasses.
32
///
33
/// The scene that received the object through SceneBase::AddObject()
34
/// owns it. Never `delete` a GameObject. Use SceneBase::DestroyObject()
35
/// for deferred destruction, which is what you want while iterating, or
36
/// SceneBase::RemoveObject() for immediate destruction.
37
///
38
/// A parent owns every child that was not itself added to a scene, so a
39
/// hierarchy built with SetParent() (for example by ModelLoader) only
40
/// needs its root added. Deleting a parent deletes those children too.
41
///
42
/// Camera, Light, and its subclasses all derive from GameObject, so
43
/// they are added and found the same way as anything else.
44
///
45
/// @code{.cpp}
46
/// auto* crate = Sleak::GameObject::CreateCube(
47
/// Sleak::Math::Vector3D(0.0f, 1.0f, 0.0f));
48
/// crate->SetTag("Destructible");
49
///
50
/// crate->AddComponent<Sleak::MaterialComponent>(
51
/// Sleak::RefPtr<Sleak::Material>(new Sleak::Material()));
52
/// crate->AddComponent<Sleak::RigidbodyComponent>(
53
/// Sleak::BodyType::Dynamic);
54
///
55
/// if (auto* t = crate->GetComponent<Sleak::TransformComponent>()) {
56
/// t->SetScale(Sleak::Math::Vector3D(2.0f, 2.0f, 2.0f));
57
/// }
58
///
59
/// AddObject(crate); // the scene now owns it
60
/// @endcode
61
///
62
/// @see Component, SceneBase, TransformComponent, MeshComponent,
63
/// MaterialComponent, Camera
64
/// @ingroup scene
65
class
ENGINE_API
GameObject
:
public
Object
{
66
public
:
67
GameObject
(
const
std::string& name =
"GameObject"
)
68
:
Object
(name), m_isActive(true),
bIsInitialized
(false),
69
m_pendingDestroy(false), m_parent(nullptr) {}
70
71
~GameObject
()
override
;
72
73
/// Constructs and attaches a component of type T. Warns and no-ops if one already exists.
74
template
<
typename
T,
typename
... Args>
75
void
AddComponent
(Args&&... args) {
76
static_assert
(std::is_base_of<Component, T>::value,
"T must derive from Component!"
);
77
78
if
(
GetComponent<T>
() !=
nullptr
) {
79
SLEAK_WARN
(
"The component already exists!"
);
80
return
;
81
}
82
83
RefPtr<Component>
newComponent =
RefPtr<T>
(
new
T(
this
, std::forward<Args>(args)...));
84
if
(
bIsInitialized
) InitializeComponent(newComponent.
get
());
85
Components.add(std::move(newComponent));
86
RefreshComponentCache();
87
}
88
89
/// Destroys and detaches the first component of type T, if present.
90
template
<
typename
T>
91
void
RemoveComponent
() {
92
static_assert
(std::is_base_of<Component, T>::value,
"T must derive from Component!"
);
93
94
for
(
size_t
i = 0; i < Components.GetSize(); ++i) {
95
if
(
dynamic_cast<
T*
>
(Components[i].get()) !=
nullptr
) {
96
Components[i]->OnDestroy();
97
Components.erase(i);
98
RefreshComponentCache();
99
break
;
100
}
101
}
102
}
103
104
/// Finds the first attached component of type T, or nullptr.
105
template
<
typename
T>
106
T*
GetComponent
() {
107
static_assert
(std::is_base_of_v<Component, T>,
108
"T must derive from Component!"
);
109
110
if
constexpr
(std::is_same_v<T, TransformComponent>) {
111
return
m_cachedTransform;
112
}
else
if
constexpr
(std::is_same_v<T, MaterialComponent>) {
113
return
m_cachedMaterial;
114
}
else
if
constexpr
(std::is_same_v<T, MeshComponent>) {
115
return
m_cachedMesh;
116
}
else
{
117
for
(
size_t
i = 0; i < Components.GetSize(); ++i) {
118
Component
* rawPtr = Components[i].get();
119
if
(!rawPtr)
continue
;
120
121
T* component =
dynamic_cast<
T*
>
(rawPtr);
122
if
(component)
return
component;
123
}
124
125
return
nullptr
;
126
}
127
}
128
129
/// True if a component of type T is attached.
130
template
<
typename
T>
131
bool
HasComponent
() {
132
static_assert
(std::is_base_of_v<Component, T>,
133
"T must derive from Component!"
);
134
return
GetComponent<T>
() !=
nullptr
;
135
}
136
137
/// Initializes the object, components and children; repeats no-op.
138
virtual
void
Initialize();
139
bool
IsInitialized
()
const
{
return
bIsInitialized
; }
140
virtual
void
Update
(
float
deltaTime);
141
virtual
void
FixedUpdate(
float
fixedDeltaTime);
142
virtual
void
LateUpdate(
float
deltaTime);
143
144
/// Enables or disables the object, firing OnEnable/OnDisable on its components.
145
void
SetActive(
bool
active);
146
bool
IsActive
()
const
{
return
m_isActive; }
147
148
void
SetTag
(
const
std::string& tag) { m_tag = tag; }
149
const
std::string&
GetTag
()
const
{
return
m_tag; }
150
151
/// Reparents this object, updating both the old and new parent's child lists.
152
void
SetParent(
GameObject
* parent);
153
GameObject
*
GetParent
()
const
{
return
m_parent; }
154
const
List<GameObject*>
&
GetChildren
()
const
{
return
m_children; }
155
void
AddChild(
GameObject
* child);
156
void
RemoveChild(
GameObject
* child);
157
bool
HasParent
()
const
{
return
m_parent !=
nullptr
; }
158
bool
HasChildren
()
const
{
return
m_children.GetSize() > 0; }
159
/// True once a scene took ownership through SceneBase::AddObject().
160
bool
IsOwnedByScene
()
const
{
return
m_ownedByScene; }
161
162
virtual
bool
IsLight
()
const
{
return
false
; }
163
164
/// Flags the object for deferred destruction on the next scene pass.
165
void
MarkForDestroy
() { m_pendingDestroy =
true
; }
166
bool
IsPendingDestroy
()
const
{
return
m_pendingDestroy; }
167
168
/// Built-in primitive factories, mainly for prototyping and debug scenes.
169
static
GameObject
* CreatePlane(
Math::Vector3D
position,
int
width
= 100,
int
height
= 100);
170
static
GameObject
* CreateCube(
Math::Vector3D
position);
171
static
GameObject
* CreateSphere(
Math::Vector3D
position,
int
stack = 16,
int
slices = 16);
172
static
GameObject
* CreateCapsule(
Math::Vector3D
position,
int
segments = 16,
int
rings = 8,
float
height
= 1,
float
radius = 0.5);
173
static
GameObject
* CreateCylinder(
Math::Vector3D
position,
int
segments = 16,
float
height
= 1,
float
radius = 0.5);
174
static
GameObject
*
CreateTorus
(
Math::Vector3D
position,
int
segments = 16,
int
rings = 8,
float
innerRadius = 8,
float
outerRadius = 9);
175
176
protected
:
177
bool
bIsInitialized
;
178
179
private
:
180
bool
m_isActive;
181
bool
m_pendingDestroy;
182
bool
m_ownedByScene =
false
;
183
std::string m_tag =
"Untagged"
;
184
185
List<RefPtr<Component>
> Components;
186
187
// First matches in Components, kept in sync by RefreshComponentCache
188
TransformComponent
* m_cachedTransform =
nullptr
;
189
MaterialComponent
* m_cachedMaterial =
nullptr
;
190
MeshComponent
* m_cachedMesh =
nullptr
;
191
192
// Hierarchy
193
GameObject
* m_parent;
194
List<GameObject*>
m_children;
195
196
/// Calls OnDestroy() on and drops every attached component.
197
void
DestroyComponents();
198
/// Re-resolves the cached transform, material and mesh pointers.
199
void
RefreshComponentCache();
200
/// Initializes a component once, then enables it if active.
201
void
InitializeComponent(
Component
* component);
202
203
friend
class
SceneBase
;
204
};
205
}
206
207
#endif
// _GAMEOBJECT_H_
width
int width
Definition
Application.cpp:44
height
int height
Definition
Application.cpp:45
Component.hpp
List.hpp
Logger.hpp
SLEAK_WARN
#define SLEAK_WARN(...)
Definition
Logger.hpp:21
Object.hpp
RefPtr.hpp
Sleak::Component
Definition
Component.hpp:59
Sleak::GameObject
Definition
GameObject.hpp:65
Sleak::GameObject::HasComponent
bool HasComponent()
True if a component of type T is attached.
Definition
GameObject.hpp:131
Sleak::GameObject::GetParent
GameObject * GetParent() const
Definition
GameObject.hpp:153
Sleak::GameObject::AddComponent
void AddComponent(Args &&... args)
Constructs and attaches a component of type T. Warns and no-ops if one already exists.
Definition
GameObject.hpp:75
Sleak::GameObject::GetChildren
const List< GameObject * > & GetChildren() const
Definition
GameObject.hpp:154
Sleak::GameObject::HasParent
bool HasParent() const
Definition
GameObject.hpp:157
Sleak::GameObject::MarkForDestroy
void MarkForDestroy()
Flags the object for deferred destruction on the next scene pass.
Definition
GameObject.hpp:165
Sleak::GameObject::IsOwnedByScene
bool IsOwnedByScene() const
True once a scene took ownership through SceneBase::AddObject().
Definition
GameObject.hpp:160
Sleak::GameObject::IsActive
bool IsActive() const
Definition
GameObject.hpp:146
Sleak::GameObject::HasChildren
bool HasChildren() const
Definition
GameObject.hpp:158
Sleak::GameObject::IsPendingDestroy
bool IsPendingDestroy() const
Definition
GameObject.hpp:166
Sleak::GameObject::IsLight
virtual bool IsLight() const
Definition
GameObject.hpp:162
Sleak::GameObject::bIsInitialized
bool bIsInitialized
Definition
GameObject.hpp:177
Sleak::GameObject::GetComponent
T * GetComponent()
Finds the first attached component of type T, or nullptr.
Definition
GameObject.hpp:106
Sleak::GameObject::SetTag
void SetTag(const std::string &tag)
Definition
GameObject.hpp:148
Sleak::GameObject::GameObject
GameObject(const std::string &name="GameObject")
Definition
GameObject.hpp:67
Sleak::GameObject::CreateTorus
static GameObject * CreateTorus(Math::Vector3D position, int segments=16, int rings=8, float innerRadius=8, float outerRadius=9)
Sleak::GameObject::SceneBase
friend class SceneBase
Definition
GameObject.hpp:203
Sleak::GameObject::IsInitialized
bool IsInitialized() const
Definition
GameObject.hpp:139
Sleak::GameObject::GetTag
const std::string & GetTag() const
Definition
GameObject.hpp:149
Sleak::GameObject::RemoveComponent
void RemoveComponent()
Destroys and detaches the first component of type T, if present.
Definition
GameObject.hpp:91
Sleak::List
Implements a dynamic array-like list for storing and managing a collection of elements.
Definition
List.hpp:21
Sleak::MaterialComponent
Definition
MaterialComponent.hpp:13
Sleak::Math::Vector3D
Definition
Vector.hpp:354
Sleak::MeshComponent
Definition
MeshComponent.hpp:26
Sleak::Object::Object
Object(const std::string &name="Object")
Definition
Object.hpp:14
Sleak::RefPtr
Definition
RefPtr.hpp:62
Sleak::RefPtr::get
T * get() const
Definition
RefPtr.hpp:170
Sleak::SceneBase
Definition
SceneBase.hpp:72
Sleak::TransformComponent
Represents the position, rotation, and scale of an entity in 3D space.
Definition
TransformComponent.hpp:26
Sleak::EventType::Update
@ Update
Definition
Event.hpp:26
Sleak::Math
Vectors, matrices, quaternions, colors, AABBs, and random helpers.
Definition
GameObject.hpp:13
Sleak
Root namespace for everything the engine exposes.
Definition
Camera.hpp:10
include
public
Core
GameObject.hpp
Generated on
for SleakEngine by
1.18.0