CPlayerInterface.cpp 76 KB

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