Client.cpp 22 KB

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