CSpellHandler.cpp 28 KB

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