CSpellHandler.cpp 28 KB

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