CBattleCallback.cpp 67 KB

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