BattleState.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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)
  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::totalHelth() const
  876. {
  877. return (MaxHealth() * (count-1)) + firstHPleft;
  878. }
  879. std::string CStack::nodeName() const
  880. {
  881. std::ostringstream oss;
  882. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  883. if(type)
  884. oss << type->namePl;
  885. else
  886. oss << "[UNDEFINED TYPE]";
  887. oss << " from slot " << slot;
  888. if(base && base->armyObj)
  889. oss << " of armyobj=" << base->armyObj->id.getNum();
  890. return oss.str();
  891. }
  892. std::pair<int,int> CStack::countKilledByAttack(int damageReceived) const
  893. {
  894. int killedCount = 0;
  895. int newRemainingHP = 0;
  896. killedCount = damageReceived / MaxHealth();
  897. unsigned damageFirst = damageReceived % MaxHealth();
  898. if (damageReceived && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  899. {
  900. killedCount = count;
  901. }
  902. else
  903. {
  904. if( firstHPleft <= damageFirst )
  905. {
  906. killedCount++;
  907. newRemainingHP = firstHPleft + MaxHealth() - damageFirst;
  908. }
  909. else
  910. {
  911. newRemainingHP = firstHPleft - damageFirst;
  912. }
  913. }
  914. return std::make_pair(killedCount, newRemainingHP);
  915. }
  916. void CStack::prepareAttacked(BattleStackAttacked &bsa, CRandomGenerator & rand, boost::optional<int> customCount /*= boost::none*/) const
  917. {
  918. auto afterAttack = countKilledByAttack(bsa.damageAmount);
  919. bsa.killedAmount = afterAttack.first;
  920. bsa.newHP = afterAttack.second;
  921. if(bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  922. {
  923. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  924. return; // no rebirth I believe
  925. }
  926. const int countToUse = customCount ? *customCount : count;
  927. if(countToUse <= bsa.killedAmount) //stack killed
  928. {
  929. bsa.newAmount = 0;
  930. bsa.flags |= BattleStackAttacked::KILLED;
  931. bsa.killedAmount = countToUse; //we cannot kill more creatures than we have
  932. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  933. if(resurrectFactor > 0 && casts) //there must be casts left
  934. {
  935. int resurrectedStackCount = base->count * resurrectFactor / 100;
  936. // last stack has proportional chance to rebirth
  937. auto diff = base->count * resurrectFactor / 100.0 - resurrectedStackCount;
  938. if (diff > rand.nextDouble(0, 0.99))
  939. {
  940. resurrectedStackCount += 1;
  941. }
  942. if(hasBonusOfType(Bonus::REBIRTH, 1))
  943. {
  944. // resurrect at least one Sacred Phoenix
  945. vstd::amax(resurrectedStackCount, 1);
  946. }
  947. if(resurrectedStackCount > 0)
  948. {
  949. bsa.flags |= BattleStackAttacked::REBIRTH;
  950. bsa.newAmount = resurrectedStackCount; //risky?
  951. bsa.newHP = MaxHealth(); //resore full health
  952. }
  953. }
  954. }
  955. else
  956. {
  957. bsa.newAmount = countToUse - bsa.killedAmount;
  958. }
  959. }
  960. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  961. {
  962. if (!attackerPos.isValid())
  963. {
  964. attackerPos = attacker->position;
  965. }
  966. if (!defenderPos.isValid())
  967. {
  968. defenderPos = defender->position;
  969. }
  970. return
  971. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  972. || (attacker->doubleWide() //back <=> front
  973. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos) >= 0)
  974. || (defender->doubleWide() //front <=> back
  975. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0)
  976. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  977. && BattleHex::mutualPosition(attackerPos + (attacker->attackerOwned ? -1 : 1), defenderPos + (defender->attackerOwned ? -1 : 1)) >= 0);
  978. }
  979. bool CStack::ableToRetaliate() const //FIXME: crash after clone is killed
  980. {
  981. return alive()
  982. && (counterAttacksPerformed < counterAttacksTotal() || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  983. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  984. && !hasBonusOfType(Bonus::HYPNOTIZED)
  985. && !hasBonusOfType(Bonus::NO_RETALIATION);
  986. }
  987. ui8 CStack::counterAttacksTotal() const
  988. {
  989. //after dispell bonus should remain during current round
  990. ui8 val = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  991. vstd::amax(counterAttacksTotalCache, val);
  992. return counterAttacksTotalCache;
  993. }
  994. si8 CStack::counterAttacksRemaining() const
  995. {
  996. return counterAttacksTotal() - counterAttacksPerformed;
  997. }
  998. std::string CStack::getName() const
  999. {
  1000. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  1001. }
  1002. bool CStack::isValidTarget(bool allowDead/* = false*/) const
  1003. {
  1004. return (alive() || (allowDead && isDead())) && position.isValid() && !isTurret();
  1005. }
  1006. bool CStack::isDead() const
  1007. {
  1008. return !alive() && !isGhost();
  1009. }
  1010. bool CStack::isGhost() const
  1011. {
  1012. return vstd::contains(state,EBattleStackState::GHOST);
  1013. }
  1014. bool CStack::isTurret() const
  1015. {
  1016. return type->idNumber == CreatureID::ARROW_TOWERS;
  1017. }
  1018. bool CStack::canBeHealed() const
  1019. {
  1020. return firstHPleft < MaxHealth()
  1021. && isValidTarget()
  1022. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  1023. }
  1024. void CStack::makeGhost()
  1025. {
  1026. state.erase(EBattleStackState::ALIVE);
  1027. state.insert(EBattleStackState::GHOST_PENDING);
  1028. }
  1029. ui32 CStack::calculateHealedHealthPoints(ui32 toHeal, const bool resurrect) const
  1030. {
  1031. if(!resurrect && !alive())
  1032. {
  1033. logGlobal->warnStream() <<"Attempt to heal corpse detected.";
  1034. return 0;
  1035. }
  1036. return std::min<ui32>(toHeal, MaxHealth() - firstHPleft + (resurrect ? (baseAmount - count) * MaxHealth() : 0));
  1037. }
  1038. ui8 CStack::getSpellSchoolLevel(const CSpell * spell, int * outSelectedSchool) const
  1039. {
  1040. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->id));
  1041. vstd::abetween(skill, 0, 3);
  1042. return skill;
  1043. }
  1044. ui32 CStack::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  1045. {
  1046. //stacks does not have sorcery-like bonuses (yet?)
  1047. return base;
  1048. }
  1049. int CStack::getEffectLevel(const CSpell * spell) const
  1050. {
  1051. return getSpellSchoolLevel(spell);
  1052. }
  1053. int CStack::getEffectPower(const CSpell * spell) const
  1054. {
  1055. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * count / 100;
  1056. }
  1057. int CStack::getEnchantPower(const CSpell * spell) const
  1058. {
  1059. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  1060. if(res<=0)
  1061. res = 3;//default for creatures
  1062. return res;
  1063. }
  1064. int CStack::getEffectValue(const CSpell * spell) const
  1065. {
  1066. return valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->id.toEnum()) * count;
  1067. }
  1068. const PlayerColor CStack::getOwner() const
  1069. {
  1070. return owner;
  1071. }
  1072. void CStack::getCasterName(MetaString & text) const
  1073. {
  1074. //always plural name in case of spell cast.
  1075. text.addReplacement(MetaString::CRE_PL_NAMES, type->idNumber.num);
  1076. }
  1077. void CStack::getCastDescription(const CSpell * spell, const std::vector<const CStack*> & attacked, MetaString & text) const
  1078. {
  1079. text.addTxt(MetaString::GENERAL_TXT, 565);//The %s casts %s
  1080. //todo: use text 566 for single creature
  1081. getCasterName(text);
  1082. text.addReplacement(MetaString::SPELL_NAME, spell->id.toEnum());
  1083. }
  1084. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  1085. {
  1086. switch(phase)
  1087. {
  1088. case 0: //catapult moves after turrets
  1089. return a->getCreature()->idNumber > b->getCreature()->idNumber; //catapult is 145 and turrets are 149
  1090. case 1: //fastest first, upper slot first
  1091. {
  1092. int as = a->Speed(turn), bs = b->Speed(turn);
  1093. if(as != bs)
  1094. return as > bs;
  1095. else
  1096. return a->slot < b->slot;
  1097. }
  1098. case 2: //fastest last, upper slot first
  1099. //TODO: should be replaced with order of receiving morale!
  1100. case 3: //fastest last, upper slot first
  1101. {
  1102. int as = a->Speed(turn), bs = b->Speed(turn);
  1103. if(as != bs)
  1104. return as < bs;
  1105. else
  1106. return a->slot < b->slot;
  1107. }
  1108. default:
  1109. assert(0);
  1110. return false;
  1111. }
  1112. }
  1113. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  1114. {
  1115. phase = Phase;
  1116. turn = Turn;
  1117. }
  1118. SideInBattle::SideInBattle()
  1119. {
  1120. color = PlayerColor::CANNOT_DETERMINE;
  1121. hero = nullptr;
  1122. armyObject = nullptr;
  1123. castSpellsCount = 0;
  1124. enchanterCounter = 0;
  1125. }
  1126. void SideInBattle::init(const CGHeroInstance *Hero, const CArmedInstance *Army)
  1127. {
  1128. hero = Hero;
  1129. armyObject = Army;
  1130. color = armyObject->getOwner();
  1131. if(color == PlayerColor::UNFLAGGABLE)
  1132. color = PlayerColor::NEUTRAL;
  1133. }