CBattleInfoCallback.cpp 60 KB

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