Client.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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/CAdventureMapInterface.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. CPlayerInterface::battleInt.reset();
  316. playerint.clear();
  317. battleints.clear();
  318. battleCallbacks.clear();
  319. playerEnvironments.clear();
  320. logNetwork->info("Deleted playerInts.");
  321. logNetwork->info("Client stopped.");
  322. }
  323. void CClient::initMapHandler()
  324. {
  325. // TODO: CMapHandler initialization can probably go somewhere else
  326. // It's can't be before initialization of interfaces
  327. // During loading CPlayerInterface from serialized state it's depend on MH
  328. if(!settings["session"]["headless"].Bool())
  329. {
  330. const_cast<CGameInfo *>(CGI)->mh = new CMapHandler(gs->map);
  331. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  332. }
  333. pathCache.clear();
  334. }
  335. void CClient::initPlayerEnvironments()
  336. {
  337. playerEnvironments.clear();
  338. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  339. bool hasHumanPlayer = false;
  340. for(auto & color : allPlayers)
  341. {
  342. logNetwork->info("Preparing environment for player %s", color.getStr());
  343. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  344. if(!hasHumanPlayer && gs->players[color].isHuman())
  345. hasHumanPlayer = true;
  346. }
  347. if(!hasHumanPlayer)
  348. {
  349. Settings session = settings.write["session"];
  350. session["spectate"].Bool() = true;
  351. session["spectate-skip-battle-result"].Bool() = true;
  352. session["spectate-ignore-hero"].Bool() = true;
  353. }
  354. if(settings["session"]["spectate"].Bool())
  355. {
  356. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
  357. }
  358. }
  359. void CClient::initPlayerInterfaces()
  360. {
  361. for(auto & elem : gs->scenarioOps->playerInfos)
  362. {
  363. PlayerColor color = elem.first;
  364. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  365. continue;
  366. if(!vstd::contains(playerint, color))
  367. {
  368. logNetwork->info("Preparing interface for player %s", color.getStr());
  369. if(elem.second.isControlledByAI())
  370. {
  371. auto AiToGive = aiNameForPlayer(elem.second, false);
  372. logNetwork->info("Player %s will be lead by %s", color.getStr(), AiToGive);
  373. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  374. }
  375. else
  376. {
  377. logNetwork->info("Player %s will be lead by human", color.getStr());
  378. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  379. }
  380. }
  381. }
  382. if(settings["session"]["spectate"].Bool())
  383. {
  384. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  385. }
  386. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  387. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  388. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  389. }
  390. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI)
  391. {
  392. if(ps.name.size())
  393. {
  394. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  395. if(boost::filesystem::exists(aiPath))
  396. return ps.name;
  397. }
  398. return aiNameForPlayer(battleAI);
  399. }
  400. std::string CClient::aiNameForPlayer(bool battleAI)
  401. {
  402. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  403. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  404. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  405. //TODO what about human players
  406. if(battleints.size() >= sensibleAILimit)
  407. return badAI;
  408. return goodAI;
  409. }
  410. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  411. {
  412. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  413. playerint[color] = gameInterface;
  414. logGlobal->trace("\tInitializing the interface for player %s", color.getStr());
  415. auto cb = std::make_shared<CCallback>(gs, color, this);
  416. battleCallbacks[color] = cb;
  417. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  418. installNewBattleInterface(gameInterface, color, battlecb);
  419. }
  420. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  421. {
  422. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  423. battleints[color] = battleInterface;
  424. if(needCallback)
  425. {
  426. logGlobal->trace("\tInitializing the battle interface for player %s", color.getStr());
  427. auto cbc = std::make_shared<CBattleCallback>(color, this);
  428. battleCallbacks[color] = cbc;
  429. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  430. }
  431. }
  432. void CClient::handlePack(CPack * pack)
  433. {
  434. CBaseForCLApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  435. if(apply)
  436. {
  437. boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
  438. apply->applyOnClBefore(this, pack);
  439. logNetwork->trace("\tMade first apply on cl: %s", typeList.getTypeInfo(pack)->name());
  440. gs->apply(pack);
  441. logNetwork->trace("\tApplied on gs: %s", typeList.getTypeInfo(pack)->name());
  442. apply->applyOnClAfter(this, pack);
  443. logNetwork->trace("\tMade second apply on cl: %s", typeList.getTypeInfo(pack)->name());
  444. }
  445. else
  446. {
  447. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
  448. }
  449. delete pack;
  450. }
  451. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  452. {
  453. static ui32 requestCounter = 0;
  454. ui32 requestID = requestCounter++;
  455. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  456. waitingRequest.pushBack(requestID);
  457. request->requestID = requestID;
  458. request->player = player;
  459. CSH->c->sendPack(request);
  460. if(vstd::contains(playerint, player))
  461. playerint[player]->requestSent(request, requestID);
  462. return requestID;
  463. }
  464. void CClient::battleStarted(const BattleInfo * info)
  465. {
  466. setBattle(info);
  467. for(auto & battleCb : battleCallbacks)
  468. {
  469. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  470. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  471. {
  472. battleCb.second->setBattle(info);
  473. }
  474. }
  475. std::shared_ptr<CPlayerInterface> att, def;
  476. auto & leftSide = info->sides[0], & rightSide = info->sides[1];
  477. //If quick combat is not, do not prepare interfaces for battleint
  478. auto callBattleStart = [&](PlayerColor color, ui8 side)
  479. {
  480. if(vstd::contains(battleints, color))
  481. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  482. };
  483. callBattleStart(leftSide.color, 0);
  484. callBattleStart(rightSide.color, 1);
  485. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  486. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  487. callBattleStart(PlayerColor::SPECTATOR, 1);
  488. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  489. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  490. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  491. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  492. //Remove player interfaces for auto battle (quickCombat option)
  493. if(att && att->isAutoFightOn)
  494. {
  495. att.reset();
  496. def.reset();
  497. }
  498. if(!settings["session"]["headless"].Bool())
  499. {
  500. if(!!att || !!def)
  501. {
  502. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  503. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  504. }
  505. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  506. {
  507. //TODO: This certainly need improvement
  508. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  509. spectratorInt->cb->setBattle(info);
  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, spectratorInt);
  512. }
  513. }
  514. if(info->tacticDistance && vstd::contains(battleints, info->sides[info->tacticsSide].color))
  515. {
  516. PlayerColor color = info->sides[info->tacticsSide].color;
  517. playerTacticThreads[color] = std::make_unique<boost::thread>(&CClient::commenceTacticPhaseForInt, this, battleints[color]);
  518. }
  519. }
  520. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  521. {
  522. setThreadName("CClient::commenceTacticPhaseForInt");
  523. try
  524. {
  525. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  526. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  527. {
  528. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).value()));
  529. sendRequest(&ma, battleInt->playerID);
  530. }
  531. }
  532. catch(...)
  533. {
  534. handleException();
  535. }
  536. }
  537. void CClient::battleFinished()
  538. {
  539. stopAllBattleActions();
  540. for(auto & side : gs->curB->sides)
  541. if(battleCallbacks.count(side.color))
  542. battleCallbacks[side.color]->setBattle(nullptr);
  543. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  544. battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
  545. setBattle(nullptr);
  546. gs->curB.dellNull();
  547. }
  548. void CClient::startPlayerBattleAction(PlayerColor color)
  549. {
  550. stopPlayerBattleAction(color);
  551. if(vstd::contains(battleints, color))
  552. {
  553. auto thread = std::make_shared<boost::thread>(std::bind(&CClient::waitForMoveAndSend, this, color));
  554. playerActionThreads[color] = thread;
  555. }
  556. }
  557. void CClient::stopPlayerBattleAction(PlayerColor color)
  558. {
  559. if(vstd::contains(playerActionThreads, color))
  560. {
  561. auto thread = playerActionThreads.at(color);
  562. if(thread->joinable())
  563. {
  564. thread->interrupt();
  565. thread->join();
  566. }
  567. playerActionThreads.erase(color);
  568. }
  569. }
  570. void CClient::stopAllBattleActions()
  571. {
  572. while(!playerActionThreads.empty())
  573. stopPlayerBattleAction(playerActionThreads.begin()->first);
  574. }
  575. void CClient::waitForMoveAndSend(PlayerColor color)
  576. {
  577. try
  578. {
  579. setThreadName("CClient::waitForMoveAndSend");
  580. assert(vstd::contains(battleints, color));
  581. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  582. if(ba.actionType != EActionType::CANCEL)
  583. {
  584. logNetwork->trace("Send battle action to server: %s", ba.toString());
  585. MakeAction temp_action(ba);
  586. sendRequest(&temp_action, color);
  587. }
  588. }
  589. catch(boost::thread_interrupted &)
  590. {
  591. logNetwork->debug("Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?");
  592. }
  593. catch(...)
  594. {
  595. handleException();
  596. }
  597. }
  598. void CClient::invalidatePaths()
  599. {
  600. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  601. pathCache.clear();
  602. }
  603. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  604. {
  605. assert(h);
  606. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  607. auto iter = pathCache.find(h);
  608. if(iter == std::end(pathCache))
  609. {
  610. std::shared_ptr<CPathsInfo> paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  611. gs->calculatePaths(h, *paths.get());
  612. pathCache[h] = paths;
  613. return paths;
  614. }
  615. else
  616. {
  617. return iter->second;
  618. }
  619. }
  620. PlayerColor CClient::getLocalPlayer() const
  621. {
  622. if(LOCPLINT)
  623. return LOCPLINT->playerID;
  624. return getCurrentPlayer();
  625. }
  626. #if SCRIPTING_ENABLED
  627. scripting::Pool * CClient::getGlobalContextPool() const
  628. {
  629. return clientScripts.get();
  630. }
  631. scripting::Pool * CClient::getContextPool() const
  632. {
  633. return clientScripts.get();
  634. }
  635. #endif
  636. void CClient::reinitScripting()
  637. {
  638. clientEventBus = std::make_unique<events::EventBus>();
  639. #if SCRIPTING_ENABLED
  640. clientScripts.reset(new scripting::PoolImpl(this));
  641. #endif
  642. }
  643. void CClient::removeGUI()
  644. {
  645. // CClient::endGame
  646. GH.curInt = nullptr;
  647. if(GH.topInt())
  648. GH.topInt()->deactivate();
  649. adventureInt.reset();
  650. GH.listInt.clear();
  651. GH.objsToBlit.clear();
  652. GH.statusbar.reset();
  653. logGlobal->info("Removed GUI.");
  654. LOCPLINT = nullptr;
  655. }
  656. void CClient::cleanThreads()
  657. {
  658. stopAllBattleActions();
  659. while (!playerTacticThreads.empty())
  660. {
  661. PlayerColor color = playerTacticThreads.begin()->first;
  662. //set tacticcMode of the players to false to stop tacticThread
  663. if (vstd::contains(battleints, color))
  664. battleints[color]->forceEndTacticPhase();
  665. playerTacticThreads[color]->join();
  666. playerTacticThreads.erase(color);
  667. }
  668. }
  669. #ifdef VCMI_ANDROID
  670. #ifndef SINGLE_PROCESS_APP
  671. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerClosed(JNIEnv * env, jclass cls)
  672. {
  673. logNetwork->info("Received server closed signal");
  674. if (CSH) {
  675. CSH->campaignServerRestartLock.setn(false);
  676. }
  677. }
  678. extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jclass cls)
  679. {
  680. logNetwork->info("Received server ready signal");
  681. androidTestServerReadyFlag.store(true);
  682. }
  683. #endif
  684. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  685. {
  686. logGlobal->info("Received emergency save game request");
  687. if(!LOCPLINT || !LOCPLINT->cb)
  688. {
  689. return false;
  690. }
  691. LOCPLINT->cb->save("Saves/_Android_Autosave");
  692. return true;
  693. }
  694. #endif