CStack.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*
  2. * CStack.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 "CStack.h"
  12. #include "battle/BattleInfo.h"
  13. #include "spells/CSpellHandler.h"
  14. #include "CRandomGenerator.h"
  15. #include "NetPacks.h"
  16. CStack::CStack(const CStackInstance *Base, PlayerColor O, int I, ui8 Side, SlotID S)
  17. : base(Base), ID(I), owner(O), slot(S), side(Side),
  18. counterAttacksPerformed(0),counterAttacksTotalCache(0), cloneID(-1),
  19. firstHPleft(-1), position(), shots(0), casts(0), resurrected(0)
  20. {
  21. assert(base);
  22. type = base->type;
  23. count = baseAmount = base->count;
  24. setNodeType(STACK_BATTLE);
  25. }
  26. CStack::CStack()
  27. {
  28. init();
  29. setNodeType(STACK_BATTLE);
  30. }
  31. CStack::CStack(const CStackBasicDescriptor *stack, PlayerColor O, int I, ui8 Side, SlotID S)
  32. : base(nullptr), ID(I), owner(O), slot(S), side(Side),
  33. counterAttacksPerformed(0), counterAttacksTotalCache(0), cloneID(-1),
  34. firstHPleft(-1), position(), shots(0), casts(0), resurrected(0)
  35. {
  36. type = stack->type;
  37. count = baseAmount = stack->count;
  38. setNodeType(STACK_BATTLE);
  39. }
  40. void CStack::init()
  41. {
  42. base = nullptr;
  43. type = nullptr;
  44. ID = -1;
  45. count = baseAmount = -1;
  46. firstHPleft = -1;
  47. owner = PlayerColor::NEUTRAL;
  48. slot = SlotID(255);
  49. side = 1;
  50. position = BattleHex();
  51. counterAttacksPerformed = 0;
  52. counterAttacksTotalCache = 0;
  53. cloneID = -1;
  54. shots = 0;
  55. casts = 0;
  56. resurrected = 0;
  57. }
  58. void CStack::postInit()
  59. {
  60. assert(type);
  61. assert(getParentNodes().size());
  62. firstHPleft = MaxHealth();
  63. shots = getCreature()->valOfBonuses(Bonus::SHOTS);
  64. counterAttacksPerformed = 0;
  65. counterAttacksTotalCache = 0;
  66. casts = valOfBonuses(Bonus::CASTS);
  67. resurrected = 0;
  68. cloneID = -1;
  69. }
  70. ui32 CStack::level() const
  71. {
  72. if (base)
  73. return base->getLevel(); //creatture or commander
  74. else
  75. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  76. }
  77. si32 CStack::magicResistance() const
  78. {
  79. si32 magicResistance;
  80. if (base) //TODO: make war machines receive aura of magic resistance
  81. {
  82. magicResistance = base->magicResistance();
  83. int auraBonus = 0;
  84. for (const CStack * stack : base->armyObj->battle-> batteAdjacentCreatures(this))
  85. {
  86. if (stack->owner == owner)
  87. {
  88. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  89. }
  90. }
  91. magicResistance += auraBonus;
  92. vstd::amin (magicResistance, 100);
  93. }
  94. else
  95. magicResistance = type->magicResistance();
  96. return magicResistance;
  97. }
  98. bool CStack::willMove(int turn /*= 0*/) const
  99. {
  100. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  101. && !moved(turn)
  102. && canMove(turn);
  103. }
  104. bool CStack::canMove( int turn /*= 0*/ ) const
  105. {
  106. return alive()
  107. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  108. }
  109. bool CStack::moved( int turn /*= 0*/ ) const
  110. {
  111. if(!turn)
  112. return vstd::contains(state, EBattleStackState::MOVED);
  113. else
  114. return false;
  115. }
  116. bool CStack::waited(int turn /*= 0*/) const
  117. {
  118. if(!turn)
  119. return vstd::contains(state, EBattleStackState::WAITING);
  120. else
  121. return false;
  122. }
  123. bool CStack::doubleWide() const
  124. {
  125. return getCreature()->doubleWide;
  126. }
  127. BattleHex CStack::occupiedHex() const
  128. {
  129. return occupiedHex(position);
  130. }
  131. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  132. {
  133. if(doubleWide())
  134. {
  135. if(side == BattleSide::ATTACKER)
  136. return assumedPos - 1;
  137. else
  138. return assumedPos + 1;
  139. }
  140. else
  141. {
  142. return BattleHex::INVALID;
  143. }
  144. }
  145. std::vector<BattleHex> CStack::getHexes() const
  146. {
  147. return getHexes(position);
  148. }
  149. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  150. {
  151. return getHexes(assumedPos, doubleWide(), side);
  152. }
  153. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, ui8 side)
  154. {
  155. std::vector<BattleHex> hexes;
  156. hexes.push_back(assumedPos);
  157. if(twoHex)
  158. {
  159. if(side == BattleSide::ATTACKER)
  160. hexes.push_back(assumedPos - 1);
  161. else
  162. hexes.push_back(assumedPos + 1);
  163. }
  164. return hexes;
  165. }
  166. bool CStack::coversPos(BattleHex pos) const
  167. {
  168. return vstd::contains(getHexes(), pos);
  169. }
  170. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  171. {
  172. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  173. std::vector<BattleHex> hexes;
  174. if(doubleWide())
  175. {
  176. const int WN = GameConstants::BFIELD_WIDTH;
  177. if(side == BattleSide::ATTACKER)
  178. { //position is equal to front hex
  179. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  180. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  181. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  182. BattleHex::checkAndPush(hex - 2, hexes);
  183. BattleHex::checkAndPush(hex + 1, hexes);
  184. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  185. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  186. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  187. }
  188. else
  189. {
  190. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  191. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  192. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  193. BattleHex::checkAndPush(hex + 2, hexes);
  194. BattleHex::checkAndPush(hex - 1, hexes);
  195. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  196. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  197. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  198. }
  199. return hexes;
  200. }
  201. else
  202. {
  203. return hex.neighbouringTiles();
  204. }
  205. }
  206. BattleHex::EDir CStack::destShiftDir() const
  207. {
  208. if(doubleWide())
  209. {
  210. if(side == BattleSide::ATTACKER)
  211. return BattleHex::EDir::RIGHT;
  212. else
  213. return BattleHex::EDir::LEFT;
  214. }
  215. else
  216. {
  217. return BattleHex::EDir::NONE;
  218. }
  219. }
  220. std::vector<si32> CStack::activeSpells() const
  221. {
  222. std::vector<si32> ret;
  223. std::stringstream cachingStr;
  224. cachingStr << "!type_" << Bonus::NONE << "source_" << Bonus::SPELL_EFFECT;
  225. CSelector selector = Selector::sourceType(Bonus::SPELL_EFFECT)
  226. .And(CSelector([](const Bonus *b)->bool
  227. {
  228. return b->type != Bonus::NONE;
  229. }));
  230. TBonusListPtr spellEffects = getBonuses(selector, Selector::all, cachingStr.str());
  231. for(const std::shared_ptr<Bonus> it : *spellEffects)
  232. {
  233. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  234. ret.push_back(it->sid);
  235. }
  236. return ret;
  237. }
  238. CStack::~CStack()
  239. {
  240. detachFromAll();
  241. }
  242. const CGHeroInstance * CStack::getMyHero() const
  243. {
  244. if(base)
  245. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  246. else //we are attached directly?
  247. for(const CBonusSystemNode *n : getParentNodes())
  248. if(n->getNodeType() == HERO)
  249. return dynamic_cast<const CGHeroInstance *>(n);
  250. return nullptr;
  251. }
  252. ui32 CStack::totalHealth() const
  253. {
  254. return ((count > 0) ? MaxHealth() * (count-1) : 0) + firstHPleft;//do not hide possible invalid firstHPleft for dead stack
  255. }
  256. std::string CStack::nodeName() const
  257. {
  258. std::ostringstream oss;
  259. oss << "Battle stack [" << ID << "]: " << count << " creatures of ";
  260. if(type)
  261. oss << type->namePl;
  262. else
  263. oss << "[UNDEFINED TYPE]";
  264. oss << " from slot " << slot;
  265. if(base && base->armyObj)
  266. oss << " of armyobj=" << base->armyObj->id.getNum();
  267. return oss.str();
  268. }
  269. std::pair<int,int> CStack::countKilledByAttack(int damageReceived) const
  270. {
  271. int newRemainingHP = 0;
  272. int killedCount = damageReceived / MaxHealth();
  273. unsigned damageFirst = damageReceived % MaxHealth();
  274. if (damageReceived && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  275. {
  276. killedCount = count;
  277. }
  278. else
  279. {
  280. if( firstHPleft <= damageFirst )
  281. {
  282. killedCount++;
  283. newRemainingHP = firstHPleft + MaxHealth() - damageFirst;
  284. }
  285. else
  286. {
  287. newRemainingHP = firstHPleft - damageFirst;
  288. }
  289. }
  290. if(killedCount == count)
  291. newRemainingHP = 0;
  292. return std::make_pair(killedCount, newRemainingHP);
  293. }
  294. void CStack::prepareAttacked(BattleStackAttacked &bsa, CRandomGenerator & rand, boost::optional<int> customCount /*= boost::none*/) const
  295. {
  296. auto afterAttack = countKilledByAttack(bsa.damageAmount);
  297. bsa.killedAmount = afterAttack.first;
  298. bsa.newHP = afterAttack.second;
  299. if(bsa.damageAmount && vstd::contains(state, EBattleStackState::CLONED)) // block ability should not kill clone (0 damage)
  300. {
  301. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  302. return; // no rebirth I believe
  303. }
  304. const int countToUse = customCount ? *customCount : count;
  305. if(countToUse <= bsa.killedAmount) //stack killed
  306. {
  307. bsa.newAmount = 0;
  308. bsa.flags |= BattleStackAttacked::KILLED;
  309. bsa.killedAmount = countToUse; //we cannot kill more creatures than we have
  310. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  311. if(resurrectFactor > 0 && casts) //there must be casts left
  312. {
  313. int resurrectedStackCount = base->count * resurrectFactor / 100;
  314. // last stack has proportional chance to rebirth
  315. auto diff = base->count * resurrectFactor / 100.0 - resurrectedStackCount;
  316. if (diff > rand.nextDouble(0, 0.99))
  317. {
  318. resurrectedStackCount += 1;
  319. }
  320. if(hasBonusOfType(Bonus::REBIRTH, 1))
  321. {
  322. // resurrect at least one Sacred Phoenix
  323. vstd::amax(resurrectedStackCount, 1);
  324. }
  325. if(resurrectedStackCount > 0)
  326. {
  327. bsa.flags |= BattleStackAttacked::REBIRTH;
  328. bsa.newAmount = resurrectedStackCount; //risky?
  329. bsa.newHP = MaxHealth(); //resore full health
  330. }
  331. }
  332. }
  333. else
  334. {
  335. bsa.newAmount = countToUse - bsa.killedAmount;
  336. }
  337. }
  338. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  339. {
  340. if (!attackerPos.isValid())
  341. {
  342. attackerPos = attacker->position;
  343. }
  344. if (!defenderPos.isValid())
  345. {
  346. defenderPos = defender->position;
  347. }
  348. return
  349. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  350. || (attacker->doubleWide() //back <=> front
  351. && BattleHex::mutualPosition(attackerPos + (attacker->side == BattleSide::ATTACKER ? -1 : 1), defenderPos) >= 0)
  352. || (defender->doubleWide() //front <=> back
  353. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->side == BattleSide::ATTACKER ? -1 : 1)) >= 0)
  354. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  355. && BattleHex::mutualPosition(attackerPos + (attacker->side == BattleSide::ATTACKER ? -1 : 1), defenderPos + (defender->side == BattleSide::ATTACKER ? -1 : 1)) >= 0);
  356. }
  357. bool CStack::ableToRetaliate() const //FIXME: crash after clone is killed
  358. {
  359. return alive()
  360. && (counterAttacksPerformed < counterAttacksTotal() || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  361. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  362. && !hasBonusOfType(Bonus::HYPNOTIZED)
  363. && !hasBonusOfType(Bonus::NO_RETALIATION);
  364. }
  365. ui8 CStack::counterAttacksTotal() const
  366. {
  367. //after dispell bonus should remain during current round
  368. ui8 val = 1 + valOfBonuses(Bonus::ADDITIONAL_RETALIATION);
  369. vstd::amax(counterAttacksTotalCache, val);
  370. return counterAttacksTotalCache;
  371. }
  372. si8 CStack::counterAttacksRemaining() const
  373. {
  374. return counterAttacksTotal() - counterAttacksPerformed;
  375. }
  376. std::string CStack::getName() const
  377. {
  378. return (count > 1) ? type->namePl : type->nameSing; //War machines can't use base
  379. }
  380. bool CStack::isValidTarget(bool allowDead/* = false*/) const
  381. {
  382. return (alive() || (allowDead && isDead())) && position.isValid() && !isTurret();
  383. }
  384. bool CStack::isDead() const
  385. {
  386. return !alive() && !isGhost();
  387. }
  388. bool CStack::isGhost() const
  389. {
  390. return vstd::contains(state,EBattleStackState::GHOST);
  391. }
  392. bool CStack::isTurret() const
  393. {
  394. return type->idNumber == CreatureID::ARROW_TOWERS;
  395. }
  396. bool CStack::canBeHealed() const
  397. {
  398. return firstHPleft < MaxHealth()
  399. && isValidTarget()
  400. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  401. }
  402. void CStack::makeGhost()
  403. {
  404. state.erase(EBattleStackState::ALIVE);
  405. state.insert(EBattleStackState::GHOST_PENDING);
  406. }
  407. bool CStack::alive() const //determines if stack is alive
  408. {
  409. return vstd::contains(state,EBattleStackState::ALIVE);
  410. }
  411. ui32 CStack::calculateHealedHealthPoints(ui32 toHeal, const bool resurrect) const
  412. {
  413. if(!resurrect && !alive())
  414. {
  415. logGlobal->warnStream() <<"Attempt to heal corpse detected.";
  416. return 0;
  417. }
  418. return std::min<ui32>(toHeal, MaxHealth() - firstHPleft + (resurrect ? (baseAmount - count) * MaxHealth() : 0));
  419. }
  420. ui8 CStack::getSpellSchoolLevel(const CSpell * spell, int * outSelectedSchool) const
  421. {
  422. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->id));
  423. vstd::abetween(skill, 0, 3);
  424. return skill;
  425. }
  426. ui32 CStack::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  427. {
  428. //stacks does not have sorcery-like bonuses (yet?)
  429. return base;
  430. }
  431. int CStack::getEffectLevel(const CSpell * spell) const
  432. {
  433. return getSpellSchoolLevel(spell);
  434. }
  435. int CStack::getEffectPower(const CSpell * spell) const
  436. {
  437. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * count / 100;
  438. }
  439. int CStack::getEnchantPower(const CSpell * spell) const
  440. {
  441. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  442. if(res<=0)
  443. res = 3;//default for creatures
  444. return res;
  445. }
  446. int CStack::getEffectValue(const CSpell * spell) const
  447. {
  448. return valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->id.toEnum()) * count;
  449. }
  450. const PlayerColor CStack::getOwner() const
  451. {
  452. return owner;
  453. }
  454. void CStack::getCasterName(MetaString & text) const
  455. {
  456. //always plural name in case of spell cast.
  457. text.addReplacement(MetaString::CRE_PL_NAMES, type->idNumber.num);
  458. }
  459. void CStack::getCastDescription(const CSpell * spell, const std::vector<const CStack*> & attacked, MetaString & text) const
  460. {
  461. text.addTxt(MetaString::GENERAL_TXT, 565);//The %s casts %s
  462. //todo: use text 566 for single creature
  463. getCasterName(text);
  464. text.addReplacement(MetaString::SPELL_NAME, spell->id.toEnum());
  465. }