CPlayerInterface.cpp 54 KB

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