Client.cpp 21 KB

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