CBattleCallback.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293
  1. #include "StdInc.h"
  2. #include "CBattleCallback.h"
  3. #include "BattleState.h"
  4. #include "CGameState.h"
  5. #include "NetPacks.h"
  6. #include "CSpellHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "CTownHandler.h"
  9. /*
  10. * CBattleCallback.cpp, part of VCMI engine
  11. *
  12. * Authors: listed in file AUTHORS in main folder
  13. *
  14. * License: GNU General Public License v2.0 or later
  15. * Full text of license available in license.txt file, in main folder
  16. *
  17. */
  18. #define RETURN_IF_NOT_BATTLE(X) if(!duringBattle()) {logGlobal->errorStream() << __FUNCTION__ << " called when no battle!"; return X; }
  19. namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
  20. {
  21. static void retreiveTurretDamageRange(const 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::battleCanShoot(const CStack * stack, BattleHex dest) const
  647. {
  648. RETURN_IF_NOT_BATTLE(false);
  649. if(battleTacticDist()) //no shooting during tactics
  650. return false;
  651. const CStack *dst = battleGetStackByPos(dest);
  652. if(!stack || !dst)
  653. return false;
  654. if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  655. return false;
  656. if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
  657. return false;
  658. //const CGHeroInstance * stackHero = battleGetOwner(stack);
  659. if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  660. && stack->owner != dst->owner
  661. && dst->alive()
  662. && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
  663. && stack->shots
  664. )
  665. return true;
  666. return false;
  667. }
  668. TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
  669. ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
  670. {
  671. return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  672. }
  673. TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo &info) const
  674. {
  675. auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
  676. {
  677. auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
  678. auto limitMatches = info.shooting
  679. ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
  680. : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
  681. //any regular bonuses or just ones for melee/ranged
  682. return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
  683. };
  684. double additiveBonus = 1.0, multBonus = 1.0,
  685. minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
  686. maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
  687. const CCreature *attackerType = info.attacker->getCreature(),
  688. *defenderType = info.defender->getCreature();
  689. if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
  690. {
  691. SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
  692. }
  693. 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)
  694. { //minDmg and maxDmg are multiplied by hero attack + 1
  695. auto retreiveHeroPrimSkill = [&](int skill) -> int
  696. {
  697. const Bonus *b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
  698. return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
  699. };
  700. minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  701. maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
  702. }
  703. int attackDefenceDifference = 0;
  704. double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
  705. attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
  706. double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
  707. attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
  708. if(const Bonus *slayerEffect = info.attackerBonuses->getEffect(SpellID::SLAYER)) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
  709. {
  710. std::vector<int> affectedIds;
  711. int spLevel = slayerEffect->val;
  712. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  713. {
  714. for(const Bonus *b : VLC->creh->creatures[g]->getBonusList())
  715. {
  716. if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
  717. (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
  718. (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  719. {
  720. affectedIds.push_back(g);
  721. break;
  722. }
  723. }
  724. }
  725. for(auto & affectedId : affectedIds)
  726. {
  727. if(defenderType->idNumber == affectedId)
  728. {
  729. attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
  730. break;
  731. }
  732. }
  733. }
  734. //bonus from attack/defense skills
  735. if(attackDefenceDifference < 0) //decreasing dmg
  736. {
  737. const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
  738. multBonus *= 1.0 - dec;
  739. }
  740. else //increasing dmg
  741. {
  742. const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
  743. additiveBonus += inc;
  744. }
  745. //applying jousting bonus
  746. if( info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  747. additiveBonus += info.chargedFields * 0.05;
  748. //handling secondary abilities and artifacts giving premies to them
  749. if(info.shooting)
  750. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
  751. else
  752. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
  753. if(info.defenderBonuses)
  754. multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
  755. //handling hate effect
  756. additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
  757. //luck bonus
  758. if (info.luckyHit)
  759. {
  760. additiveBonus += 1.0;
  761. }
  762. //unlucky hit, used only if negative luck is enabled
  763. if (info.unluckyHit)
  764. {
  765. additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
  766. }
  767. //ballista double dmg
  768. if(info.ballistaDoubleDamage)
  769. {
  770. additiveBonus += 1.0;
  771. }
  772. if (info.deathBlow) //Dread Knight and many WoGified creatures
  773. {
  774. additiveBonus += 1.0;
  775. }
  776. //handling spell effects
  777. if(!info.shooting) //eg. shield
  778. {
  779. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
  780. }
  781. else if(info.shooting) //eg. air shield
  782. {
  783. multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
  784. }
  785. TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
  786. TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
  787. int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
  788. double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
  789. if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
  790. {
  791. multBonus *= 1.0 - curseMultiplicativePenalty/100;
  792. }
  793. auto isAdvancedAirShield = [](const Bonus *bonus)
  794. {
  795. return bonus->source == Bonus::SPELL_EFFECT
  796. && bonus->sid == SpellID::AIR_SHIELD
  797. && bonus->val >= SecSkillLevel::ADVANCED;
  798. };
  799. //wall / distance penalty + advanced air shield
  800. const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  801. const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
  802. if (info.shooting)
  803. {
  804. if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
  805. {
  806. multBonus *= 0.5;
  807. }
  808. if (obstaclePenalty)
  809. {
  810. multBonus *= 0.5; //cumulative
  811. }
  812. }
  813. if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  814. {
  815. multBonus *= 0.5;
  816. }
  817. // TODO attack on petrified unit 50%
  818. // psychic elementals versus mind immune units 50%
  819. // blinded unit retaliates
  820. minDmg *= additiveBonus * multBonus;
  821. maxDmg *= additiveBonus * multBonus;
  822. TDmgRange returnedVal;
  823. if(curseEffects->size()) //curse handling (rest)
  824. {
  825. minDmg += curseBlessAdditiveModifier;
  826. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  827. }
  828. else if(blessEffects->size()) //bless handling
  829. {
  830. maxDmg += curseBlessAdditiveModifier;
  831. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  832. }
  833. else
  834. {
  835. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  836. }
  837. //damage cannot be less than 1
  838. vstd::amax(returnedVal.first, 1);
  839. vstd::amax(returnedVal.second, 1);
  840. return returnedVal;
  841. }
  842. TDmgRange CBattleInfoCallback::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount,
  843. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg ) const
  844. {
  845. BattleAttackInfo bai(attacker, defender, shooting);
  846. bai.attackerCount = attackerCount;
  847. bai.chargedFields = charge;
  848. bai.luckyHit = lucky;
  849. bai.unluckyHit = unlucky;
  850. bai.deathBlow = deathBlow;
  851. bai.ballistaDoubleDamage = ballistaDoubleDmg;
  852. return calculateDmgRange(bai);
  853. }
  854. TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
  855. {
  856. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  857. const bool shooting = battleCanShoot(attacker, defender->position);
  858. const BattleAttackInfo bai(attacker, defender, shooting);
  859. return battleEstimateDamage(bai, retaliationDmg);
  860. }
  861. std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo &bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
  862. {
  863. RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
  864. //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
  865. //const ui8 mySide = !attacker->attackerOwned;
  866. TDmgRange ret = calculateDmgRange(bai);
  867. if(retaliationDmg)
  868. {
  869. if(bai.shooting)
  870. {
  871. retaliationDmg->first = retaliationDmg->second = 0;
  872. }
  873. else
  874. {
  875. ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
  876. for (int i=0; i<2; ++i)
  877. {
  878. BattleStackAttacked bsa;
  879. bsa.damageAmount = ret.*pairElems[i];
  880. bai.defender->prepareAttacked(bsa, gs->getRandomGenerator(), bai.defenderCount);
  881. auto retaliationAttack = bai.reverse();
  882. retaliationAttack.attackerCount = bsa.newAmount;
  883. retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
  884. }
  885. }
  886. }
  887. return ret;
  888. }
  889. shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
  890. {
  891. RETURN_IF_NOT_BATTLE(shared_ptr<const CObstacleInstance>());
  892. for(auto &obs : battleGetAllObstacles())
  893. {
  894. if(vstd::contains(obs->getBlockedTiles(), tile)
  895. || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
  896. {
  897. return obs;
  898. }
  899. }
  900. return shared_ptr<const CObstacleInstance>();
  901. }
  902. AccessibilityInfo CBattleInfoCallback::getAccesibility() const
  903. {
  904. AccessibilityInfo ret;
  905. ret.fill(EAccessibility::ACCESSIBLE);
  906. //removing accessibility for side columns of hexes
  907. for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
  908. {
  909. ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
  910. ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
  911. }
  912. //gate -> should be before stacks
  913. if(battleGetSiegeLevel() > 0 && battleGetWallState(EWallPart::GATE) != EWallState::DESTROYED)
  914. {
  915. ret[95] = ret[96] = EAccessibility::GATE; //block gate's hexes
  916. }
  917. //tiles occupied by standing stacks
  918. for(auto stack : battleAliveStacks())
  919. {
  920. for(auto hex : stack->getHexes())
  921. if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
  922. ret[hex] = EAccessibility::ALIVE_STACK;
  923. }
  924. //obstacles
  925. for(const auto &obst : battleGetAllObstacles())
  926. {
  927. for(auto hex : obst->getBlockedTiles())
  928. ret[hex] = EAccessibility::OBSTACLE;
  929. }
  930. //walls
  931. if(battleGetSiegeLevel() > 0)
  932. {
  933. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  934. for(auto hex : permanentlyLocked)
  935. ret[hex] = EAccessibility::UNAVAILABLE;
  936. //TODO likely duplicated logic
  937. static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  938. {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
  939. std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
  940. for(auto & elem : lockedIfNotDestroyed)
  941. {
  942. if(battleGetWallState(elem.first) != EWallState::DESTROYED)
  943. ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
  944. }
  945. }
  946. return ret;
  947. }
  948. AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack *stack) const
  949. {
  950. return getAccesibility(stack->getHexes());
  951. }
  952. AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> &accessibleHexes) const
  953. {
  954. auto ret = getAccesibility();
  955. for(auto hex : accessibleHexes)
  956. if(hex.isValid())
  957. ret[hex] = EAccessibility::ACCESSIBLE;
  958. return ret;
  959. }
  960. ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters &params) const
  961. {
  962. ReachabilityInfo ret;
  963. ret.accessibility = accessibility;
  964. ret.params = params;
  965. ret.predecessors.fill(BattleHex::INVALID);
  966. ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
  967. if(!params.startPosition.isValid()) //if got call for arrow turrets
  968. return ret;
  969. const std::set<BattleHex> quicksands = getStoppers(params.perspective);
  970. //const bool twoHexCreature = params.doubleWide;
  971. std::queue<BattleHex> hexq; //bfs queue
  972. //first element
  973. hexq.push(params.startPosition);
  974. ret.distances[params.startPosition] = 0;
  975. while(!hexq.empty()) //bfs loop
  976. {
  977. const BattleHex curHex = hexq.front();
  978. hexq.pop();
  979. //walking stack can't step past the quicksands
  980. //TODO what if second hex of two-hex creature enters quicksand
  981. if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
  982. continue;
  983. const int costToNeighbour = ret.distances[curHex] + 1;
  984. for(BattleHex neighbour : curHex.neighbouringTiles())
  985. {
  986. const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.attackerOwned);
  987. const int costFoundSoFar = ret.distances[neighbour];
  988. if(accessible && costToNeighbour < costFoundSoFar)
  989. {
  990. hexq.push(neighbour);
  991. ret.distances[neighbour] = costToNeighbour;
  992. ret.predecessors[neighbour] = curHex;
  993. }
  994. }
  995. }
  996. return ret;
  997. }
  998. ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack *stack) const
  999. {
  1000. return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
  1001. }
  1002. std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
  1003. {
  1004. std::set<BattleHex> ret;
  1005. RETURN_IF_NOT_BATTLE(ret);
  1006. for(auto &oi : battleGetAllObstacles(whichSidePerspective))
  1007. {
  1008. if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
  1009. {
  1010. range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
  1011. }
  1012. }
  1013. return ret;
  1014. }
  1015. std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  1016. {
  1017. auto reachability = getReachability(closest);
  1018. // I hate std::pairs with their undescriptive member names first / second
  1019. struct DistStack
  1020. {
  1021. int distanceToPred;
  1022. const CStack *stack;
  1023. };
  1024. std::vector<DistStack> stackPairs; //pairs <<distance, hex>, stack>
  1025. for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
  1026. {
  1027. const CStack * atG = battleGetStackByPos(g);
  1028. if(!atG || atG->ID == closest->ID) //if there is no stack or we are the closest one
  1029. continue;
  1030. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  1031. {
  1032. if (reachability.isReachable(g))
  1033. //FIXME: hexes occupied by enemy stack are not accessible. Need to use BattleInfo::getPath or similar
  1034. {
  1035. DistStack hlp = {reachability.distances[reachability.predecessors[g]], atG};
  1036. stackPairs.push_back(hlp);
  1037. }
  1038. }
  1039. }
  1040. if (stackPairs.size())
  1041. {
  1042. auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
  1043. auto minimal = boost::min_element(stackPairs, comparator);
  1044. return std::make_pair(minimal->stack, reachability.predecessors[minimal->stack->position]);
  1045. }
  1046. else
  1047. return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
  1048. }
  1049. si8 CBattleInfoCallback::battleGetTacticDist() const
  1050. {
  1051. RETURN_IF_NOT_BATTLE(0);
  1052. //TODO get rid of this method
  1053. if(battleDoWeKnowAbout(battleGetTacticsSide()))
  1054. return battleTacticDist();
  1055. return 0;
  1056. }
  1057. bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
  1058. {
  1059. RETURN_IF_NOT_BATTLE(false);
  1060. auto side = battleGetTacticsSide();
  1061. auto dist = battleGetTacticDist();
  1062. return ((!side && dest.getX() > 0 && dest.getX() <= dist)
  1063. || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
  1064. }
  1065. ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
  1066. {
  1067. ReachabilityInfo::Parameters params(stack);
  1068. if(!battleDoWeKnowAbout(!stack->attackerOwned))
  1069. {
  1070. //Stack is held by enemy, we can't use his perspective to check for reachability.
  1071. // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
  1072. params.perspective = battleGetMySide();
  1073. }
  1074. return getReachability(params);
  1075. }
  1076. ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters &params) const
  1077. {
  1078. if(params.flying)
  1079. return getFlyingReachability(params);
  1080. else
  1081. return makeBFS(getAccesibility(params.knownAccessible), params);
  1082. }
  1083. ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters &params) const
  1084. {
  1085. ReachabilityInfo ret;
  1086. ret.accessibility = getAccesibility(params.knownAccessible);
  1087. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1088. {
  1089. if(ret.accessibility.accessible(i, params.doubleWide, params.attackerOwned))
  1090. {
  1091. ret.predecessors[i] = params.startPosition;
  1092. ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
  1093. }
  1094. }
  1095. return ret;
  1096. }
  1097. AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
  1098. {
  1099. //does not return hex attacked directly
  1100. //TODO: apply rotation to two-hex attackers
  1101. bool isAttacker = attacker->attackerOwned;
  1102. AttackableTiles at;
  1103. RETURN_IF_NOT_BATTLE(at);
  1104. const int WN = GameConstants::BFIELD_WIDTH;
  1105. ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
  1106. //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
  1107. bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
  1108. if (reverse)
  1109. {
  1110. hex = attacker->occupiedHex(hex); //the other hex stack stands on
  1111. }
  1112. if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
  1113. {
  1114. boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
  1115. }
  1116. if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
  1117. {
  1118. std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
  1119. for (BattleHex tile : hexes)
  1120. {
  1121. if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
  1122. {
  1123. const CStack * st = battleGetStackByPos(tile, true);
  1124. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1125. {
  1126. at.hostileCreaturePositions.insert(tile);
  1127. }
  1128. }
  1129. }
  1130. }
  1131. if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
  1132. {
  1133. std::vector<BattleHex> hexes; //only one, in fact
  1134. int pseudoVector = destinationTile.hex - hex;
  1135. switch (pseudoVector)
  1136. {
  1137. case 1:
  1138. case -1:
  1139. BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
  1140. break;
  1141. case WN: //17 //left-down or right-down
  1142. case -WN: //-17 //left-up or right-up
  1143. case WN + 1: //18 //right-down
  1144. case -WN + 1: //-16 //right-up
  1145. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : -1 ), hexes);
  1146. break;
  1147. case WN-1: //16 //left-down
  1148. case -WN-1: //-18 //left-up
  1149. BattleHex::checkAndPush (destinationTile.hex + pseudoVector + (((hex/WN)%2) ? 1 : 0), hexes);
  1150. break;
  1151. }
  1152. for (BattleHex tile : hexes)
  1153. {
  1154. //friendly stacks can also be damaged by Dragon Breath
  1155. if (battleGetStackByPos (tile, true))
  1156. at.friendlyCreaturePositions.insert (tile);
  1157. }
  1158. }
  1159. return at;
  1160. }
  1161. std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
  1162. {
  1163. std::set<const CStack*> attackedCres;
  1164. RETURN_IF_NOT_BATTLE(attackedCres);
  1165. AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
  1166. for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
  1167. {
  1168. const CStack * st = battleGetStackByPos(tile, true);
  1169. if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
  1170. {
  1171. attackedCres.insert(st);
  1172. }
  1173. }
  1174. for (BattleHex tile : at.friendlyCreaturePositions)
  1175. {
  1176. const CStack * st = battleGetStackByPos(tile, true);
  1177. if(st) //friendly stacks can also be damaged by Dragon Breath
  1178. {
  1179. attackedCres.insert(st);
  1180. }
  1181. }
  1182. return attackedCres;
  1183. }
  1184. //TODO: this should apply also to mechanics and cursor interface
  1185. bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
  1186. {
  1187. int fromX = hexFrom.getX();
  1188. int fromY = hexFrom.getY();
  1189. int toX = hexTo.getX();
  1190. int toY = hexTo.getY();
  1191. if (curDir) // attacker, facing right
  1192. {
  1193. if (fromX < toX)
  1194. return false;
  1195. if (fromX > toX)
  1196. return true;
  1197. if (fromY % 2 == 0 && toY % 2 == 1)
  1198. return true;
  1199. return false;
  1200. }
  1201. else // defender, facing left
  1202. {
  1203. if(fromX < toX)
  1204. return true;
  1205. if(fromX > toX)
  1206. return false;
  1207. if (fromY % 2 == 1 && toY % 2 == 0)
  1208. return true;
  1209. return false;
  1210. }
  1211. }
  1212. //TODO: this should apply also to mechanics and cursor interface
  1213. bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
  1214. {
  1215. if (hexTo < 0 || hexFrom < 0) //turret
  1216. return false;
  1217. if (toDoubleWide)
  1218. {
  1219. if (isToReverseHlp (hexFrom, hexTo, curDir))
  1220. {
  1221. if (toDir)
  1222. return isToReverseHlp (hexFrom, hexTo-1, curDir);
  1223. else
  1224. return isToReverseHlp (hexFrom, hexTo+1, curDir);
  1225. }
  1226. return false;
  1227. }
  1228. else
  1229. {
  1230. return isToReverseHlp(hexFrom, hexTo, curDir);
  1231. }
  1232. }
  1233. ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
  1234. {
  1235. ReachabilityInfo::TDistances ret;
  1236. ret.fill(-1);
  1237. RETURN_IF_NOT_BATTLE(ret);
  1238. ReachabilityInfo::Parameters params(stack);
  1239. params.perspective = battleGetMySide();
  1240. params.startPosition = hex.isValid() ? hex : stack->position;
  1241. auto reachability = getReachability(params);
  1242. boost::copy(reachability.distances, ret.begin());
  1243. if(predecessors)
  1244. for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
  1245. predecessors[i] = reachability.predecessors[i];
  1246. return ret;
  1247. }
  1248. si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
  1249. {
  1250. return battleHasDistancePenalty(stack, stack->position, destHex);
  1251. }
  1252. si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
  1253. {
  1254. RETURN_IF_NOT_BATTLE(false);
  1255. if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
  1256. return false;
  1257. if(const CStack * dstStack = battleGetStackByPos(destHex, false))
  1258. {
  1259. //If any hex of target creature is within range, there is no penalty
  1260. for(auto hex : dstStack->getHexes())
  1261. if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1262. return false;
  1263. //TODO what about two-hex shooters?
  1264. }
  1265. else
  1266. {
  1267. if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
  1268. return false;
  1269. }
  1270. return true;
  1271. }
  1272. BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
  1273. {
  1274. RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
  1275. return WallPartToHex(part);
  1276. }
  1277. EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
  1278. {
  1279. RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
  1280. return hexToWallPart(hex);
  1281. }
  1282. bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
  1283. {
  1284. RETURN_IF_NOT_BATTLE(false);
  1285. return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
  1286. wallPart != EWallPart::INVALID;
  1287. }
  1288. std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
  1289. {
  1290. std::vector<BattleHex> attackableBattleHexes;
  1291. RETURN_IF_NOT_BATTLE(attackableBattleHexes);
  1292. for(auto & wallPartPair : wallParts)
  1293. {
  1294. if(isWallPartPotentiallyAttackable(wallPartPair.second))
  1295. {
  1296. auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
  1297. if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
  1298. {
  1299. attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
  1300. }
  1301. }
  1302. }
  1303. return attackableBattleHexes;
  1304. }
  1305. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
  1306. {
  1307. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1308. // Get all stacks at destination hex -> subject of our spell. only alive if not rising spell
  1309. TStacks stacks = battleGetStacksIf([=](const CStack * s){
  1310. return s->coversPos(dest) && (spell->isRisingSpell() || s->alive());
  1311. });
  1312. if(!stacks.empty())
  1313. {
  1314. bool allImmune = true;
  1315. ESpellCastProblem::ESpellCastProblem problem;
  1316. for(auto s : stacks)
  1317. {
  1318. ESpellCastProblem::ESpellCastProblem res = spell->isImmuneByStack(caster,s);
  1319. if(res == ESpellCastProblem::OK)
  1320. {
  1321. allImmune = false;
  1322. }
  1323. else
  1324. {
  1325. problem = res;
  1326. }
  1327. }
  1328. if(allImmune)
  1329. return problem;
  1330. }
  1331. else //no target stack on this tile
  1332. {
  1333. if(spell->getTargetType() == CSpell::CREATURE)
  1334. {
  1335. if(caster && mode == ECastingMode::HERO_CASTING) //TODO why???
  1336. {
  1337. const CSpell::TargetInfo ti = spell->getTargetInfo(caster->getSpellSchoolLevel(spell));
  1338. if(!ti.massive)
  1339. return ESpellCastProblem::WRONG_SPELL_TARGET;
  1340. }
  1341. else
  1342. {
  1343. return ESpellCastProblem::WRONG_SPELL_TARGET;
  1344. }
  1345. }
  1346. }
  1347. return ESpellCastProblem::OK;
  1348. }
  1349. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpell( PlayerColor player, const CSpell * spell, ECastingMode::ECastingMode mode ) const
  1350. {
  1351. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1352. const ui8 side = playerToSide(player);
  1353. if(!battleDoWeKnowAbout(side))
  1354. return ESpellCastProblem::INVALID;
  1355. ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
  1356. if(genProblem != ESpellCastProblem::OK)
  1357. return genProblem;
  1358. //Casting hero, set only if he is an actual caster.
  1359. const CGHeroInstance *castingHero = mode == ECastingMode::HERO_CASTING
  1360. ? battleGetFightingHero(side)
  1361. : nullptr;
  1362. switch(mode)
  1363. {
  1364. case ECastingMode::HERO_CASTING:
  1365. {
  1366. assert(castingHero);
  1367. if(!castingHero->canCastThisSpell(spell))
  1368. return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
  1369. if(castingHero->mana < battleGetSpellCost(spell, castingHero)) //not enough mana
  1370. return ESpellCastProblem::NOT_ENOUGH_MANA;
  1371. }
  1372. break;
  1373. }
  1374. if(!spell->combatSpell)
  1375. return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
  1376. if(spell->isNegative() || spell->hasEffects())
  1377. {
  1378. bool allStacksImmune = true;
  1379. //we are interested only in enemy stacks when casting offensive spells
  1380. //TODO: should hero be able to cast non-smart negative spell if all enemy stacks are immune?
  1381. auto stacks = spell->isNegative() ? battleAliveStacks(!side) : battleAliveStacks();
  1382. for(auto stack : stacks)
  1383. {
  1384. if(ESpellCastProblem::OK == spell->isImmuneByStack(castingHero, stack))
  1385. {
  1386. allStacksImmune = false;
  1387. break;
  1388. }
  1389. }
  1390. if(allStacksImmune)
  1391. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1392. }
  1393. if(battleMaxSpellLevel() < spell->level) //effect like Recanter's Cloak or Orb of Inhibition
  1394. return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
  1395. //IDs of summon elemental spells (fire, earth, water, air)
  1396. int spellIDs[] = { SpellID::SUMMON_FIRE_ELEMENTAL, SpellID::SUMMON_EARTH_ELEMENTAL,
  1397. SpellID::SUMMON_WATER_ELEMENTAL, SpellID::SUMMON_AIR_ELEMENTAL };
  1398. //(fire, earth, water, air) elementals
  1399. int creIDs[] = {CreatureID::FIRE_ELEMENTAL, CreatureID::EARTH_ELEMENTAL,
  1400. CreatureID::WATER_ELEMENTAL, CreatureID::AIR_ELEMENTAL};
  1401. int arpos = vstd::find_pos(spellIDs, spell->id);
  1402. if(arpos < ARRAY_COUNT(spellIDs))
  1403. {
  1404. //check if there are summoned elementals of other type
  1405. for( const CStack * st : battleAliveStacks())
  1406. if(vstd::contains(st->state, EBattleStackState::SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
  1407. return ESpellCastProblem::ANOTHER_ELEMENTAL_SUMMONED;
  1408. }
  1409. //checking if there exists an appropriate target
  1410. switch(spell->getTargetType())
  1411. {
  1412. case CSpell::CREATURE:
  1413. if(mode == ECastingMode::HERO_CASTING)
  1414. {
  1415. const CGHeroInstance * caster = battleGetFightingHero(side);
  1416. const CSpell::TargetInfo ti = spell->getTargetInfo(caster->getSpellSchoolLevel(spell));
  1417. bool targetExists = false;
  1418. bool targetToSacrificeExists = false; // for sacrifice we have to check for 2 targets (one dead to resurrect and one living to destroy)
  1419. for(const CStack * stack : battleGetAllStacks()) //dead stacks will be immune anyway
  1420. {
  1421. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  1422. bool casterStack = stack->owner == caster->getOwner();
  1423. if(spell->id == SpellID::SACRIFICE)
  1424. {
  1425. if(!immune && casterStack)
  1426. {
  1427. if(stack->alive())
  1428. targetToSacrificeExists = true;
  1429. else
  1430. targetExists = true;
  1431. if(targetExists && targetToSacrificeExists)
  1432. break;
  1433. }
  1434. }
  1435. else if(!immune)
  1436. {
  1437. switch (spell->positiveness)
  1438. {
  1439. case CSpell::POSITIVE:
  1440. if(casterStack || !ti.smart)
  1441. {
  1442. targetExists = true;
  1443. break;
  1444. }
  1445. break;
  1446. case CSpell::NEUTRAL:
  1447. targetExists = true;
  1448. break;
  1449. case CSpell::NEGATIVE:
  1450. if(!casterStack || !ti.smart)
  1451. {
  1452. targetExists = true;
  1453. break;
  1454. }
  1455. break;
  1456. }
  1457. }
  1458. }
  1459. if(!targetExists || (spell->id == SpellID::SACRIFICE && !targetExists && !targetToSacrificeExists))
  1460. {
  1461. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1462. }
  1463. }
  1464. break;
  1465. case CSpell::OBSTACLE:
  1466. break;
  1467. }
  1468. return ESpellCastProblem::OK;
  1469. }
  1470. std::vector<BattleHex> CBattleInfoCallback::battleGetPossibleTargets(PlayerColor player, const CSpell *spell) const
  1471. {
  1472. std::vector<BattleHex> ret;
  1473. RETURN_IF_NOT_BATTLE(ret);
  1474. switch(spell->getTargetType())
  1475. {
  1476. case CSpell::CREATURE:
  1477. {
  1478. const CGHeroInstance * caster = battleGetFightingHero(playerToSide(player)); //TODO
  1479. const CSpell::TargetInfo ti = spell->getTargetInfo(caster->getSpellSchoolLevel(spell));
  1480. for(const CStack * stack : battleAliveStacks())
  1481. {
  1482. bool immune = ESpellCastProblem::OK != spell->isImmuneByStack(caster, stack);
  1483. bool casterStack = stack->owner == caster->getOwner();
  1484. if(!immune)
  1485. switch (spell->positiveness)
  1486. {
  1487. case CSpell::POSITIVE:
  1488. if(casterStack || ti.smart)
  1489. ret.push_back(stack->position);
  1490. break;
  1491. case CSpell::NEUTRAL:
  1492. ret.push_back(stack->position);
  1493. break;
  1494. case CSpell::NEGATIVE:
  1495. if(!casterStack || ti.smart)
  1496. ret.push_back(stack->position);
  1497. break;
  1498. }
  1499. }
  1500. }
  1501. break;
  1502. default:
  1503. logGlobal->errorStream() << "FIXME " << __FUNCTION__ << " doesn't work with target type " << spell->getTargetType();
  1504. }
  1505. return ret;
  1506. }
  1507. ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  1508. {
  1509. RETURN_IF_NOT_BATTLE(-1);
  1510. //TODO should be replaced using bonus system facilities (propagation onto battle node)
  1511. ui32 ret = caster->getSpellCost(sp);
  1512. //checking for friendly stacks reducing cost of the spell and
  1513. //enemy stacks increasing it
  1514. si32 manaReduction = 0;
  1515. si32 manaIncrease = 0;
  1516. for(auto stack : battleAliveStacks())
  1517. {
  1518. if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  1519. {
  1520. vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  1521. }
  1522. if( stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  1523. {
  1524. vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  1525. }
  1526. }
  1527. return ret - manaReduction + manaIncrease;
  1528. }
  1529. ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpellHere( PlayerColor player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest ) const
  1530. {
  1531. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1532. ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
  1533. if(moreGeneralProblem != ESpellCastProblem::OK)
  1534. return moreGeneralProblem;
  1535. if(spell->getTargetType() == CSpell::OBSTACLE)
  1536. {
  1537. if(spell->id == SpellID::REMOVE_OBSTACLE)
  1538. {
  1539. if(auto obstacle = battleGetObstacleOnPos(dest, false))
  1540. {
  1541. switch (obstacle->obstacleType)
  1542. {
  1543. case CObstacleInstance::ABSOLUTE_OBSTACLE: //cliff-like obstacles can't be removed
  1544. case CObstacleInstance::MOAT:
  1545. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1546. case CObstacleInstance::USUAL:
  1547. return ESpellCastProblem::OK;
  1548. // //TODO FIRE_WALL only for ADVANCED level casters
  1549. // case CObstacleInstance::FIRE_WALL:
  1550. // return
  1551. // //TODO other magic obstacles for EXPERT
  1552. // case CObstacleInstance::QUICKSAND:
  1553. // case CObstacleInstance::LAND_MINE:
  1554. // case CObstacleInstance::FORCE_FIELD:
  1555. // return
  1556. default:
  1557. // assert(0);
  1558. return ESpellCastProblem::OK;
  1559. }
  1560. }
  1561. }
  1562. //isObstacleOnTile(dest)
  1563. //
  1564. //
  1565. //TODO
  1566. //assert that it's remove obstacle
  1567. //rules whether we can remove spell-created obstacle
  1568. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1569. }
  1570. //get dead stack if we cast resurrection or animate dead
  1571. const CStack *deadStack = getStackIf([dest](const CStack *s) { return !s->alive() && s->coversPos(dest); });
  1572. const CStack *aliveStack = getStackIf([dest](const CStack *s) { return s->alive() && s->coversPos(dest);});
  1573. if(spell->isRisingSpell())
  1574. {
  1575. if(!deadStack && !aliveStack)
  1576. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1577. if(spell->id == SpellID::ANIMATE_DEAD && deadStack && !deadStack->hasBonusOfType(Bonus::UNDEAD))
  1578. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1579. if(deadStack && deadStack->owner != player) //you can resurrect only your own stacks //FIXME: it includes alive stacks as well
  1580. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1581. }
  1582. else if(spell->getTargetType() == CSpell::CREATURE)
  1583. {
  1584. if(!aliveStack)
  1585. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1586. if(spell->isNegative() && aliveStack->owner == player)
  1587. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1588. if(spell->isPositive() && aliveStack->owner != player)
  1589. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  1590. }
  1591. if (mode == ECastingMode::HERO_CASTING)
  1592. return battleIsImmune(battleGetFightingHero(playerToSide(player)), spell, mode, dest);
  1593. else
  1594. return battleIsImmune(nullptr, spell, mode, dest);
  1595. }
  1596. const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
  1597. {
  1598. RETURN_IF_NOT_BATTLE(nullptr);
  1599. auto stacks = battleGetAllStacks();
  1600. auto stackItr = range::find_if(stacks, pred);
  1601. return stackItr == stacks.end()
  1602. ? nullptr
  1603. : *stackItr;
  1604. }
  1605. bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
  1606. {
  1607. RETURN_IF_NOT_BATTLE(false);
  1608. if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
  1609. return false;
  1610. for(const CStack * s : batteAdjacentCreatures(stack))
  1611. {
  1612. if (s->owner != stack->owner) //blocked by enemy stack
  1613. return true;
  1614. }
  1615. return false;
  1616. }
  1617. std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
  1618. {
  1619. std::set<const CStack*> stacks;
  1620. RETURN_IF_NOT_BATTLE(stacks);
  1621. for (BattleHex hex : stack->getSurroundingHexes())
  1622. if(const CStack *neighbour = battleGetStackByPos(hex, true))
  1623. stacks.insert(neighbour);
  1624. return stacks;
  1625. }
  1626. SpellID CBattleInfoCallback::getRandomBeneficialSpell(const CStack * subject) const
  1627. {
  1628. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1629. std::vector<SpellID> possibleSpells;
  1630. for(const CSpell *spell : VLC->spellh->objects)
  1631. {
  1632. if (spell->isPositive() && !spell->isRisingSpell()) //only positive and not rising
  1633. {
  1634. if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, spell->id)
  1635. || battleCanCastThisSpellHere(subject->owner, spell, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
  1636. continue;
  1637. switch (spell->id)
  1638. {
  1639. case SpellID::SHIELD:
  1640. case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
  1641. {
  1642. auto walker = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
  1643. {
  1644. return stack->owner != subject->owner && !stack->shots;
  1645. });
  1646. if (!walker)
  1647. continue;
  1648. }
  1649. break;
  1650. case SpellID::AIR_SHIELD: //only against active shooters
  1651. {
  1652. auto shooter = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
  1653. {
  1654. return stack->owner != subject->owner && stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
  1655. });
  1656. if (!shooter)
  1657. continue;
  1658. }
  1659. break;
  1660. case SpellID::ANTI_MAGIC:
  1661. case SpellID::MAGIC_MIRROR:
  1662. {
  1663. if (!battleHasHero(subject->attackerOwned)) //only if there is enemy hero
  1664. continue;
  1665. }
  1666. break;
  1667. case SpellID::CURE: //only damaged units - what about affected by curse?
  1668. {
  1669. if (subject->firstHPleft >= subject->MaxHealth())
  1670. continue;
  1671. }
  1672. break;
  1673. case SpellID::BLOODLUST:
  1674. {
  1675. if (subject->shots) //if can shoot - only if enemy uits are adjacent
  1676. continue;
  1677. }
  1678. break;
  1679. case SpellID::PRECISION:
  1680. {
  1681. if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
  1682. continue;
  1683. }
  1684. break;
  1685. case SpellID::SLAYER://only if monsters are present
  1686. {
  1687. auto kingMonster = getStackIf([&](const CStack *stack) -> bool //look for enemy, non-shooting stack
  1688. {
  1689. const auto isKing = Selector::type(Bonus::KING1)
  1690. .Or(Selector::type(Bonus::KING2))
  1691. .Or(Selector::type(Bonus::KING3));
  1692. return stack->owner != subject->owner && stack->hasBonus(isKing);
  1693. });
  1694. if (!kingMonster)
  1695. continue;
  1696. }
  1697. break;
  1698. case SpellID::TELEPORT: //issue 1928
  1699. case SpellID::CLONE: //not allowed
  1700. continue;
  1701. break;
  1702. }
  1703. possibleSpells.push_back(spell->id);
  1704. }
  1705. }
  1706. if(!possibleSpells.empty())
  1707. {
  1708. return *RandomGeneratorUtil::nextItem(possibleSpells, gs->getRandomGenerator());
  1709. }
  1710. else
  1711. {
  1712. return SpellID::NONE;
  1713. }
  1714. }
  1715. SpellID CBattleInfoCallback::getRandomCastedSpell(const CStack * caster) const
  1716. {
  1717. RETURN_IF_NOT_BATTLE(SpellID::NONE);
  1718. TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
  1719. if (!bl->size())
  1720. return SpellID::NONE;
  1721. int totalWeight = 0;
  1722. for(Bonus * b : *bl)
  1723. {
  1724. totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
  1725. }
  1726. int randomPos = gs->getRandomGenerator().nextInt(totalWeight - 1);
  1727. for(Bonus * b : *bl)
  1728. {
  1729. randomPos -= std::max(b->additionalInfo, 1);
  1730. if(randomPos < 0)
  1731. {
  1732. return SpellID(b->subtype);
  1733. }
  1734. }
  1735. return SpellID::NONE;
  1736. }
  1737. int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
  1738. {
  1739. RETURN_IF_NOT_BATTLE(-3);
  1740. if(!battleCanSurrender(Player))
  1741. return -1;
  1742. int ret = 0;
  1743. double discount = 0;
  1744. for(const CStack *s : battleAliveStacks(playerToSide(Player)))
  1745. if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
  1746. ret += s->getCreature()->cost[Res::GOLD] * s->count;
  1747. if(const CGHeroInstance *h = battleGetFightingHero(playerToSide(Player)))
  1748. discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
  1749. ret *= (100.0 - discount) / 100.0;
  1750. vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
  1751. return ret;
  1752. }
  1753. si8 CBattleInfoCallback::battleMaxSpellLevel() const
  1754. {
  1755. const CBonusSystemNode *node = nullptr;
  1756. if(const CGHeroInstance *h = battleGetFightingHero(battleGetMySide()))
  1757. node = h;
  1758. //TODO else use battle node
  1759. if(!node)
  1760. return GameConstants::SPELL_LEVELS;
  1761. //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
  1762. auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
  1763. if(b->size())
  1764. return b->totalValue();
  1765. return GameConstants::SPELL_LEVELS;
  1766. }
  1767. boost::optional<int> CBattleInfoCallback::battleIsFinished() const
  1768. {
  1769. auto stacks = battleGetAllStacks();
  1770. //checking winning condition
  1771. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
  1772. hasStack[0] = hasStack[1] = false;
  1773. for(auto & stack : stacks)
  1774. {
  1775. if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1776. {
  1777. hasStack[1-stack->attackerOwned] = true;
  1778. }
  1779. }
  1780. if(!hasStack[0] && !hasStack[1])
  1781. return 2;
  1782. if(!hasStack[1])
  1783. return 0;
  1784. if(!hasStack[0])
  1785. return 1;
  1786. return boost::none;
  1787. }
  1788. bool AccessibilityInfo::accessible(BattleHex tile, const CStack *stack) const
  1789. {
  1790. return accessible(tile, stack->doubleWide(), stack->attackerOwned);
  1791. }
  1792. bool AccessibilityInfo::accessible(BattleHex tile, bool doubleWide, bool attackerOwned) const
  1793. {
  1794. // All hexes that stack would cover if standing on tile have to be accessible.
  1795. for(auto hex : CStack::getHexes(tile, doubleWide, attackerOwned))
  1796. {
  1797. // If the hex is out of range then the tile isn't accessible
  1798. if(!hex.isValid())
  1799. return false;
  1800. // If we're no defender which step on gate and the hex isn't accessible, then the tile
  1801. // isn't accessible
  1802. else if(at(hex) != EAccessibility::ACCESSIBLE &&
  1803. !(at(hex) == EAccessibility::GATE && !attackerOwned))
  1804. return false;
  1805. }
  1806. return true;
  1807. }
  1808. bool AccessibilityInfo::occupiable(const CStack *stack, BattleHex tile) const
  1809. {
  1810. //obviously, we can occupy tile by standing on it
  1811. if(accessible(tile, stack))
  1812. return true;
  1813. if(stack->doubleWide())
  1814. {
  1815. //Check the tile next to -> if stack stands there, it'll also occupy considered hex
  1816. const BattleHex anotherTile = tile + (stack->attackerOwned ? BattleHex::RIGHT : BattleHex::LEFT);
  1817. if(accessible(anotherTile, stack))
  1818. return true;
  1819. }
  1820. return false;
  1821. }
  1822. ReachabilityInfo::Parameters::Parameters()
  1823. {
  1824. stack = nullptr;
  1825. perspective = BattlePerspective::ALL_KNOWING;
  1826. attackerOwned = doubleWide = flying = false;
  1827. }
  1828. ReachabilityInfo::Parameters::Parameters(const CStack *Stack)
  1829. {
  1830. stack = Stack;
  1831. perspective = (BattlePerspective::BattlePerspective)(!Stack->attackerOwned);
  1832. startPosition = Stack->position;
  1833. doubleWide = stack->doubleWide();
  1834. attackerOwned = stack->attackerOwned;
  1835. flying = stack->hasBonusOfType(Bonus::FLYING);
  1836. knownAccessible = stack->getHexes();
  1837. }
  1838. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell) const
  1839. {
  1840. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1841. ASSERT_IF_CALLED_WITH_PLAYER
  1842. return CBattleInfoCallback::battleCanCastThisSpell(*player, spell, ECastingMode::HERO_CASTING);
  1843. }
  1844. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell, BattleHex destination) const
  1845. {
  1846. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1847. ASSERT_IF_CALLED_WITH_PLAYER
  1848. return battleCanCastThisSpellHere(*player, spell, ECastingMode::HERO_CASTING, destination);
  1849. }
  1850. ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCreatureCastThisSpell(const CSpell * spell, BattleHex destination) const
  1851. {
  1852. RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
  1853. ASSERT_IF_CALLED_WITH_PLAYER
  1854. return battleCanCastThisSpellHere(*player, spell, ECastingMode::CREATURE_ACTIVE_CASTING, destination);
  1855. }
  1856. bool CPlayerBattleCallback::battleCanFlee() const
  1857. {
  1858. RETURN_IF_NOT_BATTLE(false);
  1859. ASSERT_IF_CALLED_WITH_PLAYER
  1860. return CBattleInfoEssentials::battleCanFlee(*player);
  1861. }
  1862. TStacks CPlayerBattleCallback::battleGetStacks(EStackOwnership whose /*= MINE_AND_ENEMY*/, bool onlyAlive /*= true*/) const
  1863. {
  1864. if(whose != MINE_AND_ENEMY)
  1865. {
  1866. ASSERT_IF_CALLED_WITH_PLAYER
  1867. }
  1868. return battleGetStacksIf([=](const CStack * s){
  1869. const bool ownerMatches = (whose == MINE_AND_ENEMY)
  1870. || (whose == ONLY_MINE && s->owner == player)
  1871. || (whose == ONLY_ENEMY && s->owner != player);
  1872. const bool alivenessMatches = s->alive() || !onlyAlive;
  1873. return ownerMatches && alivenessMatches;
  1874. });
  1875. }
  1876. int CPlayerBattleCallback::battleGetSurrenderCost() const
  1877. {
  1878. RETURN_IF_NOT_BATTLE(-3)
  1879. ASSERT_IF_CALLED_WITH_PLAYER
  1880. return CBattleInfoCallback::battleGetSurrenderCost(*player);
  1881. }
  1882. bool CPlayerBattleCallback::battleCanCastSpell(ESpellCastProblem::ESpellCastProblem *outProblem /*= nullptr*/) const
  1883. {
  1884. RETURN_IF_NOT_BATTLE(false);
  1885. ASSERT_IF_CALLED_WITH_PLAYER
  1886. auto problem = CBattleInfoCallback::battleCanCastSpell(*player, ECastingMode::HERO_CASTING);
  1887. if(outProblem)
  1888. *outProblem = problem;
  1889. return problem == ESpellCastProblem::OK;
  1890. }
  1891. const CGHeroInstance * CPlayerBattleCallback::battleGetMyHero() const
  1892. {
  1893. return CBattleInfoEssentials::battleGetFightingHero(battleGetMySide());
  1894. }
  1895. InfoAboutHero CPlayerBattleCallback::battleGetEnemyHero() const
  1896. {
  1897. return battleGetHeroInfo(!battleGetMySide());
  1898. }
  1899. BattleAttackInfo::BattleAttackInfo(const CStack *Attacker, const CStack *Defender, bool Shooting)
  1900. {
  1901. attacker = Attacker;
  1902. defender = Defender;
  1903. attackerBonuses = Attacker;
  1904. defenderBonuses = Defender;
  1905. attackerPosition = Attacker->position;
  1906. defenderPosition = Defender->position;
  1907. attackerCount = Attacker->count;
  1908. defenderCount = Defender->count;
  1909. shooting = Shooting;
  1910. chargedFields = 0;
  1911. luckyHit = false;
  1912. deathBlow = false;
  1913. ballistaDoubleDamage = false;
  1914. }
  1915. BattleAttackInfo BattleAttackInfo::reverse() const
  1916. {
  1917. BattleAttackInfo ret = *this;
  1918. std::swap(ret.attacker, ret.defender);
  1919. std::swap(ret.attackerBonuses, ret.defenderBonuses);
  1920. std::swap(ret.attackerPosition, ret.defenderPosition);
  1921. std::swap(ret.attackerCount, ret.defenderCount);
  1922. ret.shooting = false;
  1923. ret.chargedFields = 0;
  1924. ret.luckyHit = ret.ballistaDoubleDamage = ret.deathBlow = false;
  1925. return ret;
  1926. }