Monad Engine da02fba2
> Undercity Codex_
Loading...
Searching...
No Matches
Component.h
Go to the documentation of this file.
1#pragma once
2
3#include <nlohmann/json.hpp>
4
5#include <cstddef>
6#include <string>
7#include <unordered_map>
8#include <memory>
9
10namespace eng
11{
12 class GameObject;
13
15 {
16 public:
17 virtual ~Component() = default;
18 virtual void LoadProperties(const nlohmann::json& json);
19 virtual void Update(float deltaTime) = 0;
20 virtual void Init();
21 virtual size_t GetTypeId() const = 0;
22
24
25 template<typename T>
26 static size_t StaticTypeId()
27 {
28 static size_t typeId = nextId++;
29 return typeId;
30 }
31
32 protected:
33 GameObject* m_owner = nullptr;
34
35 friend class GameObject;
36
37 private:
38 static size_t nextId;
39 };
40
42 {
43 public:
44 virtual ~ComponentCreatorBase() = default;
45 virtual Component* CreateComponent() = 0;
46 };
47
48 template<typename T>
50 {
51 public:
53 {
54 return new T();
55 }
56 };
57
59 {
60 public:
62
63 template<typename T>
64 void RegisterComponent(const std::string& name)
65 {
66 m_creators.emplace(name, std::make_unique<ComponentCreator<T>>());
67 }
68
69 Component* CreateComponent(const std::string& name);
70
71 private:
72 std::unordered_map<std::string, std::unique_ptr<ComponentCreatorBase>> m_creators;
73 };
74
75#define COMPONENT(ComponentClass) \
76public: \
77 static size_t TypeId() { return eng::Component::StaticTypeId<ComponentClass>(); } \
78 size_t GetTypeId() const override { return TypeId(); } \
79 static void Register() { eng::ComponentFactory::GetInstance().RegisterComponent<ComponentClass>(std::string(#ComponentClass)); }
80}
virtual Component * CreateComponent()=0
virtual ~ComponentCreatorBase()=default
Component * CreateComponent() override
Definition Component.h:52
void RegisterComponent(const std::string &name)
Definition Component.h:64
static ComponentFactory & GetInstance()
Definition Component.cpp:20
Component * CreateComponent(const std::string &name)
Definition Component.cpp:26
virtual void Init()
Definition Component.cpp:11
virtual void Update(float deltaTime)=0
GameObject * GetOwner()
Definition Component.cpp:15
virtual ~Component()=default
static size_t StaticTypeId()
Definition Component.h:26
virtual void LoadProperties(const nlohmann::json &json)
Definition Component.cpp:7
virtual size_t GetTypeId() const =0
GameObject * m_owner
Definition Component.h:33