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