Create a dynamic scene loader function that loads/creates entities and objects using…
- User
Create a dynamic scene loader function that loads/creates entities and objects using rapidjson. It will create each entity and add the corresponding components by calling template<class C, typename... Args> C* ECS::AddComponent(const EntityId entityId, Args&&... args).
- Assistant
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <unordered_map> #include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include "ECS.h" using namespace rapidjson; using ComponentLoaderFunction = std::function<void(EntityId, const Value&)>; static std::unordered_map<std::string, ComponentLoaderFunction> componentLoaders; void LoadScene(const std::string& filePath) { FILE* fp = std::fopen(filePath.c_str(), "r"); if (!fp) { std::cerr << "Error opening scene file: " << filePath << std::endl; return; } char readBuffer[65536]; FileReadStream inputStream(fp, readBuffer, sizeof(readBuffer)); Document document; document.ParseStream<0, UTF8<>, FileReadStream>(inputStream); std::fclose(fp); if (document.HasParseError()) { std::cerr << "Error parsing JSON from scene file: " << filePath << std::endl; return; } if (document.HasMember("entities") && document["entities"].IsArray()) { const Value& entities = document["entities"]; for (SizeType i = 0; i < entities.Size(); i++) { const Value& entityData = entities[i]; EntityId entityId = ECS::CreateEntity(); for (const auto& component : componentLoaders) { const char* componentName = component.first.c_str(); if (entityData.HasMember(componentName)) { component.second(entityId, entityData[componentName]); } } } } }You will need some example component loaders like this:
void LoadTransformComponent(EntityId entityId, const Value& component) { float x = component["x"].GetFloat(); float y = component["y"].GetFloat(); float z = component["z"].GetFloat(); ECS::AddComponent<TransformComponent>(entityId, x, y, z); } void LoadMeshComponent(EntityId entityId, const Value& component) { std::string meshPath = component["path"].GetString(); ECS::AddComponent<MeshComponent>(entityId, meshPath); }And register them in your main function:
int main() { componentLoaders["transform"] = LoadTransformComponent; componentLoaders["mesh"] = LoadMeshComponent; LoadScene("path/to/scene_file.json"); return 0; }This code snippet assumes that you have implemented the
ECS::AddComponentandECS::CreateEntityfunctions and their associated classes. The code also assumes that the JSON scene file contains an array of entities with their components represented as key-value pairs. - User
Here's the Implementation of my ecs #pragma once #include #include #include
#include "TypeIdGenerator.h"
class ComponentBase { public: virtual ~ComponentBase() {} virtual void DestroyData(unsigned char* data) const = 0; virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0; virtual void ConstructData(unsigned char* data) const = 0; virtual std::size_t GetSize() const = 0; };
template class Component : public ComponentBase { public: virtual void DestroyData(unsigned char* data) const override;
virtual void MoveData(unsigned char* source, unsigned char* destination) const override; virtual void ConstructData(unsigned char* data) const override; virtual size_t GetSize() const override; static size_t GetTypeID();};
template void Component::DestroyData(unsigned char* data) const { C* dataLocation = std::launder(reinterpret_cast<C*>(data));
dataLocation->~C();}
template void Component::ConstructData(unsigned char* data) const { new (&data[0]) C(); }
template void Component::MoveData(unsigned char* source, unsigned char* destination) const { new (&destination[0]) C(std::move(std::bit_cast<C>(source))); }
template std::size_t Component::GetSize() const { return sizeof(C); }
template std::size_t Component::GetTypeID() { return TypeIdGenerator::template GetNewID(); }
template static const std::size_t GetTypeID() { return TypeIdGenerator::GetNewID(); }
struct Position { float x; float y; };
struct Name { std::string name; };
struct Size { int width; int height; };
struct Velocity { int vel; };class SystemBase; class ECS { private:
using SystemsArrayMap = std::unordered_map<std::uint8_t, std::vector<SystemBase*>>; using ComponentTypeIdBaseMap = std::unordered_map<size_t, ComponentBase*>; struct Record { Archetype* archetype; size_t index; }; using EntityArchetypeMap = std::unordered_map<size_t, Record>; using ArchetypesArray = std::vector<Archetype*>; using ComponentMasks = std::unordered_map<size_t, ComponentMask>;public: explicit ECS();
~ECS(); void Update(const std::uint8_t layer, const std::uint32_t delta); void RegisterEntity(const EntityId entityId); void DestroyEntity(const EntityId entityId); template <class C> void RegisterComponent(); template <class C> const bool IsComponentRegistered() const; template<class C, typename... Args> C* AddComponent(const EntityId entityId, Args&&... args); template<class C> void RemoveComponent(const EntityId entityId); template<class C> C* GetComponent(const EntityId entityId); const bool HasComponent(const EntityId entityId, size_t compTypeId) const; template<class C> size_t GetComponentTypeId(); template<class C> const bool HasComponent(const EntityId entityId); void RegisterSystem(const std::uint8_t& layer, SystemBase* system); void UnregisterSystem(const std::uint8_t& layer, SystemBase* system); template<class... Cs> std::vector<size_t> GetEntitiesWithComponents(); Archetype* GetArchetype(const ComponentMask& componentMask); EntityId GetNewId(); std::shared_ptr<EventBus> GetEventBus() { return eventBus_; } //ComponentBase* CreateComponentByName(const std::string& componentName) { // return componentRegistry_.CreateComponentByName(componentName); //} //std::shared_ptr<EventQueueManager> GetEventQueueManager() //{ // return eventQueueManager_; //}private: std::shared_ptr eventBus_;
//ComponentRegistry componentRegistry_; //std::shared_ptr<EventQueueManager> eventQueueManager_; EntityId entityIdCounter; SystemsArrayMap systems; ComponentTypeIdBaseMap componentMap; EntityArchetypeMap entityArchetypeMap; ArchetypesArray archetypes; ComponentMasks componentMasks; ComponentManager componentManager_; template<class C, typename... Args> C* TransferComponentsAndAdd(const EntityId entityId, Archetype* newArchetype, Archetype* oldArchetype, Args&... args); template<class C> void TransferComponentsAndRemove(size_t entityIndex, Archetype* oldArchetype, Archetype* newArchetype); size_t GetEntityIndex(const Archetype* archetype, EntityId entityId); void UpdateRecord(EntityId entityId, Archetype* archetype, Record& record); void UpdateEntitiesInArchetypes(Archetype* oldArchetype, Archetype* newArchetype, EntityId entityId);};
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 const bool ECS::IsComponentRegistered() const { size_t componentTypeId = Component::GetTypeID(); return (componentMap.contains(componentTypeId)); }
template<class C, typename... Args> C* ECS::AddComponent(const EntityId entityId, Args&&... args) { // 1. Get the component type ID and check if the component already exists for the entity auto newComponentID = GetTypeID();
if (HasComponent(entityId, newComponentID)) { return nullptr; } // 2. Update the component mask for the entity and get the new archetype componentMasks[entityId].AddComponent(newComponentID); Archetype* newArchetype = GetArchetype(componentMasks[entityId]); // 3. Get and store the record of the entity Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; C* newComponent = nullptr; // 4. If the entity has existing components, transfer or add the new component if (oldArchetype) { newComponent = TransferComponentsAndAdd<C>(entityId, newArchetype, oldArchetype, args...); } // 5. If the entity has no existing components, allocate and add the new component else { size_t currentSize = componentManager_.FindCurrentSize(newComponentID, newArchetype, 0); newComponent = new (&newArchetype->componentData[0][currentSize]) C(std::forward<Args>(args)...); } // 6. Update the record and return the new component UpdateRecord(entityId, newArchetype, record); return newComponent;}
template void ECS::RemoveComponent(const EntityId entityId) { auto componentID = GetTypeID();
if (!IsComponentRegistered<C>() || !HasComponent(entityId, componentID)) { return; } componentMasks[entityId].RemoveComponent(componentID); Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; if (!oldArchetype) { return; } Archetype* newArchetype = GetArchetype(componentMasks[entityId]); size_t entityIndex = GetEntityIndex(oldArchetype, entityId); TransferComponentsAndRemove<C>(entityIndex, oldArchetype, newArchetype); UpdateRecord(entityId, newArchetype, record);}class ECS; class Entity { public: explicit Entity(ECS& ecs);
EntityId GetId() const { return id_; } template<class C> C* AddComponent(C&& c); template<class C> C* AddComponent(C& c); template<class C> void RemoveComponent();private: EntityId id_; ECS& ecs_; };
template C* Entity::AddComponent(C&& c) { return ecs_.AddComponent(id_, std::forward(c)); }
template C* Entity::AddComponent(C& c) { return ecs_.AddComponent(id_, std::move(c)); }
template void Entity::RemoveComponent() { ecs_.RemoveComponent(id_); } Entity::Entity(ECS& ecs) : ecs_(ecs), id_(ecs.GetNewId()) { ecs.RegisterEntity(id_); } using ComponentData = unsigned char*; using ArchetypeId = std::vector; using EntityId = uint32_t;
struct Archetype { ComponentMask componentMask; std::vector componentData; std::vector entityIds; std::vectorstd::size_t componentDataSize; }; Here's how it works so far create a scene::load function that creates a bunch of objects dynamically?
- Assistant
Based on your provided ECS implementation, I have updated the
LoadScenefunction and added a few helper functions to create entities and components dynamically. Here's the updated code:#include <iostream> #include <fstream> #include <sstream> #include <string> #include <unordered_map> #include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include "ECS.h" using namespace rapidjson; using ComponentLoaderFunction = std::function<void(Entity&, const Value&)>; static std::unordered_map<std::string, ComponentLoaderFunction> componentLoaders; void LoadScene(ECS& ecs, const std::string& filePath) { FILE* fp = std::fopen(filePath.c_str(), "r"); if (!fp) { std::cerr << "Error opening scene file: " << filePath << std::endl; return; } char readBuffer[65536]; FileReadStream inputStream(fp, readBuffer, sizeof(readBuffer)); Document document; document.ParseStream<0, UTF8<>, FileReadStream>(inputStream); std::fclose(fp); if (document.HasParseError()) { std::cerr << "Error parsing JSON from scene file: " << filePath << std::endl; return; } if (document.HasMember("entities") && document["entities"].IsArray()) { const Value& entities = document["entities"]; for (SizeType i = 0; i < entities.Size(); i++) { const Value& entityData = entities[i]; Entity entity(ecs); for (const auto& component : componentLoaders) { const char* componentName = component.first.c_str(); if (entityData.HasMember(componentName)) { component.second(entity, entityData[componentName]); } } } } } void LoadPositionComponent(Entity& entity, const Value& component) { float x = component["x"].GetFloat(); float y = component["y"].GetFloat(); entity.AddComponent<Position>({x, y}); } void LoadNameComponent(Entity& entity, const Value& component) { std::string name = component["name"].GetString(); entity.AddComponent<Name>({name}); } void LoadSizeComponent(Entity& entity, const Value& component) { int width = component["width"].GetInt(); int height = component["height"].GetInt(); entity.AddComponent<Size>({width, height}); } void LoadVelocityComponent(Entity& entity, const Value& component) { int vel = component["vel"].GetInt(); entity.AddComponent<Velocity>({vel}); } int main() { ECS ecs; componentLoaders["position"] = LoadPositionComponent; componentLoaders["name"] = LoadNameComponent; componentLoaders["size"] = LoadSizeComponent; componentLoaders["velocity"] = LoadVelocityComponent; LoadScene(ecs, "path/to/scene_file.json"); return 0; }This code snippet assumes that the JSON scene file contains an array of entities with their components represented as key-value pairs. The
LoadScenefunction now takes anECSobject as a parameter, and the component loader functions take anEntityobject instead of anEntityId. - User
template <> void load_component_data(Entity& entity, const rapidjson::Value& component) { if (component.HasMember(“x”) && component[“x”].IsFloat() && component.HasMember(“y”) && component[“y”].IsFloat()) { entity.AddComponent({ component[“x”].GetFloat(), component[“y”].GetFloat() }); } else { throw std::runtime_error(“Invalid component data for Position”); } }
template <> void load_component_data(Entity& entity, const rapidjson::Value& component) { if (component.IsString()) { entity.AddComponent({ component.GetString() }); } else { throw std::runtime_error(“Invalid component data for Name”); } }
template <> void load_component_data(Entity& entity, const rapidjson::Value& component) { if (component.HasMember(“width”) && component[“width”].IsInt() && component.HasMember(“height”) && component[“height”].IsInt()) { entity.AddComponent({ component[“width”].GetInt(), component[“height”].GetInt() }); } else { throw std::runtime_error(“Invalid component data for Size”); } }
template <> void load_component_data(Entity& entity, const rapidjson::Value& component) { if (component.HasMember(“vel”) && component[“vel”].IsInt()) { entity.AddComponent({ component[“vel”].GetInt() }); } else { throw std::runtime_error(“Invalid component data for Velocity”); } }#pragma once #include #include #include
#include "TypeIdGenerator.h"
class ComponentBase { public: virtual ~ComponentBase() {} virtual void DestroyData(unsigned char* data) const = 0; virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0; virtual void ConstructData(unsigned char* data) const = 0; virtual std::size_t GetSize() const = 0; };
template class Component : public ComponentBase { public: virtual void DestroyData(unsigned char* data) const override;
virtual void MoveData(unsigned char* source, unsigned char* destination) const override; virtual void ConstructData(unsigned char* data) const override; virtual size_t GetSize() const override; static size_t GetTypeID();};
template void Component::DestroyData(unsigned char* data) const { C* dataLocation = std::launder(reinterpret_cast<C*>(data));
dataLocation->~C();}
template void Component::ConstructData(unsigned char* data) const { new (&data[0]) C(); }
template void Component::MoveData(unsigned char* source, unsigned char* destination) const { new (&destination[0]) C(std::move(std::bit_cast<C>(source))); }
template std::size_t Component::GetSize() const { return sizeof(C); }
template std::size_t Component::GetTypeID() { return TypeIdGenerator::template GetNewID(); }
template static const std::size_t GetTypeID() { return TypeIdGenerator::GetNewID(); }
struct Position { float x; float y; };
struct Name { std::string name; };
struct Size { int width; int height; };
struct Velocity { int vel; }; Is there a way to do this dynamically?
- Assistant
Yes, you can create a function template
load_component_dataand specialize it for each component type. Then, you can use a map to store the component loader functions and call them dynamically. Here's an example of how you can do this:#include <iostream> #include <fstream> #include <sstream> #include <string> #include <unordered_map> #include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include "ECS.h" using namespace rapidjson; template <typename T> void load_component_data(Entity& entity, const rapidjson::Value& component); template <> void load_component_data<Position>(Entity& entity, const rapidjson::Value& component) { if (component.HasMember("x") && component["x"].IsFloat() && component.HasMember("y") && component["y"].IsFloat()) { entity.AddComponent<Position>({ component["x"].GetFloat(), component["y"].GetFloat() }); } else { throw std::runtime_error("Invalid component data for Position"); } } // ... (other component specializations) using ComponentLoaderFunction = std::function<void(Entity&, const Value&)>; using ComponentLoaderMap = std::unordered_map<std::string, ComponentLoaderFunction>; ComponentLoaderMap create_component_loader_map() { ComponentLoaderMap componentLoaders; componentLoaders["position"] = load_component_data<Position>; // ... (add other component loaders) return componentLoaders; } void LoadScene(ECS& ecs, const std::string& filePath) { ComponentLoaderMap componentLoaders = create_component_loader_map(); // ... (rest of the LoadScene function) }This way, you can add new component types and their loader functions more easily. Just create a new specialization for
load_component_dataand add it to thecreate_component_loader_mapfunction. - User
Create an dynamic entity loader using rapidjson that can dynamically create components for an entity without defining a function for each component class. Using this definition of component #pragma once #include #include #include
#include "TypeIdGenerator.h"
class ComponentBase { public: virtual ~ComponentBase() {} virtual void DestroyData(unsigned char* data) const = 0; virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0; virtual void ConstructData(unsigned char* data) const = 0; virtual std::size_t GetSize() const = 0; };
template class Component : public ComponentBase { public: virtual void DestroyData(unsigned char* data) const override;
virtual void MoveData(unsigned char* source, unsigned char* destination) const override; virtual void ConstructData(unsigned char* data) const override; virtual size_t GetSize() const override; static size_t GetTypeID();};
template void Component::DestroyData(unsigned char* data) const { C* dataLocation = std::launder(reinterpret_cast<C*>(data));
dataLocation->~C();}
template void Component::ConstructData(unsigned char* data) const { new (&data[0]) C(); }
template void Component::MoveData(unsigned char* source, unsigned char* destination) const { new (&destination[0]) C(std::move(std::bit_cast<C>(source))); }
template std::size_t Component::GetSize() const { return sizeof(C); }
template std::size_t Component::GetTypeID() { return TypeIdGenerator::template GetNewID(); }
template static const std::size_t GetTypeID() { return TypeIdGenerator::GetNewID(); }
struct Position { float x; float y; };
struct Name { std::string name; };
struct Size { int width; int height; };
struct Velocity { int vel; };
- Assistant
To create a dynamic entity loader that can create components without defining a function for each component class, you can use a factory pattern to create components based on their type name. Here's an example of how you can do this:
- Create a
ComponentFactoryclass that can create components based on their type name:
#include <memory> #include <string> #include <unordered_map> #include <functional> class ComponentFactory { public: template <typename T> void RegisterComponent(const std::string& typeName) { creators_[typeName] = []() -> std::unique_ptr<ComponentBase> { return std::make_unique<Component<T>>(); }; } std::unique_ptr<ComponentBase> CreateComponent(const std::string& typeName) { auto it = creators_.find(typeName); if (it != creators_.end()) { return it->second(); } return nullptr; } private: std::unordered_map<std::string, std::function<std::unique_ptr<ComponentBase>()>> creators_; };- Register the component types in the
ComponentFactory:
ComponentFactory componentFactory; componentFactory.RegisterComponent<Position>("position"); componentFactory.RegisterComponent<Name>("name"); componentFactory.RegisterComponent<Size>("size"); componentFactory.RegisterComponent<Velocity>("velocity");- Modify the
LoadScenefunction to use theComponentFactoryto create components dynamically:
void LoadScene(ECS& ecs, const std::string& filePath, ComponentFactory& componentFactory) { // ... (rest of the LoadScene function) for (SizeType i = 0; i < entities.Size(); i++) { const Value& entityData = entities[i]; Entity entity(ecs); for (auto it = entityData.MemberBegin(); it != entityData.MemberEnd(); ++it) { const char* componentName = it->name.GetString(); const Value& componentData = it->value; std::unique_ptr<ComponentBase> component = componentFactory.CreateComponent(componentName); if (component) { // Deserialize component data from JSON and add it to the entity // This step depends on how you store component data in the JSON file } } } }Please note that this example assumes that you have a way to deserialize component data from the JSON file and add it to the entity. You may need to modify the
ComponentBaseclass to include methods for deserializing component data from JSON. - Create a
- User
How would you modify the componentBase class to derserialize component data? #pragma once #include #include #include
#include "TypeIdGenerator.h"
class ComponentBase { public: virtual ~ComponentBase() {} virtual void DestroyData(unsigned char* data) const = 0; virtual void MoveData(unsigned char* source, unsigned char* destination) const = 0; virtual void ConstructData(unsigned char* data) const = 0; virtual std::size_t GetSize() const = 0; };
template class Component : public ComponentBase { public: virtual void DestroyData(unsigned char* data) const override;
virtual void MoveData(unsigned char* source, unsigned char* destination) const override; virtual void ConstructData(unsigned char* data) const override; virtual size_t GetSize() const override; static size_t GetTypeID();};
template void Component::DestroyData(unsigned char* data) const { C* dataLocation = std::launder(reinterpret_cast<C*>(data));
dataLocation->~C();}
template void Component::ConstructData(unsigned char* data) const { new (&data[0]) C(); }
template void Component::MoveData(unsigned char* source, unsigned char* destination) const { new (&destination[0]) C(std::move(std::bit_cast<C>(source))); }
template std::size_t Component::GetSize() const { return sizeof(C); }
template std::size_t Component::GetTypeID() { return TypeIdGenerator::template GetNewID(); }
template static const std::size_t GetTypeID() { return TypeIdGenerator::GetNewID(); }
struct Position { float x; float y; };
struct Name { std::string name; };
struct Size { int width; int height; };
struct Velocity { int vel; };
- Assistant
To modify the
ComponentBaseclass to deserialize component data, you can add a new virtual method calledDeserializethat takes arapidjson::Valuereference as an argument. Then, you can override this method in theComponenttemplate class and provide a specialization for each component type to deserialize its data.Here's an example of how you can modify the
ComponentBaseandComponentclasses:#include "rapidjson/document.h" class ComponentBase { public: // ... (existing methods) virtual void Deserialize(Entity& entity, const rapidjson::Value& data) const = 0; }; template<class C> class Component : public ComponentBase { public: // ... (existing methods) virtual void Deserialize(Entity& entity, const rapidjson::Value& data) const override; }; template<class C> void Component<C>::Deserialize(Entity& entity, const rapidjson::Value& data) const { // Default implementation does nothing }Now, you can provide a specialization for each component type to deserialize its data:
template<> void Component<Position>::Deserialize(Entity& entity, const rapidjson::Value& data) const { if (data.HasMember("x") && data["x"].IsFloat() && data.HasMember("y") && data["y"].IsFloat()) { entity.AddComponent<Position>({ data["x"].GetFloat(), data["y"].GetFloat() }); } else { throw std::runtime_error("Invalid component data for Position"); } } // ... (other component specializations)Finally, update the
LoadScenefunction to call theDeserializemethod for each component:void LoadScene(ECS& ecs, const std::string& filePath, ComponentFactory& componentFactory) { // ... (rest of the LoadScene function) for (SizeType i = 0; i < entities.Size(); i++) { const Value& entityData = entities[i]; Entity entity(ecs); for (auto it = entityData.MemberBegin(); it != entityData.MemberEnd(); ++it) { const char* componentName = it->name.GetString(); const Value& componentData = it->value; std::unique_ptr<ComponentBase> component = componentFactory.CreateComponent(componentName); if (component) { component->Deserialize(entity, componentData); } } } }This way, you can deserialize component data dynamically without defining a separate function for each component class.