ECS.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * 2D Game Engine
  3. * ECS.cpp:
  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. #include <Logger.h>
  10. #include <algorithm>
  11. #include <ECS.h>
  12. /* Entity */
  13. uint32_t IComponent::nextId = 0;
  14. /* TODO: this should be moved to the header file for optimisation purposes */
  15. uint32_t Entity::getId() const
  16. {
  17. return this->id;
  18. }
  19. /* System */
  20. void System::addEntity(Entity entity)
  21. {
  22. this->entities.push_back(entity);
  23. }
  24. void System::removeEntity(Entity entity)
  25. {
  26. this->entities.erase(std::remove_if(this->entities.begin(), this->entities.end(), [&entity](Entity other)
  27. {
  28. return other.getId() == entity.getId();
  29. }), this->entities.end());
  30. }
  31. std::vector<Entity> System::getSystemEntities() const
  32. {
  33. return this->entities;
  34. }
  35. const Signature& System::getComponentSignature() const
  36. {
  37. return this->componentSignature;
  38. }
  39. Entity Registry::createEntity()
  40. {
  41. uint32_t entityId = this->numEntities++;
  42. Entity entity(entityId);
  43. entity.registry = this;
  44. this->entitiesToBeAdded.insert(entity);
  45. if (entityId >= this->entityComponentSignatures.size())
  46. {
  47. this->entityComponentSignatures.resize(entityId + 1);
  48. }
  49. Logger::Info("Entity created with id = %d", entityId);
  50. return entity;
  51. }
  52. void Registry::addEntityToSystems(Entity entity)
  53. {
  54. const auto entityId = entity.getId();
  55. const auto entityComponentSignature = this->entityComponentSignatures[entityId];
  56. for(auto &system: this->systems)
  57. {
  58. const auto systemComponentSignature = system.second->getComponentSignature();
  59. bool isInterested = (entityComponentSignature & systemComponentSignature) == systemComponentSignature;
  60. if (isInterested)
  61. {
  62. system.second->addEntity(entity);
  63. }
  64. }
  65. }
  66. void Registry::update()
  67. {
  68. /* Add pending entities */
  69. for(auto entity: entitiesToBeAdded)
  70. {
  71. this->addEntityToSystems(entity);
  72. }
  73. entitiesToBeAdded.clear();
  74. }