CPlayerInterface.cpp 95 KB

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