CSpellHandler.cpp 25 KB

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