CPlayerInterface.cpp 95 KB

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