CSpellHandler.cpp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. /*
  2. * CSpellHandler.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 <cctype>
  12. #include "CSpellHandler.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../JsonNode.h"
  16. #include "../CModHandler.h"
  17. #include "../StringConstants.h"
  18. #include "../BattleState.h"
  19. #include "../CBattleCallback.h"
  20. #include "../CGameState.h" //todo: remove
  21. #include "../NetPacks.h" //todo: remove
  22. #include "ISpellMechanics.h"
  23. namespace SpellConfig
  24. {
  25. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  26. static const SpellSchoolInfo SCHOOL[4] =
  27. {
  28. {
  29. ESpellSchool::AIR,
  30. Bonus::AIR_SPELL_DMG_PREMY,
  31. Bonus::AIR_IMMUNITY,
  32. "air",
  33. SecondarySkill::AIR_MAGIC,
  34. Bonus::AIR_SPELLS
  35. },
  36. {
  37. ESpellSchool::FIRE,
  38. Bonus::FIRE_SPELL_DMG_PREMY,
  39. Bonus::FIRE_IMMUNITY,
  40. "fire",
  41. SecondarySkill::FIRE_MAGIC,
  42. Bonus::FIRE_SPELLS
  43. },
  44. {
  45. ESpellSchool::WATER,
  46. Bonus::WATER_SPELL_DMG_PREMY,
  47. Bonus::WATER_IMMUNITY,
  48. "water",
  49. SecondarySkill::WATER_MAGIC,
  50. Bonus::WATER_SPELLS
  51. },
  52. {
  53. ESpellSchool::EARTH,
  54. Bonus::EARTH_SPELL_DMG_PREMY,
  55. Bonus::EARTH_IMMUNITY,
  56. "earth",
  57. SecondarySkill::EARTH_MAGIC,
  58. Bonus::EARTH_SPELLS
  59. }
  60. };
  61. }
  62. ///CSpell::LevelInfo
  63. CSpell::LevelInfo::LevelInfo()
  64. :description(""),cost(0),power(0),AIValue(0),smartTarget(true), clearTarget(false), clearAffected(false), range("0")
  65. {
  66. }
  67. CSpell::LevelInfo::~LevelInfo()
  68. {
  69. }
  70. ///CSpell
  71. CSpell::CSpell():
  72. id(SpellID::NONE), level(0),
  73. combatSpell(false), creatureAbility(false),
  74. positiveness(ESpellPositiveness::NEUTRAL),
  75. defaultProbability(0),
  76. isRising(false), isDamage(false), isOffensive(false),
  77. targetType(ETargetType::NO_TARGET),
  78. mechanics(),
  79. adventureMechanics()
  80. {
  81. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  82. }
  83. CSpell::~CSpell()
  84. {
  85. }
  86. void CSpell::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  87. {
  88. mechanics->applyBattle(battle, packet);
  89. }
  90. bool CSpell::adventureCast(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  91. {
  92. assert(env);
  93. if(!adventureMechanics.get())
  94. {
  95. env->complain("Invalid adventure spell cast attempt!");
  96. return false;
  97. }
  98. return adventureMechanics->adventureCast(env, parameters);
  99. }
  100. void CSpell::battleCast(const SpellCastEnvironment * env, const BattleSpellCastParameters & parameters) const
  101. {
  102. assert(env);
  103. if(parameters.destinations.size()<1)
  104. {
  105. env->complain("Spell must have at least one destination");
  106. return;
  107. }
  108. mechanics->battleCast(env, parameters);
  109. }
  110. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  111. {
  112. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  113. {
  114. logGlobal->error("CSpell::getLevelInfo invalid school level %d", level);
  115. throw new std::runtime_error("Invalid school level");
  116. }
  117. return levels.at(level);
  118. }
  119. ui32 CSpell::calculateDamage(const ISpellCaster * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  120. {
  121. //check if spell really does damage - if not, return 0
  122. if(!isDamageSpell())
  123. return 0;
  124. return adjustRawDamage(caster, affectedCreature, calculateRawEffectValue(spellSchoolLevel, usedSpellPower));
  125. }
  126. ESpellCastProblem::ESpellCastProblem CSpell::canBeCast(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster) const
  127. {
  128. const ESpellCastProblem::ESpellCastProblem generalProblem = mechanics->canBeCast(cb, mode, caster);
  129. if(generalProblem != ESpellCastProblem::OK)
  130. return generalProblem;
  131. //check for creature target existence
  132. if(mechanics->requiresCreatureTarget())
  133. {
  134. switch(mode)
  135. {
  136. case ECastingMode::HERO_CASTING:
  137. case ECastingMode::CREATURE_ACTIVE_CASTING:
  138. case ECastingMode::ENCHANTER_CASTING:
  139. case ECastingMode::PASSIVE_CASTING:
  140. {
  141. TargetInfo tinfo(this, caster->getSpellSchoolLevel(this), mode);
  142. bool targetExists = false;
  143. for(const CStack * stack : cb->battleGetAllStacks())
  144. {
  145. bool immune = !(stack->isValidTarget(!tinfo.onlyAlive) && ESpellCastProblem::OK == isImmuneByStack(caster, stack));
  146. bool casterStack = stack->owner == caster->getOwner();
  147. if(!immune)
  148. {
  149. switch (positiveness)
  150. {
  151. case CSpell::POSITIVE:
  152. if(casterStack || !tinfo.smart)
  153. targetExists = true;
  154. break;
  155. case CSpell::NEUTRAL:
  156. targetExists = true;
  157. break;
  158. case CSpell::NEGATIVE:
  159. if(!casterStack || !tinfo.smart)
  160. targetExists = true;
  161. break;
  162. }
  163. }
  164. if(targetExists)
  165. break;
  166. }
  167. if(!targetExists)
  168. {
  169. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  170. }
  171. }
  172. break;
  173. }
  174. }
  175. return ESpellCastProblem::OK;
  176. }
  177. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  178. {
  179. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  180. }
  181. std::vector<const CStack *> CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster, int spellLvl, BattleHex destination) const
  182. {
  183. SpellTargetingContext ctx(this, mode, caster, spellLvl, destination);
  184. return mechanics->getAffectedStacks(cb, ctx);
  185. }
  186. CSpell::ETargetType CSpell::getTargetType() const
  187. {
  188. return targetType;
  189. }
  190. void CSpell::forEachSchool(const std::function<void(const SpellSchoolInfo &, bool &)>& cb) const
  191. {
  192. bool stop = false;
  193. for(const SpellSchoolInfo & cnf : SpellConfig::SCHOOL)
  194. {
  195. if(school.at(cnf.id))
  196. {
  197. cb(cnf, stop);
  198. if(stop)
  199. break;
  200. }
  201. }
  202. }
  203. bool CSpell::isCombatSpell() const
  204. {
  205. return combatSpell;
  206. }
  207. bool CSpell::isAdventureSpell() const
  208. {
  209. return !combatSpell;
  210. }
  211. bool CSpell::isCreatureAbility() const
  212. {
  213. return creatureAbility;
  214. }
  215. bool CSpell::isPositive() const
  216. {
  217. return positiveness == POSITIVE;
  218. }
  219. bool CSpell::isNegative() const
  220. {
  221. return positiveness == NEGATIVE;
  222. }
  223. bool CSpell::isNeutral() const
  224. {
  225. return positiveness == NEUTRAL;
  226. }
  227. boost::logic::tribool CSpell::getPositiveness() const
  228. {
  229. switch (positiveness)
  230. {
  231. case CSpell::POSITIVE:
  232. return true;
  233. case CSpell::NEGATIVE:
  234. return false;
  235. default:
  236. return boost::logic::indeterminate;
  237. }
  238. }
  239. bool CSpell::isRisingSpell() const
  240. {
  241. return isRising;
  242. }
  243. bool CSpell::isDamageSpell() const
  244. {
  245. return isDamage;
  246. }
  247. bool CSpell::isOffensiveSpell() const
  248. {
  249. return isOffensive;
  250. }
  251. bool CSpell::isSpecialSpell() const
  252. {
  253. return isSpecial;
  254. }
  255. bool CSpell::hasEffects() const
  256. {
  257. return !levels[0].effects.empty();
  258. }
  259. const std::string & CSpell::getIconImmune() const
  260. {
  261. return iconImmune;
  262. }
  263. const std::string & CSpell::getCastSound() const
  264. {
  265. return castSound;
  266. }
  267. si32 CSpell::getCost(const int skillLevel) const
  268. {
  269. return getLevelInfo(skillLevel).cost;
  270. }
  271. si32 CSpell::getPower(const int skillLevel) const
  272. {
  273. return getLevelInfo(skillLevel).power;
  274. }
  275. si32 CSpell::getProbability(const TFaction factionId) const
  276. {
  277. if(!vstd::contains(probabilities,factionId))
  278. {
  279. return defaultProbability;
  280. }
  281. return probabilities.at(factionId);
  282. }
  283. void CSpell::getEffects(std::vector<Bonus> & lst, const int level) const
  284. {
  285. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  286. {
  287. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  288. return;
  289. }
  290. const std::vector<Bonus> & effects = levels[level].effects;
  291. if(effects.empty())
  292. {
  293. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  294. return;
  295. }
  296. lst.reserve(lst.size() + effects.size());
  297. for(const Bonus & b : effects)
  298. {
  299. lst.push_back(Bonus(b));
  300. }
  301. }
  302. ESpellCastProblem::ESpellCastProblem CSpell::canBeCastAt(const CBattleInfoCallback * cb, const ISpellCaster * caster, ECastingMode::ECastingMode mode, BattleHex destination) const
  303. {
  304. SpellTargetingContext ctx(this, mode, caster, caster->getSpellSchoolLevel(this), destination);
  305. return mechanics->canBeCast(cb, ctx);
  306. }
  307. int CSpell::adjustRawDamage(const ISpellCaster * caster, const CStack * affectedCreature, int rawDamage) const
  308. {
  309. int ret = rawDamage;
  310. //affected creature-specific part
  311. if(nullptr != affectedCreature)
  312. {
  313. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  314. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  315. {
  316. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  317. {
  318. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  319. ret /= 100;
  320. stop = true;//only bonus from one school is used
  321. }
  322. });
  323. //general spell dmg reduction
  324. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  325. {
  326. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  327. ret /= 100;
  328. }
  329. //dmg increasing
  330. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  331. {
  332. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  333. ret /= 100;
  334. }
  335. }
  336. if(caster != nullptr)
  337. ret = caster->getSpellBonus(this, ret, affectedCreature);
  338. return ret;
  339. }
  340. int CSpell::calculateRawEffectValue(int effectLevel, int effectPower) const
  341. {
  342. return effectPower * power + getPower(effectLevel);
  343. }
  344. ESpellCastProblem::ESpellCastProblem CSpell::internalIsImmune(const ISpellCaster * caster, const CStack *obj) const
  345. {
  346. //todo: use new bonus API
  347. //1. Check absolute limiters
  348. for(auto b : absoluteLimiters)
  349. {
  350. if (!obj->hasBonusOfType(b))
  351. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  352. }
  353. //2. Check absolute immunities
  354. for(auto b : absoluteImmunities)
  355. {
  356. if (obj->hasBonusOfType(b))
  357. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  358. }
  359. {
  360. //spell-based spell immunity (only ANTIMAGIC in OH3) is treated as absolute
  361. std::stringstream cachingStr;
  362. cachingStr << "type_" << Bonus::LEVEL_SPELL_IMMUNITY << "source_" << Bonus::SPELL_EFFECT;
  363. TBonusListPtr levelImmunitiesFromSpell = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY).And(Selector::sourceType(Bonus::SPELL_EFFECT)), cachingStr.str());
  364. if(levelImmunitiesFromSpell->size() > 0 && levelImmunitiesFromSpell->totalValue() >= level && level)
  365. {
  366. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  367. }
  368. }
  369. {
  370. //SPELL_IMMUNITY absolute case
  371. std::stringstream cachingStr;
  372. cachingStr << "type_" << Bonus::SPELL_IMMUNITY << "subtype_" << id.toEnum() << "addInfo_1";
  373. if(obj->hasBonus(Selector::typeSubtypeInfo(Bonus::SPELL_IMMUNITY, id.toEnum(), 1), cachingStr.str()))
  374. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  375. }
  376. //check receptivity
  377. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  378. return ESpellCastProblem::OK;
  379. //3. Check negation
  380. //Orb of vulnerability
  381. //FIXME: Orb of vulnerability mechanics is not such trivial (issue 1791)
  382. const bool battleWideNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 0);
  383. const bool heroNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 1);
  384. //anyone can cast on artifact holder`s stacks
  385. if(heroNegation)
  386. return ESpellCastProblem::NOT_DECIDED;
  387. //this stack is from other player
  388. //todo: check that caster is always present (not trivial is this case)
  389. //todo: NEGATE_ALL_NATURAL_IMMUNITIES special cases: dispell, chain lightning
  390. else if(battleWideNegation && caster)
  391. {
  392. if(obj->owner != caster->getOwner())
  393. return ESpellCastProblem::NOT_DECIDED;
  394. }
  395. //4. Check negatable limit
  396. for(auto b : limiters)
  397. {
  398. if (!obj->hasBonusOfType(b))
  399. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  400. }
  401. //5. Check negatable immunities
  402. for(auto b : immunities)
  403. {
  404. if (obj->hasBonusOfType(b))
  405. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  406. }
  407. //6. Check elemental immunities
  408. ESpellCastProblem::ESpellCastProblem tmp = ESpellCastProblem::NOT_DECIDED;
  409. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  410. {
  411. auto element = cnf.immunityBonus;
  412. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  413. {
  414. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  415. stop = true;
  416. }
  417. else if(!isPositive()) //negative or indifferent
  418. {
  419. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  420. {
  421. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  422. stop = true;
  423. }
  424. }
  425. });
  426. if(tmp != ESpellCastProblem::NOT_DECIDED)
  427. return tmp;
  428. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  429. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  430. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  431. {
  432. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  433. }
  434. return ESpellCastProblem::NOT_DECIDED;
  435. }
  436. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const ISpellCaster * caster, const CStack * obj) const
  437. {
  438. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  439. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  440. return immuneResult;
  441. return ESpellCastProblem::OK;
  442. }
  443. void CSpell::setIsOffensive(const bool val)
  444. {
  445. isOffensive = val;
  446. if(val)
  447. {
  448. positiveness = CSpell::NEGATIVE;
  449. isDamage = true;
  450. }
  451. }
  452. void CSpell::setIsRising(const bool val)
  453. {
  454. isRising = val;
  455. if(val)
  456. {
  457. positiveness = CSpell::POSITIVE;
  458. }
  459. }
  460. void CSpell::setup()
  461. {
  462. setupMechanics();
  463. }
  464. void CSpell::setupMechanics()
  465. {
  466. mechanics = ISpellMechanics::createMechanics(this);
  467. adventureMechanics = IAdventureSpellMechanics::createMechanics(this);
  468. }
  469. ///CSpell::AnimationInfo
  470. CSpell::AnimationItem::AnimationItem()
  471. :resourceName(""),verticalPosition(VerticalPosition::TOP),pause(0)
  472. {
  473. }
  474. ///CSpell::AnimationInfo
  475. CSpell::AnimationInfo::AnimationInfo()
  476. {
  477. }
  478. CSpell::AnimationInfo::~AnimationInfo()
  479. {
  480. }
  481. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  482. {
  483. std::string res;
  484. double maximum = 0.0;
  485. for(const auto & info : projectile)
  486. {
  487. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  488. {
  489. maximum = info.minimumAngle;
  490. res = info.resourceName;
  491. }
  492. }
  493. return res;
  494. }
  495. ///CSpell::TargetInfo
  496. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  497. {
  498. init(spell, level);
  499. }
  500. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  501. {
  502. init(spell, level);
  503. if(mode == ECastingMode::ENCHANTER_CASTING)
  504. {
  505. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  506. massive = true;
  507. }
  508. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  509. {
  510. alwaysHitDirectly = true;
  511. }
  512. else if(mode == ECastingMode::CREATURE_ACTIVE_CASTING)
  513. {
  514. massive = false;//FIXME: find better solution for Commander spells
  515. }
  516. }
  517. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  518. {
  519. auto & levelInfo = spell->getLevelInfo(level);
  520. type = spell->getTargetType();
  521. smart = levelInfo.smartTarget;
  522. massive = levelInfo.range == "X";
  523. onlyAlive = !spell->isRisingSpell();
  524. alwaysHitDirectly = false;
  525. clearAffected = levelInfo.clearAffected;
  526. clearTarget = levelInfo.clearTarget;
  527. }
  528. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  529. {
  530. int3 diff = pos - center;
  531. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  532. return true;
  533. else
  534. return false;
  535. }
  536. ///CSpellHandler
  537. CSpellHandler::CSpellHandler()
  538. {
  539. }
  540. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  541. {
  542. using namespace SpellConfig;
  543. std::vector<JsonNode> legacyData;
  544. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  545. auto readSchool = [&](JsonMap & schools, const std::string & name)
  546. {
  547. if (parser.readString() == "x")
  548. {
  549. schools[name].Bool() = true;
  550. }
  551. };
  552. auto read = [&,this](bool combat, bool ability)
  553. {
  554. do
  555. {
  556. JsonNode lineNode(JsonNode::DATA_STRUCT);
  557. const si32 id = legacyData.size();
  558. lineNode["index"].Float() = id;
  559. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  560. lineNode["name"].String() = parser.readString();
  561. parser.readString(); //ignored unused abbreviated name
  562. lineNode["level"].Float() = parser.readNumber();
  563. auto& schools = lineNode["school"].Struct();
  564. readSchool(schools, "earth");
  565. readSchool(schools, "water");
  566. readSchool(schools, "fire");
  567. readSchool(schools, "air");
  568. auto& levels = lineNode["levels"].Struct();
  569. auto getLevel = [&](const size_t idx)->JsonMap&
  570. {
  571. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  572. return levels[LEVEL_NAMES[idx]].Struct();
  573. };
  574. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  575. lineNode["power"].Float() = parser.readNumber();
  576. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  577. auto& chances = lineNode["gainChance"].Struct();
  578. for(size_t i = 0; i < GameConstants::F_NUMBER; i++){
  579. chances[ETownType::names[i]].Float() = parser.readNumber();
  580. }
  581. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  582. std::vector<std::string> descriptions;
  583. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  584. descriptions.push_back(parser.readString());
  585. parser.readString(); //ignore attributes. All data present in JSON
  586. //save parsed level specific data
  587. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  588. {
  589. auto& level = getLevel(i);
  590. level["description"].String() = descriptions[i];
  591. level["cost"].Float() = costs[i];
  592. level["power"].Float() = powers[i];
  593. level["aiValue"].Float() = AIVals[i];
  594. }
  595. legacyData.push_back(lineNode);
  596. }
  597. while (parser.endLine() && !parser.isNextEntryEmpty());
  598. };
  599. auto skip = [&](int cnt)
  600. {
  601. for(int i=0; i<cnt; i++)
  602. parser.endLine();
  603. };
  604. skip(5);// header
  605. read(false,false); //read adventure map spells
  606. skip(3);
  607. read(true,false); //read battle spells
  608. skip(3);
  609. read(true,true);//read creature abilities
  610. //TODO: maybe move to config
  611. //clone Acid Breath attributes for Acid Breath damage effect
  612. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  613. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  614. legacyData.push_back(temp);
  615. objects.resize(legacyData.size());
  616. return legacyData;
  617. }
  618. const std::string CSpellHandler::getTypeName() const
  619. {
  620. return "spell";
  621. }
  622. CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & identifier)
  623. {
  624. using namespace SpellConfig;
  625. CSpell * spell = new CSpell();
  626. spell->identifier = identifier;
  627. const auto type = json["type"].String();
  628. if(type == "ability")
  629. {
  630. spell->creatureAbility = true;
  631. spell->combatSpell = true;
  632. }
  633. else
  634. {
  635. spell->creatureAbility = false;
  636. spell->combatSpell = type == "combat";
  637. }
  638. spell->name = json["name"].String();
  639. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  640. const auto schoolNames = json["school"];
  641. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  642. {
  643. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  644. }
  645. spell->level = json["level"].Float();
  646. spell->power = json["power"].Float();
  647. spell->defaultProbability = json["defaultGainChance"].Float();
  648. for(const auto & node : json["gainChance"].Struct())
  649. {
  650. const int chance = node.second.Float();
  651. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  652. {
  653. spell->probabilities[factionID] = chance;
  654. });
  655. }
  656. auto targetType = json["targetType"].String();
  657. if(targetType == "NO_TARGET")
  658. spell->targetType = CSpell::NO_TARGET;
  659. else if(targetType == "CREATURE")
  660. spell->targetType = CSpell::CREATURE;
  661. else if(targetType == "OBSTACLE")
  662. spell->targetType = CSpell::OBSTACLE;
  663. else if(targetType == "LOCATION")
  664. spell->targetType = CSpell::LOCATION;
  665. else
  666. logGlobal->warnStream() << "Spell " << spell->name << ": target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ", assumed NO_TARGET.";
  667. for(const auto & counteredSpell: json["counters"].Struct())
  668. if (counteredSpell.second.Bool())
  669. {
  670. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  671. {
  672. spell->counteredSpells.push_back(SpellID(id));
  673. });
  674. }
  675. //TODO: more error checking - f.e. conflicting flags
  676. const auto flags = json["flags"];
  677. //by default all flags are set to false in constructor
  678. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  679. if(flags["offensive"].Bool())
  680. {
  681. spell->setIsOffensive(true);
  682. }
  683. if(flags["rising"].Bool())
  684. {
  685. spell->setIsRising(true);
  686. }
  687. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  688. if(flags["indifferent"].Bool())
  689. {
  690. spell->positiveness = CSpell::NEUTRAL;
  691. }
  692. else if(flags["negative"].Bool())
  693. {
  694. spell->positiveness = CSpell::NEGATIVE;
  695. }
  696. else if(flags["positive"].Bool())
  697. {
  698. spell->positiveness = CSpell::POSITIVE;
  699. }
  700. else if(!implicitPositiveness)
  701. {
  702. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  703. logGlobal->errorStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL.";
  704. }
  705. spell->isSpecial = flags["special"].Bool();
  706. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  707. {
  708. auto it = bonusNameMap.find(name);
  709. if(it == bonusNameMap.end())
  710. {
  711. logGlobal->errorStream() << "Spell " << spell->name << ": invalid bonus name " << name;
  712. }
  713. else
  714. {
  715. vec.push_back((Bonus::BonusType)it->second);
  716. }
  717. };
  718. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  719. {
  720. for(auto bonusData: json[name].Struct())
  721. {
  722. const std::string bonusId = bonusData.first;
  723. const bool flag = bonusData.second.Bool();
  724. if(flag)
  725. findBonus(bonusId, vec);
  726. }
  727. };
  728. readBonusStruct("immunity", spell->immunities);
  729. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  730. readBonusStruct("limit", spell->limiters);
  731. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  732. const JsonNode & graphicsNode = json["graphics"];
  733. spell->iconImmune = graphicsNode["iconImmune"].String();
  734. spell->iconBook = graphicsNode["iconBook"].String();
  735. spell->iconEffect = graphicsNode["iconEffect"].String();
  736. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  737. spell->iconScroll = graphicsNode["iconScroll"].String();
  738. const JsonNode & animationNode = json["animation"];
  739. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  740. {
  741. auto queueNode = animationNode[jsonName].Vector();
  742. for(const JsonNode & item : queueNode)
  743. {
  744. CSpell::TAnimation newItem;
  745. if(item.getType() == JsonNode::DATA_STRING)
  746. newItem.resourceName = item.String();
  747. else if(item.getType() == JsonNode::DATA_STRUCT)
  748. {
  749. newItem.resourceName = item["defName"].String();
  750. auto vPosStr = item["verticalPosition"].String();
  751. if("bottom" == vPosStr)
  752. newItem.verticalPosition = VerticalPosition::BOTTOM;
  753. }
  754. else if(item.getType() == JsonNode::DATA_FLOAT)
  755. {
  756. newItem.pause = item.Float();
  757. }
  758. q.push_back(newItem);
  759. }
  760. };
  761. loadAnimationQueue("affect", spell->animationInfo.affect);
  762. loadAnimationQueue("cast", spell->animationInfo.cast);
  763. loadAnimationQueue("hit", spell->animationInfo.hit);
  764. const JsonVector & projectile = animationNode["projectile"].Vector();
  765. for(const JsonNode & item : projectile)
  766. {
  767. CSpell::ProjectileInfo info;
  768. info.resourceName = item["defName"].String();
  769. info.minimumAngle = item["minimumAngle"].Float();
  770. spell->animationInfo.projectile.push_back(info);
  771. }
  772. const JsonNode & soundsNode = json["sounds"];
  773. spell->castSound = soundsNode["cast"].String();
  774. //load level attributes
  775. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  776. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  777. {
  778. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  779. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  780. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  781. levelObject.description = levelNode["description"].String();
  782. levelObject.cost = levelNode["cost"].Float();
  783. levelObject.AIValue = levelNode["aiValue"].Float();
  784. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  785. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  786. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  787. levelObject.range = levelNode["range"].String();
  788. for(const auto & elem : levelNode["effects"].Struct())
  789. {
  790. const JsonNode & bonusNode = elem.second;
  791. auto b = JsonUtils::parseBonus(bonusNode);
  792. const bool usePowerAsValue = bonusNode["val"].isNull();
  793. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  794. //b->sid = spell->id; //for all
  795. b->source = Bonus::SPELL_EFFECT;//for all
  796. if(usePowerAsValue)
  797. b->val = levelPower;
  798. levelObject.effectsTmp.push_back(b);
  799. }
  800. }
  801. return spell;
  802. }
  803. void CSpellHandler::afterLoadFinalization()
  804. {
  805. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  806. for(auto spell: objects)
  807. {
  808. for(auto & level: spell->levels)
  809. {
  810. for(auto bonus : level.effectsTmp)
  811. {
  812. level.effects.push_back(*bonus);
  813. }
  814. level.effectsTmp.clear();
  815. for(auto & bonus: level.effects)
  816. bonus.sid = spell->id;
  817. }
  818. spell->setup();
  819. }
  820. }
  821. void CSpellHandler::beforeValidate(JsonNode & object)
  822. {
  823. //handle "base" level info
  824. JsonNode & levels = object["levels"];
  825. JsonNode & base = levels["base"];
  826. auto inheritNode = [&](const std::string & name){
  827. JsonUtils::inherit(levels[name],base);
  828. };
  829. inheritNode("none");
  830. inheritNode("basic");
  831. inheritNode("advanced");
  832. inheritNode("expert");
  833. }
  834. CSpellHandler::~CSpellHandler()
  835. {
  836. }
  837. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  838. {
  839. std::vector<bool> allowedSpells;
  840. allowedSpells.reserve(objects.size());
  841. for(const CSpell * s : objects)
  842. {
  843. allowedSpells.push_back( !(s->isSpecialSpell() || s->isCreatureAbility()));
  844. }
  845. return allowedSpells;
  846. }
  847. si32 CSpellHandler::decodeSpell(const std::string& identifier)
  848. {
  849. auto rawId = VLC->modh->identifiers.getIdentifier("core", "spell", identifier);
  850. if(rawId)
  851. return rawId.get();
  852. else
  853. return -1;
  854. }
  855. std::string CSpellHandler::encodeSpell(const si32 index)
  856. {
  857. return VLC->spellh->objects[index]->identifier;
  858. }