CSpellHandler.cpp 27 KB

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