CSpellHandler.cpp 27 KB

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