CBattleInfoCallback.cpp 59 KB

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