CBattleInfoCallback.cpp 62 KB

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