CServerHandler.cpp 26 KB

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