CServerHandler.cpp 26 KB

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