CBattleCallback.cpp 60 KB

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