2
0

CBattleInfoCallback.cpp 59 KB

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