CSpellHandler.cpp 25 KB

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