CSpellHandler.cpp 26 KB

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