CPlayerInterface.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761
  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/spells/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. if(spellID == SpellID::VIEW_EARTH)
  1909. {
  1910. //TODO: implement on server side
  1911. int level = caster->getSpellSchoolLevel(spell);
  1912. adventureInt->worldViewOptions.showAllTerrain = (level>2);
  1913. }
  1914. auto castSoundPath = spell->getCastSound();
  1915. if (!castSoundPath.empty())
  1916. CCS->soundh->playSound(castSoundPath);
  1917. }
  1918. void CPlayerInterface::eraseCurrentPathOf( const CGHeroInstance * ho, bool checkForExistanceOfPath /*= true */ )
  1919. {
  1920. if(checkForExistanceOfPath)
  1921. {
  1922. assert(vstd::contains(paths, ho));
  1923. }
  1924. else if (!vstd::contains(paths, ho))
  1925. {
  1926. return;
  1927. }
  1928. assert(ho == adventureInt->selection);
  1929. paths.erase(ho);
  1930. adventureInt->terrain.currentPath = nullptr;
  1931. adventureInt->updateMoveHero(ho, false);
  1932. }
  1933. void CPlayerInterface::removeLastNodeFromPath(const CGHeroInstance *ho)
  1934. {
  1935. adventureInt->terrain.currentPath->nodes.erase(adventureInt->terrain.currentPath->nodes.end()-1);
  1936. 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
  1937. eraseCurrentPathOf(ho);
  1938. }
  1939. CGPath * CPlayerInterface::getAndVerifyPath(const CGHeroInstance * h)
  1940. {
  1941. if(vstd::contains(paths,h)) //hero has assigned path
  1942. {
  1943. CGPath &path = paths[h];
  1944. if(!path.nodes.size())
  1945. {
  1946. logGlobal->warnStream() << "Warning: empty path found...";
  1947. paths.erase(h);
  1948. }
  1949. else
  1950. {
  1951. assert(h->getPosition(false) == path.startPos());
  1952. //update the hero path in case of something has changed on map
  1953. if(LOCPLINT->cb->getPathsInfo(h)->getPath(path.endPos(), path))
  1954. return &path;
  1955. else
  1956. paths.erase(h);
  1957. }
  1958. }
  1959. return nullptr;
  1960. }
  1961. void CPlayerInterface::acceptTurn()
  1962. {
  1963. if(settings["session"]["autoSkip"].Bool())
  1964. {
  1965. while(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt()))
  1966. iw->close();
  1967. }
  1968. waitWhileDialog();
  1969. if(howManyPeople > 1)
  1970. adventureInt->startTurn();
  1971. adventureInt->heroList.update();
  1972. adventureInt->townList.update();
  1973. const CGHeroInstance * heroToSelect = nullptr;
  1974. // find first non-sleeping hero
  1975. for (auto hero : wanderingHeroes)
  1976. {
  1977. if (boost::range::find(sleepingHeroes, hero) == sleepingHeroes.end())
  1978. {
  1979. heroToSelect = hero;
  1980. break;
  1981. }
  1982. }
  1983. //select first hero if available.
  1984. if(heroToSelect != nullptr)
  1985. {
  1986. adventureInt->select(heroToSelect);
  1987. }
  1988. else
  1989. adventureInt->select(towns.front());
  1990. //show new day animation and sound on infobar
  1991. adventureInt->infoBar.showDate();
  1992. adventureInt->updateNextHero(nullptr);
  1993. adventureInt->showAll(screen);
  1994. if(settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  1995. {
  1996. if(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt()))
  1997. iw->close();
  1998. adventureInt->fendTurn();
  1999. }
  2000. // warn player if he has no town
  2001. if(cb->howManyTowns() == 0)
  2002. {
  2003. auto playerColor = *cb->getPlayerID();
  2004. std::vector<Component> components;
  2005. components.push_back(Component(Component::FLAG, playerColor.getNum(), 0, 0));
  2006. MetaString text;
  2007. auto daysWithoutCastle = *cb->getPlayer(playerColor)->daysWithoutCastle;
  2008. if (daysWithoutCastle < 6)
  2009. {
  2010. 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.
  2011. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  2012. text.addReplacement(7 - daysWithoutCastle);
  2013. }
  2014. else if(daysWithoutCastle == 6)
  2015. {
  2016. text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  2017. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  2018. }
  2019. showInfoDialogAndWait(components, text);
  2020. }
  2021. }
  2022. void CPlayerInterface::tryDiggging(const CGHeroInstance *h)
  2023. {
  2024. std::string hlp;
  2025. CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  2026. int msgToShow = -1;
  2027. CGHeroInstance::ECanDig isDiggingPossible = h->diggingStatus();
  2028. if(hlp.length())
  2029. isDiggingPossible = CGHeroInstance::TILE_OCCUPIED; //TODO integrate with canDig
  2030. switch(isDiggingPossible)
  2031. {
  2032. case CGHeroInstance::CAN_DIG:
  2033. break;
  2034. case CGHeroInstance::LACK_OF_MOVEMENT:
  2035. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  2036. break;
  2037. case CGHeroInstance::TILE_OCCUPIED:
  2038. msgToShow = 97; //Try searching on clear ground.
  2039. break;
  2040. case CGHeroInstance::WRONG_TERRAIN:
  2041. msgToShow = 60; ////Try looking on land!
  2042. break;
  2043. default:
  2044. assert(0);
  2045. }
  2046. if(msgToShow < 0)
  2047. cb->dig(h);
  2048. else
  2049. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  2050. }
  2051. void CPlayerInterface::updateInfo(const CGObjectInstance * specific)
  2052. {
  2053. adventureInt->infoBar.showSelection();
  2054. }
  2055. void CPlayerInterface::battleNewRoundFirst( int round )
  2056. {
  2057. EVENT_HANDLER_CALLED_BY_CLIENT;
  2058. BATTLE_EVENT_POSSIBLE_RETURN;
  2059. battleInt->newRoundFirst(round);
  2060. }
  2061. void CPlayerInterface::stopMovement()
  2062. {
  2063. if(stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  2064. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  2065. }
  2066. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  2067. {
  2068. EVENT_HANDLER_CALLED_BY_CLIENT;
  2069. if(market->o->ID == Obj::ALTAR_OF_SACRIFICE)
  2070. {
  2071. //EEMarketMode mode = market->availableModes().front();
  2072. if(market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  2073. GH.pushInt(new CAltarWindow(market, visitor, EMarketMode::ARTIFACT_EXP));
  2074. else if(market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  2075. GH.pushInt(new CAltarWindow(market, visitor, EMarketMode::CREATURE_EXP));
  2076. }
  2077. else
  2078. GH.pushInt(new CMarketplaceWindow(market, visitor, market->availableModes().front()));
  2079. }
  2080. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  2081. {
  2082. EVENT_HANDLER_CALLED_BY_CLIENT;
  2083. auto cuw = new CUniversityWindow(visitor, market);
  2084. GH.pushInt(cuw);
  2085. }
  2086. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  2087. {
  2088. EVENT_HANDLER_CALLED_BY_CLIENT;
  2089. auto chfw = new CHillFortWindow(visitor, object);
  2090. GH.pushInt(chfw);
  2091. }
  2092. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket *bm /*= nullptr*/)
  2093. {
  2094. EVENT_HANDLER_CALLED_BY_CLIENT;
  2095. if(CMarketplaceWindow *cmw = dynamic_cast<CMarketplaceWindow*>(GH.topInt()))
  2096. cmw->artifactsChanged(false);
  2097. }
  2098. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  2099. {
  2100. EVENT_HANDLER_CALLED_BY_CLIENT;
  2101. auto tv = new CTavernWindow(townOrTavern);
  2102. GH.pushInt(tv);
  2103. }
  2104. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  2105. {
  2106. EVENT_HANDLER_CALLED_BY_CLIENT;
  2107. auto tgw = new CThievesGuildWindow(obj);
  2108. GH.pushInt(tgw);
  2109. }
  2110. void CPlayerInterface::showQuestLog()
  2111. {
  2112. EVENT_HANDLER_CALLED_BY_CLIENT;
  2113. CQuestLog * ql = new CQuestLog (LOCPLINT->cb->getMyQuests());
  2114. GH.pushInt (ql);
  2115. }
  2116. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  2117. {
  2118. if(obj->shipyardStatus() != IBoatGenerator::GOOD)
  2119. {
  2120. MetaString txt;
  2121. obj->getProblemText(txt);
  2122. showInfoDialog(txt.toString());
  2123. }
  2124. else
  2125. showShipyardDialog(obj);
  2126. }
  2127. void CPlayerInterface::requestReturningToMainMenu()
  2128. {
  2129. sendCustomEvent(RETURN_TO_MAIN_MENU);
  2130. cb->unregisterAllInterfaces();
  2131. }
  2132. void CPlayerInterface::requestStoppingClient()
  2133. {
  2134. sendCustomEvent(STOP_CLIENT);
  2135. }
  2136. void CPlayerInterface::sendCustomEvent( int code )
  2137. {
  2138. CGuiHandler::pushSDLEvent(SDL_USEREVENT, code);
  2139. }
  2140. void CPlayerInterface::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  2141. {
  2142. EVENT_HANDLER_CALLED_BY_CLIENT;
  2143. garrisonChanged(location.army);
  2144. }
  2145. void CPlayerInterface::stackChangedType(const StackLocation &location, const CCreature &newType)
  2146. {
  2147. EVENT_HANDLER_CALLED_BY_CLIENT;
  2148. garrisonChanged(location.army);
  2149. }
  2150. void CPlayerInterface::stacksErased(const StackLocation &location)
  2151. {
  2152. EVENT_HANDLER_CALLED_BY_CLIENT;
  2153. garrisonChanged(location.army);
  2154. }
  2155. void CPlayerInterface::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  2156. {
  2157. EVENT_HANDLER_CALLED_BY_CLIENT;
  2158. std::vector<const CGObjectInstance *> objects;
  2159. objects.push_back(loc1.army);
  2160. if(loc2.army != loc1.army)
  2161. objects.push_back(loc2.army);
  2162. garrisonsChanged(objects);
  2163. }
  2164. void CPlayerInterface::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  2165. {
  2166. EVENT_HANDLER_CALLED_BY_CLIENT;
  2167. garrisonChanged(location.army);
  2168. }
  2169. void CPlayerInterface::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  2170. {
  2171. EVENT_HANDLER_CALLED_BY_CLIENT;
  2172. std::vector<const CGObjectInstance *> objects;
  2173. objects.push_back(src.army);
  2174. if(src.army != dst.army)
  2175. objects.push_back(dst.army);
  2176. garrisonsChanged(objects);
  2177. }
  2178. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  2179. {
  2180. EVENT_HANDLER_CALLED_BY_CLIENT;
  2181. }
  2182. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  2183. {
  2184. EVENT_HANDLER_CALLED_BY_CLIENT;
  2185. adventureInt->infoBar.showSelection();
  2186. for(IShowActivatable *isa : GH.listInt)
  2187. {
  2188. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2189. if(artWin)
  2190. artWin->artifactRemoved(al);
  2191. }
  2192. }
  2193. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  2194. {
  2195. EVENT_HANDLER_CALLED_BY_CLIENT;
  2196. adventureInt->infoBar.showSelection();
  2197. for(IShowActivatable *isa : GH.listInt)
  2198. {
  2199. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2200. if(artWin)
  2201. artWin->artifactMoved(src, dst);
  2202. }
  2203. }
  2204. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  2205. {
  2206. EVENT_HANDLER_CALLED_BY_CLIENT;
  2207. adventureInt->infoBar.showSelection();
  2208. for(IShowActivatable *isa : GH.listInt)
  2209. {
  2210. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2211. if(artWin)
  2212. artWin->artifactAssembled(al);
  2213. }
  2214. }
  2215. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  2216. {
  2217. EVENT_HANDLER_CALLED_BY_CLIENT;
  2218. adventureInt->infoBar.showSelection();
  2219. for(IShowActivatable *isa : GH.listInt)
  2220. {
  2221. auto artWin = dynamic_cast<CArtifactHolder*>(isa);
  2222. if(artWin)
  2223. artWin->artifactDisassembled(al);
  2224. }
  2225. }
  2226. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  2227. {
  2228. EVENT_HANDLER_CALLED_BY_CLIENT;
  2229. adventureInt->infoBar.showSelection();
  2230. if (!vstd::contains (GH.listInt, adventureInt))
  2231. {
  2232. GH.popInts (GH.listInt.size()); //after map load - remove everything else
  2233. GH.pushInt (adventureInt);
  2234. }
  2235. else
  2236. {
  2237. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front())) //don't remove dialogs that expect query answer
  2238. GH.popInts(1);
  2239. }
  2240. if(howManyPeople == 1)
  2241. {
  2242. GH.curInt = this;
  2243. adventureInt->startTurn();
  2244. }
  2245. if(player != playerID && this == LOCPLINT)
  2246. {
  2247. waitWhileDialog();
  2248. adventureInt->aiTurnStarted();
  2249. }
  2250. }
  2251. void CPlayerInterface::waitForAllDialogs(bool unlockPim /*= true*/)
  2252. {
  2253. while(!dialogs.empty())
  2254. {
  2255. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  2256. SDL_Delay(5);
  2257. }
  2258. waitWhileDialog(unlockPim);
  2259. }
  2260. void CPlayerInterface::proposeLoadingGame()
  2261. {
  2262. showYesNoDialog(CGI->generaltexth->allTexts[68], [this] { sendCustomEvent(RETURN_TO_MENU_LOAD); }, 0, false);
  2263. }
  2264. CPlayerInterface::SpellbookLastSetting::SpellbookLastSetting()
  2265. {
  2266. spellbookLastPageBattle = spellbokLastPageAdvmap = 0;
  2267. spellbookLastTabBattle = spellbookLastTabAdvmap = 4;
  2268. }
  2269. bool CPlayerInterface::capturedAllEvents()
  2270. {
  2271. if(duringMovement)
  2272. {
  2273. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  2274. return true;
  2275. }
  2276. if(ignoreEvents)
  2277. {
  2278. boost::unique_lock<boost::mutex> un(eventsM);
  2279. while(!events.empty())
  2280. {
  2281. events.pop();
  2282. }
  2283. return true;
  2284. }
  2285. return false;
  2286. }
  2287. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  2288. {
  2289. int i = 1;
  2290. auto getObj = [&](int3 coord, bool ignoreHero)
  2291. {
  2292. return cb->getTile(CGHeroInstance::convertPosition(coord,false))->topVisitableObj(ignoreHero);
  2293. };
  2294. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  2295. stillMoveHero.data = CONTINUE_MOVE;
  2296. auto doMovement = [&](int3 dst, bool transit)
  2297. {
  2298. stillMoveHero.data = WAITING_MOVE;
  2299. cb->moveHero(h, dst, transit);
  2300. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  2301. stillMoveHero.cond.wait(un);
  2302. };
  2303. {
  2304. path.convert(0);
  2305. ETerrainType currentTerrain = ETerrainType::BORDER; // not init yet
  2306. ETerrainType newTerrain;
  2307. int sh = -1;
  2308. for(i=path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE); i--)
  2309. {
  2310. int3 currentCoord = path.nodes[i].coord;
  2311. int3 nextCoord = path.nodes[i-1].coord;
  2312. auto nextObject = getObj(nextCoord, nextCoord == h->pos);
  2313. if(CGTeleport::isConnected(getObj(currentCoord, currentCoord == h->pos), nextObject))
  2314. {
  2315. CCS->soundh->stopSound(sh);
  2316. destinationTeleport = nextObject->id;
  2317. doMovement(h->pos, false);
  2318. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[currentTerrain], -1);
  2319. continue;
  2320. }
  2321. if(path.nodes[i-1].turns)
  2322. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  2323. stillMoveHero.data = STOP_MOVE;
  2324. break;
  2325. }
  2326. // Start a new sound for the hero movement or let the existing one carry on.
  2327. #if 0
  2328. // TODO
  2329. if(hero is flying && sh == -1)
  2330. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  2331. #endif
  2332. {
  2333. newTerrain = cb->getTile(CGHeroInstance::convertPosition(currentCoord, false))->terType;
  2334. if(newTerrain != currentTerrain)
  2335. {
  2336. CCS->soundh->stopSound(sh);
  2337. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[newTerrain], -1);
  2338. currentTerrain = newTerrain;
  2339. }
  2340. }
  2341. 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
  2342. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  2343. logGlobal->traceStream() << "Requesting hero movement to " << endpos;
  2344. if((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  2345. && (CGTeleport::isConnected(nextObject, getObj(path.nodes[i-2].coord, false))
  2346. || CGTeleport::isTeleport(nextObject)))
  2347. { // Hero should be able to go through object if it's allow transit
  2348. doMovement(endpos, true);
  2349. }
  2350. else
  2351. doMovement(endpos, false);
  2352. logGlobal->traceStream() << "Resuming " << __FUNCTION__;
  2353. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  2354. if(guarded || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  2355. break;
  2356. }
  2357. CCS->soundh->stopSound(sh);
  2358. }
  2359. //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
  2360. if(!showingDialog->get())
  2361. GH.fakeMouseMove();
  2362. //todo: this should be in main thread
  2363. if(adventureInt)
  2364. {
  2365. // (i == 0) means hero went through all the path
  2366. adventureInt->updateMoveHero(h, (i != 0));
  2367. adventureInt->updateNextHero(h);
  2368. }
  2369. duringMovement = false;
  2370. }
  2371. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions)
  2372. {
  2373. EVENT_HANDLER_CALLED_BY_CLIENT;
  2374. //TODO: showWorldViewEx
  2375. std::copy(objectPositions.begin(), objectPositions.end(), std::back_inserter(adventureInt->worldViewOptions.iconPositions));
  2376. viewWorldMap();
  2377. }