CServerHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. setState(EClientState::GAMEPLAY);
  553. }
  554. void CServerHandler::showHighScoresAndEndGameplay(PlayerColor player, bool victory, const StatisticDataSet & statistic)
  555. {
  556. HighScoreParameter param = HighScore::prepareHighScores(&client->gameState(), player, victory);
  557. if(victory && client->gameState().getStartInfo()->campState)
  558. {
  559. startCampaignScenario(param, client->gameState().getStartInfo()->campState, statistic);
  560. }
  561. else
  562. {
  563. HighScoreCalculation scenarioHighScores;
  564. scenarioHighScores.parameters.push_back(param);
  565. scenarioHighScores.isCampaign = false;
  566. endGameplay();
  567. GAME->mainmenu()->menu->switchToTab("main");
  568. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(victory, scenarioHighScores, statistic);
  569. }
  570. }
  571. void CServerHandler::endGameplay()
  572. {
  573. client->finishGameplay();
  574. // Game is ending
  575. // Tell the network thread to reach a stable state
  576. sendClientDisconnecting();
  577. logNetwork->info("Closed connection.");
  578. client->endGame();
  579. client.reset();
  580. if (GAME->mainmenu())
  581. {
  582. GAME->mainmenu()->enable();
  583. GAME->mainmenu()->playMusic();
  584. GAME->mainmenu()->makeActiveInterface();
  585. }
  586. }
  587. void CServerHandler::restartGameplay()
  588. {
  589. client->finishGameplay();
  590. client->endGame();
  591. client.reset();
  592. logicConnection->enterLobbyConnectionMode();
  593. }
  594. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs, const StatisticDataSet & statistic)
  595. {
  596. std::shared_ptr<CampaignState> ourCampaign = cs;
  597. if (!cs)
  598. ourCampaign = si->campState;
  599. param.campaignName = cs->getNameTranslated();
  600. cs->highscoreParameters.push_back(param);
  601. auto campaignScoreCalculator = std::make_shared<HighScoreCalculation>();
  602. campaignScoreCalculator->isCampaign = true;
  603. campaignScoreCalculator->parameters = cs->highscoreParameters;
  604. endGameplay();
  605. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  606. auto finisher = [ourCampaign, campaignScoreCalculator, statistic]()
  607. {
  608. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  609. {
  610. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  611. entry->Bool() = true;
  612. }
  613. if(!ourCampaign->isCampaignFinished())
  614. GAME->mainmenu()->openCampaignLobby(ourCampaign);
  615. else
  616. {
  617. GAME->mainmenu()->openCampaignScreen(ourCampaign->campaignSet);
  618. if(!ourCampaign->getOutroVideo().empty() && ENGINE->video().open(ourCampaign->getOutroVideo(), 1))
  619. {
  620. ENGINE->music().stopMusic();
  621. ENGINE->windows().createAndPushWindow<VideoWindow>(ourCampaign->getOutroVideo(), ourCampaign->getVideoRim().empty() ? ImagePath::builtin("INTRORIM") : ourCampaign->getVideoRim(), false, 1, [campaignScoreCalculator, statistic](bool skipped){
  622. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  623. });
  624. }
  625. else
  626. ENGINE->windows().createAndPushWindow<CHighScoreInputScreen>(true, *campaignScoreCalculator, statistic);
  627. }
  628. };
  629. if(epilogue.hasPrologEpilog)
  630. {
  631. ENGINE->windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  632. }
  633. else
  634. {
  635. finisher();
  636. }
  637. }
  638. void CServerHandler::showServerError(const std::string & txt) const
  639. {
  640. if(auto w = ENGINE->windows().topWindow<CLoadingScreen>())
  641. ENGINE->windows().popWindow(w);
  642. CInfoWindow::showInfoDialog(txt, {});
  643. }
  644. int CServerHandler::howManyPlayerInterfaces()
  645. {
  646. int playerInts = 0;
  647. for(auto pint : client->playerint)
  648. {
  649. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  650. playerInts++;
  651. }
  652. return playerInts;
  653. }
  654. ELoadMode CServerHandler::getLoadMode()
  655. {
  656. if(loadMode != ELoadMode::TUTORIAL && getState() == EClientState::GAMEPLAY)
  657. {
  658. if(si->campState)
  659. return ELoadMode::CAMPAIGN;
  660. for(auto pn : playerNames)
  661. {
  662. if(pn.second.connection != logicConnection->connectionID)
  663. return ELoadMode::MULTI;
  664. }
  665. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  666. return ELoadMode::MULTI;
  667. return ELoadMode::SINGLE;
  668. }
  669. return loadMode;
  670. }
  671. void CServerHandler::debugStartTest(std::string filename, bool save)
  672. {
  673. logGlobal->info("Starting debug test with file: %s", filename);
  674. auto mapInfo = std::make_shared<CMapInfo>();
  675. if(save)
  676. {
  677. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, EServerMode::LOCAL, {});
  678. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  679. }
  680. else
  681. {
  682. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, EServerMode::LOCAL, {});
  683. mapInfo->mapInit(filename);
  684. }
  685. if(settings["session"]["donotstartserver"].Bool())
  686. connectToServer(getLocalHostname(), getLocalPort());
  687. else
  688. startLocalServerAndConnect(false);
  689. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  690. while(!settings["session"]["headless"].Bool() && !ENGINE->windows().topWindow<CLobbyScreen>())
  691. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  692. while(!mi || mapInfo->fileURI != mi->fileURI)
  693. {
  694. setMapInfo(mapInfo);
  695. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  696. }
  697. // "Click" on color to remove us from it
  698. setPlayer(myFirstColor());
  699. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  700. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  701. while(true)
  702. {
  703. try
  704. {
  705. sendStartGame();
  706. break;
  707. }
  708. catch(...)
  709. {
  710. }
  711. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  712. }
  713. }
  714. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  715. {
  716. private:
  717. CServerHandler & handler;
  718. public:
  719. ServerHandlerCPackVisitor(CServerHandler & handler)
  720. :handler(handler)
  721. {
  722. }
  723. bool callTyped() override { return false; }
  724. void visitForLobby(CPackForLobby & lobbyPack) override
  725. {
  726. handler.visitForLobby(lobbyPack);
  727. }
  728. void visitForClient(CPackForClient & clientPack) override
  729. {
  730. handler.visitForClient(clientPack);
  731. }
  732. };
  733. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<std::byte> & message)
  734. {
  735. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  736. if(getState() == EClientState::DISCONNECTING)
  737. return;
  738. auto pack = logicConnection->retrievePack(message);
  739. ServerHandlerCPackVisitor visitor(*this);
  740. pack->visit(visitor);
  741. }
  742. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  743. {
  744. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  745. if (connection != networkConnection)
  746. {
  747. // ServerHandler already closed this connection on its own
  748. // This is the final call from network thread that informs serverHandler that connection has died
  749. // ignore it since serverHandler have already shut down this connection (and possibly started a new one)
  750. return;
  751. }
  752. waitForServerShutdown();
  753. if(getState() == EClientState::DISCONNECTING)
  754. {
  755. // Note: this branch can be reached on app shutdown, when main thread holds mutex till destruction
  756. logNetwork->info("Successfully closed connection to server!");
  757. return;
  758. }
  759. logNetwork->error("Lost connection to server! Connection has been closed");
  760. if(client)
  761. {
  762. endGameplay();
  763. GAME->mainmenu()->menu->switchToTab("main");
  764. showServerError(LIBRARY->generaltexth->translate("vcmi.server.errors.disconnected"));
  765. }
  766. else
  767. {
  768. LobbyClientDisconnected lcd;
  769. lcd.clientId = logicConnection->connectionID;
  770. applyPackOnLobbyScreen(lcd);
  771. }
  772. networkConnection.reset();
  773. }
  774. void CServerHandler::waitForServerShutdown()
  775. {
  776. if (!serverRunner)
  777. return; // may not exist for guest in MP
  778. serverRunner->wait();
  779. int exitCode = serverRunner->exitCode();
  780. serverRunner.reset();
  781. if (exitCode == 0)
  782. {
  783. logNetwork->info("Server closed correctly");
  784. }
  785. else
  786. {
  787. if (getState() == EClientState::CONNECTING)
  788. {
  789. showServerError(LIBRARY->generaltexth->translate("vcmi.server.errors.existingProcess"));
  790. setState(EClientState::CONNECTION_CANCELLED); // stop attempts to reconnect
  791. }
  792. logNetwork->error("Error: server failed to close correctly or crashed!");
  793. logNetwork->error("Check log file for more info");
  794. }
  795. serverRunner.reset();
  796. }
  797. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  798. {
  799. ApplyOnLobbyHandlerNetPackVisitor visitor(*this);
  800. lobbyPack.visit(visitor);
  801. if(visitor.getResult())
  802. {
  803. if(!settings["session"]["headless"].Bool())
  804. applyPackOnLobbyScreen(lobbyPack);
  805. }
  806. }
  807. void CServerHandler::visitForClient(CPackForClient & clientPack)
  808. {
  809. client->handlePack(clientPack);
  810. }
  811. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  812. {
  813. if(getState() != EClientState::STARTING)
  814. logicConnection->sendPack(pack);
  815. }
  816. bool CServerHandler::inLobbyRoom() const
  817. {
  818. return serverMode == EServerMode::LOBBY_HOST || serverMode == EServerMode::LOBBY_GUEST;
  819. }
  820. bool CServerHandler::inGame() const
  821. {
  822. return logicConnection != nullptr;
  823. }