CBattleCallback.cpp 77 KB

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