CBattleInfoCallback.cpp 56 KB

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