CSpellHandler.cpp 28 KB

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