CSpellHandler.cpp 25 KB

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