BattleState.cpp 35 KB

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