BattleState.cpp 37 KB

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