CSpellHandler.cpp 28 KB

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