CPlayerInterface.cpp 53 KB

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