CServerHandler.cpp 25 KB

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