CSpellHandler.cpp 26 KB

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