CServerHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. static const std::string NAME_AFFIX = "client";
  109. static const std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  110. CServerHandler::~CServerHandler()
  111. {
  112. networkHandler->stop();
  113. threadNetwork->join();
  114. }
  115. CServerHandler::CServerHandler()
  116. : state(EClientState::NONE)
  117. , networkHandler(INetworkHandler::createHandler())
  118. , applier(std::make_unique<CApplier<CBaseForLobbyApply>>())
  119. , lobbyClient(std::make_unique<GlobalLobbyClient>())
  120. , client(nullptr)
  121. , loadMode(0)
  122. , campaignStateToSend(nullptr)
  123. , campaignServerRestartLock(false)
  124. {
  125. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  126. registerTypesLobbyPacks(*applier);
  127. threadNetwork = std::make_unique<boost::thread>(&CServerHandler::threadRunNetwork, this);
  128. }
  129. void CServerHandler::threadRunNetwork()
  130. {
  131. logGlobal->info("Starting network thread");
  132. setThreadName("runNetwork");
  133. networkHandler->run();
  134. logGlobal->info("Ending network thread");
  135. }
  136. void CServerHandler::resetStateForLobby(const StartInfo::EMode mode, const std::vector<std::string> * names)
  137. {
  138. hostClientId = -1;
  139. state = EClientState::NONE;
  140. mapToStart = nullptr;
  141. th = std::make_unique<CStopWatch>();
  142. c.reset();
  143. si = std::make_shared<StartInfo>();
  144. playerNames.clear();
  145. si->difficulty = 1;
  146. si->mode = mode;
  147. myNames.clear();
  148. if(names && !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. nextClient = std::make_unique<CClient>();
  239. c->setCallback(nextClient.get());
  240. }
  241. else
  242. {
  243. // remote server refused connection - show error message
  244. state = EClientState::CONNECTION_FAILED;
  245. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.mainMenu.serverConnectionFailed"), {});
  246. }
  247. }
  248. void CServerHandler::onTimer()
  249. {
  250. if(state == EClientState::CONNECTION_CANCELLED)
  251. {
  252. logNetwork->info("Connection aborted by player!");
  253. return;
  254. }
  255. assert(isServerLocal());
  256. networkHandler->connectToRemote(*this, getLocalHostname(), getLocalPort());
  257. }
  258. void CServerHandler::onConnectionEstablished(const std::shared_ptr<INetworkConnection> & netConnection)
  259. {
  260. networkConnection = netConnection;
  261. logNetwork->info("Connection established");
  262. c = std::make_shared<CConnection>(netConnection);
  263. c->uuid = uuid;
  264. c->enterLobbyConnectionMode();
  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. GH.windows().createAndPushWindow<CLoadingScreen>();
  530. LobbyStartGame lsg;
  531. if(client)
  532. {
  533. lsg.initializedStartInfo = std::make_shared<StartInfo>(* const_cast<StartInfo *>(client->getStartInfo(true)));
  534. lsg.initializedStartInfo->mode = StartInfo::NEW_GAME;
  535. lsg.initializedStartInfo->seedToBeUsed = lsg.initializedStartInfo->seedPostInit = 0;
  536. * si = * lsg.initializedStartInfo;
  537. }
  538. sendLobbyPack(lsg);
  539. c->enterLobbyConnectionMode();
  540. }
  541. void CServerHandler::startMapAfterConnection(std::shared_ptr<CMapInfo> to)
  542. {
  543. mapToStart = to;
  544. }
  545. void CServerHandler::startGameplay(VCMI_LIB_WRAP_NAMESPACE(CGameState) * gameState)
  546. {
  547. if(CMM)
  548. CMM->disable();
  549. std::swap(client, nextClient);
  550. highScoreCalc = nullptr;
  551. switch(si->mode)
  552. {
  553. case StartInfo::NEW_GAME:
  554. client->newGame(gameState);
  555. break;
  556. case StartInfo::CAMPAIGN:
  557. client->newGame(gameState);
  558. break;
  559. case StartInfo::LOAD_GAME:
  560. client->loadGame(gameState);
  561. break;
  562. default:
  563. throw std::runtime_error("Invalid mode");
  564. }
  565. // After everything initialized we can accept CPackToClient netpacks
  566. c->enterGameplayConnectionMode(client->gameState());
  567. state = EClientState::GAMEPLAY;
  568. }
  569. void CServerHandler::endGameplay(bool closeConnection, bool restart)
  570. {
  571. if(closeConnection)
  572. {
  573. // Game is ending
  574. // Tell the network thread to reach a stable state
  575. CSH->sendClientDisconnecting();
  576. logNetwork->info("Closed connection.");
  577. }
  578. client->endGame();
  579. client.reset();
  580. if(!restart)
  581. {
  582. if(CMM)
  583. {
  584. GH.curInt = CMM.get();
  585. CMM->enable();
  586. }
  587. else
  588. {
  589. GH.curInt = CMainMenu::create().get();
  590. }
  591. }
  592. if(c)
  593. {
  594. nextClient = std::make_unique<CClient>();
  595. c->setCallback(nextClient.get());
  596. c->enterLobbyConnectionMode();
  597. }
  598. }
  599. void CServerHandler::startCampaignScenario(HighScoreParameter param, std::shared_ptr<CampaignState> cs)
  600. {
  601. std::shared_ptr<CampaignState> ourCampaign = cs;
  602. if (!cs)
  603. ourCampaign = si->campState;
  604. if(highScoreCalc == nullptr)
  605. {
  606. highScoreCalc = std::make_shared<HighScoreCalculation>();
  607. highScoreCalc->isCampaign = true;
  608. highScoreCalc->parameters.clear();
  609. }
  610. param.campaignName = cs->getNameTranslated();
  611. highScoreCalc->parameters.push_back(param);
  612. GH.dispatchMainThread([ourCampaign, this]()
  613. {
  614. CSH->campaignServerRestartLock.set(true);
  615. CSH->endGameplay();
  616. auto & epilogue = ourCampaign->scenario(*ourCampaign->lastScenario()).epilog;
  617. auto finisher = [=]()
  618. {
  619. if(ourCampaign->campaignSet != "" && ourCampaign->isCampaignFinished())
  620. {
  621. Settings entry = persistentStorage.write["completedCampaigns"][ourCampaign->getFilename()];
  622. entry->Bool() = true;
  623. }
  624. GH.windows().pushWindow(CMM);
  625. GH.windows().pushWindow(CMM->menu);
  626. if(!ourCampaign->isCampaignFinished())
  627. CMM->openCampaignLobby(ourCampaign);
  628. else
  629. {
  630. CMM->openCampaignScreen(ourCampaign->campaignSet);
  631. GH.windows().createAndPushWindow<CHighScoreInputScreen>(true, *highScoreCalc);
  632. }
  633. };
  634. if(epilogue.hasPrologEpilog)
  635. {
  636. GH.windows().createAndPushWindow<CPrologEpilogVideo>(epilogue, finisher);
  637. }
  638. else
  639. {
  640. CSH->campaignServerRestartLock.waitUntil(false);
  641. finisher();
  642. }
  643. });
  644. }
  645. void CServerHandler::showServerError(const std::string & txt) const
  646. {
  647. if(auto w = GH.windows().topWindow<CLoadingScreen>())
  648. GH.windows().popWindow(w);
  649. CInfoWindow::showInfoDialog(txt, {});
  650. }
  651. int CServerHandler::howManyPlayerInterfaces()
  652. {
  653. int playerInts = 0;
  654. for(auto pint : client->playerint)
  655. {
  656. if(dynamic_cast<CPlayerInterface *>(pint.second.get()))
  657. playerInts++;
  658. }
  659. return playerInts;
  660. }
  661. ui8 CServerHandler::getLoadMode()
  662. {
  663. if(loadMode != ELoadMode::TUTORIAL && state == EClientState::GAMEPLAY)
  664. {
  665. if(si->campState)
  666. return ELoadMode::CAMPAIGN;
  667. for(auto pn : playerNames)
  668. {
  669. if(pn.second.connection != c->connectionID)
  670. return ELoadMode::MULTI;
  671. }
  672. if(howManyPlayerInterfaces() > 1) //this condition will work for hotseat mode OR multiplayer with allowed more than 1 color per player to control
  673. return ELoadMode::MULTI;
  674. return ELoadMode::SINGLE;
  675. }
  676. return loadMode;
  677. }
  678. void CServerHandler::debugStartTest(std::string filename, bool save)
  679. {
  680. logGlobal->info("Starting debug test with file: %s", filename);
  681. auto mapInfo = std::make_shared<CMapInfo>();
  682. if(save)
  683. {
  684. resetStateForLobby(StartInfo::LOAD_GAME);
  685. mapInfo->saveInit(ResourcePath(filename, EResType::SAVEGAME));
  686. screenType = ESelectionScreen::loadGame;
  687. }
  688. else
  689. {
  690. resetStateForLobby(StartInfo::NEW_GAME);
  691. mapInfo->mapInit(filename);
  692. screenType = ESelectionScreen::newGame;
  693. }
  694. if(settings["session"]["donotstartserver"].Bool())
  695. connectToServer(getLocalHostname(), getLocalPort());
  696. else
  697. startLocalServerAndConnect(false);
  698. boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
  699. while(!settings["session"]["headless"].Bool() && !GH.windows().topWindow<CLobbyScreen>())
  700. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  701. while(!mi || mapInfo->fileURI != CSH->mi->fileURI)
  702. {
  703. setMapInfo(mapInfo);
  704. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  705. }
  706. // "Click" on color to remove us from it
  707. setPlayer(myFirstColor());
  708. while(myFirstColor() != PlayerColor::CANNOT_DETERMINE)
  709. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  710. while(true)
  711. {
  712. try
  713. {
  714. sendStartGame();
  715. break;
  716. }
  717. catch(...)
  718. {
  719. }
  720. boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
  721. }
  722. }
  723. class ServerHandlerCPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  724. {
  725. private:
  726. CServerHandler & handler;
  727. public:
  728. ServerHandlerCPackVisitor(CServerHandler & handler)
  729. :handler(handler)
  730. {
  731. }
  732. virtual bool callTyped() override { return false; }
  733. virtual void visitForLobby(CPackForLobby & lobbyPack) override
  734. {
  735. handler.visitForLobby(lobbyPack);
  736. }
  737. virtual void visitForClient(CPackForClient & clientPack) override
  738. {
  739. handler.visitForClient(clientPack);
  740. }
  741. };
  742. void CServerHandler::onPacketReceived(const std::shared_ptr<INetworkConnection> &, const std::vector<uint8_t> & message)
  743. {
  744. CPack * pack = c->retrievePack(message);
  745. if(state == EClientState::DISCONNECTING)
  746. {
  747. // FIXME: server shouldn't really send netpacks after it's tells client to disconnect
  748. // Though currently they'll be delivered and might cause crash.
  749. vstd::clear_pointer(pack);
  750. }
  751. else
  752. {
  753. ServerHandlerCPackVisitor visitor(*this);
  754. pack->visit(visitor);
  755. }
  756. }
  757. void CServerHandler::onDisconnected(const std::shared_ptr<INetworkConnection> & connection)
  758. {
  759. assert(networkConnection == connection);
  760. networkConnection.reset();
  761. if(state == EClientState::DISCONNECTING)
  762. {
  763. logNetwork->info("Successfully closed connection to server, ending listening thread!");
  764. }
  765. else
  766. {
  767. logNetwork->error("Lost connection to server, ending listening thread! Connection has been closed");
  768. if(client)
  769. {
  770. state = EClientState::DISCONNECTING;
  771. GH.dispatchMainThread([]()
  772. {
  773. CSH->endGameplay();
  774. GH.defActionsDef = 63;
  775. CMM->menu->switchToTab("main");
  776. });
  777. }
  778. else
  779. {
  780. LobbyClientDisconnected lcd;
  781. lcd.clientId = c->connectionID;
  782. applyPackOnLobbyScreen(lcd);
  783. }
  784. }
  785. }
  786. void CServerHandler::visitForLobby(CPackForLobby & lobbyPack)
  787. {
  788. if(applier->getApplier(CTypeList::getInstance().getTypeID(&lobbyPack))->applyOnLobbyHandler(this, lobbyPack))
  789. {
  790. if(!settings["session"]["headless"].Bool())
  791. applyPackOnLobbyScreen(lobbyPack);
  792. }
  793. }
  794. void CServerHandler::visitForClient(CPackForClient & clientPack)
  795. {
  796. client->handlePack(&clientPack);
  797. }
  798. void CServerHandler::threadRunServer(bool connectToLobby)
  799. {
  800. #if !defined(VCMI_MOBILE)
  801. setThreadName("runServer");
  802. const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
  803. std::string comm = VCMIDirs::get().serverPath().string()
  804. + " --port=" + std::to_string(getLocalPort())
  805. + " --run-by-client";
  806. if(connectToLobby)
  807. comm += " --lobby";
  808. comm += " > \"" + logName + '\"';
  809. logGlobal->info("Server command line: %s", comm);
  810. #ifdef VCMI_WINDOWS
  811. int result = -1;
  812. const auto bufSize = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), nullptr, 0);
  813. if(bufSize > 0)
  814. {
  815. std::wstring wComm(bufSize, {});
  816. const auto convertResult = ::MultiByteToWideChar(CP_UTF8, 0, comm.c_str(), comm.size(), &wComm[0], bufSize);
  817. if(convertResult > 0)
  818. result = ::_wsystem(wComm.c_str());
  819. else
  820. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to convert server launch command to wide string: " + comm);
  821. }
  822. else
  823. logNetwork->error("Error " + std::to_string(GetLastError()) + ": failed to obtain buffer length to convert server launch command to wide string : " + comm);
  824. #else
  825. int result = std::system(comm.c_str());
  826. #endif
  827. if (result == 0)
  828. {
  829. logNetwork->info("Server closed correctly");
  830. }
  831. else
  832. {
  833. if (state != EClientState::DISCONNECTING)
  834. {
  835. if (state == EClientState::CONNECTING)
  836. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.server.errors.existingProcess"), {});
  837. else
  838. CInfoWindow::showInfoDialog(CGI->generaltexth->translate("vcmi.server.errors.serverCrashed"), {});
  839. }
  840. state = EClientState::CONNECTION_CANCELLED; // stop attempts to reconnect
  841. logNetwork->error("Error: server failed to close correctly or crashed!");
  842. logNetwork->error("Check %s for more info", logName);
  843. }
  844. onServerFinished();
  845. #endif
  846. }
  847. void CServerHandler::onServerFinished()
  848. {
  849. threadRunLocalServer.reset();
  850. if (CSH)
  851. CSH->campaignServerRestartLock.setn(false);
  852. }
  853. void CServerHandler::sendLobbyPack(const CPackForLobby & pack) const
  854. {
  855. if(state != EClientState::STARTING)
  856. c->sendPack(&pack);
  857. }