CBattleCallback.cpp 64 KB

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