BattleState.cpp 36 KB

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