CServerHandler.cpp 24 KB

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