Client.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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 "Global.h"
  12. #include "Client.h"
  13. #include "CGameInfo.h"
  14. #include "CPlayerInterface.h"
  15. #include "PlayerLocalState.h"
  16. #include "CServerHandler.h"
  17. #include "ClientNetPackVisitors.h"
  18. #include "adventureMap/AdventureMapInterface.h"
  19. #include "battle/BattleInterface.h"
  20. #include "gui/CGuiHandler.h"
  21. #include "gui/WindowHandler.h"
  22. #include "mapView/mapHandler.h"
  23. #include "../CCallback.h"
  24. #include "../lib/CConfigHandler.h"
  25. #include "../lib/gameState/CGameState.h"
  26. #include "../lib/CPlayerState.h"
  27. #include "../lib/CThreadHelper.h"
  28. #include "../lib/VCMIDirs.h"
  29. #include "../lib/UnlockGuard.h"
  30. #include "../lib/battle/BattleInfo.h"
  31. #include "../lib/serializer/Connection.h"
  32. #include "../lib/mapping/CMapService.h"
  33. #include "../lib/pathfinder/CGPathNode.h"
  34. #include "../lib/filesystem/Filesystem.h"
  35. #include <memory>
  36. #include <vcmi/events/EventBus.h>
  37. #if SCRIPTING_ENABLED
  38. #include "../lib/ScriptHandler.h"
  39. #endif
  40. #ifdef VCMI_ANDROID
  41. #include "lib/CAndroidVMHelper.h"
  42. #endif
  43. ThreadSafeVector<int> CClient::waitingRequest;
  44. CPlayerEnvironment::CPlayerEnvironment(PlayerColor player_, CClient * cl_, std::shared_ptr<CCallback> mainCallback_)
  45. : player(player_),
  46. cl(cl_),
  47. mainCallback(mainCallback_)
  48. {
  49. }
  50. const Services * CPlayerEnvironment::services() const
  51. {
  52. return VLC;
  53. }
  54. vstd::CLoggerBase * CPlayerEnvironment::logger() const
  55. {
  56. return logGlobal;
  57. }
  58. events::EventBus * CPlayerEnvironment::eventBus() const
  59. {
  60. return cl->eventBus();//always get actual value
  61. }
  62. const CPlayerEnvironment::BattleCb * CPlayerEnvironment::battle(const BattleID & battleID) const
  63. {
  64. return mainCallback->getBattle(battleID).get();
  65. }
  66. const CPlayerEnvironment::GameCb * CPlayerEnvironment::game() const
  67. {
  68. return mainCallback.get();
  69. }
  70. CClient::CClient()
  71. {
  72. waitingRequest.clear();
  73. gs = nullptr;
  74. }
  75. CClient::~CClient() = default;
  76. const Services * CClient::services() const
  77. {
  78. return VLC; //todo: this should be CGI
  79. }
  80. const CClient::BattleCb * CClient::battle(const BattleID & battleID) const
  81. {
  82. return nullptr; //todo?
  83. }
  84. const CClient::GameCb * CClient::game() const
  85. {
  86. return this;
  87. }
  88. vstd::CLoggerBase * CClient::logger() const
  89. {
  90. return logGlobal;
  91. }
  92. events::EventBus * CClient::eventBus() const
  93. {
  94. return clientEventBus.get();
  95. }
  96. void CClient::newGame(CGameState * initializedGameState)
  97. {
  98. CSH->th->update();
  99. CMapService mapService;
  100. assert(initializedGameState);
  101. gs = initializedGameState;
  102. gs->preInit(VLC, this);
  103. logNetwork->trace("\tCreating gamestate: %i", CSH->th->getDiff());
  104. if(!initializedGameState)
  105. {
  106. Load::ProgressAccumulator progressTracking;
  107. gs->init(&mapService, CSH->si.get(), progressTracking, settings["general"]["saveRandomMaps"].Bool());
  108. }
  109. logNetwork->trace("Initializing GameState (together): %d ms", CSH->th->getDiff());
  110. initMapHandler();
  111. reinitScripting();
  112. initPlayerEnvironments();
  113. initPlayerInterfaces();
  114. }
  115. void CClient::loadGame(CGameState * initializedGameState)
  116. {
  117. logNetwork->info("Loading procedure started!");
  118. logNetwork->info("Game state was transferred over network, loading.");
  119. gs = initializedGameState;
  120. gs->preInit(VLC, this);
  121. gs->updateOnLoad(CSH->si.get());
  122. logNetwork->info("Game loaded, initialize interfaces.");
  123. initMapHandler();
  124. reinitScripting();
  125. initPlayerEnvironments();
  126. initPlayerInterfaces();
  127. }
  128. void CClient::save(const std::string & fname)
  129. {
  130. if(!gs->currentBattles.empty())
  131. {
  132. logNetwork->error("Game cannot be saved during battle!");
  133. return;
  134. }
  135. SaveGame save_game(fname);
  136. sendRequest(save_game, PlayerColor::NEUTRAL);
  137. }
  138. void CClient::endNetwork()
  139. {
  140. if (CGI->mh)
  141. CGI->mh->endNetwork();
  142. if (CPlayerInterface::battleInt)
  143. CPlayerInterface::battleInt->endNetwork();
  144. for(auto & i : playerint)
  145. {
  146. auto interface = std::dynamic_pointer_cast<CPlayerInterface>(i.second);
  147. if (interface)
  148. interface->endNetwork();
  149. }
  150. }
  151. void CClient::endGame()
  152. {
  153. #if SCRIPTING_ENABLED
  154. clientScripts.reset();
  155. #endif
  156. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  157. for(auto & i : playerint)
  158. i.second->finish();
  159. GH.curInt = nullptr;
  160. {
  161. logNetwork->info("Ending current game!");
  162. removeGUI();
  163. CGI->mh.reset();
  164. vstd::clear_pointer(gs);
  165. logNetwork->info("Deleted mapHandler and gameState.");
  166. }
  167. CPlayerInterface::battleInt.reset();
  168. playerint.clear();
  169. battleints.clear();
  170. battleCallbacks.clear();
  171. playerEnvironments.clear();
  172. logNetwork->info("Deleted playerInts.");
  173. logNetwork->info("Client stopped.");
  174. }
  175. void CClient::initMapHandler()
  176. {
  177. // TODO: CMapHandler initialization can probably go somewhere else
  178. // It's can't be before initialization of interfaces
  179. // During loading CPlayerInterface from serialized state it's depend on MH
  180. if(!settings["session"]["headless"].Bool())
  181. {
  182. CGI->mh = std::make_shared<CMapHandler>(gs->map);
  183. logNetwork->trace("Creating mapHandler: %d ms", CSH->th->getDiff());
  184. }
  185. pathCache.clear();
  186. }
  187. void CClient::initPlayerEnvironments()
  188. {
  189. playerEnvironments.clear();
  190. auto allPlayers = CSH->getAllClientPlayers(CSH->logicConnection->connectionID);
  191. bool hasHumanPlayer = false;
  192. for(auto & color : allPlayers)
  193. {
  194. logNetwork->info("Preparing environment for player %s", color.toString());
  195. playerEnvironments[color] = std::make_shared<CPlayerEnvironment>(color, this, std::make_shared<CCallback>(gs, color, this));
  196. if(!hasHumanPlayer && gs->players[color].isHuman())
  197. hasHumanPlayer = true;
  198. }
  199. if(!hasHumanPlayer && !settings["session"]["headless"].Bool())
  200. {
  201. Settings session = settings.write["session"];
  202. session["spectate"].Bool() = true;
  203. session["spectate-skip-battle-result"].Bool() = true;
  204. session["spectate-ignore-hero"].Bool() = true;
  205. }
  206. if(settings["session"]["spectate"].Bool())
  207. {
  208. playerEnvironments[PlayerColor::SPECTATOR] = std::make_shared<CPlayerEnvironment>(PlayerColor::SPECTATOR, this, std::make_shared<CCallback>(gs, std::nullopt, this));
  209. }
  210. }
  211. void CClient::initPlayerInterfaces()
  212. {
  213. for(auto & playerInfo : gs->scenarioOps->playerInfos)
  214. {
  215. PlayerColor color = playerInfo.first;
  216. if(!vstd::contains(CSH->getAllClientPlayers(CSH->logicConnection->connectionID), color))
  217. continue;
  218. if(!vstd::contains(playerint, color))
  219. {
  220. logNetwork->info("Preparing interface for player %s", color.toString());
  221. if(playerInfo.second.isControlledByAI() || settings["session"]["onlyai"].Bool())
  222. {
  223. bool alliedToHuman = false;
  224. for(auto & allyInfo : gs->scenarioOps->playerInfos)
  225. if (gs->getPlayerTeam(allyInfo.first) == gs->getPlayerTeam(playerInfo.first) && allyInfo.second.isControlledByHuman())
  226. alliedToHuman = true;
  227. auto AiToGive = aiNameForPlayer(playerInfo.second, false, alliedToHuman);
  228. logNetwork->info("Player %s will be lead by %s", color.toString(), AiToGive);
  229. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  230. }
  231. else
  232. {
  233. logNetwork->info("Player %s will be lead by human", color.toString());
  234. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  235. }
  236. }
  237. }
  238. if(settings["session"]["spectate"].Bool())
  239. {
  240. installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
  241. }
  242. if(CSH->getAllClientPlayers(CSH->logicConnection->connectionID).count(PlayerColor::NEUTRAL))
  243. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  244. logNetwork->trace("Initialized player interfaces %d ms", CSH->th->getDiff());
  245. }
  246. std::string CClient::aiNameForPlayer(const PlayerSettings & ps, bool battleAI, bool alliedToHuman) const
  247. {
  248. if(ps.name.size())
  249. {
  250. const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
  251. if(boost::filesystem::exists(aiPath))
  252. return ps.name;
  253. }
  254. return aiNameForPlayer(battleAI, alliedToHuman);
  255. }
  256. std::string CClient::aiNameForPlayer(bool battleAI, bool alliedToHuman) const
  257. {
  258. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  259. std::string goodAdventureAI = alliedToHuman ? settings["server"]["alliedAI"].String() : settings["server"]["playerAI"].String();
  260. std::string goodBattleAI = settings["server"]["neutralAI"].String();
  261. std::string goodAI = battleAI ? goodBattleAI : goodAdventureAI;
  262. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  263. //TODO what about human players
  264. if(battleints.size() >= sensibleAILimit)
  265. return badAI;
  266. return goodAI;
  267. }
  268. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, PlayerColor color, bool battlecb)
  269. {
  270. playerint[color] = gameInterface;
  271. logGlobal->trace("\tInitializing the interface for player %s", color.toString());
  272. auto cb = std::make_shared<CCallback>(gs, color, this);
  273. battleCallbacks[color] = cb;
  274. gameInterface->initGameInterface(playerEnvironments.at(color), cb);
  275. installNewBattleInterface(gameInterface, color, battlecb);
  276. }
  277. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, PlayerColor color, bool needCallback)
  278. {
  279. battleints[color] = battleInterface;
  280. if(needCallback)
  281. {
  282. logGlobal->trace("\tInitializing the battle interface for player %s", color.toString());
  283. auto cbc = std::make_shared<CBattleCallback>(color, this);
  284. battleCallbacks[color] = cbc;
  285. battleInterface->initBattleInterface(playerEnvironments.at(color), cbc);
  286. }
  287. }
  288. void CClient::handlePack(CPackForClient & pack)
  289. {
  290. ApplyClientNetPackVisitor afterVisitor(*this, *gameState());
  291. ApplyFirstClientNetPackVisitor beforeVisitor(*this, *gameState());
  292. pack.visit(beforeVisitor);
  293. logNetwork->trace("\tMade first apply on cl: %s", typeid(pack).name());
  294. {
  295. boost::unique_lock lock(CGameState::mutex);
  296. gs->apply(pack);
  297. }
  298. logNetwork->trace("\tApplied on gs: %s", typeid(pack).name());
  299. pack.visit(afterVisitor);
  300. logNetwork->trace("\tMade second apply on cl: %s", typeid(pack).name());
  301. }
  302. int CClient::sendRequest(const CPackForServer & request, PlayerColor player)
  303. {
  304. static ui32 requestCounter = 1;
  305. ui32 requestID = requestCounter++;
  306. logNetwork->trace("Sending a request \"%s\". It'll have an ID=%d.", typeid(request).name(), requestID);
  307. waitingRequest.pushBack(requestID);
  308. request.requestID = requestID;
  309. request.player = player;
  310. CSH->logicConnection->sendPack(request);
  311. if(vstd::contains(playerint, player))
  312. playerint[player]->requestSent(&request, requestID);
  313. return requestID;
  314. }
  315. void CClient::battleStarted(const BattleInfo * info)
  316. {
  317. std::shared_ptr<CPlayerInterface> att;
  318. std::shared_ptr<CPlayerInterface> def;
  319. const auto & leftSide = info->getSide(BattleSide::LEFT_SIDE);
  320. const auto & rightSide = info->getSide(BattleSide::RIGHT_SIDE);
  321. for(auto & battleCb : battleCallbacks)
  322. {
  323. if(!battleCb.first.isValidPlayer() || battleCb.first == leftSide.color || battleCb.first == rightSide.color)
  324. battleCb.second->onBattleStarted(info);
  325. }
  326. //If quick combat is not, do not prepare interfaces for battleint
  327. auto callBattleStart = [&](PlayerColor color, BattleSide side)
  328. {
  329. if(vstd::contains(battleints, color))
  330. battleints[color]->battleStart(info->battleID, leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side, info->replayAllowed);
  331. };
  332. callBattleStart(leftSide.color, BattleSide::LEFT_SIDE);
  333. callBattleStart(rightSide.color, BattleSide::RIGHT_SIDE);
  334. callBattleStart(PlayerColor::UNFLAGGABLE, BattleSide::RIGHT_SIDE);
  335. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  336. callBattleStart(PlayerColor::SPECTATOR, BattleSide::RIGHT_SIDE);
  337. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  338. att = std::dynamic_pointer_cast<CPlayerInterface>(playerint[leftSide.color]);
  339. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  340. def = std::dynamic_pointer_cast<CPlayerInterface>(playerint[rightSide.color]);
  341. //Remove player interfaces for auto battle (quickCombat option)
  342. if((att && att->isAutoFightOn) || (def && def->isAutoFightOn))
  343. {
  344. auto endTacticPhaseIfEligible = [info](const CPlayerInterface * interface)
  345. {
  346. if (interface->cb->getBattle(info->battleID)->battleGetTacticDist())
  347. {
  348. auto side = interface->cb->getBattle(info->battleID)->playerToSide(interface->playerID);
  349. if(interface->playerID == info->getSide(info->tacticsSide).color)
  350. {
  351. auto action = BattleAction::makeEndOFTacticPhase(side);
  352. interface->cb->battleMakeTacticAction(info->battleID, action);
  353. }
  354. }
  355. };
  356. if(att && att->isAutoFightOn)
  357. endTacticPhaseIfEligible(att.get());
  358. else // def && def->isAutoFightOn
  359. endTacticPhaseIfEligible(def.get());
  360. att.reset();
  361. def.reset();
  362. }
  363. if(!settings["session"]["headless"].Bool())
  364. {
  365. if(att || def)
  366. {
  367. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def);
  368. }
  369. else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  370. {
  371. //TODO: This certainly need improvement
  372. auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
  373. spectratorInt->cb->onBattleStarted(info);
  374. CPlayerInterface::battleInt = std::make_shared<BattleInterface>(info->getBattleID(), leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero, att, def, spectratorInt);
  375. }
  376. }
  377. if(info->tacticDistance)
  378. {
  379. auto tacticianColor = info->getSide(info->tacticsSide).color;
  380. if (vstd::contains(battleints, tacticianColor))
  381. battleints[tacticianColor]->yourTacticPhase(info->battleID, info->tacticDistance);
  382. }
  383. }
  384. void CClient::battleFinished(const BattleID & battleID)
  385. {
  386. for(auto side : { BattleSide::ATTACKER, BattleSide::DEFENDER })
  387. {
  388. if(battleCallbacks.count(gs->getBattle(battleID)->getSide(side).color))
  389. battleCallbacks[gs->getBattle(battleID)->getSide(side).color]->onBattleEnded(battleID);
  390. }
  391. if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
  392. battleCallbacks[PlayerColor::SPECTATOR]->onBattleEnded(battleID);
  393. }
  394. void CClient::startPlayerBattleAction(const BattleID & battleID, PlayerColor color)
  395. {
  396. if (battleints.count(color) == 0)
  397. return; // not our combat in MP
  398. auto battleint = battleints.at(color);
  399. if (!battleint->human)
  400. {
  401. // we want to avoid locking gamestate and causing UI to freeze while AI is making turn
  402. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  403. battleint->activeStack(battleID, gs->getBattle(battleID)->battleGetStackByID(gs->getBattle(battleID)->activeStack, false));
  404. }
  405. else
  406. {
  407. battleint->activeStack(battleID, gs->getBattle(battleID)->battleGetStackByID(gs->getBattle(battleID)->activeStack, false));
  408. }
  409. }
  410. void CClient::updatePath(const ObjectInstanceID & id)
  411. {
  412. invalidatePaths();
  413. auto hero = getHero(id);
  414. updatePath(hero);
  415. }
  416. void CClient::updatePath(const CGHeroInstance * hero)
  417. {
  418. if(LOCPLINT && hero)
  419. LOCPLINT->localState->verifyPath(hero);
  420. }
  421. void CClient::invalidatePaths()
  422. {
  423. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  424. pathCache.clear();
  425. }
  426. vstd::RNG & CClient::getRandomGenerator()
  427. {
  428. // Client should use CRandomGenerator::getDefault() for UI logic
  429. // Gamestate should never call this method on client!
  430. throw std::runtime_error("Illegal access to random number generator from client code!");
  431. }
  432. std::shared_ptr<const CPathsInfo> CClient::getPathsInfo(const CGHeroInstance * h)
  433. {
  434. assert(h);
  435. boost::unique_lock<boost::mutex> pathLock(pathCacheMutex);
  436. auto iter = pathCache.find(h);
  437. if(iter == std::end(pathCache))
  438. {
  439. auto paths = std::make_shared<CPathsInfo>(getMapSize(), h);
  440. gs->calculatePaths(h, *paths.get());
  441. pathCache[h] = paths;
  442. return paths;
  443. }
  444. else
  445. {
  446. return iter->second;
  447. }
  448. }
  449. #if SCRIPTING_ENABLED
  450. scripting::Pool * CClient::getGlobalContextPool() const
  451. {
  452. return clientScripts.get();
  453. }
  454. #endif
  455. void CClient::reinitScripting()
  456. {
  457. clientEventBus = std::make_unique<events::EventBus>();
  458. #if SCRIPTING_ENABLED
  459. clientScripts.reset(new scripting::PoolImpl(this));
  460. #endif
  461. }
  462. void CClient::removeGUI() const
  463. {
  464. // CClient::endGame
  465. GH.curInt = nullptr;
  466. GH.windows().clear();
  467. adventureInt.reset();
  468. logGlobal->info("Removed GUI.");
  469. LOCPLINT = nullptr;
  470. }
  471. #ifdef VCMI_ANDROID
  472. extern "C" JNIEXPORT jboolean JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jclass cls)
  473. {
  474. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  475. logGlobal->info("Received emergency save game request");
  476. if(!LOCPLINT || !LOCPLINT->cb)
  477. {
  478. logGlobal->info("... but no active player interface found!");
  479. return false;
  480. }
  481. if (!CSH || !CSH->logicConnection)
  482. {
  483. logGlobal->info("... but no active connection found!");
  484. return false;
  485. }
  486. LOCPLINT->cb->save("Saves/_Android_Autosave");
  487. return true;
  488. }
  489. #endif