CSpellHandler.cpp 26 KB

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