CBattleInfoCallback.cpp 55 KB

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