ECS.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 <ECS.h>
  11. /* Entity */
  12. uint32_t IComponent::nextId = 0;
  13. /* TODO: this should be moved to the header file for optimisation purposes */
  14. uint32_t Entity::getId() const
  15. {
  16. return this->id;
  17. }
  18. /* System */
  19. void System::addEntity(Entity entity)
  20. {
  21. this->entities.push_back(entity);
  22. }
  23. void System::removeEntity(Entity entity)
  24. {
  25. this->entities.erase(std::remove_if(this->entities.begin(), this->entities.end(), [&entity](Entity other)
  26. {
  27. return other.getId() == entity.getId();
  28. }), this->entities.end());
  29. }
  30. std::vector<Entity> System::getEntities() const
  31. {
  32. return this->entities;
  33. }
  34. const Signature& System::getComponentSignature() const
  35. {
  36. return this->componentSignature;
  37. }
  38. Entity Registry::CreateEntity()
  39. {
  40. uint32_t entityId = this->numEntities++;
  41. Entity entity(entityId);
  42. this->entitiesToBeAdded.insert(entity);
  43. Logger::Info("Entity created with id = %s", entityId);
  44. return entity;
  45. }
  46. void Registry::addEntityToSystem(Entity entity)
  47. {
  48. const auto entityId = entity.getId();
  49. const auto entityComponentSignature = this->entityComponentSignatures[entityId];
  50. for(auto &system: this->systems)
  51. {
  52. const auto systemComponentSignature = system.second->getComponentSignature();
  53. bool isInterested = (entityComponentSignature & systemComponentSignature) == systemComponentSignature;
  54. if (isInterested)
  55. {
  56. system.second->addEntity(entity);
  57. }
  58. }
  59. }
  60. void Registry::Update()
  61. {
  62. }