CStack.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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 "CGeneralTextHandler.h"
  13. #include "battle/BattleInfo.h"
  14. #include "spells/CSpellHandler.h"
  15. #include "CRandomGenerator.h"
  16. #include "NetPacks.h"
  17. ///CAmmo
  18. CAmmo::CAmmo(const CStack * Owner, CSelector totalSelector):
  19. CStackResource(Owner), totalProxy(Owner, totalSelector)
  20. {
  21. }
  22. int32_t CAmmo::available() const
  23. {
  24. return total() - used;
  25. }
  26. bool CAmmo::canUse(int32_t amount) const
  27. {
  28. return available() - amount >= 0;
  29. }
  30. void CAmmo::reset()
  31. {
  32. used = 0;
  33. }
  34. int32_t CAmmo::total() const
  35. {
  36. return totalProxy->totalValue();
  37. }
  38. void CAmmo::use(int32_t amount)
  39. {
  40. if(available() - amount < 0)
  41. {
  42. logGlobal->error("Stack ammo overuse");
  43. used += available();
  44. }
  45. else
  46. used += amount;
  47. }
  48. ///CShots
  49. CShots::CShots(const CStack * Owner):
  50. CAmmo(Owner, Selector::type(Bonus::SHOTS))
  51. {
  52. }
  53. void CShots::use(int32_t amount)
  54. {
  55. //don't remove ammo if we control a working ammo cart
  56. bool hasAmmoCart = false;
  57. for(const CStack * st : owner->battle->stacks)
  58. {
  59. if(owner->battle->battleMatchOwner(st, owner, true) && st->getCreature()->idNumber == CreatureID::AMMO_CART && st->alive())
  60. {
  61. hasAmmoCart = true;
  62. break;
  63. }
  64. }
  65. if(!hasAmmoCart)
  66. CAmmo::use(amount);
  67. }
  68. ///CCasts
  69. CCasts::CCasts(const CStack * Owner):
  70. CAmmo(Owner, Selector::type(Bonus::CASTS))
  71. {
  72. }
  73. ///CRetaliations
  74. CRetaliations::CRetaliations(const CStack * Owner):
  75. CAmmo(Owner, Selector::type(Bonus::ADDITIONAL_RETALIATION)), totalCache(0)
  76. {
  77. }
  78. int32_t CRetaliations::total() const
  79. {
  80. //after dispell bonus should remain during current round
  81. int32_t val = 1 + totalProxy->totalValue();
  82. vstd::amax(totalCache, val);
  83. return totalCache;
  84. }
  85. void CRetaliations::reset()
  86. {
  87. CAmmo::reset();
  88. totalCache = 0;
  89. }
  90. ///CHealth
  91. CHealth::CHealth(const CStack * Owner):
  92. owner(Owner)
  93. {
  94. reset();
  95. }
  96. CHealth::CHealth(const CHealth & other):
  97. owner(other.owner),
  98. firstHPleft(other.firstHPleft),
  99. fullUnits(other.fullUnits),
  100. resurrected(other.resurrected)
  101. {
  102. }
  103. void CHealth::init(const int32_t baseAmount)
  104. {
  105. reset();
  106. fullUnits = baseAmount > 1 ? baseAmount - 1 : 0;
  107. firstHPleft = baseAmount > 0 ? owner->MaxHealth() : 0;
  108. }
  109. void CHealth::addResurrected(int32_t amount)
  110. {
  111. resurrected += amount;
  112. vstd::amax(resurrected, 0);
  113. }
  114. int64_t CHealth::available() const
  115. {
  116. return static_cast<int64_t>(firstHPleft) + owner->MaxHealth() * fullUnits;
  117. }
  118. int64_t CHealth::total() const
  119. {
  120. return static_cast<int64_t>(owner->MaxHealth()) * owner->baseAmount;
  121. }
  122. void CHealth::damage(int32_t & amount)
  123. {
  124. if(owner->isClone())
  125. {
  126. // block ability should not kill clone (0 damage)
  127. if(amount > 0)
  128. reset();
  129. return;
  130. }
  131. const int32_t oldCount = getCount();
  132. const bool withKills = amount >= firstHPleft;
  133. if(withKills)
  134. {
  135. int64_t totalHealth = available();
  136. if(amount > totalHealth)
  137. amount = totalHealth;
  138. totalHealth -= amount;
  139. if(totalHealth <= 0)
  140. {
  141. fullUnits = 0;
  142. firstHPleft = 0;
  143. }
  144. else
  145. {
  146. setFromTotal(totalHealth);
  147. }
  148. }
  149. else
  150. {
  151. firstHPleft -= amount;
  152. }
  153. addResurrected(getCount() - oldCount);
  154. }
  155. void CHealth::heal(int32_t & amount, EHealLevel level, EHealPower power)
  156. {
  157. const int32_t unitHealth = owner->MaxHealth();
  158. const int32_t oldCount = getCount();
  159. int32_t maxHeal = std::numeric_limits<int32_t>::max();
  160. switch(level)
  161. {
  162. case EHealLevel::HEAL:
  163. maxHeal = std::max(0, unitHealth-firstHPleft);
  164. break;
  165. case EHealLevel::RESURRECT:
  166. maxHeal = total() - available();
  167. break;
  168. default:
  169. assert(level == EHealLevel::OVERHEAL);
  170. break;
  171. }
  172. vstd::amax(maxHeal, 0);
  173. vstd::abetween(amount, 0, maxHeal);
  174. if(amount == 0)
  175. return;
  176. int64_t totalHealth = total();
  177. totalHealth += amount;
  178. setFromTotal(totalHealth);
  179. if(power == EHealPower::ONE_BATTLE)
  180. addResurrected(getCount() - oldCount);
  181. else
  182. assert(power == EHealPower::PERMANENT);
  183. }
  184. void CHealth::setFromTotal(const int64_t totalHealth)
  185. {
  186. const int32_t unitHealth = owner->MaxHealth();
  187. firstHPleft = totalHealth % unitHealth;
  188. fullUnits = totalHealth / unitHealth;
  189. if(firstHPleft == 0 && fullUnits > 1)
  190. {
  191. firstHPleft = unitHealth;
  192. fullUnits -= 1;
  193. }
  194. }
  195. void CHealth::reset()
  196. {
  197. fullUnits = 0;
  198. firstHPleft = 0;
  199. resurrected = 0;
  200. }
  201. int32_t CHealth::getCount() const
  202. {
  203. return fullUnits + (firstHPleft > 0 ? 1 : 0);
  204. }
  205. int32_t CHealth::getFirstHPleft() const
  206. {
  207. return firstHPleft;
  208. }
  209. int32_t CHealth::getResurrected() const
  210. {
  211. return resurrected;
  212. }
  213. void CHealth::fromInfo(const CHealthInfo & info)
  214. {
  215. firstHPleft = info.firstHPleft;
  216. fullUnits = info.fullUnits;
  217. resurrected = info.resurrected;
  218. }
  219. void CHealth::toInfo(CHealthInfo & info) const
  220. {
  221. info.stackId = owner->ID;
  222. info.firstHPleft = firstHPleft;
  223. info.fullUnits = fullUnits;
  224. info.resurrected = resurrected;
  225. }
  226. void CHealth::takeResurrected()
  227. {
  228. int64_t totalHealth = total();
  229. totalHealth -= resurrected * owner->MaxHealth();
  230. vstd::amax(totalHealth, 0);
  231. setFromTotal(totalHealth);
  232. resurrected = 0;
  233. }
  234. ///CStack
  235. CStack::CStack(const CStackInstance * Base, PlayerColor O, int I, ui8 Side, SlotID S)
  236. : base(Base), ID(I), owner(O), slot(S), side(Side),
  237. counterAttacks(this), shots(this), casts(this), health(this), cloneID(-1),
  238. position()
  239. {
  240. assert(base);
  241. type = base->type;
  242. baseAmount = base->count;
  243. health.init(baseAmount); //???
  244. setNodeType(STACK_BATTLE);
  245. }
  246. CStack::CStack():
  247. counterAttacks(this), shots(this), casts(this), health(this)
  248. {
  249. init();
  250. setNodeType(STACK_BATTLE);
  251. }
  252. CStack::CStack(const CStackBasicDescriptor * stack, PlayerColor O, int I, ui8 Side, SlotID S)
  253. : base(nullptr), ID(I), owner(O), slot(S), side(Side),
  254. counterAttacks(this), shots(this), casts(this), health(this), cloneID(-1),
  255. position()
  256. {
  257. type = stack->type;
  258. baseAmount = stack->count;
  259. health.init(baseAmount); //???
  260. setNodeType(STACK_BATTLE);
  261. }
  262. int32_t CStack::getKilled() const
  263. {
  264. int32_t res = baseAmount - health.getCount() + health.getResurrected();
  265. vstd::amax(res, 0);
  266. return res;
  267. }
  268. int32_t CStack::getCount() const
  269. {
  270. return health.getCount();
  271. }
  272. int32_t CStack::getFirstHPleft() const
  273. {
  274. return health.getFirstHPleft();
  275. }
  276. const CCreature * CStack::getCreature() const
  277. {
  278. return type;
  279. }
  280. void CStack::init()
  281. {
  282. base = nullptr;
  283. type = nullptr;
  284. ID = -1;
  285. baseAmount = -1;
  286. owner = PlayerColor::NEUTRAL;
  287. slot = SlotID(255);
  288. side = 1;
  289. position = BattleHex();
  290. cloneID = -1;
  291. }
  292. void CStack::localInit(BattleInfo * battleInfo)
  293. {
  294. battle = battleInfo;
  295. assert(type);
  296. exportBonuses();
  297. if(base) //stack originating from "real" stack in garrison -> attach to it
  298. {
  299. attachTo(const_cast<CStackInstance *>(base));
  300. }
  301. else //attach directly to obj to which stack belongs and creature type
  302. {
  303. CArmedInstance * army = battle->battleGetArmyObject(side);
  304. attachTo(army);
  305. attachTo(const_cast<CCreature *>(type));
  306. }
  307. shots.reset();
  308. counterAttacks.reset();
  309. casts.reset();
  310. health.init(baseAmount);
  311. cloneID = -1;
  312. }
  313. ui32 CStack::level() const
  314. {
  315. if (base)
  316. return base->getLevel(); //creatture or commander
  317. else
  318. return std::max(1, (int)getCreature()->level); //war machine, clone etc
  319. }
  320. si32 CStack::magicResistance() const
  321. {
  322. si32 magicResistance;
  323. if (base) //TODO: make war machines receive aura of magic resistance
  324. {
  325. magicResistance = base->magicResistance();
  326. int auraBonus = 0;
  327. for (const CStack * stack : base->armyObj->battle-> batteAdjacentCreatures(this))
  328. {
  329. if (stack->owner == owner)
  330. {
  331. vstd::amax(auraBonus, stack->valOfBonuses(Bonus::SPELL_RESISTANCE_AURA)); //max value
  332. }
  333. }
  334. magicResistance += auraBonus;
  335. vstd::amin (magicResistance, 100);
  336. }
  337. else
  338. magicResistance = type->magicResistance();
  339. return magicResistance;
  340. }
  341. bool CStack::willMove(int turn /*= 0*/) const
  342. {
  343. return ( turn ? true : !vstd::contains(state, EBattleStackState::DEFENDING) )
  344. && !moved(turn)
  345. && canMove(turn);
  346. }
  347. bool CStack::canMove( int turn /*= 0*/ ) const
  348. {
  349. return alive()
  350. && !hasBonus(Selector::type(Bonus::NOT_ACTIVE).And(Selector::turns(turn))); //eg. Ammo Cart or blinded creature
  351. }
  352. bool CStack::canCast() const
  353. {
  354. return casts.canUse(1);//do not check specific cast abilities here
  355. }
  356. bool CStack::isCaster() const
  357. {
  358. return casts.total() > 0;//do not check specific cast abilities here
  359. }
  360. bool CStack::canShoot() const
  361. {
  362. return shots.canUse(1) && hasBonusOfType(Bonus::SHOOTER);
  363. }
  364. bool CStack::isShooter() const
  365. {
  366. return shots.total() > 0 && hasBonusOfType(Bonus::SHOOTER);
  367. }
  368. bool CStack::moved( int turn /*= 0*/ ) const
  369. {
  370. if(!turn)
  371. return vstd::contains(state, EBattleStackState::MOVED);
  372. else
  373. return false;
  374. }
  375. bool CStack::waited(int turn /*= 0*/) const
  376. {
  377. if(!turn)
  378. return vstd::contains(state, EBattleStackState::WAITING);
  379. else
  380. return false;
  381. }
  382. bool CStack::doubleWide() const
  383. {
  384. return getCreature()->doubleWide;
  385. }
  386. BattleHex CStack::occupiedHex() const
  387. {
  388. return occupiedHex(position);
  389. }
  390. BattleHex CStack::occupiedHex(BattleHex assumedPos) const
  391. {
  392. if(doubleWide())
  393. {
  394. if(side == BattleSide::ATTACKER)
  395. return assumedPos - 1;
  396. else
  397. return assumedPos + 1;
  398. }
  399. else
  400. {
  401. return BattleHex::INVALID;
  402. }
  403. }
  404. std::vector<BattleHex> CStack::getHexes() const
  405. {
  406. return getHexes(position);
  407. }
  408. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos) const
  409. {
  410. return getHexes(assumedPos, doubleWide(), side);
  411. }
  412. std::vector<BattleHex> CStack::getHexes(BattleHex assumedPos, bool twoHex, ui8 side)
  413. {
  414. std::vector<BattleHex> hexes;
  415. hexes.push_back(assumedPos);
  416. if(twoHex)
  417. {
  418. if(side == BattleSide::ATTACKER)
  419. hexes.push_back(assumedPos - 1);
  420. else
  421. hexes.push_back(assumedPos + 1);
  422. }
  423. return hexes;
  424. }
  425. bool CStack::coversPos(BattleHex pos) const
  426. {
  427. return vstd::contains(getHexes(), pos);
  428. }
  429. std::vector<BattleHex> CStack::getSurroundingHexes(BattleHex attackerPos) const
  430. {
  431. BattleHex hex = (attackerPos != BattleHex::INVALID) ? attackerPos : position; //use hypothetical position
  432. std::vector<BattleHex> hexes;
  433. if(doubleWide())
  434. {
  435. const int WN = GameConstants::BFIELD_WIDTH;
  436. if(side == BattleSide::ATTACKER)
  437. { //position is equal to front hex
  438. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+2 : WN+1 ), hexes);
  439. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  440. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  441. BattleHex::checkAndPush(hex - 2, hexes);
  442. BattleHex::checkAndPush(hex + 1, hexes);
  443. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-2 : WN-1 ), hexes);
  444. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  445. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  446. }
  447. else
  448. {
  449. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN+1 : WN ), hexes);
  450. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN : WN-1 ), hexes);
  451. BattleHex::checkAndPush(hex - ( (hex/WN)%2 ? WN-1 : WN-2 ), hexes);
  452. BattleHex::checkAndPush(hex + 2, hexes);
  453. BattleHex::checkAndPush(hex - 1, hexes);
  454. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN-1 : WN ), hexes);
  455. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN : WN+1 ), hexes);
  456. BattleHex::checkAndPush(hex + ( (hex/WN)%2 ? WN+1 : WN+2 ), hexes);
  457. }
  458. return hexes;
  459. }
  460. else
  461. {
  462. return hex.neighbouringTiles();
  463. }
  464. }
  465. BattleHex::EDir CStack::destShiftDir() const
  466. {
  467. if(doubleWide())
  468. {
  469. if(side == BattleSide::ATTACKER)
  470. return BattleHex::EDir::RIGHT;
  471. else
  472. return BattleHex::EDir::LEFT;
  473. }
  474. else
  475. {
  476. return BattleHex::EDir::NONE;
  477. }
  478. }
  479. std::vector<si32> CStack::activeSpells() const
  480. {
  481. std::vector<si32> ret;
  482. std::stringstream cachingStr;
  483. cachingStr << "!type_" << Bonus::NONE << "source_" << Bonus::SPELL_EFFECT;
  484. CSelector selector = Selector::sourceType(Bonus::SPELL_EFFECT)
  485. .And(CSelector([](const Bonus *b)->bool
  486. {
  487. return b->type != Bonus::NONE;
  488. }));
  489. TBonusListPtr spellEffects = getBonuses(selector, Selector::all, cachingStr.str());
  490. for(const std::shared_ptr<Bonus> it : *spellEffects)
  491. {
  492. if (!vstd::contains(ret, it->sid)) //do not duplicate spells with multiple effects
  493. ret.push_back(it->sid);
  494. }
  495. return ret;
  496. }
  497. CStack::~CStack()
  498. {
  499. detachFromAll();
  500. }
  501. const CGHeroInstance * CStack::getMyHero() const
  502. {
  503. if(base)
  504. return dynamic_cast<const CGHeroInstance *>(base->armyObj);
  505. else //we are attached directly?
  506. for(const CBonusSystemNode *n : getParentNodes())
  507. if(n->getNodeType() == HERO)
  508. return dynamic_cast<const CGHeroInstance *>(n);
  509. return nullptr;
  510. }
  511. ui32 CStack::totalHealth() const
  512. {
  513. return health.available();//do not hide possible invalid firstHPleft for dead stack
  514. }
  515. std::string CStack::nodeName() const
  516. {
  517. std::ostringstream oss;
  518. oss << "Battle stack [" << ID << "]: " << health.getCount() << " creatures of ";
  519. if(type)
  520. oss << type->namePl;
  521. else
  522. oss << "[UNDEFINED TYPE]";
  523. oss << " from slot " << slot;
  524. if(base && base->armyObj)
  525. oss << " of armyobj=" << base->armyObj->id.getNum();
  526. return oss.str();
  527. }
  528. CHealth CStack::healthAfterAttacked(int32_t & damage) const
  529. {
  530. CHealth res = health;
  531. res.damage(damage);
  532. return res;
  533. }
  534. CHealth CStack::healthAfterHealed(int32_t & toHeal, EHealLevel level, EHealPower power) const
  535. {
  536. CHealth res = health;
  537. if(level == EHealLevel::HEAL && power == EHealPower::ONE_BATTLE)
  538. logGlobal->error("Heal for one battle does not make sense", nodeName(), toHeal);
  539. else if(isClone())
  540. logGlobal->error("Attempt to heal clone: %s for %d HP", nodeName(), toHeal);
  541. else
  542. res.heal(toHeal, level, power);
  543. return res;
  544. }
  545. void CStack::prepareAttacked(BattleStackAttacked & bsa, CRandomGenerator & rand) const
  546. {
  547. prepareAttacked(bsa, rand, health);
  548. }
  549. void CStack::prepareAttacked(BattleStackAttacked & bsa, CRandomGenerator & rand, const CHealth & customHealth) const
  550. {
  551. CHealth afterAttack = customHealth;
  552. afterAttack.damage(bsa.damageAmount);
  553. bsa.killedAmount = customHealth.getCount() - afterAttack.getCount();
  554. afterAttack.toInfo(bsa.newHealth);
  555. bsa.newHealth.delta = -bsa.damageAmount;
  556. if(afterAttack.available() <= 0 && isClone())
  557. {
  558. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  559. return; // no rebirth I believe
  560. }
  561. if(afterAttack.available() <= 0) //stack killed
  562. {
  563. bsa.flags |= BattleStackAttacked::KILLED;
  564. int resurrectFactor = valOfBonuses(Bonus::REBIRTH);
  565. if(resurrectFactor > 0 && canCast()) //there must be casts left
  566. {
  567. int resurrectedStackCount = baseAmount * resurrectFactor / 100;
  568. // last stack has proportional chance to rebirth
  569. //FIXME: diff is always 0
  570. auto diff = baseAmount * resurrectFactor / 100.0 - resurrectedStackCount;
  571. if(diff > rand.nextDouble(0, 0.99))
  572. {
  573. resurrectedStackCount += 1;
  574. }
  575. if(hasBonusOfType(Bonus::REBIRTH, 1))
  576. {
  577. // resurrect at least one Sacred Phoenix
  578. vstd::amax(resurrectedStackCount, 1);
  579. }
  580. if(resurrectedStackCount > 0)
  581. {
  582. bsa.flags |= BattleStackAttacked::REBIRTH;
  583. //TODO: use StackHealedOrResurrected
  584. bsa.newHealth.firstHPleft = MaxHealth();
  585. bsa.newHealth.fullUnits = resurrectedStackCount - 1;
  586. bsa.newHealth.resurrected = 0; //TODO: add one-battle rebirth?
  587. }
  588. }
  589. }
  590. }
  591. bool CStack::isMeleeAttackPossible(const CStack * attacker, const CStack * defender, BattleHex attackerPos /*= BattleHex::INVALID*/, BattleHex defenderPos /*= BattleHex::INVALID*/)
  592. {
  593. if(!attackerPos.isValid())
  594. attackerPos = attacker->position;
  595. if(!defenderPos.isValid())
  596. defenderPos = defender->position;
  597. return
  598. (BattleHex::mutualPosition(attackerPos, defenderPos) >= 0) //front <=> front
  599. || (attacker->doubleWide() //back <=> front
  600. && BattleHex::mutualPosition(attackerPos + (attacker->side == BattleSide::ATTACKER ? -1 : 1), defenderPos) >= 0)
  601. || (defender->doubleWide() //front <=> back
  602. && BattleHex::mutualPosition(attackerPos, defenderPos + (defender->side == BattleSide::ATTACKER ? -1 : 1)) >= 0)
  603. || (defender->doubleWide() && attacker->doubleWide()//back <=> back
  604. && BattleHex::mutualPosition(attackerPos + (attacker->side == BattleSide::ATTACKER ? -1 : 1), defenderPos + (defender->side == BattleSide::ATTACKER ? -1 : 1)) >= 0);
  605. }
  606. bool CStack::ableToRetaliate() const
  607. {
  608. return alive()
  609. && (counterAttacks.canUse() || hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS))
  610. && !hasBonusOfType(Bonus::SIEGE_WEAPON)
  611. && !hasBonusOfType(Bonus::HYPNOTIZED)
  612. && !hasBonusOfType(Bonus::NO_RETALIATION);
  613. }
  614. std::string CStack::getName() const
  615. {
  616. return (health.getCount() == 1) ? type->nameSing : type->namePl; //War machines can't use base
  617. }
  618. bool CStack::isValidTarget(bool allowDead/* = false*/) const
  619. {
  620. return (alive() || (allowDead && isDead())) && position.isValid() && !isTurret();
  621. }
  622. bool CStack::isDead() const
  623. {
  624. return !alive() && !isGhost();
  625. }
  626. bool CStack::isClone() const
  627. {
  628. return vstd::contains(state, EBattleStackState::CLONED);
  629. }
  630. bool CStack::isGhost() const
  631. {
  632. return vstd::contains(state, EBattleStackState::GHOST);
  633. }
  634. bool CStack::isTurret() const
  635. {
  636. return type->idNumber == CreatureID::ARROW_TOWERS;
  637. }
  638. bool CStack::canBeHealed() const
  639. {
  640. return getFirstHPleft() < MaxHealth()
  641. && isValidTarget()
  642. && !hasBonusOfType(Bonus::SIEGE_WEAPON);
  643. }
  644. void CStack::makeGhost()
  645. {
  646. state.erase(EBattleStackState::ALIVE);
  647. state.insert(EBattleStackState::GHOST_PENDING);
  648. }
  649. bool CStack::alive() const //determines if stack is alive
  650. {
  651. return vstd::contains(state, EBattleStackState::ALIVE);
  652. }
  653. ui8 CStack::getSpellSchoolLevel(const CSpell * spell, int * outSelectedSchool) const
  654. {
  655. int skill = valOfBonuses(Selector::typeSubtype(Bonus::SPELLCASTER, spell->id));
  656. vstd::abetween(skill, 0, 3);
  657. return skill;
  658. }
  659. ui32 CStack::getSpellBonus(const CSpell * spell, ui32 base, const CStack * affectedStack) const
  660. {
  661. //stacks does not have sorcery-like bonuses (yet?)
  662. return base;
  663. }
  664. int CStack::getEffectLevel(const CSpell * spell) const
  665. {
  666. return getSpellSchoolLevel(spell);
  667. }
  668. int CStack::getEffectPower(const CSpell * spell) const
  669. {
  670. return valOfBonuses(Bonus::CREATURE_SPELL_POWER) * health.getCount() / 100;
  671. }
  672. int CStack::getEnchantPower(const CSpell * spell) const
  673. {
  674. int res = valOfBonuses(Bonus::CREATURE_ENCHANT_POWER);
  675. if(res <= 0)
  676. res = 3;//default for creatures
  677. return res;
  678. }
  679. int CStack::getEffectValue(const CSpell * spell) const
  680. {
  681. return valOfBonuses(Bonus::SPECIFIC_SPELL_POWER, spell->id.toEnum()) * health.getCount();
  682. }
  683. const PlayerColor CStack::getOwner() const
  684. {
  685. return owner;
  686. }
  687. void CStack::getCasterName(MetaString & text) const
  688. {
  689. //always plural name in case of spell cast.
  690. addNameReplacement(text, true);
  691. }
  692. void CStack::getCastDescription(const CSpell * spell, const std::vector<const CStack*> & attacked, MetaString & text) const
  693. {
  694. text.addTxt(MetaString::GENERAL_TXT, 565);//The %s casts %s
  695. //todo: use text 566 for single creature
  696. getCasterName(text);
  697. text.addReplacement(MetaString::SPELL_NAME, spell->id.toEnum());
  698. }
  699. void CStack::addText(MetaString & text, ui8 type, int32_t serial, const boost::logic::tribool & plural) const
  700. {
  701. if(boost::logic::indeterminate(plural))
  702. serial = VLC->generaltexth->pluralText(serial, health.getCount());
  703. else if(plural)
  704. serial = VLC->generaltexth->pluralText(serial, 2);
  705. else
  706. serial = VLC->generaltexth->pluralText(serial, 1);
  707. text.addTxt(type, serial);
  708. }
  709. void CStack::addNameReplacement(MetaString & text, const boost::logic::tribool & plural) const
  710. {
  711. if(boost::logic::indeterminate(plural))
  712. text.addCreReplacement(type->idNumber, health.getCount());
  713. else if(plural)
  714. text.addReplacement(MetaString::CRE_PL_NAMES, type->idNumber.num);
  715. else
  716. text.addReplacement(MetaString::CRE_SING_NAMES, type->idNumber.num);
  717. }
  718. std::string CStack::formatGeneralMessage(const int32_t baseTextId) const
  719. {
  720. const int32_t textId = VLC->generaltexth->pluralText(baseTextId, health.getCount());
  721. MetaString text;
  722. text.addTxt(MetaString::GENERAL_TXT, textId);
  723. text.addCreReplacement(type->idNumber, health.getCount());
  724. return text.toString();
  725. }
  726. void CStack::setHealth(const CHealthInfo & value)
  727. {
  728. health.reset();
  729. health.fromInfo(value);
  730. }
  731. void CStack::setHealth(const CHealth & value)
  732. {
  733. health = value;
  734. }