#pragma once
#include
#include <unordered_map>
#include <unordered_set>
#include
#include
#include
#include "System.h"
#include "Archetype.h"
#include "ComponentMask.h"
typedef std::vector ArchetypeId;
class ECS
{
private:
typedef std::unordered_map<std::uint8_t, std::vector<SystemBase*>>
SystemsArrayMap;
typedef std::unordered_map<std::size_t, ComponentBase*>
ComponentTypeIdBaseMap;
struct Record
{
Archetype* archetype;
std::size_t index;
};
typedef std::unordered_map<std::size_t, Record> EntityArchetypeMap;
typedef std::vector<Archetype*> ArchetypesArray;
typedef std::unordered_map<std::size_t, ComponentMask> ComponentMasks;
public:
explicit ECS();
~ECS();
void Update(const std::uint8_t layer, const std::uint32_t delta);
void RegisterEntity(const uint32_t entityId);
void DestroyEntity(const std::uint32_t entityId);
template <class C>
void RegisterComponent();
template <class C>
bool IsComponentRegistered();
template<class C, typename... Args>
C* AddComponent(const uint32_t entityId, Args&&... args);
template<class C>
void RemoveComponent(const uint32_t entityId);
template<class C>
C* GetComponent(const uint32_t entityId);
template<class C>
bool HasComponent(const uint32_t entityId);
void RegisterSystem(const std::uint8_t& layer, SystemBase* system);
void UnregisterSystem(const std::uint8_t& layer, SystemBase* system);
template<class... Cs>
std::vector<uint32_t> GetEntitiesWithComponents();
Archetype* GetArchetype(const ComponentMask& compMask);
std::uint32_t GetNewId();
private:
std::uint32_t entityIdCounter;
SystemsArrayMap systems;
EntityArchetypeMap entityArchetypeMap;
ArchetypesArray archetypes;
ComponentMasks componentMasks;
ComponentTypeIdBaseMap componentMap;
void Reallocate(const ComponentBase* compbase, const size_t& newCompSize, Archetype* arch, size_t index);
void TransferComponentData(const ComponentBase* compbase, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex);
void SwapComponentData(const ComponentBase* compbase, Archetype* arch, size_t i, size_t entityIndex);
void RemoveAndAllocateComponentData(const ComponentBase* compbase, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex);
};
template
void ECS::RegisterComponent()
{
size_t componentTypeId = Component::GetTypeID();
if (componentMap.contains(componentTypeId))
return; // can't re-register a type
componentMap.emplace(componentTypeId, new Component<C>);
};
template
bool ECS::IsComponentRegistered() {
size_t componentTypeId = Component::GetTypeID();
return (componentMap.contains(componentTypeId));
}
template<class C, typename... Args>
C* ECS::AddComponent(const uint32_t entityId, Args&&... args) {
auto newComponentID = Component::GetTypeID();
if (componentMasks[entityId].HasComponent(newComponentID)) {
return nullptr; // Component already exists for the entity
}
componentMasks[entityId].AddComponent(newComponentID);
Archetype* newArchetype = nullptr;
C* newComponent = nullptr;
Record& record = entityArchetypeMap[entityId];
Archetype* oldArchetype = record.archetype;
auto& newComponentMask = componentMasks[entityId];
newArchetype = GetArchetype(componentMasks[entityId]);
// if the entity already has components
if (oldArchetype) {
auto oldComponentMask = oldArchetype->componentMask;
std::size_t entityIndex = std::find(
oldArchetype->entityIds.begin(),
oldArchetype->entityIds.end() - 1,
entityId
) - oldArchetype->entityIds.begin();
std::size_t index = 0;
std::size_t j = 0;
for (std::size_t i = 0; i < newComponentMask.GetBitsetMask().size() - 1; ++i) {
if (newComponentMask.GetBitsetMask().test(i)) {
const ComponentBase* const componentBase = componentMap[i];
const std::size_t newComponentDataSize = componentBase->GetSize();
std::size_t currentSize = newArchetype->entityIds.size() * newComponentDataSize;
std::size_t newSize = currentSize + newComponentDataSize;
if (newSize > newArchetype->componentDataSize[index]) {
Reallocate(componentBase, newComponentDataSize, newArchetype, index);
}
if (oldComponentMask.HasComponent(i)) {
TransferComponentData(componentBase, oldArchetype, newArchetype, index, j, entityIndex);
++j;
}
else {
/*newComponent = */ new (&newArchetype->componentData[index][currentSize]) C(std::forward<Args>(args)...);
}
index++;
}
}
auto lastEntity = oldArchetype->entityIds.size() - 1;
// If the old archetype still has entities in
if (!oldArchetype->entityIds.empty() && entityIndex < oldArchetype->entityIds.size()) {
std::iter_swap(oldArchetype->entityIds.begin() + entityIndex, oldArchetype->entityIds.begin() + lastEntity);
for (std::size_t i = 0, j = 0, index = 0; i < oldComponentMask.GetBitsetMask().size() - 1; ++i) {
if (oldComponentMask.GetBitsetMask().test(i)) {
const ComponentBase* const componentBase = componentMap[i];
SwapComponentData(componentBase, oldArchetype, index, entityIndex);
++index;
}
}
// swap the entity leaving the archetype with the one at the end of the list before deleting the leaving entity by popping
oldArchetype->entityIds.pop_back();
}
}
// If this is the first time we're adding a component to this entity
else
{
// Get size of the new component
const ComponentBase* const newComponentBase = componentMap[newComponentID];
const std::size_t& newComponentDataSize = newComponentBase->GetSize();
std::size_t currentSize = newArchetype->entityIds.size() * newComponentDataSize;
std::size_t newSize = currentSize + newComponentDataSize;
//Reallocate(newComponentBase, newArchetype, 0);
if (newSize > newArchetype->componentDataSize[0]) {
Reallocate(newComponentBase, newComponentDataSize, newArchetype, 0);
}
newComponent = new (&newArchetype->componentData[0][currentSize]) C(std::forward<Args>(args)...);
}
newArchetype->entityIds.push_back(entityId);
record.index = newArchetype->entityIds.size() - 1;
record.archetype = newArchetype;
return newComponent;
}
template
void ECS::RemoveComponent(const uint32_t entityId) {
auto newComponentID = Component::GetTypeID();
if (!IsComponentRegistered<C>()) { return; };
if (!componentMasks[entityId].HasComponent(newComponentID)) { return; };
componentMasks[entityId].RemoveComponent(newComponentID);
Record& record = entityArchetypeMap[entityId];
auto oldArchetype = record.archetype;
if (!oldArchetype) { return; };
auto oldComponentMask = oldArchetype->componentMask;
auto newArchetype = GetArchetype(componentMasks[entityId]);
auto newComponentMask = newArchetype->componentMask;
auto lastEntity = oldArchetype->entityIds.size() - 1;
auto entityIndex = std::find(
oldArchetype->entityIds.begin(),
oldArchetype->entityIds.end() - 1,
entityId
) - oldArchetype->entityIds.begin();
std::size_t index = 0;
std::size_t j = 0;
for (std::size_t i = 0; i < newComponentMask.GetBitsetMask().size(); ++i) {
//for (std::size_t i = oldComponentMask.GetBitsetMask().size() - 1, j = i - 1; j >= 0; --j) {
if (newComponentMask.GetBitsetMask().test(i)) {
const ComponentBase* const componentBase = componentMap[i];
const std::size_t newComponentDataSize = componentBase->GetSize();
std::size_t currentSize = newArchetype->entityIds.size() * newComponentDataSize;
std::size_t newSize = currentSize + newComponentDataSize;
if (newSize > newArchetype->componentDataSize[index]) {
Reallocate(componentBase, newComponentDataSize, newArchetype, index);
}
if (oldComponentMask.HasComponent(i)) {
RemoveAndAllocateComponentData(componentBase, oldArchetype, newArchetype, index, j, entityIndex);
j++;
}
else {
componentBase->MoveData(&oldArchetype->componentData[j][lastEntity * newComponentDataSize],
&oldArchetype->componentData[j][entityIndex * newComponentDataSize]);
ComponentBase* removeWrapper = componentMap[i];
removeWrapper->DestroyData(
&oldArchetype->componentData[j][record.index * sizeof(C)]);
}
index++;
}
}
//std::swap(oldArchetype->entityIds[entityIndex], oldArchetype->entityIds[lastEntity]);
std::iter_swap(oldArchetype->entityIds.begin() + entityIndex, oldArchetype->entityIds.begin() + lastEntity);
oldArchetype->entityIds.pop_back();
newArchetype->entityIds.push_back(entityId);
record.index = newArchetype->entityIds.size() - 1;
record.archetype = newArchetype;
}
template
C* ECS::GetComponent(const uint32_t entityId) {
std::size_t componentTypeId = Component::GetTypeID();
if (!componentMasks[entityId].HasComponent(componentTypeId)) {
return nullptr; // Component doesn't exist for the entity
}
const Archetype* archetype = entityArchetypeMap[entityId].archetype;
if (!archetype) {
return nullptr; // Archetype doesn't exist for the entity
}
std::size_t componentIndex = archetype->componentMask.ReturnArchetypeIndex(componentTypeId);
auto entityIterator = std::find(
archetype->entityIds.begin(),
archetype->entityIds.end(),
entityId
);
if (entityIterator == archetype->entityIds.end()) {
return nullptr; // Entity not found in the archetype
}
std::size_t entityIndex = entityIterator - archetype->entityIds.begin();
std::size_t componentSize = componentMap[componentTypeId]->GetSize();
C* component = reinterpret_cast<C*>(&archetype->componentData[componentIndex][entityIndex * componentSize]);
return component;
}
template
bool ECS::HasComponent(const uint32_t entityId) {
return (componentMasks[entityId]).HasComponent(Component::GetTypeID());
}
template<class... Cs>
std::vector<uint32_t> ECS::GetEntitiesWithComponents()
{
std::vector<uint32_t> entities;
std::vectorstd::size_t componentTypeIds;
componentTypeIds.reserve(sizeof...(Cs));
// Collect the type IDs of the desired components
((componentTypeIds.push_back(Component<Cs>::GetTypeID())), ...);
for (const auto& [entityId, record] : entityArchetypeMap)
{
const Archetype* archetype = record.archetype;
if (!archetype)
continue;
const ComponentMask& mask = componentMasks[entityId];
bool hasAllComponents = true;
for (std::size_t typeId : componentTypeIds)
{
if (!mask.HasComponent(typeId))
{
hasAllComponents = false;
break;
}
}
if (hasAllComponents)
entities.push_back(entityId);
}
return entities;
}
Imrpove this code?