CSpellHandler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. /*
  11. * CSpellHandler.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. namespace SpellConfig
  20. {
  21. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  22. }
  23. namespace SRSLPraserHelpers
  24. {
  25. static int XYToHex(int x, int y)
  26. {
  27. return x + 17 * y;
  28. }
  29. static int XYToHex(std::pair<int, int> xy)
  30. {
  31. return XYToHex(xy.first, xy.second);
  32. }
  33. static int hexToY(int battleFieldPosition)
  34. {
  35. return battleFieldPosition/17;
  36. }
  37. static int hexToX(int battleFieldPosition)
  38. {
  39. int pos = battleFieldPosition - hexToY(battleFieldPosition) * 17;
  40. return pos;
  41. }
  42. static std::pair<int, int> hexToPair(int battleFieldPosition)
  43. {
  44. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  45. }
  46. //moves hex by one hex in given direction
  47. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  48. static std::pair<int, int> gotoDir(int x, int y, int direction)
  49. {
  50. switch(direction)
  51. {
  52. case 0: //top left
  53. return std::make_pair((y%2) ? x-1 : x, y-1);
  54. case 1: //top right
  55. return std::make_pair((y%2) ? x : x+1, y-1);
  56. case 2: //right
  57. return std::make_pair(x+1, y);
  58. case 3: //right bottom
  59. return std::make_pair((y%2) ? x : x+1, y+1);
  60. case 4: //left bottom
  61. return std::make_pair((y%2) ? x-1 : x, y+1);
  62. case 5: //left
  63. return std::make_pair(x-1, y);
  64. default:
  65. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  66. }
  67. }
  68. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  69. {
  70. return gotoDir(xy.first, xy.second, direction);
  71. }
  72. static bool isGoodHex(std::pair<int, int> xy)
  73. {
  74. return xy.first >=0 && xy.first < 17 && xy.second >= 0 && xy.second < 11;
  75. }
  76. //helper function for std::set<ui16> CSpell::rangeInHexes(unsigned int centralHex, ui8 schoolLvl ) const
  77. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  78. {
  79. std::set<ui16> ret;
  80. if(low == 0)
  81. {
  82. ret.insert(center);
  83. }
  84. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  85. for(auto & elem : mainPointForLayer)
  86. elem = hexToPair(center);
  87. for(int it=1; it<=high; ++it) //it - distance to the center
  88. {
  89. for(int b=0; b<6; ++b)
  90. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  91. if(it>=low)
  92. {
  93. std::pair<int, int> curHex;
  94. //adding lines (A-b, B-c, C-d, etc)
  95. for(int v=0; v<6; ++v)
  96. {
  97. curHex = mainPointForLayer[v];
  98. for(int h=0; h<it; ++h)
  99. {
  100. if(isGoodHex(curHex))
  101. ret.insert(XYToHex(curHex));
  102. curHex = gotoDir(curHex, (v+2)%6);
  103. }
  104. }
  105. } //if(it>=low)
  106. }
  107. return ret;
  108. }
  109. }
  110. CSpell::LevelInfo::LevelInfo()
  111. :description(""),cost(0),power(0),AIValue(0),smartTarget(true),range("0")
  112. {
  113. }
  114. CSpell::LevelInfo::~LevelInfo()
  115. {
  116. }
  117. CSpell::CSpell():
  118. id(SpellID::NONE), level(0),
  119. earth(false), water(false), fire(false), air(false),
  120. combatSpell(false), creatureAbility(false),
  121. positiveness(ESpellPositiveness::NEUTRAL),
  122. mainEffectAnim(-1),
  123. defaultProbability(0),
  124. isRising(false), isDamage(false), isOffensive(false),
  125. targetType(ETargetType::NO_TARGET)
  126. {
  127. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  128. }
  129. CSpell::~CSpell()
  130. {
  131. }
  132. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  133. {
  134. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  135. {
  136. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  137. throw new std::runtime_error("Invalid school level");
  138. }
  139. return levels.at(level);
  140. }
  141. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  142. {
  143. using namespace SRSLPraserHelpers;
  144. std::vector<BattleHex> ret;
  145. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  146. {
  147. //Special case - shape of obstacle depends on caster's side
  148. //TODO make it possible through spell_info config
  149. BattleHex::EDir firstStep, secondStep;
  150. if(side)
  151. {
  152. firstStep = BattleHex::TOP_LEFT;
  153. secondStep = BattleHex::TOP_RIGHT;
  154. }
  155. else
  156. {
  157. firstStep = BattleHex::TOP_RIGHT;
  158. secondStep = BattleHex::TOP_LEFT;
  159. }
  160. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  161. auto addIfValid = [&](BattleHex hex)
  162. {
  163. if(hex.isValid())
  164. ret.push_back(hex);
  165. else if(outDroppedHexes)
  166. *outDroppedHexes = true;
  167. };
  168. ret.push_back(centralHex);
  169. addIfValid(centralHex.moveInDir(firstStep, false));
  170. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  171. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  172. return ret;
  173. }
  174. std::string rng = getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  175. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  176. {
  177. std::string number1, number2;
  178. int beg, end;
  179. bool readingFirst = true;
  180. for(auto & elem : rng)
  181. {
  182. if(std::isdigit(elem) ) //reading number
  183. {
  184. if(readingFirst)
  185. number1 += elem;
  186. else
  187. number2 += elem;
  188. }
  189. else if(elem == ',') //comma
  190. {
  191. //calculating variables
  192. if(readingFirst)
  193. {
  194. beg = atoi(number1.c_str());
  195. number1 = "";
  196. }
  197. else
  198. {
  199. end = atoi(number2.c_str());
  200. number2 = "";
  201. }
  202. //obtaining new hexes
  203. std::set<ui16> curLayer;
  204. if(readingFirst)
  205. {
  206. curLayer = getInRange(centralHex, beg, beg);
  207. }
  208. else
  209. {
  210. curLayer = getInRange(centralHex, beg, end);
  211. readingFirst = true;
  212. }
  213. //adding abtained hexes
  214. for(auto & curLayer_it : curLayer)
  215. {
  216. ret.push_back(curLayer_it);
  217. }
  218. }
  219. else if(elem == '-') //dash
  220. {
  221. beg = atoi(number1.c_str());
  222. number1 = "";
  223. readingFirst = false;
  224. }
  225. }
  226. }
  227. //remove duplicates (TODO check if actually needed)
  228. range::unique(ret);
  229. return ret;
  230. }
  231. CSpell::ETargetType CSpell::getTargetType() const
  232. {
  233. return targetType;
  234. }
  235. const CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  236. {
  237. TargetInfo info;
  238. auto & levelInfo = getLevelInfo(level);
  239. info.type = getTargetType();
  240. info.smart = levelInfo.smartTarget;
  241. info.massive = levelInfo.range == "X";
  242. info.onlyAlive = !isRisingSpell();
  243. return info;
  244. }
  245. bool CSpell::isCombatSpell() const
  246. {
  247. return combatSpell;
  248. }
  249. bool CSpell::isAdventureSpell() const
  250. {
  251. return !combatSpell;
  252. }
  253. bool CSpell::isCreatureAbility() const
  254. {
  255. return creatureAbility;
  256. }
  257. bool CSpell::isPositive() const
  258. {
  259. return positiveness == POSITIVE;
  260. }
  261. bool CSpell::isNegative() const
  262. {
  263. return positiveness == NEGATIVE;
  264. }
  265. bool CSpell::isNeutral() const
  266. {
  267. return positiveness == NEUTRAL;
  268. }
  269. bool CSpell::isRisingSpell() const
  270. {
  271. return isRising;
  272. }
  273. bool CSpell::isDamageSpell() const
  274. {
  275. return isDamage;
  276. }
  277. bool CSpell::isOffensiveSpell() const
  278. {
  279. return isOffensive;
  280. }
  281. bool CSpell::isSpecialSpell() const
  282. {
  283. return isSpecial;
  284. }
  285. bool CSpell::hasEffects() const
  286. {
  287. return !levels[0].effects.empty();
  288. }
  289. const std::string& CSpell::getIconImmune() const
  290. {
  291. return iconImmune;
  292. }
  293. const std::string& CSpell::getCastSound() const
  294. {
  295. return castSound;
  296. }
  297. si32 CSpell::getCost(const int skillLevel) const
  298. {
  299. return getLevelInfo(skillLevel).cost;
  300. }
  301. si32 CSpell::getPower(const int skillLevel) const
  302. {
  303. return getLevelInfo(skillLevel).power;
  304. }
  305. //si32 CSpell::calculatePower(const int skillLevel) const
  306. //{
  307. // return power + getPower(skillLevel);
  308. //}
  309. si32 CSpell::getProbability(const TFaction factionId) const
  310. {
  311. if(!vstd::contains(probabilities,factionId))
  312. {
  313. return defaultProbability;
  314. }
  315. return probabilities.at(factionId);
  316. }
  317. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  318. {
  319. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  320. {
  321. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  322. return;
  323. }
  324. const std::vector<Bonus> & effects = levels[level].effects;
  325. if(effects.empty())
  326. {
  327. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  328. return;
  329. }
  330. lst.reserve(lst.size() + effects.size());
  331. for(const Bonus & b : effects)
  332. {
  333. lst.push_back(Bonus(b));
  334. }
  335. }
  336. bool CSpell::isImmuneBy(const IBonusBearer* obj) const
  337. {
  338. //todo: use new bonus API
  339. //1. Check absolute limiters
  340. for(auto b : absoluteLimiters)
  341. {
  342. if (!obj->hasBonusOfType(b))
  343. return true;
  344. }
  345. //2. Check absolute immunities
  346. for(auto b : absoluteImmunities)
  347. {
  348. if (obj->hasBonusOfType(b))
  349. return true;
  350. }
  351. //3. Check negation
  352. //FIXME: Orb of vulnerability mechanics is not such trivial
  353. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  354. return false;
  355. //4. Check negatable limit
  356. for(auto b : limiters)
  357. {
  358. if (!obj->hasBonusOfType(b))
  359. return true;
  360. }
  361. //5. Check negatable immunities
  362. for(auto b : immunities)
  363. {
  364. if (obj->hasBonusOfType(b))
  365. return true;
  366. }
  367. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  368. {
  369. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  370. return true;
  371. else if(!isPositive()) //negative or indifferent
  372. {
  373. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  374. return true;
  375. }
  376. return false;
  377. };
  378. //6. Check elemental immunities
  379. if(fire)
  380. {
  381. if(battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  382. return true;
  383. }
  384. if(water)
  385. {
  386. if(battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  387. return true;
  388. }
  389. if(earth)
  390. {
  391. if(battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  392. return true;
  393. }
  394. if(air)
  395. {
  396. if(battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  397. return true;
  398. }
  399. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  400. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  401. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  402. {
  403. return true;
  404. }
  405. return false;
  406. }
  407. void CSpell::setIsOffensive(const bool val)
  408. {
  409. isOffensive = val;
  410. if(val)
  411. {
  412. positiveness = CSpell::NEGATIVE;
  413. isDamage = true;
  414. }
  415. }
  416. void CSpell::setIsRising(const bool val)
  417. {
  418. isRising = val;
  419. if(val)
  420. {
  421. positiveness = CSpell::POSITIVE;
  422. }
  423. }
  424. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  425. {
  426. int3 diff = pos - center;
  427. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  428. return true;
  429. else
  430. return false;
  431. }
  432. CSpellHandler::CSpellHandler()
  433. {
  434. }
  435. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  436. {
  437. using namespace SpellConfig;
  438. std::vector<JsonNode> legacyData;
  439. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  440. auto readSchool = [&](JsonMap& schools, const std::string& name)
  441. {
  442. if (parser.readString() == "x")
  443. {
  444. schools[name].Bool() = true;
  445. }
  446. };
  447. auto read = [&,this](bool combat, bool ability)
  448. {
  449. do
  450. {
  451. JsonNode lineNode(JsonNode::DATA_STRUCT);
  452. const si32 id = legacyData.size();
  453. lineNode["index"].Float() = id;
  454. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  455. lineNode["name"].String() = parser.readString();
  456. parser.readString(); //ignored unused abbreviated name
  457. lineNode["level"].Float() = parser.readNumber();
  458. auto& schools = lineNode["school"].Struct();
  459. readSchool(schools, "earth");
  460. readSchool(schools, "water");
  461. readSchool(schools, "fire");
  462. readSchool(schools, "air");
  463. auto& levels = lineNode["levels"].Struct();
  464. auto getLevel = [&](const size_t idx)->JsonMap&
  465. {
  466. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  467. return levels[LEVEL_NAMES[idx]].Struct();
  468. };
  469. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  470. lineNode["power"].Float() = parser.readNumber();
  471. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  472. auto& chances = lineNode["gainChance"].Struct();
  473. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  474. chances[ETownType::names[i]].Float() = parser.readNumber();
  475. }
  476. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  477. std::vector<std::string> descriptions;
  478. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  479. descriptions.push_back(parser.readString());
  480. std::string attributes = parser.readString();
  481. std::string targetType = "NO_TARGET";
  482. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  483. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  484. targetType = "CREATURE_EXPERT_MASSIVE";
  485. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  486. targetType = "CREATURE";
  487. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  488. targetType = "OBSTACLE";
  489. //save parsed level specific data
  490. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  491. {
  492. auto& level = getLevel(i);
  493. level["description"].String() = descriptions[i];
  494. level["cost"].Float() = costs[i];
  495. level["power"].Float() = powers[i];
  496. level["aiValue"].Float() = AIVals[i];
  497. }
  498. if(targetType == "CREATURE_EXPERT_MASSIVE")
  499. {
  500. lineNode["targetType"].String() = "CREATURE";
  501. getLevel(3)["range"].String() = "X";
  502. }
  503. else
  504. {
  505. lineNode["targetType"].String() = targetType;
  506. }
  507. legacyData.push_back(lineNode);
  508. }
  509. while (parser.endLine() && !parser.isNextEntryEmpty());
  510. };
  511. auto skip = [&](int cnt)
  512. {
  513. for(int i=0; i<cnt; i++)
  514. parser.endLine();
  515. };
  516. skip(5);// header
  517. read(false,false); //read adventure map spells
  518. skip(3);
  519. read(true,false); //read battle spells
  520. skip(3);
  521. read(true,true);//read creature abilities
  522. //TODO: maybe move to config
  523. //clone Acid Breath attributes for Acid Breath damage effect
  524. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  525. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  526. legacyData.push_back(temp);
  527. objects.resize(legacyData.size());
  528. return legacyData;
  529. }
  530. const std::string CSpellHandler::getTypeName() const
  531. {
  532. return "spell";
  533. }
  534. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  535. {
  536. using namespace SpellConfig;
  537. CSpell * spell = new CSpell();
  538. const auto type = json["type"].String();
  539. if(type == "ability")
  540. {
  541. spell->creatureAbility = true;
  542. spell->combatSpell = true;
  543. }
  544. else
  545. {
  546. spell->creatureAbility = false;
  547. spell->combatSpell = type == "combat";
  548. }
  549. spell->name = json["name"].String();
  550. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  551. const auto schoolNames = json["school"];
  552. spell->air = schoolNames["air"].Bool();
  553. spell->earth = schoolNames["earth"].Bool();
  554. spell->fire = schoolNames["fire"].Bool();
  555. spell->water = schoolNames["water"].Bool();
  556. spell->level = json["level"].Float();
  557. spell->power = json["power"].Float();
  558. spell->defaultProbability = json["defaultGainChance"].Float();
  559. for(const auto & node : json["gainChance"].Struct())
  560. {
  561. const int chance = node.second.Float();
  562. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  563. {
  564. spell->probabilities[factionID] = chance;
  565. });
  566. }
  567. auto targetType = json["targetType"].String();
  568. if(targetType == "NO_TARGET")
  569. spell->targetType = CSpell::NO_TARGET;
  570. else if(targetType == "CREATURE")
  571. spell->targetType = CSpell::CREATURE;
  572. else if(targetType == "OBSTACLE")
  573. spell->targetType = CSpell::OBSTACLE;
  574. spell->mainEffectAnim = json["anim"].Float();
  575. for(const auto & counteredSpell: json["counters"].Struct())
  576. if (counteredSpell.second.Bool())
  577. {
  578. JsonNode tmp(JsonNode::DATA_STRING);
  579. tmp.meta = json.meta;
  580. tmp.String() = counteredSpell.first;
  581. VLC->modh->identifiers.requestIdentifier(tmp,[=](si32 id){
  582. spell->counteredSpells.push_back(SpellID(id));
  583. });
  584. }
  585. //TODO: more error checking - f.e. conflicting flags
  586. const auto flags = json["flags"];
  587. //by default all flags are set to false in constructor
  588. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  589. if(flags["offensive"].Bool())
  590. {
  591. spell->setIsOffensive(true);
  592. }
  593. if(flags["rising"].Bool())
  594. {
  595. spell->setIsRising(true);
  596. }
  597. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  598. if(flags["indifferent"].Bool())
  599. {
  600. spell->positiveness = CSpell::NEUTRAL;
  601. }
  602. else if(flags["negative"].Bool())
  603. {
  604. spell->positiveness = CSpell::NEGATIVE;
  605. }
  606. else if(flags["positive"].Bool())
  607. {
  608. spell->positiveness = CSpell::POSITIVE;
  609. }
  610. else if(!implicitPositiveness)
  611. {
  612. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  613. logGlobal->errorStream() << "No positiveness specified, assumed NEUTRAL";
  614. }
  615. spell->isSpecial = flags["special"].Bool();
  616. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  617. {
  618. auto it = bonusNameMap.find(name);
  619. if(it == bonusNameMap.end())
  620. {
  621. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  622. }
  623. else
  624. {
  625. vec.push_back((Bonus::BonusType)it->second);
  626. }
  627. };
  628. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  629. {
  630. for(auto bonusData: json[name].Struct())
  631. {
  632. const std::string bonusId = bonusData.first;
  633. const bool flag = bonusData.second.Bool();
  634. if(flag)
  635. findBonus(bonusId, vec);
  636. }
  637. };
  638. readBonusStruct("immunity", spell->immunities);
  639. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  640. readBonusStruct("limit", spell->limiters);
  641. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  642. const JsonNode & graphicsNode = json["graphics"];
  643. spell->iconImmune = graphicsNode["iconImmune"].String();
  644. spell->iconBook = graphicsNode["iconBook"].String();
  645. spell->iconEffect = graphicsNode["iconEffect"].String();
  646. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  647. spell->iconScroll = graphicsNode["iconScroll"].String();
  648. const JsonNode & soundsNode = json["sounds"];
  649. spell->castSound = soundsNode["cast"].String();
  650. //load level attributes
  651. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  652. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  653. {
  654. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  655. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  656. const si32 levelPower = levelNode["power"].Float();
  657. levelObject.description = levelNode["description"].String();
  658. levelObject.cost = levelNode["cost"].Float();
  659. levelObject.power = levelPower;
  660. levelObject.AIValue = levelNode["aiValue"].Float();
  661. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  662. levelObject.range = levelNode["range"].String();
  663. for(const auto & elem : levelNode["effects"].Struct())
  664. {
  665. const JsonNode & bonusNode = elem.second;
  666. Bonus * b = JsonUtils::parseBonus(bonusNode);
  667. const bool usePowerAsValue = bonusNode["val"].isNull();
  668. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  669. //b->sid = spell->id; //for all
  670. b->source = Bonus::SPELL_EFFECT;//for all
  671. if(usePowerAsValue)
  672. b->val = levelPower;
  673. levelObject.effects.push_back(*b);
  674. }
  675. }
  676. return spell;
  677. }
  678. void CSpellHandler::afterLoadFinalization()
  679. {
  680. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  681. for(auto spell: objects)
  682. for(auto & level: spell->levels)
  683. for(auto & bonus: level.effects)
  684. bonus.sid = spell->id;
  685. }
  686. void CSpellHandler::beforeValidate(JsonNode & object)
  687. {
  688. //handle "base" level info
  689. JsonNode& levels = object["levels"];
  690. JsonNode& base = levels["base"];
  691. auto inheritNode = [&](const std::string & name){
  692. JsonUtils::inherit(levels[name],base);
  693. };
  694. inheritNode("none");
  695. inheritNode("basic");
  696. inheritNode("advanced");
  697. inheritNode("expert");
  698. }
  699. CSpellHandler::~CSpellHandler()
  700. {
  701. }
  702. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  703. {
  704. std::vector<bool> allowedSpells;
  705. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  706. return allowedSpells;
  707. }