Skip to content

Instantly share code, notes, and snippets.

@seivan seivan/world.cpp
Created Sep 22, 2018

Embed
What would you like to do?
C++ ECS prototype
#include <map>
#include <memory>
#include <set>
#include <typeindex>
#include <vector>
// ────────────────────────────────────────────────────────────────────────────────
struct Position {};
struct Weapon {};
// ────────────────────────────────────────────────────────────────────────────────
struct StorageBase {
virtual ~StorageBase() {}
};
// ────────────────────────────────────────────────────────────────────────────────
using TypeVector = std::vector<const std::type_info*>;
using StorageVector = std::vector<StorageBase*>;
// ────────────────────────────────────────────────────────────────────────────────
template<typename T> struct Storage : StorageBase {
void storageFunc() {}
};
// ────────────────────────────────────────────────────────────────────────────────
struct SystemBase {
virtual ~SystemBase() {}
virtual TypeVector types() const = 0;
virtual void update(StorageVector) = 0;
};
// ────────────────────────────────────────────────────────────────────────────────
template<typename... T> struct System : SystemBase {
TypeVector types() const override { return {typeid(T)...}; }
template<std::size_t I>
std::tuple_element_t<I, std::tuple<T...>>*
castStorage(StorageVector storages) {
return static_cast<std::tuple_element_t<I, std::tuple<T...>>*>(storages[I]);
}
};
// ────────────────────────────────────────────────────────────────────────────────
struct MovementSystem : System<Storage<Position>> {
void update(StorageVector storages) override {
auto positions = castStorage<0>(storages);
}
};
// ────────────────────────────────────────────────────────────────────────────────
struct ShootingSystem : System<Storage<Position>, Storage<Weapon>> {
void update(StorageVector storages) override {
auto positions = castStorage<0>(storages);
auto weapons = castStorage<1>(storages);
}
};
// ────────────────────────────────────────────────────────────────────────────────
struct World {
std::vector<std::unique_ptr<SystemBase>> systems;
std::map<std::type_index, std::unique_ptr<StorageBase>> storages;
void update() {
for(auto& system : systems) {
system->update(storagesForTypes(system->types()));
}
}
StorageVector storagesForTypes(TypeVector types) {
StorageVector o;
for(auto type : types) { o.push_back(storages[*type].get()); }
return o;
}
};
// ────────────────────────────────────────────────────────────────────────────────
int main() {
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.