BattleState.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. /*
  2. * BattleState.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "BattleState.h"
  12. #include <numeric>
  13. #include "VCMI_Lib.h"
  14. #include "mapObjects/CObjectHandler.h"
  15. #include "CHeroHandler.h"
  16. #include "CCreatureHandler.h"
  17. #include "spells/CSpellHandler.h"
  18. #include "CTownHandler.h"
  19. #include "NetPacks.h"
  20. #include "JsonNode.h"
  21. #include "filesystem/Filesystem.h"
  22. #include "CRandomGenerator.h"
  23. #include "mapObjects/CGTownInstance.h"
  24. SiegeInfo::SiegeInfo()
  25. {
  26. for (int i = 0; i < wallState.size(); ++i)
  27. {
  28. wallState[i] = EWallState::NONE;
  29. }
  30. gateState = EGateState::NONE;
  31. }
  32. const CStack * BattleInfo::getNextStack() const
  33. {
  34. std::vector<const CStack *> hlp;
  35. battleGetStackQueue(hlp, 1, -1);
  36. if(hlp.size())
  37. return hlp[0];
  38. else
  39. return nullptr;
  40. }
  41. int BattleInfo::getAvaliableHex(CreatureID creID, bool attackerOwned, int initialPos) const
  42. {
  43. bool twoHex = VLC->creh->creatures[creID]->isDoubleWide();
  44. //bool flying = VLC->creh->creatures[creID]->isFlying();
  45. int pos;
  46. if (initialPos > -1)
  47. pos = initialPos;
  48. else //summon elementals depending on player side
  49. {
  50. if (attackerOwned)
  51. pos = 0; //top left
  52. else
  53. pos = GameConstants::BFIELD_WIDTH - 1; //top right
  54. }
  55. auto accessibility = getAccesibility();
  56. std::set<BattleHex> occupyable;
  57. for(int i = 0; i < accessibility.size(); i++)
  58. if(accessibility.accessible(i, twoHex, attackerOwned))
  59. occupyable.insert(i);
  60. if (occupyable.empty())
  61. {
  62. return BattleHex::INVALID; //all tiles are covered
  63. }
  64. return BattleHex::getClosestTile(attackerOwned, pos, occupyable);
  65. }
  66. std::pair< std::vector<BattleHex>, int > BattleInfo::getPath(BattleHex start, BattleHex dest, const CStack *stack)
  67. {
  68. auto reachability = getReachability(stack);
  69. if(reachability.predecessors[dest] == -1) //cannot reach destination
  70. {
  71. return std::make_pair(std::vector<BattleHex>(), 0);
  72. }
  73. //making the Path
  74. std::vector<BattleHex> path;
  75. BattleHex curElem = dest;
  76. while(curElem != start)
  77. {
  78. path.push_back(curElem);
  79. curElem = reachability.predecessors[curElem];
  80. }
  81. return std::make_pair(path, reachability.distances[dest]);
  82. }
  83. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero,
  84. bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg, CRandomGenerator & rand )
  85. {
  86. TDmgRange range = calculateDmgRange(attacker, defender, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
  87. if(range.first != range.second)
  88. {
  89. int valuesToAverage[10];
  90. int howManyToAv = std::min<ui32>(10, attacker->count);
  91. for (int g=0; g<howManyToAv; ++g)
  92. {
  93. valuesToAverage[g] = rand.nextInt(range.first, range.second);
  94. }
  95. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  96. }
  97. else
  98. return range.first;
  99. }
  100. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  101. {
  102. for(auto & elem : stacks)//setting casualties
  103. {
  104. const CStack * const st = elem;
  105. si32 killed = (st->alive() ? (st->baseAmount - st->count + st->resurrected) : st->baseAmount);
  106. vstd::amax(killed, 0);
  107. if(killed)
  108. casualties[!st->attackerOwned][st->getCreature()->idNumber] += killed;
  109. }
  110. }
  111. CStack * BattleInfo::generateNewStack(const CStackInstance &base, bool attackerOwned, SlotID slot, BattleHex position) const
  112. {
  113. int stackID = getIdForNewStack();
  114. PlayerColor owner = sides[attackerOwned ? 0 : 1].color;
  115. assert((owner >= PlayerColor::PLAYER_LIMIT) ||
  116. (base.armyObj && base.armyObj->tempOwner == owner));
  117. auto ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  118. ret->position = getAvaliableHex (base.getCreatureID(), attackerOwned, position); //TODO: what if no free tile on battlefield was found?
  119. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  120. return ret;
  121. }
  122. CStack * BattleInfo::generateNewStack(const CStackBasicDescriptor &base, bool attackerOwned, SlotID slot, BattleHex position) const
  123. {
  124. int stackID = getIdForNewStack();
  125. PlayerColor owner = sides[attackerOwned ? 0 : 1].color;
  126. auto ret = new CStack(&base, owner, stackID, attackerOwned, slot);
  127. ret->position = position;
  128. ret->state.insert(EBattleStackState::ALIVE); //alive state indication
  129. return ret;
  130. }
  131. const CGHeroInstance * BattleInfo::battleGetOwner(const CStack * stack) const
  132. {
  133. return sides[!stack->attackerOwned].hero;
  134. }
  135. void BattleInfo::localInit()
  136. {
  137. for(int i = 0; i < 2; i++)
  138. {
  139. auto armyObj = battleGetArmyObject(i);
  140. armyObj->battle = this;
  141. armyObj->attachTo(this);
  142. }
  143. for(CStack *s : stacks)
  144. localInitStack(s);
  145. exportBonuses();
  146. }
  147. void BattleInfo::localInitStack(CStack * s)
  148. {
  149. s->exportBonuses();
  150. if(s->base) //stack originating from "real" stack in garrison -> attach to it
  151. {
  152. s->attachTo(const_cast<CStackInstance*>(s->base));
  153. }
  154. else //attach directly to obj to which stack belongs and creature type
  155. {
  156. CArmedInstance *army = battleGetArmyObject(!s->attackerOwned);
  157. s->attachTo(army);
  158. assert(s->type);
  159. s->attachTo(const_cast<CCreature*>(s->type));
  160. }
  161. s->postInit();
  162. }
  163. namespace CGH
  164. {
  165. static void readBattlePositions(const JsonNode &node, std::vector< std::vector<int> > & dest)
  166. {
  167. for(const JsonNode &level : node.Vector())
  168. {
  169. std::vector<int> pom;
  170. for(const JsonNode &value : level.Vector())
  171. {
  172. pom.push_back(value.Float());
  173. }
  174. dest.push_back(pom);
  175. }
  176. }
  177. }
  178. //RNG that works like H3 one
  179. struct RandGen
  180. {
  181. int seed;
  182. void srand(int s)
  183. {
  184. seed = s;
  185. }
  186. void srand(int3 pos)
  187. {
  188. srand(110291 * pos.x + 167801 * pos.y + 81569);
  189. }
  190. int rand()
  191. {
  192. seed = 214013 * seed + 2531011;
  193. return (seed >> 16) & 0x7FFF;
  194. }
  195. int rand(int min, int max)
  196. {
  197. if(min == max)
  198. return min;
  199. if(min > max)
  200. return min;
  201. return min + rand() % (max - min + 1);
  202. }
  203. };
  204. struct RangeGenerator
  205. {
  206. class ExhaustedPossibilities : public std::exception
  207. {
  208. };
  209. RangeGenerator(int _min, int _max, std::function<int()> _myRand):
  210. min(_min),
  211. remainingCount(_max - _min + 1),
  212. remaining(remainingCount, true),
  213. myRand(_myRand)
  214. {
  215. }
  216. int generateNumber()
  217. {
  218. if(!remainingCount)
  219. throw ExhaustedPossibilities();
  220. if(remainingCount == 1)
  221. return 0;
  222. return myRand() % remainingCount;
  223. }
  224. //get number fulfilling predicate. Never gives the same number twice.
  225. int getSuchNumber(std::function<bool(int)> goodNumberPred = nullptr)
  226. {
  227. int ret = -1;
  228. do
  229. {
  230. int n = generateNumber();
  231. int i = 0;
  232. for(;;i++)
  233. {
  234. assert(i < (int)remaining.size());
  235. if(!remaining[i])
  236. continue;
  237. if(!n)
  238. break;
  239. n--;
  240. }
  241. remainingCount--;
  242. remaining[i] = false;
  243. ret = i + min;
  244. } while(goodNumberPred && !goodNumberPred(ret));
  245. return ret;
  246. }
  247. int min, remainingCount;
  248. std::vector<bool> remaining;
  249. std::function<int()> myRand;
  250. };
  251. BattleInfo * BattleInfo::setupBattle( int3 tile, ETerrainType terrain, BFieldType battlefieldType, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town )
  252. {
  253. CMP_stack cmpst;
  254. auto curB = new BattleInfo();
  255. for(auto i = 0u; i < curB->sides.size(); i++)
  256. curB->sides[i].init(heroes[i], armies[i]);
  257. std::vector<CStack*> & stacks = (curB->stacks);
  258. curB->tile = tile;
  259. curB->battlefieldType = battlefieldType;
  260. curB->round = -2;
  261. curB->activeStack = -1;
  262. if(town)
  263. {
  264. curB->town = town;
  265. curB->terrainType = VLC->townh->factions[town->subID]->nativeTerrain;
  266. }
  267. else
  268. {
  269. curB->town = nullptr;
  270. curB->terrainType = terrain;
  271. }
  272. //setting up siege obstacles
  273. if (town && town->hasFort())
  274. {
  275. curB->si.gateState = EGateState::CLOSED;
  276. for (int b = 0; b < curB->si.wallState.size(); ++b)
  277. {
  278. curB->si.wallState[b] = EWallState::INTACT;
  279. }
  280. if (!town->hasBuilt(BuildingID::CITADEL))
  281. {
  282. curB->si.wallState[EWallPart::KEEP] = EWallState::NONE;
  283. }
  284. if (!town->hasBuilt(BuildingID::CASTLE))
  285. {
  286. curB->si.wallState[EWallPart::UPPER_TOWER] = EWallState::NONE;
  287. curB->si.wallState[EWallPart::BOTTOM_TOWER] = EWallState::NONE;
  288. }
  289. }
  290. //randomize obstacles
  291. if (town == nullptr && !creatureBank) //do it only when it's not siege and not creature bank
  292. {
  293. const int ABSOLUTE_OBSTACLES_COUNT = 34, USUAL_OBSTACLES_COUNT = 91; //shouldn't be changes if we want H3-like obstacle placement
  294. RandGen r;
  295. auto ourRand = [&]{ return r.rand(); };
  296. r.srand(tile);
  297. r.rand(1,8); //battle sound ID to play... can't do anything with it here
  298. int tilesToBlock = r.rand(5,12);
  299. const int specialBattlefield = battlefieldTypeToBI(battlefieldType);
  300. std::vector<BattleHex> blockedTiles;
  301. auto appropriateAbsoluteObstacle = [&](int id)
  302. {
  303. return VLC->heroh->absoluteObstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  304. };
  305. auto appropriateUsualObstacle = [&](int id) -> bool
  306. {
  307. return VLC->heroh->obstacles[id].isAppropriate(curB->terrainType, specialBattlefield);
  308. };
  309. if(r.rand(1,100) <= 40) //put cliff-like obstacle
  310. {
  311. RangeGenerator obidgen(0, ABSOLUTE_OBSTACLES_COUNT-1, ourRand);
  312. try
  313. {
  314. auto obstPtr = std::make_shared<CObstacleInstance>();
  315. obstPtr->obstacleType = CObstacleInstance::ABSOLUTE_OBSTACLE;
  316. obstPtr->ID = obidgen.getSuchNumber(appropriateAbsoluteObstacle);
  317. obstPtr->uniqueID = curB->obstacles.size();
  318. curB->obstacles.push_back(obstPtr);
  319. for(BattleHex blocked : obstPtr->getBlockedTiles())
  320. blockedTiles.push_back(blocked);
  321. tilesToBlock -= VLC->heroh->absoluteObstacles[obstPtr->ID].blockedTiles.size() / 2;
  322. }
  323. catch(RangeGenerator::ExhaustedPossibilities &)
  324. {
  325. //silently ignore, if we can't place absolute obstacle, we'll go with the usual ones
  326. }
  327. }
  328. RangeGenerator obidgen(0, USUAL_OBSTACLES_COUNT-1, ourRand);
  329. try
  330. {
  331. while(tilesToBlock > 0)
  332. {
  333. const int obid = obidgen.getSuchNumber(appropriateUsualObstacle);
  334. const CObstacleInfo &obi = VLC->heroh->obstacles[obid];
  335. auto validPosition = [&](BattleHex pos) -> bool
  336. {
  337. if(obi.height >= pos.getY())
  338. return false;
  339. if(pos.getX() == 0)
  340. return false;
  341. if(pos.getX() + obi.width > 15)
  342. return false;
  343. if(vstd::contains(blockedTiles, pos))
  344. return false;
  345. for(BattleHex blocked : obi.getBlocked(pos))
  346. {
  347. if(vstd::contains(blockedTiles, blocked))
  348. return false;
  349. int x = blocked.getX();
  350. if(x <= 2 || x >= 14)
  351. return false;
  352. }
  353. return true;
  354. };
  355. RangeGenerator posgenerator(18, 168, ourRand);
  356. auto obstPtr = std::make_shared<CObstacleInstance>();
  357. obstPtr->ID = obid;
  358. obstPtr->pos = posgenerator.getSuchNumber(validPosition);
  359. obstPtr->uniqueID = curB->obstacles.size();
  360. curB->obstacles.push_back(obstPtr);
  361. for(BattleHex blocked : obstPtr->getBlockedTiles())
  362. blockedTiles.push_back(blocked);
  363. tilesToBlock -= obi.blockedTiles.size();
  364. }
  365. }
  366. catch(RangeGenerator::ExhaustedPossibilities &)
  367. {
  368. }
  369. }
  370. //reading battleStartpos - add creatures AFTER random obstacles are generated
  371. //TODO: parse once to some structure
  372. std::vector< std::vector<int> > looseFormations[2], tightFormations[2], creBankFormations[2];
  373. std::vector <int> commanderField, commanderBank;
  374. const JsonNode config(ResourceID("config/battleStartpos.json"));
  375. const JsonVector &positions = config["battle_positions"].Vector();
  376. CGH::readBattlePositions(positions[0]["levels"], looseFormations[0]);
  377. CGH::readBattlePositions(positions[1]["levels"], looseFormations[1]);
  378. CGH::readBattlePositions(positions[2]["levels"], tightFormations[0]);
  379. CGH::readBattlePositions(positions[3]["levels"], tightFormations[1]);
  380. CGH::readBattlePositions(positions[4]["levels"], creBankFormations[0]);
  381. CGH::readBattlePositions(positions[5]["levels"], creBankFormations[1]);
  382. for (auto position : config["commanderPositions"]["field"].Vector())
  383. {
  384. commanderField.push_back (position.Float());
  385. }
  386. for (auto position : config["commanderPositions"]["creBank"].Vector())
  387. {
  388. commanderBank.push_back (position.Float());
  389. }
  390. //adding war machines
  391. if(!creatureBank)
  392. {
  393. //Checks if hero has artifact and create appropriate stack
  394. auto handleWarMachine= [&](int side, ArtifactPosition artslot, CreatureID cretype, BattleHex hex)
  395. {
  396. if(heroes[side] && heroes[side]->getArt(artslot))
  397. stacks.push_back(curB->generateNewStack(CStackBasicDescriptor(cretype, 1), !side, SlotID::WAR_MACHINES_SLOT, hex));
  398. };
  399. handleWarMachine(0, ArtifactPosition::MACH1, CreatureID::BALLISTA, 52);
  400. handleWarMachine(0, ArtifactPosition::MACH2, CreatureID::AMMO_CART, 18);
  401. handleWarMachine(0, ArtifactPosition::MACH3, CreatureID::FIRST_AID_TENT, 154);
  402. if(town && town->hasFort())
  403. handleWarMachine(0, ArtifactPosition::MACH4, CreatureID::CATAPULT, 120);
  404. if(!town) //defending hero shouldn't receive ballista (bug #551)
  405. handleWarMachine(1, ArtifactPosition::MACH1, CreatureID::BALLISTA, 66);
  406. handleWarMachine(1, ArtifactPosition::MACH2, CreatureID::AMMO_CART, 32);
  407. handleWarMachine(1, ArtifactPosition::MACH3, CreatureID::FIRST_AID_TENT, 168);
  408. }
  409. //war machines added
  410. //battleStartpos read
  411. for(int side = 0; side < 2; side++)
  412. {
  413. int formationNo = armies[side]->stacksCount() - 1;
  414. vstd::abetween(formationNo, 0, GameConstants::ARMY_SIZE - 1);
  415. int k = 0; //stack serial
  416. for(auto i = armies[side]->Slots().begin(); i != armies[side]->Slots().end(); i++, k++)
  417. {
  418. std::vector<int> *formationVector = nullptr;
  419. if(creatureBank)
  420. formationVector = &creBankFormations[side][formationNo];
  421. else if(armies[side]->formation)
  422. formationVector = &tightFormations[side][formationNo];
  423. else
  424. formationVector = &looseFormations[side][formationNo];
  425. BattleHex pos = (k < formationVector->size() ? formationVector->at(k) : 0);
  426. if(creatureBank && i->second->type->isDoubleWide())
  427. pos += side ? BattleHex::LEFT : BattleHex::RIGHT;
  428. CStack * stack = curB->generateNewStack(*i->second, !side, i->first, pos);
  429. stacks.push_back(stack);
  430. }
  431. }
  432. //adding commanders
  433. for (int i = 0; i < 2; ++i)
  434. {
  435. if (heroes[i] && heroes[i]->commander)
  436. {
  437. CStack * stack = curB->generateNewStack (*heroes[i]->commander, !i, SlotID::COMMANDER_SLOT_PLACEHOLDER,
  438. creatureBank ? commanderBank[i] : commanderField[i]);
  439. stacks.push_back(stack);
  440. }
  441. }
  442. if (curB->town && curB->town->fortLevel() >= CGTownInstance::CITADEL)
  443. {
  444. // keep tower
  445. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID::ARROW_TOWERS_SLOT, -2);
  446. stacks.push_back(stack);
  447. if (curB->town->fortLevel() >= CGTownInstance::CASTLE)
  448. {
  449. // lower tower + upper tower
  450. CStack * stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID::ARROW_TOWERS_SLOT, -4);
  451. stacks.push_back(stack);
  452. stack = curB->generateNewStack(CStackBasicDescriptor(CreatureID::ARROW_TOWERS, 1), false, SlotID::ARROW_TOWERS_SLOT, -3);
  453. stacks.push_back(stack);
  454. }
  455. //moat
  456. auto moat = std::make_shared<MoatObstacle>();
  457. moat->ID = curB->town->subID;
  458. moat->obstacleType = CObstacleInstance::MOAT;
  459. moat->uniqueID = curB->obstacles.size();
  460. curB->obstacles.push_back(moat);
  461. }
  462. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  463. //spell level limiting bonus
  464. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::LEVEL_SPELL_IMMUNITY, Bonus::OTHER,
  465. 0, -1, -1, Bonus::INDEPENDENT_MAX));
  466. //giving terrain overalay premies
  467. int bonusSubtype = -1;
  468. switch(battlefieldType)
  469. {
  470. case BFieldType::MAGIC_PLAINS:
  471. {
  472. bonusSubtype = 0;
  473. }
  474. case BFieldType::FIERY_FIELDS:
  475. {
  476. if(bonusSubtype == -1) bonusSubtype = 1;
  477. }
  478. case BFieldType::ROCKLANDS:
  479. {
  480. if(bonusSubtype == -1) bonusSubtype = 8;
  481. }
  482. case BFieldType::MAGIC_CLOUDS:
  483. {
  484. if(bonusSubtype == -1) bonusSubtype = 2;
  485. }
  486. case BFieldType::LUCID_POOLS:
  487. {
  488. if(bonusSubtype == -1) bonusSubtype = 4;
  489. }
  490. { //common part for cases 9, 14, 15, 16, 17
  491. curB->addNewBonus(new Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::TERRAIN_OVERLAY, 3, -1, "", bonusSubtype));
  492. break;
  493. }
  494. case BFieldType::HOLY_GROUND:
  495. {
  496. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  497. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  498. break;
  499. }
  500. case BFieldType::CLOVER_FIELD:
  501. { //+2 luck bonus for neutral creatures
  502. curB->addNewBonus(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, +2, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared<CreatureAlignmentLimiter>(EAlignment::NEUTRAL)));
  503. break;
  504. }
  505. case BFieldType::EVIL_FOG:
  506. {
  507. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared<CreatureAlignmentLimiter>(EAlignment::GOOD)));
  508. curB->addNewBonus(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, +1, Bonus::TERRAIN_OVERLAY)->addLimiter(std::make_shared<CreatureAlignmentLimiter>(EAlignment::EVIL)));
  509. break;
  510. }
  511. case BFieldType::CURSED_GROUND:
  512. {
  513. curB->addNewBonus(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  514. curB->addNewBonus(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  515. Bonus * b = makeFeature(Bonus::LEVEL_SPELL_IMMUNITY, Bonus::ONE_BATTLE, GameConstants::SPELL_LEVELS, 1, Bonus::TERRAIN_OVERLAY);
  516. b->valType = Bonus::INDEPENDENT_MAX;
  517. curB->addNewBonus(b);
  518. break;
  519. }
  520. }
  521. //overlay premies given
  522. //native terrain bonuses
  523. auto nativeTerrain = std::make_shared<CreatureNativeTerrainLimiter>(curB->terrainType);
  524. curB->addNewBonus(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  525. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  526. curB->addNewBonus(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE)->addLimiter(nativeTerrain));
  527. //////////////////////////////////////////////////////////////////////////
  528. //tactics
  529. bool isTacticsAllowed = !creatureBank; //no tactics in creature banks
  530. int tacticLvls[2] = {0};
  531. for(int i = 0; i < ARRAY_COUNT(tacticLvls); i++)
  532. {
  533. if(heroes[i])
  534. tacticLvls[i] += heroes[i]->getSecSkillLevel(SecondarySkill::TACTICS);
  535. }
  536. int tacticsSkillDiff = tacticLvls[0] - tacticLvls[1];
  537. if(tacticsSkillDiff && isTacticsAllowed)
  538. {
  539. curB->tacticsSide = tacticsSkillDiff < 0;
  540. curB->tacticDistance = std::abs(tacticsSkillDiff)*2 + 1;
  541. }
  542. else
  543. curB->tacticDistance = 0;
  544. // workaround — bonuses affecting only enemy - DOES NOT WORK
  545. for(int i = 0; i < 2; i++)
  546. {
  547. TNodes nodes;
  548. curB->battleGetArmyObject(i)->getRedAncestors(nodes);
  549. for(CBonusSystemNode *n : nodes)
  550. {
  551. for(Bonus *b : n->getExportedBonusList())
  552. {
  553. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY/* && b->propagator && b->propagator->shouldBeAttached(curB)*/)
  554. {
  555. auto bCopy = new Bonus(*b);
  556. bCopy->effectRange = Bonus::NO_LIMIT;
  557. bCopy->propagator.reset();
  558. bCopy->limiter.reset(new StackOwnerLimiter(curB->sides[!i].color));
  559. curB->addNewBonus(bCopy);
  560. }
  561. }
  562. }
  563. }
  564. return curB;
  565. }
  566. const CGHeroInstance * BattleInfo::getHero( PlayerColor player ) const
  567. {
  568. for(int i = 0; i < sides.size(); i++)
  569. if(sides[i].color == player)
  570. return sides[i].hero;
  571. logGlobal->errorStream() << "Player " << player << " is not in battle!";
  572. return nullptr;
  573. }
  574. PlayerColor BattleInfo::theOtherPlayer(PlayerColor player) const
  575. {
  576. return sides[!whatSide(player)].color;
  577. }
  578. ui8 BattleInfo::whatSide(PlayerColor player) const
  579. {
  580. for(int i = 0; i < sides.size(); i++)
  581. if(sides[i].color == player)
  582. return i;
  583. logGlobal->warnStream() << "BattleInfo::whatSide: Player " << player << " is not in battle!";
  584. return -1;
  585. }
  586. int BattleInfo::getIdForNewStack() const
  587. {
  588. if(stacks.size())
  589. {
  590. //stacks vector may be sorted not by ID and they may be not contiguous -> find stack with max ID
  591. auto highestIDStack = *std::max_element(stacks.begin(), stacks.end(),
  592. [](const CStack *a, const CStack *b) { return a->ID < b->ID; });
  593. return highestIDStack->ID + 1;
  594. }
  595. return 0;
  596. }
  597. std::shared_ptr<CObstacleInstance> BattleInfo::getObstacleOnTile(BattleHex tile) const
  598. {
  599. for(auto &obs : obstacles)
  600. if(vstd::contains(obs->getAffectedTiles(), tile))
  601. return obs;
  602. return std::shared_ptr<CObstacleInstance>();
  603. }
  604. BattlefieldBI::BattlefieldBI BattleInfo::battlefieldTypeToBI(BFieldType bfieldType)
  605. {
  606. static const std::map<BFieldType, BattlefieldBI::BattlefieldBI> theMap =
  607. {
  608. {BFieldType::CLOVER_FIELD, BattlefieldBI::CLOVER_FIELD},
  609. {BFieldType::CURSED_GROUND, BattlefieldBI::CURSED_GROUND},
  610. {BFieldType::EVIL_FOG, BattlefieldBI::EVIL_FOG},
  611. {BFieldType::FAVORABLE_WINDS, BattlefieldBI::NONE},
  612. {BFieldType::FIERY_FIELDS, BattlefieldBI::FIERY_FIELDS},
  613. {BFieldType::HOLY_GROUND, BattlefieldBI::HOLY_GROUND},
  614. {BFieldType::LUCID_POOLS, BattlefieldBI::LUCID_POOLS},
  615. {BFieldType::MAGIC_CLOUDS, BattlefieldBI::MAGIC_CLOUDS},
  616. {BFieldType::MAGIC_PLAINS, BattlefieldBI::MAGIC_PLAINS},
  617. {BFieldType::ROCKLANDS, BattlefieldBI::ROCKLANDS},
  618. {BFieldType::SAND_SHORE, BattlefieldBI::COASTAL}
  619. };
  620. auto itr = theMap.find(bfieldType);
  621. if(itr != theMap.end())
  622. return itr->second;
  623. return BattlefieldBI::NONE;
  624. }
  625. CStack * BattleInfo::getStack(int stackID, bool onlyAlive /*= true*/)
  626. {
  627. return const_cast<CStack *>(battleGetStackByID(stackID, onlyAlive));
  628. }
  629. BattleInfo::BattleInfo()
  630. : round(-1), activeStack(-1), selectedStack(-1), town(nullptr), tile(-1,-1,-1),
  631. battlefieldType(BFieldType::NONE), terrainType(ETerrainType::WRONG),
  632. tacticsSide(0), tacticDistance(0)
  633. {
  634. setBattle(this);
  635. setNodeType(BATTLE);
  636. }
  637. CArmedInstance * BattleInfo::battleGetArmyObject(ui8 side) const
  638. {
  639. return const_cast<CArmedInstance*>(CBattleInfoEssentials::battleGetArmyObject(side));
  640. }
  641. CGHeroInstance * BattleInfo::battleGetFightingHero(ui8 side) const
  642. {
  643. return const_cast<CGHeroInstance*>(CBattleInfoEssentials::battleGetFightingHero(side));
  644. }
  645. CStack::CStack(const CStackInstance *Base, PlayerColor O, int I, bool AO, SlotID S)
  646. : base(Base), ID(I), owner(O), slot(S), attackerOwned(AO),
  647. counterAttacksPerformed(0),counterAttacksTotalCache(0), cloneID(-1),
  648. firstHPleft(-1), position(), shots(0), casts(0), resurrected(0)
  649. {
  650. assert(base);
  651. type = base->type;
  652. count = baseAmount = base->count;
  653. setNodeType(STACK_BATTLE);
  654. }
  655. CStack::CStack()
  656. {
  657. init();
  658. setNodeType(STACK_BATTLE);
  659. }
  660. CStack::CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, bool AO, SlotID S)
  661. : base(nullptr), ID(I), owner(O), slot(S), attackerOwned(AO),
  662. counterAttacksPerformed(0), counterAttacksTotalCache(0), cloneID(-1),
  663. firstHPleft(-1), position(), shots(0), casts(0), resurrected(0)
  664. {
  665. type = stack->type;
  666. count = baseAmount = stack->count;
  667. setNodeType(STACK_BATTLE);
  668. }
  669. void CStack::init()
  670. {
  671. base = nullptr;
  672. type = nullptr;
  673. ID = -1;
  674. count = baseAmount = -1;
  675. firstHPleft = -1;
  676. owner = PlayerColor::NEUTRAL;
  677. slot = SlotID(255);
  678. attackerOwned = false;
  679. position = BattleHex();
  680. counterAttacksPerformed = 0;
  681. counterAttacksTotalCache = 0;
  682. cloneID = -1;
  683. shots = 0;
  684. casts = 0;
  685. resurrected = 0;
  686. }
  687. void CStack::postInit()
  688. {
  689. assert(type);
  690. assert(getParentNodes().size());
  691. firstHPleft = MaxHealth();
  692. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  693. counterAttacksPerformed = 0;
  694. counterAttacksTotalCache = 0;
  695. casts = valOfBonuses(Bonus::CASTS);
  696. resurrected = 0;
  697. cloneID = -1;
  698. }
  699. ui32 CStack::level() const
  700. {
  701. if (base)
  702. return base->getLevel(); //creatture or commander
  703. else
  704. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  705. }
  706. si32 CStack::magicResistance() const
  707. {
  708. si32 magicResistance;
  709. if (base) //TODO: make war machines receive aura of magic resistance
  710. {
  711. magicResistance = base->magicResistance();
  712. int auraBonus = 0;
  713. for (const CStack * stack : base->armyObj->battle-> batteAdjacentCreatures(this))
  714. {
  715. if (stack->owner == owner)
  716. {
  717. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  718. }
  719. }
  720. magicResistance += auraBonus;
  721. vstd::amin (magicResistance, 100);
  722. }
  723. else
  724. magicResistance = type->magicResistance();
  725. return magicResistance;
  726. }
  727. void CStack::stackEffectToFeature(std::vector<Bonus> & sf, const Bonus & sse)
  728. {
  729. const CSpell * sp = SpellID(sse.sid).toSpell();
  730. std::vector<Bonus> tmp;
  731. sp->getEffects(tmp, sse.val);
  732. for(Bonus& b : tmp)
  733. {
  734. if(b.turnsRemain == 0)
  735. b.turnsRemain = sse.turnsRemain;
  736. sf.push_back(b);
  737. }
  738. }
  739. bool CStack::willMove(int turn /*= 0*/) const
  740. {
  741. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  742. && !moved(turn)
  743. && canMove(turn);
  744. }
  745. bool CStack::canMove( int turn /*= 0*/ ) const
  746. {
  747. return alive()
  748. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  749. }
  750. bool CStack::moved( int turn /*= 0*/ ) const
  751. {
  752. if(!turn)
  753. return vstd::contains(state, EBattleStackState::MOVED);
  754. else
  755. return false;
  756. }
  757. bool CStack::waited(int turn /*= 0*/) const
  758. {
  759. if(!turn)
  760. return vstd::contains(state, EBattleStackState::WAITING);
  761. else
  762. return false;
  763. }
  764. bool CStack::doubleWide() const
  765. {
  766. return getCreature()->doubleWide;
  767. }
  768. BattleHex CStack::occupiedHex() const
  769. {
  770. return occupiedHex(position);
  771. }
  772. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  773. {
  774. if (doubleWide())
  775. {
  776. if (attackerOwned)
  777. return assumedPos - 1;
  778. else
  779. return assumedPos + 1;
  780. }
  781. else
  782. {
  783. return BattleHex::INVALID;
  784. }
  785. }
  786. std::vector<BattleHex> CStack::getHexes() const
  787. {
  788. return getHexes(position);
  789. }
  790. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  791. {
  792. return getHexes(assumedPos, doubleWide(), attackerOwned);
  793. }
  794. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, bool AttackerOwned)
  795. {
  796. std::vector<BattleHex> hexes;
  797. hexes.push_back(assumedPos);
  798. if (twoHex)
  799. {
  800. if (AttackerOwned)
  801. hexes.push_back(assumedPos - 1);
  802. else
  803. hexes.push_back(assumedPos + 1);
  804. }
  805. return hexes;
  806. }
  807. bool CStack::coversPos(BattleHex pos) const
  808. {
  809. return vstd::contains(getHexes(), pos);
  810. }
  811. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  812. {
  813. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  814. std::vector<BattleHex> hexes;
  815. if (doubleWide())
  816. {
  817. const int WN = GameConstants::BFIELD_WIDTH;
  818. if(attackerOwned)
  819. { //position is equal to front hex
  820. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  821. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  822. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  823. BattleHex::checkAndPush(hex - 2, hexes);
  824. BattleHex::checkAndPush(hex + 1, hexes);
  825. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  826. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  827. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  828. }
  829. else
  830. {
  831. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  832. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  833. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  834. BattleHex::checkAndPush(hex + 2, hexes);
  835. BattleHex::checkAndPush(hex - 1, hexes);
  836. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  837. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  838. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  839. }
  840. return hexes;
  841. }
  842. else
  843. {
  844. return hex.neighbouringTiles();
  845. }
  846. }
  847. std::vector<si32> CStack::activeSpells() const
  848. {
  849. std::vector<si32> ret;
  850. TBonusListPtr spellEffects = getSpellBonuses();
  851. for(const Bonus *it : *spellEffects)
  852. {
  853. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  854. ret.push_back(it->sid);
  855. }
  856. return ret;
  857. }
  858. CStack::~CStack()
  859. {
  860. detachFromAll();
  861. }
  862. const CGHeroInstance * CStack::getMyHero() const
  863. {
  864. if(base)
  865. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  866. else //we are attached directly?
  867. for(const CBonusSystemNode *n : getParentNodes())
  868. if(n->getNodeType() == HERO)
  869. return dynamic_cast<const CGHeroInstance *>(n);
  870. return nullptr;
  871. }
  872. ui32 CStack::totalHelth() const
  873. {
  874. return (MaxHealth() * (count-1)) + firstHPleft;
  875. }
  876. std::string CStack::nodeName() const
  877. {
  878. std::ostringstream oss;
  879. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  880. if(type)
  881. oss << type->namePl;
  882. else
  883. oss << "[UNDEFINED TYPE]";
  884. oss << " from slot " << slot;
  885. if(base && base->armyObj)
  886. oss << " of armyobj=" << base->armyObj->id.getNum();
  887. return oss.str();
  888. }
  889. std::pair<int,int> CStack::countKilledByAttack(int damageReceived) const
  890. {
  891. int killedCount = 0;
  892. int newRemainingHP = 0;
  893. killedCount = damageReceived / MaxHealth();
  894. unsigned damageFirst = damageReceived % MaxHealth();
  895. if (damageReceived && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  896. {
  897. killedCount = count;
  898. }
  899. else
  900. {
  901. if( firstHPleft <= damageFirst )
  902. {
  903. killedCount++;
  904. newRemainingHP = firstHPleft + MaxHealth() - damageFirst;
  905. }
  906. else
  907. {
  908. newRemainingHP = firstHPleft - damageFirst;
  909. }
  910. }
  911. return std::make_pair(killedCount, newRemainingHP);
  912. }
  913. void CStack::prepareAttacked(BattleStackAttacked &bsa, CRandomGenerator & rand, boost::optional<int> customCount /*= boost::none*/) const
  914. {
  915. auto afterAttack = countKilledByAttack(bsa.damageAmount);
  916. bsa.killedAmount = afterAttack.first;
  917. bsa.newHP = afterAttack.second;
  918. if(bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  919. {
  920. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  921. return; // no rebirth I believe
  922. }
  923. const int countToUse = customCount ? *customCount : count;
  924. if(countToUse <= bsa.killedAmount) //stack killed
  925. {
  926. bsa.newAmount = 0;
  927. bsa.flags |= BattleStackAttacked::KILLED;
  928. bsa.killedAmount = countToUse; //we cannot kill more creatures than we have
  929. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  930. if(resurrectFactor > 0 && casts) //there must be casts left
  931. {
  932. int resurrectedStackCount = base->count * resurrectFactor / 100;
  933. // last stack has proportional chance to rebirth
  934. auto diff = base->count * resurrectFactor / 100.0 - resurrectedStackCount;
  935. if (diff > rand.nextDouble(0, 0.99))
  936. {
  937. resurrectedStackCount += 1;
  938. }
  939. if(hasBonusOfType(Bonus::REBIRTH, 1))
  940. {
  941. // resurrect at least one Sacred Phoenix
  942. vstd::amax(resurrectedStackCount, 1);
  943. }
  944. if(resurrectedStackCount > 0)
  945. {
  946. bsa.flags |= BattleStackAttacked::REBIRTH;
  947. bsa.newAmount = resurrectedStackCount; //risky?
  948. bsa.newHP = MaxHealth(); //resore full health
  949. }
  950. }
  951. }
  952. else
  953. {
  954. bsa.newAmount = countToUse - bsa.killedAmount;
  955. }
  956. }
  957. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  958. {
  959. if (!attackerPos.isValid())
  960. {
  961. attackerPos = attacker->position;
  962. }
  963. if (!defenderPos.isValid())
  964. {
  965. defenderPos = defender->position;
  966. }
  967. return
  968. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  969. || (attacker->doubleWide() //back <=> front
  970. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  971. || (defender->doubleWide() //front <=> back
  972. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  973. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  974. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  975. }
  976. bool CStack::ableToRetaliate() const //FIXME: crash after clone is killed
  977. {
  978. return alive()
  979. && (counterAttacksPerformed < counterAttacksTotal() || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  980. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  981. && !hasBonusOfType(Bonus::HYPNOTIZED)
  982. && !hasBonusOfType(Bonus::NO_RETALIATION);
  983. }
  984. ui8 CStack::counterAttacksTotal() const
  985. {
  986. //after dispell bonus should remain during current round
  987. ui8 val = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  988. vstd::amax(counterAttacksTotalCache, val);
  989. return counterAttacksTotalCache;
  990. }
  991. si8 CStack::counterAttacksRemaining() const
  992. {
  993. return counterAttacksTotal() - counterAttacksPerformed;
  994. }
  995. std::string CStack::getName() const
  996. {
  997. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  998. }
  999. bool CStack::isValidTarget(bool allowDead/* = false*/) const
  1000. {
  1001. return (alive() || (allowDead && isDead())) && position.isValid() && !isTurret();
  1002. }
  1003. bool CStack::isDead() const
  1004. {
  1005. return !alive() && !isGhost();
  1006. }
  1007. bool CStack::isGhost() const
  1008. {
  1009. return vstd::contains(state,EBattleStackState::GHOST);
  1010. }
  1011. bool CStack::isTurret() const
  1012. {
  1013. return type->idNumber == CreatureID::ARROW_TOWERS;
  1014. }
  1015. bool CStack::canBeHealed() const
  1016. {
  1017. return firstHPleft < MaxHealth()
  1018. && isValidTarget()
  1019. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1020. }
  1021. void CStack::makeGhost()
  1022. {
  1023. state.erase(EBattleStackState::ALIVE);
  1024. state.insert(EBattleStackState::GHOST_PENDING);
  1025. }
  1026. ui32 CStack::calculateHealedHealthPoints(ui32 toHeal, const bool resurrect) const
  1027. {
  1028. if(!resurrect && !alive())
  1029. {
  1030. logGlobal->warnStream() <<"Attempt to heal corpse detected.";
  1031. return 0;
  1032. }
  1033. return std::min<ui32>(toHeal, MaxHealth() - firstHPleft + (resurrect ? (baseAmount - count) * MaxHealth() : 0));
  1034. }
  1035. ui8 CStack::getSpellSchoolLevel(const CSpell * spell, int * outSelectedSchool) const
  1036. {
  1037. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->id));
  1038. vstd::abetween(skill, 0, 3);
  1039. return skill;
  1040. }
  1041. ui32 CStack::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  1042. {
  1043. //stacks does not have sorcery-like bonuses (yet?)
  1044. return base;
  1045. }
  1046. int CStack::getEffectLevel(const CSpell * spell) const
  1047. {
  1048. return getSpellSchoolLevel(spell);
  1049. }
  1050. int CStack::getEffectPower(const CSpell * spell) const
  1051. {
  1052. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * count / 100;
  1053. }
  1054. int CStack::getEnchantPower(const CSpell * spell) const
  1055. {
  1056. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  1057. if(res<=0)
  1058. res = 3;//default for creatures
  1059. return res;
  1060. }
  1061. int CStack::getEffectValue(const CSpell * spell) const
  1062. {
  1063. return valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->id.toEnum()) * count;
  1064. }
  1065. const PlayerColor CStack::getOwner() const
  1066. {
  1067. return owner;
  1068. }
  1069. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1070. {
  1071. switch(phase)
  1072. {
  1073. case 0: //catapult moves after turrets
  1074. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1075. case 1: //fastest first, upper slot first
  1076. {
  1077. int as = a->Speed(turn), bs = b->Speed(turn);
  1078. if(as != bs)
  1079. return as > bs;
  1080. else
  1081. return a->slot < b->slot;
  1082. }
  1083. case 2: //fastest last, upper slot first
  1084. //TODO: should be replaced with order of receiving morale!
  1085. case 3: //fastest last, upper slot first
  1086. {
  1087. int as = a->Speed(turn), bs = b->Speed(turn);
  1088. if(as != bs)
  1089. return as < bs;
  1090. else
  1091. return a->slot < b->slot;
  1092. }
  1093. default:
  1094. assert(0);
  1095. return false;
  1096. }
  1097. }
  1098. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1099. {
  1100. phase = Phase;
  1101. turn = Turn;
  1102. }
  1103. SideInBattle::SideInBattle()
  1104. {
  1105. color = PlayerColor::CANNOT_DETERMINE;
  1106. hero = nullptr;
  1107. armyObject = nullptr;
  1108. castSpellsCount = 0;
  1109. enchanterCounter = 0;
  1110. }
  1111. void SideInBattle::init(const CGHeroInstance *Hero, const CArmedInstance *Army)
  1112. {
  1113. hero = Hero;
  1114. armyObject = Army;
  1115. color = armyObject->getOwner();
  1116. if(color == PlayerColor::UNFLAGGABLE)
  1117. color = PlayerColor::NEUTRAL;
  1118. }