CBattleCallback.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412
  1. #include "StdInc.h"
  2. #include "CBattleCallback.h"
  3. #include "BattleState.h"
  4. #include "CGameState.h"
  5. #include "NetPacks.h"
  6. #include "CSpellHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "CTownHandler.h"
  9. /*
  10. * CBattleCallback.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. #define RETURN_IF_NOT_BATTLE(X) if(!duringBattle()) {logGlobal->errorStream() << __FUNCTION__ << " called when no battle!"; return X; }
  19. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  20. {
  21. static void retreiveTurretDamageRange(const CStack *turret, double &outMinDmg, double &outMaxDmg)
  22. {
  23. assert(turret->getCreature()->idNumber == CreatureID::ARROW_TOWERS);
  24. switch(turret->position)
  25. {
  26. case -2: //keep
  27. outMinDmg = 15;
  28. outMaxDmg = 15;
  29. break;
  30. case -3: case -4: //turrets
  31. outMinDmg = 7.5;
  32. outMaxDmg = 7.5;
  33. break;
  34. default:
  35. logGlobal->warnStream() << "Unknown turret type!";
  36. outMaxDmg = outMinDmg = 1;
  37. }
  38. }
  39. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  40. {
  41. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  42. return lineToHex[line];
  43. }
  44. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  45. {
  46. const int wallInStackLine = lineToWallHex(pos1.getY());
  47. const int wallInDestLine = lineToWallHex(pos2.getY());
  48. const bool stackLeft = pos1 < wallInStackLine;
  49. const bool destLeft = pos2 < wallInDestLine;
  50. return stackLeft != destLeft;
  51. }
  52. static EWallParts::EWallParts hexToWallPart(BattleHex hex)
  53. {
  54. //potentially attackable parts of wall
  55. // -2 - indestructible walls
  56. static const std::pair<int, EWallParts::EWallParts> attackable[] =
  57. {
  58. std::make_pair(50, EWallParts::KEEP),
  59. std::make_pair(183, EWallParts::BOTTOM_TOWER),
  60. std::make_pair(182, EWallParts::BOTTOM_WALL),
  61. std::make_pair(130, EWallParts::BELOW_GATE),
  62. std::make_pair(62, EWallParts::OVER_GATE),
  63. std::make_pair(29, EWallParts::UPPER_WAL),
  64. std::make_pair(12, EWallParts::UPPER_TOWER),
  65. std::make_pair(95, EWallParts::GATE),
  66. std::make_pair(96, EWallParts::GATE),
  67. std::make_pair(45, EWallParts::INDESTRUCTIBLE_PART),
  68. std::make_pair(78, EWallParts::INDESTRUCTIBLE_PART),
  69. std::make_pair(112, EWallParts::INDESTRUCTIBLE_PART),
  70. std::make_pair(147, EWallParts::INDESTRUCTIBLE_PART)
  71. };
  72. for(auto & elem : attackable)
  73. {
  74. if(elem.first == hex)
  75. return elem.second;
  76. }
  77. return EWallParts::INVALID; //not found!
  78. }
  79. }
  80. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  81. boost::shared_mutex& CCallbackBase::getGsMutex()
  82. {
  83. return *gs->mx;
  84. }
  85. bool CCallbackBase::duringBattle() const
  86. {
  87. return getBattle() != nullptr;
  88. }
  89. void CCallbackBase::setBattle(const BattleInfo *B)
  90. {
  91. battle = B;
  92. }
  93. boost::optional<PlayerColor> CCallbackBase::getPlayerID() const
  94. {
  95. return player;
  96. }
  97. ETerrainType CBattleInfoEssentials::battleTerrainType() const
  98. {
  99. RETURN_IF_NOT_BATTLE(ETerrainType::WRONG);
  100. return getBattle()->terrainType;
  101. }
  102. BFieldType CBattleInfoEssentials::battleGetBattlefieldType() const
  103. {
  104. RETURN_IF_NOT_BATTLE(BFieldType::NONE);
  105. return getBattle()->battlefieldType;
  106. }
  107. std::vector<shared_ptr<const CObstacleInstance> > CBattleInfoEssentials::battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective /*= boost::none*/) const
  108. {
  109. std::vector<shared_ptr<const CObstacleInstance> > ret;
  110. RETURN_IF_NOT_BATTLE(ret);
  111. if(!perspective)
  112. {
  113. //if no particular perspective request, use default one
  114. perspective = battleGetMySide();
  115. }
  116. else
  117. {
  118. if(!!player && *perspective != battleGetMySide())
  119. {
  120. logGlobal->errorStream() << "Unauthorized access attempt!";
  121. assert(0); //I want to notice if that happens
  122. //perspective = battleGetMySide();
  123. }
  124. }
  125. for(auto oi : getBattle()->obstacles)
  126. {
  127. if(getBattle()->battleIsObstacleVisibleForSide(*oi, *perspective))
  128. ret.push_back(oi);
  129. }
  130. return ret;
  131. }
  132. bool CBattleInfoEssentials::battleIsObstacleVisibleForSide(const CObstacleInstance & coi, BattlePerspective::BattlePerspective side) const
  133. {
  134. RETURN_IF_NOT_BATTLE(false);
  135. return side == BattlePerspective::ALL_KNOWING || coi.visibleForSide(side, battleHasNativeStack(side));
  136. }
  137. bool CBattleInfoEssentials::battleHasNativeStack(ui8 side) const
  138. {
  139. RETURN_IF_NOT_BATTLE(false);
  140. for(const CStack *s : battleGetAllStacks())
  141. {
  142. if(s->attackerOwned == !side && s->getCreature()->isItNativeTerrain(getBattle()->terrainType))
  143. return true;
  144. }
  145. return false;
  146. }
  147. TStacks CBattleInfoEssentials::battleGetAllStacks() const /*returns all stacks, alive or dead or undead or mechanical :) */
  148. {
  149. TStacks ret;
  150. RETURN_IF_NOT_BATTLE(ret);
  151. boost::copy(getBattle()->stacks, std::back_inserter(ret));
  152. return ret;
  153. }
  154. TStacks CBattleInfoEssentials::battleAliveStacks() const
  155. {
  156. TStacks ret;
  157. vstd::copy_if(battleGetAllStacks(), std::back_inserter(ret), [](const CStack *s){ return s->alive(); });
  158. return ret;
  159. }
  160. TStacks CBattleInfoEssentials::battleAliveStacks(ui8 side) const
  161. {
  162. TStacks ret;
  163. vstd::copy_if(battleGetAllStacks(), std::back_inserter(ret), [=](const CStack *s){ return s->alive() && s->attackerOwned == !side; });
  164. return ret;
  165. }
  166. int CBattleInfoEssentials::battleGetMoatDmg() const
  167. {
  168. RETURN_IF_NOT_BATTLE(0);
  169. auto town = getBattle()->town;
  170. if(!town)
  171. return 0;
  172. return town->town->moatDamage;
  173. }
  174. const CGTownInstance * CBattleInfoEssentials::battleGetDefendedTown() const
  175. {
  176. RETURN_IF_NOT_BATTLE(nullptr);
  177. if(!getBattle() || getBattle()->town == nullptr)
  178. return nullptr;
  179. return getBattle()->town;
  180. }
  181. BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const
  182. {
  183. RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID);
  184. if(!player)
  185. return BattlePerspective::ALL_KNOWING;
  186. if(*player == getBattle()->sides[0].color)
  187. return BattlePerspective::LEFT_SIDE;
  188. if(*player == getBattle()->sides[1].color)
  189. return BattlePerspective::RIGHT_SIDE;
  190. logGlobal->errorStream() << "Cannot find player " << *player << " in battle!";
  191. return BattlePerspective::INVALID;
  192. }
  193. const CStack * CBattleInfoEssentials::battleActiveStack() const
  194. {
  195. RETURN_IF_NOT_BATTLE(nullptr);
  196. return battleGetStackByID(getBattle()->activeStack);
  197. }
  198. const CStack* CBattleInfoEssentials::battleGetStackByID(int ID, bool onlyAlive) const
  199. {
  200. RETURN_IF_NOT_BATTLE(nullptr);
  201. for(auto s : battleGetAllStacks())
  202. if(s->ID == ID && (!onlyAlive || s->alive()))
  203. return s;
  204. return nullptr;
  205. }
  206. bool CBattleInfoEssentials::battleDoWeKnowAbout(ui8 side) const
  207. {
  208. RETURN_IF_NOT_BATTLE(false);
  209. auto p = battleGetMySide();
  210. return p == BattlePerspective::ALL_KNOWING || p == side;
  211. }
  212. si8 CBattleInfoEssentials::battleTacticDist() const
  213. {
  214. RETURN_IF_NOT_BATTLE(0);
  215. return getBattle()->tacticDistance;
  216. }
  217. si8 CBattleInfoEssentials::battleGetTacticsSide() const
  218. {
  219. RETURN_IF_NOT_BATTLE(-1);
  220. return getBattle()->tacticsSide;
  221. }
  222. const CGHeroInstance * CBattleInfoEssentials::battleGetFightingHero(ui8 side) const
  223. {
  224. RETURN_IF_NOT_BATTLE(nullptr);
  225. if(side > 1)
  226. {
  227. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
  228. return nullptr;
  229. }
  230. if(!battleDoWeKnowAbout(side))
  231. {
  232. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
  233. return nullptr;
  234. }
  235. return getBattle()->sides[side].hero;
  236. }
  237. const CArmedInstance * CBattleInfoEssentials::battleGetArmyObject(ui8 side) const
  238. {
  239. RETURN_IF_NOT_BATTLE(nullptr);
  240. if(side > 1)
  241. {
  242. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
  243. return nullptr;
  244. }
  245. if(!battleDoWeKnowAbout(side))
  246. {
  247. logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
  248. return nullptr;
  249. }
  250. return getBattle()->sides[side].armyObject;
  251. }
  252. InfoAboutHero CBattleInfoEssentials::battleGetHeroInfo( ui8 side ) const
  253. {
  254. auto hero = getBattle()->sides[side].hero;
  255. if(!hero)
  256. {
  257. logGlobal->warnStream() << __FUNCTION__ << ": side " << (int)side << " does not have hero!";
  258. return InfoAboutHero();
  259. }
  260. return InfoAboutHero(hero, battleDoWeKnowAbout(side));
  261. }
  262. int CBattleInfoEssentials::battleCastSpells(ui8 side) const
  263. {
  264. RETURN_IF_NOT_BATTLE(-1);
  265. return getBattle()->sides[side].castSpellsCount;
  266. }
  267. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(PlayerColor player, ECastingMode::ECastingMode mode) const
  268. {
  269. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  270. const ui8 side = playerToSide(player);
  271. if(!battleDoWeKnowAbout(side))
  272. {
  273. logGlobal->warnStream() << "You can't check if enemy can cast given spell!";
  274. return ESpellCastProblem::INVALID;
  275. }
  276. switch (mode)
  277. {
  278. case ECastingMode::HERO_CASTING:
  279. {
  280. if(battleTacticDist())
  281. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  282. if(battleCastSpells(side) > 0)
  283. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  284. auto hero = battleGetFightingHero(side);
  285. if(!hero)
  286. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  287. if(!hero->getArt(ArtifactPosition::SPELLBOOK))
  288. return ESpellCastProblem::NO_SPELLBOOK;
  289. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  290. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  291. }
  292. break;
  293. default:
  294. break;
  295. }
  296. return ESpellCastProblem::OK;
  297. }
  298. bool CBattleInfoEssentials::battleCanFlee(PlayerColor player) const
  299. {
  300. RETURN_IF_NOT_BATTLE(false);
  301. ui8 mySide = playerToSide(player);
  302. const CGHeroInstance *myHero = battleGetFightingHero(mySide);
  303. //current player have no hero
  304. if(!myHero)
  305. return false;
  306. //eg. one of heroes is wearing shakles of war
  307. if(myHero->hasBonusOfType(Bonus::BATTLE_NO_FLEEING))
  308. return false;
  309. //we are besieged defender
  310. if(mySide == BattleSide::DEFENDER && battleGetSiegeLevel())
  311. {
  312. auto town = battleGetDefendedTown();
  313. if(!town->hasBuilt(BuildingID::ESCAPE_TUNNEL, ETownType::STRONGHOLD))
  314. return false;
  315. }
  316. return true;
  317. }
  318. ui8 CBattleInfoEssentials::playerToSide(PlayerColor player) const
  319. {
  320. RETURN_IF_NOT_BATTLE(-1);
  321. int ret = vstd::find_pos_if(getBattle()->sides, [=](const SideInBattle &side){ return side.color == player; });
  322. if(ret < 0)
  323. logGlobal->warnStream() << "Cannot find side for player " << player;
  324. return ret;
  325. }
  326. ui8 CBattleInfoEssentials::battleGetSiegeLevel() const
  327. {
  328. RETURN_IF_NOT_BATTLE(0);
  329. return getBattle()->siege;
  330. }
  331. bool CBattleInfoEssentials::battleCanSurrender(PlayerColor player) const
  332. {
  333. RETURN_IF_NOT_BATTLE(false);
  334. //conditions like for fleeing + enemy must have a hero
  335. return battleCanFlee(player) && battleHasHero(!playerToSide(player));
  336. }
  337. bool CBattleInfoEssentials::battleHasHero(ui8 side) const
  338. {
  339. RETURN_IF_NOT_BATTLE(false);
  340. assert(side < 2);
  341. return getBattle()->sides[side].hero;
  342. }
  343. ui8 CBattleInfoEssentials::battleGetWallState(int partOfWall) const
  344. {
  345. RETURN_IF_NOT_BATTLE(0);
  346. if(getBattle()->siege == CGTownInstance::NONE)
  347. return 0;
  348. assert(partOfWall >= 0 && partOfWall < EWallParts::PARTS_COUNT);
  349. return getBattle()->si.wallState[partOfWall];
  350. }
  351. si8 CBattleInfoCallback::battleHasWallPenalty( const CStack * stack, BattleHex destHex ) const
  352. {
  353. return battleHasWallPenalty(stack, stack->position, destHex);
  354. }
  355. si8 CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  356. {
  357. RETURN_IF_NOT_BATTLE(false);
  358. if (!battleGetSiegeLevel() || bonusBearer->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  359. return false;
  360. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  361. const int wallInDestLine = lineToWallHex(destHex.getY());
  362. const bool stackLeft = shooterPosition < wallInStackLine;
  363. const bool destRight = destHex > wallInDestLine;
  364. if (stackLeft && destRight) //shooting from outside to inside
  365. {
  366. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  367. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  368. row -= 2;
  369. const int wallPos = lineToWallHex(row);
  370. if (battleHexToWallPart(wallPos) < 0) //wall still exists or is indestructible
  371. return true;
  372. }
  373. return false;
  374. }
  375. si8 CBattleInfoCallback::battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  376. {
  377. RETURN_IF_NOT_BATTLE(false);
  378. if(getAccesibility(stack).accessible(destHex, stack))
  379. return false;
  380. if (battleGetSiegeLevel() && telportLevel < 2) //check for wall
  381. return sameSideOfWall(stack->position, destHex);
  382. return true;
  383. }
  384. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  385. {
  386. std::set<BattleHex> attackedHexes;
  387. RETURN_IF_NOT_BATTLE(attackedHexes);
  388. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  389. for (BattleHex tile : at.hostileCreaturePositions)
  390. {
  391. const CStack * st = battleGetStackByPos(tile, true);
  392. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  393. {
  394. attackedHexes.insert(tile);
  395. }
  396. }
  397. for (BattleHex tile : at.friendlyCreaturePositions)
  398. {
  399. if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  400. {
  401. attackedHexes.insert(tile);
  402. }
  403. }
  404. return attackedHexes;
  405. }
  406. SpellID CBattleInfoCallback::battleGetRandomStackSpell(const CStack * stack, ERandomSpell mode) const
  407. {
  408. switch (mode)
  409. {
  410. case RANDOM_GENIE:
  411. return getRandomBeneficialSpell(stack); //target
  412. break;
  413. case RANDOM_AIMED:
  414. return getRandomCastedSpell(stack); //caster
  415. break;
  416. default:
  417. logGlobal->errorStream() << "Incorrect mode of battleGetRandomSpell (" << mode <<")";
  418. return SpellID::NONE;
  419. }
  420. }
  421. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  422. {
  423. RETURN_IF_NOT_BATTLE(nullptr);
  424. for(auto s : battleGetAllStacks())
  425. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  426. return s;
  427. return nullptr;
  428. }
  429. void CBattleInfoCallback::battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn /*= 0*/, int lastMoved /*= -1*/) const
  430. {
  431. RETURN_IF_NOT_BATTLE();
  432. //let's define a huge lambda
  433. auto takeStack = [&](std::vector<const CStack *> &st) -> const CStack*
  434. {
  435. const CStack *ret = nullptr;
  436. unsigned i, //fastest stack
  437. j=0; //fastest stack of the other side
  438. for(i = 0; i < st.size(); i++)
  439. if(st[i])
  440. break;
  441. //no stacks left
  442. if(i == st.size())
  443. return nullptr;
  444. const CStack *fastest = st[i], *other = nullptr;
  445. int bestSpeed = fastest->Speed(turn);
  446. if(fastest->attackerOwned != lastMoved)
  447. {
  448. ret = fastest;
  449. }
  450. else
  451. {
  452. for(j = i + 1; j < st.size(); j++)
  453. {
  454. if(!st[j]) continue;
  455. if(st[j]->attackerOwned != lastMoved || st[j]->Speed(turn) != bestSpeed)
  456. break;
  457. }
  458. if(j >= st.size())
  459. {
  460. ret = fastest;
  461. }
  462. else
  463. {
  464. other = st[j];
  465. if(other->Speed(turn) != bestSpeed)
  466. ret = fastest;
  467. else
  468. ret = other;
  469. }
  470. }
  471. assert(ret);
  472. if(ret == fastest)
  473. st[i] = nullptr;
  474. else
  475. st[j] = nullptr;
  476. lastMoved = ret->attackerOwned;
  477. return ret;
  478. };
  479. //We'll split creatures with remaining movement to 4 buckets
  480. // [0] - turrets/catapult,
  481. // [1] - normal (unmoved) creatures, other war machines,
  482. // [2] - waited cres that had morale,
  483. // [3] - rest of waited cres
  484. std::vector<const CStack *> phase[4];
  485. int toMove = 0; //how many stacks still has move
  486. const CStack *active = battleActiveStack();
  487. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  488. if(!turn && active && active->willMove() && !active->waited())
  489. {
  490. out.push_back(active);
  491. if(out.size() == howMany)
  492. return;
  493. }
  494. auto allStacks = battleGetAllStacks();
  495. if(!vstd::contains_if(allStacks, [](const CStack *stack) { return stack->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  496. {
  497. //No stack will be able to move, battle is over.
  498. out.clear();
  499. return;
  500. }
  501. for(auto s : battleGetAllStacks())
  502. {
  503. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  504. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  505. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  506. {
  507. continue;
  508. }
  509. int p = -1; //in which phase this tack will move?
  510. if(turn <= 0 && s->waited()) //consider waiting state only for ongoing round
  511. {
  512. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  513. p = 2;
  514. else
  515. p = 3;
  516. }
  517. else if(s->getCreature()->idNumber == CreatureID::CATAPULT || s->getCreature()->idNumber == CreatureID::ARROW_TOWERS) //catapult and turrets are first
  518. {
  519. p = 0;
  520. }
  521. else
  522. {
  523. p = 1;
  524. }
  525. phase[p].push_back(s);
  526. toMove++;
  527. }
  528. for(int i = 0; i < 4; i++)
  529. boost::sort(phase[i], CMP_stack(i, turn > 0 ? turn : 0));
  530. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  531. out.push_back(phase[0][i]);
  532. if(out.size() == howMany)
  533. return;
  534. if(lastMoved == -1)
  535. {
  536. if(active)
  537. {
  538. if(out.size() && out.front() == active)
  539. lastMoved = active->attackerOwned;
  540. else
  541. lastMoved = active->attackerOwned;
  542. }
  543. else
  544. {
  545. lastMoved = 0;
  546. }
  547. }
  548. int pi = 1;
  549. while(out.size() < howMany)
  550. {
  551. const CStack *hlp = takeStack(phase[pi]);
  552. if(!hlp)
  553. {
  554. pi++;
  555. if(pi > 3)
  556. {
  557. //if(turn != 2)
  558. battleGetStackQueue(out, howMany, turn + 1, lastMoved);
  559. return;
  560. }
  561. }
  562. else
  563. {
  564. out.push_back(hlp);
  565. }
  566. }
  567. }
  568. void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
  569. {
  570. RETURN_IF_NOT_BATTLE();
  571. auto accessibility = getAccesibility();
  572. for(int i = 0; i < accessibility.size(); i++)
  573. ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  574. }
  575. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable) const
  576. {
  577. std::vector<BattleHex> ret;
  578. RETURN_IF_NOT_BATTLE(ret);
  579. if(!stack->position.isValid()) //turrets
  580. return ret;
  581. auto reachability = getReachability(stack);
  582. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  583. {
  584. // If obstacles or other stacks makes movement impossible, it can't be helped.
  585. if(!reachability.isReachable(i))
  586. continue;
  587. if(battleTacticDist() && battleGetTacticsSide() == !stack->attackerOwned)
  588. {
  589. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  590. if(!isInTacticRange(i))
  591. continue;
  592. }
  593. else
  594. {
  595. //Not tactics phase -> destination must be reachable and within stack range.
  596. if(reachability.distances[i] > stack->Speed(0, true))
  597. continue;
  598. }
  599. ret.push_back(i);
  600. if(addOccupiable && stack->doubleWide())
  601. {
  602. //If two-hex stack can stand on hex i then obviously it can occupy its second hex from that position
  603. ret.push_back(stack->occupiedHex(i));
  604. }
  605. }
  606. if(attackable)
  607. {
  608. auto meleeAttackable = [&](BattleHex hex) -> bool
  609. {
  610. // Return true if given hex has at least one available neighbour.
  611. // Available hexes are already present in ret vector.
  612. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  613. { return BattleHex::mutualPosition(hex, availableHex) >= 0; });
  614. return availableNeighbor != ret.end();
  615. };
  616. for(const CStack * otherSt : battleAliveStacks(stack->attackerOwned))
  617. {
  618. if(!otherSt->isValidTarget(false))
  619. continue;
  620. std::vector<BattleHex> occupied = otherSt->getHexes();
  621. if(battleCanShoot(stack, otherSt->position))
  622. {
  623. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  624. continue;
  625. }
  626. for(BattleHex he : occupied)
  627. {
  628. if(meleeAttackable(he))
  629. attackable->push_back(he);
  630. }
  631. }
  632. }
  633. //adding occupiable likely adds duplicates to ret -> clean it up
  634. boost::sort(ret);
  635. ret.erase(boost::unique(ret).end(), ret.end());
  636. return ret;
  637. }
  638. bool CBattleInfoCallback::battleCanShoot(const CStack * stack, BattleHex dest) const
  639. {
  640. RETURN_IF_NOT_BATTLE(false);
  641. if(battleTacticDist()) //no shooting during tactics
  642. return false;
  643. const CStack *dst = battleGetStackByPos(dest);
  644. if(!stack || !dst)
  645. return false;
  646. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  647. return false;
  648. if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
  649. return false;
  650. //const CGHeroInstance * stackHero = battleGetOwner(stack);
  651. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  652. && stack->owner != dst->owner
  653. && dst->alive()
  654. && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
  655. && stack->shots
  656. )
  657. return true;
  658. return false;
  659. }
  660. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
  661. ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  662. {
  663. return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  664. }
  665. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo &info) const
  666. {
  667. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  668. {
  669. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  670. auto limitMatches = info.shooting
  671. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  672. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  673. //any regular bonuses or just ones for melee/ranged
  674. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  675. };
  676. double additiveBonus = 1.0, multBonus = 1.0,
  677. minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
  678. maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
  679. const CCreature *attackerType = info.attacker->getCreature(),
  680. *defenderType = info.defender->getCreature();
  681. if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
  682. {
  683. SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(info.attacker, minDmg, maxDmg);
  684. }
  685. if(info.attackerBonuses->hasBonusOfType(Bonus::SIEGE_WEAPON) && attackerType->idNumber != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  686. { //minDmg and maxDmg are multiplied by hero attack + 1
  687. auto retreiveHeroPrimSkill = [&](int skill) -> int
  688. {
  689. const Bonus *b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  690. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  691. };
  692. minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  693. maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  694. }
  695. int attackDefenceDifference = 0;
  696. double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
  697. attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
  698. double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
  699. attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
  700. if(const Bonus *slayerEffect = info.attackerBonuses->getEffect(SpellID::SLAYER)) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  701. {
  702. std::vector<int> affectedIds;
  703. int spLevel = slayerEffect->val;
  704. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  705. {
  706. for(const Bonus *b : VLC->creh->creatures[g]->getBonusList())
  707. {
  708. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  709. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  710. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  711. {
  712. affectedIds.push_back(g);
  713. break;
  714. }
  715. }
  716. }
  717. for(auto & affectedId : affectedIds)
  718. {
  719. if(defenderType->idNumber == affectedId)
  720. {
  721. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->powers[spLevel];
  722. break;
  723. }
  724. }
  725. }
  726. //bonus from attack/defense skills
  727. if(attackDefenceDifference < 0) //decreasing dmg
  728. {
  729. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  730. multBonus *= 1.0 - dec;
  731. }
  732. else //increasing dmg
  733. {
  734. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  735. additiveBonus += inc;
  736. }
  737. //applying jousting bonus
  738. if( info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  739. additiveBonus += info.chargedFields * 0.05;
  740. //handling secondary abilities and artifacts giving premies to them
  741. if(info.shooting)
  742. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
  743. else
  744. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
  745. if(info.defenderBonuses)
  746. multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
  747. //handling hate effect
  748. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
  749. //luck bonus
  750. if (info.luckyHit)
  751. {
  752. additiveBonus += 1.0;
  753. }
  754. //unlucky hit, used only if negative luck is enabled
  755. if (info.unluckyHit)
  756. {
  757. additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
  758. }
  759. //ballista double dmg
  760. if(info.ballistaDoubleDamage)
  761. {
  762. additiveBonus += 1.0;
  763. }
  764. if (info.deathBlow) //Dread Knight and many WoGified creatures
  765. {
  766. additiveBonus += 1.0;
  767. }
  768. //handling spell effects
  769. if(!info.shooting) //eg. shield
  770. {
  771. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
  772. }
  773. else if(info.shooting) //eg. air shield
  774. {
  775. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
  776. }
  777. TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
  778. TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
  779. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  780. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
  781. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  782. {
  783. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  784. }
  785. auto isAdvancedAirShield = [](const Bonus *bonus)
  786. {
  787. return bonus->source == Bonus::SPELL_EFFECT
  788. && bonus->sid == SpellID::AIR_SHIELD
  789. && bonus->val >= SecSkillLevel::ADVANCED;
  790. };
  791. //wall / distance penalty + advanced air shield
  792. const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  793. const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  794. if (info.shooting)
  795. {
  796. if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
  797. {
  798. multBonus *= 0.5;
  799. }
  800. if (obstaclePenalty)
  801. {
  802. multBonus *= 0.5; //cumulative
  803. }
  804. }
  805. if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  806. {
  807. multBonus *= 0.5;
  808. }
  809. // TODO attack on petrified unit 50%
  810. // psychic elementals versus mind immune units 50%
  811. // blinded unit retaliates
  812. minDmg *= additiveBonus * multBonus;
  813. maxDmg *= additiveBonus * multBonus;
  814. TDmgRange returnedVal;
  815. if(curseEffects->size()) //curse handling (rest)
  816. {
  817. minDmg += curseBlessAdditiveModifier;
  818. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  819. }
  820. else if(blessEffects->size()) //bless handling
  821. {
  822. maxDmg += curseBlessAdditiveModifier;
  823. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  824. }
  825. else
  826. {
  827. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  828. }
  829. //damage cannot be less than 1
  830. vstd::amax(returnedVal.first, 1);
  831. vstd::amax(returnedVal.second, 1);
  832. return returnedVal;
  833. }
  834. TDmgRange CBattleInfoCallback::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount,
  835. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg ) const
  836. {
  837. BattleAttackInfo bai(attacker, defender, shooting);
  838. bai.attackerCount = attackerCount;
  839. bai.chargedFields = charge;
  840. bai.luckyHit = lucky;
  841. bai.unluckyHit = unlucky;
  842. bai.deathBlow = deathBlow;
  843. bai.ballistaDoubleDamage = ballistaDoubleDmg;
  844. return calculateDmgRange(bai);
  845. }
  846. TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  847. {
  848. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  849. const bool shooting = battleCanShoot(attacker, defender->position);
  850. const BattleAttackInfo bai(attacker, defender, shooting);
  851. return battleEstimateDamage(bai, retaliationDmg);
  852. }
  853. std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo &bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
  854. {
  855. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  856. //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
  857. //const ui8 mySide = !attacker->attackerOwned;
  858. TDmgRange ret = calculateDmgRange(bai);
  859. if(retaliationDmg)
  860. {
  861. if(bai.shooting)
  862. {
  863. retaliationDmg->first = retaliationDmg->second = 0;
  864. }
  865. else
  866. {
  867. ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  868. for (int i=0; i<2; ++i)
  869. {
  870. BattleStackAttacked bsa;
  871. bsa.damageAmount = ret.*pairElems[i];
  872. bai.defender->prepareAttacked(bsa, bai.defenderCount);
  873. auto retaliationAttack = bai.reverse();
  874. retaliationAttack.attackerCount = bsa.newAmount;
  875. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  876. }
  877. }
  878. }
  879. return ret;
  880. }
  881. shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
  882. {
  883. RETURN_IF_NOT_BATTLE(shared_ptr<const CObstacleInstance>());
  884. for(auto &obs : battleGetAllObstacles())
  885. {
  886. if(vstd::contains(obs->getBlockedTiles(), tile)
  887. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  888. {
  889. return obs;
  890. }
  891. }
  892. return shared_ptr<const CObstacleInstance>();
  893. }
  894. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  895. {
  896. AccessibilityInfo ret;
  897. ret.fill(EAccessibility::ACCESSIBLE);
  898. //removing accessibility for side columns of hexes
  899. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  900. {
  901. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  902. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  903. }
  904. //gate -> should be before stacks
  905. if(battleGetSiegeLevel() > 0 && battleGetWallState(EWallParts::GATE) < 3) //gate is not destroyed
  906. {
  907. ret[95] = ret[96] = EAccessibility::GATE; //block gate's hexes
  908. }
  909. //tiles occupied by standing stacks
  910. for(auto stack : battleAliveStacks())
  911. {
  912. for(auto hex : stack->getHexes())
  913. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  914. ret[hex] = EAccessibility::ALIVE_STACK;
  915. }
  916. //obstacles
  917. for(const auto &obst : battleGetAllObstacles())
  918. {
  919. for(auto hex : obst->getBlockedTiles())
  920. ret[hex] = EAccessibility::OBSTACLE;
  921. }
  922. //walls
  923. if(battleGetSiegeLevel() > 0)
  924. {
  925. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  926. for(auto hex : permanentlyLocked)
  927. ret[hex] = EAccessibility::UNAVAILABLE;
  928. //TODO likely duplicated logic
  929. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  930. {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
  931. std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
  932. for(auto & elem : lockedIfNotDestroyed)
  933. {
  934. if(battleGetWallState(elem.first) < 3)
  935. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  936. }
  937. }
  938. return ret;
  939. }
  940. AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack *stack) const
  941. {
  942. return getAccesibility(stack->getHexes());
  943. }
  944. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> &accessibleHexes) const
  945. {
  946. auto ret = getAccesibility();
  947. for(auto hex : accessibleHexes)
  948. if(hex.isValid())
  949. ret[hex] = EAccessibility::ACCESSIBLE;
  950. return ret;
  951. }
  952. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters params) const
  953. {
  954. ReachabilityInfo ret;
  955. ret.accessibility = accessibility;
  956. ret.params = params;
  957. ret.predecessors.fill(BattleHex::INVALID);
  958. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  959. if(!params.startPosition.isValid()) //if got call for arrow turrets
  960. return ret;
  961. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  962. //const bool twoHexCreature = params.doubleWide;
  963. std::queue<BattleHex> hexq; //bfs queue
  964. //first element
  965. hexq.push(params.startPosition);
  966. ret.distances[params.startPosition] = 0;
  967. while(!hexq.empty()) //bfs loop
  968. {
  969. const BattleHex curHex = hexq.front();
  970. hexq.pop();
  971. //walking stack can't step past the quicksands
  972. //TODO what if second hex of two-hex creature enters quicksand
  973. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  974. continue;
  975. const int costToNeighbour = ret.distances[curHex] + 1;
  976. for(BattleHex neighbour : curHex.neighbouringTiles())
  977. {
  978. const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.attackerOwned);
  979. const int costFoundSoFar = ret.distances[neighbour];
  980. if(accessible && costToNeighbour < costFoundSoFar)
  981. {
  982. hexq.push(neighbour);
  983. ret.distances[neighbour] = costToNeighbour;
  984. ret.predecessors[neighbour] = curHex;
  985. }
  986. }
  987. }
  988. return ret;
  989. }
  990. ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack *stack) const
  991. {
  992. return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
  993. }
  994. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  995. {
  996. std::set<BattleHex> ret;
  997. RETURN_IF_NOT_BATTLE(ret);
  998. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  999. {
  1000. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  1001. {
  1002. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  1003. }
  1004. }
  1005. return ret;
  1006. }
  1007. std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  1008. {
  1009. auto reachability = getReachability(closest);
  1010. // I hate std::pairs with their undescriptive member names first / second
  1011. struct DistStack
  1012. {
  1013. int distanceToPred;
  1014. const CStack *stack;
  1015. };
  1016. std::vector<DistStack> stackPairs; //pairs <<distance, hex>, stack>
  1017. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  1018. {
  1019. const CStack * atG = battleGetStackByPos(g);
  1020. if(!atG || atG->ID == closest->ID) //if there is no stack or we are the closest one
  1021. continue;
  1022. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  1023. {
  1024. if (reachability.isReachable(g))
  1025. //FIXME: hexes occupied by enemy stack are not accessible. Need to use BattleInfo::getPath or similiar
  1026. {
  1027. DistStack hlp = {reachability.distances[reachability.predecessors[g]], atG};
  1028. stackPairs.push_back(hlp);
  1029. }
  1030. }
  1031. }
  1032. if (stackPairs.size())
  1033. {
  1034. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  1035. auto minimal = boost::min_element(stackPairs, comparator);
  1036. return std::make_pair(minimal->stack, reachability.predecessors[minimal->stack->position]);
  1037. }
  1038. else
  1039. return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
  1040. }
  1041. si8 CBattleInfoCallback::battleGetTacticDist() const
  1042. {
  1043. RETURN_IF_NOT_BATTLE(0);
  1044. //TODO get rid of this method
  1045. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1046. return battleTacticDist();
  1047. return 0;
  1048. }
  1049. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  1050. {
  1051. RETURN_IF_NOT_BATTLE(false);
  1052. auto side = battleGetTacticsSide();
  1053. auto dist = battleGetTacticDist();
  1054. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  1055. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  1056. }
  1057. ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
  1058. {
  1059. ReachabilityInfo::Parameters params(stack);
  1060. if(!battleDoWeKnowAbout(!stack->attackerOwned))
  1061. {
  1062. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1063. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1064. params.perspective = battleGetMySide();
  1065. }
  1066. return getReachability(params);
  1067. }
  1068. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1069. {
  1070. if(params.flying)
  1071. return getFlyingReachability(params);
  1072. else
  1073. return makeBFS(getAccesibility(params.knownAccessible), params);
  1074. }
  1075. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters params) const
  1076. {
  1077. ReachabilityInfo ret;
  1078. ret.accessibility = getAccesibility(params.knownAccessible);
  1079. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1080. {
  1081. if(ret.accessibility.accessible(i, params.doubleWide, params.attackerOwned))
  1082. {
  1083. ret.predecessors[i] = params.startPosition;
  1084. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1085. }
  1086. }
  1087. return ret;
  1088. }
  1089. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1090. {
  1091. //does not return hex attacked directly
  1092. //TODO: apply rotation to two-hex attackers
  1093. bool isAttacker = attacker->attackerOwned;
  1094. AttackableTiles at;
  1095. RETURN_IF_NOT_BATTLE(at);
  1096. const int WN = GameConstants::BFIELD_WIDTH;
  1097. ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  1098. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  1099. bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  1100. if (reverse)
  1101. {
  1102. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  1103. }
  1104. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  1105. {
  1106. boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
  1107. }
  1108. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  1109. {
  1110. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1111. for (BattleHex tile : hexes)
  1112. {
  1113. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  1114. {
  1115. const CStack * st = battleGetStackByPos(tile, true);
  1116. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1117. {
  1118. at.hostileCreaturePositions.insert(tile);
  1119. }
  1120. }
  1121. }
  1122. }
  1123. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  1124. {
  1125. std::vector<BattleHex> hexes; //only one, in fact
  1126. int pseudoVector = destinationTile.hex - hex;
  1127. switch (pseudoVector)
  1128. {
  1129. case 1:
  1130. case -1:
  1131. BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
  1132. break;
  1133. case WN: //17 //left-down or right-down
  1134. case -WN: //-17 //left-up or right-up
  1135. case WN + 1: //18 //right-down
  1136. case -WN + 1: //-16 //right-up
  1137. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : -1 ), hexes);
  1138. break;
  1139. case WN-1: //16 //left-down
  1140. case -WN-1: //-18 //left-up
  1141. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : 0), hexes);
  1142. break;
  1143. }
  1144. for (BattleHex tile : hexes)
  1145. {
  1146. //friendly stacks can also be damaged by Dragon Breath
  1147. if (battleGetStackByPos (tile, true))
  1148. at.friendlyCreaturePositions.insert (tile);
  1149. }
  1150. }
  1151. return at;
  1152. }
  1153. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  1154. {
  1155. std::set<const CStack*> attackedCres;
  1156. RETURN_IF_NOT_BATTLE(attackedCres);
  1157. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1158. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1159. {
  1160. const CStack * st = battleGetStackByPos(tile, true);
  1161. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1162. {
  1163. attackedCres.insert(st);
  1164. }
  1165. }
  1166. for (BattleHex tile : at.friendlyCreaturePositions)
  1167. {
  1168. const CStack * st = battleGetStackByPos(tile, true);
  1169. if(st) //friendly stacks can also be damaged by Dragon Breath
  1170. {
  1171. attackedCres.insert(st);
  1172. }
  1173. }
  1174. return attackedCres;
  1175. }
  1176. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const //TODO: this should apply also to mechanics and cursor interface
  1177. {
  1178. int fromMod = hexFrom % GameConstants::BFIELD_WIDTH;
  1179. int fromDiv = hexFrom / GameConstants::BFIELD_WIDTH;
  1180. int toMod = hexTo % GameConstants::BFIELD_WIDTH;
  1181. if(curDir && fromMod < toMod)
  1182. return false;
  1183. else if(curDir && fromMod > toMod)
  1184. return true;
  1185. else if(curDir && fromMod == toMod)
  1186. {
  1187. return fromDiv % 2 == 0;
  1188. }
  1189. else if(!curDir && fromMod < toMod)
  1190. return true;
  1191. else if(!curDir && fromMod > toMod)
  1192. return false;
  1193. else if(!curDir && fromMod == toMod)
  1194. {
  1195. return fromDiv % 2 == 1;
  1196. }
  1197. logGlobal->errorStream() << "Catastrope in CBattleInfoCallback::isToReverse!";
  1198. return false; //should never happen
  1199. }
  1200. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const //TODO: this should apply also to mechanics and cursor interface
  1201. {
  1202. if (hexTo < 0 || hexFrom < 0) //turret
  1203. return false;
  1204. if (toDoubleWide)
  1205. {
  1206. return (isToReverseHlp (hexFrom, hexTo, curDir)) &&
  1207. (toDir ? isToReverseHlp (hexFrom, hexTo-1, curDir) : isToReverseHlp (hexFrom, hexTo+1, curDir));
  1208. }
  1209. else
  1210. {
  1211. return isToReverseHlp(hexFrom, hexTo, curDir);
  1212. }
  1213. }
  1214. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
  1215. {
  1216. ReachabilityInfo::TDistances ret;
  1217. ret.fill(-1);
  1218. RETURN_IF_NOT_BATTLE(ret);
  1219. ReachabilityInfo::Parameters params(stack);
  1220. params.perspective = battleGetMySide();
  1221. params.startPosition = hex.isValid() ? hex : stack->position;
  1222. auto reachability = getReachability(params);
  1223. boost::copy(reachability.distances, ret.begin());
  1224. if(predecessors)
  1225. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1226. predecessors[i] = reachability.predecessors[i];
  1227. return ret;
  1228. }
  1229. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1230. {
  1231. return battleHasDistancePenalty(stack, stack->position, destHex);
  1232. }
  1233. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1234. {
  1235. RETURN_IF_NOT_BATTLE(false);
  1236. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1237. return false;
  1238. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1239. {
  1240. //If any hex of target creature is within range, there is no penalty
  1241. for(auto hex : dstStack->getHexes())
  1242. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1243. return false;
  1244. //TODO what about two-hex shooters?
  1245. }
  1246. else
  1247. {
  1248. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1249. return false;
  1250. }
  1251. return true;
  1252. }
  1253. EWallParts::EWallParts CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1254. {
  1255. RETURN_IF_NOT_BATTLE(EWallParts::INVALID);
  1256. return hexToWallPart(hex);
  1257. }
  1258. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
  1259. {
  1260. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1261. // Get stack at destination hex -> subject of our spell.
  1262. const CStack * subject = battleGetStackByPos(dest, !spell->isRisingSpell()); //only alive if not rising spell
  1263. if(subject)
  1264. {
  1265. if (spell->isPositive() && subject->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  1266. return ESpellCastProblem::OK;
  1267. if (spell->isImmuneBy(subject)) //TODO: move all logic to spellhandler
  1268. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1269. switch (spell->id) //TODO: more general logic for new spells?
  1270. {
  1271. case SpellID::CLONE:
  1272. {
  1273. //can't clone already cloned creature
  1274. if (vstd::contains(subject->state, EBattleStackState::CLONED))
  1275. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1276. //TODO: how about stacks casting Clone?
  1277. //currently Clone casted by stack is assumed Expert level
  1278. ui8 schoolLevel;
  1279. if (caster)
  1280. {
  1281. schoolLevel = caster->getSpellSchoolLevel(spell);
  1282. }
  1283. else
  1284. {
  1285. schoolLevel = 3;
  1286. }
  1287. if (schoolLevel < 3)
  1288. {
  1289. int maxLevel = (std::max(schoolLevel, (ui8)1) + 4);
  1290. int creLevel = subject->getCreature()->level;
  1291. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, any level for expert
  1292. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1293. }
  1294. }
  1295. break;
  1296. case SpellID::DISPEL_HELPFUL_SPELLS:
  1297. {
  1298. TBonusListPtr spellBon = subject->getSpellBonuses();
  1299. bool hasPositiveSpell = false;
  1300. for(const Bonus * b : *spellBon)
  1301. {
  1302. if(SpellID(b->sid).toSpell()->isPositive())
  1303. {
  1304. hasPositiveSpell = true;
  1305. break;
  1306. }
  1307. }
  1308. if(!hasPositiveSpell)
  1309. {
  1310. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  1311. }
  1312. }
  1313. break;
  1314. }
  1315. if (spell->isRisingSpell())
  1316. {
  1317. if (subject->count >= subject->baseAmount) //TODO: calculate potential hp raised
  1318. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  1319. }
  1320. }
  1321. else //no target stack on this tile
  1322. {
  1323. if(spell->getTargetType() == CSpell::CREATURE
  1324. || (spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE
  1325. && mode == ECastingMode::HERO_CASTING //TODO why???
  1326. && caster
  1327. && caster->getSpellSchoolLevel(spell) < SecSkillLevel::EXPERT))
  1328. {
  1329. return ESpellCastProblem::WRONG_SPELL_TARGET;
  1330. }
  1331. }
  1332. return ESpellCastProblem::OK;
  1333. }
  1334. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpell( PlayerColor player, const CSpell * spell, ECastingMode::ECastingMode mode ) const
  1335. {
  1336. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1337. const ui8 side = playerToSide(player);
  1338. if(!battleDoWeKnowAbout(side))
  1339. return ESpellCastProblem::INVALID;
  1340. ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
  1341. if(genProblem != ESpellCastProblem::OK)
  1342. return genProblem;
  1343. //Casting hero, set only if he is an actual caster.
  1344. const CGHeroInstance *castingHero = mode == ECastingMode::HERO_CASTING
  1345. ? battleGetFightingHero(side)
  1346. : nullptr;
  1347. switch(mode)
  1348. {
  1349. case ECastingMode::HERO_CASTING:
  1350. {
  1351. assert(castingHero);
  1352. if(!castingHero->canCastThisSpell(spell))
  1353. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  1354. if(castingHero->mana < battleGetSpellCost(spell, castingHero)) //not enough mana
  1355. return ESpellCastProblem::NOT_ENOUGH_MANA;
  1356. }
  1357. break;
  1358. }
  1359. if(!spell->combatSpell)
  1360. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1361. //TODO?
  1362. //if(NBonus::hasOfType(heroes[1-cside], Bonus::SPELL_IMMUNITY, spell->id)) //non - casting hero provides immunity for this spell
  1363. // return ESpellCastProblem::SECOND_HEROS_SPELL_IMMUNITY;
  1364. if(spell->isNegative())
  1365. {
  1366. bool allEnemiesImmune = true;
  1367. for(auto enemyStack : battleAliveStacks(!side))
  1368. {
  1369. if(!enemyStack->hasBonusOfType(Bonus::SPELL_IMMUNITY, spell->id))
  1370. {
  1371. allEnemiesImmune = false;
  1372. break;
  1373. }
  1374. }
  1375. if(allEnemiesImmune)
  1376. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1377. }
  1378. if(battleMaxSpellLevel() < spell->level) //effect like Recanter's Cloak or Orb of Inhibition
  1379. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  1380. //IDs of summon elemental spells (fire, earth, water, air)
  1381. int spellIDs[] = { SpellID::SUMMON_FIRE_ELEMENTAL, SpellID::SUMMON_EARTH_ELEMENTAL,
  1382. SpellID::SUMMON_WATER_ELEMENTAL, SpellID::SUMMON_AIR_ELEMENTAL };
  1383. //(fire, earth, water, air) elementals
  1384. int creIDs[] = {114, 113, 115, 112};
  1385. int arpos = vstd::find_pos(spellIDs, spell->id);
  1386. if(arpos < ARRAY_COUNT(spellIDs))
  1387. {
  1388. //check if there are summoned elementals of other type
  1389. for( const CStack * st : battleAliveStacks())
  1390. if(vstd::contains(st->state, EBattleStackState::SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
  1391. return ESpellCastProblem::ANOTHER_ELEMENTAL_SUMMONED;
  1392. }
  1393. //checking if there exists an appropriate target
  1394. switch(spell->getTargetType())
  1395. {
  1396. case CSpell::CREATURE:
  1397. case CSpell::CREATURE_EXPERT_MASSIVE:
  1398. if(mode == ECastingMode::HERO_CASTING)
  1399. {
  1400. const CGHeroInstance * caster = battleGetFightingHero(side);
  1401. bool targetExists = false;
  1402. for(const CStack * stack : battleAliveStacks())
  1403. {
  1404. switch (spell->positiveness)
  1405. {
  1406. case CSpell::POSITIVE:
  1407. if(stack->owner == caster->getOwner())
  1408. {
  1409. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1410. {
  1411. targetExists = true;
  1412. break;
  1413. }
  1414. }
  1415. break;
  1416. case CSpell::NEUTRAL:
  1417. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1418. {
  1419. targetExists = true;
  1420. break;
  1421. }
  1422. break;
  1423. case CSpell::NEGATIVE:
  1424. if(stack->owner != caster->getOwner())
  1425. {
  1426. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1427. {
  1428. targetExists = true;
  1429. break;
  1430. }
  1431. }
  1432. break;
  1433. }
  1434. }
  1435. if(!targetExists)
  1436. {
  1437. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1438. }
  1439. }
  1440. break;
  1441. case CSpell::OBSTACLE:
  1442. break;
  1443. }
  1444. return ESpellCastProblem::OK;
  1445. }
  1446. std::vector<BattleHex> CBattleInfoCallback::battleGetPossibleTargets(PlayerColor player, const CSpell *spell) const
  1447. {
  1448. std::vector<BattleHex> ret;
  1449. RETURN_IF_NOT_BATTLE(ret);
  1450. auto mode = ECastingMode::HERO_CASTING; //TODO get rid of this!
  1451. switch(spell->getTargetType())
  1452. {
  1453. case CSpell::CREATURE:
  1454. case CSpell::CREATURE_EXPERT_MASSIVE:
  1455. {
  1456. const CGHeroInstance * caster = battleGetFightingHero(playerToSide(player)); //TODO
  1457. for(const CStack * stack : battleAliveStacks())
  1458. {
  1459. switch (spell->positiveness)
  1460. {
  1461. case CSpell::POSITIVE:
  1462. if(stack->owner == caster->getOwner())
  1463. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1464. ret.push_back(stack->position);
  1465. break;
  1466. case CSpell::NEUTRAL:
  1467. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1468. ret.push_back(stack->position);
  1469. break;
  1470. case CSpell::NEGATIVE:
  1471. if(stack->owner != caster->getOwner())
  1472. if(battleIsImmune(caster, spell, mode, stack->position) == ESpellCastProblem::OK)
  1473. ret.push_back(stack->position);
  1474. break;
  1475. }
  1476. }
  1477. }
  1478. break;
  1479. default:
  1480. logGlobal->errorStream() << "FIXME " << __FUNCTION__ << " doesn't work with target type " << spell->getTargetType();
  1481. }
  1482. return ret;
  1483. }
  1484. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1485. {
  1486. RETURN_IF_NOT_BATTLE(-1);
  1487. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1488. ui32 ret = caster->getSpellCost(sp);
  1489. //checking for friendly stacks reducing cost of the spell and
  1490. //enemy stacks increasing it
  1491. si32 manaReduction = 0;
  1492. si32 manaIncrease = 0;
  1493. for(auto stack : battleAliveStacks())
  1494. {
  1495. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  1496. {
  1497. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1498. }
  1499. if( stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  1500. {
  1501. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1502. }
  1503. }
  1504. return ret - manaReduction + manaIncrease;
  1505. }
  1506. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpellHere( PlayerColor player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest ) const
  1507. {
  1508. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1509. ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
  1510. if(moreGeneralProblem != ESpellCastProblem::OK)
  1511. return moreGeneralProblem;
  1512. if(spell->getTargetType() == CSpell::OBSTACLE)
  1513. {
  1514. if(spell->id == SpellID::REMOVE_OBSTACLE)
  1515. {
  1516. if(auto obstacle = battleGetObstacleOnPos(dest, false))
  1517. {
  1518. switch (obstacle->obstacleType)
  1519. {
  1520. case CObstacleInstance::ABSOLUTE_OBSTACLE: //cliff-like obstacles cant be removed
  1521. case CObstacleInstance::MOAT:
  1522. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1523. case CObstacleInstance::USUAL:
  1524. return ESpellCastProblem::OK;
  1525. // //TODO FIRE_WALL only for ADVANCED level casters
  1526. // case CObstacleInstance::FIRE_WALL:
  1527. // return
  1528. // //TODO other magic obstacles for EXPERT
  1529. // case CObstacleInstance::QUICKSAND:
  1530. // case CObstacleInstance::LAND_MINE:
  1531. // case CObstacleInstance::FORCE_FIELD:
  1532. // return
  1533. default:
  1534. // assert(0);
  1535. return ESpellCastProblem::OK;
  1536. }
  1537. }
  1538. }
  1539. //isObstacleOnTile(dest)
  1540. //
  1541. //
  1542. //TODO
  1543. //assert that it's remove obstacle
  1544. //rules whether we can remove spell-created obstacle
  1545. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1546. }
  1547. //get dead stack if we cast resurrection or animate dead
  1548. const CStack *deadStack = getStackIf([dest](const CStack *s) { return !s->alive() && s->coversPos(dest); });
  1549. const CStack *aliveStack = getStackIf([dest](const CStack *s) { return s->alive() && s->coversPos(dest);});
  1550. if(spell->isRisingSpell())
  1551. {
  1552. if(!deadStack && !aliveStack)
  1553. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1554. if(spell->id == SpellID::ANIMATE_DEAD && deadStack && !deadStack->hasBonusOfType(Bonus::UNDEAD))
  1555. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1556. if(deadStack && deadStack->owner != player) //you can resurrect only your own stacks //FIXME: it includes alive stacks as well
  1557. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1558. }
  1559. else if(spell->getTargetType() == CSpell::CREATURE || spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  1560. {
  1561. if(!aliveStack)
  1562. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1563. if(spell->isNegative() && aliveStack->owner == player)
  1564. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1565. if(spell->isPositive() && aliveStack->owner != player)
  1566. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1567. }
  1568. if (mode == ECastingMode::HERO_CASTING)
  1569. return battleIsImmune(battleGetFightingHero(playerToSide(player)), spell, mode, dest);
  1570. else
  1571. return battleIsImmune(nullptr, spell, mode, dest);
  1572. }
  1573. ui32 CBattleInfoCallback::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  1574. {
  1575. ui32 ret = baseDamage;
  1576. //applying sorcery secondary skill
  1577. if(caster)
  1578. {
  1579. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  1580. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id.toEnum())) / 100.0;
  1581. if(sp->air)
  1582. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  1583. else if(sp->fire) //only one type of bonus for Magic Arrow
  1584. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  1585. else if(sp->water)
  1586. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  1587. else if(sp->earth)
  1588. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  1589. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  1590. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  1591. }
  1592. return ret;
  1593. }
  1594. ui32 CBattleInfoCallback::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  1595. {
  1596. ui32 ret = 0; //value to return
  1597. //check if spell really does damage - if not, return 0
  1598. if(!sp->isDamageSpell())
  1599. return 0;
  1600. ret = usedSpellPower * sp->power;
  1601. ret += sp->powers[spellSchoolLevel];
  1602. //affected creature-specific part
  1603. if(affectedCreature)
  1604. {
  1605. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  1606. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  1607. {
  1608. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  1609. ret /= 100;
  1610. }
  1611. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  1612. {
  1613. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  1614. ret /= 100;
  1615. }
  1616. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  1617. {
  1618. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  1619. ret /= 100;
  1620. }
  1621. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  1622. {
  1623. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  1624. ret /= 100;
  1625. }
  1626. //general spell dmg reduction
  1627. //FIXME?
  1628. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  1629. {
  1630. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  1631. ret /= 100;
  1632. }
  1633. //dmg increasing
  1634. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  1635. {
  1636. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id.toEnum());
  1637. ret /= 100;
  1638. }
  1639. }
  1640. ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
  1641. return ret;
  1642. }
  1643. std::set<const CStack*> CBattleInfoCallback::getAffectedCreatures(const CSpell * spell, int skillLevel, PlayerColor attackerOwner, BattleHex destinationTile)
  1644. {
  1645. std::set<const CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  1646. const ui8 attackerSide = playerToSide(attackerOwner) == 1;
  1647. const auto attackedHexes = spell->rangeInHexes(destinationTile, skillLevel, attackerSide);
  1648. const bool onlyAlive = spell->id != SpellID::RESURRECTION && spell->id != SpellID::ANIMATE_DEAD; //when casting resurrection or animate dead we should be allow to select dead stack
  1649. //fixme: what about other rising spells (Sacrifice) ?
  1650. if(spell->id == SpellID::DEATH_RIPPLE || spell->id == SpellID::DESTROY_UNDEAD || spell->id == SpellID::ARMAGEDDON)
  1651. {
  1652. for(const CStack *stack : battleGetAllStacks())
  1653. {
  1654. if((spell->id == SpellID::DEATH_RIPPLE && !stack->getCreature()->isUndead()) //death ripple
  1655. || (spell->id == SpellID::DESTROY_UNDEAD && stack->getCreature()->isUndead()) //destroy undead
  1656. || (spell->id == SpellID::ARMAGEDDON) //Armageddon
  1657. )
  1658. {
  1659. if(stack->isValidTarget())
  1660. attackedCres.insert(stack);
  1661. }
  1662. }
  1663. }
  1664. else if (spell->id == SpellID::CHAIN_LIGHTNING)
  1665. {
  1666. std::set<BattleHex> possibleHexes;
  1667. for (auto stack : battleGetAllStacks())
  1668. {
  1669. if (stack->isValidTarget())
  1670. {
  1671. for (auto hex : stack->getHexes())
  1672. {
  1673. possibleHexes.insert (hex);
  1674. }
  1675. }
  1676. }
  1677. int targetsOnLevel[4] = {4, 4, 5, 5};
  1678. BattleHex lightningHex = destinationTile;
  1679. for (int i = 0; i < targetsOnLevel[skillLevel]; ++i)
  1680. {
  1681. auto stack = battleGetStackByPos (lightningHex, true);
  1682. if (!stack)
  1683. break;
  1684. attackedCres.insert (stack);
  1685. for (auto hex : stack->getHexes())
  1686. {
  1687. possibleHexes.erase (hex); //can't hit same place twice
  1688. }
  1689. if (!possibleHexes.size()) //not enough targets
  1690. break;
  1691. lightningHex = BattleHex::getClosestTile (stack->attackerOwned, destinationTile, possibleHexes);
  1692. }
  1693. }
  1694. else if (spell->range[skillLevel].size() > 1) //custom many-hex range
  1695. {
  1696. for(BattleHex hex : attackedHexes)
  1697. {
  1698. if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
  1699. {
  1700. if (spell->id == 76) //Death Cloud //TODO: fireball and fire immunity
  1701. {
  1702. if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
  1703. {
  1704. attackedCres.insert(st);
  1705. }
  1706. }
  1707. else
  1708. attackedCres.insert(st);
  1709. }
  1710. }
  1711. }
  1712. else if(spell->getTargetType() == CSpell::CREATURE_EXPERT_MASSIVE)
  1713. {
  1714. if(skillLevel < 3) /*not expert */
  1715. {
  1716. const CStack * st = battleGetStackByPos(destinationTile, onlyAlive);
  1717. if(st)
  1718. attackedCres.insert(st);
  1719. }
  1720. else
  1721. {
  1722. for (auto stack : battleGetAllStacks())
  1723. {
  1724. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  1725. if((!spell->isNegative() && stack->owner == attackerOwner)
  1726. ||(!spell->isPositive() && stack->owner != attackerOwner )
  1727. )
  1728. {
  1729. if(stack->isValidTarget(!onlyAlive))
  1730. attackedCres.insert(stack);
  1731. }
  1732. }
  1733. } //if(caster->getSpellSchoolLevel(s) < 3)
  1734. }
  1735. else if(spell->getTargetType() == CSpell::CREATURE)
  1736. {
  1737. if(const CStack * st = battleGetStackByPos(destinationTile, onlyAlive))
  1738. attackedCres.insert(st);
  1739. }
  1740. else //custom range from attackedHexes
  1741. {
  1742. for(BattleHex hex : attackedHexes)
  1743. {
  1744. if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
  1745. attackedCres.insert(st);
  1746. }
  1747. }
  1748. return attackedCres;
  1749. }
  1750. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1751. {
  1752. RETURN_IF_NOT_BATTLE(nullptr);
  1753. auto stacks = battleGetAllStacks();
  1754. auto stackItr = range::find_if(stacks, pred);
  1755. return stackItr == stacks.end()
  1756. ? nullptr
  1757. : *stackItr;
  1758. }
  1759. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1760. {
  1761. RETURN_IF_NOT_BATTLE(false);
  1762. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1763. return false;
  1764. for(const CStack * s : batteAdjacentCreatures(stack))
  1765. {
  1766. if (s->owner != stack->owner) //blocked by enemy stack
  1767. return true;
  1768. }
  1769. return false;
  1770. }
  1771. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1772. {
  1773. std::set<const CStack*> stacks;
  1774. RETURN_IF_NOT_BATTLE(stacks);
  1775. for (BattleHex hex : stack->getSurroundingHexes())
  1776. if(const CStack *neighbour = battleGetStackByPos(hex, true))
  1777. stacks.insert(neighbour);
  1778. return stacks;
  1779. }
  1780. SpellID CBattleInfoCallback::getRandomBeneficialSpell(const CStack * subject) const
  1781. {
  1782. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1783. std::vector<SpellID> possibleSpells;
  1784. for(const CSpell *spell : VLC->spellh->spells)
  1785. {
  1786. if (spell->isPositive()) //only positive
  1787. {
  1788. if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, spell->id)
  1789. || battleCanCastThisSpellHere(subject->owner, spell, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1790. continue;
  1791. switch (spell->id)
  1792. {
  1793. case SpellID::SHIELD:
  1794. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1795. {
  1796. auto walker = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
  1797. {
  1798. return stack->owner != subject->owner && !stack->shots;
  1799. });
  1800. if (!walker)
  1801. continue;
  1802. }
  1803. break;
  1804. case SpellID::AIR_SHIELD: //only against active shooters
  1805. {
  1806. auto shooter = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
  1807. {
  1808. return stack->owner != subject->owner && stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
  1809. });
  1810. if (!shooter)
  1811. continue;
  1812. }
  1813. break;
  1814. case SpellID::ANTI_MAGIC:
  1815. case SpellID::MAGIC_MIRROR:
  1816. {
  1817. if (!battleHasHero(subject->attackerOwned)) //only if there is enemy hero
  1818. continue;
  1819. }
  1820. break;
  1821. case SpellID::CURE: //only damaged units - what about affected by curse?
  1822. {
  1823. if (subject->firstHPleft >= subject->MaxHealth())
  1824. continue;
  1825. }
  1826. break;
  1827. case SpellID::BLOODLUST:
  1828. {
  1829. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1830. continue;
  1831. }
  1832. break;
  1833. case SpellID::PRECISION:
  1834. {
  1835. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1836. continue;
  1837. }
  1838. break;
  1839. case SpellID::SLAYER://only if monsters are present
  1840. {
  1841. auto kingMonster = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
  1842. {
  1843. const auto isKing = Selector::type(Bonus::KING1)
  1844. .Or(Selector::type(Bonus::KING2))
  1845. .Or(Selector::type(Bonus::KING3));
  1846. return stack->owner != subject->owner && stack->hasBonus(isKing);
  1847. });
  1848. if (!kingMonster)
  1849. continue;
  1850. }
  1851. break;
  1852. case SpellID::CLONE: //not allowed
  1853. continue;
  1854. break;
  1855. }
  1856. possibleSpells.push_back(spell->id);
  1857. }
  1858. }
  1859. if (possibleSpells.size())
  1860. return possibleSpells[rand() % possibleSpells.size()];
  1861. else
  1862. return SpellID::NONE;
  1863. }
  1864. SpellID CBattleInfoCallback::getRandomCastedSpell(const CStack * caster) const
  1865. {
  1866. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1867. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1868. if (!bl->size())
  1869. return SpellID::NONE;
  1870. int totalWeight = 0;
  1871. for(Bonus * b : *bl)
  1872. {
  1873. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1874. }
  1875. int randomPos = rand() % totalWeight;
  1876. for(Bonus * b : *bl)
  1877. {
  1878. randomPos -= std::max(b->additionalInfo, 1);
  1879. if(randomPos < 0)
  1880. {
  1881. return SpellID(b->subtype);
  1882. }
  1883. }
  1884. return SpellID::NONE;
  1885. }
  1886. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1887. {
  1888. RETURN_IF_NOT_BATTLE(-3);
  1889. if(!battleCanSurrender(Player))
  1890. return -1;
  1891. int ret = 0;
  1892. double discount = 0;
  1893. for(const CStack *s : battleAliveStacks(playerToSide(Player)))
  1894. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1895. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  1896. if(const CGHeroInstance *h = battleGetFightingHero(playerToSide(Player)))
  1897. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1898. ret *= (100.0 - discount) / 100.0;
  1899. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1900. return ret;
  1901. }
  1902. si8 CBattleInfoCallback::battleMaxSpellLevel() const
  1903. {
  1904. const CBonusSystemNode *node = nullptr;
  1905. if(const CGHeroInstance *h = battleGetFightingHero(battleGetMySide()))
  1906. node = h;
  1907. //TODO else use battle node
  1908. if(!node)
  1909. return GameConstants::SPELL_LEVELS;
  1910. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1911. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1912. if(b->size())
  1913. return b->totalValue();
  1914. return GameConstants::SPELL_LEVELS;
  1915. }
  1916. bool AccessibilityInfo::accessible(BattleHex tile, const CStack *stack) const
  1917. {
  1918. return accessible(tile, stack->doubleWide(), stack->attackerOwned);
  1919. }
  1920. bool AccessibilityInfo::accessible(BattleHex tile, bool doubleWide, bool attackerOwned) const
  1921. {
  1922. // All hexes that stack would cover if standing on tile have to be accessible.
  1923. for(auto hex : CStack::getHexes(tile, doubleWide, attackerOwned))
  1924. {
  1925. // If the hex is out of range then the tile isn't accessible
  1926. if(!hex.isValid())
  1927. return false;
  1928. // If we're no defender which step on gate and the hex isn't accessible, then the tile
  1929. // isn't accessible
  1930. else if(at(hex) != EAccessibility::ACCESSIBLE &&
  1931. !(at(hex) == EAccessibility::GATE && !attackerOwned))
  1932. return false;
  1933. }
  1934. return true;
  1935. }
  1936. bool AccessibilityInfo::occupiable(const CStack *stack, BattleHex tile) const
  1937. {
  1938. //obviously, we can occupy tile by standing on it
  1939. if(accessible(tile, stack))
  1940. return true;
  1941. if(stack->doubleWide())
  1942. {
  1943. //Check the tile next to -> if stack stands there, it'll also occupy considered hex
  1944. const BattleHex anotherTile = tile + (stack->attackerOwned ? BattleHex::RIGHT : BattleHex::LEFT);
  1945. if(accessible(anotherTile, stack))
  1946. return true;
  1947. }
  1948. return false;
  1949. }
  1950. ReachabilityInfo::Parameters::Parameters()
  1951. {
  1952. stack = nullptr;
  1953. perspective = BattlePerspective::ALL_KNOWING;
  1954. attackerOwned = doubleWide = flying = false;
  1955. }
  1956. ReachabilityInfo::Parameters::Parameters(const CStack *Stack)
  1957. {
  1958. stack = Stack;
  1959. perspective = (BattlePerspective::BattlePerspective)(!Stack->attackerOwned);
  1960. startPosition = Stack->position;
  1961. doubleWide = stack->doubleWide();
  1962. attackerOwned = stack->attackerOwned;
  1963. flying = stack->hasBonusOfType(Bonus::FLYING);
  1964. knownAccessible = stack->getHexes();
  1965. }
  1966. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell) const
  1967. {
  1968. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1969. ASSERT_IF_CALLED_WITH_PLAYER
  1970. return CBattleInfoCallback::battleCanCastThisSpell(*player, spell, ECastingMode::HERO_CASTING);
  1971. }
  1972. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell, BattleHex destination) const
  1973. {
  1974. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1975. ASSERT_IF_CALLED_WITH_PLAYER
  1976. return battleCanCastThisSpellHere(*player, spell, ECastingMode::HERO_CASTING, destination);
  1977. }
  1978. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCreatureCastThisSpell(const CSpell * spell, BattleHex destination) const
  1979. {
  1980. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1981. ASSERT_IF_CALLED_WITH_PLAYER
  1982. return battleCanCastThisSpellHere(*player, spell, ECastingMode::CREATURE_ACTIVE_CASTING, destination);
  1983. }
  1984. bool CPlayerBattleCallback::battleCanFlee() const
  1985. {
  1986. RETURN_IF_NOT_BATTLE(false);
  1987. ASSERT_IF_CALLED_WITH_PLAYER
  1988. return CBattleInfoEssentials::battleCanFlee(*player);
  1989. }
  1990. TStacks CPlayerBattleCallback::battleGetStacks(EStackOwnership whose /*= MINE_AND_ENEMY*/, bool onlyAlive /*= true*/) const
  1991. {
  1992. TStacks ret;
  1993. RETURN_IF_NOT_BATTLE(ret);
  1994. if(whose != MINE_AND_ENEMY)
  1995. {
  1996. ASSERT_IF_CALLED_WITH_PLAYER
  1997. }
  1998. vstd::copy_if(battleGetAllStacks(), std::back_inserter(ret), [=](const CStack *s) -> bool
  1999. {
  2000. const bool ownerMatches = (whose == MINE_AND_ENEMY)
  2001. || (whose == ONLY_MINE && s->owner == player)
  2002. || (whose == ONLY_ENEMY && s->owner != player);
  2003. const bool alivenessMatches = s->alive() || !onlyAlive;
  2004. return ownerMatches && alivenessMatches;
  2005. });
  2006. return ret;
  2007. }
  2008. int CPlayerBattleCallback::battleGetSurrenderCost() const
  2009. {
  2010. RETURN_IF_NOT_BATTLE(-3)
  2011. ASSERT_IF_CALLED_WITH_PLAYER
  2012. return CBattleInfoCallback::battleGetSurrenderCost(*player);
  2013. }
  2014. bool CPlayerBattleCallback::battleCanCastSpell(ESpellCastProblem::ESpellCastProblem *outProblem /*= nullptr*/) const
  2015. {
  2016. RETURN_IF_NOT_BATTLE(false);
  2017. ASSERT_IF_CALLED_WITH_PLAYER
  2018. auto problem = CBattleInfoCallback::battleCanCastSpell(*player, ECastingMode::HERO_CASTING);
  2019. if(outProblem)
  2020. *outProblem = problem;
  2021. return problem == ESpellCastProblem::OK;
  2022. }
  2023. const CGHeroInstance * CPlayerBattleCallback::battleGetMyHero() const
  2024. {
  2025. return CBattleInfoEssentials::battleGetFightingHero(battleGetMySide());
  2026. }
  2027. InfoAboutHero CPlayerBattleCallback::battleGetEnemyHero() const
  2028. {
  2029. return battleGetHeroInfo(!battleGetMySide());
  2030. }
  2031. BattleAttackInfo::BattleAttackInfo(const CStack *Attacker, const CStack *Defender, bool Shooting)
  2032. {
  2033. attacker = Attacker;
  2034. defender = Defender;
  2035. attackerBonuses = Attacker;
  2036. defenderBonuses = Defender;
  2037. attackerPosition = Attacker->position;
  2038. defenderPosition = Defender->position;
  2039. attackerCount = Attacker->count;
  2040. defenderCount = Defender->count;
  2041. shooting = Shooting;
  2042. chargedFields = 0;
  2043. luckyHit = false;
  2044. deathBlow = false;
  2045. ballistaDoubleDamage = false;
  2046. }
  2047. BattleAttackInfo BattleAttackInfo::reverse() const
  2048. {
  2049. BattleAttackInfo ret = *this;
  2050. std::swap(ret.attacker, ret.defender);
  2051. std::swap(ret.attackerBonuses, ret.defenderBonuses);
  2052. std::swap(ret.attackerPosition, ret.defenderPosition);
  2053. std::swap(ret.attackerCount, ret.defenderCount);
  2054. ret.shooting = false;
  2055. ret.chargedFields = 0;
  2056. ret.luckyHit = ret.ballistaDoubleDamage = ret.deathBlow = false;
  2057. return ret;
  2058. }