CSpellHandler.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. #include "StdInc.h"
  2. #include "CSpellHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "JsonNode.h"
  6. #include <cctype>
  7. #include "BattleHex.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. #include "mapObjects/CGHeroInstance.h"
  11. #include "BattleState.h"
  12. /*
  13. * CSpellHandler.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. namespace SpellConfig
  22. {
  23. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  24. }
  25. namespace SRSLPraserHelpers
  26. {
  27. static int XYToHex(int x, int y)
  28. {
  29. return x + 17 * y;
  30. }
  31. static int XYToHex(std::pair<int, int> xy)
  32. {
  33. return XYToHex(xy.first, xy.second);
  34. }
  35. static int hexToY(int battleFieldPosition)
  36. {
  37. return battleFieldPosition/17;
  38. }
  39. static int hexToX(int battleFieldPosition)
  40. {
  41. int pos = battleFieldPosition - hexToY(battleFieldPosition) * 17;
  42. return pos;
  43. }
  44. static std::pair<int, int> hexToPair(int battleFieldPosition)
  45. {
  46. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  47. }
  48. //moves hex by one hex in given direction
  49. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  50. static std::pair<int, int> gotoDir(int x, int y, int direction)
  51. {
  52. switch(direction)
  53. {
  54. case 0: //top left
  55. return std::make_pair((y%2) ? x-1 : x, y-1);
  56. case 1: //top right
  57. return std::make_pair((y%2) ? x : x+1, y-1);
  58. case 2: //right
  59. return std::make_pair(x+1, y);
  60. case 3: //right bottom
  61. return std::make_pair((y%2) ? x : x+1, y+1);
  62. case 4: //left bottom
  63. return std::make_pair((y%2) ? x-1 : x, y+1);
  64. case 5: //left
  65. return std::make_pair(x-1, y);
  66. default:
  67. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  68. }
  69. }
  70. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  71. {
  72. return gotoDir(xy.first, xy.second, direction);
  73. }
  74. static bool isGoodHex(std::pair<int, int> xy)
  75. {
  76. return xy.first >=0 && xy.first < 17 && xy.second >= 0 && xy.second < 11;
  77. }
  78. //helper function for std::set<ui16> CSpell::rangeInHexes(unsigned int centralHex, ui8 schoolLvl ) const
  79. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  80. {
  81. std::set<ui16> ret;
  82. if(low == 0)
  83. {
  84. ret.insert(center);
  85. }
  86. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  87. for(auto & elem : mainPointForLayer)
  88. elem = hexToPair(center);
  89. for(int it=1; it<=high; ++it) //it - distance to the center
  90. {
  91. for(int b=0; b<6; ++b)
  92. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  93. if(it>=low)
  94. {
  95. std::pair<int, int> curHex;
  96. //adding lines (A-b, B-c, C-d, etc)
  97. for(int v=0; v<6; ++v)
  98. {
  99. curHex = mainPointForLayer[v];
  100. for(int h=0; h<it; ++h)
  101. {
  102. if(isGoodHex(curHex))
  103. ret.insert(XYToHex(curHex));
  104. curHex = gotoDir(curHex, (v+2)%6);
  105. }
  106. }
  107. } //if(it>=low)
  108. }
  109. return ret;
  110. }
  111. }
  112. ///CSpellMechanics
  113. CSpellMechanics::CSpellMechanics(CSpell * s):
  114. owner(s)
  115. {
  116. }
  117. CSpellMechanics::~CSpellMechanics()
  118. {
  119. }
  120. ESpellCastProblem::ESpellCastProblem CSpellMechanics::isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj)
  121. {
  122. //by default use general algorithm
  123. return owner->isImmuneBy(obj);
  124. }
  125. namespace
  126. {
  127. class CloneMechnics: public CSpellMechanics
  128. {
  129. public:
  130. CloneMechnics(CSpell * s): CSpellMechanics(s){};
  131. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  132. };
  133. class DispellHelpfulMechanics: public CSpellMechanics
  134. {
  135. public:
  136. DispellHelpfulMechanics(CSpell * s): CSpellMechanics(s){};
  137. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  138. };
  139. class HypnotizeMechanics: public CSpellMechanics
  140. {
  141. public:
  142. HypnotizeMechanics(CSpell * s): CSpellMechanics(s){};
  143. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  144. };
  145. ///all rising spells
  146. class RisingSpellMechanics: public CSpellMechanics
  147. {
  148. public:
  149. RisingSpellMechanics(CSpell * s): CSpellMechanics(s){};
  150. };
  151. ///all rising spells but SACRIFICE
  152. class SpecialRisingSpellMechanics: public RisingSpellMechanics
  153. {
  154. public:
  155. SpecialRisingSpellMechanics(CSpell * s): RisingSpellMechanics(s){};
  156. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  157. };
  158. class SacrificeMechanics: public RisingSpellMechanics
  159. {
  160. public:
  161. SacrificeMechanics(CSpell * s): RisingSpellMechanics(s){};
  162. };
  163. ///CloneMechanics
  164. ESpellCastProblem::ESpellCastProblem CloneMechnics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack * obj)
  165. {
  166. //can't clone already cloned creature
  167. if (vstd::contains(obj->state, EBattleStackState::CLONED))
  168. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  169. //TODO: how about stacks casting Clone?
  170. //currently Clone casted by stack is assumed Expert level
  171. ui8 schoolLevel;
  172. if (caster)
  173. {
  174. schoolLevel = caster->getSpellSchoolLevel(owner);
  175. }
  176. else
  177. {
  178. schoolLevel = 3;
  179. }
  180. if (schoolLevel < 3)
  181. {
  182. int maxLevel = (std::max(schoolLevel, (ui8)1) + 4);
  183. int creLevel = obj->getCreature()->level;
  184. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, any level for expert
  185. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  186. }
  187. //use default algorithm only if there is no mechanics-related problem
  188. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  189. }
  190. ///DispellHelpfulMechanics
  191. ESpellCastProblem::ESpellCastProblem DispellHelpfulMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  192. {
  193. TBonusListPtr spellBon = obj->getSpellBonuses();
  194. bool hasPositiveSpell = false;
  195. for(const Bonus * b : *spellBon)
  196. {
  197. if(SpellID(b->sid).toSpell()->isPositive())
  198. {
  199. hasPositiveSpell = true;
  200. break;
  201. }
  202. }
  203. if(!hasPositiveSpell)
  204. {
  205. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  206. }
  207. //use default algorithm only if there is no mechanics-related problem
  208. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  209. }
  210. ///HypnotizeMechanics
  211. ESpellCastProblem::ESpellCastProblem HypnotizeMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  212. {
  213. if(nullptr != caster) //do not resist hypnotize casted after attack, for example
  214. {
  215. //TODO: what with other creatures casting hypnotize, Faerie Dragons style?
  216. ui64 subjectHealth = (obj->count - 1) * obj->MaxHealth() + obj->firstHPleft;
  217. //apply 'damage' bonus for hypnotize, including hero specialty
  218. ui64 maxHealth = owner->calculateBonus(caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER)
  219. * owner->power + owner->getPower(caster->getSpellSchoolLevel(owner)), caster, obj);
  220. if (subjectHealth > maxHealth)
  221. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  222. }
  223. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  224. }
  225. ///SpecialRisingSpellMechanics
  226. ESpellCastProblem::ESpellCastProblem SpecialRisingSpellMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  227. {
  228. // following does apply to resurrect and animate dead(?) only
  229. // for sacrifice health calculation and health limit check don't matter
  230. if(obj->count >= obj->baseAmount)
  231. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  232. if (caster) //FIXME: Archangels can cast immune stack
  233. {
  234. auto maxHealth = owner->calculateHealedHP (caster, obj);
  235. if (maxHealth < obj->MaxHealth()) //must be able to rise at least one full creature
  236. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  237. }
  238. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  239. }
  240. }
  241. ///CSpell::LevelInfo
  242. CSpell::LevelInfo::LevelInfo()
  243. :description(""),cost(0),power(0),AIValue(0),smartTarget(true),range("0")
  244. {
  245. }
  246. CSpell::LevelInfo::~LevelInfo()
  247. {
  248. }
  249. ///CSpell
  250. CSpell::CSpell():
  251. id(SpellID::NONE), level(0),
  252. earth(false), water(false), fire(false), air(false),
  253. combatSpell(false), creatureAbility(false),
  254. positiveness(ESpellPositiveness::NEUTRAL),
  255. mainEffectAnim(-1),
  256. defaultProbability(0),
  257. isRising(false), isDamage(false), isOffensive(false),
  258. targetType(ETargetType::NO_TARGET),
  259. mechanics(nullptr)
  260. {
  261. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  262. }
  263. CSpell::~CSpell()
  264. {
  265. delete mechanics;
  266. }
  267. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  268. {
  269. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  270. {
  271. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  272. throw new std::runtime_error("Invalid school level");
  273. }
  274. return levels.at(level);
  275. }
  276. ui32 CSpell::calculateBonus(ui32 baseDamage, const CGHeroInstance* caster, const CStack* affectedCreature) const
  277. {
  278. ui32 ret = baseDamage;
  279. //applying sorcery secondary skill
  280. if(caster)
  281. {
  282. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  283. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, id.toEnum())) / 100.0;
  284. if(air)
  285. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  286. else if(fire) //only one type of bonus for Magic Arrow
  287. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  288. else if(water)
  289. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  290. else if(earth)
  291. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  292. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  293. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  294. }
  295. return ret;
  296. }
  297. ui32 CSpell::calculateHealedHP(const CGHeroInstance* caster, const CStack* stack, const CStack* sacrificedStack) const
  298. {
  299. //todo: use Mechanics class
  300. int healedHealth;
  301. if(!isHealingSpell())
  302. {
  303. logGlobal->errorStream() << "calculateHealedHP called for nonhealing spell "<< name;
  304. return 0;
  305. }
  306. const int spellPowerSkill = caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  307. const int levelPower = getPower(caster->getSpellSchoolLevel(this));
  308. if (id == SpellID::SACRIFICE && sacrificedStack)
  309. healedHealth = (spellPowerSkill + sacrificedStack->MaxHealth() + levelPower) * sacrificedStack->count;
  310. else
  311. healedHealth = spellPowerSkill * power + levelPower; //???
  312. healedHealth = calculateBonus(healedHealth, caster, stack);
  313. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (isRisingSpell() ? stack->baseAmount * stack->MaxHealth() : 0));
  314. }
  315. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  316. {
  317. using namespace SRSLPraserHelpers;
  318. std::vector<BattleHex> ret;
  319. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  320. {
  321. //Special case - shape of obstacle depends on caster's side
  322. //TODO make it possible through spell_info config
  323. BattleHex::EDir firstStep, secondStep;
  324. if(side)
  325. {
  326. firstStep = BattleHex::TOP_LEFT;
  327. secondStep = BattleHex::TOP_RIGHT;
  328. }
  329. else
  330. {
  331. firstStep = BattleHex::TOP_RIGHT;
  332. secondStep = BattleHex::TOP_LEFT;
  333. }
  334. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  335. auto addIfValid = [&](BattleHex hex)
  336. {
  337. if(hex.isValid())
  338. ret.push_back(hex);
  339. else if(outDroppedHexes)
  340. *outDroppedHexes = true;
  341. };
  342. ret.push_back(centralHex);
  343. addIfValid(centralHex.moveInDir(firstStep, false));
  344. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  345. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  346. return ret;
  347. }
  348. std::string rng = getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  349. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  350. {
  351. std::string number1, number2;
  352. int beg, end;
  353. bool readingFirst = true;
  354. for(auto & elem : rng)
  355. {
  356. if(std::isdigit(elem) ) //reading number
  357. {
  358. if(readingFirst)
  359. number1 += elem;
  360. else
  361. number2 += elem;
  362. }
  363. else if(elem == ',') //comma
  364. {
  365. //calculating variables
  366. if(readingFirst)
  367. {
  368. beg = atoi(number1.c_str());
  369. number1 = "";
  370. }
  371. else
  372. {
  373. end = atoi(number2.c_str());
  374. number2 = "";
  375. }
  376. //obtaining new hexes
  377. std::set<ui16> curLayer;
  378. if(readingFirst)
  379. {
  380. curLayer = getInRange(centralHex, beg, beg);
  381. }
  382. else
  383. {
  384. curLayer = getInRange(centralHex, beg, end);
  385. readingFirst = true;
  386. }
  387. //adding abtained hexes
  388. for(auto & curLayer_it : curLayer)
  389. {
  390. ret.push_back(curLayer_it);
  391. }
  392. }
  393. else if(elem == '-') //dash
  394. {
  395. beg = atoi(number1.c_str());
  396. number1 = "";
  397. readingFirst = false;
  398. }
  399. }
  400. }
  401. //remove duplicates (TODO check if actually needed)
  402. range::unique(ret);
  403. return ret;
  404. }
  405. CSpell::ETargetType CSpell::getTargetType() const
  406. {
  407. return targetType;
  408. }
  409. const CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  410. {
  411. TargetInfo info;
  412. auto & levelInfo = getLevelInfo(level);
  413. info.type = getTargetType();
  414. info.smart = levelInfo.smartTarget;
  415. info.massive = levelInfo.range == "X";
  416. info.onlyAlive = !isRisingSpell();
  417. return info;
  418. }
  419. bool CSpell::isCombatSpell() const
  420. {
  421. return combatSpell;
  422. }
  423. bool CSpell::isAdventureSpell() const
  424. {
  425. return !combatSpell;
  426. }
  427. bool CSpell::isCreatureAbility() const
  428. {
  429. return creatureAbility;
  430. }
  431. bool CSpell::isPositive() const
  432. {
  433. return positiveness == POSITIVE;
  434. }
  435. bool CSpell::isNegative() const
  436. {
  437. return positiveness == NEGATIVE;
  438. }
  439. bool CSpell::isNeutral() const
  440. {
  441. return positiveness == NEUTRAL;
  442. }
  443. bool CSpell::isHealingSpell() const
  444. {
  445. return isRisingSpell() || (id == SpellID::CURE);
  446. }
  447. bool CSpell::isRisingSpell() const
  448. {
  449. return isRising;
  450. }
  451. bool CSpell::isDamageSpell() const
  452. {
  453. return isDamage;
  454. }
  455. bool CSpell::isOffensiveSpell() const
  456. {
  457. return isOffensive;
  458. }
  459. bool CSpell::isSpecialSpell() const
  460. {
  461. return isSpecial;
  462. }
  463. bool CSpell::hasEffects() const
  464. {
  465. return !levels[0].effects.empty();
  466. }
  467. const std::string& CSpell::getIconImmune() const
  468. {
  469. return iconImmune;
  470. }
  471. const std::string& CSpell::getCastSound() const
  472. {
  473. return castSound;
  474. }
  475. si32 CSpell::getCost(const int skillLevel) const
  476. {
  477. return getLevelInfo(skillLevel).cost;
  478. }
  479. si32 CSpell::getPower(const int skillLevel) const
  480. {
  481. return getLevelInfo(skillLevel).power;
  482. }
  483. //si32 CSpell::calculatePower(const int skillLevel) const
  484. //{
  485. // return power + getPower(skillLevel);
  486. //}
  487. si32 CSpell::getProbability(const TFaction factionId) const
  488. {
  489. if(!vstd::contains(probabilities,factionId))
  490. {
  491. return defaultProbability;
  492. }
  493. return probabilities.at(factionId);
  494. }
  495. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  496. {
  497. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  498. {
  499. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  500. return;
  501. }
  502. const std::vector<Bonus> & effects = levels[level].effects;
  503. if(effects.empty())
  504. {
  505. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  506. return;
  507. }
  508. lst.reserve(lst.size() + effects.size());
  509. for(const Bonus & b : effects)
  510. {
  511. lst.push_back(Bonus(b));
  512. }
  513. }
  514. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  515. {
  516. //0. check receptivity
  517. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  518. return ESpellCastProblem::OK;
  519. //todo: use new bonus API
  520. //1. Check absolute limiters
  521. for(auto b : absoluteLimiters)
  522. {
  523. if (!obj->hasBonusOfType(b))
  524. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  525. }
  526. //2. Check absolute immunities
  527. for(auto b : absoluteImmunities)
  528. {
  529. if (obj->hasBonusOfType(b))
  530. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  531. }
  532. //3. Check negation
  533. //FIXME: Orb of vulnerability mechanics is not such trivial
  534. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  535. return ESpellCastProblem::NOT_DECIDED;
  536. //4. Check negatable limit
  537. for(auto b : limiters)
  538. {
  539. if (!obj->hasBonusOfType(b))
  540. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  541. }
  542. //5. Check negatable immunities
  543. for(auto b : immunities)
  544. {
  545. if (obj->hasBonusOfType(b))
  546. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  547. }
  548. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  549. {
  550. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  551. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  552. else if(!isPositive()) //negative or indifferent
  553. {
  554. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  555. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  556. }
  557. return ESpellCastProblem::NOT_DECIDED;
  558. };
  559. //6. Check elemental immunities
  560. if(fire)
  561. {
  562. if(battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  563. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  564. }
  565. if(water)
  566. {
  567. if(battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  568. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  569. }
  570. if(earth)
  571. {
  572. if(battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  573. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  574. }
  575. if(air)
  576. {
  577. if(battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  578. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  579. }
  580. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  581. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  582. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  583. {
  584. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  585. }
  586. return ESpellCastProblem::NOT_DECIDED;
  587. }
  588. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj) const
  589. {
  590. const auto immuneResult = mechanics->isImmuneByStack(caster,mode,obj);
  591. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  592. return immuneResult;
  593. return ESpellCastProblem::OK;
  594. }
  595. void CSpell::setIsOffensive(const bool val)
  596. {
  597. isOffensive = val;
  598. if(val)
  599. {
  600. positiveness = CSpell::NEGATIVE;
  601. isDamage = true;
  602. }
  603. }
  604. void CSpell::setIsRising(const bool val)
  605. {
  606. isRising = val;
  607. if(val)
  608. {
  609. positiveness = CSpell::POSITIVE;
  610. }
  611. }
  612. void CSpell::setupMechanics()
  613. {
  614. if(nullptr != mechanics)
  615. {
  616. logGlobal->errorStream() << "Spell " << this->name << " mechanics already set";
  617. delete mechanics;
  618. mechanics = nullptr;
  619. }
  620. switch (id)
  621. {
  622. case SpellID::CLONE:
  623. mechanics = new CloneMechnics(this);
  624. break;
  625. case SpellID::DISPEL_HELPFUL_SPELLS:
  626. mechanics = new DispellHelpfulMechanics(this);
  627. break;
  628. case SpellID::SACRIFICE:
  629. mechanics = new SacrificeMechanics(this);
  630. break;
  631. default:
  632. if(isRisingSpell())
  633. mechanics = new SpecialRisingSpellMechanics(this);
  634. else
  635. mechanics = new CSpellMechanics(this);
  636. break;
  637. }
  638. }
  639. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  640. {
  641. int3 diff = pos - center;
  642. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  643. return true;
  644. else
  645. return false;
  646. }
  647. ///CSpellHandler
  648. CSpellHandler::CSpellHandler()
  649. {
  650. }
  651. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  652. {
  653. using namespace SpellConfig;
  654. std::vector<JsonNode> legacyData;
  655. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  656. auto readSchool = [&](JsonMap& schools, const std::string& name)
  657. {
  658. if (parser.readString() == "x")
  659. {
  660. schools[name].Bool() = true;
  661. }
  662. };
  663. auto read = [&,this](bool combat, bool ability)
  664. {
  665. do
  666. {
  667. JsonNode lineNode(JsonNode::DATA_STRUCT);
  668. const si32 id = legacyData.size();
  669. lineNode["index"].Float() = id;
  670. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  671. lineNode["name"].String() = parser.readString();
  672. parser.readString(); //ignored unused abbreviated name
  673. lineNode["level"].Float() = parser.readNumber();
  674. auto& schools = lineNode["school"].Struct();
  675. readSchool(schools, "earth");
  676. readSchool(schools, "water");
  677. readSchool(schools, "fire");
  678. readSchool(schools, "air");
  679. auto& levels = lineNode["levels"].Struct();
  680. auto getLevel = [&](const size_t idx)->JsonMap&
  681. {
  682. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  683. return levels[LEVEL_NAMES[idx]].Struct();
  684. };
  685. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  686. lineNode["power"].Float() = parser.readNumber();
  687. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  688. auto& chances = lineNode["gainChance"].Struct();
  689. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  690. chances[ETownType::names[i]].Float() = parser.readNumber();
  691. }
  692. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  693. std::vector<std::string> descriptions;
  694. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  695. descriptions.push_back(parser.readString());
  696. std::string attributes = parser.readString();
  697. std::string targetType = "NO_TARGET";
  698. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  699. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  700. targetType = "CREATURE_EXPERT_MASSIVE";
  701. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  702. targetType = "CREATURE";
  703. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  704. targetType = "OBSTACLE";
  705. //save parsed level specific data
  706. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  707. {
  708. auto& level = getLevel(i);
  709. level["description"].String() = descriptions[i];
  710. level["cost"].Float() = costs[i];
  711. level["power"].Float() = powers[i];
  712. level["aiValue"].Float() = AIVals[i];
  713. }
  714. if(targetType == "CREATURE_EXPERT_MASSIVE")
  715. {
  716. lineNode["targetType"].String() = "CREATURE";
  717. getLevel(3)["range"].String() = "X";
  718. }
  719. else
  720. {
  721. lineNode["targetType"].String() = targetType;
  722. }
  723. legacyData.push_back(lineNode);
  724. }
  725. while (parser.endLine() && !parser.isNextEntryEmpty());
  726. };
  727. auto skip = [&](int cnt)
  728. {
  729. for(int i=0; i<cnt; i++)
  730. parser.endLine();
  731. };
  732. skip(5);// header
  733. read(false,false); //read adventure map spells
  734. skip(3);
  735. read(true,false); //read battle spells
  736. skip(3);
  737. read(true,true);//read creature abilities
  738. //TODO: maybe move to config
  739. //clone Acid Breath attributes for Acid Breath damage effect
  740. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  741. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  742. legacyData.push_back(temp);
  743. objects.resize(legacyData.size());
  744. return legacyData;
  745. }
  746. const std::string CSpellHandler::getTypeName() const
  747. {
  748. return "spell";
  749. }
  750. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  751. {
  752. using namespace SpellConfig;
  753. CSpell * spell = new CSpell();
  754. const auto type = json["type"].String();
  755. if(type == "ability")
  756. {
  757. spell->creatureAbility = true;
  758. spell->combatSpell = true;
  759. }
  760. else
  761. {
  762. spell->creatureAbility = false;
  763. spell->combatSpell = type == "combat";
  764. }
  765. spell->name = json["name"].String();
  766. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  767. const auto schoolNames = json["school"];
  768. spell->air = schoolNames["air"].Bool();
  769. spell->earth = schoolNames["earth"].Bool();
  770. spell->fire = schoolNames["fire"].Bool();
  771. spell->water = schoolNames["water"].Bool();
  772. spell->level = json["level"].Float();
  773. spell->power = json["power"].Float();
  774. spell->defaultProbability = json["defaultGainChance"].Float();
  775. for(const auto & node : json["gainChance"].Struct())
  776. {
  777. const int chance = node.second.Float();
  778. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  779. {
  780. spell->probabilities[factionID] = chance;
  781. });
  782. }
  783. const std::string targetType = json["targetType"].String();
  784. if(targetType == "NO_TARGET")
  785. spell->targetType = CSpell::NO_TARGET;
  786. else if(targetType == "CREATURE")
  787. spell->targetType = CSpell::CREATURE;
  788. else if(targetType == "OBSTACLE")
  789. spell->targetType = CSpell::OBSTACLE;
  790. else
  791. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  792. spell->mainEffectAnim = json["anim"].Float();
  793. for(const auto & counteredSpell: json["counters"].Struct())
  794. if (counteredSpell.second.Bool())
  795. {
  796. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  797. {
  798. spell->counteredSpells.push_back(SpellID(id));
  799. });
  800. }
  801. //TODO: more error checking - f.e. conflicting flags
  802. const auto flags = json["flags"];
  803. //by default all flags are set to false in constructor
  804. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  805. if(flags["offensive"].Bool())
  806. {
  807. spell->setIsOffensive(true);
  808. }
  809. if(flags["rising"].Bool())
  810. {
  811. spell->setIsRising(true);
  812. }
  813. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  814. if(flags["indifferent"].Bool())
  815. {
  816. spell->positiveness = CSpell::NEUTRAL;
  817. }
  818. else if(flags["negative"].Bool())
  819. {
  820. spell->positiveness = CSpell::NEGATIVE;
  821. }
  822. else if(flags["positive"].Bool())
  823. {
  824. spell->positiveness = CSpell::POSITIVE;
  825. }
  826. else if(!implicitPositiveness)
  827. {
  828. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  829. logGlobal->warnStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL";
  830. }
  831. spell->isSpecial = flags["special"].Bool();
  832. auto findBonus = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  833. {
  834. auto it = bonusNameMap.find(name);
  835. if(it == bonusNameMap.end())
  836. {
  837. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  838. }
  839. else
  840. {
  841. vec.push_back((Bonus::BonusType)it->second);
  842. }
  843. };
  844. auto readBonusStruct = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  845. {
  846. for(auto bonusData: json[name].Struct())
  847. {
  848. const std::string bonusId = bonusData.first;
  849. const bool flag = bonusData.second.Bool();
  850. if(flag)
  851. findBonus(bonusId, vec);
  852. }
  853. };
  854. readBonusStruct("immunity", spell->immunities);
  855. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  856. readBonusStruct("limit", spell->limiters);
  857. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  858. const JsonNode & graphicsNode = json["graphics"];
  859. spell->iconImmune = graphicsNode["iconImmune"].String();
  860. spell->iconBook = graphicsNode["iconBook"].String();
  861. spell->iconEffect = graphicsNode["iconEffect"].String();
  862. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  863. spell->iconScroll = graphicsNode["iconScroll"].String();
  864. const JsonNode & soundsNode = json["sounds"];
  865. spell->castSound = soundsNode["cast"].String();
  866. //load level attributes
  867. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  868. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  869. {
  870. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  871. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  872. const si32 levelPower = levelNode["power"].Float();
  873. levelObject.description = levelNode["description"].String();
  874. levelObject.cost = levelNode["cost"].Float();
  875. levelObject.power = levelPower;
  876. levelObject.AIValue = levelNode["aiValue"].Float();
  877. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  878. levelObject.range = levelNode["range"].String();
  879. for(const auto & elem : levelNode["effects"].Struct())
  880. {
  881. const JsonNode & bonusNode = elem.second;
  882. Bonus * b = JsonUtils::parseBonus(bonusNode);
  883. const bool usePowerAsValue = bonusNode["val"].isNull();
  884. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  885. //b->sid = spell->id; //for all
  886. b->source = Bonus::SPELL_EFFECT;//for all
  887. if(usePowerAsValue)
  888. b->val = levelPower;
  889. levelObject.effects.push_back(*b);
  890. }
  891. }
  892. return spell;
  893. }
  894. void CSpellHandler::afterLoadFinalization()
  895. {
  896. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  897. for(auto spell: objects)
  898. {
  899. for(auto & level: spell->levels)
  900. for(auto & bonus: level.effects)
  901. bonus.sid = spell->id;
  902. spell->setupMechanics();
  903. }
  904. }
  905. void CSpellHandler::beforeValidate(JsonNode & object)
  906. {
  907. //handle "base" level info
  908. JsonNode& levels = object["levels"];
  909. JsonNode& base = levels["base"];
  910. auto inheritNode = [&](const std::string & name){
  911. JsonUtils::inherit(levels[name],base);
  912. };
  913. inheritNode("none");
  914. inheritNode("basic");
  915. inheritNode("advanced");
  916. inheritNode("expert");
  917. }
  918. CSpellHandler::~CSpellHandler()
  919. {
  920. }
  921. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  922. {
  923. std::vector<bool> allowedSpells;
  924. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  925. return allowedSpells;
  926. }