CServerHandler.cpp 22 KB

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