CBattleInfoCallback.cpp 49 KB

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