Client.cpp 21 KB

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