CUnitState.cpp 23 KB

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