CUnitState.cpp 22 KB

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