2
0

CServerHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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 "CPlayerInterface.h"
  15. #include "gui/CGuiHandler.h"
  16. #include "gui/WindowHandler.h"
  17. #include "globalLobby/GlobalLobbyClient.h"
  18. #include "lobby/CSelectionBase.h"
  19. #include "lobby/CLobbyScreen.h"
  20. #include "windows/InfoWindows.h"
  21. #include "mainmenu/CMainMenu.h"
  22. #include "mainmenu/CPrologEpilogVideo.h"
  23. #include "mainmenu/CHighScoreScreen.h"
  24. #ifdef VCMI_ANDROID
  25. #include "../lib/CAndroidVMHelper.h"
  26. #elif defined(VCMI_IOS)
  27. #include "ios/utils.h"
  28. #include <dispatch/dispatch.h>
  29. #endif
  30. #ifdef SINGLE_PROCESS_APP
  31. #include "../server/CVCMIServer.h"
  32. #endif
  33. #include "../lib/CConfigHandler.h"
  34. #include "../lib/CGeneralTextHandler.h"
  35. #include "../lib/CThreadHelper.h"
  36. #include "../lib/StartInfo.h"
  37. #include "../lib/TurnTimerInfo.h"
  38. #include "../lib/VCMIDirs.h"
  39. #include "../lib/campaign/CampaignState.h"
  40. #include "../lib/mapping/CMapInfo.h"
  41. #include "../lib/mapObjects/MiscObjects.h"
  42. #include "../lib/modding/ModIncompatibility.h"
  43. #include "../lib/rmg/CMapGenOptions.h"
  44. #include "../lib/serializer/Connection.h"
  45. #include "../lib/filesystem/Filesystem.h"
  46. #include "../lib/registerTypes/RegisterTypesLobbyPacks.h"
  47. #include "../lib/serializer/CMemorySerializer.h"
  48. #include "../lib/UnlockGuard.h"
  49. #include <boost/uuid/uuid.hpp>
  50. #include <boost/uuid/uuid_io.hpp>
  51. #include <boost/uuid/uuid_generators.hpp>
  52. #include "../lib/serializer/Cast.h"
  53. #include "LobbyClientNetPackVisitors.h"
  54. #include <vcmi/events/EventBus.h>
  55. #ifdef VCMI_WINDOWS
  56. #include <windows.h>
  57. #endif
  58. template<typename T> class CApplyOnLobby;
  59. #if defined(VCMI_ANDROID) && !defined(SINGLE_PROCESS_APP)
  60. extern std::atomic_bool androidTestServerReadyFlag;
  61. #endif
  62. class CBaseForLobbyApply
  63. {
  64. public:
  65. virtual bool applyOnLobbyHandler(CServerHandler * handler, CPackForLobby & pack) const = 0;
  66. virtual void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, CPackForLobby & pack) const = 0;
  67. virtual ~CBaseForLobbyApply(){};
  68. template<typename U> static CBaseForLobbyApply * getApplier(const U * t = nullptr)
  69. {
  70. return new CApplyOnLobby<U>();
  71. }
  72. };
  73. template<typename T> class CApplyOnLobby : public CBaseForLobbyApply
  74. {
  75. public:
  76. bool applyOnLobbyHandler(CServerHandler * handler, CPackForLobby & pack) const override
  77. {
  78. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  79. auto & ref = static_cast<T&>(pack);
  80. ApplyOnLobbyHandlerNetPackVisitor visitor(*handler);
  81. logNetwork->trace("\tImmediately apply on lobby: %s", typeid(ref).name());
  82. ref.visit(visitor);
  83. return visitor.getResult();
  84. }
  85. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, CPackForLobby & pack) const override
  86. {
  87. auto & ref = static_cast<T &>(pack);
  88. ApplyOnLobbyScreenNetPackVisitor visitor(*handler, lobby);
  89. logNetwork->trace("\tApply on lobby from queue: %s", typeid(ref).name());
  90. ref.visit(visitor);
  91. }
  92. };
  93. template<> class CApplyOnLobby<CPack>: public CBaseForLobbyApply
  94. {
  95. public:
  96. bool applyOnLobbyHandler(CServerHandler * handler, CPackForLobby & pack) const override
  97. {
  98. logGlobal->error("Cannot apply plain CPack!");
  99. assert(0);
  100. return false;
  101. }
  102. void applyOnLobbyScreen(CLobbyScreen * lobby, CServerHandler * handler, CPackForLobby & pack) const override
  103. {
  104. logGlobal->error("Cannot apply plain CPack!");
  105. assert(0);
  106. }
  107. };
  108. CServerHandler::~CServerHandler()
  109. {
  110. networkHandler->stop();
  111. threadNetwork->join();
  112. }
  113. CServerHandler::CServerHandler()
  114. : applier(std::make_unique<CApplier<CBaseForLobbyApply>>())
  115. , lobbyClient(std::make_unique<GlobalLobbyClient>())
  116. , networkHandler(INetworkHandler::createHandler())
  117. , state(EClientState::NONE)
  118. , campaignStateToSend(nullptr)
  119. , screenType(ESelectionScreen::unknown)
  120. , loadMode(ELoadMode::NONE)
  121. , client(nullptr)
  122. , campaignServerRestartLock(false)
  123. {
  124. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  125. registerTypesLobbyPacks(*applier);
  126. threadNetwork = std::make_unique<boost::thread>(&CServerHandler::threadRunNetwork, this);
  127. }
  128. void CServerHandler::threadRunNetwork()
  129. {
  130. logGlobal->info("Starting network thread");
  131. setThreadName("runNetwork");
  132. networkHandler->run();
  133. logGlobal->info("Ending network thread");
  134. }
  135. void CServerHandler::resetStateForLobby(EStartMode mode, ESelectionScreen screen, const std::vector<std::string> & names)
  136. {
  137. hostClientId = -1;
  138. state = EClientState::NONE;
  139. mapToStart = nullptr;
  140. th = std::make_unique<CStopWatch>();
  141. c.reset();
  142. si = std::make_shared<StartInfo>();
  143. playerNames.clear();
  144. si->difficulty = 1;
  145. si->mode = mode;
  146. screenType = screen;
  147. myNames.clear();
  148. if(!names.empty()) //if have custom set of player names - use it
  149. myNames = names;
  150. else
  151. myNames.push_back(settings["general"]["playerName"].String());
  152. }
  153. GlobalLobbyClient & CServerHandler::getGlobalLobby()
  154. {
  155. return *lobbyClient;
  156. }
  157. void CServerHandler::startLocalServerAndConnect(bool connectToLobby)
  158. {
  159. if(threadRunLocalServer)
  160. threadRunLocalServer->join();
  161. th->update();
  162. #if defined(SINGLE_PROCESS_APP)
  163. boost::condition_variable cond;
  164. std::vector<std::string> args{"--port=" + std::to_string(getLocalPort())};
  165. if(connectToLobby)
  166. args.push_back("--lobby");
  167. threadRunLocalServer = std::make_unique<boost::thread>([&cond, args, this] {
  168. setThreadName("CVCMIServer");
  169. CVCMIServer::create(&cond, args);
  170. onServerFinished();
  171. });
  172. threadRunLocalServer->detach();
  173. #elif defined(VCMI_ANDROID)
  174. {
  175. CAndroidVMHelper envHelper;
  176. envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "startServer", true);
  177. }
  178. #else
  179. threadRunLocalServer = std::make_unique<boost::thread>(&CServerHandler::threadRunServer, this, connectToLobby); //runs server executable;
  180. #endif
  181. logNetwork->trace("Setting up thread calling server: %d ms", th->getDiff());
  182. th->update();
  183. #ifdef SINGLE_PROCESS_APP
  184. {
  185. #ifdef VCMI_IOS
  186. dispatch_sync(dispatch_get_main_queue(), ^{
  187. iOS_utils::showLoadingIndicator();
  188. });
  189. #endif
  190. boost::mutex m;
  191. boost::unique_lock<boost::mutex> lock{m};
  192. logNetwork->info("waiting for server");
  193. cond.wait(lock);
  194. logNetwork->info("server is ready");
  195. #ifdef VCMI_IOS
  196. dispatch_sync(dispatch_get_main_queue(), ^{
  197. iOS_utils::hideLoadingIndicator();
  198. });
  199. #endif
  200. }
  201. #elif defined(VCMI_ANDROID)
  202. logNetwork->info("waiting for server");
  203. while(!androidTestServerReadyFlag.load())
  204. {
  205. logNetwork->info("still waiting...");
  206. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  207. }
  208. logNetwork->info("waiting for server finished...");
  209. androidTestServerReadyFlag = false;
  210. #endif
  211. logNetwork->trace("Waiting for server: %d ms", th->getDiff());
  212. th->update(); //put breakpoint here to attach to server before it does something stupid
  213. connectToServer(getLocalHostname(), getLocalPort());
  214. logNetwork->trace("\tConnecting to the server: %d ms", th->getDiff());
  215. }
  216. void CServerHandler::connectToServer(const std::string & addr, const ui16 port)
  217. {
  218. logNetwork->info("Establishing connection to %s:%d...", addr, port);
  219. state = EClientState::CONNECTING;
  220. serverHostname = addr;
  221. serverPort = port;
  222. if (!isServerLocal())
  223. {
  224. Settings remoteAddress = settings.write["server"]["remoteHostname"];
  225. remoteAddress->String() = addr;
  226. Settings remotePort = settings.write["server"]["remotePort"];
  227. remotePort->Integer() = port;
  228. }
  229. networkHandler->connectToRemote(*this, addr, port);
  230. }
  231. void CServerHandler::onConnectionFailed(const std::string & errorMessage)
  232. {
  233. if (isServerLocal())
  234. {
  235. // retry - local server might be still starting up
  236. logNetwork->debug("\nCannot establish connection. %s. Retrying...", errorMessage);
  237. networkHandler->createTimer(*this, std::chrono::milliseconds(100));
  238. }
  239. else
  240. {
  241. // remote server refused connection - show error message
  242. state = EClientState::CONNECTION_FAILED;
  243. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  244. }
  245. }
  246. void CServerHandler::onTimer()
  247. {
  248. if(state == EClientState::CONNECTION_CANCELLED)
  249. {
  250. logNetwork->info("Connection aborted by player!");
  251. return;
  252. }
  253. assert(isServerLocal());
  254. networkHandler->connectToRemote(*this, getLocalHostname(), getLocalPort());
  255. }
  256. void CServerHandler::onConnectionEstablished(const std::shared_ptr<INetworkConnection> & netConnection)
  257. {
  258. networkConnection = netConnection;
  259. logNetwork->info("Connection established");
  260. c = std::make_shared<CConnection>(netConnection);
  261. nextClient = std::make_unique<CClient>();
  262. c->uuid = uuid;
  263. c->enterLobbyConnectionMode();
  264. c->setCallback(nextClient.get());
  265. sendClientConnecting();
  266. }
  267. void CServerHandler::applyPackOnLobbyScreen(CPackForLobby & pack)
  268. {
  269. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  270. const CBaseForLobbyApply * apply = applier->getApplier(CTypeList::getInstance().getTypeID(&pack)); //find the applier
  271. apply->applyOnLobbyScreen(dynamic_cast<CLobbyScreen *>(SEL), this, pack);
  272. GH.windows().totalRedraw();
  273. }
  274. std::set<PlayerColor> CServerHandler::getHumanColors()
  275. {
  276. return clientHumanColors(c->connectionID);
  277. }
  278. PlayerColor CServerHandler::myFirstColor() const
  279. {
  280. return clientFirstColor(c->connectionID);
  281. }
  282. bool CServerHandler::isMyColor(PlayerColor color) const
  283. {
  284. return isClientColor(c->connectionID, color);
  285. }
  286. ui8 CServerHandler::myFirstId() const
  287. {
  288. return clientFirstId(c->connectionID);
  289. }
  290. bool CServerHandler::isServerLocal() const
  291. {
  292. if(threadRunLocalServer)
  293. return true;
  294. return false;
  295. }
  296. bool CServerHandler::isHost() const
  297. {
  298. return c && hostClientId == c->connectionID;
  299. }
  300. bool CServerHandler::isGuest() const
  301. {
  302. return !c || hostClientId != c->connectionID;
  303. }
  304. const std::string & CServerHandler::getLocalHostname() const
  305. {
  306. return settings["server"]["localHostname"].String();
  307. }
  308. ui16 CServerHandler::getLocalPort() const
  309. {
  310. return settings["server"]["localPort"].Integer();
  311. }
  312. const std::string & CServerHandler::getRemoteHostname() const
  313. {
  314. return settings["server"]["remoteHostname"].String();
  315. }
  316. ui16 CServerHandler::getRemotePort() const
  317. {
  318. return settings["server"]["remotePort"].Integer();
  319. }
  320. const std::string & CServerHandler::getCurrentHostname() const
  321. {
  322. return serverHostname;
  323. }
  324. ui16 CServerHandler::getCurrentPort() const
  325. {
  326. return serverPort;
  327. }
  328. void CServerHandler::sendClientConnecting() const
  329. {
  330. LobbyClientConnected lcc;
  331. lcc.uuid = uuid;
  332. lcc.names = myNames;
  333. lcc.mode = si->mode;
  334. sendLobbyPack(lcc);
  335. }
  336. void CServerHandler::sendClientDisconnecting()
  337. {
  338. // FIXME: This is workaround needed to make sure client not trying to sent anything to non existed server
  339. if(state == EClientState::DISCONNECTING)
  340. return;
  341. state = EClientState::DISCONNECTING;
  342. mapToStart = nullptr;
  343. LobbyClientDisconnected lcd;
  344. lcd.clientId = c->connectionID;
  345. logNetwork->info("Connection has been requested to be closed.");
  346. if(isServerLocal())
  347. {
  348. lcd.shutdownServer = true;
  349. logNetwork->info("Sent closing signal to the server");
  350. }
  351. else
  352. {
  353. logNetwork->info("Sent leaving signal to the server");
  354. }
  355. sendLobbyPack(lcd);
  356. {
  357. // Network thread might be applying network pack at this moment
  358. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  359. c.reset();
  360. }
  361. }
  362. void CServerHandler::setCampaignState(std::shared_ptr<CampaignState> newCampaign)
  363. {
  364. state = EClientState::LOBBY_CAMPAIGN;
  365. LobbySetCampaign lsc;
  366. lsc.ourCampaign = newCampaign;
  367. sendLobbyPack(lsc);
  368. }
  369. void CServerHandler::setCampaignMap(CampaignScenarioID mapId) const
  370. {
  371. if(state == 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(state == 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. LobbyChatMessage lcm;
  476. lcm.message = txt;
  477. lcm.playerName = playerNames.find(myFirstId())->second.name;
  478. sendLobbyPack(lcm);
  479. }
  480. }
  481. void CServerHandler::sendGuiAction(ui8 action) const
  482. {
  483. LobbyGuiAction lga;
  484. lga.action = static_cast<LobbyGuiAction::EAction>(action);
  485. sendLobbyPack(lga);
  486. }
  487. void CServerHandler::sendRestartGame() const
  488. {
  489. GH.windows().createAndPushWindow<CLoadingScreen>();
  490. LobbyEndGame endGame;
  491. endGame.closeConnection = false;
  492. endGame.restart = true;
  493. sendLobbyPack(endGame);
  494. }
  495. bool CServerHandler::validateGameStart(bool allowOnlyAI) const
  496. {
  497. try
  498. {
  499. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  500. }
  501. catch(ModIncompatibility & e)
  502. {
  503. logGlobal->warn("Incompatibility exception during start scenario: %s", e.what());
  504. std::string errorMsg;
  505. if(!e.whatMissing().empty())
  506. {
  507. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToEnable") + '\n';
  508. errorMsg += e.whatMissing();
  509. }
  510. if(!e.whatExcessive().empty())
  511. {
  512. errorMsg += VLC->generaltexth->translate("vcmi.server.errors.modsToDisable") + '\n';
  513. errorMsg += e.whatExcessive();
  514. }
  515. showServerError(errorMsg);
  516. return false;
  517. }
  518. catch(std::exception & e)
  519. {
  520. logGlobal->error("Exception during startScenario: %s", e.what());
  521. showServerError( std::string("Unable to start map! Reason: ") + e.what());
  522. return false;
  523. }
  524. return true;
  525. }
  526. void CServerHandler::sendStartGame(bool allowOnlyAI) const
  527. {
  528. verifyStateBeforeStart(allowOnlyAI ? true : settings["session"]["onlyai"].Bool());
  529. if(!settings["session"]["headless"].Bool())
  530. GH.windows().createAndPushWindow<CLoadingScreen>();
  531. LobbyStartGame lsg;
  532. if(client)
  533. {
  534. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  535. lsg.initializedStartInfo->mode = EStartMode::NEW_GAME;
  536. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  537. * si = * lsg.initializedStartInfo;
  538. }
  539. sendLobbyPack(lsg);
  540. c->enterLobbyConnectionMode();
  541. }
  542. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  543. {
  544. mapToStart = to;
  545. }
  546. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  547. {
  548. if(CMM)
  549. CMM->disable();
  550. std::swap(client, nextClient);
  551. highScoreCalc = nullptr;
  552. switch(si->mode)
  553. {
  554. case EStartMode::NEW_GAME:
  555. client->newGame(gameState);
  556. break;
  557. case EStartMode::CAMPAIGN:
  558. client->newGame(gameState);
  559. break;
  560. case EStartMode::LOAD_GAME:
  561. client->loadGame(gameState);
  562. break;
  563. default:
  564. throw std::runtime_error("Invalid mode");
  565. }
  566. // After everything initialized we can accept CPackToClient netpacks
  567. c->enterGameplayConnectionMode(client->gameState());
  568. state = EClientState::GAMEPLAY;
  569. }
  570. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  571. {
  572. if(closeConnection)
  573. {
  574. // Game is ending
  575. // Tell the network thread to reach a stable state
  576. CSH->sendClientDisconnecting();
  577. logNetwork->info("Closed connection.");
  578. }
  579. client->endGame();
  580. client.reset();
  581. if(!restart)
  582. {
  583. if(CMM)
  584. {
  585. GH.curInt = CMM.get();
  586. CMM->enable();
  587. }
  588. else
  589. {
  590. GH.curInt = CMainMenu::create().get();
  591. }
  592. }
  593. if(c)
  594. {
  595. nextClient = std::make_unique<CClient>();
  596. c->setCallback(nextClient.get());
  597. c->enterLobbyConnectionMode();
  598. }
  599. }
  600. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  601. {
  602. std::shared_ptr<CampaignState> ourCampaign = cs;
  603. if (!cs)
  604. ourCampaign = si->campState;
  605. if(highScoreCalc == nullptr)
  606. {
  607. highScoreCalc = std::make_shared<HighScoreCalculation>();
  608. highScoreCalc->isCampaign = true;
  609. highScoreCalc->parameters.clear();
  610. }
  611. param.campaignName = cs->getNameTranslated();
  612. highScoreCalc->parameters.push_back(param);
  613. GH.dispatchMainThread([ourCampaign, this]()
  614. {
  615. CSH->campaignServerRestartLock.set(true);
  616. CSH->endGameplay();
  617. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  618. auto finisher = [=]()
  619. {
  620. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  621. {
  622. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  623. entry->Bool() = true;
  624. }
  625. GH.windows().pushWindow(CMM);
  626. GH.windows().pushWindow(CMM->menu);
  627. if(!ourCampaign->isCampaignFinished())
  628. CMM->openCampaignLobby(ourCampaign);
  629. else
  630. {
  631. CMM->openCampaignScreen(ourCampaign->campaignSet);
  632. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  633. }
  634. };
  635. if(epilogue.hasPrologEpilog)
  636. {
  637. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  638. }
  639. else
  640. {
  641. CSH->campaignServerRestartLock.waitUntil(false);
  642. finisher();
  643. }
  644. });
  645. }
  646. void CServerHandler::showServerError(const std::string & txt) const
  647. {
  648. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  649. GH.windows().popWindow(w);
  650. CInfoWindow::showInfoDialog(txt, {});
  651. }
  652. int CServerHandler::howManyPlayerInterfaces()
  653. {
  654. int playerInts = 0;
  655. for(auto pint : client->playerint)
  656. {
  657. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  658. playerInts++;
  659. }
  660. return playerInts;
  661. }
  662. ELoadMode CServerHandler::getLoadMode()
  663. {
  664. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  665. {
  666. if(si->campState)
  667. return ELoadMode::CAMPAIGN;
  668. for(auto pn : playerNames)
  669. {
  670. if(pn.second.connection != c->connectionID)
  671. return ELoadMode::MULTI;
  672. }
  673. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  674. return ELoadMode::MULTI;
  675. return ELoadMode::SINGLE;
  676. }
  677. return loadMode;
  678. }
  679. void CServerHandler::debugStartTest(std::string filename, bool save)
  680. {
  681. logGlobal->info("Starting debug test with file: %s", filename);
  682. auto mapInfo = std::make_shared<CMapInfo>();
  683. if(save)
  684. {
  685. resetStateForLobby(EStartMode::LOAD_GAME, ESelectionScreen::loadGame, {});
  686. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  687. }
  688. else
  689. {
  690. resetStateForLobby(EStartMode::NEW_GAME, ESelectionScreen::newGame, {});
  691. mapInfo->mapInit(filename);
  692. }
  693. if(settings["session"]["donotstartserver"].Bool())
  694. connectToServer(getLocalHostname(), getLocalPort());
  695. else
  696. startLocalServerAndConnect(false);
  697. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  698. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  699. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  700. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  701. {
  702. setMapInfo(mapInfo);
  703. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  704. }
  705. // "Click" on color to remove us from it
  706. setPlayer(myFirstColor());
  707. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  708. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  709. while(true)
  710. {
  711. try
  712. {
  713. sendStartGame();
  714. break;
  715. }
  716. catch(...)
  717. {
  718. }
  719. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  720. }
  721. }
  722. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  723. {
  724. private:
  725. CServerHandler & handler;
  726. public:
  727. ServerHandlerCPackVisitor(CServerHandler & handler)
  728. :handler(handler)
  729. {
  730. }
  731. virtual bool callTyped() override { return false; }
  732. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  733. {
  734. handler.visitForLobby(lobbyPack);
  735. }
  736. virtual void visitForClient(CPackForClient & clientPack) override
  737. {
  738. handler.visitForClient(clientPack);
  739. }
  740. };
  741. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<uint8_t> & message)
  742. {
  743. CPack * pack = c->retrievePack(message);
  744. if(state == EClientState::DISCONNECTING)
  745. {
  746. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  747. // Though currently they'll be delivered and might cause crash.
  748. vstd::clear_pointer(pack);
  749. }
  750. else
  751. {
  752. ServerHandlerCPackVisitor visitor(*this);
  753. pack->visit(visitor);
  754. }
  755. }
  756. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection)
  757. {
  758. assert(networkConnection == connection);
  759. networkConnection.reset();
  760. if(state == EClientState::DISCONNECTING)
  761. {
  762. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  763. }
  764. else
  765. {
  766. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  767. if(client)
  768. {
  769. state = EClientState::DISCONNECTING;
  770. GH.dispatchMainThread([]()
  771. {
  772. CSH->endGameplay();
  773. GH.defActionsDef = 63;
  774. CMM->menu->switchToTab("main");
  775. });
  776. }
  777. else
  778. {
  779. LobbyClientDisconnected lcd;
  780. lcd.clientId = c->connectionID;
  781. applyPackOnLobbyScreen(lcd);
  782. }
  783. }
  784. }
  785. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  786. {
  787. if(applier->getApplier(CTypeList::getInstance().getTypeID(&lobbyPack))->applyOnLobbyHandler(this, lobbyPack))
  788. {
  789. if(!settings["session"]["headless"].Bool())
  790. applyPackOnLobbyScreen(lobbyPack);
  791. }
  792. }
  793. void CServerHandler::visitForClient(CPackForClient & clientPack)
  794. {
  795. client->handlePack(&clientPack);
  796. }
  797. void CServerHandler::threadRunServer(bool connectToLobby)
  798. {
  799. #if !defined(VCMI_MOBILE)
  800. setThreadName("runServer");
  801. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  802. std::string comm = VCMIDirs::get().serverPath().string()
  803. + " --port=" + std::to_string(getLocalPort())
  804. + " --run-by-client";
  805. if(connectToLobby)
  806. comm += " --lobby";
  807. comm += " > \"" + logName + '\"';
  808. logGlobal->info("Server command line: %s", comm);
  809. #ifdef VCMI_WINDOWS
  810. int result = -1;
  811. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  812. if(bufSize > 0)
  813. {
  814. std::wstring wComm(bufSize, {});
  815. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  816. if(convertResult > 0)
  817. result = ::_wsystem(wComm.c_str());
  818. else
  819. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  820. }
  821. else
  822. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  823. #else
  824. int result = std::system(comm.c_str());
  825. #endif
  826. if (result == 0)
  827. {
  828. logNetwork->info("Server closed correctly");
  829. }
  830. else
  831. {
  832. if (state != EClientState::DISCONNECTING)
  833. {
  834. if (state == EClientState::CONNECTING)
  835. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.server.errors.existingProcess"), {});
  836. else
  837. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.server.errors.serverCrashed"), {});
  838. }
  839. state = EClientState::CONNECTION_CANCELLED; // stop attempts to reconnect
  840. logNetwork->error("Error: server failed to close correctly or crashed!");
  841. logNetwork->error("Check %s for more info", logName);
  842. }
  843. onServerFinished();
  844. #endif
  845. }
  846. void CServerHandler::onServerFinished()
  847. {
  848. threadRunLocalServer.reset();
  849. if (CSH)
  850. CSH->campaignServerRestartLock.setn(false);
  851. }
  852. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  853. {
  854. if(state != EClientState::STARTING)
  855. c->sendPack(&pack);
  856. }