CPlayerInterface.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605
  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::initGameInterface(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 == hero->convertToVisitablePos(details.start)
  230. && (nodesIt - 1)->coord == hero->convertToVisitablePos(details.end))
  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. if (settings["adventure"]["quickCombat"].Bool())
  598. {
  599. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  600. autofightingAI->initBattleInterface(env, cb);
  601. autofightingAI->battleStart(army1, army2, int3(0,0,0), hero1, hero2, side);
  602. isAutoFightOn = true;
  603. cb->registerBattleInterface(autofightingAI);
  604. // Player shouldn't be able to move on adventure map if quick combat is going
  605. adventureInt->quickCombatLock();
  606. }
  607. //Don't wait for dialogs when we are non-active hot-seat player
  608. if (LOCPLINT == this)
  609. waitForAllDialogs();
  610. BATTLE_EVENT_POSSIBLE_RETURN;
  611. }
  612. void CPlayerInterface::battleUnitsChanged(const std::vector<UnitChanges> & units, const std::vector<CustomEffectInfo> & customEffects)
  613. {
  614. EVENT_HANDLER_CALLED_BY_CLIENT;
  615. BATTLE_EVENT_POSSIBLE_RETURN;
  616. for(auto & info : units)
  617. {
  618. switch(info.operation)
  619. {
  620. case UnitChanges::EOperation::RESET_STATE:
  621. {
  622. const battle::Unit * unit = cb->battleGetUnitByID(info.id);
  623. if(!unit)
  624. {
  625. logGlobal->error("Invalid unit ID %d", info.id);
  626. continue;
  627. }
  628. auto iter = battleInt->creAnims.find(info.id);
  629. if(iter == battleInt->creAnims.end())
  630. {
  631. logGlobal->error("Unit %d have no animation", info.id);
  632. continue;
  633. }
  634. auto animation = iter->second;
  635. if(unit->alive() && animation->isDead())
  636. animation->setType(CCreatureAnim::HOLDING);
  637. if (unit->isClone())
  638. {
  639. std::unique_ptr<ColorShifterDeepBlue> shifter(new ColorShifterDeepBlue());
  640. animation->shiftColor(shifter.get());
  641. }
  642. //TODO: handle more cases
  643. }
  644. break;
  645. case UnitChanges::EOperation::REMOVE:
  646. battleInt->stackRemoved(info.id);
  647. break;
  648. case UnitChanges::EOperation::ADD:
  649. {
  650. const CStack * unit = cb->battleGetStackByID(info.id);
  651. if(!unit)
  652. {
  653. logGlobal->error("Invalid unit ID %d", info.id);
  654. continue;
  655. }
  656. battleInt->unitAdded(unit);
  657. }
  658. break;
  659. default:
  660. logGlobal->error("Unknown unit operation %d", (int)info.operation);
  661. break;
  662. }
  663. }
  664. battleInt->displayCustomEffects(customEffects);
  665. }
  666. void CPlayerInterface::battleObstaclesChanged(const std::vector<ObstacleChanges> & obstacles)
  667. {
  668. EVENT_HANDLER_CALLED_BY_CLIENT;
  669. BATTLE_EVENT_POSSIBLE_RETURN;
  670. bool needUpdate = false;
  671. for(auto & change : obstacles)
  672. {
  673. if(change.operation == BattleChanges::EOperation::ADD)
  674. {
  675. auto instance = cb->battleGetObstacleByID(change.id);
  676. if(instance)
  677. battleInt->obstaclePlaced(*instance);
  678. else
  679. logNetwork->error("Invalid obstacle instance %d", change.id);
  680. }
  681. else
  682. {
  683. needUpdate = true;
  684. }
  685. }
  686. if(needUpdate)
  687. //update accessible hexes
  688. battleInt->redrawBackgroundWithHexes(battleInt->activeStack);
  689. }
  690. void CPlayerInterface::battleCatapultAttacked(const CatapultAttack & ca)
  691. {
  692. EVENT_HANDLER_CALLED_BY_CLIENT;
  693. BATTLE_EVENT_POSSIBLE_RETURN;
  694. battleInt->stackIsCatapulting(ca);
  695. }
  696. 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
  697. {
  698. EVENT_HANDLER_CALLED_BY_CLIENT;
  699. BATTLE_EVENT_POSSIBLE_RETURN;
  700. battleInt->newRound(round);
  701. }
  702. void CPlayerInterface::actionStarted(const BattleAction &action)
  703. {
  704. EVENT_HANDLER_CALLED_BY_CLIENT;
  705. BATTLE_EVENT_POSSIBLE_RETURN;
  706. curAction = new BattleAction(action);
  707. battleInt->startAction(curAction);
  708. }
  709. void CPlayerInterface::actionFinished(const BattleAction &action)
  710. {
  711. EVENT_HANDLER_CALLED_BY_CLIENT;
  712. BATTLE_EVENT_POSSIBLE_RETURN;
  713. battleInt->endAction(curAction);
  714. delete curAction;
  715. curAction = nullptr;
  716. }
  717. BattleAction CPlayerInterface::activeStack(const CStack * stack) //called when it's turn of that stack
  718. {
  719. THREAD_CREATED_BY_CLIENT;
  720. logGlobal->trace("Awaiting command for %s", stack->nodeName());
  721. auto stackId = stack->ID;
  722. auto stackName = stack->nodeName();
  723. if (autofightingAI)
  724. {
  725. if (isAutoFightOn)
  726. {
  727. auto ret = autofightingAI->activeStack(stack);
  728. if(cb->battleIsFinished())
  729. {
  730. return BattleAction::makeDefend(stack); // battle finished with spellcast
  731. }
  732. if (isAutoFightOn)
  733. {
  734. return ret;
  735. }
  736. }
  737. cb->unregisterBattleInterface(autofightingAI);
  738. autofightingAI.reset();
  739. }
  740. CBattleInterface *b = battleInt;
  741. if(!b)
  742. {
  743. return BattleAction::makeDefend(stack); // probably battle is finished already
  744. }
  745. if(CBattleInterface::givenCommand.get())
  746. {
  747. logGlobal->error("Command buffer must be clean! (we don't want to use old command)");
  748. vstd::clear_pointer(CBattleInterface::givenCommand.data);
  749. }
  750. {
  751. boost::unique_lock<boost::recursive_mutex> un(*pim);
  752. b->stackActivated(stack);
  753. //Regeneration & mana drain go there
  754. }
  755. //wait till BattleInterface sets its command
  756. boost::unique_lock<boost::mutex> lock(CBattleInterface::givenCommand.mx);
  757. while(!CBattleInterface::givenCommand.data)
  758. {
  759. CBattleInterface::givenCommand.cond.wait(lock);
  760. if (!battleInt) //battle ended while we were waiting for movement (eg. because of spell)
  761. throw boost::thread_interrupted(); //will shut the thread peacefully
  762. }
  763. //tidy up
  764. BattleAction ret = *(CBattleInterface::givenCommand.data);
  765. vstd::clear_pointer(CBattleInterface::givenCommand.data);
  766. if(ret.actionType == EActionType::CANCEL)
  767. {
  768. if(stackId != ret.stackNumber)
  769. logGlobal->error("Not current active stack action canceled");
  770. logGlobal->trace("Canceled command for %s", stackName);
  771. }
  772. else
  773. logGlobal->trace("Giving command for %s", stackName);
  774. return ret;
  775. }
  776. void CPlayerInterface::battleEnd(const BattleResult *br)
  777. {
  778. EVENT_HANDLER_CALLED_BY_CLIENT;
  779. if(isAutoFightOn || autofightingAI)
  780. {
  781. isAutoFightOn = false;
  782. cb->unregisterBattleInterface(autofightingAI);
  783. autofightingAI.reset();
  784. if(!battleInt)
  785. {
  786. GH.pushIntT<CBattleResultWindow>(*br, *this);
  787. // #1490 - during AI turn when quick combat is on, we need to display the message and wait for user to close it.
  788. // Otherwise NewTurn causes freeze.
  789. waitWhileDialog();
  790. adventureInt->quickCombatUnlock();
  791. return;
  792. }
  793. }
  794. BATTLE_EVENT_POSSIBLE_RETURN;
  795. battleInt->battleFinished(*br);
  796. adventureInt->quickCombatUnlock();
  797. }
  798. void CPlayerInterface::battleLogMessage(const std::vector<MetaString> & lines)
  799. {
  800. EVENT_HANDLER_CALLED_BY_CLIENT;
  801. BATTLE_EVENT_POSSIBLE_RETURN;
  802. battleInt->displayBattleLog(lines);
  803. }
  804. void CPlayerInterface::battleStackMoved(const CStack * stack, std::vector<BattleHex> dest, int distance)
  805. {
  806. EVENT_HANDLER_CALLED_BY_CLIENT;
  807. BATTLE_EVENT_POSSIBLE_RETURN;
  808. battleInt->stackMoved(stack, dest, distance);
  809. }
  810. void CPlayerInterface::battleSpellCast( const BattleSpellCast *sc )
  811. {
  812. EVENT_HANDLER_CALLED_BY_CLIENT;
  813. BATTLE_EVENT_POSSIBLE_RETURN;
  814. battleInt->spellCast(sc);
  815. }
  816. void CPlayerInterface::battleStacksEffectsSet( const SetStackEffect & sse )
  817. {
  818. EVENT_HANDLER_CALLED_BY_CLIENT;
  819. BATTLE_EVENT_POSSIBLE_RETURN;
  820. battleInt->battleStacksEffectsSet(sse);
  821. }
  822. void CPlayerInterface::battleTriggerEffect (const BattleTriggerEffect & bte)
  823. {
  824. EVENT_HANDLER_CALLED_BY_CLIENT;
  825. //TODO why is this different (no return on LOPLINT != this) ?
  826. RETURN_IF_QUICK_COMBAT;
  827. battleInt->battleTriggerEffect(bte);
  828. }
  829. void CPlayerInterface::battleStacksAttacked(const std::vector<BattleStackAttacked> & bsa)
  830. {
  831. EVENT_HANDLER_CALLED_BY_CLIENT;
  832. BATTLE_EVENT_POSSIBLE_RETURN;
  833. std::vector<StackAttackedInfo> arg;
  834. for(auto & elem : bsa)
  835. {
  836. const CStack * defender = cb->battleGetStackByID(elem.stackAttacked, false);
  837. const CStack * attacker = cb->battleGetStackByID(elem.attackerID, false);
  838. if(elem.isEffect())
  839. {
  840. if(defender && !elem.isSecondary())
  841. battleInt->displayEffect(elem.effect, defender->getPosition());
  842. }
  843. if(elem.isSpell())
  844. {
  845. if(defender)
  846. battleInt->displaySpellEffect(elem.spellID, defender->getPosition());
  847. }
  848. //FIXME: why action is deleted during enchanter cast?
  849. bool remoteAttack = false;
  850. if(LOCPLINT->curAction)
  851. remoteAttack |= LOCPLINT->curAction->actionType != EActionType::WALK_AND_ATTACK;
  852. StackAttackedInfo to_put = {defender, elem.damageAmount, elem.killedAmount, attacker, remoteAttack, elem.killed(), elem.willRebirth(), elem.cloneKilled()};
  853. arg.push_back(to_put);
  854. }
  855. battleInt->stacksAreAttacked(arg);
  856. }
  857. void CPlayerInterface::battleAttack(const BattleAttack * ba)
  858. {
  859. EVENT_HANDLER_CALLED_BY_CLIENT;
  860. BATTLE_EVENT_POSSIBLE_RETURN;
  861. assert(curAction);
  862. const CStack * attacker = cb->battleGetStackByID(ba->stackAttacking);
  863. if(!attacker)
  864. {
  865. logGlobal->error("Attacking stack not found");
  866. return;
  867. }
  868. if(ba->lucky()) //lucky hit
  869. {
  870. battleInt->console->addText(attacker->formatGeneralMessage(-45));
  871. battleInt->displayEffect(18, attacker->getPosition());
  872. CCS->soundh->playSound(soundBase::GOODLUCK);
  873. }
  874. if(ba->unlucky()) //unlucky hit
  875. {
  876. battleInt->console->addText(attacker->formatGeneralMessage(-44));
  877. battleInt->displayEffect(48, attacker->getPosition());
  878. CCS->soundh->playSound(soundBase::BADLUCK);
  879. }
  880. if(ba->deathBlow())
  881. {
  882. battleInt->console->addText(attacker->formatGeneralMessage(365));
  883. for(auto & elem : ba->bsa)
  884. {
  885. const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
  886. battleInt->displayEffect(73, attacked->getPosition());
  887. }
  888. CCS->soundh->playSound(soundBase::deathBlow);
  889. }
  890. battleInt->displayCustomEffects(ba->customEffects);
  891. battleInt->waitForAnims();
  892. auto actionTarget = curAction->getTarget(cb.get());
  893. if(actionTarget.empty() || (actionTarget.size() < 2 && !ba->shot()))
  894. {
  895. logNetwork->error("Invalid current action: no destination.");
  896. return;
  897. }
  898. if(ba->shot())
  899. {
  900. for(auto & elem : ba->bsa)
  901. {
  902. if(!elem.isSecondary()) //display projectile only for primary target
  903. {
  904. const CStack * attacked = cb->battleGetStackByID(elem.stackAttacked);
  905. battleInt->stackAttacking(attacker, attacked->getPosition(), attacked, true);
  906. }
  907. }
  908. }
  909. else
  910. {
  911. auto attackTarget = actionTarget.at(1).hexValue;
  912. //TODO: use information from BattleAttack but not curAction
  913. int shift = 0;
  914. if(ba->counter() && BattleHex::mutualPosition(attackTarget, attacker->getPosition()) < 0)
  915. {
  916. int distp = BattleHex::getDistance(attackTarget + 1, attacker->getPosition());
  917. int distm = BattleHex::getDistance(attackTarget - 1, attacker->getPosition());
  918. if(distp < distm)
  919. shift = 1;
  920. else
  921. shift = -1;
  922. }
  923. if(!ba->bsa.empty())
  924. {
  925. const CStack * attacked = cb->battleGetStackByID(ba->bsa.begin()->stackAttacked);
  926. battleInt->stackAttacking(attacker, ba->counter() ? BattleHex(attackTarget + shift) : attackTarget, attacked, false);
  927. }
  928. }
  929. //battleInt->waitForAnims(); //FIXME: freeze
  930. if(ba->spellLike())
  931. {
  932. //TODO: use information from BattleAttack but not curAction
  933. auto destination = actionTarget.at(0).hexValue;
  934. //display hit animation
  935. SpellID spellID = ba->spellID;
  936. battleInt->displaySpellHit(spellID, destination);
  937. }
  938. }
  939. void CPlayerInterface::battleGateStateChanged(const EGateState state)
  940. {
  941. EVENT_HANDLER_CALLED_BY_CLIENT;
  942. BATTLE_EVENT_POSSIBLE_RETURN;
  943. battleInt->gateStateChanged(state);
  944. }
  945. void CPlayerInterface::yourTacticPhase(int distance)
  946. {
  947. THREAD_CREATED_BY_CLIENT;
  948. while(battleInt && battleInt->tacticsMode)
  949. boost::this_thread::sleep(boost::posix_time::millisec(1));
  950. }
  951. void CPlayerInterface::showComp(const Component &comp, std::string message)
  952. {
  953. EVENT_HANDLER_CALLED_BY_CLIENT;
  954. waitWhileDialog(); //Fix for mantis #98
  955. CCS->soundh->playSoundFromSet(CCS->soundh->pickupSounds);
  956. adventureInt->infoBar.showComponent(comp, message);
  957. }
  958. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<Component> & components, int soundID)
  959. {
  960. EVENT_HANDLER_CALLED_BY_CLIENT;
  961. if (settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  962. {
  963. return;
  964. }
  965. std::vector<std::shared_ptr<CComponent>> intComps;
  966. for (auto & component : components)
  967. intComps.push_back(std::make_shared<CComponent>(component));
  968. showInfoDialog(text,intComps,soundID);
  969. }
  970. void CPlayerInterface::showInfoDialog(const std::string & text, std::shared_ptr<CComponent> component)
  971. {
  972. std::vector<std::shared_ptr<CComponent>> intComps;
  973. intComps.push_back(component);
  974. showInfoDialog(text, intComps, soundBase::sound_todo);
  975. }
  976. void CPlayerInterface::showInfoDialog(const std::string &text, const std::vector<std::shared_ptr<CComponent>> & components, int soundID)
  977. {
  978. LOG_TRACE_PARAMS(logGlobal, "player=%s, text=%s, is LOCPLINT=%d", playerID % text % (this==LOCPLINT));
  979. waitWhileDialog();
  980. if (settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  981. {
  982. return;
  983. }
  984. std::shared_ptr<CInfoWindow> temp = CInfoWindow::create(text, playerID, components);
  985. if (makingTurn && GH.listInt.size() && LOCPLINT == this)
  986. {
  987. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  988. showingDialog->set(true);
  989. stopMovement(); // interrupt movement to show dialog
  990. GH.pushInt(temp);
  991. }
  992. else
  993. {
  994. dialogs.push_back(temp);
  995. }
  996. }
  997. void CPlayerInterface::showInfoDialogAndWait(std::vector<Component> & components, const MetaString & text)
  998. {
  999. EVENT_HANDLER_CALLED_BY_CLIENT;
  1000. std::string str;
  1001. text.toString(str);
  1002. showInfoDialog(str, components, 0);
  1003. waitWhileDialog();
  1004. }
  1005. void CPlayerInterface::showYesNoDialog(const std::string &text, CFunctionList<void()> onYes, CFunctionList<void()> onNo, const std::vector<std::shared_ptr<CComponent>> & components)
  1006. {
  1007. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1008. stopMovement();
  1009. LOCPLINT->showingDialog->setn(true);
  1010. CInfoWindow::showYesNoDialog(text, components, onYes, onNo, playerID);
  1011. }
  1012. void CPlayerInterface::showBlockingDialog( const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel )
  1013. {
  1014. EVENT_HANDLER_CALLED_BY_CLIENT;
  1015. waitWhileDialog();
  1016. stopMovement();
  1017. CCS->soundh->playSound(static_cast<soundBase::soundID>(soundID));
  1018. if (!selection && cancel) //simple yes/no dialog
  1019. {
  1020. std::vector<std::shared_ptr<CComponent>> intComps;
  1021. for (auto & component : components)
  1022. intComps.push_back(std::make_shared<CComponent>(component)); //will be deleted by close in window
  1023. showYesNoDialog(text, [=](){ cb->selectionMade(1, askID); }, [=](){ cb->selectionMade(0, askID); }, intComps);
  1024. }
  1025. else if (selection)
  1026. {
  1027. std::vector<std::shared_ptr<CSelectableComponent>> intComps;
  1028. for (auto & component : components)
  1029. intComps.push_back(std::make_shared<CSelectableComponent>(component)); //will be deleted by CSelWindow::close
  1030. std::vector<std::pair<std::string,CFunctionList<void()> > > pom;
  1031. pom.push_back(std::pair<std::string,CFunctionList<void()> >("IOKAY.DEF",0));
  1032. if (cancel)
  1033. {
  1034. pom.push_back(std::pair<std::string,CFunctionList<void()> >("ICANCEL.DEF",0));
  1035. }
  1036. int charperline = 35;
  1037. if (pom.size() > 1)
  1038. charperline = 50;
  1039. GH.pushIntT<CSelWindow>(text, playerID, charperline, intComps, pom, askID);
  1040. intComps[0]->clickLeft(true, false);
  1041. }
  1042. }
  1043. void CPlayerInterface::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  1044. {
  1045. EVENT_HANDLER_CALLED_BY_CLIENT;
  1046. int choosenExit = -1;
  1047. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  1048. if (destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  1049. choosenExit = vstd::find_pos(exits, neededExit);
  1050. cb->selectionMade(choosenExit, askID);
  1051. }
  1052. void CPlayerInterface::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  1053. {
  1054. EVENT_HANDLER_CALLED_BY_CLIENT;
  1055. auto selectCallback = [=](int selection)
  1056. {
  1057. JsonNode reply(JsonNode::JsonType::DATA_INTEGER);
  1058. reply.Integer() = selection;
  1059. cb->sendQueryReply(reply, askID);
  1060. };
  1061. auto cancelCallback = [=]()
  1062. {
  1063. JsonNode reply(JsonNode::JsonType::DATA_NULL);
  1064. cb->sendQueryReply(reply, askID);
  1065. };
  1066. const std::string localTitle = title.toString();
  1067. const std::string localDescription = description.toString();
  1068. std::vector<int> tempList;
  1069. tempList.reserve(objects.size());
  1070. for(auto item : objects)
  1071. tempList.push_back(item.getNum());
  1072. CComponent localIconC(icon);
  1073. std::shared_ptr<CIntObject> localIcon = localIconC.image;
  1074. localIconC.removeChild(localIcon.get(), false);
  1075. std::shared_ptr<CObjectListWindow> wnd = std::make_shared<CObjectListWindow>(tempList, localIcon, localTitle, localDescription, selectCallback);
  1076. wnd->onExit = cancelCallback;
  1077. GH.pushInt(wnd);
  1078. }
  1079. void CPlayerInterface::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  1080. {
  1081. EVENT_HANDLER_CALLED_BY_CLIENT;
  1082. //FIXME: wait for dialog? Magi hut/eye would benefit from this but may break other areas
  1083. for (auto & po : pos)
  1084. adventureInt->minimap.showTile(po);
  1085. if (!pos.empty())
  1086. GH.totalRedraw();
  1087. }
  1088. void CPlayerInterface::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  1089. {
  1090. EVENT_HANDLER_CALLED_BY_CLIENT;
  1091. for (auto & po : pos)
  1092. adventureInt->minimap.hideTile(po);
  1093. if (!pos.empty())
  1094. GH.totalRedraw();
  1095. }
  1096. void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
  1097. {
  1098. boost::unique_lock<boost::recursive_mutex> un(*pim);
  1099. GH.pushIntT<CHeroWindow>(hero);
  1100. }
  1101. void CPlayerInterface::availableCreaturesChanged( const CGDwelling *town )
  1102. {
  1103. EVENT_HANDLER_CALLED_BY_CLIENT;
  1104. if (const CGTownInstance * townObj = dynamic_cast<const CGTownInstance*>(town))
  1105. {
  1106. CFortScreen *fs = dynamic_cast<CFortScreen*>(GH.topInt().get());
  1107. if (fs)
  1108. fs->creaturesChanged();
  1109. for(auto isa : GH.listInt)
  1110. {
  1111. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  1112. if (ki && townObj)
  1113. ki->townChanged(townObj);
  1114. }
  1115. }
  1116. else if(town && GH.listInt.size() && (town->ID == Obj::CREATURE_GENERATOR1
  1117. || town->ID == Obj::CREATURE_GENERATOR4 || town->ID == Obj::WAR_MACHINE_FACTORY))
  1118. {
  1119. CRecruitmentWindow *crw = dynamic_cast<CRecruitmentWindow*>(GH.topInt().get());
  1120. if (crw && crw->dwelling == town)
  1121. crw->availableCreaturesChanged();
  1122. }
  1123. }
  1124. void CPlayerInterface::heroBonusChanged( const CGHeroInstance *hero, const Bonus &bonus, bool gain )
  1125. {
  1126. EVENT_HANDLER_CALLED_BY_CLIENT;
  1127. if (bonus.type == Bonus::NONE)
  1128. return;
  1129. updateInfo(hero);
  1130. if ((bonus.type == Bonus::FLYING_MOVEMENT || bonus.type == Bonus::WATER_WALKING) && !gain)
  1131. {
  1132. //recalculate paths because hero has lost bonus influencing pathfinding
  1133. eraseCurrentPathOf(hero, false);
  1134. }
  1135. }
  1136. template <typename Handler> void CPlayerInterface::serializeTempl( Handler &h, const int version )
  1137. {
  1138. h & wanderingHeroes;
  1139. h & towns;
  1140. h & sleepingHeroes;
  1141. std::map<const CGHeroInstance *, int3> pathsMap; //hero -> dest
  1142. if (h.saving)
  1143. {
  1144. for (auto &p : paths)
  1145. {
  1146. if (p.second.nodes.size())
  1147. pathsMap[p.first] = p.second.endPos();
  1148. else
  1149. logGlobal->debug("%s has assigned an empty path! Ignoring it...", p.first->name);
  1150. }
  1151. h & pathsMap;
  1152. }
  1153. else
  1154. {
  1155. h & pathsMap;
  1156. if (cb)
  1157. for (auto &p : pathsMap)
  1158. {
  1159. CGPath path;
  1160. cb->getPathsInfo(p.first)->getPath(path, p.second);
  1161. paths[p.first] = path;
  1162. logGlobal->trace("Restored path for hero %s leading to %s with %d nodes", p.first->nodeName(), p.second.toString(), path.nodes.size());
  1163. }
  1164. }
  1165. h & spellbookSettings;
  1166. }
  1167. void CPlayerInterface::saveGame( BinarySerializer & h, const int version )
  1168. {
  1169. EVENT_HANDLER_CALLED_BY_CLIENT;
  1170. serializeTempl(h,version);
  1171. }
  1172. void CPlayerInterface::loadGame( BinaryDeserializer & h, const int version )
  1173. {
  1174. EVENT_HANDLER_CALLED_BY_CLIENT;
  1175. serializeTempl(h,version);
  1176. firstCall = -1;
  1177. }
  1178. void CPlayerInterface::moveHero( const CGHeroInstance *h, CGPath path )
  1179. {
  1180. LOG_TRACE(logGlobal);
  1181. if (!LOCPLINT->makingTurn)
  1182. return;
  1183. if (!h)
  1184. return; //can't find hero
  1185. //It shouldn't be possible to move hero with open dialog (or dialog waiting in bg)
  1186. if (showingDialog->get() || !dialogs.empty())
  1187. return;
  1188. setMovementStatus(true);
  1189. if (adventureInt && adventureInt->isHeroSleeping(h))
  1190. {
  1191. adventureInt->sleepWake->clickLeft(true, false);
  1192. adventureInt->sleepWake->clickLeft(false, true);
  1193. //could've just called
  1194. //adventureInt->fsleepWake();
  1195. //but no authentic button click/sound ;-)
  1196. }
  1197. boost::thread moveHeroTask(std::bind(&CPlayerInterface::doMoveHero,this,h,path));
  1198. }
  1199. bool CPlayerInterface::shiftPressed() const
  1200. {
  1201. return isShiftKeyDown();
  1202. }
  1203. bool CPlayerInterface::altPressed() const
  1204. {
  1205. return isAltKeyDown();
  1206. }
  1207. void CPlayerInterface::showGarrisonDialog( const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  1208. {
  1209. EVENT_HANDLER_CALLED_BY_CLIENT;
  1210. auto onEnd = [=](){ cb->selectionMade(0, queryID); };
  1211. if (stillMoveHero.get() == DURING_MOVE && adventureInt->terrain.currentPath && adventureInt->terrain.currentPath->nodes.size() > 1) //to ignore calls on passing through garrisons
  1212. {
  1213. onEnd();
  1214. return;
  1215. }
  1216. waitForAllDialogs();
  1217. auto cgw = std::make_shared<CGarrisonWindow>(up, down, removableUnits);
  1218. cgw->quit->addCallback(onEnd);
  1219. GH.pushInt(cgw);
  1220. }
  1221. /**
  1222. * Shows the dialog that appears when right-clicking an artifact that can be assembled
  1223. * into a combinational one on an artifact screen. Does not require the combination of
  1224. * artifacts to be legal.
  1225. */
  1226. void CPlayerInterface::showArtifactAssemblyDialog(const Artifact * artifact, const Artifact * assembledArtifact, CFunctionList<bool()> onYes)
  1227. {
  1228. std::string text = artifact->getDescription();
  1229. text += "\n\n";
  1230. std::vector<std::shared_ptr<CComponent>> scs;
  1231. if(assembledArtifact)
  1232. {
  1233. // You possess all of the components to...
  1234. text += boost::str(boost::format(CGI->generaltexth->allTexts[732]) % assembledArtifact->getName());
  1235. // Picture of assembled artifact at bottom.
  1236. auto sc = std::make_shared<CComponent>(CComponent::artifact, assembledArtifact->getIndex(), 0);
  1237. scs.push_back(sc);
  1238. }
  1239. else
  1240. {
  1241. // Do you wish to disassemble this artifact?
  1242. text += CGI->generaltexth->allTexts[733];
  1243. }
  1244. showYesNoDialog(text, onYes, nullptr, scs);
  1245. }
  1246. void CPlayerInterface::requestRealized( PackageApplied *pa )
  1247. {
  1248. EVENT_HANDLER_CALLED_BY_CLIENT;
  1249. if (pa->packType == typeList.getTypeID<MoveHero>() && stillMoveHero.get() == DURING_MOVE
  1250. && destinationTeleport == ObjectInstanceID())
  1251. stillMoveHero.setn(CONTINUE_MOVE);
  1252. if (destinationTeleport != ObjectInstanceID()
  1253. && pa->packType == typeList.getTypeID<QueryReply>()
  1254. && stillMoveHero.get() == DURING_MOVE)
  1255. { // After teleportation via CGTeleport object is finished
  1256. destinationTeleport = ObjectInstanceID();
  1257. destinationTeleportPos = int3(-1);
  1258. stillMoveHero.setn(CONTINUE_MOVE);
  1259. }
  1260. }
  1261. void CPlayerInterface::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  1262. {
  1263. EVENT_HANDLER_CALLED_BY_CLIENT;
  1264. GH.pushIntT<CExchangeWindow>(hero1, hero2, query);
  1265. }
  1266. void CPlayerInterface::objectPropertyChanged(const SetObjectProperty * sop)
  1267. {
  1268. EVENT_HANDLER_CALLED_BY_CLIENT;
  1269. //redraw minimap if owner changed
  1270. if (sop->what == ObjProperty::OWNER)
  1271. {
  1272. const CGObjectInstance * obj = cb->getObj(sop->id);
  1273. std::set<int3> pos = obj->getBlockedPos();
  1274. for(auto & po : pos)
  1275. {
  1276. if(cb->isVisible(po))
  1277. adventureInt->minimap.showTile(po);
  1278. }
  1279. if(obj->ID == Obj::TOWN)
  1280. {
  1281. if(obj->tempOwner == playerID)
  1282. towns.push_back(static_cast<const CGTownInstance *>(obj));
  1283. else
  1284. towns -= obj;
  1285. adventureInt->townList.update();
  1286. adventureInt->minimap.update();
  1287. }
  1288. assert(cb->getTownsInfo().size() == towns.size());
  1289. }
  1290. }
  1291. void CPlayerInterface::initializeHeroTownList()
  1292. {
  1293. if(!wanderingHeroes.size())
  1294. {
  1295. std::vector<const CGHeroInstance*> heroes = cb->getHeroesInfo();
  1296. for(auto & hero : heroes)
  1297. {
  1298. if(!hero->inTownGarrison)
  1299. wanderingHeroes.push_back(hero);
  1300. }
  1301. }
  1302. if(!towns.size())
  1303. towns = cb->getTownsInfo();
  1304. if(adventureInt)
  1305. adventureInt->updateNextHero(nullptr);
  1306. }
  1307. void CPlayerInterface::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  1308. {
  1309. EVENT_HANDLER_CALLED_BY_CLIENT;
  1310. waitWhileDialog();
  1311. auto recruitCb = [=](CreatureID id, int count)
  1312. {
  1313. LOCPLINT->cb->recruitCreatures(dwelling, dst, id, count, -1);
  1314. };
  1315. GH.pushIntT<CRecruitmentWindow>(dwelling, level, dst, recruitCb);
  1316. }
  1317. void CPlayerInterface::waitWhileDialog(bool unlockPim)
  1318. {
  1319. if (GH.amIGuiThread())
  1320. {
  1321. logGlobal->warn("Cannot wait for dialogs in gui thread (deadlock risk)!");
  1322. return;
  1323. }
  1324. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  1325. boost::unique_lock<boost::mutex> un(showingDialog->mx);
  1326. while(showingDialog->data)
  1327. showingDialog->cond.wait(un);
  1328. }
  1329. void CPlayerInterface::showShipyardDialog(const IShipyard *obj)
  1330. {
  1331. EVENT_HANDLER_CALLED_BY_CLIENT;
  1332. auto state = obj->shipyardStatus();
  1333. std::vector<si32> cost;
  1334. obj->getBoatCost(cost);
  1335. GH.pushIntT<CShipyardWindow>(cost, state, obj->getBoatType(), [=](){ cb->buildBoat(obj); });
  1336. }
  1337. void CPlayerInterface::newObject( const CGObjectInstance * obj )
  1338. {
  1339. EVENT_HANDLER_CALLED_BY_CLIENT;
  1340. //we might have built a boat in shipyard in opened town screen
  1341. if (obj->ID == Obj::BOAT
  1342. && LOCPLINT->castleInt
  1343. && obj->visitablePos() == LOCPLINT->castleInt->town->bestLocation())
  1344. {
  1345. CCS->soundh->playSound(soundBase::newBuilding);
  1346. LOCPLINT->castleInt->addBuilding(BuildingID::SHIP);
  1347. }
  1348. }
  1349. void CPlayerInterface::centerView (int3 pos, int focusTime)
  1350. {
  1351. EVENT_HANDLER_CALLED_BY_CLIENT;
  1352. waitWhileDialog();
  1353. CCS->curh->hide();
  1354. adventureInt->centerOn (pos);
  1355. if (focusTime)
  1356. {
  1357. GH.totalRedraw();
  1358. {
  1359. auto unlockPim = vstd::makeUnlockGuard(*pim);
  1360. IgnoreEvents ignore(*this);
  1361. SDL_Delay(focusTime);
  1362. }
  1363. }
  1364. CCS->curh->show();
  1365. }
  1366. void CPlayerInterface::objectRemoved(const CGObjectInstance * obj)
  1367. {
  1368. EVENT_HANDLER_CALLED_BY_CLIENT;
  1369. if(LOCPLINT->cb->getCurrentPlayer() == playerID && obj->getRemovalSound())
  1370. {
  1371. waitWhileDialog();
  1372. CCS->soundh->playSound(obj->getRemovalSound().get());
  1373. }
  1374. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  1375. {
  1376. const CGHeroInstance * h = static_cast<const CGHeroInstance *>(obj);
  1377. heroKilled(h);
  1378. }
  1379. }
  1380. void CPlayerInterface::playerBlocked(int reason, bool start)
  1381. {
  1382. if(reason == PlayerBlocked::EReason::UPCOMING_BATTLE)
  1383. {
  1384. if(CSH->howManyPlayerInterfaces() > 1 && LOCPLINT != this && LOCPLINT->makingTurn == false)
  1385. {
  1386. //one of our players who isn't last in order got attacked not by our another player (happens for example in hotseat mode)
  1387. boost::unique_lock<boost::mutex> lock(eventsM); //TODO: copied from yourTurn, no idea if it's needed
  1388. LOCPLINT = this;
  1389. GH.curInt = this;
  1390. adventureInt->selection = nullptr;
  1391. adventureInt->setPlayer(playerID);
  1392. std::string msg = CGI->generaltexth->localizedTexts["adventureMap"]["playerAttacked"].String();
  1393. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  1394. std::vector<std::shared_ptr<CComponent>> cmp;
  1395. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  1396. makingTurn = true; //workaround for stiff showInfoDialog implementation
  1397. showInfoDialog(msg, cmp);
  1398. makingTurn = false;
  1399. }
  1400. }
  1401. }
  1402. bool CPlayerInterface::ctrlPressed() const
  1403. {
  1404. return isCtrlKeyDown();
  1405. }
  1406. const CArmedInstance * CPlayerInterface::getSelection()
  1407. {
  1408. return currentSelection;
  1409. }
  1410. void CPlayerInterface::setSelection(const CArmedInstance * obj)
  1411. {
  1412. currentSelection = obj;
  1413. updateAmbientSounds(true);
  1414. }
  1415. void CPlayerInterface::update()
  1416. {
  1417. // Make sure that gamestate won't change when GUI objects may obtain its parts on event processing or drawing request
  1418. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1419. // While mutexes were locked away we may be have stopped being the active interface
  1420. if (LOCPLINT != this)
  1421. return;
  1422. //if there are any waiting dialogs, show them
  1423. if ((CSH->howManyPlayerInterfaces() <= 1 || makingTurn) && !dialogs.empty() && !showingDialog->get())
  1424. {
  1425. showingDialog->set(true);
  1426. GH.pushInt(dialogs.front());
  1427. dialogs.pop_front();
  1428. }
  1429. //in some conditions we may receive calls before selection is initialized - we must ignore them
  1430. if(adventureInt && GH.topInt() == adventureInt
  1431. && (!adventureInt->selection && !settings["session"]["spectate"].Bool()))
  1432. {
  1433. return;
  1434. }
  1435. // Handles mouse and key input
  1436. GH.updateTime();
  1437. GH.handleEvents();
  1438. if (!adventureInt || adventureInt->isActive())
  1439. GH.simpleRedraw();
  1440. else if((adventureInt->swipeEnabled && adventureInt->swipeMovementRequested) || adventureInt->scrollingDir)
  1441. GH.totalRedraw(); //player forces map scrolling though interface is disabled
  1442. else
  1443. GH.simpleRedraw();
  1444. }
  1445. int CPlayerInterface::getLastIndex( std::string namePrefix)
  1446. {
  1447. using namespace boost::filesystem;
  1448. using namespace boost::algorithm;
  1449. path gamesDir = VCMIDirs::get().userSavePath();
  1450. std::map<std::time_t, int> dates; //save number => datestamp
  1451. const directory_iterator enddir;
  1452. if (!exists(gamesDir))
  1453. create_directory(gamesDir);
  1454. else
  1455. for (directory_iterator dir(gamesDir); dir != enddir; ++dir)
  1456. {
  1457. if (is_regular(dir->status()))
  1458. {
  1459. std::string name = dir->path().filename().string();
  1460. if (starts_with(name, namePrefix) && ends_with(name, ".vcgm1"))
  1461. {
  1462. char nr = name[namePrefix.size()];
  1463. if (std::isdigit(nr))
  1464. dates[last_write_time(dir->path())] = boost::lexical_cast<int>(nr);
  1465. }
  1466. }
  1467. }
  1468. if (!dates.empty())
  1469. return (--dates.end())->second; //return latest file number
  1470. return 0;
  1471. }
  1472. void CPlayerInterface::initMovement( const TryMoveHero &details, const CGHeroInstance * ho, const int3 &hp )
  1473. {
  1474. auto subArr = (CGI->mh->ttiles)[hp.z];
  1475. ho->isStanding = false;
  1476. int heroWidth = ho->appearance->getWidth();
  1477. int heroHeight = ho->appearance->getHeight();
  1478. int tileMinX = std::min(details.start.x, details.end.x) - heroWidth;
  1479. int tileMaxX = std::max(details.start.x, details.end.x);
  1480. int tileMinY = std::min(details.start.y, details.end.y) - heroHeight;
  1481. int tileMaxY = std::max(details.start.y, details.end.y);
  1482. // determine tiles on which hero will be visible during movement and add hero as visible object on these tiles where necessary
  1483. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1484. {
  1485. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1486. {
  1487. bool heroVisibleHere = false;
  1488. auto & tile = subArr[tileX][tileY];
  1489. for ( auto const & obj : tile.objects)
  1490. {
  1491. if (obj.obj == ho)
  1492. {
  1493. heroVisibleHere = true;
  1494. break;
  1495. }
  1496. }
  1497. if ( !heroVisibleHere)
  1498. {
  1499. tile.objects.push_back(TerrainTileObject(ho, {0,0,32,32}));
  1500. std::stable_sort(tile.objects.begin(), tile.objects.end(), objectBlitOrderSorter);
  1501. }
  1502. }
  1503. }
  1504. }
  1505. void CPlayerInterface::movementPxStep( const TryMoveHero &details, int i, const int3 &hp, const CGHeroInstance * ho )
  1506. {
  1507. auto subArr = (CGI->mh->ttiles)[hp.z];
  1508. int heroWidth = ho->appearance->getWidth();
  1509. int heroHeight = ho->appearance->getHeight();
  1510. int tileMinX = std::min(details.start.x, details.end.x) - heroWidth;
  1511. int tileMaxX = std::max(details.start.x, details.end.x);
  1512. int tileMinY = std::min(details.start.y, details.end.y) - heroHeight;
  1513. int tileMaxY = std::max(details.start.y, details.end.y);
  1514. std::shared_ptr<CAnimation> animation = graphics->getAnimation(ho);
  1515. assert(animation);
  1516. assert(animation->size(0) != 0);
  1517. auto image = animation->getImage(0,0);
  1518. int heroImageOldX = details.start.x * 32;
  1519. int heroImageOldY = details.start.y * 32;
  1520. int heroImageNewX = details.end.x * 32;
  1521. int heroImageNewY = details.end.y * 32;
  1522. int heroImageCurrX = heroImageOldX + i*(heroImageNewX - heroImageOldX)/32;
  1523. int heroImageCurrY = heroImageOldY + i*(heroImageNewY - heroImageOldY)/32;
  1524. // recompute which part of hero sprite will be visible on each tile at this point of movement animation
  1525. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1526. {
  1527. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1528. {
  1529. auto & tile = subArr[tileX][tileY];
  1530. for ( auto & obj : tile.objects)
  1531. {
  1532. if (obj.obj == ho)
  1533. {
  1534. int tilePosX = tileX * 32;
  1535. int tilePosY = tileY * 32;
  1536. obj.rect.x = tilePosX - heroImageCurrX + image->width() - 32;
  1537. obj.rect.y = tilePosY - heroImageCurrY + image->height() - 32;
  1538. }
  1539. }
  1540. }
  1541. }
  1542. adventureInt->terrain.moveX = (32 - i) * (heroImageNewX - heroImageOldX) / 32;
  1543. adventureInt->terrain.moveY = (32 - i) * (heroImageNewY - heroImageOldY) / 32;
  1544. }
  1545. void CPlayerInterface::finishMovement( const TryMoveHero &details, const int3 &hp, const CGHeroInstance * ho )
  1546. {
  1547. auto subArr = (CGI->mh->ttiles)[hp.z];
  1548. int heroWidth = ho->appearance->getWidth();
  1549. int heroHeight = ho->appearance->getHeight();
  1550. int tileMinX = std::min(details.start.x, details.end.x) - heroWidth;
  1551. int tileMaxX = std::max(details.start.x, details.end.x);
  1552. int tileMinY = std::min(details.start.y, details.end.y) - heroHeight;
  1553. int tileMaxY = std::max(details.start.y, details.end.y);
  1554. // erase hero from all tiles on which he is currently visible
  1555. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1556. {
  1557. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1558. {
  1559. auto & tile = subArr[tileX][tileY];
  1560. for (size_t i = 0; i < tile.objects.size(); ++i)
  1561. {
  1562. if ( tile.objects[i].obj == ho)
  1563. {
  1564. tile.objects.erase(tile.objects.begin() + i);
  1565. break;
  1566. }
  1567. }
  1568. }
  1569. }
  1570. // re-add hero to all tiles on which he will still be visible after animation is over
  1571. for ( int tileX = details.end.x - heroWidth + 1; tileX <= details.end.x; ++tileX)
  1572. {
  1573. for ( int tileY = details.end.y - heroHeight + 1; tileY <= details.end.y; ++tileY)
  1574. {
  1575. auto & tile = subArr[tileX][tileY];
  1576. tile.objects.push_back(TerrainTileObject(ho, {0,0,32,32}));
  1577. }
  1578. }
  1579. // update object list on all tiles that were affected during previous operations
  1580. for ( int tileX = tileMinX; tileX <= tileMaxX; ++tileX)
  1581. {
  1582. for ( int tileY = tileMinY; tileY <= tileMaxY; ++tileY)
  1583. {
  1584. auto & tile = subArr[tileX][tileY];
  1585. std::stable_sort(tile.objects.begin(), tile.objects.end(), objectBlitOrderSorter);
  1586. }
  1587. }
  1588. //recompute hero sprite positioning using hero's final position
  1589. movementPxStep(details, 32, hp, ho);
  1590. }
  1591. void CPlayerInterface::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult )
  1592. {
  1593. EVENT_HANDLER_CALLED_BY_CLIENT;
  1594. if (player == playerID)
  1595. {
  1596. if (victoryLossCheckResult.loss())
  1597. showInfoDialog(CGI->generaltexth->allTexts[95]);
  1598. //we assume GH.curInt == LOCPLINT
  1599. auto previousInterface = LOCPLINT; //without multiple player interfaces some of lines below are useless, but for hotseat we wanna swap player interface temporarily
  1600. LOCPLINT = this; //this is needed for dialog to show and avoid freeze, dialog showing logic should be reworked someday
  1601. GH.curInt = this; //waiting for dialogs requires this to get events
  1602. if(!makingTurn)
  1603. {
  1604. makingTurn = true; //also needed for dialog to show with current implementation
  1605. waitForAllDialogs();
  1606. makingTurn = false;
  1607. }
  1608. else
  1609. waitForAllDialogs();
  1610. GH.curInt = previousInterface;
  1611. LOCPLINT = previousInterface;
  1612. if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool()) //all human players eliminated
  1613. {
  1614. if(adventureInt)
  1615. {
  1616. GH.terminate_cond->setn(true);
  1617. adventureInt->deactivate();
  1618. if (GH.topInt() == adventureInt)
  1619. GH.popInt(adventureInt);
  1620. adventureInt.reset();
  1621. }
  1622. }
  1623. if (victoryLossCheckResult.victory() && LOCPLINT == this)
  1624. {
  1625. // end game if current human player has won
  1626. CSH->sendClientDisconnecting();
  1627. requestReturningToMainMenu(true);
  1628. }
  1629. else if(CSH->howManyPlayerInterfaces() == 1 && !settings["session"]["spectate"].Bool())
  1630. {
  1631. //all human players eliminated
  1632. CSH->sendClientDisconnecting();
  1633. requestReturningToMainMenu(false);
  1634. }
  1635. if (GH.curInt == this) GH.curInt = nullptr;
  1636. }
  1637. else
  1638. {
  1639. if (victoryLossCheckResult.loss() && cb->getPlayerStatus(playerID) == EPlayerStatus::INGAME) //enemy has lost
  1640. {
  1641. std::string str = victoryLossCheckResult.messageToSelf;
  1642. boost::algorithm::replace_first(str, "%s", CGI->generaltexth->capColors[player.getNum()]);
  1643. showInfoDialog(str, std::vector<std::shared_ptr<CComponent>>(1, std::make_shared<CComponent>(CComponent::flag, player.getNum(), 0)));
  1644. }
  1645. }
  1646. }
  1647. void CPlayerInterface::playerBonusChanged( const Bonus &bonus, bool gain )
  1648. {
  1649. EVENT_HANDLER_CALLED_BY_CLIENT;
  1650. }
  1651. void CPlayerInterface::showPuzzleMap()
  1652. {
  1653. EVENT_HANDLER_CALLED_BY_CLIENT;
  1654. waitWhileDialog();
  1655. //TODO: interface should not know the real position of Grail...
  1656. double ratio = 0;
  1657. int3 grailPos = cb->getGrailPos(&ratio);
  1658. GH.pushIntT<CPuzzleWindow>(grailPos, ratio);
  1659. }
  1660. void CPlayerInterface::viewWorldMap()
  1661. {
  1662. adventureInt->changeMode(EAdvMapMode::WORLD_VIEW);
  1663. }
  1664. void CPlayerInterface::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  1665. {
  1666. EVENT_HANDLER_CALLED_BY_CLIENT;
  1667. if(dynamic_cast<CSpellWindow *>(GH.topInt().get()))
  1668. GH.popInts(1);
  1669. if(spellID == SpellID::FLY || spellID == SpellID::WATER_WALK)
  1670. eraseCurrentPathOf(caster, false);
  1671. const spells::Spell * spell = CGI->spells()->getByIndex(spellID);
  1672. if(spellID == SpellID::VIEW_EARTH)
  1673. {
  1674. //TODO: implement on server side
  1675. const auto level = caster->getSpellSchoolLevel(spell);
  1676. adventureInt->worldViewOptions.showAllTerrain = (level > 2);
  1677. }
  1678. auto castSoundPath = spell->getCastSound();
  1679. if(!castSoundPath.empty())
  1680. CCS->soundh->playSound(castSoundPath);
  1681. }
  1682. void CPlayerInterface::eraseCurrentPathOf(const CGHeroInstance * ho, bool checkForExistanceOfPath)
  1683. {
  1684. if (checkForExistanceOfPath)
  1685. {
  1686. assert(vstd::contains(paths, ho));
  1687. }
  1688. else if (!vstd::contains(paths, ho))
  1689. {
  1690. return;
  1691. }
  1692. assert(ho == adventureInt->selection);
  1693. paths.erase(ho);
  1694. adventureInt->terrain.currentPath = nullptr;
  1695. adventureInt->updateMoveHero(ho, false);
  1696. }
  1697. void CPlayerInterface::removeLastNodeFromPath(const CGHeroInstance *ho)
  1698. {
  1699. adventureInt->terrain.currentPath->nodes.erase(adventureInt->terrain.currentPath->nodes.end()-1);
  1700. 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
  1701. eraseCurrentPathOf(ho);
  1702. }
  1703. CGPath * CPlayerInterface::getAndVerifyPath(const CGHeroInstance * h)
  1704. {
  1705. if (vstd::contains(paths,h)) //hero has assigned path
  1706. {
  1707. CGPath &path = paths[h];
  1708. if (!path.nodes.size())
  1709. {
  1710. logGlobal->warn("Warning: empty path found...");
  1711. paths.erase(h);
  1712. }
  1713. else
  1714. {
  1715. assert(h->visitablePos() == path.startPos());
  1716. //update the hero path in case of something has changed on map
  1717. if (LOCPLINT->cb->getPathsInfo(h)->getPath(path, path.endPos()))
  1718. return &path;
  1719. else
  1720. paths.erase(h);
  1721. }
  1722. }
  1723. return nullptr;
  1724. }
  1725. void CPlayerInterface::acceptTurn()
  1726. {
  1727. bool centerView = true;
  1728. if (settings["session"]["autoSkip"].Bool())
  1729. {
  1730. centerView = false;
  1731. while(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt().get()))
  1732. iw->close();
  1733. }
  1734. if(CSH->howManyPlayerInterfaces() > 1)
  1735. {
  1736. waitWhileDialog(); // wait for player to accept turn in hot-seat mode
  1737. adventureInt->startTurn();
  1738. }
  1739. adventureInt->heroList.update();
  1740. adventureInt->townList.update();
  1741. const CGHeroInstance * heroToSelect = nullptr;
  1742. // find first non-sleeping hero
  1743. for (auto hero : wanderingHeroes)
  1744. {
  1745. if (boost::range::find(sleepingHeroes, hero) == sleepingHeroes.end())
  1746. {
  1747. heroToSelect = hero;
  1748. break;
  1749. }
  1750. }
  1751. //select first hero if available.
  1752. if (heroToSelect != nullptr)
  1753. {
  1754. adventureInt->select(heroToSelect, centerView);
  1755. }
  1756. else if (towns.size())
  1757. adventureInt->select(towns.front(), centerView);
  1758. else
  1759. adventureInt->select(wanderingHeroes.front());
  1760. //show new day animation and sound on infobar
  1761. adventureInt->infoBar.showDate();
  1762. adventureInt->updateNextHero(nullptr);
  1763. adventureInt->showAll(screen);
  1764. if(settings["session"]["autoSkip"].Bool() && !LOCPLINT->shiftPressed())
  1765. {
  1766. if(CInfoWindow *iw = dynamic_cast<CInfoWindow *>(GH.topInt().get()))
  1767. iw->close();
  1768. adventureInt->fendTurn();
  1769. }
  1770. // warn player if he has no town
  1771. if (cb->howManyTowns() == 0)
  1772. {
  1773. auto playerColor = *cb->getPlayerID();
  1774. std::vector<Component> components;
  1775. components.push_back(Component(Component::FLAG, playerColor.getNum(), 0, 0));
  1776. MetaString text;
  1777. const auto & optDaysWithoutCastle = cb->getPlayerState(playerColor)->daysWithoutCastle;
  1778. if(optDaysWithoutCastle)
  1779. {
  1780. auto daysWithoutCastle = optDaysWithoutCastle.get();
  1781. if (daysWithoutCastle < 6)
  1782. {
  1783. 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.
  1784. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  1785. text.addReplacement(7 - daysWithoutCastle);
  1786. }
  1787. else if (daysWithoutCastle == 6)
  1788. {
  1789. text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  1790. text.addReplacement(MetaString::COLOR, playerColor.getNum());
  1791. }
  1792. showInfoDialogAndWait(components, text);
  1793. }
  1794. else
  1795. logGlobal->warn("Player has no towns, but daysWithoutCastle is not set");
  1796. }
  1797. }
  1798. void CPlayerInterface::tryDiggging(const CGHeroInstance * h)
  1799. {
  1800. int msgToShow = -1;
  1801. const bool isBlocked = CGI->mh->hasObjectHole(h->visitablePos()); // Don't dig in the pit.
  1802. const auto diggingStatus = isBlocked
  1803. ? EDiggingStatus::TILE_OCCUPIED
  1804. : h->diggingStatus().num;
  1805. switch(diggingStatus)
  1806. {
  1807. case EDiggingStatus::CAN_DIG:
  1808. break;
  1809. case EDiggingStatus::LACK_OF_MOVEMENT:
  1810. msgToShow = 56; //"Digging for artifacts requires a whole day, try again tomorrow."
  1811. break;
  1812. case EDiggingStatus::TILE_OCCUPIED:
  1813. msgToShow = 97; //Try searching on clear ground.
  1814. break;
  1815. case EDiggingStatus::WRONG_TERRAIN:
  1816. msgToShow = 60; ////Try looking on land!
  1817. break;
  1818. default:
  1819. assert(0);
  1820. }
  1821. if(msgToShow < 0)
  1822. cb->dig(h);
  1823. else
  1824. showInfoDialog(CGI->generaltexth->allTexts[msgToShow]);
  1825. }
  1826. void CPlayerInterface::updateInfo(const CGObjectInstance * specific)
  1827. {
  1828. adventureInt->infoBar.showSelection();
  1829. }
  1830. void CPlayerInterface::battleNewRoundFirst( int round )
  1831. {
  1832. EVENT_HANDLER_CALLED_BY_CLIENT;
  1833. BATTLE_EVENT_POSSIBLE_RETURN;
  1834. battleInt->newRoundFirst(round);
  1835. }
  1836. void CPlayerInterface::stopMovement()
  1837. {
  1838. if (stillMoveHero.get() == DURING_MOVE)//if we are in the middle of hero movement
  1839. stillMoveHero.setn(STOP_MOVE); //after showing dialog movement will be stopped
  1840. }
  1841. void CPlayerInterface::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  1842. {
  1843. EVENT_HANDLER_CALLED_BY_CLIENT;
  1844. if (market->o->ID == Obj::ALTAR_OF_SACRIFICE)
  1845. {
  1846. //EEMarketMode mode = market->availableModes().front();
  1847. if (market->allowsTrade(EMarketMode::ARTIFACT_EXP) && visitor->getAlignment() != EAlignment::EVIL)
  1848. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::ARTIFACT_EXP);
  1849. else if (market->allowsTrade(EMarketMode::CREATURE_EXP) && visitor->getAlignment() != EAlignment::GOOD)
  1850. GH.pushIntT<CAltarWindow>(market, visitor, EMarketMode::CREATURE_EXP);
  1851. }
  1852. else
  1853. {
  1854. GH.pushIntT<CMarketplaceWindow>(market, visitor, market->availableModes().front());
  1855. }
  1856. }
  1857. void CPlayerInterface::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  1858. {
  1859. EVENT_HANDLER_CALLED_BY_CLIENT;
  1860. GH.pushIntT<CUniversityWindow>(visitor, market);
  1861. }
  1862. void CPlayerInterface::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  1863. {
  1864. EVENT_HANDLER_CALLED_BY_CLIENT;
  1865. GH.pushIntT<CHillFortWindow>(visitor, object);
  1866. }
  1867. void CPlayerInterface::availableArtifactsChanged(const CGBlackMarket * bm)
  1868. {
  1869. EVENT_HANDLER_CALLED_BY_CLIENT;
  1870. if (CMarketplaceWindow *cmw = dynamic_cast<CMarketplaceWindow*>(GH.topInt().get()))
  1871. cmw->artifactsChanged(false);
  1872. }
  1873. void CPlayerInterface::showTavernWindow(const CGObjectInstance *townOrTavern)
  1874. {
  1875. EVENT_HANDLER_CALLED_BY_CLIENT;
  1876. GH.pushIntT<CTavernWindow>(townOrTavern);
  1877. }
  1878. void CPlayerInterface::showThievesGuildWindow (const CGObjectInstance * obj)
  1879. {
  1880. EVENT_HANDLER_CALLED_BY_CLIENT;
  1881. GH.pushIntT<CThievesGuildWindow>(obj);
  1882. }
  1883. void CPlayerInterface::showQuestLog()
  1884. {
  1885. EVENT_HANDLER_CALLED_BY_CLIENT;
  1886. GH.pushIntT<CQuestLog>(LOCPLINT->cb->getMyQuests());
  1887. }
  1888. void CPlayerInterface::showShipyardDialogOrProblemPopup(const IShipyard *obj)
  1889. {
  1890. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  1891. {
  1892. MetaString txt;
  1893. obj->getProblemText(txt);
  1894. showInfoDialog(txt.toString());
  1895. }
  1896. else
  1897. showShipyardDialog(obj);
  1898. }
  1899. void CPlayerInterface::requestReturningToMainMenu(bool won)
  1900. {
  1901. CCS->soundh->ambientStopAllChannels();
  1902. if(won && cb->getStartInfo()->campState)
  1903. CSH->startCampaignScenario(cb->getStartInfo()->campState);
  1904. else
  1905. sendCustomEvent(EUserEvent::RETURN_TO_MAIN_MENU);
  1906. }
  1907. void CPlayerInterface::sendCustomEvent( int code )
  1908. {
  1909. CGuiHandler::pushSDLEvent(SDL_USEREVENT, code);
  1910. }
  1911. void CPlayerInterface::askToAssembleArtifact(const ArtifactLocation &al)
  1912. {
  1913. auto hero = boost::apply_visitor(HeroObjectRetriever(), al.artHolder);
  1914. if(hero)
  1915. {
  1916. auto art = hero->getArt(al.slot);
  1917. if(art == nullptr)
  1918. {
  1919. logGlobal->error("artifact location %d points to nothing",
  1920. al.slot.num);
  1921. return;
  1922. }
  1923. CHeroArtPlace::askToAssemble(art, al.slot, hero);
  1924. }
  1925. }
  1926. void CPlayerInterface::artifactPut(const ArtifactLocation &al)
  1927. {
  1928. EVENT_HANDLER_CALLED_BY_CLIENT;
  1929. adventureInt->infoBar.showSelection();
  1930. askToAssembleArtifact(al);
  1931. }
  1932. void CPlayerInterface::artifactRemoved(const ArtifactLocation &al)
  1933. {
  1934. EVENT_HANDLER_CALLED_BY_CLIENT;
  1935. adventureInt->infoBar.showSelection();
  1936. for(auto isa : GH.listInt)
  1937. {
  1938. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1939. if (artWin)
  1940. artWin->artifactRemoved(al);
  1941. }
  1942. }
  1943. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1944. {
  1945. EVENT_HANDLER_CALLED_BY_CLIENT;
  1946. adventureInt->infoBar.showSelection();
  1947. for(auto isa : GH.listInt)
  1948. {
  1949. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1950. if (artWin)
  1951. artWin->artifactMoved(src, dst);
  1952. }
  1953. if(!GH.objsToBlit.empty())
  1954. GH.objsToBlit.back()->redraw();
  1955. }
  1956. void CPlayerInterface::artifactPossibleAssembling(const ArtifactLocation & dst)
  1957. {
  1958. askToAssembleArtifact(dst);
  1959. }
  1960. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1961. {
  1962. EVENT_HANDLER_CALLED_BY_CLIENT;
  1963. adventureInt->infoBar.showSelection();
  1964. for(auto isa : GH.listInt)
  1965. {
  1966. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1967. if (artWin)
  1968. artWin->artifactAssembled(al);
  1969. }
  1970. }
  1971. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1972. {
  1973. EVENT_HANDLER_CALLED_BY_CLIENT;
  1974. adventureInt->infoBar.showSelection();
  1975. for(auto isa : GH.listInt)
  1976. {
  1977. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1978. if (artWin)
  1979. artWin->artifactDisassembled(al);
  1980. }
  1981. }
  1982. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  1983. {
  1984. EVENT_HANDLER_CALLED_BY_CLIENT;
  1985. if (!vstd::contains (GH.listInt, adventureInt))
  1986. {
  1987. GH.popInts ((int)GH.listInt.size()); //after map load - remove everything else
  1988. GH.pushInt (adventureInt);
  1989. }
  1990. else
  1991. {
  1992. adventureInt->infoBar.showSelection();
  1993. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front().get())) //don't remove dialogs that expect query answer
  1994. GH.popInts(1);
  1995. }
  1996. if(CSH->howManyPlayerInterfaces() == 1)
  1997. {
  1998. GH.curInt = this;
  1999. adventureInt->startTurn();
  2000. }
  2001. if (player != playerID && this == LOCPLINT)
  2002. {
  2003. waitWhileDialog();
  2004. adventureInt->aiTurnStarted();
  2005. }
  2006. }
  2007. void CPlayerInterface::waitForAllDialogs(bool unlockPim)
  2008. {
  2009. while(!dialogs.empty())
  2010. {
  2011. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  2012. SDL_Delay(5);
  2013. }
  2014. waitWhileDialog(unlockPim);
  2015. }
  2016. void CPlayerInterface::proposeLoadingGame()
  2017. {
  2018. showYesNoDialog(CGI->generaltexth->allTexts[68], [this](){ sendCustomEvent(EUserEvent::RETURN_TO_MENU_LOAD); }, nullptr);
  2019. }
  2020. CPlayerInterface::SpellbookLastSetting::SpellbookLastSetting()
  2021. {
  2022. spellbookLastPageBattle = spellbokLastPageAdvmap = 0;
  2023. spellbookLastTabBattle = spellbookLastTabAdvmap = 4;
  2024. }
  2025. bool CPlayerInterface::capturedAllEvents()
  2026. {
  2027. if (duringMovement)
  2028. {
  2029. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  2030. return true;
  2031. }
  2032. if (ignoreEvents)
  2033. {
  2034. boost::unique_lock<boost::mutex> un(eventsM);
  2035. while(!SDLEventsQueue.empty())
  2036. {
  2037. SDLEventsQueue.pop();
  2038. }
  2039. return true;
  2040. }
  2041. return false;
  2042. }
  2043. void CPlayerInterface::setMovementStatus(bool value)
  2044. {
  2045. duringMovement = value;
  2046. if (value)
  2047. {
  2048. CCS->curh->hide();
  2049. }
  2050. else
  2051. {
  2052. CCS->curh->show();
  2053. }
  2054. }
  2055. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  2056. {
  2057. int i = 1;
  2058. auto getObj = [&](int3 coord, bool ignoreHero)
  2059. {
  2060. return cb->getTile(h->convertToVisitablePos(coord))->topVisitableObj(ignoreHero);
  2061. };
  2062. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  2063. {
  2064. if (action != CGPathNode::TELEPORT_NORMAL &&
  2065. action != CGPathNode::TELEPORT_BLOCKING_VISIT &&
  2066. action != CGPathNode::TELEPORT_BATTLE)
  2067. {
  2068. return false;
  2069. }
  2070. return true;
  2071. };
  2072. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  2073. {
  2074. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  2075. return nextObjectTop;
  2076. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  2077. CGTeleport::isConnected(currentObject, nextObject))
  2078. {
  2079. return nextObject;
  2080. }
  2081. return nullptr;
  2082. };
  2083. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  2084. stillMoveHero.data = CONTINUE_MOVE;
  2085. auto doMovement = [&](int3 dst, bool transit)
  2086. {
  2087. stillMoveHero.data = WAITING_MOVE;
  2088. cb->moveHero(h, dst, transit);
  2089. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  2090. stillMoveHero.cond.wait(un);
  2091. };
  2092. {
  2093. for (auto & elem : path.nodes)
  2094. elem.coord = h->convertFromVisitablePos(elem.coord);
  2095. TerrainId currentTerrain = Terrain::BORDER; // not init yet
  2096. TerrainId newTerrain;
  2097. int sh = -1;
  2098. auto canStop = [&](CGPathNode * node) -> bool
  2099. {
  2100. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  2101. return true;
  2102. if (node->accessible == CGPathNode::ACCESSIBLE)
  2103. return true;
  2104. return false;
  2105. };
  2106. for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  2107. {
  2108. int3 currentCoord = path.nodes[i].coord;
  2109. int3 nextCoord = path.nodes[i-1].coord;
  2110. auto currentObject = getObj(currentCoord, currentCoord == h->pos);
  2111. auto nextObjectTop = getObj(nextCoord, false);
  2112. auto nextObject = getObj(nextCoord, true);
  2113. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  2114. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  2115. {
  2116. CCS->soundh->stopSound(sh);
  2117. destinationTeleport = destTeleportObj->id;
  2118. destinationTeleportPos = nextCoord;
  2119. doMovement(h->pos, false);
  2120. if (path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT
  2121. || path.nodes[i-1].action == CGPathNode::TELEPORT_BATTLE)
  2122. {
  2123. destinationTeleport = ObjectInstanceID();
  2124. destinationTeleportPos = int3(-1);
  2125. }
  2126. if(i != path.nodes.size() - 1)
  2127. {
  2128. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[currentTerrain], -1);
  2129. }
  2130. continue;
  2131. }
  2132. if (path.nodes[i-1].turns)
  2133. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  2134. stillMoveHero.data = STOP_MOVE;
  2135. break;
  2136. }
  2137. // Start a new sound for the hero movement or let the existing one carry on.
  2138. #if 0
  2139. // TODO
  2140. if (hero is flying && sh == -1)
  2141. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  2142. #endif
  2143. {
  2144. newTerrain = cb->getTile(h->convertToVisitablePos(currentCoord))->terType->id;
  2145. if(newTerrain != currentTerrain)
  2146. {
  2147. CCS->soundh->stopSound(sh);
  2148. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[newTerrain], -1);
  2149. currentTerrain = newTerrain;
  2150. }
  2151. }
  2152. 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
  2153. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  2154. logGlobal->trace("Requesting hero movement to %s", endpos.toString());
  2155. bool useTransit = false;
  2156. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  2157. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  2158. || CGTeleport::isTeleport(nextObjectTop)))
  2159. { // Hero should be able to go through object if it's allow transit
  2160. useTransit = true;
  2161. }
  2162. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  2163. useTransit = true;
  2164. doMovement(endpos, useTransit);
  2165. logGlobal->trace("Resuming %s", __FUNCTION__);
  2166. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  2167. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  2168. break;
  2169. }
  2170. CCS->soundh->stopSound(sh);
  2171. }
  2172. //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
  2173. if (!showingDialog->get())
  2174. GH.fakeMouseMove();
  2175. //todo: this should be in main thread
  2176. if (adventureInt)
  2177. {
  2178. // (i == 0) means hero went through all the path
  2179. adventureInt->updateMoveHero(h, (i != 0));
  2180. adventureInt->updateNextHero(h);
  2181. }
  2182. setMovementStatus(false);
  2183. }
  2184. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions)
  2185. {
  2186. EVENT_HANDLER_CALLED_BY_CLIENT;
  2187. //TODO: showWorldViewEx
  2188. std::copy(objectPositions.begin(), objectPositions.end(), std::back_inserter(adventureInt->worldViewOptions.iconPositions));
  2189. viewWorldMap();
  2190. }
  2191. void CPlayerInterface::updateAmbientSounds(bool resetAll)
  2192. {
  2193. if(castleInt || battleInt || !makingTurn || !currentSelection)
  2194. {
  2195. CCS->soundh->ambientStopAllChannels();
  2196. return;
  2197. }
  2198. else if(!dynamic_cast<CAdvMapInt *>(GH.topInt().get()))
  2199. {
  2200. return;
  2201. }
  2202. if(resetAll)
  2203. CCS->soundh->ambientStopAllChannels();
  2204. std::map<std::string, int> currentSounds;
  2205. auto updateSounds = [&](std::string soundId, int distance) -> void
  2206. {
  2207. if(vstd::contains(currentSounds, soundId))
  2208. currentSounds[soundId] = std::max(currentSounds[soundId], distance);
  2209. else
  2210. currentSounds.insert(std::make_pair(soundId, distance));
  2211. };
  2212. int3 pos = currentSelection->getSightCenter();
  2213. std::unordered_set<int3, ShashInt3> tiles;
  2214. cb->getVisibleTilesInRange(tiles, pos, CCS->soundh->ambientGetRange(), int3::DIST_CHEBYSHEV);
  2215. for(int3 tile : tiles)
  2216. {
  2217. int dist = pos.dist(tile, int3::DIST_CHEBYSHEV);
  2218. // We want sound for every special terrain on tile and not just one on top
  2219. for(auto & ttObj : CGI->mh->ttiles[tile.z][tile.x][tile.y].objects)
  2220. {
  2221. if(ttObj.ambientSound)
  2222. updateSounds(ttObj.ambientSound.get(), dist);
  2223. }
  2224. if(CGI->mh->map->isCoastalTile(tile))
  2225. updateSounds("LOOPOCEA", dist);
  2226. }
  2227. CCS->soundh->ambientUpdateChannels(currentSounds);
  2228. }