CPlayerInterface.cpp 96 KB

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