ECS.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * 2D Game Engine
  3. * ECS.h:
  4. * Based on pikuma.com 2D game engine in C++ and Lua course
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 11/02/2021.
  8. */
  9. #ifndef GAMEENGINE_ECS_H
  10. #define GAMEENGINE_ECS_H
  11. #include <stdint.h>
  12. #include <bitset>
  13. #include <vector>
  14. #include <unordered_map>
  15. #include <typeindex>
  16. #include <Pool.h>
  17. const uint32_t MAX_COMPONENTS = 32;
  18. typedef std::bitset<MAX_COMPONENTS> Signature;
  19. struct IComponent
  20. {
  21. protected:
  22. static uint32_t nextId;
  23. };
  24. template <typename T> class Component: public IComponent
  25. {
  26. public:
  27. static uint32_t getId()
  28. {
  29. static auto id = IComponent::nextId++;
  30. return id;
  31. }
  32. };
  33. class Entity
  34. {
  35. private:
  36. uint32_t id;
  37. public:
  38. explicit Entity(uint32_t id): id(id) {};
  39. Entity(const Entity & entity) = default;
  40. uint32_t getId() const;
  41. Entity& operator=(const Entity & other) = default;
  42. bool operator==(const Entity &other) const { return this->id == other.id; };
  43. bool operator!=(const Entity &other) const { return this->id != other.id; };
  44. bool operator>(const Entity &other) const { return this->id > other.id; };
  45. bool operator<(const Entity &other) const { return this->id < other.id; };
  46. };
  47. class System
  48. {
  49. private:
  50. Signature componentSignature;
  51. std::vector<Entity> entities;
  52. public:
  53. System() = default;
  54. ~System() = default;
  55. void addEntity(Entity entity);
  56. void removeEntity(Entity entity);
  57. std::vector<Entity> getEntities() const;
  58. const Signature& getComponentSignature() const;
  59. template<typename T> void requireComponent();
  60. };
  61. template<typename T> void System::requireComponent()
  62. {
  63. const auto componentId = Component<T>::getId();
  64. this->componentSignature.set(componentId);
  65. }
  66. class Registry
  67. {
  68. private:
  69. uint32_t numEntities = 0;
  70. std::vector<IPool*> componentPools;
  71. std::vector<Signature> entityComponentSignatures;
  72. std::unordered_map<std::type_index, System*> systems;
  73. public:
  74. Registry() = default;
  75. ~Registry() = default;
  76. };
  77. #endif /* GAMEENGINE_ECS_H */