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 "Replay.h"
21 :
22 : #include "lib/code_generation.h"
23 : #include "lib/debug.h"
24 : #include "lib/file/file_system.h"
25 : #include "lib/path.h"
26 : #include "lib/timer.h"
27 : #include "ps/CLogger.h"
28 : #include "ps/CStr.h"
29 : #include "ps/Errors.h"
30 : #include "ps/Game.h"
31 : #include "ps/GameSetup/CmdLineArgs.h"
32 : #include "ps/GameSetup/GameSetup.h"
33 : #include "ps/GameSetup/Paths.h"
34 : #include "ps/Loader.h"
35 : #include "ps/Mod.h"
36 : #include "ps/Profile.h"
37 : #include "ps/ProfileViewer.h"
38 : #include "ps/Profiler2.h"
39 : #include "ps/Pyrogenesis.h"
40 : #include "ps/Util.h"
41 : #include "ps/VisualReplay.h"
42 : #include "scriptinterface/JSON.h"
43 : #include "scriptinterface/Object.h"
44 : #include "scriptinterface/Context.h"
45 : #include "scriptinterface/Interface.h"
46 : #include "scriptinterface/Request.h"
47 : #include "scriptinterface/Stats.h"
48 : #include "simulation2/Simulation2.h"
49 : #include "simulation2/components/ICmpGuiInterface.h"
50 : #include "simulation2/helpers/Player.h"
51 : #include "simulation2/helpers/SimulationCommand.h"
52 : #include "simulation2/system/Component.h"
53 : #include "simulation2/system/Entity.h"
54 :
55 : #include <ctime>
56 : #include <fstream>
57 : #include <memory>
58 :
59 : /**
60 : * Number of turns between two saved profiler snapshots.
61 : * Keep in sync with source/tools/replayprofile/graph.js
62 : */
63 : static const int PROFILE_TURN_INTERVAL = 20;
64 :
65 0 : CReplayLogger::CReplayLogger(const Script::Interface& scriptInterface) :
66 0 : m_ScriptInterface(scriptInterface), m_Stream(NULL)
67 : {
68 0 : }
69 :
70 0 : CReplayLogger::~CReplayLogger()
71 : {
72 0 : delete m_Stream;
73 0 : }
74 :
75 0 : void CReplayLogger::StartGame(JS::MutableHandleValue attribs)
76 : {
77 0 : Script::Request rq(m_ScriptInterface);
78 :
79 : // Add timestamp, since the file-modification-date can change
80 0 : Script::SetProperty(rq, attribs, "timestamp", (double)std::time(nullptr));
81 :
82 : // Add engine version and currently loaded mods for sanity checks when replaying
83 0 : Script::SetProperty(rq, attribs, "engine_serialization_version", PS_SERIALIZATION_VERSION);
84 0 : JS::RootedValue mods(rq.cx);
85 0 : Script::ToJSVal(rq, &mods, g_Mods.GetEnabledModsData());
86 0 : Script::SetProperty(rq, attribs, "mods", mods);
87 :
88 0 : m_Directory = createDateIndexSubdirectory(VisualReplay::GetDirectoryPath());
89 0 : debug_printf("Replay written to '%s'\n", m_Directory.string8().c_str());
90 :
91 0 : m_Stream = new std::ofstream(OsString(m_Directory / L"commands.txt"), std::ofstream::out | std::ofstream::trunc);
92 0 : *m_Stream << "start " << Script::StringifyJSON(rq, attribs, false) << "\n";
93 0 : }
94 :
95 0 : void CReplayLogger::Turn(std::uint32_t n, std::uint32_t turnLength, std::vector<SimulationCommand>& commands)
96 : {
97 0 : Script::Request rq(m_ScriptInterface);
98 :
99 0 : *m_Stream << "turn " << n << " " << turnLength << "\n";
100 :
101 0 : for (SimulationCommand& command : commands)
102 0 : *m_Stream << "cmd " << command.player << " " << Script::StringifyJSON(rq, &command.data, false) << "\n";
103 :
104 0 : *m_Stream << "end\n";
105 0 : m_Stream->flush();
106 0 : }
107 :
108 0 : void CReplayLogger::Hash(const std::string& hash, bool quick)
109 : {
110 0 : if (quick)
111 0 : *m_Stream << "hash-quick " << Hexify(hash) << "\n";
112 : else
113 0 : *m_Stream << "hash " << Hexify(hash) << "\n";
114 0 : }
115 :
116 0 : void CReplayLogger::SaveMetadata(const CSimulation2& simulation)
117 : {
118 0 : CmpPtr<ICmpGuiInterface> cmpGuiInterface(simulation, SYSTEM_ENTITY);
119 0 : if (!cmpGuiInterface)
120 : {
121 0 : LOGERROR("Could not save replay metadata!");
122 0 : return;
123 : }
124 :
125 0 : Script::Interface& scriptInterface = simulation.GetScriptInterface();
126 0 : Script::Request rq(scriptInterface);
127 :
128 0 : JS::RootedValue arg(rq.cx);
129 0 : JS::RootedValue metadata(rq.cx);
130 0 : cmpGuiInterface->ScriptCall(INVALID_PLAYER, L"GetReplayMetadata", arg, &metadata);
131 :
132 0 : const OsPath fileName = g_Game->GetReplayLogger().GetDirectory() / L"metadata.json";
133 0 : CreateDirectories(fileName.Parent(), 0700);
134 :
135 0 : std::ofstream stream (OsString(fileName), std::ofstream::out | std::ofstream::trunc);
136 0 : if (stream)
137 : {
138 0 : stream << Script::StringifyJSON(rq, &metadata, false);
139 0 : stream.close();
140 0 : debug_printf("Replay metadata written to '%s'\n", fileName.string8().c_str());
141 : }
142 : else
143 0 : debug_printf("Failed to write replay metadata to '%s'\n", fileName.string8().c_str());
144 :
145 0 : }
146 :
147 0 : OsPath CReplayLogger::GetDirectory() const
148 : {
149 0 : return m_Directory;
150 : }
151 :
152 : ////////////////////////////////////////////////////////////////
153 :
154 0 : CReplayPlayer::CReplayPlayer() :
155 0 : m_Stream(NULL)
156 : {
157 0 : }
158 :
159 0 : CReplayPlayer::~CReplayPlayer()
160 : {
161 0 : delete m_Stream;
162 0 : }
163 :
164 0 : void CReplayPlayer::Load(const OsPath& path)
165 : {
166 0 : ENSURE(!m_Stream);
167 :
168 0 : m_Stream = new std::ifstream(OsString(path));
169 0 : ENSURE(m_Stream->good());
170 0 : }
171 :
172 : namespace
173 : {
174 0 : CStr ModListToString(const std::vector<const Mod::ModData*>& list)
175 : {
176 0 : CStr text;
177 0 : for (const Mod::ModData* data : list)
178 0 : text += data->m_Pathname + " (" + data->m_Version + ")\n";
179 0 : return text;
180 0 : }
181 :
182 0 : void CheckReplayMods(const std::vector<Mod::ModData>& replayMods)
183 : {
184 0 : std::vector<const Mod::ModData*> replayData;
185 0 : replayData.reserve(replayMods.size());
186 0 : for (const Mod::ModData& data : replayMods)
187 0 : replayData.push_back(&data);
188 0 : if (!Mod::AreModsPlayCompatible(g_Mods.GetEnabledModsData(), replayData))
189 : {
190 0 : LOGWARNING("Incompatible replay mods detected.\nThe mods of the replay are:\n{}\n"
191 : "These mods are enabled:\n{}", ModListToString(replayData),
192 : ModListToString(g_Mods.GetEnabledModsData()));
193 : }
194 0 : }
195 : } // anonymous namespace
196 :
197 0 : void CReplayPlayer::Replay(const int serializationtestturn, const int rejointestturn, const bool ooslog,
198 : const bool testHashFull, const bool testHashQuick)
199 : {
200 0 : ENSURE(m_Stream);
201 :
202 0 : new CProfileViewer;
203 0 : new CProfileManager;
204 0 : g_ScriptStatsTable = new Script::CScriptStatsTable;
205 0 : g_ProfileViewer.AddRootTable(g_ScriptStatsTable);
206 :
207 0 : const int contextSize = 384 * 1024 * 1024;
208 0 : const int heapGrowthBytesGCTrigger = 12 * 1024 * 1024;
209 0 : g_ScriptContext = std::make_shared<Script::Context>(contextSize, heapGrowthBytesGCTrigger);
210 :
211 0 : std::vector<SimulationCommand> commands;
212 0 : std::uint32_t turn = 0;
213 0 : std::uint32_t turnLength = 0;
214 :
215 0 : {
216 0 : std::string type;
217 :
218 0 : while ((*m_Stream >> type).good())
219 : {
220 0 : if (type == "start")
221 : {
222 0 : std::string attribsStr;
223 0 : {
224 0 : Script::Interface scriptInterface("Engine", "Replay", g_ScriptContext);
225 0 : Script::Request rq(scriptInterface);
226 0 : std::getline(*m_Stream, attribsStr);
227 0 : JS::RootedValue attribs(rq.cx);
228 0 : if (!Script::ParseJSON(rq, attribsStr, &attribs))
229 : {
230 0 : LOGERROR("Error parsing JSON attributes: {}", attribsStr);
231 : // TODO: do something cleverer than crashing.
232 0 : ENSURE(false);
233 : }
234 :
235 : // Load the mods specified in the replay.
236 0 : std::vector<Mod::ModData> replayMods;
237 0 : if (!Script::GetProperty(rq, attribs, "mods", replayMods))
238 : {
239 0 : LOGERROR("Could not get replay mod information.");
240 : // TODO: do something cleverer than crashing.
241 0 : ENSURE(false);
242 : }
243 :
244 0 : std::vector<CStr> mods;
245 0 : for (const Mod::ModData& data : replayMods)
246 0 : mods.emplace_back(data.m_Pathname);
247 :
248 : // Ignore the return value, we check below.
249 0 : g_Mods.UpdateAvailableMods(scriptInterface);
250 0 : g_Mods.EnableMods(mods, false);
251 0 : CheckReplayMods(replayMods);
252 :
253 0 : MountMods(Paths(g_CmdLineArgs), g_Mods.GetEnabledMods());
254 0 : }
255 :
256 0 : if (serializationtestturn >= 0 && rejointestturn >= 0)
257 0 : LOGERROR("serializationtest and rejointest can't be activ at the same time.");
258 :
259 0 : SimulationDebugOptions debugOption{};
260 0 : if (serializationtestturn >= 0)
261 : {
262 0 : debugOption.test =
263 0 : SimulationDebugOptions::SerializationTest{serializationtestturn};
264 : }
265 0 : if (rejointestturn >= 0)
266 0 : debugOption.test = SimulationDebugOptions::RejoinTest{rejointestturn};
267 0 : if (ooslog)
268 0 : debugOption.oosLog = true;
269 :
270 0 : g_Game = new CGame(false, debugOption);
271 :
272 0 : Script::Request rq(g_Game->GetSimulation2()->GetScriptInterface());
273 0 : JS::RootedValue attribs(rq.cx);
274 0 : ENSURE(Script::ParseJSON(rq, attribsStr, &attribs));
275 0 : g_Game->StartGame(&attribs, "");
276 :
277 : // TODO: Non progressive load can fail - need a decent way to handle this
278 0 : PS::Loader::NonprogressiveLoad();
279 :
280 0 : PSRETURN ret = g_Game->ReallyStartGame();
281 0 : ENSURE(ret == PSRETURN_OK);
282 0 : }
283 0 : else if (type == "turn")
284 : {
285 0 : *m_Stream >> turn >> turnLength;
286 0 : debug_printf("Turn %u (%u)...\n", turn, turnLength);
287 : }
288 0 : else if (type == "cmd")
289 : {
290 0 : player_id_t player;
291 0 : *m_Stream >> player;
292 :
293 0 : std::string line;
294 0 : std::getline(*m_Stream, line);
295 0 : Script::Request rq(g_Game->GetSimulation2()->GetScriptInterface());
296 0 : JS::RootedValue data(rq.cx);
297 0 : Script::ParseJSON(rq, line, &data);
298 0 : Script::DeepFreezeObject(rq, data);
299 0 : commands.emplace_back(SimulationCommand(player, rq.cx, data));
300 0 : }
301 0 : else if (type == "hash" || type == "hash-quick")
302 : {
303 0 : std::string replayHash;
304 0 : *m_Stream >> replayHash;
305 0 : TestHash(type, replayHash, testHashFull, testHashQuick);
306 0 : }
307 0 : else if (type == "end")
308 : {
309 0 : {
310 0 : g_Profiler2.RecordFrameStart();
311 0 : PROFILE2("frame");
312 0 : g_Profiler2.IncrementFrameNumber();
313 0 : PROFILE2_ATTR("%d", g_Profiler2.GetFrameNumber());
314 :
315 0 : g_Game->GetSimulation2()->Update(turnLength, commands);
316 0 : commands.clear();
317 0 : }
318 :
319 0 : g_Profiler.Frame();
320 :
321 0 : if (turn % PROFILE_TURN_INTERVAL == 0)
322 0 : g_ProfileViewer.SaveToFile();
323 : }
324 : else
325 0 : debug_printf("Unrecognized replay token %s\n", type.c_str());
326 : }
327 0 : }
328 :
329 0 : SAFE_DELETE(m_Stream);
330 :
331 0 : g_Profiler2.SaveToFile();
332 :
333 0 : std::string hash;
334 0 : bool ok = g_Game->GetSimulation2()->ComputeStateHash(hash, false);
335 0 : ENSURE(ok);
336 0 : debug_printf("# Final state: %s\n", Hexify(hash).c_str());
337 :
338 0 : SAFE_DELETE(g_Game);
339 :
340 : // Must be explicitly destructed here to avoid callbacks from the JSAPI trying to use g_Profiler2 when
341 : // it's already destructed.
342 0 : g_ScriptContext.reset();
343 :
344 0 : delete &g_Profiler;
345 0 : delete &g_ProfileViewer;
346 0 : SAFE_DELETE(g_ScriptStatsTable);
347 0 : }
348 :
349 0 : void CReplayPlayer::TestHash(const std::string& hashType, const std::string& replayHash, const bool testHashFull, const bool testHashQuick)
350 : {
351 0 : bool quick = (hashType == "hash-quick");
352 0 : if ((quick && !testHashQuick) || (!quick && !testHashFull))
353 0 : return;
354 :
355 0 : std::string hash;
356 0 : ENSURE(g_Game->GetSimulation2()->ComputeStateHash(hash, quick));
357 :
358 0 : std::string hexHash = Hexify(hash);
359 :
360 0 : if (hexHash == replayHash)
361 0 : debug_printf("%s ok (%s)\n", hashType.c_str(), hexHash.c_str());
362 : else
363 0 : debug_printf("%s MISMATCH (%s != %s)\n", hashType.c_str(), hexHash.c_str(), replayHash.c_str());
364 0 : }
|