SpellMechanics.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /*
  2. * SpellMechanics.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 "SpellMechanics.h"
  12. #include "mapObjects/CGHeroInstance.h"
  13. #include "BattleState.h"
  14. #include "CRandomGenerator.h"
  15. #include "NetPacks.h"
  16. namespace SRSLPraserHelpers
  17. {
  18. static int XYToHex(int x, int y)
  19. {
  20. return x + GameConstants::BFIELD_WIDTH * y;
  21. }
  22. static int XYToHex(std::pair<int, int> xy)
  23. {
  24. return XYToHex(xy.first, xy.second);
  25. }
  26. static int hexToY(int battleFieldPosition)
  27. {
  28. return battleFieldPosition/GameConstants::BFIELD_WIDTH;
  29. }
  30. static int hexToX(int battleFieldPosition)
  31. {
  32. int pos = battleFieldPosition - hexToY(battleFieldPosition) * GameConstants::BFIELD_WIDTH;
  33. return pos;
  34. }
  35. static std::pair<int, int> hexToPair(int battleFieldPosition)
  36. {
  37. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  38. }
  39. //moves hex by one hex in given direction
  40. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  41. static std::pair<int, int> gotoDir(int x, int y, int direction)
  42. {
  43. switch(direction)
  44. {
  45. case 0: //top left
  46. return std::make_pair((y%2) ? x-1 : x, y-1);
  47. case 1: //top right
  48. return std::make_pair((y%2) ? x : x+1, y-1);
  49. case 2: //right
  50. return std::make_pair(x+1, y);
  51. case 3: //right bottom
  52. return std::make_pair((y%2) ? x : x+1, y+1);
  53. case 4: //left bottom
  54. return std::make_pair((y%2) ? x-1 : x, y+1);
  55. case 5: //left
  56. return std::make_pair(x-1, y);
  57. default:
  58. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  59. }
  60. }
  61. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  62. {
  63. return gotoDir(xy.first, xy.second, direction);
  64. }
  65. static bool isGoodHex(std::pair<int, int> xy)
  66. {
  67. return xy.first >=0 && xy.first < GameConstants::BFIELD_WIDTH && xy.second >= 0 && xy.second < GameConstants::BFIELD_HEIGHT;
  68. }
  69. //helper function for rangeInHexes
  70. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  71. {
  72. std::set<ui16> ret;
  73. if(low == 0)
  74. {
  75. ret.insert(center);
  76. }
  77. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  78. for(auto & elem : mainPointForLayer)
  79. elem = hexToPair(center);
  80. for(int it=1; it<=high; ++it) //it - distance to the center
  81. {
  82. for(int b=0; b<6; ++b)
  83. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  84. if(it>=low)
  85. {
  86. std::pair<int, int> curHex;
  87. //adding lines (A-b, B-c, C-d, etc)
  88. for(int v=0; v<6; ++v)
  89. {
  90. curHex = mainPointForLayer[v];
  91. for(int h=0; h<it; ++h)
  92. {
  93. if(isGoodHex(curHex))
  94. ret.insert(XYToHex(curHex));
  95. curHex = gotoDir(curHex, (v+2)%6);
  96. }
  97. }
  98. } //if(it>=low)
  99. }
  100. return ret;
  101. }
  102. }
  103. ///ISpellMechanics
  104. ISpellMechanics::ISpellMechanics(CSpell * s):
  105. owner(s)
  106. {
  107. }
  108. ISpellMechanics * ISpellMechanics::createMechanics(CSpell* s)
  109. {
  110. switch (s->id)
  111. {
  112. case SpellID::CLONE:
  113. return new CloneMechanics(s);
  114. case SpellID::DISPEL_HELPFUL_SPELLS:
  115. return new DispellHelpfulMechanics(s);
  116. case SpellID::SACRIFICE:
  117. return new SacrificeMechanics(s);
  118. case SpellID::CHAIN_LIGHTNING:
  119. return new ChainLightningMechanics(s);
  120. case SpellID::FIRE_WALL:
  121. case SpellID::FORCE_FIELD:
  122. return new WallMechanics(s);
  123. case SpellID::LAND_MINE:
  124. case SpellID::QUICKSAND:
  125. return new ObstacleMechanics(s);
  126. default:
  127. if(s->isRisingSpell())
  128. return new SpecialRisingSpellMechanics(s);
  129. else
  130. return new DefaultSpellMechanics(s);
  131. }
  132. }
  133. ///DefaultSpellMechanics
  134. //bool DefaultSpellMechanics::adventureCast(const SpellCastContext& context) const
  135. //{
  136. // return false; //there is no general algorithm for casting adventure spells
  137. //}
  138. bool DefaultSpellMechanics::battleCast(const SpellCastEnvironment * env, const BattleSpellCastParameters & parameters) const
  139. {
  140. BattleSpellCast sc;
  141. sc.side = parameters.casterSide;
  142. sc.id = owner->id;
  143. sc.skill = parameters.spellLvl;
  144. sc.tile = parameters.destination;
  145. sc.dmgToDisplay = 0;
  146. sc.castedByHero = nullptr != parameters.caster;
  147. sc.attackerType = (parameters.casterStack ? parameters.casterStack->type->idNumber : CreatureID(CreatureID::NONE));
  148. sc.manaGained = 0;
  149. sc.spellCost = 0;
  150. //calculate spell cost
  151. if (parameters.caster)
  152. {
  153. sc.spellCost = parameters.cb->battleGetSpellCost(owner, parameters.caster);
  154. if (parameters.secHero && parameters.mode == ECastingMode::HERO_CASTING) //handle mana channel
  155. {
  156. int manaChannel = 0;
  157. for(const CStack * stack : parameters.cb->battleGetAllStacks(true)) //TODO: shouldn't bonus system handle it somehow?
  158. {
  159. if (stack->owner == parameters.secHero->tempOwner)
  160. {
  161. vstd::amax(manaChannel, stack->valOfBonuses(Bonus::MANA_CHANNELING));
  162. }
  163. }
  164. sc.manaGained = (manaChannel * sc.spellCost) / 100;
  165. }
  166. }
  167. //calculating affected creatures for all spells
  168. //must be vector, as in Chain Lightning order matters
  169. std::vector<const CStack*> attackedCres; //CStack vector is somewhat more suitable than ID vector
  170. auto creatures = owner->getAffectedStacks(parameters.cb, parameters.mode, parameters.casterColor, parameters.spellLvl, parameters.destination, parameters.caster);
  171. std::copy(creatures.begin(), creatures.end(), std::back_inserter(attackedCres));
  172. for (auto cre : attackedCres)
  173. {
  174. sc.affectedCres.insert (cre->ID);
  175. }
  176. //checking if creatures resist
  177. //resistance is applied only to negative spells
  178. if(owner->isNegative())
  179. {
  180. for(auto s : attackedCres)
  181. {
  182. const int prob = std::min((s)->magicResistance(), 100); //probability of resistance in %
  183. if(env->getRandomGenerator().nextInt(99) < prob)
  184. {
  185. sc.resisted.push_back(s->ID);
  186. }
  187. }
  188. }
  189. //TODO: extract dmg to display calculation
  190. //calculating dmg to display
  191. if (owner->id == SpellID::DEATH_STARE || owner->id == SpellID::ACID_BREATH_DAMAGE)
  192. {
  193. sc.dmgToDisplay = parameters.usedSpellPower;
  194. if (owner->id == SpellID::DEATH_STARE)
  195. vstd::amin(sc.dmgToDisplay, (*attackedCres.begin())->count); //stack is already reduced after attack
  196. }
  197. StacksInjured si;
  198. //TODO:applying effects
  199. env->sendAndApply(&sc);
  200. if(!si.stacks.empty()) //after spellcast info shows
  201. env->sendAndApply(&si);
  202. //reduce number of casts remaining
  203. //TODO: this should be part of BattleSpellCast apply
  204. if (parameters.mode == ECastingMode::CREATURE_ACTIVE_CASTING || parameters.mode == ECastingMode::ENCHANTER_CASTING)
  205. {
  206. assert(parameters.casterStack);
  207. BattleSetStackProperty ssp;
  208. ssp.stackID = parameters.casterStack->ID;
  209. ssp.which = BattleSetStackProperty::CASTS;
  210. ssp.val = -1;
  211. ssp.absolute = false;
  212. env->sendAndApply(&ssp);
  213. }
  214. //Magic Mirror effect
  215. if (owner->isNegative() && parameters.mode != ECastingMode::MAGIC_MIRROR && owner->level && owner->getLevelInfo(0).range == "0") //it is actual spell and can be reflected to single target, no recurrence
  216. {
  217. for(auto & attackedCre : attackedCres)
  218. {
  219. int mirrorChance = (attackedCre)->valOfBonuses(Bonus::MAGIC_MIRROR);
  220. if(mirrorChance > env->getRandomGenerator().nextInt(99))
  221. {
  222. std::vector<const CStack *> mirrorTargets;
  223. auto battleStacks = parameters.cb->battleGetAllStacks(true);
  224. for (auto & battleStack : battleStacks)
  225. {
  226. if(battleStack->owner == parameters.casterColor) //get enemy stacks which can be affected by this spell
  227. {
  228. if (ESpellCastProblem::OK == owner->isImmuneByStack(nullptr, battleStack))
  229. mirrorTargets.push_back(battleStack);
  230. }
  231. }
  232. if (!mirrorTargets.empty())
  233. {
  234. int targetHex = (*RandomGeneratorUtil::nextItem(mirrorTargets, env->getRandomGenerator()))->position;
  235. BattleSpellCastParameters mirrorParameters = parameters;
  236. mirrorParameters.spellLvl = 0;
  237. mirrorParameters.casterSide = 1-parameters.casterSide;
  238. mirrorParameters.casterColor = (attackedCre)->owner;
  239. mirrorParameters.caster = nullptr;
  240. mirrorParameters.destination = targetHex;
  241. mirrorParameters.secHero = parameters.caster;
  242. mirrorParameters.mode = ECastingMode::MAGIC_MIRROR;
  243. mirrorParameters.casterStack = (attackedCre);
  244. mirrorParameters.selectedStack = nullptr;
  245. battleCast(env, mirrorParameters);
  246. }
  247. }
  248. }
  249. }
  250. return true;
  251. }
  252. std::vector<BattleHex> DefaultSpellMechanics::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  253. {
  254. using namespace SRSLPraserHelpers;
  255. std::vector<BattleHex> ret;
  256. std::string rng = owner->getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  257. if(rng.size() >= 2 && rng[0] != 'X') //there is at lest one hex in range (+artificial comma)
  258. {
  259. std::string number1, number2;
  260. int beg, end;
  261. bool readingFirst = true;
  262. for(auto & elem : rng)
  263. {
  264. if(std::isdigit(elem) ) //reading number
  265. {
  266. if(readingFirst)
  267. number1 += elem;
  268. else
  269. number2 += elem;
  270. }
  271. else if(elem == ',') //comma
  272. {
  273. //calculating variables
  274. if(readingFirst)
  275. {
  276. beg = atoi(number1.c_str());
  277. number1 = "";
  278. }
  279. else
  280. {
  281. end = atoi(number2.c_str());
  282. number2 = "";
  283. }
  284. //obtaining new hexes
  285. std::set<ui16> curLayer;
  286. if(readingFirst)
  287. {
  288. curLayer = getInRange(centralHex, beg, beg);
  289. }
  290. else
  291. {
  292. curLayer = getInRange(centralHex, beg, end);
  293. readingFirst = true;
  294. }
  295. //adding abtained hexes
  296. for(auto & curLayer_it : curLayer)
  297. {
  298. ret.push_back(curLayer_it);
  299. }
  300. }
  301. else if(elem == '-') //dash
  302. {
  303. beg = atoi(number1.c_str());
  304. number1 = "";
  305. readingFirst = false;
  306. }
  307. }
  308. }
  309. //remove duplicates (TODO check if actually needed)
  310. range::unique(ret);
  311. return ret;
  312. }
  313. std::set<const CStack *> DefaultSpellMechanics::getAffectedStacks(SpellTargetingContext & ctx) const
  314. {
  315. std::set<const CStack* > attackedCres;//std::set to exclude multiple occurrences of two hex creatures
  316. const ui8 attackerSide = ctx.cb->playerToSide(ctx.casterColor) == 1;
  317. const auto attackedHexes = rangeInHexes(ctx.destination, ctx.schoolLvl, attackerSide);
  318. const CSpell::TargetInfo ti(owner, ctx.schoolLvl, ctx.mode);
  319. //TODO: more generic solution for mass spells
  320. if (owner->getLevelInfo(ctx.schoolLvl).range.size() > 1) //custom many-hex range
  321. {
  322. for(BattleHex hex : attackedHexes)
  323. {
  324. if(const CStack * st = ctx.cb->battleGetStackByPos(hex, ti.onlyAlive))
  325. {
  326. attackedCres.insert(st);
  327. }
  328. }
  329. }
  330. else if(ti.type == CSpell::CREATURE)
  331. {
  332. auto predicate = [=](const CStack * s){
  333. const bool positiveToAlly = owner->isPositive() && s->owner == ctx.casterColor;
  334. const bool negativeToEnemy = owner->isNegative() && s->owner != ctx.casterColor;
  335. const bool validTarget = s->isValidTarget(!ti.onlyAlive); //todo: this should be handled by spell class
  336. //for single target spells select stacks covering destination tile
  337. const bool rangeCovers = ti.massive || s->coversPos(ctx.destination);
  338. //handle smart targeting
  339. const bool positivenessFlag = !ti.smart || owner->isNeutral() || positiveToAlly || negativeToEnemy;
  340. return rangeCovers && positivenessFlag && validTarget;
  341. };
  342. TStacks stacks = ctx.cb->battleGetStacksIf(predicate);
  343. if (ti.massive)
  344. {
  345. //for massive spells add all targets
  346. for (auto stack : stacks)
  347. attackedCres.insert(stack);
  348. }
  349. else
  350. {
  351. //for single target spells we must select one target. Alive stack is preferred (issue #1763)
  352. for(auto stack : stacks)
  353. {
  354. if(stack->alive())
  355. {
  356. attackedCres.insert(stack);
  357. break;
  358. }
  359. }
  360. if(attackedCres.empty() && !stacks.empty())
  361. {
  362. attackedCres.insert(stacks.front());
  363. }
  364. }
  365. }
  366. else //custom range from attackedHexes
  367. {
  368. for(BattleHex hex : attackedHexes)
  369. {
  370. if(const CStack * st = ctx.cb->battleGetStackByPos(hex, ti.onlyAlive))
  371. attackedCres.insert(st);
  372. }
  373. }
  374. return attackedCres;
  375. }
  376. ESpellCastProblem::ESpellCastProblem DefaultSpellMechanics::isImmuneByStack(const CGHeroInstance * caster, const CStack * obj) const
  377. {
  378. //by default use general algorithm
  379. return owner->isImmuneBy(obj);
  380. }
  381. ///WallMechanics
  382. std::vector<BattleHex> WallMechanics::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool* outDroppedHexes) const
  383. {
  384. using namespace SRSLPraserHelpers;
  385. std::vector<BattleHex> ret;
  386. //Special case - shape of obstacle depends on caster's side
  387. //TODO make it possible through spell_info config
  388. BattleHex::EDir firstStep, secondStep;
  389. if(side)
  390. {
  391. firstStep = BattleHex::TOP_LEFT;
  392. secondStep = BattleHex::TOP_RIGHT;
  393. }
  394. else
  395. {
  396. firstStep = BattleHex::TOP_RIGHT;
  397. secondStep = BattleHex::TOP_LEFT;
  398. }
  399. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  400. auto addIfValid = [&](BattleHex hex)
  401. {
  402. if(hex.isValid())
  403. ret.push_back(hex);
  404. else if(outDroppedHexes)
  405. *outDroppedHexes = true;
  406. };
  407. ret.push_back(centralHex);
  408. addIfValid(centralHex.moveInDir(firstStep, false));
  409. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  410. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  411. return ret;
  412. }
  413. ///ChainLightningMechanics
  414. std::set<const CStack *> ChainLightningMechanics::getAffectedStacks(SpellTargetingContext & ctx) const
  415. {
  416. std::set<const CStack* > attackedCres;
  417. std::set<BattleHex> possibleHexes;
  418. for(auto stack : ctx.cb->battleGetAllStacks())
  419. {
  420. if(stack->isValidTarget())
  421. {
  422. for(auto hex : stack->getHexes())
  423. {
  424. possibleHexes.insert (hex);
  425. }
  426. }
  427. }
  428. int targetsOnLevel[4] = {4, 4, 5, 5};
  429. BattleHex lightningHex = ctx.destination;
  430. for(int i = 0; i < targetsOnLevel[ctx.schoolLvl]; ++i)
  431. {
  432. auto stack = ctx.cb->battleGetStackByPos(lightningHex, true);
  433. if(!stack)
  434. break;
  435. attackedCres.insert (stack);
  436. for(auto hex : stack->getHexes())
  437. {
  438. possibleHexes.erase(hex); //can't hit same place twice
  439. }
  440. if(possibleHexes.empty()) //not enough targets
  441. break;
  442. lightningHex = BattleHex::getClosestTile(stack->attackerOwned, ctx.destination, possibleHexes);
  443. }
  444. return attackedCres;
  445. }
  446. ///CloneMechanics
  447. ESpellCastProblem::ESpellCastProblem CloneMechanics::isImmuneByStack(const CGHeroInstance* caster, const CStack * obj) const
  448. {
  449. //can't clone already cloned creature
  450. if (vstd::contains(obj->state, EBattleStackState::CLONED))
  451. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  452. //TODO: how about stacks casting Clone?
  453. //currently Clone casted by stack is assumed Expert level
  454. ui8 schoolLevel;
  455. if (caster)
  456. {
  457. schoolLevel = caster->getSpellSchoolLevel(owner);
  458. }
  459. else
  460. {
  461. schoolLevel = 3;
  462. }
  463. if (schoolLevel < 3)
  464. {
  465. int maxLevel = (std::max(schoolLevel, (ui8)1) + 4);
  466. int creLevel = obj->getCreature()->level;
  467. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, any level for expert
  468. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  469. }
  470. //use default algorithm only if there is no mechanics-related problem
  471. return DefaultSpellMechanics::isImmuneByStack(caster,obj);
  472. }
  473. ///DispellHelpfulMechanics
  474. ESpellCastProblem::ESpellCastProblem DispellHelpfulMechanics::isImmuneByStack(const CGHeroInstance* caster, const CStack* obj) const
  475. {
  476. TBonusListPtr spellBon = obj->getSpellBonuses();
  477. bool hasPositiveSpell = false;
  478. for(const Bonus * b : *spellBon)
  479. {
  480. if(SpellID(b->sid).toSpell()->isPositive())
  481. {
  482. hasPositiveSpell = true;
  483. break;
  484. }
  485. }
  486. if(!hasPositiveSpell)
  487. {
  488. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  489. }
  490. //use default algorithm only if there is no mechanics-related problem
  491. return DefaultSpellMechanics::isImmuneByStack(caster,obj);
  492. }
  493. ///HypnotizeMechanics
  494. ESpellCastProblem::ESpellCastProblem HypnotizeMechanics::isImmuneByStack(const CGHeroInstance* caster, const CStack* obj) const
  495. {
  496. if(nullptr != caster) //do not resist hypnotize casted after attack, for example
  497. {
  498. //TODO: what with other creatures casting hypnotize, Faerie Dragons style?
  499. ui64 subjectHealth = (obj->count - 1) * obj->MaxHealth() + obj->firstHPleft;
  500. //apply 'damage' bonus for hypnotize, including hero specialty
  501. ui64 maxHealth = owner->calculateBonus(caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER)
  502. * owner->power + owner->getPower(caster->getSpellSchoolLevel(owner)), caster, obj);
  503. if (subjectHealth > maxHealth)
  504. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  505. }
  506. return DefaultSpellMechanics::isImmuneByStack(caster,obj);
  507. }
  508. ///SpecialRisingSpellMechanics
  509. ESpellCastProblem::ESpellCastProblem SpecialRisingSpellMechanics::isImmuneByStack(const CGHeroInstance* caster, const CStack* obj) const
  510. {
  511. // following does apply to resurrect and animate dead(?) only
  512. // for sacrifice health calculation and health limit check don't matter
  513. if(obj->count >= obj->baseAmount)
  514. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  515. if (caster) //FIXME: Archangels can cast immune stack
  516. {
  517. auto maxHealth = owner->calculateHealedHP (caster, obj);
  518. if (maxHealth < obj->MaxHealth()) //must be able to rise at least one full creature
  519. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  520. }
  521. return DefaultSpellMechanics::isImmuneByStack(caster,obj);
  522. }