CBattleCallback.cpp 75 KB

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