CPlayerInterface.cpp 52 KB

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