CSpellHandler.cpp 26 KB

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