Created
June 2, 2021 04:41
-
-
Save nikki93/61bee6d07ab0411c472443528a94b305 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Entities | |
// | |
using Entity = entt::entity; | |
inline constexpr auto nullEntity = entt::null; | |
// The global entity registry | |
inline entt::registry registry; | |
// Create a new entity | |
Entity createEntity() { | |
return registry.create(); | |
} | |
// Destroy an entity | |
inline std::vector<void (*)(Entity)> componentRemovers; | |
void destroyEntity(Entity ent) { | |
for (auto &remover : componentRemovers) { | |
remover(ent); | |
} | |
registry.destroy(ent); | |
} | |
// Destroy all entities | |
void clearEntities() { | |
registry.each(destroyEntity); | |
} | |
// | |
// Components | |
// | |
// Component pools | |
template<typename T> | |
void remove(Entity ent); | |
template<typename T> | |
inline auto componentPool = []() { | |
componentRemovers.emplace_back(remove<T>); | |
return entt::storage<T>(); | |
}(); | |
// Check whether entity has a component | |
template<typename T> | |
bool has(Entity ent) { | |
return componentPool<T>.contains(ent); | |
} | |
// Get a component on an entity | |
template<typename T> | |
decltype(auto) get(Entity ent) { | |
return componentPool<T>.get(ent); | |
} | |
// Add a component to an entity | |
template<typename T> | |
decltype(auto) add(Entity ent) { | |
if (has<T>(ent)) { | |
return get<T>(ent); | |
} else { | |
return componentPool<T>.emplace(ent); | |
} | |
} | |
// Remove a component from an entity | |
template<typename T> | |
void remove(Entity ent) { | |
if (has<T>(ent)) { | |
if constexpr (requires { remove(ent, *((T *)nullptr)); }) { | |
remove(ent, get<T>(ent)); | |
} | |
componentPool<T>.remove(ent); | |
} | |
} | |
// Query component combinations | |
template<typename T, typename... Ts, typename F> | |
void each(F &&f) { | |
for (auto ent : static_cast<entt::sparse_set &>(componentPool<T>)) { | |
if ((has<Ts>(ent) && ...)) { | |
f(ent, get<T>(ent), get<Ts>(ent)...); | |
} | |
} | |
} | |
// Sort component data | |
template<typename T, typename F> | |
void sort(F &&f) { | |
componentPool<T>.sort(std::forward<F>(f)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment