Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "lib/debug.h"
21 : #include "ps/CLogger.h"
22 : #include "ps/Profiler2.h"
23 : #include "simulation2/MessageTypes.h"
24 : #include "simulation2/components/ICmpTemplateManager.h"
25 : #include "simulation2/serialization/DebugSerializer.h"
26 : #include "simulation2/serialization/HashSerializer.h"
27 : #include "simulation2/serialization/StdDeserializer.h"
28 : #include "simulation2/serialization/StdSerializer.h"
29 : #include "simulation2/system/Component.h"
30 : #include "simulation2/system/Entity.h"
31 :
32 : #include <algorithm>
33 : #include <boost/random/linear_congruential.hpp>
34 : #include <cstdint>
35 : #include <cstdio>
36 : #include <map>
37 : #include <set>
38 : #include <sstream>
39 : #include <string>
40 : #include <utility>
41 : #include <vector>
42 :
43 25 : std::string SerializeRNG(const boost::random::rand48& rng)
44 : {
45 25 : std::stringstream s;
46 25 : s << rng;
47 50 : return s.str();
48 25 : }
49 :
50 3 : void DeserializeRNG(const std::string& str, boost::random::rand48& rng)
51 : {
52 3 : std::stringstream s;
53 3 : s << str;
54 3 : s >> rng;
55 3 : }
56 :
57 2 : bool CComponentManager::DumpDebugState(std::ostream& stream, bool includeDebugInfo) const
58 : {
59 2 : CDebugSerializer serializer(m_ScriptInterface, stream, includeDebugInfo);
60 :
61 2 : serializer.StringASCII("rng", SerializeRNG(m_RNG), 0, 32);
62 :
63 2 : serializer.TextLine("entities:");
64 :
65 : // We want the output to be grouped by entity ID, so invert the CComponentManager data structures
66 2 : std::map<entity_id_t, std::map<ComponentTypeId, IComponent*> > components;
67 : //std::map<ComponentTypeId, std::string> names;
68 :
69 2 : std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::const_iterator ctit = m_ComponentsByTypeId.begin();
70 8 : for (; ctit != m_ComponentsByTypeId.end(); ++ctit)
71 : {
72 6 : std::map<entity_id_t, IComponent*>::const_iterator eit = ctit->second.begin();
73 14 : for (; eit != ctit->second.end(); ++eit)
74 : {
75 8 : components[eit->first][ctit->first] = eit->second;
76 : }
77 : }
78 :
79 2 : std::map<entity_id_t, std::map<ComponentTypeId, IComponent*> >::const_iterator cit = components.begin();
80 9 : for (; cit != components.end(); ++cit)
81 : {
82 7 : std::stringstream n;
83 7 : n << "- id: " << cit->first;
84 7 : serializer.TextLine(n.str());
85 :
86 7 : if (ENTITY_IS_LOCAL(cit->first))
87 2 : serializer.TextLine(" type: local");
88 :
89 7 : std::map<ComponentTypeId, IComponent*>::const_iterator it = cit->second.begin();
90 15 : for (; it != cit->second.end(); ++it)
91 : {
92 8 : std::stringstream st;
93 16 : st << " " << LookupComponentTypeName(it->first) << ":";
94 8 : serializer.TextLine(st.str());
95 8 : serializer.Indent(4);
96 8 : it->second->Serialize(serializer);
97 8 : serializer.Dedent(4);
98 8 : }
99 7 : serializer.TextLine("");
100 7 : }
101 :
102 : // TODO: catch exceptions
103 2 : return true;
104 2 : }
105 :
106 10 : bool CComponentManager::ComputeStateHash(std::string& outHash, bool quick) const
107 : {
108 10 : PROFILE2("ComputeStateHash");
109 : // Hash serialization: this includes the minimal data necessary to detect
110 : // differences in the state, and ignores things like counts and names
111 :
112 : // If 'quick' is set, this checks even fewer things, so that it will
113 : // be fast enough to run every turn but will typically detect any
114 : // out-of-syncs fairly soon
115 :
116 10 : CHashSerializer serializer(m_ScriptInterface);
117 :
118 10 : serializer.StringASCII("rng", SerializeRNG(m_RNG), 0, 32);
119 10 : serializer.NumberU32_Unbounded("next entity id", m_NextEntityId);
120 :
121 10 : std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::const_iterator cit = m_ComponentsByTypeId.begin();
122 696 : for (; cit != m_ComponentsByTypeId.end(); ++cit)
123 : {
124 : // In quick mode, only check unit positions
125 686 : if (quick && !(cit->first == CID_Position))
126 0 : continue;
127 :
128 : // Only emit component types if they have a component that will be serialized
129 686 : bool hasEmittedComponent = false;
130 18054 : for (std::map<entity_id_t, IComponent*>::const_iterator eit = cit->second.begin(); eit != cit->second.end(); ++eit)
131 : {
132 : // Don't serialize local entities
133 17368 : if (ENTITY_IS_LOCAL(eit->first))
134 100 : continue;
135 17268 : if (!hasEmittedComponent)
136 : {
137 683 : serializer.NumberI32_Unbounded("component type id", cit->first);
138 : hasEmittedComponent = true;
139 : }
140 :
141 17268 : serializer.NumberU32_Unbounded("entity id", eit->first);
142 17268 : eit->second->Serialize(serializer);
143 : }
144 : }
145 :
146 10 : outHash = std::string((const char*)serializer.ComputeHash(), serializer.GetHashLength());
147 :
148 : // TODO: catch exceptions
149 10 : return true;
150 10 : }
151 :
152 : /*
153 : * Simulation state serialization format:
154 : *
155 : * TODO: Global version number.
156 : * Number of SYSTEM_ENTITY component types
157 : * For each SYSTEM_ENTITY component type:
158 : * Component type name
159 : * TODO: Component type version number.
160 : * Component state.
161 : * Number of (non-empty, non-SYSTEM_ENTITY-only) component types.
162 : * For each component type:
163 : * Component type name.
164 : * TODO: Component type version number.
165 : * Number of entities.
166 : * For each entity:
167 : * Entity id.
168 : * Component state.
169 : *
170 : * Rationale:
171 : * Saved games should be valid across patches, which might change component
172 : * type IDs. Thus the names are serialized, not the IDs.
173 : * Version numbers are used so saved games from future versions can be rejected,
174 : * and those from older versions can be fixed up to work with the latest version.
175 : * (These aren't really needed for networked games (where everyone will have the same
176 : * version), but it doesn't seem worth having a separate codepath for that.)
177 : */
178 :
179 13 : bool CComponentManager::SerializeState(std::ostream& stream) const
180 : {
181 13 : CStdSerializer serializer(m_ScriptInterface, stream);
182 :
183 : // We don't serialize the destruction queue, since we'd have to be careful to skip local entities etc.
184 : // This means we cannot have non-local entities in the destruction queue at this point.
185 13 : ENSURE(m_DestructionQueue.empty() || std::find_if(m_DestructionQueue.begin(), m_DestructionQueue.end(),
186 : [](entity_id_t ent) { return !ENTITY_IS_LOCAL(ent); }) == m_DestructionQueue.end());
187 :
188 14 : serializer.StringASCII("rng", SerializeRNG(m_RNG), 0, 32);
189 13 : serializer.NumberU32_Unbounded("next entity id", m_NextEntityId);
190 :
191 13 : std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::const_iterator cit;
192 :
193 13 : uint32_t numSystemComponentTypes = 0;
194 13 : uint32_t numComponentTypes = 0;
195 26 : std::set<ComponentTypeId> serializedSystemComponentTypes;
196 13 : std::set<ComponentTypeId> serializedComponentTypes;
197 :
198 706 : for (cit = m_ComponentsByTypeId.begin(); cit != m_ComponentsByTypeId.end(); ++cit)
199 : {
200 : // Only emit component types if they have a component that will be serialized
201 693 : bool needsSerialization = false;
202 948 : for (std::map<entity_id_t, IComponent*>::const_iterator eit = cit->second.begin(); eit != cit->second.end(); ++eit)
203 : {
204 : // Don't serialize local entities, and handle SYSTEM_ENTITY separately
205 690 : if (ENTITY_IS_LOCAL(eit->first) || eit->first == SYSTEM_ENTITY)
206 255 : continue;
207 :
208 : needsSerialization = true;
209 : break;
210 : }
211 :
212 693 : if (needsSerialization)
213 : {
214 435 : numComponentTypes++;
215 435 : serializedComponentTypes.insert(cit->first);
216 : }
217 :
218 1386 : if (cit->second.find(SYSTEM_ENTITY) != cit->second.end())
219 : {
220 255 : numSystemComponentTypes++;
221 948 : serializedSystemComponentTypes.insert(cit->first);
222 : }
223 : }
224 :
225 13 : serializer.NumberU32_Unbounded("num system component types", numSystemComponentTypes);
226 :
227 705 : for (cit = m_ComponentsByTypeId.begin(); cit != m_ComponentsByTypeId.end(); ++cit)
228 : {
229 1386 : if (serializedSystemComponentTypes.find(cit->first) == serializedSystemComponentTypes.end())
230 438 : continue;
231 :
232 255 : std::map<ComponentTypeId, ComponentType>::const_iterator ctit = m_ComponentTypesById.find(cit->first);
233 255 : if (ctit == m_ComponentTypesById.end())
234 : {
235 0 : debug_warn(L"Invalid ctit"); // this should never happen
236 12 : return false;
237 : }
238 :
239 255 : serializer.StringASCII("name", ctit->second.name, 0, 255);
240 :
241 255 : std::map<entity_id_t, IComponent*>::const_iterator eit = cit->second.find(SYSTEM_ENTITY);
242 255 : if (eit == cit->second.end())
243 : {
244 0 : debug_warn(L"Invalid eit"); // this should never happen
245 0 : return false;
246 : }
247 255 : eit->second->Serialize(serializer);
248 : }
249 :
250 12 : serializer.NumberU32_Unbounded("num component types", numComponentTypes);
251 :
252 704 : for (cit = m_ComponentsByTypeId.begin(); cit != m_ComponentsByTypeId.end(); ++cit)
253 : {
254 1384 : if (serializedComponentTypes.find(cit->first) == serializedComponentTypes.end())
255 257 : continue;
256 :
257 435 : std::map<ComponentTypeId, ComponentType>::const_iterator ctit = m_ComponentTypesById.find(cit->first);
258 435 : if (ctit == m_ComponentTypesById.end())
259 : {
260 0 : debug_warn(L"Invalid ctit"); // this should never happen
261 0 : return false;
262 : }
263 :
264 435 : serializer.StringASCII("name", ctit->second.name, 0, 255);
265 :
266 : // Count the components before serializing any of them
267 435 : uint32_t numComponents = 0;
268 17555 : for (std::map<entity_id_t, IComponent*>::const_iterator eit = cit->second.begin(); eit != cit->second.end(); ++eit)
269 : {
270 : // Don't serialize local entities or SYSTEM_ENTITY
271 17120 : if (ENTITY_IS_LOCAL(eit->first) || eit->first == SYSTEM_ENTITY)
272 100 : continue;
273 :
274 17020 : numComponents++;
275 : }
276 :
277 : // Emit the count
278 435 : serializer.NumberU32_Unbounded("num components", numComponents);
279 :
280 : // Serialize the components now
281 17555 : for (std::map<entity_id_t, IComponent*>::const_iterator eit = cit->second.begin(); eit != cit->second.end(); ++eit)
282 : {
283 : // Don't serialize local entities or SYSTEM_ENTITY
284 17120 : if (ENTITY_IS_LOCAL(eit->first) || eit->first == SYSTEM_ENTITY)
285 100 : continue;
286 :
287 17020 : serializer.NumberU32_Unbounded("entity id", eit->first);
288 17020 : eit->second->Serialize(serializer);
289 : }
290 : }
291 :
292 : // TODO: catch exceptions
293 : return true;
294 12 : }
295 :
296 3 : bool CComponentManager::DeserializeState(std::istream& stream)
297 : {
298 3 : try
299 : {
300 3 : CStdDeserializer deserializer(m_ScriptInterface, stream);
301 :
302 3 : ResetState();
303 3 : InitSystemEntity();
304 :
305 3 : std::string rng;
306 3 : deserializer.StringASCII("rng", rng, 0, 32);
307 3 : DeserializeRNG(rng, m_RNG);
308 :
309 3 : deserializer.NumberU32_Unbounded("next entity id", m_NextEntityId); // TODO: use sensible bounds
310 :
311 3 : uint32_t numSystemComponentTypes;
312 3 : deserializer.NumberU32_Unbounded("num system component types", numSystemComponentTypes);
313 :
314 3 : ICmpTemplateManager* templateManager = NULL;
315 3 : CParamNode noParam;
316 :
317 5 : for (size_t i = 0; i < numSystemComponentTypes; ++i)
318 : {
319 2 : std::string ctname;
320 2 : deserializer.StringASCII("name", ctname, 0, 255);
321 :
322 2 : ComponentTypeId ctid = LookupCID(ctname);
323 2 : if (ctid == CID__Invalid)
324 : {
325 0 : LOGERROR("Deserialization saw unrecognized component type '{}'", ctname);
326 0 : return false;
327 : }
328 :
329 2 : IComponent* component = ConstructComponent(m_SystemEntity, ctid);
330 2 : if (!component)
331 : return false;
332 :
333 2 : component->Deserialize(noParam, deserializer);
334 :
335 : // If this was the template manager, remember it so we can use it when
336 : // deserializing any further non-system entities
337 2 : if (ctid == CID_TemplateManager)
338 1 : templateManager = static_cast<ICmpTemplateManager*> (component);
339 2 : }
340 :
341 3 : uint32_t numComponentTypes;
342 3 : deserializer.NumberU32_Unbounded("num component types", numComponentTypes);
343 :
344 9 : for (size_t i = 0; i < numComponentTypes; ++i)
345 : {
346 6 : std::string ctname;
347 6 : deserializer.StringASCII("name", ctname, 0, 255);
348 :
349 6 : ComponentTypeId ctid = LookupCID(ctname);
350 6 : if (ctid == CID__Invalid)
351 : {
352 0 : LOGERROR("Deserialization saw unrecognized component type '{}'", ctname);
353 0 : return false;
354 : }
355 :
356 6 : uint32_t numComponents;
357 6 : deserializer.NumberU32_Unbounded("num components", numComponents);
358 :
359 13 : for (size_t j = 0; j < numComponents; ++j)
360 : {
361 7 : entity_id_t ent;
362 7 : deserializer.NumberU32_Unbounded("entity id", ent);
363 7 : IComponent* component = ConstructComponent(LookupEntityHandle(ent, true), ctid);
364 7 : if (!component)
365 0 : return false;
366 :
367 : // Try to find the template for this entity
368 7 : const CParamNode* entTemplate = NULL;
369 7 : if (templateManager)
370 1 : entTemplate = templateManager->LoadLatestTemplate(ent);
371 :
372 : // Deserialize, with the appropriate template for this component
373 1 : if (entTemplate)
374 1 : component->Deserialize(entTemplate->GetChild(ctname.c_str()), deserializer);
375 : else
376 6 : component->Deserialize(noParam, deserializer);
377 : }
378 6 : }
379 :
380 3 : if (stream.peek() != EOF)
381 : {
382 0 : LOGERROR("Deserialization didn't reach EOF");
383 0 : return false;
384 : }
385 :
386 : // Allow components to do some final reinitialisation after everything is loaded
387 3 : CMessageDeserialized msg;
388 3 : BroadcastMessage(msg);
389 :
390 3 : return true;
391 3 : }
392 0 : catch (PSERROR_Deserialize& e)
393 : {
394 0 : LOGERROR("Deserialization failed: {}", e.what());
395 0 : return false;
396 0 : }
397 : }
|