BattleState.cpp 37 KB

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