CStack.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /*
  2. * CStack.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 "CStack.h"
  12. #include <vstd/RNG.h>
  13. #include <vcmi/Entity.h>
  14. #include <vcmi/ServerCallback.h>
  15. #include "texts/CGeneralTextHandler.h"
  16. #include "battle/BattleInfo.h"
  17. #include "GameLibrary.h"
  18. #include "spells/CSpellHandler.h"
  19. #include "networkPacks/PacksForClientBattle.h"
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. ///CStack
  22. CStack::CStack(const CStackInstance * Base, const PlayerColor & O, int I, BattleSide Side, const SlotID & S):
  23. CBonusSystemNode(BonusNodeType::STACK_BATTLE),
  24. base(Base),
  25. ID(I),
  26. typeID(Base->getId()),
  27. baseAmount(Base->getCount()),
  28. owner(O),
  29. slot(S),
  30. side(Side)
  31. {
  32. health.init(); //???
  33. doubleWideCached = battle::CUnitState::doubleWide();
  34. }
  35. CStack::CStack():
  36. CBonusSystemNode(BonusNodeType::STACK_BATTLE),
  37. owner(PlayerColor::NEUTRAL),
  38. slot(SlotID(255)),
  39. initialPosition(BattleHex())
  40. {
  41. }
  42. CStack::CStack(const CStackBasicDescriptor * stack, const PlayerColor & O, int I, BattleSide Side, const SlotID & S):
  43. CBonusSystemNode(BonusNodeType::STACK_BATTLE),
  44. ID(I),
  45. typeID(stack->getId()),
  46. baseAmount(stack->getCount()),
  47. owner(O),
  48. slot(S),
  49. side(Side)
  50. {
  51. health.init(); //???
  52. doubleWideCached = battle::CUnitState::doubleWide();
  53. }
  54. void CStack::localInit(BattleInfo * battleInfo)
  55. {
  56. battle = battleInfo;
  57. assert(typeID.hasValue());
  58. exportBonuses();
  59. if(base) //stack originating from "real" stack in garrison -> attach to it
  60. {
  61. attachTo(const_cast<CStackInstance&>(*base));
  62. }
  63. else //attach directly to obj to which stack belongs and creature type
  64. {
  65. CArmedInstance * army = battle->battleGetArmyObject(side);
  66. assert(army);
  67. attachTo(*army);
  68. attachToSource(*typeID.toCreature());
  69. }
  70. CUnitState::localInit(this); //it causes execution of the CStack::isOnNativeTerrain where nativeTerrain will be considered
  71. position = initialPosition;
  72. }
  73. ui32 CStack::level() const
  74. {
  75. if(base)
  76. return base->getLevel(); //creature or commander
  77. else
  78. return std::max(1, static_cast<int>(unitType()->getLevel())); //war machine, clone etc
  79. }
  80. si32 CStack::magicResistance() const
  81. {
  82. auto magicResistance = AFactionMember::magicResistance();
  83. si32 auraBonus = 0;
  84. for(const auto * one : battle->battleAdjacentUnits(this))
  85. {
  86. if(one->unitOwner() == owner)
  87. vstd::amax(auraBonus, one->valOfBonuses(BonusType::SPELL_RESISTANCE_AURA)); //max value
  88. }
  89. vstd::abetween(auraBonus, 0, 100);
  90. vstd::abetween(magicResistance, 0, 100);
  91. float castChance = (100 - magicResistance) * (100 - auraBonus)/100.0;
  92. return static_cast<si32>(100 - castChance);
  93. }
  94. std::vector<SpellID> CStack::activeSpells() const
  95. {
  96. std::vector<SpellID> ret;
  97. std::stringstream cachingStr;
  98. cachingStr << "!type_" << vstd::to_underlying(BonusType::NONE) << "source_" << vstd::to_underlying(BonusSource::SPELL_EFFECT);
  99. CSelector selector = Selector::sourceType()(BonusSource::SPELL_EFFECT)
  100. .And(CSelector([](const Bonus * b)->bool
  101. {
  102. return b->type != BonusType::NONE && b->sid.as<SpellID>().toSpell() && !b->sid.as<SpellID>().toSpell()->isAdventure();
  103. }));
  104. TConstBonusListPtr spellEffects = getBonuses(selector, cachingStr.str());
  105. for(const auto & it : *spellEffects)
  106. {
  107. if(!vstd::contains(ret, it->sid.as<SpellID>())) //do not duplicate spells with multiple effects
  108. ret.push_back(it->sid.as<SpellID>());
  109. }
  110. return ret;
  111. }
  112. CStack::~CStack()
  113. {
  114. detachFromAll();
  115. }
  116. const CGHeroInstance * CStack::getMyHero() const
  117. {
  118. if(base)
  119. return dynamic_cast<const CGHeroInstance *>(base->getArmy());
  120. else //we are attached directly?
  121. for(const CBonusSystemNode * n : getParentNodes())
  122. if(n->getNodeType() == BonusNodeType::HERO)
  123. return dynamic_cast<const CGHeroInstance *>(n);
  124. return nullptr;
  125. }
  126. std::string CStack::nodeName() const
  127. {
  128. std::ostringstream oss;
  129. oss << owner.toString();
  130. oss << " battle stack [" << ID << "]: " << getCount() << " of ";
  131. if(typeID.hasValue())
  132. oss << typeID.toEntity(LIBRARY)->getJsonKey();
  133. else
  134. oss << "[UNDEFINED TYPE]";
  135. oss << " from slot " << slot;
  136. if(base && base->getArmy())
  137. oss << " of armyobj=" << base->getArmy()->id.getNum();
  138. return oss.str();
  139. }
  140. void CStack::prepareAttacked(BattleStackAttacked & bsa, vstd::RNG & rand) const
  141. {
  142. auto newState = acquireState();
  143. prepareAttacked(bsa, rand, newState);
  144. }
  145. void CStack::prepareAttacked(BattleStackAttacked & bsa, vstd::RNG & rand, const std::shared_ptr<battle::CUnitState> & customState)
  146. {
  147. auto initialCount = customState->getCount();
  148. // compute damage and update bsa.damageAmount
  149. customState->damage(bsa.damageAmount);
  150. bsa.killedAmount = initialCount - customState->getCount();
  151. if(!customState->alive() && customState->isClone())
  152. {
  153. bsa.flags |= BattleStackAttacked::CLONE_KILLED;
  154. }
  155. else if(!customState->alive()) //stack killed
  156. {
  157. bsa.flags |= BattleStackAttacked::KILLED;
  158. auto resurrectValue = customState->valOfBonuses(BonusType::REBIRTH);
  159. if(resurrectValue > 0 && customState->canCast()) //there must be casts left
  160. {
  161. double resurrectFactor = resurrectValue / 100.0;
  162. auto baseAmount = customState->unitBaseAmount();
  163. double resurrectedRaw = baseAmount * resurrectFactor;
  164. auto resurrectedCount = static_cast<int32_t>(floor(resurrectedRaw));
  165. auto resurrectedAdd = static_cast<int32_t>(baseAmount - (resurrectedCount / resurrectFactor));
  166. for(int32_t i = 0; i < resurrectedAdd; i++)
  167. {
  168. if(resurrectValue > rand.nextInt(0, 99))
  169. resurrectedCount += 1;
  170. }
  171. if(customState->hasBonusOfType(BonusType::REBIRTH, BonusCustomSubtype::rebirthSpecial))
  172. {
  173. // resurrect at least one Sacred Phoenix
  174. vstd::amax(resurrectedCount, 1);
  175. }
  176. if(resurrectedCount > 0)
  177. {
  178. customState->casts.use();
  179. bsa.flags |= BattleStackAttacked::REBIRTH;
  180. int64_t toHeal = customState->getMaxHealth() * resurrectedCount;
  181. //TODO: add one-battle rebirth?
  182. customState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  183. customState->counterAttacks.use(customState->counterAttacks.available());
  184. }
  185. }
  186. }
  187. customState->save(bsa.newState.data);
  188. bsa.newState.healthDelta = -bsa.damageAmount;
  189. bsa.newState.id = customState->unitId();
  190. bsa.newState.operation = UnitChanges::EOperation::RESET_STATE;
  191. }
  192. BattleHexArray CStack::meleeAttackHexes(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPos, BattleHex defenderPos)
  193. {
  194. BattleHexArray res;
  195. if (!attackerPos.isValid())
  196. attackerPos = attacker->getPosition();
  197. if (!defenderPos.isValid())
  198. defenderPos = defender->getPosition();
  199. BattleHexArray defenderHexes = defender->getHexes(defenderPos);
  200. BattleHexArray attackerHexes = attacker->getHexes(attackerPos);
  201. for (BattleHex defenderHex : defenderHexes)
  202. {
  203. if (attackerHexes.contains(defenderHex))
  204. {
  205. logGlobal->debug("CStack::meleeAttackHexes: defender and attacker positions overlap");
  206. return res;
  207. }
  208. }
  209. const BattleHexArray attackableHxs = attacker->getSurroundingHexes(attackerPos);
  210. for (BattleHex defenderHex : defenderHexes)
  211. {
  212. if (attackableHxs.contains(defenderHex))
  213. res.insert(defenderHex);
  214. }
  215. return res;
  216. }
  217. bool CStack::isMeleeAttackPossible(const battle::Unit * attacker, const battle::Unit * defender, BattleHex attackerPos, BattleHex defenderPos)
  218. {
  219. if(defender->isInvincible())
  220. return false;
  221. return !meleeAttackHexes(attacker, defender, attackerPos, defenderPos).empty();
  222. }
  223. std::string CStack::getName() const
  224. {
  225. return (getCount() == 1) ? typeID.toEntity(LIBRARY)->getNameSingularTranslated() : typeID.toEntity(LIBRARY)->getNamePluralTranslated(); //War machines can't use base
  226. }
  227. bool CStack::canBeHealed() const
  228. {
  229. return getFirstHPleft() < static_cast<int32_t>(getMaxHealth()) && isValidTarget() && !hasBonusOfType(BonusType::SIEGE_WEAPON);
  230. }
  231. bool CStack::isOnNativeTerrain() const
  232. {
  233. auto nativeTerrain = getNativeTerrain();
  234. return nativeTerrain == ETerrainId::ANY_TERRAIN || getCurrentTerrain() == nativeTerrain;
  235. }
  236. TerrainId CStack::getCurrentTerrain() const
  237. {
  238. return battle->getTerrainType();
  239. }
  240. const CCreature * CStack::unitType() const
  241. {
  242. return typeID.toCreature();
  243. }
  244. int32_t CStack::unitBaseAmount() const
  245. {
  246. return baseAmount;
  247. }
  248. const IBonusBearer* CStack::getBonusBearer() const
  249. {
  250. return this;
  251. }
  252. bool CStack::unitHasAmmoCart(const battle::Unit * unit) const
  253. {
  254. for(const auto & st : battle->stacks)
  255. {
  256. if(battle->battleMatchOwner(st.get(), unit, true) && st->unitType()->getId() == CreatureID::AMMO_CART)
  257. {
  258. return st->alive();
  259. }
  260. }
  261. //ammo cart works during creature bank battle while not on battlefield
  262. const auto * ownerHero = battle->battleGetOwnerHero(unit);
  263. if(ownerHero && ownerHero->artifactsWorn.find(ArtifactPosition::MACH2) != ownerHero->artifactsWorn.end())
  264. {
  265. if(battle->battleGetOwnerHero(unit)->artifactsWorn.at(ArtifactPosition::MACH2).getArt()->getTypeId() == ArtifactID::AMMO_CART)
  266. {
  267. return true;
  268. }
  269. }
  270. return false; //will be always false if trying to examine enemy hero in "special battle"
  271. }
  272. PlayerColor CStack::unitEffectiveOwner(const battle::Unit * unit) const
  273. {
  274. return battle->battleGetOwner(unit);
  275. }
  276. uint32_t CStack::unitId() const
  277. {
  278. return ID;
  279. }
  280. BattleSide CStack::unitSide() const
  281. {
  282. return side;
  283. }
  284. PlayerColor CStack::unitOwner() const
  285. {
  286. return owner;
  287. }
  288. SlotID CStack::unitSlot() const
  289. {
  290. return slot;
  291. }
  292. std::string CStack::getDescription() const
  293. {
  294. return nodeName();
  295. }
  296. void CStack::spendMana(ServerCallback * server, const int spellCost) const
  297. {
  298. if(spellCost != 1)
  299. logGlobal->warn("Unexpected spell cost %d for creature", spellCost);
  300. BattleSetStackProperty ssp;
  301. ssp.battleID = battle->battleID;
  302. ssp.stackID = unitId();
  303. ssp.which = BattleSetStackProperty::CASTS;
  304. ssp.val = -spellCost;
  305. ssp.absolute = false;
  306. server->apply(ssp);
  307. }
  308. void CStack::postDeserialize(const CArmedInstance * army)
  309. {
  310. if(slot == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  311. {
  312. const auto * hero = dynamic_cast<const CGHeroInstance *>(army);
  313. assert(hero);
  314. base = hero->getCommander();
  315. }
  316. else if(slot == SlotID::SUMMONED_SLOT_PLACEHOLDER || slot == SlotID::ARROW_TOWERS_SLOT || slot == SlotID::WAR_MACHINES_SLOT)
  317. {
  318. //no external slot possible, so no base stack
  319. base = nullptr;
  320. }
  321. else if(!army || slot == SlotID() || !army->hasStackAtSlot(slot))
  322. {
  323. throw std::runtime_error(typeID.toEntity(LIBRARY)->getNameSingularTranslated() + " doesn't have a base stack!");
  324. }
  325. else
  326. {
  327. base = &army->getStack(slot);
  328. }
  329. doubleWideCached = battle::CUnitState::doubleWide();
  330. }
  331. VCMI_LIB_NAMESPACE_END