CBattleCallback.cpp 62 KB

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