CBattleCallback.cpp 65 KB

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