CSpellHandler.cpp 26 KB

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