CSpellHandler.cpp 26 KB

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