CUnitState.cpp 19 KB

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