CUnitState.cpp 21 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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::HYPNOTIZED)).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. health = other.health;
  305. cloneID = other.cloneID;
  306. position = other.position;
  307. return *this;
  308. }
  309. int32_t CUnitState::creatureIndex() const
  310. {
  311. return static_cast<int32_t>(creatureId().toEnum());
  312. }
  313. CreatureID CUnitState::creatureId() const
  314. {
  315. return unitType()->getId();
  316. }
  317. int32_t CUnitState::creatureLevel() const
  318. {
  319. return static_cast<int32_t>(unitType()->getLevel());
  320. }
  321. bool CUnitState::doubleWide() const
  322. {
  323. return unitType()->isDoubleWide();
  324. }
  325. int32_t CUnitState::creatureCost() const
  326. {
  327. return unitType()->getRecruitCost(EGameResID::GOLD);
  328. }
  329. int32_t CUnitState::creatureIconIndex() const
  330. {
  331. return unitType()->getIconIndex();
  332. }
  333. FactionID CUnitState::getFactionID() const
  334. {
  335. return unitType()->getFactionID();
  336. }
  337. int32_t CUnitState::getCasterUnitId() const
  338. {
  339. return static_cast<int32_t>(unitId());
  340. }
  341. const CGHeroInstance * CUnitState::getHeroCaster() const
  342. {
  343. return nullptr;
  344. }
  345. int32_t CUnitState::getSpellSchoolLevel(const spells::Spell * spell, SpellSchool * outSelectedSchool) const
  346. {
  347. int32_t skill = valOfBonuses(Selector::typeSubtype(BonusType::SPELLCASTER, BonusSubtypeID(spell->getId())));
  348. vstd::abetween(skill, 0, 3);
  349. return skill;
  350. }
  351. int64_t CUnitState::getSpellBonus(const spells::Spell * spell, int64_t base, const Unit * affectedStack) const
  352. {
  353. //does not have sorcery-like bonuses (yet?)
  354. return base;
  355. }
  356. int64_t CUnitState::getSpecificSpellBonus(const spells::Spell * spell, int64_t base) const
  357. {
  358. return base;
  359. }
  360. int32_t CUnitState::getEffectLevel(const spells::Spell * spell) const
  361. {
  362. return getSpellSchoolLevel(spell);
  363. }
  364. int32_t CUnitState::getEffectPower(const spells::Spell * spell) const
  365. {
  366. return valOfBonuses(BonusType::CREATURE_SPELL_POWER) * getCount() / 100;
  367. }
  368. int32_t CUnitState::getEnchantPower(const spells::Spell * spell) const
  369. {
  370. int32_t res = valOfBonuses(BonusType::CREATURE_ENCHANT_POWER);
  371. if(res <= 0)
  372. res = 3;//default for creatures
  373. return res;
  374. }
  375. int64_t CUnitState::getEffectValue(const spells::Spell * spell) const
  376. {
  377. return static_cast<int64_t>(getCount()) * valOfBonuses(BonusType::SPECIFIC_SPELL_POWER, BonusSubtypeID(spell->getId()));
  378. }
  379. PlayerColor CUnitState::getCasterOwner() const
  380. {
  381. return env->unitEffectiveOwner(this);
  382. }
  383. void CUnitState::getCasterName(MetaString & text) const
  384. {
  385. //always plural name in case of spell cast.
  386. addNameReplacement(text, true);
  387. }
  388. void CUnitState::getCastDescription(const spells::Spell * spell, const std::vector<const Unit *> & attacked, MetaString & text) const
  389. {
  390. text.appendLocalString(EMetaText::GENERAL_TXT, 565);//The %s casts %s
  391. //todo: use text 566 for single creature
  392. getCasterName(text);
  393. text.replaceName(spell->getId());
  394. }
  395. int32_t CUnitState::manaLimit() const
  396. {
  397. return 0; //TODO: creature casting with mana mode (for mods)
  398. }
  399. bool CUnitState::ableToRetaliate() const
  400. {
  401. return alive()
  402. && counterAttacks.canUse();
  403. }
  404. bool CUnitState::alive() const
  405. {
  406. return health.getCount() > 0;
  407. }
  408. bool CUnitState::isGhost() const
  409. {
  410. return ghost;
  411. }
  412. bool CUnitState::isFrozen() const
  413. {
  414. return hasBonus(Selector::source(BonusSource::SPELL_EFFECT, BonusSourceID(SpellID(SpellID::STONE_GAZE))), Selector::all);
  415. }
  416. bool CUnitState::isValidTarget(bool allowDead) const
  417. {
  418. return (alive() || (allowDead && isDead())) && getPosition().isValid() && !isTurret();
  419. }
  420. bool CUnitState::isClone() const
  421. {
  422. return cloned;
  423. }
  424. bool CUnitState::hasClone() const
  425. {
  426. return cloneID > 0;
  427. }
  428. bool CUnitState::canCast() const
  429. {
  430. return casts.canUse(1) && !castSpellThisTurn;//do not check specific cast abilities here
  431. }
  432. bool CUnitState::isCaster() const
  433. {
  434. return casts.total() > 0;//do not check specific cast abilities here
  435. }
  436. bool CUnitState::canShootBlocked() const
  437. {
  438. return bonusCache.getBonusValue(UnitBonusValuesProxy::HAS_FREE_SHOOTING);
  439. }
  440. bool CUnitState::canShoot() const
  441. {
  442. return
  443. shots.canUse(1) &&
  444. bonusCache.getBonusValue(UnitBonusValuesProxy::FORGETFULL) <= 1; //advanced+ level
  445. }
  446. bool CUnitState::isShooter() const
  447. {
  448. return shots.total() > 0;
  449. }
  450. int32_t CUnitState::getKilled() const
  451. {
  452. int32_t res = unitBaseAmount() - health.getCount() + health.getResurrected();
  453. vstd::amax(res, 0);
  454. return res;
  455. }
  456. int32_t CUnitState::getCount() const
  457. {
  458. return health.getCount();
  459. }
  460. int32_t CUnitState::getFirstHPleft() const
  461. {
  462. return health.getFirstHPleft();
  463. }
  464. int64_t CUnitState::getAvailableHealth() const
  465. {
  466. return health.available();
  467. }
  468. int64_t CUnitState::getTotalHealth() const
  469. {
  470. return health.total();
  471. }
  472. uint32_t CUnitState::getMaxHealth() const
  473. {
  474. return std::max(1, bonusCache.getBonusValue(UnitBonusValuesProxy::STACK_HEALTH));
  475. }
  476. BattleHex CUnitState::getPosition() const
  477. {
  478. return position;
  479. }
  480. void CUnitState::setPosition(BattleHex hex)
  481. {
  482. position = hex;
  483. }
  484. int32_t CUnitState::getInitiative(int turn) const
  485. {
  486. return stackSpeedPerTurn.getValue(turn);
  487. }
  488. ui32 CUnitState::getMovementRange(int turn) const
  489. {
  490. if (immobilizedPerTurn.getValue(0) != 0)
  491. return 0;
  492. return stackSpeedPerTurn.getValue(0);
  493. }
  494. ui32 CUnitState::getMovementRange() const
  495. {
  496. return getMovementRange(0);
  497. }
  498. uint8_t CUnitState::getRangedFullDamageDistance() const
  499. {
  500. if(!isShooter())
  501. return 0;
  502. uint8_t rangedFullDamageDistance = GameConstants::BATTLE_SHOOTING_PENALTY_DISTANCE;
  503. // overwrite full ranged damage distance with the value set in Additional info field of LIMITED_SHOOTING_RANGE bonus
  504. if(hasBonusOfType(BonusType::LIMITED_SHOOTING_RANGE))
  505. {
  506. auto bonus = this->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  507. if(bonus != nullptr && bonus->additionalInfo != CAddInfo::NONE)
  508. rangedFullDamageDistance = bonus->additionalInfo[0];
  509. }
  510. return rangedFullDamageDistance;
  511. }
  512. uint8_t CUnitState::getShootingRangeDistance() const
  513. {
  514. if(!isShooter())
  515. return 0;
  516. uint8_t shootingRangeDistance = GameConstants::BATTLE_SHOOTING_RANGE_DISTANCE;
  517. // overwrite full ranged damage distance with the value set in Additional info field of LIMITED_SHOOTING_RANGE bonus
  518. if(hasBonusOfType(BonusType::LIMITED_SHOOTING_RANGE))
  519. {
  520. auto bonus = this->getBonus(Selector::type()(BonusType::LIMITED_SHOOTING_RANGE));
  521. if(bonus != nullptr)
  522. shootingRangeDistance = bonus->val;
  523. }
  524. return shootingRangeDistance;
  525. }
  526. bool CUnitState::canMove(int turn) const
  527. {
  528. if (!alive())
  529. return false;
  530. if (turn == 0)
  531. return !hasBonusOfType(BonusType::NOT_ACTIVE);
  532. std::string cachingStr = "type_NOT_ACTIVE_turns_" + std::to_string(turn);
  533. return !hasBonus(Selector::type()(BonusType::NOT_ACTIVE).And(Selector::turns(turn)), cachingStr); //eg. Ammo Cart or blinded creature
  534. }
  535. bool CUnitState::defended(int turn) const
  536. {
  537. return !turn && defending;
  538. }
  539. bool CUnitState::moved(int turn) const
  540. {
  541. if(!turn && !waiting)
  542. return movedThisRound;
  543. else
  544. return false;
  545. }
  546. bool CUnitState::willMove(int turn) const
  547. {
  548. return (turn ? true : !defending)
  549. && !moved(turn)
  550. && canMove(turn);
  551. }
  552. bool CUnitState::waited(int turn) const
  553. {
  554. if(!turn)
  555. return waiting;
  556. else
  557. return false;
  558. }
  559. BattlePhases::Type CUnitState::battleQueuePhase(int turn) const
  560. {
  561. if(turn <= 0 && waited()) //consider waiting state only for ongoing round
  562. {
  563. if(hadMorale)
  564. return BattlePhases::WAIT_MORALE;
  565. else
  566. return BattlePhases::WAIT;
  567. }
  568. else if(creatureIndex() == CreatureID::CATAPULT || isTurret()) //catapult and turrets are first
  569. {
  570. return BattlePhases::SIEGE;
  571. }
  572. else
  573. {
  574. return BattlePhases::NORMAL;
  575. }
  576. }
  577. bool CUnitState::isHypnotized() const
  578. {
  579. return bonusCache.getBonusValue(UnitBonusValuesProxy::HYPNOTIZED);
  580. }
  581. int CUnitState::getTotalAttacks(bool ranged) const
  582. {
  583. return 1 + (ranged ?
  584. bonusCache.getBonusValue(UnitBonusValuesProxy::TOTAL_ATTACKS_RANGED):
  585. bonusCache.getBonusValue(UnitBonusValuesProxy::TOTAL_ATTACKS_MELEE));
  586. }
  587. int CUnitState::getMinDamage(bool ranged) const
  588. {
  589. return ranged ?
  590. bonusCache.getBonusValue(UnitBonusValuesProxy::MIN_DAMAGE_RANGED):
  591. bonusCache.getBonusValue(UnitBonusValuesProxy::MIN_DAMAGE_MELEE);
  592. }
  593. int CUnitState::getMaxDamage(bool ranged) const
  594. {
  595. return ranged ?
  596. bonusCache.getBonusValue(UnitBonusValuesProxy::MAX_DAMAGE_RANGED):
  597. bonusCache.getBonusValue(UnitBonusValuesProxy::MAX_DAMAGE_MELEE);
  598. }
  599. int CUnitState::getAttack(bool ranged) const
  600. {
  601. int attack = ranged ?
  602. bonusCache.getBonusValue(UnitBonusValuesProxy::ATTACK_RANGED):
  603. bonusCache.getBonusValue(UnitBonusValuesProxy::ATTACK_MELEE);
  604. int frenzy = bonusCache.getBonusValue(UnitBonusValuesProxy::IN_FRENZY);
  605. if(frenzy != 0)
  606. {
  607. int defence = ranged ?
  608. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_RANGED):
  609. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_MELEE);
  610. int frenzyBonus = frenzy * defence / 100;
  611. attack += frenzyBonus;
  612. }
  613. vstd::amax(attack, 0);
  614. return attack;
  615. }
  616. int CUnitState::getDefense(bool ranged) const
  617. {
  618. int frenzy = bonusCache.getBonusValue(UnitBonusValuesProxy::IN_FRENZY);
  619. if(frenzy != 0)
  620. {
  621. return 0;
  622. }
  623. else
  624. {
  625. int defence = ranged ?
  626. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_RANGED):
  627. bonusCache.getBonusValue(UnitBonusValuesProxy::DEFENCE_MELEE);
  628. vstd::amax(defence, 0);
  629. return defence;
  630. }
  631. }
  632. std::shared_ptr<Unit> CUnitState::acquire() const
  633. {
  634. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  635. ret->localInit(env);
  636. *ret = *this;
  637. return ret;
  638. }
  639. std::shared_ptr<CUnitState> CUnitState::acquireState() const
  640. {
  641. auto ret = std::make_shared<CUnitStateDetached>(this, this);
  642. ret->localInit(env);
  643. *ret = *this;
  644. return ret;
  645. }
  646. void CUnitState::serializeJson(JsonSerializeFormat & handler)
  647. {
  648. handler.serializeBool("cloned", cloned);
  649. handler.serializeBool("defending", defending);
  650. handler.serializeBool("defendingAnim", defendingAnim);
  651. handler.serializeBool("drainedMana", drainedMana);
  652. handler.serializeBool("fear", fear);
  653. handler.serializeBool("hadMorale", hadMorale);
  654. handler.serializeBool("castSpellThisTurn", castSpellThisTurn);
  655. handler.serializeBool("ghost", ghost);
  656. handler.serializeBool("ghostPending", ghostPending);
  657. handler.serializeBool("moved", movedThisRound);
  658. handler.serializeBool("summoned", summoned);
  659. handler.serializeBool("waiting", waiting);
  660. handler.serializeBool("waitedThisTurn", waitedThisTurn);
  661. handler.serializeStruct("casts", casts);
  662. handler.serializeStruct("counterAttacks", counterAttacks);
  663. handler.serializeStruct("health", health);
  664. handler.serializeStruct("shots", shots);
  665. handler.serializeInt("cloneID", cloneID);
  666. si16 posValue = position.toInt();
  667. handler.serializeInt("position", posValue);
  668. position = posValue;
  669. }
  670. void CUnitState::localInit(const IUnitEnvironment * env_)
  671. {
  672. env = env_;
  673. shots.setEnv(env);
  674. reset();
  675. health.init();
  676. }
  677. void CUnitState::reset()
  678. {
  679. cloned = false;
  680. defending = false;
  681. defendingAnim = false;
  682. drainedMana = false;
  683. fear = false;
  684. hadMorale = false;
  685. castSpellThisTurn = false;
  686. ghost = false;
  687. ghostPending = false;
  688. movedThisRound = false;
  689. summoned = false;
  690. waiting = false;
  691. waitedThisTurn = false;
  692. casts.reset();
  693. counterAttacks.reset();
  694. health.reset();
  695. shots.reset();
  696. cloneID = -1;
  697. position = BattleHex::INVALID;
  698. }
  699. void CUnitState::save(JsonNode & data)
  700. {
  701. //TODO: use instance resolver
  702. data.clear();
  703. JsonSerializer ser(nullptr, data);
  704. ser.serializeStruct("state", *this);
  705. }
  706. void CUnitState::load(const JsonNode & data)
  707. {
  708. //TODO: use instance resolver
  709. reset();
  710. JsonDeserializer deser(nullptr, data);
  711. deser.serializeStruct("state", *this);
  712. }
  713. void CUnitState::damage(int64_t & amount)
  714. {
  715. if(cloned)
  716. {
  717. // block ability should not kill clone (0 damage)
  718. if(amount > 0)
  719. {
  720. amount = 0;
  721. health.reset();
  722. }
  723. }
  724. else
  725. {
  726. health.damage(amount);
  727. }
  728. bool disintegrate = hasBonusOfType(BonusType::DISINTEGRATE);
  729. if(health.available() <= 0 && (cloned || summoned || disintegrate))
  730. ghostPending = true;
  731. }
  732. HealInfo CUnitState::heal(int64_t & amount, EHealLevel level, EHealPower power)
  733. {
  734. if(level == EHealLevel::HEAL && power == EHealPower::ONE_BATTLE)
  735. logGlobal->error("Heal for one battle does not make sense");
  736. else if(cloned)
  737. logGlobal->error("Attempt to heal clone");
  738. else
  739. return health.heal(amount, level, power);
  740. return {};
  741. }
  742. void CUnitState::afterAttack(bool ranged, bool counter)
  743. {
  744. if(counter)
  745. counterAttacks.use();
  746. if(ranged)
  747. shots.use();
  748. }
  749. void CUnitState::afterNewRound()
  750. {
  751. defending = false;
  752. waiting = false;
  753. waitedThisTurn = false;
  754. movedThisRound = false;
  755. hadMorale = false;
  756. castSpellThisTurn = false;
  757. fear = false;
  758. drainedMana = false;
  759. counterAttacks.reset();
  760. if(alive() && isClone())
  761. {
  762. if(!bonusCache.hasBonus(UnitBonusValuesProxy::CLONE_MARKER))
  763. makeGhost();
  764. }
  765. }
  766. void CUnitState::afterGetsTurn()
  767. {
  768. //if moving second time this round it must be high morale bonus
  769. if(movedThisRound)
  770. hadMorale = true;
  771. }
  772. void CUnitState::makeGhost()
  773. {
  774. health.reset();
  775. ghostPending = true;
  776. }
  777. void CUnitState::onRemoved()
  778. {
  779. health.reset();
  780. ghostPending = false;
  781. ghost = true;
  782. }
  783. CUnitStateDetached::CUnitStateDetached(const IUnitInfo * unit_, const IBonusBearer * bonus_):
  784. unit(unit_),
  785. bonus(bonus_)
  786. {
  787. }
  788. TConstBonusListPtr CUnitStateDetached::getAllBonuses(const CSelector & selector, const CSelector & limit, const std::string & cachingStr) const
  789. {
  790. return bonus->getAllBonuses(selector, limit, cachingStr);
  791. }
  792. int64_t CUnitStateDetached::getTreeVersion() const
  793. {
  794. return bonus->getTreeVersion();
  795. }
  796. CUnitStateDetached & CUnitStateDetached::operator=(const CUnitState & other)
  797. {
  798. CUnitState::operator=(other);
  799. return *this;
  800. }
  801. uint32_t CUnitStateDetached::unitId() const
  802. {
  803. return unit->unitId();
  804. }
  805. BattleSide CUnitStateDetached::unitSide() const
  806. {
  807. return unit->unitSide();
  808. }
  809. const CCreature * CUnitStateDetached::unitType() const
  810. {
  811. return unit->unitType();
  812. }
  813. PlayerColor CUnitStateDetached::unitOwner() const
  814. {
  815. return unit->unitOwner();
  816. }
  817. SlotID CUnitStateDetached::unitSlot() const
  818. {
  819. return unit->unitSlot();
  820. }
  821. int32_t CUnitStateDetached::unitBaseAmount() const
  822. {
  823. return unit->unitBaseAmount();
  824. }
  825. void CUnitStateDetached::spendMana(ServerCallback * server, const int spellCost) const
  826. {
  827. if(spellCost != 1)
  828. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  829. //this is evil, but
  830. //use of netpacks in detached state is an error
  831. //non const API is more evil for hero
  832. const_cast<CUnitStateDetached *>(this)->casts.use(spellCost);
  833. }
  834. }
  835. VCMI_LIB_NAMESPACE_END