CBattleInfoCallback.cpp 57 KB

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