CSpellHandler.cpp 25 KB

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