CBattleCallback.cpp 67 KB

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