Client.cpp 21 KB

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