CBattleInfoCallback.cpp 58 KB

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