CSpellHandler.cpp 29 KB

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