Last active
June 11, 2020 21:49
-
-
Save anthofoxo/21c52da679c6161eeda066cf3614406a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <vector> | |
| #include <memory> | |
| #include <iostream> | |
| #include <unordered_map> | |
| class Entity; | |
| class Component | |
| { | |
| friend class Entity; | |
| private: | |
| Entity* m_Entity = nullptr; | |
| public: | |
| Component() = default; | |
| virtual ~Component() = default; | |
| virtual void Update() | |
| { | |
| } | |
| inline Entity* GetEntity() { return m_Entity; } | |
| }; | |
| template<typename T> | |
| struct ComponentName | |
| { | |
| static const char* GetName(); | |
| }; | |
| #define CREATE_COMPONENT_NAME(name)\ | |
| template<>\ | |
| struct ComponentName<name>\ | |
| {\ | |
| static const char* GetName()\ | |
| {\ | |
| return #name;\ | |
| }\ | |
| } | |
| class Entity final | |
| { | |
| private: | |
| std::unordered_map<const char*, std::shared_ptr<Component>> components; | |
| public: | |
| Entity() = default; | |
| inline ~Entity() | |
| { | |
| for (auto& [key, value] : components) | |
| value->m_Entity = nullptr; | |
| } | |
| template<typename T, typename... Params> | |
| inline std::shared_ptr<T> AddComponent(Params&&... params) | |
| { | |
| if (HasComponent<T>()) return nullptr; | |
| std::shared_ptr<T> component = std::make_shared<T>(params...); | |
| component->m_Entity = this; | |
| components[ComponentName<T>::GetName()] = component; | |
| return component; | |
| } | |
| inline virtual void update() | |
| { | |
| for (auto& [key, value] : components) | |
| value->Update(); | |
| } | |
| template<typename T> | |
| inline bool HasComponent() | |
| { | |
| return components.find(ComponentName<T>::GetName()) != components.end(); | |
| } | |
| template<typename T> | |
| inline std::shared_ptr<T> GetComponent() | |
| { | |
| auto result = components.find(ComponentName<T>::GetName()); | |
| if (result != components.end()) | |
| return std::dynamic_pointer_cast<T>(result->second); | |
| return nullptr; | |
| } | |
| inline std::unordered_map<const char*, std::shared_ptr<Component>>& GetComponents() | |
| { | |
| return components; | |
| } | |
| template<typename T> | |
| inline std::shared_ptr<T> RemoveComponent() | |
| { | |
| if (!HasComponent<T>()) return nullptr; | |
| const char* key = ComponentName<T>::GetName(); | |
| std::shared_ptr<T> c = std::dynamic_pointer_cast<T>(std::move(components[key])); | |
| components.erase(key); | |
| return c; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment