engine/include/ecs_system.hpp

67 lines
1.4 KiB
C++
Raw Normal View History

2023-04-29 14:22:25 +00:00
#ifndef ENGINE_INCLUDE_ECS_SYSTEM_H_
#define ENGINE_INCLUDE_ECS_SYSTEM_H_
2023-01-02 17:24:20 +00:00
#include <bitset>
2023-04-29 14:22:25 +00:00
#include <cassert>
#include <cstddef>
2023-01-02 17:24:20 +00:00
#include <cstdint>
2023-04-29 14:22:25 +00:00
#include <map>
#include <set>
2023-04-24 10:53:43 +00:00
2023-01-02 17:24:20 +00:00
namespace engine {
2023-04-29 14:22:25 +00:00
class Scene;
constexpr size_t kMaxComponents = 64;
class IComponentArray {
2023-04-29 14:56:49 +00:00
public:
2023-04-29 14:22:25 +00:00
virtual ~IComponentArray() = default;
};
2023-01-02 17:24:20 +00:00
2023-04-29 14:56:49 +00:00
template <typename T>
2023-04-29 14:22:25 +00:00
class ComponentArray : public IComponentArray {
2023-04-29 14:56:49 +00:00
public:
void InsertData(uint32_t entity, T component) {
2023-04-29 14:22:25 +00:00
assert(component_array_.find(entity) == component_array_.end() &&
2023-04-29 14:56:49 +00:00
"Adding component which already exists to entity");
2023-04-29 14:22:25 +00:00
component_array_.emplace(entity, component);
}
2023-01-02 17:24:20 +00:00
2023-04-29 14:56:49 +00:00
void DeleteData(uint32_t entity) { component_array_.erase(entity); }
T* GetData(uint32_t entity) {
2023-04-29 14:22:25 +00:00
if (component_array_.contains(entity)) {
return &(component_array_.at(entity));
} else {
return nullptr;
}
}
2023-01-02 17:24:20 +00:00
2023-04-29 14:56:49 +00:00
private:
2023-04-29 14:22:25 +00:00
std::map<uint32_t, T> component_array_{};
};
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
class System {
2023-04-29 14:56:49 +00:00
public:
2023-04-29 14:22:25 +00:00
System(Scene* scene, std::set<size_t> required_component_hashes);
virtual ~System() {}
System(const System&) = delete;
System& operator=(const System&) = delete;
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
virtual void OnUpdate(float ts) = 0;
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
virtual void OnComponentInsert(uint32_t) {}
virtual void OnComponentRemove(uint32_t) {}
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
Scene* const scene_;
2023-02-02 17:32:19 +00:00
2023-04-29 14:22:25 +00:00
std::bitset<kMaxComponents> signature_;
2023-04-29 14:56:49 +00:00
2023-04-29 14:22:25 +00:00
// entities that contain the needed components
std::set<uint32_t> entities_{};
};
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
} // namespace engine
2023-01-02 17:24:20 +00:00
2023-04-29 14:22:25 +00:00
#endif