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 "Game.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/GameView.h"
24 : #include "graphics/LOSTexture.h"
25 : #include "graphics/UnitManager.h"
26 : #include "gui/CGUI.h"
27 : #include "gui/GUIManager.h"
28 : #include "lib/code_generation.h"
29 : #include "lib/debug.h"
30 : #include "network/NetClient.h"
31 : #include "ps/CLogger.h"
32 : #include "ps/CStr.h"
33 : #include "ps/GameSetup/GameSetup.h"
34 : #include "ps/Loader.h"
35 : #include "ps/Profile.h"
36 : #include "ps/Replay.h"
37 : #include "ps/VideoMode.h"
38 : #include "ps/World.h"
39 : #include "renderer/Renderer.h"
40 : #include "renderer/SceneRenderer.h"
41 : #include "renderer/TimeManager.h"
42 : #include "renderer/WaterManager.h"
43 : #include "scriptinterface/FunctionWrapper.h"
44 : #include "scriptinterface/JSON.h"
45 : #include "scriptinterface/Object.h"
46 : #include "scriptinterface/Context.h"
47 : #include "scriptinterface/Interface.h"
48 : #include "scriptinterface/Request.h"
49 : #include "simulation2/Simulation2.h"
50 : #include "simulation2/components/ICmpPlayer.h"
51 : #include "simulation2/components/ICmpPlayerManager.h"
52 : #include "simulation2/system/Component.h"
53 : #include "simulation2/system/Entity.h"
54 : #include "simulation2/system/LocalTurnManager.h"
55 : #include "simulation2/system/ReplayTurnManager.h"
56 : #include "simulation2/system/TurnManager.h"
57 : #include "tools/atlas/GameInterface/GameLoop.h"
58 :
59 : #include <cstddef>
60 : #include <fstream>
61 : #include <js/RootingAPI.h>
62 : #include <js/Value.h>
63 : #include <memory>
64 : #include <sstream>
65 : #include <utility>
66 :
67 : extern GameLoopState* g_AtlasGameLoop;
68 :
69 : /**
70 : * Globally accessible pointer to the CGame object.
71 : **/
72 : CGame *g_Game=NULL;
73 :
74 : const CStr CGame::EventNameSimulationUpdate = "SimulationUpdate";
75 :
76 : /**
77 : * Constructor
78 : *
79 : **/
80 3 : CGame::CGame(bool replayLog, const SimulationDebugOptions debugOptions):
81 3 : m_World(new CWorld(*this)),
82 3 : m_Simulation2{new CSimulation2{&m_World->GetUnitManager(), *g_ScriptContext, &m_World->GetTerrain(),
83 6 : CSimulation2::DEFAULT_SCRIPTS, debugOptions}},
84 : // TODO: we need to remove that global dependency. Maybe the game view
85 : // should be created outside only if needed.
86 3 : m_GameView(CRenderer::IsInitialised() ? new CGameView(g_VideoMode.GetBackendDevice(), this) : nullptr),
87 3 : m_GameStarted(false),
88 3 : m_CheatsEnabled(false),
89 3 : m_Paused(false),
90 3 : m_SimRate(1.0f),
91 3 : m_PlayerID(-1),
92 3 : m_ViewedPlayerID(-1),
93 3 : m_IsVisualReplay(false),
94 3 : m_ReplayStream(NULL)
95 : {
96 : // TODO: should use CDummyReplayLogger unless activated by cmd-line arg, perhaps?
97 3 : if (replayLog)
98 0 : m_ReplayLogger = new CReplayLogger(m_Simulation2->GetScriptInterface());
99 : else
100 3 : m_ReplayLogger = new CDummyReplayLogger();
101 :
102 : // Need to set the CObjectManager references after various objects have
103 : // been initialised, so do it here rather than via the initialisers above.
104 3 : if (m_GameView)
105 0 : m_World->GetUnitManager().SetObjectManager(m_GameView->GetObjectManager());
106 :
107 3 : m_TurnManager = new CLocalTurnManager(*m_Simulation2, GetReplayLogger()); // this will get replaced if we're a net server/client
108 3 : }
109 :
110 : /**
111 : * Destructor
112 : *
113 : **/
114 3 : CGame::~CGame()
115 : {
116 : // Again, the in-game call tree is going to be different to the main menu one.
117 3 : if (CProfileManager::IsInitialised())
118 3 : g_Profiler.StructuralReset();
119 :
120 3 : if (m_ReplayLogger && m_GameStarted)
121 3 : m_ReplayLogger->SaveMetadata(*m_Simulation2);
122 :
123 3 : delete m_TurnManager;
124 3 : delete m_GameView;
125 3 : delete m_Simulation2;
126 3 : delete m_World;
127 3 : delete m_ReplayLogger;
128 3 : delete m_ReplayStream;
129 3 : }
130 :
131 0 : void CGame::SetTurnManager(CTurnManager* turnManager)
132 : {
133 0 : if (m_TurnManager)
134 0 : delete m_TurnManager;
135 :
136 0 : m_TurnManager = turnManager;
137 :
138 0 : if (m_TurnManager)
139 0 : m_TurnManager->SetPlayerID(m_PlayerID);
140 0 : }
141 :
142 0 : int CGame::LoadVisualReplayData()
143 : {
144 0 : ENSURE(m_IsVisualReplay);
145 0 : ENSURE(!m_ReplayPath.empty());
146 0 : ENSURE(m_ReplayStream);
147 :
148 0 : CReplayTurnManager* replayTurnMgr = static_cast<CReplayTurnManager*>(GetTurnManager());
149 :
150 0 : std::uint32_t currentTurn = 0;
151 0 : std::string type;
152 0 : while ((*m_ReplayStream >> type).good())
153 : {
154 0 : if (type == "turn")
155 : {
156 0 : std::uint32_t turn = 0;
157 0 : std::uint32_t turnLength = 0;
158 0 : *m_ReplayStream >> turn >> turnLength;
159 0 : ENSURE(turn == currentTurn && "You tried to replay a commands.txt file of a rejoined client. Please use the host's file.");
160 0 : replayTurnMgr->StoreReplayTurnLength(currentTurn, turnLength);
161 : }
162 0 : else if (type == "cmd")
163 : {
164 0 : player_id_t player;
165 0 : *m_ReplayStream >> player;
166 :
167 0 : std::string line;
168 0 : std::getline(*m_ReplayStream, line);
169 0 : replayTurnMgr->StoreReplayCommand(currentTurn, player, line);
170 0 : }
171 0 : else if (type == "hash" || type == "hash-quick")
172 : {
173 0 : bool quick = (type == "hash-quick");
174 0 : std::string replayHash;
175 0 : *m_ReplayStream >> replayHash;
176 0 : replayTurnMgr->StoreReplayHash(currentTurn, replayHash, quick);
177 0 : }
178 0 : else if (type == "end")
179 0 : ++currentTurn;
180 : else
181 0 : CancelLoad(L"Failed to load replay data (unrecognized content)");
182 : }
183 0 : SAFE_DELETE(m_ReplayStream);
184 0 : m_FinalReplayTurn = currentTurn > 0 ? currentTurn - 1 : 0;
185 0 : replayTurnMgr->StoreFinalReplayTurn(m_FinalReplayTurn);
186 0 : return 0;
187 : }
188 :
189 0 : bool CGame::StartVisualReplay(const OsPath& replayPath)
190 : {
191 0 : debug_printf("Starting to replay %s\n", replayPath.string8().c_str());
192 :
193 0 : m_IsVisualReplay = true;
194 :
195 0 : SetTurnManager(new CReplayTurnManager(*m_Simulation2, GetReplayLogger()));
196 :
197 0 : m_ReplayPath = replayPath;
198 0 : m_ReplayStream = new std::ifstream(OsString(replayPath));
199 :
200 0 : std::string type;
201 0 : ENSURE((*m_ReplayStream >> type).good() && type == "start");
202 :
203 0 : std::string line;
204 0 : std::getline(*m_ReplayStream, line);
205 :
206 0 : const Script::Interface& scriptInterface = m_Simulation2->GetScriptInterface();
207 0 : Script::Request rq(scriptInterface);
208 :
209 0 : JS::RootedValue attribs(rq.cx);
210 0 : Script::ParseJSON(rq, line, &attribs);
211 0 : StartGame(&attribs, "");
212 :
213 0 : return true;
214 0 : }
215 :
216 : /**
217 : * Initializes the game with the set of attributes provided.
218 : * Makes calls to initialize the game view, world, and simulation objects.
219 : * Calls are made to facilitate progress reporting of the initialization.
220 : **/
221 3 : void CGame::RegisterInit(const JS::HandleValue attribs, const std::string& savedState)
222 : {
223 3 : const Script::Interface& scriptInterface = m_Simulation2->GetScriptInterface();
224 3 : Script::Request rq(scriptInterface);
225 :
226 3 : const bool isSavedGame{!savedState.empty()};
227 :
228 3 : m_Simulation2->SetInitAttributes(attribs);
229 :
230 3 : std::string mapType;
231 3 : Script::GetProperty(rq, attribs, "mapType", mapType);
232 :
233 3 : JS::RootedValue settings(rq.cx);
234 3 : Script::GetProperty(rq, attribs, "settings", &settings);
235 :
236 6 : if (Script::HasProperty(rq, attribs, "settings") &&
237 3 : Script::HasProperty(rq, settings, "CheatsEnabled"))
238 : {
239 3 : Script::GetProperty(rq, settings, "CheatsEnabled", m_CheatsEnabled);
240 : }
241 :
242 3 : float speed;
243 3 : if (Script::HasProperty(rq, attribs, "gameSpeed"))
244 : {
245 0 : if (Script::GetProperty(rq, attribs, "gameSpeed", speed))
246 0 : SetSimRate(speed);
247 : else
248 0 : LOGERROR("GameSpeed could not be parsed.");
249 : }
250 :
251 3 : PS::Loader::BeginRegistering();
252 :
253 6 : PS::Loader::Register([this]
254 : {
255 3 : return m_Simulation2->ProgressiveLoad();
256 : }, L"Simulation init", 1000);
257 :
258 : // RC, 040804 - GameView needs to be initialized before World, otherwise GameView initialization
259 : // overwrites anything stored in the map file that gets loaded by CWorld::Initialize with default
260 : // values. At the minute, it's just lighting settings, but could be extended to store camera position.
261 : // Storing lighting settings in the game view seems a little odd, but it's no big deal; maybe move it at
262 : // some point to be stored in the world object?
263 3 : if (m_GameView)
264 0 : m_GameView->RegisterInit();
265 :
266 3 : if (mapType == "random")
267 : {
268 : // Load random map attributes
269 0 : std::wstring scriptFile;
270 0 : Script::GetProperty(rq, attribs, "script", scriptFile);
271 :
272 0 : m_World->RegisterInitRMS(scriptFile, scriptInterface.GetContext(), settings, m_PlayerID);
273 0 : }
274 : else
275 : {
276 3 : std::wstring mapFile;
277 3 : Script::GetProperty(rq, attribs, "map", mapFile);
278 :
279 9 : m_World->RegisterInit(mapFile, scriptInterface.GetContext(), settings, m_PlayerID);
280 3 : }
281 3 : if (m_GameView)
282 0 : PS::Loader::Register([]() -> PS::Loader::Task
283 : {
284 : co_return g_Renderer.GetSceneRenderer().GetWaterManager().LoadWaterTextures();
285 0 : }, L"LoadWaterTextures", 80);
286 :
287 3 : if (isSavedGame)
288 0 : PS::Loader::Register(std::bind_front(
289 0 : [](CGame* game, const std::string& state) -> PS::Loader::Task
290 : {
291 : co_return game->LoadInitialState(state);
292 0 : }, this, savedState), L"Loading game", 1000);
293 :
294 3 : if (m_IsVisualReplay)
295 0 : PS::Loader::Register(std::bind_front([](CGame* game) -> PS::Loader::Task
296 : {
297 : co_return game->LoadVisualReplayData();
298 0 : }, this), L"Loading visual replay data", 1000);
299 :
300 : // Call the script function InitGame only for new games, not saved games
301 3 : if (!isSavedGame)
302 : {
303 : // Perform some simulation initializations (replace skirmish entities, explore territories, etc.)
304 : // that needs to be done before setting up the AI and shouldn't be done in Atlas
305 3 : if (!g_AtlasGameLoop->running)
306 : {
307 6 : PS::Loader::Register(std::bind_front([](CGame* game) -> PS::Loader::Task
308 : {
309 : game->m_Simulation2->PreInitGame();
310 : co_return 0;
311 6 : }, this), L"PreInitGame", 5000);
312 : }
313 :
314 6 : PS::Loader::Register(std::bind_front([](CGame* game) -> PS::Loader::Task
315 : {
316 : game->m_Simulation2->InitGame();
317 : co_return 0;
318 6 : }, this), L"InitGame", 4000);
319 : }
320 :
321 3 : PS::Loader::EndRegistering();
322 3 : }
323 :
324 0 : int CGame::LoadInitialState(const std::string& savedState)
325 : {
326 0 : std::stringstream stream(savedState);
327 :
328 0 : bool ok = m_Simulation2->DeserializeState(stream);
329 0 : if (!ok)
330 : {
331 0 : CancelLoad(L"Failed to load saved game state. It might have been\nsaved with an incompatible version of the game.");
332 0 : return 0;
333 : }
334 :
335 : return 0;
336 0 : }
337 :
338 : /**
339 : * Game initialization has been completed. Set game started flag and start the session.
340 : *
341 : * @return PSRETURN 0
342 : **/
343 3 : PSRETURN CGame::ReallyStartGame()
344 : {
345 : // We need to do an initial Interpolate call to set up all the models etc,
346 : // because Update might never interpolate (e.g. if the game starts paused)
347 : // and we could end up rendering before having set up any models (so they'd
348 : // all be invisible)
349 6 : Interpolate(0, 0);
350 :
351 : // Run a shrinking GC to reset the memory before starting the game proper.
352 : // This also clears JIT code, which seems like a good idea as the game init
353 : // might have different patterns to the game itself.
354 3 : m_Simulation2->GetScriptInterface().GetContext().ShrinkingGC();
355 :
356 3 : m_GameStarted = true;
357 :
358 : // Preload resources to avoid blinking on a first game frame.
359 3 : if (CRenderer::IsInitialised())
360 0 : g_Renderer.PreloadResourcesBeforeNextFrame();
361 :
362 3 : if (g_NetClient)
363 0 : g_NetClient->LoadFinished();
364 :
365 : // Call the reallyStartGame GUI function, but only if it exists
366 3 : if (g_GUI && g_GUI->GetPageCount())
367 : {
368 0 : std::shared_ptr<Script::Interface> scriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface();
369 0 : Script::Request rq(scriptInterface);
370 :
371 0 : JS::RootedValue global(rq.cx, rq.globalValue());
372 0 : if (Script::HasProperty(rq, global, "reallyStartGame"))
373 0 : Script::Function::CallVoid(rq, global, "reallyStartGame");
374 0 : }
375 :
376 :
377 : // The call tree we've built for pregame probably isn't useful in-game.
378 3 : if (CProfileManager::IsInitialised())
379 3 : g_Profiler.StructuralReset();
380 :
381 3 : return 0;
382 : }
383 :
384 0 : int CGame::GetPlayerID()
385 : {
386 0 : return m_PlayerID;
387 : }
388 :
389 0 : void CGame::SetPlayerID(player_id_t playerID)
390 : {
391 0 : m_PlayerID = playerID;
392 0 : m_ViewedPlayerID = playerID;
393 :
394 0 : if (m_TurnManager)
395 0 : m_TurnManager->SetPlayerID(m_PlayerID);
396 0 : }
397 :
398 5607 : int CGame::GetViewedPlayerID()
399 : {
400 5607 : return m_ViewedPlayerID;
401 : }
402 :
403 0 : void CGame::SetViewedPlayerID(player_id_t playerID)
404 : {
405 0 : m_ViewedPlayerID = playerID;
406 0 : }
407 :
408 0 : bool CGame::CheatsEnabled() const
409 : {
410 0 : return m_CheatsEnabled;
411 : }
412 :
413 3 : void CGame::StartGame(JS::MutableHandleValue attribs, const std::string& savedState)
414 : {
415 3 : if (m_ReplayLogger)
416 3 : m_ReplayLogger->StartGame(attribs);
417 :
418 3 : RegisterInit(attribs, savedState);
419 3 : }
420 :
421 : // TODO: doInterpolate is optional because Atlas interpolates explicitly,
422 : // so that it has more control over the update rate. The game might want to
423 : // do the same, and then doInterpolate should be redundant and removed.
424 :
425 208 : void CGame::Update(const double deltaRealTime, bool doInterpolate)
426 : {
427 208 : if (m_Paused || !m_TurnManager)
428 : return;
429 :
430 208 : const double deltaSimTime = deltaRealTime * m_SimRate;
431 :
432 208 : if (deltaSimTime)
433 : {
434 : // At the normal sim rate, we currently want to render at least one
435 : // frame per simulation turn, so let maxTurns be 1. But for fast-forward
436 : // sim rates we want to allow more, so it's not bounded by framerate,
437 : // so just use the sim rate itself as the number of turns per frame.
438 208 : size_t maxTurns = (size_t)m_SimRate;
439 :
440 208 : if (m_TurnManager->Update(deltaSimTime, maxTurns,
441 416 : std::bind_front(&CGUIManager::SendEventToAll, g_GUI)))
442 : {
443 150 : {
444 150 : PROFILE3("gui sim update");
445 150 : g_GUI->SendEventToAll(EventNameSimulationUpdate);
446 150 : }
447 :
448 150 : if (m_GameView)
449 0 : m_GameView->GetLOSTexture().MakeDirty();
450 : }
451 :
452 208 : if (CRenderer::IsInitialised())
453 0 : g_Renderer.GetTimeManager().Update(deltaSimTime);
454 : }
455 :
456 208 : if (doInterpolate)
457 0 : m_TurnManager->Interpolate(deltaSimTime, deltaRealTime);
458 : }
459 :
460 3 : void CGame::Interpolate(float simFrameLength, float realFrameLength)
461 : {
462 3 : if (!m_TurnManager)
463 : return;
464 :
465 3 : m_TurnManager->Interpolate(simFrameLength, realFrameLength);
466 : }
467 :
468 :
469 : static CColor BrokenColor(0.3f, 0.3f, 0.3f, 1.0f);
470 :
471 0 : void CGame::CachePlayerColors()
472 : {
473 0 : m_PlayerColors.clear();
474 :
475 0 : CmpPtr<ICmpPlayerManager> cmpPlayerManager(*m_Simulation2, SYSTEM_ENTITY);
476 0 : if (!cmpPlayerManager)
477 0 : return;
478 :
479 0 : int numPlayers = cmpPlayerManager->GetNumPlayers();
480 0 : m_PlayerColors.resize(numPlayers);
481 :
482 0 : for (int i = 0; i < numPlayers; ++i)
483 : {
484 0 : CmpPtr<ICmpPlayer> cmpPlayer(*m_Simulation2, cmpPlayerManager->GetPlayerByID(i));
485 0 : if (!cmpPlayer)
486 0 : m_PlayerColors[i] = BrokenColor;
487 : else
488 0 : m_PlayerColors[i] = cmpPlayer->GetDisplayedColor();
489 : }
490 : }
491 :
492 0 : const CColor& CGame::GetPlayerColor(player_id_t player) const
493 : {
494 0 : if (player < 0 || player >= (int)m_PlayerColors.size())
495 : return BrokenColor;
496 :
497 0 : return m_PlayerColors[player];
498 : }
499 :
500 0 : bool CGame::IsGameFinished() const
501 : {
502 0 : for (const std::pair<entity_id_t, IComponent*>& p : m_Simulation2->GetEntitiesWithInterface(IID_Player))
503 : {
504 0 : CmpPtr<ICmpPlayer> cmpPlayer(*m_Simulation2, p.first);
505 0 : if (cmpPlayer && cmpPlayer->HasWon())
506 0 : return true;
507 0 : }
508 :
509 0 : return false;
510 : }
511 :
512 : // This function is implemented so that mods can't change it's result. See ICmpPlayer.cpp
513 0 : bool CGame::PlayerFinished(player_id_t playerID) const
514 : {
515 0 : CmpPtr<ICmpPlayerManager> cmpPlayerManager(*m_Simulation2, SYSTEM_ENTITY);
516 0 : if (!cmpPlayerManager)
517 : return false;
518 :
519 0 : CmpPtr<ICmpPlayer> cmpPlayer(*m_Simulation2, cmpPlayerManager->GetPlayerByID(playerID));
520 0 : return cmpPlayer && !cmpPlayer->IsActive();
521 : }
|