CBattleInfoCallback.cpp 59 KB

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