CBattleInfoCallback.cpp 58 KB

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