CPlayerInterface.cpp 93 KB

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