CBattleCallback.cpp 73 KB

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