CBattleCallback.cpp 74 KB

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