CPlayerInterface.cpp 95 KB

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