CSpellHandler.cpp 25 KB

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