CServerHandler.cpp 24 KB

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