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 "NetClient.h"
21 :
22 : #include "lib/byte_order.h"
23 : #include "lib/config2.h"
24 : #include "lib/debug.h"
25 : #include "lib/external_libraries/enet.h"
26 : #include "lib/status.h"
27 : #include "lib/utf8.h"
28 : #include "lobby/XmppClient.h"
29 : #include "network/NetClientSession.h"
30 : #include "network/NetClientTurnManager.h"
31 : #include "network/NetEnet.h"
32 : #include "network/NetFileTransfer.h"
33 : #include "network/NetMessage.h"
34 : #include "network/NetProtocol.h"
35 : #include "network/StunClient.h"
36 : #include "ps/CLogger.h"
37 : #include "ps/CStr.h"
38 : #include "ps/Game.h"
39 : #include "ps/Hashing.h"
40 : #include "ps/Profile.h"
41 : #include "ps/Threading.h"
42 : #include "scriptinterface/JSON.h"
43 : #include "scriptinterface/Context.h"
44 : #include "scriptinterface/Interface.h"
45 : #include "simulation2/Simulation2.h"
46 : #include "simulation2/system/TurnManager.h"
47 :
48 : #include <SDL_timer.h>
49 : #include <algorithm>
50 : #include <functional>
51 : #include <iterator>
52 : #include <js/GCAPI.h>
53 : #include <js/Promise.h>
54 : #include <js/TracingAPI.h>
55 : #include <map>
56 : #include <memory>
57 : #include <sstream>
58 : #include <utility>
59 :
60 : /**
61 : * Once ping goes above turn length * command delay,
62 : * the game will start 'freezing' for other clients while we catch up.
63 : * Since commands are sent client -> server -> client, divide by 2.
64 : * (duplicated in NetServer.cpp to avoid having to fetch the constants in a header file)
65 : */
66 : constexpr std::uint32_t NETWORK_BAD_PING = DEFAULT_TURN_LENGTH * COMMAND_DELAY_MP / 2;
67 :
68 : CNetClient *g_NetClient = NULL;
69 :
70 0 : CNetClient::CNetClient(CGame* game, std::string serverAddressOrHostname, std::uint16_t serverPort,
71 : const CStrW& username, const CStr& hostJID, std::string hashedPassword,
72 0 : std::string controllerSecret) :
73 : CNetClient{PrivateTag{}, game, std::move(serverAddressOrHostname), serverPort, username, hostJID,
74 0 : std::move(hashedPassword), std::move(controllerSecret)}
75 : {
76 0 : SetupConnection(nullptr);
77 0 : }
78 :
79 0 : CNetClient::CNetClient(PrivateTag, CGame* game, std::string serverAddressOrHostname,
80 : std::uint16_t serverPort, const CStrW& username, const CStr& hostJID, std::string hashedPassword,
81 0 : std::string controllerSecret) :
82 0 : m_UserName{username},
83 0 : m_HostJID{hostJID},
84 0 : m_Game{game},
85 0 : m_ServerAddressOrHostname{std::move(serverAddressOrHostname)},
86 0 : m_ServerPort{serverPort},
87 : // Hash on top with the user's name, to make sure not all
88 : // hashing data is in control of the host.
89 0 : m_Password{HashCryptographically(std::move(hashedPassword), m_UserName.ToUTF8())},
90 0 : m_ControllerSecret{std::move(controllerSecret)}
91 : {
92 0 : m_Game->SetTurnManager(NULL); // delete the old local turn manager so we don't accidentally use it
93 :
94 : // Set up transitions for session
95 0 : AddTransition(NCS_UNCONNECTED, static_cast<unsigned int>(NMT_CONNECT_COMPLETE), NCS_CONNECT,
96 : &OnConnect, this);
97 :
98 0 : AddTransition(NCS_CONNECT, static_cast<unsigned int>(NMT_SERVER_HANDSHAKE), NCS_HANDSHAKE,
99 : &OnHandshake, this);
100 :
101 0 : AddTransition(NCS_HANDSHAKE, static_cast<unsigned int>(NMT_SERVER_HANDSHAKE_RESPONSE),
102 : NCS_AUTHENTICATE, &OnHandshakeResponse, this);
103 :
104 0 : AddTransition(NCS_AUTHENTICATE, static_cast<unsigned int>(NMT_AUTHENTICATE), NCS_AUTHENTICATE,
105 : &OnAuthenticateRequest, this);
106 0 : AddTransition(NCS_AUTHENTICATE, static_cast<unsigned int>(NMT_AUTHENTICATE_RESULT), NCS_PREGAME,
107 : &OnAuthenticate, this);
108 :
109 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_CHAT), NCS_PREGAME, &OnChat, this);
110 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_READY), NCS_PREGAME, &OnReady, this);
111 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_GAME_SETUP), NCS_PREGAME, &OnGameSetup,
112 : this);
113 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_PLAYER_ASSIGNMENT), NCS_PREGAME,
114 : &OnPlayerAssignment, this);
115 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_KICKED), NCS_PREGAME, &OnKicked, this);
116 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_CLIENT_TIMEOUT), NCS_PREGAME,
117 : &OnClientTimeout, this);
118 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_CLIENT_PERFORMANCE), NCS_PREGAME,
119 : &OnClientPerformance, this);
120 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_GAME_START), NCS_LOADING, &OnGameStart,
121 : this);
122 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_SAVED_GAME_START), NCS_LOADING,
123 : &OnSavedGameStart, this);
124 0 : AddTransition(NCS_PREGAME, static_cast<unsigned int>(NMT_JOIN_SYNC_START), NCS_JOIN_SYNCING,
125 : &OnJoinSyncStart, this);
126 :
127 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_CHAT), NCS_JOIN_SYNCING, &OnChat,
128 : this);
129 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_GAME_SETUP), NCS_JOIN_SYNCING,
130 : &OnGameSetup, this);
131 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_PLAYER_ASSIGNMENT), NCS_JOIN_SYNCING,
132 : &OnPlayerAssignment, this);
133 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_KICKED), NCS_JOIN_SYNCING, &OnKicked,
134 : this);
135 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_CLIENT_TIMEOUT), NCS_JOIN_SYNCING,
136 : &OnClientTimeout, this);
137 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_CLIENT_PERFORMANCE), NCS_JOIN_SYNCING,
138 : &OnClientPerformance, this);
139 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_GAME_START), NCS_JOIN_SYNCING,
140 : &OnGameStart, this);
141 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_SAVED_GAME_START), NCS_LOADING,
142 : &OnSavedGameStart, this);
143 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_SIMULATION_COMMAND), NCS_JOIN_SYNCING,
144 : &OnInGame, this);
145 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_END_COMMAND_BATCH), NCS_JOIN_SYNCING,
146 : &OnJoinSyncEndCommandBatch, this);
147 0 : AddTransition(NCS_JOIN_SYNCING, static_cast<unsigned int>(NMT_LOADED_GAME), NCS_INGAME,
148 : &OnLoadedGame, this);
149 :
150 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_CHAT), NCS_LOADING, &OnChat, this);
151 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_GAME_SETUP), NCS_LOADING, &OnGameSetup,
152 : this);
153 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_PLAYER_ASSIGNMENT), NCS_LOADING,
154 : &OnPlayerAssignment, this);
155 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_KICKED), NCS_LOADING, &OnKicked, this);
156 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_CLIENT_TIMEOUT), NCS_LOADING,
157 : &OnClientTimeout, this);
158 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_CLIENT_PERFORMANCE), NCS_LOADING,
159 : &OnClientPerformance, this);
160 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_CLIENTS_LOADING), NCS_LOADING,
161 : &OnClientsLoading, this);
162 0 : AddTransition(NCS_LOADING, static_cast<unsigned int>(NMT_LOADED_GAME), NCS_INGAME, &OnLoadedGame,
163 : this);
164 :
165 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_REJOINED), NCS_INGAME, &OnRejoined, this);
166 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_KICKED), NCS_INGAME, &OnKicked, this);
167 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_CLIENT_TIMEOUT), NCS_INGAME,
168 : &OnClientTimeout, this);
169 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_CLIENT_PERFORMANCE), NCS_INGAME,
170 : &OnClientPerformance, this);
171 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_CLIENTS_LOADING), NCS_INGAME,
172 : &OnClientsLoading, this);
173 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_CLIENT_PAUSED), NCS_INGAME, &OnClientPaused,
174 : this);
175 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_CHAT), NCS_INGAME, &OnChat, this);
176 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_GAME_SETUP), NCS_INGAME, &OnGameSetup, this);
177 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_PLAYER_ASSIGNMENT), NCS_INGAME,
178 : &OnPlayerAssignment, this);
179 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_SIMULATION_COMMAND), NCS_INGAME, &OnInGame,
180 : this);
181 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_FLARE), NCS_INGAME, &OnFlare, this);
182 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_SYNC_ERROR), NCS_INGAME, &OnInGame, this);
183 0 : AddTransition(NCS_INGAME, static_cast<unsigned int>(NMT_END_COMMAND_BATCH), NCS_INGAME, &OnInGame,
184 : this);
185 :
186 : // Set first state
187 0 : SetFirstState(NCS_UNCONNECTED);
188 0 : }
189 :
190 : #if CONFIG2_LOBBY
191 0 : CNetClient::CNetClient(CGame* game, const CStrW& username, const CStr& hostJID,
192 0 : std::string hashedPassword, XmppClient& xmppClient) :
193 0 : CNetClient{PrivateTag{}, game, {}, 0, username, hostJID, std::move(hashedPassword)}
194 : {
195 0 : xmppClient.SendIqGetConnectionData(m_HostJID, m_Password, m_UserName.ToUTF8(), false);
196 0 : }
197 : #endif // CONFIG2_LOBBY
198 :
199 0 : CNetClient::~CNetClient()
200 : {
201 0 : Unregister(nullptr);
202 :
203 : // Try to flush messages before dying (probably fails).
204 0 : if (m_ClientTurnManager)
205 0 : m_ClientTurnManager->OnDestroyConnection();
206 :
207 0 : DestroyConnection();
208 0 : }
209 :
210 :
211 0 : void CNetClient::SetupConnection(ENetHost* enetClient)
212 : {
213 0 : CNetClientSession* session = new CNetClientSession(*this);
214 0 : bool ok = session->Connect(m_ServerAddressOrHostname, m_ServerPort, enetClient);
215 0 : SetAndOwnSession(session);
216 0 : if (ok)
217 0 : m_PollingThread = std::thread(Threading::HandleExceptions<CNetClientSession::RunNetLoop>::Wrapper, m_Session);
218 : else
219 0 : throw std::runtime_error{"Failed to connect to server"};
220 0 : }
221 :
222 0 : void CNetClient::HandleGetServerDataFailed(const CStr& error)
223 : {
224 0 : if (m_Session)
225 : return;
226 :
227 0 : PushGuiMessage(
228 : "type", "serverdata",
229 : "status", "failed",
230 : "reason", error
231 : );
232 : }
233 :
234 : #if CONFIG2_LOBBY
235 0 : bool CNetClient::TryToConnectWithSTUN(std::string serverAddressOrHostname, std::uint16_t serverPort,
236 : const CStr& hostJID, bool localNetwork)
237 : {
238 0 : ENSURE(g_XmppClient);
239 :
240 0 : m_ServerAddressOrHostname = std::move(serverAddressOrHostname);
241 0 : m_ServerPort = serverPort;
242 :
243 0 : if (m_Session)
244 : return false;
245 :
246 0 : if (m_ServerAddressOrHostname.empty())
247 : {
248 0 : PushGuiMessage(
249 : "type", "netstatus",
250 : "status", "disconnected",
251 0 : "reason", static_cast<std::int32_t>(NDR_SERVER_REFUSED));
252 0 : return false;
253 : }
254 :
255 0 : ENetAddress hostAddr{ ENET_HOST_ANY, ENET_PORT_ANY };
256 0 : ENetHost* enetClient = PS::Enet::CreateHost(&hostAddr, 1, 1);
257 :
258 0 : if (!enetClient)
259 : {
260 0 : PushGuiMessage(
261 : "type", "netstatus",
262 : "status", "disconnected",
263 0 : "reason", static_cast<std::int32_t>(NDR_STUN_PORT_FAILED));
264 0 : return false;
265 : }
266 :
267 0 : CStr ip;
268 0 : std::uint16_t port = 0;
269 0 : if (!localNetwork)
270 : {
271 0 : if (!StunClient::FindPublicIP(*enetClient, ip, port))
272 : {
273 0 : PushGuiMessage(
274 : "type", "netstatus",
275 : "status", "disconnected",
276 0 : "reason", static_cast<std::int32_t>(NDR_STUN_ENDPOINT_FAILED));
277 0 : return false;
278 : }
279 :
280 : // If the host is on the same network, we risk failing to connect
281 : // on routers that don't support NAT hairpinning/NAT loopback.
282 : // To work around that, send again a connection data request, but for internal IP this time.
283 0 : if (ip == m_ServerAddressOrHostname)
284 : {
285 0 : g_XmppClient->SendIqGetConnectionData(m_HostJID, m_Password, m_UserName.ToUTF8(), true);
286 : // Return true anyways - we're on a success path here.
287 0 : return true;
288 : }
289 : }
290 : else
291 : {
292 : // We may need to punch a hole through the local firewall, so fetch our local IP.
293 : // NB: we'll ignore failures here, and hope that the firewall will be open to connection
294 : // if we fail to fetch the local IP (which is unlikely anyways).
295 0 : if (!StunClient::FindLocalIP(ip))
296 0 : ip = "";
297 : // Check if we're hosting on localhost, and if so, explicitly use that
298 : // (this circumvents, at least, the 'block all incoming connections' setting
299 : // on the MacOS firewall).
300 0 : if (ip == m_ServerAddressOrHostname)
301 : {
302 0 : m_ServerAddressOrHostname = "127.0.0.1";
303 0 : ip = "";
304 : }
305 0 : port = enetClient->address.port;
306 : }
307 :
308 0 : LOGMESSAGE("NetClient: connecting to server at {}:{}", m_ServerAddressOrHostname, m_ServerPort);
309 :
310 0 : if (!ip.empty())
311 : {
312 : // UDP hole-punching
313 : // Step 0: send a message, via XMPP, to the server with our external IP & port.
314 0 : g_XmppClient->SendStunEndpointToHost(ip, port, hostJID);
315 :
316 : // Step 1b: Wait some time - we need the host to receive the stun endpoint and start punching a hole themselves before
317 : // we try to establish the connection below.
318 0 : SDL_Delay(1000);
319 :
320 : // Step 2: Send a message ourselves to the server so that the NAT, if any, routes incoming trafic correctly.
321 : // TODO: verify if this step is necessary, since we'll try and connect anyways below.
322 0 : StunClient::SendHolePunchingMessages(*enetClient, m_ServerAddressOrHostname, m_ServerPort);
323 : }
324 :
325 0 : try
326 : {
327 0 : g_NetClient->SetupConnection(enetClient);
328 : }
329 0 : catch (...)
330 : {
331 0 : PushGuiMessage(
332 : "type", "netstatus",
333 : "status", "disconnected",
334 0 : "reason", static_cast<std::int32_t>(NDR_UNKNOWN));
335 0 : return false;
336 0 : }
337 :
338 : return true;
339 : }
340 : #endif // CONFIG2_LOBBY
341 :
342 :
343 0 : void CNetClient::SetAndOwnSession(CNetClientSession* session)
344 : {
345 0 : delete m_Session;
346 0 : m_Session = session;
347 0 : }
348 :
349 0 : void CNetClient::DestroyConnection()
350 : {
351 0 : if (m_Session)
352 0 : m_Session->Shutdown();
353 :
354 0 : if (m_PollingThread.joinable())
355 : // Use detach() over join() because we don't want to wait for the session
356 : // (which may be polling or trying to send messages).
357 0 : m_PollingThread.detach();
358 :
359 : // The polling thread will cleanup the session on its own,
360 : // mark it as nullptr here so we know we're done using it.
361 0 : m_Session = nullptr;
362 0 : }
363 :
364 0 : void CNetClient::Poll()
365 : {
366 0 : if (!m_Session)
367 0 : return;
368 :
369 0 : PROFILE3("NetClient::poll");
370 :
371 0 : CheckServerConnection();
372 0 : m_Session->ProcessPolledMessages();
373 0 : FetchMessage();
374 0 : }
375 :
376 0 : void CNetClient::CheckServerConnection()
377 : {
378 : // Trigger local warnings if the connection to the server is bad.
379 : // At most once per second.
380 0 : std::time_t now = std::time(nullptr);
381 0 : if (now <= m_LastConnectionCheck)
382 0 : return;
383 :
384 0 : m_LastConnectionCheck = now;
385 :
386 : // Report if we are losing the connection to the server
387 0 : std::uint32_t lastReceived = m_Session->GetLastReceivedTime();
388 0 : if (lastReceived > NETWORK_WARNING_TIMEOUT)
389 : {
390 0 : PushGuiMessage(
391 : "type", "netwarn",
392 : "warntype", "server-timeout",
393 : "lastReceivedTime", lastReceived);
394 0 : return;
395 : }
396 :
397 : // Report if we have a bad ping to the server.
398 0 : std::uint32_t meanRTT = m_Session->GetMeanRTT();
399 0 : if (meanRTT > NETWORK_BAD_PING)
400 : {
401 0 : PushGuiMessage(
402 : "type", "netwarn",
403 : "warntype", "server-latency",
404 : "meanRTT", meanRTT);
405 : }
406 : }
407 :
408 0 : JSObject* CNetClient::GetNextGUIMessage(const Script::Interface& guiInterface)
409 : {
410 0 : Unregister(nullptr);
411 0 : const Script::Request rq{guiInterface};
412 0 : m_GuiMessagePoll.emplace(GuiPollData{guiInterface, {rq.cx, JS::NewPromiseObject(rq.cx, nullptr)}});
413 :
414 0 : FetchMessage();
415 0 : return m_GuiMessagePoll.value().promise;
416 0 : }
417 :
418 0 : void CNetClient::Unregister(const Script::Interface* guiInterface)
419 : {
420 0 : if (!m_GuiMessagePoll.has_value() ||
421 0 : (guiInterface && &m_GuiMessagePoll.value().interface != guiInterface))
422 : {
423 0 : return;
424 : }
425 0 : auto& [interface, promise] = m_GuiMessagePoll.value();
426 0 : const Script::Request oldRq{interface};
427 0 : JS::ResolvePromise(oldRq.cx, promise, JS::UndefinedHandleValue);
428 0 : m_GuiMessagePoll.reset();
429 0 : }
430 :
431 0 : void CNetClient::FetchMessage()
432 : {
433 0 : if (m_GuiMessageQueue.empty() || !m_GuiMessagePoll.has_value() ||
434 0 : JS::GetPromiseState(m_GuiMessagePoll.value().promise) != JS::PromiseState::Pending)
435 : {
436 0 : return;
437 : }
438 :
439 0 : const Script::Request rq{m_GuiMessagePoll.value().interface};
440 0 : JS::RootedValue message{rq.cx};
441 0 : Script::ReadStructuredClone(rq, std::move(m_GuiMessageQueue.front()), &message);
442 0 : m_GuiMessageQueue.pop_front();
443 :
444 0 : JS::ResolvePromise(rq.cx, m_GuiMessagePoll.value().promise, message);
445 0 : }
446 :
447 0 : std::string CNetClient::TestReadGuiMessages()
448 : {
449 0 : Script::Request rq(GetScriptInterface());
450 :
451 0 : std::string r;
452 0 : while (true)
453 : {
454 0 : JS::RootedObject promise{rq.cx, GetNextGUIMessage(GetScriptInterface())};
455 0 : g_ScriptContext->RunJobs();
456 :
457 0 : if (JS::GetPromiseState(promise) == JS::PromiseState::Pending)
458 : break;
459 :
460 0 : JS::RootedValue msg{rq.cx, JS::GetPromiseResult(promise)};
461 0 : r += Script::ToString(rq, &msg) + "\n";
462 0 : }
463 0 : return r;
464 0 : }
465 :
466 0 : const Script::Interface& CNetClient::GetScriptInterface()
467 : {
468 0 : return m_Game->GetSimulation2()->GetScriptInterface();
469 : }
470 :
471 0 : void CNetClient::PostPlayerAssignmentsToScript()
472 : {
473 0 : Script::Request rq(GetScriptInterface());
474 :
475 0 : JS::RootedValue newAssignments(rq.cx);
476 0 : Script::CreateObject(rq, &newAssignments);
477 :
478 0 : for (const std::pair<const CStr, PlayerAssignment>& p : m_PlayerAssignments)
479 : {
480 0 : JS::RootedValue assignment(rq.cx);
481 :
482 0 : Script::CreateObject(
483 : rq,
484 : &assignment,
485 0 : "name", p.second.m_Name,
486 0 : "player", p.second.m_PlayerID,
487 0 : "status", p.second.m_Status);
488 :
489 0 : Script::SetProperty(rq, newAssignments, p.first.c_str(), assignment);
490 0 : }
491 :
492 0 : PushGuiMessage(
493 : "type", "players",
494 : "newAssignments", newAssignments);
495 0 : }
496 :
497 0 : bool CNetClient::SendMessage(const CNetMessage* message)
498 : {
499 0 : if (!m_Session)
500 : return false;
501 :
502 0 : return m_Session->SendMessage(message);
503 : }
504 :
505 0 : void CNetClient::HandleConnect()
506 : {
507 0 : Update(static_cast<unsigned int>(NMT_CONNECT_COMPLETE), nullptr);
508 0 : }
509 :
510 0 : void CNetClient::HandleDisconnect(std::uint32_t reason)
511 : {
512 0 : if (reason == NDR_INCORRECT_SOFTWARE_VERSION) {
513 0 : const auto& mismatch = CheckHandshake(m_ServerHandshake, CreateHandshake<CCliHandshakeMessage>());
514 0 : ENSURE(mismatch.has_value());
515 0 : PushGuiMessage(
516 : "type", "netstatus",
517 : "status", "disconnected",
518 : "reason", reason,
519 0 : "mismatch_type", mismatch->componentType,
520 0 : "client_mismatch_component", mismatch->clientComponent,
521 0 : "server_mismatch_component", mismatch->serverComponent);
522 0 : } else
523 0 : PushGuiMessage(
524 : "type", "netstatus",
525 : "status", "disconnected",
526 : "reason", reason);
527 :
528 0 : DestroyConnection();
529 :
530 : // Update the state immediately to UNCONNECTED (don't bother with FSM transitions since
531 : // we'd need one for every single state, and we don't need to use per-state actions)
532 0 : SetCurrState(NCS_UNCONNECTED);
533 0 : }
534 :
535 0 : void CNetClient::SendGameSetupMessage(JS::MutableHandleValue attrs, const Script::Interface& scriptInterface)
536 : {
537 0 : CGameSetupMessage gameSetup(scriptInterface);
538 0 : gameSetup.m_Data = attrs;
539 0 : SendMessage(&gameSetup);
540 0 : }
541 :
542 0 : void CNetClient::SendAssignPlayerMessage(const int playerID, const CStr& guid)
543 : {
544 0 : CAssignPlayerMessage assignPlayer;
545 0 : assignPlayer.m_PlayerID = playerID;
546 0 : assignPlayer.m_GUID = guid;
547 0 : SendMessage(&assignPlayer);
548 0 : }
549 :
550 0 : void CNetClient::SendChatMessage(const std::wstring& text,
551 : std::optional<std::vector<std::string>> receivers)
552 : {
553 0 : CChatMessage chat;
554 0 : chat.m_Message = text;
555 0 : if (receivers)
556 0 : std::transform(receivers->begin(), receivers->end(), std::back_inserter(chat.m_Receivers),
557 0 : [](std::string& receiver)
558 : {
559 0 : return CChatMessage::S_m_Receivers{std::move(receiver)};
560 : });
561 0 : SendMessage(&chat);
562 0 : }
563 :
564 0 : void CNetClient::SendReadyMessage(const int status)
565 : {
566 0 : CReadyMessage readyStatus;
567 0 : readyStatus.m_Status = status;
568 0 : SendMessage(&readyStatus);
569 0 : }
570 :
571 0 : void CNetClient::SendClearAllReadyMessage()
572 : {
573 0 : CClearAllReadyMessage clearAllReady;
574 0 : SendMessage(&clearAllReady);
575 0 : }
576 :
577 0 : void CNetClient::SendStartGameMessage(const CStr& initAttribs)
578 : {
579 0 : CGameStartMessage gameStart;
580 0 : gameStart.m_InitAttributes = initAttribs;
581 0 : SendMessage(&gameStart);
582 0 : }
583 :
584 0 : void CNetClient::SendFlareMessage(const CStr& positionX, const CStr& positionY, const CStr& positionZ)
585 : {
586 0 : CFlareMessage flare;
587 0 : flare.m_PositionX = positionX;
588 0 : flare.m_PositionY = positionY;
589 0 : flare.m_PositionZ = positionZ;
590 0 : SendMessage(&flare);
591 0 : }
592 :
593 0 : void CNetClient::SendStartSavedGameMessage(const CStr& initAttribs, const CStr& savedState)
594 : {
595 0 : m_SavedState = savedState;
596 :
597 0 : CGameSavedStartMessage gameSavedStart;
598 0 : gameSavedStart.m_InitAttributes = initAttribs;
599 0 : SendMessage(&gameSavedStart);
600 0 : }
601 :
602 0 : void CNetClient::SendRejoinedMessage()
603 : {
604 0 : CRejoinedMessage rejoinedMessage;
605 0 : SendMessage(&rejoinedMessage);
606 0 : }
607 :
608 0 : void CNetClient::SendKickPlayerMessage(const CStrW& playerName, bool ban)
609 : {
610 0 : CKickedMessage kickPlayer;
611 0 : kickPlayer.m_Name = playerName;
612 0 : kickPlayer.m_Ban = ban;
613 0 : SendMessage(&kickPlayer);
614 0 : }
615 :
616 0 : void CNetClient::SendPausedMessage(bool pause)
617 : {
618 0 : CClientPausedMessage pausedMessage;
619 0 : pausedMessage.m_Pause = pause;
620 0 : SendMessage(&pausedMessage);
621 0 : }
622 :
623 0 : bool CNetClient::HandleMessage(CNetMessage* message)
624 : {
625 : // Handle non-FSM messages first
626 :
627 0 : Status status = m_Session->GetFileTransferer().HandleMessageReceive(*message);
628 0 : if (status == INFO::OK)
629 : return true;
630 0 : if (status != INFO::SKIPPED)
631 : return false;
632 :
633 0 : if (message->GetType() == NMT_FILE_TRANSFER_REQUEST)
634 : {
635 0 : CFileTransferRequestMessage* reqMessage = static_cast<CFileTransferRequestMessage*>(message);
636 :
637 0 : std::string gameState{[&]
638 : {
639 0 : if (static_cast<CNetFileTransferer::RequestType>(reqMessage->m_RequestType) ==
640 : CNetFileTransferer::RequestType::LOADGAME)
641 : {
642 0 : return std::exchange(m_SavedState, {});
643 : }
644 :
645 0 : std::stringstream stream;
646 :
647 0 : LOGMESSAGERENDER("Serializing game at turn {} for rejoining player",
648 : m_ClientTurnManager->GetCurrentTurn());
649 0 : std::uint32_t turn = to_le32(m_ClientTurnManager->GetCurrentTurn());
650 0 : stream.write((char*)&turn, sizeof(turn));
651 :
652 0 : bool ok = m_Game->GetSimulation2()->SerializeState(stream);
653 0 : ENSURE(ok);
654 0 : return stream.str();
655 0 : }()};
656 :
657 0 : m_Session->GetFileTransferer().StartResponse(reqMessage->m_RequestID,
658 : std::move(gameState));
659 :
660 0 : return true;
661 0 : }
662 :
663 : // Update FSM
664 0 : bool ok = Update(message->GetType(), message);
665 0 : if (!ok)
666 : {
667 0 : LOGERROR("Net client: Error running FSM update (type={} state={})",
668 : static_cast<int>(message->GetType()), GetCurrState());
669 : }
670 : return ok;
671 : }
672 :
673 0 : void CNetClient::LoadFinished()
674 : {
675 0 : if (!m_JoinSyncBuffer.empty())
676 : {
677 : // We're rejoining a game, and just finished loading the initial map,
678 : // so deserialize the saved game state now
679 :
680 0 : std::stringstream stream(m_JoinSyncBuffer);
681 :
682 0 : std::uint32_t turn;
683 0 : stream.read((char*)&turn, sizeof(turn));
684 0 : turn = to_le32(turn);
685 :
686 0 : LOGMESSAGE("Rejoining client deserializing state at turn {}\n", turn);
687 :
688 0 : bool ok = m_Game->GetSimulation2()->DeserializeState(stream);
689 0 : ENSURE(ok);
690 :
691 0 : m_ClientTurnManager->ResetState(turn, turn);
692 :
693 0 : PushGuiMessage(
694 : "type", "netstatus",
695 : "status", "join_syncing");
696 0 : }
697 : else
698 : {
699 : // Connecting at the start of a game, so we'll wait for other players to finish loading
700 0 : PushGuiMessage(
701 : "type", "netstatus",
702 : "status", "waiting_for_players");
703 : }
704 :
705 0 : CLoadedGameMessage loaded;
706 0 : loaded.m_CurrentTurn = m_ClientTurnManager->GetCurrentTurn();
707 0 : SendMessage(&loaded);
708 0 : }
709 :
710 0 : void CNetClient::SendAuthenticateMessage()
711 : {
712 0 : CAuthenticateMessage authenticate;
713 0 : authenticate.m_Name = m_UserName;
714 0 : authenticate.m_Password = m_Password;
715 0 : authenticate.m_ControllerSecret = m_ControllerSecret;
716 0 : SendMessage(&authenticate);
717 0 : }
718 :
719 0 : void CNetClient::StartGame(const JS::MutableHandleValue initAttributes, const std::string& savedState)
720 : {
721 0 : const auto foundPlayer = m_PlayerAssignments.find(m_GUID);
722 0 : const std::int32_t player{foundPlayer != m_PlayerAssignments.end() ? foundPlayer->second.m_PlayerID :
723 0 : -1};
724 :
725 0 : m_ClientTurnManager = new CNetClientTurnManager{*m_Game->GetSimulation2(), *this,
726 0 : static_cast<int>(m_HostID), m_Game->GetReplayLogger()};
727 :
728 0 : m_Game->SetPlayerID(player);
729 0 : m_Game->StartGame(initAttributes, savedState);
730 0 : }
731 :
732 0 : bool CNetClient::OnConnect(CNetClient* client, CFsmEvent<CNetMessage*>* event)
733 : {
734 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CONNECT_COMPLETE));
735 :
736 0 : client->PushGuiMessage(
737 : "type", "netstatus",
738 : "status", "connected");
739 :
740 0 : return true;
741 : }
742 :
743 0 : bool CNetClient::OnHandshake(CNetClient* client, CFsmEvent<CNetMessage*>* event)
744 : {
745 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_SERVER_HANDSHAKE));
746 0 : client->m_ServerHandshake = *static_cast<CSrvHandshakeMessage*>(event->GetParamRef());
747 :
748 0 : CCliHandshakeMessage handshake(CreateHandshake<CCliHandshakeMessage>());
749 :
750 0 : client->SendMessage(&handshake);
751 0 : return true;
752 : }
753 :
754 0 : bool CNetClient::OnHandshakeResponse(CNetClient* client, CFsmEvent<CNetMessage*>* event)
755 : {
756 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_SERVER_HANDSHAKE_RESPONSE));
757 :
758 0 : CSrvHandshakeResponseMessage* message = static_cast<CSrvHandshakeResponseMessage*>(event->GetParamRef());
759 :
760 0 : client->m_GUID = message->m_GUID;
761 :
762 0 : if (message->m_Flags & PS_NETWORK_FLAG_REQUIRE_LOBBYAUTH)
763 : {
764 : #if CONFIG2_LOBBY
765 0 : if (g_XmppClient && !client->m_HostJID.empty())
766 0 : g_XmppClient->SendIqLobbyAuth(client->m_HostJID, client->m_GUID);
767 : else
768 : #endif
769 : {
770 0 : client->PushGuiMessage(
771 : "type", "netstatus",
772 : "status", "disconnected",
773 0 : "reason", static_cast<std::int32_t>(NDR_LOBBY_AUTH_FAILED));
774 :
775 0 : LOGMESSAGE("Net client: Couldn't send lobby auth xmpp message");
776 : }
777 0 : return true;
778 : }
779 :
780 0 : client->SendAuthenticateMessage();
781 0 : return true;
782 : }
783 :
784 0 : bool CNetClient::OnAuthenticateRequest(CNetClient* client, CFsmEvent<CNetMessage*>* event)
785 : {
786 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_AUTHENTICATE));
787 :
788 0 : client->SendAuthenticateMessage();
789 0 : return true;
790 : }
791 :
792 0 : bool CNetClient::OnAuthenticate(CNetClient* client, CFsmEvent<CNetMessage*>* event)
793 : {
794 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_AUTHENTICATE_RESULT));
795 :
796 0 : CAuthenticateResultMessage* message = static_cast<CAuthenticateResultMessage*>(event->GetParamRef());
797 :
798 0 : LOGMESSAGE("Net: Authentication result: host={}, {}", message->m_HostID,
799 : utf8_from_wstring(message->m_Message));
800 :
801 0 : client->m_HostID = message->m_HostID;
802 0 : client->m_Rejoin = message->m_Code == ARC_OK_REJOINING;
803 0 : client->m_IsController = message->m_IsController;
804 :
805 0 : client->PushGuiMessage(
806 : "type", "netstatus",
807 : "status", "authenticated",
808 0 : "rejoining", client->m_Rejoin,
809 0 : "savedGame", message->m_Code == ARC_OK_SAVED_GAME);
810 :
811 0 : return true;
812 : }
813 :
814 0 : bool CNetClient::OnChat(CNetClient* client, CFsmEvent<CNetMessage*>* event)
815 : {
816 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CHAT));
817 :
818 0 : CChatMessage* message = static_cast<CChatMessage*>(event->GetParamRef());
819 :
820 0 : client->PushGuiMessage(
821 : "type", "chat",
822 0 : "guid", message->m_SenderGUID,
823 0 : "text", message->m_Message);
824 :
825 0 : return true;
826 : }
827 :
828 0 : bool CNetClient::OnReady(CNetClient* client, CFsmEvent<CNetMessage*>* event)
829 : {
830 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_READY));
831 :
832 0 : CReadyMessage* message = static_cast<CReadyMessage*>(event->GetParamRef());
833 :
834 0 : client->PushGuiMessage(
835 : "type", "ready",
836 0 : "guid", message->m_GUID,
837 0 : "status", message->m_Status);
838 :
839 0 : return true;
840 : }
841 :
842 0 : bool CNetClient::OnGameSetup(CNetClient* client, CFsmEvent<CNetMessage*>* event)
843 : {
844 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_GAME_SETUP));
845 :
846 0 : CGameSetupMessage* message = static_cast<CGameSetupMessage*>(event->GetParamRef());
847 :
848 0 : client->PushGuiMessage(
849 : "type", "gamesetup",
850 0 : "data", message->m_Data);
851 :
852 0 : return true;
853 : }
854 :
855 0 : bool CNetClient::OnPlayerAssignment(CNetClient* client, CFsmEvent<CNetMessage*>* event)
856 : {
857 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_PLAYER_ASSIGNMENT));
858 :
859 0 : CPlayerAssignmentMessage* message = static_cast<CPlayerAssignmentMessage*>(event->GetParamRef());
860 :
861 : // Unpack the message
862 0 : PlayerAssignmentMap newPlayerAssignments;
863 0 : for (size_t i = 0; i < message->m_Hosts.size(); ++i)
864 : {
865 0 : PlayerAssignment assignment;
866 0 : assignment.m_Enabled = true;
867 0 : assignment.m_Name = message->m_Hosts[i].m_Name;
868 0 : assignment.m_PlayerID = message->m_Hosts[i].m_PlayerID;
869 0 : assignment.m_Status = message->m_Hosts[i].m_Status;
870 0 : newPlayerAssignments[message->m_Hosts[i].m_GUID] = assignment;
871 0 : }
872 :
873 0 : client->m_PlayerAssignments.swap(newPlayerAssignments);
874 :
875 0 : client->PostPlayerAssignmentsToScript();
876 :
877 0 : return true;
878 : }
879 :
880 : // This is called either when the host clicks the StartGame button or
881 : // if this client rejoins and finishes the download of the simstate.
882 0 : bool CNetClient::OnGameStart(CNetClient* client, CFsmEvent<CNetMessage*>* event)
883 : {
884 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_GAME_START));
885 :
886 0 : CGameStartMessage* message = static_cast<CGameStartMessage*>(event->GetParamRef());
887 :
888 0 : const Script::Interface& scriptInterface{client->m_Game->GetSimulation2()->GetScriptInterface()};
889 0 : Script::Request rq{scriptInterface};
890 0 : JS::RootedValue initAttribs{rq.cx};
891 0 : Script::ParseJSON(rq, message->m_InitAttributes, &initAttribs);
892 :
893 0 : client->PushGuiMessage("type", "start", "initAttributes", initAttribs);
894 0 : client->StartGame(&initAttribs, "");
895 0 : return true;
896 : }
897 :
898 0 : bool CNetClient::OnSavedGameStart(CNetClient* client, CFsmEvent<CNetMessage*>* event)
899 : {
900 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_SAVED_GAME_START));
901 0 : CGameSavedStartMessage* message{static_cast<CGameSavedStartMessage*>(event->GetParamRef())};
902 :
903 0 : const Script::Interface& scriptInterface{client->m_Game->GetSimulation2()->GetScriptInterface()};
904 0 : Script::Request rq{scriptInterface};
905 0 : const std::shared_ptr<JS::RootedValue> initAttribs{std::make_shared<JS::RootedValue>(rq.cx)};
906 0 : Script::ParseJSON(rq, message->m_InitAttributes, &*initAttribs);
907 :
908 0 : client->PushGuiMessage("type", "start", "initAttributes", *initAttribs);
909 :
910 0 : client->m_Session->GetFileTransferer().StartTask(CNetFileTransferer::RequestType::LOADGAME,
911 0 : [client, initAttribs](std::string buffer)
912 : {
913 0 : client->StartGame(&*initAttribs, std::move(buffer));
914 : });
915 0 : return true;
916 0 : }
917 :
918 :
919 0 : bool CNetClient::OnJoinSyncStart(CNetClient* client, CFsmEvent<CNetMessage*>* event)
920 : {
921 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_JOIN_SYNC_START));
922 :
923 0 : CJoinSyncStartMessage* joinSyncStartMessage = (CJoinSyncStartMessage*)event->GetParamRef();
924 :
925 : // The server wants us to start downloading the game state from it, so do so
926 0 : client->m_Session->GetFileTransferer().StartTask(CNetFileTransferer::RequestType::REJOIN,
927 0 : [client, initAttributes = std::move(joinSyncStartMessage->m_InitAttributes)](std::string buffer)
928 0 : mutable
929 : {
930 : // We've received the game state from the server.
931 :
932 : // Save it so we can use it after the map has finished loading.
933 0 : client->m_JoinSyncBuffer = std::move(buffer);
934 :
935 : // Pretend the server told us to start the game.
936 0 : CGameStartMessage start;
937 0 : start.m_InitAttributes = std::move(initAttributes);
938 0 : client->HandleMessage(&start);
939 0 : });
940 :
941 0 : return true;
942 0 : }
943 :
944 0 : bool CNetClient::OnJoinSyncEndCommandBatch(CNetClient* client, CFsmEvent<CNetMessage*>* event)
945 : {
946 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_END_COMMAND_BATCH));
947 :
948 0 : CEndCommandBatchMessage* endMessage = (CEndCommandBatchMessage*)event->GetParamRef();
949 :
950 0 : client->m_ClientTurnManager->FinishedAllCommands(endMessage->m_Turn, endMessage->m_TurnLength);
951 :
952 : // Execute all the received commands for the latest turn
953 0 : client->m_ClientTurnManager->UpdateFastForward();
954 :
955 0 : return true;
956 : }
957 :
958 0 : bool CNetClient::OnRejoined(CNetClient* client, CFsmEvent<CNetMessage*>* event)
959 : {
960 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_REJOINED));
961 :
962 0 : CRejoinedMessage* message = static_cast<CRejoinedMessage*>(event->GetParamRef());
963 :
964 0 : client->PushGuiMessage(
965 : "type", "rejoined",
966 0 : "guid", message->m_GUID);
967 :
968 0 : return true;
969 : }
970 :
971 0 : bool CNetClient::OnKicked(CNetClient* client, CFsmEvent<CNetMessage*>* event)
972 : {
973 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_KICKED));
974 :
975 0 : CKickedMessage* message = static_cast<CKickedMessage*>(event->GetParamRef());
976 :
977 0 : client->PushGuiMessage(
978 0 : "username", message->m_Name,
979 : "type", "kicked",
980 0 : "banned", message->m_Ban != 0);
981 :
982 0 : return true;
983 : }
984 :
985 0 : bool CNetClient::OnClientTimeout(CNetClient* client, CFsmEvent<CNetMessage*>* event)
986 : {
987 : // Report the timeout of some other client
988 :
989 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLIENT_TIMEOUT));
990 :
991 0 : CClientTimeoutMessage* message = static_cast<CClientTimeoutMessage*>(event->GetParamRef());
992 :
993 0 : client->PushGuiMessage(
994 : "type", "netwarn",
995 : "warntype", "client-timeout",
996 0 : "guid", message->m_GUID,
997 0 : "lastReceivedTime", message->m_LastReceivedTime);
998 :
999 0 : return true;
1000 : }
1001 :
1002 0 : bool CNetClient::OnClientPerformance(CNetClient* client, CFsmEvent<CNetMessage*>* event)
1003 : {
1004 : // Performance statistics for one or multiple clients
1005 :
1006 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLIENT_PERFORMANCE));
1007 :
1008 0 : CClientPerformanceMessage* message = static_cast<CClientPerformanceMessage*>(event->GetParamRef());
1009 :
1010 : // Display warnings for other clients with bad ping
1011 0 : for (size_t i = 0; i < message->m_Clients.size(); ++i)
1012 : {
1013 0 : if (message->m_Clients[i].m_MeanRTT < NETWORK_BAD_PING || message->m_Clients[i].m_GUID == client->m_GUID)
1014 0 : continue;
1015 :
1016 0 : client->PushGuiMessage(
1017 : "type", "netwarn",
1018 : "warntype", "client-latency",
1019 0 : "guid", message->m_Clients[i].m_GUID,
1020 0 : "meanRTT", message->m_Clients[i].m_MeanRTT);
1021 : }
1022 :
1023 0 : return true;
1024 : }
1025 :
1026 0 : bool CNetClient::OnClientsLoading(CNetClient* client, CFsmEvent<CNetMessage*> *event)
1027 : {
1028 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLIENTS_LOADING));
1029 :
1030 0 : CClientsLoadingMessage* message = static_cast<CClientsLoadingMessage*>(event->GetParamRef());
1031 :
1032 0 : std::vector<CStr> guids;
1033 0 : guids.reserve(message->m_Clients.size());
1034 0 : for (const CClientsLoadingMessage::S_m_Clients& mClient : message->m_Clients)
1035 0 : guids.push_back(mClient.m_GUID);
1036 :
1037 0 : client->PushGuiMessage(
1038 : "type", "clients-loading",
1039 : "guids", guids);
1040 0 : return true;
1041 : }
1042 :
1043 0 : bool CNetClient::OnClientPaused(CNetClient* client, CFsmEvent<CNetMessage*> *event)
1044 : {
1045 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLIENT_PAUSED));
1046 :
1047 0 : CClientPausedMessage* message = static_cast<CClientPausedMessage*>(event->GetParamRef());
1048 :
1049 0 : client->PushGuiMessage(
1050 : "type", "paused",
1051 0 : "pause", message->m_Pause != 0,
1052 0 : "guid", message->m_GUID);
1053 :
1054 0 : return true;
1055 : }
1056 :
1057 0 : bool CNetClient::OnLoadedGame(CNetClient* client, CFsmEvent<CNetMessage*>* event)
1058 : {
1059 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_LOADED_GAME));
1060 :
1061 : // All players have loaded the game - start running the turn manager
1062 : // so that the game begins
1063 0 : client->m_Game->SetTurnManager(client->m_ClientTurnManager);
1064 :
1065 0 : client->PushGuiMessage(
1066 : "type", "netstatus",
1067 : "status", "active");
1068 :
1069 : // If we have rejoined an in progress game, send the rejoined message to the server.
1070 0 : if (client->m_Rejoin)
1071 0 : client->SendRejoinedMessage();
1072 :
1073 0 : return true;
1074 : }
1075 :
1076 0 : bool CNetClient::OnInGame(CNetClient* client, CFsmEvent<CNetMessage*>* event)
1077 : {
1078 : // TODO: should split each of these cases into a separate method
1079 :
1080 0 : CNetMessage* message = static_cast<CNetMessage*>(event->GetParamRef());
1081 :
1082 0 : if (message)
1083 : {
1084 0 : if (message->GetType() == NMT_SIMULATION_COMMAND)
1085 : {
1086 0 : CSimulationMessage* simMessage = static_cast<CSimulationMessage*> (message);
1087 0 : client->m_ClientTurnManager->OnSimulationMessage(simMessage);
1088 : }
1089 0 : else if (message->GetType() == NMT_SYNC_ERROR)
1090 : {
1091 0 : CSyncErrorMessage* syncMessage = static_cast<CSyncErrorMessage*> (message);
1092 0 : client->m_ClientTurnManager->OnSyncError(syncMessage->m_Turn, syncMessage->m_HashExpected, syncMessage->m_PlayerNames);
1093 : }
1094 0 : else if (message->GetType() == NMT_END_COMMAND_BATCH)
1095 : {
1096 0 : CEndCommandBatchMessage* endMessage = static_cast<CEndCommandBatchMessage*> (message);
1097 0 : client->m_ClientTurnManager->FinishedAllCommands(endMessage->m_Turn, endMessage->m_TurnLength);
1098 : }
1099 : }
1100 :
1101 0 : return true;
1102 : }
1103 :
1104 0 : bool CNetClient::OnFlare(CNetClient* client, CFsmEvent<CNetMessage*>* event)
1105 : {
1106 0 : ENSURE(event->GetType() == static_cast<unsigned int>(NMT_FLARE));
1107 :
1108 0 : CFlareMessage* message = static_cast<CFlareMessage*>(event->GetParamRef());
1109 :
1110 0 : const Script::Interface& scriptInterface = client->m_Game->GetSimulation2()->GetScriptInterface();
1111 0 : Script::Request rq(scriptInterface);
1112 0 : JS::RootedValue position(rq.cx);
1113 0 : Script::CreateObject(
1114 : rq, &position,
1115 : // The coordinates are transmitted as strings (because because direct (de)serialisation of floating point numbers is not supported).
1116 0 : "x", message->m_PositionX.ToDouble(),
1117 0 : "y", message->m_PositionY.ToDouble(),
1118 0 : "z", message->m_PositionZ.ToDouble()
1119 : );
1120 :
1121 0 : client->PushGuiMessage(
1122 : "type", "flare",
1123 0 : "guid", message->m_GUID,
1124 : "position", position);
1125 :
1126 0 : return true;
1127 : }
|