CSpellHandler.cpp 25 KB

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