CPlayerInterface.cpp 95 KB

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