CSpellHandler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  1. #include "StdInc.h"
  2. #include "CSpellHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "JsonNode.h"
  6. #include <cctype>
  7. #include "BattleHex.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. #include "mapObjects/CGHeroInstance.h"
  11. #include "BattleState.h"
  12. #include "CBattleCallback.h"
  13. #include "SpellMechanics.h"
  14. /*
  15. * CSpellHandler.cpp, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. namespace SpellConfig
  24. {
  25. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  26. static const SpellSchoolInfo SCHOOL[4] =
  27. {
  28. {
  29. ESpellSchool::AIR,
  30. Bonus::AIR_SPELL_DMG_PREMY,
  31. Bonus::AIR_IMMUNITY,
  32. "air",
  33. SecondarySkill::AIR_MAGIC,
  34. Bonus::AIR_SPELLS
  35. },
  36. {
  37. ESpellSchool::FIRE,
  38. Bonus::FIRE_SPELL_DMG_PREMY,
  39. Bonus::FIRE_IMMUNITY,
  40. "fire",
  41. SecondarySkill::FIRE_MAGIC,
  42. Bonus::FIRE_SPELLS
  43. },
  44. {
  45. ESpellSchool::WATER,
  46. Bonus::WATER_SPELL_DMG_PREMY,
  47. Bonus::WATER_IMMUNITY,
  48. "water",
  49. SecondarySkill::WATER_MAGIC,
  50. Bonus::WATER_SPELLS
  51. },
  52. {
  53. ESpellSchool::EARTH,
  54. Bonus::EARTH_SPELL_DMG_PREMY,
  55. Bonus::EARTH_IMMUNITY,
  56. "earth",
  57. SecondarySkill::EARTH_MAGIC,
  58. Bonus::EARTH_SPELLS
  59. }
  60. };
  61. }
  62. BattleSpellCastParameters::BattleSpellCastParameters(const BattleInfo* cb)
  63. : spellLvl(0), destination(BattleHex::INVALID), casterSide(0),casterColor(PlayerColor::CANNOT_DETERMINE),caster(nullptr), secHero(nullptr),
  64. usedSpellPower(0),mode(ECastingMode::HERO_CASTING), casterStack(nullptr), selectedStack(nullptr), cb(cb)
  65. {
  66. }
  67. ///CSpell::LevelInfo
  68. CSpell::LevelInfo::LevelInfo()
  69. :description(""),cost(0),power(0),AIValue(0),smartTarget(true), clearTarget(false), clearAffected(false), range("0")
  70. {
  71. }
  72. CSpell::LevelInfo::~LevelInfo()
  73. {
  74. }
  75. ///CSpell
  76. CSpell::CSpell():
  77. id(SpellID::NONE), level(0),
  78. earth(false), water(false), fire(false), air(false),
  79. combatSpell(false), creatureAbility(false),
  80. positiveness(ESpellPositiveness::NEUTRAL),
  81. defaultProbability(0),
  82. isRising(false), isDamage(false), isOffensive(false),
  83. targetType(ETargetType::NO_TARGET),
  84. mechanics(nullptr)
  85. {
  86. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  87. }
  88. CSpell::~CSpell()
  89. {
  90. delete mechanics;
  91. }
  92. void CSpell::afterCast(BattleInfo * battle, const BattleSpellCast * packet) const
  93. {
  94. mechanics->afterCast(battle, packet);
  95. }
  96. bool CSpell::adventureCast(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  97. {
  98. assert(env);
  99. return mechanics->adventureCast(env, parameters);
  100. }
  101. void CSpell::battleCast(const SpellCastEnvironment * env, BattleSpellCastParameters & parameters) const
  102. {
  103. assert(env);
  104. mechanics->battleCast(env, parameters);
  105. }
  106. bool CSpell::isCastableBy(const IBonusBearer * caster, bool hasSpellBook, const std::set<SpellID> & spellBook) const
  107. {
  108. if(!hasSpellBook)
  109. return false;
  110. const bool inSpellBook = vstd::contains(spellBook, id);
  111. const bool isBonus = caster->hasBonusOfType(Bonus::SPELL, id);
  112. bool inTome = false;
  113. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  114. {
  115. if(caster->hasBonusOfType(cnf.knoledgeBonus))
  116. {
  117. inTome = stop = true;
  118. }
  119. });
  120. if (isSpecialSpell())
  121. {
  122. if (inSpellBook)
  123. {//hero has this spell in spellbook
  124. logGlobal->errorStream() << "Special spell in spellbook "<<name;
  125. }
  126. return isBonus;
  127. }
  128. else
  129. {
  130. return inSpellBook || inTome || isBonus || caster->hasBonusOfType(Bonus::SPELLS_OF_LEVEL, level);
  131. }
  132. }
  133. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  134. {
  135. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  136. {
  137. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  138. throw new std::runtime_error("Invalid school level");
  139. }
  140. return levels.at(level);
  141. }
  142. ui32 CSpell::calculateBonus(ui32 baseDamage, const CGHeroInstance* caster, const CStack* affectedCreature) const
  143. {
  144. ui32 ret = baseDamage;
  145. //applying sorcery secondary skill
  146. if(caster)
  147. {
  148. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  149. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, id.toEnum())) / 100.0;
  150. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  151. {
  152. ret *= (100.0 + caster->valOfBonuses(cnf.damagePremyBonus)) / 100.0;
  153. stop = true; //only bonus from one school is used
  154. });
  155. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  156. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  157. }
  158. return ret;
  159. }
  160. ui32 CSpell::calculateDamage(const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  161. {
  162. ui32 ret = 0; //value to return
  163. //check if spell really does damage - if not, return 0
  164. if(!isDamageSpell())
  165. return 0;
  166. ret = usedSpellPower * power;
  167. ret += getPower(spellSchoolLevel);
  168. //affected creature-specific part
  169. if(nullptr != affectedCreature)
  170. {
  171. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  172. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  173. {
  174. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  175. {
  176. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  177. ret /= 100;
  178. stop = true;//only bonus from one school is used
  179. }
  180. });
  181. //general spell dmg reduction
  182. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  183. {
  184. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  185. ret /= 100;
  186. }
  187. //dmg increasing
  188. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  189. {
  190. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  191. ret /= 100;
  192. }
  193. }
  194. ret = calculateBonus(ret, caster, affectedCreature);
  195. return ret;
  196. }
  197. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  198. {
  199. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  200. }
  201. std::set<const CStack* > CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, PlayerColor casterColor, int spellLvl, BattleHex destination, const CGHeroInstance * caster) const
  202. {
  203. ISpellMechanics::SpellTargetingContext ctx(this, cb,mode,casterColor,spellLvl,destination);
  204. std::set<const CStack* > attackedCres = mechanics->getAffectedStacks(ctx);
  205. //now handle immunities
  206. auto predicate = [&, this](const CStack * s)->bool
  207. {
  208. bool hitDirectly = ctx.ti.alwaysHitDirectly && s->coversPos(destination);
  209. bool notImmune = (ESpellCastProblem::OK == isImmuneByStack(caster, s));
  210. return !(hitDirectly || notImmune);
  211. };
  212. vstd::erase_if(attackedCres, predicate);
  213. return attackedCres;
  214. }
  215. CSpell::ETargetType CSpell::getTargetType() const
  216. {
  217. return targetType;
  218. }
  219. CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  220. {
  221. TargetInfo info(this, level);
  222. return info;
  223. }
  224. void CSpell::forEachSchool(const std::function<void(const SpellSchoolInfo &, bool &)>& cb) const
  225. {
  226. bool stop = false;
  227. for(const SpellSchoolInfo & cnf : SpellConfig::SCHOOL)
  228. {
  229. if(school.at(cnf.id))
  230. {
  231. cb(cnf, stop);
  232. if(stop)
  233. break;
  234. }
  235. }
  236. }
  237. bool CSpell::isCombatSpell() const
  238. {
  239. return combatSpell;
  240. }
  241. bool CSpell::isAdventureSpell() const
  242. {
  243. return !combatSpell;
  244. }
  245. bool CSpell::isCreatureAbility() const
  246. {
  247. return creatureAbility;
  248. }
  249. bool CSpell::isPositive() const
  250. {
  251. return positiveness == POSITIVE;
  252. }
  253. bool CSpell::isNegative() const
  254. {
  255. return positiveness == NEGATIVE;
  256. }
  257. bool CSpell::isNeutral() const
  258. {
  259. return positiveness == NEUTRAL;
  260. }
  261. bool CSpell::isHealingSpell() const
  262. {
  263. return isRisingSpell() || (id == SpellID::CURE);
  264. }
  265. bool CSpell::isRisingSpell() const
  266. {
  267. return isRising;
  268. }
  269. bool CSpell::isDamageSpell() const
  270. {
  271. return isDamage;
  272. }
  273. bool CSpell::isOffensiveSpell() const
  274. {
  275. return isOffensive;
  276. }
  277. bool CSpell::isSpecialSpell() const
  278. {
  279. return isSpecial;
  280. }
  281. bool CSpell::hasEffects() const
  282. {
  283. return !levels[0].effects.empty();
  284. }
  285. const std::string& CSpell::getIconImmune() const
  286. {
  287. return iconImmune;
  288. }
  289. const std::string& CSpell::getCastSound() const
  290. {
  291. return castSound;
  292. }
  293. si32 CSpell::getCost(const int skillLevel) const
  294. {
  295. return getLevelInfo(skillLevel).cost;
  296. }
  297. si32 CSpell::getPower(const int skillLevel) const
  298. {
  299. return getLevelInfo(skillLevel).power;
  300. }
  301. si32 CSpell::getProbability(const TFaction factionId) const
  302. {
  303. if(!vstd::contains(probabilities,factionId))
  304. {
  305. return defaultProbability;
  306. }
  307. return probabilities.at(factionId);
  308. }
  309. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  310. {
  311. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  312. {
  313. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  314. return;
  315. }
  316. const std::vector<Bonus> & effects = levels[level].effects;
  317. if(effects.empty())
  318. {
  319. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  320. return;
  321. }
  322. lst.reserve(lst.size() + effects.size());
  323. for(const Bonus & b : effects)
  324. {
  325. lst.push_back(Bonus(b));
  326. }
  327. }
  328. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneAt(const CBattleInfoCallback * cb, const CGHeroInstance * caster, ECastingMode::ECastingMode mode, BattleHex destination) const
  329. {
  330. // Get all stacks at destination hex. only alive if not rising spell
  331. TStacks stacks = cb->battleGetStacksIf([=](const CStack * s){
  332. return s->coversPos(destination) && (isRisingSpell() || s->alive());
  333. });
  334. if(!stacks.empty())
  335. {
  336. bool allImmune = true;
  337. ESpellCastProblem::ESpellCastProblem problem;
  338. for(auto s : stacks)
  339. {
  340. ESpellCastProblem::ESpellCastProblem res = isImmuneByStack(caster,s);
  341. if(res == ESpellCastProblem::OK)
  342. {
  343. allImmune = false;
  344. }
  345. else
  346. {
  347. problem = res;
  348. }
  349. }
  350. if(allImmune)
  351. return problem;
  352. }
  353. else //no target stack on this tile
  354. {
  355. if(getTargetType() == CSpell::CREATURE)
  356. {
  357. if(caster && mode == ECastingMode::HERO_CASTING) //TODO why???
  358. {
  359. const CSpell::TargetInfo ti(this, caster->getSpellSchoolLevel(this), mode);
  360. if(!ti.massive)
  361. return ESpellCastProblem::WRONG_SPELL_TARGET;
  362. }
  363. else
  364. {
  365. return ESpellCastProblem::WRONG_SPELL_TARGET;
  366. }
  367. }
  368. }
  369. return ESpellCastProblem::OK;
  370. }
  371. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  372. {
  373. //todo: use new bonus API
  374. //1. Check absolute limiters
  375. for(auto b : absoluteLimiters)
  376. {
  377. if (!obj->hasBonusOfType(b))
  378. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  379. }
  380. //2. Check absolute immunities
  381. for(auto b : absoluteImmunities)
  382. {
  383. if (obj->hasBonusOfType(b))
  384. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  385. }
  386. //check receptivity
  387. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  388. return ESpellCastProblem::OK;
  389. //3. Check negation
  390. //FIXME: Orb of vulnerability mechanics is not such trivial
  391. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  392. return ESpellCastProblem::NOT_DECIDED;
  393. //4. Check negatable limit
  394. for(auto b : limiters)
  395. {
  396. if (!obj->hasBonusOfType(b))
  397. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  398. }
  399. //5. Check negatable immunities
  400. for(auto b : immunities)
  401. {
  402. if (obj->hasBonusOfType(b))
  403. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  404. }
  405. //6. Check elemental immunities
  406. ESpellCastProblem::ESpellCastProblem tmp = ESpellCastProblem::NOT_DECIDED;
  407. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  408. {
  409. auto element = cnf.immunityBonus;
  410. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  411. {
  412. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  413. stop = true;
  414. }
  415. else if(!isPositive()) //negative or indifferent
  416. {
  417. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  418. {
  419. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  420. stop = true;
  421. }
  422. }
  423. });
  424. if(tmp != ESpellCastProblem::NOT_DECIDED)
  425. return tmp;
  426. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  427. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  428. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  429. {
  430. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  431. }
  432. return ESpellCastProblem::NOT_DECIDED;
  433. }
  434. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance* caster, const CStack* obj) const
  435. {
  436. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  437. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  438. return immuneResult;
  439. return ESpellCastProblem::OK;
  440. }
  441. void CSpell::setIsOffensive(const bool val)
  442. {
  443. isOffensive = val;
  444. if(val)
  445. {
  446. positiveness = CSpell::NEGATIVE;
  447. isDamage = true;
  448. }
  449. }
  450. void CSpell::setIsRising(const bool val)
  451. {
  452. isRising = val;
  453. if(val)
  454. {
  455. positiveness = CSpell::POSITIVE;
  456. }
  457. }
  458. void CSpell::setup()
  459. {
  460. setupMechanics();
  461. air = school[ESpellSchool::AIR];
  462. fire = school[ESpellSchool::FIRE];
  463. water = school[ESpellSchool::WATER];
  464. earth = school[ESpellSchool::EARTH];
  465. }
  466. void CSpell::setupMechanics()
  467. {
  468. if(nullptr != mechanics)
  469. {
  470. logGlobal->errorStream() << "Spell " << this->name << " mechanics already set";
  471. delete mechanics;
  472. }
  473. mechanics = ISpellMechanics::createMechanics(this);
  474. }
  475. ///CSpell::AnimationInfo
  476. CSpell::AnimationInfo::AnimationInfo()
  477. {
  478. }
  479. CSpell::AnimationInfo::~AnimationInfo()
  480. {
  481. }
  482. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  483. {
  484. std::string res;
  485. double maximum = 0.0;
  486. for(const auto & info : projectile)
  487. {
  488. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  489. {
  490. maximum = info.minimumAngle;
  491. res = info.resourceName;
  492. }
  493. }
  494. return std::move(res);
  495. }
  496. ///CSpell::TargetInfo
  497. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  498. {
  499. init(spell, level);
  500. }
  501. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  502. {
  503. init(spell, level);
  504. if(mode == ECastingMode::ENCHANTER_CASTING)
  505. {
  506. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  507. massive = true;
  508. }
  509. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  510. {
  511. alwaysHitDirectly = true;
  512. }
  513. }
  514. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  515. {
  516. auto & levelInfo = spell->getLevelInfo(level);
  517. type = spell->getTargetType();
  518. smart = levelInfo.smartTarget;
  519. massive = levelInfo.range == "X";
  520. onlyAlive = !spell->isRisingSpell();
  521. alwaysHitDirectly = false;
  522. clearAffected = levelInfo.clearAffected;
  523. clearTarget = levelInfo.clearTarget;
  524. }
  525. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  526. {
  527. int3 diff = pos - center;
  528. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  529. return true;
  530. else
  531. return false;
  532. }
  533. ///CSpellHandler
  534. CSpellHandler::CSpellHandler()
  535. {
  536. }
  537. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  538. {
  539. using namespace SpellConfig;
  540. std::vector<JsonNode> legacyData;
  541. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  542. auto readSchool = [&](JsonMap& schools, const std::string& name)
  543. {
  544. if (parser.readString() == "x")
  545. {
  546. schools[name].Bool() = true;
  547. }
  548. };
  549. auto read = [&,this](bool combat, bool ability)
  550. {
  551. do
  552. {
  553. JsonNode lineNode(JsonNode::DATA_STRUCT);
  554. const si32 id = legacyData.size();
  555. lineNode["index"].Float() = id;
  556. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  557. lineNode["name"].String() = parser.readString();
  558. parser.readString(); //ignored unused abbreviated name
  559. lineNode["level"].Float() = parser.readNumber();
  560. auto& schools = lineNode["school"].Struct();
  561. readSchool(schools, "earth");
  562. readSchool(schools, "water");
  563. readSchool(schools, "fire");
  564. readSchool(schools, "air");
  565. auto& levels = lineNode["levels"].Struct();
  566. auto getLevel = [&](const size_t idx)->JsonMap&
  567. {
  568. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  569. return levels[LEVEL_NAMES[idx]].Struct();
  570. };
  571. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  572. lineNode["power"].Float() = parser.readNumber();
  573. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  574. auto& chances = lineNode["gainChance"].Struct();
  575. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  576. chances[ETownType::names[i]].Float() = parser.readNumber();
  577. }
  578. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  579. std::vector<std::string> descriptions;
  580. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  581. descriptions.push_back(parser.readString());
  582. parser.readString(); //ignore attributes. All data present in JSON
  583. //save parsed level specific data
  584. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  585. {
  586. auto& level = getLevel(i);
  587. level["description"].String() = descriptions[i];
  588. level["cost"].Float() = costs[i];
  589. level["power"].Float() = powers[i];
  590. level["aiValue"].Float() = AIVals[i];
  591. }
  592. legacyData.push_back(lineNode);
  593. }
  594. while (parser.endLine() && !parser.isNextEntryEmpty());
  595. };
  596. auto skip = [&](int cnt)
  597. {
  598. for(int i=0; i<cnt; i++)
  599. parser.endLine();
  600. };
  601. skip(5);// header
  602. read(false,false); //read adventure map spells
  603. skip(3);
  604. read(true,false); //read battle spells
  605. skip(3);
  606. read(true,true);//read creature abilities
  607. //TODO: maybe move to config
  608. //clone Acid Breath attributes for Acid Breath damage effect
  609. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  610. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  611. legacyData.push_back(temp);
  612. objects.resize(legacyData.size());
  613. return legacyData;
  614. }
  615. const std::string CSpellHandler::getTypeName() const
  616. {
  617. return "spell";
  618. }
  619. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  620. {
  621. using namespace SpellConfig;
  622. CSpell * spell = new CSpell();
  623. const auto type = json["type"].String();
  624. if(type == "ability")
  625. {
  626. spell->creatureAbility = true;
  627. spell->combatSpell = true;
  628. }
  629. else
  630. {
  631. spell->creatureAbility = false;
  632. spell->combatSpell = type == "combat";
  633. }
  634. spell->name = json["name"].String();
  635. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  636. const auto schoolNames = json["school"];
  637. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  638. {
  639. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  640. }
  641. spell->level = json["level"].Float();
  642. spell->power = json["power"].Float();
  643. spell->defaultProbability = json["defaultGainChance"].Float();
  644. for(const auto & node : json["gainChance"].Struct())
  645. {
  646. const int chance = node.second.Float();
  647. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  648. {
  649. spell->probabilities[factionID] = chance;
  650. });
  651. }
  652. auto targetType = json["targetType"].String();
  653. if(targetType == "NO_TARGET")
  654. spell->targetType = CSpell::NO_TARGET;
  655. else if(targetType == "CREATURE")
  656. spell->targetType = CSpell::CREATURE;
  657. else if(targetType == "OBSTACLE")
  658. spell->targetType = CSpell::OBSTACLE;
  659. else if(targetType == "LOCATION")
  660. spell->targetType = CSpell::LOCATION;
  661. else
  662. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  663. for(const auto & counteredSpell: json["counters"].Struct())
  664. if (counteredSpell.second.Bool())
  665. {
  666. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  667. {
  668. spell->counteredSpells.push_back(SpellID(id));
  669. });
  670. }
  671. //TODO: more error checking - f.e. conflicting flags
  672. const auto flags = json["flags"];
  673. //by default all flags are set to false in constructor
  674. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  675. if(flags["offensive"].Bool())
  676. {
  677. spell->setIsOffensive(true);
  678. }
  679. if(flags["rising"].Bool())
  680. {
  681. spell->setIsRising(true);
  682. }
  683. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  684. if(flags["indifferent"].Bool())
  685. {
  686. spell->positiveness = CSpell::NEUTRAL;
  687. }
  688. else if(flags["negative"].Bool())
  689. {
  690. spell->positiveness = CSpell::NEGATIVE;
  691. }
  692. else if(flags["positive"].Bool())
  693. {
  694. spell->positiveness = CSpell::POSITIVE;
  695. }
  696. else if(!implicitPositiveness)
  697. {
  698. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  699. logGlobal->errorStream() << "No positiveness specified, assumed NEUTRAL";
  700. }
  701. spell->isSpecial = flags["special"].Bool();
  702. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  703. {
  704. auto it = bonusNameMap.find(name);
  705. if(it == bonusNameMap.end())
  706. {
  707. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  708. }
  709. else
  710. {
  711. vec.push_back((Bonus::BonusType)it->second);
  712. }
  713. };
  714. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  715. {
  716. for(auto bonusData: json[name].Struct())
  717. {
  718. const std::string bonusId = bonusData.first;
  719. const bool flag = bonusData.second.Bool();
  720. if(flag)
  721. findBonus(bonusId, vec);
  722. }
  723. };
  724. readBonusStruct("immunity", spell->immunities);
  725. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  726. readBonusStruct("limit", spell->limiters);
  727. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  728. const JsonNode & graphicsNode = json["graphics"];
  729. spell->iconImmune = graphicsNode["iconImmune"].String();
  730. spell->iconBook = graphicsNode["iconBook"].String();
  731. spell->iconEffect = graphicsNode["iconEffect"].String();
  732. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  733. spell->iconScroll = graphicsNode["iconScroll"].String();
  734. const JsonNode & animationNode = json["animation"];
  735. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  736. {
  737. auto queueNode = animationNode[jsonName].Vector();
  738. for(const JsonNode & item : queueNode)
  739. {
  740. CSpell::TAnimation newItem;
  741. newItem.verticalPosition = VerticalPosition::TOP;
  742. if(item.getType() == JsonNode::DATA_STRING)
  743. newItem.resourceName = item.String();
  744. else if(item.getType() == JsonNode::DATA_STRUCT)
  745. {
  746. newItem.resourceName = item["defName"].String();
  747. auto vPosStr = item["verticalPosition"].String();
  748. if("bottom" == vPosStr)
  749. newItem.verticalPosition = VerticalPosition::BOTTOM;
  750. }
  751. q.push_back(newItem);
  752. }
  753. };
  754. loadAnimationQueue("affect", spell->animationInfo.affect);
  755. loadAnimationQueue("cast", spell->animationInfo.cast);
  756. loadAnimationQueue("hit", spell->animationInfo.hit);
  757. const JsonVector & projectile = animationNode["projectile"].Vector();
  758. for(const JsonNode & item : projectile)
  759. {
  760. CSpell::ProjectileInfo info;
  761. info.resourceName = item["defName"].String();
  762. info.minimumAngle = item["minimumAngle"].Float();
  763. spell->animationInfo.projectile.push_back(info);
  764. }
  765. const JsonNode & soundsNode = json["sounds"];
  766. spell->castSound = soundsNode["cast"].String();
  767. //load level attributes
  768. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  769. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  770. {
  771. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  772. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  773. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  774. levelObject.description = levelNode["description"].String();
  775. levelObject.cost = levelNode["cost"].Float();
  776. levelObject.AIValue = levelNode["aiValue"].Float();
  777. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  778. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  779. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  780. levelObject.range = levelNode["range"].String();
  781. for(const auto & elem : levelNode["effects"].Struct())
  782. {
  783. const JsonNode & bonusNode = elem.second;
  784. Bonus * b = JsonUtils::parseBonus(bonusNode);
  785. const bool usePowerAsValue = bonusNode["val"].isNull();
  786. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  787. //b->sid = spell->id; //for all
  788. b->source = Bonus::SPELL_EFFECT;//for all
  789. if(usePowerAsValue)
  790. b->val = levelPower;
  791. levelObject.effects.push_back(*b);
  792. }
  793. }
  794. return spell;
  795. }
  796. void CSpellHandler::afterLoadFinalization()
  797. {
  798. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  799. for(auto spell: objects)
  800. {
  801. for(auto & level: spell->levels)
  802. for(auto & bonus: level.effects)
  803. bonus.sid = spell->id;
  804. spell->setup();
  805. }
  806. }
  807. void CSpellHandler::beforeValidate(JsonNode & object)
  808. {
  809. //handle "base" level info
  810. JsonNode& levels = object["levels"];
  811. JsonNode& base = levels["base"];
  812. auto inheritNode = [&](const std::string & name){
  813. JsonUtils::inherit(levels[name],base);
  814. };
  815. inheritNode("none");
  816. inheritNode("basic");
  817. inheritNode("advanced");
  818. inheritNode("expert");
  819. }
  820. CSpellHandler::~CSpellHandler()
  821. {
  822. }
  823. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  824. {
  825. std::vector<bool> allowedSpells;
  826. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  827. return allowedSpells;
  828. }