CPlayerInterface.cpp 53 KB

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