CBattleCallback.cpp 72 KB

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