CPlayerInterface.cpp 95 KB

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