CBattleInfoCallback.cpp 62 KB

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