CBattleCallback.cpp 65 KB

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