CSpellHandler.cpp 27 KB

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