CUnitState.cpp 21 KB

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