CBattleInfoCallback.cpp 62 KB

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