CSpellHandler.cpp 26 KB

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