CSpellHandler.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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 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 < (si32)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. return diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8;
  496. }
  497. ///CSpellHandler
  498. CSpellHandler::CSpellHandler() = default;
  499. CSpellHandler::~CSpellHandler() = default;
  500. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  501. {
  502. using namespace SpellConfig;
  503. std::vector<JsonNode> legacyData;
  504. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  505. auto readSchool = [&](JsonMap & schools, const std::string & name)
  506. {
  507. if (parser.readString() == "x")
  508. {
  509. schools[name].Bool() = true;
  510. }
  511. };
  512. auto read = [&](bool combat, bool ability)
  513. {
  514. do
  515. {
  516. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  517. const auto id = legacyData.size();
  518. lineNode["index"].Integer() = id;
  519. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  520. lineNode["name"].String() = parser.readString();
  521. parser.readString(); //ignored unused abbreviated name
  522. lineNode["level"].Integer() = static_cast<si64>(parser.readNumber());
  523. auto& schools = lineNode["school"].Struct();
  524. readSchool(schools, "earth");
  525. readSchool(schools, "water");
  526. readSchool(schools, "fire");
  527. readSchool(schools, "air");
  528. auto& levels = lineNode["levels"].Struct();
  529. auto getLevel = [&](const size_t idx)->JsonMap&
  530. {
  531. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  532. return levels[LEVEL_NAMES[idx]].Struct();
  533. };
  534. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  535. lineNode["power"].Integer() = static_cast<si64>(parser.readNumber());
  536. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  537. auto & chances = lineNode["gainChance"].Struct();
  538. for(size_t i = 0; i < GameConstants::F_NUMBER; i++)
  539. chances[ETownType::names[i]].Integer() = static_cast<si64>(parser.readNumber());
  540. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  541. std::vector<std::string> descriptions;
  542. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  543. descriptions.push_back(parser.readString());
  544. parser.readString(); //ignore attributes. All data present in JSON
  545. //save parsed level specific data
  546. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  547. {
  548. auto& level = getLevel(i);
  549. level["description"].String() = descriptions[i];
  550. level["cost"].Integer() = costs[i];
  551. level["power"].Integer() = powers[i];
  552. level["aiValue"].Integer() = AIVals[i];
  553. }
  554. legacyData.push_back(lineNode);
  555. }
  556. while (parser.endLine() && !parser.isNextEntryEmpty());
  557. };
  558. auto skip = [&](int cnt)
  559. {
  560. for(int i=0; i<cnt; i++)
  561. parser.endLine();
  562. };
  563. skip(5);// header
  564. read(false,false); //read adventure map spells
  565. skip(3);
  566. read(true,false); //read battle spells
  567. skip(3);
  568. read(true,true);//read creature abilities
  569. //TODO: maybe move to config
  570. //clone Acid Breath attributes for Acid Breath damage effect
  571. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  572. temp["index"].Integer() = SpellID::ACID_BREATH_DAMAGE;
  573. legacyData.push_back(temp);
  574. objects.resize(legacyData.size());
  575. return legacyData;
  576. }
  577. const std::vector<std::string> & CSpellHandler::getTypeNames() const
  578. {
  579. static const std::vector<std::string> typeNames = { "spell" };
  580. return typeNames;
  581. }
  582. CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & identifier, size_t index)
  583. {
  584. using namespace SpellConfig;
  585. SpellID id(static_cast<si32>(index));
  586. CSpell * spell = new CSpell();
  587. spell->id = id;
  588. spell->identifier = identifier;
  589. const auto type = json["type"].String();
  590. if(type == "ability")
  591. {
  592. spell->creatureAbility = true;
  593. spell->combatSpell = true;
  594. }
  595. else
  596. {
  597. spell->creatureAbility = false;
  598. spell->combatSpell = type == "combat";
  599. }
  600. spell->name = json["name"].String();
  601. logMod->trace("%s: loading spell %s", __FUNCTION__, spell->name);
  602. const auto schoolNames = json["school"];
  603. for(const spells::SchoolInfo & info : SpellConfig::SCHOOL)
  604. {
  605. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  606. }
  607. spell->level = static_cast<si32>(json["level"].Integer());
  608. spell->power = static_cast<si32>(json["power"].Integer());
  609. spell->defaultProbability = static_cast<si32>(json["defaultGainChance"].Integer());
  610. for(const auto & node : json["gainChance"].Struct())
  611. {
  612. const int chance = static_cast<int>(node.second.Integer());
  613. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  614. {
  615. spell->probabilities[factionID] = chance;
  616. });
  617. }
  618. auto targetType = json["targetType"].String();
  619. if(targetType == "NO_TARGET")
  620. spell->targetType = spells::AimType::NO_TARGET;
  621. else if(targetType == "CREATURE")
  622. spell->targetType = spells::AimType::CREATURE;
  623. else if(targetType == "OBSTACLE")
  624. spell->targetType = spells::AimType::OBSTACLE;
  625. else if(targetType == "LOCATION")
  626. spell->targetType = spells::AimType::LOCATION;
  627. else
  628. logMod->warn("Spell %s: target type %s - assumed NO_TARGET.", spell->name, (targetType.empty() ? "empty" : "unknown ("+targetType+")"));
  629. for(const auto & counteredSpell: json["counters"].Struct())
  630. {
  631. if(counteredSpell.second.Bool())
  632. {
  633. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  634. {
  635. spell->counteredSpells.push_back(SpellID(id));
  636. });
  637. }
  638. }
  639. //TODO: more error checking - f.e. conflicting flags
  640. const auto flags = json["flags"];
  641. //by default all flags are set to false in constructor
  642. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  643. if(flags["offensive"].Bool())
  644. {
  645. spell->setIsOffensive(true);
  646. }
  647. if(flags["rising"].Bool())
  648. {
  649. spell->setIsRising(true);
  650. }
  651. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  652. if(flags["indifferent"].Bool())
  653. {
  654. spell->positiveness = CSpell::NEUTRAL;
  655. }
  656. else if(flags["negative"].Bool())
  657. {
  658. spell->positiveness = CSpell::NEGATIVE;
  659. }
  660. else if(flags["positive"].Bool())
  661. {
  662. spell->positiveness = CSpell::POSITIVE;
  663. }
  664. else if(!implicitPositiveness)
  665. {
  666. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  667. logMod->error("Spell %s: no positiveness specified, assumed NEUTRAL.", spell->name);
  668. }
  669. spell->isSpecial = flags["special"].Bool();
  670. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  671. {
  672. auto it = bonusNameMap.find(name);
  673. if(it == bonusNameMap.end())
  674. {
  675. logMod->error("Spell %s: invalid bonus name %s", spell->name, name);
  676. }
  677. else
  678. {
  679. vec.push_back((Bonus::BonusType)it->second);
  680. }
  681. };
  682. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  683. {
  684. for(auto bonusData: json[name].Struct())
  685. {
  686. const std::string bonusId = bonusData.first;
  687. const bool flag = bonusData.second.Bool();
  688. if(flag)
  689. findBonus(bonusId, vec);
  690. }
  691. };
  692. if(json["targetCondition"].isNull())
  693. {
  694. CSpell::BTVector immunities;
  695. CSpell::BTVector absoluteImmunities;
  696. CSpell::BTVector limiters;
  697. CSpell::BTVector absoluteLimiters;
  698. readBonusStruct("immunity", immunities);
  699. readBonusStruct("absoluteImmunity", absoluteImmunities);
  700. readBonusStruct("limit", limiters);
  701. readBonusStruct("absoluteLimit", absoluteLimiters);
  702. if(!(immunities.empty() && absoluteImmunities.empty() && limiters.empty() && absoluteLimiters.empty()))
  703. {
  704. logMod->warn("Spell %s has old target condition format. Expected configuration: ", spell->name);
  705. spell->targetCondition = spell->convertTargetCondition(immunities, absoluteImmunities, limiters, absoluteLimiters);
  706. logMod->warn("\n\"targetCondition\" : %s", spell->targetCondition.toJson());
  707. }
  708. }
  709. else
  710. {
  711. spell->targetCondition = json["targetCondition"];
  712. //TODO: could this be safely merged instead of discarding?
  713. if(!json["immunity"].isNull())
  714. logMod->warn("Spell %s 'immunity' field mixed with 'targetCondition' discarded", spell->name);
  715. if(!json["absoluteImmunity"].isNull())
  716. logMod->warn("Spell %s 'absoluteImmunity' field mixed with 'targetCondition' discarded", spell->name);
  717. if(!json["limit"].isNull())
  718. logMod->warn("Spell %s 'limit' field mixed with 'targetCondition' discarded", spell->name);
  719. if(!json["absoluteLimit"].isNull())
  720. logMod->warn("Spell %s 'absoluteLimit' field mixed with 'targetCondition' discarded", spell->name);
  721. }
  722. const JsonNode & graphicsNode = json["graphics"];
  723. spell->iconImmune = graphicsNode["iconImmune"].String();
  724. spell->iconBook = graphicsNode["iconBook"].String();
  725. spell->iconEffect = graphicsNode["iconEffect"].String();
  726. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  727. spell->iconScroll = graphicsNode["iconScroll"].String();
  728. const JsonNode & animationNode = json["animation"];
  729. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  730. {
  731. auto queueNode = animationNode[jsonName].Vector();
  732. for(const JsonNode & item : queueNode)
  733. {
  734. CSpell::TAnimation newItem;
  735. if(item.getType() == JsonNode::JsonType::DATA_STRING)
  736. newItem.resourceName = item.String();
  737. else if(item.getType() == JsonNode::JsonType::DATA_STRUCT)
  738. {
  739. newItem.resourceName = item["defName"].String();
  740. auto vPosStr = item["verticalPosition"].String();
  741. if("bottom" == vPosStr)
  742. newItem.verticalPosition = VerticalPosition::BOTTOM;
  743. }
  744. else if(item.isNumber())
  745. {
  746. newItem.pause = static_cast<int>(item.Float());
  747. }
  748. q.push_back(newItem);
  749. }
  750. };
  751. loadAnimationQueue("affect", spell->animationInfo.affect);
  752. loadAnimationQueue("cast", spell->animationInfo.cast);
  753. loadAnimationQueue("hit", spell->animationInfo.hit);
  754. const JsonVector & projectile = animationNode["projectile"].Vector();
  755. for(const JsonNode & item : projectile)
  756. {
  757. CSpell::ProjectileInfo info;
  758. info.resourceName = item["defName"].String();
  759. info.minimumAngle = item["minimumAngle"].Float();
  760. spell->animationInfo.projectile.push_back(info);
  761. }
  762. const JsonNode & soundsNode = json["sounds"];
  763. spell->castSound = soundsNode["cast"].String();
  764. //load level attributes
  765. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  766. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  767. {
  768. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  769. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  770. const si32 levelPower = levelObject.power = static_cast<si32>(levelNode["power"].Integer());
  771. levelObject.description = levelNode["description"].String();
  772. levelObject.cost = static_cast<si32>(levelNode["cost"].Integer());
  773. levelObject.AIValue = static_cast<si32>(levelNode["aiValue"].Integer());
  774. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  775. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  776. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  777. levelObject.range = levelNode["range"].String();
  778. for(const auto & elem : levelNode["effects"].Struct())
  779. {
  780. const JsonNode & bonusNode = elem.second;
  781. auto b = JsonUtils::parseBonus(bonusNode);
  782. const bool usePowerAsValue = bonusNode["val"].isNull();
  783. b->sid = spell->id; //for all
  784. b->source = Bonus::SPELL_EFFECT;//for all
  785. if(usePowerAsValue)
  786. b->val = levelPower;
  787. levelObject.effects.push_back(b);
  788. }
  789. for(const auto & elem : levelNode["cumulativeEffects"].Struct())
  790. {
  791. const JsonNode & bonusNode = elem.second;
  792. auto b = JsonUtils::parseBonus(bonusNode);
  793. const bool usePowerAsValue = bonusNode["val"].isNull();
  794. b->sid = spell->id; //for all
  795. b->source = Bonus::SPELL_EFFECT;//for all
  796. if(usePowerAsValue)
  797. b->val = levelPower;
  798. levelObject.cumulativeEffects.push_back(b);
  799. }
  800. if(levelNode["battleEffects"].getType() == JsonNode::JsonType::DATA_STRUCT && !levelNode["battleEffects"].Struct().empty())
  801. {
  802. levelObject.battleEffects = levelNode["battleEffects"];
  803. if(!levelObject.cumulativeEffects.empty() || !levelObject.effects.empty() || spell->isOffensiveSpell())
  804. logGlobal->error("Mixing %s special effects with old format effects gives unpredictable result", spell->name);
  805. }
  806. }
  807. return spell;
  808. }
  809. void CSpellHandler::afterLoadFinalization()
  810. {
  811. for(auto spell : objects)
  812. {
  813. spell->setupMechanics();
  814. }
  815. }
  816. void CSpellHandler::beforeValidate(JsonNode & object)
  817. {
  818. //handle "base" level info
  819. JsonNode & levels = object["levels"];
  820. JsonNode & base = levels["base"];
  821. auto inheritNode = [&](const std::string & name)
  822. {
  823. JsonUtils::inherit(levels[name],base);
  824. };
  825. inheritNode("none");
  826. inheritNode("basic");
  827. inheritNode("advanced");
  828. inheritNode("expert");
  829. }
  830. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  831. {
  832. std::vector<bool> allowedSpells;
  833. allowedSpells.reserve(objects.size());
  834. for(const CSpell * s : objects)
  835. {
  836. allowedSpells.push_back( !(s->isSpecialSpell() || s->isCreatureAbility()));
  837. }
  838. return allowedSpells;
  839. }
  840. void CSpellHandler::update780()
  841. {
  842. static_assert(MINIMAL_SERIALIZATION_VERSION < 780, "No longer needed CSpellHandler::update780");
  843. auto spellsContent = (*VLC->modh->content)["spells"];
  844. const ContentTypeHandler::ModInfo & coreData = spellsContent.modData.at("core");
  845. const JsonNode & coreSpells = coreData.modData;
  846. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  847. for(CSpell * spell : objects)
  848. {
  849. auto identifier = spell->identifier;
  850. size_t colonPos = identifier.find(':');
  851. if(colonPos != std::string::npos)
  852. continue;
  853. const JsonNode & actualConfig = coreSpells[spell->identifier];
  854. if(actualConfig.getType() != JsonNode::JsonType::DATA_STRUCT)
  855. {
  856. logGlobal->error("Spell not found %s", spell->identifier);
  857. continue;
  858. }
  859. if(actualConfig["targetCondition"].getType() == JsonNode::JsonType::DATA_STRUCT && !actualConfig["targetCondition"].Struct().empty())
  860. {
  861. spell->targetCondition = actualConfig["targetCondition"];
  862. }
  863. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  864. {
  865. const JsonNode & levelNode = actualConfig["levels"][SpellConfig::LEVEL_NAMES[levelIndex]];
  866. logGlobal->debug(levelNode.toJson());
  867. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  868. if(levelNode["battleEffects"].getType() == JsonNode::JsonType::DATA_STRUCT && !levelNode["battleEffects"].Struct().empty())
  869. {
  870. levelObject.battleEffects = levelNode["battleEffects"];
  871. logGlobal->trace("Updated special effects for level %d of spell %s", levelIndex, spell->identifier);
  872. }
  873. }
  874. }
  875. }