CSpellHandler.cpp 27 KB

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