Client.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. /*
  2. * Client.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 "Global.h"
  11. #include "StdInc.h"
  12. #include "Client.h"
  13. #include "CGameInfo.h"
  14. #include "CPlayerInterface.h"
  15. #include "CServerHandler.h"
  16. #include "ClientNetPackVisitors.h"
  17. #include "adventureMap/CAdvMapInt.h"
  18. #include "battle/BattleInterface.h"
  19. #include "gui/CGuiHandler.h"
  20. #include "mapView/mapHandler.h"
  21. #include "../CCallback.h"
  22. #include "../lib/CConfigHandler.h"
  23. #include "../lib/CGameState.h"
  24. #include "../lib/CThreadHelper.h"
  25. #include "../lib/VCMIDirs.h"
  26. #include "../lib/battle/BattleInfo.h"
  27. #include "../lib/serializer/BinaryDeserializer.h"
  28. #include "../lib/mapping/CMapService.h"
  29. #include "../lib/filesystem/Filesystem.h"
  30. #include "../lib/registerTypes/RegisterTypes.h"
  31. #include "../lib/serializer/Connection.h"
  32. #include <memory>
  33. #include <vcmi/events/EventBus.h>
  34. #if SCRIPTING_ENABLED
  35. #include "../lib/ScriptHandler.h"
  36. #endif
  37. #ifdef VCMI_ANDROID
  38. #include "lib/CAndroidVMHelper.h"
  39. #ifndef SINGLE_PROCESS_APP
  40. std::atomic_bool androidTestServerReadyFlag;
  41. #endif
  42. #endif
  43. ThreadSafeVector<int> CClient::waitingRequest;
  44. template<typename T> class CApplyOnCL;
  45. class CBaseForCLApply
  46. {
  47. public:
  48. virtual void applyOnClAfter(CClient * cl, void * pack) const =0;
  49. virtual void applyOnClBefore(CClient * cl, void * pack) const =0;
  50. virtual ~CBaseForCLApply(){}
  51. template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
  52. {
  53. return new CApplyOnCL<U>();
  54. }
  55. };
  56. template<typename T> class CApplyOnCL : public CBaseForCLApply
  57. {
  58. public:
  59. void applyOnClAfter(CClient * cl, void * pack) const override
  60. {
  61. T * ptr = static_cast<T *>(pack);
  62. ApplyClientNetPackVisitor visitor(*cl, *cl->gameState());
  63. ptr->visit(visitor);
  64. }
  65. void applyOnClBefore(CClient * cl, void * pack) const override
  66. {
  67. T * ptr = static_cast<T *>(pack);
  68. ApplyFirstClientNetPackVisitor visitor(*cl, *cl->gameState());
  69. ptr->visit(visitor);
  70. }
  71. };
  72. template<> class CApplyOnCL<CPack>: public CBaseForCLApply
  73. {
  74. public:
  75. void applyOnClAfter(CClient * cl, void * pack) const override
  76. {
  77. logGlobal->error("Cannot apply on CL plain CPack!");
  78. assert(0);
  79. }
  80. void applyOnClBefore(CClient * cl, void * pack) const override
  81. {
  82. logGlobal->error("Cannot apply on CL plain CPack!");
  83. assert(0);
  84. }
  85. };
  86. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  87. : player(player_),
  88. cl(cl_),
  89. mainCallback(mainCallback_)
  90. {
  91. }
  92. const Services * CPlayerEnvironment::services() const
  93. {
  94. return VLC;
  95. }
  96. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  97. {
  98. return logGlobal;
  99. }
  100. events::EventBus * CPlayerEnvironment::eventBus() const
  101. {
  102. return cl->eventBus();//always get actual value
  103. }
  104. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle() const
  105. {
  106. return mainCallback.get();
  107. }
  108. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  109. {
  110. return mainCallback.get();
  111. }
  112. CClient::CClient()
  113. {
  114. waitingRequest.clear();
  115. applier = std::make_shared<CApplier<CBaseForCLApply>>();
  116. registerTypesClientPacks1(*applier);
  117. registerTypesClientPacks2(*applier);
  118. IObjectInterface::cb = this;
  119. gs = nullptr;
  120. }
  121. CClient::~CClient()
  122. {
  123. IObjectInterface::cb = nullptr;
  124. }
  125. const Services * CClient::services() const
  126. {
  127. return VLC; //todo: this should be CGI
  128. }
  129. const CClient::BattleCb * CClient::battle() const
  130. {
  131. return this;
  132. }
  133. const CClient::GameCb * CClient::game() const
  134. {
  135. return this;
  136. }
  137. vstd::CLoggerBase * CClient::logger() const
  138. {
  139. return logGlobal;
  140. }
  141. events::EventBus * CClient::eventBus() const
  142. {
  143. return clientEventBus.get();
  144. }
  145. void CClient::newGame(CGameState * initializedGameState)
  146. {
  147. CSH->th->update();
  148. CMapService mapService;
  149. gs = initializedGameState ? initializedGameState : new CGameState();
  150. gs->preInit(VLC);
  151. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  152. if(!initializedGameState)
  153. gs->init(&mapService, CSH->si.get(), settings["general"]["saveRandomMaps"].Bool());
  154. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  155. initMapHandler();
  156. reinitScripting();
  157. initPlayerEnvironments();
  158. initPlayerInterfaces();
  159. }
  160. void CClient::loadGame(CGameState * initializedGameState)
  161. {
  162. logNetwork->info("Loading procedure started!");
  163. logNetwork->info("Game state was transferred over network, loading.");
  164. gs = initializedGameState;
  165. gs->preInit(VLC);
  166. gs->updateOnLoad(CSH->si.get());
  167. logNetwork->info("Game loaded, initialize interfaces.");
  168. initMapHandler();
  169. reinitScripting();
  170. initPlayerEnvironments();
  171. // Loading of client state - disabled for now
  172. // Since client no longer writes or loads its own state and instead receives it from server
  173. // client state serializer will serialize its own copies of all pointers, e.g. heroes/towns/objects
  174. // and on deserialize will create its own copies (instead of using copies from state received from server)
  175. // Potential solutions:
  176. // 1) Use server gamestate to deserialize pointers, so any pointer to same object will point to server instance and not our copy
  177. // 2) Remove all serialization of pointers with instance ID's and restore them on load (including AI deserializer code)
  178. // 3) Completely remove client savegame and send all information, like hero paths and sleeping status to server (either in form of hero properties or as some generic "client options" message
  179. #ifdef BROKEN_CLIENT_STATE_SERIALIZATION_HAS_BEEN_FIXED
  180. // try to deserialize client data including sleepingHeroes
  181. try
  182. {
  183. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(CSH->si->mapname, EResType::CLIENT_SAVEGAME));
  184. if(clientSaveName.empty())
  185. throw std::runtime_error("Cannot open client part of " + CSH->si->mapname);
  186. std::unique_ptr<CLoadFile> loader (new CLoadFile(clientSaveName));
  187. serialize(loader->serializer, loader->serializer.fileVersion);
  188. logNetwork->info("Client data loaded.");
  189. }
  190. catch(std::exception & e)
  191. {
  192. logGlobal->info("Cannot load client data for game %s. Error: %s", CSH->si->mapname, e.what());
  193. }
  194. #endif
  195. initPlayerInterfaces();
  196. }
  197. void CClient::serialize(BinarySerializer & h, const int version)
  198. {
  199. assert(h.saving);
  200. ui8 players = static_cast<ui8>(playerint.size());
  201. h & players;
  202. for(auto i = playerint.begin(); i != playerint.end(); i++)
  203. {
  204. logGlobal->trace("Saving player %s interface", i->first);
  205. assert(i->first == i->second->playerID);
  206. h & i->first;
  207. h & i->second->dllName;
  208. h & i->second->human;
  209. i->second->saveGame(h, version);
  210. }
  211. #if SCRIPTING_ENABLED
  212. if(version >= 800)
  213. {
  214. JsonNode scriptsState;
  215. clientScripts->serializeState(h.saving, scriptsState);
  216. h & scriptsState;
  217. }
  218. #endif
  219. }
  220. void CClient::serialize(BinaryDeserializer & h, const int version)
  221. {
  222. assert(!h.saving);
  223. ui8 players = 0;
  224. h & players;
  225. for(int i = 0; i < players; i++)
  226. {
  227. std::string dllname;
  228. PlayerColor pid;
  229. bool isHuman = false;
  230. auto prevInt = LOCPLINT;
  231. h & pid;
  232. h & dllname;
  233. h & isHuman;
  234. assert(dllname.length() == 0 || !isHuman);
  235. if(pid == PlayerColor::NEUTRAL)
  236. {
  237. logGlobal->trace("Neutral battle interfaces are not serialized.");
  238. continue;
  239. }
  240. logGlobal->trace("Loading player %s interface", pid);
  241. std::shared_ptr<CGameInterface> nInt;
  242. if(dllname.length())
  243. nInt = CDynLibHandler::getNewAI(dllname);
  244. else
  245. nInt = std::make_shared<CPlayerInterface>(pid);
  246. nInt->dllName = dllname;
  247. nInt->human = isHuman;
  248. nInt->playerID = pid;
  249. bool shouldResetInterface = true;
  250. // Client no longer handle this player at all
  251. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), pid))
  252. {
  253. logGlobal->trace("Player %s is not belong to this client. Destroying interface", pid);
  254. }
  255. else if(isHuman && !vstd::contains(CSH->getHumanColors(), pid))
  256. {
  257. logGlobal->trace("Player %s is no longer controlled by human. Destroying interface", pid);
  258. }
  259. else if(!isHuman && vstd::contains(CSH->getHumanColors(), pid))
  260. {
  261. logGlobal->trace("Player %s is no longer controlled by AI. Destroying interface", pid);
  262. }
  263. else
  264. {
  265. installNewPlayerInterface(nInt, pid);
  266. shouldResetInterface = false;
  267. }
  268. // loadGame needs to be called after initGameInterface to load paths correctly
  269. // initGameInterface is called in installNewPlayerInterface
  270. nInt->loadGame(h, version);
  271. if (shouldResetInterface)
  272. {
  273. nInt.reset();
  274. LOCPLINT = prevInt;
  275. }
  276. }
  277. #if SCRIPTING_ENABLED
  278. {
  279. JsonNode scriptsState;
  280. h & scriptsState;
  281. clientScripts->serializeState(h.saving, scriptsState);
  282. }
  283. #endif
  284. logNetwork->trace("Loaded client part of save %d ms", CSH->th->getDiff());
  285. }
  286. void CClient::save(const std::string & fname)
  287. {
  288. if(gs->curB)
  289. {
  290. logNetwork->error("Game cannot be saved during battle!");
  291. return;
  292. }
  293. SaveGame save_game(fname);
  294. sendRequest(&save_game, PlayerColor::NEUTRAL);
  295. }
  296. void CClient::endGame()
  297. {
  298. #if SCRIPTING_ENABLED
  299. clientScripts.reset();
  300. #endif
  301. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  302. for(auto & i : playerint)
  303. i.second->finish();
  304. GH.curInt = nullptr;
  305. {
  306. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  307. logNetwork->info("Ending current game!");
  308. removeGUI();
  309. vstd::clear_pointer(const_cast<CGameInfo *>(CGI)->mh);
  310. vstd::clear_pointer(gs);
  311. logNetwork->info("Deleted mapHandler and gameState.");
  312. }
  313. //threads cleanup has to be after gs cleanup and before battleints cleanup to stop tacticThread
  314. cleanThreads();
  315. CPlayerInterface::battleInt.reset();
  316. playerint.clear();
  317. battleints.clear();
  318. battleCallbacks.clear();
  319. playerEnvironments.clear();
  320. logNetwork->info("Deleted playerInts.");
  321. logNetwork->info("Client stopped.");
  322. }
  323. void CClient::initMapHandler()
  324. {
  325. // TODO: CMapHandler initialization can probably go somewhere else
  326. // It's can't be before initialization of interfaces
  327. // During loading CPlayerInterface from serialized state it's depend on MH
  328. if(!settings["session"]["headless"].Bool())
  329. {
  330. const_cast<CGameInfo *>(CGI)->mh = new CMapHandler(gs->map);
  331. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  332. }
  333. pathCache.clear();
  334. }
  335. void CClient::initPlayerEnvironments()
  336. {
  337. playerEnvironments.clear();
  338. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  339. for(auto & color : allPlayers)
  340. {
  341. logNetwork->info("Preparing environment for player %s", color.getStr());
  342. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  343. }
  344. if(settings["session"]["spectate"].Bool())
  345. {
  346. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, boost::none, this));
  347. }
  348. }
  349. void CClient::initPlayerInterfaces()
  350. {
  351. for(auto & elem : gs->scenarioOps->playerInfos)
  352. {
  353. PlayerColor color = elem.first;
  354. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  355. continue;
  356. if(!vstd::contains(playerint, color))
  357. {
  358. logNetwork->info("Preparing interface for player %s", color.getStr());
  359. if(elem.second.isControlledByAI())
  360. {
  361. auto AiToGive = aiNameForPlayer(elem.second, false);
  362. logNetwork->info("Player %s will be lead by %s", color.getStr(), AiToGive);
  363. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  364. }
  365. else
  366. {
  367. logNetwork->info("Player %s will be lead by human", color.getStr());
  368. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  369. }
  370. }
  371. }
  372. if(settings["session"]["spectate"].Bool())
  373. {
  374. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  375. }
  376. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  377. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  378. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  379. }
  380. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI)
  381. {
  382. if(ps.name.size())
  383. {
  384. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  385. if(boost::filesystem::exists(aiPath))
  386. return ps.name;
  387. }
  388. return aiNameForPlayer(battleAI);
  389. }
  390. std::string CClient::aiNameForPlayer(bool battleAI)
  391. {
  392. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  393. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  394. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  395. //TODO what about human players
  396. if(battleints.size() >= sensibleAILimit)
  397. return badAI;
  398. return goodAI;
  399. }
  400. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  401. {
  402. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  403. playerint[color] = gameInterface;
  404. logGlobal->trace("\tInitializing the interface for player %s", color.getStr());
  405. auto cb = std::make_shared<CCallback>(gs, color, this);
  406. battleCallbacks[color] = cb;
  407. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  408. installNewBattleInterface(gameInterface, color, battlecb);
  409. }
  410. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  411. {
  412. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  413. battleints[color] = battleInterface;
  414. if(needCallback)
  415. {
  416. logGlobal->trace("\tInitializing the battle interface for player %s", color.getStr());
  417. auto cbc = std::make_shared<CBattleCallback>(color, this);
  418. battleCallbacks[color] = cbc;
  419. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  420. }
  421. }
  422. void CClient::handlePack(CPack * pack)
  423. {
  424. CBaseForCLApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  425. if(apply)
  426. {
  427. boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
  428. apply->applyOnClBefore(this, pack);
  429. logNetwork->trace("\tMade first apply on cl: %s", typeList.getTypeInfo(pack)->name());
  430. gs->apply(pack);
  431. logNetwork->trace("\tApplied on gs: %s", typeList.getTypeInfo(pack)->name());
  432. apply->applyOnClAfter(this, pack);
  433. logNetwork->trace("\tMade second apply on cl: %s", typeList.getTypeInfo(pack)->name());
  434. }
  435. else
  436. {
  437. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
  438. }
  439. delete pack;
  440. }
  441. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  442. {
  443. static ui32 requestCounter = 0;
  444. ui32 requestID = requestCounter++;
  445. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  446. waitingRequest.pushBack(requestID);
  447. request->requestID = requestID;
  448. request->player = player;
  449. CSH->c->sendPack(request);
  450. if(vstd::contains(playerint, player))
  451. playerint[player]->requestSent(request, requestID);
  452. return requestID;
  453. }
  454. void CClient::battleStarted(const BattleInfo * info)
  455. {
  456. setBattle(info);
  457. for(auto & battleCb : battleCallbacks)
  458. {
  459. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  460. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  461. {
  462. battleCb.second->setBattle(info);
  463. }
  464. }
  465. std::shared_ptr<CPlayerInterface> att, def;
  466. auto & leftSide = info->sides[0], & rightSide = info->sides[1];
  467. //If quick combat is not, do not prepare interfaces for battleint
  468. if(!settings["adventure"]["quickCombat"].Bool())
  469. {
  470. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  471. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  472. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  473. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  474. }
  475. if(!settings["session"]["headless"].Bool())
  476. {
  477. if(!!att || !!def)
  478. {
  479. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  480. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  481. }
  482. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  483. {
  484. //TODO: This certainly need improvement
  485. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  486. spectratorInt->cb->setBattle(info);
  487. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  488. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  489. }
  490. }
  491. auto callBattleStart = [&](PlayerColor color, ui8 side)
  492. {
  493. if(vstd::contains(battleints, color))
  494. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  495. };
  496. callBattleStart(leftSide.color, 0);
  497. callBattleStart(rightSide.color, 1);
  498. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  499. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  500. callBattleStart(PlayerColor::SPECTATOR, 1);
  501. if(info->tacticDistance && vstd::contains(battleints, info->sides[info->tacticsSide].color))
  502. {
  503. PlayerColor color = info->sides[info->tacticsSide].color;
  504. playerTacticThreads[color] = std::make_unique<boost::thread>(&CClient::commenceTacticPhaseForInt, this, battleints[color]);
  505. }
  506. }
  507. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  508. {
  509. setThreadName("CClient::commenceTacticPhaseForInt");
  510. try
  511. {
  512. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  513. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  514. {
  515. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).get()));
  516. sendRequest(&ma, battleInt->playerID);
  517. }
  518. }
  519. catch(...)
  520. {
  521. handleException();
  522. }
  523. }
  524. void CClient::battleFinished()
  525. {
  526. stopAllBattleActions();
  527. for(auto & side : gs->curB->sides)
  528. if(battleCallbacks.count(side.color))
  529. battleCallbacks[side.color]->setBattle(nullptr);
  530. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  531. battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
  532. setBattle(nullptr);
  533. }
  534. void CClient::startPlayerBattleAction(PlayerColor color)
  535. {
  536. stopPlayerBattleAction(color);
  537. if(vstd::contains(battleints, color))
  538. {
  539. auto thread = std::make_shared<boost::thread>(std::bind(&CClient::waitForMoveAndSend, this, color));
  540. playerActionThreads[color] = thread;
  541. }
  542. }
  543. void CClient::stopPlayerBattleAction(PlayerColor color)
  544. {
  545. if(vstd::contains(playerActionThreads, color))
  546. {
  547. auto thread = playerActionThreads.at(color);
  548. if(thread->joinable())
  549. {
  550. thread->interrupt();
  551. thread->join();
  552. }
  553. playerActionThreads.erase(color);
  554. }
  555. }
  556. void CClient::stopAllBattleActions()
  557. {
  558. while(!playerActionThreads.empty())
  559. stopPlayerBattleAction(playerActionThreads.begin()->first);
  560. }
  561. void CClient::waitForMoveAndSend(PlayerColor color)
  562. {
  563. try
  564. {
  565. setThreadName("CClient::waitForMoveAndSend");
  566. assert(vstd::contains(battleints, color));
  567. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  568. if(ba.actionType != EActionType::CANCEL)
  569. {
  570. logNetwork->trace("Send battle action to server: %s", ba.toString());
  571. MakeAction temp_action(ba);
  572. sendRequest(&temp_action, color);
  573. }
  574. }
  575. catch(boost::thread_interrupted &)
  576. {
  577. logNetwork->debug("Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?");
  578. }
  579. catch(...)
  580. {
  581. handleException();
  582. }
  583. }
  584. void CClient::invalidatePaths()
  585. {
  586. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  587. pathCache.clear();
  588. }
  589. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  590. {
  591. assert(h);
  592. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  593. auto iter = pathCache.find(h);
  594. if(iter == std::end(pathCache))
  595. {
  596. std::shared_ptr<CPathsInfo> paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  597. gs->calculatePaths(h, *paths.get());
  598. pathCache[h] = paths;
  599. return paths;
  600. }
  601. else
  602. {
  603. return iter->second;
  604. }
  605. }
  606. PlayerColor CClient::getLocalPlayer() const
  607. {
  608. if(LOCPLINT)
  609. return LOCPLINT->playerID;
  610. return getCurrentPlayer();
  611. }
  612. #if SCRIPTING_ENABLED
  613. scripting::Pool * CClient::getGlobalContextPool() const
  614. {
  615. return clientScripts.get();
  616. }
  617. scripting::Pool * CClient::getContextPool() const
  618. {
  619. return clientScripts.get();
  620. }
  621. #endif
  622. void CClient::reinitScripting()
  623. {
  624. clientEventBus = std::make_unique<events::EventBus>();
  625. #if SCRIPTING_ENABLED
  626. clientScripts.reset(new scripting::PoolImpl(this));
  627. #endif
  628. }
  629. void CClient::removeGUI()
  630. {
  631. // CClient::endGame
  632. GH.curInt = nullptr;
  633. if(GH.topInt())
  634. GH.topInt()->deactivate();
  635. adventureInt.reset();
  636. GH.listInt.clear();
  637. GH.objsToBlit.clear();
  638. GH.statusbar.reset();
  639. logGlobal->info("Removed GUI.");
  640. LOCPLINT = nullptr;
  641. }
  642. void CClient::cleanThreads()
  643. {
  644. stopAllBattleActions();
  645. while (!playerTacticThreads.empty())
  646. {
  647. PlayerColor color = playerTacticThreads.begin()->first;
  648. //set tacticcMode of the players to false to stop tacticThread
  649. if (vstd::contains(battleints, color))
  650. battleints[color]->forceEndTacticPhase();
  651. playerTacticThreads[color]->join();
  652. playerTacticThreads.erase(color);
  653. }
  654. }
  655. #ifdef VCMI_ANDROID
  656. #ifndef SINGLE_PROCESS_APP
  657. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerClosed(JNIEnv * env, jclass cls)
  658. {
  659. logNetwork->info("Received server closed signal");
  660. if (CSH) {
  661. CSH->campaignServerRestartLock.setn(false);
  662. }
  663. }
  664. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jclass cls)
  665. {
  666. logNetwork->info("Received server ready signal");
  667. androidTestServerReadyFlag.store(true);
  668. }
  669. #endif
  670. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  671. {
  672. logGlobal->info("Received emergency save game request");
  673. if(!LOCPLINT || !LOCPLINT->cb)
  674. {
  675. return false;
  676. }
  677. LOCPLINT->cb->save("Saves/_Android_Autosave");
  678. return true;
  679. }
  680. #endif