/* * 2D Game Engine * ECS.cpp: * Based on pikuma.com 2D game engine in C++ and Lua course * Copyright (c) 2021 986-Studio. All rights reserved. * * Created by Manoƫl Trapier on 11/02/2021. */ #include #include #include /* Entity */ uint32_t IComponent::nextId = 0; /* TODO: this should be moved to the header file for optimisation purposes */ uint32_t Entity::getId() const { return this->id; } void Entity::kill() { this->registry->killEntity(*this); } /* System */ void System::addEntity(Entity entity) { this->entities.push_back(entity); } void System::removeEntity(Entity entity) { this->entities.erase(std::remove_if(this->entities.begin(), this->entities.end(), [&entity](Entity other) { return other.getId() == entity.getId(); }), this->entities.end()); } std::vector System::getSystemEntities() const { return this->entities; } const Signature& System::getComponentSignature() const { return this->componentSignature; } Entity Registry::createEntity() { uint32_t entityId; if (this->freeIds.empty()) { entityId = this->numEntities++; } else { entityId = this->freeIds.front(); this->freeIds.pop_front(); } Entity entity(entityId); entity.registry = this; this->entitiesToBeAdded.insert(entity); if (entityId >= this->entityComponentSignatures.size()) { this->entityComponentSignatures.resize(entityId + 1); } Logger::Info("Entity created with id = %d", entityId); return entity; } void Registry::killEntity(Entity entity) { Logger::Info("Entity #%d flagged for killing", entity.getId()); this->entitiesToBeKilled.insert(entity); } void Registry::addEntityToSystems(Entity entity) { const auto entityId = entity.getId(); const auto entityComponentSignature = this->entityComponentSignatures[entityId]; for(auto &system: this->systems) { const auto systemComponentSignature = system.second->getComponentSignature(); bool isInterested = (entityComponentSignature & systemComponentSignature) == systemComponentSignature; if (isInterested) { system.second->addEntity(entity); } } } void Registry::removeEntityFromSystems(Entity entity) { for (auto &system: this->systems) { system.second->removeEntity(entity); } } void Registry::update() { /* Add pending entities */ for(auto entity: this->entitiesToBeAdded) { this->addEntityToSystems(entity); } this->entitiesToBeAdded.clear(); for(auto entity: this->entitiesToBeKilled) { this->removeEntityFromSystems(entity); this->entityComponentSignatures[entity.getId()].reset(); this->freeIds.push_back(entity.getId()); } this->entitiesToBeKilled.clear(); }