CSpellHandler.cpp 27 KB

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