CBattleCallback.cpp 67 KB

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