CServerHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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. if(si->campState && !si->campState->getLoadingBackground().empty())
  464. GH.windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  465. else
  466. GH.windows().createAndPushWindow<CLoadingScreen>();
  467. LobbyRestartGame endGame;
  468. sendLobbyPack(endGame);
  469. }
  470. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  471. {
  472. try
  473. {
  474. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  475. }
  476. catch(ModIncompatibility & e)
  477. {
  478. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  479. std::string errorMsg;
  480. if(!e.whatMissing().empty())
  481. {
  482. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  483. errorMsg += e.whatMissing();
  484. }
  485. if(!e.whatExcessive().empty())
  486. {
  487. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  488. errorMsg += e.whatExcessive();
  489. }
  490. showServerError(errorMsg);
  491. return false;
  492. }
  493. catch(std::exception & e)
  494. {
  495. logGlobal->error("Exception during startScenario: %s", e.what());
  496. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  497. return false;
  498. }
  499. return true;
  500. }
  501. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  502. {
  503. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  504. if(!settings["session"]["headless"].Bool())
  505. {
  506. if(si->campState && !si->campState->getLoadingBackground().empty())
  507. GH.windows().createAndPushWindow<CLoadingScreen>(si->campState->getLoadingBackground());
  508. else
  509. GH.windows().createAndPushWindow<CLoadingScreen>();
  510. }
  511. LobbyPrepareStartGame lpsg;
  512. sendLobbyPack(lpsg);
  513. LobbyStartGame lsg;
  514. sendLobbyPack(lsg);
  515. }
  516. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  517. {
  518. mapToStart = to;
  519. }
  520. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  521. {
  522. if(CMM)
  523. CMM->disable();
  524. switch(si->mode)
  525. {
  526. case EStartMode::NEW_GAME:
  527. client->newGame(gameState);
  528. break;
  529. case EStartMode::CAMPAIGN:
  530. if(si->campState->conqueredScenarios().empty())
  531. si->campState->highscoreParameters.clear();
  532. client->newGame(gameState);
  533. break;
  534. case EStartMode::LOAD_GAME:
  535. client->loadGame(gameState);
  536. break;
  537. default:
  538. throw std::runtime_error("Invalid mode");
  539. }
  540. // After everything initialized we can accept CPackToClient netpacks
  541. logicConnection->enterGameplayConnectionMode(client->gameState());
  542. setState(EClientState::GAMEPLAY);
  543. }
  544. void CServerHandler::showHighScoresAndEndGameplay(PlayerColor player, bool victory, const StatisticDataSet & statistic)
  545. {
  546. HighScoreParameter param = HighScore::prepareHighScores(client->gameState(), player, victory);
  547. if(victory && client->gameState()->getStartInfo()->campState)
  548. {
  549. startCampaignScenario(param, client->gameState()->getStartInfo()->campState, statistic);
  550. }
  551. else
  552. {
  553. HighScoreCalculation scenarioHighScores;
  554. scenarioHighScores.parameters.push_back(param);
  555. scenarioHighScores.isCampaign = false;
  556. endGameplay();
  557. CMM->menu->switchToTab("main");
  558. GH.windows().createAndPushWindow<CHighScoreInputScreen>(victory, scenarioHighScores, statistic);
  559. }
  560. }
  561. void CServerHandler::endGameplay()
  562. {
  563. // Game is ending
  564. // Tell the network thread to reach a stable state
  565. sendClientDisconnecting();
  566. logNetwork->info("Closed connection.");
  567. client->endGame();
  568. client.reset();
  569. if(CMM)
  570. {
  571. GH.curInt = CMM.get();
  572. CMM->enable();
  573. }
  574. else
  575. {
  576. GH.curInt = CMainMenu::create().get();
  577. }
  578. }
  579. void CServerHandler::restartGameplay()
  580. {
  581. client->endGame();
  582. client.reset();
  583. logicConnection->enterLobbyConnectionMode();
  584. }
  585. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs, const StatisticDataSet & statistic)
  586. {
  587. std::shared_ptr<CampaignState> ourCampaign = cs;
  588. if (!cs)
  589. ourCampaign = si->campState;
  590. param.campaignName = cs->getNameTranslated();
  591. cs->highscoreParameters.push_back(param);
  592. auto campaignScoreCalculator = std::make_shared<HighScoreCalculation>();
  593. campaignScoreCalculator->isCampaign = true;
  594. campaignScoreCalculator->parameters = cs->highscoreParameters;
  595. endGameplay();
  596. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  597. auto finisher = [ourCampaign, campaignScoreCalculator, statistic]()
  598. {
  599. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  600. {
  601. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  602. entry->Bool() = true;
  603. }
  604. GH.windows().pushWindow(CMM);
  605. GH.windows().pushWindow(CMM->menu);
  606. if(!ourCampaign->isCampaignFinished())
  607. CMM->openCampaignLobby(ourCampaign);
  608. else
  609. {
  610. CMM->openCampaignScreen(ourCampaign->campaignSet);
  611. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  612. }
  613. };
  614. if(epilogue.hasPrologEpilog)
  615. {
  616. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  617. }
  618. else
  619. {
  620. finisher();
  621. }
  622. }
  623. void CServerHandler::showServerError(const std::string & txt) const
  624. {
  625. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  626. GH.windows().popWindow(w);
  627. CInfoWindow::showInfoDialog(txt, {});
  628. }
  629. int CServerHandler::howManyPlayerInterfaces()
  630. {
  631. int playerInts = 0;
  632. for(auto pint : client->playerint)
  633. {
  634. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  635. playerInts++;
  636. }
  637. return playerInts;
  638. }
  639. ELoadMode CServerHandler::getLoadMode()
  640. {
  641. if(loadMode != ELoadMode::TUTORIAL && getState() == EClientState::GAMEPLAY)
  642. {
  643. if(si->campState)
  644. return ELoadMode::CAMPAIGN;
  645. for(auto pn : playerNames)
  646. {
  647. if(pn.second.connection != logicConnection->connectionID)
  648. return ELoadMode::MULTI;
  649. }
  650. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  651. return ELoadMode::MULTI;
  652. return ELoadMode::SINGLE;
  653. }
  654. return loadMode;
  655. }
  656. void CServerHandler::debugStartTest(std::string filename, bool save)
  657. {
  658. logGlobal->info("Starting debug test with file: %s", filename);
  659. auto mapInfo = std::make_shared<CMapInfo>();
  660. if(save)
  661. {
  662. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, EServerMode::LOCAL, {});
  663. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  664. }
  665. else
  666. {
  667. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOCAL, {});
  668. mapInfo->mapInit(filename);
  669. }
  670. if(settings["session"]["donotstartserver"].Bool())
  671. connectToServer(getLocalHostname(), getLocalPort());
  672. else
  673. startLocalServerAndConnect(false);
  674. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  675. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  676. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  677. while(!mi || mapInfo->fileURI != mi->fileURI)
  678. {
  679. setMapInfo(mapInfo);
  680. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  681. }
  682. // "Click" on color to remove us from it
  683. setPlayer(myFirstColor());
  684. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  685. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  686. while(true)
  687. {
  688. try
  689. {
  690. sendStartGame();
  691. break;
  692. }
  693. catch(...)
  694. {
  695. }
  696. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  697. }
  698. }
  699. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  700. {
  701. private:
  702. CServerHandler & handler;
  703. public:
  704. ServerHandlerCPackVisitor(CServerHandler & handler)
  705. :handler(handler)
  706. {
  707. }
  708. bool callTyped() override { return false; }
  709. void visitForLobby(CPackForLobby & lobbyPack) override
  710. {
  711. handler.visitForLobby(lobbyPack);
  712. }
  713. void visitForClient(CPackForClient & clientPack) override
  714. {
  715. handler.visitForClient(clientPack);
  716. }
  717. };
  718. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  719. {
  720. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  721. if(getState() == EClientState::DISCONNECTING)
  722. return;
  723. CPack * pack = logicConnection->retrievePack(message);
  724. ServerHandlerCPackVisitor visitor(*this);
  725. pack->visit(visitor);
  726. }
  727. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  728. {
  729. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  730. if (connection != networkConnection)
  731. {
  732. // ServerHandler already closed this connection on its own
  733. // This is the final call from network thread that informs serverHandler that connection has died
  734. // ignore it since serverHandler have already shut down this connection (and possibly started a new one)
  735. return;
  736. }
  737. waitForServerShutdown();
  738. if(getState() == EClientState::DISCONNECTING)
  739. {
  740. // Note: this branch can be reached on app shutdown, when main thread holds mutex till destruction
  741. logNetwork->info("Successfully closed connection to server!");
  742. return;
  743. }
  744. logNetwork->error("Lost connection to server! Connection has been closed");
  745. if(client)
  746. {
  747. endGameplay();
  748. CMM->menu->switchToTab("main");
  749. showServerError(CGI->generaltexth->translate("vcmi.server.errors.disconnected"));
  750. }
  751. else
  752. {
  753. LobbyClientDisconnected lcd;
  754. lcd.clientId = logicConnection->connectionID;
  755. applyPackOnLobbyScreen(lcd);
  756. }
  757. networkConnection.reset();
  758. }
  759. void CServerHandler::waitForServerShutdown()
  760. {
  761. if (!serverRunner)
  762. return; // may not exist for guest in MP
  763. serverRunner->wait();
  764. int exitCode = serverRunner->exitCode();
  765. serverRunner.reset();
  766. if (exitCode == 0)
  767. {
  768. logNetwork->info("Server closed correctly");
  769. }
  770. else
  771. {
  772. if (getState() == EClientState::CONNECTING)
  773. {
  774. showServerError(CGI->generaltexth->translate("vcmi.server.errors.existingProcess"));
  775. setState(EClientState::CONNECTION_CANCELLED); // stop attempts to reconnect
  776. }
  777. logNetwork->error("Error: server failed to close correctly or crashed!");
  778. logNetwork->error("Check log file for more info");
  779. }
  780. serverRunner.reset();
  781. }
  782. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  783. {
  784. ApplyOnLobbyHandlerNetPackVisitor visitor(*this);
  785. lobbyPack.visit(visitor);
  786. if(visitor.getResult())
  787. {
  788. if(!settings["session"]["headless"].Bool())
  789. applyPackOnLobbyScreen(lobbyPack);
  790. }
  791. }
  792. void CServerHandler::visitForClient(CPackForClient & clientPack)
  793. {
  794. client->handlePack(&clientPack);
  795. }
  796. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  797. {
  798. if(getState() != EClientState::STARTING)
  799. logicConnection->sendPack(&pack);
  800. }
  801. bool CServerHandler::inLobbyRoom() const
  802. {
  803. return serverMode == EServerMode::LOBBY_HOST || serverMode == EServerMode::LOBBY_GUEST;
  804. }
  805. bool CServerHandler::inGame() const
  806. {
  807. return logicConnection != nullptr;
  808. }