BattleState.cpp 36 KB

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