CPlayerInterface.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  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 "adventureMap/CAdventureMapInterface.h"
  14. #include "mapView/mapHandler.h"
  15. #include "adventureMap/CList.h"
  16. #include "adventureMap/CInfoBar.h"
  17. #include "battle/BattleInterface.h"
  18. #include "battle/BattleEffectsController.h"
  19. #include "battle/BattleFieldController.h"
  20. #include "battle/BattleInterfaceClasses.h"
  21. #include "battle/BattleWindow.h"
  22. #include "../CCallback.h"
  23. #include "windows/CCastleInterface.h"
  24. #include "gui/CursorHandler.h"
  25. #include "windows/CKingdomInterface.h"
  26. #include "CGameInfo.h"
  27. #include "PlayerLocalState.h"
  28. #include "CMT.h"
  29. #include "windows/CHeroWindow.h"
  30. #include "windows/CCreatureWindow.h"
  31. #include "windows/CQuestLog.h"
  32. #include "windows/CPuzzleWindow.h"
  33. #include "widgets/CComponent.h"
  34. #include "widgets/Buttons.h"
  35. #include "windows/CTradeWindow.h"
  36. #include "windows/CSpellWindow.h"
  37. #include "../lib/CConfigHandler.h"
  38. #include "windows/GUIClasses.h"
  39. #include "render/CAnimation.h"
  40. #include "render/IImage.h"
  41. #include "../lib/CArtHandler.h"
  42. #include "../lib/CGeneralTextHandler.h"
  43. #include "../lib/CHeroHandler.h"
  44. #include "../lib/serializer/CTypeList.h"
  45. #include "../lib/serializer/BinaryDeserializer.h"
  46. #include "../lib/serializer/BinarySerializer.h"
  47. #include "../lib/spells/CSpellHandler.h"
  48. #include "../lib/CTownHandler.h"
  49. #include "../lib/mapObjects/CObjectClassesHandler.h" // For displaying correct UI when interacting with objects
  50. #include "../lib/CStack.h"
  51. #include "../lib/JsonNode.h"
  52. #include "CMusicHandler.h"
  53. #include "../lib/CondSh.h"
  54. #include "../lib/NetPacksBase.h"
  55. #include "../lib/NetPacks.h"//todo: remove
  56. #include "../lib/mapping/CMap.h"
  57. #include "../lib/VCMIDirs.h"
  58. #include "../lib/CStopWatch.h"
  59. #include "../lib/StartInfo.h"
  60. #include "../lib/CPlayerState.h"
  61. #include "../lib/GameConstants.h"
  62. #include "gui/CGuiHandler.h"
  63. #include "windows/InfoWindows.h"
  64. #include "../lib/UnlockGuard.h"
  65. #include "../lib/CPathfinder.h"
  66. #include "../lib/RoadHandler.h"
  67. #include "../lib/TerrainHandler.h"
  68. #include "CServerHandler.h"
  69. // FIXME: only needed for CGameState::mutex
  70. #include "../lib/CGameState.h"
  71. #include "gui/NotificationHandler.h"
  72. #include "adventureMap/CInGameConsole.h"
  73. #include <SDL_events.h>
  74. // The macro below is used to mark functions that are called by client when game state changes.
  75. // They all assume that CPlayerInterface::pim mutex is locked.
  76. #define EVENT_HANDLER_CALLED_BY_CLIENT
  77. // The macro marks functions that are run on a new thread by client.
  78. // They do not own any mutexes intiially.
  79. #define THREAD_CREATED_BY_CLIENT
  80. #define RETURN_IF_QUICK_COMBAT \
  81. if (isAutoFightOn && !battleInt) \
  82. return;
  83. #define BATTLE_EVENT_POSSIBLE_RETURN\
  84. if (LOCPLINT != this) \
  85. return; \
  86. RETURN_IF_QUICK_COMBAT
  87. extern std::queue<SDL_Event> SDLEventsQueue;
  88. extern boost::mutex eventsM;
  89. boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
  90. CPlayerInterface * LOCPLINT;
  91. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  92. enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
  93. CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
  94. struct HeroObjectRetriever
  95. {
  96. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  97. {
  98. return h;
  99. }
  100. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  101. {
  102. return nullptr;
  103. }
  104. };
  105. CPlayerInterface::CPlayerInterface(PlayerColor Player):
  106. localState(std::make_unique<PlayerLocalState>(*this))
  107. {
  108. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.getStr());
  109. destinationTeleport = ObjectInstanceID();
  110. destinationTeleportPos = int3(-1);
  111. GH.defActionsDef = 0;
  112. LOCPLINT = this;
  113. curAction = nullptr;
  114. playerID=Player;
  115. human=true;
  116. battleInt = nullptr;
  117. castleInt = nullptr;
  118. makingTurn = false;
  119. showingDialog = new CondSh<bool>(false);
  120. cingconsole = new CInGameConsole();
  121. GH.terminate_cond->set(false);
  122. firstCall = 1; //if loading will be overwritten in serialize
  123. autosaveCount = 0;
  124. isAutoFightOn = false;
  125. duringMovement = false;
  126. ignoreEvents = false;
  127. numOfMovedArts = 0;
  128. }
  129. CPlayerInterface::~CPlayerInterface()
  130. {
  131. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.getStr());
  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. // always recreate advmap interface to avoid possible memory-corruption bugs
  144. adventureInt.reset(new CAdventureMapInterface());
  145. }
  146. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  147. {
  148. EVENT_HANDLER_CALLED_BY_CLIENT;
  149. if (!vstd::contains (GH.listInt, adventureInt))
  150. {
  151. // after map load - remove all active windows and replace them with adventure map
  152. GH.popInts ((int)GH.listInt.size());
  153. GH.pushInt (adventureInt);
  154. }
  155. // remove all dialogs that do not expect query answer
  156. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front().get()))
  157. GH.popInts(1);
  158. if (player != playerID && LOCPLINT == this)
  159. {
  160. waitWhileDialog();
  161. adventureInt->onEnemyTurnStarted(player);
  162. }
  163. }
  164. void CPlayerInterface::performAutosave()
  165. {
  166. std::string prefix = settings["session"]["saveprefix"].String();
  167. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  168. if(firstCall)
  169. {
  170. autosaveCount = getLastIndex(prefix + "Autosave_");
  171. if(firstCall > 0) //new game, not loaded
  172. {
  173. int index = getLastIndex(prefix + "Newgame_");
  174. index %= SAVES_COUNT;
  175. cb->save("Saves/" + prefix + "Newgame_Autosave_" + std::to_string(index + 1));
  176. }
  177. firstCall = 0;
  178. }
  179. else if(frequency > 0 && cb->getDate() % frequency == 0)
  180. {
  181. LOCPLINT->cb->save("Saves/" + prefix + "Autosave_" + std::to_string(autosaveCount++ + 1));
  182. autosaveCount %= 5;
  183. }
  184. }
  185. void CPlayerInterface::yourTurn()
  186. {
  187. EVENT_HANDLER_CALLED_BY_CLIENT;
  188. {
  189. boost::unique_lock<boost::mutex> lock(eventsM); //block handling events until interface is ready
  190. LOCPLINT = this;
  191. GH.curInt = this;
  192. NotificationHandler::notify("Your turn");
  193. performAutosave();
  194. if (CSH->howManyPlayerInterfaces() > 1) //hot seat message
  195. {
  196. adventureInt->onHotseatWaitStarted(playerID);
  197. makingTurn = true;
  198. std::string msg = CGI->generaltexth->allTexts[13];
  199. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  200. std::vector<std::shared_ptr<CComponent>> cmp;
  201. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  202. showInfoDialog(msg, cmp);
  203. }
  204. else
  205. {
  206. makingTurn = true;
  207. adventureInt->onPlayerTurnStarted(playerID);
  208. }
  209. }
  210. acceptTurn();
  211. }
  212. void CPlayerInterface::acceptTurn()
  213. {
  214. if (settings["session"]["autoSkip"].Bool())
  215. {
  216. while(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt().get()))
  217. iw->close();
  218. }
  219. if(CSH->howManyPlayerInterfaces() > 1)
  220. {
  221. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  222. adventureInt->onPlayerTurnStarted(playerID);
  223. }
  224. // warn player if he has no town
  225. if (cb->howManyTowns() == 0)
  226. {
  227. auto playerColor = *cb->getPlayerID();
  228. std::vector<Component> components;
  229. components.emplace_back(Component::EComponentType::FLAG, playerColor.getNum(), 0, 0);
  230. MetaString text;
  231. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  232. if(optDaysWithoutCastle)
  233. {
  234. auto daysWithoutCastle = optDaysWithoutCastle.value();
  235. if (daysWithoutCastle < 6)
  236. {
  237. text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  238. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  239. text.addReplacement(7 - daysWithoutCastle);
  240. }
  241. else if (daysWithoutCastle == 6)
  242. {
  243. text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  244. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  245. }
  246. showInfoDialogAndWait(components, text);
  247. }
  248. else
  249. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  250. }
  251. }
  252. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  253. {
  254. EVENT_HANDLER_CALLED_BY_CLIENT;
  255. waitWhileDialog();
  256. if(LOCPLINT != this)
  257. return;
  258. //FIXME: read once and store
  259. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  260. return;
  261. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  262. if (!hero)
  263. return;
  264. if (details.result == TryMoveHero::EMBARK || details.result == TryMoveHero::DISEMBARK)
  265. {
  266. if(hero->getRemovalSound() && hero->tempOwner == playerID)
  267. CCS->soundh->playSound(hero->getRemovalSound().value());
  268. }
  269. std::unordered_set<int3> changedTiles {
  270. hero->convertToVisitablePos(details.start),
  271. hero->convertToVisitablePos(details.end)
  272. };
  273. adventureInt->onMapTilesChanged(changedTiles);
  274. bool directlyAttackingCreature = details.attackedFrom && localState->hasPath(hero) && localState->getPath(hero).endPos() == *details.attackedFrom;
  275. if(makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
  276. {
  277. if(details.result == TryMoveHero::TELEPORTATION)
  278. {
  279. if(localState->hasPath(hero))
  280. {
  281. assert(localState->getPath(hero).nodes.size() >= 2);
  282. auto nodesIt = localState->getPath(hero).nodes.end() - 1;
  283. if((nodesIt)->coord == hero->convertToVisitablePos(details.start)
  284. && (nodesIt - 1)->coord == hero->convertToVisitablePos(details.end))
  285. {
  286. //path was between entrance and exit of teleport -> OK, erase node as usual
  287. localState->removeLastNode(hero);
  288. }
  289. else
  290. {
  291. //teleport was not along current path, it'll now be invalid (hero is somewhere else)
  292. localState->erasePath(hero);
  293. }
  294. }
  295. }
  296. if(hero->pos != details.end //hero didn't change tile but visit succeeded
  297. || directlyAttackingCreature) // or creature was attacked from endangering tile.
  298. {
  299. localState->erasePath(hero);
  300. }
  301. else if(localState->hasPath(hero) && hero->pos == details.end) //&& hero is moving
  302. {
  303. if(details.start != details.end) //so we don't touch path when revisiting with spacebar
  304. localState->removeLastNode(hero);
  305. }
  306. }
  307. if(details.stopMovement()) //hero failed to move
  308. {
  309. stillMoveHero.setn(STOP_MOVE);
  310. adventureInt->onHeroChanged(hero);
  311. return;
  312. }
  313. CGI->mh->waitForOngoingAnimations();
  314. //move finished
  315. adventureInt->onHeroChanged(hero);
  316. //check if user cancelled movement
  317. {
  318. boost::unique_lock<boost::mutex> un(eventsM);
  319. while(!SDLEventsQueue.empty())
  320. {
  321. SDL_Event ev = SDLEventsQueue.front();
  322. SDLEventsQueue.pop();
  323. switch(ev.type)
  324. {
  325. case SDL_MOUSEBUTTONDOWN:
  326. stillMoveHero.setn(STOP_MOVE);
  327. break;
  328. case SDL_KEYDOWN:
  329. if (ev.key.keysym.sym < SDLK_F1 || ev.key.keysym.sym > SDLK_F15)
  330. stillMoveHero.setn(STOP_MOVE);
  331. break;
  332. }
  333. }
  334. }
  335. if (stillMoveHero.get() == WAITING_MOVE)
  336. stillMoveHero.setn(DURING_MOVE);
  337. // Hero attacked creature directly, set direction to face it.
  338. if (directlyAttackingCreature) {
  339. // Get direction to attacker.
  340. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  341. static const ui8 dirLookup[3][3] = {
  342. { 1, 2, 3 },
  343. { 8, 0, 4 },
  344. { 7, 6, 5 }
  345. };
  346. // FIXME: Avoid const_cast, make moveDir mutable in some other way?
  347. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  348. }
  349. }
  350. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  351. {
  352. EVENT_HANDLER_CALLED_BY_CLIENT;
  353. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  354. localState->wanderingHeroes -= hero;
  355. adventureInt->onHeroChanged(hero);
  356. localState->erasePath(hero);
  357. }
  358. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  359. {
  360. EVENT_HANDLER_CALLED_BY_CLIENT;
  361. if(start && visitedObj)
  362. {
  363. if(visitedObj->getVisitSound())
  364. CCS->soundh->playSound(visitedObj->getVisitSound().value());
  365. }
  366. }
  367. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  368. {
  369. EVENT_HANDLER_CALLED_BY_CLIENT;
  370. localState->wanderingHeroes.push_back(hero);
  371. adventureInt->onHeroChanged(hero);
  372. }
  373. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  374. {
  375. if(castleInt)
  376. castleInt->close();
  377. castleInt = nullptr;
  378. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  379. GH.pushInt(newCastleInt);
  380. }
  381. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  382. {
  383. EVENT_HANDLER_CALLED_BY_CLIENT;
  384. if (which == 4)
  385. {
  386. if (CAltarWindow *ctw = dynamic_cast<CAltarWindow *>(GH.topInt().get()))
  387. ctw->setExpToLevel();
  388. }
  389. else
  390. adventureInt->onHeroChanged(hero);
  391. }
  392. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  393. {
  394. EVENT_HANDLER_CALLED_BY_CLIENT;
  395. CUniversityWindow* cuw = dynamic_cast<CUniversityWindow*>(GH.topInt().get());
  396. if (cuw) //university window is open
  397. {
  398. GH.totalRedraw();
  399. }
  400. }
  401. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  402. {
  403. EVENT_HANDLER_CALLED_BY_CLIENT;
  404. adventureInt->onHeroChanged(hero);
  405. if (makingTurn && hero->tempOwner == playerID)
  406. adventureInt->onHeroChanged(hero);
  407. }
  408. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  409. {
  410. EVENT_HANDLER_CALLED_BY_CLIENT;
  411. if (makingTurn && hero->tempOwner == playerID)
  412. adventureInt->onHeroChanged(hero);
  413. }
  414. void CPlayerInterface::receivedResource()
  415. {
  416. EVENT_HANDLER_CALLED_BY_CLIENT;
  417. if (CMarketplaceWindow *mw = dynamic_cast<CMarketplaceWindow *>(GH.topInt().get()))
  418. mw->resourceChanged();
  419. GH.totalRedraw();
  420. }
  421. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  422. {
  423. EVENT_HANDLER_CALLED_BY_CLIENT;
  424. waitWhileDialog();
  425. CCS->soundh->playSound(soundBase::heroNewLevel);
  426. GH.pushIntT<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  427. {
  428. cb->selectionMade(selection, queryID);
  429. });
  430. }
  431. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  432. {
  433. EVENT_HANDLER_CALLED_BY_CLIENT;
  434. waitWhileDialog();
  435. CCS->soundh->playSound(soundBase::heroNewLevel);
  436. GH.pushIntT<CStackWindow>(commander, skills, [=](ui32 selection)
  437. {
  438. cb->selectionMade(selection, queryID);
  439. });
  440. }
  441. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  442. {
  443. EVENT_HANDLER_CALLED_BY_CLIENT;
  444. if (town->garrisonHero) //wandering hero moved to the garrison
  445. {
  446. if (town->garrisonHero->tempOwner == playerID && vstd::contains(localState->wanderingHeroes,town->garrisonHero)) // our hero
  447. localState->wanderingHeroes -= town->garrisonHero;
  448. }
  449. if (town->visitingHero) //hero leaves garrison
  450. {
  451. if (town->visitingHero->tempOwner == playerID && !vstd::contains(localState->wanderingHeroes,town->visitingHero)) // our hero
  452. localState->wanderingHeroes.push_back(town->visitingHero);
  453. }
  454. adventureInt->onHeroChanged(nullptr);
  455. adventureInt->onTownChanged(town);
  456. if(castleInt)
  457. {
  458. castleInt->garr->selectSlot(nullptr);
  459. castleInt->garr->setArmy(town->getUpperArmy(), 0);
  460. castleInt->garr->setArmy(town->visitingHero, 1);
  461. castleInt->garr->recreateSlots();
  462. castleInt->heroes->update();
  463. castleInt->redraw();
  464. }
  465. for (auto isa : GH.listInt)
  466. {
  467. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  468. if (ki)
  469. {
  470. ki->townChanged(town);
  471. ki->updateGarrisons();
  472. ki->redraw();
  473. }
  474. }
  475. }
  476. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  477. {
  478. EVENT_HANDLER_CALLED_BY_CLIENT;
  479. if (hero->tempOwner != playerID )
  480. return;
  481. waitWhileDialog();
  482. openTownWindow(town);
  483. }
  484. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  485. {
  486. std::vector<const CGObjectInstance *> instances;
  487. if(auto obj = cb->getObj(id1))
  488. instances.push_back(obj);
  489. if(id2 != ObjectInstanceID() && id2 != id1)
  490. {
  491. if(auto obj = cb->getObj(id2))
  492. instances.push_back(obj);
  493. }
  494. garrisonsChanged(instances);
  495. }
  496. void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
  497. {
  498. boost::unique_lock<boost::recursive_mutex> un(*pim);
  499. for (auto object : objs)
  500. {
  501. auto * hero = dynamic_cast<const CGHeroInstance*>(object);
  502. auto * town = dynamic_cast<const CGTownInstance*>(object);
  503. if (hero)
  504. adventureInt->onHeroChanged(hero);
  505. if (town)
  506. adventureInt->onTownChanged(town);
  507. }
  508. for (auto & elem : GH.listInt)
  509. {
  510. CGarrisonHolder *cgh = dynamic_cast<CGarrisonHolder*>(elem.get());
  511. if (cgh)
  512. cgh->updateGarrisons();
  513. if (CTradeWindow *cmw = dynamic_cast<CTradeWindow*>(elem.get()))
  514. {
  515. if (vstd::contains(objs, cmw->hero))
  516. cmw->garrisonChanged();
  517. }
  518. }
  519. GH.totalRedraw();
  520. }
  521. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  522. {
  523. EVENT_HANDLER_CALLED_BY_CLIENT;
  524. if (castleInt)
  525. {
  526. castleInt->townlist->update(town);
  527. if (castleInt->town == town)
  528. {
  529. switch(what)
  530. {
  531. case 1:
  532. CCS->soundh->playSound(soundBase::newBuilding);
  533. castleInt->addBuilding(buildingID);
  534. break;
  535. case 2:
  536. castleInt->removeBuilding(buildingID);
  537. break;
  538. }
  539. }
  540. }
  541. adventureInt->onTownChanged(town);
  542. }
  543. void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  544. {
  545. //Don't wait for dialogs when we are non-active hot-seat player
  546. if (LOCPLINT == this)
  547. waitForAllDialogs();
  548. }
  549. void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  550. {
  551. EVENT_HANDLER_CALLED_BY_CLIENT;
  552. bool autoBattleResultRefused = (lastBattleArmies.first == army1 && lastBattleArmies.second == army2);
  553. lastBattleArmies.first = army1;
  554. lastBattleArmies.second = army2;
  555. //quick combat with neutral creatures only
  556. auto * army2_object = dynamic_cast<const CGObjectInstance *>(army2);
  557. if((!autoBattleResultRefused && !allowBattleReplay && army2_object
  558. && army2_object->getOwner() == PlayerColor::UNFLAGGABLE
  559. && settings["adventure"]["quickCombat"].Bool())
  560. || settings["adventure"]["alwaysSkipCombat"].Bool())
  561. {
  562. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  563. autofightingAI->initBattleInterface(env, cb);
  564. autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
  565. isAutoFightOn = true;
  566. cb->registerBattleInterface(autofightingAI);
  567. // Player shouldn't be able to move on adventure map if quick combat is going
  568. allowBattleReplay = true;
  569. }
  570. //Don't wait for dialogs when we are non-active hot-seat player
  571. if (LOCPLINT == this)
  572. waitForAllDialogs();
  573. BATTLE_EVENT_POSSIBLE_RETURN;
  574. }
  575. void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units)
  576. {
  577. EVENT_HANDLER_CALLED_BY_CLIENT;
  578. BATTLE_EVENT_POSSIBLE_RETURN;
  579. for(auto & info : units)
  580. {
  581. switch(info.operation)
  582. {
  583. case UnitChanges::EOperation::RESET_STATE:
  584. {
  585. const CStack * stack = cb->battleGetStackByID(info.id );
  586. if(!stack)
  587. {
  588. logGlobal->error("Invalid unit ID %d", info.id);
  589. continue;
  590. }
  591. battleInt->stackReset(stack);
  592. }
  593. break;
  594. case UnitChanges::EOperation::REMOVE:
  595. battleInt->stackRemoved(info.id);
  596. break;
  597. case UnitChanges::EOperation::ADD:
  598. {
  599. const CStack * unit = cb->battleGetStackByID(info.id);
  600. if(!unit)
  601. {
  602. logGlobal->error("Invalid unit ID %d", info.id);
  603. continue;
  604. }
  605. battleInt->stackAdded(unit);
  606. }
  607. break;
  608. default:
  609. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  610. break;
  611. }
  612. }
  613. }
  614. void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges> & obstacles)
  615. {
  616. EVENT_HANDLER_CALLED_BY_CLIENT;
  617. BATTLE_EVENT_POSSIBLE_RETURN;
  618. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  619. std::vector<ObstacleChanges> removedObstacles;
  620. for(auto & change : obstacles)
  621. {
  622. if(change.operation == BattleChanges::EOperation::ADD)
  623. {
  624. auto instance = cb->battleGetObstacleByID(change.id);
  625. if(instance)
  626. newObstacles.push_back(instance);
  627. else
  628. logNetwork->error("Invalid obstacle instance %d", change.id);
  629. }
  630. if(change.operation == BattleChanges::EOperation::REMOVE)
  631. removedObstacles.push_back(change); //Obstacles are already removed, so, show animation based on json struct
  632. }
  633. if (!newObstacles.empty())
  634. battleInt->obstaclePlaced(newObstacles);
  635. if (!removedObstacles.empty())
  636. battleInt->obstacleRemoved(removedObstacles);
  637. battleInt->fieldController->redrawBackgroundWithHexes();
  638. }
  639. void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
  640. {
  641. EVENT_HANDLER_CALLED_BY_CLIENT;
  642. BATTLE_EVENT_POSSIBLE_RETURN;
  643. battleInt->stackIsCatapulting(ca);
  644. }
  645. void CPlayerInterface::battleNewRound(int round) //called at the beginning of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
  646. {
  647. EVENT_HANDLER_CALLED_BY_CLIENT;
  648. BATTLE_EVENT_POSSIBLE_RETURN;
  649. battleInt->newRound(round);
  650. }
  651. void CPlayerInterface::actionStarted(const BattleAction &action)
  652. {
  653. EVENT_HANDLER_CALLED_BY_CLIENT;
  654. BATTLE_EVENT_POSSIBLE_RETURN;
  655. curAction = new BattleAction(action);
  656. battleInt->startAction(curAction);
  657. }
  658. void CPlayerInterface::actionFinished(const BattleAction &action)
  659. {
  660. EVENT_HANDLER_CALLED_BY_CLIENT;
  661. BATTLE_EVENT_POSSIBLE_RETURN;
  662. battleInt->endAction(curAction);
  663. delete curAction;
  664. curAction = nullptr;
  665. }
  666. BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
  667. {
  668. THREAD_CREATED_BY_CLIENT;
  669. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  670. auto stackId = stack->ID;
  671. auto stackName = stack->nodeName();
  672. if (autofightingAI)
  673. {
  674. if (isAutoFightOn)
  675. {
  676. auto ret = autofightingAI->activeStack(stack);
  677. if(cb->battleIsFinished())
  678. {
  679. return BattleAction::makeDefend(stack); // battle finished with spellcast
  680. }
  681. if (isAutoFightOn)
  682. {
  683. return ret;
  684. }
  685. }
  686. cb->unregisterBattleInterface(autofightingAI);
  687. autofightingAI.reset();
  688. }
  689. assert(battleInt);
  690. if(!battleInt)
  691. {
  692. return BattleAction::makeDefend(stack); // probably battle is finished already
  693. }
  694. if(BattleInterface::givenCommand.get())
  695. {
  696. logGlobal->error("Command buffer must be clean! (we don't want to use old command)");
  697. vstd::clear_pointer(BattleInterface::givenCommand.data);
  698. }
  699. {
  700. boost::unique_lock<boost::recursive_mutex> un(*pim);
  701. battleInt->stackActivated(stack);
  702. //Regeneration & mana drain go there
  703. }
  704. //wait till BattleInterface sets its command
  705. boost::unique_lock<boost::mutex> lock(BattleInterface::givenCommand.mx);
  706. while(!BattleInterface::givenCommand.data)
  707. {
  708. BattleInterface::givenCommand.cond.wait(lock);
  709. if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
  710. throw boost::thread_interrupted(); //will shut the thread peacefully
  711. }
  712. //tidy up
  713. BattleAction ret = *(BattleInterface::givenCommand.data);
  714. vstd::clear_pointer(BattleInterface::givenCommand.data);
  715. if(ret.actionType == EActionType::CANCEL)
  716. {
  717. if(stackId != ret.stackNumber)
  718. logGlobal->error("Not current active stack action canceled");
  719. logGlobal->trace("Canceled command for %s", stackName);
  720. }
  721. else
  722. logGlobal->trace("Giving command for %s", stackName);
  723. return ret;
  724. }
  725. void CPlayerInterface::battleEnd(const BattleResult *br, QueryID queryID)
  726. {
  727. EVENT_HANDLER_CALLED_BY_CLIENT;
  728. if(isAutoFightOn || autofightingAI)
  729. {
  730. isAutoFightOn = false;
  731. cb->unregisterBattleInterface(autofightingAI);
  732. autofightingAI.reset();
  733. if(!battleInt)
  734. {
  735. bool allowManualReplay = allowBattleReplay && !settings["adventure"]["alwaysSkipCombat"].Bool();
  736. allowBattleReplay = false;
  737. auto wnd = std::make_shared<BattleResultWindow>(*br, *this, allowManualReplay);
  738. wnd->resultCallback = [=](ui32 selection)
  739. {
  740. cb->selectionMade(selection, queryID);
  741. };
  742. GH.pushInt(wnd);
  743. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  744. // Otherwise NewTurn causes freeze.
  745. waitWhileDialog();
  746. return;
  747. }
  748. }
  749. BATTLE_EVENT_POSSIBLE_RETURN;
  750. battleInt->battleFinished(*br, queryID);
  751. }
  752. void CPlayerInterface::battleLogMessage(const std::vector<MetaString> & lines)
  753. {
  754. EVENT_HANDLER_CALLED_BY_CLIENT;
  755. BATTLE_EVENT_POSSIBLE_RETURN;
  756. battleInt->displayBattleLog(lines);
  757. }
  758. void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance, bool teleport)
  759. {
  760. EVENT_HANDLER_CALLED_BY_CLIENT;
  761. BATTLE_EVENT_POSSIBLE_RETURN;
  762. battleInt->stackMoved(stack, dest, distance, teleport);
  763. }
  764. void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
  765. {
  766. EVENT_HANDLER_CALLED_BY_CLIENT;
  767. BATTLE_EVENT_POSSIBLE_RETURN;
  768. battleInt->spellCast(sc);
  769. }
  770. void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
  771. {
  772. EVENT_HANDLER_CALLED_BY_CLIENT;
  773. BATTLE_EVENT_POSSIBLE_RETURN;
  774. battleInt->battleStacksEffectsSet(sse);
  775. }
  776. void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
  777. {
  778. EVENT_HANDLER_CALLED_BY_CLIENT;
  779. BATTLE_EVENT_POSSIBLE_RETURN;
  780. RETURN_IF_QUICK_COMBAT;
  781. battleInt->effectsController->battleTriggerEffect(bte);
  782. }
  783. void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa, bool ranged)
  784. {
  785. EVENT_HANDLER_CALLED_BY_CLIENT;
  786. BATTLE_EVENT_POSSIBLE_RETURN;
  787. std::vector<StackAttackedInfo> arg;
  788. for(auto & elem : bsa)
  789. {
  790. const CStack * defender = cb->battleGetStackByID(elem.stackAttacked, false);
  791. const CStack * attacker = cb->battleGetStackByID(elem.attackerID, false);
  792. assert(defender);
  793. StackAttackedInfo info;
  794. info.defender = defender;
  795. info.attacker = attacker;
  796. info.damageDealt = elem.damageAmount;
  797. info.amountKilled = elem.killedAmount;
  798. info.spellEffect = SpellID::NONE;
  799. info.indirectAttack = ranged;
  800. info.killed = elem.killed();
  801. info.rebirth = elem.willRebirth();
  802. info.cloneKilled = elem.cloneKilled();
  803. info.fireShield = elem.fireShield();
  804. if (elem.isSpell())
  805. info.spellEffect = elem.spellID;
  806. arg.push_back(info);
  807. }
  808. battleInt->stacksAreAttacked(arg);
  809. }
  810. void CPlayerInterface::battleAttack(const BattleAttack * ba)
  811. {
  812. EVENT_HANDLER_CALLED_BY_CLIENT;
  813. BATTLE_EVENT_POSSIBLE_RETURN;
  814. assert(curAction);
  815. StackAttackInfo info;
  816. info.attacker = cb->battleGetStackByID(ba->stackAttacking);
  817. info.defender = nullptr;
  818. info.indirectAttack = ba->shot();
  819. info.lucky = ba->lucky();
  820. info.unlucky = ba->unlucky();
  821. info.deathBlow = ba->deathBlow();
  822. info.lifeDrain = ba->lifeDrain();
  823. info.tile = ba->tile;
  824. info.spellEffect = SpellID::NONE;
  825. if (ba->spellLike())
  826. info.spellEffect = ba->spellID;
  827. for(auto & elem : ba->bsa)
  828. {
  829. if(!elem.isSecondary())
  830. {
  831. assert(info.defender == nullptr);
  832. info.defender = cb->battleGetStackByID(elem.stackAttacked);
  833. }
  834. else
  835. {
  836. info.secondaryDefender.push_back(cb->battleGetStackByID(elem.stackAttacked));
  837. }
  838. }
  839. assert(info.defender != nullptr);
  840. assert(info.attacker != nullptr);
  841. battleInt->stackAttacking(info);
  842. }
  843. void CPlayerInterface::battleGateStateChanged(const EGateState state)
  844. {
  845. EVENT_HANDLER_CALLED_BY_CLIENT;
  846. BATTLE_EVENT_POSSIBLE_RETURN;
  847. battleInt->gateStateChanged(state);
  848. }
  849. void CPlayerInterface::yourTacticPhase(int distance)
  850. {
  851. THREAD_CREATED_BY_CLIENT;
  852. while(battleInt && battleInt->tacticsMode)
  853. boost::this_thread::sleep(boost::posix_time::millisec(1));
  854. }
  855. void CPlayerInterface::forceEndTacticPhase()
  856. {
  857. if (battleInt)
  858. battleInt->tacticsMode = false;
  859. }
  860. void CPlayerInterface::showInfoDialog(EInfoWindowMode type, const std::string &text, const std::vector<Component> & components, int soundID)
  861. {
  862. EVENT_HANDLER_CALLED_BY_CLIENT;
  863. bool autoTryHover = settings["gameTweaks"]["infoBarPick"].Bool() && type == EInfoWindowMode::AUTO;
  864. auto timer = type == EInfoWindowMode::INFO ? 3000 : 4500; //Implement long info windows like in HD mod
  865. if(autoTryHover || type == EInfoWindowMode::INFO)
  866. {
  867. waitWhileDialog(); //Fix for mantis #98
  868. adventureInt->showInfoBoxMessage(components, text, timer);
  869. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  870. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  871. return;
  872. }
  873. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  874. {
  875. return;
  876. }
  877. std::vector<Component> vect = components; //I do not know currently how to avoid copy here
  878. do
  879. {
  880. std::vector<Component> sender = {vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8))};
  881. std::vector<std::shared_ptr<CComponent>> intComps;
  882. for (auto & component : sender)
  883. intComps.push_back(std::make_shared<CComponent>(component));
  884. showInfoDialog(text,intComps,soundID);
  885. vect.erase(vect.begin(), vect.begin() + std::min(vect.size(), static_cast<size_t>(8)));
  886. }
  887. while(!vect.empty());
  888. }
  889. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  890. {
  891. std::vector<std::shared_ptr<CComponent>> intComps;
  892. intComps.push_back(component);
  893. showInfoDialog(text, intComps, soundBase::sound_todo);
  894. }
  895. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  896. {
  897. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  898. waitWhileDialog();
  899. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  900. {
  901. return;
  902. }
  903. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  904. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  905. {
  906. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  907. showingDialog->set(true);
  908. stopMovement(); // interrupt movement to show dialog
  909. GH.pushInt(temp);
  910. }
  911. else
  912. {
  913. dialogs.push_back(temp);
  914. }
  915. }
  916. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  917. {
  918. EVENT_HANDLER_CALLED_BY_CLIENT;
  919. std::string str;
  920. text.toString(str);
  921. showInfoDialog(EInfoWindowMode::MODAL, str, components, 0);
  922. waitWhileDialog();
  923. }
  924. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  925. {
  926. boost::unique_lock<boost::recursive_mutex> un(*pim);
  927. stopMovement();
  928. LOCPLINT->showingDialog->setn(true);
  929. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  930. }
  931. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  932. {
  933. EVENT_HANDLER_CALLED_BY_CLIENT;
  934. waitWhileDialog();
  935. stopMovement();
  936. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  937. if (!selection && cancel) //simple yes/no dialog
  938. {
  939. std::vector<std::shared_ptr<CComponent>> intComps;
  940. for (auto & component : components)
  941. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  942. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  943. }
  944. else if (selection)
  945. {
  946. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  947. for (auto & component : components)
  948. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  949. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  950. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  951. if (cancel)
  952. {
  953. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  954. }
  955. int charperline = 35;
  956. if (pom.size() > 1)
  957. charperline = 50;
  958. GH.pushIntT<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  959. intComps[0]->clickLeft(true, false);
  960. }
  961. }
  962. void CPlayerInterface::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  963. {
  964. EVENT_HANDLER_CALLED_BY_CLIENT;
  965. int choosenExit = -1;
  966. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  967. if (destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  968. choosenExit = vstd::find_pos(exits, neededExit);
  969. cb->selectionMade(choosenExit, askID);
  970. }
  971. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  972. {
  973. EVENT_HANDLER_CALLED_BY_CLIENT;
  974. auto selectCallback = [=](int selection)
  975. {
  976. JsonNode reply(JsonNode::JsonType::DATA_INTEGER);
  977. reply.Integer() = selection;
  978. cb->sendQueryReply(reply, askID);
  979. };
  980. auto cancelCallback = [=]()
  981. {
  982. JsonNode reply(JsonNode::JsonType::DATA_NULL);
  983. cb->sendQueryReply(reply, askID);
  984. };
  985. const std::string localTitle = title.toString();
  986. const std::string localDescription = description.toString();
  987. std::vector<int> tempList;
  988. tempList.reserve(objects.size());
  989. for(auto item : objects)
  990. tempList.push_back(item.getNum());
  991. CComponent localIconC(icon);
  992. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  993. localIconC.removeChild(localIcon.get(), false);
  994. std::shared_ptr<CObjectListWindow> wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback);
  995. wnd->onExit = cancelCallback;
  996. GH.pushInt(wnd);
  997. }
  998. void CPlayerInterface::tileRevealed(const std::unordered_set<int3> &pos)
  999. {
  1000. EVENT_HANDLER_CALLED_BY_CLIENT;
  1001. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  1002. adventureInt->onMapTilesChanged(pos);
  1003. }
  1004. void CPlayerInterface::tileHidden(const std::unordered_set<int3> &pos)
  1005. {
  1006. EVENT_HANDLER_CALLED_BY_CLIENT;
  1007. adventureInt->onMapTilesChanged(pos);
  1008. }
  1009. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  1010. {
  1011. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1012. GH.pushIntT<CHeroWindow>(hero);
  1013. }
  1014. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  1015. {
  1016. EVENT_HANDLER_CALLED_BY_CLIENT;
  1017. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  1018. {
  1019. CFortScreen * fortScreen = dynamic_cast<CFortScreen*>(GH.topInt().get());
  1020. CCastleInterface * castleInterface = dynamic_cast<CCastleInterface*>(GH.topInt().get());
  1021. if (fortScreen)
  1022. fortScreen->creaturesChangedEventHandler();
  1023. else if(castleInterface)
  1024. castleInterface->creaturesChangedEventHandler();
  1025. for(auto isa : GH.listInt)
  1026. {
  1027. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  1028. if (ki && townObj)
  1029. ki->townChanged(townObj);
  1030. }
  1031. }
  1032. else if(town && GH.listInt.size() && (town->ID == Obj::CREATURE_GENERATOR1
  1033. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  1034. {
  1035. CRecruitmentWindow *crw = dynamic_cast<CRecruitmentWindow*>(GH.topInt().get());
  1036. if (crw && crw->dwelling == town)
  1037. crw->availableCreaturesChanged();
  1038. }
  1039. }
  1040. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1041. {
  1042. EVENT_HANDLER_CALLED_BY_CLIENT;
  1043. if (bonus.type == Bonus::NONE)
  1044. return;
  1045. adventureInt->onHeroChanged(hero);
  1046. if ((bonus.type == Bonus::FLYING_MOVEMENT || bonus.type == Bonus::WATER_WALKING) && !gain)
  1047. {
  1048. //recalculate paths because hero has lost bonus influencing pathfinding
  1049. localState->erasePath(hero);
  1050. }
  1051. }
  1052. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  1053. {
  1054. EVENT_HANDLER_CALLED_BY_CLIENT;
  1055. h & localState;
  1056. }
  1057. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  1058. {
  1059. EVENT_HANDLER_CALLED_BY_CLIENT;
  1060. h & localState;
  1061. firstCall = -1;
  1062. }
  1063. void CPlayerInterface::moveHero( const CGHeroInstance *h, const CGPath& path )
  1064. {
  1065. LOG_TRACE(logGlobal);
  1066. if (!LOCPLINT->makingTurn)
  1067. return;
  1068. if (!h)
  1069. return; //can't find hero
  1070. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1071. if (showingDialog->get() || !dialogs.empty())
  1072. return;
  1073. setMovementStatus(true);
  1074. if (adventureInt)
  1075. adventureInt->onHeroWokeUp(h);
  1076. boost::thread moveHeroTask(std::bind(&CPlayerInterface::doMoveHero,this,h,path));
  1077. }
  1078. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1079. {
  1080. EVENT_HANDLER_CALLED_BY_CLIENT;
  1081. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1082. if (stillMoveHero.get() == DURING_MOVE && localState->hasPath(down) && localState->getPath(down).nodes.size() > 1) //to ignore calls on passing through garrisons
  1083. {
  1084. onEnd();
  1085. return;
  1086. }
  1087. waitForAllDialogs();
  1088. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1089. cgw->quit->addCallback(onEnd);
  1090. GH.pushInt(cgw);
  1091. }
  1092. /**
  1093. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1094. * into a combinational one on an artifact screen. Does not require the combination of
  1095. * artifacts to be legal.
  1096. */
  1097. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<bool()> onYes)
  1098. {
  1099. std::string text = artifact->getDescriptionTranslated();
  1100. text += "\n\n";
  1101. std::vector<std::shared_ptr<CComponent>> scs;
  1102. if(assembledArtifact)
  1103. {
  1104. // You possess all of the components to...
  1105. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getNameTranslated());
  1106. // Picture of assembled artifact at bottom.
  1107. auto sc = std::make_shared<CComponent>(CComponent::artifact, assembledArtifact->getIndex(), 0);
  1108. scs.push_back(sc);
  1109. }
  1110. else
  1111. {
  1112. // Do you wish to disassemble this artifact?
  1113. text += CGI->generaltexth->allTexts[733];
  1114. }
  1115. showYesNoDialog(text, onYes, nullptr, scs);
  1116. }
  1117. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1118. {
  1119. EVENT_HANDLER_CALLED_BY_CLIENT;
  1120. if (pa->packType == typeList.getTypeID<MoveHero>() && stillMoveHero.get() == DURING_MOVE
  1121. && destinationTeleport == ObjectInstanceID())
  1122. stillMoveHero.setn(CONTINUE_MOVE);
  1123. if (destinationTeleport != ObjectInstanceID()
  1124. && pa->packType == typeList.getTypeID<QueryReply>()
  1125. && stillMoveHero.get() == DURING_MOVE)
  1126. { // After teleportation via CGTeleport object is finished
  1127. destinationTeleport = ObjectInstanceID();
  1128. destinationTeleportPos = int3(-1);
  1129. stillMoveHero.setn(CONTINUE_MOVE);
  1130. }
  1131. }
  1132. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1133. {
  1134. EVENT_HANDLER_CALLED_BY_CLIENT;
  1135. GH.pushIntT<CExchangeWindow>(hero1, hero2, query);
  1136. }
  1137. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1138. {
  1139. EVENT_HANDLER_CALLED_BY_CLIENT;
  1140. //redraw minimap if owner changed
  1141. if (sop->what == ObjProperty::OWNER)
  1142. {
  1143. const CGObjectInstance * obj = cb->getObj(sop->id);
  1144. if(obj->ID == Obj::TOWN)
  1145. {
  1146. auto town = static_cast<const CGTownInstance *>(obj);
  1147. if(obj->tempOwner == playerID)
  1148. localState->ownedTowns.push_back(town);
  1149. else
  1150. localState->ownedTowns -= obj;
  1151. adventureInt->onTownChanged(town);
  1152. }
  1153. std::set<int3> pos = obj->getBlockedPos();
  1154. std::unordered_set<int3> upos(pos.begin(), pos.end());
  1155. adventureInt->onMapTilesChanged(upos);
  1156. assert(cb->getTownsInfo().size() == localState->ownedTowns.size());
  1157. }
  1158. }
  1159. void CPlayerInterface::initializeHeroTownList()
  1160. {
  1161. if(!localState->wanderingHeroes.size())
  1162. {
  1163. std::vector<const CGHeroInstance*> heroes = cb->getHeroesInfo();
  1164. for(auto & hero : heroes)
  1165. {
  1166. if(!hero->inTownGarrison)
  1167. localState->wanderingHeroes.push_back(hero);
  1168. }
  1169. }
  1170. if(!localState->ownedTowns.size())
  1171. localState->ownedTowns = cb->getTownsInfo();
  1172. if(adventureInt)
  1173. adventureInt->onHeroChanged(nullptr);
  1174. }
  1175. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  1176. {
  1177. EVENT_HANDLER_CALLED_BY_CLIENT;
  1178. waitWhileDialog();
  1179. auto recruitCb = [=](CreatureID id, int count)
  1180. {
  1181. LOCPLINT->cb->recruitCreatures(dwelling, dst, id, count, -1);
  1182. };
  1183. GH.pushIntT<CRecruitmentWindow>(dwelling, level, dst, recruitCb);
  1184. }
  1185. void CPlayerInterface::waitWhileDialog(bool unlockPim)
  1186. {
  1187. if (GH.amIGuiThread())
  1188. {
  1189. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1190. return;
  1191. }
  1192. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1193. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1194. while(showingDialog->data)
  1195. showingDialog->cond.wait(un);
  1196. }
  1197. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1198. {
  1199. EVENT_HANDLER_CALLED_BY_CLIENT;
  1200. auto state = obj->shipyardStatus();
  1201. TResources cost;
  1202. obj->getBoatCost(cost);
  1203. GH.pushIntT<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1204. }
  1205. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1206. {
  1207. EVENT_HANDLER_CALLED_BY_CLIENT;
  1208. //we might have built a boat in shipyard in opened town screen
  1209. if (obj->ID == Obj::BOAT
  1210. && LOCPLINT->castleInt
  1211. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1212. {
  1213. CCS->soundh->playSound(soundBase::newBuilding);
  1214. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1215. }
  1216. }
  1217. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1218. {
  1219. EVENT_HANDLER_CALLED_BY_CLIENT;
  1220. waitWhileDialog();
  1221. CCS->curh->hide();
  1222. adventureInt->centerOnTile(pos);
  1223. if (focusTime)
  1224. {
  1225. GH.totalRedraw();
  1226. {
  1227. auto unlockPim = vstd::makeUnlockGuard(*pim);
  1228. IgnoreEvents ignore(*this);
  1229. boost::this_thread::sleep(boost::posix_time::milliseconds(focusTime));
  1230. }
  1231. }
  1232. CCS->curh->show();
  1233. }
  1234. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj)
  1235. {
  1236. EVENT_HANDLER_CALLED_BY_CLIENT;
  1237. if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound())
  1238. {
  1239. waitWhileDialog();
  1240. CCS->soundh->playSound(obj->getRemovalSound().value());
  1241. }
  1242. CGI->mh->waitForOngoingAnimations();
  1243. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1244. {
  1245. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1246. heroKilled(h);
  1247. }
  1248. GH.fakeMouseMove();
  1249. }
  1250. void CPlayerInterface::objectRemovedAfter()
  1251. {
  1252. EVENT_HANDLER_CALLED_BY_CLIENT;
  1253. adventureInt->onMapTilesChanged(boost::none);
  1254. }
  1255. void CPlayerInterface::playerBlocked(int reason, bool start)
  1256. {
  1257. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1258. {
  1259. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1260. {
  1261. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1262. boost::unique_lock<boost::mutex> lock(eventsM); //TODO: copied from yourTurn, no idea if it's needed
  1263. LOCPLINT = this;
  1264. GH.curInt = this;
  1265. adventureInt->onCurrentPlayerChanged(playerID);
  1266. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1267. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1268. std::vector<std::shared_ptr<CComponent>> cmp;
  1269. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  1270. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1271. showInfoDialog(msg, cmp);
  1272. makingTurn = false;
  1273. }
  1274. }
  1275. }
  1276. void CPlayerInterface::update()
  1277. {
  1278. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1279. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1280. // While mutexes were locked away we may be have stopped being the active interface
  1281. if (LOCPLINT != this)
  1282. return;
  1283. //if there are any waiting dialogs, show them
  1284. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1285. {
  1286. showingDialog->set(true);
  1287. GH.pushInt(dialogs.front());
  1288. dialogs.pop_front();
  1289. }
  1290. assert(adventureInt);
  1291. // Handles mouse and key input
  1292. GH.updateTime();
  1293. GH.handleEvents();
  1294. GH.simpleRedraw();
  1295. }
  1296. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1297. {
  1298. using namespace boost::filesystem;
  1299. using namespace boost::algorithm;
  1300. path gamesDir = VCMIDirs::get().userSavePath();
  1301. std::map<std::time_t, int> dates; //save number => datestamp
  1302. const directory_iterator enddir;
  1303. if (!exists(gamesDir))
  1304. create_directory(gamesDir);
  1305. else
  1306. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1307. {
  1308. if (is_regular_file(dir->status()))
  1309. {
  1310. std::string name = dir->path().filename().string();
  1311. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1312. {
  1313. char nr = name[namePrefix.size()];
  1314. if (std::isdigit(nr))
  1315. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1316. }
  1317. }
  1318. }
  1319. if (!dates.empty())
  1320. return (--dates.end())->second; //return latest file number
  1321. return 0;
  1322. }
  1323. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1324. {
  1325. EVENT_HANDLER_CALLED_BY_CLIENT;
  1326. if (player == playerID)
  1327. {
  1328. if (victoryLossCheckResult.loss())
  1329. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1330. assert(GH.curInt == LOCPLINT);
  1331. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1332. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1333. GH.curInt = this; //waiting for dialogs requires this to get events
  1334. if(!makingTurn)
  1335. {
  1336. makingTurn = true; //also needed for dialog to show with current implementation
  1337. waitForAllDialogs();
  1338. makingTurn = false;
  1339. }
  1340. else
  1341. waitForAllDialogs();
  1342. GH.curInt = previousInterface;
  1343. LOCPLINT = previousInterface;
  1344. if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1345. {
  1346. if(adventureInt)
  1347. {
  1348. GH.terminate_cond->setn(true);
  1349. GH.popInts(GH.listInt.size());
  1350. adventureInt.reset();
  1351. }
  1352. }
  1353. if (victoryLossCheckResult.victory() && LOCPLINT == this)
  1354. {
  1355. // end game if current human player has won
  1356. CSH->sendClientDisconnecting();
  1357. requestReturningToMainMenu(true);
  1358. }
  1359. else if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool())
  1360. {
  1361. //all human players eliminated
  1362. CSH->sendClientDisconnecting();
  1363. requestReturningToMainMenu(false);
  1364. }
  1365. if (GH.curInt == this)
  1366. GH.curInt = nullptr;
  1367. }
  1368. else
  1369. {
  1370. if (victoryLossCheckResult.loss() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME) //enemy has lost
  1371. {
  1372. std::string str = victoryLossCheckResult.messageToSelf;
  1373. boost::algorithm::replace_first(str, "%s", CGI->generaltexth->capColors[player.getNum()]);
  1374. showInfoDialog(str, std::vector<std::shared_ptr<CComponent>>(1, std::make_shared<CComponent>(CComponent::flag, player.getNum(), 0)));
  1375. }
  1376. }
  1377. }
  1378. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1379. {
  1380. EVENT_HANDLER_CALLED_BY_CLIENT;
  1381. }
  1382. void CPlayerInterface::showPuzzleMap()
  1383. {
  1384. EVENT_HANDLER_CALLED_BY_CLIENT;
  1385. waitWhileDialog();
  1386. //TODO: interface should not know the real position of Grail...
  1387. double ratio = 0;
  1388. int3 grailPos = cb->getGrailPos(&ratio);
  1389. GH.pushIntT<CPuzzleWindow>(grailPos, ratio);
  1390. }
  1391. void CPlayerInterface::viewWorldMap()
  1392. {
  1393. adventureInt->openWorldView();
  1394. }
  1395. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  1396. {
  1397. EVENT_HANDLER_CALLED_BY_CLIENT;
  1398. if(dynamic_cast<CSpellWindow *>(GH.topInt().get()))
  1399. GH.popInts(1);
  1400. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1401. localState->erasePath(caster);
  1402. const spells::Spell * spell = CGI->spells()->getByIndex(spellID);
  1403. auto castSoundPath = spell->getCastSound();
  1404. if(!castSoundPath.empty())
  1405. CCS->soundh->playSound(castSoundPath);
  1406. }
  1407. void CPlayerInterface::tryDiggging(const CGHeroInstance * h)
  1408. {
  1409. int msgToShow = -1;
  1410. const auto diggingStatus = h->diggingStatus();
  1411. switch(diggingStatus)
  1412. {
  1413. case EDiggingStatus::CAN_DIG:
  1414. break;
  1415. case EDiggingStatus::LACK_OF_MOVEMENT:
  1416. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1417. break;
  1418. case EDiggingStatus::TILE_OCCUPIED:
  1419. msgToShow = 97; //Try searching on clear ground.
  1420. break;
  1421. case EDiggingStatus::WRONG_TERRAIN:
  1422. msgToShow = 60; ////Try looking on land!
  1423. break;
  1424. case EDiggingStatus::BACKPACK_IS_FULL:
  1425. msgToShow = 247; //Searching for the Grail is fruitless...
  1426. break;
  1427. default:
  1428. assert(0);
  1429. }
  1430. if(msgToShow < 0)
  1431. cb->dig(h);
  1432. else
  1433. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1434. }
  1435. void CPlayerInterface::battleNewRoundFirst( int round )
  1436. {
  1437. EVENT_HANDLER_CALLED_BY_CLIENT;
  1438. BATTLE_EVENT_POSSIBLE_RETURN;
  1439. battleInt->newRoundFirst(round);
  1440. }
  1441. void CPlayerInterface::stopMovement()
  1442. {
  1443. if (stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  1444. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  1445. }
  1446. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  1447. {
  1448. EVENT_HANDLER_CALLED_BY_CLIENT;
  1449. if (market->o->ID == Obj::ALTAR_OF_SACRIFICE)
  1450. {
  1451. //EEMarketMode mode = market->availableModes().front();
  1452. if (market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1453. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::ARTIFACT_EXP);
  1454. else if (market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1455. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::CREATURE_EXP);
  1456. }
  1457. else
  1458. {
  1459. GH.pushIntT<CMarketplaceWindow>(market, visitor, market->availableModes().front());
  1460. }
  1461. }
  1462. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  1463. {
  1464. EVENT_HANDLER_CALLED_BY_CLIENT;
  1465. GH.pushIntT<CUniversityWindow>(visitor, market);
  1466. }
  1467. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1468. {
  1469. EVENT_HANDLER_CALLED_BY_CLIENT;
  1470. GH.pushIntT<CHillFortWindow>(visitor, object);
  1471. }
  1472. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1473. {
  1474. EVENT_HANDLER_CALLED_BY_CLIENT;
  1475. if (CMarketplaceWindow *cmw = dynamic_cast<CMarketplaceWindow*>(GH.topInt().get()))
  1476. cmw->artifactsChanged(false);
  1477. }
  1478. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  1479. {
  1480. EVENT_HANDLER_CALLED_BY_CLIENT;
  1481. GH.pushIntT<CTavernWindow>(townOrTavern);
  1482. }
  1483. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1484. {
  1485. EVENT_HANDLER_CALLED_BY_CLIENT;
  1486. GH.pushIntT<CThievesGuildWindow>(obj);
  1487. }
  1488. void CPlayerInterface::showQuestLog()
  1489. {
  1490. EVENT_HANDLER_CALLED_BY_CLIENT;
  1491. GH.pushIntT<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1492. }
  1493. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1494. {
  1495. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1496. {
  1497. MetaString txt;
  1498. obj->getProblemText(txt);
  1499. showInfoDialog(txt.toString());
  1500. }
  1501. else
  1502. showShipyardDialog(obj);
  1503. }
  1504. void CPlayerInterface::requestReturningToMainMenu(bool won)
  1505. {
  1506. if(won && cb->getStartInfo()->campState)
  1507. CSH->startCampaignScenario(cb->getStartInfo()->campState);
  1508. else
  1509. GH.pushUserEvent(EUserEvent::RETURN_TO_MAIN_MENU);
  1510. }
  1511. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1512. {
  1513. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1514. if(hero)
  1515. {
  1516. auto art = hero->getArt(al.slot);
  1517. if(art == nullptr)
  1518. {
  1519. logGlobal->error("artifact location %d points to nothing",
  1520. al.slot.num);
  1521. return;
  1522. }
  1523. CHeroArtPlace::askToAssemble(hero, al.slot);
  1524. }
  1525. }
  1526. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1527. {
  1528. EVENT_HANDLER_CALLED_BY_CLIENT;
  1529. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1530. adventureInt->onHeroChanged(hero);
  1531. }
  1532. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1533. {
  1534. EVENT_HANDLER_CALLED_BY_CLIENT;
  1535. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1536. adventureInt->onHeroChanged(hero);
  1537. for(auto isa : GH.listInt)
  1538. {
  1539. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1540. if (artWin)
  1541. artWin->artifactRemoved(al);
  1542. }
  1543. waitWhileDialog();
  1544. }
  1545. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1546. {
  1547. EVENT_HANDLER_CALLED_BY_CLIENT;
  1548. auto hero = std::visit(HeroObjectRetriever(), dst.artHolder);
  1549. adventureInt->onHeroChanged(hero);
  1550. bool redraw = true;
  1551. // If a bulk transfer has arrived, then redrawing only the last art movement.
  1552. if(numOfMovedArts != 0)
  1553. {
  1554. numOfMovedArts--;
  1555. if(numOfMovedArts != 0)
  1556. redraw = false;
  1557. }
  1558. for(auto isa : GH.listInt)
  1559. {
  1560. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1561. if (artWin)
  1562. artWin->artifactMoved(src, dst, redraw);
  1563. }
  1564. waitWhileDialog();
  1565. }
  1566. void CPlayerInterface::bulkArtMovementStart(size_t numOfArts)
  1567. {
  1568. numOfMovedArts = numOfArts;
  1569. }
  1570. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1571. {
  1572. EVENT_HANDLER_CALLED_BY_CLIENT;
  1573. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1574. adventureInt->onHeroChanged(hero);
  1575. for(auto isa : GH.listInt)
  1576. {
  1577. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1578. if (artWin)
  1579. artWin->artifactAssembled(al);
  1580. }
  1581. }
  1582. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1583. {
  1584. EVENT_HANDLER_CALLED_BY_CLIENT;
  1585. auto hero = std::visit(HeroObjectRetriever(), al.artHolder);
  1586. adventureInt->onHeroChanged(hero);
  1587. for(auto isa : GH.listInt)
  1588. {
  1589. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1590. if (artWin)
  1591. artWin->artifactDisassembled(al);
  1592. }
  1593. }
  1594. void CPlayerInterface::waitForAllDialogs(bool unlockPim)
  1595. {
  1596. while(!dialogs.empty())
  1597. {
  1598. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1599. boost::this_thread::sleep(boost::posix_time::milliseconds(5));
  1600. }
  1601. waitWhileDialog(unlockPim);
  1602. }
  1603. void CPlayerInterface::proposeLoadingGame()
  1604. {
  1605. showYesNoDialog(CGI->generaltexth->allTexts[68], [](){ GH.pushUserEvent(EUserEvent::RETURN_TO_MENU_LOAD); }, nullptr);
  1606. }
  1607. bool CPlayerInterface::capturedAllEvents()
  1608. {
  1609. if(duringMovement)
  1610. {
  1611. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1612. return true;
  1613. }
  1614. bool needToLockAdventureMap = adventureInt && adventureInt->active && CGI->mh->hasOngoingAnimations();
  1615. if (ignoreEvents || needToLockAdventureMap || isAutoFightOn)
  1616. {
  1617. boost::unique_lock<boost::mutex> un(eventsM);
  1618. while(!SDLEventsQueue.empty())
  1619. {
  1620. SDLEventsQueue.pop();
  1621. }
  1622. return true;
  1623. }
  1624. return false;
  1625. }
  1626. void CPlayerInterface::setMovementStatus(bool value)
  1627. {
  1628. duringMovement = value;
  1629. if (value)
  1630. {
  1631. CCS->curh->hide();
  1632. }
  1633. else
  1634. {
  1635. CCS->curh->show();
  1636. }
  1637. }
  1638. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  1639. {
  1640. int i = 1;
  1641. auto getObj = [&](int3 coord, bool ignoreHero)
  1642. {
  1643. return cb->getTile(h->convertToVisitablePos(coord))->topVisitableObj(ignoreHero);
  1644. };
  1645. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1646. {
  1647. if (action != CGPathNode::TELEPORT_NORMAL &&
  1648. action != CGPathNode::TELEPORT_BLOCKING_VISIT &&
  1649. action != CGPathNode::TELEPORT_BATTLE)
  1650. {
  1651. return false;
  1652. }
  1653. return true;
  1654. };
  1655. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1656. {
  1657. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  1658. return nextObjectTop;
  1659. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  1660. CGTeleport::isConnected(currentObject, nextObject))
  1661. {
  1662. return nextObject;
  1663. }
  1664. return nullptr;
  1665. };
  1666. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  1667. stillMoveHero.data = CONTINUE_MOVE;
  1668. auto doMovement = [&](int3 dst, bool transit)
  1669. {
  1670. stillMoveHero.data = WAITING_MOVE;
  1671. cb->moveHero(h, dst, transit);
  1672. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  1673. stillMoveHero.cond.wait(un);
  1674. };
  1675. {
  1676. for (auto & elem : path.nodes)
  1677. elem.coord = h->convertFromVisitablePos(elem.coord);
  1678. TerrainId currentTerrain = ETerrainId::NONE;
  1679. TerrainId newTerrain;
  1680. bool wasOnRoad = true;
  1681. int sh = -1;
  1682. auto canStop = [&](CGPathNode * node) -> bool
  1683. {
  1684. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  1685. return true;
  1686. if (node->accessible == CGPathNode::ACCESSIBLE)
  1687. return true;
  1688. return false;
  1689. };
  1690. for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  1691. {
  1692. int3 prevCoord = path.nodes[i].coord;
  1693. int3 nextCoord = path.nodes[i-1].coord;
  1694. auto prevRoad = cb->getTile(h->convertToVisitablePos(prevCoord))->roadType;
  1695. auto nextRoad = cb->getTile(h->convertToVisitablePos(nextCoord))->roadType;
  1696. bool movingOnRoad = prevRoad->getId() != Road::NO_ROAD && nextRoad->getId() != Road::NO_ROAD;
  1697. auto prevObject = getObj(prevCoord, prevCoord == h->pos);
  1698. auto nextObjectTop = getObj(nextCoord, false);
  1699. auto nextObject = getObj(nextCoord, true);
  1700. auto destTeleportObj = getDestTeleportObj(prevObject, nextObjectTop, nextObject);
  1701. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  1702. {
  1703. CCS->soundh->stopSound(sh);
  1704. destinationTeleport = destTeleportObj->id;
  1705. destinationTeleportPos = nextCoord;
  1706. doMovement(h->pos, false);
  1707. if (path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT
  1708. || path.nodes[i-1].action == CGPathNode::TELEPORT_BATTLE)
  1709. {
  1710. destinationTeleport = ObjectInstanceID();
  1711. destinationTeleportPos = int3(-1);
  1712. }
  1713. if(i != path.nodes.size() - 1)
  1714. {
  1715. if (movingOnRoad)
  1716. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(currentTerrain)->horseSound, -1);
  1717. else
  1718. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(currentTerrain)->horseSoundPenalty, -1);
  1719. }
  1720. continue;
  1721. }
  1722. if (path.nodes[i-1].turns)
  1723. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1724. stillMoveHero.data = STOP_MOVE;
  1725. break;
  1726. }
  1727. // Start a new sound for the hero movement or let the existing one carry on.
  1728. #if 0
  1729. // TODO
  1730. if (hero is flying && sh == -1)
  1731. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  1732. #endif
  1733. {
  1734. newTerrain = cb->getTile(h->convertToVisitablePos(prevCoord))->terType->getId();
  1735. if(newTerrain != currentTerrain || wasOnRoad != movingOnRoad)
  1736. {
  1737. CCS->soundh->stopSound(sh);
  1738. if (movingOnRoad)
  1739. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(newTerrain)->horseSound, -1);
  1740. else
  1741. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(newTerrain)->horseSoundPenalty, -1);
  1742. currentTerrain = newTerrain;
  1743. wasOnRoad = movingOnRoad;
  1744. }
  1745. }
  1746. assert(h->pos.z == nextCoord.z); // Z should change only if it's movement via teleporter and in this case this code shouldn't be executed at all
  1747. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  1748. logGlobal->trace("Requesting hero movement to %s", endpos.toString());
  1749. bool useTransit = false;
  1750. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  1751. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  1752. || CGTeleport::isTeleport(nextObjectTop)))
  1753. { // Hero should be able to go through object if it's allow transit
  1754. useTransit = true;
  1755. }
  1756. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  1757. useTransit = true;
  1758. doMovement(endpos, useTransit);
  1759. logGlobal->trace("Resuming %s", __FUNCTION__);
  1760. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  1761. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  1762. break;
  1763. }
  1764. CCS->soundh->stopSound(sh);
  1765. }
  1766. //Update cursor so icon can change if needed when it reappears; doesn;'t apply if a dialog box pops up at the end of the movement
  1767. if (!showingDialog->get())
  1768. GH.fakeMouseMove();
  1769. CGI->mh->waitForOngoingAnimations();
  1770. setMovementStatus(false);
  1771. }
  1772. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions, bool showTerrain)
  1773. {
  1774. EVENT_HANDLER_CALLED_BY_CLIENT;
  1775. adventureInt->openWorldView(objectPositions, showTerrain );
  1776. }