CSpellHandler.cpp 27 KB

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