CServerHandler.cpp 26 KB

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