Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
TurnManager.h
Go to the documentation of this file.
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#ifndef INCLUDED_TURNMANAGER
19#define INCLUDED_TURNMANAGER
20
21#include "lib/code_annotation.h"
22#include "ps/CStr.h"
24
25#include <cstddef>
26#include <deque>
27#include <js/RootingAPI.h>
28#include <js/TypeDecls.h>
29#include <js/Value.h>
30#include <js/ValueArray.h>
31#include <list>
32#include <map>
33#include <optional>
34#include <string>
35#include <vector>
36
37class CSimulation2;
39class IReplayLogger;
40
41/**
42 * This file defines the base class of the turn managers for clients, local games and replays.
43 * The basic idea of our turn managing system across a network is as in this article:
44 * http://www.gamasutra.com/view/feature/3094/1500_archers_on_a_288_network_.php?print=1
45 *
46 * Each player performs the simulation for turn N.
47 * User input is translated into commands scheduled for execution in turn N+2 which are
48 * distributed to all other clients.
49 * After a while, a client wants to perform the simulation for turn N+1,
50 * which first requires that it has all the other clients' commands for turn N+1.
51 * In that case, it does the simulation and tells all the other clients (via the server)
52 * it has finished sending commands for turn N+2, and it starts sending commands for turn N+3.
53 *
54 * Commands are redistributed immediately by the server.
55 * To ensure a consistent execution of commands, they are each associated with a
56 * client session ID (which is globally unique and consistent), which is used to sort them.
57 */
58
59/**
60 * Default turn length in SP & MP.
61 * This value should be as low as possible, while not introducing un-necessary lag.
62 */
63inline constexpr std::uint32_t DEFAULT_TURN_LENGTH = 200;
64
65/**
66 * In single-player, commands are directly scheduled for the next turn.
67 */
68inline constexpr std::uint32_t COMMAND_DELAY_SP = 1;
69
70/**
71 * In multi-player, clients can only compute turn N if all clients have finished sending commands for it,
72 * i.e. N < CurrentTurn + COMMAND_DELAY for all clients.
73 * Commands are sent from client to server to client, and both client and network can lag.
74 * If a client reaches turn CURRENT_TURN + COMMAND_DELAY - 1, it'll freeze while waiting for commands.
75 * To avoid that, we increase the command-delay to make sure that in general players will have received all commands
76 * by the time they reach a given turn. Keep in mind the minimum delay is one turn.
77 * This value should be as low as possible while avoiding 'freezing' in general usage.
78 * TODO:
79 * - this command-delay could vary based on server-client pings
80 * - it ought be possible to send commands in a P2P fashion (with server verification), which would lower the ping.
81 */
82inline constexpr std::uint32_t COMMAND_DELAY_MP = 4;
83
84/**
85 * Common turn system (used by clients and offline games).
86 */
88{
90public:
92 std::function<void(const std::string&, const std::optional<JS::HandleValueArray>)>;
93
94 static const CStr EventNameSavegameLoaded;
95
96 /**
97 * Construct for a given network session ID.
98 */
99 CTurnManager(CSimulation2& simulation, std::uint32_t defaultTurnLength, std::uint32_t commandDelay,
100 int clientId, IReplayLogger& replay);
101
102 virtual ~CTurnManager() { }
103
104 void ResetState(turn_id_t newCurrentTurn, turn_id_t newReadyTurn);
105
106 /**
107 * Set the current user's player ID, which will be added into command messages.
108 */
109 void SetPlayerID(int playerId);
110
111 /**
112 * Advance the simulation by a certain time. If this brings us past the current
113 * turn length, the next turns are processed and the function returns true.
114 * Otherwise, nothing happens and it returns false.
115 *
116 * @param simFrameLength Length of the previous frame, in simulation seconds
117 * @param maxTurns Maximum number of turns to simulate at once
118 */
119 bool Update(float simFrameLength, size_t maxTurns, const UpdateCallback& sendEventToAll);
120
121 /**
122 * Advance the simulation by as much as possible. Intended for catching up
123 * over a small number of turns when rejoining a multiplayer match.
124 * Returns true if it advanced by at least one turn.
125 */
126 bool UpdateFastForward();
127
128 /**
129 * Advance the graphics by a certain time.
130 * @param simFrameLength Length of the previous frame, in simulation seconds
131 * @param realFrameLength Length of the previous frame, in real time seconds
132 */
133 void Interpolate(float simFrameLength, float realFrameLength);
134
135 /**
136 * Called by networking code when a simulation message is received.
137 */
139
140 /**
141 * Called by simulation code, to add a new command to be distributed to all clients and executed soon.
142 */
143 virtual void PostCommand(JS::HandleValue data) = 0;
144
145 /**
146 * Called when all commands for a given turn have been received.
147 * This allows Update to progress to that turn.
148 */
149 void FinishedAllCommands(turn_id_t turn, std::uint32_t turnLength);
150
151 /**
152 * Enables the recording of state snapshots every @p numTurns,
153 * which can be jumped back to via RewindTimeWarp().
154 * If @p numTurns is 0 then recording is disabled.
155 */
156 void EnableTimeWarpRecording(size_t numTurns);
157
158 /**
159 * Jumps back to the latest recorded state snapshot (if any).
160 */
161 void RewindTimeWarp();
162
163 void QuickSave(JS::HandleValue GUIMetadata);
164 std::optional<JS::Value> TryQuickLoad();
165
167
168 /**
169 * @return how many turns are ready to be computed.
170 * (used to detect players/observers that fall behind the live game.
171 */
173
174protected:
175 /**
176 * Store a command to be executed at a given turn.
177 */
178 void AddCommand(int client, int player, JS::HandleValue data, turn_id_t turn);
179
180 /**
181 * Called when this client has finished sending all its commands scheduled for the given turn.
182 */
183 virtual void NotifyFinishedOwnCommands(turn_id_t turn) = 0;
184
185 /**
186 * Called when this client has finished a simulation update.
187 */
188 virtual void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback& sendEventToAll) = 0;
189
190 /**
191 * Returns whether we should compute a complete state hash for the given turn,
192 * instead of a quick less-complete hash.
193 */
194 bool TurnNeedsFullHash(turn_id_t turn) const;
195
197
198 /// The turn that we have most recently executed
200
201 // Current command delay (commands are scheduled for m_CurrentTurn + m_CommandDelay)
202 std::uint32_t m_CommandDelay;
203
204 /// The latest turn for which we have received all commands from all clients
206
207 // Current turn length
208 std::uint32_t m_TurnLength;
209
210 /// Commands queued at each turn (index 0 is for m_CurrentTurn+1)
211 std::deque<std::map<turn_id_t, std::vector<SimulationCommand>>> m_QueuedCommands;
212
214 unsigned int m_ClientId;
215
216 /// Simulation time remaining until we ought to execute the next turn (as a negative value to
217 /// add elapsed time increments to until we reach 0).
219
221
222 // The number of the last turn that is allowed to be executed (used for replays)
224
225private:
226 size_t m_TimeWarpNumTurns; // 0 if disabled
227 std::list<std::string> m_TimeWarpStates;
228 std::string m_QuickSaveState; // TODO: should implement a proper disk-based quicksave system
229 JS::PersistentRootedValue m_QuickSaveMetadata;
230};
231
232#endif // INCLUDED_TURNMANAGER
std::int32_t turn_id_t
At 1000 turns/second, a 32-bit counter would overflow in ~49 days.
Definition: SimulationCommand.h:31
constexpr std::uint32_t COMMAND_DELAY_SP
In single-player, commands are directly scheduled for the next turn.
Definition: TurnManager.h:68
constexpr std::uint32_t COMMAND_DELAY_MP
In multi-player, clients can only compute turn N if all clients have finished sending commands for it...
Definition: TurnManager.h:82
constexpr std::uint32_t DEFAULT_TURN_LENGTH
This file defines the base class of the turn managers for clients, local games and replays.
Definition: TurnManager.h:63
Public API for simulation system.
Definition: Simulation2.h:57
Special message type for simulation commands.
Definition: NetMessage.h:123
Common turn system (used by clients and offline games).
Definition: TurnManager.h:88
std::uint32_t m_CommandDelay
Definition: TurnManager.h:202
std::deque< std::map< turn_id_t, std::vector< SimulationCommand > > > m_QueuedCommands
Commands queued at each turn (index 0 is for m_CurrentTurn+1)
Definition: TurnManager.h:211
turn_id_t m_FinalTurn
Definition: TurnManager.h:223
virtual ~CTurnManager()
Definition: TurnManager.h:102
void Interpolate(float simFrameLength, float realFrameLength)
Advance the graphics by a certain time.
Definition: TurnManager.cpp:204
turn_id_t GetPendingTurns() const
Definition: TurnManager.h:172
std::optional< JS::Value > TryQuickLoad()
Definition: TurnManager.cpp:312
std::list< std::string > m_TimeWarpStates
Definition: TurnManager.h:227
JS::PersistentRootedValue m_QuickSaveMetadata
Definition: TurnManager.h:229
std::uint32_t m_TurnLength
Definition: TurnManager.h:208
CSimulation2 & m_Simulation2
Definition: TurnManager.h:196
virtual void PostCommand(JS::HandleValue data)=0
Called by simulation code, to add a new command to be distributed to all clients and executed soon.
turn_id_t m_ReadyTurn
The latest turn for which we have received all commands from all clients.
Definition: TurnManager.h:205
void QuickSave(JS::HandleValue GUIMetadata)
Definition: TurnManager.cpp:290
NONCOPYABLE(CTurnManager)
void RewindTimeWarp()
Jumps back to the latest recorded state snapshot (if any).
Definition: TurnManager.cpp:274
static const CStr EventNameSavegameLoaded
Definition: TurnManager.h:94
std::function< void(const std::string &, const std::optional< JS::HandleValueArray >)> UpdateCallback
Definition: TurnManager.h:92
void SetPlayerID(int playerId)
Set the current user's player ID, which will be added into command messages.
Definition: TurnManager.cpp:69
bool TurnNeedsFullHash(turn_id_t turn) const
Returns whether we should compute a complete state hash for the given turn, instead of a quick less-c...
Definition: TurnManager.cpp:252
bool UpdateFastForward()
Advance the simulation by as much as possible.
Definition: TurnManager.cpp:166
bool Update(float simFrameLength, size_t maxTurns, const UpdateCallback &sendEventToAll)
Advance the simulation by a certain time.
Definition: TurnManager.cpp:74
void AddCommand(int client, int player, JS::HandleValue data, turn_id_t turn)
Store a command to be executed at a given turn.
Definition: TurnManager.cpp:218
size_t m_TimeWarpNumTurns
Definition: TurnManager.h:226
void FinishedAllCommands(turn_id_t turn, std::uint32_t turnLength)
Called when all commands for a given turn have been received.
Definition: TurnManager.cpp:243
std::string m_QuickSaveState
Definition: TurnManager.h:228
turn_id_t GetCurrentTurn() const
Definition: TurnManager.h:166
virtual void NotifyFinishedUpdate(turn_id_t turn, const UpdateCallback &sendEventToAll)=0
Called when this client has finished a simulation update.
virtual void NotifyFinishedOwnCommands(turn_id_t turn)=0
Called when this client has finished sending all its commands scheduled for the given turn.
turn_id_t m_CurrentTurn
The turn that we have most recently executed.
Definition: TurnManager.h:199
IReplayLogger & m_Replay
Definition: TurnManager.h:220
float m_DeltaSimTime
Simulation time remaining until we ought to execute the next turn (as a negative value to add elapsed...
Definition: TurnManager.h:218
int m_PlayerId
Definition: TurnManager.h:213
void EnableTimeWarpRecording(size_t numTurns)
Enables the recording of state snapshots every numTurns, which can be jumped back to via RewindTimeWa...
Definition: TurnManager.cpp:268
virtual void OnSimulationMessage(CSimulationMessage *msg)=0
Called by networking code when a simulation message is received.
void ResetState(turn_id_t newCurrentTurn, turn_id_t newReadyTurn)
Definition: TurnManager.cpp:59
CTurnManager(CSimulation2 &simulation, std::uint32_t defaultTurnLength, std::uint32_t commandDelay, int clientId, IReplayLogger &replay)
Construct for a given network session ID.
Definition: TurnManager.cpp:48
unsigned int m_ClientId
Definition: TurnManager.h:214
Replay log recorder interface.
Definition: Replay.h:40