CSpellHandler.cpp 29 KB

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