CBattleInfoCallback.cpp 62 KB

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