CPlayerInterface.cpp 53 KB

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