CUnitState.cpp 21 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * CUnitState.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 "CUnitState.h"
  12. #include <vcmi/spells/Spell.h>
  13. #include "../CCreatureHandler.h"
  14. #include "../serializer/JsonDeserializer.h"
  15. #include "../serializer/JsonSerializer.h"
  16. VCMI_LIB_NAMESPACE_BEGIN
  17. namespace battle
  18. {
  19. ///CAmmo
  20. CAmmo::CAmmo(const battle::Unit * Owner, CSelector totalSelector):
  21. used(0),
  22. owner(Owner),
  23. totalProxy(Owner, totalSelector)
  24. {
  25. reset();
  26. }
  27. CAmmo & CAmmo::operator= (const CAmmo & other)
  28. {
  29. used = other.used;
  30. return *this;
  31. }
  32. int32_t CAmmo::available() const
  33. {
  34. return total() - used;
  35. }
  36. bool CAmmo::canUse(int32_t amount) const
  37. {
  38. return (available() - amount >= 0) || !isLimited();
  39. }
  40. bool CAmmo::isLimited() const
  41. {
  42. return true;
  43. }
  44. void CAmmo::reset()
  45. {
  46. used = 0;
  47. }
  48. int32_t CAmmo::total() const
  49. {
  50. return totalProxy.getValue();
  51. }
  52. void CAmmo::use(int32_t amount)
  53. {
  54. if(!isLimited())
  55. return;
  56. if(available() - amount < 0)
  57. {
  58. logGlobal->error("Stack ammo overuse. total: %d, used: %d, requested: %d", total(), used, amount);
  59. used += available();
  60. }
  61. else
  62. used += amount;
  63. }
  64. void CAmmo::serializeJson(JsonSerializeFormat & handler)
  65. {
  66. handler.serializeInt("used", used, 0);
  67. }
  68. ///CShots
  69. CShots::CShots(const battle::Unit * Owner)
  70. : CAmmo(Owner, Selector::type()(BonusType::SHOTS)),
  71. shooter(Owner, Selector::type()(BonusType::SHOOTER))
  72. {
  73. }
  74. bool CShots::isLimited() const
  75. {
  76. return !shooter.hasBonus() || !env->unitHasAmmoCart(owner);
  77. }
  78. void CShots::setEnv(const IUnitEnvironment * env_)
  79. {
  80. env = env_;
  81. }
  82. int32_t CShots::total() const
  83. {
  84. if(shooter.hasBonus())
  85. return CAmmo::total();
  86. else
  87. return 0;
  88. }
  89. ///CCasts
  90. CCasts::CCasts(const battle::Unit * Owner):
  91. CAmmo(Owner, Selector::type()(BonusType::CASTS))
  92. {
  93. }
  94. ///CRetaliations
  95. CRetaliations::CRetaliations(const battle::Unit * Owner)
  96. : CAmmo(Owner, Selector::type()(BonusType::ADDITIONAL_RETALIATION)),
  97. totalCache(0),
  98. noRetaliation(Owner, Selector::type()(BonusType::SIEGE_WEAPON).Or(Selector::type()(BonusType::NO_RETALIATION))),
  99. unlimited(Owner, Selector::type()(BonusType::UNLIMITED_RETALIATIONS))
  100. {
  101. }
  102. bool CRetaliations::isLimited() const
  103. {
  104. return !unlimited.hasBonus() || noRetaliation.hasBonus();
  105. }
  106. int32_t CRetaliations::total() const
  107. {
  108. if(noRetaliation.hasBonus())
  109. return 0;
  110. //after dispel bonus should remain during current round
  111. int32_t val = 1 + totalProxy.getValue();
  112. vstd::amax(totalCache, val);
  113. return totalCache;
  114. }
  115. void CRetaliations::reset()
  116. {
  117. CAmmo::reset();
  118. totalCache = 0;
  119. }
  120. void CRetaliations::serializeJson(JsonSerializeFormat & handler)
  121. {
  122. CAmmo::serializeJson(handler);
  123. //we may be serialized in the middle of turn
  124. handler.serializeInt("totalCache", totalCache, 0);
  125. }
  126. ///CHealth
  127. CHealth::CHealth(const battle::Unit * Owner):
  128. owner(Owner)
  129. {
  130. reset();
  131. }
  132. CHealth & CHealth::operator=(const CHealth & other)
  133. {
  134. //do not change owner
  135. firstHPleft = other.firstHPleft;
  136. fullUnits = other.fullUnits;
  137. resurrected = other.resurrected;
  138. return *this;
  139. }
  140. void CHealth::init()
  141. {
  142. reset();
  143. fullUnits = owner->unitBaseAmount() > 1 ? owner->unitBaseAmount() - 1 : 0;
  144. firstHPleft = owner->unitBaseAmount() > 0 ? owner->getMaxHealth() : 0;
  145. }
  146. void CHealth::addResurrected(int32_t amount)
  147. {
  148. resurrected += amount;
  149. vstd::amax(resurrected, 0);
  150. }
  151. int64_t CHealth::available() const
  152. {
  153. return static_cast<int64_t>(firstHPleft) + owner->getMaxHealth() * fullUnits;
  154. }
  155. int64_t CHealth::total() const
  156. {
  157. return static_cast<int64_t>(owner->getMaxHealth()) * owner->unitBaseAmount();
  158. }
  159. void CHealth::damage(int64_t & amount)
  160. {
  161. const int32_t oldCount = getCount();
  162. const bool withKills = amount >= firstHPleft;
  163. if(withKills)
  164. {
  165. int64_t totalHealth = available();
  166. if(amount > totalHealth)
  167. amount = totalHealth;
  168. totalHealth -= amount;
  169. if(totalHealth <= 0)
  170. {
  171. fullUnits = 0;
  172. firstHPleft = 0;
  173. }
  174. else
  175. {
  176. setFromTotal(totalHealth);
  177. }
  178. }
  179. else
  180. {
  181. firstHPleft -= static_cast<int32_t>(amount);
  182. }
  183. addResurrected(getCount() - oldCount);
  184. }
  185. HealInfo CHealth::heal(int64_t & amount, EHealLevel level, EHealPower power)
  186. {
  187. const int32_t unitHealth = owner->getMaxHealth();
  188. const int32_t oldCount = getCount();
  189. int64_t maxHeal = std::numeric_limits<int64_t>::max();
  190. switch(level)
  191. {
  192. case EHealLevel::HEAL:
  193. maxHeal = std::max(0, unitHealth - firstHPleft);
  194. break;
  195. case EHealLevel::RESURRECT:
  196. maxHeal = total() - available();
  197. break;
  198. default:
  199. assert(level == EHealLevel::OVERHEAL);
  200. break;
  201. }
  202. vstd::amax(maxHeal, 0);
  203. vstd::abetween(amount, int64_t(0), maxHeal);
  204. if(amount == 0)
  205. return {};
  206. int64_t availableHealth = available();
  207. availableHealth += amount;
  208. setFromTotal(availableHealth);
  209. if(power == EHealPower::ONE_BATTLE)
  210. addResurrected(getCount() - oldCount);
  211. else
  212. assert(power == EHealPower::PERMANENT);
  213. return HealInfo(amount, getCount() - oldCount);
  214. }
  215. void CHealth::setFromTotal(const int64_t totalHealth)
  216. {
  217. const int32_t unitHealth = owner->getMaxHealth();
  218. firstHPleft = totalHealth % unitHealth;
  219. fullUnits = static_cast<int32_t>(totalHealth / unitHealth);
  220. if(firstHPleft == 0 && fullUnits >= 1)
  221. {
  222. firstHPleft = unitHealth;
  223. fullUnits -= 1;
  224. }
  225. }
  226. void CHealth::reset()
  227. {
  228. fullUnits = 0;
  229. firstHPleft = 0;
  230. resurrected = 0;
  231. }
  232. int32_t CHealth::getCount() const
  233. {
  234. return fullUnits + (firstHPleft > 0 ? 1 : 0);
  235. }
  236. int32_t CHealth::getFirstHPleft() const
  237. {
  238. return firstHPleft;
  239. }
  240. int32_t CHealth::getResurrected() const
  241. {
  242. return resurrected;
  243. }
  244. void CHealth::takeResurrected()
  245. {
  246. if(resurrected != 0)
  247. {
  248. int64_t totalHealth = available();
  249. totalHealth -= resurrected * owner->getMaxHealth();
  250. vstd::amax(totalHealth, 0);
  251. setFromTotal(totalHealth);
  252. resurrected = 0;
  253. }
  254. }
  255. void CHealth::serializeJson(JsonSerializeFormat & handler)
  256. {
  257. handler.serializeInt("firstHPleft", firstHPleft, 0);
  258. handler.serializeInt("fullUnits", fullUnits, 0);
  259. handler.serializeInt("resurrected", resurrected, 0);
  260. }
  261. ///CUnitState
  262. CUnitState::CUnitState():
  263. env(nullptr),
  264. cloned(false),
  265. defending(false),
  266. defendingAnim(false),
  267. drainedMana(false),
  268. fear(false),
  269. hadMorale(false),
  270. castSpellThisTurn(false),
  271. ghost(false),
  272. ghostPending(false),
  273. movedThisRound(false),
  274. summoned(false),
  275. waiting(false),
  276. waitedThisTurn(false),
  277. casts(this),
  278. counterAttacks(this),
  279. health(this),
  280. shots(this),
  281. stackSpeedPerTurn(this, Selector::type()(BonusType::STACKS_SPEED), BonusCacheMode::VALUE),
  282. immobilizedPerTurn(this, Selector::type()(BonusType::SIEGE_WEAPON).Or(Selector::type()(BonusType::BIND_EFFECT)), BonusCacheMode::PRESENCE),
  283. bonusCache(this),
  284. cloneID(-1)
  285. {
  286. }
  287. CUnitState & CUnitState::operator=(const CUnitState & other)
  288. {
  289. //do not change unit and bonus info
  290. cloned = other.cloned;
  291. defending = other.defending;
  292. defendingAnim = other.defendingAnim;
  293. drainedMana = other.drainedMana;
  294. fear = other.fear;
  295. hadMorale = other.hadMorale;
  296. castSpellThisTurn = other.castSpellThisTurn;
  297. ghost = other.ghost;
  298. ghostPending = other.ghostPending;
  299. movedThisRound = other.movedThisRound;
  300. summoned = other.summoned;
  301. waiting = other.waiting;
  302. waitedThisTurn = other.waitedThisTurn;
  303. casts = other.casts;
  304. counterAttacks = other.counterAttacks;
  305. shots = other.shots;
  306. health = other.health;
  307. cloneID = other.cloneID;
  308. position = other.position;
  309. return *this;
  310. }
  311. int32_t CUnitState::creatureIndex() const
  312. {
  313. return static_cast<int32_t>(creatureId().toEnum());
  314. }
  315. CreatureID CUnitState::creatureId() const
  316. {
  317. return unitType()->getId();
  318. }
  319. int32_t CUnitState::creatureLevel() const
  320. {
  321. return static_cast<int32_t>(unitType()->getLevel());
  322. }
  323. bool CUnitState::doubleWide() const
  324. {
  325. return unitType()->isDoubleWide();
  326. }
  327. int32_t CUnitState::creatureCost() const
  328. {
  329. return unitType()->getRecruitCost(EGameResID::GOLD);
  330. }
  331. int32_t CUnitState::creatureIconIndex() const
  332. {
  333. return unitType()->getIconIndex();
  334. }
  335. FactionID CUnitState::getFactionID() const
  336. {
  337. return unitType()->getFactionID();
  338. }
  339. int32_t CUnitState::getCasterUnitId() const
  340. {
  341. return static_cast<int32_t>(unitId());
  342. }
  343. const CGHeroInstance * CUnitState::getHeroCaster() const
  344. {
  345. return nullptr;
  346. }
  347. int32_t CUnitState::getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool) const
  348. {
  349. int32_t skill = valOfBonuses(Selector::typeSubtype(BonusType::SPELLCASTER, BonusSubtypeID(spell->getId())));
  350. vstd::abetween(skill, 0, 3);
  351. return skill;
  352. }
  353. int64_t CUnitState::getSpellBonus(const spells::Spell * spell, int64_t base, const Unit * affectedStack) const
  354. {
  355. //does not have sorcery-like bonuses (yet?)
  356. return base;
  357. }
  358. int64_t CUnitState::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  359. {
  360. return base;
  361. }
  362. int32_t CUnitState::getEffectLevel(const spells::Spell * spell) const
  363. {
  364. return getSpellSchoolLevel(spell);
  365. }
  366. int32_t CUnitState::getEffectPower(const spells::Spell * spell) const
  367. {
  368. return valOfBonuses(BonusType::CREATURE_SPELL_POWER) * getCount() / 100;
  369. }
  370. int32_t CUnitState::getEnchantPower(const spells::Spell * spell) const
  371. {
  372. int32_t res = valOfBonuses(BonusType::CREATURE_ENCHANT_POWER);
  373. if(res <= 0)
  374. res = 3;//default for creatures
  375. return res;
  376. }
  377. int64_t CUnitState::getEffectValue(const spells::Spell * spell) const
  378. {
  379. return static_cast<int64_t>(getCount()) * valOfBonuses(BonusType::SPECIFIC_SPELL_POWER, BonusSubtypeID(spell->getId()));
  380. }
  381. int64_t CUnitState::getEffectRange(const spells::Spell * spell) const
  382. {
  383. return valOfBonuses(BonusType::SPECIFIC_SPELL_RANGE, BonusSubtypeID(spell->getId()));
  384. }
  385. PlayerColor CUnitState::getCasterOwner() const
  386. {
  387. return env->unitEffectiveOwner(this);
  388. }
  389. void CUnitState::getCasterName(MetaString & text) const
  390. {
  391. //always plural name in case of spell cast.
  392. addNameReplacement(text, true);
  393. }
  394. void CUnitState::getCastDescription(const spells::Spell * spell, const battle::Units & attacked, MetaString & text) const
  395. {
  396. text.appendLocalString(EMetaText::GENERAL_TXT, 565);//The %s casts %s
  397. //todo: use text 566 for single creature
  398. getCasterName(text);
  399. text.replaceName(spell->getId());
  400. }
  401. int32_t CUnitState::manaLimit() const
  402. {
  403. return 0; //TODO: creature casting with mana mode (for mods)
  404. }
  405. bool CUnitState::ableToRetaliate() const
  406. {
  407. return alive()
  408. && counterAttacks.canUse();
  409. }
  410. bool CUnitState::alive() const
  411. {
  412. return health.getCount() > 0;
  413. }
  414. bool CUnitState::isGhost() const
  415. {
  416. return ghost;
  417. }
  418. bool CUnitState::isFrozen() const
  419. {
  420. return hasBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(SpellID(SpellID::STONE_GAZE))));
  421. }
  422. bool CUnitState::isValidTarget(bool allowDead) const
  423. {
  424. return (alive() || (allowDead && isDead())) && getPosition().isValid() && !isTurret();
  425. }
  426. bool CUnitState::isClone() const
  427. {
  428. return cloned;
  429. }
  430. bool CUnitState::hasClone() const
  431. {
  432. return cloneID > 0;
  433. }
  434. bool CUnitState::canCast() const
  435. {
  436. return casts.canUse(1) && !castSpellThisTurn;//do not check specific cast abilities here
  437. }
  438. bool CUnitState::isCaster() const
  439. {
  440. return casts.total() > 0;//do not check specific cast abilities here
  441. }
  442. bool CUnitState::canShootBlocked() const
  443. {
  444. return bonusCache.hasBonus(UnitBonusValuesProxy::HAS_FREE_SHOOTING);
  445. }
  446. bool CUnitState::canShoot() const
  447. {
  448. return
  449. shots.canUse(1) &&
  450. bonusCache.getBonusValue(UnitBonusValuesProxy::FORGETFULL) <= 1; //advanced+ level
  451. }
  452. bool CUnitState::isShooter() const
  453. {
  454. return shots.total() > 0;
  455. }
  456. int32_t CUnitState::getKilled() const
  457. {
  458. int32_t res = unitBaseAmount() - health.getCount() + health.getResurrected();
  459. vstd::amax(res, 0);
  460. return res;
  461. }
  462. int32_t CUnitState::getCount() const
  463. {
  464. return health.getCount();
  465. }
  466. int32_t CUnitState::getFirstHPleft() const
  467. {
  468. return health.getFirstHPleft();
  469. }
  470. int64_t CUnitState::getAvailableHealth() const
  471. {
  472. return health.available();
  473. }
  474. int64_t CUnitState::getTotalHealth() const
  475. {
  476. return health.total();
  477. }
  478. uint32_t CUnitState::getMaxHealth() const
  479. {
  480. return std::max(1, bonusCache.getBonusValue(UnitBonusValuesProxy::STACK_HEALTH));
  481. }
  482. BattleHex CUnitState::getPosition() const
  483. {
  484. return position;
  485. }
  486. void CUnitState::setPosition(const BattleHex & hex)
  487. {
  488. position = hex;
  489. }
  490. int32_t CUnitState::getInitiative(int turn) const
  491. {
  492. return stackSpeedPerTurn.getValue(turn);
  493. }
  494. ui32 CUnitState::getMovementRange(int turn) const
  495. {
  496. if (immobilizedPerTurn.getValue(0) != 0)
  497. return 0;
  498. return stackSpeedPerTurn.getValue(0);
  499. }
  500. ui32 CUnitState::getMovementRange() const
  501. {
  502. return getMovementRange(0);
  503. }
  504. uint8_t CUnitState::getRangedFullDamageDistance() const
  505. {
  506. if(!isShooter())
  507. return 0;
  508. // overwrite full ranged damage distance with the value set in Additional info field of LIMITED_SHOOTING_RANGE bonus
  509. if(hasBonusOfType(BonusType::LIMITED_SHOOTING_RANGE))
  510. {
  511. auto bonus = this->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  512. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  513. return bonus->additionalInfo[0];
  514. }
  515. if (hasBonusOfType(BonusType::NO_DISTANCE_PENALTY))
  516. return GameConstants::BATTLE_SHOOTING_RANGE_DISTANCE;
  517. return GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE;
  518. }
  519. uint8_t CUnitState::getShootingRangeDistance() const
  520. {
  521. if(!isShooter())
  522. return 0;
  523. uint8_t shootingRangeDistance = GameConstants::BATTLE_SHOOTING_RANGE_DISTANCE;
  524. // overwrite full ranged damage distance with the value set in Additional info field of LIMITED_SHOOTING_RANGE bonus
  525. if(hasBonusOfType(BonusType::LIMITED_SHOOTING_RANGE))
  526. {
  527. auto bonus = this->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  528. if(bonus != nullptr)
  529. shootingRangeDistance = bonus->val;
  530. }
  531. return shootingRangeDistance;
  532. }
  533. bool CUnitState::canMove(int turn) const
  534. {
  535. if (!alive())
  536. return false;
  537. if (turn == 0)
  538. return !hasBonusOfType(BonusType::NOT_ACTIVE);
  539. std::string cachingStr = "type_NOT_ACTIVE_turns_" + std::to_string(turn);
  540. return !hasBonus(Selector::type()(BonusType::NOT_ACTIVE).And(Selector::turns(turn)), cachingStr); //eg. Ammo Cart or blinded creature
  541. }
  542. bool CUnitState::defended(int turn) const
  543. {
  544. return !turn && defending;
  545. }
  546. bool CUnitState::moved(int turn) const
  547. {
  548. if(!turn && !waiting)
  549. return movedThisRound;
  550. else
  551. return false;
  552. }
  553. bool CUnitState::willMove(int turn) const
  554. {
  555. return (turn ? true : !defending)
  556. && !moved(turn)
  557. && canMove(turn);
  558. }
  559. bool CUnitState::waited(int turn) const
  560. {
  561. if(!turn)
  562. return waiting;
  563. else
  564. return false;
  565. }
  566. BattlePhases::Type CUnitState::battleQueuePhase(int turn) const
  567. {
  568. if(turn <= 0 && waited()) //consider waiting state only for ongoing round
  569. {
  570. if(hadMorale)
  571. return BattlePhases::WAIT_MORALE;
  572. else
  573. return BattlePhases::WAIT;
  574. }
  575. else if(creatureIndex() == CreatureID::CATAPULT || isTurret()) //catapult and turrets are first
  576. {
  577. return BattlePhases::SIEGE;
  578. }
  579. else
  580. {
  581. return BattlePhases::NORMAL;
  582. }
  583. }
  584. bool CUnitState::isHypnotized() const
  585. {
  586. return bonusCache.hasBonus(UnitBonusValuesProxy::HYPNOTIZED);
  587. }
  588. bool CUnitState::isInvincible() const
  589. {
  590. return bonusCache.hasBonus(UnitBonusValuesProxy::INVINCIBLE);
  591. }
  592. int CUnitState::getTotalAttacks(bool ranged) const
  593. {
  594. return 1 + (ranged ?
  595. bonusCache.getBonusValue(UnitBonusValuesProxy::TOTAL_ATTACKS_RANGED):
  596. bonusCache.getBonusValue(UnitBonusValuesProxy::TOTAL_ATTACKS_MELEE));
  597. }
  598. int CUnitState::getMinDamage(bool ranged) const
  599. {
  600. return ranged ?
  601. bonusCache.getBonusValue(UnitBonusValuesProxy::MIN_DAMAGE_RANGED):
  602. bonusCache.getBonusValue(UnitBonusValuesProxy::MIN_DAMAGE_MELEE);
  603. }
  604. int CUnitState::getMaxDamage(bool ranged) const
  605. {
  606. return ranged ?
  607. bonusCache.getBonusValue(UnitBonusValuesProxy::MAX_DAMAGE_RANGED):
  608. bonusCache.getBonusValue(UnitBonusValuesProxy::MAX_DAMAGE_MELEE);
  609. }
  610. int CUnitState::getAttack(bool ranged) const
  611. {
  612. int attack = ranged ?
  613. bonusCache.getBonusValue(UnitBonusValuesProxy::ATTACK_RANGED):
  614. bonusCache.getBonusValue(UnitBonusValuesProxy::ATTACK_MELEE);
  615. int frenzy = bonusCache.getBonusValue(UnitBonusValuesProxy::IN_FRENZY);
  616. if(frenzy != 0)
  617. {
  618. int defence = ranged ?
  619. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_RANGED):
  620. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_MELEE);
  621. int frenzyBonus = frenzy * defence / 100;
  622. attack += frenzyBonus;
  623. }
  624. vstd::amax(attack, 0);
  625. return attack;
  626. }
  627. int CUnitState::getDefense(bool ranged) const
  628. {
  629. int frenzy = bonusCache.getBonusValue(UnitBonusValuesProxy::IN_FRENZY);
  630. if(frenzy != 0)
  631. {
  632. return 0;
  633. }
  634. else
  635. {
  636. int defence = ranged ?
  637. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_RANGED):
  638. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_MELEE);
  639. vstd::amax(defence, 0);
  640. return defence;
  641. }
  642. }
  643. std::shared_ptr<Unit> CUnitState::acquire() const
  644. {
  645. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  646. ret->localInit(env);
  647. *ret = *this;
  648. return ret;
  649. }
  650. std::shared_ptr<CUnitState> CUnitState::acquireState() const
  651. {
  652. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  653. ret->localInit(env);
  654. *ret = *this;
  655. return ret;
  656. }
  657. void CUnitState::serializeJson(JsonSerializeFormat & handler)
  658. {
  659. handler.serializeBool("cloned", cloned);
  660. handler.serializeBool("defending", defending);
  661. handler.serializeBool("defendingAnim", defendingAnim);
  662. handler.serializeBool("drainedMana", drainedMana);
  663. handler.serializeBool("fear", fear);
  664. handler.serializeBool("hadMorale", hadMorale);
  665. handler.serializeBool("castSpellThisTurn", castSpellThisTurn);
  666. handler.serializeBool("ghost", ghost);
  667. handler.serializeBool("ghostPending", ghostPending);
  668. handler.serializeBool("moved", movedThisRound);
  669. handler.serializeBool("summoned", summoned);
  670. handler.serializeBool("waiting", waiting);
  671. handler.serializeBool("waitedThisTurn", waitedThisTurn);
  672. handler.serializeStruct("casts", casts);
  673. handler.serializeStruct("counterAttacks", counterAttacks);
  674. handler.serializeStruct("health", health);
  675. handler.serializeStruct("shots", shots);
  676. handler.serializeInt("cloneID", cloneID);
  677. si16 posValue = position.toInt();
  678. handler.serializeInt("position", posValue);
  679. position = posValue;
  680. }
  681. void CUnitState::localInit(const IUnitEnvironment * env_)
  682. {
  683. env = env_;
  684. shots.setEnv(env);
  685. reset();
  686. health.init();
  687. }
  688. void CUnitState::reset()
  689. {
  690. cloned = false;
  691. defending = false;
  692. defendingAnim = false;
  693. drainedMana = false;
  694. fear = false;
  695. hadMorale = false;
  696. castSpellThisTurn = false;
  697. ghost = false;
  698. ghostPending = false;
  699. movedThisRound = false;
  700. summoned = false;
  701. waiting = false;
  702. waitedThisTurn = false;
  703. casts.reset();
  704. counterAttacks.reset();
  705. health.reset();
  706. shots.reset();
  707. cloneID = -1;
  708. position = BattleHex::INVALID;
  709. }
  710. void CUnitState::save(JsonNode & data)
  711. {
  712. //TODO: use instance resolver
  713. data.clear();
  714. JsonSerializer ser(nullptr, data);
  715. ser.serializeStruct("state", *this);
  716. }
  717. void CUnitState::load(const JsonNode & data)
  718. {
  719. //TODO: use instance resolver
  720. reset();
  721. JsonDeserializer deser(nullptr, data);
  722. deser.serializeStruct("state", *this);
  723. }
  724. void CUnitState::damage(int64_t & amount)
  725. {
  726. if(cloned)
  727. {
  728. // block ability should not kill clone (0 damage)
  729. if(amount > 0)
  730. {
  731. amount = 0;
  732. health.reset();
  733. }
  734. }
  735. else
  736. {
  737. health.damage(amount);
  738. }
  739. bool disintegrate = hasBonusOfType(BonusType::DISINTEGRATE);
  740. if(health.available() <= 0 && (cloned || summoned || disintegrate))
  741. ghostPending = true;
  742. }
  743. HealInfo CUnitState::heal(int64_t & amount, EHealLevel level, EHealPower power)
  744. {
  745. if(level == EHealLevel::HEAL && power == EHealPower::ONE_BATTLE)
  746. logGlobal->error("Heal for one battle does not make sense");
  747. else if(cloned)
  748. logGlobal->error("Attempt to heal clone");
  749. else
  750. return health.heal(amount, level, power);
  751. return {};
  752. }
  753. void CUnitState::afterAttack(bool ranged, bool counter)
  754. {
  755. if(counter)
  756. counterAttacks.use();
  757. if(ranged)
  758. shots.use();
  759. }
  760. void CUnitState::afterNewRound()
  761. {
  762. defending = false;
  763. waiting = false;
  764. waitedThisTurn = false;
  765. movedThisRound = false;
  766. hadMorale = false;
  767. castSpellThisTurn = false;
  768. fear = false;
  769. drainedMana = false;
  770. counterAttacks.reset();
  771. if(alive() && isClone() && !bonusCache.hasBonus(UnitBonusValuesProxy::CLONE_MARKER))
  772. makeGhost();
  773. }
  774. void CUnitState::afterGetsTurn(BattleUnitTurnReason reason)
  775. {
  776. if(reason == BattleUnitTurnReason::MORALE)
  777. {
  778. hadMorale = true;
  779. castSpellThisTurn = false;
  780. movedThisRound = false;
  781. }
  782. }
  783. void CUnitState::makeGhost()
  784. {
  785. health.reset();
  786. ghostPending = true;
  787. }
  788. void CUnitState::onRemoved()
  789. {
  790. health.reset();
  791. ghostPending = false;
  792. ghost = true;
  793. }
  794. CUnitStateDetached::CUnitStateDetached(const IUnitInfo * unit_, const IBonusBearer * bonus_):
  795. unit(unit_),
  796. bonus(bonus_)
  797. {
  798. }
  799. TConstBonusListPtr CUnitStateDetached::getAllBonuses(const CSelector & selector, const std::string & cachingStr) const
  800. {
  801. return bonus->getAllBonuses(selector, cachingStr);
  802. }
  803. int32_t CUnitStateDetached::getTreeVersion() const
  804. {
  805. return bonus->getTreeVersion();
  806. }
  807. CUnitStateDetached & CUnitStateDetached::operator=(const CUnitState & other)
  808. {
  809. CUnitState::operator=(other);
  810. return *this;
  811. }
  812. uint32_t CUnitStateDetached::unitId() const
  813. {
  814. return unit->unitId();
  815. }
  816. BattleSide CUnitStateDetached::unitSide() const
  817. {
  818. return unit->unitSide();
  819. }
  820. const CCreature * CUnitStateDetached::unitType() const
  821. {
  822. return unit->unitType();
  823. }
  824. PlayerColor CUnitStateDetached::unitOwner() const
  825. {
  826. return unit->unitOwner();
  827. }
  828. SlotID CUnitStateDetached::unitSlot() const
  829. {
  830. return unit->unitSlot();
  831. }
  832. int32_t CUnitStateDetached::unitBaseAmount() const
  833. {
  834. return unit->unitBaseAmount();
  835. }
  836. void CUnitStateDetached::spendMana(ServerCallback * server, const int spellCost) const
  837. {
  838. if(spellCost != 1)
  839. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  840. //this is evil, but
  841. //use of netpacks in detached state is an error
  842. //non const API is more evil for hero
  843. const_cast<CUnitStateDetached *>(this)->casts.use(spellCost);
  844. }
  845. }
  846. VCMI_LIB_NAMESPACE_END