CSpellHandler.cpp 27 KB

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