Client.cpp 23 KB

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