CSpellHandler.cpp 25 KB

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