CSpellHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. #include "StdInc.h"
  2. #include "CSpellHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "JsonNode.h"
  6. #include <cctype>
  7. #include "BattleHex.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. #include "mapObjects/CGHeroInstance.h"
  11. #include "BattleState.h"
  12. #include "CBattleCallback.h"
  13. #include "SpellMechanics.h"
  14. /*
  15. * CSpellHandler.cpp, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. namespace SpellConfig
  24. {
  25. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  26. }
  27. ///CSpell::LevelInfo
  28. CSpell::LevelInfo::LevelInfo()
  29. :description(""),cost(0),power(0),AIValue(0),smartTarget(true),range("0")
  30. {
  31. }
  32. CSpell::LevelInfo::~LevelInfo()
  33. {
  34. }
  35. ///CSpell
  36. CSpell::CSpell():
  37. id(SpellID::NONE), level(0),
  38. earth(false), water(false), fire(false), air(false),
  39. combatSpell(false), creatureAbility(false),
  40. positiveness(ESpellPositiveness::NEUTRAL),
  41. mainEffectAnim(-1),
  42. defaultProbability(0),
  43. isRising(false), isDamage(false), isOffensive(false),
  44. targetType(ETargetType::NO_TARGET),
  45. mechanics(nullptr)
  46. {
  47. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  48. }
  49. CSpell::~CSpell()
  50. {
  51. delete mechanics;
  52. }
  53. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  54. {
  55. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  56. {
  57. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  58. throw new std::runtime_error("Invalid school level");
  59. }
  60. return levels.at(level);
  61. }
  62. ui32 CSpell::calculateBonus(ui32 baseDamage, const CGHeroInstance* caster, const CStack* affectedCreature) const
  63. {
  64. ui32 ret = baseDamage;
  65. //applying sorcery secondary skill
  66. if(caster)
  67. {
  68. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  69. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, id.toEnum())) / 100.0;
  70. for(const SpellSchoolInfo & cnf : spellSchoolConfig)
  71. {
  72. if(school.at(cnf.id))
  73. {
  74. ret *= (100.0 + caster->valOfBonuses(cnf.damagePremyBonus)) / 100.0;
  75. break; //only bonus from one school is used
  76. }
  77. }
  78. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  79. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  80. }
  81. return ret;
  82. }
  83. ui32 CSpell::calculateDamage(const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  84. {
  85. ui32 ret = 0; //value to return
  86. //check if spell really does damage - if not, return 0
  87. if(!isDamageSpell())
  88. return 0;
  89. ret = usedSpellPower * power;
  90. ret += getPower(spellSchoolLevel);
  91. //affected creature-specific part
  92. if(nullptr != affectedCreature)
  93. {
  94. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  95. for(const SpellSchoolInfo & cnf : spellSchoolConfig)
  96. {
  97. if(school.at(cnf.id) && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  98. {
  99. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  100. ret /= 100;
  101. break; //only bonus from one school is used
  102. }
  103. }
  104. //general spell dmg reduction
  105. //FIXME?
  106. if(air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  107. {
  108. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  109. ret /= 100;
  110. }
  111. //dmg increasing
  112. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  113. {
  114. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  115. ret /= 100;
  116. }
  117. }
  118. ret = calculateBonus(ret, caster, affectedCreature);
  119. return ret;
  120. }
  121. ui32 CSpell::calculateHealedHP(const CGHeroInstance* caster, const CStack* stack, const CStack* sacrificedStack) const
  122. {
  123. //todo: use Mechanics class
  124. int healedHealth;
  125. if(!isHealingSpell())
  126. {
  127. logGlobal->errorStream() << "calculateHealedHP called for nonhealing spell "<< name;
  128. return 0;
  129. }
  130. const int spellPowerSkill = caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  131. const int levelPower = getPower(caster->getSpellSchoolLevel(this));
  132. if (id == SpellID::SACRIFICE && sacrificedStack)
  133. healedHealth = (spellPowerSkill + sacrificedStack->MaxHealth() + levelPower) * sacrificedStack->count;
  134. else
  135. healedHealth = spellPowerSkill * power + levelPower; //???
  136. healedHealth = calculateBonus(healedHealth, caster, stack);
  137. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (isRisingSpell() ? stack->baseAmount * stack->MaxHealth() : 0));
  138. }
  139. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  140. {
  141. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  142. }
  143. std::set<const CStack* > CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, PlayerColor casterColor, int spellLvl, BattleHex destination, const CGHeroInstance * caster) const
  144. {
  145. ISpellMechanics::SpellTargetingContext ctx(this, cb,mode,casterColor,spellLvl,destination);
  146. std::set<const CStack* > attackedCres = mechanics->getAffectedStacks(ctx);
  147. //now handle immunities
  148. auto predicate = [&, this](const CStack * s)->bool
  149. {
  150. bool hitDirectly = ctx.ti.alwaysHitDirectly && s->coversPos(destination);
  151. bool notImmune = (ESpellCastProblem::OK == isImmuneByStack(caster, s));
  152. return !(hitDirectly || notImmune);
  153. };
  154. vstd::erase_if(attackedCres, predicate);
  155. return attackedCres;
  156. }
  157. CSpell::ETargetType CSpell::getTargetType() const
  158. {
  159. return targetType;
  160. }
  161. CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  162. {
  163. TargetInfo info(this, level);
  164. return info;
  165. }
  166. bool CSpell::isCombatSpell() const
  167. {
  168. return combatSpell;
  169. }
  170. bool CSpell::isAdventureSpell() const
  171. {
  172. return !combatSpell;
  173. }
  174. bool CSpell::isCreatureAbility() const
  175. {
  176. return creatureAbility;
  177. }
  178. bool CSpell::isPositive() const
  179. {
  180. return positiveness == POSITIVE;
  181. }
  182. bool CSpell::isNegative() const
  183. {
  184. return positiveness == NEGATIVE;
  185. }
  186. bool CSpell::isNeutral() const
  187. {
  188. return positiveness == NEUTRAL;
  189. }
  190. bool CSpell::isHealingSpell() const
  191. {
  192. return isRisingSpell() || (id == SpellID::CURE);
  193. }
  194. bool CSpell::isRisingSpell() const
  195. {
  196. return isRising;
  197. }
  198. bool CSpell::isDamageSpell() const
  199. {
  200. return isDamage;
  201. }
  202. bool CSpell::isOffensiveSpell() const
  203. {
  204. return isOffensive;
  205. }
  206. bool CSpell::isSpecialSpell() const
  207. {
  208. return isSpecial;
  209. }
  210. bool CSpell::hasEffects() const
  211. {
  212. return !levels[0].effects.empty();
  213. }
  214. const std::string& CSpell::getIconImmune() const
  215. {
  216. return iconImmune;
  217. }
  218. const std::string& CSpell::getCastSound() const
  219. {
  220. return castSound;
  221. }
  222. si32 CSpell::getCost(const int skillLevel) const
  223. {
  224. return getLevelInfo(skillLevel).cost;
  225. }
  226. si32 CSpell::getPower(const int skillLevel) const
  227. {
  228. return getLevelInfo(skillLevel).power;
  229. }
  230. //si32 CSpell::calculatePower(const int skillLevel) const
  231. //{
  232. // return power + getPower(skillLevel);
  233. //}
  234. si32 CSpell::getProbability(const TFaction factionId) const
  235. {
  236. if(!vstd::contains(probabilities,factionId))
  237. {
  238. return defaultProbability;
  239. }
  240. return probabilities.at(factionId);
  241. }
  242. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  243. {
  244. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  245. {
  246. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  247. return;
  248. }
  249. const std::vector<Bonus> & effects = levels[level].effects;
  250. if(effects.empty())
  251. {
  252. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  253. return;
  254. }
  255. lst.reserve(lst.size() + effects.size());
  256. for(const Bonus & b : effects)
  257. {
  258. lst.push_back(Bonus(b));
  259. }
  260. }
  261. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  262. {
  263. //todo: use new bonus API
  264. //1. Check absolute limiters
  265. for(auto b : absoluteLimiters)
  266. {
  267. if (!obj->hasBonusOfType(b))
  268. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  269. }
  270. //2. Check absolute immunities
  271. for(auto b : absoluteImmunities)
  272. {
  273. if (obj->hasBonusOfType(b))
  274. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  275. }
  276. //check receptivity
  277. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  278. return ESpellCastProblem::OK;
  279. //3. Check negation
  280. //FIXME: Orb of vulnerability mechanics is not such trivial
  281. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  282. return ESpellCastProblem::NOT_DECIDED;
  283. //4. Check negatable limit
  284. for(auto b : limiters)
  285. {
  286. if (!obj->hasBonusOfType(b))
  287. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  288. }
  289. //5. Check negatable immunities
  290. for(auto b : immunities)
  291. {
  292. if (obj->hasBonusOfType(b))
  293. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  294. }
  295. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  296. {
  297. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  298. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  299. else if(!isPositive()) //negative or indifferent
  300. {
  301. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  302. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  303. }
  304. return ESpellCastProblem::NOT_DECIDED;
  305. };
  306. //6. Check elemental immunities
  307. for(const SpellSchoolInfo & cnf : spellSchoolConfig)
  308. {
  309. if(school.at(cnf.id))
  310. if(battleTestElementalImmunity(cnf.immunityBonus))
  311. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  312. }
  313. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  314. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  315. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  316. {
  317. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  318. }
  319. return ESpellCastProblem::NOT_DECIDED;
  320. }
  321. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance* caster, const CStack* obj) const
  322. {
  323. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  324. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  325. return immuneResult;
  326. return ESpellCastProblem::OK;
  327. }
  328. void CSpell::setIsOffensive(const bool val)
  329. {
  330. isOffensive = val;
  331. if(val)
  332. {
  333. positiveness = CSpell::NEGATIVE;
  334. isDamage = true;
  335. }
  336. }
  337. void CSpell::setIsRising(const bool val)
  338. {
  339. isRising = val;
  340. if(val)
  341. {
  342. positiveness = CSpell::POSITIVE;
  343. }
  344. }
  345. void CSpell::setup()
  346. {
  347. setupMechanics();
  348. school[ESpellSchool::AIR] = air;
  349. school[ESpellSchool::FIRE] = fire;
  350. school[ESpellSchool::WATER] = water;
  351. school[ESpellSchool::EARTH] = earth;
  352. }
  353. void CSpell::setupMechanics()
  354. {
  355. if(nullptr != mechanics)
  356. {
  357. logGlobal->errorStream() << "Spell " << this->name << " mechanics already set";
  358. delete mechanics;
  359. mechanics = nullptr;
  360. }
  361. switch (id)
  362. {
  363. case SpellID::CLONE:
  364. mechanics = new CloneMechanics(this);
  365. break;
  366. case SpellID::DISPEL_HELPFUL_SPELLS:
  367. mechanics = new DispellHelpfulMechanics(this);
  368. break;
  369. case SpellID::SACRIFICE:
  370. mechanics = new SacrificeMechanics(this);
  371. break;
  372. case SpellID::CHAIN_LIGHTNING:
  373. mechanics = new ChainLightningMechanics(this);
  374. break;
  375. case SpellID::FIRE_WALL:
  376. case SpellID::FORCE_FIELD:
  377. mechanics = new WallMechanics(this);
  378. break;
  379. default:
  380. if(isRisingSpell())
  381. mechanics = new SpecialRisingSpellMechanics(this);
  382. else
  383. mechanics = new DefaultSpellMechanics(this);
  384. break;
  385. }
  386. }
  387. ///CSpell::TargetInfo
  388. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  389. {
  390. init(spell, level);
  391. }
  392. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  393. {
  394. init(spell, level);
  395. if(mode == ECastingMode::ENCHANTER_CASTING)
  396. {
  397. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  398. massive = true;
  399. }
  400. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  401. {
  402. alwaysHitDirectly = true;
  403. }
  404. }
  405. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  406. {
  407. auto & levelInfo = spell->getLevelInfo(level);
  408. type = spell->getTargetType();
  409. smart = levelInfo.smartTarget;
  410. massive = levelInfo.range == "X";
  411. onlyAlive = !spell->isRisingSpell();
  412. alwaysHitDirectly = false;
  413. }
  414. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  415. {
  416. int3 diff = pos - center;
  417. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  418. return true;
  419. else
  420. return false;
  421. }
  422. ///CSpellHandler
  423. CSpellHandler::CSpellHandler()
  424. {
  425. }
  426. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  427. {
  428. using namespace SpellConfig;
  429. std::vector<JsonNode> legacyData;
  430. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  431. auto readSchool = [&](JsonMap& schools, const std::string& name)
  432. {
  433. if (parser.readString() == "x")
  434. {
  435. schools[name].Bool() = true;
  436. }
  437. };
  438. auto read = [&,this](bool combat, bool ability)
  439. {
  440. do
  441. {
  442. JsonNode lineNode(JsonNode::DATA_STRUCT);
  443. const si32 id = legacyData.size();
  444. lineNode["index"].Float() = id;
  445. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  446. lineNode["name"].String() = parser.readString();
  447. parser.readString(); //ignored unused abbreviated name
  448. lineNode["level"].Float() = parser.readNumber();
  449. auto& schools = lineNode["school"].Struct();
  450. readSchool(schools, "earth");
  451. readSchool(schools, "water");
  452. readSchool(schools, "fire");
  453. readSchool(schools, "air");
  454. auto& levels = lineNode["levels"].Struct();
  455. auto getLevel = [&](const size_t idx)->JsonMap&
  456. {
  457. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  458. return levels[LEVEL_NAMES[idx]].Struct();
  459. };
  460. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  461. lineNode["power"].Float() = parser.readNumber();
  462. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  463. auto& chances = lineNode["gainChance"].Struct();
  464. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  465. chances[ETownType::names[i]].Float() = parser.readNumber();
  466. }
  467. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  468. std::vector<std::string> descriptions;
  469. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  470. descriptions.push_back(parser.readString());
  471. std::string attributes = parser.readString();
  472. std::string targetType = "NO_TARGET";
  473. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  474. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  475. targetType = "CREATURE_EXPERT_MASSIVE";
  476. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  477. targetType = "CREATURE";
  478. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  479. targetType = "OBSTACLE";
  480. //save parsed level specific data
  481. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  482. {
  483. auto& level = getLevel(i);
  484. level["description"].String() = descriptions[i];
  485. level["cost"].Float() = costs[i];
  486. level["power"].Float() = powers[i];
  487. level["aiValue"].Float() = AIVals[i];
  488. }
  489. if(targetType == "CREATURE_EXPERT_MASSIVE")
  490. {
  491. lineNode["targetType"].String() = "CREATURE";
  492. getLevel(3)["range"].String() = "X";
  493. }
  494. else
  495. {
  496. lineNode["targetType"].String() = targetType;
  497. }
  498. legacyData.push_back(lineNode);
  499. }
  500. while (parser.endLine() && !parser.isNextEntryEmpty());
  501. };
  502. auto skip = [&](int cnt)
  503. {
  504. for(int i=0; i<cnt; i++)
  505. parser.endLine();
  506. };
  507. skip(5);// header
  508. read(false,false); //read adventure map spells
  509. skip(3);
  510. read(true,false); //read battle spells
  511. skip(3);
  512. read(true,true);//read creature abilities
  513. //TODO: maybe move to config
  514. //clone Acid Breath attributes for Acid Breath damage effect
  515. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  516. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  517. legacyData.push_back(temp);
  518. objects.resize(legacyData.size());
  519. return legacyData;
  520. }
  521. const std::string CSpellHandler::getTypeName() const
  522. {
  523. return "spell";
  524. }
  525. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  526. {
  527. using namespace SpellConfig;
  528. CSpell * spell = new CSpell();
  529. const auto type = json["type"].String();
  530. if(type == "ability")
  531. {
  532. spell->creatureAbility = true;
  533. spell->combatSpell = true;
  534. }
  535. else
  536. {
  537. spell->creatureAbility = false;
  538. spell->combatSpell = type == "combat";
  539. }
  540. spell->name = json["name"].String();
  541. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  542. const auto schoolNames = json["school"];
  543. spell->air = schoolNames["air"].Bool();
  544. spell->earth = schoolNames["earth"].Bool();
  545. spell->fire = schoolNames["fire"].Bool();
  546. spell->water = schoolNames["water"].Bool();
  547. spell->level = json["level"].Float();
  548. spell->power = json["power"].Float();
  549. spell->defaultProbability = json["defaultGainChance"].Float();
  550. for(const auto & node : json["gainChance"].Struct())
  551. {
  552. const int chance = node.second.Float();
  553. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  554. {
  555. spell->probabilities[factionID] = chance;
  556. });
  557. }
  558. const std::string targetType = json["targetType"].String();
  559. if(targetType == "NO_TARGET")
  560. spell->targetType = CSpell::NO_TARGET;
  561. else if(targetType == "CREATURE")
  562. spell->targetType = CSpell::CREATURE;
  563. else if(targetType == "OBSTACLE")
  564. spell->targetType = CSpell::OBSTACLE;
  565. else
  566. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  567. spell->mainEffectAnim = json["anim"].Float();
  568. for(const auto & counteredSpell: json["counters"].Struct())
  569. if (counteredSpell.second.Bool())
  570. {
  571. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  572. {
  573. spell->counteredSpells.push_back(SpellID(id));
  574. });
  575. }
  576. //TODO: more error checking - f.e. conflicting flags
  577. const auto flags = json["flags"];
  578. //by default all flags are set to false in constructor
  579. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  580. if(flags["offensive"].Bool())
  581. {
  582. spell->setIsOffensive(true);
  583. }
  584. if(flags["rising"].Bool())
  585. {
  586. spell->setIsRising(true);
  587. }
  588. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  589. if(flags["indifferent"].Bool())
  590. {
  591. spell->positiveness = CSpell::NEUTRAL;
  592. }
  593. else if(flags["negative"].Bool())
  594. {
  595. spell->positiveness = CSpell::NEGATIVE;
  596. }
  597. else if(flags["positive"].Bool())
  598. {
  599. spell->positiveness = CSpell::POSITIVE;
  600. }
  601. else if(!implicitPositiveness)
  602. {
  603. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  604. logGlobal->warnStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL";
  605. }
  606. spell->isSpecial = flags["special"].Bool();
  607. auto findBonus = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  608. {
  609. auto it = bonusNameMap.find(name);
  610. if(it == bonusNameMap.end())
  611. {
  612. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  613. }
  614. else
  615. {
  616. vec.push_back((Bonus::BonusType)it->second);
  617. }
  618. };
  619. auto readBonusStruct = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  620. {
  621. for(auto bonusData: json[name].Struct())
  622. {
  623. const std::string bonusId = bonusData.first;
  624. const bool flag = bonusData.second.Bool();
  625. if(flag)
  626. findBonus(bonusId, vec);
  627. }
  628. };
  629. readBonusStruct("immunity", spell->immunities);
  630. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  631. readBonusStruct("limit", spell->limiters);
  632. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  633. const JsonNode & graphicsNode = json["graphics"];
  634. spell->iconImmune = graphicsNode["iconImmune"].String();
  635. spell->iconBook = graphicsNode["iconBook"].String();
  636. spell->iconEffect = graphicsNode["iconEffect"].String();
  637. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  638. spell->iconScroll = graphicsNode["iconScroll"].String();
  639. const JsonNode & soundsNode = json["sounds"];
  640. spell->castSound = soundsNode["cast"].String();
  641. //load level attributes
  642. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  643. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  644. {
  645. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  646. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  647. const si32 levelPower = levelNode["power"].Float();
  648. levelObject.description = levelNode["description"].String();
  649. levelObject.cost = levelNode["cost"].Float();
  650. levelObject.power = levelPower;
  651. levelObject.AIValue = levelNode["aiValue"].Float();
  652. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  653. levelObject.range = levelNode["range"].String();
  654. for(const auto & elem : levelNode["effects"].Struct())
  655. {
  656. const JsonNode & bonusNode = elem.second;
  657. Bonus * b = JsonUtils::parseBonus(bonusNode);
  658. const bool usePowerAsValue = bonusNode["val"].isNull();
  659. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  660. //b->sid = spell->id; //for all
  661. b->source = Bonus::SPELL_EFFECT;//for all
  662. if(usePowerAsValue)
  663. b->val = levelPower;
  664. levelObject.effects.push_back(*b);
  665. }
  666. }
  667. return spell;
  668. }
  669. void CSpellHandler::afterLoadFinalization()
  670. {
  671. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  672. for(auto spell: objects)
  673. {
  674. for(auto & level: spell->levels)
  675. for(auto & bonus: level.effects)
  676. bonus.sid = spell->id;
  677. spell->setup();
  678. }
  679. }
  680. void CSpellHandler::beforeValidate(JsonNode & object)
  681. {
  682. //handle "base" level info
  683. JsonNode& levels = object["levels"];
  684. JsonNode& base = levels["base"];
  685. auto inheritNode = [&](const std::string & name){
  686. JsonUtils::inherit(levels[name],base);
  687. };
  688. inheritNode("none");
  689. inheritNode("basic");
  690. inheritNode("advanced");
  691. inheritNode("expert");
  692. }
  693. CSpellHandler::~CSpellHandler()
  694. {
  695. }
  696. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  697. {
  698. std::vector<bool> allowedSpells;
  699. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  700. return allowedSpells;
  701. }