CServerHandler.cpp 24 KB

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