CBattleInfoCallback.cpp 54 KB

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