CSpellHandler.cpp 25 KB

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