CBattleInfoCallback.cpp 59 KB

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