CSpellHandler.cpp 26 KB

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