Made ECS use dualkey map over nested maps

still need to implement a has check
This commit is contained in:
2026-01-28 13:33:47 +02:00
parent 63b6d705a9
commit 3840276f1a
2 changed files with 40 additions and 117 deletions

View File

@@ -6,15 +6,16 @@
* v. 2.0. If a copy of the MPL was not distributed with this file, You can * v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. * obtain one at http://mozilla.org/MPL/2.0/.
*/ */
#ifndef GUARD_TOURMALINE_ECS_H #ifndef GUARD_TOURMALINE_ECS_H
#define GUARD_TOURMALINE_ECS_H #define GUARD_TOURMALINE_ECS_H
#include <any> #include <any>
#include <concepts> #include <concepts>
#include <format> #include <format>
#include <typeindex> #include <typeindex>
#include <unordered_map>
#include <utility> #include <utility>
#include "../Containers/DualkeyMap.hpp"
#include "../Types.hpp" #include "../Types.hpp"
#include "Logging.hpp" #include "Logging.hpp"
@@ -42,105 +43,48 @@ public:
Entity CreateEntity(); Entity CreateEntity();
bool EntityExists(const Entity &entity) noexcept; bool EntityExists(const Entity &entity) noexcept;
[[nodiscard("It is not guaranteed that an entity can always be destroyed, " [[nodiscard("It is not guaranteed that an entity can always be destroyed, "
"please make " "please make sure by checking the returned bool")]]
"sure by checking the returned bool")]]
bool DestroyEntity(Entity entity); bool DestroyEntity(Entity entity);
// Components // Components
template <Component T, typename... Args> template <Component component, typename... Args>
T &AddComponent(const Entity &entity, Args &&...constructionArguments) { component &AddComponent(const Entity &entity,
auto entityIter = GetEntityIterator( Args &&...constructionArguments) {
entity, auto newComponent = entityComponentMap.insert(
std::format( entity, typeid(component), component(constructionArguments...));
"Cannot add component \"{}\"! Entity \"{}\" does not exist!",
typeid(T).name(), entity.asString()),
"AddComponent", Systems::Logging::LogLevel::Error);
auto [componentIter, success] = entityIter->second.try_emplace( return std::any_cast<component &>(std::get<2>(newComponent));
typeid(T), T(std::forward<Args>(constructionArguments)...));
Systems::Logging::Log(
std::format("Cannot add component! Component \"{}\" already exists "
"in entity \"{}\" ",
typeid(T).name(), entity.asString()),
"AddComponent", Systems::Logging::LogLevel::Error, !success);
T &component = std::any_cast<T &>(componentIter->second);
component.owner = &entity;
return component;
} }
template <Component T> template <Component component>
[[nodiscard("Discarding an expensive operation's result!")]] [[nodiscard("Discarding an expensive operation's result!")]]
T &GetComponent(const Entity &entity) { component &GetComponent(const Entity &entity) {
auto iter = GetEntityIterator( auto result = entityComponentMap.query(entity, typeid(component));
entity, if (result.empty()) {
std::format("Can't get entity \"{}\"'s component \"{}\", since " Logging::Log(std::format("Entity {} does not have component {}!",
"entity does not exist!", entity.asString(), typeid(component).name()),
entity.asString(), typeid(T).name()), "ECS/GetComponent", Logging::LogLevel::Error);
"GetComponent", Systems::Logging::LogLevel::Error); }
return std::any_cast<component &>(result.begin()->second);
auto component = iter->second.find(typeid(T));
Systems::Logging::Log(
std::format(
"Entity \"{}\" does not have component \"{}\", cannot get it!",
entity.asString(), typeid(T).name()),
"GetComponent", Systems::Logging::LogLevel::Error,
component == iter->second.end());
return std::any_cast<T &>(component->second);
} }
template <Component T> template <Component component>
[[nodiscard("Discarding an expensive operation's result!")]] [[nodiscard("Discarding an expensive operation's result!")]]
bool HasComponent(const Entity &entity) { bool HasComponent(const Entity &entity) {
auto iter = GetEntityIterator( // TO BE IMPLEMENTED
entity,
std::format("Can't find if entity \"{}\" has component \"{}\", since "
"entity does not exist!",
entity.asString(), typeid(T).name()));
return iter != entityComponentList.end() &&
(iter->second.find(typeid(T)) != iter->second.end());
}
template <Component T>
[[nodiscard("It is not guaranteed that a component can always be removed, "
"please make "
"sure by checking the returned bool")]]
bool RemoveComponent(const Entity &entity) {
auto entityIter = GetEntityIterator(
entity,
std::format("Cannot remove component {} from entity {}, since entity "
"does not exist!",
typeid(T).name(), entity.asString()),
"RemoveComponent", Systems::Logging::LogLevel::Warning);
if (entityIter == entityComponentList.end()) {
return false;
}
auto componentIter = entityIter->second.find(typeid(T));
if (componentIter == entityIter->second.end()) {
Systems::Logging::Log(
std::format("Cannot remove component {} from entity {}, since entity "
"does not have that component",
typeid(T).name(), entity.asString()),
"RemoveComponent", Systems::Logging::LogLevel::Warning);
return false;
}
entityIter->second.erase(componentIter);
return true; return true;
} }
private: template <Component component>
std::unordered_map<Entity, std::unordered_map<std::type_index, std::any>> [[nodiscard("It is not guaranteed that a component can always be removed, "
entityComponentList{}; "please make sure by checking the returned bool")]]
bool RemoveComponent(const Entity &entity) {
return entityComponentMap.remove(entity, typeid(component));
}
decltype(entityComponentList)::iterator private:
GetEntityIterator(const Entity &entity, const std::string &errorMessage = "", Tourmaline::Containers::DualkeyMap<Entity, std::type_index, std::any>
const std::string &position = "", entityComponentMap{};
Tourmaline::Systems::Logging::LogLevel severity =
Systems::Logging::LogLevel::Warning);
}; };
} // namespace Tourmaline::Systems::ECS } // namespace Tourmaline::Systems::ECS
#endif #endif

