BattleState.cpp 37 KB

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