CServerHandler.cpp 24 KB

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