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 "TurnManager.h"
21 :
22 : #include "lib/debug.h"
23 : #include "maths/MathUtil.h"
24 : #include "ps/CLogger.h"
25 : #include "ps/Profile.h"
26 : #include "ps/Profiler2.h"
27 : #include "ps/Replay.h"
28 : #include "scriptinterface/Object.h"
29 : #include "scriptinterface/Request.h"
30 : #include "scriptinterface/StructuredClone.h"
31 : #include "simulation2/Simulation2.h"
32 :
33 : #include <algorithm>
34 : #include <iterator>
35 : #include <js/ValueArray.h>
36 : #include <limits>
37 : #include <sstream>
38 : #include <utility>
39 :
40 : #if 0
41 : #define NETTURN_LOG(...) debug_printf(__VA_ARGS__)
42 : #else
43 : #define NETTURN_LOG(...)
44 : #endif
45 :
46 : const CStr CTurnManager::EventNameSavegameLoaded = "SavegameLoaded";
47 :
48 3 : CTurnManager::CTurnManager(CSimulation2& simulation, std::uint32_t defaultTurnLength,
49 3 : std::uint32_t commandDelay, int clientId, IReplayLogger& replay)
50 3 : : m_Simulation2(simulation), m_CurrentTurn(0), m_CommandDelay(commandDelay), m_ReadyTurn(commandDelay - 1), m_TurnLength(defaultTurnLength),
51 3 : m_PlayerId(-1), m_ClientId(clientId), m_DeltaSimTime(0), m_Replay(replay),
52 3 : m_FinalTurn(std::numeric_limits<turn_id_t>::max()), m_TimeWarpNumTurns(0)
53 : {
54 3 : Script::Request rq(m_Simulation2.GetScriptInterface());
55 3 : m_QuickSaveMetadata.init(rq.cx);
56 3 : m_QueuedCommands.resize(1);
57 3 : }
58 :
59 0 : void CTurnManager::ResetState(turn_id_t newCurrentTurn, turn_id_t newReadyTurn)
60 : {
61 0 : m_CurrentTurn = newCurrentTurn;
62 0 : m_ReadyTurn = newReadyTurn;
63 0 : m_DeltaSimTime = 0;
64 0 : size_t queuedCommandsSize = m_QueuedCommands.size();
65 0 : m_QueuedCommands.clear();
66 0 : m_QueuedCommands.resize(queuedCommandsSize);
67 0 : }
68 :
69 0 : void CTurnManager::SetPlayerID(int playerId)
70 : {
71 0 : m_PlayerId = playerId;
72 0 : }
73 :
74 208 : bool CTurnManager::Update(float simFrameLength, size_t maxTurns, const UpdateCallback& sendEventToAll)
75 : {
76 208 : if (m_CurrentTurn > m_FinalTurn)
77 : return false;
78 :
79 208 : m_DeltaSimTime += simFrameLength;
80 :
81 : // If the game becomes laggy, m_DeltaSimTime increases progressively.
82 : // The engine will fast forward accordingly to catch up.
83 : // To keep the game playable, stop fast forwarding after 2 turn lengths.
84 208 : m_DeltaSimTime = std::min(m_DeltaSimTime, 2.0f * m_TurnLength / 1000.0f);
85 :
86 : // If we haven't reached the next turn yet, do nothing
87 208 : if (m_DeltaSimTime < 0)
88 : return false;
89 :
90 150 : NETTURN_LOG("Update current=%d ready=%d\n", m_CurrentTurn, m_ReadyTurn);
91 :
92 : // Check that the next turn is ready for execution
93 150 : if (m_ReadyTurn <= m_CurrentTurn && m_CommandDelay > 1)
94 : {
95 : // Oops, we wanted to start the next turn but it's not ready yet -
96 : // there must be too much network lag.
97 : // TODO: complain to the user.
98 : // TODO: send feedback to the server to increase the turn length.
99 :
100 : // Reset the next-turn timer to 0 so we try again next update but
101 : // so we don't rush to catch up in subsequent turns.
102 : // TODO: we should do clever rate adjustment instead of just pausing like this.
103 0 : m_DeltaSimTime = 0;
104 :
105 0 : return false;
106 : }
107 :
108 150 : maxTurns = std::max((size_t)1, maxTurns); // always do at least one turn
109 :
110 330 : for (size_t i = 0; i < maxTurns; ++i)
111 : {
112 : // Check that we've reached the i'th next turn
113 180 : if (m_DeltaSimTime < 0)
114 : break;
115 :
116 : // Check that the i'th next turn is still ready
117 180 : if (m_ReadyTurn <= m_CurrentTurn && m_CommandDelay > 1)
118 : break;
119 :
120 : // To avoid confusing the profiler, we need to trigger the new turn
121 : // while we're not nested inside any PROFILE blocks
122 180 : g_Profiler.Turn();
123 :
124 180 : NotifyFinishedOwnCommands(m_CurrentTurn + m_CommandDelay);
125 :
126 : // Increase now, so Update can send new commands for a subsequent turn
127 180 : ++m_CurrentTurn;
128 :
129 : // Clean up any destroyed entities since the last turn (e.g. placement previews
130 : // or rally point flags generated by the GUI). (Must do this before the time warp
131 : // serialization.)
132 180 : m_Simulation2.FlushDestroyedEntities();
133 :
134 : // Save the current state for rewinding, if enabled
135 180 : if (m_TimeWarpNumTurns && (m_CurrentTurn % m_TimeWarpNumTurns) == 0)
136 : {
137 0 : PROFILE3("time warp serialization");
138 0 : std::stringstream stream;
139 0 : m_Simulation2.SerializeState(stream);
140 0 : m_TimeWarpStates.push_back(stream.str());
141 0 : }
142 :
143 : // Put all the client commands into a single list, in a globally consistent order
144 180 : std::vector<SimulationCommand> commands;
145 180 : for (std::pair<const turn_id_t, std::vector<SimulationCommand>>& p : m_QueuedCommands[0])
146 0 : commands.insert(commands.end(), std::make_move_iterator(p.second.begin()), std::make_move_iterator(p.second.end()));
147 :
148 180 : m_QueuedCommands.pop_front();
149 180 : m_QueuedCommands.resize(m_QueuedCommands.size() + 1);
150 :
151 180 : m_Replay.Turn(m_CurrentTurn-1, m_TurnLength, commands);
152 :
153 180 : NETTURN_LOG("Running %d cmds\n", commands.size());
154 :
155 180 : m_Simulation2.Update(m_TurnLength, commands);
156 :
157 180 : NotifyFinishedUpdate(m_CurrentTurn, sendEventToAll);
158 :
159 : // Set the time for the next turn update
160 180 : m_DeltaSimTime -= m_TurnLength / 1000.f;
161 180 : }
162 :
163 : return true;
164 : }
165 :
166 0 : bool CTurnManager::UpdateFastForward()
167 : {
168 0 : m_DeltaSimTime = 0;
169 :
170 0 : NETTURN_LOG("UpdateFastForward current=%d ready=%d\n", m_CurrentTurn, m_ReadyTurn);
171 :
172 : // Check that the next turn is ready for execution
173 0 : if (m_ReadyTurn <= m_CurrentTurn)
174 : return false;
175 :
176 0 : while (m_ReadyTurn > m_CurrentTurn)
177 : {
178 : // TODO: It would be nice to remove some of the duplication with Update()
179 : // (This is similar but doesn't call any Notify functions or update DeltaTime,
180 : // it just updates the simulation state)
181 :
182 0 : ++m_CurrentTurn;
183 :
184 0 : m_Simulation2.FlushDestroyedEntities();
185 :
186 : // Put all the client commands into a single list, in a globally consistent order
187 0 : std::vector<SimulationCommand> commands;
188 0 : for (std::pair<const turn_id_t, std::vector<SimulationCommand>>& p : m_QueuedCommands[0])
189 0 : commands.insert(commands.end(), std::make_move_iterator(p.second.begin()), std::make_move_iterator(p.second.end()));
190 :
191 0 : m_QueuedCommands.pop_front();
192 0 : m_QueuedCommands.resize(m_QueuedCommands.size() + 1);
193 :
194 0 : m_Replay.Turn(m_CurrentTurn-1, m_TurnLength, commands);
195 :
196 0 : NETTURN_LOG("Running %d cmds\n", commands.size());
197 :
198 0 : m_Simulation2.Update(m_TurnLength, commands);
199 0 : }
200 :
201 : return true;
202 : }
203 :
204 3 : void CTurnManager::Interpolate(float simFrameLength, float realFrameLength)
205 : {
206 : // TODO: using m_TurnLength might be a bit dodgy when length changes - maybe
207 : // we need to save the previous turn length?
208 :
209 3 : float offset = Clamp(m_DeltaSimTime / (m_TurnLength / 1000.f) + 1.0, 0.0, 1.0);
210 :
211 : // Stop animations while still updating the selection highlight
212 3 : if (m_CurrentTurn > m_FinalTurn)
213 0 : simFrameLength = 0;
214 :
215 3 : m_Simulation2.Interpolate(simFrameLength, offset, realFrameLength);
216 3 : }
217 :
218 0 : void CTurnManager::AddCommand(int client, int player, JS::HandleValue data, turn_id_t turn)
219 : {
220 0 : NETTURN_LOG("AddCommand(client=%d player=%d turn=%d current=%d, ready=%d)\n", client, player, turn, m_CurrentTurn, m_ReadyTurn);
221 :
222 : // Reject commands for turns that we should not be able to compute (in the past).
223 0 : if (m_CurrentTurn >= turn)
224 : {
225 : // The most likely explanation is that an observer that's lagging behind is sending commands,
226 : // which is possible when cheats are enabled. Report & ignore.
227 : // It seems a bad idea to error out too badly here:
228 : // nefarious clients could try and send broken commands to DOS.
229 0 : LOGWARNING("Received command for invalid turn {} (current turn is {})", turn, m_CurrentTurn);
230 0 : return;
231 : }
232 :
233 0 : Script::Request rq(m_Simulation2.GetScriptInterface());
234 :
235 0 : Script::DeepFreezeObject(rq, data);
236 :
237 0 : size_t command_in_turns = turn - (m_CurrentTurn+1);
238 0 : if (m_QueuedCommands.size() <= command_in_turns)
239 0 : m_QueuedCommands.resize(command_in_turns+1);
240 0 : m_QueuedCommands[turn - (m_CurrentTurn+1)][client].emplace_back(player, rq.cx, data);
241 0 : }
242 :
243 180 : void CTurnManager::FinishedAllCommands(turn_id_t turn, std::uint32_t turnLength)
244 : {
245 180 : NETTURN_LOG("FinishedAllCommands(%d, %d)\n", turn, turnLength);
246 :
247 180 : ENSURE(turn == m_ReadyTurn + 1);
248 180 : m_ReadyTurn = turn;
249 180 : m_TurnLength = turnLength;
250 180 : }
251 :
252 0 : bool CTurnManager::TurnNeedsFullHash(turn_id_t turn) const
253 : {
254 : // Check immediately for errors caused by e.g. inconsistent game versions
255 : // (The hash is computed after the first sim update, so we start at turn == 1)
256 0 : if (turn == 1)
257 : return true;
258 :
259 : // Otherwise check the full state every ~10 seconds in multiplayer games
260 : // (TODO: should probably remove this when we're reasonably sure the game
261 : // isn't too buggy, since the full hash is still pretty slow)
262 0 : if (turn % 20 == 0)
263 0 : return true;
264 :
265 : return false;
266 : }
267 :
268 0 : void CTurnManager::EnableTimeWarpRecording(size_t numTurns)
269 : {
270 0 : m_TimeWarpStates.clear();
271 0 : m_TimeWarpNumTurns = numTurns;
272 0 : }
273 :
274 0 : void CTurnManager::RewindTimeWarp()
275 : {
276 0 : if (m_TimeWarpStates.empty())
277 0 : return;
278 :
279 0 : std::stringstream stream(m_TimeWarpStates.back());
280 0 : m_Simulation2.DeserializeState(stream);
281 0 : m_TimeWarpStates.pop_back();
282 :
283 : // Reset the turn manager state, so we won't execute stray commands and
284 : // won't do the next snapshot until the appropriate time.
285 : // (Ideally we ought to serialise the turn manager state and restore it
286 : // here, but this is simpler for now.)
287 0 : ResetState(1, m_CommandDelay);
288 0 : }
289 :
290 0 : void CTurnManager::QuickSave(JS::HandleValue GUIMetadata)
291 : {
292 0 : PROFILE2("QuickSave");
293 :
294 0 : std::stringstream stream;
295 0 : if (!m_Simulation2.SerializeState(stream))
296 : {
297 0 : LOGERROR("Failed to quicksave game");
298 0 : return;
299 : }
300 :
301 0 : m_QuickSaveState = stream.str();
302 :
303 0 : Script::Request rq(m_Simulation2.GetScriptInterface());
304 :
305 0 : m_QuickSaveMetadata.set(Script::DeepCopy(rq, GUIMetadata));
306 : // Freeze state to ensure that consectuvie loads don't modify the state
307 0 : Script::DeepFreezeObject(rq, m_QuickSaveMetadata);
308 :
309 0 : LOGMESSAGERENDER("Quicksaved game");
310 0 : }
311 :
312 0 : std::optional<JS::Value> CTurnManager::TryQuickLoad()
313 : {
314 0 : PROFILE2("QuickLoad");
315 :
316 0 : if (m_QuickSaveState.empty())
317 : {
318 0 : LOGERROR("Cannot quickload game - no game was quicksaved");
319 0 : return std::nullopt;
320 : }
321 :
322 0 : std::stringstream stream(m_QuickSaveState);
323 0 : if (!m_Simulation2.DeserializeState(stream))
324 : {
325 0 : LOGERROR("Failed to quickload game");
326 0 : return std::nullopt;
327 : }
328 :
329 : // See RewindTimeWarp
330 0 : ResetState(1, m_CommandDelay);
331 :
332 0 : return m_QuickSaveMetadata;
333 0 : }
|