Client.cpp 24 KB

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