CUnitState.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 "../MetaString.h"
  15. #include "../serializer/JsonDeserializer.h"
  16. #include "../serializer/JsonSerializer.h"
  17. VCMI_LIB_NAMESPACE_BEGIN
  18. namespace battle
  19. {
  20. ///CAmmo
  21. CAmmo::CAmmo(const battle::Unit * Owner, CSelector totalSelector):
  22. used(0),
  23. owner(Owner),
  24. totalProxy(Owner, std::move(totalSelector))
  25. {
  26. reset();
  27. }
  28. CAmmo & CAmmo::operator= (const CAmmo & other)
  29. {
  30. used = other.used;
  31. totalProxy = other.totalProxy;
  32. return *this;
  33. }
  34. int32_t CAmmo::available() const
  35. {
  36. return total() - used;
  37. }
  38. bool CAmmo::canUse(int32_t amount) const
  39. {
  40. return !isLimited() || (available() - amount >= 0);
  41. }
  42. bool CAmmo::isLimited() const
  43. {
  44. return true;
  45. }
  46. void CAmmo::reset()
  47. {
  48. used = 0;
  49. }
  50. int32_t CAmmo::total() const
  51. {
  52. return totalProxy->totalValue();
  53. }
  54. void CAmmo::use(int32_t amount)
  55. {
  56. if(!isLimited())
  57. return;
  58. if(available() - amount < 0)
  59. {
  60. logGlobal->error("Stack ammo overuse. total: %d, used: %d, requested: %d", total(), used, amount);
  61. used += available();
  62. }
  63. else
  64. used += amount;
  65. }
  66. void CAmmo::serializeJson(JsonSerializeFormat & handler)
  67. {
  68. handler.serializeInt("used", used, 0);
  69. }
  70. ///CShots
  71. CShots::CShots(const battle::Unit * Owner)
  72. : CAmmo(Owner, Selector::type()(BonusType::SHOTS)),
  73. shooter(Owner, Selector::type()(BonusType::SHOOTER))
  74. {
  75. }
  76. CShots & CShots::operator=(const CShots & other)
  77. {
  78. CAmmo::operator=(other);
  79. shooter = other.shooter;
  80. return *this;
  81. }
  82. bool CShots::isLimited() const
  83. {
  84. return !env->unitHasAmmoCart(owner) || !shooter.getHasBonus();
  85. }
  86. void CShots::setEnv(const IUnitEnvironment * env_)
  87. {
  88. env = env_;
  89. }
  90. int32_t CShots::total() const
  91. {
  92. if(shooter.getHasBonus())
  93. return CAmmo::total();
  94. else
  95. return 0;
  96. }
  97. ///CCasts
  98. CCasts::CCasts(const battle::Unit * Owner):
  99. CAmmo(Owner, Selector::type()(BonusType::CASTS))
  100. {
  101. }
  102. ///CRetaliations
  103. CRetaliations::CRetaliations(const battle::Unit * Owner)
  104. : CAmmo(Owner, Selector::type()(BonusType::ADDITIONAL_RETALIATION)),
  105. totalCache(0),
  106. noRetaliation(Owner, Selector::type()(BonusType::SIEGE_WEAPON).Or(Selector::type()(BonusType::HYPNOTIZED)).Or(Selector::type()(BonusType::NO_RETALIATION))),
  107. unlimited(Owner, Selector::type()(BonusType::UNLIMITED_RETALIATIONS))
  108. {
  109. }
  110. bool CRetaliations::isLimited() const
  111. {
  112. return !unlimited.getHasBonus() || noRetaliation.getHasBonus();
  113. }
  114. int32_t CRetaliations::total() const
  115. {
  116. if(noRetaliation.getHasBonus())
  117. return 0;
  118. //after dispell bonus should remain during current round
  119. int32_t val = 1 + totalProxy->totalValue();
  120. vstd::amax(totalCache, val);
  121. return totalCache;
  122. }
  123. void CRetaliations::reset()
  124. {
  125. CAmmo::reset();
  126. totalCache = 0;
  127. }
  128. void CRetaliations::serializeJson(JsonSerializeFormat & handler)
  129. {
  130. CAmmo::serializeJson(handler);
  131. //we may be serialized in the middle of turn
  132. handler.serializeInt("totalCache", totalCache, 0);
  133. }
  134. ///CHealth
  135. CHealth::CHealth(const battle::Unit * Owner):
  136. owner(Owner)
  137. {
  138. reset();
  139. }
  140. CHealth & CHealth::operator=(const CHealth & other)
  141. {
  142. //do not change owner
  143. firstHPleft = other.firstHPleft;
  144. fullUnits = other.fullUnits;
  145. resurrected = other.resurrected;
  146. return *this;
  147. }
  148. void CHealth::init()
  149. {
  150. reset();
  151. fullUnits = owner->unitBaseAmount() > 1 ? owner->unitBaseAmount() - 1 : 0;
  152. firstHPleft = owner->unitBaseAmount() > 0 ? owner->getMaxHealth() : 0;
  153. }
  154. void CHealth::addResurrected(int32_t amount)
  155. {
  156. resurrected += amount;
  157. vstd::amax(resurrected, 0);
  158. }
  159. int64_t CHealth::available() const
  160. {
  161. return static_cast<int64_t>(firstHPleft) + owner->getMaxHealth() * fullUnits;
  162. }
  163. int64_t CHealth::total() const
  164. {
  165. return static_cast<int64_t>(owner->getMaxHealth()) * owner->unitBaseAmount();
  166. }
  167. void CHealth::damage(int64_t & amount)
  168. {
  169. const int32_t oldCount = getCount();
  170. const bool withKills = amount >= firstHPleft;
  171. if(withKills)
  172. {
  173. int64_t totalHealth = available();
  174. if(amount > totalHealth)
  175. amount = totalHealth;
  176. totalHealth -= amount;
  177. if(totalHealth <= 0)
  178. {
  179. fullUnits = 0;
  180. firstHPleft = 0;
  181. }
  182. else
  183. {
  184. setFromTotal(totalHealth);
  185. }
  186. }
  187. else
  188. {
  189. firstHPleft -= static_cast<int32_t>(amount);
  190. }
  191. addResurrected(getCount() - oldCount);
  192. }
  193. void CHealth::heal(int64_t & amount, EHealLevel level, EHealPower power)
  194. {
  195. const int32_t unitHealth = owner->getMaxHealth();
  196. const int32_t oldCount = getCount();
  197. int64_t maxHeal = std::numeric_limits<int64_t>::max();
  198. switch(level)
  199. {
  200. case EHealLevel::HEAL:
  201. maxHeal = std::max(0, unitHealth - firstHPleft);
  202. break;
  203. case EHealLevel::RESURRECT:
  204. maxHeal = total() - available();
  205. break;
  206. default:
  207. assert(level == EHealLevel::OVERHEAL);
  208. break;
  209. }
  210. vstd::amax(maxHeal, 0);
  211. vstd::abetween(amount, int64_t(0), maxHeal);
  212. if(amount == 0)
  213. return;
  214. int64_t availableHealth = available();
  215. availableHealth += amount;
  216. setFromTotal(availableHealth);
  217. if(power == EHealPower::ONE_BATTLE)
  218. addResurrected(getCount() - oldCount);
  219. else
  220. assert(power == EHealPower::PERMANENT);
  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. void 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. health.heal(amount, level, power);
  710. }
  711. void CUnitState::afterAttack(bool ranged, bool counter)
  712. {
  713. if(counter)
  714. counterAttacks.use();
  715. if(ranged)
  716. shots.use();
  717. }
  718. void CUnitState::afterNewRound()
  719. {
  720. defending = false;
  721. waiting = false;
  722. waitedThisTurn = false;
  723. movedThisRound = false;
  724. hadMorale = false;
  725. fear = false;
  726. drainedMana = false;
  727. counterAttacks.reset();
  728. if(alive() && isClone())
  729. {
  730. if(!cloneLifetimeMarker.getHasBonus())
  731. makeGhost();
  732. }
  733. }
  734. void CUnitState::afterGetsTurn()
  735. {
  736. //if moving second time this round it must be high morale bonus
  737. if(movedThisRound)
  738. hadMorale = true;
  739. }
  740. void CUnitState::makeGhost()
  741. {
  742. health.reset();
  743. ghostPending = true;
  744. }
  745. void CUnitState::onRemoved()
  746. {
  747. health.reset();
  748. ghostPending = false;
  749. ghost = true;
  750. }
  751. CUnitStateDetached::CUnitStateDetached(const IUnitInfo * unit_, const IBonusBearer * bonus_):
  752. unit(unit_),
  753. bonus(bonus_)
  754. {
  755. }
  756. TConstBonusListPtr CUnitStateDetached::getAllBonuses(const CSelector & selector, const CSelector & limit, const CBonusSystemNode * root, const std::string & cachingStr) const
  757. {
  758. return bonus->getAllBonuses(selector, limit, root, cachingStr);
  759. }
  760. int64_t CUnitStateDetached::getTreeVersion() const
  761. {
  762. return bonus->getTreeVersion();
  763. }
  764. CUnitStateDetached & CUnitStateDetached::operator=(const CUnitState & other)
  765. {
  766. CUnitState::operator=(other);
  767. return *this;
  768. }
  769. uint32_t CUnitStateDetached::unitId() const
  770. {
  771. return unit->unitId();
  772. }
  773. ui8 CUnitStateDetached::unitSide() const
  774. {
  775. return unit->unitSide();
  776. }
  777. const CCreature * CUnitStateDetached::unitType() const
  778. {
  779. return unit->unitType();
  780. }
  781. PlayerColor CUnitStateDetached::unitOwner() const
  782. {
  783. return unit->unitOwner();
  784. }
  785. SlotID CUnitStateDetached::unitSlot() const
  786. {
  787. return unit->unitSlot();
  788. }
  789. int32_t CUnitStateDetached::unitBaseAmount() const
  790. {
  791. return unit->unitBaseAmount();
  792. }
  793. void CUnitStateDetached::spendMana(ServerCallback * server, const int spellCost) const
  794. {
  795. if(spellCost != 1)
  796. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  797. //this is evil, but
  798. //use of netpacks in detached state is an error
  799. //non const API is more evil for hero
  800. const_cast<CUnitStateDetached *>(this)->casts.use(spellCost);
  801. }
  802. }
  803. VCMI_LIB_NAMESPACE_END