CServerHandler.cpp 24 KB

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