96 lines
2.0 KiB
C++
96 lines
2.0 KiB
C++
#include "ecs.h"
|
|
|
|
#include <iostream>
|
|
|
|
namespace ecs {
|
|
size_t ComponentID::_id;
|
|
// This needs to be a function because otherwise it might not be initialized on time
|
|
std::unordered_map<std::string, size_t>& ComponentID::_ids() {
|
|
static std::unordered_map<std::string, size_t> ids;
|
|
return ids;
|
|
};
|
|
|
|
std::vector<size_t> ComponentID::get_id(std::vector<std::string> names) {
|
|
std::vector<size_t> ids;
|
|
|
|
for (const auto& name : names) {
|
|
auto it = _ids().find(name);
|
|
if (it != _ids().end()) {
|
|
ids.push_back(it->second);
|
|
} else {
|
|
size_t id = _id++;
|
|
_ids()[name] = id;
|
|
ids.push_back(id);
|
|
}
|
|
}
|
|
|
|
return ids;
|
|
}
|
|
|
|
Entity::~Entity() {
|
|
// @todo This does not work...
|
|
for (auto component : _components) {
|
|
delete component.second;
|
|
component.second = nullptr;
|
|
}
|
|
_components.clear();
|
|
}
|
|
|
|
void Entity::add_component(size_t id, Component* component) {
|
|
if (_components.find(id) != _components.end()) {
|
|
throw std::runtime_error("Component already exists");
|
|
}
|
|
|
|
_components[id] = component;
|
|
}
|
|
|
|
bool Entity::has_components(std::vector<size_t> ids) {
|
|
for (const auto& id : ids) {
|
|
if (_components.find(id) == _components.end()) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
Component* Entity::get_component(size_t id) {
|
|
auto it = _components.find(id);
|
|
if (it == _components.end()) {
|
|
throw std::runtime_error("Component does not exist");
|
|
}
|
|
|
|
return it->second;
|
|
}
|
|
|
|
Manager::~Manager() {
|
|
for (auto entity : _entities) {
|
|
delete entity.second;
|
|
entity.second = nullptr;
|
|
}
|
|
_entities.clear();
|
|
}
|
|
|
|
Entity* Manager::create_entity() {
|
|
uuids::uuid uuid = uuids::uuid_system_generator{}();
|
|
|
|
return create_entity(uuid);
|
|
}
|
|
|
|
void Manager::remove_entity(ecs::Entity* entity) {
|
|
auto it = _entities.find(entity->uuid);
|
|
if (it == _entities.end()) {
|
|
throw std::runtime_error("Entity with uuid does not exists");
|
|
}
|
|
|
|
delete it->second;
|
|
_entities.erase(it);
|
|
}
|
|
|
|
Entity* Manager::create_entity(uuids::uuid uuid) {
|
|
Entity* entity = new Entity(uuid);
|
|
_entities.insert({uuid, entity});
|
|
return entity;
|
|
}
|
|
}
|