CSpellHandler.cpp 27 KB

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