CSpellHandler.cpp 28 KB

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