BattleState.cpp 37 KB

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