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