CPlayerInterface.cpp 95 KB

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