CSpellHandler.cpp 26 KB

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