BattleState.cpp 36 KB

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