CSpellHandler.cpp 27 KB

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