Client.cpp 23 KB

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