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 "Simulation2.h"
21 :
22 : #include "graphics/MapReader.h"
23 : #include "graphics/Terrain.h"
24 : #include "lib/debug.h"
25 : #include "lib/file/file_system.h"
26 : #include "lib/file/vfs/vfs_util.h"
27 : #include "lib/os_path.h"
28 : #include "lib/path.h"
29 : #include "lib/sysdep/filesystem.h"
30 : #include "lib/timer.h"
31 : #include "lib/utf8.h"
32 : #include "maths/Fixed.h"
33 : #include "maths/MathUtil.h"
34 : #include "ps/CLogger.h"
35 : #include "ps/CStr.h"
36 : #include "ps/ConfigDB.h"
37 : #include "ps/Errors.h"
38 : #include "ps/Filesystem.h"
39 : #include "ps/Loader.h"
40 : #include "ps/Profile.h"
41 : #include "ps/Profiler2.h"
42 : #include "ps/Pyrogenesis.h"
43 : #include "ps/Util.h"
44 : #include "scriptinterface/FunctionWrapper.h"
45 : #include "scriptinterface/JSON.h"
46 : #include "scriptinterface/Object.h"
47 : #include "scriptinterface/Context.h"
48 : #include "scriptinterface/Interface.h"
49 : #include "scriptinterface/Request.h"
50 : #include "scriptinterface/StructuredClone.h"
51 : #include "simulation2/MessageTypes.h"
52 : #include "simulation2/components/ICmpAIManager.h"
53 : #include "simulation2/components/ICmpCommandQueue.h"
54 : #include "simulation2/components/ICmpPathfinder.h"
55 : #include "simulation2/helpers/Player.h"
56 : #include "simulation2/helpers/SimulationCommand.h"
57 : #include "simulation2/system/Component.h"
58 :
59 : #include <algorithm>
60 : #include <cstddef>
61 : #include <cstdint>
62 : #include <filesystem>
63 : #include <fstream>
64 : #include <functional>
65 : #include <iomanip>
66 : #include <js/CallArgs.h>
67 : #include <js/RootingAPI.h>
68 : #include <js/Value.h>
69 : #include <memory>
70 : #include <optional>
71 : #include <set>
72 : #include <sstream>
73 : #include <system_error>
74 :
75 : class CSimulation2Impl
76 : {
77 : public:
78 10 : CSimulation2Impl(CUnitManager* unitManager, Script::Context& cx, CTerrain* terrain,
79 10 : const std::span<const wchar_t* const> scriptDirectories, const SimulationDebugOptions debugOptions) :
80 10 : m_SimContext{terrain, unitManager},
81 10 : m_ComponentManager{m_SimContext, cx},
82 10 : m_InitAttributes{cx.GetGeneralJSContext()},
83 10 : m_MapSettings{cx.GetGeneralJSContext()},
84 : // Tests won't have config initialised
85 10 : m_EnableOOSLog{debugOptions.oosLog || CConfigDB::GetIfInitialised("ooslog", false)},
86 : // Handle bogus values of the arg
87 30 : m_SerializationTestTurn{[&]
88 : {
89 10 : const auto* serializationTestOption{
90 10 : std::get_if<SimulationDebugOptions::SerializationTest>(&debugOptions.test)};
91 0 : return serializationTestOption ? serializationTestOption->turn :
92 10 : std::max(CConfigDB::GetIfInitialised("serializationtest", -1), -1);
93 10 : }()},
94 30 : m_RejoinTestTurn{[&]() -> std::optional<turn_id_t>
95 : {
96 10 : const auto* rejoinTestOption{
97 10 : std::get_if<SimulationDebugOptions::RejoinTest>(&debugOptions.test)};
98 0 : if (rejoinTestOption)
99 0 : return rejoinTestOption->turn;
100 10 : const turn_id_t configVal{CConfigDB::GetIfInitialised("rejointest", -1)};
101 10 : if (configVal >= 0)
102 0 : return configVal;
103 10 : return std::nullopt;
104 40 : }()}
105 : {
106 10 : m_ComponentManager.LoadComponentTypes();
107 :
108 10 : RegisterFileReloadFunc(ReloadChangedFileCB, this);
109 :
110 10 : if (m_EnableOOSLog)
111 : {
112 0 : m_OOSLogPath = createDateIndexSubdirectory(psLogDir() / "oos_logs");
113 0 : debug_printf("Writing ooslogs to %s\n", m_OOSLogPath.string8().c_str());
114 : }
115 :
116 20 : std::ranges::for_each(scriptDirectories,
117 10 : std::bind_front(LoadScripts, std::ref(m_ComponentManager), &m_LoadedScripts));
118 10 : }
119 :
120 10 : ~CSimulation2Impl()
121 : {
122 10 : UnregisterFileReloadFunc(ReloadChangedFileCB, this);
123 30 : }
124 :
125 7 : void ResetState(bool skipScriptedComponents, bool skipAI)
126 : {
127 7 : m_LastFrameOffset = 0.0f;
128 7 : m_TurnNumber = 0;
129 7 : ResetComponentState(m_ComponentManager, skipScriptedComponents, skipAI);
130 : }
131 :
132 7 : static void ResetComponentState(CComponentManager& componentManager, bool skipScriptedComponents, bool skipAI)
133 : {
134 7 : componentManager.ResetState();
135 7 : componentManager.InitSystemEntity();
136 7 : componentManager.AddSystemComponents(skipScriptedComponents, skipAI);
137 7 : }
138 :
139 : static void LoadScripts(CComponentManager& componentManager, std::set<VfsPath>* loadedScripts, const VfsPath& path);
140 : static bool LoadTriggerScripts(CComponentManager& componentManager, JS::HandleValue mapSettings, std::set<VfsPath>* loadedScripts);
141 : Status ReloadChangedFile(const VfsPath& path);
142 :
143 0 : static Status ReloadChangedFileCB(void* param, const VfsPath& path)
144 : {
145 0 : return static_cast<CSimulation2Impl*>(param)->ReloadChangedFile(path);
146 : }
147 :
148 : PS::Loader::Task ProgressiveLoad();
149 : void Update(int turnLength, const std::vector<SimulationCommand>& commands);
150 : static void UpdateComponents(CSimContext& simContext, fixed turnLengthFixed, const std::vector<SimulationCommand>& commands);
151 : void Interpolate(float simFrameLength, float frameOffset, float realFrameLength);
152 :
153 : void DumpState();
154 :
155 : CSimContext m_SimContext;
156 : CComponentManager m_ComponentManager;
157 : float m_LastFrameOffset;
158 :
159 : std::string m_StartupScript;
160 : JS::PersistentRootedValue m_InitAttributes;
161 : JS::PersistentRootedValue m_MapSettings;
162 :
163 : std::set<VfsPath> m_LoadedScripts;
164 :
165 : turn_id_t m_TurnNumber;
166 :
167 : bool m_EnableOOSLog{false};
168 : OsPath m_OOSLogPath;
169 :
170 : // Functions and data for the serialization test mode: (see Update() for relevant comments)
171 :
172 : std::optional<turn_id_t> m_SerializationTestTurn;
173 : bool m_TestingSerialization{false};
174 : bool m_EnableSerializationTest{false};
175 : std::optional<turn_id_t> m_RejoinTestTurn;
176 : bool m_TestingRejoin{false};
177 :
178 : // Secondary simulation (NB: order matters for destruction).
179 : std::unique_ptr<CComponentManager> m_SecondaryComponentManager;
180 : std::unique_ptr<CTerrain> m_SecondaryTerrain;
181 : std::unique_ptr<CSimContext> m_SecondaryContext;
182 : std::unique_ptr<std::set<VfsPath>> m_SecondaryLoadedScripts;
183 :
184 : struct SerializationTestState
185 : {
186 : std::stringstream state;
187 : std::stringstream debug;
188 : std::string hash;
189 : };
190 :
191 : void DumpSerializationTestState(SerializationTestState& state, const OsPath& path, const OsPath::String& suffix);
192 :
193 : void ReportSerializationFailure(
194 : SerializationTestState* primaryStateBefore, SerializationTestState* primaryStateAfter,
195 : SerializationTestState* secondaryStateBefore, SerializationTestState* secondaryStateAfter);
196 :
197 : void InitRNGSeedSimulation();
198 : void InitRNGSeedAI();
199 :
200 0 : static std::vector<SimulationCommand> CloneCommandsFromOtherCompartment(const Script::Interface& newScript, const Script::Interface& oldScript,
201 : const std::vector<SimulationCommand>& commands)
202 : {
203 0 : std::vector<SimulationCommand> newCommands;
204 0 : newCommands.reserve(commands.size());
205 :
206 0 : Script::Request rqNew(newScript);
207 0 : for (const SimulationCommand& command : commands)
208 : {
209 0 : JS::RootedValue tmpCommand(rqNew.cx, Script::CloneValueFromOtherCompartment(newScript, oldScript, command.data));
210 0 : Script::DeepFreezeObject(rqNew, tmpCommand);
211 0 : SimulationCommand cmd(command.player, rqNew.cx, tmpCommand);
212 0 : newCommands.emplace_back(std::move(cmd));
213 0 : }
214 0 : return newCommands;
215 0 : }
216 : };
217 :
218 15 : void CSimulation2Impl::LoadScripts(CComponentManager& componentManager, std::set<VfsPath>* loadedScripts, const VfsPath& path)
219 : {
220 15 : VfsPaths pathnames;
221 15 : if (vfs::GetPathnames(g_VFS, path, L"*.js", pathnames) < 0)
222 0 : throw CSimulation2::LoadScriptError{"Error enumerating " + path.string8()};
223 :
224 690 : for (const VfsPath& scriptPath : pathnames)
225 : {
226 675 : if (loadedScripts)
227 675 : loadedScripts->insert(scriptPath);
228 2025 : LOGMESSAGE("Loading simulation script '{}'", scriptPath.string8());
229 675 : if (!componentManager.LoadScript(scriptPath))
230 0 : throw CSimulation2::LoadScriptError{"Error loading " + scriptPath.string8()};
231 : }
232 15 : }
233 :
234 3 : bool CSimulation2Impl::LoadTriggerScripts(CComponentManager& componentManager, JS::HandleValue mapSettings, std::set<VfsPath>* loadedScripts)
235 : {
236 3 : bool ok = true;
237 3 : Script::Request rq(componentManager.GetScriptInterface());
238 3 : if (Script::HasProperty(rq, mapSettings, "TriggerScripts"))
239 : {
240 3 : std::vector<std::string> scriptNames;
241 3 : Script::GetProperty(rq, mapSettings, "TriggerScripts", scriptNames);
242 9 : for (const std::string& triggerScript : scriptNames)
243 : {
244 6 : std::string scriptName = "maps/" + triggerScript;
245 6 : if (loadedScripts)
246 : {
247 12 : if (loadedScripts->find(scriptName) != loadedScripts->end())
248 0 : continue;
249 12 : loadedScripts->insert(scriptName);
250 : }
251 12 : LOGMESSAGE("Loading trigger script '{}'", scriptName);
252 12 : if (!componentManager.LoadScript(scriptName.data()))
253 0 : ok = false;
254 6 : }
255 3 : }
256 3 : return ok;
257 3 : }
258 :
259 5 : Status CSimulation2Impl::ReloadChangedFile(const VfsPath& path)
260 : {
261 : // Ignore if this file wasn't loaded as a script
262 : // (TODO: Maybe we ought to load in any new .js files that are created in the right directories)
263 5 : if (m_LoadedScripts.find(path) == m_LoadedScripts.end())
264 : return INFO::OK;
265 :
266 : // If the file doesn't exist (e.g. it was deleted), don't bother loading it since that'll give an error message.
267 : // (Also don't bother trying to 'unload' it from the component manager, because that's not possible)
268 2 : if (!VfsFileExists(path))
269 : return INFO::OK;
270 :
271 6 : LOGMESSAGE("Reloading simulation script '{}'", path.string8());
272 2 : if (!m_ComponentManager.LoadScript(path, true))
273 : return ERR::FAIL;
274 :
275 : return INFO::OK;
276 : }
277 :
278 6 : PS::Loader::Task CSimulation2Impl::ProgressiveLoad()
279 : {
280 : while (true)
281 : {
282 : bool progressed = false;
283 : int total = 0;
284 : int progress = 0;
285 :
286 : CMessageProgressiveLoad msg(&progressed, &total, &progress);
287 :
288 : m_ComponentManager.BroadcastMessage(msg);
289 :
290 : if (!progressed || total == 0)
291 : co_return 0; // we have nothing left to load
292 :
293 : co_yield Clamp(100*progress / total, 1, 100);
294 : }
295 3 : }
296 :
297 0 : void CSimulation2Impl::DumpSerializationTestState(SerializationTestState& state, const OsPath& path, const OsPath::String& suffix)
298 : {
299 0 : if (!state.hash.empty())
300 : {
301 0 : std::ofstream file (OsString(path / (L"hash." + suffix)), std::ofstream::out | std::ofstream::trunc);
302 0 : file << Hexify(state.hash);
303 0 : }
304 :
305 0 : if (!state.debug.str().empty())
306 : {
307 0 : std::ofstream file (OsString(path / (L"debug." + suffix)), std::ofstream::out | std::ofstream::trunc);
308 0 : file << state.debug.str();
309 0 : }
310 :
311 0 : if (!state.state.str().empty())
312 : {
313 0 : std::ofstream file (OsString(path / (L"state." + suffix)), std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
314 0 : file << state.state.str();
315 0 : }
316 0 : }
317 :
318 0 : void CSimulation2Impl::ReportSerializationFailure(
319 : SerializationTestState* primaryStateBefore, SerializationTestState* primaryStateAfter,
320 : SerializationTestState* secondaryStateBefore, SerializationTestState* secondaryStateAfter)
321 : {
322 0 : const OsPath path = createDateIndexSubdirectory(psLogDir() / "serializationtest");
323 0 : debug_printf("Writing serializationtest-data to %s\n", path.string8().c_str());
324 :
325 : // Try to clean up obsolete files from previous runs.
326 0 : constexpr auto namesToRemove{std::to_array<std::string_view>({
327 : "hash.before.a",
328 : "hash.before.b",
329 : "debug.before.a",
330 : "debug.before.b",
331 : "state.before.a",
332 : "state.before.b",
333 : "hash.after.a",
334 : "hash.after.b",
335 : "debug.after.a",
336 : "debug.after.b",
337 : "state.after.a",
338 : "state.after.b",
339 : })};
340 :
341 0 : const std::filesystem::path fspath{path.string()};
342 0 : std::error_code ec{};
343 0 : for (const std::string_view nameToRemove : namesToRemove)
344 0 : std::filesystem::remove(fspath / nameToRemove, ec);
345 :
346 0 : if (primaryStateBefore)
347 0 : DumpSerializationTestState(*primaryStateBefore, path, L"before.a");
348 0 : if (primaryStateAfter)
349 0 : DumpSerializationTestState(*primaryStateAfter, path, L"after.a");
350 0 : if (secondaryStateBefore)
351 0 : DumpSerializationTestState(*secondaryStateBefore, path, L"before.b");
352 0 : if (secondaryStateAfter)
353 0 : DumpSerializationTestState(*secondaryStateAfter, path, L"after.b");
354 :
355 0 : debug_warn(L"Serialization test failure");
356 0 : }
357 :
358 3 : void CSimulation2Impl::InitRNGSeedSimulation()
359 : {
360 3 : std::uint32_t seed = 0;
361 3 : Script::Request rq(m_ComponentManager.GetScriptInterface());
362 6 : if (!Script::HasProperty(rq, m_MapSettings, "Seed") ||
363 6 : !Script::GetProperty(rq, m_MapSettings, "Seed", seed))
364 : {
365 0 : LOGWARNING("CSimulation2Impl::InitRNGSeedSimulation: No seed value specified - using {}",
366 : seed);
367 : }
368 :
369 3 : m_ComponentManager.SetRNGSeed(seed);
370 3 : }
371 :
372 3 : void CSimulation2Impl::InitRNGSeedAI()
373 : {
374 3 : std::uint32_t seed = 0;
375 3 : Script::Request rq(m_ComponentManager.GetScriptInterface());
376 6 : if (!Script::HasProperty(rq, m_MapSettings, "AISeed") ||
377 6 : !Script::GetProperty(rq, m_MapSettings, "AISeed", seed))
378 : {
379 0 : LOGWARNING("CSimulation2Impl::InitRNGSeedAI: No seed value specified - using {}", seed);
380 : }
381 :
382 3 : CmpPtr<ICmpAIManager> cmpAIManager(m_SimContext, SYSTEM_ENTITY);
383 3 : if (cmpAIManager)
384 3 : cmpAIManager->SetRNGSeed(seed);
385 3 : }
386 :
387 180 : void CSimulation2Impl::Update(int turnLength, const std::vector<SimulationCommand>& commands)
388 : {
389 180 : PROFILE3("sim update");
390 180 : PROFILE2_ATTR("turn %d", m_TurnNumber);
391 :
392 180 : fixed turnLengthFixed = fixed::FromInt(turnLength) / 1000;
393 :
394 : /*
395 : * In serialization test mode, we save the original (primary) simulation state before each turn update.
396 : * We run the update, then load the saved state into a secondary context.
397 : * We serialize that again and compare to the original serialization (to check that
398 : * serialize->deserialize->serialize is equivalent to serialize).
399 : * Then we run the update on the secondary context, and check that its new serialized
400 : * state matches the primary context after the update (to check that the simulation doesn't depend
401 : * on anything that's not serialized).
402 : *
403 : * In rejoin test mode, the secondary simulation is initialized from serialized data at turn N, then both
404 : * simulations run independantly while comparing their states each turn. This is way faster than a
405 : * complete serialization test and allows us to reproduce OOSes on rejoin.
406 : */
407 :
408 180 : const bool serializationTestDebugDump = false; // set true to save human-readable state dumps before an error is detected, for debugging (but slow)
409 180 : const bool serializationTestHash = true; // set true to save and compare hash of state
410 :
411 180 : SerializationTestState primaryStateBefore;
412 180 : const Script::Interface& scriptInterface = m_ComponentManager.GetScriptInterface();
413 :
414 180 : const bool startSerializationTest = m_SerializationTestTurn.has_value() &&
415 180 : m_SerializationTestTurn.value() == m_TurnNumber;
416 0 : if (startSerializationTest)
417 0 : m_TestingSerialization = true;
418 180 : const bool startRejoinTest = m_RejoinTestTurn.has_value() &&
419 0 : m_RejoinTestTurn.value() == m_TurnNumber;
420 0 : if (startRejoinTest)
421 0 : m_TestingRejoin = true;
422 :
423 180 : if (m_TestingSerialization || m_TestingRejoin)
424 : {
425 0 : ENSURE(m_ComponentManager.SerializeState(primaryStateBefore.state));
426 0 : if (serializationTestDebugDump)
427 : ENSURE(m_ComponentManager.DumpDebugState(primaryStateBefore.debug, false));
428 0 : if (serializationTestHash)
429 0 : ENSURE(m_ComponentManager.ComputeStateHash(primaryStateBefore.hash, false));
430 : }
431 :
432 180 : UpdateComponents(m_SimContext, turnLengthFixed, commands);
433 :
434 180 : if (m_TestingSerialization || startRejoinTest)
435 : {
436 0 : if (startSerializationTest)
437 0 : debug_printf("Starting serializationtest\n");
438 0 : if (startRejoinTest)
439 0 : debug_printf("Initializing the secondary simulation\n");
440 :
441 0 : m_SecondaryTerrain = std::make_unique<CTerrain>();
442 :
443 0 : m_SecondaryContext = std::make_unique<CSimContext>(m_SecondaryTerrain.get());
444 :
445 0 : m_SecondaryComponentManager = std::make_unique<CComponentManager>(*m_SecondaryContext, scriptInterface.GetContext());
446 0 : m_SecondaryComponentManager->LoadComponentTypes();
447 :
448 0 : m_SecondaryLoadedScripts = std::make_unique<std::set<VfsPath>>();
449 0 : std::ranges::for_each(CSimulation2::DEFAULT_SCRIPTS, std::bind_front(LoadScripts,
450 0 : std::ref(*m_SecondaryComponentManager), m_SecondaryLoadedScripts.get()));
451 0 : ResetComponentState(*m_SecondaryComponentManager, false, false);
452 :
453 0 : Script::Request rq(scriptInterface);
454 :
455 : // Clone InitAttributes.
456 0 : {
457 0 : const Script::Request rq2(m_SecondaryComponentManager->GetScriptInterface());
458 0 : const JS::RootedValue initAttributesCloned(rq2.cx, Script::CloneValueFromOtherCompartment(m_SecondaryComponentManager->GetScriptInterface(), scriptInterface, m_InitAttributes));
459 0 : m_SecondaryComponentManager->GetScriptInterface().SetGlobal("InitAttributes", initAttributesCloned, true, true, true);
460 0 : }
461 :
462 : // Load the trigger scripts after we have loaded the simulation.
463 0 : {
464 0 : Script::Request rq2(m_SecondaryComponentManager->GetScriptInterface());
465 0 : JS::RootedValue mapSettingsCloned(rq2.cx, Script::CloneValueFromOtherCompartment(m_SecondaryComponentManager->GetScriptInterface(), scriptInterface, m_MapSettings));
466 0 : ENSURE(LoadTriggerScripts(*m_SecondaryComponentManager, mapSettingsCloned, m_SecondaryLoadedScripts.get()));
467 0 : }
468 :
469 : // Load the map into the secondary simulation
470 :
471 0 : PS::Loader::BeginRegistering();
472 0 : std::unique_ptr<CMapReader> mapReader = std::make_unique<CMapReader>();
473 :
474 0 : std::string mapType;
475 0 : Script::GetProperty(rq, m_InitAttributes, "mapType", mapType);
476 0 : if (mapType == "random")
477 : {
478 : // TODO: support random map scripts
479 0 : debug_warn(L"Serialization test mode does not support random maps");
480 : }
481 : else
482 : {
483 0 : std::wstring mapFile;
484 0 : Script::GetProperty(rq, m_InitAttributes, "map", mapFile);
485 :
486 0 : VfsPath mapfilename = VfsPath(mapFile).ChangeExtension(L".pmp");
487 0 : mapReader->LoadMap(mapfilename, scriptInterface.GetContext(), JS::UndefinedHandleValue,
488 : m_SecondaryTerrain.get(), NULL, NULL, NULL, NULL, NULL, NULL,
489 0 : NULL, NULL, m_SecondaryContext.get(), INVALID_PLAYER, true); // throws exception on failure
490 0 : }
491 :
492 0 : PS::Loader::EndRegistering();
493 0 : ENSURE(PS::Loader::NonprogressiveLoad() == INFO::OK);
494 0 : ENSURE(m_SecondaryComponentManager->DeserializeState(primaryStateBefore.state));
495 0 : }
496 :
497 180 : if (m_TestingSerialization || m_TestingRejoin)
498 : {
499 0 : SerializationTestState secondaryStateBefore;
500 0 : ENSURE(m_SecondaryComponentManager->SerializeState(secondaryStateBefore.state));
501 0 : if (serializationTestDebugDump)
502 : ENSURE(m_SecondaryComponentManager->DumpDebugState(secondaryStateBefore.debug, false));
503 0 : if (serializationTestHash)
504 0 : ENSURE(m_SecondaryComponentManager->ComputeStateHash(secondaryStateBefore.hash, false));
505 :
506 0 : if (primaryStateBefore.state.str() != secondaryStateBefore.state.str() ||
507 0 : primaryStateBefore.hash != secondaryStateBefore.hash)
508 : {
509 0 : ReportSerializationFailure(&primaryStateBefore, NULL, &secondaryStateBefore, NULL);
510 : }
511 :
512 0 : SerializationTestState primaryStateAfter;
513 0 : ENSURE(m_ComponentManager.SerializeState(primaryStateAfter.state));
514 0 : if (serializationTestHash)
515 0 : ENSURE(m_ComponentManager.ComputeStateHash(primaryStateAfter.hash, false));
516 :
517 0 : UpdateComponents(*m_SecondaryContext, turnLengthFixed,
518 0 : CloneCommandsFromOtherCompartment(m_SecondaryComponentManager->GetScriptInterface(), scriptInterface, commands));
519 0 : SerializationTestState secondaryStateAfter;
520 0 : ENSURE(m_SecondaryComponentManager->SerializeState(secondaryStateAfter.state));
521 0 : if (serializationTestHash)
522 0 : ENSURE(m_SecondaryComponentManager->ComputeStateHash(secondaryStateAfter.hash, false));
523 :
524 0 : if (primaryStateAfter.state.str() != secondaryStateAfter.state.str() ||
525 0 : primaryStateAfter.hash != secondaryStateAfter.hash)
526 : {
527 : // Only do the (slow) dumping now we know we're going to need to report it
528 0 : ENSURE(m_ComponentManager.DumpDebugState(primaryStateAfter.debug, false));
529 0 : ENSURE(m_SecondaryComponentManager->DumpDebugState(secondaryStateAfter.debug, false));
530 :
531 0 : ReportSerializationFailure(&primaryStateBefore, &primaryStateAfter, &secondaryStateBefore, &secondaryStateAfter);
532 : }
533 0 : }
534 :
535 : // (TODO: we ought to schedule this for a frame where we're not
536 : // running the sim update, to spread the load)
537 180 : scriptInterface.GetContext().MaybeIncrementalGC();
538 :
539 180 : if (m_EnableOOSLog)
540 0 : DumpState();
541 :
542 180 : ++m_TurnNumber;
543 180 : }
544 :
545 180 : void CSimulation2Impl::UpdateComponents(CSimContext& simContext, fixed turnLengthFixed, const std::vector<SimulationCommand>& commands)
546 : {
547 : // TODO: the update process is pretty ugly, with lots of messages and dependencies
548 : // between different components. Ought to work out a nicer way to do this.
549 :
550 180 : CComponentManager& componentManager = simContext.GetComponentManager();
551 :
552 180 : CmpPtr<ICmpPathfinder> cmpPathfinder(simContext, SYSTEM_ENTITY);
553 180 : if (cmpPathfinder)
554 180 : cmpPathfinder->SendRequestedPaths();
555 :
556 180 : {
557 180 : PROFILE2("Sim - Update Start");
558 180 : CMessageTurnStart msgTurnStart;
559 180 : componentManager.BroadcastMessage(msgTurnStart);
560 180 : }
561 :
562 :
563 180 : CmpPtr<ICmpCommandQueue> cmpCommandQueue(simContext, SYSTEM_ENTITY);
564 180 : if (cmpCommandQueue)
565 180 : cmpCommandQueue->FlushTurn(commands);
566 :
567 : // Process newly generated move commands so the UI feels snappy
568 180 : if (cmpPathfinder)
569 : {
570 180 : cmpPathfinder->StartProcessingMoves(true);
571 180 : cmpPathfinder->SendRequestedPaths();
572 : }
573 : // Send all the update phases
574 180 : {
575 180 : PROFILE2("Sim - Update");
576 180 : CMessageUpdate msgUpdate(turnLengthFixed);
577 180 : componentManager.BroadcastMessage(msgUpdate);
578 180 : }
579 :
580 180 : {
581 180 : CMessageUpdate_MotionFormation msgUpdate(turnLengthFixed);
582 180 : componentManager.BroadcastMessage(msgUpdate);
583 0 : }
584 :
585 : // Process move commands for formations (group proxy)
586 180 : if (cmpPathfinder)
587 : {
588 180 : cmpPathfinder->StartProcessingMoves(true);
589 180 : cmpPathfinder->SendRequestedPaths();
590 : }
591 :
592 180 : {
593 180 : PROFILE2("Sim - Motion Unit");
594 180 : CMessageUpdate_MotionUnit msgUpdate(turnLengthFixed);
595 180 : componentManager.BroadcastMessage(msgUpdate);
596 180 : }
597 180 : {
598 180 : PROFILE2("Sim - Update Final");
599 180 : CMessageUpdate_Final msgUpdate(turnLengthFixed);
600 180 : componentManager.BroadcastMessage(msgUpdate);
601 180 : }
602 :
603 : // Clean up any entities destroyed during the simulation update
604 180 : componentManager.FlushDestroyedComponents();
605 :
606 : // Compute AI immediately at turn's end.
607 180 : CmpPtr<ICmpAIManager> cmpAIManager(simContext, SYSTEM_ENTITY);
608 180 : if (cmpAIManager)
609 : {
610 180 : cmpAIManager->StartComputation();
611 180 : cmpAIManager->PushCommands();
612 : }
613 :
614 : // Process all remaining moves
615 180 : if (cmpPathfinder)
616 : {
617 180 : cmpPathfinder->UpdateGrid();
618 180 : cmpPathfinder->StartProcessingMoves(false);
619 : }
620 :
621 180 : componentManager.GetScriptInterface().GetContext().RunJobs();
622 180 : }
623 :
624 4 : void CSimulation2Impl::Interpolate(float simFrameLength, float frameOffset, float realFrameLength)
625 : {
626 4 : PROFILE3("sim interpolate");
627 :
628 4 : m_LastFrameOffset = frameOffset;
629 :
630 4 : CMessageInterpolate msg(simFrameLength, frameOffset, realFrameLength);
631 4 : m_ComponentManager.BroadcastMessage(msg);
632 :
633 : // Clean up any entities destroyed during interpolate (e.g. local corpses)
634 4 : m_ComponentManager.FlushDestroyedComponents();
635 4 : }
636 :
637 0 : void CSimulation2Impl::DumpState()
638 : {
639 0 : PROFILE("DumpState");
640 :
641 0 : std::stringstream name;\
642 0 : name << std::setw(5) << std::setfill('0') << m_TurnNumber << ".txt";
643 0 : const OsPath path = m_OOSLogPath / name.str();
644 0 : std::ofstream file (OsString(path), std::ofstream::out | std::ofstream::trunc);
645 :
646 0 : if (!DirectoryExists(m_OOSLogPath))
647 : {
648 0 : LOGWARNING("OOS-log directory {} was deleted, creating it again.", m_OOSLogPath.string8());
649 0 : CreateDirectories(m_OOSLogPath, 0700);
650 : }
651 :
652 0 : file << "State hash: " << std::hex;
653 0 : std::string hashRaw;
654 0 : m_ComponentManager.ComputeStateHash(hashRaw, false);
655 0 : for (size_t i = 0; i < hashRaw.size(); ++i)
656 0 : file << std::setfill('0') << std::setw(2) << (int)(unsigned char)hashRaw[i];
657 0 : file << std::dec << "\n";
658 :
659 0 : file << "\n";
660 :
661 0 : m_ComponentManager.DumpDebugState(file, true);
662 :
663 0 : std::ofstream binfile (OsString(path.ChangeExtension(L".dat")), std::ofstream::out | std::ofstream::trunc | std::ofstream::binary);
664 0 : m_ComponentManager.SerializeState(binfile);
665 0 : }
666 :
667 : ////////////////////////////////////////////////////////////////
668 :
669 10 : CSimulation2::CSimulation2(CUnitManager* unitManager, Script::Context& cx, CTerrain* terrain,
670 10 : const std::span<const wchar_t* const> scriptDirectories, const SimulationDebugOptions debugOptions) :
671 10 : m(std::make_unique<CSimulation2Impl>(unitManager, cx, terrain, scriptDirectories, debugOptions))
672 : {
673 10 : }
674 :
675 10 : CSimulation2::~CSimulation2() = default;
676 :
677 : // Forward all method calls to the appropriate CSimulation2Impl/CComponentManager methods:
678 :
679 6 : entity_id_t CSimulation2::AddEntity(const std::wstring& templateName)
680 : {
681 6 : return m->m_ComponentManager.AddEntity(templateName, m->m_ComponentManager.AllocateNewEntity());
682 : }
683 :
684 0 : entity_id_t CSimulation2::AddEntity(const std::wstring& templateName, entity_id_t preferredId)
685 : {
686 0 : return m->m_ComponentManager.AddEntity(templateName, m->m_ComponentManager.AllocateNewEntity(preferredId));
687 : }
688 :
689 0 : entity_id_t CSimulation2::AddLocalEntity(const std::wstring& templateName)
690 : {
691 0 : return m->m_ComponentManager.AddEntity(templateName, m->m_ComponentManager.AllocateNewLocalEntity());
692 : }
693 :
694 5 : void CSimulation2::DestroyEntity(entity_id_t ent)
695 : {
696 5 : m->m_ComponentManager.DestroyComponentsSoon(ent);
697 5 : }
698 :
699 185 : void CSimulation2::FlushDestroyedEntities()
700 : {
701 185 : m->m_ComponentManager.FlushDestroyedComponents();
702 185 : }
703 :
704 23 : IComponent* CSimulation2::QueryInterface(entity_id_t ent, int iid) const
705 : {
706 23 : return m->m_ComponentManager.QueryInterface(ent, iid);
707 : }
708 :
709 0 : void CSimulation2::PostMessage(entity_id_t ent, const CMessage& msg) const
710 : {
711 0 : m->m_ComponentManager.PostMessage(ent, msg);
712 0 : }
713 :
714 1 : void CSimulation2::BroadcastMessage(const CMessage& msg) const
715 : {
716 1 : m->m_ComponentManager.BroadcastMessage(msg);
717 1 : }
718 :
719 6 : CSimulation2::InterfaceList CSimulation2::GetEntitiesWithInterface(int iid)
720 : {
721 6 : return m->m_ComponentManager.GetEntitiesWithInterface(iid);
722 : }
723 :
724 1 : const CSimulation2::InterfaceListUnordered& CSimulation2::GetEntitiesWithInterfaceUnordered(int iid)
725 : {
726 1 : return m->m_ComponentManager.GetEntitiesWithInterfaceUnordered(iid);
727 : }
728 :
729 7 : const CSimContext& CSimulation2::GetSimContext() const
730 : {
731 7 : return m->m_SimContext;
732 : }
733 :
734 30 : Script::Interface& CSimulation2::GetScriptInterface() const
735 : {
736 30 : return m->m_ComponentManager.GetScriptInterface();
737 : }
738 :
739 3 : void CSimulation2::PreInitGame()
740 : {
741 3 : Script::Request rq(GetScriptInterface());
742 3 : JS::RootedValue global(rq.cx, rq.globalValue());
743 3 : Script::Function::CallVoid(rq, global, "PreInitGame");
744 3 : }
745 :
746 3 : void CSimulation2::InitGame()
747 : {
748 3 : Script::Request rq(GetScriptInterface());
749 3 : JS::RootedValue global(rq.cx, rq.globalValue());
750 :
751 3 : JS::RootedValue settings(rq.cx);
752 3 : JS::RootedValue tmpInitAttributes(rq.cx, GetInitAttributes());
753 3 : Script::GetProperty(rq, tmpInitAttributes, "settings", &settings);
754 :
755 3 : Script::Function::CallVoid(rq, global, "InitGame", settings);
756 3 : }
757 :
758 0 : void CSimulation2::Update(int turnLength)
759 : {
760 0 : std::vector<SimulationCommand> commands;
761 0 : m->Update(turnLength, commands);
762 0 : }
763 :
764 180 : void CSimulation2::Update(int turnLength, const std::vector<SimulationCommand>& commands)
765 : {
766 180 : m->Update(turnLength, commands);
767 180 : }
768 :
769 4 : void CSimulation2::Interpolate(float simFrameLength, float frameOffset, float realFrameLength)
770 : {
771 4 : m->Interpolate(simFrameLength, frameOffset, realFrameLength);
772 4 : }
773 :
774 0 : void CSimulation2::RenderSubmit(SceneCollector& collector, const CFrustum& frustum, bool culling)
775 : {
776 0 : PROFILE3("sim submit");
777 :
778 0 : CMessageRenderSubmit msg(collector, frustum, culling);
779 0 : m->m_ComponentManager.BroadcastMessage(msg);
780 0 : }
781 :
782 0 : float CSimulation2::GetLastFrameOffset() const
783 : {
784 0 : return m->m_LastFrameOffset;
785 : }
786 :
787 0 : void CSimulation2::SetStartupScript(const std::string& code)
788 : {
789 0 : m->m_StartupScript = code;
790 0 : }
791 :
792 0 : const std::string& CSimulation2::GetStartupScript()
793 : {
794 0 : return m->m_StartupScript;
795 : }
796 :
797 3 : void CSimulation2::SetInitAttributes(JS::HandleValue attribs)
798 : {
799 3 : m->m_InitAttributes = attribs;
800 3 : }
801 :
802 3 : JS::Value CSimulation2::GetInitAttributes()
803 : {
804 3 : return m->m_InitAttributes.get();
805 : }
806 :
807 0 : void CSimulation2::GetInitAttributes(JS::MutableHandleValue ret)
808 : {
809 0 : ret.set(m->m_InitAttributes);
810 0 : }
811 :
812 0 : void CSimulation2::SetMapSettings(const std::string& settings)
813 : {
814 0 : Script::ParseJSON(Script::Request(m->m_ComponentManager.GetScriptInterface()), settings, &m->m_MapSettings);
815 0 : }
816 :
817 3 : void CSimulation2::SetMapSettings(JS::HandleValue settings)
818 : {
819 3 : m->m_MapSettings = settings;
820 :
821 3 : m->InitRNGSeedSimulation();
822 3 : m->InitRNGSeedAI();
823 3 : }
824 :
825 0 : std::string CSimulation2::GetMapSettingsString()
826 : {
827 0 : return Script::StringifyJSON(Script::Request(m->m_ComponentManager.GetScriptInterface()), &m->m_MapSettings);
828 : }
829 :
830 0 : void CSimulation2::GetMapSettings(JS::MutableHandleValue ret)
831 : {
832 0 : ret.set(m->m_MapSettings);
833 0 : }
834 :
835 3 : void CSimulation2::LoadPlayerSettings(bool newPlayers)
836 : {
837 3 : Script::Request rq(GetScriptInterface());
838 3 : JS::RootedValue global(rq.cx, rq.globalValue());
839 3 : Script::Function::CallVoid(rq, global, "LoadPlayerSettings", m->m_MapSettings, newPlayers);
840 3 : }
841 :
842 3 : void CSimulation2::LoadMapSettings()
843 : {
844 3 : Script::Request rq(GetScriptInterface());
845 :
846 3 : JS::RootedValue global(rq.cx, rq.globalValue());
847 :
848 : // Initialize here instead of in Update()
849 3 : Script::Function::CallVoid(rq, global, "LoadMapSettings", m->m_MapSettings);
850 :
851 3 : Script::DeepFreezeObject(rq, m->m_InitAttributes);
852 3 : GetScriptInterface().SetGlobal("InitAttributes", m->m_InitAttributes, true, true, true);
853 :
854 3 : if (!m->m_StartupScript.empty())
855 0 : GetScriptInterface().LoadScript(L"map startup script", m->m_StartupScript);
856 :
857 : // Load the trigger scripts after we have loaded the simulation and the map.
858 3 : m->LoadTriggerScripts(m->m_ComponentManager, m->m_MapSettings, &m->m_LoadedScripts);
859 3 : }
860 :
861 3 : PS::Loader::Task CSimulation2::ProgressiveLoad()
862 : {
863 3 : return m->ProgressiveLoad();
864 : }
865 :
866 5 : Status CSimulation2::ReloadChangedFile(const VfsPath& path)
867 : {
868 5 : return m->ReloadChangedFile(path);
869 : }
870 :
871 7 : void CSimulation2::ResetState(bool skipScriptedComponents, bool skipAI)
872 : {
873 7 : m->ResetState(skipScriptedComponents, skipAI);
874 7 : }
875 :
876 9 : bool CSimulation2::ComputeStateHash(std::string& outHash, bool quick)
877 : {
878 9 : return m->m_ComponentManager.ComputeStateHash(outHash, quick);
879 : }
880 :
881 0 : bool CSimulation2::DumpDebugState(std::ostream& stream)
882 : {
883 0 : stream << "sim turn: " << m->m_TurnNumber << std::endl;
884 0 : return m->m_ComponentManager.DumpDebugState(stream, true);
885 : }
886 :
887 9 : bool CSimulation2::SerializeState(std::ostream& stream)
888 : {
889 9 : return m->m_ComponentManager.SerializeState(stream);
890 : }
891 :
892 0 : bool CSimulation2::DeserializeState(std::istream& stream)
893 : {
894 : // TODO: need to make sure the required SYSTEM_ENTITY components get constructed
895 0 : return m->m_ComponentManager.DeserializeState(stream);
896 : }
897 :
898 0 : void CSimulation2::ActivateRejoinTest(turn_id_t turn)
899 : {
900 0 : if (m->m_RejoinTestTurn.has_value())
901 : return;
902 0 : LOGMESSAGERENDER("Rejoin test will activate in {} turns", turn - m->m_TurnNumber);
903 0 : m->m_RejoinTestTurn = turn;
904 : }
905 :
906 0 : std::string CSimulation2::GenerateSchema()
907 : {
908 0 : return m->m_ComponentManager.GenerateSchema();
909 : }
910 :
911 0 : static std::vector<std::string> GetJSONData(const VfsPath& path)
912 : {
913 0 : VfsPaths pathnames;
914 0 : Status ret = vfs::GetPathnames(g_VFS, path, L"*.json", pathnames);
915 0 : if (ret != INFO::OK)
916 : {
917 : // Some error reading directory
918 0 : wchar_t error[200];
919 0 : LOGERROR("Error reading directory '{}': {}", path.string8(),
920 : utf8_from_wstring(StatusDescription(ret, error, ARRAY_SIZE(error))));
921 0 : return std::vector<std::string>();
922 : }
923 :
924 0 : std::vector<std::string> data;
925 0 : for (const VfsPath& p : pathnames)
926 : {
927 : // Load JSON file
928 0 : CVFSFile file;
929 0 : PSRETURN loadStatus = file.Load(g_VFS, p);
930 0 : if (loadStatus != PSRETURN_OK)
931 : {
932 0 : LOGERROR("GetJSONData: Failed to load file '{}': {}", p.string8(),
933 : GetErrorString(loadStatus));
934 0 : continue;
935 0 : }
936 :
937 0 : data.push_back(file.DecodeUTF8()); // assume it's UTF-8
938 0 : }
939 :
940 0 : return data;
941 0 : }
942 :
943 0 : std::vector<std::string> CSimulation2::GetRMSData()
944 : {
945 0 : return GetJSONData(L"maps/random/");
946 : }
947 :
948 0 : std::vector<std::string> CSimulation2::GetVictoryConditiondData()
949 : {
950 0 : return GetJSONData(L"simulation/data/settings/victory_conditions/");
951 : }
952 :
953 0 : static std::string ReadJSON(const VfsPath& path)
954 : {
955 0 : if (!VfsFileExists(path))
956 : {
957 0 : LOGERROR("File '{}' does not exist", path.string8());
958 0 : return std::string();
959 : }
960 :
961 : // Load JSON file
962 0 : CVFSFile file;
963 0 : PSRETURN ret = file.Load(g_VFS, path);
964 0 : if (ret != PSRETURN_OK)
965 : {
966 0 : LOGERROR("Failed to load file '{}': {}", path.string8(), GetErrorString(ret));
967 0 : return std::string();
968 : }
969 :
970 0 : return file.DecodeUTF8(); // assume it's UTF-8
971 0 : }
972 :
973 0 : std::string CSimulation2::GetPlayerDefaults()
974 : {
975 0 : return ReadJSON(L"simulation/data/settings/player_defaults.json");
976 : }
977 :
978 0 : std::string CSimulation2::GetMapSizes()
979 : {
980 0 : return ReadJSON(L"simulation/data/settings/map_sizes.json");
981 : }
982 :
983 0 : std::string CSimulation2::GetAIData()
984 : {
985 0 : const Script::Interface& scriptInterface = GetScriptInterface();
986 0 : Script::Request rq(scriptInterface);
987 0 : JS::RootedValue aiData(rq.cx, ICmpAIManager::GetAIs(scriptInterface));
988 :
989 : // Build single JSON string with array of AI data
990 0 : JS::RootedValue ais(rq.cx);
991 :
992 0 : if (!Script::CreateObject(rq, &ais, "AIData", aiData))
993 0 : return std::string();
994 :
995 0 : return Script::StringifyJSON(rq, &ais);
996 0 : }
|