CBattleInfoCallback.cpp 62 KB

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