View File

@@ -8,48 +8,27 @@
*/ */
#include <Systems/ECS.hpp> #include <Systems/ECS.hpp>
#include <Systems/ECS/BuiltinComponents.hpp>
#include <Systems/Random.hpp> #include <Systems/Random.hpp>
#include <optional>
using namespace Tourmaline::Systems::ECS; using namespace Tourmaline::Systems::ECS;
// It is preferable to send a copy of the UUID instead of reference since
// the entity itself may be destroyed in the memory
Entity World::CreateEntity() { Entity World::CreateEntity() {
auto [iterator, success] = auto newEntity = entityComponentMap.insert(
entityComponentList.try_emplace(Systems::Random::GenerateUUID()); Random::GenerateUUID(), typeid(Tourmaline::Systems::Components::Position),
Tourmaline::Systems::Components::Position());
Systems::Logging::Log("Failed to create an entity! Possibly by incredible " return Entity(std::get<0>(newEntity));
"luck generated already existing UUID?",
"CreateEntity", Systems::Logging::LogLevel::Critical,
!success);
return iterator->first;
} }
bool World::EntityExists(const Entity &entity) noexcept { bool World::EntityExists(const Entity &entity) noexcept {
return entityComponentList.find(entity) != entityComponentList.end(); // TO BE IMPLEMENTED
}
bool World::DestroyEntity(Entity entity) {
auto entityIter = GetEntityIterator(
entity,
std::format("Cannot delete entity \"{}\", it does not exist!",
entity.asString()),
"DestroyEntity");
if (entityIter == entityComponentList.end()) {
return false;
}
entityComponentList.erase(entityIter);
return true; return true;
} }
// Very repetitive code bool World::DestroyEntity(Entity entity) {
decltype(World::entityComponentList)::iterator return entityComponentMap.remove(entity, std::nullopt);
World::GetEntityIterator(const Entity &entity, const std::string &errorMessage,
const std::string &position,
Tourmaline::Systems::Logging::LogLevel severity) {
auto iter = entityComponentList.find(entity);
Systems::Logging::Log(errorMessage, "GetEntityIterator/" + position, severity,
iter == entityComponentList.end());
return iter;
} }