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. int32_t CSpell::getLevel() const
  212. {
  213. return level;
  214. }
  215. bool CSpell::isCombatSpell() const
  216. {
  217. return combatSpell;
  218. }
  219. bool CSpell::isAdventureSpell() const
  220. {
  221. return !combatSpell;
  222. }
  223. bool CSpell::isCreatureAbility() const
  224. {
  225. return creatureAbility;
  226. }
  227. bool CSpell::isPositive() const
  228. {
  229. return positiveness == POSITIVE;
  230. }
  231. bool CSpell::isNegative() const
  232. {
  233. return positiveness == NEGATIVE;
  234. }
  235. bool CSpell::isNeutral() const
  236. {
  237. return positiveness == NEUTRAL;
  238. }
  239. boost::logic::tribool CSpell::getPositiveness() const
  240. {
  241. switch (positiveness)
  242. {
  243. case CSpell::POSITIVE:
  244. return true;
  245. case CSpell::NEGATIVE:
  246. return false;
  247. default:
  248. return boost::logic::indeterminate;
  249. }
  250. }
  251. bool CSpell::isRisingSpell() const
  252. {
  253. return isRising;
  254. }
  255. bool CSpell::isDamageSpell() const
  256. {
  257. return isDamage;
  258. }
  259. bool CSpell::isOffensiveSpell() const
  260. {
  261. return isOffensive;
  262. }
  263. bool CSpell::isSpecialSpell() const
  264. {
  265. return isSpecial;
  266. }
  267. bool CSpell::hasEffects() const
  268. {
  269. return !levels[0].effects.empty() || !levels[0].cumulativeEffects.empty();
  270. }
  271. bool CSpell::hasBattleEffects() const
  272. {
  273. return levels[0].battleEffects.getType() == JsonNode::JsonType::DATA_STRUCT && !levels[0].battleEffects.Struct().empty();
  274. }
  275. const std::string & CSpell::getIconImmune() const
  276. {
  277. return iconImmune;
  278. }
  279. const std::string & CSpell::getCastSound() const
  280. {
  281. return castSound;
  282. }
  283. si32 CSpell::getCost(const int skillLevel) const
  284. {
  285. return getLevelInfo(skillLevel).cost;
  286. }
  287. si32 CSpell::getPower(const int skillLevel) const
  288. {
  289. return getLevelInfo(skillLevel).power;
  290. }
  291. si32 CSpell::getProbability(const TFaction factionId) const
  292. {
  293. if(!vstd::contains(probabilities,factionId))
  294. {
  295. return defaultProbability;
  296. }
  297. return probabilities.at(factionId);
  298. }
  299. void CSpell::getEffects(std::vector<Bonus> & lst, const int level, const bool cumulative, const si32 duration, boost::optional<si32 *> maxDuration) const
  300. {
  301. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  302. {
  303. logGlobal->error("invalid school level %d", level);
  304. return;
  305. }
  306. const auto & levelObject = levels.at(level);
  307. if(levelObject.effects.empty() && levelObject.cumulativeEffects.empty())
  308. {
  309. logGlobal->error("This spell (%s) has no effects for level %d", name, level);
  310. return;
  311. }
  312. const auto & effects = cumulative ? levelObject.cumulativeEffects : levelObject.effects;
  313. lst.reserve(lst.size() + effects.size());
  314. for(const auto b : effects)
  315. {
  316. Bonus nb(*b);
  317. //use configured duration if present
  318. if(nb.turnsRemain == 0)
  319. nb.turnsRemain = duration;
  320. if(maxDuration)
  321. vstd::amax(*(maxDuration.get()), nb.turnsRemain);
  322. lst.push_back(nb);
  323. }
  324. }
  325. bool CSpell::canBeCastAt(const CBattleInfoCallback * cb, spells::Mode mode, const spells::Caster * caster, BattleHex destination) const
  326. {
  327. if(canBeCast(cb, mode, caster))
  328. {
  329. spells::BattleCast event(cb, caster, mode, this);
  330. spells::Target tmp;
  331. tmp.emplace_back(destination);
  332. return battleMechanics(&event)->canBeCastAt(tmp);
  333. }
  334. else
  335. {
  336. return false;
  337. }
  338. }
  339. bool CSpell::canBeCastAt(const CBattleInfoCallback * cb, spells::Mode mode, const spells::Caster * caster, const spells::Target & target) const
  340. {
  341. if(canBeCast(cb, mode, caster))
  342. {
  343. spells::BattleCast event(cb, caster, mode, this);
  344. return battleMechanics(&event)->canBeCastAt(target);
  345. }
  346. else
  347. {
  348. return false;
  349. }
  350. }
  351. int64_t CSpell::adjustRawDamage(const spells::Caster * caster, const battle::Unit * affectedCreature, int64_t rawDamage) const
  352. {
  353. auto ret = rawDamage;
  354. //affected creature-specific part
  355. if(nullptr != affectedCreature)
  356. {
  357. auto bearer = affectedCreature;
  358. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  359. forEachSchool([&](const spells::SchoolInfo & cnf, bool & stop)
  360. {
  361. if(bearer->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  362. {
  363. ret *= 100 - bearer->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  364. ret /= 100;
  365. stop = true;//only bonus from one school is used
  366. }
  367. });
  368. CSelector selector = Selector::type(Bonus::SPELL_DAMAGE_REDUCTION).And(Selector::subtype(-1));
  369. //general spell dmg reduction
  370. if(bearer->hasBonus(selector))
  371. {
  372. ret *= 100 - bearer->valOfBonuses(selector);
  373. ret /= 100;
  374. }
  375. //dmg increasing
  376. if(bearer->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  377. {
  378. ret *= 100 + bearer->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  379. ret /= 100;
  380. }
  381. }
  382. ret = caster->getSpellBonus(this, ret, affectedCreature);
  383. return ret;
  384. }
  385. int64_t CSpell::calculateRawEffectValue(int32_t effectLevel, int32_t basePowerMultiplier, int32_t levelPowerMultiplier) const
  386. {
  387. return basePowerMultiplier * power + levelPowerMultiplier * getPower(effectLevel);
  388. }
  389. void CSpell::setIsOffensive(const bool val)
  390. {
  391. isOffensive = val;
  392. if(val)
  393. {
  394. positiveness = CSpell::NEGATIVE;
  395. isDamage = true;
  396. }
  397. }
  398. void CSpell::setIsRising(const bool val)
  399. {
  400. isRising = val;
  401. if(val)
  402. {
  403. positiveness = CSpell::POSITIVE;
  404. }
  405. }
  406. JsonNode CSpell::convertTargetCondition(const BTVector & immunity, const BTVector & absImmunity, const BTVector & limit, const BTVector & absLimit) const
  407. {
  408. static const std::string CONDITION_NORMAL = "normal";
  409. static const std::string CONDITION_ABSOLUTE = "absolute";
  410. #define BONUS_NAME(x) { Bonus::x, #x },
  411. static const std::map<Bonus::BonusType, std::string> bonusNameRMap = { BONUS_LIST };
  412. #undef BONUS_NAME
  413. JsonNode res;
  414. auto convertVector = [&](const std::string & targetName, const BTVector & source, const std::string & value)
  415. {
  416. for(auto bonusType : source)
  417. {
  418. auto iter = bonusNameRMap.find(bonusType);
  419. if(iter != bonusNameRMap.end())
  420. {
  421. auto fullId = CModHandler::makeFullIdentifier("", "bonus", iter->second);
  422. res[targetName][fullId].String() = value;
  423. }
  424. else
  425. {
  426. logGlobal->error("Invalid bonus type %d", static_cast<int32_t>(bonusType));
  427. }
  428. }
  429. };
  430. auto convertSection = [&](const std::string & targetName, const BTVector & normal, const BTVector & absolute)
  431. {
  432. convertVector(targetName, normal, CONDITION_NORMAL);
  433. convertVector(targetName, absolute, CONDITION_ABSOLUTE);
  434. };
  435. convertSection("allOf", limit, absLimit);
  436. convertSection("noneOf", immunity, absImmunity);
  437. return res;
  438. }
  439. void CSpell::setupMechanics()
  440. {
  441. mechanics = spells::ISpellMechanicsFactory::get(this);
  442. adventureMechanics = IAdventureSpellMechanics::createMechanics(this);
  443. }
  444. std::unique_ptr<spells::Mechanics> CSpell::battleMechanics(const spells::IBattleCast * event) const
  445. {
  446. return mechanics->create(event);
  447. }
  448. ///CSpell::AnimationInfo
  449. CSpell::AnimationItem::AnimationItem()
  450. :resourceName(""),verticalPosition(VerticalPosition::TOP),pause(0)
  451. {
  452. }
  453. ///CSpell::AnimationInfo
  454. CSpell::AnimationInfo::AnimationInfo()
  455. {
  456. }
  457. CSpell::AnimationInfo::~AnimationInfo()
  458. {
  459. }
  460. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  461. {
  462. std::string res;
  463. double maximum = 0.0;
  464. for(const auto & info : projectile)
  465. {
  466. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  467. {
  468. maximum = info.minimumAngle;
  469. res = info.resourceName;
  470. }
  471. }
  472. return res;
  473. }
  474. ///CSpell::TargetInfo
  475. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, spells::Mode mode)
  476. : type(spell->getTargetType()),
  477. smart(false),
  478. massive(false),
  479. clearAffected(false),
  480. clearTarget(false)
  481. {
  482. auto & levelInfo = spell->getLevelInfo(level);
  483. smart = levelInfo.smartTarget;
  484. massive = levelInfo.range == "X";
  485. clearAffected = levelInfo.clearAffected;
  486. clearTarget = levelInfo.clearTarget;
  487. if(mode == spells::Mode::CREATURE_ACTIVE)
  488. {
  489. massive = false;//FIXME: find better solution for Commander spells
  490. }
  491. }
  492. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  493. {
  494. int3 diff = pos - center;
  495. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  496. return true;
  497. else
  498. return false;
  499. }
  500. ///CSpellHandler
  501. CSpellHandler::CSpellHandler() = default;
  502. CSpellHandler::~CSpellHandler() = default;
  503. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  504. {
  505. using namespace SpellConfig;
  506. std::vector<JsonNode> legacyData;
  507. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  508. auto readSchool = [&](JsonMap & schools, const std::string & name)
  509. {
  510. if (parser.readString() == "x")
  511. {
  512. schools[name].Bool() = true;
  513. }
  514. };
  515. auto read = [&,this](bool combat, bool ability)
  516. {
  517. do
  518. {
  519. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  520. const auto id = legacyData.size();
  521. lineNode["index"].Integer() = id;
  522. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  523. lineNode["name"].String() = parser.readString();
  524. parser.readString(); //ignored unused abbreviated name
  525. lineNode["level"].Integer() = parser.readNumber();
  526. auto& schools = lineNode["school"].Struct();
  527. readSchool(schools, "earth");
  528. readSchool(schools, "water");
  529. readSchool(schools, "fire");
  530. readSchool(schools, "air");
  531. auto& levels = lineNode["levels"].Struct();
  532. auto getLevel = [&](const size_t idx)->JsonMap&
  533. {
  534. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  535. return levels[LEVEL_NAMES[idx]].Struct();
  536. };
  537. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  538. lineNode["power"].Integer() = parser.readNumber();
  539. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  540. auto & chances = lineNode["gainChance"].Struct();
  541. for(size_t i = 0; i < GameConstants::F_NUMBER; i++)
  542. chances[ETownType::names[i]].Integer() = parser.readNumber();
  543. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  544. std::vector<std::string> descriptions;
  545. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  546. descriptions.push_back(parser.readString());
  547. parser.readString(); //ignore attributes. All data present in JSON
  548. //save parsed level specific data
  549. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  550. {
  551. auto& level = getLevel(i);
  552. level["description"].String() = descriptions[i];
  553. level["cost"].Integer() = costs[i];
  554. level["power"].Integer() = powers[i];
  555. level["aiValue"].Integer() = AIVals[i];
  556. }
  557. legacyData.push_back(lineNode);
  558. }
  559. while (parser.endLine() && !parser.isNextEntryEmpty());
  560. };
  561. auto skip = [&](int cnt)
  562. {
  563. for(int i=0; i<cnt; i++)
  564. parser.endLine();
  565. };
  566. skip(5);// header
  567. read(false,false); //read adventure map spells
  568. skip(3);
  569. read(true,false); //read battle spells
  570. skip(3);
  571. read(true,true);//read creature abilities
  572. //TODO: maybe move to config
  573. //clone Acid Breath attributes for Acid Breath damage effect
  574. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  575. temp["index"].Integer() = SpellID::ACID_BREATH_DAMAGE;
  576. legacyData.push_back(temp);
  577. objects.resize(legacyData.size());
  578. return legacyData;
  579. }
  580. const std::string CSpellHandler::getTypeName() const
  581. {
  582. return "spell";
  583. }
  584. CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & identifier, size_t index)
  585. {
  586. using namespace SpellConfig;
  587. SpellID id(static_cast<si32>(index));
  588. CSpell * spell = new CSpell();
  589. spell->id = id;
  590. spell->identifier = identifier;
  591. const auto type = json["type"].String();
  592. if(type == "ability")
  593. {
  594. spell->creatureAbility = true;
  595. spell->combatSpell = true;
  596. }
  597. else
  598. {
  599. spell->creatureAbility = false;
  600. spell->combatSpell = type == "combat";
  601. }
  602. spell->name = json["name"].String();
  603. logMod->trace("%s: loading spell %s", __FUNCTION__, spell->name);
  604. const auto schoolNames = json["school"];
  605. for(const spells::SchoolInfo & info : SpellConfig::SCHOOL)
  606. {
  607. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  608. }
  609. spell->level = json["level"].Integer();
  610. spell->power = json["power"].Integer();
  611. spell->defaultProbability = json["defaultGainChance"].Integer();
  612. for(const auto & node : json["gainChance"].Struct())
  613. {
  614. const int chance = node.second.Integer();
  615. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  616. {
  617. spell->probabilities[factionID] = chance;
  618. });
  619. }
  620. auto targetType = json["targetType"].String();
  621. if(targetType == "NO_TARGET")
  622. spell->targetType = spells::AimType::NO_TARGET;
  623. else if(targetType == "CREATURE")
  624. spell->targetType = spells::AimType::CREATURE;
  625. else if(targetType == "OBSTACLE")
  626. spell->targetType = spells::AimType::OBSTACLE;
  627. else if(targetType == "LOCATION")
  628. spell->targetType = spells::AimType::LOCATION;
  629. else
  630. logMod->warn("Spell %s: target type %s - assumed NO_TARGET.", spell->name, (targetType.empty() ? "empty" : "unknown ("+targetType+")"));
  631. for(const auto & counteredSpell: json["counters"].Struct())
  632. {
  633. if(counteredSpell.second.Bool())
  634. {
  635. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  636. {
  637. spell->counteredSpells.push_back(SpellID(id));
  638. });
  639. }
  640. }
  641. //TODO: more error checking - f.e. conflicting flags
  642. const auto flags = json["flags"];
  643. //by default all flags are set to false in constructor
  644. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  645. if(flags["offensive"].Bool())
  646. {
  647. spell->setIsOffensive(true);
  648. }
  649. if(flags["rising"].Bool())
  650. {
  651. spell->setIsRising(true);
  652. }
  653. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  654. if(flags["indifferent"].Bool())
  655. {
  656. spell->positiveness = CSpell::NEUTRAL;
  657. }
  658. else if(flags["negative"].Bool())
  659. {
  660. spell->positiveness = CSpell::NEGATIVE;
  661. }
  662. else if(flags["positive"].Bool())
  663. {
  664. spell->positiveness = CSpell::POSITIVE;
  665. }
  666. else if(!implicitPositiveness)
  667. {
  668. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  669. logMod->error("Spell %s: no positiveness specified, assumed NEUTRAL.", spell->name);
  670. }
  671. spell->isSpecial = flags["special"].Bool();
  672. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  673. {
  674. auto it = bonusNameMap.find(name);
  675. if(it == bonusNameMap.end())
  676. {
  677. logMod->error("Spell %s: invalid bonus name %s", spell->name, name);
  678. }
  679. else
  680. {
  681. vec.push_back((Bonus::BonusType)it->second);
  682. }
  683. };
  684. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  685. {
  686. for(auto bonusData: json[name].Struct())
  687. {
  688. const std::string bonusId = bonusData.first;
  689. const bool flag = bonusData.second.Bool();
  690. if(flag)
  691. findBonus(bonusId, vec);
  692. }
  693. };
  694. if(json["targetCondition"].isNull())
  695. {
  696. CSpell::BTVector immunities;
  697. CSpell::BTVector absoluteImmunities;
  698. CSpell::BTVector limiters;
  699. CSpell::BTVector absoluteLimiters;
  700. readBonusStruct("immunity", immunities);
  701. readBonusStruct("absoluteImmunity", absoluteImmunities);
  702. readBonusStruct("limit", limiters);
  703. readBonusStruct("absoluteLimit", absoluteLimiters);
  704. if(!(immunities.empty() && absoluteImmunities.empty() && limiters.empty() && absoluteLimiters.empty()))
  705. {
  706. logMod->warn("Spell %s has old target condition format. Expected configuration: ", spell->name);
  707. spell->targetCondition = spell->convertTargetCondition(immunities, absoluteImmunities, limiters, absoluteLimiters);
  708. logMod->warn("\n\"targetCondition\" : %s", spell->targetCondition.toJson());
  709. }
  710. }
  711. else
  712. {
  713. spell->targetCondition = json["targetCondition"];
  714. //TODO: could this be safely merged instead of discarding?
  715. if(!json["immunity"].isNull())
  716. logMod->warn("Spell %s 'immunity' field mixed with 'targetCondition' discarded", spell->name);
  717. if(!json["absoluteImmunity"].isNull())
  718. logMod->warn("Spell %s 'absoluteImmunity' field mixed with 'targetCondition' discarded", spell->name);
  719. if(!json["limit"].isNull())
  720. logMod->warn("Spell %s 'limit' field mixed with 'targetCondition' discarded", spell->name);
  721. if(!json["absoluteLimit"].isNull())
  722. logMod->warn("Spell %s 'absoluteLimit' field mixed with 'targetCondition' discarded", spell->name);
  723. }
  724. const JsonNode & graphicsNode = json["graphics"];
  725. spell->iconImmune = graphicsNode["iconImmune"].String();
  726. spell->iconBook = graphicsNode["iconBook"].String();
  727. spell->iconEffect = graphicsNode["iconEffect"].String();
  728. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  729. spell->iconScroll = graphicsNode["iconScroll"].String();
  730. const JsonNode & animationNode = json["animation"];
  731. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  732. {
  733. auto queueNode = animationNode[jsonName].Vector();
  734. for(const JsonNode & item : queueNode)
  735. {
  736. CSpell::TAnimation newItem;
  737. if(item.getType() == JsonNode::JsonType::DATA_STRING)
  738. newItem.resourceName = item.String();
  739. else if(item.getType() == JsonNode::JsonType::DATA_STRUCT)
  740. {
  741. newItem.resourceName = item["defName"].String();
  742. auto vPosStr = item["verticalPosition"].String();
  743. if("bottom" == vPosStr)
  744. newItem.verticalPosition = VerticalPosition::BOTTOM;
  745. }
  746. else if(item.isNumber())
  747. {
  748. newItem.pause = item.Float();
  749. }
  750. q.push_back(newItem);
  751. }
  752. };
  753. loadAnimationQueue("affect", spell->animationInfo.affect);
  754. loadAnimationQueue("cast", spell->animationInfo.cast);
  755. loadAnimationQueue("hit", spell->animationInfo.hit);
  756. const JsonVector & projectile = animationNode["projectile"].Vector();
  757. for(const JsonNode & item : projectile)
  758. {
  759. CSpell::ProjectileInfo info;
  760. info.resourceName = item["defName"].String();
  761. info.minimumAngle = item["minimumAngle"].Float();
  762. spell->animationInfo.projectile.push_back(info);
  763. }
  764. const JsonNode & soundsNode = json["sounds"];
  765. spell->castSound = soundsNode["cast"].String();
  766. //load level attributes
  767. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  768. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  769. {
  770. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  771. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  772. const si32 levelPower = levelObject.power = levelNode["power"].Integer();
  773. levelObject.description = levelNode["description"].String();
  774. levelObject.cost = levelNode["cost"].Integer();
  775. levelObject.AIValue = levelNode["aiValue"].Integer();
  776. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  777. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  778. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  779. levelObject.range = levelNode["range"].String();
  780. for(const auto & elem : levelNode["effects"].Struct())
  781. {
  782. const JsonNode & bonusNode = elem.second;
  783. auto b = JsonUtils::parseBonus(bonusNode);
  784. const bool usePowerAsValue = bonusNode["val"].isNull();
  785. b->sid = spell->id; //for all
  786. b->source = Bonus::SPELL_EFFECT;//for all
  787. if(usePowerAsValue)
  788. b->val = levelPower;
  789. levelObject.effects.push_back(b);
  790. }
  791. for(const auto & elem : levelNode["cumulativeEffects"].Struct())
  792. {
  793. const JsonNode & bonusNode = elem.second;
  794. auto b = JsonUtils::parseBonus(bonusNode);
  795. const bool usePowerAsValue = bonusNode["val"].isNull();
  796. b->sid = spell->id; //for all
  797. b->source = Bonus::SPELL_EFFECT;//for all
  798. if(usePowerAsValue)
  799. b->val = levelPower;
  800. levelObject.cumulativeEffects.push_back(b);
  801. }
  802. if(levelNode["battleEffects"].getType() == JsonNode::JsonType::DATA_STRUCT && !levelNode["battleEffects"].Struct().empty())
  803. {
  804. levelObject.battleEffects = levelNode["battleEffects"];
  805. if(!levelObject.cumulativeEffects.empty() || !levelObject.effects.empty() || spell->isOffensiveSpell())
  806. logGlobal->error("Mixing %s special effects with old format effects gives unpredictable result", spell->name);
  807. }
  808. }
  809. return spell;
  810. }
  811. void CSpellHandler::afterLoadFinalization()
  812. {
  813. for(auto spell : objects)
  814. {
  815. spell->setupMechanics();
  816. }
  817. }
  818. void CSpellHandler::beforeValidate(JsonNode & object)
  819. {
  820. //handle "base" level info
  821. JsonNode & levels = object["levels"];
  822. JsonNode & base = levels["base"];
  823. auto inheritNode = [&](const std::string & name)
  824. {
  825. JsonUtils::inherit(levels[name],base);
  826. };
  827. inheritNode("none");
  828. inheritNode("basic");
  829. inheritNode("advanced");
  830. inheritNode("expert");
  831. }
  832. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  833. {
  834. std::vector<bool> allowedSpells;
  835. allowedSpells.reserve(objects.size());
  836. for(const CSpell * s : objects)
  837. {
  838. allowedSpells.push_back( !(s->isSpecialSpell() || s->isCreatureAbility()));
  839. }
  840. return allowedSpells;
  841. }
  842. void CSpellHandler::update780()
  843. {
  844. static_assert(MINIMAL_SERIALIZATION_VERSION < 780, "No longer needed CSpellHandler::update780");
  845. auto spellsContent = VLC->modh->content["spells"];
  846. const ContentTypeHandler::ModInfo & coreData = spellsContent.modData.at("core");
  847. const JsonNode & coreSpells = coreData.modData;
  848. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  849. for(CSpell * spell : objects)
  850. {
  851. auto identifier = spell->identifier;
  852. size_t colonPos = identifier.find(':');
  853. if(colonPos != std::string::npos)
  854. continue;
  855. const JsonNode & actualConfig = coreSpells[spell->identifier];
  856. if(actualConfig.getType() != JsonNode::JsonType::DATA_STRUCT)
  857. {
  858. logGlobal->error("Spell not found %s", spell->identifier);
  859. continue;
  860. }
  861. if(actualConfig["targetCondition"].getType() == JsonNode::JsonType::DATA_STRUCT && !actualConfig["targetCondition"].Struct().empty())
  862. {
  863. spell->targetCondition = actualConfig["targetCondition"];
  864. }
  865. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  866. {
  867. const JsonNode & levelNode = actualConfig["levels"][SpellConfig::LEVEL_NAMES[levelIndex]];
  868. logGlobal->debug(levelNode.toJson());
  869. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  870. if(levelNode["battleEffects"].getType() == JsonNode::JsonType::DATA_STRUCT && !levelNode["battleEffects"].Struct().empty())
  871. {
  872. levelObject.battleEffects = levelNode["battleEffects"];
  873. logGlobal->trace("Updated special effects for level %d of spell %s", levelIndex, spell->identifier);
  874. }
  875. }
  876. }
  877. }