CServerHandler.cpp 25 KB

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