BattleState.cpp 37 KB

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