CPlayerInterface.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607
  1. /*
  2. * CPlayerInterface.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <vcmi/Artifact.h>
  12. #include "windows/CAdvmapInterface.h"
  13. #include "battle/CBattleInterface.h"
  14. #include "battle/CBattleInterfaceClasses.h"
  15. #include "../CCallback.h"
  16. #include "windows/CCastleInterface.h"
  17. #include "gui/CCursorHandler.h"
  18. #include "windows/CKingdomInterface.h"
  19. #include "CGameInfo.h"
  20. #include "windows/CHeroWindow.h"
  21. #include "windows/CCreatureWindow.h"
  22. #include "windows/CQuestLog.h"
  23. #include "CMessage.h"
  24. #include "CPlayerInterface.h"
  25. #include "gui/SDL_Extensions.h"
  26. #include "widgets/CComponent.h"
  27. #include "windows/CTradeWindow.h"
  28. #include "windows/CSpellWindow.h"
  29. #include "../lib/CConfigHandler.h"
  30. #include "battle/CCreatureAnimation.h"
  31. #include "Graphics.h"
  32. #include "windows/GUIClasses.h"
  33. #include "../lib/CArtHandler.h"
  34. #include "../lib/CGeneralTextHandler.h"
  35. #include "../lib/CHeroHandler.h"
  36. #include "../lib/serializer/CTypeList.h"
  37. #include "../lib/serializer/BinaryDeserializer.h"
  38. #include "../lib/serializer/BinarySerializer.h"
  39. #include "../lib/spells/CSpellHandler.h"
  40. #include "../lib/CTownHandler.h"
  41. #include "../lib/mapObjects/CObjectClassesHandler.h" // For displaying correct UI when interacting with objects
  42. #include "../lib/CStack.h"
  43. #include "../lib/JsonNode.h"
  44. #include "CMusicHandler.h"
  45. #include "../lib/CondSh.h"
  46. #include "../lib/NetPacksBase.h"
  47. #include "../lib/NetPacks.h"//todo: remove
  48. #include "../lib/mapping/CMap.h"
  49. #include "../lib/VCMIDirs.h"
  50. #include "mapHandler.h"
  51. #include "../lib/CStopWatch.h"
  52. #include "../lib/StartInfo.h"
  53. #include "../lib/CPlayerState.h"
  54. #include "../lib/GameConstants.h"
  55. #include "gui/CGuiHandler.h"
  56. #include "windows/InfoWindows.h"
  57. #include "../lib/UnlockGuard.h"
  58. #include "../lib/CPathfinder.h"
  59. #include <SDL.h>
  60. #include "CServerHandler.h"
  61. // FIXME: only needed for CGameState::mutex
  62. #include "../lib/CGameState.h"
  63. #include "gui/NotificationHandler.h"
  64. // The macro below is used to mark functions that are called by client when game state changes.
  65. // They all assume that CPlayerInterface::pim mutex is locked.
  66. #define EVENT_HANDLER_CALLED_BY_CLIENT
  67. // The macro marks functions that are run on a new thread by client.
  68. // They do not own any mutexes intiially.
  69. #define THREAD_CREATED_BY_CLIENT
  70. #define RETURN_IF_QUICK_COMBAT \
  71. if (isAutoFightOn && !battleInt) \
  72. return;
  73. #define BATTLE_EVENT_POSSIBLE_RETURN\
  74. if (LOCPLINT != this) \
  75. return; \
  76. RETURN_IF_QUICK_COMBAT
  77. using namespace CSDL_Ext;
  78. extern std::queue<SDL_Event> SDLEventsQueue;
  79. extern boost::mutex eventsM;
  80. boost::recursive_mutex * CPlayerInterface::pim = new boost::recursive_mutex;
  81. CPlayerInterface * LOCPLINT;
  82. CBattleInterface * CPlayerInterface::battleInt;
  83. enum EMoveState {STOP_MOVE, WAITING_MOVE, CONTINUE_MOVE, DURING_MOVE};
  84. CondSh<EMoveState> stillMoveHero(STOP_MOVE); //used during hero movement
  85. static bool objectBlitOrderSorter(const TerrainTileObject & a, const TerrainTileObject & b)
  86. {
  87. return CMapHandler::compareObjectBlitOrder(a.obj, b.obj);
  88. }
  89. struct HeroObjectRetriever : boost::static_visitor<const CGHeroInstance *>
  90. {
  91. const CGHeroInstance * operator()(const ConstTransitivePtr<CGHeroInstance> &h) const
  92. {
  93. return h;
  94. }
  95. const CGHeroInstance * operator()(const ConstTransitivePtr<CStackInstance> &s) const
  96. {
  97. return nullptr;
  98. }
  99. };
  100. CPlayerInterface::CPlayerInterface(PlayerColor Player)
  101. {
  102. logGlobal->trace("\tHuman player interface for player %s being constructed", Player.getStr());
  103. destinationTeleport = ObjectInstanceID();
  104. destinationTeleportPos = int3(-1);
  105. GH.defActionsDef = 0;
  106. LOCPLINT = this;
  107. curAction = nullptr;
  108. playerID=Player;
  109. human=true;
  110. currentSelection = nullptr;
  111. battleInt = nullptr;
  112. castleInt = nullptr;
  113. makingTurn = false;
  114. showingDialog = new CondSh<bool>(false);
  115. cingconsole = new CInGameConsole();
  116. GH.terminate_cond->set(false);
  117. firstCall = 1; //if loading will be overwritten in serialize
  118. autosaveCount = 0;
  119. isAutoFightOn = false;
  120. duringMovement = false;
  121. ignoreEvents = false;
  122. }
  123. CPlayerInterface::~CPlayerInterface()
  124. {
  125. if(CCS->soundh) CCS->soundh->ambientStopAllChannels();
  126. logGlobal->trace("\tHuman player interface for player %s being destructed", playerID.getStr());
  127. delete showingDialog;
  128. delete cingconsole;
  129. if (LOCPLINT == this)
  130. LOCPLINT = nullptr;
  131. }
  132. void CPlayerInterface::init(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  133. {
  134. cb = CB;
  135. env = ENV;
  136. CCS->soundh->loadHorseSounds();
  137. CCS->musich->loadTerrainMusicThemes();
  138. initializeHeroTownList();
  139. // always recreate advmap interface to avoid possible memory-corruption bugs
  140. adventureInt.reset(new CAdvMapInt());
  141. }
  142. void CPlayerInterface::yourTurn()
  143. {
  144. EVENT_HANDLER_CALLED_BY_CLIENT;
  145. {
  146. boost::unique_lock<boost::mutex> lock(eventsM); //block handling events until interface is ready
  147. LOCPLINT = this;
  148. GH.curInt = this;
  149. adventureInt->selection = nullptr;
  150. NotificationHandler::notify("Your turn");
  151. std::string prefix = settings["session"]["saveprefix"].String();
  152. int frequency = static_cast<int>(settings["general"]["saveFrequency"].Integer());
  153. if (firstCall)
  154. {
  155. if(CSH->howManyPlayerInterfaces() == 1)
  156. adventureInt->setPlayer(playerID);
  157. autosaveCount = getLastIndex(prefix + "Autosave_");
  158. if (firstCall > 0) //new game, not loaded
  159. {
  160. int index = getLastIndex(prefix + "Newgame_");
  161. index %= SAVES_COUNT;
  162. cb->save("Saves/" + prefix + "Newgame_Autosave_" + boost::lexical_cast<std::string>(index + 1));
  163. }
  164. firstCall = 0;
  165. }
  166. else if(frequency > 0 && cb->getDate() % frequency == 0)
  167. {
  168. LOCPLINT->cb->save("Saves/" + prefix + "Autosave_" + boost::lexical_cast<std::string>(autosaveCount++ + 1));
  169. autosaveCount %= 5;
  170. }
  171. if (adventureInt->player != playerID)
  172. adventureInt->setPlayer(playerID);
  173. if (CSH->howManyPlayerInterfaces() > 1) //hot seat message
  174. {
  175. adventureInt->startHotSeatWait(playerID);
  176. makingTurn = true;
  177. std::string msg = CGI->generaltexth->allTexts[13];
  178. boost::replace_first(msg, "%s", cb->getStartInfo()->playerInfos.find(playerID)->second.name);
  179. std::vector<std::shared_ptr<CComponent>> cmp;
  180. cmp.push_back(std::make_shared<CComponent>(CComponent::flag, playerID.getNum(), 0));
  181. showInfoDialog(msg, cmp);
  182. }
  183. else
  184. {
  185. makingTurn = true;
  186. adventureInt->startTurn();
  187. }
  188. }
  189. acceptTurn();
  190. }
  191. void CPlayerInterface::heroMoved(const TryMoveHero & details, bool verbose)
  192. {
  193. EVENT_HANDLER_CALLED_BY_CLIENT;
  194. waitWhileDialog();
  195. if(LOCPLINT != this)
  196. return;
  197. //FIXME: read once and store
  198. if(settings["session"]["spectate"].Bool() && settings["session"]["spectate-ignore-hero"].Bool())
  199. return;
  200. const CGHeroInstance * hero = cb->getHero(details.id); //object representing this hero
  201. int3 hp = details.start;
  202. if(!hero)
  203. {
  204. //AI hero left the visible area (we can't obtain info)
  205. //TODO very evil workaround -> retrieve pointer to hero so we could animate it
  206. // TODO -> we should not need full CGHeroInstance structure to display animation or it should not be handled by playerint (but by the client itself)
  207. const TerrainTile2 & tile = CGI->mh->ttiles[hp.z][hp.x - 1][hp.y];
  208. for(auto & elem : tile.objects)
  209. if(elem.obj && elem.obj->id == details.id)
  210. hero = dynamic_cast<const CGHeroInstance *>(elem.obj);
  211. if(!hero) //still nothing...
  212. return;
  213. }
  214. bool directlyAttackingCreature =
  215. details.attackedFrom
  216. && adventureInt->terrain.currentPath //in case if movement has been canceled in the meantime and path was already erased
  217. && adventureInt->terrain.currentPath->nodes.size() == 3;//FIXME should be 2 but works nevertheless...
  218. if(makingTurn && hero->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
  219. {
  220. updateAmbientSounds();
  221. //We may need to change music - select new track, music handler will change it if needed
  222. CCS->musich->playMusicFromSet("terrain", LOCPLINT->cb->getTile(hero->visitablePos())->terType->name, true, false);
  223. if(details.result == TryMoveHero::TELEPORTATION)
  224. {
  225. if(adventureInt->terrain.currentPath)
  226. {
  227. assert(adventureInt->terrain.currentPath->nodes.size() >= 2);
  228. std::vector<CGPathNode>::const_iterator nodesIt = adventureInt->terrain.currentPath->nodes.end() - 1;
  229. if((nodesIt)->coord == CGHeroInstance::convertPosition(details.start, false)
  230. && (nodesIt - 1)->coord == CGHeroInstance::convertPosition(details.end, false))
  231. {
  232. //path was between entrance and exit of teleport -> OK, erase node as usual
  233. removeLastNodeFromPath(hero);
  234. }
  235. else
  236. {
  237. //teleport was not along current path, it'll now be invalid (hero is somewhere else)
  238. eraseCurrentPathOf(hero);
  239. }
  240. }
  241. adventureInt->centerOn(hero, true); //actualizing screen pos
  242. adventureInt->minimap.redraw();
  243. adventureInt->heroList.update(hero);
  244. return; //teleport - no fancy moving animation
  245. //TODO: smooth disappear / appear effect
  246. }
  247. if(hero->pos != details.end //hero didn't change tile but visit succeeded
  248. || directlyAttackingCreature) // or creature was attacked from endangering tile.
  249. {
  250. eraseCurrentPathOf(hero, false);
  251. }
  252. else if(adventureInt->terrain.currentPath && hero->pos == details.end) //&& hero is moving
  253. {
  254. if(details.start != details.end) //so we don't touch path when revisiting with spacebar
  255. removeLastNodeFromPath(hero);
  256. }
  257. }
  258. if(details.stopMovement()) //hero failed to move
  259. {
  260. hero->isStanding = true;
  261. stillMoveHero.setn(STOP_MOVE);
  262. GH.totalRedraw();
  263. adventureInt->heroList.update(hero);
  264. return;
  265. }
  266. ui32 speed = 0;
  267. if(settings["session"]["spectate"].Bool())
  268. {
  269. if(!settings["session"]["spectate-hero-speed"].isNull())
  270. speed = static_cast<ui32>(settings["session"]["spectate-hero-speed"].Integer());
  271. }
  272. else if(makingTurn) // our turn, our hero moves
  273. speed = static_cast<ui32>(settings["adventure"]["heroSpeed"].Float());
  274. else
  275. speed = static_cast<ui32>(settings["adventure"]["enemySpeed"].Float());
  276. if(speed == 0)
  277. {
  278. //FIXME: is this a proper solution?
  279. CGI->mh->hideObject(hero);
  280. CGI->mh->printObject(hero);
  281. return; // no animation
  282. }
  283. adventureInt->centerOn(hero); //actualizing screen pos
  284. adventureInt->minimap.redraw();
  285. adventureInt->heroList.redraw();
  286. initMovement(details, hero, hp);
  287. auto waitFrame = [&]()
  288. {
  289. int frameNumber = GH.mainFPSmng->getFrameNumber();
  290. auto unlockPim = vstd::makeUnlockGuard(*pim);
  291. while(frameNumber == GH.mainFPSmng->getFrameNumber())
  292. SDL_Delay(5);
  293. };
  294. //first initializing done
  295. //main moving
  296. for(int i = 1; i < 32; i += 2 * speed)
  297. {
  298. movementPxStep(details, i, hp, hero);
  299. #ifndef VCMI_ANDROID
  300. // currently android doesn't seem to be able to handle all these full redraws here, so let's disable it so at least it looks less choppy;
  301. // most likely this is connected with the way that this manual animation+framerate handling is solved
  302. adventureInt->updateScreen = true;
  303. #endif
  304. //evil returns here ...
  305. //todo: get rid of it
  306. waitFrame(); //for animation purposes
  307. }
  308. //main moving done
  309. //finishing move
  310. finishMovement(details, hp, hero);
  311. hero->isStanding = true;
  312. //move finished
  313. adventureInt->minimap.redraw();
  314. adventureInt->heroList.update(hero);
  315. //check if user cancelled movement
  316. {
  317. boost::unique_lock<boost::mutex> un(eventsM);
  318. while(!SDLEventsQueue.empty())
  319. {
  320. SDL_Event ev = SDLEventsQueue.front();
  321. SDLEventsQueue.pop();
  322. switch(ev.type)
  323. {
  324. case SDL_MOUSEBUTTONDOWN:
  325. stillMoveHero.setn(STOP_MOVE);
  326. break;
  327. case SDL_KEYDOWN:
  328. if (ev.key.keysym.sym < SDLK_F1 || ev.key.keysym.sym > SDLK_F15)
  329. stillMoveHero.setn(STOP_MOVE);
  330. break;
  331. }
  332. }
  333. }
  334. if (stillMoveHero.get() == WAITING_MOVE)
  335. stillMoveHero.setn(DURING_MOVE);
  336. // Hero attacked creature directly, set direction to face it.
  337. if (directlyAttackingCreature) {
  338. // Get direction to attacker.
  339. int3 posOffset = *details.attackedFrom - details.end + int3(2, 1, 0);
  340. static const ui8 dirLookup[3][3] = {
  341. { 1, 2, 3 },
  342. { 8, 0, 4 },
  343. { 7, 6, 5 }
  344. };
  345. // FIXME: Avoid const_cast, make moveDir mutable in some other way?
  346. const_cast<CGHeroInstance *>(hero)->moveDir = dirLookup[posOffset.y][posOffset.x];
  347. }
  348. }
  349. void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
  350. {
  351. EVENT_HANDLER_CALLED_BY_CLIENT;
  352. LOG_TRACE_PARAMS(logGlobal, "Hero %s killed handler for player %s", hero->name % playerID);
  353. const CArmedInstance *newSelection = nullptr;
  354. if (makingTurn)
  355. {
  356. //find new object for selection: either hero
  357. int next = adventureInt->getNextHeroIndex(vstd::find_pos(wanderingHeroes, hero));
  358. if (next >= 0)
  359. newSelection = wanderingHeroes[next];
  360. //or town
  361. if (!newSelection || newSelection == hero)
  362. {
  363. if (towns.empty())
  364. newSelection = nullptr;
  365. else
  366. newSelection = towns.front();
  367. }
  368. }
  369. wanderingHeroes -= hero;
  370. adventureInt->heroList.update(hero);
  371. if (makingTurn && newSelection)
  372. adventureInt->select(newSelection, true);
  373. else if (adventureInt->selection == hero)
  374. adventureInt->selection = nullptr;
  375. if (vstd::contains(paths, hero))
  376. paths.erase(hero);
  377. }
  378. void CPlayerInterface::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  379. {
  380. EVENT_HANDLER_CALLED_BY_CLIENT;
  381. if(start && visitedObj)
  382. {
  383. if(visitedObj->getVisitSound())
  384. CCS->soundh->playSound(visitedObj->getVisitSound().get());
  385. }
  386. }
  387. void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
  388. {
  389. EVENT_HANDLER_CALLED_BY_CLIENT;
  390. wanderingHeroes.push_back(hero);
  391. adventureInt->heroList.update(hero);
  392. }
  393. void CPlayerInterface::openTownWindow(const CGTownInstance * town)
  394. {
  395. if(castleInt)
  396. castleInt->close();
  397. castleInt = nullptr;
  398. auto newCastleInt = std::make_shared<CCastleInterface>(town);
  399. GH.pushInt(newCastleInt);
  400. }
  401. int3 CPlayerInterface::repairScreenPos(int3 pos)
  402. {
  403. if (pos.x<-CGI->mh->frameW)
  404. pos.x = -CGI->mh->frameW;
  405. if (pos.y<-CGI->mh->frameH)
  406. pos.y = -CGI->mh->frameH;
  407. if (pos.x>CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW)
  408. pos.x = CGI->mh->sizes.x - adventureInt->terrain.tilesw + CGI->mh->frameW;
  409. if (pos.y>CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH)
  410. pos.y = CGI->mh->sizes.y - adventureInt->terrain.tilesh + CGI->mh->frameH;
  411. return pos;
  412. }
  413. void CPlayerInterface::activateForSpectator()
  414. {
  415. adventureInt->state = CAdvMapInt::INGAME;
  416. adventureInt->activate();
  417. adventureInt->minimap.activate();
  418. }
  419. void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  420. {
  421. EVENT_HANDLER_CALLED_BY_CLIENT;
  422. if (which == 4)
  423. {
  424. if (CAltarWindow *ctw = dynamic_cast<CAltarWindow *>(GH.topInt().get()))
  425. ctw->setExpToLevel();
  426. }
  427. else if (which < GameConstants::PRIMARY_SKILLS) //no need to redraw infowin if this is experience (exp is treated as prim skill with id==4)
  428. updateInfo(hero);
  429. }
  430. void CPlayerInterface::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  431. {
  432. EVENT_HANDLER_CALLED_BY_CLIENT;
  433. CUniversityWindow* cuw = dynamic_cast<CUniversityWindow*>(GH.topInt().get());
  434. if (cuw) //university window is open
  435. {
  436. GH.totalRedraw();
  437. }
  438. }
  439. void CPlayerInterface::heroManaPointsChanged(const CGHeroInstance * hero)
  440. {
  441. EVENT_HANDLER_CALLED_BY_CLIENT;
  442. updateInfo(hero);
  443. if (makingTurn && hero->tempOwner == playerID)
  444. adventureInt->heroList.update(hero);
  445. }
  446. void CPlayerInterface::heroMovePointsChanged(const CGHeroInstance * hero)
  447. {
  448. EVENT_HANDLER_CALLED_BY_CLIENT;
  449. if (makingTurn && hero->tempOwner == playerID)
  450. adventureInt->heroList.update(hero);
  451. }
  452. void CPlayerInterface::receivedResource()
  453. {
  454. EVENT_HANDLER_CALLED_BY_CLIENT;
  455. if (CMarketplaceWindow *mw = dynamic_cast<CMarketplaceWindow *>(GH.topInt().get()))
  456. mw->resourceChanged();
  457. GH.totalRedraw();
  458. }
  459. void CPlayerInterface::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill>& skills, QueryID queryID)
  460. {
  461. EVENT_HANDLER_CALLED_BY_CLIENT;
  462. waitWhileDialog();
  463. CCS->soundh->playSound(soundBase::heroNewLevel);
  464. GH.pushIntT<CLevelWindow>(hero, pskill, skills, [=](ui32 selection)
  465. {
  466. cb->selectionMade(selection, queryID);
  467. });
  468. }
  469. void CPlayerInterface::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  470. {
  471. EVENT_HANDLER_CALLED_BY_CLIENT;
  472. waitWhileDialog();
  473. CCS->soundh->playSound(soundBase::heroNewLevel);
  474. GH.pushIntT<CStackWindow>(commander, skills, [=](ui32 selection)
  475. {
  476. cb->selectionMade(selection, queryID);
  477. });
  478. }
  479. void CPlayerInterface::heroInGarrisonChange(const CGTownInstance *town)
  480. {
  481. EVENT_HANDLER_CALLED_BY_CLIENT;
  482. updateInfo(town);
  483. if (town->garrisonHero) //wandering hero moved to the garrison
  484. {
  485. CGI->mh->hideObject(town->garrisonHero);
  486. if (town->garrisonHero->tempOwner == playerID && vstd::contains(wanderingHeroes,town->garrisonHero)) // our hero
  487. wanderingHeroes -= town->garrisonHero;
  488. }
  489. if (town->visitingHero) //hero leaves garrison
  490. {
  491. CGI->mh->printObject(town->visitingHero);
  492. if (town->visitingHero->tempOwner == playerID && !vstd::contains(wanderingHeroes,town->visitingHero)) // our hero
  493. wanderingHeroes.push_back(town->visitingHero);
  494. }
  495. adventureInt->heroList.update();
  496. adventureInt->updateNextHero(nullptr);
  497. if(castleInt)
  498. {
  499. castleInt->garr->selectSlot(nullptr);
  500. castleInt->garr->setArmy(town->getUpperArmy(), 0);
  501. castleInt->garr->setArmy(town->visitingHero, 1);
  502. castleInt->garr->recreateSlots();
  503. castleInt->heroes->update();
  504. }
  505. for (auto isa : GH.listInt)
  506. {
  507. CKingdomInterface *ki = dynamic_cast<CKingdomInterface*>(isa.get());
  508. if (ki)
  509. {
  510. ki->townChanged(town);
  511. ki->updateGarrisons();
  512. }
  513. }
  514. GH.totalRedraw();
  515. }
  516. void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  517. {
  518. EVENT_HANDLER_CALLED_BY_CLIENT;
  519. if (hero->tempOwner != playerID )
  520. return;
  521. waitWhileDialog();
  522. openTownWindow(town);
  523. }
  524. void CPlayerInterface::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  525. {
  526. std::vector<const CGObjectInstance *> instances;
  527. if(auto obj = cb->getObj(id1))
  528. instances.push_back(obj);
  529. if(id2 != ObjectInstanceID() && id2 != id1)
  530. {
  531. if(auto obj = cb->getObj(id2))
  532. instances.push_back(obj);
  533. }
  534. garrisonsChanged(instances);
  535. }
  536. void CPlayerInterface::garrisonsChanged(std::vector<const CGObjectInstance *> objs)
  537. {
  538. boost::unique_lock<boost::recursive_mutex> un(*pim);
  539. for (auto object : objs)
  540. updateInfo(object);
  541. for (auto & elem : GH.listInt)
  542. {
  543. CGarrisonHolder *cgh = dynamic_cast<CGarrisonHolder*>(elem.get());
  544. if (cgh)
  545. cgh->updateGarrisons();
  546. if (CTradeWindow *cmw = dynamic_cast<CTradeWindow*>(elem.get()))
  547. {
  548. if (vstd::contains(objs, cmw->hero))
  549. cmw->garrisonChanged();
  550. }
  551. }
  552. GH.totalRedraw();
  553. }
  554. void CPlayerInterface::garrisonChanged( const CGObjectInstance * obj)
  555. {
  556. garrisonsChanged(std::vector<const CGObjectInstance *>(1, obj));
  557. }
  558. void CPlayerInterface::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what) //what: 1 - built, 2 - demolished
  559. {
  560. EVENT_HANDLER_CALLED_BY_CLIENT;
  561. switch (buildingID)
  562. {
  563. case BuildingID::FORT: case BuildingID::CITADEL: case BuildingID::CASTLE:
  564. case BuildingID::VILLAGE_HALL: case BuildingID::TOWN_HALL: case BuildingID::CITY_HALL: case BuildingID::CAPITOL:
  565. case BuildingID::RESOURCE_SILO:
  566. updateInfo(town);
  567. break;
  568. }
  569. if (castleInt)
  570. {
  571. castleInt->townlist->update(town);
  572. if (castleInt->town == town)
  573. {
  574. switch(what)
  575. {
  576. case 1:
  577. CCS->soundh->playSound(soundBase::newBuilding);
  578. castleInt->addBuilding(buildingID);
  579. break;
  580. case 2:
  581. castleInt->removeBuilding(buildingID);
  582. break;
  583. }
  584. }
  585. }
  586. adventureInt->townList.update(town);
  587. }
  588. void CPlayerInterface::battleStartBefore(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  589. {
  590. //Don't wait for dialogs when we are non-active hot-seat player
  591. if (LOCPLINT == this)
  592. waitForAllDialogs();
  593. }
  594. void CPlayerInterface::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  595. {
  596. EVENT_HANDLER_CALLED_BY_CLIENT;
  597. if (settings["adventure"]["quickCombat"].Bool())
  598. {
  599. autofightingAI = CDynLibHandler::getNewBattleAI(settings["server"]["friendlyAI"].String());
  600. autofightingAI->init(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->pos-obj->getVisitableOffset() == 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->getPosition(false) == 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->getPosition(false)); // 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. waitWhileDialog();
  1943. }
  1944. void CPlayerInterface::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  1945. {
  1946. EVENT_HANDLER_CALLED_BY_CLIENT;
  1947. adventureInt->infoBar.showSelection();
  1948. for(auto isa : GH.listInt)
  1949. {
  1950. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1951. if (artWin)
  1952. artWin->artifactMoved(src, dst);
  1953. }
  1954. if(!GH.objsToBlit.empty())
  1955. GH.objsToBlit.back()->redraw();
  1956. waitWhileDialog();
  1957. }
  1958. void CPlayerInterface::artifactPossibleAssembling(const ArtifactLocation & dst)
  1959. {
  1960. askToAssembleArtifact(dst);
  1961. }
  1962. void CPlayerInterface::artifactAssembled(const ArtifactLocation &al)
  1963. {
  1964. EVENT_HANDLER_CALLED_BY_CLIENT;
  1965. adventureInt->infoBar.showSelection();
  1966. for(auto isa : GH.listInt)
  1967. {
  1968. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1969. if (artWin)
  1970. artWin->artifactAssembled(al);
  1971. }
  1972. }
  1973. void CPlayerInterface::artifactDisassembled(const ArtifactLocation &al)
  1974. {
  1975. EVENT_HANDLER_CALLED_BY_CLIENT;
  1976. adventureInt->infoBar.showSelection();
  1977. for(auto isa : GH.listInt)
  1978. {
  1979. auto artWin = dynamic_cast<CArtifactHolder*>(isa.get());
  1980. if (artWin)
  1981. artWin->artifactDisassembled(al);
  1982. }
  1983. }
  1984. void CPlayerInterface::playerStartsTurn(PlayerColor player)
  1985. {
  1986. EVENT_HANDLER_CALLED_BY_CLIENT;
  1987. if (!vstd::contains (GH.listInt, adventureInt))
  1988. {
  1989. GH.popInts ((int)GH.listInt.size()); //after map load - remove everything else
  1990. GH.pushInt (adventureInt);
  1991. }
  1992. else
  1993. {
  1994. adventureInt->infoBar.showSelection();
  1995. while (GH.listInt.front() != adventureInt && !dynamic_cast<CInfoWindow*>(GH.listInt.front().get())) //don't remove dialogs that expect query answer
  1996. GH.popInts(1);
  1997. }
  1998. if(CSH->howManyPlayerInterfaces() == 1)
  1999. {
  2000. GH.curInt = this;
  2001. adventureInt->startTurn();
  2002. }
  2003. if (player != playerID && this == LOCPLINT)
  2004. {
  2005. waitWhileDialog();
  2006. adventureInt->aiTurnStarted();
  2007. }
  2008. }
  2009. void CPlayerInterface::waitForAllDialogs(bool unlockPim)
  2010. {
  2011. while(!dialogs.empty())
  2012. {
  2013. auto unlock = vstd::makeUnlockGuardIf(*pim, unlockPim);
  2014. SDL_Delay(5);
  2015. }
  2016. waitWhileDialog(unlockPim);
  2017. }
  2018. void CPlayerInterface::proposeLoadingGame()
  2019. {
  2020. showYesNoDialog(CGI->generaltexth->allTexts[68], [this](){ sendCustomEvent(EUserEvent::RETURN_TO_MENU_LOAD); }, nullptr);
  2021. }
  2022. CPlayerInterface::SpellbookLastSetting::SpellbookLastSetting()
  2023. {
  2024. spellbookLastPageBattle = spellbokLastPageAdvmap = 0;
  2025. spellbookLastTabBattle = spellbookLastTabAdvmap = 4;
  2026. }
  2027. bool CPlayerInterface::capturedAllEvents()
  2028. {
  2029. if (duringMovement)
  2030. {
  2031. //just inform that we are capturing events. they will be processed by heroMoved() in client thread.
  2032. return true;
  2033. }
  2034. if (ignoreEvents)
  2035. {
  2036. boost::unique_lock<boost::mutex> un(eventsM);
  2037. while(!SDLEventsQueue.empty())
  2038. {
  2039. SDLEventsQueue.pop();
  2040. }
  2041. return true;
  2042. }
  2043. return false;
  2044. }
  2045. void CPlayerInterface::setMovementStatus(bool value)
  2046. {
  2047. duringMovement = value;
  2048. if (value)
  2049. {
  2050. CCS->curh->hide();
  2051. }
  2052. else
  2053. {
  2054. CCS->curh->show();
  2055. }
  2056. }
  2057. void CPlayerInterface::doMoveHero(const CGHeroInstance * h, CGPath path)
  2058. {
  2059. int i = 1;
  2060. auto getObj = [&](int3 coord, bool ignoreHero)
  2061. {
  2062. return cb->getTile(CGHeroInstance::convertPosition(coord,false))->topVisitableObj(ignoreHero);
  2063. };
  2064. auto isTeleportAction = [&](CGPathNode::ENodeAction action) -> bool
  2065. {
  2066. if (action != CGPathNode::TELEPORT_NORMAL &&
  2067. action != CGPathNode::TELEPORT_BLOCKING_VISIT &&
  2068. action != CGPathNode::TELEPORT_BATTLE)
  2069. {
  2070. return false;
  2071. }
  2072. return true;
  2073. };
  2074. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  2075. {
  2076. if (CGTeleport::isConnected(currentObject, nextObjectTop))
  2077. return nextObjectTop;
  2078. if (nextObjectTop && nextObjectTop->ID == Obj::HERO &&
  2079. CGTeleport::isConnected(currentObject, nextObject))
  2080. {
  2081. return nextObject;
  2082. }
  2083. return nullptr;
  2084. };
  2085. boost::unique_lock<boost::mutex> un(stillMoveHero.mx);
  2086. stillMoveHero.data = CONTINUE_MOVE;
  2087. auto doMovement = [&](int3 dst, bool transit)
  2088. {
  2089. stillMoveHero.data = WAITING_MOVE;
  2090. cb->moveHero(h, dst, transit);
  2091. while(stillMoveHero.data != STOP_MOVE && stillMoveHero.data != CONTINUE_MOVE)
  2092. stillMoveHero.cond.wait(un);
  2093. };
  2094. {
  2095. path.convert(0);
  2096. TerrainId currentTerrain = Terrain::BORDER; // not init yet
  2097. TerrainId newTerrain;
  2098. int sh = -1;
  2099. auto canStop = [&](CGPathNode * node) -> bool
  2100. {
  2101. if (node->layer == EPathfindingLayer::LAND || node->layer == EPathfindingLayer::SAIL)
  2102. return true;
  2103. if (node->accessible == CGPathNode::ACCESSIBLE)
  2104. return true;
  2105. return false;
  2106. };
  2107. for (i=(int)path.nodes.size()-1; i>0 && (stillMoveHero.data == CONTINUE_MOVE || !canStop(&path.nodes[i])); i--)
  2108. {
  2109. int3 currentCoord = path.nodes[i].coord;
  2110. int3 nextCoord = path.nodes[i-1].coord;
  2111. auto currentObject = getObj(currentCoord, currentCoord == h->pos);
  2112. auto nextObjectTop = getObj(nextCoord, false);
  2113. auto nextObject = getObj(nextCoord, true);
  2114. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  2115. if (isTeleportAction(path.nodes[i-1].action) && destTeleportObj != nullptr)
  2116. {
  2117. CCS->soundh->stopSound(sh);
  2118. destinationTeleport = destTeleportObj->id;
  2119. destinationTeleportPos = nextCoord;
  2120. doMovement(h->pos, false);
  2121. if (path.nodes[i-1].action == CGPathNode::TELEPORT_BLOCKING_VISIT
  2122. || path.nodes[i-1].action == CGPathNode::TELEPORT_BATTLE)
  2123. {
  2124. destinationTeleport = ObjectInstanceID();
  2125. destinationTeleportPos = int3(-1);
  2126. }
  2127. if(i != path.nodes.size() - 1)
  2128. {
  2129. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[currentTerrain], -1);
  2130. }
  2131. continue;
  2132. }
  2133. if (path.nodes[i-1].turns)
  2134. { //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  2135. stillMoveHero.data = STOP_MOVE;
  2136. break;
  2137. }
  2138. // Start a new sound for the hero movement or let the existing one carry on.
  2139. #if 0
  2140. // TODO
  2141. if (hero is flying && sh == -1)
  2142. sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
  2143. #endif
  2144. {
  2145. newTerrain = cb->getTile(CGHeroInstance::convertPosition(currentCoord, false))->terType->id;
  2146. if(newTerrain != currentTerrain)
  2147. {
  2148. CCS->soundh->stopSound(sh);
  2149. sh = CCS->soundh->playSound(CCS->soundh->horseSounds[newTerrain], -1);
  2150. currentTerrain = newTerrain;
  2151. }
  2152. }
  2153. 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
  2154. int3 endpos(nextCoord.x, nextCoord.y, h->pos.z);
  2155. logGlobal->trace("Requesting hero movement to %s", endpos.toString());
  2156. bool useTransit = false;
  2157. if ((i-2 >= 0) // Check there is node after next one; otherwise transit is pointless
  2158. && (CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i-2].coord, false))
  2159. || CGTeleport::isTeleport(nextObjectTop)))
  2160. { // Hero should be able to go through object if it's allow transit
  2161. useTransit = true;
  2162. }
  2163. else if (path.nodes[i-1].layer == EPathfindingLayer::AIR)
  2164. useTransit = true;
  2165. doMovement(endpos, useTransit);
  2166. logGlobal->trace("Resuming %s", __FUNCTION__);
  2167. bool guarded = cb->isInTheMap(cb->getGuardingCreaturePosition(endpos - int3(1, 0, 0)));
  2168. if ((!useTransit && guarded) || showingDialog->get() == true) // Abort movement if a guard was fought or there is a dialog to display (Mantis #1136)
  2169. break;
  2170. }
  2171. CCS->soundh->stopSound(sh);
  2172. }
  2173. //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
  2174. if (!showingDialog->get())
  2175. GH.fakeMouseMove();
  2176. //todo: this should be in main thread
  2177. if (adventureInt)
  2178. {
  2179. // (i == 0) means hero went through all the path
  2180. adventureInt->updateMoveHero(h, (i != 0));
  2181. adventureInt->updateNextHero(h);
  2182. }
  2183. setMovementStatus(false);
  2184. }
  2185. void CPlayerInterface::showWorldViewEx(const std::vector<ObjectPosInfo>& objectPositions)
  2186. {
  2187. EVENT_HANDLER_CALLED_BY_CLIENT;
  2188. //TODO: showWorldViewEx
  2189. std::copy(objectPositions.begin(), objectPositions.end(), std::back_inserter(adventureInt->worldViewOptions.iconPositions));
  2190. viewWorldMap();
  2191. }
  2192. void CPlayerInterface::updateAmbientSounds(bool resetAll)
  2193. {
  2194. if(castleInt || battleInt || !makingTurn || !currentSelection)
  2195. {
  2196. CCS->soundh->ambientStopAllChannels();
  2197. return;
  2198. }
  2199. else if(!dynamic_cast<CAdvMapInt *>(GH.topInt().get()))
  2200. {
  2201. return;
  2202. }
  2203. if(resetAll)
  2204. CCS->soundh->ambientStopAllChannels();
  2205. std::map<std::string, int> currentSounds;
  2206. auto updateSounds = [&](std::string soundId, int distance) -> void
  2207. {
  2208. if(vstd::contains(currentSounds, soundId))
  2209. currentSounds[soundId] = std::max(currentSounds[soundId], distance);
  2210. else
  2211. currentSounds.insert(std::make_pair(soundId, distance));
  2212. };
  2213. int3 pos = currentSelection->getSightCenter();
  2214. std::unordered_set<int3, ShashInt3> tiles;
  2215. cb->getVisibleTilesInRange(tiles, pos, CCS->soundh->ambientGetRange(), int3::DIST_CHEBYSHEV);
  2216. for(int3 tile : tiles)
  2217. {
  2218. int dist = pos.dist(tile, int3::DIST_CHEBYSHEV);
  2219. // We want sound for every special terrain on tile and not just one on top
  2220. for(auto & ttObj : CGI->mh->ttiles[tile.z][tile.x][tile.y].objects)
  2221. {
  2222. if(ttObj.ambientSound)
  2223. updateSounds(ttObj.ambientSound.get(), dist);
  2224. }
  2225. if(CGI->mh->map->isCoastalTile(tile))
  2226. updateSounds("LOOPOCEA", dist);
  2227. }
  2228. CCS->soundh->ambientUpdateChannels(currentSounds);
  2229. }