CBattleInfoCallback.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. /*
  2. * CBattleCallback.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. static void retreiveTurretDamageRange(const CGTownInstance * town, const CStack * turret, double & outMinDmg, double & outMaxDmg)
  20. {
  21. assert(turret->getCreature()->idNumber == CreatureID::ARROW_TOWERS);
  22. assert(town);
  23. assert(turret->position >= -4 && turret->position <= -2);
  24. float multiplier = (turret->position == -2) ? 1 : 0.5;
  25. int baseMin = 6;
  26. int baseMax = 10;
  27. outMinDmg = multiplier * (baseMin + town->getTownLevel() * 2);
  28. outMaxDmg = multiplier * (baseMax + town->getTownLevel() * 3);
  29. }
  30. static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
  31. {
  32. static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  33. return lineToHex[line];
  34. }
  35. static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
  36. {
  37. const int wallInStackLine = lineToWallHex(pos1.getY());
  38. const int wallInDestLine = lineToWallHex(pos2.getY());
  39. const bool stackLeft = pos1 < wallInStackLine;
  40. const bool destLeft = pos2 < wallInDestLine;
  41. return stackLeft == destLeft;
  42. }
  43. // parts of wall
  44. static const std::pair<int, EWallPart::EWallPart> wallParts[] =
  45. {
  46. std::make_pair(50, EWallPart::KEEP),
  47. std::make_pair(183, EWallPart::BOTTOM_TOWER),
  48. std::make_pair(182, EWallPart::BOTTOM_WALL),
  49. std::make_pair(130, EWallPart::BELOW_GATE),
  50. std::make_pair(78, EWallPart::OVER_GATE),
  51. std::make_pair(29, EWallPart::UPPER_WALL),
  52. std::make_pair(12, EWallPart::UPPER_TOWER),
  53. std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
  54. std::make_pair(96, EWallPart::GATE),
  55. std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
  56. std::make_pair(62, EWallPart::INDESTRUCTIBLE_PART),
  57. std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
  58. std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART),
  59. std::make_pair(165, EWallPart::INDESTRUCTIBLE_PART)
  60. };
  61. static EWallPart::EWallPart hexToWallPart(BattleHex hex)
  62. {
  63. for(auto & elem : wallParts)
  64. {
  65. if(elem.first == hex)
  66. return elem.second;
  67. }
  68. return EWallPart::INVALID; //not found!
  69. }
  70. static BattleHex WallPartToHex(EWallPart::EWallPart part)
  71. {
  72. for(auto & elem : wallParts)
  73. {
  74. if(elem.second == part)
  75. return elem.first;
  76. }
  77. return BattleHex::INVALID; //not found!
  78. }
  79. }
  80. using namespace SiegeStuffThatShouldBeMovedToHandlers;
  81. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(const ISpellCaster * caster, ECastingMode::ECastingMode mode) const
  82. {
  83. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  84. if(caster == nullptr)
  85. {
  86. logGlobal->error("CBattleInfoCallback::battleCanCastSpell: no spellcaster.");
  87. return ESpellCastProblem::INVALID;
  88. }
  89. const PlayerColor player = caster->getOwner();
  90. const si8 side = playerToSide(player);
  91. if(side < 0)
  92. return ESpellCastProblem::INVALID;
  93. if(!battleDoWeKnowAbout(side))
  94. {
  95. logGlobal->warnStream() << "You can't check if enemy can cast given spell!";
  96. return ESpellCastProblem::INVALID;
  97. }
  98. if(battleTacticDist())
  99. return ESpellCastProblem::ONGOING_TACTIC_PHASE;
  100. switch (mode)
  101. {
  102. case ECastingMode::HERO_CASTING:
  103. {
  104. if(battleCastSpells(side) > 0)
  105. return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
  106. auto hero = dynamic_cast<const CGHeroInstance *>(caster);
  107. if(!hero)
  108. return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
  109. if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
  110. return ESpellCastProblem::MAGIC_IS_BLOCKED;
  111. }
  112. break;
  113. default:
  114. break;
  115. }
  116. return ESpellCastProblem::OK;
  117. }
  118. si8 CBattleInfoCallback::battleHasWallPenalty(const CStack * stack, BattleHex destHex) const
  119. {
  120. return battleHasWallPenalty(stack, stack->position, destHex);
  121. }
  122. si8 CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer * bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  123. {
  124. RETURN_IF_NOT_BATTLE(false);
  125. if (!battleGetSiegeLevel() || bonusBearer->hasBonusOfType(Bonus::NO_WALL_PENALTY))
  126. return false;
  127. const int wallInStackLine = lineToWallHex(shooterPosition.getY());
  128. const int wallInDestLine = lineToWallHex(destHex.getY());
  129. const bool stackLeft = shooterPosition < wallInStackLine;
  130. const bool destRight = destHex > wallInDestLine;
  131. if (stackLeft && destRight) //shooting from outside to inside
  132. {
  133. int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
  134. if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
  135. row -= 2;
  136. const int wallPos = lineToWallHex(row);
  137. if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
  138. }
  139. return false;
  140. }
  141. si8 CBattleInfoCallback::battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
  142. {
  143. RETURN_IF_NOT_BATTLE(false);
  144. if (!getAccesibility(stack).accessible(destHex, stack))
  145. return false;
  146. const ui8 siegeLevel = battleGetSiegeLevel();
  147. //check for wall
  148. //advanced teleport can pass wall of fort|citadel, expert - of castle
  149. if ((siegeLevel > CGTownInstance::NONE && telportLevel < 2) || (siegeLevel >= CGTownInstance::CASTLE && telportLevel < 3))
  150. return sameSideOfWall(stack->position, destHex);
  151. return true;
  152. }
  153. std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  154. {
  155. std::set<BattleHex> attackedHexes;
  156. RETURN_IF_NOT_BATTLE(attackedHexes);
  157. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  158. for (BattleHex tile : at.hostileCreaturePositions)
  159. {
  160. const CStack * st = battleGetStackByPos(tile, true);
  161. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  162. {
  163. attackedHexes.insert(tile);
  164. }
  165. }
  166. for (BattleHex tile : at.friendlyCreaturePositions)
  167. {
  168. if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
  169. {
  170. attackedHexes.insert(tile);
  171. }
  172. }
  173. return attackedHexes;
  174. }
  175. SpellID CBattleInfoCallback::battleGetRandomStackSpell(CRandomGenerator & rand, const CStack * stack, ERandomSpell mode) const
  176. {
  177. switch (mode)
  178. {
  179. case RANDOM_GENIE:
  180. return getRandomBeneficialSpell(rand, stack); //target
  181. break;
  182. case RANDOM_AIMED:
  183. return getRandomCastedSpell(rand, stack); //caster
  184. break;
  185. default:
  186. logGlobal->errorStream() << "Incorrect mode of battleGetRandomSpell (" << mode <<")";
  187. return SpellID::NONE;
  188. }
  189. }
  190. const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
  191. {
  192. RETURN_IF_NOT_BATTLE(nullptr);
  193. for(auto s : battleGetAllStacks(true))
  194. if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
  195. return s;
  196. return nullptr;
  197. }
  198. void CBattleInfoCallback::battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn /*= 0*/, int lastMoved /*= -1*/) const
  199. {
  200. RETURN_IF_NOT_BATTLE();
  201. //let's define a huge lambda
  202. auto takeStack = [&](std::vector<const CStack *> &st) -> const CStack*
  203. {
  204. const CStack * ret = nullptr;
  205. unsigned i, //fastest stack
  206. j=0; //fastest stack of the other side
  207. for(i = 0; i < st.size(); i++)
  208. if(st[i])
  209. break;
  210. //no stacks left
  211. if(i == st.size())
  212. return nullptr;
  213. const CStack * fastest = st[i], *other = nullptr;
  214. int bestSpeed = fastest->Speed(turn);
  215. //FIXME: comparison between bool and integer. Logic does not makes sense either
  216. if(fastest->attackerOwned != lastMoved)
  217. {
  218. ret = fastest;
  219. }
  220. else
  221. {
  222. for(j = i + 1; j < st.size(); j++)
  223. {
  224. if(!st[j]) continue;
  225. if(st[j]->attackerOwned != lastMoved || st[j]->Speed(turn) != bestSpeed)
  226. break;
  227. }
  228. if(j >= st.size())
  229. {
  230. ret = fastest;
  231. }
  232. else
  233. {
  234. other = st[j];
  235. if(other->Speed(turn) != bestSpeed)
  236. ret = fastest;
  237. else
  238. ret = other;
  239. }
  240. }
  241. assert(ret);
  242. if(ret == fastest)
  243. st[i] = nullptr;
  244. else
  245. st[j] = nullptr;
  246. lastMoved = ret->attackerOwned;
  247. return ret;
  248. };
  249. //We'll split creatures with remaining movement to 4 buckets
  250. // [0] - turrets/catapult,
  251. // [1] - normal (unmoved) creatures, other war machines,
  252. // [2] - waited cres that had morale,
  253. // [3] - rest of waited cres
  254. std::vector<const CStack *> phase[4];
  255. int toMove = 0; //how many stacks still has move
  256. const CStack * active = battleActiveStack();
  257. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  258. if(!turn && active && active->willMove() && !active->waited())
  259. {
  260. out.push_back(active);
  261. if(out.size() == howMany)
  262. return;
  263. }
  264. auto allStacks = battleGetAllStacks(true);
  265. if(!vstd::contains_if(allStacks, [](const CStack *stack) { return stack->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
  266. {
  267. //No stack will be able to move, battle is over.
  268. out.clear();
  269. return;
  270. }
  271. for(auto s : battleGetAllStacks(true))
  272. {
  273. if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
  274. || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
  275. || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
  276. {
  277. continue;
  278. }
  279. int p = -1; //in which phase this tack will move?
  280. if(turn <= 0 && s->waited()) //consider waiting state only for ongoing round
  281. {
  282. if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
  283. p = 2;
  284. else
  285. p = 3;
  286. }
  287. else if(s->getCreature()->idNumber == CreatureID::CATAPULT || s->getCreature()->idNumber == CreatureID::ARROW_TOWERS) //catapult and turrets are first
  288. {
  289. p = 0;
  290. }
  291. else
  292. {
  293. p = 1;
  294. }
  295. phase[p].push_back(s);
  296. toMove++;
  297. }
  298. for(int i = 0; i < 4; i++)
  299. boost::sort(phase[i], CMP_stack(i, turn > 0 ? turn : 0));
  300. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  301. out.push_back(phase[0][i]);
  302. if(out.size() == howMany)
  303. return;
  304. if(lastMoved == -1)
  305. {
  306. if(active)
  307. {
  308. //FIXME: both branches contain same code!!!
  309. if(out.size() && out.front() == active)
  310. lastMoved = active->attackerOwned;
  311. else
  312. lastMoved = active->attackerOwned;
  313. }
  314. else
  315. {
  316. lastMoved = 0;
  317. }
  318. }
  319. int pi = 1;
  320. while(out.size() < howMany)
  321. {
  322. const CStack * hlp = takeStack(phase[pi]);
  323. if(!hlp)
  324. {
  325. pi++;
  326. if(pi > 3)
  327. {
  328. //if(turn != 2)
  329. battleGetStackQueue(out, howMany, turn + 1, lastMoved);
  330. return;
  331. }
  332. }
  333. else
  334. {
  335. out.push_back(hlp);
  336. }
  337. }
  338. }
  339. void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
  340. {
  341. RETURN_IF_NOT_BATTLE();
  342. auto accessibility = getAccesibility();
  343. for(int i = 0; i < accessibility.size(); i++)
  344. ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
  345. }
  346. std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable) const
  347. {
  348. std::vector<BattleHex> ret;
  349. RETURN_IF_NOT_BATTLE(ret);
  350. if(!stack->position.isValid()) //turrets
  351. return ret;
  352. auto reachability = getReachability(stack);
  353. for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
  354. {
  355. // If obstacles or other stacks makes movement impossible, it can't be helped.
  356. if(!reachability.isReachable(i))
  357. continue;
  358. if(battleTacticDist() && battleGetTacticsSide() == !stack->attackerOwned)
  359. {
  360. //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
  361. if(!isInTacticRange(i))
  362. continue;
  363. }
  364. else
  365. {
  366. //Not tactics phase -> destination must be reachable and within stack range.
  367. if(reachability.distances[i] > stack->Speed(0, true))
  368. continue;
  369. }
  370. ret.push_back(i);
  371. if(addOccupiable && stack->doubleWide())
  372. {
  373. //If two-hex stack can stand on hex i then obviously it can occupy its second hex from that position
  374. ret.push_back(stack->occupiedHex(i));
  375. }
  376. }
  377. if(attackable)
  378. {
  379. auto meleeAttackable = [&](BattleHex hex) -> bool
  380. {
  381. // Return true if given hex has at least one available neighbour.
  382. // Available hexes are already present in ret vector.
  383. auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
  384. {
  385. return BattleHex::mutualPosition(hex, availableHex) >= 0;
  386. });
  387. return availableNeighbor != ret.end();
  388. };
  389. for(const CStack * otherSt : battleAliveStacks(stack->attackerOwned))
  390. {
  391. if(!otherSt->isValidTarget(false))
  392. continue;
  393. std::vector<BattleHex> occupied = otherSt->getHexes();
  394. if(battleCanShoot(stack, otherSt->position))
  395. {
  396. attackable->insert(attackable->end(), occupied.begin(), occupied.end());
  397. continue;
  398. }
  399. for(BattleHex he : occupied)
  400. {
  401. if(meleeAttackable(he))
  402. attackable->push_back(he);
  403. }
  404. }
  405. }
  406. //adding occupiable likely adds duplicates to ret -> clean it up
  407. boost::sort(ret);
  408. ret.erase(boost::unique(ret).end(), ret.end());
  409. return ret;
  410. }
  411. bool CBattleInfoCallback::battleCanAttack(const CStack * stack, const CStack * target, BattleHex dest) const
  412. {
  413. RETURN_IF_NOT_BATTLE(false);
  414. if(battleTacticDist())
  415. return false;
  416. if (!stack || !target)
  417. return false;
  418. if(!battleMatchOwner(stack, target))
  419. return false;
  420. auto &id = stack->getCreature()->idNumber;
  421. if (id == CreatureID::FIRST_AID_TENT || id == CreatureID::CATAPULT)
  422. return false;
  423. if (!target->alive())
  424. return false;
  425. return true;
  426. }
  427. bool CBattleInfoCallback::battleCanShoot(const CStack * stack, BattleHex dest) const
  428. {
  429. RETURN_IF_NOT_BATTLE(false);
  430. if(battleTacticDist()) //no shooting during tactics
  431. return false;
  432. const CStack * dst = battleGetStackByPos(dest);
  433. if(!stack || !dst)
  434. return false;
  435. //forgetfulness
  436. TBonusListPtr forgetfulList = stack->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  437. if(!forgetfulList->empty())
  438. {
  439. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  440. //advanced+ level
  441. if(forgetful > 1)
  442. return false;
  443. }
  444. if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
  445. return false;
  446. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  447. && battleMatchOwner(stack, dst)
  448. && dst->alive()
  449. && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
  450. && stack->shots
  451. )
  452. return true;
  453. return false;
  454. }
  455. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
  456. ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  457. {
  458. return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  459. }
  460. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo & info) const
  461. {
  462. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  463. {
  464. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  465. auto limitMatches = info.shooting
  466. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  467. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  468. //any regular bonuses or just ones for melee/ranged
  469. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  470. };
  471. double additiveBonus = 1.0, multBonus = 1.0,
  472. minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
  473. maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
  474. const CCreature *attackerType = info.attacker->getCreature(),
  475. *defenderType = info.defender->getCreature();
  476. if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
  477. {
  478. SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  479. }
  480. if(info.attackerBonuses->hasBonusOfType(Bonus::SIEGE_WEAPON) && attackerType->idNumber != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  481. { //minDmg and maxDmg are multiplied by hero attack + 1
  482. auto retreiveHeroPrimSkill = [&](int skill) -> int
  483. {
  484. const std::shared_ptr<Bonus> b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  485. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  486. };
  487. minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  488. maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  489. }
  490. int attackDefenceDifference = 0;
  491. double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
  492. attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
  493. double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
  494. attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
  495. if(const std::shared_ptr<Bonus> slayerEffect = info.attackerBonuses->getBonus(Selector::type(Bonus::SLAYER))) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  496. {
  497. std::vector<int> affectedIds;
  498. int spLevel = slayerEffect->val;
  499. //FIXME: do not check all creatures
  500. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  501. {
  502. for(const std::shared_ptr<Bonus> b : VLC->creh->creatures[g]->getBonusList())
  503. {
  504. if ((b->type == Bonus::KING3 && spLevel >= 3) || //expert
  505. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  506. (b->type == Bonus::KING1 && spLevel >= 0)) //none or basic +
  507. {
  508. affectedIds.push_back(g);
  509. break;
  510. }
  511. }
  512. }
  513. for(auto & affectedId : affectedIds)
  514. {
  515. if(defenderType->idNumber == affectedId)
  516. {
  517. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
  518. break;
  519. }
  520. }
  521. }
  522. //bonus from attack/defense skills
  523. if(attackDefenceDifference < 0) //decreasing dmg
  524. {
  525. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  526. multBonus *= 1.0 - dec;
  527. }
  528. else //increasing dmg
  529. {
  530. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  531. additiveBonus += inc;
  532. }
  533. //applying jousting bonus
  534. if(info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY))
  535. additiveBonus += info.chargedFields * 0.05;
  536. //handling secondary abilities and artifacts giving premies to them
  537. if(info.shooting)
  538. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
  539. else
  540. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
  541. if(info.defenderBonuses)
  542. multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
  543. //handling hate effect
  544. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
  545. //luck bonus
  546. if (info.luckyHit)
  547. {
  548. additiveBonus += 1.0;
  549. }
  550. //unlucky hit, used only if negative luck is enabled
  551. if (info.unluckyHit)
  552. {
  553. additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
  554. }
  555. //ballista double dmg
  556. if(info.ballistaDoubleDamage)
  557. {
  558. additiveBonus += 1.0;
  559. }
  560. if (info.deathBlow) //Dread Knight and many WoGified creatures
  561. {
  562. additiveBonus += 1.0;
  563. }
  564. //handling spell effects
  565. if(!info.shooting) //eg. shield
  566. {
  567. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
  568. }
  569. else if(info.shooting) //eg. air shield
  570. {
  571. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
  572. }
  573. if(info.shooting)
  574. {
  575. //todo: set actual percentage in spell bonus configuration instead of just level; requires non trivial backward compatibility handling
  576. //get list first, total value of 0 also counts
  577. TBonusListPtr forgetfulList = info.attackerBonuses->getBonuses(Selector::type(Bonus::FORGETFULL),"");
  578. if(!forgetfulList->empty())
  579. {
  580. int forgetful = forgetfulList->valOfBonuses(Selector::type(Bonus::FORGETFULL));
  581. //none of basic level
  582. if(forgetful == 0 || forgetful == 1)
  583. multBonus *= 0.5;
  584. else
  585. logGlobal->warn("Attempt to calculate shooting damage with adv+ FORGETFULL effect");
  586. }
  587. }
  588. TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
  589. TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
  590. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  591. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo<std::shared_ptr<Bonus>>))->additionalInfo : 0;
  592. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  593. {
  594. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  595. }
  596. auto isAdvancedAirShield = [](const Bonus* bonus)
  597. {
  598. return bonus->source == Bonus::SPELL_EFFECT
  599. && bonus->sid == SpellID::AIR_SHIELD
  600. && bonus->val >= SecSkillLevel::ADVANCED;
  601. };
  602. //wall / distance penalty + advanced air shield
  603. const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  604. const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  605. if(info.shooting)
  606. {
  607. if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
  608. {
  609. multBonus *= 0.5;
  610. }
  611. if (obstaclePenalty)
  612. {
  613. multBonus *= 0.5; //cumulative
  614. }
  615. }
  616. if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  617. {
  618. multBonus *= 0.5;
  619. }
  620. // psychic elementals versus mind immune units 50%
  621. if(attackerType->idNumber == CreatureID::PSYCHIC_ELEMENTAL
  622. && info.defenderBonuses->hasBonusOfType(Bonus::MIND_IMMUNITY))
  623. {
  624. multBonus *= 0.5;
  625. }
  626. // TODO attack on petrified unit 50%
  627. // blinded unit retaliates
  628. minDmg *= additiveBonus * multBonus;
  629. maxDmg *= additiveBonus * multBonus;
  630. TDmgRange returnedVal;
  631. if(curseEffects->size()) //curse handling (rest)
  632. {
  633. minDmg += curseBlessAdditiveModifier;
  634. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  635. }
  636. else if(blessEffects->size()) //bless handling
  637. {
  638. maxDmg += curseBlessAdditiveModifier;
  639. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  640. }
  641. else
  642. {
  643. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  644. }
  645. //damage cannot be less than 1
  646. vstd::amax(returnedVal.first, 1);
  647. vstd::amax(returnedVal.second, 1);
  648. return returnedVal;
  649. }
  650. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, TQuantity attackerCount,
  651. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  652. {
  653. BattleAttackInfo bai(attacker, defender, shooting);
  654. bai.attackerCount = attackerCount;
  655. bai.chargedFields = charge;
  656. bai.luckyHit = lucky;
  657. bai.unluckyHit = unlucky;
  658. bai.deathBlow = deathBlow;
  659. bai.ballistaDoubleDamage = ballistaDoubleDmg;
  660. return calculateDmgRange(bai);
  661. }
  662. TDmgRange CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  663. {
  664. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  665. const bool shooting = battleCanShoot(attacker, defender->position);
  666. const BattleAttackInfo bai(attacker, defender, shooting);
  667. return battleEstimateDamage(rand, bai, retaliationDmg);
  668. }
  669. std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(CRandomGenerator & rand, const BattleAttackInfo & bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
  670. {
  671. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  672. //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
  673. //const ui8 mySide = !attacker->attackerOwned;
  674. TDmgRange ret = calculateDmgRange(bai);
  675. if(retaliationDmg)
  676. {
  677. if(bai.shooting)
  678. {
  679. retaliationDmg->first = retaliationDmg->second = 0;
  680. }
  681. else
  682. {
  683. ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  684. for (int i=0; i<2; ++i)
  685. {
  686. BattleStackAttacked bsa;
  687. bsa.damageAmount = ret.*pairElems[i];
  688. bai.defender->prepareAttacked(bsa, rand, bai.defenderCount);
  689. auto retaliationAttack = bai.reverse();
  690. retaliationAttack.attackerCount = bsa.newAmount;
  691. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  692. }
  693. }
  694. }
  695. return ret;
  696. }
  697. std::shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
  698. {
  699. RETURN_IF_NOT_BATTLE(std::shared_ptr<const CObstacleInstance>());
  700. for(auto &obs : battleGetAllObstacles())
  701. {
  702. if(vstd::contains(obs->getBlockedTiles(), tile)
  703. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  704. {
  705. return obs;
  706. }
  707. }
  708. return std::shared_ptr<const CObstacleInstance>();
  709. }
  710. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  711. {
  712. AccessibilityInfo ret;
  713. ret.fill(EAccessibility::ACCESSIBLE);
  714. //removing accessibility for side columns of hexes
  715. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  716. {
  717. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  718. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  719. }
  720. //gate -> should be before stacks
  721. if(battleGetSiegeLevel() > 0)
  722. {
  723. EAccessibility accessability = EAccessibility::ACCESSIBLE;
  724. switch(battleGetGateState())
  725. {
  726. case EGateState::CLOSED:
  727. accessability = EAccessibility::GATE;
  728. break;
  729. case EGateState::BLOCKED:
  730. accessability = EAccessibility::UNAVAILABLE;
  731. break;
  732. }
  733. ret[ESiegeHex::GATE_OUTER] = ret[ESiegeHex::GATE_INNER] = accessability;
  734. }
  735. //tiles occupied by standing stacks
  736. for(auto stack : battleAliveStacks())
  737. {
  738. for(auto hex : stack->getHexes())
  739. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  740. ret[hex] = EAccessibility::ALIVE_STACK;
  741. }
  742. //obstacles
  743. for(const auto &obst : battleGetAllObstacles())
  744. {
  745. for(auto hex : obst->getBlockedTiles())
  746. ret[hex] = EAccessibility::OBSTACLE;
  747. }
  748. //walls
  749. if(battleGetSiegeLevel() > 0)
  750. {
  751. static const int permanentlyLocked[] = {12, 45, 62, 112, 147, 165};
  752. for(auto hex : permanentlyLocked)
  753. ret[hex] = EAccessibility::UNAVAILABLE;
  754. //TODO likely duplicated logic
  755. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] =
  756. {
  757. //which part of wall, which hex is blocked if this part of wall is not destroyed
  758. std::make_pair(2, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_4)),
  759. std::make_pair(3, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_3)),
  760. std::make_pair(4, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_2)),
  761. std::make_pair(5, BattleHex(ESiegeHex::DESTRUCTIBLE_WALL_1))
  762. };
  763. for(auto & elem : lockedIfNotDestroyed)
  764. {
  765. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  766. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  767. }
  768. }
  769. return ret;
  770. }
  771. AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack * stack) const
  772. {
  773. return getAccesibility(stack->getHexes());
  774. }
  775. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> & accessibleHexes) const
  776. {
  777. auto ret = getAccesibility();
  778. for(auto hex : accessibleHexes)
  779. if(hex.isValid())
  780. ret[hex] = EAccessibility::ACCESSIBLE;
  781. return ret;
  782. }
  783. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters & params) const
  784. {
  785. ReachabilityInfo ret;
  786. ret.accessibility = accessibility;
  787. ret.params = params;
  788. ret.predecessors.fill(BattleHex::INVALID);
  789. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  790. if(!params.startPosition.isValid()) //if got call for arrow turrets
  791. return ret;
  792. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  793. //const bool twoHexCreature = params.doubleWide;
  794. std::queue<BattleHex> hexq; //bfs queue
  795. //first element
  796. hexq.push(params.startPosition);
  797. ret.distances[params.startPosition] = 0;
  798. while(!hexq.empty()) //bfs loop
  799. {
  800. const BattleHex curHex = hexq.front();
  801. hexq.pop();
  802. //walking stack can't step past the quicksands
  803. //TODO what if second hex of two-hex creature enters quicksand
  804. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  805. continue;
  806. const int costToNeighbour = ret.distances[curHex] + 1;
  807. for(BattleHex neighbour : curHex.neighbouringTiles())
  808. {
  809. const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.attackerOwned);
  810. const int costFoundSoFar = ret.distances[neighbour];
  811. if(accessible && costToNeighbour < costFoundSoFar)
  812. {
  813. hexq.push(neighbour);
  814. ret.distances[neighbour] = costToNeighbour;
  815. ret.predecessors[neighbour] = curHex;
  816. }
  817. }
  818. }
  819. return ret;
  820. }
  821. ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack * stack) const
  822. {
  823. return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
  824. }
  825. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  826. {
  827. std::set<BattleHex> ret;
  828. RETURN_IF_NOT_BATTLE(ret);
  829. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  830. {
  831. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  832. {
  833. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  834. }
  835. }
  836. return ret;
  837. }
  838. std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  839. {
  840. auto reachability = getReachability(closest);
  841. auto avHexes = battleGetAvailableHexes(closest, false);
  842. // I hate std::pairs with their undescriptive member names first / second
  843. struct DistStack
  844. {
  845. int distanceToPred;
  846. BattleHex destination;
  847. const CStack * stack;
  848. };
  849. std::vector<DistStack> stackPairs;
  850. std::vector<const CStack *> possibleStacks = battleGetStacksIf([=](const CStack * s)
  851. {
  852. return s->isValidTarget(false) && s != closest && (boost::logic::indeterminate(attackerOwned) || s->attackerOwned == attackerOwned);
  853. });
  854. for(const CStack * st : possibleStacks)
  855. for(BattleHex hex : avHexes)
  856. if(CStack::isMeleeAttackPossible(closest, st, hex))
  857. {
  858. DistStack hlp = {reachability.distances[hex], hex, st};
  859. stackPairs.push_back(hlp);
  860. }
  861. if (stackPairs.size())
  862. {
  863. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  864. auto minimal = boost::min_element(stackPairs, comparator);
  865. return std::make_pair(minimal->stack, minimal->destination);
  866. }
  867. else
  868. return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
  869. }
  870. si8 CBattleInfoCallback::battleGetTacticDist() const
  871. {
  872. RETURN_IF_NOT_BATTLE(0);
  873. //TODO get rid of this method
  874. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  875. return battleTacticDist();
  876. return 0;
  877. }
  878. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  879. {
  880. RETURN_IF_NOT_BATTLE(false);
  881. auto side = battleGetTacticsSide();
  882. auto dist = battleGetTacticDist();
  883. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  884. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  885. }
  886. ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
  887. {
  888. ReachabilityInfo::Parameters params(stack);
  889. if(!battleDoWeKnowAbout(!stack->attackerOwned))
  890. {
  891. //Stack is held by enemy, we can't use his perspective to check for reachability.
  892. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  893. params.perspective = battleGetMySide();
  894. }
  895. return getReachability(params);
  896. }
  897. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  898. {
  899. if(params.flying)
  900. return getFlyingReachability(params);
  901. else
  902. return makeBFS(getAccesibility(params.knownAccessible), params);
  903. }
  904. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  905. {
  906. ReachabilityInfo ret;
  907. ret.accessibility = getAccesibility(params.knownAccessible);
  908. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  909. {
  910. if(ret.accessibility.accessible(i, params.doubleWide, params.attackerOwned))
  911. {
  912. ret.predecessors[i] = params.startPosition;
  913. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  914. }
  915. }
  916. return ret;
  917. }
  918. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  919. {
  920. //does not return hex attacked directly
  921. //TODO: apply rotation to two-hex attackers
  922. bool isAttacker = attacker->attackerOwned;
  923. AttackableTiles at;
  924. RETURN_IF_NOT_BATTLE(at);
  925. const int WN = GameConstants::BFIELD_WIDTH;
  926. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  927. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  928. bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  929. if (reverse && attacker->doubleWide())
  930. {
  931. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  932. }
  933. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  934. {
  935. boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
  936. }
  937. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  938. {
  939. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  940. for (BattleHex tile : hexes)
  941. {
  942. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  943. {
  944. const CStack * st = battleGetStackByPos(tile, true);
  945. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  946. {
  947. at.hostileCreaturePositions.insert(tile);
  948. }
  949. }
  950. }
  951. }
  952. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  953. {
  954. std::vector<BattleHex> hexes; //only one, in fact
  955. int pseudoVector = destinationTile.hex - hex;
  956. switch (pseudoVector)
  957. {
  958. case 1:
  959. case -1:
  960. BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
  961. break;
  962. case WN: //17 //left-down or right-down
  963. case -WN: //-17 //left-up or right-up
  964. case WN + 1: //18 //right-down
  965. case -WN + 1: //-16 //right-up
  966. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : -1), hexes);
  967. break;
  968. case WN-1: //16 //left-down
  969. case -WN-1: //-18 //left-up
  970. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : 0), hexes);
  971. break;
  972. }
  973. for (BattleHex tile : hexes)
  974. {
  975. //friendly stacks can also be damaged by Dragon Breath
  976. if (battleGetStackByPos (tile, true))
  977. at.friendlyCreaturePositions.insert (tile);
  978. }
  979. }
  980. return at;
  981. }
  982. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  983. {
  984. std::set<const CStack*> attackedCres;
  985. RETURN_IF_NOT_BATTLE(attackedCres);
  986. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  987. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  988. {
  989. const CStack * st = battleGetStackByPos(tile, true);
  990. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  991. {
  992. attackedCres.insert(st);
  993. }
  994. }
  995. for (BattleHex tile : at.friendlyCreaturePositions)
  996. {
  997. const CStack * st = battleGetStackByPos(tile, true);
  998. if(st) //friendly stacks can also be damaged by Dragon Breath
  999. {
  1000. attackedCres.insert(st);
  1001. }
  1002. }
  1003. return attackedCres;
  1004. }
  1005. //TODO: this should apply also to mechanics and cursor interface
  1006. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1007. {
  1008. int fromX = hexFrom.getX();
  1009. int fromY = hexFrom.getY();
  1010. int toX = hexTo.getX();
  1011. int toY = hexTo.getY();
  1012. if (curDir) // attacker, facing right
  1013. {
  1014. if (fromX < toX)
  1015. return false;
  1016. if (fromX > toX)
  1017. return true;
  1018. if (fromY % 2 == 0 && toY % 2 == 1)
  1019. return true;
  1020. return false;
  1021. }
  1022. else // defender, facing left
  1023. {
  1024. if(fromX < toX)
  1025. return true;
  1026. if(fromX > toX)
  1027. return false;
  1028. if (fromY % 2 == 1 && toY % 2 == 0)
  1029. return true;
  1030. return false;
  1031. }
  1032. }
  1033. //TODO: this should apply also to mechanics and cursor interface
  1034. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1035. {
  1036. if (hexTo < 0 || hexFrom < 0) //turret
  1037. return false;
  1038. if (toDoubleWide)
  1039. {
  1040. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1041. {
  1042. if (toDir)
  1043. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1044. else
  1045. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1046. }
  1047. return false;
  1048. }
  1049. else
  1050. {
  1051. return isToReverseHlp(hexFrom, hexTo, curDir);
  1052. }
  1053. }
  1054. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
  1055. {
  1056. ReachabilityInfo::TDistances ret;
  1057. ret.fill(-1);
  1058. RETURN_IF_NOT_BATTLE(ret);
  1059. ReachabilityInfo::Parameters params(stack);
  1060. params.perspective = battleGetMySide();
  1061. params.startPosition = hex.isValid() ? hex : stack->position;
  1062. auto reachability = getReachability(params);
  1063. boost::copy(reachability.distances, ret.begin());
  1064. if(predecessors)
  1065. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1066. predecessors[i] = reachability.predecessors[i];
  1067. return ret;
  1068. }
  1069. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1070. {
  1071. return battleHasDistancePenalty(stack, stack->position, destHex);
  1072. }
  1073. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1074. {
  1075. RETURN_IF_NOT_BATTLE(false);
  1076. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1077. return false;
  1078. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1079. {
  1080. //If any hex of target creature is within range, there is no penalty
  1081. for(auto hex : dstStack->getHexes())
  1082. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1083. return false;
  1084. //TODO what about two-hex shooters?
  1085. }
  1086. else
  1087. {
  1088. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1089. return false;
  1090. }
  1091. return true;
  1092. }
  1093. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1094. {
  1095. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1096. return WallPartToHex(part);
  1097. }
  1098. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1099. {
  1100. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1101. return hexToWallPart(hex);
  1102. }
  1103. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1104. {
  1105. RETURN_IF_NOT_BATTLE(false);
  1106. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1107. wallPart != EWallPart::INVALID;
  1108. }
  1109. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1110. {
  1111. std::vector<BattleHex> attackableBattleHexes;
  1112. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1113. for(auto & wallPartPair : wallParts)
  1114. {
  1115. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1116. {
  1117. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1118. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1119. {
  1120. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1121. }
  1122. }
  1123. }
  1124. return attackableBattleHexes;
  1125. }
  1126. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1127. {
  1128. RETURN_IF_NOT_BATTLE(-1);
  1129. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1130. ui32 ret = caster->getSpellCost(sp);
  1131. //checking for friendly stacks reducing cost of the spell and
  1132. //enemy stacks increasing it
  1133. si32 manaReduction = 0;
  1134. si32 manaIncrease = 0;
  1135. for(auto stack : battleAliveStacks())
  1136. {
  1137. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY))
  1138. {
  1139. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1140. }
  1141. if(stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY))
  1142. {
  1143. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1144. }
  1145. }
  1146. return ret - manaReduction + manaIncrease;
  1147. }
  1148. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1149. {
  1150. RETURN_IF_NOT_BATTLE(nullptr);
  1151. auto stacks = battleGetAllStacks();
  1152. auto stackItr = range::find_if(stacks, pred);
  1153. return stackItr == stacks.end() ? nullptr : *stackItr;
  1154. }
  1155. si8 CBattleInfoCallback::battleHasShootingPenalty(const CStack * stack, BattleHex destHex)
  1156. {
  1157. return battleHasDistancePenalty(stack, destHex) || battleHasWallPenalty(stack, destHex);
  1158. }
  1159. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1160. {
  1161. RETURN_IF_NOT_BATTLE(false);
  1162. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1163. return false;
  1164. for(const CStack * s : batteAdjacentCreatures(stack))
  1165. {
  1166. if (s->owner != stack->owner) //blocked by enemy stack
  1167. return true;
  1168. }
  1169. return false;
  1170. }
  1171. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1172. {
  1173. std::set<const CStack*> stacks;
  1174. RETURN_IF_NOT_BATTLE(stacks);
  1175. for (BattleHex hex : stack->getSurroundingHexes())
  1176. if(const CStack * neighbour = battleGetStackByPos(hex, true))
  1177. stacks.insert(neighbour);
  1178. return stacks;
  1179. }
  1180. SpellID CBattleInfoCallback::getRandomBeneficialSpell(CRandomGenerator & rand, const CStack * subject) const
  1181. {
  1182. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1183. //This is complete list. No spells from mods.
  1184. //todo: this should be Spellbook of caster Stack
  1185. static const std::set<SpellID> allPossibleSpells =
  1186. {
  1187. SpellID::AIR_SHIELD,
  1188. SpellID::ANTI_MAGIC,
  1189. SpellID::BLESS,
  1190. SpellID::BLOODLUST,
  1191. SpellID::COUNTERSTRIKE,
  1192. SpellID::CURE,
  1193. SpellID::FIRE_SHIELD,
  1194. SpellID::FORTUNE,
  1195. SpellID::HASTE,
  1196. SpellID::MAGIC_MIRROR,
  1197. SpellID::MIRTH,
  1198. SpellID::PRAYER,
  1199. SpellID::PRECISION,
  1200. SpellID::PROTECTION_FROM_AIR,
  1201. SpellID::PROTECTION_FROM_EARTH,
  1202. SpellID::PROTECTION_FROM_FIRE,
  1203. SpellID::PROTECTION_FROM_WATER,
  1204. SpellID::SHIELD,
  1205. SpellID::SLAYER,
  1206. SpellID::STONE_SKIN
  1207. };
  1208. std::vector<SpellID> beneficialSpells;
  1209. auto getAliveEnemy = [=](const std::function<bool(const CStack *)> & pred)
  1210. {
  1211. return getStackIf([=](const CStack * stack)
  1212. {
  1213. return pred(stack) && stack->owner != subject->owner && stack->alive();
  1214. });
  1215. };
  1216. for(const SpellID spellID : allPossibleSpells)
  1217. {
  1218. std::stringstream cachingStr;
  1219. cachingStr << "source_" << Bonus::SPELL_EFFECT << "id_" << spellID.num;
  1220. if(subject->hasBonus(Selector::source(Bonus::SPELL_EFFECT, spellID), Selector::all, cachingStr.str())
  1221. //TODO: this ability has special limitations
  1222. || spellID.toSpell()->canBeCastAt(this, subject, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1223. continue;
  1224. switch (spellID)
  1225. {
  1226. case SpellID::SHIELD:
  1227. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1228. {
  1229. auto walker = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1230. {
  1231. return !stack->shots;
  1232. });
  1233. if (!walker)
  1234. continue;
  1235. }
  1236. break;
  1237. case SpellID::AIR_SHIELD: //only against active shooters
  1238. {
  1239. auto shooter = getAliveEnemy([&](const CStack * stack) //look for enemy, non-shooting stack
  1240. {
  1241. return stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
  1242. });
  1243. if (!shooter)
  1244. continue;
  1245. }
  1246. break;
  1247. case SpellID::ANTI_MAGIC:
  1248. case SpellID::MAGIC_MIRROR:
  1249. case SpellID::PROTECTION_FROM_AIR:
  1250. case SpellID::PROTECTION_FROM_EARTH:
  1251. case SpellID::PROTECTION_FROM_FIRE:
  1252. case SpellID::PROTECTION_FROM_WATER:
  1253. {
  1254. const ui8 enemySide = (ui8)subject->attackerOwned;
  1255. //todo: only if enemy has spellbook
  1256. if (!battleHasHero(enemySide)) //only if there is enemy hero
  1257. continue;
  1258. }
  1259. break;
  1260. case SpellID::CURE: //only damaged units
  1261. {
  1262. //do not cast on affected by debuffs
  1263. if (subject->firstHPleft >= subject->MaxHealth())
  1264. continue;
  1265. }
  1266. break;
  1267. case SpellID::BLOODLUST:
  1268. {
  1269. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1270. continue;
  1271. }
  1272. break;
  1273. case SpellID::PRECISION:
  1274. {
  1275. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1276. continue;
  1277. }
  1278. break;
  1279. case SpellID::SLAYER://only if monsters are present
  1280. {
  1281. auto kingMonster = getAliveEnemy([&](const CStack * stack) -> bool //look for enemy, non-shooting stack
  1282. {
  1283. const auto isKing = Selector::type(Bonus::KING1)
  1284. .Or(Selector::type(Bonus::KING2))
  1285. .Or(Selector::type(Bonus::KING3));
  1286. return stack->hasBonus(isKing);
  1287. });
  1288. if (!kingMonster)
  1289. continue;
  1290. }
  1291. break;
  1292. }
  1293. beneficialSpells.push_back(spellID);
  1294. }
  1295. if(!beneficialSpells.empty())
  1296. {
  1297. return *RandomGeneratorUtil::nextItem(beneficialSpells, rand);
  1298. }
  1299. else
  1300. {
  1301. return SpellID::NONE;
  1302. }
  1303. }
  1304. SpellID CBattleInfoCallback::getRandomCastedSpell(CRandomGenerator & rand,const CStack * caster) const
  1305. {
  1306. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1307. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1308. if (!bl->size())
  1309. return SpellID::NONE;
  1310. int totalWeight = 0;
  1311. for(auto b : *bl)
  1312. {
  1313. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1314. }
  1315. int randomPos = rand.nextInt(totalWeight - 1);
  1316. for(auto b : *bl)
  1317. {
  1318. randomPos -= std::max(b->additionalInfo, 1);
  1319. if(randomPos < 0)
  1320. {
  1321. return SpellID(b->subtype);
  1322. }
  1323. }
  1324. return SpellID::NONE;
  1325. }
  1326. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1327. {
  1328. RETURN_IF_NOT_BATTLE(-3);
  1329. if(!battleCanSurrender(Player))
  1330. return -1;
  1331. const si8 playerSide = playerToSide(Player);
  1332. if(playerSide < 0)
  1333. return -1;
  1334. int ret = 0;
  1335. double discount = 0;
  1336. for(const CStack *s : battleAliveStacks(playerSide))
  1337. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1338. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  1339. if(const CGHeroInstance * h = battleGetFightingHero(playerSide))
  1340. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1341. ret *= (100.0 - discount) / 100.0;
  1342. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1343. return ret;
  1344. }
  1345. si8 CBattleInfoCallback::battleMaxSpellLevel(ui8 side) const
  1346. {
  1347. const IBonusBearer *node = nullptr;
  1348. if(const CGHeroInstance * h = battleGetFightingHero(side))
  1349. node = h;
  1350. else
  1351. node = getBattleNode();
  1352. if(!node)
  1353. return GameConstants::SPELL_LEVELS;
  1354. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1355. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1356. if(b->size())
  1357. return b->totalValue();
  1358. return GameConstants::SPELL_LEVELS;
  1359. }
  1360. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1361. {
  1362. auto stacks = battleGetAllStacks();
  1363. //checking winning condition
  1364. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
  1365. hasStack[0] = hasStack[1] = false;
  1366. for(auto & stack : stacks)
  1367. {
  1368. if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1369. {
  1370. hasStack[1-stack->attackerOwned] = true;
  1371. }
  1372. }
  1373. if(!hasStack[0] && !hasStack[1])
  1374. return 2;
  1375. if(!hasStack[1])
  1376. return 0;
  1377. if(!hasStack[0])
  1378. return 1;
  1379. return boost::none;
  1380. }