CBattleCallback.cpp 66 KB

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