CBattleInfoCallback.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. /*
  2. * CBattleInfoCallback.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CBattleInfoCallback.h"
  12. #include <vcmi/scripting/Service.h>
  13. #include <vstd/RNG.h>
  14. #include "../CStack.h"
  15. #include "BattleInfo.h"
  16. #include "CObstacleInstance.h"
  17. #include "DamageCalculator.h"
  18. #include "IGameSettings.h"
  19. #include "PossiblePlayerBattleAction.h"
  20. #include "../entities/building/TownFortifications.h"
  21. #include "../spells/ObstacleCasterProxy.h"
  22. #include "../spells/ISpellMechanics.h"
  23. #include "../spells/Problem.h"
  24. #include "../spells/CSpellHandler.h"
  25. #include "../mapObjects/CGTownInstance.h"
  26. #include "../networkPacks/PacksForClientBattle.h"
  27. #include "../BattleFieldHandler.h"
  28. #include "../Rect.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  31. {
  32. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  33. {
  34. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 96, 112, 130, 147, 165, 182};
  35. return lineToHex[line];
  36. }
  37. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  38. {
  39. const int wallInStackLine = lineToWallHex(pos1.getY());
  40. const int wallInDestLine = lineToWallHex(pos2.getY());
  41. const bool stackLeft = pos1 < wallInStackLine;
  42. const bool destLeft = pos2 < wallInDestLine;
  43. return stackLeft == destLeft;
  44. }
  45. static bool isInsideWalls(BattleHex pos)
  46. {
  47. const int wallInStackLine = lineToWallHex(pos.getY());
  48. return wallInStackLine < pos;
  49. }
  50. // parts of wall
  51. static const std::pair<int, EWallPart> wallParts[] =
  52. {
  53. std::make_pair(50, EWallPart::KEEP),
  54. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  55. std::make_pair(182, EWallPart::BOTTOM_WALL),
  56. std::make_pair(130, EWallPart::BELOW_GATE),
  57. std::make_pair(78, EWallPart::OVER_GATE),
  58. std::make_pair(29, EWallPart::UPPER_WALL),
  59. std::make_pair(12, EWallPart::UPPER_TOWER),
  60. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  61. std::make_pair(96, EWallPart::GATE),
  62. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  63. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  64. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  65. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  66. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  67. };
  68. static EWallPart hexToWallPart(BattleHex hex)
  69. {
  70. for(const auto & elem : wallParts)
  71. {
  72. if(elem.first == hex)
  73. return elem.second;
  74. }
  75. return EWallPart::INVALID; //not found!
  76. }
  77. static BattleHex WallPartToHex(EWallPart part)
  78. {
  79. for(const auto & elem : wallParts)
  80. {
  81. if(elem.second == part)
  82. return elem.first;
  83. }
  84. return BattleHex::INVALID; //not found!
  85. }
  86. }
  87. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  88. ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  89. {
  90. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  91. if(caster == nullptr)
  92. {
  93. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  94. return ESpellCastProblem::INVALID;
  95. }
  96. const PlayerColor player = caster->getCasterOwner();
  97. const auto side = playerToSide(player);
  98. if(side == BattleSide::NONE)
  99. return ESpellCastProblem::INVALID;
  100. if(!battleDoWeKnowAbout(side))
  101. {
  102. logGlobal->warn("You can't check if enemy can cast given spell!");
  103. return ESpellCastProblem::INVALID;
  104. }
  105. if(battleTacticDist())
  106. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  107. switch(mode)
  108. {
  109. case spells::Mode::HERO:
  110. {
  111. if(battleCastSpells(side) > 0)
  112. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  113. const auto * hero = dynamic_cast<const CGHeroInstance *>(caster);
  114. if(!hero)
  115. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  116. if(hero->hasBonusOfType(BonusType::BLOCK_ALL_MAGIC))
  117. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  118. if(!hero->hasSpellbook())
  119. return ESpellCastProblem::NO_SPELLBOOK;
  120. }
  121. break;
  122. default:
  123. break;
  124. }
  125. return ESpellCastProblem::OK;
  126. }
  127. std::pair< BattleHexArray, int > CBattleInfoCallback::getPath(BattleHex start, BattleHex dest, const battle::Unit * stack) const
  128. {
  129. auto reachability = getReachability(stack);
  130. if(reachability.predecessors[dest] == -1) //cannot reach destination
  131. {
  132. return std::make_pair(BattleHexArray(), 0);
  133. }
  134. //making the Path
  135. BattleHexArray path;
  136. BattleHex curElem = dest;
  137. while(curElem != start)
  138. {
  139. path.insert(curElem);
  140. curElem = reachability.predecessors[curElem];
  141. }
  142. return std::make_pair(path, reachability.distances[dest]);
  143. }
  144. bool CBattleInfoCallback::battleIsInsideWalls(BattleHex from) const
  145. {
  146. return isInsideWalls(from);
  147. }
  148. bool CBattleInfoCallback::battleHasPenaltyOnLine(BattleHex from, BattleHex dest, bool checkWall, bool checkMoat) const
  149. {
  150. if (!from.isAvailable() || !dest.isAvailable())
  151. throw std::runtime_error("Invalid hex (" + std::to_string(from) + " and " + std::to_string(dest) + ") received in battleHasPenaltyOnLine!" );
  152. auto isTileBlocked = [&](BattleHex tile)
  153. {
  154. EWallPart wallPart = battleHexToWallPart(tile);
  155. if (wallPart == EWallPart::INVALID)
  156. return false; // there is no wall here
  157. if (wallPart == EWallPart::INDESTRUCTIBLE_PART_OF_GATE)
  158. return false; // does not blocks ranged attacks
  159. if (wallPart == EWallPart::INDESTRUCTIBLE_PART)
  160. return true; // always blocks ranged attacks
  161. return isWallPartAttackable(wallPart);
  162. };
  163. // Count wall penalty requirement by shortest path, not by arbitrary line, to avoid various OH3 bugs
  164. auto getShortestPath = [](BattleHex from, BattleHex dest) -> BattleHexArray
  165. {
  166. //Out early
  167. if(from == dest)
  168. return {};
  169. BattleHexArray ret;
  170. auto next = from;
  171. //Not a real direction, only to indicate to which side we should search closest tile
  172. auto direction = from.getX() > dest.getX() ? BattleSide::DEFENDER : BattleSide::ATTACKER;
  173. while (next != dest)
  174. {
  175. next = BattleHex::getClosestTile(next.getNeighbouringTiles(), direction, dest);
  176. ret.insert(next);
  177. }
  178. assert(!ret.empty());
  179. ret.pop_back(); //Remove destination hex
  180. return ret;
  181. };
  182. RETURN_IF_NOT_BATTLE(false);
  183. auto checkNeeded = !sameSideOfWall(from, dest);
  184. bool pathHasWall = false;
  185. bool pathHasMoat = false;
  186. for(const auto & hex : getShortestPath(from, dest))
  187. {
  188. pathHasWall |= isTileBlocked(hex);
  189. if(!checkMoat)
  190. continue;
  191. auto obstacles = battleGetAllObstaclesOnPos(hex, false);
  192. if(hex != BattleHex::GATE_BRIDGE || (battleIsGatePassable()))
  193. for(const auto & obst : obstacles)
  194. if(obst->obstacleType == CObstacleInstance::MOAT)
  195. pathHasMoat |= true;
  196. }
  197. return checkNeeded && ( (checkWall && pathHasWall) || (checkMoat && pathHasMoat) );
  198. }
  199. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  200. {
  201. RETURN_IF_NOT_BATTLE(false);
  202. if(battleGetFortifications().wallsHealth == 0)
  203. return false;
  204. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  205. static const auto selectorNoWallPenalty = Selector::type()(BonusType::NO_WALL_PENALTY);
  206. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  207. return false;
  208. const auto shooterOutsideWalls = shooterPosition < lineToWallHex(shooterPosition.getY());
  209. return shooterOutsideWalls && battleHasPenaltyOnLine(shooterPosition, destHex, true, false);
  210. }
  211. std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsForStack(const CStack * stack, const BattleClientInterfaceData & data)
  212. {
  213. RETURN_IF_NOT_BATTLE(std::vector<PossiblePlayerBattleAction>());
  214. std::vector<PossiblePlayerBattleAction> allowedActionList;
  215. if(data.tacticsMode) //would "if(battleGetTacticDist() > 0)" work?
  216. {
  217. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_TACTICS);
  218. allowedActionList.push_back(PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK);
  219. }
  220. else
  221. {
  222. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  223. {
  224. if(stack->hasBonusOfType(BonusType::SPELLCASTER))
  225. {
  226. for(const auto & spellID : data.creatureSpellsToCast)
  227. {
  228. const CSpell *spell = spellID.toSpell();
  229. PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
  230. allowedActionList.push_back(act);
  231. }
  232. }
  233. if(stack->hasBonusOfType(BonusType::RANDOM_SPELLCASTER))
  234. allowedActionList.push_back(PossiblePlayerBattleAction::RANDOM_GENIE_SPELL);
  235. }
  236. if(stack->canShoot())
  237. allowedActionList.push_back(PossiblePlayerBattleAction::SHOOT);
  238. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE))
  239. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK_AND_RETURN);
  240. allowedActionList.push_back(PossiblePlayerBattleAction::ATTACK); //all active stacks can attack
  241. allowedActionList.push_back(PossiblePlayerBattleAction::WALK_AND_ATTACK); //not all stacks can always walk, but we will check this elsewhere
  242. if(stack->canMove() && stack->getMovementRange(0)) //probably no reason to try move war machines or bound stacks
  243. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_STACK);
  244. const auto * siegedTown = battleGetDefendedTown();
  245. if(siegedTown && siegedTown->fortificationsLevel().wallsHealth > 0 && stack->hasBonusOfType(BonusType::CATAPULT)) //TODO: check shots
  246. allowedActionList.push_back(PossiblePlayerBattleAction::CATAPULT);
  247. if(stack->hasBonusOfType(BonusType::HEALER))
  248. allowedActionList.push_back(PossiblePlayerBattleAction::HEAL);
  249. }
  250. return allowedActionList;
  251. }
  252. PossiblePlayerBattleAction CBattleInfoCallback::getCasterAction(const CSpell * spell, const spells::Caster * caster, spells::Mode mode) const
  253. {
  254. RETURN_IF_NOT_BATTLE(PossiblePlayerBattleAction::INVALID);
  255. auto spellSelMode = PossiblePlayerBattleAction::ANY_LOCATION;
  256. const CSpell::TargetInfo ti(spell, caster->getSpellSchoolLevel(spell), mode);
  257. if(ti.massive || ti.type == spells::AimType::NO_TARGET)
  258. spellSelMode = PossiblePlayerBattleAction::NO_LOCATION;
  259. else if(ti.type == spells::AimType::LOCATION && ti.clearAffected)
  260. spellSelMode = PossiblePlayerBattleAction::FREE_LOCATION;
  261. else if(ti.type == spells::AimType::CREATURE)
  262. spellSelMode = PossiblePlayerBattleAction::AIMED_SPELL_CREATURE;
  263. else if(ti.type == spells::AimType::OBSTACLE)
  264. spellSelMode = PossiblePlayerBattleAction::OBSTACLE;
  265. return PossiblePlayerBattleAction(spellSelMode, spell->id);
  266. }
  267. BattleHexArray CBattleInfoCallback::battleGetAttackedHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  268. {
  269. BattleHexArray attackedHexes;
  270. RETURN_IF_NOT_BATTLE(attackedHexes);
  271. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  272. for (BattleHex tile : at.hostileCreaturePositions)
  273. {
  274. const auto * st = battleGetUnitByPos(tile, true);
  275. if(st && st->unitOwner() != attacker->unitOwner()) //only hostile stacks - does it work well with Berserk?
  276. {
  277. attackedHexes.insert(tile);
  278. }
  279. }
  280. for (BattleHex tile : at.friendlyCreaturePositions)
  281. {
  282. if(battleGetUnitByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  283. {
  284. attackedHexes.insert(tile);
  285. }
  286. }
  287. return attackedHexes;
  288. }
  289. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  290. {
  291. RETURN_IF_NOT_BATTLE(nullptr);
  292. for(const auto * s : battleGetAllStacks(true))
  293. if(s->getHexes().contains(pos) && (!onlyAlive || s->alive()))
  294. return s;
  295. return nullptr;
  296. }
  297. const battle::Unit * CBattleInfoCallback::battleGetUnitByPos(BattleHex pos, bool onlyAlive) const
  298. {
  299. RETURN_IF_NOT_BATTLE(nullptr);
  300. auto ret = battleGetUnitsIf([=](const battle::Unit * unit)
  301. {
  302. return !unit->isGhost()
  303. && unit->coversPos(pos)
  304. && (!onlyAlive || unit->alive());
  305. });
  306. if(!ret.empty())
  307. return ret.front();
  308. else
  309. return nullptr;
  310. }
  311. battle::Units CBattleInfoCallback::battleAliveUnits() const
  312. {
  313. return battleGetUnitsIf([](const battle::Unit * unit)
  314. {
  315. return unit->isValidTarget(false);
  316. });
  317. }
  318. battle::Units CBattleInfoCallback::battleAliveUnits(BattleSide side) const
  319. {
  320. return battleGetUnitsIf([=](const battle::Unit * unit)
  321. {
  322. return unit->isValidTarget(false) && unit->unitSide() == side;
  323. });
  324. }
  325. using namespace battle;
  326. //T is battle::Unit descendant
  327. template <typename T>
  328. const T * takeOneUnit(std::vector<const T*> & allUnits, const int turn, BattleSide & sideThatLastMoved, int phase)
  329. {
  330. const T * returnedUnit = nullptr;
  331. size_t currentUnitIndex = 0;
  332. for(size_t i = 0; i < allUnits.size(); i++)
  333. {
  334. int32_t currentUnitInitiative = -1;
  335. int32_t returnedUnitInitiative = -1;
  336. if(returnedUnit)
  337. returnedUnitInitiative = returnedUnit->getInitiative(turn);
  338. if(!allUnits[i])
  339. continue;
  340. auto currentUnit = allUnits[i];
  341. currentUnitInitiative = currentUnit->getInitiative(turn);
  342. switch(phase)
  343. {
  344. case BattlePhases::NORMAL: // Faster first, attacker priority, higher slot first
  345. if(returnedUnit == nullptr || currentUnitInitiative > returnedUnitInitiative)
  346. {
  347. returnedUnit = currentUnit;
  348. currentUnitIndex = i;
  349. }
  350. else if(currentUnitInitiative == returnedUnitInitiative)
  351. {
  352. if(sideThatLastMoved == BattleSide::NONE && turn <= 0 && currentUnit->unitSide() == BattleSide::ATTACKER
  353. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Turn 0 attacker priority
  354. {
  355. returnedUnit = currentUnit;
  356. currentUnitIndex = i;
  357. }
  358. else if(sideThatLastMoved != BattleSide::NONE && currentUnit->unitSide() != sideThatLastMoved
  359. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  360. {
  361. returnedUnit = currentUnit;
  362. currentUnitIndex = i;
  363. }
  364. }
  365. break;
  366. case BattlePhases::WAIT_MORALE: // Slower first, higher slot first
  367. case BattlePhases::WAIT:
  368. if(returnedUnit == nullptr || currentUnitInitiative < returnedUnitInitiative)
  369. {
  370. returnedUnit = currentUnit;
  371. currentUnitIndex = i;
  372. }
  373. else if(currentUnitInitiative == returnedUnitInitiative && sideThatLastMoved != BattleSide::NONE && currentUnit->unitSide() != sideThatLastMoved
  374. && !(returnedUnit->unitSide() == currentUnit->unitSide() && returnedUnit->unitSlot() < currentUnit->unitSlot())) // Alternate equal speeds units
  375. {
  376. returnedUnit = currentUnit;
  377. currentUnitIndex = i;
  378. }
  379. break;
  380. default:
  381. break;
  382. }
  383. }
  384. if(!returnedUnit)
  385. return nullptr;
  386. allUnits[currentUnitIndex] = nullptr;
  387. return returnedUnit;
  388. }
  389. void CBattleInfoCallback::battleGetTurnOrder(std::vector<battle::Units> & turns, const size_t maxUnits, const int maxTurns, const int turn, BattleSide sideThatLastMoved) const
  390. {
  391. RETURN_IF_NOT_BATTLE();
  392. if(maxUnits == 0 && maxTurns == 0)
  393. {
  394. logGlobal->error("Attempt to get infinite battle queue");
  395. return;
  396. }
  397. auto actualTurn = turn > 0 ? turn : 0;
  398. auto turnsIsFull = [&]() -> bool
  399. {
  400. if(maxUnits == 0)
  401. return false;//no limit
  402. size_t turnsSize = 0;
  403. for(const auto & oneTurn : turns)
  404. turnsSize += oneTurn.size();
  405. return turnsSize >= maxUnits;
  406. };
  407. turns.emplace_back();
  408. // We'll split creatures with remaining movement to 4 buckets (SIEGE, NORMAL, WAIT_MORALE, WAIT)
  409. std::array<battle::Units, BattlePhases::NUMBER_OF_PHASES> phases; // Access using BattlePhases enum
  410. const battle::Unit * activeUnit = battleActiveUnit();
  411. if(activeUnit)
  412. {
  413. //its first turn and active unit hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  414. if(turn == 0 && activeUnit->willMove())
  415. {
  416. turns.back().push_back(activeUnit);
  417. if(turnsIsFull())
  418. return;
  419. }
  420. //its first or current turn, turn priority for active stack side
  421. //TODO: what if active stack mind-controlled?
  422. if(turn <= 0 && sideThatLastMoved == BattleSide::NONE)
  423. sideThatLastMoved = activeUnit->unitSide();
  424. }
  425. auto allUnits = battleGetUnitsIf([](const battle::Unit * unit)
  426. {
  427. return !unit->isGhost();
  428. });
  429. // If no unit will be EVER! able to move, battle is over.
  430. if(!vstd::contains_if(allUnits, [](const battle::Unit * unit) { return unit->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  431. {
  432. turns.clear();
  433. return;
  434. }
  435. for(const auto * unit : allUnits)
  436. {
  437. if((actualTurn == 0 && !unit->willMove()) //we are considering current round and unit won't move
  438. || (actualTurn > 0 && !unit->canMove(turn)) //unit won't be able to move in later rounds
  439. || (actualTurn == 0 && unit == activeUnit && !turns.at(0).empty() && unit == turns.front().front())) //it's active unit already added at the beginning of queue
  440. {
  441. continue;
  442. }
  443. int unitPhase = unit->battleQueuePhase(turn);
  444. phases[unitPhase].push_back(unit);
  445. }
  446. boost::sort(phases[BattlePhases::SIEGE], CMP_stack(BattlePhases::SIEGE, actualTurn, sideThatLastMoved));
  447. std::copy(phases[BattlePhases::SIEGE].begin(), phases[BattlePhases::SIEGE].end(), std::back_inserter(turns.back()));
  448. if(turnsIsFull())
  449. return;
  450. for(uint8_t phase = BattlePhases::NORMAL; phase < BattlePhases::NUMBER_OF_PHASES; phase++)
  451. boost::sort(phases[phase], CMP_stack(phase, actualTurn, sideThatLastMoved));
  452. uint8_t phase = BattlePhases::NORMAL;
  453. while(!turnsIsFull() && phase < BattlePhases::NUMBER_OF_PHASES)
  454. {
  455. const battle::Unit * currentUnit = nullptr;
  456. if(phases[phase].empty())
  457. phase++;
  458. else
  459. {
  460. currentUnit = takeOneUnit(phases[phase], actualTurn, sideThatLastMoved, phase);
  461. if(!currentUnit)
  462. {
  463. phase++;
  464. }
  465. else
  466. {
  467. turns.back().push_back(currentUnit);
  468. sideThatLastMoved = currentUnit->unitSide();
  469. }
  470. }
  471. }
  472. if(sideThatLastMoved == BattleSide::NONE)
  473. sideThatLastMoved = BattleSide::ATTACKER;
  474. if(!turnsIsFull() && (maxTurns == 0 || turns.size() < maxTurns))
  475. battleGetTurnOrder(turns, maxUnits, maxTurns, actualTurn + 1, sideThatLastMoved);
  476. }
  477. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange) const
  478. {
  479. RETURN_IF_NOT_BATTLE(BattleHexArray());
  480. if(!unit->getPosition().isValid()) //turrets
  481. return BattleHexArray();
  482. auto reachability = getReachability(unit);
  483. return battleGetAvailableHexes(reachability, unit, obtainMovementRange);
  484. }
  485. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const ReachabilityInfo & cache, const battle::Unit * unit, bool obtainMovementRange) const
  486. {
  487. BattleHexArray ret;
  488. RETURN_IF_NOT_BATTLE(ret);
  489. if(!unit->getPosition().isValid()) //turrets
  490. return ret;
  491. auto unitSpeed = unit->getMovementRange(0);
  492. const bool tacticsPhase = battleTacticDist() && battleGetTacticsSide() == unit->unitSide();
  493. for(int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  494. {
  495. // If obstacles or other stacks makes movement impossible, it can't be helped.
  496. if(!cache.isReachable(i))
  497. continue;
  498. if(tacticsPhase && !obtainMovementRange) // if obtainMovementRange requested do not return tactics range
  499. {
  500. // Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  501. if(!isInTacticRange(i))
  502. continue;
  503. }
  504. else
  505. {
  506. // Not tactics phase -> destination must be reachable and within unit range.
  507. if(cache.distances[i] > static_cast<int>(unitSpeed))
  508. continue;
  509. }
  510. ret.insert(i);
  511. }
  512. return ret;
  513. }
  514. BattleHexArray CBattleInfoCallback::battleGetAvailableHexes(const battle::Unit * unit, bool obtainMovementRange, bool addOccupiable, BattleHexArray * attackable) const
  515. {
  516. BattleHexArray ret = battleGetAvailableHexes(unit, obtainMovementRange);
  517. if(ret.empty())
  518. return ret;
  519. if(addOccupiable && unit->doubleWide())
  520. {
  521. BattleHexArray occupiable;
  522. for(auto hex : ret)
  523. occupiable.insert(unit->occupiedHex(hex));
  524. ret.insert(occupiable);
  525. }
  526. if(attackable)
  527. {
  528. auto meleeAttackable = [&](BattleHex hex) -> bool
  529. {
  530. // Return true if given hex has at least one available neighbour.
  531. // Available hexes are already present in ret vector.
  532. auto availableNeighbour = boost::find_if(ret, [=] (BattleHex availableHex)
  533. {
  534. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  535. });
  536. return availableNeighbour != ret.end();
  537. };
  538. for(const auto * otherSt : battleAliveUnits(otherSide(unit->unitSide())))
  539. {
  540. if(!otherSt->isValidTarget(false))
  541. continue;
  542. const BattleHexArray & occupied = otherSt->getHexes();
  543. if(battleCanShoot(unit, otherSt->getPosition()))
  544. {
  545. attackable->insert(occupied);
  546. continue;
  547. }
  548. for(BattleHex he : occupied)
  549. {
  550. if(meleeAttackable(he))
  551. attackable->insert(he);
  552. }
  553. }
  554. }
  555. return ret;
  556. }
  557. bool CBattleInfoCallback::battleCanAttack(const battle::Unit * stack, const battle::Unit * target, BattleHex dest) const
  558. {
  559. RETURN_IF_NOT_BATTLE(false);
  560. if(battleTacticDist())
  561. return false;
  562. if (!stack || !target)
  563. return false;
  564. if(target->hasBonusOfType(BonusType::INVINCIBLE))
  565. return false;
  566. if(!battleMatchOwner(stack, target))
  567. return false;
  568. auto id = stack->unitType()->getId();
  569. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  570. return false;
  571. return target->alive();
  572. }
  573. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker) const
  574. {
  575. RETURN_IF_NOT_BATTLE(false);
  576. if(battleTacticDist()) //no shooting during tactics
  577. return false;
  578. if (!attacker)
  579. return false;
  580. if (attacker->creatureIndex() == CreatureID::CATAPULT) //catapult cannot attack creatures
  581. return false;
  582. if (!attacker->canShoot())
  583. return false;
  584. return attacker->canShootBlocked() || !battleIsUnitBlocked(attacker);
  585. }
  586. bool CBattleInfoCallback::battleCanTargetEmptyHex(const battle::Unit * attacker) const
  587. {
  588. RETURN_IF_NOT_BATTLE(false);
  589. if(!VLC->engineSettings()->getBoolean(EGameSettings::COMBAT_AREA_SHOT_CAN_TARGET_EMPTY_HEX))
  590. return false;
  591. if(attacker->hasBonusOfType(BonusType::SPELL_LIKE_ATTACK))
  592. {
  593. auto bonus = attacker->getBonus(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  594. const CSpell * spell = bonus->subtype.as<SpellID>().toSpell();
  595. spells::BattleCast cast(this, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  596. BattleHex dummySpellTarget = BattleHex(50); //check arbitrary hex for general spell range since currently there is no general way to access amount of hexes
  597. if(spell->battleMechanics(&cast)->rangeInHexes(dummySpellTarget).size() > 1)
  598. {
  599. return true;
  600. }
  601. }
  602. return false;
  603. }
  604. bool CBattleInfoCallback::battleCanShoot(const battle::Unit * attacker, BattleHex dest) const
  605. {
  606. RETURN_IF_NOT_BATTLE(false);
  607. const battle::Unit * defender = battleGetUnitByPos(dest);
  608. if(!attacker)
  609. return false;
  610. bool emptyHexAreaAttack = battleCanTargetEmptyHex(attacker);
  611. if(!emptyHexAreaAttack)
  612. {
  613. if(!defender)
  614. return false;
  615. if(defender->hasBonusOfType(BonusType::INVINCIBLE))
  616. return false;
  617. }
  618. if(emptyHexAreaAttack || (battleMatchOwner(attacker, defender) && defender->alive()))
  619. {
  620. if(battleCanShoot(attacker))
  621. {
  622. auto limitedRangeBonus = attacker->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  623. if(limitedRangeBonus == nullptr)
  624. {
  625. return true;
  626. }
  627. int shootingRange = limitedRangeBonus->val;
  628. if(defender)
  629. return isEnemyUnitWithinSpecifiedRange(attacker->getPosition(), defender, shootingRange);
  630. else
  631. return isHexWithinSpecifiedRange(attacker->getPosition(), dest, shootingRange);
  632. }
  633. }
  634. return false;
  635. }
  636. DamageEstimation CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  637. {
  638. DamageCalculator calculator(*this, info);
  639. return calculator.calculateDmgRange();
  640. }
  641. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPosition, DamageEstimation * retaliationDmg) const
  642. {
  643. RETURN_IF_NOT_BATTLE({});
  644. auto reachability = battleGetDistances(attacker, attacker->getPosition());
  645. int movementRange = attackerPosition.isValid() ? reachability[attackerPosition] : 0;
  646. return battleEstimateDamage(attacker, defender, movementRange, retaliationDmg);
  647. }
  648. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const battle::Unit * attacker, const battle::Unit * defender, int movementRange, DamageEstimation * retaliationDmg) const
  649. {
  650. RETURN_IF_NOT_BATTLE({});
  651. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  652. const BattleAttackInfo bai(attacker, defender, movementRange, shooting);
  653. return battleEstimateDamage(bai, retaliationDmg);
  654. }
  655. DamageEstimation CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, DamageEstimation * retaliationDmg) const
  656. {
  657. RETURN_IF_NOT_BATTLE({});
  658. DamageEstimation ret = calculateDmgRange(bai);
  659. if(retaliationDmg == nullptr)
  660. return ret;
  661. *retaliationDmg = DamageEstimation();
  662. if(bai.shooting) //FIXME: handle RANGED_RETALIATION
  663. return ret;
  664. if (!bai.defender->ableToRetaliate())
  665. return ret;
  666. if (bai.attacker->hasBonusOfType(BonusType::BLOCKS_RETALIATION) || bai.attacker->hasBonusOfType(BonusType::INVINCIBLE))
  667. return ret;
  668. //TODO: rewrite using boost::numeric::interval
  669. //TODO: rewire once more using interval-based fuzzy arithmetic
  670. const auto & estimateRetaliation = [&](int64_t damage)
  671. {
  672. auto retaliationAttack = bai.reverse();
  673. auto state = retaliationAttack.attacker->acquireState();
  674. state->damage(damage);
  675. retaliationAttack.attacker = state.get();
  676. if (state->alive())
  677. return calculateDmgRange(retaliationAttack);
  678. else
  679. return DamageEstimation();
  680. };
  681. DamageEstimation retaliationMin = estimateRetaliation(ret.damage.min);
  682. DamageEstimation retaliationMax = estimateRetaliation(ret.damage.max);
  683. retaliationDmg->damage.min = std::min(retaliationMin.damage.min, retaliationMax.damage.min);
  684. retaliationDmg->damage.max = std::max(retaliationMin.damage.max, retaliationMax.damage.max);
  685. retaliationDmg->kills.min = std::min(retaliationMin.kills.min, retaliationMax.kills.min);
  686. retaliationDmg->kills.max = std::max(retaliationMin.kills.max, retaliationMax.kills.max);
  687. return ret;
  688. }
  689. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  690. {
  691. auto obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  692. RETURN_IF_NOT_BATTLE(obstacles);
  693. for(auto & obs : battleGetAllObstacles())
  694. {
  695. if(obs->getBlockedTiles().contains(tile)
  696. || (!onlyBlocking && obs->getAffectedTiles().contains(tile)))
  697. {
  698. obstacles.push_back(obs);
  699. }
  700. }
  701. return obstacles;
  702. }
  703. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit, const BattleHexArray & passed) const
  704. {
  705. auto affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  706. RETURN_IF_NOT_BATTLE(affectedObstacles);
  707. if(unit->alive())
  708. {
  709. if(!passed.contains(unit->getPosition()))
  710. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  711. if(unit->doubleWide())
  712. {
  713. BattleHex otherHex = unit->occupiedHex();
  714. if(otherHex.isValid() && !passed.contains(otherHex))
  715. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  716. if(!vstd::contains(affectedObstacles, i))
  717. affectedObstacles.push_back(i);
  718. }
  719. for(auto hex : unit->getHexes())
  720. if(hex == BattleHex::GATE_BRIDGE && battleIsGatePassable())
  721. for(int i=0; i<affectedObstacles.size(); i++)
  722. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  723. affectedObstacles.erase(affectedObstacles.begin()+i);
  724. }
  725. return affectedObstacles;
  726. }
  727. bool CBattleInfoCallback::handleObstacleTriggersForUnit(SpellCastEnvironment & spellEnv, const battle::Unit & unit, const BattleHexArray & passed) const
  728. {
  729. if(!unit.alive())
  730. return false;
  731. bool movementStopped = false;
  732. for(auto & obstacle : getAllAffectedObstaclesByStack(&unit, passed))
  733. {
  734. //helper info
  735. const SpellCreatedObstacle * spellObstacle = dynamic_cast<const SpellCreatedObstacle *>(obstacle.get());
  736. if(spellObstacle)
  737. {
  738. auto revealObstacles = [&](const SpellCreatedObstacle & spellObstacle) -> void
  739. {
  740. // For the hidden spell created obstacles, e.g. QuickSand, it should be revealed after taking damage
  741. auto operation = ObstacleChanges::EOperation::UPDATE;
  742. if (spellObstacle.removeOnTrigger)
  743. operation = ObstacleChanges::EOperation::REMOVE;
  744. SpellCreatedObstacle changedObstacle;
  745. changedObstacle.uniqueID = spellObstacle.uniqueID;
  746. changedObstacle.revealed = true;
  747. BattleObstaclesChanged bocp;
  748. bocp.battleID = getBattle()->getBattleID();
  749. bocp.changes.emplace_back(spellObstacle.uniqueID, operation);
  750. changedObstacle.toInfo(bocp.changes.back(), operation);
  751. spellEnv.apply(bocp);
  752. };
  753. const auto side = unit.unitSide();
  754. auto shouldReveal = !spellObstacle->hidden || !battleIsObstacleVisibleForSide(*obstacle, side);
  755. const auto * hero = battleGetFightingHero(spellObstacle->casterSide);
  756. auto caster = spells::ObstacleCasterProxy(getBattle()->getSidePlayer(spellObstacle->casterSide), hero, *spellObstacle);
  757. if(obstacle->triggersEffects() && obstacle->getTrigger().hasValue())
  758. {
  759. const auto * sp = obstacle->getTrigger().toSpell();
  760. auto cast = spells::BattleCast(this, &caster, spells::Mode::PASSIVE, sp);
  761. spells::detail::ProblemImpl ignored;
  762. auto target = spells::Target(1, spells::Destination(&unit));
  763. if(sp->battleMechanics(&cast)->canBeCastAt(target, ignored)) // Obstacles should not be revealed by immune creatures
  764. {
  765. if(shouldReveal) { //hidden obstacle triggers effects after revealed
  766. revealObstacles(*spellObstacle);
  767. cast.cast(&spellEnv, target);
  768. }
  769. }
  770. }
  771. else if(shouldReveal)
  772. revealObstacles(*spellObstacle);
  773. }
  774. if(!unit.alive())
  775. return false;
  776. if(obstacle->stopsMovement())
  777. movementStopped = true;
  778. }
  779. return unit.alive() && !movementStopped;
  780. }
  781. AccessibilityInfo CBattleInfoCallback::getAccessibility() const
  782. {
  783. AccessibilityInfo ret;
  784. ret.fill(EAccessibility::ACCESSIBLE);
  785. //removing accessibility for side columns of hexes
  786. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  787. {
  788. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  789. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  790. }
  791. //special battlefields with logically unavailable tiles
  792. auto bFieldType = battleGetBattlefieldType();
  793. if(bFieldType != BattleField::NONE)
  794. {
  795. for(auto hex : bFieldType.getInfo()->impassableHexes)
  796. ret[hex] = EAccessibility::UNAVAILABLE;
  797. }
  798. //gate -> should be before stacks
  799. if(battleGetFortifications().wallsHealth > 0)
  800. {
  801. EAccessibility accessibility = EAccessibility::ACCESSIBLE;
  802. switch(battleGetGateState())
  803. {
  804. case EGateState::CLOSED:
  805. accessibility = EAccessibility::GATE;
  806. break;
  807. case EGateState::BLOCKED:
  808. accessibility = EAccessibility::UNAVAILABLE;
  809. break;
  810. }
  811. ret[BattleHex::GATE_OUTER] = ret[BattleHex::GATE_INNER] = accessibility;
  812. }
  813. //tiles occupied by standing stacks
  814. for(const auto * unit : battleAliveUnits())
  815. {
  816. for(auto hex : unit->getHexes())
  817. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  818. ret[hex] = EAccessibility::ALIVE_STACK;
  819. }
  820. //obstacles
  821. for(const auto &obst : battleGetAllObstacles())
  822. {
  823. for(auto hex : obst->getBlockedTiles())
  824. ret[hex] = EAccessibility::OBSTACLE;
  825. }
  826. //walls
  827. if(battleGetFortifications().wallsHealth > 0)
  828. {
  829. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  830. for(auto hex : permanentlyLocked)
  831. ret[hex] = EAccessibility::UNAVAILABLE;
  832. //TODO likely duplicated logic
  833. static const std::pair<EWallPart, BattleHex> lockedIfNotDestroyed[] =
  834. {
  835. //which part of wall, which hex is blocked if this part of wall is not destroyed
  836. std::make_pair(EWallPart::BOTTOM_WALL, BattleHex(BattleHex::DESTRUCTIBLE_WALL_4)),
  837. std::make_pair(EWallPart::BELOW_GATE, BattleHex(BattleHex::DESTRUCTIBLE_WALL_3)),
  838. std::make_pair(EWallPart::OVER_GATE, BattleHex(BattleHex::DESTRUCTIBLE_WALL_2)),
  839. std::make_pair(EWallPart::UPPER_WALL, BattleHex(BattleHex::DESTRUCTIBLE_WALL_1))
  840. };
  841. for(const auto & elem : lockedIfNotDestroyed)
  842. {
  843. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  844. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  845. }
  846. }
  847. return ret;
  848. }
  849. AccessibilityInfo CBattleInfoCallback::getAccessibility(const battle::Unit * stack) const
  850. {
  851. return getAccessibility(& battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  852. }
  853. AccessibilityInfo CBattleInfoCallback::getAccessibility(const BattleHexArray * accessibleHexes) const
  854. {
  855. auto ret = getAccessibility();
  856. for(auto hex : *accessibleHexes)
  857. if(hex.isValid())
  858. ret[hex] = EAccessibility::ACCESSIBLE;
  859. return ret;
  860. }
  861. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo & accessibility, const ReachabilityInfo::Parameters & params) const
  862. {
  863. ReachabilityInfo ret;
  864. ret.accessibility = accessibility;
  865. ret.params = params;
  866. ret.predecessors.fill(BattleHex::INVALID);
  867. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  868. if(!params.startPosition.isValid()) //if got call for arrow turrets
  869. return ret;
  870. const BattleHexArray obstacles = getStoppers(params.perspective);
  871. auto checkParams = params;
  872. checkParams.ignoreKnownAccessible = true; //Ignore starting hexes obstacles
  873. std::queue<BattleHex> hexq; //bfs queue
  874. //first element
  875. hexq.push(params.startPosition);
  876. ret.distances[params.startPosition] = 0;
  877. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache{};
  878. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  879. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  880. while(!hexq.empty()) //bfs loop
  881. {
  882. const BattleHex curHex = hexq.front();
  883. hexq.pop();
  884. //walking stack can't step past the obstacles
  885. if(isInObstacle(curHex, obstacles, checkParams))
  886. continue;
  887. const int costToNeighbour = ret.distances.at(curHex) + 1;
  888. for(BattleHex neighbour : curHex.getNeighbouringTiles())
  889. {
  890. auto additionalCost = 0;
  891. if(params.bypassEnemyStacks)
  892. {
  893. auto enemyToBypass = params.destructibleEnemyTurns.at(neighbour);
  894. if(enemyToBypass >= 0)
  895. {
  896. additionalCost = enemyToBypass;
  897. }
  898. }
  899. const int costFoundSoFar = ret.distances[neighbour];
  900. if(accessibleCache[neighbour] && costToNeighbour + additionalCost < costFoundSoFar)
  901. {
  902. hexq.push(neighbour);
  903. ret.distances[neighbour] = costToNeighbour + additionalCost;
  904. ret.predecessors[neighbour] = curHex;
  905. }
  906. }
  907. }
  908. return ret;
  909. }
  910. bool CBattleInfoCallback::isInObstacle(
  911. BattleHex hex,
  912. const BattleHexArray & obstacleHexes,
  913. const ReachabilityInfo::Parameters & params) const
  914. {
  915. for(auto occupiedHex : battle::Unit::getHexes(hex, params.doubleWide, params.side))
  916. {
  917. if(params.ignoreKnownAccessible && params.knownAccessible->contains(occupiedHex))
  918. continue;
  919. if(obstacleHexes.contains(occupiedHex))
  920. {
  921. if(occupiedHex == BattleHex::GATE_BRIDGE)
  922. {
  923. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  924. return true;
  925. }
  926. else
  927. return true;
  928. }
  929. }
  930. return false;
  931. }
  932. BattleHexArray CBattleInfoCallback::getStoppers(BattleSide whichSidePerspective) const
  933. {
  934. BattleHexArray ret;
  935. RETURN_IF_NOT_BATTLE(ret);
  936. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  937. {
  938. if(!battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  939. continue;
  940. for(auto hex : oi->getStoppingTile())
  941. {
  942. if(hex == BattleHex::GATE_BRIDGE && oi->obstacleType == CObstacleInstance::MOAT)
  943. {
  944. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  945. continue; // this tile is disabled by drawbridge on top of it
  946. }
  947. ret.insert(hex);
  948. }
  949. }
  950. return ret;
  951. }
  952. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  953. {
  954. auto reachability = getReachability(closest);
  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. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  964. {
  965. return unit->isValidTarget(false) && unit != closest;
  966. });
  967. for(const battle::Unit * st : possible)
  968. {
  969. for(BattleHex hex : battleGetAvailableHexes(reachability, closest, false))
  970. if(CStack::isMeleeAttackPossible(closest, st, hex))
  971. {
  972. DistStack hlp = {reachability.distances[hex], 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 = VLC->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(occupyable, side, pos);
  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(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 = & params.destructibleEnemyTurns;
  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 != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1090. defenderPos = (defenderPos != 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. std::vector<const battle::Unit*> 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. std::vector<const battle::Unit*> 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. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1411. {
  1412. std::set<const battle::Unit *> ret;
  1413. RETURN_IF_NOT_BATTLE(ret);
  1414. for(auto hex : unit->getSurroundingHexes())
  1415. {
  1416. if(const auto * neighbour = battleGetUnitByPos(hex, true))
  1417. ret.insert(neighbour);
  1418. }
  1419. return ret;
  1420. }
  1421. SpellID CBattleInfoCallback::getRandomBeneficialSpell(vstd::RNG & rand, const battle::Unit * caster, const battle::Unit * subject) const
  1422. {
  1423. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1424. //This is complete list. No spells from mods.
  1425. //todo: this should be Spellbook of caster Stack
  1426. static const std::set<SpellID> allPossibleSpells =
  1427. {
  1428. SpellID::AIR_SHIELD,
  1429. SpellID::ANTI_MAGIC,
  1430. SpellID::BLESS,
  1431. SpellID::BLOODLUST,
  1432. SpellID::COUNTERSTRIKE,
  1433. SpellID::CURE,
  1434. SpellID::FIRE_SHIELD,
  1435. SpellID::FORTUNE,
  1436. SpellID::HASTE,
  1437. SpellID::MAGIC_MIRROR,
  1438. SpellID::MIRTH,
  1439. SpellID::PRAYER,
  1440. SpellID::PRECISION,
  1441. SpellID::PROTECTION_FROM_AIR,
  1442. SpellID::PROTECTION_FROM_EARTH,
  1443. SpellID::PROTECTION_FROM_FIRE,
  1444. SpellID::PROTECTION_FROM_WATER,
  1445. SpellID::SHIELD,
  1446. SpellID::SLAYER,
  1447. SpellID::STONE_SKIN
  1448. };
  1449. std::vector<SpellID> beneficialSpells;
  1450. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1451. {
  1452. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1453. {
  1454. return pred(stack) && stack->unitOwner() != subject->unitOwner() && stack->isValidTarget(false);
  1455. });
  1456. if(stacks.empty())
  1457. return nullptr;
  1458. else
  1459. return stacks.front();
  1460. };
  1461. for(const SpellID& spellID : allPossibleSpells)
  1462. {
  1463. std::stringstream cachingStr;
  1464. cachingStr << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT) << "id_" << spellID.num;
  1465. if(subject->hasBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(spellID)), Selector::all, cachingStr.str()))
  1466. continue;
  1467. auto spellPtr = spellID.toSpell();
  1468. spells::Target target;
  1469. target.emplace_back(subject);
  1470. spells::BattleCast cast(this, caster, spells::Mode::CREATURE_ACTIVE, spellPtr);
  1471. auto m = spellPtr->battleMechanics(&cast);
  1472. spells::detail::ProblemImpl problem;
  1473. if (!m->canBeCastAt(target, problem))
  1474. continue;
  1475. switch (spellID.toEnum())
  1476. {
  1477. case SpellID::SHIELD:
  1478. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1479. {
  1480. const auto * walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1481. {
  1482. return !stack->canShoot();
  1483. });
  1484. if(!walker)
  1485. continue;
  1486. }
  1487. break;
  1488. case SpellID::AIR_SHIELD: //only against active shooters
  1489. {
  1490. const auto * shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1491. {
  1492. return stack->canShoot();
  1493. });
  1494. if(!shooter)
  1495. continue;
  1496. }
  1497. break;
  1498. case SpellID::ANTI_MAGIC:
  1499. case SpellID::MAGIC_MIRROR:
  1500. case SpellID::PROTECTION_FROM_AIR:
  1501. case SpellID::PROTECTION_FROM_EARTH:
  1502. case SpellID::PROTECTION_FROM_FIRE:
  1503. case SpellID::PROTECTION_FROM_WATER:
  1504. {
  1505. const BattleSide enemySide = otherSide(subject->unitSide());
  1506. //todo: only if enemy has spellbook
  1507. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1508. continue;
  1509. }
  1510. break;
  1511. case SpellID::CURE: //only damaged units
  1512. {
  1513. //do not cast on affected by debuffs
  1514. if(subject->getFirstHPleft() == subject->getMaxHealth())
  1515. continue;
  1516. }
  1517. break;
  1518. case SpellID::BLOODLUST:
  1519. {
  1520. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1521. continue;
  1522. }
  1523. break;
  1524. case SpellID::PRECISION:
  1525. {
  1526. if(!subject->canShoot())
  1527. continue;
  1528. }
  1529. break;
  1530. case SpellID::SLAYER://only if monsters are present
  1531. {
  1532. const auto * kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1533. {
  1534. return stack->hasBonusOfType(BonusType::KING);
  1535. });
  1536. if (!kingMonster)
  1537. continue;
  1538. }
  1539. break;
  1540. }
  1541. beneficialSpells.push_back(spellID);
  1542. }
  1543. if(!beneficialSpells.empty())
  1544. {
  1545. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1546. }
  1547. else
  1548. {
  1549. return SpellID::NONE;
  1550. }
  1551. }
  1552. SpellID CBattleInfoCallback::getRandomCastedSpell(vstd::RNG & rand,const CStack * caster) const
  1553. {
  1554. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1555. TConstBonusListPtr bl = caster->getBonusesOfType(BonusType::SPELLCASTER);
  1556. if (!bl->size())
  1557. return SpellID::NONE;
  1558. if(bl->size() == 1)
  1559. return bl->front()->subtype.as<SpellID>();
  1560. int totalWeight = 0;
  1561. for(const auto & b : *bl)
  1562. {
  1563. totalWeight += std::max(b->additionalInfo[0], 0); //spells with 0 weight are non-random, exclude them
  1564. }
  1565. if (totalWeight == 0)
  1566. return SpellID::NONE;
  1567. int randomPos = rand.nextInt(totalWeight - 1);
  1568. for(const auto & b : *bl)
  1569. {
  1570. randomPos -= std::max(b->additionalInfo[0], 0);
  1571. if(randomPos < 0)
  1572. {
  1573. return b->subtype.as<SpellID>();
  1574. }
  1575. }
  1576. return SpellID::NONE;
  1577. }
  1578. int CBattleInfoCallback::battleGetSurrenderCost(const PlayerColor & Player) const
  1579. {
  1580. RETURN_IF_NOT_BATTLE(-3);
  1581. if(!battleCanSurrender(Player))
  1582. return -1;
  1583. const BattleSide side = playerToSide(Player);
  1584. if(side == BattleSide::NONE)
  1585. return -1;
  1586. int ret = 0;
  1587. double discount = 0;
  1588. for(const auto * unit : battleAliveUnits(side))
  1589. ret += unit->getRawSurrenderCost();
  1590. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1591. discount += h->valOfBonuses(BonusType::SURRENDER_DISCOUNT);
  1592. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1593. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1594. return ret;
  1595. }
  1596. si8 CBattleInfoCallback::battleMinSpellLevel(BattleSide side) const
  1597. {
  1598. const IBonusBearer * node = nullptr;
  1599. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1600. node = h;
  1601. else
  1602. node = getBonusBearer();
  1603. if(!node)
  1604. return 0;
  1605. auto b = node->getBonusesOfType(BonusType::BLOCK_MAGIC_BELOW);
  1606. if(b->size())
  1607. return b->totalValue();
  1608. return 0;
  1609. }
  1610. si8 CBattleInfoCallback::battleMaxSpellLevel(BattleSide side) const
  1611. {
  1612. const IBonusBearer *node = nullptr;
  1613. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1614. node = h;
  1615. else
  1616. node = getBonusBearer();
  1617. if(!node)
  1618. return GameConstants::SPELL_LEVELS;
  1619. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1620. auto b = node->getBonusesOfType(BonusType::BLOCK_MAGIC_ABOVE);
  1621. if(b->size())
  1622. return b->totalValue();
  1623. return GameConstants::SPELL_LEVELS;
  1624. }
  1625. std::optional<BattleSide> CBattleInfoCallback::battleIsFinished() const
  1626. {
  1627. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1628. {
  1629. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(BonusType::SIEGE_WEAPON);
  1630. });
  1631. BattleSideArray<bool> hasUnit = {false, false}; //index is BattleSide
  1632. for(auto & unit : units)
  1633. {
  1634. //todo: move SIEGE_WEAPON check to Unit state
  1635. hasUnit.at(unit->unitSide()) = true;
  1636. if(hasUnit[BattleSide::ATTACKER] && hasUnit[BattleSide::DEFENDER])
  1637. return std::nullopt;
  1638. }
  1639. hasUnit = {false, false};
  1640. for(auto & unit : units)
  1641. {
  1642. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1643. {
  1644. hasUnit.at(unit->unitSide()) = true;
  1645. }
  1646. }
  1647. if(!hasUnit[BattleSide::ATTACKER] && !hasUnit[BattleSide::DEFENDER])
  1648. return BattleSide::NONE;
  1649. if(!hasUnit[BattleSide::DEFENDER])
  1650. return BattleSide::ATTACKER;
  1651. else
  1652. return BattleSide::DEFENDER;
  1653. }
  1654. VCMI_LIB_NAMESPACE_END