CPlayerInterface.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  1. /*
  2. * CPlayerInterface.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 "CPlayerInterface.h"
  12. #include <vcmi/Artifact.h>
  13. #include "CGameInfo.h"
  14. #include "CServerHandler.h"
  15. #include "HeroMovementController.h"
  16. #include "PlayerLocalState.h"
  17. #include "adventureMap/AdventureMapInterface.h"
  18. #include "adventureMap/CInGameConsole.h"
  19. #include "adventureMap/CList.h"
  20. #include "battle/BattleEffectsController.h"
  21. #include "battle/BattleFieldController.h"
  22. #include "battle/BattleInterface.h"
  23. #include "battle/BattleInterfaceClasses.h"
  24. #include "battle/BattleWindow.h"
  25. #include "eventsSDL/InputHandler.h"
  26. #include "eventsSDL/NotificationHandler.h"
  27. #include "gui/CGuiHandler.h"
  28. #include "gui/CursorHandler.h"
  29. #include "gui/WindowHandler.h"
  30. #include "mainmenu/CMainMenu.h"
  31. #include "mainmenu/CHighScoreScreen.h"
  32. #include "mapView/mapHandler.h"
  33. #include "media/IMusicPlayer.h"
  34. #include "media/ISoundPlayer.h"
  35. #include "render/CAnimation.h"
  36. #include "render/IImage.h"
  37. #include "render/IRenderHandler.h"
  38. #include "widgets/Buttons.h"
  39. #include "widgets/CComponent.h"
  40. #include "widgets/CGarrisonInt.h"
  41. #include "windows/CCastleInterface.h"
  42. #include "windows/CCreatureWindow.h"
  43. #include "windows/CExchangeWindow.h"
  44. #include "windows/CHeroWindow.h"
  45. #include "windows/CKingdomInterface.h"
  46. #include "windows/CMarketWindow.h"
  47. #include "windows/CPuzzleWindow.h"
  48. #include "windows/CQuestLog.h"
  49. #include "windows/CSpellWindow.h"
  50. #include "windows/CTutorialWindow.h"
  51. #include "windows/GUIClasses.h"
  52. #include "windows/InfoWindows.h"
  53. #include "../CCallback.h"
  54. #include "../lib/CConfigHandler.h"
  55. #include "../lib/texts/CGeneralTextHandler.h"
  56. #include "../lib/CPlayerState.h"
  57. #include "../lib/CRandomGenerator.h"
  58. #include "../lib/CStack.h"
  59. #include "../lib/CStopWatch.h"
  60. #include "../lib/CThreadHelper.h"
  61. #include "../lib/GameConstants.h"
  62. #include "../lib/RoadHandler.h"
  63. #include "../lib/StartInfo.h"
  64. #include "../lib/TerrainHandler.h"
  65. #include "../lib/UnlockGuard.h"
  66. #include "../lib/VCMIDirs.h"
  67. #include "../lib/bonuses/Limiters.h"
  68. #include "../lib/bonuses/Propagators.h"
  69. #include "../lib/bonuses/Updaters.h"
  70. #include "../lib/gameState/CGameState.h"
  71. #include "../lib/mapObjects/CGMarket.h"
  72. #include "../lib/mapObjects/CGTownInstance.h"
  73. #include "../lib/mapObjects/MiscObjects.h"
  74. #include "../lib/mapObjects/ObjectTemplate.h"
  75. #include "../lib/mapping/CMapHeader.h"
  76. #include "../lib/networkPacks/PacksForClient.h"
  77. #include "../lib/networkPacks/PacksForClientBattle.h"
  78. #include "../lib/networkPacks/PacksForServer.h"
  79. #include "../lib/pathfinder/CGPathNode.h"
  80. #include "../lib/pathfinder/PathfinderCache.h"
  81. #include "../lib/pathfinder/PathfinderOptions.h"
  82. #include "../lib/serializer/CTypeList.h"
  83. #include "../lib/serializer/ESerializationVersion.h"
  84. #include "../lib/spells/CSpellHandler.h"
  85. #include "../lib/texts/TextOperations.h"
  86. // The macro below is used to mark functions that are called by client when game state changes.
  87. // They all assume that interface mutex is locked.
  88. #define EVENT_HANDLER_CALLED_BY_CLIENT
  89. #define BATTLE_EVENT_POSSIBLE_RETURN if (LOCPLINT != this) return; if (isAutoFightOn && !battleInt) return
  90. CPlayerInterface * LOCPLINT;
  91. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  92. struct HeroObjectRetriever
  93. {
  94. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  95. {
  96. return h;
  97. }
  98. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  99. {
  100. return nullptr;
  101. }
  102. };
  103. CPlayerInterface::CPlayerInterface(PlayerColor Player):
  104. localState(std::make_unique<PlayerLocalState>(*this)),
  105. movementController(std::make_unique<HeroMovementController>()),
  106. artifactController(std::make_unique<ArtifactsUIController>())
  107. {
  108. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.toString());
  109. LOCPLINT = this;
  110. playerID=Player;
  111. human=true;
  112. battleInt.reset();
  113. castleInt = nullptr;
  114. makingTurn = false;
  115. showingDialog = new ConditionalWait();
  116. cingconsole = new CInGameConsole();
  117. autosaveCount = 0;
  118. isAutoFightOn = false;
  119. isAutoFightEndBattle = false;
  120. ignoreEvents = false;
  121. }
  122. CPlayerInterface::~CPlayerInterface()
  123. {
  124. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.toString());
  125. delete showingDialog;
  126. delete cingconsole;
  127. if (LOCPLINT == this)
  128. LOCPLINT = nullptr;
  129. }
  130. void CPlayerInterface::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  131. {
  132. cb = CB;
  133. env = ENV;
  134. CCS->musich->loadTerrainMusicThemes();
  135. initializeHeroTownList();
  136. pathfinderCache = std::make_unique<PathfinderCache>(cb.get(), PathfinderOptions(cb.get()));
  137. adventureInt.reset(new AdventureMapInterface());
  138. }
  139. std::shared_ptr<const CPathsInfo> CPlayerInterface::getPathsInfo(const CGHeroInstance * h)
  140. {
  141. return pathfinderCache->getPathsInfo(h);
  142. }
  143. void CPlayerInterface::invalidatePaths()
  144. {
  145. pathfinderCache->invalidatePaths();
  146. }
  147. void CPlayerInterface::closeAllDialogs()
  148. {
  149. // remove all active dialogs that do not expect query answer
  150. while(true)
  151. {
  152. auto adventureWindow = GH.windows().topWindow<AdventureMapInterface>();
  153. auto infoWindow = GH.windows().topWindow<CInfoWindow>();
  154. auto topWindow = GH.windows().topWindow<WindowBase>();
  155. if(adventureWindow != nullptr)
  156. break;
  157. if(infoWindow && infoWindow->ID != QueryID::NONE)
  158. break;
  159. if (topWindow == nullptr)
  160. throw std::runtime_error("Invalid or non-existing top window! Total windows: " + std::to_string(GH.windows().count()));
  161. topWindow->close();
  162. }
  163. }
  164. void CPlayerInterface::playerEndsTurn(PlayerColor player)
  165. {
  166. EVENT_HANDLER_CALLED_BY_CLIENT;
  167. if (player == playerID)
  168. {
  169. makingTurn = false;
  170. closeAllDialogs();
  171. // remove all pending dialogs that do not expect query answer
  172. vstd::erase_if(dialogs, [](const std::shared_ptr<CInfoWindow> & window){
  173. return window->ID == QueryID::NONE;
  174. });
  175. }
  176. }
  177. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  178. {
  179. if(GH.windows().findWindows<AdventureMapInterface>().empty())
  180. {
  181. // after map load - remove all active windows and replace them with adventure map
  182. GH.windows().clear();
  183. GH.windows().pushWindow(adventureInt);
  184. }
  185. EVENT_HANDLER_CALLED_BY_CLIENT;
  186. if (player != playerID && LOCPLINT == this)
  187. {
  188. waitWhileDialog();
  189. bool isHuman = cb->getStartInfo()->playerInfos.count(player) && cb->getStartInfo()->playerInfos.at(player).isControlledByHuman();
  190. if (makingTurn == false)
  191. adventureInt->onEnemyTurnStarted(player, isHuman);
  192. }
  193. }
  194. void CPlayerInterface::performAutosave()
  195. {
  196. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  197. if(frequency > 0 && cb->getDate() % frequency == 0)
  198. {
  199. bool usePrefix = settings["general"]["useSavePrefix"].Bool();
  200. std::string prefix = std::string();
  201. if(usePrefix)
  202. {
  203. prefix = settings["general"]["savePrefix"].String();
  204. if(prefix.empty())
  205. {
  206. std::string name = cb->getMapHeader()->name.toString();
  207. int txtlen = TextOperations::getUnicodeCharactersCount(name);
  208. TextOperations::trimRightUnicode(name, std::max(0, txtlen - 14));
  209. auto const & isSymbolIllegal = [&](char c) {
  210. static const std::string forbiddenChars("\\/:*?\"<>| ");
  211. bool charForbidden = forbiddenChars.find(c) != std::string::npos;
  212. bool charNonprintable = static_cast<unsigned char>(c) < static_cast<unsigned char>(' ');
  213. return charForbidden || charNonprintable;
  214. };
  215. std::replace_if(name.begin(), name.end(), isSymbolIllegal, '_' );
  216. prefix = vstd::getFormattedDateTime(cb->getStartInfo()->startTime, "%Y-%m-%d_%H-%M") + "_" + name + "/";
  217. }
  218. }
  219. autosaveCount++;
  220. int autosaveCountLimit = settings["general"]["autosaveCountLimit"].Integer();
  221. if(autosaveCountLimit > 0)
  222. {
  223. cb->save("Saves/Autosave/" + prefix + std::to_string(autosaveCount));
  224. autosaveCount %= autosaveCountLimit;
  225. }
  226. else
  227. {
  228. std::string stringifiedDate = std::to_string(cb->getDate(Date::MONTH))
  229. + std::to_string(cb->getDate(Date::WEEK))
  230. + std::to_string(cb->getDate(Date::DAY_OF_WEEK));
  231. cb->save("Saves/Autosave/" + prefix + stringifiedDate);
  232. }
  233. }
  234. }
  235. void CPlayerInterface::gamePause(bool pause)
  236. {
  237. cb->gamePause(pause);
  238. }
  239. void CPlayerInterface::yourTurn(QueryID queryID)
  240. {
  241. closeAllDialogs();
  242. CTutorialWindow::openWindowFirstTime(TutorialMode::TOUCH_ADVENTUREMAP);
  243. EVENT_HANDLER_CALLED_BY_CLIENT;
  244. int humanPlayersCount = 0;
  245. for(const auto & info : cb->getStartInfo()->playerInfos)
  246. if (info.second.isControlledByHuman())
  247. humanPlayersCount++;
  248. bool hotseatWait = humanPlayersCount > 1;
  249. LOCPLINT = this;
  250. GH.curInt = this;
  251. NotificationHandler::notify("Your turn");
  252. if(settings["general"]["startTurnAutosave"].Bool())
  253. {
  254. performAutosave();
  255. }
  256. if (hotseatWait) //hot seat or MP message
  257. {
  258. adventureInt->onHotseatWaitStarted(playerID);
  259. makingTurn = true;
  260. std::string msg = CGI->generaltexth->allTexts[13];
  261. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  262. std::vector<std::shared_ptr<CComponent>> cmp;
  263. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  264. showInfoDialog(msg, cmp);
  265. }
  266. else
  267. {
  268. makingTurn = true;
  269. adventureInt->onPlayerTurnStarted(playerID);
  270. }
  271. acceptTurn(queryID, hotseatWait);
  272. }
  273. void CPlayerInterface::acceptTurn(QueryID queryID, bool hotseatWait)
  274. {
  275. if (settings["session"]["autoSkip"].Bool())
  276. {
  277. while(auto iw = GH.windows().topWindow<CInfoWindow>())
  278. iw->close();
  279. }
  280. if(hotseatWait)
  281. {
  282. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  283. adventureInt->onPlayerTurnStarted(playerID);
  284. }
  285. // warn player if he has no town
  286. if (cb->howManyTowns() == 0)
  287. {
  288. auto playerColor = *cb->getPlayerID();
  289. std::vector<Component> components;
  290. components.emplace_back(ComponentType::FLAG, playerColor);
  291. MetaString text;
  292. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  293. if(optDaysWithoutCastle)
  294. {
  295. auto daysWithoutCastle = optDaysWithoutCastle.value();
  296. if (daysWithoutCastle < 6)
  297. {
  298. text.appendLocalString(EMetaText::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  299. text.replaceName(playerColor);
  300. text.replaceNumber(7 - daysWithoutCastle);
  301. }
  302. else if (daysWithoutCastle == 6)
  303. {
  304. text.appendLocalString(EMetaText::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  305. text.replaceName(playerColor);
  306. }
  307. showInfoDialogAndWait(components, text);
  308. }
  309. else
  310. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  311. }
  312. cb->selectionMade(0, queryID);
  313. movementController->onPlayerTurnStarted();
  314. }
  315. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  316. {
  317. EVENT_HANDLER_CALLED_BY_CLIENT;
  318. waitWhileDialog();
  319. if(LOCPLINT != this)
  320. return;
  321. //FIXME: read once and store
  322. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  323. return;
  324. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  325. if (!hero)
  326. return;
  327. movementController->onTryMoveHero(hero, details);
  328. }
  329. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  330. {
  331. EVENT_HANDLER_CALLED_BY_CLIENT;
  332. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  333. // if hero is not in town garrison
  334. if (vstd::contains(localState->getWanderingHeroes(), hero))
  335. localState->removeWanderingHero(hero);
  336. adventureInt->onHeroChanged(hero);
  337. localState->erasePath(hero);
  338. }
  339. void CPlayerInterface::townRemoved(const CGTownInstance* town)
  340. {
  341. EVENT_HANDLER_CALLED_BY_CLIENT;
  342. if(town->tempOwner == playerID)
  343. {
  344. localState->removeOwnedTown(town);
  345. adventureInt->onTownChanged(town);
  346. }
  347. }
  348. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  349. {
  350. EVENT_HANDLER_CALLED_BY_CLIENT;
  351. if(start && visitedObj)
  352. {
  353. auto visitSound = visitedObj->getVisitSound(CRandomGenerator::getDefault());
  354. if (visitSound)
  355. CCS->soundh->playSound(visitSound.value());
  356. }
  357. }
  358. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  359. {
  360. EVENT_HANDLER_CALLED_BY_CLIENT;
  361. localState->addWanderingHero(hero);
  362. adventureInt->onHeroChanged(hero);
  363. if(castleInt)
  364. CCS->soundh->playSound(soundBase::newBuilding);
  365. }
  366. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  367. {
  368. if(castleInt)
  369. castleInt->close();
  370. castleInt = nullptr;
  371. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  372. GH.windows().pushWindow(newCastleInt);
  373. }
  374. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  375. {
  376. EVENT_HANDLER_CALLED_BY_CLIENT;
  377. if (which == PrimarySkill::EXPERIENCE)
  378. {
  379. for(auto ctw : GH.windows().findWindows<IMarketHolder>())
  380. ctw->updateExperience();
  381. }
  382. else
  383. {
  384. adventureInt->onHeroChanged(hero);
  385. }
  386. }
  387. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  388. {
  389. EVENT_HANDLER_CALLED_BY_CLIENT;
  390. for (auto cuw : GH.windows().findWindows<IMarketHolder>())
  391. cuw->updateSecondarySkills();
  392. localState->verifyPath(hero);
  393. }
  394. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  395. {
  396. EVENT_HANDLER_CALLED_BY_CLIENT;
  397. adventureInt->onHeroChanged(hero);
  398. if (makingTurn && hero->tempOwner == playerID)
  399. adventureInt->onHeroChanged(hero);
  400. }
  401. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  402. {
  403. EVENT_HANDLER_CALLED_BY_CLIENT;
  404. if (makingTurn && hero->tempOwner == playerID)
  405. adventureInt->onHeroChanged(hero);
  406. }
  407. void CPlayerInterface::receivedResource()
  408. {
  409. EVENT_HANDLER_CALLED_BY_CLIENT;
  410. for (auto mw : GH.windows().findWindows<IMarketHolder>())
  411. mw->updateResources();
  412. GH.windows().totalRedraw();
  413. }
  414. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  415. {
  416. EVENT_HANDLER_CALLED_BY_CLIENT;
  417. waitWhileDialog();
  418. CCS->soundh->playSound(soundBase::heroNewLevel);
  419. GH.windows().createAndPushWindow<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  420. {
  421. cb->selectionMade(selection, queryID);
  422. });
  423. }
  424. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  425. {
  426. EVENT_HANDLER_CALLED_BY_CLIENT;
  427. waitWhileDialog();
  428. CCS->soundh->playSound(soundBase::heroNewLevel);
  429. GH.windows().createAndPushWindow<CStackWindow>(commander, skills, [=](ui32 selection)
  430. {
  431. cb->selectionMade(selection, queryID);
  432. });
  433. }
  434. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  435. {
  436. EVENT_HANDLER_CALLED_BY_CLIENT;
  437. if(town->garrisonHero) //wandering hero moved to the garrison
  438. {
  439. // This method also gets called on hero recruitment -> garrisoned hero is already in garrison
  440. if(town->garrisonHero->tempOwner == playerID && vstd::contains(localState->getWanderingHeroes(), town->garrisonHero))
  441. localState->removeWanderingHero(town->garrisonHero);
  442. }
  443. if(town->visitingHero) //hero leaves garrison
  444. {
  445. // This method also gets called on hero recruitment -> wandering heroes already contains new hero
  446. if(town->visitingHero->tempOwner == playerID && !vstd::contains(localState->getWanderingHeroes(), town->visitingHero))
  447. localState->addWanderingHero(town->visitingHero);
  448. }
  449. adventureInt->onHeroChanged(nullptr);
  450. adventureInt->onTownChanged(town);
  451. for (auto cgh : GH.windows().findWindows<IGarrisonHolder>())
  452. if (cgh->holdsGarrison(town))
  453. cgh->updateGarrisons();
  454. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  455. ki->townChanged(town);
  456. // Perform totalRedraw to update hero list on adventure map, if any dialogs are open
  457. GH.windows().totalRedraw();
  458. }
  459. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  460. {
  461. EVENT_HANDLER_CALLED_BY_CLIENT;
  462. if (hero->tempOwner != playerID )
  463. return;
  464. waitWhileDialog();
  465. openTownWindow(town);
  466. }
  467. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  468. {
  469. std::vector<const CArmedInstance *> instances;
  470. if(auto obj = dynamic_cast<const CArmedInstance *>(cb->getObjInstance(id1)))
  471. instances.push_back(obj);
  472. if(id2 != ObjectInstanceID() && id2 != id1)
  473. {
  474. if(auto obj = dynamic_cast<const CArmedInstance *>(cb->getObjInstance(id2)))
  475. instances.push_back(obj);
  476. }
  477. garrisonsChanged(instances);
  478. }
  479. void CPlayerInterface::garrisonsChanged(std::vector<const CArmedInstance *> objs)
  480. {
  481. for (auto object : objs)
  482. {
  483. auto * hero = dynamic_cast<const CGHeroInstance*>(object);
  484. auto * town = dynamic_cast<const CGTownInstance*>(object);
  485. if (town)
  486. adventureInt->onTownChanged(town);
  487. if (hero)
  488. {
  489. localState->verifyPath(hero);
  490. adventureInt->onHeroChanged(hero);
  491. if(hero->inTownGarrison && hero->visitedTown != town)
  492. adventureInt->onTownChanged(hero->visitedTown);
  493. }
  494. }
  495. for (auto cgh : GH.windows().findWindows<IGarrisonHolder>())
  496. if (cgh->holdsGarrisons(objs))
  497. cgh->updateGarrisons();
  498. GH.windows().totalRedraw();
  499. }
  500. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  501. {
  502. EVENT_HANDLER_CALLED_BY_CLIENT;
  503. adventureInt->onTownChanged(town);
  504. if (castleInt)
  505. {
  506. castleInt->townlist->updateElement(town);
  507. if (castleInt->town == town)
  508. {
  509. switch(what)
  510. {
  511. case 1:
  512. CCS->soundh->playSound(soundBase::newBuilding);
  513. castleInt->addBuilding(buildingID);
  514. break;
  515. case 2:
  516. castleInt->removeBuilding(buildingID);
  517. break;
  518. }
  519. }
  520. // Perform totalRedraw in order to force redraw of updated town list icon from adventure map
  521. GH.windows().totalRedraw();
  522. }
  523. for (auto cgh : GH.windows().findWindows<ITownHolder>())
  524. cgh->buildChanged();
  525. }
  526. void CPlayerInterface::battleStartBefore(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  527. {
  528. movementController->onBattleStarted();
  529. waitForAllDialogs();
  530. }
  531. void CPlayerInterface::battleStart(const BattleID & battleID, const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, BattleSide side, bool replayAllowed)
  532. {
  533. EVENT_HANDLER_CALLED_BY_CLIENT;
  534. bool useQuickCombat = settings["adventure"]["quickCombat"].Bool();
  535. bool forceQuickCombat = settings["adventure"]["forceQuickCombat"].Bool();
  536. if ((replayAllowed && useQuickCombat) || forceQuickCombat)
  537. {
  538. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  539. AutocombatPreferences autocombatPreferences = AutocombatPreferences();
  540. autocombatPreferences.enableSpellsUsage = settings["battle"]["enableAutocombatSpells"].Bool();
  541. autofightingAI->initBattleInterface(env, cb, autocombatPreferences);
  542. autofightingAI->battleStart(battleID, army1, army2, tile, hero1, hero2, side, false);
  543. isAutoFightOn = true;
  544. cb->registerBattleInterface(autofightingAI);
  545. }
  546. waitForAllDialogs();
  547. BATTLE_EVENT_POSSIBLE_RETURN;
  548. }
  549. void CPlayerInterface::battleUnitsChanged(const BattleID & battleID, const std::vector<UnitChanges> & units)
  550. {
  551. EVENT_HANDLER_CALLED_BY_CLIENT;
  552. BATTLE_EVENT_POSSIBLE_RETURN;
  553. for(auto & info : units)
  554. {
  555. switch(info.operation)
  556. {
  557. case UnitChanges::EOperation::RESET_STATE:
  558. {
  559. const CStack * stack = cb->getBattle(battleID)->battleGetStackByID(info.id );
  560. if(!stack)
  561. {
  562. logGlobal->error("Invalid unit ID %d", info.id);
  563. continue;
  564. }
  565. battleInt->stackReset(stack);
  566. }
  567. break;
  568. case UnitChanges::EOperation::REMOVE:
  569. battleInt->stackRemoved(info.id);
  570. break;
  571. case UnitChanges::EOperation::ADD:
  572. {
  573. const CStack * unit = cb->getBattle(battleID)->battleGetStackByID(info.id);
  574. if(!unit)
  575. {
  576. logGlobal->error("Invalid unit ID %d", info.id);
  577. continue;
  578. }
  579. battleInt->stackAdded(unit);
  580. }
  581. break;
  582. default:
  583. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  584. break;
  585. }
  586. }
  587. }
  588. void CPlayerInterface::battleObstaclesChanged(const BattleID & battleID, const std::vector<ObstacleChanges> & obstacles)
  589. {
  590. EVENT_HANDLER_CALLED_BY_CLIENT;
  591. BATTLE_EVENT_POSSIBLE_RETURN;
  592. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  593. std::vector<ObstacleChanges> removedObstacles;
  594. for(auto & change : obstacles)
  595. {
  596. if(change.operation == BattleChanges::EOperation::ADD)
  597. {
  598. auto instance = cb->getBattle(battleID)->battleGetObstacleByID(change.id);
  599. if(instance)
  600. newObstacles.push_back(instance);
  601. else
  602. logNetwork->error("Invalid obstacle instance %d", change.id);
  603. }
  604. if(change.operation == BattleChanges::EOperation::REMOVE)
  605. removedObstacles.push_back(change); //Obstacles are already removed, so, show animation based on json struct
  606. }
  607. if (!newObstacles.empty())
  608. battleInt->obstaclePlaced(newObstacles);
  609. if (!removedObstacles.empty())
  610. battleInt->obstacleRemoved(removedObstacles);
  611. battleInt->fieldController->redrawBackgroundWithHexes();
  612. }
  613. void CPlayerInterface::battleCatapultAttacked(const BattleID & battleID, const CatapultAttack & ca)
  614. {
  615. EVENT_HANDLER_CALLED_BY_CLIENT;
  616. BATTLE_EVENT_POSSIBLE_RETURN;
  617. battleInt->stackIsCatapulting(ca);
  618. }
  619. void CPlayerInterface::battleNewRound(const BattleID & battleID) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  620. {
  621. EVENT_HANDLER_CALLED_BY_CLIENT;
  622. BATTLE_EVENT_POSSIBLE_RETURN;
  623. battleInt->newRound();
  624. }
  625. void CPlayerInterface::actionStarted(const BattleID & battleID, const BattleAction &action)
  626. {
  627. EVENT_HANDLER_CALLED_BY_CLIENT;
  628. BATTLE_EVENT_POSSIBLE_RETURN;
  629. battleInt->startAction(action);
  630. }
  631. void CPlayerInterface::actionFinished(const BattleID & battleID, const BattleAction &action)
  632. {
  633. EVENT_HANDLER_CALLED_BY_CLIENT;
  634. BATTLE_EVENT_POSSIBLE_RETURN;
  635. battleInt->endAction(action);
  636. }
  637. void CPlayerInterface::activeStack(const BattleID & battleID, const CStack * stack) //called when it's turn of that stack
  638. {
  639. EVENT_HANDLER_CALLED_BY_CLIENT;
  640. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  641. assert(!cb->getBattle(battleID)->battleIsFinished());
  642. if (cb->getBattle(battleID)->battleIsFinished())
  643. {
  644. logGlobal->error("Received CPlayerInterface::activeStack after battle is finished!");
  645. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  646. return ;
  647. }
  648. if (autofightingAI)
  649. {
  650. if (isAutoFightOn)
  651. {
  652. //FIXME: we want client rendering to proceed while AI is making actions
  653. // so unlock mutex while AI is busy since this might take quite a while, especially if hero has many spells
  654. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  655. autofightingAI->activeStack(battleID, stack);
  656. return;
  657. }
  658. cb->unregisterBattleInterface(autofightingAI);
  659. autofightingAI.reset();
  660. }
  661. assert(battleInt);
  662. if(!battleInt)
  663. {
  664. // probably battle is finished already
  665. cb->battleMakeUnitAction(battleID, BattleAction::makeDefend(stack));
  666. }
  667. battleInt->stackActivated(stack);
  668. }
  669. void CPlayerInterface::battleEnd(const BattleID & battleID, const BattleResult *br, QueryID queryID)
  670. {
  671. EVENT_HANDLER_CALLED_BY_CLIENT;
  672. if(isAutoFightOn || autofightingAI)
  673. {
  674. isAutoFightOn = false;
  675. cb->unregisterBattleInterface(autofightingAI);
  676. autofightingAI.reset();
  677. if(!battleInt)
  678. {
  679. bool allowManualReplay = queryID != QueryID::NONE && !isAutoFightEndBattle;
  680. auto wnd = std::make_shared<BattleResultWindow>(*br, *this, allowManualReplay);
  681. if (allowManualReplay || isAutoFightEndBattle)
  682. {
  683. wnd->resultCallback = [=](ui32 selection)
  684. {
  685. cb->selectionMade(selection, queryID);
  686. };
  687. }
  688. isAutoFightEndBattle = false;
  689. GH.windows().pushWindow(wnd);
  690. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  691. // Otherwise NewTurn causes freeze.
  692. waitWhileDialog();
  693. return;
  694. }
  695. }
  696. BATTLE_EVENT_POSSIBLE_RETURN;
  697. battleInt->battleFinished(*br, queryID);
  698. }
  699. void CPlayerInterface::battleLogMessage(const BattleID & battleID, const std::vector<MetaString> & lines)
  700. {
  701. EVENT_HANDLER_CALLED_BY_CLIENT;
  702. BATTLE_EVENT_POSSIBLE_RETURN;
  703. battleInt->displayBattleLog(lines);
  704. }
  705. void CPlayerInterface::battleStackMoved(const BattleID & battleID, const CStack * stack, const BattleHexArray & dest, int distance, bool teleport)
  706. {
  707. EVENT_HANDLER_CALLED_BY_CLIENT;
  708. BATTLE_EVENT_POSSIBLE_RETURN;
  709. battleInt->stackMoved(stack, dest, distance, teleport);
  710. }
  711. void CPlayerInterface::battleSpellCast(const BattleID & battleID, const BattleSpellCast * sc)
  712. {
  713. EVENT_HANDLER_CALLED_BY_CLIENT;
  714. BATTLE_EVENT_POSSIBLE_RETURN;
  715. battleInt->spellCast(sc);
  716. }
  717. void CPlayerInterface::battleStacksEffectsSet(const BattleID & battleID, const SetStackEffect & sse)
  718. {
  719. EVENT_HANDLER_CALLED_BY_CLIENT;
  720. BATTLE_EVENT_POSSIBLE_RETURN;
  721. battleInt->battleStacksEffectsSet(sse);
  722. }
  723. void CPlayerInterface::battleTriggerEffect(const BattleID & battleID, const BattleTriggerEffect & bte)
  724. {
  725. EVENT_HANDLER_CALLED_BY_CLIENT;
  726. BATTLE_EVENT_POSSIBLE_RETURN;
  727. battleInt->effectsController->battleTriggerEffect(bte);
  728. if(bte.effect == vstd::to_underlying(BonusType::MANA_DRAIN))
  729. {
  730. const CGHeroInstance * manaDrainedHero = LOCPLINT->cb->getHero(ObjectInstanceID(bte.additionalInfo));
  731. battleInt->windowObject->heroManaPointsChanged(manaDrainedHero);
  732. }
  733. }
  734. void CPlayerInterface::battleStacksAttacked(const BattleID & battleID, const std::vector<BattleStackAttacked> & bsa, bool ranged)
  735. {
  736. EVENT_HANDLER_CALLED_BY_CLIENT;
  737. BATTLE_EVENT_POSSIBLE_RETURN;
  738. std::vector<StackAttackedInfo> arg;
  739. for(auto & elem : bsa)
  740. {
  741. const CStack * defender = cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked, false);
  742. const CStack * attacker = cb->getBattle(battleID)->battleGetStackByID(elem.attackerID, false);
  743. assert(defender);
  744. StackAttackedInfo info;
  745. info.defender = defender;
  746. info.attacker = attacker;
  747. info.damageDealt = elem.damageAmount;
  748. info.amountKilled = elem.killedAmount;
  749. info.spellEffect = SpellID::NONE;
  750. info.indirectAttack = ranged;
  751. info.killed = elem.killed();
  752. info.rebirth = elem.willRebirth();
  753. info.cloneKilled = elem.cloneKilled();
  754. info.fireShield = elem.fireShield();
  755. if (elem.isSpell())
  756. info.spellEffect = elem.spellID;
  757. arg.push_back(info);
  758. }
  759. battleInt->stacksAreAttacked(arg);
  760. }
  761. void CPlayerInterface::battleAttack(const BattleID & battleID, const BattleAttack * ba)
  762. {
  763. EVENT_HANDLER_CALLED_BY_CLIENT;
  764. BATTLE_EVENT_POSSIBLE_RETURN;
  765. StackAttackInfo info;
  766. info.attacker = cb->getBattle(battleID)->battleGetStackByID(ba->stackAttacking);
  767. info.defender = nullptr;
  768. info.indirectAttack = ba->shot();
  769. info.lucky = ba->lucky();
  770. info.unlucky = ba->unlucky();
  771. info.deathBlow = ba->deathBlow();
  772. info.lifeDrain = ba->lifeDrain();
  773. info.tile = ba->tile;
  774. info.spellEffect = SpellID::NONE;
  775. if (ba->spellLike())
  776. info.spellEffect = ba->spellID;
  777. for(auto & elem : ba->bsa)
  778. {
  779. if(!elem.isSecondary())
  780. {
  781. assert(info.defender == nullptr);
  782. info.defender = cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked);
  783. }
  784. else
  785. {
  786. info.secondaryDefender.push_back(cb->getBattle(battleID)->battleGetStackByID(elem.stackAttacked));
  787. }
  788. }
  789. assert(info.defender != nullptr || (info.spellEffect != SpellID::NONE && info.indirectAttack));
  790. assert(info.attacker != nullptr);
  791. battleInt->stackAttacking(info);
  792. }
  793. void CPlayerInterface::battleGateStateChanged(const BattleID & battleID, const EGateState state)
  794. {
  795. EVENT_HANDLER_CALLED_BY_CLIENT;
  796. BATTLE_EVENT_POSSIBLE_RETURN;
  797. battleInt->gateStateChanged(state);
  798. }
  799. void CPlayerInterface::yourTacticPhase(const BattleID & battleID, int distance)
  800. {
  801. EVENT_HANDLER_CALLED_BY_CLIENT;
  802. }
  803. void CPlayerInterface::showInfoDialog(EInfoWindowMode type, const std::string &text, const std::vector<Component> & components, int soundID)
  804. {
  805. EVENT_HANDLER_CALLED_BY_CLIENT;
  806. bool autoTryHover = settings["gameTweaks"]["infoBarPick"].Bool() && type == EInfoWindowMode::AUTO;
  807. auto timer = type == EInfoWindowMode::INFO ? 3000 : 4500; //Implement long info windows like in HD mod
  808. if(autoTryHover || type == EInfoWindowMode::INFO)
  809. {
  810. waitWhileDialog(); //Fix for mantis #98
  811. adventureInt->showInfoBoxMessage(components, text, timer);
  812. // abort movement, if any. Strictly speaking unnecessary, but prevents some edge cases, like movement sound on visiting Magi Hut with "show messages in status window" on
  813. movementController->requestMovementAbort();
  814. if (makingTurn && GH.windows().count() > 0 && LOCPLINT == this)
  815. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  816. return;
  817. }
  818. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  819. {
  820. return;
  821. }
  822. std::vector<Component> vect = components; //I do not know currently how to avoid copy here
  823. do
  824. {
  825. std::vector<Component> sender = {vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8))};
  826. std::vector<std::shared_ptr<CComponent>> intComps;
  827. for (auto & component : sender)
  828. intComps.push_back(std::make_shared<CComponent>(component));
  829. showInfoDialog(text,intComps,soundID);
  830. vect.erase(vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8)));
  831. }
  832. while(!vect.empty());
  833. }
  834. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  835. {
  836. std::vector<std::shared_ptr<CComponent>> intComps;
  837. intComps.push_back(component);
  838. showInfoDialog(text, intComps, soundBase::sound_todo);
  839. }
  840. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  841. {
  842. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  843. waitWhileDialog();
  844. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  845. {
  846. return;
  847. }
  848. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  849. if ((makingTurn || (battleInt && battleInt->curInt && battleInt->curInt.get() == this)) && GH.windows().count() > 0 && LOCPLINT == this)
  850. {
  851. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  852. showingDialog->setBusy();
  853. movementController->requestMovementAbort(); // interrupt movement to show dialog
  854. GH.windows().pushWindow(temp);
  855. }
  856. else
  857. {
  858. dialogs.push_back(temp);
  859. }
  860. }
  861. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  862. {
  863. EVENT_HANDLER_CALLED_BY_CLIENT;
  864. std::string str = text.toString();
  865. showInfoDialog(EInfoWindowMode::MODAL, str, components, 0);
  866. waitWhileDialog();
  867. }
  868. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  869. {
  870. movementController->requestMovementAbort();
  871. LOCPLINT->showingDialog->setBusy();
  872. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  873. }
  874. void CPlayerInterface::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
  875. {
  876. EVENT_HANDLER_CALLED_BY_CLIENT;
  877. waitWhileDialog();
  878. movementController->requestMovementAbort();
  879. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  880. if (!selection && cancel) //simple yes/no dialog
  881. {
  882. if(settings["general"]["enableUiEnhancements"].Bool() && safeToAutoaccept)
  883. {
  884. cb->selectionMade(1, askID); //as in HD mod, we try to skip dialogs that server considers visual fluff which does not affect gamestate
  885. return;
  886. }
  887. std::vector<std::shared_ptr<CComponent>> intComps;
  888. for (auto & component : components)
  889. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  890. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  891. }
  892. else if (selection)
  893. {
  894. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  895. for (auto & component : components)
  896. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  897. std::vector<std::pair<AnimationPath,CFunctionList<void()> > > pom;
  898. pom.push_back({ AnimationPath::builtin("IOKAY.DEF"),0});
  899. if (cancel)
  900. {
  901. pom.push_back({AnimationPath::builtin("ICANCEL.DEF"),0});
  902. }
  903. int charperline = 35;
  904. if (pom.size() > 1)
  905. charperline = 50;
  906. GH.windows().createAndPushWindow<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  907. intComps[0]->clickPressed(GH.getCursorPosition());
  908. intComps[0]->clickReleased(GH.getCursorPosition());
  909. }
  910. }
  911. void CPlayerInterface::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  912. {
  913. EVENT_HANDLER_CALLED_BY_CLIENT;
  914. movementController->showTeleportDialog(hero, channel, exits, impassable, askID);
  915. }
  916. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  917. {
  918. EVENT_HANDLER_CALLED_BY_CLIENT;
  919. std::vector<ObjectInstanceID> objectGuiOrdered = objects;
  920. std::map<ObjectInstanceID, int> townOrder;
  921. auto ownedTowns = localState->getOwnedTowns();
  922. for (int i = 0; i < ownedTowns.size(); ++i)
  923. townOrder[ownedTowns[i]->id] = i;
  924. auto townComparator = [&townOrder](const ObjectInstanceID & left, const ObjectInstanceID & right){
  925. uint32_t leftIndex= townOrder.count(left) ? townOrder.at(left) : std::numeric_limits<uint32_t>::max();
  926. uint32_t rightIndex = townOrder.count(right) ? townOrder.at(right) : std::numeric_limits<uint32_t>::max();
  927. return leftIndex < rightIndex;
  928. };
  929. std::stable_sort(objectGuiOrdered.begin(), objectGuiOrdered.end(), townComparator);
  930. auto selectCallback = [=](int selection)
  931. {
  932. cb->sendQueryReply(selection, askID);
  933. };
  934. auto cancelCallback = [=]()
  935. {
  936. cb->sendQueryReply(std::nullopt, askID);
  937. };
  938. const std::string localTitle = title.toString();
  939. const std::string localDescription = description.toString();
  940. std::vector<int> tempList;
  941. tempList.reserve(objectGuiOrdered.size());
  942. for(const auto & item : objectGuiOrdered)
  943. tempList.push_back(item.getNum());
  944. CComponent localIconC(icon);
  945. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  946. localIconC.removeChild(localIcon.get(), false);
  947. std::vector<std::shared_ptr<IImage>> images;
  948. for(const auto & obj : objectGuiOrdered)
  949. {
  950. if(!settings["general"]["enableUiEnhancements"].Bool())
  951. break;
  952. const CGTownInstance * t = dynamic_cast<const CGTownInstance *>(cb->getObj(obj));
  953. if(t)
  954. {
  955. auto image = GH.renderHandler().loadImage(AnimationPath::builtin("ITPA"), t->getTown()->clientInfo.icons[t->hasFort()][false] + 2, 0, EImageBlitMode::OPAQUE);
  956. image->scaleTo(Point(35, 23));
  957. images.push_back(image);
  958. }
  959. }
  960. auto wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback, 0, images);
  961. wnd->onExit = cancelCallback;
  962. wnd->onPopup = [this, objectGuiOrdered](int index) { CRClickPopup::createAndPush(cb->getObj(objectGuiOrdered[index]), GH.getCursorPosition()); };
  963. wnd->onClicked = [this, objectGuiOrdered](int index) { adventureInt->centerOnObject(cb->getObj(objectGuiOrdered[index])); GH.windows().totalRedraw(); };
  964. GH.windows().pushWindow(wnd);
  965. }
  966. void CPlayerInterface::tileRevealed(const std::unordered_set<int3> &pos)
  967. {
  968. EVENT_HANDLER_CALLED_BY_CLIENT;
  969. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  970. adventureInt->onMapTilesChanged(pos);
  971. }
  972. void CPlayerInterface::tileHidden(const std::unordered_set<int3> &pos)
  973. {
  974. EVENT_HANDLER_CALLED_BY_CLIENT;
  975. adventureInt->onMapTilesChanged(pos);
  976. }
  977. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  978. {
  979. GH.windows().createAndPushWindow<CHeroWindow>(hero);
  980. }
  981. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  982. {
  983. EVENT_HANDLER_CALLED_BY_CLIENT;
  984. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  985. {
  986. for (auto fortScreen : GH.windows().findWindows<CFortScreen>())
  987. fortScreen->creaturesChangedEventHandler();
  988. for (auto castleInterface : GH.windows().findWindows<CCastleInterface>())
  989. if(castleInterface->town == town)
  990. castleInterface->creaturesChangedEventHandler();
  991. if (townObj)
  992. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  993. ki->townChanged(townObj);
  994. }
  995. else if(town && GH.windows().count() > 0 && (town->ID == Obj::CREATURE_GENERATOR1
  996. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  997. {
  998. for (auto crw : GH.windows().findWindows<CRecruitmentWindow>())
  999. if (crw->dwelling == town)
  1000. crw->availableCreaturesChanged();
  1001. }
  1002. }
  1003. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1004. {
  1005. EVENT_HANDLER_CALLED_BY_CLIENT;
  1006. if (bonus.type == BonusType::NONE)
  1007. return;
  1008. adventureInt->onHeroChanged(hero);
  1009. if ((bonus.type == BonusType::FLYING_MOVEMENT || bonus.type == BonusType::WATER_WALKING) && !gain)
  1010. {
  1011. //recalculate paths because hero has lost bonus influencing pathfinding
  1012. localState->erasePath(hero);
  1013. }
  1014. }
  1015. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  1016. {
  1017. LOG_TRACE(logGlobal);
  1018. if (!LOCPLINT->makingTurn)
  1019. return;
  1020. assert(h);
  1021. assert(!showingDialog->isBusy());
  1022. assert(dialogs.empty());
  1023. if (!h)
  1024. return; //can't find hero
  1025. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1026. if (showingDialog->isBusy() || !dialogs.empty())
  1027. return;
  1028. if (localState->isHeroSleeping(h))
  1029. localState->setHeroAwaken(h);
  1030. movementController->requestMovementStart(h, path);
  1031. }
  1032. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1033. {
  1034. EVENT_HANDLER_CALLED_BY_CLIENT;
  1035. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1036. if (movementController->isHeroMovingThroughGarrison(down, up))
  1037. {
  1038. onEnd();
  1039. return;
  1040. }
  1041. waitForAllDialogs();
  1042. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1043. cgw->quit->addCallback(onEnd);
  1044. GH.windows().pushWindow(cgw);
  1045. }
  1046. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1047. {
  1048. if(pa->packType == CTypeList::getInstance().getTypeID<MoveHero>(nullptr))
  1049. movementController->onMoveHeroApplied();
  1050. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  1051. movementController->onQueryReplyApplied();
  1052. }
  1053. void CPlayerInterface::showHeroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  1054. {
  1055. heroExchangeStarted(hero1, hero2, QueryID(-1));
  1056. }
  1057. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1058. {
  1059. EVENT_HANDLER_CALLED_BY_CLIENT;
  1060. GH.windows().createAndPushWindow<CExchangeWindow>(hero1, hero2, query);
  1061. }
  1062. void CPlayerInterface::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  1063. {
  1064. if (sop->what == ObjProperty::OWNER)
  1065. {
  1066. const CGObjectInstance * obj = cb->getObj(sop->id);
  1067. if(obj->ID == Obj::TOWN)
  1068. {
  1069. auto town = static_cast<const CGTownInstance *>(obj);
  1070. if(obj->tempOwner == playerID)
  1071. {
  1072. localState->removeOwnedTown(town);
  1073. adventureInt->onTownChanged(town);
  1074. }
  1075. }
  1076. }
  1077. }
  1078. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1079. {
  1080. EVENT_HANDLER_CALLED_BY_CLIENT;
  1081. if (sop->what == ObjProperty::OWNER)
  1082. {
  1083. const CGObjectInstance * obj = cb->getObj(sop->id);
  1084. if(obj->ID == Obj::TOWN)
  1085. {
  1086. auto town = static_cast<const CGTownInstance *>(obj);
  1087. if(obj->tempOwner == playerID)
  1088. {
  1089. localState->addOwnedTown(town);
  1090. adventureInt->onTownChanged(town);
  1091. }
  1092. }
  1093. //redraw minimap if owner changed
  1094. std::set<int3> pos = obj->getBlockedPos();
  1095. std::unordered_set<int3> upos(pos.begin(), pos.end());
  1096. adventureInt->onMapTilesChanged(upos);
  1097. assert(cb->getTownsInfo().size() == localState->getOwnedTowns().size());
  1098. }
  1099. }
  1100. void CPlayerInterface::initializeHeroTownList()
  1101. {
  1102. if(localState->getWanderingHeroes().empty())
  1103. {
  1104. for(auto & hero : cb->getHeroesInfo())
  1105. {
  1106. if(!hero->inTownGarrison)
  1107. localState->addWanderingHero(hero);
  1108. }
  1109. }
  1110. if(localState->getOwnedTowns().empty())
  1111. {
  1112. for(auto & town : cb->getTownsInfo())
  1113. localState->addOwnedTown(town);
  1114. }
  1115. localState->deserialize(*cb->getPlayerState(playerID)->playerLocalSettings);
  1116. if(adventureInt)
  1117. adventureInt->onHeroChanged(nullptr);
  1118. }
  1119. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level, QueryID queryID)
  1120. {
  1121. EVENT_HANDLER_CALLED_BY_CLIENT;
  1122. waitWhileDialog();
  1123. auto recruitCb = [=](CreatureID id, int count)
  1124. {
  1125. cb->recruitCreatures(dwelling, dst, id, count, -1);
  1126. };
  1127. auto closeCb = [=]()
  1128. {
  1129. cb->selectionMade(0, queryID);
  1130. };
  1131. GH.windows().createAndPushWindow<CRecruitmentWindow>(dwelling, level, dst, recruitCb, closeCb);
  1132. }
  1133. void CPlayerInterface::waitWhileDialog()
  1134. {
  1135. if (GH.amIGuiThread())
  1136. {
  1137. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1138. return;
  1139. }
  1140. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1141. showingDialog->waitWhileBusy();
  1142. }
  1143. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1144. {
  1145. EVENT_HANDLER_CALLED_BY_CLIENT;
  1146. auto state = obj->shipyardStatus();
  1147. TResources cost;
  1148. obj->getBoatCost(cost);
  1149. GH.windows().createAndPushWindow<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1150. }
  1151. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1152. {
  1153. EVENT_HANDLER_CALLED_BY_CLIENT;
  1154. //we might have built a boat in shipyard in opened town screen
  1155. if (obj->ID == Obj::BOAT
  1156. && LOCPLINT->castleInt
  1157. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1158. {
  1159. CCS->soundh->playSound(soundBase::newBuilding);
  1160. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1161. }
  1162. }
  1163. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1164. {
  1165. EVENT_HANDLER_CALLED_BY_CLIENT;
  1166. waitWhileDialog();
  1167. CCS->curh->hide();
  1168. adventureInt->centerOnTile(pos);
  1169. if (focusTime)
  1170. {
  1171. GH.windows().totalRedraw();
  1172. {
  1173. IgnoreEvents ignore(*this);
  1174. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1175. boost::this_thread::sleep_for(boost::chrono::milliseconds(focusTime));
  1176. }
  1177. }
  1178. CCS->curh->show();
  1179. }
  1180. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  1181. {
  1182. EVENT_HANDLER_CALLED_BY_CLIENT;
  1183. if(playerID == initiator)
  1184. {
  1185. auto removalSound = obj->getRemovalSound(CRandomGenerator::getDefault());
  1186. if (removalSound)
  1187. {
  1188. waitWhileDialog();
  1189. CCS->soundh->playSound(removalSound.value());
  1190. }
  1191. }
  1192. CGI->mh->waitForOngoingAnimations();
  1193. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1194. {
  1195. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1196. heroKilled(h);
  1197. }
  1198. if(obj->ID == Obj::TOWN && obj->tempOwner == playerID)
  1199. {
  1200. const CGTownInstance * t = static_cast<const CGTownInstance *>(obj);
  1201. townRemoved(t);
  1202. }
  1203. GH.fakeMouseMove();
  1204. }
  1205. void CPlayerInterface::objectRemovedAfter()
  1206. {
  1207. EVENT_HANDLER_CALLED_BY_CLIENT;
  1208. adventureInt->onMapTilesChanged(boost::none);
  1209. // visiting or garrisoned hero removed - update window
  1210. if (castleInt)
  1211. castleInt->updateGarrisons();
  1212. for (auto ki : GH.windows().findWindows<CKingdomInterface>())
  1213. ki->heroRemoved();
  1214. }
  1215. void CPlayerInterface::playerBlocked(int reason, bool start)
  1216. {
  1217. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1218. {
  1219. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1220. {
  1221. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1222. LOCPLINT = this;
  1223. GH.curInt = this;
  1224. adventureInt->onCurrentPlayerChanged(playerID);
  1225. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1226. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1227. std::vector<std::shared_ptr<CComponent>> cmp;
  1228. cmp.push_back(std::make_shared<CComponent>(ComponentType::FLAG, playerID));
  1229. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1230. showInfoDialog(msg, cmp);
  1231. waitWhileDialog();
  1232. makingTurn = false;
  1233. }
  1234. }
  1235. }
  1236. void CPlayerInterface::update()
  1237. {
  1238. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1239. boost::shared_lock gsLock(CGameState::mutex);
  1240. // While mutexes were locked away we may be have stopped being the active interface
  1241. if (LOCPLINT != this)
  1242. return;
  1243. //if there are any waiting dialogs, show them
  1244. if (makingTurn && !dialogs.empty() && !showingDialog->isBusy())
  1245. {
  1246. showingDialog->setBusy();
  1247. GH.windows().pushWindow(dialogs.front());
  1248. dialogs.pop_front();
  1249. }
  1250. assert(adventureInt);
  1251. // Handles mouse and key input
  1252. GH.handleEvents();
  1253. GH.windows().simpleRedraw();
  1254. }
  1255. void CPlayerInterface::endNetwork()
  1256. {
  1257. showingDialog->requestTermination();
  1258. }
  1259. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1260. {
  1261. using namespace boost::filesystem;
  1262. using namespace boost::algorithm;
  1263. path gamesDir = VCMIDirs::get().userSavePath();
  1264. std::map<std::time_t, int> dates; //save number => datestamp
  1265. const directory_iterator enddir;
  1266. if (!exists(gamesDir))
  1267. create_directory(gamesDir);
  1268. else
  1269. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1270. {
  1271. if (is_regular_file(dir->status()))
  1272. {
  1273. std::string name = dir->path().filename().string();
  1274. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1275. {
  1276. char nr = name[namePrefix.size()];
  1277. if (std::isdigit(nr))
  1278. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1279. }
  1280. }
  1281. }
  1282. if (!dates.empty())
  1283. return (--dates.end())->second; //return latest file number
  1284. return 0;
  1285. }
  1286. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1287. {
  1288. EVENT_HANDLER_CALLED_BY_CLIENT;
  1289. if (player == playerID)
  1290. {
  1291. if (victoryLossCheckResult.loss())
  1292. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1293. assert(GH.curInt == LOCPLINT);
  1294. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1295. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1296. GH.curInt = this; //waiting for dialogs requires this to get events
  1297. if(!makingTurn)
  1298. {
  1299. makingTurn = true; //also needed for dialog to show with current implementation
  1300. waitForAllDialogs();
  1301. makingTurn = false;
  1302. }
  1303. else
  1304. waitForAllDialogs();
  1305. GH.curInt = previousInterface;
  1306. LOCPLINT = previousInterface;
  1307. }
  1308. }
  1309. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1310. {
  1311. EVENT_HANDLER_CALLED_BY_CLIENT;
  1312. }
  1313. void CPlayerInterface::showPuzzleMap()
  1314. {
  1315. EVENT_HANDLER_CALLED_BY_CLIENT;
  1316. waitWhileDialog();
  1317. //TODO: interface should not know the real position of Grail...
  1318. double ratio = 0;
  1319. int3 grailPos = cb->getGrailPos(&ratio);
  1320. GH.windows().createAndPushWindow<CPuzzleWindow>(grailPos, ratio);
  1321. }
  1322. void CPlayerInterface::viewWorldMap()
  1323. {
  1324. adventureInt->openWorldView();
  1325. }
  1326. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  1327. {
  1328. EVENT_HANDLER_CALLED_BY_CLIENT;
  1329. if(GH.windows().topWindow<CSpellWindow>())
  1330. GH.windows().popWindows(1);
  1331. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1332. localState->erasePath(caster);
  1333. auto castSoundPath = spellID.toSpell()->getCastSound();
  1334. if(!castSoundPath.empty())
  1335. CCS->soundh->playSound(castSoundPath);
  1336. }
  1337. void CPlayerInterface::tryDigging(const CGHeroInstance * h)
  1338. {
  1339. int msgToShow = -1;
  1340. const auto diggingStatus = h->diggingStatus();
  1341. switch(diggingStatus)
  1342. {
  1343. case EDiggingStatus::CAN_DIG:
  1344. break;
  1345. case EDiggingStatus::LACK_OF_MOVEMENT:
  1346. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1347. break;
  1348. case EDiggingStatus::TILE_OCCUPIED:
  1349. msgToShow = 97; //Try searching on clear ground.
  1350. break;
  1351. case EDiggingStatus::WRONG_TERRAIN:
  1352. msgToShow = 60; ////Try looking on land!
  1353. break;
  1354. case EDiggingStatus::BACKPACK_IS_FULL:
  1355. msgToShow = 247; //Searching for the Grail is fruitless...
  1356. break;
  1357. default:
  1358. assert(0);
  1359. }
  1360. if(msgToShow < 0)
  1361. cb->dig(h);
  1362. else
  1363. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1364. }
  1365. void CPlayerInterface::battleNewRoundFirst(const BattleID & battleID)
  1366. {
  1367. EVENT_HANDLER_CALLED_BY_CLIENT;
  1368. BATTLE_EVENT_POSSIBLE_RETURN;
  1369. battleInt->newRoundFirst();
  1370. }
  1371. void CPlayerInterface::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  1372. {
  1373. EVENT_HANDLER_CALLED_BY_CLIENT;
  1374. auto onWindowClosed = [this, queryID](){
  1375. cb->selectionMade(0, queryID);
  1376. };
  1377. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1378. GH.windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, EMarketMode::ARTIFACT_EXP);
  1379. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1380. GH.windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, EMarketMode::CREATURE_EXP);
  1381. else if(market->allowsTrade(EMarketMode::CREATURE_UNDEAD))
  1382. GH.windows().createAndPushWindow<CTransformerWindow>(market, visitor, onWindowClosed);
  1383. else if (!market->availableModes().empty())
  1384. for(auto mode = EMarketMode::RESOURCE_RESOURCE; mode != EMarketMode::MARKET_AFTER_LAST_PLACEHOLDER; mode = vstd::next(mode, 1))
  1385. {
  1386. if(vstd::contains(market->availableModes(), mode))
  1387. {
  1388. GH.windows().createAndPushWindow<CMarketWindow>(market, visitor, onWindowClosed, mode);
  1389. break;
  1390. }
  1391. }
  1392. else
  1393. onWindowClosed();
  1394. }
  1395. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor, QueryID queryID)
  1396. {
  1397. EVENT_HANDLER_CALLED_BY_CLIENT;
  1398. auto onWindowClosed = [this, queryID](){
  1399. cb->selectionMade(0, queryID);
  1400. };
  1401. GH.windows().createAndPushWindow<CUniversityWindow>(visitor, BuildingID::NONE, market, onWindowClosed);
  1402. }
  1403. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1404. {
  1405. EVENT_HANDLER_CALLED_BY_CLIENT;
  1406. GH.windows().createAndPushWindow<CHillFortWindow>(visitor, object);
  1407. }
  1408. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1409. {
  1410. EVENT_HANDLER_CALLED_BY_CLIENT;
  1411. for (auto cmw : GH.windows().findWindows<IMarketHolder>())
  1412. cmw->updateArtifacts();
  1413. }
  1414. void CPlayerInterface::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  1415. {
  1416. EVENT_HANDLER_CALLED_BY_CLIENT;
  1417. auto onWindowClosed = [this, queryID](){
  1418. if (queryID != QueryID::NONE)
  1419. cb->selectionMade(0, queryID);
  1420. };
  1421. GH.windows().createAndPushWindow<CTavernWindow>(object, onWindowClosed);
  1422. }
  1423. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1424. {
  1425. EVENT_HANDLER_CALLED_BY_CLIENT;
  1426. GH.windows().createAndPushWindow<CThievesGuildWindow>(obj);
  1427. }
  1428. void CPlayerInterface::showQuestLog()
  1429. {
  1430. EVENT_HANDLER_CALLED_BY_CLIENT;
  1431. GH.windows().createAndPushWindow<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1432. }
  1433. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1434. {
  1435. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1436. {
  1437. MetaString txt;
  1438. obj->getProblemText(txt);
  1439. showInfoDialog(txt.toString());
  1440. }
  1441. else
  1442. showShipyardDialog(obj);
  1443. }
  1444. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1445. {
  1446. artifactController->askToAssemble(al, true, true);
  1447. }
  1448. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1449. {
  1450. EVENT_HANDLER_CALLED_BY_CLIENT;
  1451. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1452. }
  1453. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1454. {
  1455. EVENT_HANDLER_CALLED_BY_CLIENT;
  1456. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1457. artifactController->artifactRemoved();
  1458. }
  1459. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1460. {
  1461. EVENT_HANDLER_CALLED_BY_CLIENT;
  1462. adventureInt->onHeroChanged(cb->getHero(dst.artHolder));
  1463. artifactController->artifactMoved();
  1464. }
  1465. void CPlayerInterface::bulkArtMovementStart(size_t totalNumOfArts, size_t possibleAssemblyNumOfArts)
  1466. {
  1467. artifactController->bulkArtMovementStart(totalNumOfArts, possibleAssemblyNumOfArts);
  1468. }
  1469. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1470. {
  1471. EVENT_HANDLER_CALLED_BY_CLIENT;
  1472. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1473. artifactController->artifactAssembled();
  1474. }
  1475. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1476. {
  1477. EVENT_HANDLER_CALLED_BY_CLIENT;
  1478. adventureInt->onHeroChanged(cb->getHero(al.artHolder));
  1479. artifactController->artifactDisassembled();
  1480. }
  1481. void CPlayerInterface::waitForAllDialogs()
  1482. {
  1483. if (!makingTurn)
  1484. return;
  1485. while(!dialogs.empty())
  1486. {
  1487. auto unlockInterface = vstd::makeUnlockGuard(GH.interfaceMutex);
  1488. boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
  1489. }
  1490. waitWhileDialog();
  1491. }
  1492. void CPlayerInterface::proposeLoadingGame()
  1493. {
  1494. showYesNoDialog(
  1495. CGI->generaltexth->allTexts[68],
  1496. []()
  1497. {
  1498. CSH->endGameplay();
  1499. CMM->menu->switchToTab("load");
  1500. },
  1501. nullptr
  1502. );
  1503. }
  1504. bool CPlayerInterface::capturedAllEvents()
  1505. {
  1506. if(movementController->isHeroMoving())
  1507. {
  1508. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1509. return true;
  1510. }
  1511. bool needToLockAdventureMap = adventureInt && adventureInt->isActive() && CGI->mh->hasOngoingAnimations();
  1512. bool quickCombatOngoing = isAutoFightOn && !battleInt;
  1513. if (ignoreEvents || needToLockAdventureMap || quickCombatOngoing )
  1514. {
  1515. GH.input().ignoreEventsUntilInput();
  1516. return true;
  1517. }
  1518. return false;
  1519. }
  1520. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1521. {
  1522. EVENT_HANDLER_CALLED_BY_CLIENT;
  1523. adventureInt->openWorldView(objectPositions, showTerrain );
  1524. }
  1525. std::optional<BattleAction> CPlayerInterface::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  1526. {
  1527. return std::nullopt;
  1528. }