CSpellHandler.cpp 27 KB

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