CBattleInfoCallback.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  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. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  20. {
  21. /*
  22. *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:
  23. *
  24. *1. http://heroes.thelazy.net/wiki/Arrow_tower
  25. *
  26. *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.
  27. *Buildings increase turrets' damage, but only those buildings that are new in town view, not upgrades to the existing. So, every building save:
  28. *- dwellings' upgrades
  29. *- Mage Guild upgrades
  30. *- Horde buildings
  31. *- income upgrades
  32. *- some special ones
  33. *increases middle Turret damage by 3, and 1,5 for the other two.
  34. *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).
  35. *Maximum damage for Castle, Conflux is 120, Necropolis, Inferno, Fortress 125, Stronghold, Turret, and Dungeon 130 (for all three Turrets).
  36. *Artillery allows the player to control the Turrets.
  37. */
  38. static void retrieveTurretDamageRange(const CGTownInstance * town, const battle::Unit * turret, double & outMinDmg, double & outMaxDmg)//does not match OH3 yet, but damage is somewhat close
  39. {
  40. assert(turret->creatureIndex() == CreatureID::ARROW_TOWERS);
  41. assert(town);
  42. assert(turret->getPosition() >= -4 && turret->getPosition() <= -2);
  43. const float multiplier = (turret->getPosition() == -2) ? 1.0f : 0.5f;
  44. //Revised - Where do below values come from?
  45. /*int baseMin = 6;
  46. int baseMax = 10;*/
  47. const int baseDamage = 15;
  48. outMinDmg = multiplier * (baseDamage + town->getTownLevel() * 3);
  49. outMaxDmg = multiplier * (baseDamage + town->getTownLevel() * 3);
  50. }
  51. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  52. {
  53. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  54. return lineToHex[line];
  55. }
  56. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  57. {
  58. const int wallInStackLine = lineToWallHex(pos1.getY());
  59. const int wallInDestLine = lineToWallHex(pos2.getY());
  60. const bool stackLeft = pos1 < wallInStackLine;
  61. const bool destLeft = pos2 < wallInDestLine;
  62. return stackLeft == destLeft;
  63. }
  64. // parts of wall
  65. static const std::pair<int, EWallPart::EWallPart> wallParts[] =
  66. {
  67. std::make_pair(50, EWallPart::KEEP),
  68. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  69. std::make_pair(182, EWallPart::BOTTOM_WALL),
  70. std::make_pair(130, EWallPart::BELOW_GATE),
  71. std::make_pair(78, EWallPart::OVER_GATE),
  72. std::make_pair(29, EWallPart::UPPER_WALL),
  73. std::make_pair(12, EWallPart::UPPER_TOWER),
  74. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  75. std::make_pair(96, EWallPart::GATE),
  76. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  77. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  78. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  79. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  80. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  81. };
  82. static EWallPart::EWallPart hexToWallPart(BattleHex hex)
  83. {
  84. for(auto & elem : wallParts)
  85. {
  86. if(elem.first == hex)
  87. return elem.second;
  88. }
  89. return EWallPart::INVALID; //not found!
  90. }
  91. static BattleHex WallPartToHex(EWallPart::EWallPart part)
  92. {
  93. for(auto & elem : wallParts)
  94. {
  95. if(elem.second == part)
  96. return elem.first;
  97. }
  98. return BattleHex::INVALID; //not found!
  99. }
  100. }
  101. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  102. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const spells::Caster * caster, spells::Mode mode) const
  103. {
  104. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  105. if(caster == nullptr)
  106. {
  107. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  108. return ESpellCastProblem::INVALID;
  109. }
  110. const PlayerColor player = caster->getCasterOwner();
  111. const auto side = playerToSide(player);
  112. if(!side)
  113. return ESpellCastProblem::INVALID;
  114. if(!battleDoWeKnowAbout(side.get()))
  115. {
  116. logGlobal->warn("You can't check if enemy can cast given spell!");
  117. return ESpellCastProblem::INVALID;
  118. }
  119. if(battleTacticDist())
  120. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  121. switch(mode)
  122. {
  123. case spells::Mode::HERO:
  124. {
  125. if(battleCastSpells(side.get()) > 0)
  126. return ESpellCastProblem::CASTS_PER_TURN_LIMIT;
  127. auto hero = dynamic_cast<const CGHeroInstance *>(caster);
  128. if(!hero)
  129. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  130. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  131. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  132. }
  133. break;
  134. default:
  135. break;
  136. }
  137. return ESpellCastProblem::OK;
  138. }
  139. bool CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  140. {
  141. RETURN_IF_NOT_BATTLE(false);
  142. if(!battleGetSiegeLevel())
  143. return false;
  144. const std::string cachingStrNoWallPenalty = "type_NO_WALL_PENALTY";
  145. static const auto selectorNoWallPenalty = Selector::type()(Bonus::NO_WALL_PENALTY);
  146. if(shooter->hasBonus(selectorNoWallPenalty, cachingStrNoWallPenalty))
  147. return false;
  148. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  149. const int wallInDestLine = lineToWallHex(destHex.getY());
  150. const bool stackLeft = shooterPosition < wallInStackLine;
  151. const bool destRight = destHex > wallInDestLine;
  152. if (stackLeft && destRight) //shooting from outside to inside
  153. {
  154. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  155. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  156. row -= 2;
  157. const int wallPos = lineToWallHex(row);
  158. if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
  159. }
  160. return false;
  161. }
  162. si8 CBattleInfoCallback::battleCanTeleportTo(const battle::Unit * stack, BattleHex destHex, int telportLevel) const
  163. {
  164. RETURN_IF_NOT_BATTLE(false);
  165. if (!getAccesibility(stack).accessible(destHex, stack))
  166. return false;
  167. const ui8 siegeLevel = battleGetSiegeLevel();
  168. //check for wall
  169. //advanced teleport can pass wall of fort|citadel, expert - of castle
  170. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  171. return sameSideOfWall(stack->getPosition(), destHex);
  172. return true;
  173. }
  174. std::vector<PossiblePlayerBattleAction> CBattleInfoCallback::getClientActionsForStack(const CStack * stack, const BattleClientInterfaceData & data)
  175. {
  176. RETURN_IF_NOT_BATTLE(std::vector<PossiblePlayerBattleAction>());
  177. std::vector<PossiblePlayerBattleAction> allowedActionList;
  178. if(data.tacticsMode) //would "if(battleGetTacticDist() > 0)" work?
  179. {
  180. allowedActionList.push_back(PossiblePlayerBattleAction::MOVE_TACTICS);
  181. allowedActionList.push_back(PossiblePlayerBattleAction::CHOOSE_TACTICS_STACK);
  182. }
  183. else
  184. {
  185. if(stack->canCast()) //TODO: check for battlefield effects that prevent casting?
  186. {
  187. if(stack->hasBonusOfType(Bonus::SPELLCASTER) && data.creatureSpellToCast != -1)
  188. {
  189. const CSpell *spell = SpellID(data.creatureSpellToCast).toSpell();
  190. PossiblePlayerBattleAction act = getCasterAction(spell, stack, spells::Mode::CREATURE_ACTIVE);
  191. allowedActionList.push_back(act);
  192. }
  193. if(stack->hasBonusOfType(Bonus::RANDOM_SPELLCASTER))
  194. allowedActionList.push_back(PossiblePlayerBattleAction::RANDOM_GENIE_SPELL);
  195. if(stack->hasBonusOfType(Bonus::DAEMON_SUMMONING))
  196. allowedActionList.push_back(PossiblePlayerBattleAction::RISE_DEMONS);
  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 dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  664. multBonus *= 1.0 - dec;
  665. }
  666. else //increasing dmg
  667. {
  668. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  669. additiveBonus += inc;
  670. }
  671. const std::string cachingStrJousting = "type_JOUSTING";
  672. static const auto selectorJousting = Selector::type()(Bonus::JOUSTING);
  673. const std::string cachingStrChargeImmunity = "type_CHARGE_IMMUNITY";
  674. static const auto selectorChargeImmunity = Selector::type()(Bonus::CHARGE_IMMUNITY);
  675. //applying jousting bonus
  676. if(info.chargedFields > 0 && attackerBonuses->hasBonus(selectorJousting, cachingStrJousting) && !defenderBonuses->hasBonus(selectorChargeImmunity, cachingStrChargeImmunity))
  677. additiveBonus += info.chargedFields * 0.05;
  678. //handling secondary abilities and artifacts giving premies to them
  679. const std::string cachingStrArchery = "type_SECONDARY_SKILL_PREMYs_ARCHERY";
  680. static const auto selectorArchery = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY);
  681. const std::string cachingStrOffence = "type_SECONDARY_SKILL_PREMYs_OFFENCE";
  682. static const auto selectorOffence = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE);
  683. const std::string cachingStrArmorer = "type_SECONDARY_SKILL_PREMYs_ARMORER";
  684. static const auto selectorArmorer = Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER);
  685. if(info.shooting)
  686. additiveBonus += attackerBonuses->valOfBonuses(selectorArchery, cachingStrArchery) / 100.0;
  687. else
  688. additiveBonus += attackerBonuses->valOfBonuses(selectorOffence, cachingStrOffence) / 100.0;
  689. multBonus *= (std::max(0, 100 - defenderBonuses->valOfBonuses(selectorArmorer, cachingStrArmorer))) / 100.0;
  690. //handling hate effect
  691. //assume that unit have only few HATE features and cache them all
  692. const std::string cachingStrHate = "type_HATE";
  693. static const auto selectorHate = Selector::type()(Bonus::HATE);
  694. auto allHateEffects = attackerBonuses->getBonuses(selectorHate, cachingStrHate);
  695. additiveBonus += allHateEffects->valOfBonuses(Selector::subtype()(info.defender->creatureIndex())) / 100.0;
  696. const std::string cachingStrMeleeReduction = "type_GENERAL_DAMAGE_REDUCTIONs_0";
  697. static const auto selectorMeleeReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 0);
  698. const std::string cachingStrRangedReduction = "type_GENERAL_DAMAGE_REDUCTIONs_1";
  699. static const auto selectorRangedReduction = Selector::typeSubtype(Bonus::GENERAL_DAMAGE_REDUCTION, 1);
  700. //handling spell effects
  701. if(!info.shooting) //eg. shield
  702. {
  703. multBonus *= (100 - defenderBonuses->valOfBonuses(selectorMeleeReduction, cachingStrMeleeReduction)) / 100.0;
  704. }
  705. else //eg. air shield
  706. {
  707. multBonus *= (100 - defenderBonuses->valOfBonuses(selectorRangedReduction, cachingStrRangedReduction)) / 100.0;
  708. }
  709. if(info.shooting)
  710. {
  711. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  712. //get list first, total value of 0 also counts
  713. TConstBonusListPtr forgetfulList = attackerBonuses->getBonuses(Selector::type()(Bonus::FORGETFULL),"type_FORGETFULL");
  714. if(!forgetfulList->empty())
  715. {
  716. int forgetful = forgetfulList->valOfBonuses(Selector::all);
  717. //none of basic level
  718. if(forgetful == 0 || forgetful == 1)
  719. multBonus *= 0.5;
  720. else
  721. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  722. }
  723. }
  724. const std::string cachingStrForcedMinDamage = "type_ALWAYS_MINIMUM_DAMAGE";
  725. static const auto selectorForcedMinDamage = Selector::type()(Bonus::ALWAYS_MINIMUM_DAMAGE);
  726. const std::string cachingStrForcedMaxDamage = "type_ALWAYS_MAXIMUM_DAMAGE";
  727. static const auto selectorForcedMaxDamage = Selector::type()(Bonus::ALWAYS_MAXIMUM_DAMAGE);
  728. TConstBonusListPtr curseEffects = attackerBonuses->getBonuses(selectorForcedMinDamage, cachingStrForcedMinDamage);
  729. TConstBonusListPtr blessEffects = attackerBonuses->getBonuses(selectorForcedMaxDamage, cachingStrForcedMaxDamage);
  730. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  731. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo[0] : 0;
  732. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  733. {
  734. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  735. }
  736. const std::string cachingStrAdvAirShield = "isAdvancedAirShield";
  737. auto isAdvancedAirShield = [](const Bonus* bonus)
  738. {
  739. return bonus->source == Bonus::SPELL_EFFECT
  740. && bonus->sid == SpellID::AIR_SHIELD
  741. && bonus->val >= SecSkillLevel::ADVANCED;
  742. };
  743. if(info.shooting)
  744. {
  745. //wall / distance penalty + advanced air shield
  746. BattleHex attackerPos = info.attackerPos.isValid() ? info.attackerPos : info.attacker->getPosition();
  747. BattleHex defenderPos = info.defenderPos.isValid() ? info.defenderPos : info.defender->getPosition();
  748. const bool distPenalty = battleHasDistancePenalty(attackerBonuses, attackerPos, defenderPos);
  749. const bool obstaclePenalty = battleHasWallPenalty(attackerBonuses, attackerPos, defenderPos);
  750. if(distPenalty || defenderBonuses->hasBonus(isAdvancedAirShield, cachingStrAdvAirShield))
  751. multBonus *= 0.5;
  752. if(obstaclePenalty)
  753. multBonus *= 0.5; //cumulative
  754. }
  755. else
  756. {
  757. const std::string cachingStrNoMeleePenalty = "type_NO_MELEE_PENALTY";
  758. static const auto selectorNoMeleePenalty = Selector::type()(Bonus::NO_MELEE_PENALTY);
  759. if(info.attacker->isShooter() && !attackerBonuses->hasBonus(selectorNoMeleePenalty, cachingStrNoMeleePenalty))
  760. multBonus *= 0.5;
  761. }
  762. // psychic elementals versus mind immune units 50%
  763. if(info.attacker->creatureIndex() == CreatureID::PSYCHIC_ELEMENTAL)
  764. {
  765. const std::string cachingStrMindImmunity = "type_MIND_IMMUNITY";
  766. static const auto selectorMindImmunity = Selector::type()(Bonus::MIND_IMMUNITY);
  767. if(defenderBonuses->hasBonus(selectorMindImmunity, cachingStrMindImmunity))
  768. multBonus *= 0.5;
  769. }
  770. // TODO attack on petrified unit 50%
  771. // blinded unit retaliates
  772. minDmg *= additiveBonus * multBonus;
  773. maxDmg *= additiveBonus * multBonus;
  774. if(curseEffects->size()) //curse handling (rest)
  775. {
  776. minDmg += curseBlessAdditiveModifier;
  777. maxDmg = minDmg;
  778. }
  779. else if(blessEffects->size()) //bless handling
  780. {
  781. maxDmg += curseBlessAdditiveModifier;
  782. minDmg = maxDmg;
  783. }
  784. TDmgRange returnedVal = std::make_pair(int64_t(minDmg), int64_t(maxDmg));
  785. //damage cannot be less than 1
  786. vstd::amax(returnedVal.first, 1);
  787. vstd::amax(returnedVal.second, 1);
  788. return returnedVal;
  789. }
  790. TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  791. {
  792. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  793. const bool shooting = battleCanShoot(attacker, defender->getPosition());
  794. const BattleAttackInfo bai(attacker, defender, shooting);
  795. return battleEstimateDamage(bai, retaliationDmg);
  796. }
  797. TDmgRange CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo & bai, TDmgRange * retaliationDmg) const
  798. {
  799. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  800. TDmgRange ret = calculateDmgRange(bai);
  801. if(retaliationDmg)
  802. {
  803. if(bai.shooting)
  804. {
  805. //FIXME: handle RANGED_RETALIATION
  806. retaliationDmg->first = retaliationDmg->second = 0;
  807. }
  808. else
  809. {
  810. //TODO: rewrite using boost::numeric::interval
  811. //TODO: rewire once more using interval-based fuzzy arithmetic
  812. int64_t TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  813. for (int i=0; i<2; ++i)
  814. {
  815. auto retaliationAttack = bai.reverse();
  816. int64_t dmg = ret.*pairElems[i];
  817. auto state = retaliationAttack.attacker->acquireState();
  818. state->damage(dmg);
  819. retaliationAttack.attacker = state.get();
  820. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  821. }
  822. }
  823. }
  824. return ret;
  825. }
  826. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::battleGetAllObstaclesOnPos(BattleHex tile, bool onlyBlocking) const
  827. {
  828. std::vector<std::shared_ptr<const CObstacleInstance>> obstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  829. RETURN_IF_NOT_BATTLE(obstacles);
  830. for(auto & obs : battleGetAllObstacles())
  831. {
  832. if(vstd::contains(obs->getBlockedTiles(), tile)
  833. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  834. {
  835. obstacles.push_back(obs);
  836. }
  837. }
  838. return obstacles;
  839. }
  840. std::vector<std::shared_ptr<const CObstacleInstance>> CBattleInfoCallback::getAllAffectedObstaclesByStack(const battle::Unit * unit) const
  841. {
  842. std::vector<std::shared_ptr<const CObstacleInstance>> affectedObstacles = std::vector<std::shared_ptr<const CObstacleInstance>>();
  843. RETURN_IF_NOT_BATTLE(affectedObstacles);
  844. if(unit->alive())
  845. {
  846. affectedObstacles = battleGetAllObstaclesOnPos(unit->getPosition(), false);
  847. if(unit->doubleWide())
  848. {
  849. BattleHex otherHex = unit->occupiedHex(unit->getPosition());
  850. if(otherHex.isValid())
  851. for(auto & i : battleGetAllObstaclesOnPos(otherHex, false))
  852. affectedObstacles.push_back(i);
  853. }
  854. for(auto hex : unit->getHexes())
  855. if(hex == ESiegeHex::GATE_BRIDGE)
  856. if(battleGetGateState() == EGateState::OPENED || battleGetGateState() == EGateState::DESTROYED)
  857. for(int i=0; i<affectedObstacles.size(); i++)
  858. if(affectedObstacles.at(i)->obstacleType == CObstacleInstance::MOAT)
  859. affectedObstacles.erase(affectedObstacles.begin()+i);
  860. }
  861. return affectedObstacles;
  862. }
  863. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  864. {
  865. AccessibilityInfo ret;
  866. ret.fill(EAccessibility::ACCESSIBLE);
  867. //removing accessibility for side columns of hexes
  868. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  869. {
  870. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  871. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  872. }
  873. //special battlefields with logically unavailable tiles
  874. auto bFieldType = battleGetBattlefieldType();
  875. if(bFieldType != BattleField::NONE)
  876. {
  877. std::vector<BattleHex> impassableHexes = bFieldType.getInfo()->impassableHexes;
  878. for(auto hex : impassableHexes)
  879. ret[hex] = EAccessibility::UNAVAILABLE;
  880. }
  881. //gate -> should be before stacks
  882. if(battleGetSiegeLevel() > 0)
  883. {
  884. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  885. switch(battleGetGateState())
  886. {
  887. case EGateState::CLOSED:
  888. accessability = EAccessibility::GATE;
  889. break;
  890. case EGateState::BLOCKED:
  891. accessability = EAccessibility::UNAVAILABLE;
  892. break;
  893. }
  894. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  895. }
  896. //tiles occupied by standing stacks
  897. for(auto unit : battleAliveUnits())
  898. {
  899. for(auto hex : unit->getHexes())
  900. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  901. ret[hex] = EAccessibility::ALIVE_STACK;
  902. }
  903. //obstacles
  904. for(const auto &obst : battleGetAllObstacles())
  905. {
  906. for(auto hex : obst->getBlockedTiles())
  907. ret[hex] = EAccessibility::OBSTACLE;
  908. }
  909. //walls
  910. if(battleGetSiegeLevel() > 0)
  911. {
  912. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  913. for(auto hex : permanentlyLocked)
  914. ret[hex] = EAccessibility::UNAVAILABLE;
  915. //TODO likely duplicated logic
  916. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  917. {
  918. //which part of wall, which hex is blocked if this part of wall is not destroyed
  919. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  920. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  921. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  922. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  923. };
  924. for(auto & elem : lockedIfNotDestroyed)
  925. {
  926. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  927. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  928. }
  929. }
  930. return ret;
  931. }
  932. AccessibilityInfo CBattleInfoCallback::getAccesibility(const battle::Unit * stack) const
  933. {
  934. return getAccesibility(battle::Unit::getHexes(stack->getPosition(), stack->doubleWide(), stack->unitSide()));
  935. }
  936. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  937. {
  938. auto ret = getAccesibility();
  939. for(auto hex : accessibleHexes)
  940. if(hex.isValid())
  941. ret[hex] = EAccessibility::ACCESSIBLE;
  942. return ret;
  943. }
  944. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  945. {
  946. ReachabilityInfo ret;
  947. ret.accessibility = accessibility;
  948. ret.params = params;
  949. ret.predecessors.fill(BattleHex::INVALID);
  950. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  951. if(!params.startPosition.isValid()) //if got call for arrow turrets
  952. return ret;
  953. const std::set<BattleHex> obstacles = getStoppers(params.perspective);
  954. std::queue<BattleHex> hexq; //bfs queue
  955. //first element
  956. hexq.push(params.startPosition);
  957. ret.distances[params.startPosition] = 0;
  958. std::array<bool, GameConstants::BFIELD_SIZE> accessibleCache;
  959. for(int hex = 0; hex < GameConstants::BFIELD_SIZE; hex++)
  960. accessibleCache[hex] = accessibility.accessible(hex, params.doubleWide, params.side);
  961. while(!hexq.empty()) //bfs loop
  962. {
  963. const BattleHex curHex = hexq.front();
  964. hexq.pop();
  965. //walking stack can't step past the obstacles
  966. if(curHex != params.startPosition && isInObstacle(curHex, obstacles, params))
  967. continue;
  968. const int costToNeighbour = ret.distances[curHex.hex] + 1;
  969. for(BattleHex neighbour : BattleHex::neighbouringTilesCache[curHex.hex])
  970. {
  971. if(neighbour.isValid())
  972. {
  973. const int costFoundSoFar = ret.distances[neighbour.hex];
  974. if(accessibleCache[neighbour.hex] && costToNeighbour < costFoundSoFar)
  975. {
  976. hexq.push(neighbour);
  977. ret.distances[neighbour.hex] = costToNeighbour;
  978. ret.predecessors[neighbour.hex] = curHex;
  979. }
  980. }
  981. }
  982. }
  983. return ret;
  984. }
  985. bool CBattleInfoCallback::isInObstacle(
  986. BattleHex hex,
  987. const std::set<BattleHex> & obstacles,
  988. const ReachabilityInfo::Parameters & params) const
  989. {
  990. auto occupiedHexes = battle::Unit::getHexes(hex, params.doubleWide, params.side);
  991. for(auto occupiedHex : occupiedHexes)
  992. {
  993. if(vstd::contains(obstacles, occupiedHex))
  994. {
  995. if(occupiedHex == ESiegeHex::GATE_BRIDGE)
  996. {
  997. if(battleGetGateState() != EGateState::DESTROYED && params.side == BattleSide::ATTACKER)
  998. return true;
  999. }
  1000. else
  1001. return true;
  1002. }
  1003. }
  1004. return false;
  1005. }
  1006. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  1007. {
  1008. std::set<BattleHex> ret;
  1009. RETURN_IF_NOT_BATTLE(ret);
  1010. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  1011. {
  1012. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  1013. {
  1014. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  1015. }
  1016. }
  1017. return ret;
  1018. }
  1019. std::pair<const battle::Unit *, BattleHex> CBattleInfoCallback::getNearestStack(const battle::Unit * closest) const
  1020. {
  1021. auto reachability = getReachability(closest);
  1022. auto avHexes = battleGetAvailableHexes(reachability, closest);
  1023. // I hate std::pairs with their undescriptive member names first / second
  1024. struct DistStack
  1025. {
  1026. int distanceToPred;
  1027. BattleHex destination;
  1028. const battle::Unit * stack;
  1029. };
  1030. std::vector<DistStack> stackPairs;
  1031. std::vector<const battle::Unit *> possible = battleGetUnitsIf([=](const battle::Unit * unit)
  1032. {
  1033. return unit->isValidTarget(false) && unit != closest;
  1034. });
  1035. for(const battle::Unit * st : possible)
  1036. {
  1037. for(BattleHex hex : avHexes)
  1038. if(CStack::isMeleeAttackPossible(closest, st, hex))
  1039. {
  1040. DistStack hlp = {reachability.distances[hex], hex, st};
  1041. stackPairs.push_back(hlp);
  1042. }
  1043. }
  1044. if (stackPairs.size())
  1045. {
  1046. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  1047. auto minimal = boost::min_element(stackPairs, comparator);
  1048. return std::make_pair(minimal->stack, minimal->destination);
  1049. }
  1050. else
  1051. return std::make_pair<const battle::Unit * , BattleHex>(nullptr, BattleHex::INVALID);
  1052. }
  1053. BattleHex CBattleInfoCallback::getAvaliableHex(CreatureID creID, ui8 side, int initialPos) const
  1054. {
  1055. bool twoHex = VLC->creh->objects[creID]->isDoubleWide();
  1056. int pos;
  1057. if (initialPos > -1)
  1058. pos = initialPos;
  1059. else //summon elementals depending on player side
  1060. {
  1061. if(side == BattleSide::ATTACKER)
  1062. pos = 0; //top left
  1063. else
  1064. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  1065. }
  1066. auto accessibility = getAccesibility();
  1067. std::set<BattleHex> occupyable;
  1068. for(int i = 0; i < accessibility.size(); i++)
  1069. if(accessibility.accessible(i, twoHex, side))
  1070. occupyable.insert(i);
  1071. if(occupyable.empty())
  1072. {
  1073. return BattleHex::INVALID; //all tiles are covered
  1074. }
  1075. return BattleHex::getClosestTile(side, pos, occupyable);
  1076. }
  1077. si8 CBattleInfoCallback::battleGetTacticDist() const
  1078. {
  1079. RETURN_IF_NOT_BATTLE(0);
  1080. //TODO get rid of this method
  1081. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1082. return battleTacticDist();
  1083. return 0;
  1084. }
  1085. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  1086. {
  1087. RETURN_IF_NOT_BATTLE(false);
  1088. auto side = battleGetTacticsSide();
  1089. auto dist = battleGetTacticDist();
  1090. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  1091. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  1092. }
  1093. ReachabilityInfo CBattleInfoCallback::getReachability(const battle::Unit * unit) const
  1094. {
  1095. ReachabilityInfo::Parameters params(unit, unit->getPosition());
  1096. if(!battleDoWeKnowAbout(unit->unitSide()))
  1097. {
  1098. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1099. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1100. params.perspective = battleGetMySide();
  1101. }
  1102. return getReachability(params);
  1103. }
  1104. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1105. {
  1106. if(params.flying)
  1107. return getFlyingReachability(params);
  1108. else
  1109. return makeBFS(getAccesibility(params.knownAccessible), params);
  1110. }
  1111. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  1112. {
  1113. ReachabilityInfo ret;
  1114. ret.accessibility = getAccesibility(params.knownAccessible);
  1115. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1116. {
  1117. if(ret.accessibility.accessible(i, params.doubleWide, params.side))
  1118. {
  1119. ret.predecessors[i] = params.startPosition;
  1120. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1121. }
  1122. }
  1123. return ret;
  1124. }
  1125. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const battle::Unit* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1126. {
  1127. //does not return hex attacked directly
  1128. //TODO: apply rotation to two-hex attackers
  1129. bool isAttacker = attacker->unitSide() == BattleSide::ATTACKER;
  1130. AttackableTiles at;
  1131. RETURN_IF_NOT_BATTLE(at);
  1132. const int WN = GameConstants::BFIELD_WIDTH;
  1133. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : attacker->getPosition(); //real or hypothetical (cursor) position
  1134. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  1135. bool reverse = isToReverse(hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  1136. if(reverse && attacker->doubleWide())
  1137. {
  1138. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  1139. }
  1140. if(attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  1141. {
  1142. boost::copy(attacker->getSurroundingHexes(attackerPos), vstd::set_inserter(at.hostileCreaturePositions));
  1143. }
  1144. if(attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  1145. {
  1146. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1147. for(BattleHex tile : hexes)
  1148. {
  1149. if((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition(tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  1150. {
  1151. auto st = battleGetUnitByPos(tile, true);
  1152. if(st && battleMatchOwner(st, attacker)) //only hostile stacks - does it work well with Berserk?
  1153. at.hostileCreaturePositions.insert(tile);
  1154. }
  1155. }
  1156. }
  1157. if(attacker->hasBonusOfType(Bonus::WIDE_BREATH))
  1158. {
  1159. std::vector<BattleHex> hexes = destinationTile.neighbouringTiles();
  1160. for(int i = 0; i<hexes.size(); i++)
  1161. {
  1162. if(hexes.at(i) == hex)
  1163. {
  1164. hexes.erase(hexes.begin() + i);
  1165. i = 0;
  1166. }
  1167. }
  1168. for(BattleHex tile : hexes)
  1169. {
  1170. //friendly stacks can also be damaged by Dragon Breath
  1171. auto st = battleGetUnitByPos(tile, true);
  1172. if(st && st != attacker)
  1173. at.friendlyCreaturePositions.insert(tile);
  1174. }
  1175. }
  1176. else if(attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH))
  1177. {
  1178. int pos = BattleHex::mutualPosition(destinationTile, hex);
  1179. if(pos > -1) //only adjacent hexes are subject of dragon breath calculation
  1180. {
  1181. std::vector<BattleHex> hexes; //only one, in fact
  1182. int pseudoVector = destinationTile.hex - hex;
  1183. switch(pseudoVector)
  1184. {
  1185. case 1:
  1186. case -1:
  1187. BattleHex::checkAndPush(destinationTile.hex + pseudoVector, hexes);
  1188. break;
  1189. case WN: //17 //left-down or right-down
  1190. case -WN: //-17 //left-up or right-up
  1191. case WN + 1: //18 //right-down
  1192. case -WN + 1: //-16 //right-up
  1193. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : -1), hexes);
  1194. break;
  1195. case WN - 1: //16 //left-down
  1196. case -WN - 1: //-18 //left-up
  1197. BattleHex::checkAndPush(destinationTile.hex + pseudoVector + (((hex / WN) % 2) ? 1 : 0), hexes);
  1198. break;
  1199. }
  1200. for(BattleHex tile : hexes)
  1201. {
  1202. //friendly stacks can also be damaged by Dragon Breath
  1203. auto st = battleGetUnitByPos(tile, true);
  1204. if(st != nullptr)
  1205. at.friendlyCreaturePositions.insert(tile);
  1206. }
  1207. }
  1208. }
  1209. return at;
  1210. }
  1211. AttackableTiles CBattleInfoCallback::getPotentiallyShootableHexes(const battle::Unit * attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1212. {
  1213. //does not return hex attacked directly
  1214. AttackableTiles at;
  1215. RETURN_IF_NOT_BATTLE(at);
  1216. if(attacker->hasBonusOfType(Bonus::SHOOTS_ALL_ADJACENT) && !vstd::contains(attackerPos.neighbouringTiles(), destinationTile))
  1217. {
  1218. std::vector<BattleHex> targetHexes = destinationTile.neighbouringTiles();
  1219. targetHexes.push_back(destinationTile);
  1220. boost::copy(targetHexes, vstd::set_inserter(at.hostileCreaturePositions));
  1221. }
  1222. return at;
  1223. }
  1224. std::vector<const battle::Unit*> CBattleInfoCallback::getAttackedBattleUnits(const battle::Unit* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1225. {
  1226. std::vector<const battle::Unit*> units;
  1227. RETURN_IF_NOT_BATTLE(units);
  1228. AttackableTiles at;
  1229. if (rangedAttack)
  1230. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1231. else
  1232. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1233. units = battleGetUnitsIf([=](const battle::Unit * unit)
  1234. {
  1235. if (unit->isGhost() || !unit->alive())
  1236. return false;
  1237. for (BattleHex hex : battle::Unit::getHexes(unit->getPosition(), unit->doubleWide(), unit->unitSide()))
  1238. {
  1239. if (vstd::contains(at.hostileCreaturePositions, hex))
  1240. return true;
  1241. if (vstd::contains(at.friendlyCreaturePositions, hex))
  1242. return true;
  1243. }
  1244. return false;
  1245. });
  1246. return units;
  1247. }
  1248. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, bool rangedAttack, BattleHex attackerPos) const
  1249. {
  1250. std::set<const CStack*> attackedCres;
  1251. RETURN_IF_NOT_BATTLE(attackedCres);
  1252. AttackableTiles at;
  1253. if(rangedAttack)
  1254. at = getPotentiallyShootableHexes(attacker, destinationTile, attackerPos);
  1255. else
  1256. at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1257. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1258. {
  1259. const CStack * st = battleGetStackByPos(tile, true);
  1260. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1261. {
  1262. attackedCres.insert(st);
  1263. }
  1264. }
  1265. for (BattleHex tile : at.friendlyCreaturePositions)
  1266. {
  1267. const CStack * st = battleGetStackByPos(tile, true);
  1268. if(st) //friendly stacks can also be damaged by Dragon Breath
  1269. {
  1270. attackedCres.insert(st);
  1271. }
  1272. }
  1273. return attackedCres;
  1274. }
  1275. //TODO: this should apply also to mechanics and cursor interface
  1276. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1277. {
  1278. int fromX = hexFrom.getX();
  1279. int fromY = hexFrom.getY();
  1280. int toX = hexTo.getX();
  1281. int toY = hexTo.getY();
  1282. if (curDir) // attacker, facing right
  1283. {
  1284. if (fromX < toX)
  1285. return false;
  1286. if (fromX > toX)
  1287. return true;
  1288. if (fromY % 2 == 0 && toY % 2 == 1)
  1289. return true;
  1290. return false;
  1291. }
  1292. else // defender, facing left
  1293. {
  1294. if(fromX < toX)
  1295. return true;
  1296. if(fromX > toX)
  1297. return false;
  1298. if (fromY % 2 == 1 && toY % 2 == 0)
  1299. return true;
  1300. return false;
  1301. }
  1302. }
  1303. //TODO: this should apply also to mechanics and cursor interface
  1304. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1305. {
  1306. if (hexTo < 0 || hexFrom < 0) //turret
  1307. return false;
  1308. if (toDoubleWide)
  1309. {
  1310. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1311. {
  1312. if (toDir)
  1313. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1314. else
  1315. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1316. }
  1317. return false;
  1318. }
  1319. else
  1320. {
  1321. return isToReverseHlp(hexFrom, hexTo, curDir);
  1322. }
  1323. }
  1324. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const battle::Unit * unit, BattleHex assumedPosition) const
  1325. {
  1326. ReachabilityInfo::TDistances ret;
  1327. ret.fill(-1);
  1328. RETURN_IF_NOT_BATTLE(ret);
  1329. auto reachability = getReachability(unit);
  1330. boost::copy(reachability.distances, ret.begin());
  1331. return ret;
  1332. }
  1333. bool CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer * shooter, BattleHex shooterPosition, BattleHex destHex) const
  1334. {
  1335. RETURN_IF_NOT_BATTLE(false);
  1336. const std::string cachingStrNoDistancePenalty = "type_NO_DISTANCE_PENALTY";
  1337. static const auto selectorNoDistancePenalty = Selector::type()(Bonus::NO_DISTANCE_PENALTY);
  1338. if(shooter->hasBonus(selectorNoDistancePenalty, cachingStrNoDistancePenalty))
  1339. return false;
  1340. if(auto target = battleGetUnitByPos(destHex, true))
  1341. {
  1342. //If any hex of target creature is within range, there is no penalty
  1343. for(auto hex : target->getHexes())
  1344. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1345. return false;
  1346. //TODO what about two-hex shooters?
  1347. }
  1348. else
  1349. {
  1350. if(BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1351. return false;
  1352. }
  1353. return true;
  1354. }
  1355. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1356. {
  1357. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1358. return WallPartToHex(part);
  1359. }
  1360. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1361. {
  1362. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1363. return hexToWallPart(hex);
  1364. }
  1365. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1366. {
  1367. RETURN_IF_NOT_BATTLE(false);
  1368. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1369. wallPart != EWallPart::INVALID;
  1370. }
  1371. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1372. {
  1373. std::vector<BattleHex> attackableBattleHexes;
  1374. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1375. for(auto & wallPartPair : wallParts)
  1376. {
  1377. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1378. {
  1379. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1380. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1381. {
  1382. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1383. }
  1384. }
  1385. }
  1386. return attackableBattleHexes;
  1387. }
  1388. int32_t CBattleInfoCallback::battleGetSpellCost(const spells::Spell * sp, const CGHeroInstance * caster) const
  1389. {
  1390. RETURN_IF_NOT_BATTLE(-1);
  1391. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1392. int32_t ret = caster->getSpellCost(sp);
  1393. //checking for friendly stacks reducing cost of the spell and
  1394. //enemy stacks increasing it
  1395. int32_t manaReduction = 0;
  1396. int32_t manaIncrease = 0;
  1397. for(auto unit : battleAliveUnits())
  1398. {
  1399. if(unit->unitOwner() == caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1400. {
  1401. vstd::amax(manaReduction, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1402. }
  1403. if(unit->unitOwner() != caster->tempOwner && unit->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1404. {
  1405. vstd::amax(manaIncrease, unit->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1406. }
  1407. }
  1408. return ret - manaReduction + manaIncrease;
  1409. }
  1410. bool CBattleInfoCallback::battleHasShootingPenalty(const battle::Unit * shooter, BattleHex destHex) const
  1411. {
  1412. return battleHasDistancePenalty(shooter, shooter->getPosition(), destHex) || battleHasWallPenalty(shooter, shooter->getPosition(), destHex);
  1413. }
  1414. bool CBattleInfoCallback::battleIsUnitBlocked(const battle::Unit * unit) const
  1415. {
  1416. RETURN_IF_NOT_BATTLE(false);
  1417. if(unit->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1418. return false;
  1419. for(auto adjacent : battleAdjacentUnits(unit))
  1420. {
  1421. if(adjacent->unitOwner() != unit->unitOwner()) //blocked by enemy stack
  1422. return true;
  1423. }
  1424. return false;
  1425. }
  1426. std::set<const battle::Unit *> CBattleInfoCallback::battleAdjacentUnits(const battle::Unit * unit) const
  1427. {
  1428. std::set<const battle::Unit *> ret;
  1429. RETURN_IF_NOT_BATTLE(ret);
  1430. for(auto hex : unit->getSurroundingHexes())
  1431. {
  1432. if(auto neighbour = battleGetUnitByPos(hex, true))
  1433. ret.insert(neighbour);
  1434. }
  1435. return ret;
  1436. }
  1437. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1438. {
  1439. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1440. //This is complete list. No spells from mods.
  1441. //todo: this should be Spellbook of caster Stack
  1442. static const std::set<SpellID> allPossibleSpells =
  1443. {
  1444. SpellID::AIR_SHIELD,
  1445. SpellID::ANTI_MAGIC,
  1446. SpellID::BLESS,
  1447. SpellID::BLOODLUST,
  1448. SpellID::COUNTERSTRIKE,
  1449. SpellID::CURE,
  1450. SpellID::FIRE_SHIELD,
  1451. SpellID::FORTUNE,
  1452. SpellID::HASTE,
  1453. SpellID::MAGIC_MIRROR,
  1454. SpellID::MIRTH,
  1455. SpellID::PRAYER,
  1456. SpellID::PRECISION,
  1457. SpellID::PROTECTION_FROM_AIR,
  1458. SpellID::PROTECTION_FROM_EARTH,
  1459. SpellID::PROTECTION_FROM_FIRE,
  1460. SpellID::PROTECTION_FROM_WATER,
  1461. SpellID::SHIELD,
  1462. SpellID::SLAYER,
  1463. SpellID::STONE_SKIN
  1464. };
  1465. std::vector<SpellID> beneficialSpells;
  1466. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred) -> const CStack *
  1467. {
  1468. auto stacks = battleGetStacksIf([=](const CStack * stack)
  1469. {
  1470. return pred(stack) && stack->owner != subject->owner && stack->isValidTarget(false);
  1471. });
  1472. if(stacks.empty())
  1473. return nullptr;
  1474. else
  1475. return stacks.front();
  1476. };
  1477. for(const SpellID& spellID : allPossibleSpells)
  1478. {
  1479. std::stringstream cachingStr;
  1480. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1481. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1482. //TODO: this ability has special limitations
  1483. || !(spellID.toSpell()->canBeCast(this, spells::Mode::CREATURE_ACTIVE, subject)))
  1484. continue;
  1485. switch (spellID)
  1486. {
  1487. case SpellID::SHIELD:
  1488. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1489. {
  1490. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1491. {
  1492. return !stack->canShoot();
  1493. });
  1494. if (!walker)
  1495. continue;
  1496. }
  1497. break;
  1498. case SpellID::AIR_SHIELD: //only against active shooters
  1499. {
  1500. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1501. {
  1502. return stack->canShoot();
  1503. });
  1504. if (!shooter)
  1505. continue;
  1506. }
  1507. break;
  1508. case SpellID::ANTI_MAGIC:
  1509. case SpellID::MAGIC_MIRROR:
  1510. case SpellID::PROTECTION_FROM_AIR:
  1511. case SpellID::PROTECTION_FROM_EARTH:
  1512. case SpellID::PROTECTION_FROM_FIRE:
  1513. case SpellID::PROTECTION_FROM_WATER:
  1514. {
  1515. const ui8 enemySide = 1 - subject->side;
  1516. //todo: only if enemy has spellbook
  1517. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1518. continue;
  1519. }
  1520. break;
  1521. case SpellID::CURE: //only damaged units
  1522. {
  1523. //do not cast on affected by debuffs
  1524. if(!subject->canBeHealed())
  1525. continue;
  1526. }
  1527. break;
  1528. case SpellID::BLOODLUST:
  1529. {
  1530. if(subject->canShoot()) //TODO: if can shoot - only if enemy units are adjacent
  1531. continue;
  1532. }
  1533. break;
  1534. case SpellID::PRECISION:
  1535. {
  1536. if(!subject->canShoot())
  1537. continue;
  1538. }
  1539. break;
  1540. case SpellID::SLAYER://only if monsters are present
  1541. {
  1542. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1543. {
  1544. const auto isKing = Selector::type()(Bonus::KING1)
  1545. .Or(Selector::type()(Bonus::KING2))
  1546. .Or(Selector::type()(Bonus::KING3));
  1547. return stack->hasBonus(isKing);
  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(CRandomGenerator & rand,const CStack * caster) const
  1566. {
  1567. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1568. TConstBonusListPtr bl = caster->getBonuses(Selector::type()(Bonus::SPELLCASTER));
  1569. if (!bl->size())
  1570. return SpellID::NONE;
  1571. int totalWeight = 0;
  1572. for(auto b : *bl)
  1573. {
  1574. totalWeight += std::max(b->additionalInfo[0], 1); //minimal chance to cast is 1
  1575. }
  1576. int randomPos = rand.nextInt(totalWeight - 1);
  1577. for(auto b : *bl)
  1578. {
  1579. randomPos -= std::max(b->additionalInfo[0], 1);
  1580. if(randomPos < 0)
  1581. {
  1582. return SpellID(b->subtype);
  1583. }
  1584. }
  1585. return SpellID::NONE;
  1586. }
  1587. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1588. {
  1589. RETURN_IF_NOT_BATTLE(-3);
  1590. if(!battleCanSurrender(Player))
  1591. return -1;
  1592. const auto sideOpt = playerToSide(Player);
  1593. if(!sideOpt)
  1594. return -1;
  1595. const auto side = sideOpt.get();
  1596. int ret = 0;
  1597. double discount = 0;
  1598. for(auto unit : battleAliveUnits(side))
  1599. ret += unit->getRawSurrenderCost();
  1600. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1601. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1602. ret = static_cast<int>(ret * (100.0 - discount) / 100.0);
  1603. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1604. return ret;
  1605. }
  1606. si8 CBattleInfoCallback::battleMinSpellLevel(ui8 side) const
  1607. {
  1608. const IBonusBearer * node = nullptr;
  1609. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1610. node = h;
  1611. else
  1612. node = getBattleNode();
  1613. if(!node)
  1614. return 0;
  1615. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_BELOW));
  1616. if(b->size())
  1617. return b->totalValue();
  1618. return 0;
  1619. }
  1620. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1621. {
  1622. const IBonusBearer *node = nullptr;
  1623. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1624. node = h;
  1625. else
  1626. node = getBattleNode();
  1627. if(!node)
  1628. return GameConstants::SPELL_LEVELS;
  1629. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1630. auto b = node->getBonuses(Selector::type()(Bonus::BLOCK_MAGIC_ABOVE));
  1631. if(b->size())
  1632. return b->totalValue();
  1633. return GameConstants::SPELL_LEVELS;
  1634. }
  1635. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1636. {
  1637. auto units = battleGetUnitsIf([=](const battle::Unit * unit)
  1638. {
  1639. return unit->alive() && !unit->isTurret() && !unit->hasBonusOfType(Bonus::SIEGE_WEAPON);
  1640. });
  1641. std::array<bool, 2> hasUnit = {false, false}; //index is BattleSide
  1642. for(auto & unit : units)
  1643. {
  1644. //todo: move SIEGE_WEAPON check to Unit state
  1645. hasUnit.at(unit->unitSide()) = true;
  1646. if(hasUnit[0] && hasUnit[1])
  1647. return boost::none;
  1648. }
  1649. hasUnit = {false, false};
  1650. for(auto & unit : units)
  1651. {
  1652. if(!unit->isClone() && !unit->acquireState()->summoned && !dynamic_cast <const CCommanderInstance *>(unit))
  1653. {
  1654. hasUnit.at(unit->unitSide()) = true;
  1655. }
  1656. }
  1657. if(!hasUnit[0] && !hasUnit[1])
  1658. return 2;
  1659. if(!hasUnit[1])
  1660. return 0;
  1661. else
  1662. return 1;
  1663. }