BattleState.cpp 37 KB

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