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