Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
NetClient.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 NETCLIENT_H
19#define NETCLIENT_H
20
21#include "lib/code_annotation.h"
22#include "lib/config2.h"
24#include "network/FSM.h"
25#include "network/NetHost.h"
26#include "network/NetMessage.h"
27#include "ps/CStr.h"
31
32#include <ctime>
33#include <deque>
34#include <js/RootingAPI.h>
35#include <js/TypeDecls.h>
36#include <js/Value.h>
37#include <optional>
38#include <string>
39#include <thread>
40#include <vector>
41
42class CGame;
45class JSTracer;
46class XmppClient;
47
48namespace Script { class Interface; }
49
50typedef struct _ENetHost ENetHost;
51
52// NetClient session FSM states
53enum
54{
63};
64
65/**
66 * Network client.
67 * This code is run by every player (including the host, if they are not
68 * a dedicated server).
69 * It provides an interface between the GUI, the network (via CNetClientSession),
70 * and the game (via CGame and CNetClientTurnManager).
71 */
72class CNetClient : public CFsm<CNetClient, CNetMessage*>
73{
75
76public:
77 /**
78 * Construct a client associated with the given game object.
79 * The game must exist for the lifetime of this object.
80 * The user's name will be displayed to all players.
81 * The JID of the host is needed for the secure lobby authentication.
82 */
83 CNetClient(CGame* game, std::string serverAddressOrHostname, std::uint16_t serverPont,
84 const CStrW& username = L"anonymous", const CStr& hostJID = {},
85 std::string hashedPassword = {}, std::string controllerSecret = {});
86
87 /**
88 * This constructor additionally requests connection information over the
89 * lobby.
90 */
91#if CONFIG2_LOBBY
92 CNetClient(CGame* game, const CStrW& username, const CStr& hostJID,
93 std::string hashedPassword, XmppClient& xmppClient);
94#endif
95
96 virtual ~CNetClient();
97
98 bool IsController() const { return m_IsController; }
99
100 /**
101 * Returns the GUID of the local client.
102 * Used for distinguishing observers.
103 */
104 CStr GetGUID() const { return m_GUID; }
105
106 /**
107 * Connect to the remote networked server using lobby.
108 * Push netstatus messages on failure.
109 * @param localNetwork - if true, assume we are trying to connect on the local network.
110 * @return true on success, false on connection failure
111 */
112#if CONFIG2_LOBBY
113 bool TryToConnectWithSTUN(std::string serverAddressOrHostname, std::uint16_t serverPort,
114 const CStr& hostJID, bool localNetwork);
115#endif
116
117 /**
118 * Destroy the connection to the server.
119 * This client probably cannot be used again.
120 */
121 void DestroyConnection();
122
123 /**
124 * Poll the connection for messages from the server and process them, and send
125 * any queued messages.
126 * This must be called frequently (i.e. once per frame).
127 */
128 void Poll();
129
130 /**
131 * Locally triggers a GUI message if the connection to the server is being lost or has bad latency.
132 */
134
135 /**
136 * Retrieves the next queued GUI message, and removes it from the queue.
137 * The returned value is in the JS context of the provided
138 * @c Script::Interface.
139 *
140 * This is the only mechanism for the networking code to send messages to
141 * the GUI.
142 *
143 * The structure of the messages is <code>{ "type": "...", ... }</code>.
144 * The exact types and associated data are not specified anywhere - the
145 * implementation and GUI scripts must make the same assumptions.
146 *
147 * @return a promise resolving to the next message.
148 */
149 JSObject* GetNextGUIMessage(const Script::Interface& guiInterface);
150
151 /**
152 * Has to be called bevore the @c Script::Interface gets destroied so that
153 * no future messages are sent to it.
154 */
155 void Unregister(const Script::Interface* guiInterface);
156
157 /**
158 * Add a message to the queue, to be read by GuiPoll.
159 * The script value must be in the GetScriptInterface() JS context.
160 */
161 template<typename... Args>
162 void PushGuiMessage(Args const&... args)
163 {
165
166 JS::RootedValue message(rq.cx);
167 Script::CreateObject(rq, &message, args...);
168 m_GuiMessageQueue.push_back(Script::WriteStructuredClone(rq, message));
169 }
170
171 /**
172 * Return a concatenation of all messages in the GUI queue,
173 * for test cases to easily verify the queue contents.
174 */
175 std::string TestReadGuiMessages();
176
177 /**
178 * Get the script interface associated with this network client,
179 * which is equivalent to the one used by the CGame in the constructor.
180 */
182
183 /**
184 * Send a message to the server.
185 * @param message message to send
186 * @return true on success
187 */
188 bool SendMessage(const CNetMessage* message);
189
190 /**
191 * Call when the network connection has been successfully initiated.
192 */
193 void HandleConnect();
194
195 /**
196 * Call when the network connection has been lost.
197 */
198 void HandleDisconnect(std::uint32_t reason);
199
200 /**
201 * Call when a message has been received from the network.
202 */
203 bool HandleMessage(CNetMessage* message);
204
205 /**
206 * Call when the game has started and all data files have been loaded,
207 * to signal to the server that we are ready to begin the game.
208 */
209 void LoadFinished();
210
211 void SendGameSetupMessage(JS::MutableHandleValue attrs, const Script::Interface& scriptInterface);
212
213 void SendAssignPlayerMessage(const int playerID, const CStr& guid);
214
215 /**
216 * @param text The message to send.
217 * @param receivers The GUID of the receiving clients. If empty send it to
218 * all clients.
219 */
220 void SendChatMessage(const std::wstring& text, std::optional<std::vector<std::string>> receivers);
221
222 void SendReadyMessage(const int status);
223
225
226 void SendStartGameMessage(const CStr& initAttribs);
227
228 void SendStartSavedGameMessage(const CStr& initAttribs, const CStr& savedState);
229
230 /**
231 * Call when the client (player or observer) has sent a flare.
232 */
233 void SendFlareMessage(const CStr& positionX, const CStr& positionY, const CStr& positionZ);
234
235 /**
236 * Call when the client has rejoined a running match and finished
237 * the loading screen.
238 */
239 void SendRejoinedMessage();
240
241 /**
242 * Call to kick/ban a client
243 */
244 void SendKickPlayerMessage(const CStrW& playerName, bool ban);
245
246 /**
247 * Call when the client has paused or unpaused the game.
248 */
249 void SendPausedMessage(bool pause);
250
251 /**
252 * @return Whether the NetClient is shutting down.
253 */
254 bool ShouldShutdown() const;
255
256 /**
257 * Called when fetching connection data from the host failed, to inform JS code.
258 */
259 void HandleGetServerDataFailed(const CStr& error);
260private:
261 struct PrivateTag {};
262 CNetClient(PrivateTag, CGame* game, std::string serverAddressOrHostname,
263 std::uint16_t serverPont, const CStrW& username = L"anonymous", const CStr& hostJID = {},
264 std::string hashedPassword = {}, std::string controllerSecret = {});
265
267
268 // Net message / FSM transition handlers
269 static bool OnConnect(CNetClient* client, CFsmEvent<CNetMessage*>* event);
270 static bool OnHandshake(CNetClient* client, CFsmEvent<CNetMessage*>* event);
271 static bool OnHandshakeResponse(CNetClient* client, CFsmEvent<CNetMessage*>* event);
272 static bool OnAuthenticateRequest(CNetClient* client, CFsmEvent<CNetMessage*>* event);
273 static bool OnAuthenticate(CNetClient* client, CFsmEvent<CNetMessage*>* event);
274 static bool OnChat(CNetClient* client, CFsmEvent<CNetMessage*>* event);
275 static bool OnReady(CNetClient* client, CFsmEvent<CNetMessage*>* event);
276 static bool OnGameSetup(CNetClient* client, CFsmEvent<CNetMessage*>* event);
277 static bool OnPlayerAssignment(CNetClient* client, CFsmEvent<CNetMessage*>* event);
278 static bool OnInGame(CNetClient* client, CFsmEvent<CNetMessage*>* event);
279 static bool OnGameStart(CNetClient* client, CFsmEvent<CNetMessage*>* event);
280 static bool OnSavedGameStart(CNetClient* client, CFsmEvent<CNetMessage*>* event);
281 static bool OnJoinSyncStart(CNetClient* client, CFsmEvent<CNetMessage*>* event);
283 static bool OnFlare(CNetClient* client, CFsmEvent<CNetMessage*>* event);
284 static bool OnRejoined(CNetClient* client, CFsmEvent<CNetMessage*>* event);
285 static bool OnKicked(CNetClient* client, CFsmEvent<CNetMessage*>* event);
286 static bool OnClientTimeout(CNetClient* client, CFsmEvent<CNetMessage*>* event);
287 static bool OnClientPerformance(CNetClient* client, CFsmEvent<CNetMessage*>* event);
288 static bool OnClientsLoading(CNetClient* client, CFsmEvent<CNetMessage*>* event);
289 static bool OnClientPaused(CNetClient* client, CFsmEvent<CNetMessage*>* event);
290 static bool OnLoadedGame(CNetClient* client, CFsmEvent<CNetMessage*>* event);
291
292 /**
293 * Set up a connection to the remote networked server.
294 * @return true on success, false on connection failure
295 */
296 void SetupConnection(ENetHost* enetClient);
297
298 /**
299 * Take ownership of a session object, and use it for all network communication.
300 */
301 void SetAndOwnSession(CNetClientSession* session);
302
303 /**
304 * Starts a game with the specified init attributes and saved state. Called
305 * by the start game and start saved game callbacks.
306 */
307 void StartGame(const JS::MutableHandleValue initAttributes, const std::string& savedState);
308
309 /**
310 * Push a message onto the GUI queue listing the current player assignments.
311 */
313
314 void FetchMessage();
315
318
321 std::uint16_t m_ServerPort{0};
322
323 /**
324 * Password to join the game.
325 */
327
328 /// The 'secret' used to identify the controller of the game.
330
331 /// Note that this is just a "gui hint" with no actual impact on being controller.
332 bool m_IsController = false;
333
334 /// Current network session (or nullptr if not connected)
336
337 std::thread m_PollingThread;
338
339 /// Turn manager associated with the current game (or nullptr if we haven't started the game yet)
341
342 /// Unique-per-game identifier of this client, used to identify the sender of simulation commands
343 std::uint32_t m_HostID{static_cast<std::uint32_t>(-1)};
344
345 /// True if the player is currently rejoining or has already rejoined the game.
346 bool m_Rejoin{false};
347
348 /// Latest copy of player assignments heard from the server
350
351 /// Globally unique identifier to distinguish users beyond the lifetime of a single network session
352 CStr m_GUID;
353
354 /// Queue of messages for GuiPoll
355 std::deque<Script::StructuredClone> m_GuiMessageQueue;
356
358 {
360 /**
361 * In the context of interface.
362 * When the promise is pending @see Poll should fill it with a message.
363 * When there it's fulfilled JavaScript code can take it.
364 */
365 JS::PersistentRootedObject promise;
366 };
367 std::optional<GuiPollData> m_GuiMessagePoll;
368
369 /// Serialized game state received when joining an in-progress game
370 std::string m_JoinSyncBuffer;
371
372 std::string m_SavedState;
373
374 /// Time when the server was last checked for timeouts and bad latency
375 std::time_t m_LastConnectionCheck{0};
376
377 /// Record of the server engine version and loaded mods
378 CSrvHandshakeMessage m_ServerHandshake;
379};
380
381/// Global network client for the standard game
382extern CNetClient *g_NetClient;
383
384#endif // NETCLIENT_H
385
struct _ENetHost ENetHost
Definition: NetClient.h:50
@ NCS_UNCONNECTED
Definition: NetClient.h:55
@ NCS_PREGAME
Definition: NetClient.h:59
@ NCS_JOIN_SYNCING
Definition: NetClient.h:61
@ NCS_CONNECT
Definition: NetClient.h:56
@ NCS_LOADING
Definition: NetClient.h:60
@ NCS_AUTHENTICATE
Definition: NetClient.h:58
@ NCS_INGAME
Definition: NetClient.h:62
@ NCS_HANDSHAKE
Definition: NetClient.h:57
CNetClient * g_NetClient
Global network client for the standard game.
Definition: NetClient.cpp:68
Various declarations shared by networking code.
std::map< CStr, PlayerAssignment > PlayerAssignmentMap
Definition: NetHost.h:56
Represents a signal in the state machine that a change has occurred.
Definition: FSM.h:34
Manages states, events, actions and transitions between states.
Definition: FSM.h:69
The container that holds the rules, resources and attributes of the game.
Definition: Game.h:49
The client end of a network session.
Definition: NetClientSession.h:51
Implementation of CTurnManager for network clients.
Definition: NetClientTurnManager.h:37
Network client.
Definition: NetClient.h:73
void CheckServerConnection()
Locally triggers a GUI message if the connection to the server is being lost or has bad latency.
Definition: NetClient.cpp:376
void HandleDisconnect(std::uint32_t reason)
Call when the network connection has been lost.
Definition: NetClient.cpp:510
static bool OnClientTimeout(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:985
static bool OnClientPerformance(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:1002
void SendChatMessage(const std::wstring &text, std::optional< std::vector< std::string > > receivers)
Definition: NetClient.cpp:550
static bool OnConnect(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:732
const Script::Interface & GetScriptInterface()
Get the script interface associated with this network client, which is equivalent to the one used by ...
Definition: NetClient.cpp:466
static bool OnHandshakeResponse(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:754
static bool OnGameStart(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:882
static bool OnClientsLoading(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:1026
static bool OnAuthenticate(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:792
void SendAssignPlayerMessage(const int playerID, const CStr &guid)
Definition: NetClient.cpp:542
std::string TestReadGuiMessages()
Return a concatenation of all messages in the GUI queue, for test cases to easily verify the queue co...
Definition: NetClient.cpp:447
std::uint16_t m_ServerPort
Definition: NetClient.h:321
NONCOPYABLE(CNetClient)
void SendStartSavedGameMessage(const CStr &initAttribs, const CStr &savedState)
Definition: NetClient.cpp:593
CStrW m_UserName
Definition: NetClient.h:317
CStr GetGUID() const
Returns the GUID of the local client.
Definition: NetClient.h:104
void PushGuiMessage(Args const &... args)
Add a message to the queue, to be read by GuiPoll.
Definition: NetClient.h:162
static bool OnFlare(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:1104
void SendKickPlayerMessage(const CStrW &playerName, bool ban)
Call to kick/ban a client.
Definition: NetClient.cpp:608
std::string m_JoinSyncBuffer
Serialized game state received when joining an in-progress game.
Definition: NetClient.h:370
static bool OnGameSetup(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:842
bool IsController() const
Definition: NetClient.h:98
static bool OnInGame(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:1076
void PostPlayerAssignmentsToScript()
Push a message onto the GUI queue listing the current player assignments.
Definition: NetClient.cpp:471
std::thread m_PollingThread
Definition: NetClient.h:337
static bool OnRejoined(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:958
static bool OnAuthenticateRequest(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:784
CStr m_HostJID
Definition: NetClient.h:319
void SendRejoinedMessage()
Call when the client has rejoined a running match and finished the loading screen.
Definition: NetClient.cpp:602
bool TryToConnectWithSTUN(std::string serverAddressOrHostname, std::uint16_t serverPort, const CStr &hostJID, bool localNetwork)
Connect to the remote networked server using lobby.
Definition: NetClient.cpp:235
virtual ~CNetClient()
Definition: NetClient.cpp:199
std::deque< Script::StructuredClone > m_GuiMessageQueue
Queue of messages for GuiPoll.
Definition: NetClient.h:355
void SetupConnection(ENetHost *enetClient)
Set up a connection to the remote networked server.
Definition: NetClient.cpp:211
bool SendMessage(const CNetMessage *message)
Send a message to the server.
Definition: NetClient.cpp:497
std::string m_ControllerSecret
The 'secret' used to identify the controller of the game.
Definition: NetClient.h:329
void DestroyConnection()
Destroy the connection to the server.
Definition: NetClient.cpp:349
void SendGameSetupMessage(JS::MutableHandleValue attrs, const Script::Interface &scriptInterface)
Definition: NetClient.cpp:535
void SendReadyMessage(const int status)
Definition: NetClient.cpp:564
std::optional< GuiPollData > m_GuiMessagePoll
Definition: NetClient.h:367
CStr m_GUID
Globally unique identifier to distinguish users beyond the lifetime of a single network session.
Definition: NetClient.h:352
void SendStartGameMessage(const CStr &initAttribs)
Definition: NetClient.cpp:577
static bool OnJoinSyncStart(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:919
static bool OnReady(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:828
CStr m_Password
Password to join the game.
Definition: NetClient.h:326
bool m_Rejoin
True if the player is currently rejoining or has already rejoined the game.
Definition: NetClient.h:346
static bool OnSavedGameStart(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:898
static bool OnPlayerAssignment(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:855
bool ShouldShutdown() const
static bool OnLoadedGame(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:1057
static bool OnHandshake(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:743
CSrvHandshakeMessage m_ServerHandshake
Record of the server engine version and loaded mods.
Definition: NetClient.h:378
CStr m_ServerAddressOrHostname
Definition: NetClient.h:320
CNetClientSession * m_Session
Current network session (or nullptr if not connected)
Definition: NetClient.h:335
void LoadFinished()
Call when the game has started and all data files have been loaded, to signal to the server that we a...
Definition: NetClient.cpp:673
void FetchMessage()
Definition: NetClient.cpp:431
CNetClient(CGame *game, std::string serverAddressOrHostname, std::uint16_t serverPont, const CStrW &username=L"anonymous", const CStr &hostJID={}, std::string hashedPassword={}, std::string controllerSecret={})
Construct a client associated with the given game object.
Definition: NetClient.cpp:70
void SendFlareMessage(const CStr &positionX, const CStr &positionY, const CStr &positionZ)
Call when the client (player or observer) has sent a flare.
Definition: NetClient.cpp:584
bool HandleMessage(CNetMessage *message)
Call when a message has been received from the network.
Definition: NetClient.cpp:623
void SendClearAllReadyMessage()
Definition: NetClient.cpp:571
static bool OnKicked(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:971
void Poll()
Poll the connection for messages from the server and process them, and send any queued messages.
Definition: NetClient.cpp:364
std::time_t m_LastConnectionCheck
Time when the server was last checked for timeouts and bad latency.
Definition: NetClient.h:375
void HandleConnect()
Call when the network connection has been successfully initiated.
Definition: NetClient.cpp:505
static bool OnJoinSyncEndCommandBatch(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:944
bool m_IsController
Note that this is just a "gui hint" with no actual impact on being controller.
Definition: NetClient.h:332
void HandleGetServerDataFailed(const CStr &error)
Called when fetching connection data from the host failed, to inform JS code.
Definition: NetClient.cpp:222
PlayerAssignmentMap m_PlayerAssignments
Latest copy of player assignments heard from the server.
Definition: NetClient.h:349
JSObject * GetNextGUIMessage(const Script::Interface &guiInterface)
Retrieves the next queued GUI message, and removes it from the queue.
Definition: NetClient.cpp:408
void SendAuthenticateMessage()
Definition: NetClient.cpp:710
static bool OnChat(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:814
void SetAndOwnSession(CNetClientSession *session)
Take ownership of a session object, and use it for all network communication.
Definition: NetClient.cpp:343
std::uint32_t m_HostID
Unique-per-game identifier of this client, used to identify the sender of simulation commands.
Definition: NetClient.h:343
std::string m_SavedState
Definition: NetClient.h:372
void Unregister(const Script::Interface *guiInterface)
Has to be called bevore the Script::Interface gets destroied so that no future messages are sent to i...
Definition: NetClient.cpp:418
void SendPausedMessage(bool pause)
Call when the client has paused or unpaused the game.
Definition: NetClient.cpp:616
CGame * m_Game
Definition: NetClient.h:316
static bool OnClientPaused(CNetClient *client, CFsmEvent< CNetMessage * > *event)
Definition: NetClient.cpp:1043
void StartGame(const JS::MutableHandleValue initAttributes, const std::string &savedState)
Starts a game with the specified init attributes and saved state.
Definition: NetClient.cpp:719
CNetClientTurnManager * m_ClientTurnManager
Turn manager associated with the current game (or nullptr if we haven't started the game yet)
Definition: NetClient.h:340
The base class for all network messages exchanged within the game.
Definition: NetMessage.h:42
Definition: Interface.h:93
Definition: Request.h:51
JSContext * cx
Definition: Request.h:83
Definition: XmppClient.h:30
Abstraction around a SpiderMonkey JSContext.
Definition: DapInterface.h:32
JS::Value CreateObject(const Script::Request &rq)
Create a plain object (i.e.
Definition: Object.h:246
StructuredClone WriteStructuredClone(const Script::Request &rq, JS::HandleValue v)
Definition: StructuredClone.cpp:33
bool error(JSContext *cx, unsigned int argc, JS::Value *vp)
Definition: Interface.cpp:204
Definition: NetClient.h:358
const Script::Interface & interface
Definition: NetClient.h:359
JS::PersistentRootedObject promise
In the context of interface.
Definition: NetClient.h:365
Definition: NetClient.h:261