CStack.cpp 9.7 KB

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