CServerHandler.cpp 26 KB

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