CPlayerInterface.cpp 95 KB

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