CServerHandler.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. /*
  2. * CServerHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CServerHandler.h"
  12. #include "CPlayerInterface.h"
  13. #include "Client.h"
  14. #include "GameChatHandler.h"
  15. #include "GameEngine.h"
  16. #include "GameInstance.h"
  17. #include "LobbyClientNetPackVisitors.h"
  18. #include "ServerRunner.h"
  19. #include "globalLobby/GlobalLobbyClient.h"
  20. #include "gui/WindowHandler.h"
  21. #include "lobby/CSelectionBase.h"
  22. #include "lobby/CLobbyScreen.h"
  23. #include "lobby/CBonusSelection.h"
  24. #include "netlag/NetworkLagCompensator.h"
  25. #include "media/CMusicHandler.h"
  26. #include "media/IVideoPlayer.h"
  27. #include "mainmenu/CMainMenu.h"
  28. #include "mainmenu/CPrologEpilogVideo.h"
  29. #include "mainmenu/CHighScoreScreen.h"
  30. #include "windows/InfoWindows.h"
  31. #include "windows/GUIClasses.h"
  32. #include "../lib/CConfigHandler.h"
  33. #include "../lib/GameLibrary.h"
  34. #include "../lib/texts/CGeneralTextHandler.h"
  35. #include "../lib/ConditionalWait.h"
  36. #include "../lib/CThreadHelper.h"
  37. #include "../lib/StartInfo.h"
  38. #include "../lib/TurnTimerInfo.h"
  39. #include "../lib/VCMIDirs.h"
  40. #include "../lib/campaign/CampaignState.h"
  41. #include "../lib/gameState/CGameState.h"
  42. #include "../lib/gameState/HighScore.h"
  43. #include "../lib/CPlayerState.h"
  44. #include "../lib/mapping/CMapInfo.h"
  45. #include "../lib/mapObjects/CGTownInstance.h"
  46. #include "../lib/mapObjects/MiscObjects.h"
  47. #include "../lib/modding/ModIncompatibility.h"
  48. #include "../lib/rmg/CMapGenOptions.h"
  49. #include "../lib/serializer/GameConnection.h"
  50. #include "../lib/UnlockGuard.h"
  51. #include <boost/uuid/uuid.hpp>
  52. #include <boost/uuid/uuid_io.hpp>
  53. #include <boost/uuid/uuid_generators.hpp>
  54. #include <vcmi/events/EventBus.h>
  55. #include <SDL_thread.h>
  56. #include <boost/lexical_cast.hpp>
  57. CServerHandler::~CServerHandler()
  58. {
  59. if (serverRunner)
  60. serverRunner->shutdown();
  61. networkHandler->stop();
  62. if (serverRunner)
  63. serverRunner->wait();
  64. serverRunner.reset();
  65. if (threadNetwork.joinable())
  66. {
  67. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  68. threadNetwork.join();
  69. }
  70. }
  71. void CServerHandler::endNetwork()
  72. {
  73. if (client)
  74. client->endNetwork();
  75. networkHandler->stop();
  76. if (threadNetwork.joinable())
  77. {
  78. auto unlockInterface = vstd::makeUnlockGuard(ENGINE->interfaceMutex);
  79. threadNetwork.join();
  80. }
  81. }
  82. CServerHandler::CServerHandler()
  83. : networkHandler(INetworkHandler::createHandler())
  84. , lobbyClient(std::make_unique<GlobalLobbyClient>())
  85. , gameChat(std::make_unique<GameChatHandler>())
  86. , threadNetwork(&CServerHandler::threadRunNetwork, this)
  87. , state(EClientState::NONE)
  88. , serverPort(0)
  89. , campaignStateToSend(nullptr)
  90. , screenType(ESelectionScreen::unknown)
  91. , serverMode(EServerMode::NONE)
  92. , loadMode(ELoadMode::NONE)
  93. , battleMode(false)
  94. , client(nullptr)
  95. {
  96. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  97. }
  98. void CServerHandler::threadRunNetwork()
  99. {
  100. setThreadName("runNetwork");
  101. logGlobal->info("Starting network thread");
  102. try {
  103. networkHandler->run();
  104. }
  105. catch (const TerminationRequestedException &)
  106. {
  107. // VCMI can run SDL methods on network thread, leading to usage of thread-local storage by SDL
  108. // Such storage needs to be cleaned up manually for threads that were not created by SDL
  109. SDL_TLSCleanup();
  110. logGlobal->info("Terminating network thread");
  111. return;
  112. }
  113. SDL_TLSCleanup();
  114. logGlobal->info("Ending network thread");
  115. }
  116. void CServerHandler::resetStateForLobby(EStartMode mode, ESelectionScreen screen, EServerMode newServerMode, const std::vector<std::string> & playerNames)
  117. {
  118. hostClientId = GameConnectionID::INVALID;
  119. setState(EClientState::NONE);
  120. serverMode = newServerMode;
  121. mapToStart = nullptr;
  122. th = std::make_unique<CStopWatch>();
  123. logicConnection.reset();
  124. si = std::make_shared<StartInfo>();
  125. localPlayerNames.clear();
  126. si->difficulty = 1;
  127. si->mode = mode;
  128. screenType = screen;
  129. localPlayerNames.clear();
  130. if(!playerNames.empty()) //if have custom set of player names - use it
  131. localPlayerNames = playerNames;
  132. else
  133. {
  134. std::string playerName = settings["general"]["playerName"].String();
  135. if(playerName == "Player")
  136. playerName = LIBRARY->generaltexth->translate("core.genrltxt.434");
  137. localPlayerNames.push_back(playerName);
  138. }
  139. gameChat->resetMatchState();
  140. lobbyClient->resetMatchState();
  141. }
  142. GameChatHandler & CServerHandler::getGameChat()
  143. {
  144. return *gameChat;
  145. }
  146. GlobalLobbyClient & CServerHandler::getGlobalLobby()
  147. {
  148. return *lobbyClient;
  149. }
  150. INetworkHandler & CServerHandler::getNetworkHandler()
  151. {
  152. return *networkHandler;
  153. }
  154. void CServerHandler::startLocalServerAndConnect(bool connectToLobby)
  155. {
  156. logNetwork->trace("\tLocal server startup has been requested");
  157. #ifdef VCMI_MOBILE
  158. // mobile apps can't spawn separate processes - only thread mode is available
  159. serverRunner.reset(new ServerThreadRunner());
  160. #else
  161. if (settings["server"]["useProcess"].Bool())
  162. serverRunner.reset(new ServerProcessRunner());
  163. else
  164. serverRunner.reset(new ServerThreadRunner());
  165. #endif
  166. auto si = std::make_shared<StartInfo>();
  167. auto lastDifficulty = settings["general"]["lastDifficulty"];
  168. si->difficulty = lastDifficulty.Integer();
  169. logNetwork->trace("\tStarting local server");
  170. serverRunner->start(loadMode == ELoadMode::MULTI, connectToLobby, si);
  171. logNetwork->trace("\tConnecting to local server");
  172. connectToServer(getLocalHostname(), getLocalPort());
  173. logNetwork->trace("\tWaiting for connection");
  174. }
  175. void CServerHandler::connectToServer(const std::string & addr, const ui16 port)
  176. {
  177. setState(EClientState::CONNECTING);
  178. serverHostname = addr;
  179. serverPort = port;
  180. if (!isServerLocal())
  181. {
  182. Settings remoteAddress = settings.write["server"]["remoteHostname"];
  183. remoteAddress->String() = addr;
  184. Settings remotePort = settings.write["server"]["remotePort"];
  185. remotePort->Integer() = port;
  186. networkHandler->connectToRemote(*this, addr, port);
  187. }
  188. else
  189. {
  190. serverRunner->connect(*networkHandler, *this);
  191. }
  192. }
  193. void CServerHandler::onConnectionFailed(const std::string & errorMessage)
  194. {
  195. assert(getState() == EClientState::CONNECTING);
  196. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  197. if (isServerLocal())
  198. {
  199. // retry - local server might be still starting up
  200. logNetwork->debug("\nCannot establish connection. %s. Retrying...", errorMessage);
  201. networkHandler->createTimer(*this, std::chrono::milliseconds(100));
  202. }
  203. else
  204. {
  205. // remote server refused connection - show error message
  206. setState(EClientState::NONE);
  207. CInfoWindow::showInfoDialog(LIBRARY->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  208. }
  209. }
  210. void CServerHandler::onTimer()
  211. {
  212. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  213. if(getState() == EClientState::CONNECTION_CANCELLED)
  214. {
  215. logNetwork->info("Connection aborted by player!");
  216. serverRunner->wait();
  217. serverRunner.reset();
  218. if (ENGINE->windows().topWindow<CSimpleJoinScreen>() != nullptr)
  219. ENGINE->windows().popWindows(1);
  220. return;
  221. }
  222. assert(isServerLocal());
  223. serverRunner->connect(*networkHandler, *this);
  224. }
  225. void CServerHandler::onConnectionEstablished(const NetworkConnectionPtr & netConnection)
  226. {
  227. assert(getState() == EClientState::CONNECTING);
  228. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  229. networkConnection = netConnection;
  230. logNetwork->info("Connection established");
  231. if (serverMode == EServerMode::LOBBY_GUEST)
  232. {
  233. // say hello to lobby to switch connection to proxy mode
  234. getGlobalLobby().sendProxyConnectionLogin(netConnection);
  235. }
  236. logicConnection = std::make_shared<GameConnection>(netConnection);
  237. logicConnection->uuid = uuid;
  238. logicConnection->enterLobbyConnectionMode();
  239. sendClientConnecting();
  240. }
  241. void CServerHandler::applyPackOnLobbyScreen(CPackForLobby & pack)
  242. {
  243. ApplyOnLobbyScreenNetPackVisitor visitor(*this, dynamic_cast<CLobbyScreen *>(SEL));
  244. pack.visit(visitor);
  245. ENGINE->windows().totalRedraw();
  246. }
  247. std::set<PlayerColor> CServerHandler::getHumanColors()
  248. {
  249. return clientHumanColors(logicConnection->connectionID);
  250. }
  251. PlayerColor CServerHandler::myFirstColor() const
  252. {
  253. return clientFirstColor(logicConnection->connectionID);
  254. }
  255. bool CServerHandler::isMyColor(PlayerColor color) const
  256. {
  257. return isClientColor(logicConnection->connectionID, color);
  258. }
  259. PlayerConnectionID CServerHandler::myFirstId() const
  260. {
  261. return clientFirstId(logicConnection->connectionID);
  262. }
  263. EClientState CServerHandler::getState() const
  264. {
  265. return state;
  266. }
  267. void CServerHandler::setState(EClientState newState)
  268. {
  269. if (newState == EClientState::CONNECTION_CANCELLED && serverRunner != nullptr)
  270. serverRunner->shutdown();
  271. state = newState;
  272. }
  273. bool CServerHandler::isServerLocal() const
  274. {
  275. return serverRunner != nullptr;
  276. }
  277. bool CServerHandler::isHost() const
  278. {
  279. return logicConnection && hostClientId == logicConnection->connectionID;
  280. }
  281. bool CServerHandler::isGuest() const
  282. {
  283. return !logicConnection || hostClientId != logicConnection->connectionID;
  284. }
  285. const std::string & CServerHandler::getLocalHostname() const
  286. {
  287. return settings["server"]["localHostname"].String();
  288. }
  289. ui16 CServerHandler::getLocalPort() const
  290. {
  291. return settings["server"]["localPort"].Integer();
  292. }
  293. const std::string & CServerHandler::getRemoteHostname() const
  294. {
  295. return settings["server"]["remoteHostname"].String();
  296. }
  297. ui16 CServerHandler::getRemotePort() const
  298. {
  299. return settings["server"]["remotePort"].Integer();
  300. }
  301. const std::string & CServerHandler::getCurrentHostname() const
  302. {
  303. return serverHostname;
  304. }
  305. ui16 CServerHandler::getCurrentPort() const
  306. {
  307. return serverPort;
  308. }
  309. void CServerHandler::sendClientConnecting() const
  310. {
  311. LobbyClientConnected lcc;
  312. lcc.uuid = uuid;
  313. lcc.names = localPlayerNames;
  314. lcc.mode = si->mode;
  315. sendLobbyPack(lcc);
  316. }
  317. void CServerHandler::sendClientDisconnecting()
  318. {
  319. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  320. if(getState() == EClientState::DISCONNECTING)
  321. {
  322. assert(0);
  323. return;
  324. }
  325. setState(EClientState::DISCONNECTING);
  326. mapToStart = nullptr;
  327. LobbyClientDisconnected lcd;
  328. lcd.clientId = logicConnection->connectionID;
  329. logNetwork->info("Connection has been requested to be closed.");
  330. if(isServerLocal())
  331. {
  332. lcd.shutdownServer = true;
  333. logNetwork->info("Sent closing signal to the server");
  334. }
  335. else
  336. {
  337. logNetwork->info("Sent leaving signal to the server");
  338. }
  339. sendLobbyPack(lcd);
  340. networkConnection->close();
  341. networkConnection.reset();
  342. logicConnection.reset();
  343. waitForServerShutdown();
  344. }
  345. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  346. {
  347. setState(EClientState::LOBBY_CAMPAIGN);
  348. LobbySetCampaign lsc;
  349. lsc.ourCampaign = newCampaign;
  350. sendLobbyPack(lsc);
  351. }
  352. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  353. {
  354. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  355. return;
  356. LobbySetCampaignMap lscm;
  357. lscm.mapId = mapId;
  358. sendLobbyPack(lscm);
  359. }
  360. void CServerHandler::setCampaignBonus(int bonusId) const
  361. {
  362. if(getState() == EClientState::GAMEPLAY) // FIXME: UI shouldn't sent commands in first place
  363. return;
  364. LobbySetCampaignBonus lscb;
  365. lscb.bonusId = bonusId;
  366. sendLobbyPack(lscb);
  367. }
  368. void CServerHandler::setBattleOnlyModeStartInfo(std::shared_ptr<BattleOnlyModeStartInfo> startInfo) const
  369. {
  370. LobbySetBattleOnlyModeStartInfo lsbomsui;
  371. lsbomsui.startInfo = startInfo;
  372. sendLobbyPack(lsbomsui);
  373. }
  374. void CServerHandler::setMapInfo(std::shared_ptr<CMapInfo> to, std::shared_ptr<CMapGenOptions> mapGenOpts) const
  375. {
  376. LobbySetMap lsm;
  377. lsm.mapInfo = to;
  378. lsm.mapGenOpts = mapGenOpts;
  379. sendLobbyPack(lsm);
  380. }
  381. void CServerHandler::setPlayer(PlayerColor color) const
  382. {
  383. LobbySetPlayer lsp;
  384. lsp.clickedColor = color;
  385. sendLobbyPack(lsp);
  386. }
  387. void CServerHandler::setPlayerName(PlayerColor color, const std::string & name) const
  388. {
  389. LobbySetPlayerName lspn;
  390. lspn.color = color;
  391. lspn.name = name;
  392. sendLobbyPack(lspn);
  393. }
  394. void CServerHandler::setPlayerHandicap(PlayerColor color, Handicap handicap) const
  395. {
  396. LobbySetPlayerHandicap lsph;
  397. lsph.color = color;
  398. lsph.handicap = handicap;
  399. sendLobbyPack(lsph);
  400. }
  401. void CServerHandler::setPlayerOption(ui8 what, int32_t value, PlayerColor player) const
  402. {
  403. LobbyChangePlayerOption lcpo;
  404. lcpo.what = what;
  405. lcpo.value = value;
  406. lcpo.color = player;
  407. sendLobbyPack(lcpo);
  408. }
  409. void CServerHandler::setDifficulty(int to) const
  410. {
  411. LobbySetDifficulty lsd;
  412. lsd.difficulty = to;
  413. sendLobbyPack(lsd);
  414. }
  415. void CServerHandler::setSimturnsInfo(const SimturnsInfo & info) const
  416. {
  417. LobbySetSimturns pack;
  418. pack.simturnsInfo = info;
  419. sendLobbyPack(pack);
  420. }
  421. void CServerHandler::setTurnTimerInfo(const TurnTimerInfo & info) const
  422. {
  423. LobbySetTurnTime lstt;
  424. lstt.turnTimerInfo = info;
  425. sendLobbyPack(lstt);
  426. }
  427. void CServerHandler::setExtraOptionsInfo(const ExtraOptionsInfo & info) const
  428. {
  429. LobbySetExtraOptions lseo;
  430. lseo.extraOptionsInfo = info;
  431. sendLobbyPack(lseo);
  432. }
  433. void CServerHandler::sendMessage(const std::string & txt) const
  434. {
  435. std::istringstream readed;
  436. readed.str(txt);
  437. std::string command;
  438. readed >> command;
  439. if(command == "!passhost")
  440. {
  441. std::string id;
  442. readed >> id;
  443. if(id.length())
  444. {
  445. LobbyChangeHost lch;
  446. lch.newHostConnectionId = static_cast<GameConnectionID>(boost::lexical_cast<int>(id));
  447. sendLobbyPack(lch);
  448. }
  449. }
  450. else if(command == "!forcep")
  451. {
  452. std::string connectedId;
  453. std::string playerColorId;
  454. readed >> connectedId;
  455. readed >> playerColorId;
  456. if(connectedId.length() && playerColorId.length())
  457. {
  458. auto connected = static_cast<PlayerConnectionID>(boost::lexical_cast<int>(connectedId));
  459. auto color = PlayerColor(boost::lexical_cast<int>(playerColorId));
  460. if(color.isValidPlayer() && playerNames.find(connected) != playerNames.end())
  461. {
  462. LobbyForceSetPlayer lfsp;
  463. lfsp.targetConnectedPlayer = connected;
  464. lfsp.targetPlayerColor = color;
  465. sendLobbyPack(lfsp);
  466. }
  467. }
  468. }
  469. else
  470. {
  471. gameChat->sendMessageLobby(playerNames.find(myFirstId())->second.name, txt);
  472. }
  473. }
  474. void CServerHandler::sendGuiAction(ui8 action) const
  475. {
  476. LobbyGuiAction lga;
  477. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  478. sendLobbyPack(lga);
  479. }
  480. void CServerHandler::sendRestartGame() const
  481. {
  482. if(si->campState && !si->campState->getLoadingBackground().empty())
  483. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  484. else
  485. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  486. LobbyRestartGame endGame;
  487. sendLobbyPack(endGame);
  488. }
  489. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  490. {
  491. try
  492. {
  493. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  494. }
  495. catch(ModIncompatibility & e)
  496. {
  497. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  498. showServerError(e.getFullErrorMsg());
  499. return false;
  500. }
  501. catch(std::exception & e)
  502. {
  503. logGlobal->error("Exception during startScenario: %s", e.what());
  504. showServerError(std::string("Unable to start map!\nReason: ") + e.what());
  505. return false;
  506. }
  507. return true;
  508. }
  509. void CServerHandler::sendStartGame(bool allowOnlyAI, bool verify) const
  510. {
  511. if(verify)
  512. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  513. if(!settings["session"]["headless"].Bool())
  514. {
  515. if(si->campState && !si->campState->getLoadingBackground().empty())
  516. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  517. else
  518. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  519. }
  520. LobbyPrepareStartGame lpsg;
  521. sendLobbyPack(lpsg);
  522. LobbyStartGame lsg;
  523. sendLobbyPack(lsg);
  524. }
  525. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  526. {
  527. mapToStart = to;
  528. }
  529. void CServerHandler::enableLagCompensation(bool on)
  530. {
  531. if (on)
  532. networkLagCompensator = std::make_unique<NetworkLagCompensator>(getNetworkHandler(), client->gameStatePtr());
  533. else
  534. networkLagCompensator.reset();
  535. }
  536. void CServerHandler::startGameplay(std::shared_ptr<CGameState> gameState)
  537. {
  538. if(GAME->mainmenu())
  539. GAME->mainmenu()->disable();
  540. if (isGuest())
  541. networkLagCompensator = std::make_unique<NetworkLagCompensator>(getNetworkHandler(), gameState);
  542. switch(si->mode)
  543. {
  544. case EStartMode::NEW_GAME:
  545. client->newGame(gameState);
  546. break;
  547. case EStartMode::CAMPAIGN:
  548. if(si->campState->conqueredScenarios().empty())
  549. si->campState->highscoreParameters.clear();
  550. client->newGame(gameState);
  551. break;
  552. case EStartMode::LOAD_GAME:
  553. client->loadGame(gameState);
  554. break;
  555. default:
  556. throw std::runtime_error("Invalid mode");
  557. }
  558. // After everything initialized we can accept CPackToClient netpacks
  559. setState(EClientState::GAMEPLAY);
  560. }
  561. void CServerHandler::showHighScoresAndEndGameplay(PlayerColor player, bool victory, const StatisticDataSet & statistic)
  562. {
  563. HighScoreParameter param = HighScore::prepareHighScores(&client->gameState(), player, victory);
  564. if(victory && client->gameState().getStartInfo()->campState)
  565. {
  566. startCampaignScenario(param, client->gameState().getStartInfo()->campState, statistic);
  567. }
  568. else
  569. {
  570. HighScoreCalculation scenarioHighScores;
  571. scenarioHighScores.parameters.push_back(param);
  572. scenarioHighScores.isCampaign = false;
  573. endGameplay();
  574. GAME->mainmenu()->menu->switchToTab("main");
  575. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(victory, scenarioHighScores, statistic);
  576. }
  577. }
  578. void CServerHandler::endGameplay()
  579. {
  580. client->finishGameplay();
  581. // Game is ending
  582. // Tell the network thread to reach a stable state
  583. sendClientDisconnecting();
  584. logNetwork->info("Closed connection.");
  585. client->endGame();
  586. client.reset();
  587. if (GAME->mainmenu())
  588. {
  589. GAME->mainmenu()->enable();
  590. GAME->mainmenu()->playMusic();
  591. GAME->mainmenu()->makeActiveInterface();
  592. }
  593. }
  594. std::optional<std::string> CServerHandler::canQuickLoadGame(const std::string & path) const
  595. {
  596. auto mapInfo = std::make_shared<CMapInfo>();
  597. try
  598. {
  599. mapInfo->saveInit(ResourcePath(path, EResType::SAVEGAME));
  600. }
  601. catch(const IdentifierResolutionException & e)
  602. {
  603. return "Identifier not found.";
  604. }
  605. catch(const std::exception & e)
  606. {
  607. return "Generic error loading save.";
  608. }
  609. // initial start info from quick load slot
  610. const auto * startInfo1 = mapInfo->scenarioOptionsOfSave.get();
  611. // initial start info from game state (not current start info)
  612. const auto * startInfo2 = client->gameState().getInitialStartInfo();
  613. if (!startInfo1)
  614. return "Missing quick load start info.";
  615. if (!startInfo2)
  616. return "Missing server start info.";
  617. if (startInfo1->startTime != startInfo2->startTime)
  618. return "Different initial start time.";
  619. if (startInfo1->mapname != startInfo2->mapname)
  620. return "Different map name.";
  621. if (startInfo1->difficulty != startInfo2->difficulty)
  622. return "Different difficulty.";
  623. const auto & playerInfos1 = startInfo1->playerInfos;
  624. const auto & playerInfos2 = startInfo2->playerInfos;
  625. if (playerInfos1.size() != playerInfos2.size())
  626. return "Different number of players.";
  627. if (!std::equal(playerInfos1.begin(), playerInfos1.end(), playerInfos2.begin(), playerInfos2.end(),
  628. [](const auto& p1, const auto& p2) { return p1.first == p2.first && p1.second.connectedPlayerIDs == p2.second.connectedPlayerIDs; }))
  629. return "Different players.";
  630. return std::nullopt;
  631. }
  632. void CServerHandler::quickLoadGame(const std::string & path)
  633. {
  634. if(!settings["session"]["headless"].Bool())
  635. {
  636. if(si->campState && !si->campState->getLoadingBackground().empty())
  637. ENGINE->windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  638. else
  639. ENGINE->windows().createAndPushWindow<CLoadingScreen>();
  640. }
  641. LobbyQuickLoadGame pack;
  642. pack.saveFilePath = path;
  643. sendLobbyPack(pack);
  644. }
  645. void CServerHandler::restartGameplay()
  646. {
  647. client->finishGameplay();
  648. client->endGame();
  649. client.reset();
  650. logicConnection->enterLobbyConnectionMode();
  651. }
  652. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs, const StatisticDataSet & statistic)
  653. {
  654. std::shared_ptr<CampaignState> ourCampaign = cs;
  655. if (!cs)
  656. ourCampaign = si->campState;
  657. param.campaignName = cs->getNameTranslated();
  658. cs->highscoreParameters.push_back(param);
  659. auto campaignScoreCalculator = std::make_shared<HighScoreCalculation>();
  660. campaignScoreCalculator->isCampaign = true;
  661. campaignScoreCalculator->parameters = cs->highscoreParameters;
  662. endGameplay();
  663. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  664. auto finisher = [ourCampaign, campaignScoreCalculator, statistic]()
  665. {
  666. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  667. {
  668. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  669. entry->Bool() = true;
  670. }
  671. if(!ourCampaign->isCampaignFinished())
  672. GAME->mainmenu()->openCampaignLobby(ourCampaign);
  673. else
  674. {
  675. GAME->mainmenu()->openCampaignScreen(ourCampaign->campaignSet);
  676. if(!ourCampaign->getOutroVideo().empty() && ENGINE->video().open(ourCampaign->getOutroVideo(), 1))
  677. {
  678. ENGINE->music().stopMusic();
  679. ENGINE->windows().createAndPushWindow<VideoWindow>(ourCampaign->getOutroVideo(), ourCampaign->getVideoRim().empty() ? ImagePath::builtin("INTRORIM") : ourCampaign->getVideoRim(), false, 1, [campaignScoreCalculator, statistic](bool skipped){
  680. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  681. });
  682. }
  683. else
  684. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  685. }
  686. };
  687. if(epilogue.hasPrologEpilog)
  688. {
  689. ENGINE->windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  690. }
  691. else
  692. {
  693. finisher();
  694. }
  695. }
  696. void CServerHandler::showServerError(const std::string & txt) const
  697. {
  698. if(auto w = ENGINE->windows().topWindow<CLoadingScreen>())
  699. ENGINE->windows().popWindow(w);
  700. CInfoWindow::showInfoDialog(txt, {});
  701. }
  702. int CServerHandler::howManyPlayerInterfaces()
  703. {
  704. int playerInts = 0;
  705. for(auto pint : client->playerint)
  706. {
  707. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  708. playerInts++;
  709. }
  710. return playerInts;
  711. }
  712. ELoadMode CServerHandler::getLoadMode()
  713. {
  714. if(loadMode != ELoadMode::TUTORIAL && getState() == EClientState::GAMEPLAY)
  715. {
  716. if(si->campState)
  717. return ELoadMode::CAMPAIGN;
  718. for(auto pn : playerNames)
  719. {
  720. if(pn.second.connection != logicConnection->connectionID)
  721. return ELoadMode::MULTI;
  722. }
  723. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  724. return ELoadMode::MULTI;
  725. return ELoadMode::SINGLE;
  726. }
  727. return loadMode;
  728. }
  729. void CServerHandler::debugStartTest(std::string filename, bool save)
  730. {
  731. logGlobal->info("Starting debug test with file: %s", filename);
  732. auto mapInfo = std::make_shared<CMapInfo>();
  733. if(save)
  734. {
  735. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, EServerMode::LOCAL, {});
  736. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  737. }
  738. else
  739. {
  740. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOCAL, {});
  741. mapInfo->mapInit(filename);
  742. }
  743. if(settings["session"]["donotstartserver"].Bool())
  744. connectToServer(getLocalHostname(), getLocalPort());
  745. else
  746. startLocalServerAndConnect(false);
  747. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  748. while(!settings["session"]["headless"].Bool() && !ENGINE->windows().topWindow<CLobbyScreen>())
  749. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  750. while(!mi || mapInfo->fileURI != mi->fileURI)
  751. {
  752. setMapInfo(mapInfo);
  753. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  754. }
  755. // "Click" on color to remove us from it
  756. setPlayer(myFirstColor());
  757. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  758. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  759. while(true)
  760. {
  761. try
  762. {
  763. sendStartGame();
  764. break;
  765. }
  766. catch(...)
  767. {
  768. }
  769. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  770. }
  771. }
  772. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  773. {
  774. private:
  775. CServerHandler & handler;
  776. public:
  777. ServerHandlerCPackVisitor(CServerHandler & handler)
  778. :handler(handler)
  779. {
  780. }
  781. bool callTyped() override { return false; }
  782. void visitForLobby(CPackForLobby & lobbyPack) override
  783. {
  784. handler.visitForLobby(lobbyPack);
  785. }
  786. void visitForClient(CPackForClient & clientPack) override
  787. {
  788. handler.visitForClient(clientPack);
  789. }
  790. };
  791. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  792. {
  793. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  794. if(getState() == EClientState::DISCONNECTING)
  795. return;
  796. auto pack = logicConnection->retrievePack(message);
  797. ServerHandlerCPackVisitor visitor(*this);
  798. pack->visit(visitor);
  799. }
  800. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  801. {
  802. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  803. if (connection != networkConnection)
  804. {
  805. // ServerHandler already closed this connection on its own
  806. // This is the final call from network thread that informs serverHandler that connection has died
  807. // ignore it since serverHandler have already shut down this connection (and possibly started a new one)
  808. return;
  809. }
  810. waitForServerShutdown();
  811. if(getState() == EClientState::DISCONNECTING)
  812. {
  813. // Note: this branch can be reached on app shutdown, when main thread holds mutex till destruction
  814. logNetwork->info("Successfully closed connection to server!");
  815. return;
  816. }
  817. logNetwork->error("Lost connection to server! Connection has been closed");
  818. if(client)
  819. {
  820. endGameplay();
  821. GAME->mainmenu()->menu->switchToTab("main");
  822. showServerError(LIBRARY->generaltexth->translate("vcmi.server.errors.disconnected"));
  823. }
  824. else
  825. {
  826. LobbyClientDisconnected lcd;
  827. lcd.clientId = logicConnection->connectionID;
  828. applyPackOnLobbyScreen(lcd);
  829. }
  830. networkConnection.reset();
  831. }
  832. void CServerHandler::waitForServerShutdown()
  833. {
  834. if (!serverRunner)
  835. return; // may not exist for guest in MP
  836. serverRunner->wait();
  837. int exitCode = serverRunner->exitCode();
  838. serverRunner.reset();
  839. if (exitCode == 0)
  840. {
  841. logNetwork->info("Server closed correctly");
  842. }
  843. else
  844. {
  845. if (getState() == EClientState::CONNECTING)
  846. {
  847. showServerError(LIBRARY->generaltexth->translate("vcmi.server.errors.existingProcess"));
  848. setState(EClientState::CONNECTION_CANCELLED); // stop attempts to reconnect
  849. }
  850. logNetwork->error("Error: server failed to close correctly or crashed!");
  851. logNetwork->error("Check log file for more info");
  852. }
  853. serverRunner.reset();
  854. }
  855. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  856. {
  857. ApplyOnLobbyHandlerNetPackVisitor visitor(*this);
  858. lobbyPack.visit(visitor);
  859. if(visitor.getResult())
  860. {
  861. if(!settings["session"]["headless"].Bool())
  862. applyPackOnLobbyScreen(lobbyPack);
  863. }
  864. }
  865. void CServerHandler::visitForClient(CPackForClient & clientPack)
  866. {
  867. if (networkLagCompensator && networkLagCompensator->verifyReply(clientPack))
  868. return;
  869. client->handlePack(clientPack);
  870. }
  871. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  872. {
  873. if(getState() != EClientState::STARTING)
  874. logicConnection->sendPack(pack);
  875. }
  876. bool CServerHandler::inLobbyRoom() const
  877. {
  878. return serverMode == EServerMode::LOBBY_HOST || serverMode == EServerMode::LOBBY_GUEST;
  879. }
  880. bool CServerHandler::inGame() const
  881. {
  882. return logicConnection != nullptr;
  883. }
  884. void CServerHandler::sendGamePack(const CPackForServer & pack) const
  885. {
  886. if (networkLagCompensator)
  887. networkLagCompensator->tryPredictReply(pack);
  888. logicConnection->sendPack(pack);
  889. }