CBattleCallback.cpp 61 KB

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