CPlayerInterface.cpp 96 KB

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