CSpellHandler.cpp 27 KB

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