CSpellHandler.cpp 25 KB

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