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