CBattleInfoCallback.cpp 64 KB

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