Client.cpp 17 KB

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