22 ID id(
static_cast<uint32_t
>(m_Entities.size()), 0);
23 m_Entities.push_back(
id);
27 void DestroyEntity(
ID id)
29 if (
id.Index() < m_Entities.size())
31 m_Entities[
id.Index()] = ID::Invalid();
33 for (
auto& pair : m_ComponentStorage)
35 pair.second->RemoveComponent(
id.Index());
39 template <
typename T,
typename... Args>
40 T& AddComponent(
ID id, Args&&... args)
42 auto storage = GetOrCreateComponentStorage<T>();
43 T component{ std::forward<Args>(args)... };
44 storage->Set.Insert(
id.Index(), component);
45 return storage->Set.Get(
id.Index());
49 void RemoveComponent(
ID id)
51 auto storage = GetOrCreateComponentStorage<T>();
52 storage->Set.Erase(
id.Index());
56 bool HasComponent(
ID id)
const
59 auto it = m_ComponentStorage.find(typeId);
60 if (it != m_ComponentStorage.end())
63 return storage->Set.Has(
id.Index());
69 T& GetComponent(
ID id)
71 auto storage = GetOrCreateComponentStorage<T>();
72 return storage->Set.Get(
id.Index());
79 auto it = m_ComponentStorage.find(typeId);
80 if (it != m_ComponentStorage.end())
85 throw std::runtime_error(
"Component not found");
88 void SaveToFile(
const std::string& path)
const
91 root[
"entities"] << m_Entities;
93 for (
const auto& pair : m_ComponentStorage)
96 pair.second->Serialize(compNode);
97 comps[pair.second->GetTypeName()] = compNode;
99 root[
"components"] = comps;
100 std::ofstream ofs(path);
103 throw std::runtime_error(
"Failed to open file for writing: " + path);
105 Node::WriteYAML(root, ofs);
108 void LoadFromFile(
const std::string& path)
110 std::ifstream ifs(path);
113 throw std::runtime_error(
"Failed to open file for reading: " + path);
115 std::stringstream buffer;
116 buffer << ifs.rdbuf();
118 if (!Node::ParseYAML(root, buffer.str()))
120 throw std::runtime_error(
"Failed to parse YAML");
122 root[
"entities"] >> m_Entities;
123 Node comps = root[
"components"];
124 for (
const auto& [key, compNode] : comps.GetProperties())
126 for (
auto& pair : m_ComponentStorage)
128 if (pair.second->GetTypeName() == key)
130 pair.second->Deserialize(compNode);
139 node[
"entities"] << scene.m_Entities;
141 for (
const auto& pair : scene.m_ComponentStorage)
144 pair.second->Serialize(compNode);
145 comps[pair.second->GetTypeName()] = compNode;
147 node[
"components"] = comps;
151 friend const Node& operator>>(
const Node& node,
Scene& scene)
153 node[
"entities"] >> scene.m_Entities;
154 Node comps = node[
"components"];
155 for (
const auto& [key, compNode] : comps.GetProperties())
157 for (
auto& pair : scene.m_ComponentStorage)
159 if (pair.second->GetTypeName() == key)
161 pair.second->Deserialize(compNode);
170 std::vector<ID> m_Entities;
171 std::unordered_map<TypeID, std::unique_ptr<ComponentStorageBase>> m_ComponentStorage;
174 template <
typename T>
178 auto it = m_ComponentStorage.find(typeId);
179 if (it != m_ComponentStorage.end())
185 auto storage = std::make_unique<ComponentStorage<T>>();
187 m_ComponentStorage[typeId] = std::move(storage);