CSpellHandler.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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 "Problem.h"
  14. #include <vcmi/spells/Caster.h>
  15. #include "../filesystem/Filesystem.h"
  16. #include "../constants/StringConstants.h"
  17. #include "../battle/BattleInfo.h"
  18. #include "../battle/CBattleInfoCallback.h"
  19. #include "../battle/Unit.h"
  20. #include "../json/JsonBonus.h"
  21. #include "../json/JsonUtils.h"
  22. #include "../mapObjects/CGHeroInstance.h" //todo: remove
  23. #include "../modding/IdentifierStorage.h"
  24. #include "../modding/ModUtility.h"
  25. #include "../serializer/CSerializer.h"
  26. #include "../texts/CLegacyConfigParser.h"
  27. #include "../texts/CGeneralTextHandler.h"
  28. #include "ISpellMechanics.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. namespace SpellConfig
  31. {
  32. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  33. const spells::SchoolInfo SCHOOL[4] =
  34. {
  35. {
  36. SpellSchool::AIR,
  37. "air"
  38. },
  39. {
  40. SpellSchool::FIRE,
  41. "fire"
  42. },
  43. {
  44. SpellSchool::WATER,
  45. "water"
  46. },
  47. {
  48. SpellSchool::EARTH,
  49. "earth"
  50. }
  51. };
  52. //order as described in http://bugs.vcmi.eu/view.php?id=91
  53. static const SpellSchool SCHOOL_ORDER[4] =
  54. {
  55. SpellSchool::AIR, //=0
  56. SpellSchool::FIRE, //=1
  57. SpellSchool::EARTH,//=3(!)
  58. SpellSchool::WATER //=2(!)
  59. };
  60. } //namespace SpellConfig
  61. ///CSpell
  62. CSpell::CSpell():
  63. id(SpellID::NONE),
  64. level(0),
  65. power(0),
  66. combat(false),
  67. creatureAbility(false),
  68. castOnSelf(false),
  69. positiveness(ESpellPositiveness::NEUTRAL),
  70. defaultProbability(0),
  71. rising(false),
  72. damage(false),
  73. offensive(false),
  74. special(true),
  75. nonMagical(false),
  76. targetType(spells::AimType::NO_TARGET)
  77. {
  78. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  79. }
  80. //must be instantiated in .cpp file for access to complete types of all member fields
  81. CSpell::~CSpell() = default;
  82. bool CSpell::adventureCast(SpellCastEnvironment * env, const AdventureSpellCastParameters & parameters) const
  83. {
  84. assert(env);
  85. if(!adventureMechanics)
  86. {
  87. env->complain("Invalid adventure spell cast attempt!");
  88. return false;
  89. }
  90. return adventureMechanics->adventureCast(env, parameters);
  91. }
  92. const CSpell::LevelInfo & CSpell::getLevelInfo(const int32_t level) const
  93. {
  94. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  95. {
  96. logGlobal->error("CSpell::getLevelInfo: invalid school mastery level %d", level);
  97. return levels.at(MasteryLevel::EXPERT);
  98. }
  99. return levels.at(level);
  100. }
  101. int64_t CSpell::calculateDamage(const spells::Caster * caster) const
  102. {
  103. //check if spell really does damage - if not, return 0
  104. if(!isDamage())
  105. return 0;
  106. auto rawDamage = calculateRawEffectValue(caster->getEffectLevel(this), caster->getEffectPower(this), 1);
  107. return caster->getSpellBonus(this, rawDamage, nullptr);
  108. }
  109. bool CSpell::hasSchool(SpellSchool which) const
  110. {
  111. return school.count(which) && school.at(which);
  112. }
  113. bool CSpell::canBeCast(const CBattleInfoCallback * cb, spells::Mode mode, const spells::Caster * caster) const
  114. {
  115. //if caller do not interested in description just discard it and do not pollute even debug log
  116. spells::detail::ProblemImpl problem;
  117. return canBeCast(problem, cb, mode, caster);
  118. }
  119. bool CSpell::canBeCast(spells::Problem & problem, const CBattleInfoCallback * cb, spells::Mode mode, const spells::Caster * caster) const
  120. {
  121. spells::BattleCast event(cb, caster, mode, this);
  122. auto mechanics = battleMechanics(&event);
  123. return mechanics->canBeCast(problem);
  124. }
  125. spells::AimType CSpell::getTargetType() const
  126. {
  127. return targetType;
  128. }
  129. void CSpell::forEachSchool(const std::function<void(const SpellSchool &, bool &)>& cb) const
  130. {
  131. bool stop = false;
  132. for(auto iter : SpellConfig::SCHOOL_ORDER)
  133. {
  134. const spells::SchoolInfo & cnf = SpellConfig::SCHOOL[iter.getNum()];
  135. if(school.at(cnf.id))
  136. {
  137. cb(cnf.id, stop);
  138. if(stop)
  139. break;
  140. }
  141. }
  142. }
  143. SpellID CSpell::getId() const
  144. {
  145. return id;
  146. }
  147. std::string CSpell::getNameTextID() const
  148. {
  149. TextIdentifier id("spell", modScope, identifier, "name");
  150. return id.get();
  151. }
  152. std::string CSpell::getNameTranslated() const
  153. {
  154. return VLC->generaltexth->translate(getNameTextID());
  155. }
  156. std::string CSpell::getDescriptionTextID(int32_t level) const
  157. {
  158. TextIdentifier id("spell", modScope, identifier, "description", SpellConfig::LEVEL_NAMES[level]);
  159. return id.get();
  160. }
  161. std::string CSpell::getDescriptionTranslated(int32_t level) const
  162. {
  163. return VLC->generaltexth->translate(getDescriptionTextID(level));
  164. }
  165. std::string CSpell::getJsonKey() const
  166. {
  167. return modScope + ':' + identifier;
  168. }
  169. std::string CSpell::getModScope() const
  170. {
  171. return modScope;
  172. }
  173. int32_t CSpell::getIndex() const
  174. {
  175. return id.toEnum();
  176. }
  177. int32_t CSpell::getIconIndex() const
  178. {
  179. return getIndex();
  180. }
  181. int32_t CSpell::getLevel() const
  182. {
  183. return level;
  184. }
  185. bool CSpell::isCombat() const
  186. {
  187. return combat;
  188. }
  189. bool CSpell::isAdventure() const
  190. {
  191. return !combat;
  192. }
  193. bool CSpell::isCreatureAbility() const
  194. {
  195. return creatureAbility;
  196. }
  197. bool CSpell::isMagical() const
  198. {
  199. return !nonMagical;
  200. }
  201. bool CSpell::isPositive() const
  202. {
  203. return positiveness == POSITIVE;
  204. }
  205. bool CSpell::isNegative() const
  206. {
  207. return positiveness == NEGATIVE;
  208. }
  209. bool CSpell::isNeutral() const
  210. {
  211. return positiveness == NEUTRAL;
  212. }
  213. boost::logic::tribool CSpell::getPositiveness() const
  214. {
  215. switch (positiveness)
  216. {
  217. case CSpell::POSITIVE:
  218. return true;
  219. case CSpell::NEGATIVE:
  220. return false;
  221. default:
  222. return boost::logic::indeterminate;
  223. }
  224. }
  225. bool CSpell::isDamage() const
  226. {
  227. return damage;
  228. }
  229. bool CSpell::isOffensive() const
  230. {
  231. return offensive;
  232. }
  233. bool CSpell::isSpecial() const
  234. {
  235. return special;
  236. }
  237. bool CSpell::hasEffects() const
  238. {
  239. return !levels[0].effects.empty() || !levels[0].cumulativeEffects.empty();
  240. }
  241. bool CSpell::hasBattleEffects() const
  242. {
  243. return levels[0].battleEffects.getType() == JsonNode::JsonType::DATA_STRUCT && !levels[0].battleEffects.Struct().empty();
  244. }
  245. bool CSpell::canCastOnSelf() const
  246. {
  247. return castOnSelf;
  248. }
  249. const std::string & CSpell::getIconImmune() const
  250. {
  251. return iconImmune;
  252. }
  253. const std::string & CSpell::getIconBook() const
  254. {
  255. return iconBook;
  256. }
  257. const std::string & CSpell::getIconEffect() const
  258. {
  259. return iconEffect;
  260. }
  261. const std::string & CSpell::getIconScenarioBonus() const
  262. {
  263. return iconScenarioBonus;
  264. }
  265. const std::string & CSpell::getIconScroll() const
  266. {
  267. return iconScroll;
  268. }
  269. const AudioPath & CSpell::getCastSound() const
  270. {
  271. return castSound;
  272. }
  273. int32_t CSpell::getCost(const int32_t skillLevel) const
  274. {
  275. return getLevelInfo(skillLevel).cost;
  276. }
  277. int32_t CSpell::getBasePower() const
  278. {
  279. return power;
  280. }
  281. int32_t CSpell::getLevelPower(const int32_t skillLevel) const
  282. {
  283. return getLevelInfo(skillLevel).power;
  284. }
  285. si32 CSpell::getProbability(const FactionID & factionId) const
  286. {
  287. if(!vstd::contains(probabilities,factionId))
  288. {
  289. return defaultProbability;
  290. }
  291. return probabilities.at(factionId);
  292. }
  293. void CSpell::getEffects(std::vector<Bonus> & lst, const int level, const bool cumulative, const si32 duration, std::optional<si32 *> maxDuration) const
  294. {
  295. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  296. {
  297. logGlobal->error("invalid school level %d", level);
  298. return;
  299. }
  300. const auto & levelObject = levels.at(level);
  301. if(levelObject.effects.empty() && levelObject.cumulativeEffects.empty())
  302. {
  303. logGlobal->error("This spell (%s) has no effects for level %d", getNameTranslated(), level);
  304. return;
  305. }
  306. const auto & effects = cumulative ? levelObject.cumulativeEffects : levelObject.effects;
  307. lst.reserve(lst.size() + effects.size());
  308. for(const auto& b : effects)
  309. {
  310. Bonus nb(*b);
  311. //use configured duration if present
  312. if(nb.turnsRemain == 0)
  313. nb.turnsRemain = duration;
  314. if(maxDuration)
  315. vstd::amax(*(maxDuration.value()), nb.turnsRemain);
  316. lst.push_back(nb);
  317. }
  318. }
  319. int64_t CSpell::adjustRawDamage(const spells::Caster * caster, const battle::Unit * affectedCreature, int64_t rawDamage) const
  320. {
  321. auto ret = rawDamage;
  322. //affected creature-specific part
  323. if(nullptr != affectedCreature)
  324. {
  325. const auto * bearer = affectedCreature->getBonusBearer();
  326. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  327. forEachSchool([&](const SpellSchool & cnf, bool & stop)
  328. {
  329. if(bearer->hasBonusOfType(BonusType::SPELL_DAMAGE_REDUCTION, BonusSubtypeID(cnf)))
  330. {
  331. ret *= 100 - bearer->valOfBonuses(BonusType::SPELL_DAMAGE_REDUCTION, BonusSubtypeID(cnf));
  332. ret /= 100;
  333. stop = true; //only bonus from one school is used
  334. }
  335. });
  336. CSelector selector = Selector::typeSubtype(BonusType::SPELL_DAMAGE_REDUCTION, BonusSubtypeID(SpellSchool::ANY));
  337. auto cachingStr = "type_SPELL_DAMAGE_REDUCTION_s_ANY";
  338. //general spell dmg reduction, works only on magical effects
  339. if(bearer->hasBonus(selector, cachingStr) && isMagical())
  340. {
  341. ret *= 100 - bearer->valOfBonuses(selector, cachingStr);
  342. ret /= 100;
  343. }
  344. //dmg increasing
  345. if(bearer->hasBonusOfType(BonusType::MORE_DAMAGE_FROM_SPELL, BonusSubtypeID(id)))
  346. {
  347. ret *= 100 + bearer->valOfBonuses(BonusType::MORE_DAMAGE_FROM_SPELL, BonusSubtypeID(id));
  348. ret /= 100;
  349. }
  350. //invincible
  351. if(bearer->hasBonusOfType(BonusType::INVINCIBLE))
  352. ret = 0;
  353. }
  354. ret = caster->getSpellBonus(this, ret, affectedCreature);
  355. return ret;
  356. }
  357. int64_t CSpell::calculateRawEffectValue(int32_t effectLevel, int32_t basePowerMultiplier, int32_t levelPowerMultiplier) const
  358. {
  359. return static_cast<int64_t>(basePowerMultiplier) * getBasePower() + levelPowerMultiplier * getLevelPower(effectLevel);
  360. }
  361. void CSpell::setIsOffensive(const bool val)
  362. {
  363. offensive = val;
  364. if(val)
  365. {
  366. positiveness = CSpell::NEGATIVE;
  367. damage = true;
  368. }
  369. }
  370. void CSpell::setIsRising(const bool val)
  371. {
  372. rising = val;
  373. if(val)
  374. {
  375. positiveness = CSpell::POSITIVE;
  376. }
  377. }
  378. JsonNode CSpell::convertTargetCondition(const BTVector & immunity, const BTVector & absImmunity, const BTVector & limit, const BTVector & absLimit) const
  379. {
  380. static const std::string CONDITION_NORMAL = "normal";
  381. static const std::string CONDITION_ABSOLUTE = "absolute";
  382. #define BONUS_NAME(x) { BonusType::x, #x },
  383. static const std::map<BonusType, std::string> bonusNameRMap = { BONUS_LIST };
  384. #undef BONUS_NAME
  385. JsonNode res;
  386. auto convertVector = [&](const std::string & targetName, const BTVector & source, const std::string & value)
  387. {
  388. for(auto bonusType : source)
  389. {
  390. auto iter = bonusNameRMap.find(bonusType);
  391. if(iter != bonusNameRMap.end())
  392. {
  393. auto fullId = ModUtility::makeFullIdentifier("", "bonus", iter->second);
  394. res[targetName][fullId].String() = value;
  395. }
  396. else
  397. {
  398. logGlobal->error("Invalid bonus type %d", static_cast<int32_t>(bonusType));
  399. }
  400. }
  401. };
  402. auto convertSection = [&](const std::string & targetName, const BTVector & normal, const BTVector & absolute)
  403. {
  404. convertVector(targetName, normal, CONDITION_NORMAL);
  405. convertVector(targetName, absolute, CONDITION_ABSOLUTE);
  406. };
  407. convertSection("allOf", limit, absLimit);
  408. convertSection("noneOf", immunity, absImmunity);
  409. return res;
  410. }
  411. void CSpell::setupMechanics()
  412. {
  413. mechanics = spells::ISpellMechanicsFactory::get(this);
  414. adventureMechanics = IAdventureSpellMechanics::createMechanics(this);
  415. }
  416. const IAdventureSpellMechanics & CSpell::getAdventureMechanics() const
  417. {
  418. return *adventureMechanics;
  419. }
  420. std::unique_ptr<spells::Mechanics> CSpell::battleMechanics(const spells::IBattleCast * event) const
  421. {
  422. return mechanics->create(event);
  423. }
  424. void CSpell::registerIcons(const IconRegistar & cb) const
  425. {
  426. cb(getIndex(), 0, "SPELLS", iconBook);
  427. cb(getIndex()+1, 0, "SPELLINT", iconEffect);
  428. cb(getIndex(), 0, "SPELLBON", iconScenarioBonus);
  429. cb(getIndex(), 0, "SPELLSCR", iconScroll);
  430. }
  431. void CSpell::updateFrom(const JsonNode & data)
  432. {
  433. //todo:CSpell::updateFrom
  434. }
  435. void CSpell::serializeJson(JsonSerializeFormat & handler)
  436. {
  437. }
  438. ///CSpell::AnimationInfo
  439. CSpell::AnimationItem::AnimationItem() :
  440. verticalPosition(VerticalPosition::TOP),
  441. pause(0)
  442. {
  443. }
  444. ///CSpell::AnimationInfo
  445. AnimationPath CSpell::AnimationInfo::selectProjectile(const double angle) const
  446. {
  447. AnimationPath res;
  448. double maximum = 0.0;
  449. for(const auto & info : projectile)
  450. {
  451. if(info.minimumAngle < angle && info.minimumAngle >= maximum)
  452. {
  453. maximum = info.minimumAngle;
  454. res = info.resourceName;
  455. }
  456. }
  457. return res;
  458. }
  459. ///CSpell::TargetInfo
  460. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, spells::Mode mode)
  461. : type(spell->getTargetType()),
  462. smart(false),
  463. massive(false),
  464. clearAffected(false),
  465. clearTarget(false)
  466. {
  467. const auto & levelInfo = spell->getLevelInfo(level);
  468. smart = levelInfo.smartTarget;
  469. massive = levelInfo.range.empty();
  470. clearAffected = levelInfo.clearAffected;
  471. clearTarget = levelInfo.clearTarget;
  472. }
  473. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  474. {
  475. int3 diff = pos - center;
  476. return diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8;
  477. }
  478. ///CSpellHandler
  479. std::vector<JsonNode> CSpellHandler::loadLegacyData()
  480. {
  481. using namespace SpellConfig;
  482. std::vector<JsonNode> legacyData;
  483. CLegacyConfigParser parser(TextPath::builtin("DATA/SPTRAITS.TXT"));
  484. auto readSchool = [&](JsonMap & schools, const std::string & name)
  485. {
  486. if (parser.readString() == "x")
  487. {
  488. schools[name].Bool() = true;
  489. }
  490. };
  491. auto read = [&](bool combat, bool ability)
  492. {
  493. do
  494. {
  495. JsonNode lineNode;
  496. const auto id = legacyData.size();
  497. lineNode["index"].Integer() = id;
  498. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  499. lineNode["name"].String() = parser.readString();
  500. parser.readString(); //ignored unused abbreviated name
  501. lineNode["level"].Integer() = static_cast<si64>(parser.readNumber());
  502. auto& schools = lineNode["school"].Struct();
  503. readSchool(schools, "earth");
  504. readSchool(schools, "water");
  505. readSchool(schools, "fire");
  506. readSchool(schools, "air");
  507. auto& levels = lineNode["levels"].Struct();
  508. auto getLevel = [&](const size_t idx)->JsonMap&
  509. {
  510. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  511. return levels[LEVEL_NAMES[idx]].Struct();
  512. };
  513. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  514. lineNode["power"].Integer() = static_cast<si64>(parser.readNumber());
  515. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  516. auto & chances = lineNode["gainChance"].Struct();
  517. for(const auto & name : NFaction::names)
  518. chances[name].Integer() = static_cast<si64>(parser.readNumber());
  519. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  520. std::vector<std::string> descriptions;
  521. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  522. descriptions.push_back(parser.readString());
  523. parser.readString(); //ignore attributes. All data present in JSON
  524. //save parsed level specific data
  525. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  526. {
  527. auto& level = getLevel(i);
  528. level["description"].String() = descriptions[i];
  529. level["cost"].Integer() = costs[i];
  530. level["power"].Integer() = powers[i];
  531. level["aiValue"].Integer() = AIVals[i];
  532. }
  533. legacyData.push_back(lineNode);
  534. }
  535. while (parser.endLine() && !parser.isNextEntryEmpty());
  536. };
  537. auto skip = [&](int cnt)
  538. {
  539. for(int i=0; i<cnt; i++)
  540. parser.endLine();
  541. };
  542. skip(5);// header
  543. read(false,false); //read adventure map spells
  544. skip(3);
  545. read(true,false); //read battle spells
  546. skip(3);
  547. read(true,true);//read creature abilities
  548. //TODO: maybe move to config
  549. //clone Acid Breath attributes for Acid Breath damage effect
  550. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  551. temp["index"].Integer() = SpellID::ACID_BREATH_DAMAGE;
  552. legacyData.push_back(temp);
  553. objects.resize(legacyData.size());
  554. return legacyData;
  555. }
  556. const std::vector<std::string> & CSpellHandler::getTypeNames() const
  557. {
  558. static const std::vector<std::string> typeNames = { "spell" };
  559. return typeNames;
  560. }
  561. std::vector<int> CSpellHandler::spellRangeInHexes(std::string input) const
  562. {
  563. std::set<BattleHex> ret;
  564. std::string rng = input + ','; //copy + artificial comma for easier handling
  565. if(rng.size() >= 2 && std::tolower(rng[0]) != 'x') //there is at least one hex in range (+artificial comma)
  566. {
  567. std::string number1;
  568. std::string number2;
  569. int beg = 0;
  570. int end = 0;
  571. bool readingFirst = true;
  572. for(auto & elem : rng)
  573. {
  574. if(std::isdigit(elem) ) //reading number
  575. {
  576. if(readingFirst)
  577. number1 += elem;
  578. else
  579. number2 += elem;
  580. }
  581. else if(elem == ',') //comma
  582. {
  583. //calculating variables
  584. if(readingFirst)
  585. {
  586. beg = std::stoi(number1);
  587. number1 = "";
  588. }
  589. else
  590. {
  591. end = std::stoi(number2);
  592. number2 = "";
  593. }
  594. //obtaining new hexes
  595. std::set<ui16> curLayer;
  596. if(readingFirst)
  597. {
  598. ret.insert(beg);
  599. }
  600. else
  601. {
  602. for(int i = beg; i <= end; ++i)
  603. ret.insert(i);
  604. }
  605. }
  606. else if(elem == '-') //dash
  607. {
  608. beg = std::stoi(number1);
  609. number1 = "";
  610. readingFirst = false;
  611. }
  612. }
  613. }
  614. return std::vector<int>(ret.begin(), ret.end());
  615. }
  616. std::shared_ptr<CSpell> CSpellHandler::loadFromJson(const std::string & scope, const JsonNode & json, const std::string & identifier, size_t index)
  617. {
  618. assert(identifier.find(':') == std::string::npos);
  619. assert(!scope.empty());
  620. using namespace SpellConfig;
  621. SpellID id(static_cast<si32>(index));
  622. auto spell = std::make_shared<CSpell>();
  623. spell->id = id;
  624. spell->identifier = identifier;
  625. spell->modScope = scope;
  626. const auto type = json["type"].String();
  627. if(type == "ability")
  628. {
  629. spell->creatureAbility = true;
  630. spell->combat = true;
  631. }
  632. else
  633. {
  634. spell->creatureAbility = false;
  635. spell->combat = type == "combat";
  636. }
  637. VLC->generaltexth->registerString(scope, spell->getNameTextID(), json["name"].String());
  638. logMod->trace("%s: loading spell %s", __FUNCTION__, spell->getNameTranslated());
  639. const auto schoolNames = json["school"];
  640. for(const spells::SchoolInfo & info : SpellConfig::SCHOOL)
  641. {
  642. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  643. }
  644. spell->castOnSelf = json["canCastOnSelf"].Bool();
  645. spell->level = static_cast<si32>(json["level"].Integer());
  646. spell->power = static_cast<si32>(json["power"].Integer());
  647. spell->defaultProbability = static_cast<si32>(json["defaultGainChance"].Integer());
  648. for(const auto & node : json["gainChance"].Struct())
  649. {
  650. const int chance = static_cast<int>(node.second.Integer());
  651. VLC->identifiers()->requestIdentifier(node.second.getModScope(), "faction", node.first, [=](si32 factionID)
  652. {
  653. spell->probabilities[FactionID(factionID)] = chance;
  654. });
  655. }
  656. auto targetType = json["targetType"].String();
  657. if(targetType == "NO_TARGET")
  658. spell->targetType = spells::AimType::NO_TARGET;
  659. else if(targetType == "CREATURE")
  660. spell->targetType = spells::AimType::CREATURE;
  661. else if(targetType == "OBSTACLE")
  662. spell->targetType = spells::AimType::OBSTACLE;
  663. else if(targetType == "LOCATION")
  664. spell->targetType = spells::AimType::LOCATION;
  665. else
  666. logMod->warn("Spell %s: target type %s - assumed NO_TARGET.", spell->getNameTranslated(), (targetType.empty() ? "empty" : "unknown ("+targetType+")"));
  667. for(const auto & counteredSpell: json["counters"].Struct())
  668. {
  669. if(counteredSpell.second.Bool())
  670. {
  671. VLC->identifiers()->requestIdentifier(counteredSpell.second.getModScope(), "spell", counteredSpell.first, [=](si32 id)
  672. {
  673. spell->counteredSpells.emplace_back(id);
  674. });
  675. }
  676. }
  677. //TODO: more error checking - f.e. conflicting flags
  678. const auto flags = json["flags"];
  679. //by default all flags are set to false in constructor
  680. spell->damage = flags["damage"].Bool(); //do this before "offensive"
  681. spell->nonMagical = flags["nonMagical"].Bool();
  682. if(flags["offensive"].Bool())
  683. {
  684. spell->setIsOffensive(true);
  685. }
  686. if(flags["rising"].Bool())
  687. {
  688. spell->setIsRising(true);
  689. }
  690. const bool implicitPositiveness = spell->offensive || spell->rising; //(!) "damage" does not mean NEGATIVE --AVS
  691. if(flags["indifferent"].Bool())
  692. {
  693. spell->positiveness = CSpell::NEUTRAL;
  694. }
  695. else if(flags["negative"].Bool())
  696. {
  697. spell->positiveness = CSpell::NEGATIVE;
  698. }
  699. else if(flags["positive"].Bool())
  700. {
  701. spell->positiveness = CSpell::POSITIVE;
  702. }
  703. else if(!implicitPositiveness)
  704. {
  705. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  706. logMod->error("Spell %s: no positiveness specified, assumed NEUTRAL.", spell->getNameTranslated());
  707. }
  708. spell->special = flags["special"].Bool();
  709. spell->onlyOnWaterMap = json["onlyOnWaterMap"].Bool();
  710. auto findBonus = [&](const std::string & name, std::vector<BonusType> & vec)
  711. {
  712. auto it = bonusNameMap.find(name);
  713. if(it == bonusNameMap.end())
  714. {
  715. logMod->error("Spell %s: invalid bonus name %s", spell->getNameTranslated(), name);
  716. }
  717. else
  718. {
  719. vec.push_back(static_cast<BonusType>(it->second));
  720. }
  721. };
  722. auto readBonusStruct = [&](const std::string & name, std::vector<BonusType> & vec)
  723. {
  724. for(auto bonusData: json[name].Struct())
  725. {
  726. const std::string bonusId = bonusData.first;
  727. const bool flag = bonusData.second.Bool();
  728. if(flag)
  729. findBonus(bonusId, vec);
  730. }
  731. };
  732. if(json["targetCondition"].isNull())
  733. {
  734. CSpell::BTVector immunities;
  735. CSpell::BTVector absoluteImmunities;
  736. CSpell::BTVector limiters;
  737. CSpell::BTVector absoluteLimiters;
  738. readBonusStruct("immunity", immunities);
  739. readBonusStruct("absoluteImmunity", absoluteImmunities);
  740. readBonusStruct("limit", limiters);
  741. readBonusStruct("absoluteLimit", absoluteLimiters);
  742. if(!(immunities.empty() && absoluteImmunities.empty() && limiters.empty() && absoluteLimiters.empty()))
  743. {
  744. logMod->warn("Spell %s has old target condition format. Expected configuration: ", spell->getNameTranslated());
  745. spell->targetCondition = spell->convertTargetCondition(immunities, absoluteImmunities, limiters, absoluteLimiters);
  746. logMod->warn("\n\"targetCondition\" : %s", spell->targetCondition.toString());
  747. }
  748. }
  749. else
  750. {
  751. spell->targetCondition = json["targetCondition"];
  752. //TODO: could this be safely merged instead of discarding?
  753. if(!json["immunity"].isNull())
  754. logMod->warn("Spell %s 'immunity' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  755. if(!json["absoluteImmunity"].isNull())
  756. logMod->warn("Spell %s 'absoluteImmunity' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  757. if(!json["limit"].isNull())
  758. logMod->warn("Spell %s 'limit' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  759. if(!json["absoluteLimit"].isNull())
  760. logMod->warn("Spell %s 'absoluteLimit' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  761. }
  762. const JsonNode & graphicsNode = json["graphics"];
  763. spell->iconImmune = graphicsNode["iconImmune"].String();
  764. spell->iconBook = graphicsNode["iconBook"].String();
  765. spell->iconEffect = graphicsNode["iconEffect"].String();
  766. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  767. spell->iconScroll = graphicsNode["iconScroll"].String();
  768. const JsonNode & animationNode = json["animation"];
  769. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  770. {
  771. auto queueNode = animationNode[jsonName].Vector();
  772. for(const JsonNode & item : queueNode)
  773. {
  774. CSpell::TAnimation newItem;
  775. if(item.getType() == JsonNode::JsonType::DATA_STRING)
  776. newItem.resourceName = AnimationPath::fromJson(item);
  777. else if(item.getType() == JsonNode::JsonType::DATA_STRUCT)
  778. {
  779. newItem.resourceName = AnimationPath::fromJson(item["defName"]);
  780. newItem.effectName = item["effectName"].String();
  781. auto vPosStr = item["verticalPosition"].String();
  782. if("bottom" == vPosStr)
  783. newItem.verticalPosition = VerticalPosition::BOTTOM;
  784. }
  785. else if(item.isNumber())
  786. {
  787. newItem.pause = static_cast<int>(item.Float());
  788. }
  789. q.push_back(newItem);
  790. }
  791. };
  792. loadAnimationQueue("affect", spell->animationInfo.affect);
  793. loadAnimationQueue("cast", spell->animationInfo.cast);
  794. loadAnimationQueue("hit", spell->animationInfo.hit);
  795. const JsonVector & projectile = animationNode["projectile"].Vector();
  796. for(const JsonNode & item : projectile)
  797. {
  798. CSpell::ProjectileInfo info;
  799. info.resourceName = AnimationPath::fromJson(item["defName"]);
  800. info.minimumAngle = item["minimumAngle"].Float();
  801. spell->animationInfo.projectile.push_back(info);
  802. }
  803. const JsonNode & soundsNode = json["sounds"];
  804. spell->castSound = AudioPath::fromJson(soundsNode["cast"]);
  805. //load level attributes
  806. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  807. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  808. {
  809. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  810. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  811. const si32 levelPower = levelObject.power = static_cast<si32>(levelNode["power"].Integer());
  812. if (!spell->isCreatureAbility())
  813. VLC->generaltexth->registerString(scope, spell->getDescriptionTextID(levelIndex), levelNode["description"].String());
  814. levelObject.cost = static_cast<si32>(levelNode["cost"].Integer());
  815. levelObject.AIValue = static_cast<si32>(levelNode["aiValue"].Integer());
  816. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  817. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  818. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  819. levelObject.range = spellRangeInHexes(levelNode["range"].String());
  820. for(const auto & elem : levelNode["effects"].Struct())
  821. {
  822. const JsonNode & bonusNode = elem.second;
  823. auto b = JsonUtils::parseBonus(bonusNode);
  824. const bool usePowerAsValue = bonusNode["val"].isNull();
  825. b->sid = BonusSourceID(spell->id); //for all
  826. b->source = BonusSource::SPELL_EFFECT;//for all
  827. if(usePowerAsValue)
  828. b->val = levelPower;
  829. levelObject.effects.push_back(b);
  830. }
  831. for(const auto & elem : levelNode["cumulativeEffects"].Struct())
  832. {
  833. const JsonNode & bonusNode = elem.second;
  834. auto b = JsonUtils::parseBonus(bonusNode);
  835. const bool usePowerAsValue = bonusNode["val"].isNull();
  836. b->sid = BonusSourceID(spell->id); //for all
  837. b->source = BonusSource::SPELL_EFFECT;//for all
  838. if(usePowerAsValue)
  839. b->val = levelPower;
  840. levelObject.cumulativeEffects.push_back(b);
  841. }
  842. if(levelNode["battleEffects"].getType() == JsonNode::JsonType::DATA_STRUCT && !levelNode["battleEffects"].Struct().empty())
  843. {
  844. levelObject.battleEffects = levelNode["battleEffects"];
  845. if(!levelObject.cumulativeEffects.empty() || !levelObject.effects.empty() || spell->isOffensive())
  846. logGlobal->error("Mixing %s special effects with old format effects gives unpredictable result", spell->getNameTranslated());
  847. }
  848. }
  849. return spell;
  850. }
  851. void CSpellHandler::afterLoadFinalization()
  852. {
  853. for(auto & spell : objects)
  854. {
  855. spell->setupMechanics();
  856. }
  857. }
  858. void CSpellHandler::beforeValidate(JsonNode & object)
  859. {
  860. //handle "base" level info
  861. JsonNode & levels = object["levels"];
  862. JsonNode & base = levels["base"];
  863. auto inheritNode = [&](const std::string & name)
  864. {
  865. JsonUtils::inherit(levels[name],base);
  866. };
  867. inheritNode("none");
  868. inheritNode("basic");
  869. inheritNode("advanced");
  870. inheritNode("expert");
  871. }
  872. std::set<SpellID> CSpellHandler::getDefaultAllowed() const
  873. {
  874. std::set<SpellID> allowedSpells;
  875. for(auto const & s : objects)
  876. if (!s->isSpecial() && !s->isCreatureAbility())
  877. allowedSpells.insert(s->getId());
  878. return allowedSpells;
  879. }
  880. VCMI_LIB_NAMESPACE_END