CBattleInfoCallback.cpp 59 KB

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