CBattleInfoCallback.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286
  1. /*
  2. * CBattleInfoCallback.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CBattleInfoCallback.h"
  12. #include <vcmi/scripting/Service.h>
  13. #include <vstd/RNG.h>
  14. #include "../CStack.h"
  15. #include "BattleInfo.h"
  16. #include "CObstacleInstance.h"
  17. #include "DamageCalculator.h"
  18. #include "IGameSettings.h"
  19. #include "PossiblePlayerBattleAction.h"
  20. #include "../bonuses/BonusParameters.h"
  21. #include "../entities/building/TownFortifications.h"
  22. #include "../GameLibrary.h"
  23. #include "../spells/ObstacleCasterProxy.h"
  24. #include "../spells/ISpellMechanics.h"
  25. #include "../spells/Problem.h"
  26. #include "../spells/CSpellHandler.h"
  27. #include "../mapObjects/CGTownInstance.h"
  28. #include "../networkPacks/PacksForClientBattle.h"
  29. #include "../BattleFieldHandler.h"
  30. #include "../Rect.h"
  31. #include "../lib/spells/effects/UnitEffect.h"
  32. VCMI_LIB_NAMESPACE_BEGIN
  33. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  34. {
  35. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 96, 112, 130, 147, 165, 182};
  36. return lineToHex[line];
  37. }
  38. static bool sameSideOfWall(const BattleHex & pos1, const BattleHex & pos2)
  39. {
  40. const bool stackLeft = pos1 < lineToWallHex(pos1.getY());
  41. const bool destLeft = pos2 < lineToWallHex(pos2.getY());
  42. return stackLeft == destLeft;
  43. }
  44. // parts of wall
  45. static const std::pair<int, EWallPart> wallParts[] =
  46. {
  47. std::make_pair(50, EWallPart::KEEP),
  48. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  49. std::make_pair(182, EWallPart::BOTTOM_WALL),
  50. std::make_pair(130, EWallPart::BELOW_GATE),
  51. std::make_pair(78, EWallPart::OVER_GATE),
  52. std::make_pair(29, EWallPart::UPPER_WALL),
  53. std::make_pair(12, EWallPart::UPPER_TOWER),
  54. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  55. std::make_pair(96, EWallPart::GATE),
  56. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  57. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  58. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  59. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  60. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  61. };
  62. static EWallPart hexToWallPart(const BattleHex & hex)
  63. {
  64. si16 hexValue = hex.toInt();
  65. for(const auto & elem : wallParts)
  66. {
  67. if(elem.first == hexValue)
  68. return elem.second;
  69. }
  70. return EWallPart::INVALID; //not found!
  71. }
  72. static BattleHex WallPartToHex(EWallPart part)
  73. {
  74. for(const auto & elem : wallParts)
  75. {
  76. if(elem.second == part)
  77. return elem.first;
  78. }
  79. return BattleHex::INVALID; //not found!
  80. }
  81. ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  82. {
  83. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  84. if(caster == nullptr)
  85. {
  86. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  87. return ESpellCastProblem::INVALID;
  88. }
  89. const PlayerColor player = caster->getCasterOwner();
  90. const auto side = playerToSide(player);
  91. if(side == BattleSide::NONE)
  92. return ESpellCastProblem::INVALID;
  93. if(!battleDoWeKnowAbout(side))
  94. {
  95. logGlobal->warn("You can't check if enemy can cast given spell!");
  96. return ESpellCastProblem::INVALID;
  97. }
  98. if(battleTacticDist())
  99. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  100. switch(mode)
  101. {
  102. case spells::Mode::HERO:
  103. {
  104. const auto * hero = caster->getHeroCaster();
  105. if(!hero)
  106. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  107. if(!hero->hasSpellbook())
  108. return ESpellCastProblem::NO_SPELLBOOK;
  109. if(hero->hasBonusOfType(BonusType::BLOCK_ALL_MAGIC))
  110. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  111. if(battleCastSpells(side) >= hero->valOfBonuses(BonusType::HERO_SPELL_CASTS_PER_COMBAT_TURN))
  112. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  113. }
  114. break;
  115. default:
  116. break;
  117. }
  118. return ESpellCastProblem::OK;
  119. }
  120. std::pair< BattleHexArray, int > CBattleInfoCallback::getPath(const BattleHex & start, const BattleHex & dest, const battle::Unit * stack) const
  121. {
  122. auto reachability = getReachability(stack);
  123. if(reachability.predecessors[dest.toInt()] == -1) //cannot reach destination
  124. {
  125. return std::make_pair(BattleHexArray(), 0);
  126. }
  127. //making the Path
  128. BattleHexArray path;
  129. BattleHex curElem = dest;
  130. while(curElem != start)
  131. {
  132. path.insert(curElem);
  133. curElem = reachability.predecessors[curElem.toInt()];
  134. }
  135. return std::make_pair(path, reachability.distances[dest.toInt()]);
  136. }
  137. bool CBattleInfoCallback::battleIsInsideWalls(const BattleHex & from) const
  138. {
  139. BattleHex wallPos = lineToWallHex(from.getY());
  140. if (from < wallPos)
  141. return false;
  142. if (wallPos < from)
  143. return true;
  144. // edge case - this is the wall. (or drawbridge)
  145. // since this method is used exclusively to determine behavior of defenders,
  146. // consider it inside walls, unless this is intact drawbridge - to prevent defenders standing on it and opening the gates
  147. if (from == BattleHex::GATE_INNER)
  148. return battleGetGateState() == EGateState::DESTROYED;
  149. return true;
  150. }
  151. bool CBattleInfoCallback::battleHasPenaltyOnLine(const BattleHex & from, const BattleHex & dest, bool checkWall, bool checkMoat) const
  152. {
  153. if (!from.isAvailable() || !dest.isAvailable())
  154. throw std::runtime_error("Invalid hex (" + std::to_string(from.toInt()) + " and " + std::to_string(dest.toInt()) + ") received in battleHasPenaltyOnLine!" );
  155. auto isTileBlocked = [&](const BattleHex & tile)
  156. {
  157. EWallPart wallPart = battleHexToWallPart(tile);
  158. if (wallPart == EWallPart::INVALID)
  159. return false; // there is no wall here
  160. if (wallPart == EWallPart::INDESTRUCTIBLE_PART_OF_GATE)
  161. return false; // does not blocks ranged attacks
  162. if (wallPart == EWallPart::INDESTRUCTIBLE_PART)
  163. return true; // always blocks ranged attacks
  164. return isWallPartAttackable(wallPart);
  165. };
  166. // Count wall penalty requirement by shortest path, not by arbitrary line, to avoid various OH3 bugs
  167. auto getShortestPath = [](const BattleHex & from, const BattleHex & dest) -> BattleHexArray
  168. {
  169. //Out early
  170. if(from == dest)
  171. return {};
  172. BattleHexArray ret;
  173. auto next = from;
  174. //Not a real direction, only to indicate to which side we should search closest tile
  175. auto direction = from.getX() > dest.getX() ? BattleSide::DEFENDER : BattleSide::ATTACKER;
  176. while (next != dest)
  177. {
  178. next = BattleHex::getClosestTile(direction, dest, next.getNeighbouringTiles());
  179. ret.insert(next);
  180. }
  181. assert(!ret.empty());
  182. ret.pop_back(); //Remove destination hex
  183. return ret;
  184. };
  185. RETURN_IF_NOT_BATTLE(false);
  186. auto checkNeeded = !sameSideOfWall(from, dest);
  187. bool pathHasWall = false;
  188. bool pathHasMoat = false;
  189. for(const auto & hex : getShortestPath(from, dest))
  190. {
  191. pathHasWall |= isTileBlocked(hex);
  192. if(!checkMoat)
  193. continue;
  194. auto obstacles = battleGetAllObstaclesOnPos(hex, false);
  195. if(hex.toInt() != BattleHex::GATE_BRIDGE || (battleIsGatePassable()))
  196. for(const auto & obst : obstacles)
  197. if(obst->obstacleType == CObstacleInstance::MOAT)
  198. pathHasMoat |= true;
  199. }
  200. return checkNeeded && ( (checkWall && pathHasWall) || (checkMoat && pathHasMoat) );
  201. }
  202. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, const BattleHex & shooterPosition, const BattleHex & destHex) const
  203. {
  204. RETURN_IF_NOT_BATTLE(false);
  205. if(battleGetFortifications().wallsHealth == 0)
  206. return false;
  207. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  208. static const auto selectorNoWallPenalty = Selector::type()(BonusType::NO_WALL_PENALTY);
  209. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  210. return false;
  211. const auto shooterOutsideWalls = shooterPosition < lineToWallHex(shooterPosition.getY());
  212. return shooterOutsideWalls && battleHasPenaltyOnLine(shooterPosition, destHex, true, false);
  213. }
  214. std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsForStack(const CStack * stack, const BattleClientInterfaceData & data)
  215. {
  216. RETURN_IF_NOT_BATTLE(std::vector<PossiblePlayerBattleAction>());
  217. std::vector<PossiblePlayerBattleAction> allowedActionList;
  218. if(data.tacticsMode) //would "if(battleGetTacticDist() > 0)" work?
  219. {
  220. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_TACTICS);
  221. allowedActionList.push_back(PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK);
  222. }
  223. else
  224. {
  225. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  226. {
  227. if(stack->hasBonusOfType(BonusType::SPELLCASTER))
  228. {
  229. for(const auto & spellID : data.creatureSpellsToCast)
  230. {
  231. const CSpell *spell = spellID.toSpell();
  232. PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
  233. allowedActionList.push_back(act);
  234. }
  235. }
  236. if(stack->hasBonusOfType(BonusType::RANDOM_SPELLCASTER))
  237. allowedActionList.push_back(PossiblePlayerBattleAction::RANDOM_GENIE_SPELL);
  238. }
  239. if(stack->canShoot())
  240. allowedActionList.push_back(PossiblePlayerBattleAction::SHOOT);
  241. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE))
  242. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK_AND_RETURN);
  243. if (stack->isMeleeAttacker()) //not all stacks can actually attack or walk and attack, check this elsewhere
  244. {
  245. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK);
  246. allowedActionList.push_back(PossiblePlayerBattleAction::WALK_AND_ATTACK);
  247. }
  248. if(stack->canMove() && stack->getMovementRange(0)) //probably no reason to try move war machines or bound stacks
  249. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_STACK);
  250. const auto * siegedTown = battleGetDefendedTown();
  251. if(siegedTown && siegedTown->fortificationsLevel().wallsHealth > 0 && stack->hasBonusOfType(BonusType::CATAPULT)) //TODO: check shots
  252. allowedActionList.push_back(PossiblePlayerBattleAction::CATAPULT);
  253. if(stack->hasBonusOfType(BonusType::HEALER))
  254. allowedActionList.push_back(PossiblePlayerBattleAction::HEAL);
  255. if(stack->hasBonusOfType(BonusType::ADJACENT_SPELLCASTER))
  256. {
  257. SpellID spellID = stack->getBonus(Selector::type()(BonusType::ADJACENT_SPELLCASTER))->subtype.as<SpellID>();
  258. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  259. allowedActionList.push_back(PossiblePlayerBattleAction(PossiblePlayerBattleAction::WALK_AND_SPELLCAST, spellID));
  260. }
  261. }
  262. return allowedActionList;
  263. }
  264. PossiblePlayerBattleAction CBattleInfoCallback::getCasterAction(const CSpell * spell, const spells::Caster * caster, spells::Mode mode) const
  265. {
  266. RETURN_IF_NOT_BATTLE(PossiblePlayerBattleAction::INVALID);
  267. auto spellSelMode = PossiblePlayerBattleAction::ANY_LOCATION;
  268. const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell), mode);
  269. if(ti.massive || ti.type == spells::AimType::NO_TARGET)
  270. spellSelMode = PossiblePlayerBattleAction::NO_LOCATION;
  271. else if(ti.type == spells::AimType::LOCATION && ti.clearAffected)
  272. spellSelMode = PossiblePlayerBattleAction::FREE_LOCATION;
  273. else if(ti.type == spells::AimType::CREATURE)
  274. spellSelMode = PossiblePlayerBattleAction::AIMED_SPELL_CREATURE;
  275. else if(ti.type == spells::AimType::OBSTACLE)
  276. spellSelMode = PossiblePlayerBattleAction::OBSTACLE;
  277. return PossiblePlayerBattleAction(spellSelMode, spell->id);
  278. }
  279. BattleHexArray CBattleInfoCallback::battleGetAttackedHexes(const battle::Unit * attacker, const BattleHex & destinationTile, const BattleHex & attackerPos) const
  280. {
  281. BattleHexArray attackedHexes;
  282. RETURN_IF_NOT_BATTLE(attackedHexes);
  283. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  284. for (const BattleHex & tile : at.hostileCreaturePositions)
  285. {
  286. const auto * st = battleGetUnitByPos(tile, true);
  287. if(st && battleGetOwner(st) != battleGetOwner(attacker) && !st->isInvincible()) //only hostile stacks - does it work well with Berserk?
  288. {
  289. attackedHexes.insert(tile);
  290. }
  291. }
  292. for (const BattleHex & tile : at.friendlyCreaturePositions)
  293. {
  294. const auto * st = battleGetUnitByPos(tile, true);
  295. if(st && !st->isInvincible()) //friendly stacks can also be damaged by Dragon Breath
  296. {
  297. attackedHexes.insert(tile);
  298. }
  299. }
  300. return attackedHexes;
  301. }
  302. const CStack* CBattleInfoCallback::battleGetStackByPos(const BattleHex & pos, bool onlyAlive) const
  303. {
  304. RETURN_IF_NOT_BATTLE(nullptr);
  305. for(const auto * s : battleGetAllStacks(true))
  306. if(s->getHexes().contains(pos) && (!onlyAlive || s->alive()))
  307. return s;
  308. return nullptr;
  309. }
  310. const battle::Unit * CBattleInfoCallback::battleGetUnitByPos(const BattleHex & pos, bool onlyAlive) const
  311. {
  312. RETURN_IF_NOT_BATTLE(nullptr);
  313. auto ret = battleGetUnitsIf([=](const battle::Unit * unit)
  314. {
  315. return !unit->isGhost()
  316. && unit->coversPos(pos)
  317. && (!onlyAlive || unit->alive());
  318. });
  319. if(!ret.empty())
  320. return ret.front();
  321. else
  322. return nullptr;
  323. }
  324. battle::Units CBattleInfoCallback::battleAliveUnits() const
  325. {
  326. return battleGetUnitsIf([](const battle::Unit * unit)
  327. {
  328. return unit->isValidTarget(false);
  329. });
  330. }
  331. battle::Units CBattleInfoCallback::battleAliveUnits(BattleSide side) const
  332. {
  333. return battleGetUnitsIf([=](const battle::Unit * unit)
  334. {
  335. return unit->isValidTarget(false) && unit->unitSide() == side;
  336. });
  337. }
  338. using namespace battle;
  339. static const battle::Unit * takeOneUnit(battle::Units & allUnits, const int turn, BattleSide & sideThatLastMoved, int phase)
  340. {
  341. const battle::Unit * returnedUnit = nullptr;
  342. size_t currentUnitIndex = 0;
  343. for(size_t i = 0; i < allUnits.size(); i++)
  344. {
  345. int32_t currentUnitInitiative = -1;
  346. int32_t returnedUnitInitiative = -1;
  347. if(returnedUnit)
  348. returnedUnitInitiative = returnedUnit->getInitiative(turn);
  349. if(!allUnits[i])
  350. continue;
  351. auto currentUnit = allUnits[i];
  352. currentUnitInitiative = currentUnit->getInitiative(turn);
  353. switch(phase)
  354. {
  355. case BattlePhases::NORMAL: // Faster first, attacker priority, higher slot first
  356. if(returnedUnit == nullptr || currentUnitInitiative > returnedUnitInitiative)
  357. {
  358. returnedUnit = currentUnit;
  359. currentUnitIndex = i;
  360. }
  361. else if(currentUnitInitiative == returnedUnitInitiative)
  362. {
  363. if(sideThatLastMoved == BattleSide::NONE && turn <= 0 && currentUnit->unitSide() == BattleSide::ATTACKER
  364. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Turn 0 attacker priority
  365. {
  366. returnedUnit = currentUnit;
  367. currentUnitIndex = i;
  368. }
  369. else if(sideThatLastMoved != BattleSide::NONE && currentUnit->unitSide() != sideThatLastMoved
  370. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  371. {
  372. returnedUnit = currentUnit;
  373. currentUnitIndex = i;
  374. }
  375. }
  376. break;
  377. case BattlePhases::WAIT_MORALE: // Slower first, higher slot first
  378. case BattlePhases::WAIT:
  379. if(returnedUnit == nullptr || currentUnitInitiative < returnedUnitInitiative)
  380. {
  381. returnedUnit = currentUnit;
  382. currentUnitIndex = i;
  383. }
  384. else if(currentUnitInitiative == returnedUnitInitiative && sideThatLastMoved != BattleSide::NONE && currentUnit->unitSide() != sideThatLastMoved
  385. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  386. {
  387. returnedUnit = currentUnit;
  388. currentUnitIndex = i;
  389. }
  390. break;
  391. default:
  392. break;
  393. }
  394. }
  395. if(!returnedUnit)
  396. return nullptr;
  397. allUnits[currentUnitIndex] = nullptr;
  398. return returnedUnit;
  399. }
  400. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & turns, const size_t maxUnits, const int maxTurns, const int turn, BattleSide sideThatLastMoved) const
  401. {
  402. RETURN_IF_NOT_BATTLE();
  403. if(maxUnits == 0 && maxTurns == 0)
  404. {
  405. logGlobal->error("Attempt to get infinite battle queue");
  406. return;
  407. }
  408. auto actualTurn = turn > 0 ? turn : 0;
  409. auto turnsIsFull = [&]() -> bool
  410. {
  411. if(maxUnits == 0)
  412. return false;//no limit
  413. size_t turnsSize = 0;
  414. for(const auto & oneTurn : turns)
  415. turnsSize += oneTurn.size();
  416. return turnsSize >= maxUnits;
  417. };
  418. turns.emplace_back();
  419. // We'll split creatures with remaining movement to 4 buckets (SIEGE, NORMAL, WAIT_MORALE, WAIT)
  420. std::array<battle::Units, BattlePhases::NUMBER_OF_PHASES> phases; // Access using BattlePhases enum
  421. const battle::Unit * activeUnit = battleActiveUnit();
  422. if(activeUnit)
  423. {
  424. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  425. if(turn == 0 && activeUnit->willMove())
  426. {
  427. turns.back().push_back(activeUnit);
  428. if(turnsIsFull())
  429. return;
  430. }
  431. //its first or current turn, turn priority for active stack side
  432. //TODO: what if active stack mind-controlled?
  433. if(turn <= 0 && sideThatLastMoved == BattleSide::NONE)
  434. sideThatLastMoved = activeUnit->unitSide();
  435. }
  436. auto allUnits = battleGetUnitsIf([](const battle::Unit * unit)
  437. {
  438. return !unit->isGhost();
  439. });
  440. // If no unit will be EVER! able to move, battle is over.
  441. if(!vstd::contains_if(allUnits, [](const battle::Unit * unit) { return unit->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  442. {
  443. turns.clear();
  444. return;
  445. }
  446. for(const auto * unit : allUnits)
  447. {
  448. if((actualTurn == 0 && !unit->willMove()) //we are considering current round and unit won't move
  449. || (actualTurn > 0 && !unit->canMove(turn)) //unit won't be able to move in later rounds
  450. || (actualTurn == 0 && unit == activeUnit && !turns.at(0).empty() && unit == turns.front().front())) //it's active unit already added at the beginning of queue
  451. {
  452. continue;
  453. }
  454. int unitPhase = unit->battleQueuePhase(turn);
  455. phases[unitPhase].push_back(unit);
  456. }
  457. boost::sort(phases[BattlePhases::SIEGE], CMP_stack(BattlePhases::SIEGE, actualTurn, sideThatLastMoved));
  458. std::copy(phases[BattlePhases::SIEGE].begin(), phases[BattlePhases::SIEGE].end(), std::back_inserter(turns.back()));
  459. if(turnsIsFull())
  460. return;
  461. for(uint8_t phase = BattlePhases::NORMAL; phase < BattlePhases::NUMBER_OF_PHASES; phase++)
  462. boost::sort(phases[phase], CMP_stack(phase, actualTurn, sideThatLastMoved));
  463. uint8_t phase = BattlePhases::NORMAL;
  464. while(!turnsIsFull() && phase < BattlePhases::NUMBER_OF_PHASES)
  465. {
  466. const battle::Unit * currentUnit = nullptr;
  467. if(phases[phase].empty())
  468. phase++;
  469. else
  470. {
  471. currentUnit = takeOneUnit(phases[phase], actualTurn, sideThatLastMoved, phase);
  472. if(!currentUnit)
  473. {
  474. phase++;
  475. }
  476. else
  477. {
  478. turns.back().push_back(currentUnit);
  479. sideThatLastMoved = currentUnit->unitSide();
  480. }
  481. }
  482. }
  483. if(sideThatLastMoved == BattleSide::NONE)
  484. sideThatLastMoved = BattleSide::ATTACKER;
  485. if(!turnsIsFull() && (maxTurns == 0 || turns.size() < maxTurns))
  486. battleGetTurnOrder(turns, maxUnits, maxTurns, actualTurn + 1, sideThatLastMoved);
  487. }
  488. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange) const
  489. {
  490. RETURN_IF_NOT_BATTLE(BattleHexArray());
  491. if(!unit->getPosition().isValid()) //turrets
  492. return BattleHexArray();
  493. auto reachability = getReachability(unit);
  494. return battleGetAvailableHexes(reachability, unit, obtainMovementRange);
  495. }
  496. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit, bool obtainMovementRange) const
  497. {
  498. BattleHexArray ret;
  499. RETURN_IF_NOT_BATTLE(ret);
  500. if(!unit->getPosition().isValid()) //turrets
  501. return ret;
  502. auto unitSpeed = unit->getMovementRange(0);
  503. const bool tacticsPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  504. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  505. {
  506. // If obstacles or other stacks makes movement impossible, it can't be helped.
  507. if(!cache.isReachable(i))
  508. continue;
  509. if(tacticsPhase && !obtainMovementRange) // if obtainMovementRange requested do not return tactics range
  510. {
  511. // Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  512. if(!isInTacticRange(i))
  513. continue;
  514. }
  515. else
  516. {
  517. // Not tactics phase -> destination must be reachable and within unit range.
  518. if(cache.distances[i] > static_cast<int>(unitSpeed))
  519. continue;
  520. }
  521. ret.insert(i);
  522. }
  523. return ret;
  524. }
  525. BattleHexArray CBattleInfoCallback::battleGetOccupiableHexes(const battle::Unit * unit, bool obtainMovementRange) const
  526. {
  527. return battleGetOccupiableHexes(battleGetAvailableHexes(unit, obtainMovementRange), unit);
  528. }
  529. BattleHexArray CBattleInfoCallback::battleGetOccupiableHexes(const BattleHexArray & availableHexes, const battle::Unit * unit) const
  530. {
  531. RETURN_IF_NOT_BATTLE(BattleHexArray());
  532. if (!unit)
  533. throw std::runtime_error("Undefined unit in battleGetOccupiableHexes!");
  534. if (unit->doubleWide())
  535. {
  536. auto occupiableHexes = BattleHexArray(availableHexes);
  537. for (auto hex : availableHexes)
  538. occupiableHexes.insert(unit->occupiedHex(hex));
  539. return occupiableHexes;
  540. }
  541. return availableHexes;
  542. }
  543. BattleHex CBattleInfoCallback::fromWhichHexAttack(const battle::Unit * attacker, const BattleHex & target, const BattleHex::EDir & direction) const
  544. {
  545. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  546. if (!attacker)
  547. throw std::runtime_error("Undefined attacker in fromWhichHexAttack!");
  548. if (!target.isValid() || direction == BattleHex::NONE)
  549. return BattleHex::INVALID;
  550. bool isAttacker = attacker->unitSide() == BattleSide::ATTACKER;
  551. if (attacker->doubleWide())
  552. {
  553. // We need to find position of right hex of double-hex creature (or left for defending side)
  554. // | TOP_LEFT | TOP_RIGHT | RIGHT |BOTTOM_RIGHT|BOTTOM_LEFT| LEFT | TOP | BOTTOM
  555. // | o o - | - o o | - - | - - | - - | - - | o o | - -
  556. // | - x - | - x - | - x o o | - x - | - x - | o o x - | - x - | - x -
  557. // | - - | - - | - - | - o o | o o - | - - | - - | o o
  558. switch (direction)
  559. {
  560. case BattleHex::TOP_LEFT:
  561. case BattleHex::LEFT:
  562. case BattleHex::BOTTOM_LEFT:
  563. return target.cloneInDirection(direction, false)
  564. .cloneInDirection(isAttacker ? BattleHex::NONE : BattleHex::LEFT, false);
  565. case BattleHex::TOP_RIGHT:
  566. case BattleHex::RIGHT:
  567. case BattleHex::BOTTOM_RIGHT:
  568. return target.cloneInDirection(direction, false)
  569. .cloneInDirection(isAttacker ? BattleHex::RIGHT : BattleHex::NONE, false);
  570. case BattleHex::TOP:
  571. return target.cloneInDirection(isAttacker ? BattleHex::TOP_RIGHT : BattleHex::TOP_LEFT, false);
  572. case BattleHex::BOTTOM:
  573. return target.cloneInDirection(isAttacker ? BattleHex::BOTTOM_RIGHT : BattleHex::BOTTOM_LEFT, false);
  574. default:
  575. return BattleHex::INVALID;
  576. }
  577. }
  578. if (direction == BattleHex::TOP || direction == BattleHex::BOTTOM)
  579. return BattleHex::INVALID;
  580. return target.cloneInDirection(direction, false);
  581. }
  582. BattleHex CBattleInfoCallback::toWhichHexMove(const battle::Unit * unit, const BattleHex & position) const
  583. {
  584. return toWhichHexMove(battleGetAvailableHexes(unit, false), unit, position);
  585. }
  586. BattleHex CBattleInfoCallback::toWhichHexMove(const BattleHexArray & availableHexes, const battle::Unit * unit, const BattleHex & position) const
  587. {
  588. RETURN_IF_NOT_BATTLE(false);
  589. if (!unit)
  590. throw std::runtime_error("Undefined unit in toWhichHexMove!");
  591. if (!position.isValid())
  592. return BattleHex::INVALID;
  593. if (availableHexes.contains(position))
  594. return position;
  595. if (unit->doubleWide())
  596. {
  597. auto headPosition = position.cloneInDirection(unit->headDirection(), false);
  598. if (availableHexes.contains(headPosition))
  599. return headPosition;
  600. }
  601. return BattleHex::INVALID;
  602. }
  603. bool CBattleInfoCallback::battleCanAttackHex(const battle::Unit * attacker, const BattleHex & position) const
  604. {
  605. return battleCanAttackHex(battleGetAvailableHexes(attacker, false), attacker, position);
  606. }
  607. bool CBattleInfoCallback::battleCanAttackHex(const BattleHexArray & availableHexes, const battle::Unit * attacker, const BattleHex & position) const
  608. {
  609. for (auto direction = 0; direction < 8; direction++)
  610. {
  611. if (battleCanAttackHex(availableHexes, attacker, position, BattleHex::EDir(direction)))
  612. return true;
  613. }
  614. return false;
  615. }
  616. bool CBattleInfoCallback::battleCanAttackHex(const battle::Unit * attacker, const BattleHex & position, const BattleHex::EDir & direction) const
  617. {
  618. return battleCanAttackHex(battleGetAvailableHexes(attacker, false), attacker, position, direction);
  619. }
  620. bool CBattleInfoCallback::battleCanAttackHex(const BattleHexArray & availableHexes, const battle::Unit * attacker, const BattleHex & position, const BattleHex::EDir & direction) const
  621. {
  622. RETURN_IF_NOT_BATTLE(false);
  623. if (!attacker)
  624. throw std::runtime_error("Undefined attacker in battleCanAttackHex!");
  625. if (!position.isValid() || direction == BattleHex::NONE)
  626. return false;
  627. BattleHex fromHex = fromWhichHexAttack(attacker, position, direction);
  628. //check if the attack is performed from an available hex
  629. if (!fromHex.isValid() || !availableHexes.contains(fromHex))
  630. return false;
  631. //if the movement ends in an obstacle, check if the obstacle allows attacking from that position
  632. if (attacker->getPosition() != fromHex)
  633. {
  634. for (const auto & obstacle : battleGetAllObstacles())
  635. {
  636. if (obstacle->getStoppingTile().contains(fromHex))
  637. return false;
  638. if (attacker->doubleWide() && obstacle->getStoppingTile().contains(attacker->occupiedHex(fromHex)))
  639. return false;
  640. }
  641. const battle::Unit * defender = battleGetUnitByPos(position, false); //Do not allow to target corpses when standing on them (a WALK_AND_SPELLCAST action)
  642. if (defender && defender->isDead() && defender->coversPos(fromHex))
  643. return false;
  644. }
  645. return true;
  646. }
  647. bool CBattleInfoCallback::battleCanAttackUnit(const battle::Unit * attacker, const battle::Unit * target) const
  648. {
  649. RETURN_IF_NOT_BATTLE(false);
  650. if(battleTacticDist())
  651. return false;
  652. if (!attacker)
  653. throw std::runtime_error("Undefined attacker in battleCanAttackUnit!");
  654. if(!target || target->isInvincible())
  655. return false;
  656. if(attacker == target || !battleMatchOwner(attacker, target))
  657. return false;
  658. if (!attacker->isMeleeAttacker())
  659. return false;
  660. return target->alive();
  661. }
  662. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  663. {
  664. RETURN_IF_NOT_BATTLE(false);
  665. if(battleTacticDist()) //no shooting during tactics
  666. return false;
  667. if (!attacker)
  668. return false;
  669. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  670. return false;
  671. if (!attacker->canShoot())
  672. return false;
  673. return attacker->canShootBlocked() || !battleIsUnitBlocked(attacker);
  674. }
  675. bool CBattleInfoCallback::battleCanTargetEmptyHex(const battle::Unit * attacker) const
  676. {
  677. RETURN_IF_NOT_BATTLE(false);
  678. if(!LIBRARY->engineSettings()->getBoolean(EGameSettings::COMBAT_AREA_SHOT_CAN_TARGET_EMPTY_HEX))
  679. return false;
  680. if(attacker->hasBonusOfType(BonusType::SPELL_LIKE_ATTACK))
  681. {
  682. auto bonus = attacker->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  683. const CSpell * spell = bonus->subtype.as<SpellID>().toSpell();
  684. spells::BattleCast cast(this, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  685. BattleHex dummySpellTarget = BattleHex(50); //check arbitrary hex for general spell range since currently there is no general way to access amount of hexes
  686. if(spell->battleMechanics(&cast)->rangeInHexes(dummySpellTarget).size() > 1)
  687. {
  688. return true;
  689. }
  690. }
  691. return false;
  692. }
  693. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, const BattleHex & dest) const
  694. {
  695. RETURN_IF_NOT_BATTLE(false);
  696. const battle::Unit * defender = battleGetUnitByPos(dest);
  697. if(!attacker)
  698. return false;
  699. bool emptyHexAreaAttack = battleCanTargetEmptyHex(attacker);
  700. if(!emptyHexAreaAttack)
  701. {
  702. if(!defender)
  703. return false;
  704. if(defender->isInvincible())
  705. return false;
  706. }
  707. bool attackerIsBerserk = attacker->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE);
  708. if(emptyHexAreaAttack || (defender->alive() && (attackerIsBerserk || battleMatchOwner(attacker, defender))))
  709. {
  710. if(battleCanShoot(attacker))
  711. {
  712. auto limitedRangeBonus = attacker->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  713. if(limitedRangeBonus == nullptr)
  714. {
  715. return true;
  716. }
  717. int shootingRange = limitedRangeBonus->val;
  718. if(defender)
  719. return isEnemyUnitWithinSpecifiedRange(attacker->getPosition(), defender, shootingRange);
  720. else
  721. return isHexWithinSpecifiedRange(attacker->getPosition(), dest, shootingRange);
  722. }
  723. }
  724. return false;
  725. }
  726. DamageEstimation CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  727. {
  728. DamageCalculator calculator(*this, info);
  729. return calculator.calculateDmgRange();
  730. }
  731. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, const BattleHex & attackerPosition, DamageEstimation * retaliationDmg) const
  732. {
  733. RETURN_IF_NOT_BATTLE({});
  734. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  735. int movementRange = attackerPosition.isValid() ? reachability[attackerPosition.toInt()] : 0;
  736. return battleEstimateDamage(attacker, defender, movementRange, retaliationDmg);
  737. }
  738. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementRange, DamageEstimation * retaliationDmg) const
  739. {
  740. RETURN_IF_NOT_BATTLE({});
  741. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  742. const BattleAttackInfo bai(attacker, defender, movementRange, shooting);
  743. return battleEstimateDamage(bai, retaliationDmg);
  744. }
  745. int64_t CBattleInfoCallback::getFirstAidHealValue(const CGHeroInstance * owner, const battle::Unit * target) const
  746. {
  747. RETURN_IF_NOT_BATTLE(0);
  748. if(!owner || !target)
  749. return 0;
  750. int64_t base = owner->valOfBonuses(BonusType::MANUAL_CONTROL, BonusSubtypeID(CreatureID(CreatureID::FIRST_AID_TENT)));
  751. if(base <= 0)
  752. return 0;
  753. auto state = target->acquireState();
  754. return state->heal(base, EHealLevel::HEAL, EHealPower::PERMANENT).healedHealthPoints;
  755. }
  756. SpellEffectValUptr CBattleInfoCallback::getSpellEffectValue(
  757. const CSpell * spell,
  758. const spells::Caster * caster,
  759. const spells::Mode spellMode,
  760. const BattleHex & targetHex) const
  761. {
  762. auto result = std::make_unique<spells::effects::SpellEffectValue>();
  763. RETURN_IF_NOT_BATTLE(result);
  764. if(!spell || !caster || !targetHex.isValid())
  765. return result;
  766. spells::BattleCast params(this, caster, spellMode, spell);
  767. std::unique_ptr<spells::Mechanics> mech = spell->battleMechanics(&params);
  768. if(!mech)
  769. return result;
  770. spells::Target aim;
  771. aim.emplace_back(targetHex);
  772. const battle::Unit * hoveredUnit = battleGetUnitByPos(targetHex, false);
  773. if(hoveredUnit)
  774. aim.emplace_back(spells::Destination(hoveredUnit));
  775. const spells::Target spellTarget = mech->canonicalizeTarget(aim);
  776. mech->forEachEffect([&](const spells::effects::Effect &e){
  777. if(const auto *ue = dynamic_cast<const spells::effects::UnitEffect*>(&e))
  778. {
  779. auto effTarget = ue->transformTarget(mech.get(), aim, spellTarget);
  780. // Cure-specific safety net: if empty, but hovering a healable friendly unit, evaluate just that unit
  781. if(effTarget.empty() && hoveredUnit)
  782. {
  783. spells::EffectTarget single;
  784. single.emplace_back(spells::Destination(hoveredUnit));
  785. *result += ue->getHealthChange(mech.get(), single);
  786. return false;
  787. }
  788. if(!effTarget.empty())
  789. *result += ue->getHealthChange(mech.get(), effTarget);
  790. }
  791. return false; // continue iterating effects
  792. });
  793. return result;
  794. }
  795. DamageEstimation CBattleInfoCallback::estimateSpellLikeAttackDamage(const battle::Unit * shooter,
  796. const CSpell * spell,
  797. const BattleHex & aimHex) const
  798. {
  799. RETURN_IF_NOT_BATTLE({});
  800. if(!spell || !shooter || !aimHex.isValid())
  801. return {};
  802. spells::ProxyCaster proxy(shooter);
  803. spells::BattleCast params(this, &proxy, spells::Mode::PASSIVE, spell);
  804. std::unique_ptr<spells::Mechanics> mech = spell->battleMechanics(&params);
  805. if(!mech)
  806. return {};
  807. spells::Target aim;
  808. aim.emplace_back(aimHex);
  809. const auto affected = mech->getAffectedStacks(aim);
  810. if(affected.empty())
  811. return {};
  812. DamageEstimation total {};
  813. for(const battle::Unit * u : affected)
  814. {
  815. BattleAttackInfo bai(shooter, u, 0, true);
  816. DamageEstimation de = calculateDmgRange(bai);
  817. total.damage.min += de.damage.min;
  818. total.damage.max += de.damage.max;
  819. total.kills.min += de.kills.min;
  820. total.kills.max += de.kills.max;
  821. }
  822. return total;
  823. }
  824. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, DamageEstimation * retaliationDmg) const
  825. {
  826. RETURN_IF_NOT_BATTLE({});
  827. DamageEstimation ret = calculateDmgRange(bai);
  828. if(retaliationDmg == nullptr)
  829. return ret;
  830. *retaliationDmg = DamageEstimation();
  831. if(bai.shooting) //FIXME: handle RANGED_RETALIATION
  832. return ret;
  833. if (!bai.defender->ableToRetaliate())
  834. return ret;
  835. if (bai.attacker->hasBonusOfType(BonusType::BLOCKS_RETALIATION) || bai.attacker->isInvincible())
  836. return ret;
  837. //TODO: rewrite using boost::numeric::interval
  838. //TODO: rewire once more using interval-based fuzzy arithmetic
  839. const auto & estimateRetaliation = [&](int64_t damage)
  840. {
  841. auto retaliationAttack = bai.reverse();
  842. auto state = retaliationAttack.attacker->acquireState();
  843. state->damage(damage);
  844. retaliationAttack.attacker = state.get();
  845. if (state->alive())
  846. return calculateDmgRange(retaliationAttack);
  847. else
  848. return DamageEstimation();
  849. };
  850. DamageEstimation retaliationMin = estimateRetaliation(ret.damage.min);
  851. DamageEstimation retaliationMax = estimateRetaliation(ret.damage.max);
  852. retaliationDmg->damage.min = std::min(retaliationMin.damage.min, retaliationMax.damage.min);
  853. retaliationDmg->damage.max = std::max(retaliationMin.damage.max, retaliationMax.damage.max);
  854. retaliationDmg->kills.min = std::min(retaliationMin.kills.min, retaliationMax.kills.min);
  855. retaliationDmg->kills.max = std::max(retaliationMin.kills.max, retaliationMax.kills.max);
  856. return ret;
  857. }
  858. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(const BattleHex & tile, bool onlyBlocking) const
  859. {
  860. auto obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  861. RETURN_IF_NOT_BATTLE(obstacles);
  862. for(auto & obs : battleGetAllObstacles())
  863. {
  864. if(obs->getBlockedTiles().contains(tile)
  865. || (!onlyBlocking && obs->getAffectedTiles().contains(tile)))
  866. {
  867. obstacles.push_back(obs);
  868. }
  869. }
  870. return obstacles;
  871. }
  872. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit, const BattleHexArray & passed) const
  873. {
  874. auto affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  875. RETURN_IF_NOT_BATTLE(affectedObstacles);
  876. if(unit->alive())
  877. {
  878. if(!passed.contains(unit->getPosition()))
  879. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  880. if(unit->doubleWide())
  881. {
  882. BattleHex otherHex = unit->occupiedHex();
  883. if(otherHex.isValid() && !passed.contains(otherHex))
  884. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  885. if(!vstd::contains(affectedObstacles, i))
  886. affectedObstacles.push_back(i);
  887. }
  888. for(const auto & hex : unit->getHexes())
  889. if(hex == BattleHex::GATE_BRIDGE && battleIsGatePassable())
  890. for(int i=0; i<affectedObstacles.size(); i++)
  891. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  892. affectedObstacles.erase(affectedObstacles.begin()+i);
  893. }
  894. return affectedObstacles;
  895. }
  896. bool CBattleInfoCallback::handleObstacleTriggersForUnit(SpellCastEnvironment & spellEnv, const battle::Unit & unit, const BattleHexArray & passed) const
  897. {
  898. if(!unit.alive())
  899. return false;
  900. bool movementStopped = false;
  901. for(auto & obstacle : getAllAffectedObstaclesByStack(&unit, passed))
  902. {
  903. //helper info
  904. const SpellCreatedObstacle * spellObstacle = dynamic_cast<const SpellCreatedObstacle *>(obstacle.get());
  905. if(spellObstacle)
  906. {
  907. auto revealObstacles = [&](const SpellCreatedObstacle & spellObstacle) -> void
  908. {
  909. // For the hidden spell created obstacles, e.g. QuickSand, it should be revealed after taking damage
  910. auto operation = ObstacleChanges::EOperation::UPDATE;
  911. if (spellObstacle.removeOnTrigger)
  912. operation = ObstacleChanges::EOperation::REMOVE;
  913. SpellCreatedObstacle changedObstacle;
  914. changedObstacle.uniqueID = spellObstacle.uniqueID;
  915. changedObstacle.revealed = true;
  916. BattleObstaclesChanged bocp;
  917. bocp.battleID = getBattle()->getBattleID();
  918. bocp.changes.emplace_back(spellObstacle.uniqueID, operation);
  919. changedObstacle.toInfo(bocp.changes.back(), operation);
  920. spellEnv.apply(bocp);
  921. };
  922. const auto side = unit.unitSide();
  923. auto shouldReveal = !spellObstacle->hidden || !battleIsObstacleVisibleForSide(*obstacle, side);
  924. const auto * hero = battleGetFightingHero(spellObstacle->casterSide);
  925. auto caster = spells::ObstacleCasterProxy(getBattle()->getSidePlayer(spellObstacle->casterSide), hero, *spellObstacle);
  926. if(obstacle->triggersEffects() && obstacle->getTrigger().hasValue())
  927. {
  928. const auto * sp = obstacle->getTrigger().toSpell();
  929. auto cast = spells::BattleCast(this, &caster, spells::Mode::PASSIVE, sp);
  930. spells::detail::ProblemImpl ignored;
  931. auto target = spells::Target(1, spells::Destination(&unit));
  932. if(sp->battleMechanics(&cast)->canBeCastAt(target, ignored)) // Obstacles should not be revealed by immune creatures
  933. {
  934. if(shouldReveal) { //hidden obstacle triggers effects after revealed
  935. revealObstacles(*spellObstacle);
  936. cast.cast(&spellEnv, target);
  937. }
  938. }
  939. }
  940. else if(shouldReveal)
  941. revealObstacles(*spellObstacle);
  942. }
  943. if(!unit.alive())
  944. return false;
  945. if(obstacle->stopsMovement())
  946. movementStopped = true;
  947. }
  948. return unit.alive() && !movementStopped;
  949. }
  950. AccessibilityInfo CBattleInfoCallback::getAccessibility() const
  951. {
  952. AccessibilityInfo ret;
  953. ret.fill(EAccessibility::ACCESSIBLE);
  954. //removing accessibility for side columns of hexes
  955. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  956. {
  957. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y).toInt()] = EAccessibility::SIDE_COLUMN;
  958. ret[BattleHex(0, y).toInt()] = EAccessibility::SIDE_COLUMN;
  959. }
  960. //special battlefields with logically unavailable tiles
  961. auto bFieldType = battleGetBattlefieldType();
  962. if(bFieldType != BattleField::NONE)
  963. {
  964. for(const auto & hex : bFieldType.getInfo()->impassableHexes)
  965. ret[hex.toInt()] = EAccessibility::UNAVAILABLE;
  966. }
  967. //gate -> should be before stacks
  968. if(battleGetFortifications().wallsHealth > 0)
  969. {
  970. EAccessibility accessibility = EAccessibility::ACCESSIBLE;
  971. switch(battleGetGateState())
  972. {
  973. case EGateState::CLOSED:
  974. accessibility = EAccessibility::GATE;
  975. break;
  976. case EGateState::BLOCKED:
  977. accessibility = EAccessibility::UNAVAILABLE;
  978. break;
  979. }
  980. ret[BattleHex::GATE_OUTER] = ret[BattleHex::GATE_INNER] = accessibility;
  981. }
  982. //tiles occupied by standing stacks
  983. for(const auto * unit : battleAliveUnits())
  984. {
  985. for(const auto & hex : unit->getHexes())
  986. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  987. ret[hex.toInt()] = EAccessibility::ALIVE_STACK;
  988. }
  989. //obstacles
  990. for(const auto &obst : battleGetAllObstacles())
  991. {
  992. for(const auto & hex : obst->getBlockedTiles())
  993. ret[hex.toInt()] = EAccessibility::OBSTACLE;
  994. }
  995. //walls
  996. if(battleGetFortifications().wallsHealth > 0)
  997. {
  998. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  999. for(const auto & hex : permanentlyLocked)
  1000. ret[hex] = EAccessibility::UNAVAILABLE;
  1001. //TODO likely duplicated logic
  1002. static const std::pair<EWallPart, BattleHex> lockedIfNotDestroyed[] =
  1003. {
  1004. //which part of wall, which hex is blocked if this part of wall is not destroyed
  1005. std::make_pair(EWallPart::BOTTOM_WALL, BattleHex(BattleHex::DESTRUCTIBLE_WALL_4)),
  1006. std::make_pair(EWallPart::BELOW_GATE, BattleHex(BattleHex::DESTRUCTIBLE_WALL_3)),
  1007. std::make_pair(EWallPart::OVER_GATE, BattleHex(BattleHex::DESTRUCTIBLE_WALL_2)),
  1008. std::make_pair(EWallPart::UPPER_WALL, BattleHex(BattleHex::DESTRUCTIBLE_WALL_1))
  1009. };
  1010. for(const auto & elem : lockedIfNotDestroyed)
  1011. {
  1012. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  1013. ret[elem.second.toInt()] = EAccessibility::DESTRUCTIBLE_WALL;
  1014. }
  1015. }
  1016. return ret;
  1017. }
  1018. AccessibilityInfo CBattleInfoCallback::getAccessibility(const battle::Unit * stack) const
  1019. {
  1020. return getAccessibility(stack->getHexes());
  1021. }
  1022. AccessibilityInfo CBattleInfoCallback::getAccessibility(const BattleHexArray & accessibleHexes) const
  1023. {
  1024. auto ret = getAccessibility();
  1025. for(const auto & hex : accessibleHexes)
  1026. if(hex.isValid())
  1027. ret[hex.toInt()] = EAccessibility::ACCESSIBLE;
  1028. return ret;
  1029. }
  1030. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo & accessibility, const ReachabilityInfo::Parameters & params) const
  1031. {
  1032. ReachabilityInfo ret;
  1033. ret.accessibility = accessibility;
  1034. ret.params = params;
  1035. ret.predecessors.fill(BattleHex::INVALID);
  1036. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  1037. if(!params.startPosition.isValid()) //if got call for arrow turrets
  1038. return ret;
  1039. const BattleHexArray obstacles = getStoppers(params.perspective);
  1040. auto checkParams = params;
  1041. checkParams.ignoreKnownAccessible = true; //Ignore starting hexes obstacles
  1042. std::queue<BattleHex> hexq; //bfs queue
  1043. //first element
  1044. hexq.push(params.startPosition);
  1045. ret.distances[params.startPosition.toInt()] = 0;
  1046. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache{};
  1047. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  1048. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  1049. while(!hexq.empty()) //bfs loop
  1050. {
  1051. const BattleHex curHex = hexq.front();
  1052. hexq.pop();
  1053. //walking stack can't step past the obstacles
  1054. if(isInObstacle(curHex, obstacles, checkParams))
  1055. continue;
  1056. const int costToNeighbour = ret.distances.at(curHex.toInt()) + 1;
  1057. for(const BattleHex & neighbour : curHex.getNeighbouringTiles())
  1058. {
  1059. auto additionalCost = 0;
  1060. if(params.bypassEnemyStacks)
  1061. {
  1062. auto enemyToBypass = params.destructibleEnemyTurns.at(neighbour.toInt());
  1063. if(enemyToBypass >= 0)
  1064. {
  1065. additionalCost = enemyToBypass;
  1066. }
  1067. }
  1068. const int costFoundSoFar = ret.distances[neighbour.toInt()];
  1069. if(accessibleCache[neighbour.toInt()] && costToNeighbour + additionalCost < costFoundSoFar)
  1070. {
  1071. hexq.push(neighbour);
  1072. ret.distances[neighbour.toInt()] = costToNeighbour + additionalCost;
  1073. ret.predecessors[neighbour.toInt()] = curHex;
  1074. }
  1075. }
  1076. }
  1077. return ret;
  1078. }
  1079. bool CBattleInfoCallback::isInObstacle(
  1080. const BattleHex & hex,
  1081. const BattleHexArray & obstacleHexes,
  1082. const ReachabilityInfo::Parameters & params) const
  1083. {
  1084. for(const auto & occupiedHex : battle::Unit::getHexes(hex, params.doubleWide, params.side))
  1085. {
  1086. if(params.ignoreKnownAccessible && params.knownAccessible->contains(occupiedHex))
  1087. continue;
  1088. if(obstacleHexes.contains(occupiedHex))
  1089. {
  1090. if(occupiedHex == BattleHex::GATE_BRIDGE)
  1091. {
  1092. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  1093. return true;
  1094. }
  1095. else
  1096. return true;
  1097. }
  1098. }
  1099. return false;
  1100. }
  1101. BattleHexArray CBattleInfoCallback::getStoppers(BattleSide whichSidePerspective) const
  1102. {
  1103. BattleHexArray ret;
  1104. RETURN_IF_NOT_BATTLE(ret);
  1105. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  1106. {
  1107. if(!battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  1108. continue;
  1109. for(const auto & hex : oi->getStoppingTile())
  1110. {
  1111. if(hex == BattleHex::GATE_BRIDGE && oi->obstacleType == CObstacleInstance::MOAT)
  1112. {
  1113. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  1114. continue; // this tile is disabled by drawbridge on top of it
  1115. }
  1116. ret.insert(hex);
  1117. }
  1118. }
  1119. return ret;
  1120. }
  1121. BattleHex CBattleInfoCallback::getClosestHexToTargetInRange(const ReachabilityInfo & cache, const Unit & unit, const BattleHex & targetHex) const
  1122. {
  1123. if (unit.hasBonusOfType(BonusType::FLYING))
  1124. {
  1125. BattleHexArray reachableHexes = battleGetAvailableHexes(cache, &unit, false);
  1126. return boost::min_element(reachableHexes, [&targetHex](const BattleHex & lhs, const BattleHex & rhs)
  1127. {
  1128. return BattleHex::getDistance(lhs, targetHex) < BattleHex::getDistance(rhs, targetHex);
  1129. })[0];
  1130. }
  1131. BattleHexArray path = getPath(unit.getPosition(), targetHex, &unit).first; //TODO: does not find path through moat
  1132. if(!path.empty())
  1133. {
  1134. int pathHexIndex = path.size() - unit.getMovementRange();
  1135. if(pathHexIndex < 0)
  1136. {
  1137. return targetHex;
  1138. }
  1139. return path[pathHexIndex];
  1140. }
  1141. // FALLBACK: If path is empty (target blocked by obstacles/units),
  1142. // find the reachable hex that is geometrically closest to the target.
  1143. BattleHexArray reachableHexes = battleGetAvailableHexes(cache, &unit, false);
  1144. if (reachableHexes.empty())
  1145. return BattleHex::INVALID;
  1146. return *std::ranges::min_element(reachableHexes, {}, [&](const BattleHex & h)
  1147. {
  1148. return BattleHex::getDistance(h, targetHex);
  1149. });
  1150. }
  1151. ForcedAction CBattleInfoCallback::getBerserkForcedAction(const battle::Unit * berserker) const
  1152. {
  1153. logGlobal->trace("Handle Berserk effect");
  1154. auto targets = battleGetUnitsIf([&berserker](const battle::Unit * u)
  1155. {
  1156. return u->isValidTarget(false) && u->unitId() != berserker->unitId();
  1157. });
  1158. auto cache = getReachability(berserker);
  1159. if (battleCanShoot(berserker))
  1160. {
  1161. const auto target = boost::min_element(targets, [&berserker](const battle::Unit * lhs, const battle::Unit * rhs)
  1162. {
  1163. return BattleHex::getDistance(berserker->getPosition(), lhs->getPosition()) < BattleHex::getDistance(berserker->getPosition(), rhs->getPosition());
  1164. })[0];
  1165. ForcedAction result = {
  1166. EActionType::SHOOT,
  1167. berserker->getPosition(),
  1168. target
  1169. };
  1170. return result;
  1171. }
  1172. else
  1173. {
  1174. struct TargetData
  1175. {
  1176. const battle::Unit * target;
  1177. BattleHex closestAttackableHex;
  1178. uint32_t distance;
  1179. };
  1180. std::vector<TargetData> targetData;
  1181. targetData.reserve(targets.size());
  1182. for (const battle::Unit * uTarget : targets)
  1183. {
  1184. BattleHexArray attackableHexes = uTarget->getAttackableHexes(berserker);
  1185. auto closestAttackableHex = boost::min_element(attackableHexes, [&cache](const BattleHex & lhs, const BattleHex & rhs)
  1186. {
  1187. return cache.distances[lhs.toInt()] < cache.distances[rhs.toInt()];
  1188. })[0];
  1189. uint32_t distance = cache.distances[closestAttackableHex.toInt()];
  1190. TargetData temp = {uTarget, closestAttackableHex, distance};
  1191. targetData.push_back(temp);
  1192. }
  1193. auto closestUnit = boost::min_element(targetData, [](const TargetData & lhs, const TargetData & rhs)
  1194. {
  1195. return lhs.distance < rhs.distance;
  1196. })[0];
  1197. if (closestUnit.distance <= berserker->getMovementRange())
  1198. {
  1199. ForcedAction result = {
  1200. EActionType::WALK_AND_ATTACK,
  1201. closestUnit.closestAttackableHex,
  1202. closestUnit.target
  1203. };
  1204. return result;
  1205. }
  1206. else if (closestUnit.distance != ReachabilityInfo::INFINITE_DIST && berserker->getMovementRange() > 0)
  1207. {
  1208. BattleHex intermediaryHex = getClosestHexToTargetInRange(cache, *berserker, closestUnit.closestAttackableHex);
  1209. ForcedAction result = {
  1210. EActionType::WALK,
  1211. intermediaryHex,
  1212. closestUnit.target
  1213. };
  1214. return result;
  1215. }
  1216. else
  1217. {
  1218. logGlobal->trace("No target found or unit cannot move");
  1219. ForcedAction result = {
  1220. EActionType::NO_ACTION,
  1221. berserker->getPosition(),
  1222. nullptr
  1223. };
  1224. return result;
  1225. }
  1226. }
  1227. }
  1228. BattleHex CBattleInfoCallback::getAvailableHex(const CreatureID & creID, BattleSide side, int initialPos) const
  1229. {
  1230. bool twoHex = LIBRARY->creatures()->getById(creID)->isDoubleWide();
  1231. int pos;
  1232. if (initialPos > -1)
  1233. pos = initialPos;
  1234. else //summon elementals depending on player side
  1235. {
  1236. if(side == BattleSide::ATTACKER)
  1237. pos = 0; //top left
  1238. else
  1239. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  1240. }
  1241. auto accessibility = getAccessibility();
  1242. BattleHexArray occupyable;
  1243. for(int i = 0; i < accessibility.size(); i++)
  1244. if(accessibility.accessible(i, twoHex, side))
  1245. occupyable.insert(i);
  1246. if(occupyable.empty())
  1247. {
  1248. return BattleHex::INVALID; //all tiles are covered
  1249. }
  1250. return BattleHex::getClosestTile(side, pos, occupyable);
  1251. }
  1252. si8 CBattleInfoCallback::battleGetTacticDist() const
  1253. {
  1254. RETURN_IF_NOT_BATTLE(0);
  1255. //TODO get rid of this method
  1256. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1257. return battleTacticDist();
  1258. return 0;
  1259. }
  1260. bool CBattleInfoCallback::isInTacticRange(const BattleHex & dest) const
  1261. {
  1262. RETURN_IF_NOT_BATTLE(false);
  1263. auto side = battleGetTacticsSide();
  1264. auto dist = battleGetTacticDist();
  1265. if (side == BattleSide::ATTACKER && dest.getX() > 0 && dest.getX() <= dist)
  1266. return true;
  1267. if (side == BattleSide::DEFENDER && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1)
  1268. return true;
  1269. return false;
  1270. }
  1271. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  1272. {
  1273. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  1274. if(!battleDoWeKnowAbout(unit->unitSide()))
  1275. {
  1276. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1277. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1278. params.perspective = battleGetMySide();
  1279. }
  1280. return getReachability(params);
  1281. }
  1282. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters & params) const
  1283. {
  1284. if(params.flying)
  1285. return getFlyingReachability(params);
  1286. else
  1287. {
  1288. auto accessibility = getAccessibility(* params.knownAccessible);
  1289. accessibility.destructibleEnemyTurns = std::shared_ptr<const TBattlefieldTurnsArray>(
  1290. & params.destructibleEnemyTurns,
  1291. [](const TBattlefieldTurnsArray *) { }
  1292. );
  1293. return makeBFS(accessibility, params);
  1294. }
  1295. }
  1296. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters & params) const
  1297. {
  1298. ReachabilityInfo ret;
  1299. ret.accessibility = getAccessibility(* params.knownAccessible);
  1300. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1301. {
  1302. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  1303. {
  1304. ret.predecessors[i] = params.startPosition;
  1305. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1306. }
  1307. }
  1308. return ret;
  1309. }
  1310. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes(
  1311. const battle::Unit * attacker,
  1312. BattleHex destinationTile,
  1313. BattleHex attackerPos) const
  1314. {
  1315. const auto * defender = battleGetUnitByPos(destinationTile, true);
  1316. if(!defender)
  1317. return AttackableTiles(); // can't attack thin air
  1318. return getPotentiallyAttackableHexes(
  1319. attacker,
  1320. defender,
  1321. destinationTile,
  1322. attackerPos,
  1323. defender->getPosition());
  1324. }
  1325. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes(
  1326. const battle::Unit* attacker,
  1327. const battle::Unit * defender,
  1328. BattleHex destinationTile,
  1329. BattleHex attackerPos,
  1330. BattleHex defenderPos) const
  1331. {
  1332. //does not return hex attacked directly
  1333. AttackableTiles at;
  1334. RETURN_IF_NOT_BATTLE(at);
  1335. BattleHex attackOriginHex = (attackerPos.toInt() != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1336. defenderPos = (defenderPos.toInt() != BattleHex::INVALID) ? defenderPos : defender->getPosition(); //real or hypothetical (cursor) position
  1337. if(attacker->hasBonusOfType(BonusType::ATTACKS_ALL_ADJACENT))
  1338. at.hostileCreaturePositions.insert(attacker->getSurroundingHexes(attackerPos));
  1339. // If attacker is double-wide and its head is not adjacent to enemy we need to turn around
  1340. if(attacker->doubleWide() && !vstd::contains(defender->getSurroundingHexes(defenderPos), attackOriginHex))
  1341. attackOriginHex = attacker->occupiedHex(attackOriginHex);
  1342. auto attackDirection = BattleHex::mutualPosition(attackOriginHex, defenderPos);
  1343. // If defender is double-wide, attacker always prefers targeting its 'tail', if it is reachable
  1344. if(defender->doubleWide() && BattleHex::mutualPosition(attackOriginHex, defender->occupiedHex(defenderPos)) != BattleHex::NONE)
  1345. attackDirection = BattleHex::mutualPosition(attackOriginHex, defender->occupiedHex(defenderPos));
  1346. if (attackDirection == BattleHex::NONE)
  1347. throw std::runtime_error("!!!");
  1348. const auto & processTargets = [&](const std::vector<int> & additionalTargets) -> BattleHexArray
  1349. {
  1350. BattleHexArray output;
  1351. for (int targetPath : additionalTargets)
  1352. {
  1353. BattleHex target = attackOriginHex;
  1354. std::vector<BattleHex::EDir> path;
  1355. for (int targetPathLeft = targetPath; targetPathLeft != 0; targetPathLeft /= 10)
  1356. path.push_back(static_cast<BattleHex::EDir>((attackDirection + targetPathLeft % 10 - 1) % 6));
  1357. try
  1358. {
  1359. if(attacker->doubleWide() && attacker->coversPos(target.cloneInDirection(path.front())))
  1360. target.moveInDirection(attackDirection);
  1361. for(BattleHex::EDir nextDirection : path)
  1362. target.moveInDirection(nextDirection);
  1363. }
  1364. catch(const std::out_of_range &)
  1365. {
  1366. // Hex out of range, for example outside of battlefield. This is valid situation, so skip this hex
  1367. continue;
  1368. }
  1369. if (target.isValid() && !attacker->coversPos(target))
  1370. output.insert(target);
  1371. }
  1372. return output;
  1373. };
  1374. const auto multihexUnit = attacker->getBonusesOfType(BonusType::MULTIHEX_UNIT_ATTACK);
  1375. const auto multihexEnemy = attacker->getBonusesOfType(BonusType::MULTIHEX_ENEMY_ATTACK);
  1376. const auto multihexAnimation = attacker->getBonusesOfType(BonusType::MULTIHEX_ANIMATION);
  1377. for (const auto & bonus : *multihexUnit)
  1378. at.friendlyCreaturePositions.insert(processTargets(bonus->parameters->toVector()));
  1379. for (const auto & bonus : *multihexEnemy)
  1380. at.hostileCreaturePositions.insert(processTargets(bonus->parameters->toVector()));
  1381. for (const auto & bonus : *multihexAnimation)
  1382. at.overrideAnimationPositions.insert(processTargets(bonus->parameters->toVector()));
  1383. if(attacker->hasBonusOfType(BonusType::THREE_HEADED_ATTACK))
  1384. at.hostileCreaturePositions.insert(processTargets({2,6}));
  1385. if(attacker->hasBonusOfType(BonusType::WIDE_BREATH))
  1386. at.friendlyCreaturePositions.insert(processTargets({ 11, 111, 2, 12, 6, 16 }));
  1387. if(attacker->hasBonusOfType(BonusType::TWO_HEX_ATTACK_BREATH))
  1388. at.friendlyCreaturePositions.insert(processTargets({ 11 }));
  1389. if (attacker->hasBonusOfType(BonusType::PRISM_HEX_ATTACK_BREATH))
  1390. at.friendlyCreaturePositions.insert(processTargets({ 11, 12, 16 }));
  1391. return at;
  1392. }
  1393. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, const BattleHex & destinationTile, const BattleHex & attackerPos) const
  1394. {
  1395. //does not return hex attacked directly
  1396. AttackableTiles at;
  1397. RETURN_IF_NOT_BATTLE(at);
  1398. if(attacker->hasBonusOfType(BonusType::SHOOTS_ALL_ADJACENT) && !attackerPos.getNeighbouringTiles().contains(destinationTile))
  1399. {
  1400. at.hostileCreaturePositions.insert(destinationTile.getNeighbouringTiles());
  1401. at.hostileCreaturePositions.insert(destinationTile);
  1402. }
  1403. return at;
  1404. }
  1405. battle::Units CBattleInfoCallback::getAttackedBattleUnits(
  1406. const battle::Unit * attacker,
  1407. const battle::Unit * defender,
  1408. BattleHex destinationTile,
  1409. bool rangedAttack,
  1410. BattleHex attackerPos,
  1411. BattleHex defenderPos) const
  1412. {
  1413. battle::Units units;
  1414. RETURN_IF_NOT_BATTLE(units);
  1415. if(attackerPos == BattleHex::INVALID)
  1416. attackerPos = attacker->getPosition();
  1417. if(defenderPos == BattleHex::INVALID)
  1418. defenderPos = defender->getPosition();
  1419. AttackableTiles at;
  1420. if (rangedAttack)
  1421. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1422. else
  1423. at = getPotentiallyAttackableHexes(attacker, defender, destinationTile, attackerPos, defenderPos);
  1424. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1425. {
  1426. if (unit->isGhost() || !unit->alive() || unit->isInvincible())
  1427. return false;
  1428. for (const BattleHex & hex : unit->getHexes())
  1429. {
  1430. if (at.hostileCreaturePositions.contains(hex))
  1431. return true;
  1432. if (at.friendlyCreaturePositions.contains(hex))
  1433. return true;
  1434. }
  1435. return false;
  1436. });
  1437. return units;
  1438. }
  1439. std::pair<std::set<const CStack*>, bool> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, const BattleHex & destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1440. {
  1441. std::pair<std::set<const CStack*>, bool> attackedCres;
  1442. RETURN_IF_NOT_BATTLE(attackedCres);
  1443. AttackableTiles at;
  1444. if(rangedAttack)
  1445. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1446. else
  1447. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1448. for (const BattleHex & tile : at.hostileCreaturePositions) //all around & three-headed attack
  1449. {
  1450. const CStack * st = battleGetStackByPos(tile, true);
  1451. if(st && battleGetOwner(st) != battleGetOwner(attacker) && !st->isInvincible()) //only hostile stacks - does it work well with Berserk?
  1452. {
  1453. attackedCres.first.insert(st);
  1454. }
  1455. }
  1456. for (const BattleHex & tile : at.friendlyCreaturePositions)
  1457. {
  1458. const CStack * st = battleGetStackByPos(tile, true);
  1459. if(st && !st->isInvincible()) //friendly stacks can also be damaged by Dragon Breath
  1460. {
  1461. attackedCres.first.insert(st);
  1462. }
  1463. }
  1464. if (at.friendlyCreaturePositions.empty())
  1465. {
  1466. attackedCres.second = !attackedCres.first.empty();
  1467. }
  1468. else
  1469. {
  1470. for (const BattleHex & tile : at.friendlyCreaturePositions)
  1471. for (const auto & st : attackedCres.first)
  1472. if (st->coversPos(tile))
  1473. attackedCres.second = true;
  1474. }
  1475. return attackedCres;
  1476. }
  1477. static bool isHexInFront(const BattleHex & hex, const BattleHex & testHex, BattleSide side )
  1478. {
  1479. static const std::set<BattleHex::EDir> rightDirs { BattleHex::BOTTOM_RIGHT, BattleHex::TOP_RIGHT, BattleHex::RIGHT };
  1480. static const std::set<BattleHex::EDir> leftDirs { BattleHex::BOTTOM_LEFT, BattleHex::TOP_LEFT, BattleHex::LEFT };
  1481. auto mutualPos = BattleHex::mutualPosition(hex, testHex);
  1482. if (side == BattleSide::ATTACKER)
  1483. return rightDirs.count(mutualPos);
  1484. else
  1485. return leftDirs.count(mutualPos);
  1486. }
  1487. //TODO: this should apply also to mechanics and cursor interface
  1488. bool CBattleInfoCallback::isToReverse(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerHex, BattleHex defenderHex) const
  1489. {
  1490. if(!defenderHex.isValid())
  1491. defenderHex = defender->getPosition();
  1492. if(!attackerHex.isValid())
  1493. attackerHex = attacker->getPosition();
  1494. if (attackerHex < 0 ) //turret
  1495. return false;
  1496. if(isHexInFront(attackerHex, defenderHex, attacker->unitSide()))
  1497. return false;
  1498. auto defenderOtherHex = defenderHex;
  1499. auto attackerOtherHex = defenderHex;
  1500. if (defender->doubleWide())
  1501. {
  1502. defenderOtherHex = battle::Unit::occupiedHex(defenderHex, true, defender->unitSide());
  1503. if(isHexInFront(attackerHex, defenderOtherHex, attacker->unitSide()))
  1504. return false;
  1505. }
  1506. if (attacker->doubleWide())
  1507. {
  1508. attackerOtherHex = battle::Unit::occupiedHex(attackerHex, true, attacker->unitSide());
  1509. if(isHexInFront(attackerOtherHex, defenderHex, attacker->unitSide()))
  1510. return false;
  1511. }
  1512. // a bit weird case since here defender is slightly behind attacker, so reversing seems preferable,
  1513. // but this is how H3 handles it which is important, e.g. for direction of dragon breath attacks
  1514. if (attacker->doubleWide() && defender->doubleWide())
  1515. {
  1516. if(isHexInFront(attackerOtherHex, defenderOtherHex, attacker->unitSide()))
  1517. return false;
  1518. }
  1519. return true;
  1520. }
  1521. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, const BattleHex & assumedPosition) const
  1522. {
  1523. ReachabilityInfo::TDistances ret;
  1524. ret.fill(-1);
  1525. RETURN_IF_NOT_BATTLE(ret);
  1526. auto reachability = getReachability(unit);
  1527. boost::copy(reachability.distances, ret.begin());
  1528. return ret;
  1529. }
  1530. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, const BattleHex & shooterPosition, const BattleHex & destHex) const
  1531. {
  1532. RETURN_IF_NOT_BATTLE(false);
  1533. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1534. static const auto selectorNoDistancePenalty = Selector::type()(BonusType::NO_DISTANCE_PENALTY);
  1535. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1536. return false;
  1537. if(const auto * target = battleGetUnitByPos(destHex, true))
  1538. {
  1539. //If any hex of target creature is within range, there is no penalty
  1540. int range = GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE;
  1541. auto bonus = shooter->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  1542. if(bonus != nullptr && bonus->parameters)
  1543. range = bonus->parameters->toNumber();
  1544. if(isEnemyUnitWithinSpecifiedRange(shooterPosition, target, range))
  1545. return false;
  1546. }
  1547. else
  1548. {
  1549. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE)
  1550. return false;
  1551. }
  1552. return true;
  1553. }
  1554. bool CBattleInfoCallback::isEnemyUnitWithinSpecifiedRange(const BattleHex & attackerPosition, const battle::Unit * defenderUnit, unsigned int range) const
  1555. {
  1556. for(const auto & hex : defenderUnit->getHexes())
  1557. if(BattleHex::getDistance(attackerPosition, hex) <= range)
  1558. return true;
  1559. return false;
  1560. }
  1561. bool CBattleInfoCallback::isHexWithinSpecifiedRange(const BattleHex & attackerPosition, const BattleHex & targetPosition, unsigned int range) const
  1562. {
  1563. if(BattleHex::getDistance(attackerPosition, targetPosition) <= range)
  1564. return true;
  1565. return false;
  1566. }
  1567. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart part) const
  1568. {
  1569. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1570. return WallPartToHex(part);
  1571. }
  1572. EWallPart CBattleInfoCallback::battleHexToWallPart(const BattleHex & hex) const
  1573. {
  1574. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1575. return hexToWallPart(hex);
  1576. }
  1577. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart wallPart) const
  1578. {
  1579. RETURN_IF_NOT_BATTLE(false);
  1580. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1581. wallPart != EWallPart::INVALID;
  1582. }
  1583. bool CBattleInfoCallback::isWallPartAttackable(EWallPart wallPart) const
  1584. {
  1585. RETURN_IF_NOT_BATTLE(false);
  1586. if(isWallPartPotentiallyAttackable(wallPart))
  1587. {
  1588. auto wallState = battleGetWallState(wallPart);
  1589. return (wallState != EWallState::NONE && wallState != EWallState::DESTROYED);
  1590. }
  1591. return false;
  1592. }
  1593. BattleHexArray CBattleInfoCallback::getAttackableWallParts() const
  1594. {
  1595. BattleHexArray attackableBattleHexes;
  1596. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1597. for(const auto & wallPartPair : wallParts)
  1598. {
  1599. if(isWallPartAttackable(wallPartPair.second))
  1600. attackableBattleHexes.insert(wallPartPair.first);
  1601. }
  1602. return attackableBattleHexes;
  1603. }
  1604. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1605. {
  1606. RETURN_IF_NOT_BATTLE(-1);
  1607. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1608. int32_t ret = caster->getSpellCost(sp);
  1609. //checking for friendly stacks reducing cost of the spell and
  1610. //enemy stacks increasing it
  1611. int32_t manaReduction = 0;
  1612. int32_t manaIncrease = 0;
  1613. for(const auto * unit : battleAliveUnits())
  1614. {
  1615. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(BonusType::CHANGES_SPELL_COST_FOR_ALLY))
  1616. {
  1617. vstd::amax(manaReduction, unit->valOfBonuses(BonusType::CHANGES_SPELL_COST_FOR_ALLY));
  1618. }
  1619. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(BonusType::CHANGES_SPELL_COST_FOR_ENEMY))
  1620. {
  1621. vstd::amax(manaIncrease, unit->valOfBonuses(BonusType::CHANGES_SPELL_COST_FOR_ENEMY));
  1622. }
  1623. }
  1624. return std::max(0, ret - manaReduction + manaIncrease);
  1625. }
  1626. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, const BattleHex & destHex) const
  1627. {
  1628. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1629. }
  1630. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1631. {
  1632. RETURN_IF_NOT_BATTLE(false);
  1633. bool isBerserk = unit->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE);
  1634. for(const auto * adjacent : battleAdjacentUnits(unit))
  1635. {
  1636. if(adjacent->unitOwner() != unit->unitOwner() || isBerserk)
  1637. return true;
  1638. }
  1639. return false;
  1640. }
  1641. battle::Units CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1642. {
  1643. RETURN_IF_NOT_BATTLE({});
  1644. const auto & hexes = unit->getSurroundingHexes();
  1645. const auto & units = battleGetUnitsIf([&hexes](const battle::Unit * testedUnit)
  1646. {
  1647. if (!testedUnit->alive())
  1648. return false;
  1649. const auto & unitHexes = testedUnit->getHexes();
  1650. for (const auto & hex : unitHexes)
  1651. if (hexes.contains(hex))
  1652. return true;
  1653. return false;
  1654. });
  1655. return units;
  1656. }
  1657. SpellID CBattleInfoCallback::getRandomBeneficialSpell(vstd::RNG & rand, const battle::Unit * caster, const battle::Unit * subject) const
  1658. {
  1659. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1660. //This is complete list. No spells from mods.
  1661. //todo: this should be Spellbook of caster Stack
  1662. static const std::set<SpellID> allPossibleSpells =
  1663. {
  1664. SpellID::AIR_SHIELD,
  1665. SpellID::ANTI_MAGIC,
  1666. SpellID::BLESS,
  1667. SpellID::BLOODLUST,
  1668. SpellID::COUNTERSTRIKE,
  1669. SpellID::CURE,
  1670. SpellID::FIRE_SHIELD,
  1671. SpellID::FORTUNE,
  1672. SpellID::HASTE,
  1673. SpellID::MAGIC_MIRROR,
  1674. SpellID::MIRTH,
  1675. SpellID::PRAYER,
  1676. SpellID::PRECISION,
  1677. SpellID::PROTECTION_FROM_AIR,
  1678. SpellID::PROTECTION_FROM_EARTH,
  1679. SpellID::PROTECTION_FROM_FIRE,
  1680. SpellID::PROTECTION_FROM_WATER,
  1681. SpellID::SHIELD,
  1682. SpellID::SLAYER,
  1683. SpellID::STONE_SKIN
  1684. };
  1685. std::vector<SpellID> beneficialSpells;
  1686. auto getAliveEnemy = [&](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1687. {
  1688. auto stacks = battleGetStacksIf([&](const CStack * stack)
  1689. {
  1690. return pred(stack) && stack->unitOwner() != subject->unitOwner() && stack->isValidTarget(false);
  1691. });
  1692. if(stacks.empty())
  1693. return nullptr;
  1694. else
  1695. return stacks.front();
  1696. };
  1697. for(const SpellID& spellID : allPossibleSpells)
  1698. {
  1699. std::stringstream cachingStr;
  1700. cachingStr << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT) << "id_" << spellID.num;
  1701. if(subject->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(spellID)), cachingStr.str()))
  1702. continue;
  1703. auto spellPtr = spellID.toSpell();
  1704. spells::Target target;
  1705. target.emplace_back(subject);
  1706. spells::BattleCast cast(this, caster, spells::Mode::CREATURE_ACTIVE, spellPtr);
  1707. auto m = spellPtr->battleMechanics(&cast);
  1708. if (!m->canBeCastAt(target))
  1709. continue;
  1710. switch (spellID.toEnum())
  1711. {
  1712. case SpellID::SHIELD:
  1713. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1714. {
  1715. const auto * walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1716. {
  1717. return !stack->canShoot();
  1718. });
  1719. if(!walker)
  1720. continue;
  1721. }
  1722. break;
  1723. case SpellID::AIR_SHIELD: //only against active shooters
  1724. {
  1725. const auto * shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1726. {
  1727. return stack->canShoot();
  1728. });
  1729. if(!shooter)
  1730. continue;
  1731. }
  1732. break;
  1733. case SpellID::ANTI_MAGIC:
  1734. case SpellID::MAGIC_MIRROR:
  1735. case SpellID::PROTECTION_FROM_AIR:
  1736. case SpellID::PROTECTION_FROM_EARTH:
  1737. case SpellID::PROTECTION_FROM_FIRE:
  1738. case SpellID::PROTECTION_FROM_WATER:
  1739. {
  1740. const BattleSide enemySide = otherSide(subject->unitSide());
  1741. //todo: only if enemy has spellbook
  1742. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1743. continue;
  1744. }
  1745. break;
  1746. case SpellID::CURE: //only damaged units
  1747. {
  1748. //do not cast on affected by debuffs
  1749. if(subject->getFirstHPleft() == subject->getMaxHealth())
  1750. continue;
  1751. }
  1752. break;
  1753. case SpellID::BLOODLUST:
  1754. {
  1755. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1756. continue;
  1757. }
  1758. break;
  1759. case SpellID::PRECISION:
  1760. {
  1761. if(!subject->canShoot())
  1762. continue;
  1763. }
  1764. break;
  1765. case SpellID::SLAYER://only if monsters are present
  1766. {
  1767. const auto * kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1768. {
  1769. return stack->hasBonusOfType(BonusType::KING);
  1770. });
  1771. if (!kingMonster)
  1772. continue;
  1773. }
  1774. break;
  1775. }
  1776. beneficialSpells.push_back(spellID);
  1777. }
  1778. if(!beneficialSpells.empty())
  1779. {
  1780. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1781. }
  1782. else
  1783. {
  1784. return SpellID::NONE;
  1785. }
  1786. }
  1787. SpellID CBattleInfoCallback::getRandomCastedSpell(vstd::RNG & rand, const CStack * caster) const
  1788. {
  1789. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1790. TConstBonusListPtr bl = caster->getBonusesOfType(BonusType::SPELLCASTER);
  1791. if(bl->empty())
  1792. return SpellID::NONE;
  1793. std::vector<int> weights;
  1794. //spells with 0 weight are non-random, exclude them
  1795. for(const auto & b : *bl)
  1796. {
  1797. if(b->parameters && b->parameters->toNumber() > 0)
  1798. weights.push_back(b->parameters->toNumber());
  1799. else
  1800. weights.push_back(0);
  1801. }
  1802. int64_t itemIndex = RandomGeneratorUtil::nextItemWeighted(weights, rand);
  1803. if(itemIndex < 0)
  1804. return SpellID::NONE;
  1805. auto result = *(bl->begin() + itemIndex);
  1806. return result->subtype.as<SpellID>();
  1807. }
  1808. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1809. {
  1810. RETURN_IF_NOT_BATTLE(-3);
  1811. if(!battleCanSurrender(Player))
  1812. return -1;
  1813. const BattleSide side = playerToSide(Player);
  1814. if(side == BattleSide::NONE)
  1815. return -1;
  1816. int ret = 0;
  1817. double discount = 0;
  1818. for(const auto * unit : battleAliveUnits(side))
  1819. ret += unit->getRawSurrenderCost();
  1820. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1821. discount += h->valOfBonuses(BonusType::SURRENDER_DISCOUNT);
  1822. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1823. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1824. return ret;
  1825. }
  1826. si8 CBattleInfoCallback::battleMinSpellLevel(BattleSide side) const
  1827. {
  1828. const IBonusBearer * node = nullptr;
  1829. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1830. node = h;
  1831. else
  1832. node = getBonusBearer();
  1833. if(!node)
  1834. return 0;
  1835. auto b = node->getBonusesOfType(BonusType::BLOCK_MAGIC_BELOW);
  1836. if(b->size())
  1837. return b->totalValue();
  1838. return 0;
  1839. }
  1840. si8 CBattleInfoCallback::battleMaxSpellLevel(BattleSide side) const
  1841. {
  1842. const IBonusBearer *node = nullptr;
  1843. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1844. node = h;
  1845. else
  1846. node = getBonusBearer();
  1847. if(!node)
  1848. return GameConstants::SPELL_LEVELS;
  1849. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1850. auto b = node->getBonusesOfType(BonusType::BLOCK_MAGIC_ABOVE);
  1851. if(b->size())
  1852. return b->totalValue();
  1853. return GameConstants::SPELL_LEVELS;
  1854. }
  1855. std::optional<BattleSide> CBattleInfoCallback::battleIsFinished() const
  1856. {
  1857. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1858. {
  1859. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(BonusType::SIEGE_WEAPON);
  1860. });
  1861. BattleSideArray<bool> hasUnit = {false, false}; //index is BattleSide
  1862. for(auto & unit : units)
  1863. {
  1864. //todo: move SIEGE_WEAPON check to Unit state
  1865. hasUnit.at(unit->unitSide()) = true;
  1866. if(hasUnit[BattleSide::ATTACKER] && hasUnit[BattleSide::DEFENDER])
  1867. return std::nullopt;
  1868. }
  1869. hasUnit = {false, false};
  1870. for(auto & unit : units)
  1871. {
  1872. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1873. {
  1874. hasUnit.at(unit->unitSide()) = true;
  1875. }
  1876. }
  1877. if(!hasUnit[BattleSide::ATTACKER] && !hasUnit[BattleSide::DEFENDER])
  1878. return BattleSide::NONE;
  1879. if(!hasUnit[BattleSide::DEFENDER])
  1880. return BattleSide::ATTACKER;
  1881. else
  1882. return BattleSide::DEFENDER;
  1883. }
  1884. VCMI_LIB_NAMESPACE_END