CPlayerInterface.cpp 91 KB

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