CServerHandler.cpp 23 KB

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