CUnitState.cpp 20 KB

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