CServerHandler.cpp 25 KB

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