CSpellHandler.cpp 26 KB

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