CServerHandler.cpp 24 KB

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