2
0

CBattleCallback.cpp 63 KB

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