CSpellHandler.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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 "../CGeneralTextHandler.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../JsonNode.h"
  16. #include "../BattleHex.h"
  17. #include "../CModHandler.h"
  18. #include "../StringConstants.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../BattleState.h"
  21. #include "../CBattleCallback.h"
  22. #include "ISpellMechanics.h"
  23. namespace SpellConfig
  24. {
  25. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  26. static const SpellSchoolInfo SCHOOL[4] =
  27. {
  28. {
  29. ESpellSchool::AIR,
  30. Bonus::AIR_SPELL_DMG_PREMY,
  31. Bonus::AIR_IMMUNITY,
  32. "air",
  33. SecondarySkill::AIR_MAGIC,
  34. Bonus::AIR_SPELLS
  35. },
  36. {
  37. ESpellSchool::FIRE,
  38. Bonus::FIRE_SPELL_DMG_PREMY,
  39. Bonus::FIRE_IMMUNITY,
  40. "fire",
  41. SecondarySkill::FIRE_MAGIC,
  42. Bonus::FIRE_SPELLS
  43. },
  44. {
  45. ESpellSchool::WATER,
  46. Bonus::WATER_SPELL_DMG_PREMY,
  47. Bonus::WATER_IMMUNITY,
  48. "water",
  49. SecondarySkill::WATER_MAGIC,
  50. Bonus::WATER_SPELLS
  51. },
  52. {
  53. ESpellSchool::EARTH,
  54. Bonus::EARTH_SPELL_DMG_PREMY,
  55. Bonus::EARTH_IMMUNITY,
  56. "earth",
  57. SecondarySkill::EARTH_MAGIC,
  58. Bonus::EARTH_SPELLS
  59. }
  60. };
  61. }
  62. BattleSpellCastParameters::BattleSpellCastParameters(const BattleInfo* cb)
  63. : spellLvl(0), destination(BattleHex::INVALID), casterSide(0),casterColor(PlayerColor::CANNOT_DETERMINE),caster(nullptr), secHero(nullptr),
  64. usedSpellPower(0),mode(ECastingMode::HERO_CASTING), casterStack(nullptr), selectedStack(nullptr), cb(cb)
  65. {
  66. }
  67. ///CSpell::LevelInfo
  68. CSpell::LevelInfo::LevelInfo()
  69. :description(""),cost(0),power(0),AIValue(0),smartTarget(true), clearTarget(false), clearAffected(false), range("0")
  70. {
  71. }
  72. CSpell::LevelInfo::~LevelInfo()
  73. {
  74. }
  75. ///CSpell
  76. CSpell::CSpell():
  77. id(SpellID::NONE), level(0),
  78. combatSpell(false), creatureAbility(false),
  79. positiveness(ESpellPositiveness::NEUTRAL),
  80. defaultProbability(0),
  81. isRising(false), isDamage(false), isOffensive(false),
  82. targetType(ETargetType::NO_TARGET),
  83. mechanics(nullptr)
  84. {
  85. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  86. }
  87. CSpell::~CSpell()
  88. {
  89. delete mechanics;
  90. }
  91. void CSpell::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  92. {
  93. mechanics->applyBattle(battle, packet);
  94. }
  95. bool CSpell::adventureCast(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  96. {
  97. assert(env);
  98. return mechanics->adventureCast(env, parameters);
  99. }
  100. void CSpell::battleCast(const SpellCastEnvironment * env, BattleSpellCastParameters & parameters) const
  101. {
  102. assert(env);
  103. mechanics->battleCast(env, parameters);
  104. }
  105. bool CSpell::isCastableBy(const IBonusBearer * caster, bool hasSpellBook, const std::set<SpellID> & spellBook) const
  106. {
  107. if(!hasSpellBook)
  108. return false;
  109. const bool inSpellBook = vstd::contains(spellBook, id);
  110. const bool isBonus = caster->hasBonusOfType(Bonus::SPELL, id);
  111. bool inTome = false;
  112. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  113. {
  114. if(caster->hasBonusOfType(cnf.knoledgeBonus))
  115. {
  116. inTome = stop = true;
  117. }
  118. });
  119. if (isSpecialSpell())
  120. {
  121. if (inSpellBook)
  122. {//hero has this spell in spellbook
  123. logGlobal->errorStream() << "Special spell in spellbook "<<name;
  124. }
  125. return isBonus;
  126. }
  127. else
  128. {
  129. return inSpellBook || inTome || isBonus || caster->hasBonusOfType(Bonus::SPELLS_OF_LEVEL, level);
  130. }
  131. }
  132. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  133. {
  134. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  135. {
  136. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  137. throw new std::runtime_error("Invalid school level");
  138. }
  139. return levels.at(level);
  140. }
  141. ui32 CSpell::calculateBonus(ui32 baseDamage, const CGHeroInstance * caster, const CStack * affectedCreature) const
  142. {
  143. ui32 ret = baseDamage;
  144. //applying sorcery secondary skill
  145. if(caster)
  146. {
  147. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  148. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, id.toEnum())) / 100.0;
  149. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  150. {
  151. ret *= (100.0 + caster->valOfBonuses(cnf.damagePremyBonus)) / 100.0;
  152. stop = true; //only bonus from one school is used
  153. });
  154. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  155. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  156. }
  157. return ret;
  158. }
  159. ui32 CSpell::calculateDamage(const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  160. {
  161. ui32 ret = 0; //value to return
  162. //check if spell really does damage - if not, return 0
  163. if(!isDamageSpell())
  164. return 0;
  165. ret = usedSpellPower * power;
  166. ret += getPower(spellSchoolLevel);
  167. //affected creature-specific part
  168. if(nullptr != affectedCreature)
  169. {
  170. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  171. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  172. {
  173. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  174. {
  175. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  176. ret /= 100;
  177. stop = true;//only bonus from one school is used
  178. }
  179. });
  180. //general spell dmg reduction
  181. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  182. {
  183. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  184. ret /= 100;
  185. }
  186. //dmg increasing
  187. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  188. {
  189. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  190. ret /= 100;
  191. }
  192. }
  193. ret = calculateBonus(ret, caster, affectedCreature);
  194. return ret;
  195. }
  196. ESpellCastProblem::ESpellCastProblem CSpell::canBeCasted(const CBattleInfoCallback * cb) const
  197. {
  198. return mechanics->canBeCasted(cb);
  199. }
  200. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  201. {
  202. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  203. }
  204. std::set<const CStack *> CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, PlayerColor casterColor, int spellLvl, BattleHex destination, const CGHeroInstance * caster) const
  205. {
  206. ISpellMechanics::SpellTargetingContext ctx(this, cb,mode,casterColor,spellLvl,destination);
  207. std::set<const CStack* > attackedCres = mechanics->getAffectedStacks(ctx);
  208. //now handle immunities
  209. auto predicate = [&, this](const CStack * s)->bool
  210. {
  211. bool hitDirectly = ctx.ti.alwaysHitDirectly && s->coversPos(destination);
  212. bool notImmune = (ESpellCastProblem::OK == isImmuneByStack(caster, s));
  213. return !(hitDirectly || notImmune);
  214. };
  215. vstd::erase_if(attackedCres, predicate);
  216. return attackedCres;
  217. }
  218. CSpell::ETargetType CSpell::getTargetType() const
  219. {
  220. return targetType;
  221. }
  222. CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  223. {
  224. TargetInfo info(this, level);
  225. return info;
  226. }
  227. void CSpell::forEachSchool(const std::function<void(const SpellSchoolInfo &, bool &)>& cb) const
  228. {
  229. bool stop = false;
  230. for(const SpellSchoolInfo & cnf : SpellConfig::SCHOOL)
  231. {
  232. if(school.at(cnf.id))
  233. {
  234. cb(cnf, stop);
  235. if(stop)
  236. break;
  237. }
  238. }
  239. }
  240. bool CSpell::isCombatSpell() const
  241. {
  242. return combatSpell;
  243. }
  244. bool CSpell::isAdventureSpell() const
  245. {
  246. return !combatSpell;
  247. }
  248. bool CSpell::isCreatureAbility() const
  249. {
  250. return creatureAbility;
  251. }
  252. bool CSpell::isPositive() const
  253. {
  254. return positiveness == POSITIVE;
  255. }
  256. bool CSpell::isNegative() const
  257. {
  258. return positiveness == NEGATIVE;
  259. }
  260. bool CSpell::isNeutral() const
  261. {
  262. return positiveness == NEUTRAL;
  263. }
  264. bool CSpell::isHealingSpell() const
  265. {
  266. return isRisingSpell() || (id == SpellID::CURE);
  267. }
  268. bool CSpell::isRisingSpell() const
  269. {
  270. return isRising;
  271. }
  272. bool CSpell::isDamageSpell() const
  273. {
  274. return isDamage;
  275. }
  276. bool CSpell::isOffensiveSpell() const
  277. {
  278. return isOffensive;
  279. }
  280. bool CSpell::isSpecialSpell() const
  281. {
  282. return isSpecial;
  283. }
  284. bool CSpell::hasEffects() const
  285. {
  286. return !levels[0].effects.empty();
  287. }
  288. const std::string & CSpell::getIconImmune() const
  289. {
  290. return iconImmune;
  291. }
  292. const std::string & CSpell::getCastSound() const
  293. {
  294. return castSound;
  295. }
  296. si32 CSpell::getCost(const int skillLevel) const
  297. {
  298. return getLevelInfo(skillLevel).cost;
  299. }
  300. si32 CSpell::getPower(const int skillLevel) const
  301. {
  302. return getLevelInfo(skillLevel).power;
  303. }
  304. si32 CSpell::getProbability(const TFaction factionId) const
  305. {
  306. if(!vstd::contains(probabilities,factionId))
  307. {
  308. return defaultProbability;
  309. }
  310. return probabilities.at(factionId);
  311. }
  312. void CSpell::getEffects(std::vector<Bonus> & lst, const int level) const
  313. {
  314. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  315. {
  316. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  317. return;
  318. }
  319. const std::vector<Bonus> & effects = levels[level].effects;
  320. if(effects.empty())
  321. {
  322. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  323. return;
  324. }
  325. lst.reserve(lst.size() + effects.size());
  326. for(const Bonus & b : effects)
  327. {
  328. lst.push_back(Bonus(b));
  329. }
  330. }
  331. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneAt(const CBattleInfoCallback * cb, const CGHeroInstance * caster, ECastingMode::ECastingMode mode, BattleHex destination) const
  332. {
  333. // Get all stacks at destination hex. only alive if not rising spell
  334. TStacks stacks = cb->battleGetStacksIf([=](const CStack * s){
  335. return s->coversPos(destination) && (isRisingSpell() || s->alive());
  336. });
  337. if(!stacks.empty())
  338. {
  339. bool allImmune = true;
  340. ESpellCastProblem::ESpellCastProblem problem = ESpellCastProblem::INVALID;
  341. for(auto s : stacks)
  342. {
  343. ESpellCastProblem::ESpellCastProblem res = isImmuneByStack(caster,s);
  344. if(res == ESpellCastProblem::OK)
  345. {
  346. allImmune = false;
  347. }
  348. else
  349. {
  350. problem = res;
  351. }
  352. }
  353. if(allImmune)
  354. return problem;
  355. }
  356. else //no target stack on this tile
  357. {
  358. if(getTargetType() == CSpell::CREATURE)
  359. {
  360. if(caster && mode == ECastingMode::HERO_CASTING) //TODO why???
  361. {
  362. const CSpell::TargetInfo ti(this, caster->getSpellSchoolLevel(this), mode);
  363. if(!ti.massive)
  364. return ESpellCastProblem::WRONG_SPELL_TARGET;
  365. }
  366. else
  367. {
  368. return ESpellCastProblem::WRONG_SPELL_TARGET;
  369. }
  370. }
  371. }
  372. return ESpellCastProblem::OK;
  373. }
  374. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  375. {
  376. //todo: use new bonus API
  377. //1. Check absolute limiters
  378. for(auto b : absoluteLimiters)
  379. {
  380. if (!obj->hasBonusOfType(b))
  381. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  382. }
  383. //2. Check absolute immunities
  384. for(auto b : absoluteImmunities)
  385. {
  386. if (obj->hasBonusOfType(b))
  387. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  388. }
  389. //check receptivity
  390. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  391. return ESpellCastProblem::OK;
  392. //3. Check negation
  393. //FIXME: Orb of vulnerability mechanics is not such trivial
  394. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  395. return ESpellCastProblem::NOT_DECIDED;
  396. //4. Check negatable limit
  397. for(auto b : limiters)
  398. {
  399. if (!obj->hasBonusOfType(b))
  400. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  401. }
  402. //5. Check negatable immunities
  403. for(auto b : immunities)
  404. {
  405. if (obj->hasBonusOfType(b))
  406. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  407. }
  408. //6. Check elemental immunities
  409. ESpellCastProblem::ESpellCastProblem tmp = ESpellCastProblem::NOT_DECIDED;
  410. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  411. {
  412. auto element = cnf.immunityBonus;
  413. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  414. {
  415. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  416. stop = true;
  417. }
  418. else if(!isPositive()) //negative or indifferent
  419. {
  420. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  421. {
  422. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  423. stop = true;
  424. }
  425. }
  426. });
  427. if(tmp != ESpellCastProblem::NOT_DECIDED)
  428. return tmp;
  429. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  430. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  431. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  432. {
  433. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  434. }
  435. return ESpellCastProblem::NOT_DECIDED;
  436. }
  437. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance * caster, const CStack * obj) const
  438. {
  439. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  440. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  441. return immuneResult;
  442. return ESpellCastProblem::OK;
  443. }
  444. void CSpell::setIsOffensive(const bool val)
  445. {
  446. isOffensive = val;
  447. if(val)
  448. {
  449. positiveness = CSpell::NEGATIVE;
  450. isDamage = true;
  451. }
  452. }
  453. void CSpell::setIsRising(const bool val)
  454. {
  455. isRising = val;
  456. if(val)
  457. {
  458. positiveness = CSpell::POSITIVE;
  459. }
  460. }
  461. void CSpell::setup()
  462. {
  463. setupMechanics();
  464. }
  465. void CSpell::setupMechanics()
  466. {
  467. if(nullptr != mechanics)
  468. {
  469. logGlobal->errorStream() << "Spell " << this->name << ": mechanics already set";
  470. delete mechanics;
  471. }
  472. mechanics = ISpellMechanics::createMechanics(this);
  473. }
  474. ///CSpell::AnimationInfo
  475. CSpell::AnimationInfo::AnimationInfo()
  476. {
  477. }
  478. CSpell::AnimationInfo::~AnimationInfo()
  479. {
  480. }
  481. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  482. {
  483. std::string res;
  484. double maximum = 0.0;
  485. for(const auto & info : projectile)
  486. {
  487. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  488. {
  489. maximum = info.minimumAngle;
  490. res = info.resourceName;
  491. }
  492. }
  493. return std::move(res);
  494. }
  495. ///CSpell::TargetInfo
  496. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  497. {
  498. init(spell, level);
  499. }
  500. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  501. {
  502. init(spell, level);
  503. if(mode == ECastingMode::ENCHANTER_CASTING)
  504. {
  505. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  506. massive = true;
  507. }
  508. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  509. {
  510. alwaysHitDirectly = true;
  511. }
  512. }
  513. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  514. {
  515. auto & levelInfo = spell->getLevelInfo(level);
  516. type = spell->getTargetType();
  517. smart = levelInfo.smartTarget;
  518. massive = levelInfo.range == "X";
  519. onlyAlive = !spell->isRisingSpell();
  520. alwaysHitDirectly = false;
  521. clearAffected = levelInfo.clearAffected;
  522. clearTarget = levelInfo.clearTarget;
  523. }
  524. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  525. {
  526. int3 diff = pos - center;
  527. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  528. return true;
  529. else
  530. return false;
  531. }
  532. ///CSpellHandler
  533. CSpellHandler::CSpellHandler()
  534. {
  535. }
  536. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  537. {
  538. using namespace SpellConfig;
  539. std::vector<JsonNode> legacyData;
  540. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  541. auto readSchool = [&](JsonMap & schools, const std::string & name)
  542. {
  543. if (parser.readString() == "x")
  544. {
  545. schools[name].Bool() = true;
  546. }
  547. };
  548. auto read = [&,this](bool combat, bool ability)
  549. {
  550. do
  551. {
  552. JsonNode lineNode(JsonNode::DATA_STRUCT);
  553. const si32 id = legacyData.size();
  554. lineNode["index"].Float() = id;
  555. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  556. lineNode["name"].String() = parser.readString();
  557. parser.readString(); //ignored unused abbreviated name
  558. lineNode["level"].Float() = parser.readNumber();
  559. auto& schools = lineNode["school"].Struct();
  560. readSchool(schools, "earth");
  561. readSchool(schools, "water");
  562. readSchool(schools, "fire");
  563. readSchool(schools, "air");
  564. auto& levels = lineNode["levels"].Struct();
  565. auto getLevel = [&](const size_t idx)->JsonMap&
  566. {
  567. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  568. return levels[LEVEL_NAMES[idx]].Struct();
  569. };
  570. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  571. lineNode["power"].Float() = parser.readNumber();
  572. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  573. auto& chances = lineNode["gainChance"].Struct();
  574. for(size_t i = 0; i < GameConstants::F_NUMBER; i++){
  575. chances[ETownType::names[i]].Float() = parser.readNumber();
  576. }
  577. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  578. std::vector<std::string> descriptions;
  579. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  580. descriptions.push_back(parser.readString());
  581. parser.readString(); //ignore attributes. All data present in JSON
  582. //save parsed level specific data
  583. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  584. {
  585. auto& level = getLevel(i);
  586. level["description"].String() = descriptions[i];
  587. level["cost"].Float() = costs[i];
  588. level["power"].Float() = powers[i];
  589. level["aiValue"].Float() = AIVals[i];
  590. }
  591. legacyData.push_back(lineNode);
  592. }
  593. while (parser.endLine() && !parser.isNextEntryEmpty());
  594. };
  595. auto skip = [&](int cnt)
  596. {
  597. for(int i=0; i<cnt; i++)
  598. parser.endLine();
  599. };
  600. skip(5);// header
  601. read(false,false); //read adventure map spells
  602. skip(3);
  603. read(true,false); //read battle spells
  604. skip(3);
  605. read(true,true);//read creature abilities
  606. //TODO: maybe move to config
  607. //clone Acid Breath attributes for Acid Breath damage effect
  608. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  609. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  610. legacyData.push_back(temp);
  611. objects.resize(legacyData.size());
  612. return legacyData;
  613. }
  614. const std::string CSpellHandler::getTypeName() const
  615. {
  616. return "spell";
  617. }
  618. CSpell * CSpellHandler::loadFromJson(const JsonNode & json)
  619. {
  620. using namespace SpellConfig;
  621. CSpell * spell = new CSpell();
  622. const auto type = json["type"].String();
  623. if(type == "ability")
  624. {
  625. spell->creatureAbility = true;
  626. spell->combatSpell = true;
  627. }
  628. else
  629. {
  630. spell->creatureAbility = false;
  631. spell->combatSpell = type == "combat";
  632. }
  633. spell->name = json["name"].String();
  634. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  635. const auto schoolNames = json["school"];
  636. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  637. {
  638. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  639. }
  640. spell->level = json["level"].Float();
  641. spell->power = json["power"].Float();
  642. spell->defaultProbability = json["defaultGainChance"].Float();
  643. for(const auto & node : json["gainChance"].Struct())
  644. {
  645. const int chance = node.second.Float();
  646. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  647. {
  648. spell->probabilities[factionID] = chance;
  649. });
  650. }
  651. auto targetType = json["targetType"].String();
  652. if(targetType == "NO_TARGET")
  653. spell->targetType = CSpell::NO_TARGET;
  654. else if(targetType == "CREATURE")
  655. spell->targetType = CSpell::CREATURE;
  656. else if(targetType == "OBSTACLE")
  657. spell->targetType = CSpell::OBSTACLE;
  658. else if(targetType == "LOCATION")
  659. spell->targetType = CSpell::LOCATION;
  660. else
  661. logGlobal->warnStream() << "Spell " << spell->name << ": target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ", assumed NO_TARGET.";
  662. for(const auto & counteredSpell: json["counters"].Struct())
  663. if (counteredSpell.second.Bool())
  664. {
  665. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  666. {
  667. spell->counteredSpells.push_back(SpellID(id));
  668. });
  669. }
  670. //TODO: more error checking - f.e. conflicting flags
  671. const auto flags = json["flags"];
  672. //by default all flags are set to false in constructor
  673. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  674. if(flags["offensive"].Bool())
  675. {
  676. spell->setIsOffensive(true);
  677. }
  678. if(flags["rising"].Bool())
  679. {
  680. spell->setIsRising(true);
  681. }
  682. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  683. if(flags["indifferent"].Bool())
  684. {
  685. spell->positiveness = CSpell::NEUTRAL;
  686. }
  687. else if(flags["negative"].Bool())
  688. {
  689. spell->positiveness = CSpell::NEGATIVE;
  690. }
  691. else if(flags["positive"].Bool())
  692. {
  693. spell->positiveness = CSpell::POSITIVE;
  694. }
  695. else if(!implicitPositiveness)
  696. {
  697. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  698. logGlobal->errorStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL.";
  699. }
  700. spell->isSpecial = flags["special"].Bool();
  701. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  702. {
  703. auto it = bonusNameMap.find(name);
  704. if(it == bonusNameMap.end())
  705. {
  706. logGlobal->errorStream() << "Spell " << spell->name << ": invalid bonus name " << name;
  707. }
  708. else
  709. {
  710. vec.push_back((Bonus::BonusType)it->second);
  711. }
  712. };
  713. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  714. {
  715. for(auto bonusData: json[name].Struct())
  716. {
  717. const std::string bonusId = bonusData.first;
  718. const bool flag = bonusData.second.Bool();
  719. if(flag)
  720. findBonus(bonusId, vec);
  721. }
  722. };
  723. readBonusStruct("immunity", spell->immunities);
  724. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  725. readBonusStruct("limit", spell->limiters);
  726. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  727. const JsonNode & graphicsNode = json["graphics"];
  728. spell->iconImmune = graphicsNode["iconImmune"].String();
  729. spell->iconBook = graphicsNode["iconBook"].String();
  730. spell->iconEffect = graphicsNode["iconEffect"].String();
  731. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  732. spell->iconScroll = graphicsNode["iconScroll"].String();
  733. const JsonNode & animationNode = json["animation"];
  734. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  735. {
  736. auto queueNode = animationNode[jsonName].Vector();
  737. for(const JsonNode & item : queueNode)
  738. {
  739. CSpell::TAnimation newItem;
  740. newItem.verticalPosition = VerticalPosition::TOP;
  741. if(item.getType() == JsonNode::DATA_STRING)
  742. newItem.resourceName = item.String();
  743. else if(item.getType() == JsonNode::DATA_STRUCT)
  744. {
  745. newItem.resourceName = item["defName"].String();
  746. auto vPosStr = item["verticalPosition"].String();
  747. if("bottom" == vPosStr)
  748. newItem.verticalPosition = VerticalPosition::BOTTOM;
  749. }
  750. q.push_back(newItem);
  751. }
  752. };
  753. loadAnimationQueue("affect", spell->animationInfo.affect);
  754. loadAnimationQueue("cast", spell->animationInfo.cast);
  755. loadAnimationQueue("hit", spell->animationInfo.hit);
  756. const JsonVector & projectile = animationNode["projectile"].Vector();
  757. for(const JsonNode & item : projectile)
  758. {
  759. CSpell::ProjectileInfo info;
  760. info.resourceName = item["defName"].String();
  761. info.minimumAngle = item["minimumAngle"].Float();
  762. spell->animationInfo.projectile.push_back(info);
  763. }
  764. const JsonNode & soundsNode = json["sounds"];
  765. spell->castSound = soundsNode["cast"].String();
  766. //load level attributes
  767. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  768. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  769. {
  770. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  771. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  772. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  773. levelObject.description = levelNode["description"].String();
  774. levelObject.cost = levelNode["cost"].Float();
  775. levelObject.AIValue = levelNode["aiValue"].Float();
  776. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  777. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  778. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  779. levelObject.range = levelNode["range"].String();
  780. for(const auto & elem : levelNode["effects"].Struct())
  781. {
  782. const JsonNode & bonusNode = elem.second;
  783. Bonus * b = JsonUtils::parseBonus(bonusNode);
  784. const bool usePowerAsValue = bonusNode["val"].isNull();
  785. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  786. //b->sid = spell->id; //for all
  787. b->source = Bonus::SPELL_EFFECT;//for all
  788. if(usePowerAsValue)
  789. b->val = levelPower;
  790. levelObject.effects.push_back(*b);
  791. }
  792. }
  793. return spell;
  794. }
  795. void CSpellHandler::afterLoadFinalization()
  796. {
  797. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  798. for(auto spell: objects)
  799. {
  800. for(auto & level: spell->levels)
  801. for(auto & bonus: level.effects)
  802. bonus.sid = spell->id;
  803. spell->setup();
  804. }
  805. }
  806. void CSpellHandler::beforeValidate(JsonNode & object)
  807. {
  808. //handle "base" level info
  809. JsonNode & levels = object["levels"];
  810. JsonNode & base = levels["base"];
  811. auto inheritNode = [&](const std::string & name){
  812. JsonUtils::inherit(levels[name],base);
  813. };
  814. inheritNode("none");
  815. inheritNode("basic");
  816. inheritNode("advanced");
  817. inheritNode("expert");
  818. }
  819. CSpellHandler::~CSpellHandler()
  820. {
  821. }
  822. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  823. {
  824. std::vector<bool> allowedSpells;
  825. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  826. return allowedSpells;
  827. }