CPlayerInterface.cpp 93 KB

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