Skip to content

Instantly share code, notes, and snippets.

@meshula
Created July 20, 2014 20:53
Show Gist options
  • Save meshula/a60215d9bbb6b3299d77 to your computer and use it in GitHub Desktop.
Save meshula/a60215d9bbb6b3299d77 to your computer and use it in GitHub Desktop.
Entity System sketch
#include <unordered_map>
using namespace std;
// EntityIds are globally unique and do not get recycled.
typedef int EntityId;
const EntityId null_entity = 0;
class EntitySubSystem {
public:
virtual ~EntitySubSystem() {}
private:
friend class EntitySystem;
virtual void clear() = 0;
virtual void push_back() = 0;
virtual void pop_back() = 0;
virtual void swap(int a, int b) = 0;
virtual void clear();
};
class EntitySystem {
public:
EntitySystem() : nextEntity(1), nextIndex(0) {}
~EntitySystem() {
for (auto s : _subsystems)
s->clear();
}
const EntityId allocEntity() {
EntityId ret = nextEntity++;
_entityIndex[ret] = nextIndex;
_entityDeindex[nextIndex++] = ret;
for (auto s : _subsystems)
s->push_back();
return ret;
}
void deallocEntity(const EntityId id) {
int swap = nextIndex - 1;
EntityId swapId = _entityDeindex[swap];
int deallocIndex = _entityIndex[id];
for (auto s : _subsystems)
s->swap(swap, deallocIndex);
for (auto s : _subsystems)
s->pop_back();
}
void registerSubSystem(std::shared_ptr<EntitySubSystem> ss) {
_subsystems.push_back(ss);
for (int i = 0; i < nextIndex; ++i)
ss->push_back();
}
void deregisterSubSystem(std::shared_ptr<EntitySubSystem> ss) {
for (auto s : _subsystems)
if (s == ss) {
ss->clear();
break;
}
}
private:
int nextIndex;
EntityId nextEntity;
std::vector<std::shared_ptr<EntitySubSystem>> _subsystems;
std::unordered_map<EntityId, int> _entityIndex;
std::unordered_map<int, EntityId> _entityDeindex;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment