Client.cpp 22 KB

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