CServerHandler.cpp 23 KB

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