CStack.cpp 10 KB

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