CPlayerInterface.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526
  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 <vcmi/Artifact.h>
  12. #include "adventureMap/CAdvMapInt.h"
  13. #include "adventureMap/mapHandler.h"
  14. #include "battle/BattleInterface.h"
  15. #include "battle/BattleEffectsController.h"
  16. #include "battle/BattleFieldController.h"
  17. #include "battle/BattleInterfaceClasses.h"
  18. #include "battle/BattleWindow.h"
  19. #include "../CCallback.h"
  20. #include "windows/CCastleInterface.h"
  21. #include "gui/CursorHandler.h"
  22. #include "windows/CKingdomInterface.h"
  23. #include "CGameInfo.h"
  24. #include "CMT.h"
  25. #include "windows/CHeroWindow.h"
  26. #include "windows/CCreatureWindow.h"
  27. #include "windows/CQuestLog.h"
  28. #include "CPlayerInterface.h"
  29. #include "widgets/CComponent.h"
  30. #include "widgets/Buttons.h"
  31. #include "windows/CTradeWindow.h"
  32. #include "windows/CSpellWindow.h"
  33. #include "../lib/CConfigHandler.h"
  34. #include "windows/GUIClasses.h"
  35. #include "render/CAnimation.h"
  36. #include "render/IImage.h"
  37. #include "../lib/CArtHandler.h"
  38. #include "../lib/CGeneralTextHandler.h"
  39. #include "../lib/CHeroHandler.h"
  40. #include "../lib/serializer/CTypeList.h"
  41. #include "../lib/serializer/BinaryDeserializer.h"
  42. #include "../lib/serializer/BinarySerializer.h"
  43. #include "../lib/spells/CSpellHandler.h"
  44. #include "../lib/CTownHandler.h"
  45. #include "../lib/mapObjects/CObjectClassesHandler.h" // For displaying correct UI when interacting with objects
  46. #include "../lib/CStack.h"
  47. #include "../lib/JsonNode.h"
  48. #include "CMusicHandler.h"
  49. #include "../lib/CondSh.h"
  50. #include "../lib/NetPacksBase.h"
  51. #include "../lib/NetPacks.h"//todo: remove
  52. #include "../lib/mapping/CMap.h"
  53. #include "../lib/VCMIDirs.h"
  54. #include "../lib/CStopWatch.h"
  55. #include "../lib/StartInfo.h"
  56. #include "../lib/CPlayerState.h"
  57. #include "../lib/GameConstants.h"
  58. #include "gui/CGuiHandler.h"
  59. #include "windows/InfoWindows.h"
  60. #include "../lib/UnlockGuard.h"
  61. #include "../lib/CPathfinder.h"
  62. #include "../lib/RoadHandler.h"
  63. #include "../lib/TerrainHandler.h"
  64. #include "CServerHandler.h"
  65. // FIXME: only needed for CGameState::mutex
  66. #include "../lib/CGameState.h"
  67. #include "gui/NotificationHandler.h"
  68. #include "adventureMap/CInGameConsole.h"
  69. #include <SDL_events.h>
  70. // The macro below is used to mark functions that are called by client when game state changes.
  71. // They all assume that CPlayerInterface::pim mutex is locked.
  72. #define EVENT_HANDLER_CALLED_BY_CLIENT
  73. // The macro marks functions that are run on a new thread by client.
  74. // They do not own any mutexes intiially.
  75. #define THREAD_CREATED_BY_CLIENT
  76. #define RETURN_IF_QUICK_COMBAT \
  77. if (isAutoFightOn && !battleInt) \
  78. return;
  79. #define BATTLE_EVENT_POSSIBLE_RETURN\
  80. if (LOCPLINT != this) \
  81. return; \
  82. RETURN_IF_QUICK_COMBAT
  83. extern std::queue<SDL_Event> SDLEventsQueue;
  84. extern boost::mutex eventsM;
  85. boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
  86. CPlayerInterface * LOCPLINT;
  87. std::shared_ptr<BattleInterface> CPlayerInterface::battleInt;
  88. enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
  89. CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
  90. static bool objectBlitOrderSorter(const TerrainTileObject & a, const TerrainTileObject & b)
  91. {
  92. return CMapHandler::compareObjectBlitOrder(a.obj, b.obj);
  93. }
  94. struct HeroObjectRetriever : boost::static_visitor<const CGHeroInstance *>
  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. {
  107. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.getStr());
  108. destinationTeleport = ObjectInstanceID();
  109. destinationTeleportPos = int3(-1);
  110. GH.defActionsDef = 0;
  111. LOCPLINT = this;
  112. curAction = nullptr;
  113. playerID=Player;
  114. human=true;
  115. currentSelection = nullptr;
  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. }
  128. CPlayerInterface::~CPlayerInterface()
  129. {
  130. if(CCS && CCS->soundh)
  131. CCS->soundh->ambientStopAllChannels();
  132. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.getStr());
  133. delete showingDialog;
  134. delete cingconsole;
  135. if (LOCPLINT == this)
  136. LOCPLINT = nullptr;
  137. }
  138. void CPlayerInterface::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  139. {
  140. cb = CB;
  141. env = ENV;
  142. CCS->musich->loadTerrainMusicThemes();
  143. initializeHeroTownList();
  144. // always recreate advmap interface to avoid possible memory-corruption bugs
  145. adventureInt.reset(new CAdvMapInt());
  146. }
  147. void CPlayerInterface::yourTurn()
  148. {
  149. EVENT_HANDLER_CALLED_BY_CLIENT;
  150. {
  151. boost::unique_lock<boost::mutex> lock(eventsM); //block handling events until interface is ready
  152. LOCPLINT = this;
  153. GH.curInt = this;
  154. adventureInt->selection = nullptr;
  155. NotificationHandler::notify("Your turn");
  156. std::string prefix = settings["session"]["saveprefix"].String();
  157. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  158. if (firstCall)
  159. {
  160. if(CSH->howManyPlayerInterfaces() == 1)
  161. adventureInt->setPlayer(playerID);
  162. autosaveCount = getLastIndex(prefix + "Autosave_");
  163. if (firstCall > 0) //new game, not loaded
  164. {
  165. int index = getLastIndex(prefix + "Newgame_");
  166. index %= SAVES_COUNT;
  167. cb->save("Saves/" + prefix + "Newgame_Autosave_" + boost::lexical_cast<std::string>(index + 1));
  168. }
  169. firstCall = 0;
  170. }
  171. else if(frequency > 0 && cb->getDate() % frequency == 0)
  172. {
  173. LOCPLINT->cb->save("Saves/" + prefix + "Autosave_" + boost::lexical_cast<std::string>(autosaveCount++ + 1));
  174. autosaveCount %= 5;
  175. }
  176. if (adventureInt->player != playerID)
  177. adventureInt->setPlayer(playerID);
  178. if (CSH->howManyPlayerInterfaces() > 1) //hot seat message
  179. {
  180. adventureInt->startHotSeatWait(playerID);
  181. makingTurn = true;
  182. std::string msg = CGI->generaltexth->allTexts[13];
  183. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  184. std::vector<std::shared_ptr<CComponent>> cmp;
  185. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  186. showInfoDialog(msg, cmp);
  187. }
  188. else
  189. {
  190. makingTurn = true;
  191. adventureInt->startTurn();
  192. }
  193. }
  194. acceptTurn();
  195. }
  196. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  197. {
  198. EVENT_HANDLER_CALLED_BY_CLIENT;
  199. waitWhileDialog();
  200. if(LOCPLINT != this)
  201. return;
  202. //FIXME: read once and store
  203. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  204. return;
  205. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  206. int3 hp = details.start;
  207. if(!hero)
  208. {
  209. //AI hero left the visible area (we can't obtain info)
  210. //TODO very evil workaround -> retrieve pointer to hero so we could animate it
  211. // TODO -> we should not need full CGHeroInstance structure to display animation or it should not be handled by playerint (but by the client itself)
  212. const TerrainTile2 & tile = CGI->mh->ttiles[hp.z][hp.x - 1][hp.y];
  213. for(auto & elem : tile.objects)
  214. if(elem.obj && elem.obj->id == details.id)
  215. hero = dynamic_cast<const CGHeroInstance *>(elem.obj);
  216. if(!hero) //still nothing...
  217. return;
  218. }
  219. bool directlyAttackingCreature =
  220. details.attackedFrom
  221. && adventureInt->terrain.currentPath //in case if movement has been canceled in the meantime and path was already erased
  222. && adventureInt->terrain.currentPath->nodes.size() == 3;//FIXME should be 2 but works nevertheless...
  223. if(makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
  224. {
  225. updateAmbientSounds();
  226. //We may need to change music - select new track, music handler will change it if needed
  227. CCS->musich->playMusicFromSet("terrain", LOCPLINT->cb->getTile(hero->visitablePos())->terType->getJsonKey(), true, false);
  228. if(details.result == TryMoveHero::TELEPORTATION)
  229. {
  230. if(adventureInt->terrain.currentPath)
  231. {
  232. assert(adventureInt->terrain.currentPath->nodes.size() >= 2);
  233. std::vector<CGPathNode>::const_iterator nodesIt = adventureInt->terrain.currentPath->nodes.end() - 1;
  234. if((nodesIt)->coord == hero->convertToVisitablePos(details.start)
  235. && (nodesIt - 1)->coord == hero->convertToVisitablePos(details.end))
  236. {
  237. //path was between entrance and exit of teleport -> OK, erase node as usual
  238. removeLastNodeFromPath(hero);
  239. }
  240. else
  241. {
  242. //teleport was not along current path, it'll now be invalid (hero is somewhere else)
  243. eraseCurrentPathOf(hero);
  244. }
  245. }
  246. adventureInt->centerOn(hero, true); //actualizing screen pos
  247. adventureInt->minimap.redraw();
  248. adventureInt->heroList.update(hero);
  249. return; //teleport - no fancy moving animation
  250. //TODO: smooth disappear / appear effect
  251. }
  252. if(hero->pos != details.end //hero didn't change tile but visit succeeded
  253. || directlyAttackingCreature) // or creature was attacked from endangering tile.
  254. {
  255. eraseCurrentPathOf(hero, false);
  256. }
  257. else if(adventureInt->terrain.currentPath && hero->pos == details.end) //&& hero is moving
  258. {
  259. if(details.start != details.end) //so we don't touch path when revisiting with spacebar
  260. removeLastNodeFromPath(hero);
  261. }
  262. }
  263. if(details.stopMovement()) //hero failed to move
  264. {
  265. hero->isStanding = true;
  266. stillMoveHero.setn(STOP_MOVE);
  267. GH.totalRedraw();
  268. adventureInt->heroList.update(hero);
  269. return;
  270. }
  271. ui32 speed = 0;
  272. if(settings["session"]["spectate"].Bool())
  273. {
  274. if(!settings["session"]["spectate-hero-speed"].isNull())
  275. speed = static_cast<ui32>(settings["session"]["spectate-hero-speed"].Integer());
  276. }
  277. else if(makingTurn) // our turn, our hero moves
  278. speed = static_cast<ui32>(settings["adventure"]["heroSpeed"].Float());
  279. else
  280. speed = static_cast<ui32>(settings["adventure"]["enemySpeed"].Float());
  281. if(speed == 0)
  282. {
  283. //FIXME: is this a proper solution?
  284. CGI->mh->hideObject(hero);
  285. CGI->mh->printObject(hero);
  286. return; // no animation
  287. }
  288. adventureInt->centerOn(hero); //actualizing screen pos
  289. adventureInt->minimap.redraw();
  290. adventureInt->heroList.redraw();
  291. initMovement(details, hero, hp);
  292. auto waitFrame = [&]()
  293. {
  294. int frameNumber = GH.mainFPSmng->getFrameNumber();
  295. auto unlockPim = vstd::makeUnlockGuard(*pim);
  296. while(frameNumber == GH.mainFPSmng->getFrameNumber())
  297. boost::this_thread::sleep(boost::posix_time::milliseconds(5));
  298. };
  299. //first initializing done
  300. //main moving
  301. for(int i = 1; i < 32; i += 2 * speed)
  302. {
  303. movementPxStep(details, i, hp, hero);
  304. #ifndef VCMI_ANDROID
  305. // currently android doesn't seem to be able to handle all these full redraws here, so let's disable it so at least it looks less choppy;
  306. // most likely this is connected with the way that this manual animation+framerate handling is solved
  307. adventureInt->updateScreen = true;
  308. #endif
  309. //evil returns here ...
  310. //todo: get rid of it
  311. waitFrame(); //for animation purposes
  312. }
  313. //main moving done
  314. //finishing move
  315. finishMovement(details, hp, hero);
  316. hero->isStanding = true;
  317. //move finished
  318. adventureInt->minimap.redraw();
  319. adventureInt->heroList.update(hero);
  320. //check if user cancelled movement
  321. {
  322. boost::unique_lock<boost::mutex> un(eventsM);
  323. while(!SDLEventsQueue.empty())
  324. {
  325. SDL_Event ev = SDLEventsQueue.front();
  326. SDLEventsQueue.pop();
  327. switch(ev.type)
  328. {
  329. case SDL_MOUSEBUTTONDOWN:
  330. stillMoveHero.setn(STOP_MOVE);
  331. break;
  332. case SDL_KEYDOWN:
  333. if (ev.key.keysym.sym < SDLK_F1 || ev.key.keysym.sym > SDLK_F15)
  334. stillMoveHero.setn(STOP_MOVE);
  335. break;
  336. }
  337. }
  338. }
  339. if (stillMoveHero.get() == WAITING_MOVE)
  340. stillMoveHero.setn(DURING_MOVE);
  341. // Hero attacked creature directly, set direction to face it.
  342. if (directlyAttackingCreature) {
  343. // Get direction to attacker.
  344. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  345. static const ui8 dirLookup[3][3] = {
  346. { 1, 2, 3 },
  347. { 8, 0, 4 },
  348. { 7, 6, 5 }
  349. };
  350. // FIXME: Avoid const_cast, make moveDir mutable in some other way?
  351. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  352. }
  353. }
  354. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  355. {
  356. EVENT_HANDLER_CALLED_BY_CLIENT;
  357. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->getNameTranslated() % playerID);
  358. const CArmedInstance *newSelection = nullptr;
  359. if (makingTurn)
  360. {
  361. //find new object for selection: either hero
  362. int next = adventureInt->getNextHeroIndex(vstd::find_pos(wanderingHeroes, hero));
  363. if (next >= 0)
  364. newSelection = wanderingHeroes[next];
  365. //or town
  366. if (!newSelection || newSelection == hero)
  367. {
  368. if (towns.empty())
  369. newSelection = nullptr;
  370. else
  371. newSelection = towns.front();
  372. }
  373. }
  374. wanderingHeroes -= hero;
  375. adventureInt->heroList.update(hero);
  376. if (makingTurn && newSelection)
  377. adventureInt->select(newSelection, true);
  378. else if (adventureInt->selection == hero)
  379. adventureInt->selection = nullptr;
  380. if (vstd::contains(paths, hero))
  381. paths.erase(hero);
  382. }
  383. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  384. {
  385. EVENT_HANDLER_CALLED_BY_CLIENT;
  386. if(start && visitedObj)
  387. {
  388. if(visitedObj->getVisitSound())
  389. CCS->soundh->playSound(visitedObj->getVisitSound().get());
  390. }
  391. }
  392. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  393. {
  394. EVENT_HANDLER_CALLED_BY_CLIENT;
  395. wanderingHeroes.push_back(hero);
  396. adventureInt->heroList.update(hero);
  397. }
  398. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  399. {
  400. if(castleInt)
  401. castleInt->close();
  402. castleInt = nullptr;
  403. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  404. GH.pushInt(newCastleInt);
  405. }
  406. int3 CPlayerInterface::repairScreenPos(int3 pos)
  407. {
  408. if (pos.x<-CGI->mh->frameW)
  409. pos.x = -CGI->mh->frameW;
  410. if (pos.y<-CGI->mh->frameH)
  411. pos.y = -CGI->mh->frameH;
  412. if (pos.x>CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW)
  413. pos.x = CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW;
  414. if (pos.y>CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH)
  415. pos.y = CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH;
  416. return pos;
  417. }
  418. void CPlayerInterface::activateForSpectator()
  419. {
  420. adventureInt->state = CAdvMapInt::INGAME;
  421. adventureInt->activate();
  422. adventureInt->minimap.activate();
  423. }
  424. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  425. {
  426. EVENT_HANDLER_CALLED_BY_CLIENT;
  427. if (which == 4)
  428. {
  429. if (CAltarWindow *ctw = dynamic_cast<CAltarWindow *>(GH.topInt().get()))
  430. ctw->setExpToLevel();
  431. }
  432. else if (which < GameConstants::PRIMARY_SKILLS) //no need to redraw infowin if this is experience (exp is treated as prim skill with id==4)
  433. updateInfo(hero);
  434. }
  435. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  436. {
  437. EVENT_HANDLER_CALLED_BY_CLIENT;
  438. CUniversityWindow* cuw = dynamic_cast<CUniversityWindow*>(GH.topInt().get());
  439. if (cuw) //university window is open
  440. {
  441. GH.totalRedraw();
  442. }
  443. }
  444. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  445. {
  446. EVENT_HANDLER_CALLED_BY_CLIENT;
  447. updateInfo(hero);
  448. if (makingTurn && hero->tempOwner == playerID)
  449. adventureInt->heroList.update(hero);
  450. }
  451. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  452. {
  453. EVENT_HANDLER_CALLED_BY_CLIENT;
  454. if (makingTurn && hero->tempOwner == playerID)
  455. adventureInt->heroList.update(hero);
  456. }
  457. void CPlayerInterface::receivedResource()
  458. {
  459. EVENT_HANDLER_CALLED_BY_CLIENT;
  460. if (CMarketplaceWindow *mw = dynamic_cast<CMarketplaceWindow *>(GH.topInt().get()))
  461. mw->resourceChanged();
  462. GH.totalRedraw();
  463. }
  464. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  465. {
  466. EVENT_HANDLER_CALLED_BY_CLIENT;
  467. waitWhileDialog();
  468. CCS->soundh->playSound(soundBase::heroNewLevel);
  469. GH.pushIntT<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  470. {
  471. cb->selectionMade(selection, queryID);
  472. });
  473. }
  474. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  475. {
  476. EVENT_HANDLER_CALLED_BY_CLIENT;
  477. waitWhileDialog();
  478. CCS->soundh->playSound(soundBase::heroNewLevel);
  479. GH.pushIntT<CStackWindow>(commander, skills, [=](ui32 selection)
  480. {
  481. cb->selectionMade(selection, queryID);
  482. });
  483. }
  484. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  485. {
  486. EVENT_HANDLER_CALLED_BY_CLIENT;
  487. updateInfo(town);
  488. if (town->garrisonHero) //wandering hero moved to the garrison
  489. {
  490. CGI->mh->hideObject(town->garrisonHero);
  491. if (town->garrisonHero->tempOwner == playerID && vstd::contains(wanderingHeroes,town->garrisonHero)) // our hero
  492. wanderingHeroes -= town->garrisonHero;
  493. }
  494. if (town->visitingHero) //hero leaves garrison
  495. {
  496. CGI->mh->printObject(town->visitingHero);
  497. if (town->visitingHero->tempOwner == playerID && !vstd::contains(wanderingHeroes,town->visitingHero)) // our hero
  498. wanderingHeroes.push_back(town->visitingHero);
  499. }
  500. adventureInt->heroList.update();
  501. adventureInt->updateNextHero(nullptr);
  502. if(castleInt)
  503. {
  504. castleInt->garr->selectSlot(nullptr);
  505. castleInt->garr->setArmy(town->getUpperArmy(), 0);
  506. castleInt->garr->setArmy(town->visitingHero, 1);
  507. castleInt->garr->recreateSlots();
  508. castleInt->heroes->update();
  509. }
  510. for (auto isa : GH.listInt)
  511. {
  512. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  513. if (ki)
  514. {
  515. ki->townChanged(town);
  516. ki->updateGarrisons();
  517. }
  518. }
  519. GH.totalRedraw();
  520. }
  521. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  522. {
  523. EVENT_HANDLER_CALLED_BY_CLIENT;
  524. if (hero->tempOwner != playerID )
  525. return;
  526. waitWhileDialog();
  527. openTownWindow(town);
  528. }
  529. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  530. {
  531. std::vector<const CGObjectInstance *> instances;
  532. if(auto obj = cb->getObj(id1))
  533. instances.push_back(obj);
  534. if(id2 != ObjectInstanceID() && id2 != id1)
  535. {
  536. if(auto obj = cb->getObj(id2))
  537. instances.push_back(obj);
  538. }
  539. garrisonsChanged(instances);
  540. }
  541. void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
  542. {
  543. boost::unique_lock<boost::recursive_mutex> un(*pim);
  544. for (auto object : objs)
  545. updateInfo(object);
  546. for (auto & elem : GH.listInt)
  547. {
  548. CGarrisonHolder *cgh = dynamic_cast<CGarrisonHolder*>(elem.get());
  549. if (cgh)
  550. cgh->updateGarrisons();
  551. if (CTradeWindow *cmw = dynamic_cast<CTradeWindow*>(elem.get()))
  552. {
  553. if (vstd::contains(objs, cmw->hero))
  554. cmw->garrisonChanged();
  555. }
  556. }
  557. GH.totalRedraw();
  558. }
  559. void CPlayerInterface::garrisonChanged( const CGObjectInstance * obj)
  560. {
  561. garrisonsChanged(std::vector<const CGObjectInstance *>(1, obj));
  562. }
  563. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  564. {
  565. EVENT_HANDLER_CALLED_BY_CLIENT;
  566. switch (buildingID)
  567. {
  568. case BuildingID::FORT: case BuildingID::CITADEL: case BuildingID::CASTLE:
  569. case BuildingID::VILLAGE_HALL: case BuildingID::TOWN_HALL: case BuildingID::CITY_HALL: case BuildingID::CAPITOL:
  570. case BuildingID::RESOURCE_SILO:
  571. updateInfo(town);
  572. break;
  573. }
  574. if (castleInt)
  575. {
  576. castleInt->townlist->update(town);
  577. if (castleInt->town == town)
  578. {
  579. switch(what)
  580. {
  581. case 1:
  582. CCS->soundh->playSound(soundBase::newBuilding);
  583. castleInt->addBuilding(buildingID);
  584. break;
  585. case 2:
  586. castleInt->removeBuilding(buildingID);
  587. break;
  588. }
  589. }
  590. }
  591. adventureInt->townList.update(town);
  592. }
  593. void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  594. {
  595. //Don't wait for dialogs when we are non-active hot-seat player
  596. if (LOCPLINT == this)
  597. waitForAllDialogs();
  598. }
  599. void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  600. {
  601. EVENT_HANDLER_CALLED_BY_CLIENT;
  602. if (settings["adventure"]["quickCombat"].Bool())
  603. {
  604. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  605. autofightingAI->initBattleInterface(env, cb);
  606. autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
  607. isAutoFightOn = true;
  608. cb->registerBattleInterface(autofightingAI);
  609. // Player shouldn't be able to move on adventure map if quick combat is going
  610. adventureInt->quickCombatLock();
  611. }
  612. //Don't wait for dialogs when we are non-active hot-seat player
  613. if (LOCPLINT == this)
  614. waitForAllDialogs();
  615. BATTLE_EVENT_POSSIBLE_RETURN;
  616. }
  617. void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units)
  618. {
  619. EVENT_HANDLER_CALLED_BY_CLIENT;
  620. BATTLE_EVENT_POSSIBLE_RETURN;
  621. for(auto & info : units)
  622. {
  623. switch(info.operation)
  624. {
  625. case UnitChanges::EOperation::RESET_STATE:
  626. {
  627. const CStack * stack = cb->battleGetStackByID(info.id );
  628. if(!stack)
  629. {
  630. logGlobal->error("Invalid unit ID %d", info.id);
  631. continue;
  632. }
  633. battleInt->stackReset(stack);
  634. }
  635. break;
  636. case UnitChanges::EOperation::REMOVE:
  637. battleInt->stackRemoved(info.id);
  638. break;
  639. case UnitChanges::EOperation::ADD:
  640. {
  641. const CStack * unit = cb->battleGetStackByID(info.id);
  642. if(!unit)
  643. {
  644. logGlobal->error("Invalid unit ID %d", info.id);
  645. continue;
  646. }
  647. battleInt->stackAdded(unit);
  648. }
  649. break;
  650. default:
  651. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  652. break;
  653. }
  654. }
  655. }
  656. void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges> & obstacles)
  657. {
  658. EVENT_HANDLER_CALLED_BY_CLIENT;
  659. BATTLE_EVENT_POSSIBLE_RETURN;
  660. std::vector<std::shared_ptr<const CObstacleInstance>> newObstacles;
  661. for(auto & change : obstacles)
  662. {
  663. if(change.operation == BattleChanges::EOperation::ADD)
  664. {
  665. auto instance = cb->battleGetObstacleByID(change.id);
  666. if(instance)
  667. newObstacles.push_back(instance);
  668. else
  669. logNetwork->error("Invalid obstacle instance %d", change.id);
  670. }
  671. }
  672. if (!newObstacles.empty())
  673. battleInt->obstaclePlaced(newObstacles);
  674. battleInt->fieldController->redrawBackgroundWithHexes();
  675. }
  676. void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
  677. {
  678. EVENT_HANDLER_CALLED_BY_CLIENT;
  679. BATTLE_EVENT_POSSIBLE_RETURN;
  680. battleInt->stackIsCatapulting(ca);
  681. }
  682. 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
  683. {
  684. EVENT_HANDLER_CALLED_BY_CLIENT;
  685. BATTLE_EVENT_POSSIBLE_RETURN;
  686. battleInt->newRound(round);
  687. }
  688. void CPlayerInterface::actionStarted(const BattleAction &action)
  689. {
  690. EVENT_HANDLER_CALLED_BY_CLIENT;
  691. BATTLE_EVENT_POSSIBLE_RETURN;
  692. curAction = new BattleAction(action);
  693. battleInt->startAction(curAction);
  694. }
  695. void CPlayerInterface::actionFinished(const BattleAction &action)
  696. {
  697. EVENT_HANDLER_CALLED_BY_CLIENT;
  698. BATTLE_EVENT_POSSIBLE_RETURN;
  699. battleInt->endAction(curAction);
  700. delete curAction;
  701. curAction = nullptr;
  702. }
  703. BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
  704. {
  705. THREAD_CREATED_BY_CLIENT;
  706. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  707. auto stackId = stack->ID;
  708. auto stackName = stack->nodeName();
  709. if (autofightingAI)
  710. {
  711. if (isAutoFightOn)
  712. {
  713. auto ret = autofightingAI->activeStack(stack);
  714. if(cb->battleIsFinished())
  715. {
  716. return BattleAction::makeDefend(stack); // battle finished with spellcast
  717. }
  718. if (isAutoFightOn)
  719. {
  720. return ret;
  721. }
  722. }
  723. cb->unregisterBattleInterface(autofightingAI);
  724. autofightingAI.reset();
  725. }
  726. assert(battleInt);
  727. if(!battleInt)
  728. {
  729. return BattleAction::makeDefend(stack); // probably battle is finished already
  730. }
  731. if(BattleInterface::givenCommand.get())
  732. {
  733. logGlobal->error("Command buffer must be clean! (we don't want to use old command)");
  734. vstd::clear_pointer(BattleInterface::givenCommand.data);
  735. }
  736. {
  737. boost::unique_lock<boost::recursive_mutex> un(*pim);
  738. battleInt->stackActivated(stack);
  739. //Regeneration & mana drain go there
  740. }
  741. //wait till BattleInterface sets its command
  742. boost::unique_lock<boost::mutex> lock(BattleInterface::givenCommand.mx);
  743. while(!BattleInterface::givenCommand.data)
  744. {
  745. BattleInterface::givenCommand.cond.wait(lock);
  746. if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
  747. throw boost::thread_interrupted(); //will shut the thread peacefully
  748. }
  749. //tidy up
  750. BattleAction ret = *(BattleInterface::givenCommand.data);
  751. vstd::clear_pointer(BattleInterface::givenCommand.data);
  752. if(ret.actionType == EActionType::CANCEL)
  753. {
  754. if(stackId != ret.stackNumber)
  755. logGlobal->error("Not current active stack action canceled");
  756. logGlobal->trace("Canceled command for %s", stackName);
  757. }
  758. else
  759. logGlobal->trace("Giving command for %s", stackName);
  760. return ret;
  761. }
  762. void CPlayerInterface::battleEnd(const BattleResult *br)
  763. {
  764. EVENT_HANDLER_CALLED_BY_CLIENT;
  765. if(isAutoFightOn || autofightingAI)
  766. {
  767. isAutoFightOn = false;
  768. cb->unregisterBattleInterface(autofightingAI);
  769. autofightingAI.reset();
  770. if(!battleInt)
  771. {
  772. GH.pushIntT<BattleResultWindow>(*br, *this);
  773. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  774. // Otherwise NewTurn causes freeze.
  775. waitWhileDialog();
  776. adventureInt->quickCombatUnlock();
  777. return;
  778. }
  779. }
  780. BATTLE_EVENT_POSSIBLE_RETURN;
  781. battleInt->battleFinished(*br);
  782. adventureInt->quickCombatUnlock();
  783. }
  784. void CPlayerInterface::battleLogMessage(const std::vector<MetaString> & lines)
  785. {
  786. EVENT_HANDLER_CALLED_BY_CLIENT;
  787. BATTLE_EVENT_POSSIBLE_RETURN;
  788. battleInt->displayBattleLog(lines);
  789. }
  790. void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance, bool teleport)
  791. {
  792. EVENT_HANDLER_CALLED_BY_CLIENT;
  793. BATTLE_EVENT_POSSIBLE_RETURN;
  794. battleInt->stackMoved(stack, dest, distance, teleport);
  795. }
  796. void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
  797. {
  798. EVENT_HANDLER_CALLED_BY_CLIENT;
  799. BATTLE_EVENT_POSSIBLE_RETURN;
  800. battleInt->spellCast(sc);
  801. }
  802. void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
  803. {
  804. EVENT_HANDLER_CALLED_BY_CLIENT;
  805. BATTLE_EVENT_POSSIBLE_RETURN;
  806. battleInt->battleStacksEffectsSet(sse);
  807. }
  808. void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
  809. {
  810. EVENT_HANDLER_CALLED_BY_CLIENT;
  811. //TODO why is this different (no return on LOPLINT != this) ?
  812. RETURN_IF_QUICK_COMBAT;
  813. battleInt->effectsController->battleTriggerEffect(bte);
  814. }
  815. void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa, bool ranged)
  816. {
  817. EVENT_HANDLER_CALLED_BY_CLIENT;
  818. BATTLE_EVENT_POSSIBLE_RETURN;
  819. std::vector<StackAttackedInfo> arg;
  820. for(auto & elem : bsa)
  821. {
  822. const CStack * defender = cb->battleGetStackByID(elem.stackAttacked, false);
  823. const CStack * attacker = cb->battleGetStackByID(elem.attackerID, false);
  824. assert(defender);
  825. StackAttackedInfo info;
  826. info.defender = defender;
  827. info.attacker = attacker;
  828. info.damageDealt = elem.damageAmount;
  829. info.amountKilled = elem.killedAmount;
  830. info.spellEffect = SpellID::NONE;
  831. info.indirectAttack = ranged;
  832. info.killed = elem.killed();
  833. info.rebirth = elem.willRebirth();
  834. info.cloneKilled = elem.cloneKilled();
  835. info.fireShield = elem.fireShield();
  836. if (elem.isSpell())
  837. info.spellEffect = elem.spellID;
  838. arg.push_back(info);
  839. }
  840. battleInt->stacksAreAttacked(arg);
  841. }
  842. void CPlayerInterface::battleAttack(const BattleAttack * ba)
  843. {
  844. EVENT_HANDLER_CALLED_BY_CLIENT;
  845. BATTLE_EVENT_POSSIBLE_RETURN;
  846. assert(curAction);
  847. StackAttackInfo info;
  848. info.attacker = cb->battleGetStackByID(ba->stackAttacking);
  849. info.defender = nullptr;
  850. info.indirectAttack = ba->shot();
  851. info.lucky = ba->lucky();
  852. info.unlucky = ba->unlucky();
  853. info.deathBlow = ba->deathBlow();
  854. info.lifeDrain = ba->lifeDrain();
  855. info.tile = ba->tile;
  856. info.spellEffect = SpellID::NONE;
  857. if (ba->spellLike())
  858. info.spellEffect = ba->spellID;
  859. for(auto & elem : ba->bsa)
  860. {
  861. if(!elem.isSecondary())
  862. {
  863. assert(info.defender == nullptr);
  864. info.defender = cb->battleGetStackByID(elem.stackAttacked);
  865. }
  866. else
  867. {
  868. info.secondaryDefender.push_back(cb->battleGetStackByID(elem.stackAttacked));
  869. }
  870. }
  871. assert(info.defender != nullptr);
  872. assert(info.attacker != nullptr);
  873. battleInt->stackAttacking(info);
  874. }
  875. void CPlayerInterface::battleGateStateChanged(const EGateState state)
  876. {
  877. EVENT_HANDLER_CALLED_BY_CLIENT;
  878. BATTLE_EVENT_POSSIBLE_RETURN;
  879. battleInt->gateStateChanged(state);
  880. }
  881. void CPlayerInterface::yourTacticPhase(int distance)
  882. {
  883. THREAD_CREATED_BY_CLIENT;
  884. while(battleInt && battleInt->tacticsMode)
  885. boost::this_thread::sleep(boost::posix_time::millisec(1));
  886. }
  887. void CPlayerInterface::showComp(const Component &comp, std::string message)
  888. {
  889. EVENT_HANDLER_CALLED_BY_CLIENT;
  890. waitWhileDialog(); //Fix for mantis #98
  891. CCS->soundh->playSoundFromSet(CCS->soundh->pickupSounds);
  892. adventureInt->infoBar.showComponent(comp, message);
  893. }
  894. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<Component> & components, int soundID)
  895. {
  896. EVENT_HANDLER_CALLED_BY_CLIENT;
  897. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  898. {
  899. return;
  900. }
  901. std::vector<std::shared_ptr<CComponent>> intComps;
  902. for (auto & component : components)
  903. intComps.push_back(std::make_shared<CComponent>(component));
  904. showInfoDialog(text,intComps,soundID);
  905. }
  906. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  907. {
  908. std::vector<std::shared_ptr<CComponent>> intComps;
  909. intComps.push_back(component);
  910. showInfoDialog(text, intComps, soundBase::sound_todo);
  911. }
  912. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  913. {
  914. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  915. waitWhileDialog();
  916. if (settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  917. {
  918. return;
  919. }
  920. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  921. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  922. {
  923. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  924. showingDialog->set(true);
  925. stopMovement(); // interrupt movement to show dialog
  926. GH.pushInt(temp);
  927. }
  928. else
  929. {
  930. dialogs.push_back(temp);
  931. }
  932. }
  933. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  934. {
  935. EVENT_HANDLER_CALLED_BY_CLIENT;
  936. std::string str;
  937. text.toString(str);
  938. showInfoDialog(str, components, 0);
  939. waitWhileDialog();
  940. }
  941. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  942. {
  943. boost::unique_lock<boost::recursive_mutex> un(*pim);
  944. stopMovement();
  945. LOCPLINT->showingDialog->setn(true);
  946. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  947. }
  948. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  949. {
  950. EVENT_HANDLER_CALLED_BY_CLIENT;
  951. waitWhileDialog();
  952. stopMovement();
  953. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  954. if (!selection && cancel) //simple yes/no dialog
  955. {
  956. std::vector<std::shared_ptr<CComponent>> intComps;
  957. for (auto & component : components)
  958. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  959. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  960. }
  961. else if (selection)
  962. {
  963. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  964. for (auto & component : components)
  965. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  966. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  967. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  968. if (cancel)
  969. {
  970. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  971. }
  972. int charperline = 35;
  973. if (pom.size() > 1)
  974. charperline = 50;
  975. GH.pushIntT<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  976. intComps[0]->clickLeft(true, false);
  977. }
  978. }
  979. void CPlayerInterface::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  980. {
  981. EVENT_HANDLER_CALLED_BY_CLIENT;
  982. int choosenExit = -1;
  983. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  984. if (destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  985. choosenExit = vstd::find_pos(exits, neededExit);
  986. cb->selectionMade(choosenExit, askID);
  987. }
  988. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  989. {
  990. EVENT_HANDLER_CALLED_BY_CLIENT;
  991. auto selectCallback = [=](int selection)
  992. {
  993. JsonNode reply(JsonNode::JsonType::DATA_INTEGER);
  994. reply.Integer() = selection;
  995. cb->sendQueryReply(reply, askID);
  996. };
  997. auto cancelCallback = [=]()
  998. {
  999. JsonNode reply(JsonNode::JsonType::DATA_NULL);
  1000. cb->sendQueryReply(reply, askID);
  1001. };
  1002. const std::string localTitle = title.toString();
  1003. const std::string localDescription = description.toString();
  1004. std::vector<int> tempList;
  1005. tempList.reserve(objects.size());
  1006. for(auto item : objects)
  1007. tempList.push_back(item.getNum());
  1008. CComponent localIconC(icon);
  1009. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  1010. localIconC.removeChild(localIcon.get(), false);
  1011. std::shared_ptr<CObjectListWindow> wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback);
  1012. wnd->onExit = cancelCallback;
  1013. GH.pushInt(wnd);
  1014. }
  1015. void CPlayerInterface::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  1016. {
  1017. EVENT_HANDLER_CALLED_BY_CLIENT;
  1018. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  1019. for (auto & po : pos)
  1020. adventureInt->minimap.showTile(po);
  1021. if (!pos.empty())
  1022. GH.totalRedraw();
  1023. }
  1024. void CPlayerInterface::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  1025. {
  1026. EVENT_HANDLER_CALLED_BY_CLIENT;
  1027. for (auto & po : pos)
  1028. adventureInt->minimap.hideTile(po);
  1029. if (!pos.empty())
  1030. GH.totalRedraw();
  1031. }
  1032. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  1033. {
  1034. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1035. GH.pushIntT<CHeroWindow>(hero);
  1036. }
  1037. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  1038. {
  1039. EVENT_HANDLER_CALLED_BY_CLIENT;
  1040. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  1041. {
  1042. CFortScreen *fs = dynamic_cast<CFortScreen*>(GH.topInt().get());
  1043. if (fs)
  1044. fs->creaturesChanged();
  1045. for(auto isa : GH.listInt)
  1046. {
  1047. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  1048. if (ki && townObj)
  1049. ki->townChanged(townObj);
  1050. }
  1051. }
  1052. else if(town && GH.listInt.size() && (town->ID == Obj::CREATURE_GENERATOR1
  1053. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  1054. {
  1055. CRecruitmentWindow *crw = dynamic_cast<CRecruitmentWindow*>(GH.topInt().get());
  1056. if (crw && crw->dwelling == town)
  1057. crw->availableCreaturesChanged();
  1058. }
  1059. }
  1060. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1061. {
  1062. EVENT_HANDLER_CALLED_BY_CLIENT;
  1063. if (bonus.type == Bonus::NONE)
  1064. return;
  1065. updateInfo(hero);
  1066. if ((bonus.type == Bonus::FLYING_MOVEMENT || bonus.type == Bonus::WATER_WALKING) && !gain)
  1067. {
  1068. //recalculate paths because hero has lost bonus influencing pathfinding
  1069. eraseCurrentPathOf(hero, false);
  1070. }
  1071. }
  1072. template <typename Handler> void CPlayerInterface::serializeTempl( Handler &h, const int version )
  1073. {
  1074. h & wanderingHeroes;
  1075. h & towns;
  1076. h & sleepingHeroes;
  1077. std::map<const CGHeroInstance *, int3> pathsMap; //hero -> dest
  1078. if (h.saving)
  1079. {
  1080. for (auto &p : paths)
  1081. {
  1082. if (p.second.nodes.size())
  1083. pathsMap[p.first] = p.second.endPos();
  1084. else
  1085. logGlobal->debug("%s has assigned an empty path! Ignoring it...", p.first->getNameTranslated());
  1086. }
  1087. h & pathsMap;
  1088. }
  1089. else
  1090. {
  1091. h & pathsMap;
  1092. if (cb)
  1093. for (auto &p : pathsMap)
  1094. {
  1095. CGPath path;
  1096. cb->getPathsInfo(p.first)->getPath(path, p.second);
  1097. paths[p.first] = path;
  1098. logGlobal->trace("Restored path for hero %s leading to %s with %d nodes", p.first->nodeName(), p.second.toString(), path.nodes.size());
  1099. }
  1100. }
  1101. h & spellbookSettings;
  1102. }
  1103. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  1104. {
  1105. EVENT_HANDLER_CALLED_BY_CLIENT;
  1106. serializeTempl(h,version);
  1107. }
  1108. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  1109. {
  1110. EVENT_HANDLER_CALLED_BY_CLIENT;
  1111. serializeTempl(h,version);
  1112. firstCall = -1;
  1113. }
  1114. void CPlayerInterface::moveHero( const CGHeroInstance *h, CGPath path )
  1115. {
  1116. LOG_TRACE(logGlobal);
  1117. if (!LOCPLINT->makingTurn)
  1118. return;
  1119. if (!h)
  1120. return; //can't find hero
  1121. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1122. if (showingDialog->get() || !dialogs.empty())
  1123. return;
  1124. setMovementStatus(true);
  1125. if (adventureInt && adventureInt->isHeroSleeping(h))
  1126. {
  1127. adventureInt->sleepWake->clickLeft(true, false);
  1128. adventureInt->sleepWake->clickLeft(false, true);
  1129. //could've just called
  1130. //adventureInt->fsleepWake();
  1131. //but no authentic button click/sound ;-)
  1132. }
  1133. boost::thread moveHeroTask(std::bind(&CPlayerInterface::doMoveHero,this,h,path));
  1134. }
  1135. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1136. {
  1137. EVENT_HANDLER_CALLED_BY_CLIENT;
  1138. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1139. if (stillMoveHero.get() == DURING_MOVE && adventureInt->terrain.currentPath && adventureInt->terrain.currentPath->nodes.size() > 1) //to ignore calls on passing through garrisons
  1140. {
  1141. onEnd();
  1142. return;
  1143. }
  1144. waitForAllDialogs();
  1145. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1146. cgw->quit->addCallback(onEnd);
  1147. GH.pushInt(cgw);
  1148. }
  1149. /**
  1150. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1151. * into a combinational one on an artifact screen. Does not require the combination of
  1152. * artifacts to be legal.
  1153. */
  1154. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<bool()> onYes)
  1155. {
  1156. std::string text = artifact->getDescriptionTranslated();
  1157. text += "\n\n";
  1158. std::vector<std::shared_ptr<CComponent>> scs;
  1159. if(assembledArtifact)
  1160. {
  1161. // You possess all of the components to...
  1162. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getNameTranslated());
  1163. // Picture of assembled artifact at bottom.
  1164. auto sc = std::make_shared<CComponent>(CComponent::artifact, assembledArtifact->getIndex(), 0);
  1165. scs.push_back(sc);
  1166. }
  1167. else
  1168. {
  1169. // Do you wish to disassemble this artifact?
  1170. text += CGI->generaltexth->allTexts[733];
  1171. }
  1172. showYesNoDialog(text, onYes, nullptr, scs);
  1173. }
  1174. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1175. {
  1176. EVENT_HANDLER_CALLED_BY_CLIENT;
  1177. if (pa->packType == typeList.getTypeID<MoveHero>() && stillMoveHero.get() == DURING_MOVE
  1178. && destinationTeleport == ObjectInstanceID())
  1179. stillMoveHero.setn(CONTINUE_MOVE);
  1180. if (destinationTeleport != ObjectInstanceID()
  1181. && pa->packType == typeList.getTypeID<QueryReply>()
  1182. && stillMoveHero.get() == DURING_MOVE)
  1183. { // After teleportation via CGTeleport object is finished
  1184. destinationTeleport = ObjectInstanceID();
  1185. destinationTeleportPos = int3(-1);
  1186. stillMoveHero.setn(CONTINUE_MOVE);
  1187. }
  1188. }
  1189. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1190. {
  1191. EVENT_HANDLER_CALLED_BY_CLIENT;
  1192. GH.pushIntT<CExchangeWindow>(hero1, hero2, query);
  1193. }
  1194. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1195. {
  1196. EVENT_HANDLER_CALLED_BY_CLIENT;
  1197. //redraw minimap if owner changed
  1198. if (sop->what == ObjProperty::OWNER)
  1199. {
  1200. const CGObjectInstance * obj = cb->getObj(sop->id);
  1201. std::set<int3> pos = obj->getBlockedPos();
  1202. for(auto & po : pos)
  1203. {
  1204. if(cb->isVisible(po))
  1205. adventureInt->minimap.showTile(po);
  1206. }
  1207. if(obj->ID == Obj::TOWN)
  1208. {
  1209. if(obj->tempOwner == playerID)
  1210. towns.push_back(static_cast<const CGTownInstance *>(obj));
  1211. else
  1212. towns -= obj;
  1213. adventureInt->townList.update();
  1214. adventureInt->minimap.update();
  1215. }
  1216. assert(cb->getTownsInfo().size() == towns.size());
  1217. }
  1218. }
  1219. void CPlayerInterface::initializeHeroTownList()
  1220. {
  1221. if(!wanderingHeroes.size())
  1222. {
  1223. std::vector<const CGHeroInstance*> heroes = cb->getHeroesInfo();
  1224. for(auto & hero : heroes)
  1225. {
  1226. if(!hero->inTownGarrison)
  1227. wanderingHeroes.push_back(hero);
  1228. }
  1229. }
  1230. if(!towns.size())
  1231. towns = cb->getTownsInfo();
  1232. if(adventureInt)
  1233. adventureInt->updateNextHero(nullptr);
  1234. }
  1235. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  1236. {
  1237. EVENT_HANDLER_CALLED_BY_CLIENT;
  1238. waitWhileDialog();
  1239. auto recruitCb = [=](CreatureID id, int count)
  1240. {
  1241. LOCPLINT->cb->recruitCreatures(dwelling, dst, id, count, -1);
  1242. };
  1243. GH.pushIntT<CRecruitmentWindow>(dwelling, level, dst, recruitCb);
  1244. }
  1245. void CPlayerInterface::waitWhileDialog(bool unlockPim)
  1246. {
  1247. if (GH.amIGuiThread())
  1248. {
  1249. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1250. return;
  1251. }
  1252. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1253. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1254. while(showingDialog->data)
  1255. showingDialog->cond.wait(un);
  1256. }
  1257. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1258. {
  1259. EVENT_HANDLER_CALLED_BY_CLIENT;
  1260. auto state = obj->shipyardStatus();
  1261. std::vector<si32> cost;
  1262. obj->getBoatCost(cost);
  1263. GH.pushIntT<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1264. }
  1265. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1266. {
  1267. EVENT_HANDLER_CALLED_BY_CLIENT;
  1268. //we might have built a boat in shipyard in opened town screen
  1269. if (obj->ID == Obj::BOAT
  1270. && LOCPLINT->castleInt
  1271. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1272. {
  1273. CCS->soundh->playSound(soundBase::newBuilding);
  1274. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1275. }
  1276. }
  1277. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1278. {
  1279. EVENT_HANDLER_CALLED_BY_CLIENT;
  1280. waitWhileDialog();
  1281. CCS->curh->hide();
  1282. adventureInt->centerOn (pos);
  1283. if (focusTime)
  1284. {
  1285. GH.totalRedraw();
  1286. {
  1287. auto unlockPim = vstd::makeUnlockGuard(*pim);
  1288. IgnoreEvents ignore(*this);
  1289. boost::this_thread::sleep(boost::posix_time::milliseconds(focusTime));
  1290. }
  1291. }
  1292. CCS->curh->show();
  1293. }
  1294. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj)
  1295. {
  1296. EVENT_HANDLER_CALLED_BY_CLIENT;
  1297. if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound())
  1298. {
  1299. waitWhileDialog();
  1300. CCS->soundh->playSound(obj->getRemovalSound().get());
  1301. }
  1302. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1303. {
  1304. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1305. heroKilled(h);
  1306. }
  1307. }
  1308. void CPlayerInterface::playerBlocked(int reason, bool start)
  1309. {
  1310. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1311. {
  1312. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1313. {
  1314. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1315. boost::unique_lock<boost::mutex> lock(eventsM); //TODO: copied from yourTurn, no idea if it's needed
  1316. LOCPLINT = this;
  1317. GH.curInt = this;
  1318. adventureInt->selection = nullptr;
  1319. adventureInt->setPlayer(playerID);
  1320. std::string msg = CGI->generaltexth->translate("vcmi.adventureMap.playerAttacked");
  1321. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1322. std::vector<std::shared_ptr<CComponent>> cmp;
  1323. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  1324. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1325. showInfoDialog(msg, cmp);
  1326. makingTurn = false;
  1327. }
  1328. }
  1329. }
  1330. const CArmedInstance * CPlayerInterface::getSelection()
  1331. {
  1332. return currentSelection;
  1333. }
  1334. void CPlayerInterface::setSelection(const CArmedInstance * obj)
  1335. {
  1336. currentSelection = obj;
  1337. updateAmbientSounds(true);
  1338. }
  1339. void CPlayerInterface::update()
  1340. {
  1341. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1342. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1343. // While mutexes were locked away we may be have stopped being the active interface
  1344. if (LOCPLINT != this)
  1345. return;
  1346. //if there are any waiting dialogs, show them
  1347. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1348. {
  1349. showingDialog->set(true);
  1350. GH.pushInt(dialogs.front());
  1351. dialogs.pop_front();
  1352. }
  1353. //in some conditions we may receive calls before selection is initialized - we must ignore them
  1354. if(adventureInt && GH.topInt() == adventureInt
  1355. && (!adventureInt->selection && !settings["session"]["spectate"].Bool()))
  1356. {
  1357. return;
  1358. }
  1359. // Handles mouse and key input
  1360. GH.updateTime();
  1361. GH.handleEvents();
  1362. if (!adventureInt || adventureInt->isActive())
  1363. GH.simpleRedraw();
  1364. else if((adventureInt->swipeEnabled && adventureInt->swipeMovementRequested) || (adventureInt->scrollingDir && GH.isKeyboardCtrlDown()))
  1365. GH.totalRedraw(); //player forces map scrolling though interface is disabled
  1366. else
  1367. GH.simpleRedraw();
  1368. }
  1369. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1370. {
  1371. using namespace boost::filesystem;
  1372. using namespace boost::algorithm;
  1373. path gamesDir = VCMIDirs::get().userSavePath();
  1374. std::map<std::time_t, int> dates; //save number => datestamp
  1375. const directory_iterator enddir;
  1376. if (!exists(gamesDir))
  1377. create_directory(gamesDir);
  1378. else
  1379. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1380. {
  1381. if (is_regular_file(dir->status()))
  1382. {
  1383. std::string name = dir->path().filename().string();
  1384. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1385. {
  1386. char nr = name[namePrefix.size()];
  1387. if (std::isdigit(nr))
  1388. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1389. }
  1390. }
  1391. }
  1392. if (!dates.empty())
  1393. return (--dates.end())->second; //return latest file number
  1394. return 0;
  1395. }
  1396. void CPlayerInterface::initMovement( const TryMoveHero &details, const CGHeroInstance * ho, const int3 &hp )
  1397. {
  1398. auto subArr = (CGI->mh->ttiles)[hp.z];
  1399. ho->isStanding = false;
  1400. int heroWidth = ho->appearance->getWidth();
  1401. int heroHeight = ho->appearance->getHeight();
  1402. int tileMinX = std::min(details.start.x, details.end.x) - heroWidth;
  1403. int tileMaxX = std::max(details.start.x, details.end.x);
  1404. int tileMinY = std::min(details.start.y, details.end.y) - heroHeight;
  1405. int tileMaxY = std::max(details.start.y, details.end.y);
  1406. // determine tiles on which hero will be visible during movement and add hero as visible object on these tiles where necessary
  1407. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1408. {
  1409. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1410. {
  1411. bool heroVisibleHere = false;
  1412. auto & tile = subArr[tileX][tileY];
  1413. for ( auto const & obj : tile.objects)
  1414. {
  1415. if (obj.obj == ho)
  1416. {
  1417. heroVisibleHere = true;
  1418. break;
  1419. }
  1420. }
  1421. if ( !heroVisibleHere)
  1422. {
  1423. tile.objects.push_back(TerrainTileObject(ho, {0,0,32,32}));
  1424. std::stable_sort(tile.objects.begin(), tile.objects.end(), objectBlitOrderSorter);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. void CPlayerInterface::movementPxStep( const TryMoveHero &details, int i, const int3 &hp, const CGHeroInstance * ho )
  1430. {
  1431. auto subArr = (CGI->mh->ttiles)[hp.z];
  1432. int heroWidth = ho->appearance->getWidth();
  1433. int heroHeight = ho->appearance->getHeight();
  1434. int tileMinX = std::min(details.start.x, details.end.x) - heroWidth;
  1435. int tileMaxX = std::max(details.start.x, details.end.x);
  1436. int tileMinY = std::min(details.start.y, details.end.y) - heroHeight;
  1437. int tileMaxY = std::max(details.start.y, details.end.y);
  1438. std::shared_ptr<CAnimation> animation = graphics->getAnimation(ho);
  1439. assert(animation);
  1440. assert(animation->size(0) != 0);
  1441. auto image = animation->getImage(0,0);
  1442. int heroImageOldX = details.start.x * 32;
  1443. int heroImageOldY = details.start.y * 32;
  1444. int heroImageNewX = details.end.x * 32;
  1445. int heroImageNewY = details.end.y * 32;
  1446. int heroImageCurrX = heroImageOldX + i*(heroImageNewX - heroImageOldX)/32;
  1447. int heroImageCurrY = heroImageOldY + i*(heroImageNewY - heroImageOldY)/32;
  1448. // recompute which part of hero sprite will be visible on each tile at this point of movement animation
  1449. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1450. {
  1451. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1452. {
  1453. auto & tile = subArr[tileX][tileY];
  1454. for ( auto & obj : tile.objects)
  1455. {
  1456. if (obj.obj == ho)
  1457. {
  1458. int tilePosX = tileX * 32;
  1459. int tilePosY = tileY * 32;
  1460. obj.rect.x = tilePosX - heroImageCurrX + image->width() - 32;
  1461. obj.rect.y = tilePosY - heroImageCurrY + image->height() - 32;
  1462. }
  1463. }
  1464. }
  1465. }
  1466. adventureInt->terrain.moveX = (32 - i) * (heroImageNewX - heroImageOldX) / 32;
  1467. adventureInt->terrain.moveY = (32 - i) * (heroImageNewY - heroImageOldY) / 32;
  1468. }
  1469. void CPlayerInterface::finishMovement( const TryMoveHero &details, const int3 &hp, const CGHeroInstance * ho )
  1470. {
  1471. auto subArr = (CGI->mh->ttiles)[hp.z];
  1472. int heroWidth = ho->appearance->getWidth();
  1473. int heroHeight = ho->appearance->getHeight();
  1474. int tileMinX = std::min(details.start.x, details.end.x) - heroWidth;
  1475. int tileMaxX = std::max(details.start.x, details.end.x);
  1476. int tileMinY = std::min(details.start.y, details.end.y) - heroHeight;
  1477. int tileMaxY = std::max(details.start.y, details.end.y);
  1478. // erase hero from all tiles on which he is currently visible
  1479. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1480. {
  1481. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1482. {
  1483. auto & tile = subArr[tileX][tileY];
  1484. for (size_t i = 0; i < tile.objects.size(); ++i)
  1485. {
  1486. if ( tile.objects[i].obj == ho)
  1487. {
  1488. tile.objects.erase(tile.objects.begin() + i);
  1489. break;
  1490. }
  1491. }
  1492. }
  1493. }
  1494. // re-add hero to all tiles on which he will still be visible after animation is over
  1495. for ( int tileX = details.end.x - heroWidth + 1; tileX <= details.end.x; ++tileX)
  1496. {
  1497. for ( int tileY = details.end.y - heroHeight + 1; tileY <= details.end.y; ++tileY)
  1498. {
  1499. auto & tile = subArr[tileX][tileY];
  1500. tile.objects.push_back(TerrainTileObject(ho, {0,0,32,32}));
  1501. }
  1502. }
  1503. // update object list on all tiles that were affected during previous operations
  1504. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1505. {
  1506. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1507. {
  1508. auto & tile = subArr[tileX][tileY];
  1509. std::stable_sort(tile.objects.begin(), tile.objects.end(), objectBlitOrderSorter);
  1510. }
  1511. }
  1512. //recompute hero sprite positioning using hero's final position
  1513. movementPxStep(details, 32, hp, ho);
  1514. }
  1515. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1516. {
  1517. EVENT_HANDLER_CALLED_BY_CLIENT;
  1518. if (player == playerID)
  1519. {
  1520. if (victoryLossCheckResult.loss())
  1521. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1522. //we assume GH.curInt == LOCPLINT
  1523. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1524. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1525. GH.curInt = this; //waiting for dialogs requires this to get events
  1526. if(!makingTurn)
  1527. {
  1528. makingTurn = true; //also needed for dialog to show with current implementation
  1529. waitForAllDialogs();
  1530. makingTurn = false;
  1531. }
  1532. else
  1533. waitForAllDialogs();
  1534. GH.curInt = previousInterface;
  1535. LOCPLINT = previousInterface;
  1536. if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1537. {
  1538. if(adventureInt)
  1539. {
  1540. GH.terminate_cond->setn(true);
  1541. adventureInt->deactivate();
  1542. if (GH.topInt() == adventureInt)
  1543. GH.popInt(adventureInt);
  1544. adventureInt.reset();
  1545. }
  1546. }
  1547. if (victoryLossCheckResult.victory() && LOCPLINT == this)
  1548. {
  1549. // end game if current human player has won
  1550. CSH->sendClientDisconnecting();
  1551. requestReturningToMainMenu(true);
  1552. }
  1553. else if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool())
  1554. {
  1555. //all human players eliminated
  1556. CSH->sendClientDisconnecting();
  1557. requestReturningToMainMenu(false);
  1558. }
  1559. if (GH.curInt == this) GH.curInt = nullptr;
  1560. }
  1561. else
  1562. {
  1563. if (victoryLossCheckResult.loss() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME) //enemy has lost
  1564. {
  1565. std::string str = victoryLossCheckResult.messageToSelf;
  1566. boost::algorithm::replace_first(str, "%s", CGI->generaltexth->capColors[player.getNum()]);
  1567. showInfoDialog(str, std::vector<std::shared_ptr<CComponent>>(1, std::make_shared<CComponent>(CComponent::flag, player.getNum(), 0)));
  1568. }
  1569. }
  1570. }
  1571. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1572. {
  1573. EVENT_HANDLER_CALLED_BY_CLIENT;
  1574. }
  1575. void CPlayerInterface::showPuzzleMap()
  1576. {
  1577. EVENT_HANDLER_CALLED_BY_CLIENT;
  1578. waitWhileDialog();
  1579. //TODO: interface should not know the real position of Grail...
  1580. double ratio = 0;
  1581. int3 grailPos = cb->getGrailPos(&ratio);
  1582. GH.pushIntT<CPuzzleWindow>(grailPos, ratio);
  1583. }
  1584. void CPlayerInterface::viewWorldMap()
  1585. {
  1586. adventureInt->changeMode(EAdvMapMode::WORLD_VIEW);
  1587. }
  1588. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  1589. {
  1590. EVENT_HANDLER_CALLED_BY_CLIENT;
  1591. if(dynamic_cast<CSpellWindow *>(GH.topInt().get()))
  1592. GH.popInts(1);
  1593. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1594. eraseCurrentPathOf(caster, false);
  1595. const spells::Spell * spell = CGI->spells()->getByIndex(spellID);
  1596. if(spellID == SpellID::VIEW_EARTH)
  1597. {
  1598. //TODO: implement on server side
  1599. const auto level = caster->getSpellSchoolLevel(spell);
  1600. adventureInt->worldViewOptions.showAllTerrain = (level > 2);
  1601. }
  1602. auto castSoundPath = spell->getCastSound();
  1603. if(!castSoundPath.empty())
  1604. CCS->soundh->playSound(castSoundPath);
  1605. }
  1606. void CPlayerInterface::eraseCurrentPathOf(const CGHeroInstance * ho, bool checkForExistanceOfPath)
  1607. {
  1608. if (checkForExistanceOfPath)
  1609. {
  1610. assert(vstd::contains(paths, ho));
  1611. }
  1612. else if (!vstd::contains(paths, ho))
  1613. {
  1614. return;
  1615. }
  1616. assert(ho == adventureInt->selection);
  1617. paths.erase(ho);
  1618. adventureInt->terrain.currentPath = nullptr;
  1619. adventureInt->updateMoveHero(ho, false);
  1620. }
  1621. void CPlayerInterface::removeLastNodeFromPath(const CGHeroInstance *ho)
  1622. {
  1623. adventureInt->terrain.currentPath->nodes.erase(adventureInt->terrain.currentPath->nodes.end()-1);
  1624. if (adventureInt->terrain.currentPath->nodes.size() < 2) //if it was the last one, remove entire path and path with only one tile is not a real path
  1625. eraseCurrentPathOf(ho);
  1626. }
  1627. CGPath * CPlayerInterface::getAndVerifyPath(const CGHeroInstance * h)
  1628. {
  1629. if (vstd::contains(paths,h)) //hero has assigned path
  1630. {
  1631. CGPath &path = paths[h];
  1632. if (!path.nodes.size())
  1633. {
  1634. logGlobal->warn("Warning: empty path found...");
  1635. paths.erase(h);
  1636. }
  1637. else
  1638. {
  1639. assert(h->visitablePos() == path.startPos());
  1640. //update the hero path in case of something has changed on map
  1641. if (LOCPLINT->cb->getPathsInfo(h)->getPath(path, path.endPos()))
  1642. return &path;
  1643. else
  1644. paths.erase(h);
  1645. }
  1646. }
  1647. return nullptr;
  1648. }
  1649. void CPlayerInterface::acceptTurn()
  1650. {
  1651. bool centerView = true;
  1652. if (settings["session"]["autoSkip"].Bool())
  1653. {
  1654. centerView = false;
  1655. while(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt().get()))
  1656. iw->close();
  1657. }
  1658. if(CSH->howManyPlayerInterfaces() > 1)
  1659. {
  1660. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  1661. adventureInt->startTurn();
  1662. }
  1663. adventureInt->heroList.update();
  1664. adventureInt->townList.update();
  1665. const CGHeroInstance * heroToSelect = nullptr;
  1666. // find first non-sleeping hero
  1667. for (auto hero : wanderingHeroes)
  1668. {
  1669. if (boost::range::find(sleepingHeroes, hero) == sleepingHeroes.end())
  1670. {
  1671. heroToSelect = hero;
  1672. break;
  1673. }
  1674. }
  1675. //select first hero if available.
  1676. if (heroToSelect != nullptr)
  1677. {
  1678. adventureInt->select(heroToSelect, centerView);
  1679. }
  1680. else if (towns.size())
  1681. adventureInt->select(towns.front(), centerView);
  1682. else
  1683. adventureInt->select(wanderingHeroes.front());
  1684. //show new day animation and sound on infobar
  1685. adventureInt->infoBar.showDate();
  1686. adventureInt->updateNextHero(nullptr);
  1687. adventureInt->showAll(screen);
  1688. if(settings["session"]["autoSkip"].Bool() && !GH.isKeyboardShiftDown())
  1689. {
  1690. if(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt().get()))
  1691. iw->close();
  1692. adventureInt->fendTurn();
  1693. }
  1694. // warn player if he has no town
  1695. if (cb->howManyTowns() == 0)
  1696. {
  1697. auto playerColor = *cb->getPlayerID();
  1698. std::vector<Component> components;
  1699. components.push_back(Component(Component::FLAG, playerColor.getNum(), 0, 0));
  1700. MetaString text;
  1701. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  1702. if(optDaysWithoutCastle)
  1703. {
  1704. auto daysWithoutCastle = optDaysWithoutCastle.get();
  1705. if (daysWithoutCastle < 6)
  1706. {
  1707. 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.
  1708. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  1709. text.addReplacement(7 - daysWithoutCastle);
  1710. }
  1711. else if (daysWithoutCastle == 6)
  1712. {
  1713. text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  1714. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  1715. }
  1716. showInfoDialogAndWait(components, text);
  1717. }
  1718. else
  1719. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  1720. }
  1721. }
  1722. void CPlayerInterface::tryDiggging(const CGHeroInstance * h)
  1723. {
  1724. int msgToShow = -1;
  1725. const bool isBlocked = CGI->mh->hasObjectHole(h->visitablePos()); // Don't dig in the pit.
  1726. const auto diggingStatus = isBlocked
  1727. ? EDiggingStatus::TILE_OCCUPIED
  1728. : h->diggingStatus().num;
  1729. switch(diggingStatus)
  1730. {
  1731. case EDiggingStatus::CAN_DIG:
  1732. break;
  1733. case EDiggingStatus::LACK_OF_MOVEMENT:
  1734. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1735. break;
  1736. case EDiggingStatus::TILE_OCCUPIED:
  1737. msgToShow = 97; //Try searching on clear ground.
  1738. break;
  1739. case EDiggingStatus::WRONG_TERRAIN:
  1740. msgToShow = 60; ////Try looking on land!
  1741. break;
  1742. default:
  1743. assert(0);
  1744. }
  1745. if(msgToShow < 0)
  1746. cb->dig(h);
  1747. else
  1748. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1749. }
  1750. void CPlayerInterface::updateInfo(const CGObjectInstance * specific)
  1751. {
  1752. adventureInt->infoBar.showSelection();
  1753. }
  1754. void CPlayerInterface::battleNewRoundFirst( int round )
  1755. {
  1756. EVENT_HANDLER_CALLED_BY_CLIENT;
  1757. BATTLE_EVENT_POSSIBLE_RETURN;
  1758. battleInt->newRoundFirst(round);
  1759. }
  1760. void CPlayerInterface::stopMovement()
  1761. {
  1762. if (stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  1763. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  1764. }
  1765. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  1766. {
  1767. EVENT_HANDLER_CALLED_BY_CLIENT;
  1768. if (market->o->ID == Obj::ALTAR_OF_SACRIFICE)
  1769. {
  1770. //EEMarketMode mode = market->availableModes().front();
  1771. if (market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1772. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::ARTIFACT_EXP);
  1773. else if (market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1774. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::CREATURE_EXP);
  1775. }
  1776. else
  1777. {
  1778. GH.pushIntT<CMarketplaceWindow>(market, visitor, market->availableModes().front());
  1779. }
  1780. }
  1781. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  1782. {
  1783. EVENT_HANDLER_CALLED_BY_CLIENT;
  1784. GH.pushIntT<CUniversityWindow>(visitor, market);
  1785. }
  1786. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1787. {
  1788. EVENT_HANDLER_CALLED_BY_CLIENT;
  1789. GH.pushIntT<CHillFortWindow>(visitor, object);
  1790. }
  1791. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1792. {
  1793. EVENT_HANDLER_CALLED_BY_CLIENT;
  1794. if (CMarketplaceWindow *cmw = dynamic_cast<CMarketplaceWindow*>(GH.topInt().get()))
  1795. cmw->artifactsChanged(false);
  1796. }
  1797. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  1798. {
  1799. EVENT_HANDLER_CALLED_BY_CLIENT;
  1800. GH.pushIntT<CTavernWindow>(townOrTavern);
  1801. }
  1802. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1803. {
  1804. EVENT_HANDLER_CALLED_BY_CLIENT;
  1805. GH.pushIntT<CThievesGuildWindow>(obj);
  1806. }
  1807. void CPlayerInterface::showQuestLog()
  1808. {
  1809. EVENT_HANDLER_CALLED_BY_CLIENT;
  1810. GH.pushIntT<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1811. }
  1812. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1813. {
  1814. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1815. {
  1816. MetaString txt;
  1817. obj->getProblemText(txt);
  1818. showInfoDialog(txt.toString());
  1819. }
  1820. else
  1821. showShipyardDialog(obj);
  1822. }
  1823. void CPlayerInterface::requestReturningToMainMenu(bool won)
  1824. {
  1825. CCS->soundh->ambientStopAllChannels();
  1826. if(won && cb->getStartInfo()->campState)
  1827. CSH->startCampaignScenario(cb->getStartInfo()->campState);
  1828. else
  1829. GH.pushUserEvent(EUserEvent::RETURN_TO_MAIN_MENU);
  1830. }
  1831. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1832. {
  1833. auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder);
  1834. if(hero)
  1835. {
  1836. auto art = hero->getArt(al.slot);
  1837. if(art == nullptr)
  1838. {
  1839. logGlobal->error("artifact location %d points to nothing",
  1840. al.slot.num);
  1841. return;
  1842. }
  1843. CHeroArtPlace::askToAssemble(art, al.slot, hero);
  1844. }
  1845. }
  1846. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1847. {
  1848. EVENT_HANDLER_CALLED_BY_CLIENT;
  1849. adventureInt->infoBar.showSelection();
  1850. askToAssembleArtifact(al);
  1851. }
  1852. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1853. {
  1854. EVENT_HANDLER_CALLED_BY_CLIENT;
  1855. adventureInt->infoBar.showSelection();
  1856. for(auto isa : GH.listInt)
  1857. {
  1858. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1859. if (artWin)
  1860. artWin->artifactRemoved(al);
  1861. }
  1862. waitWhileDialog();
  1863. }
  1864. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1865. {
  1866. EVENT_HANDLER_CALLED_BY_CLIENT;
  1867. adventureInt->infoBar.showSelection();
  1868. for(auto isa : GH.listInt)
  1869. {
  1870. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1871. if (artWin)
  1872. artWin->artifactMoved(src, dst);
  1873. }
  1874. if(!GH.objsToBlit.empty())
  1875. GH.objsToBlit.back()->redraw();
  1876. waitWhileDialog();
  1877. }
  1878. void CPlayerInterface::artifactPossibleAssembling(const ArtifactLocation & dst)
  1879. {
  1880. askToAssembleArtifact(dst);
  1881. }
  1882. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1883. {
  1884. EVENT_HANDLER_CALLED_BY_CLIENT;
  1885. adventureInt->infoBar.showSelection();
  1886. for(auto isa : GH.listInt)
  1887. {
  1888. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1889. if (artWin)
  1890. artWin->artifactAssembled(al);
  1891. }
  1892. }
  1893. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1894. {
  1895. EVENT_HANDLER_CALLED_BY_CLIENT;
  1896. adventureInt->infoBar.showSelection();
  1897. for(auto isa : GH.listInt)
  1898. {
  1899. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1900. if (artWin)
  1901. artWin->artifactDisassembled(al);
  1902. }
  1903. }
  1904. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  1905. {
  1906. EVENT_HANDLER_CALLED_BY_CLIENT;
  1907. if (!vstd::contains (GH.listInt, adventureInt))
  1908. {
  1909. GH.popInts ((int)GH.listInt.size()); //after map load - remove everything else
  1910. GH.pushInt (adventureInt);
  1911. }
  1912. else
  1913. {
  1914. adventureInt->infoBar.showSelection();
  1915. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front().get())) //don't remove dialogs that expect query answer
  1916. GH.popInts(1);
  1917. }
  1918. if(CSH->howManyPlayerInterfaces() == 1)
  1919. {
  1920. GH.curInt = this;
  1921. adventureInt->startTurn();
  1922. }
  1923. if (player != playerID && this == LOCPLINT)
  1924. {
  1925. waitWhileDialog();
  1926. adventureInt->aiTurnStarted();
  1927. }
  1928. }
  1929. void CPlayerInterface::waitForAllDialogs(bool unlockPim)
  1930. {
  1931. while(!dialogs.empty())
  1932. {
  1933. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1934. boost::this_thread::sleep(boost::posix_time::milliseconds(5));
  1935. }
  1936. waitWhileDialog(unlockPim);
  1937. }
  1938. void CPlayerInterface::proposeLoadingGame()
  1939. {
  1940. showYesNoDialog(CGI->generaltexth->allTexts[68], [](){ GH.pushUserEvent(EUserEvent::RETURN_TO_MENU_LOAD); }, nullptr);
  1941. }
  1942. CPlayerInterface::SpellbookLastSetting::SpellbookLastSetting()
  1943. {
  1944. spellbookLastPageBattle = spellbokLastPageAdvmap = 0;
  1945. spellbookLastTabBattle = spellbookLastTabAdvmap = 4;
  1946. }
  1947. bool CPlayerInterface::capturedAllEvents()
  1948. {
  1949. if (duringMovement)
  1950. {
  1951. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  1952. return true;
  1953. }
  1954. if (ignoreEvents)
  1955. {
  1956. boost::unique_lock<boost::mutex> un(eventsM);
  1957. while(!SDLEventsQueue.empty())
  1958. {
  1959. SDLEventsQueue.pop();
  1960. }
  1961. return true;
  1962. }
  1963. return false;
  1964. }
  1965. void CPlayerInterface::setMovementStatus(bool value)
  1966. {
  1967. duringMovement = value;
  1968. if (value)
  1969. {
  1970. CCS->curh->hide();
  1971. }
  1972. else
  1973. {
  1974. CCS->curh->show();
  1975. }
  1976. }
  1977. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  1978. {
  1979. int i = 1;
  1980. auto getObj = [&](int3 coord, bool ignoreHero)
  1981. {
  1982. return cb->getTile(h->convertToVisitablePos(coord))->topVisitableObj(ignoreHero);
  1983. };
  1984. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  1985. {
  1986. if (action != CGPathNode::TELEPORT_NORMAL &&
  1987. action != CGPathNode::TELEPORT_BLOCKING_VISIT &&
  1988. action != CGPathNode::TELEPORT_BATTLE)
  1989. {
  1990. return false;
  1991. }
  1992. return true;
  1993. };
  1994. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1995. {
  1996. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  1997. return nextObjectTop;
  1998. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  1999. CGTeleport::isConnected(currentObject, nextObject))
  2000. {
  2001. return nextObject;
  2002. }
  2003. return nullptr;
  2004. };
  2005. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  2006. stillMoveHero.data = CONTINUE_MOVE;
  2007. auto doMovement = [&](int3 dst, bool transit)
  2008. {
  2009. stillMoveHero.data = WAITING_MOVE;
  2010. cb->moveHero(h, dst, transit);
  2011. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  2012. stillMoveHero.cond.wait(un);
  2013. };
  2014. {
  2015. for (auto & elem : path.nodes)
  2016. elem.coord = h->convertFromVisitablePos(elem.coord);
  2017. TerrainId currentTerrain = ETerrainId::NONE;
  2018. TerrainId newTerrain;
  2019. bool wasOnRoad = true;
  2020. int sh = -1;
  2021. auto canStop = [&](CGPathNode * node) -> bool
  2022. {
  2023. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  2024. return true;
  2025. if (node->accessible == CGPathNode::ACCESSIBLE)
  2026. return true;
  2027. return false;
  2028. };
  2029. for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  2030. {
  2031. int3 prevCoord = path.nodes[i].coord;
  2032. int3 nextCoord = path.nodes[i-1].coord;
  2033. auto prevRoad = cb->getTile(h->convertToVisitablePos(prevCoord))->roadType;
  2034. auto nextRoad = cb->getTile(h->convertToVisitablePos(nextCoord))->roadType;
  2035. bool movingOnRoad = prevRoad->getId() != Road::NO_ROAD && nextRoad->getId() != Road::NO_ROAD;
  2036. auto prevObject = getObj(prevCoord, prevCoord == h->pos);
  2037. auto nextObjectTop = getObj(nextCoord, false);
  2038. auto nextObject = getObj(nextCoord, true);
  2039. auto destTeleportObj = getDestTeleportObj(prevObject, nextObjectTop, nextObject);
  2040. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  2041. {
  2042. CCS->soundh->stopSound(sh);
  2043. destinationTeleport = destTeleportObj->id;
  2044. destinationTeleportPos = nextCoord;
  2045. doMovement(h->pos, false);
  2046. if (path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT
  2047. || path.nodes[i-1].action == CGPathNode::TELEPORT_BATTLE)
  2048. {
  2049. destinationTeleport = ObjectInstanceID();
  2050. destinationTeleportPos = int3(-1);
  2051. }
  2052. if(i != path.nodes.size() - 1)
  2053. {
  2054. if (movingOnRoad)
  2055. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(currentTerrain)->horseSound, -1);
  2056. else
  2057. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(currentTerrain)->horseSoundPenalty, -1);
  2058. }
  2059. continue;
  2060. }
  2061. if (path.nodes[i-1].turns)
  2062. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  2063. stillMoveHero.data = STOP_MOVE;
  2064. break;
  2065. }
  2066. // Start a new sound for the hero movement or let the existing one carry on.
  2067. #if 0
  2068. // TODO
  2069. if (hero is flying && sh == -1)
  2070. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  2071. #endif
  2072. {
  2073. newTerrain = cb->getTile(h->convertToVisitablePos(prevCoord))->terType->getId();
  2074. if(newTerrain != currentTerrain || wasOnRoad != movingOnRoad)
  2075. {
  2076. CCS->soundh->stopSound(sh);
  2077. if (movingOnRoad)
  2078. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(newTerrain)->horseSound, -1);
  2079. else
  2080. sh = CCS->soundh->playSound(VLC->terrainTypeHandler->getById(newTerrain)->horseSoundPenalty, -1);
  2081. currentTerrain = newTerrain;
  2082. wasOnRoad = movingOnRoad;
  2083. }
  2084. }
  2085. 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
  2086. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  2087. logGlobal->trace("Requesting hero movement to %s", endpos.toString());
  2088. bool useTransit = false;
  2089. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  2090. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  2091. || CGTeleport::isTeleport(nextObjectTop)))
  2092. { // Hero should be able to go through object if it's allow transit
  2093. useTransit = true;
  2094. }
  2095. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  2096. useTransit = true;
  2097. doMovement(endpos, useTransit);
  2098. logGlobal->trace("Resuming %s", __FUNCTION__);
  2099. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  2100. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  2101. break;
  2102. }
  2103. CCS->soundh->stopSound(sh);
  2104. }
  2105. //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
  2106. if (!showingDialog->get())
  2107. GH.fakeMouseMove();
  2108. //todo: this should be in main thread
  2109. if (adventureInt)
  2110. {
  2111. // (i == 0) means hero went through all the path
  2112. adventureInt->updateMoveHero(h, (i != 0));
  2113. adventureInt->updateNextHero(h);
  2114. // ugly workaround to force instant update of adventure map
  2115. adventureInt->animValHitCount = 8;
  2116. }
  2117. setMovementStatus(false);
  2118. }
  2119. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions)
  2120. {
  2121. EVENT_HANDLER_CALLED_BY_CLIENT;
  2122. //TODO: showWorldViewEx
  2123. std::copy(objectPositions.begin(), objectPositions.end(), std::back_inserter(adventureInt->worldViewOptions.iconPositions));
  2124. viewWorldMap();
  2125. }
  2126. void CPlayerInterface::updateAmbientSounds(bool resetAll)
  2127. {
  2128. if(castleInt || battleInt || !makingTurn || !currentSelection)
  2129. {
  2130. CCS->soundh->ambientStopAllChannels();
  2131. return;
  2132. }
  2133. else if(!dynamic_cast<CAdvMapInt *>(GH.topInt().get()))
  2134. {
  2135. return;
  2136. }
  2137. if(resetAll)
  2138. CCS->soundh->ambientStopAllChannels();
  2139. std::map<std::string, int> currentSounds;
  2140. auto updateSounds = [&](std::string soundId, int distance) -> void
  2141. {
  2142. if(vstd::contains(currentSounds, soundId))
  2143. currentSounds[soundId] = std::max(currentSounds[soundId], distance);
  2144. else
  2145. currentSounds.insert(std::make_pair(soundId, distance));
  2146. };
  2147. int3 pos = currentSelection->getSightCenter();
  2148. std::unordered_set<int3, ShashInt3> tiles;
  2149. cb->getVisibleTilesInRange(tiles, pos, CCS->soundh->ambientGetRange(), int3::DIST_CHEBYSHEV);
  2150. for(int3 tile : tiles)
  2151. {
  2152. int dist = pos.dist(tile, int3::DIST_CHEBYSHEV);
  2153. // We want sound for every special terrain on tile and not just one on top
  2154. for(auto & ttObj : CGI->mh->ttiles[tile.z][tile.x][tile.y].objects)
  2155. {
  2156. if(ttObj.ambientSound)
  2157. updateSounds(ttObj.ambientSound.get(), dist);
  2158. }
  2159. if(CGI->mh->map->isCoastalTile(tile))
  2160. updateSounds("LOOPOCEA", dist);
  2161. }
  2162. CCS->soundh->ambientUpdateChannels(currentSounds);
  2163. }