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/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/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/filesystem/Filesystem.h"
  31. #include "../lib/registerTypes/RegisterTypes.h"
  32. #include "../lib/serializer/Connection.h"
  33. #include <memory>
  34. #include <vcmi/events/EventBus.h>
  35. #if SCRIPTING_ENABLED
  36. #include "../lib/ScriptHandler.h"
  37. #endif
  38. #ifdef VCMI_ANDROID
  39. #include "lib/CAndroidVMHelper.h"
  40. #ifndef SINGLE_PROCESS_APP
  41. std::atomic_bool androidTestServerReadyFlag;
  42. #endif
  43. #endif
  44. ThreadSafeVector<int> CClient::waitingRequest;
  45. template<typename T> class CApplyOnCL;
  46. class CBaseForCLApply
  47. {
  48. public:
  49. virtual void applyOnClAfter(CClient * cl, void * pack) const =0;
  50. virtual void applyOnClBefore(CClient * cl, void * pack) const =0;
  51. virtual ~CBaseForCLApply(){}
  52. template<typename U> static CBaseForCLApply * getApplier(const U * t = nullptr)
  53. {
  54. return new CApplyOnCL<U>();
  55. }
  56. };
  57. template<typename T> class CApplyOnCL : public CBaseForCLApply
  58. {
  59. public:
  60. void applyOnClAfter(CClient * cl, void * pack) const override
  61. {
  62. T * ptr = static_cast<T *>(pack);
  63. ApplyClientNetPackVisitor visitor(*cl, *cl->gameState());
  64. ptr->visit(visitor);
  65. }
  66. void applyOnClBefore(CClient * cl, void * pack) const override
  67. {
  68. T * ptr = static_cast<T *>(pack);
  69. ApplyFirstClientNetPackVisitor visitor(*cl, *cl->gameState());
  70. ptr->visit(visitor);
  71. }
  72. };
  73. template<> class CApplyOnCL<CPack>: public CBaseForCLApply
  74. {
  75. public:
  76. void applyOnClAfter(CClient * cl, void * pack) const override
  77. {
  78. logGlobal->error("Cannot apply on CL plain CPack!");
  79. assert(0);
  80. }
  81. void applyOnClBefore(CClient * cl, void * pack) const override
  82. {
  83. logGlobal->error("Cannot apply on CL plain CPack!");
  84. assert(0);
  85. }
  86. };
  87. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  88. : player(player_),
  89. cl(cl_),
  90. mainCallback(mainCallback_)
  91. {
  92. }
  93. const Services * CPlayerEnvironment::services() const
  94. {
  95. return VLC;
  96. }
  97. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  98. {
  99. return logGlobal;
  100. }
  101. events::EventBus * CPlayerEnvironment::eventBus() const
  102. {
  103. return cl->eventBus();//always get actual value
  104. }
  105. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle() const
  106. {
  107. return mainCallback.get();
  108. }
  109. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  110. {
  111. return mainCallback.get();
  112. }
  113. CClient::CClient()
  114. {
  115. waitingRequest.clear();
  116. applier = std::make_shared<CApplier<CBaseForCLApply>>();
  117. registerTypesClientPacks1(*applier);
  118. registerTypesClientPacks2(*applier);
  119. IObjectInterface::cb = this;
  120. gs = nullptr;
  121. }
  122. CClient::~CClient()
  123. {
  124. IObjectInterface::cb = nullptr;
  125. }
  126. const Services * CClient::services() const
  127. {
  128. return VLC; //todo: this should be CGI
  129. }
  130. const CClient::BattleCb * CClient::battle() const
  131. {
  132. return this;
  133. }
  134. const CClient::GameCb * CClient::game() const
  135. {
  136. return this;
  137. }
  138. vstd::CLoggerBase * CClient::logger() const
  139. {
  140. return logGlobal;
  141. }
  142. events::EventBus * CClient::eventBus() const
  143. {
  144. return clientEventBus.get();
  145. }
  146. void CClient::newGame(CGameState * initializedGameState)
  147. {
  148. CSH->th->update();
  149. CMapService mapService;
  150. gs = initializedGameState ? initializedGameState : new CGameState();
  151. gs->preInit(VLC);
  152. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  153. if(!initializedGameState)
  154. gs->init(&mapService, CSH->si.get(), settings["general"]["saveRandomMaps"].Bool());
  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);
  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("local")->getResourceName(ResourceID(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.fileVersion);
  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, const int version)
  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, version);
  211. }
  212. #if SCRIPTING_ENABLED
  213. if(version >= 800)
  214. {
  215. JsonNode scriptsState;
  216. clientScripts->serializeState(h.saving, scriptsState);
  217. h & scriptsState;
  218. }
  219. #endif
  220. }
  221. void CClient::serialize(BinaryDeserializer & h, const int version)
  222. {
  223. assert(!h.saving);
  224. ui8 players = 0;
  225. h & players;
  226. for(int i = 0; i < players; i++)
  227. {
  228. std::string dllname;
  229. PlayerColor pid;
  230. bool isHuman = false;
  231. auto prevInt = LOCPLINT;
  232. h & pid;
  233. h & dllname;
  234. h & isHuman;
  235. assert(dllname.length() == 0 || !isHuman);
  236. if(pid == PlayerColor::NEUTRAL)
  237. {
  238. logGlobal->trace("Neutral battle interfaces are not serialized.");
  239. continue;
  240. }
  241. logGlobal->trace("Loading player %s interface", pid);
  242. std::shared_ptr<CGameInterface> nInt;
  243. if(dllname.length())
  244. nInt = CDynLibHandler::getNewAI(dllname);
  245. else
  246. nInt = std::make_shared<CPlayerInterface>(pid);
  247. nInt->dllName = dllname;
  248. nInt->human = isHuman;
  249. nInt->playerID = pid;
  250. bool shouldResetInterface = true;
  251. // Client no longer handle this player at all
  252. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), pid))
  253. {
  254. logGlobal->trace("Player %s is not belong to this client. Destroying interface", pid);
  255. }
  256. else if(isHuman && !vstd::contains(CSH->getHumanColors(), pid))
  257. {
  258. logGlobal->trace("Player %s is no longer controlled by human. Destroying interface", pid);
  259. }
  260. else if(!isHuman && vstd::contains(CSH->getHumanColors(), pid))
  261. {
  262. logGlobal->trace("Player %s is no longer controlled by AI. Destroying interface", pid);
  263. }
  264. else
  265. {
  266. installNewPlayerInterface(nInt, pid);
  267. shouldResetInterface = false;
  268. }
  269. // loadGame needs to be called after initGameInterface to load paths correctly
  270. // initGameInterface is called in installNewPlayerInterface
  271. nInt->loadGame(h, version);
  272. if (shouldResetInterface)
  273. {
  274. nInt.reset();
  275. LOCPLINT = prevInt;
  276. }
  277. }
  278. #if SCRIPTING_ENABLED
  279. {
  280. JsonNode scriptsState;
  281. h & scriptsState;
  282. clientScripts->serializeState(h.saving, scriptsState);
  283. }
  284. #endif
  285. logNetwork->trace("Loaded client part of save %d ms", CSH->th->getDiff());
  286. }
  287. void CClient::save(const std::string & fname)
  288. {
  289. if(gs->curB)
  290. {
  291. logNetwork->error("Game cannot be saved during battle!");
  292. return;
  293. }
  294. SaveGame save_game(fname);
  295. sendRequest(&save_game, PlayerColor::NEUTRAL);
  296. }
  297. void CClient::endGame()
  298. {
  299. #if SCRIPTING_ENABLED
  300. clientScripts.reset();
  301. #endif
  302. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  303. for(auto & i : playerint)
  304. i.second->finish();
  305. GH.curInt = nullptr;
  306. {
  307. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  308. logNetwork->info("Ending current game!");
  309. removeGUI();
  310. vstd::clear_pointer(const_cast<CGameInfo *>(CGI)->mh);
  311. vstd::clear_pointer(gs);
  312. logNetwork->info("Deleted mapHandler and gameState.");
  313. }
  314. //threads cleanup has to be after gs cleanup and before battleints cleanup to stop tacticThread
  315. cleanThreads();
  316. CPlayerInterface::battleInt.reset();
  317. playerint.clear();
  318. battleints.clear();
  319. battleCallbacks.clear();
  320. playerEnvironments.clear();
  321. logNetwork->info("Deleted playerInts.");
  322. logNetwork->info("Client stopped.");
  323. }
  324. void CClient::initMapHandler()
  325. {
  326. // TODO: CMapHandler initialization can probably go somewhere else
  327. // It's can't be before initialization of interfaces
  328. // During loading CPlayerInterface from serialized state it's depend on MH
  329. if(!settings["session"]["headless"].Bool())
  330. {
  331. const_cast<CGameInfo *>(CGI)->mh = new CMapHandler(gs->map);
  332. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  333. }
  334. pathCache.clear();
  335. }
  336. void CClient::initPlayerEnvironments()
  337. {
  338. playerEnvironments.clear();
  339. auto allPlayers = CSH->getAllClientPlayers(CSH->c->connectionID);
  340. bool hasHumanPlayer = false;
  341. for(auto & color : allPlayers)
  342. {
  343. logNetwork->info("Preparing environment for player %s", color.getStr());
  344. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  345. if(!hasHumanPlayer && gs->players[color].isHuman())
  346. hasHumanPlayer = true;
  347. }
  348. if(!hasHumanPlayer)
  349. {
  350. Settings session = settings.write["session"];
  351. session["spectate"].Bool() = true;
  352. session["spectate-skip-battle-result"].Bool() = true;
  353. session["spectate-ignore-hero"].Bool() = true;
  354. }
  355. if(settings["session"]["spectate"].Bool())
  356. {
  357. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
  358. }
  359. }
  360. void CClient::initPlayerInterfaces()
  361. {
  362. for(auto & elem : gs->scenarioOps->playerInfos)
  363. {
  364. PlayerColor color = elem.first;
  365. if(!vstd::contains(CSH->getAllClientPlayers(CSH->c->connectionID), color))
  366. continue;
  367. if(!vstd::contains(playerint, color))
  368. {
  369. logNetwork->info("Preparing interface for player %s", color.getStr());
  370. if(elem.second.isControlledByAI())
  371. {
  372. auto AiToGive = aiNameForPlayer(elem.second, false);
  373. logNetwork->info("Player %s will be lead by %s", color.getStr(), AiToGive);
  374. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  375. }
  376. else
  377. {
  378. logNetwork->info("Player %s will be lead by human", color.getStr());
  379. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  380. }
  381. }
  382. }
  383. if(settings["session"]["spectate"].Bool())
  384. {
  385. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  386. }
  387. if(CSH->getAllClientPlayers(CSH->c->connectionID).count(PlayerColor::NEUTRAL))
  388. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  389. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  390. }
  391. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI)
  392. {
  393. if(ps.name.size())
  394. {
  395. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  396. if(boost::filesystem::exists(aiPath))
  397. return ps.name;
  398. }
  399. return aiNameForPlayer(battleAI);
  400. }
  401. std::string CClient::aiNameForPlayer(bool battleAI)
  402. {
  403. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  404. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  405. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  406. //TODO what about human players
  407. if(battleints.size() >= sensibleAILimit)
  408. return badAI;
  409. return goodAI;
  410. }
  411. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  412. {
  413. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  414. playerint[color] = gameInterface;
  415. logGlobal->trace("\tInitializing the interface for player %s", color.getStr());
  416. auto cb = std::make_shared<CCallback>(gs, color, this);
  417. battleCallbacks[color] = cb;
  418. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  419. installNewBattleInterface(gameInterface, color, battlecb);
  420. }
  421. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  422. {
  423. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  424. battleints[color] = battleInterface;
  425. if(needCallback)
  426. {
  427. logGlobal->trace("\tInitializing the battle interface for player %s", color.getStr());
  428. auto cbc = std::make_shared<CBattleCallback>(color, this);
  429. battleCallbacks[color] = cbc;
  430. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  431. }
  432. }
  433. void CClient::handlePack(CPack * pack)
  434. {
  435. CBaseForCLApply * apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
  436. if(apply)
  437. {
  438. boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
  439. apply->applyOnClBefore(this, pack);
  440. logNetwork->trace("\tMade first apply on cl: %s", typeList.getTypeInfo(pack)->name());
  441. gs->apply(pack);
  442. logNetwork->trace("\tApplied on gs: %s", typeList.getTypeInfo(pack)->name());
  443. apply->applyOnClAfter(this, pack);
  444. logNetwork->trace("\tMade second apply on cl: %s", typeList.getTypeInfo(pack)->name());
  445. }
  446. else
  447. {
  448. logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
  449. }
  450. delete pack;
  451. }
  452. int CClient::sendRequest(const CPackForServer * request, PlayerColor player)
  453. {
  454. static ui32 requestCounter = 0;
  455. ui32 requestID = requestCounter++;
  456. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(*request).name(), requestID);
  457. waitingRequest.pushBack(requestID);
  458. request->requestID = requestID;
  459. request->player = player;
  460. CSH->c->sendPack(request);
  461. if(vstd::contains(playerint, player))
  462. playerint[player]->requestSent(request, requestID);
  463. return requestID;
  464. }
  465. void CClient::battleStarted(const BattleInfo * info)
  466. {
  467. setBattle(info);
  468. for(auto & battleCb : battleCallbacks)
  469. {
  470. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  471. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  472. {
  473. battleCb.second->setBattle(info);
  474. }
  475. }
  476. std::shared_ptr<CPlayerInterface> att, def;
  477. auto & leftSide = info->sides[0], & rightSide = info->sides[1];
  478. //If quick combat is not, do not prepare interfaces for battleint
  479. auto callBattleStart = [&](PlayerColor color, ui8 side)
  480. {
  481. if(vstd::contains(battleints, color))
  482. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  483. };
  484. callBattleStart(leftSide.color, 0);
  485. callBattleStart(rightSide.color, 1);
  486. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  487. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  488. callBattleStart(PlayerColor::SPECTATOR, 1);
  489. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  490. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  491. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  492. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  493. //Remove player interfaces for auto battle (quickCombat option)
  494. if(att && att->isAutoFightOn)
  495. {
  496. att.reset();
  497. def.reset();
  498. }
  499. if(!settings["session"]["headless"].Bool())
  500. {
  501. if(!!att || !!def)
  502. {
  503. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  504. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  505. }
  506. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  507. {
  508. //TODO: This certainly need improvement
  509. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  510. spectratorInt->cb->setBattle(info);
  511. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  512. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  513. }
  514. }
  515. if(info->tacticDistance && vstd::contains(battleints, info->sides[info->tacticsSide].color))
  516. {
  517. PlayerColor color = info->sides[info->tacticsSide].color;
  518. playerTacticThreads[color] = std::make_unique<boost::thread>(&CClient::commenceTacticPhaseForInt, this, battleints[color]);
  519. }
  520. }
  521. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  522. {
  523. setThreadName("CClient::commenceTacticPhaseForInt");
  524. try
  525. {
  526. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  527. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  528. {
  529. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID).value()));
  530. sendRequest(&ma, battleInt->playerID);
  531. }
  532. }
  533. catch(...)
  534. {
  535. handleException();
  536. }
  537. }
  538. void CClient::battleFinished()
  539. {
  540. stopAllBattleActions();
  541. for(auto & side : gs->curB->sides)
  542. if(battleCallbacks.count(side.color))
  543. battleCallbacks[side.color]->setBattle(nullptr);
  544. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  545. battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
  546. setBattle(nullptr);
  547. gs->curB.dellNull();
  548. }
  549. void CClient::startPlayerBattleAction(PlayerColor color)
  550. {
  551. stopPlayerBattleAction(color);
  552. if(vstd::contains(battleints, color))
  553. {
  554. auto thread = std::make_shared<boost::thread>(std::bind(&CClient::waitForMoveAndSend, this, color));
  555. playerActionThreads[color] = thread;
  556. }
  557. }
  558. void CClient::stopPlayerBattleAction(PlayerColor color)
  559. {
  560. if(vstd::contains(playerActionThreads, color))
  561. {
  562. auto thread = playerActionThreads.at(color);
  563. if(thread->joinable())
  564. {
  565. thread->interrupt();
  566. thread->join();
  567. }
  568. playerActionThreads.erase(color);
  569. }
  570. }
  571. void CClient::stopAllBattleActions()
  572. {
  573. while(!playerActionThreads.empty())
  574. stopPlayerBattleAction(playerActionThreads.begin()->first);
  575. }
  576. void CClient::waitForMoveAndSend(PlayerColor color)
  577. {
  578. try
  579. {
  580. setThreadName("CClient::waitForMoveAndSend");
  581. assert(vstd::contains(battleints, color));
  582. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  583. if(ba.actionType != EActionType::CANCEL)
  584. {
  585. logNetwork->trace("Send battle action to server: %s", ba.toString());
  586. MakeAction temp_action(ba);
  587. sendRequest(&temp_action, color);
  588. }
  589. }
  590. catch(boost::thread_interrupted &)
  591. {
  592. logNetwork->debug("Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?");
  593. }
  594. catch(...)
  595. {
  596. handleException();
  597. }
  598. }
  599. void CClient::invalidatePaths()
  600. {
  601. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  602. pathCache.clear();
  603. }
  604. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  605. {
  606. assert(h);
  607. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  608. auto iter = pathCache.find(h);
  609. if(iter == std::end(pathCache))
  610. {
  611. std::shared_ptr<CPathsInfo> paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  612. gs->calculatePaths(h, *paths.get());
  613. pathCache[h] = paths;
  614. return paths;
  615. }
  616. else
  617. {
  618. return iter->second;
  619. }
  620. }
  621. PlayerColor CClient::getLocalPlayer() const
  622. {
  623. if(LOCPLINT)
  624. return LOCPLINT->playerID;
  625. return getCurrentPlayer();
  626. }
  627. #if SCRIPTING_ENABLED
  628. scripting::Pool * CClient::getGlobalContextPool() const
  629. {
  630. return clientScripts.get();
  631. }
  632. scripting::Pool * CClient::getContextPool() const
  633. {
  634. return clientScripts.get();
  635. }
  636. #endif
  637. void CClient::reinitScripting()
  638. {
  639. clientEventBus = std::make_unique<events::EventBus>();
  640. #if SCRIPTING_ENABLED
  641. clientScripts.reset(new scripting::PoolImpl(this));
  642. #endif
  643. }
  644. void CClient::removeGUI()
  645. {
  646. // CClient::endGame
  647. GH.curInt = nullptr;
  648. if(GH.windows().topWindow())
  649. GH.windows().topWindow()->deactivate();
  650. adventureInt.reset();
  651. GH.windows().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