CBattleInfoCallback.cpp 59 KB

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