CSpellHandler.cpp 25 KB

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