CStack.cpp 10 KB

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