CCreatureHandler.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. /*
  2. * CCreatureHandler.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 "CCreatureHandler.h"
  12. #include "CBonusTypeHandler.h"
  13. #include "ResourceSet.h"
  14. #include "entities/faction/CFaction.h"
  15. #include "entities/faction/CTownHandler.h"
  16. #include "filesystem/Filesystem.h"
  17. #include "GameLibrary.h"
  18. #include "IGameSettings.h"
  19. #include "constants/StringConstants.h"
  20. #include "bonuses/Limiters.h"
  21. #include "bonuses/Updaters.h"
  22. #include "json/JsonBonus.h"
  23. #include "serializer/JsonDeserializer.h"
  24. #include "serializer/JsonUpdater.h"
  25. #include "texts/CGeneralTextHandler.h"
  26. #include "texts/CLegacyConfigParser.h"
  27. #include "mapObjectConstructors/AObjectTypeHandler.h"
  28. #include "mapObjectConstructors/CObjectClassesHandler.h"
  29. #include "modding/CModHandler.h"
  30. #include "ExceptionsCommon.h"
  31. #include <vstd/RNG.h>
  32. VCMI_LIB_NAMESPACE_BEGIN
  33. const std::map<CCreature::CreatureQuantityId, std::string> CCreature::creatureQuantityRanges =
  34. {
  35. {CCreature::CreatureQuantityId::FEW, "1-4"},
  36. {CCreature::CreatureQuantityId::SEVERAL, "5-9"},
  37. {CCreature::CreatureQuantityId::PACK, "10-19"},
  38. {CCreature::CreatureQuantityId::LOTS, "20-49"},
  39. {CCreature::CreatureQuantityId::HORDE, "50-99"},
  40. {CCreature::CreatureQuantityId::THRONG, "100-249"},
  41. {CCreature::CreatureQuantityId::SWARM, "250-499"},
  42. {CCreature::CreatureQuantityId::ZOUNDS, "500-999"},
  43. {CCreature::CreatureQuantityId::LEGION, "1000+"}
  44. };
  45. int32_t CCreature::getIndex() const
  46. {
  47. return idNumber.toEnum();
  48. }
  49. int32_t CCreature::getIconIndex() const
  50. {
  51. return iconIndex;
  52. }
  53. std::string CCreature::getJsonKey() const
  54. {
  55. return modScope + ':' + identifier;
  56. }
  57. std::string CCreature::getModScope() const
  58. {
  59. return modScope;
  60. }
  61. void CCreature::registerIcons(const IconRegistar & cb) const
  62. {
  63. cb(getIconIndex(), 0, "CPRSMALL", smallIconName);
  64. cb(getIconIndex(), 0, "TWCRPORT", largeIconName);
  65. }
  66. CreatureID CCreature::getId() const
  67. {
  68. return idNumber;
  69. }
  70. const IBonusBearer * CCreature::getBonusBearer() const
  71. {
  72. return this;
  73. }
  74. int32_t CCreature::getAdvMapAmountMin() const
  75. {
  76. return ammMin;
  77. }
  78. int32_t CCreature::getAdvMapAmountMax() const
  79. {
  80. return ammMax;
  81. }
  82. int32_t CCreature::getAIValue() const
  83. {
  84. return AIValue;
  85. }
  86. int32_t CCreature::getFightValue() const
  87. {
  88. return fightValue;
  89. }
  90. int32_t CCreature::getLevel() const
  91. {
  92. return level;
  93. }
  94. int32_t CCreature::getGrowth() const
  95. {
  96. return growth;
  97. }
  98. int32_t CCreature::getHorde() const
  99. {
  100. return hordeGrowth;
  101. }
  102. FactionID CCreature::getFactionID() const
  103. {
  104. return FactionID(faction);
  105. }
  106. int32_t CCreature::getBaseAttack() const
  107. {
  108. static const auto SELECTOR = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::ATTACK)).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  109. return getExportedBonusList().valOfBonuses(SELECTOR);
  110. }
  111. int32_t CCreature::getBaseDefense() const
  112. {
  113. static const auto SELECTOR = Selector::typeSubtype(BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE)).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  114. return getExportedBonusList().valOfBonuses(SELECTOR);
  115. }
  116. int32_t CCreature::getBaseDamageMin() const
  117. {
  118. static const auto SELECTOR = Selector::typeSubtype(BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMin).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  119. return getExportedBonusList().valOfBonuses(SELECTOR);
  120. }
  121. int32_t CCreature::getBaseDamageMax() const
  122. {
  123. static const auto SELECTOR = Selector::typeSubtype(BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMax).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  124. return getExportedBonusList().valOfBonuses(SELECTOR);
  125. }
  126. int32_t CCreature::getBaseHitPoints() const
  127. {
  128. static const auto SELECTOR = Selector::type()(BonusType::STACK_HEALTH).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  129. return getExportedBonusList().valOfBonuses(SELECTOR);
  130. }
  131. int32_t CCreature::getBaseSpellPoints() const
  132. {
  133. static const auto SELECTOR = Selector::type()(BonusType::CASTS).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  134. return getExportedBonusList().valOfBonuses(SELECTOR);
  135. }
  136. int32_t CCreature::getBaseSpeed() const
  137. {
  138. static const auto SELECTOR = Selector::type()(BonusType::STACKS_SPEED).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  139. return getExportedBonusList().valOfBonuses(SELECTOR);
  140. }
  141. int32_t CCreature::getBaseShots() const
  142. {
  143. static const auto SELECTOR = Selector::type()(BonusType::SHOTS).And(Selector::sourceTypeSel(BonusSource::CREATURE_ABILITY));
  144. return getExportedBonusList().valOfBonuses(SELECTOR);
  145. }
  146. int32_t CCreature::getRecruitCost(GameResID resIndex) const
  147. {
  148. if(resIndex.getNum() >= 0 && resIndex.getNum() < cost.size())
  149. return cost[resIndex];
  150. else
  151. return 0;
  152. }
  153. TResources CCreature::getFullRecruitCost() const
  154. {
  155. return cost;
  156. }
  157. bool CCreature::hasUpgrades() const
  158. {
  159. return !upgrades.empty();
  160. }
  161. std::string CCreature::getNameTranslated() const
  162. {
  163. return getNameSingularTranslated();
  164. }
  165. std::string CCreature::getNamePluralTranslated() const
  166. {
  167. return LIBRARY->generaltexth->translate(getNamePluralTextID());
  168. }
  169. std::string CCreature::getNameSingularTranslated() const
  170. {
  171. return LIBRARY->generaltexth->translate(getNameSingularTextID());
  172. }
  173. std::string CCreature::getNameTextID() const
  174. {
  175. return getNameSingularTextID();
  176. }
  177. std::string CCreature::getDescriptionTranslated() const
  178. {
  179. return LIBRARY->generaltexth->translate(getDescriptionTextID());
  180. }
  181. std::string CCreature::getNamePluralTextID() const
  182. {
  183. return TextIdentifier("creatures", modScope, identifier, "name", "plural" ).get();
  184. }
  185. std::string CCreature::getNameSingularTextID() const
  186. {
  187. return TextIdentifier("creatures", modScope, identifier, "name", "singular" ).get();
  188. }
  189. std::string CCreature::getDescriptionTextID() const
  190. {
  191. return TextIdentifier("creatures", modScope, identifier, "description").get();
  192. }
  193. std::string CCreature::getBonusTextID(const std::string & bonusID) const
  194. {
  195. return TextIdentifier("creatures", modScope, identifier, "bonus", bonusID).get();
  196. }
  197. CCreature::CreatureQuantityId CCreature::getQuantityID(const int & quantity)
  198. {
  199. if (quantity<5)
  200. return CCreature::CreatureQuantityId::FEW;
  201. if (quantity<10)
  202. return CCreature::CreatureQuantityId::SEVERAL;
  203. if (quantity<20)
  204. return CCreature::CreatureQuantityId::PACK;
  205. if (quantity<50)
  206. return CCreature::CreatureQuantityId::LOTS;
  207. if (quantity<100)
  208. return CCreature::CreatureQuantityId::HORDE;
  209. if (quantity<250)
  210. return CCreature::CreatureQuantityId::THRONG;
  211. if (quantity<500)
  212. return CCreature::CreatureQuantityId::SWARM;
  213. if (quantity<1000)
  214. return CCreature::CreatureQuantityId::ZOUNDS;
  215. return CCreature::CreatureQuantityId::LEGION;
  216. }
  217. std::string CCreature::getQuantityRangeStringForId(const CCreature::CreatureQuantityId & quantityId)
  218. {
  219. if(creatureQuantityRanges.find(quantityId) != creatureQuantityRanges.end())
  220. return creatureQuantityRanges.at(quantityId);
  221. logGlobal->error("Wrong quantityId: %d", (int)quantityId);
  222. assert(0);
  223. return "[ERROR]";
  224. }
  225. int CCreature::estimateCreatureCount(ui32 countID)
  226. {
  227. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  228. if(countID > 9)
  229. {
  230. logGlobal->error("Wrong countID %d!", countID);
  231. return 0;
  232. }
  233. else
  234. return creature_count[countID];
  235. }
  236. bool CCreature::isDoubleWide() const
  237. {
  238. return doubleWide;
  239. }
  240. /**
  241. * Determines if the creature is of a good alignment.
  242. * @return true if the creture is good, false otherwise.
  243. */
  244. bool CCreature::isGood () const
  245. {
  246. return LIBRARY->factions()->getById(faction)->getAlignment() == EAlignment::GOOD;
  247. }
  248. /**
  249. * Determines if the creature is of an evil alignment.
  250. * @return true if the creature is evil, false otherwise.
  251. */
  252. bool CCreature::isEvil () const
  253. {
  254. return LIBRARY->factions()->getById(faction)->getAlignment() == EAlignment::EVIL;
  255. }
  256. si32 CCreature::maxAmount(const TResources &res) const //how many creatures can be bought
  257. {
  258. int ret = 2147483645;
  259. int resAmnt = static_cast<int>(std::min(res.size(),cost.size()));
  260. for(int i=0;i<resAmnt;i++)
  261. if(cost[i])
  262. ret = std::min(ret, (res[i] / cost[i]));
  263. return ret;
  264. }
  265. CCreature::CCreature()
  266. {
  267. setNodeType(CBonusSystemNode::CREATURE);
  268. fightValue = AIValue = growth = hordeGrowth = ammMin = ammMax = 0;
  269. }
  270. void CCreature::addBonus(int val, BonusType type)
  271. {
  272. addBonus(val, type, BonusSubtypeID());
  273. }
  274. void CCreature::addBonus(int val, BonusType type, BonusSubtypeID subtype)
  275. {
  276. auto selector = Selector::typeSubtype(type, subtype).And(Selector::source(BonusSource::CREATURE_ABILITY, BonusSourceID(getId())));
  277. BonusList & exported = getExportedBonusList();
  278. BonusList existing;
  279. exported.getBonuses(existing, selector);
  280. if(existing.empty())
  281. {
  282. auto added = std::make_shared<Bonus>(BonusDuration::PERMANENT, type, BonusSource::CREATURE_ABILITY, val, BonusSourceID(getId()), subtype, BonusValueType::BASE_NUMBER);
  283. addNewBonus(added);
  284. }
  285. else
  286. {
  287. std::shared_ptr<Bonus> b = existing[0];
  288. b->val = val;
  289. }
  290. }
  291. bool CCreature::isMyDirectUpgrade(const CCreature *anotherCre) const
  292. {
  293. return vstd::contains(upgrades, anotherCre->getId());
  294. }
  295. bool CCreature::isMyDirectOrIndirectUpgrade(const CCreature *anotherCre) const
  296. {
  297. std::set<CreatureID> foundUpgrades;
  298. std::vector<CreatureID> upgradesToTest;
  299. upgradesToTest.push_back(getId());
  300. while (!upgradesToTest.empty())
  301. {
  302. CreatureID testedID = upgradesToTest.back();
  303. const CCreature * testedPtr = testedID.toCreature();
  304. upgradesToTest.pop_back();
  305. for (const auto & upgrade : testedPtr->upgrades)
  306. {
  307. if (upgrade == anotherCre->getId())
  308. return true;
  309. if (foundUpgrades.count(upgrade))
  310. continue;
  311. upgradesToTest.push_back(upgrade);
  312. foundUpgrades.insert(upgrade);
  313. }
  314. }
  315. return false;
  316. }
  317. std::string CCreature::nodeName() const
  318. {
  319. return "\"" + getNamePluralTextID() + "\"";
  320. }
  321. int CCreature::getRandomAmount(vstd::RNG & ranGen) const
  322. {
  323. if(ammMax > ammMin)
  324. return ammMin + (ranGen.nextInt(ammMin, ammMax));
  325. else
  326. return ammMax;
  327. }
  328. void CCreature::updateFrom(const JsonNode & data)
  329. {
  330. JsonUpdater handler(nullptr, data);
  331. {
  332. auto configScope = handler.enterStruct("config");
  333. const JsonNode & configNode = handler.getCurrent();
  334. serializeJson(handler);
  335. if(!configNode["hitPoints"].isNull())
  336. addBonus(configNode["hitPoints"].Integer(), BonusType::STACK_HEALTH);
  337. if(!configNode["speed"].isNull())
  338. addBonus(configNode["speed"].Integer(), BonusType::STACKS_SPEED);
  339. if(!configNode["attack"].isNull())
  340. addBonus(configNode["attack"].Integer(), BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::ATTACK));
  341. if(!configNode["defense"].isNull())
  342. addBonus(configNode["defense"].Integer(), BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE));
  343. if(!configNode["damage"]["min"].isNull())
  344. addBonus(configNode["damage"]["min"].Integer(), BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMin);
  345. if(!configNode["damage"]["max"].isNull())
  346. addBonus(configNode["damage"]["max"].Integer(), BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMax);
  347. if(!configNode["shots"].isNull())
  348. addBonus(configNode["shots"].Integer(), BonusType::SHOTS);
  349. if(!configNode["spellPoints"].isNull())
  350. addBonus(configNode["spellPoints"].Integer(), BonusType::CASTS);
  351. }
  352. handler.serializeBonuses("bonuses", this);
  353. }
  354. void CCreature::serializeJson(JsonSerializeFormat & handler)
  355. {
  356. handler.serializeInt("fightValue", fightValue);
  357. handler.serializeInt("aiValue", AIValue);
  358. handler.serializeInt("growth", growth);
  359. handler.serializeInt("horde", hordeGrowth);// Needed at least until configurable buildings
  360. {
  361. auto advMapNode = handler.enterStruct("advMapAmount");
  362. handler.serializeInt("min", ammMin);
  363. handler.serializeInt("max", ammMax);
  364. }
  365. if(handler.updating)
  366. {
  367. cost.serializeJson(handler, "cost");
  368. handler.serializeId("faction", faction);
  369. }
  370. handler.serializeInt("level", level);
  371. handler.serializeBool("doubleWide", doubleWide);
  372. if(!handler.saving)
  373. {
  374. if(ammMin > ammMax)
  375. {
  376. logMod->error("Invalid creature '%s' configuration, advMapAmount.min > advMapAmount.max", identifier);
  377. std::swap(ammMin, ammMax);
  378. }
  379. }
  380. }
  381. CCreatureHandler::CCreatureHandler()
  382. : expAfterUpgrade(0)
  383. {
  384. loadCommanders();
  385. }
  386. void CCreatureHandler::loadCommanders()
  387. {
  388. auto configResource = JsonPath::builtin("config/commanders.json");
  389. std::string modSource = LIBRARY->modh->findResourceOrigin(configResource);
  390. JsonNode data(configResource);
  391. data.setModScope(modSource);
  392. const JsonNode & config = data; // switch to const data accessors
  393. for (auto bonus : config["bonusPerLevel"].Vector())
  394. {
  395. commanderLevelPremy.push_back(JsonUtils::parseBonus(bonus.Vector()));
  396. }
  397. int level = 0;
  398. for (auto skill : config["skillLevels"].Vector())
  399. {
  400. skillLevels.emplace_back();
  401. for (auto skillLevel : skill["levels"].Vector())
  402. {
  403. skillLevels[level].push_back(static_cast<ui8>(skillLevel.Float()));
  404. }
  405. ++level;
  406. }
  407. for (auto ability : config["abilityRequirements"].Vector())
  408. {
  409. std::pair <std::vector<std::shared_ptr<Bonus> >, std::pair <ui8, ui8> > a;
  410. JsonVector & abilities = ability["ability"].Vector();
  411. a.first = std::vector<std::shared_ptr<Bonus> >();
  412. if (abilities[0].isVector())
  413. for (int i = 0; i < abilities.size(); i++)
  414. a.first.push_back(JsonUtils::parseBonus(abilities[i].Vector()));
  415. else
  416. a.first.push_back(JsonUtils::parseBonus(ability["ability"].Vector()));
  417. a.second.first = static_cast<ui8>(ability["skills"].Vector()[0].Float());
  418. a.second.second = static_cast<ui8>(ability["skills"].Vector()[1].Float());
  419. skillRequirements.push_back (a);
  420. }
  421. }
  422. std::vector<JsonNode> CCreatureHandler::loadLegacyData()
  423. {
  424. size_t dataSize = LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_CREATURE);
  425. objects.resize(dataSize);
  426. std::vector<JsonNode> h3Data;
  427. h3Data.reserve(dataSize);
  428. CLegacyConfigParser parser(TextPath::builtin("DATA/CRTRAITS.TXT"));
  429. parser.endLine(); // header
  430. // this file is a bit different in some of Russian localisations:
  431. //ENG: Singular Plural Wood ...
  432. //RUS: Singular Plural Plural2 Wood ...
  433. // Try to detect which version this is by header
  434. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  435. size_t namesCount = 2;
  436. {
  437. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  438. throw std::runtime_error("Incorrect format of CrTraits.txt");
  439. if (parser.readString() == "Plural2")
  440. namesCount = 3;
  441. parser.endLine();
  442. }
  443. for (size_t i=0; i<dataSize; i++)
  444. {
  445. //loop till non-empty line
  446. while (parser.isNextEntryEmpty())
  447. parser.endLine();
  448. JsonNode data;
  449. data["name"]["singular"].String() = parser.readString();
  450. if (namesCount == 3)
  451. parser.readString();
  452. data["name"]["plural"].String() = parser.readString();
  453. for(int v=0; v<7; ++v)
  454. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  455. data["fightValue"].Float() = parser.readNumber();
  456. data["aiValue"].Float() = parser.readNumber();
  457. data["growth"].Float() = parser.readNumber();
  458. data["horde"].Float() = parser.readNumber();
  459. data["hitPoints"].Float() = parser.readNumber();
  460. data["speed"].Float() = parser.readNumber();
  461. data["attack"].Float() = parser.readNumber();
  462. data["defense"].Float() = parser.readNumber();
  463. data["damage"]["min"].Float() = parser.readNumber();
  464. data["damage"]["max"].Float() = parser.readNumber();
  465. if (float shots = parser.readNumber())
  466. data["shots"].Float() = shots;
  467. if (float spells = parser.readNumber())
  468. data["spellPoints"].Float() = spells;
  469. data["advMapAmount"]["min"].Float() = parser.readNumber();
  470. data["advMapAmount"]["max"].Float() = parser.readNumber();
  471. // unused - ability text, not used since we no longer have original creature window
  472. parser.readString();
  473. parser.readString(); // unused - abilities, not used since we load them all from json configs
  474. h3Data.push_back(data);
  475. }
  476. loadAnimationInfo(h3Data);
  477. return h3Data;
  478. }
  479. std::shared_ptr<CCreature> CCreatureHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  480. {
  481. assert(identifier.find(':') == std::string::npos);
  482. assert(!scope.empty());
  483. auto cre = std::make_shared<CCreature>();
  484. if(node["hasDoubleWeek"].Bool())
  485. {
  486. doubledCreatures.insert(CreatureID(index));
  487. }
  488. cre->idNumber = CreatureID(index);
  489. cre->iconIndex = cre->getIndex() + 2;
  490. cre->identifier = identifier;
  491. cre->modScope = scope;
  492. JsonDeserializer handler(nullptr, node);
  493. cre->serializeJson(handler);
  494. cre->cost = ResourceSet(node["cost"]);
  495. LIBRARY->generaltexth->registerString(scope, cre->getNameSingularTextID(), node["name"]["singular"]);
  496. LIBRARY->generaltexth->registerString(scope, cre->getNamePluralTextID(), node["name"]["plural"]);
  497. LIBRARY->generaltexth->registerString(scope, cre->getDescriptionTextID(), node["description"]);
  498. cre->addBonus(node["hitPoints"].Integer(), BonusType::STACK_HEALTH);
  499. cre->addBonus(node["speed"].Integer(), BonusType::STACKS_SPEED);
  500. cre->addBonus(node["attack"].Integer(), BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::ATTACK));
  501. cre->addBonus(node["defense"].Integer(), BonusType::PRIMARY_SKILL, BonusSubtypeID(PrimarySkill::DEFENSE));
  502. int minDamage = node["damage"]["min"].Integer();
  503. int maxDamage = node["damage"]["max"].Integer();
  504. if (minDamage <= maxDamage)
  505. {
  506. cre->addBonus(minDamage, BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMin);
  507. cre->addBonus(maxDamage, BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMax);
  508. }
  509. else
  510. {
  511. logMod->error("Mod %s: creature %s has minimal damage (%d) greater than maximal damage (%d)!", scope, identifier, minDamage, maxDamage);
  512. cre->addBonus(maxDamage, BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMin);
  513. cre->addBonus(minDamage, BonusType::CREATURE_DAMAGE, BonusCustomSubtype::creatureDamageMax);
  514. }
  515. if(!node["shots"].isNull())
  516. cre->addBonus(node["shots"].Integer(), BonusType::SHOTS);
  517. loadStackExperience(cre.get(), node["stackExperience"]);
  518. loadJsonAnimation(cre.get(), node["graphics"]);
  519. loadCreatureJson(cre.get(), node);
  520. for(const auto & extraName : node["extraNames"].Vector())
  521. {
  522. for(const auto & type_name : getTypeNames())
  523. registerObject(scope, type_name, extraName.String(), cre->getIndex());
  524. }
  525. if (!cre->special &&
  526. !CResourceHandler::get()->existsResource(cre->animDefName) &&
  527. !CResourceHandler::get()->existsResource(cre->animDefName.toType<EResType::JSON>()) &&
  528. !CResourceHandler::get()->existsResource(cre->animDefName.addPrefix("SPRITES/")) &&
  529. !CResourceHandler::get()->existsResource(cre->animDefName.addPrefix("SPRITES/").toType<EResType::JSON>()))
  530. throw ModLoadingException(scope, "creature " + cre->getJsonKey() + " has no combat animation but is not marked as special!" );
  531. JsonNode advMapFile = node["graphics"]["map"];
  532. JsonNode advMapMask = node["graphics"]["mapMask"];
  533. LIBRARY->identifiers()->requestIdentifier(scope, "object", "monster", [cre, scope, advMapFile, advMapMask](si32 monsterIndex)
  534. {
  535. JsonNode conf;
  536. conf.setModScope(scope);
  537. LIBRARY->objtypeh->loadSubObject(cre->identifier, conf, Obj::MONSTER, cre->getId().num);
  538. if (!advMapFile.isNull())
  539. {
  540. JsonNode templ;
  541. templ["animation"] = advMapFile;
  542. if (!advMapMask.isNull())
  543. templ["mask"] = advMapMask;
  544. templ.setModScope(scope);
  545. // if creature has custom advMapFile, reset any potentially imported H3M templates and use provided file instead
  546. LIBRARY->objtypeh->getHandlerFor(Obj::MONSTER, cre->getId().num)->clearTemplates();
  547. LIBRARY->objtypeh->getHandlerFor(Obj::MONSTER, cre->getId().num)->addTemplate(templ);
  548. }
  549. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  550. if (LIBRARY->objtypeh->getHandlerFor(Obj::MONSTER, cre->getId().num)->getTemplates().empty())
  551. {
  552. if (!cre->special)
  553. throw ModLoadingException(scope, "creature " + cre->getJsonKey() + " has no adventure map animation but is not marked as special!" );
  554. LIBRARY->objtypeh->removeSubObject(Obj::MONSTER, cre->getId().num);
  555. }
  556. });
  557. return cre;
  558. }
  559. const std::vector<std::string> & CCreatureHandler::getTypeNames() const
  560. {
  561. static const std::vector<std::string> typeNames = { "creature" };
  562. return typeNames;
  563. }
  564. void CCreatureHandler::loadCrExpMod()
  565. {
  566. if (LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) //reading default stack experience values
  567. {
  568. //Calculate rank exp values, formula appears complicated bu no parsing needed
  569. expRanks.resize(8);
  570. int dif = 0;
  571. int it = 8000; //ignore name of this variable
  572. expRanks[0].push_back(it);
  573. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  574. {
  575. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  576. dif += it/5;
  577. }
  578. for (int i = 1; i < 8; ++i) //used for tiers 1-7
  579. {
  580. dif = 0;
  581. it = 1000 * i;
  582. expRanks[i].push_back(it);
  583. for (int j = 1; j < 10; ++j)
  584. {
  585. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  586. dif += it/5;
  587. }
  588. }
  589. CLegacyConfigParser expBonParser(TextPath::builtin("DATA/CREXPMOD.TXT"));
  590. expBonParser.endLine(); //header
  591. maxExpPerBattle.resize(8);
  592. for (int i = 1; i < 8; ++i)
  593. {
  594. expBonParser.readString(); //index
  595. expBonParser.readString(); //float multiplier -> hardcoded
  596. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  597. expBonParser.readString(); //already calculated
  598. maxExpPerBattle[i] = static_cast<ui32>(expBonParser.readNumber());
  599. expRanks[i].push_back(expRanks[i].back() + static_cast<ui32>(expBonParser.readNumber()));
  600. expBonParser.endLine();
  601. }
  602. //exp for tier >7, rank 11
  603. expRanks[0].push_back(147000);
  604. expAfterUpgrade = 75; //percent
  605. maxExpPerBattle[0] = maxExpPerBattle[7];
  606. }
  607. }
  608. void CCreatureHandler::loadCrExpBon(CBonusSystemNode & globalEffects)
  609. {
  610. if (LIBRARY->engineSettings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) //reading default stack experience bonuses
  611. {
  612. logGlobal->debug("\tLoading stack experience bonuses");
  613. auto addBonusForAllCreatures = [&](std::shared_ptr<Bonus> b) {
  614. auto limiter = std::make_shared<CreatureLevelLimiter>();
  615. b->addLimiter(limiter);
  616. globalEffects.addNewBonus(b);
  617. };
  618. auto addBonusForTier = [&](int tier, std::shared_ptr<Bonus> b) {
  619. assert(vstd::iswithin(tier, 1, 7));
  620. //bonuses from level 7 are given to high-level creatures too
  621. auto max = tier == 7 ? std::numeric_limits<int>::max() : tier + 1;
  622. auto limiter = std::make_shared<CreatureLevelLimiter>(tier, max);
  623. b->addLimiter(limiter);
  624. globalEffects.addNewBonus(b);
  625. };
  626. CLegacyConfigParser parser(TextPath::builtin("DATA/CREXPBON.TXT"));
  627. Bonus b; //prototype with some default properties
  628. b.source = BonusSource::STACK_EXPERIENCE;
  629. b.duration = BonusDuration::PERMANENT;
  630. b.valType = BonusValueType::ADDITIVE_VALUE;
  631. b.effectRange = BonusLimitEffect::NO_LIMIT;
  632. b.additionalInfo = 0;
  633. b.turnsRemain = 0;
  634. BonusList bl;
  635. parser.endLine();
  636. parser.readString(); //ignore index
  637. loadStackExp(b, bl, parser);
  638. for(const auto & b : bl)
  639. addBonusForAllCreatures(b); //health bonus is common for all
  640. parser.endLine();
  641. for (int i = 1; i < 7; ++i)
  642. {
  643. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  644. {
  645. parser.readString(); //ignore index
  646. bl.clear();
  647. loadStackExp(b, bl, parser);
  648. for(const auto & b : bl)
  649. addBonusForTier(i, b);
  650. parser.endLine();
  651. }
  652. }
  653. for (int j = 0; j < 4; ++j) //tier 7
  654. {
  655. parser.readString(); //ignore index
  656. bl.clear();
  657. loadStackExp(b, bl, parser);
  658. for(const auto & b : bl)
  659. addBonusForTier(7, b);
  660. parser.endLine();
  661. }
  662. do //parse everything that's left
  663. {
  664. CreatureID sid = parser.readNumber(); //id = this particular creature ID
  665. b.sid = BonusSourceID(sid);
  666. bl.clear();
  667. loadStackExp(b, bl, parser);
  668. for(const auto & b : bl)
  669. objects[sid.getNum()]->addNewBonus(b); //add directly to CCreature Node
  670. }
  671. while (parser.endLine());
  672. }//end of Stack Experience
  673. }
  674. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data) const
  675. {
  676. CLegacyConfigParser parser(TextPath::builtin("DATA/CRANIM.TXT"));
  677. parser.endLine(); // header
  678. parser.endLine();
  679. for(int dd = 0; dd < LIBRARY->engineSettings()->getInteger(EGameSettings::TEXTS_CREATURE); ++dd)
  680. {
  681. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  682. ;
  683. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  684. parser.endLine();
  685. }
  686. }
  687. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser) const
  688. {
  689. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  690. JsonNode & animationTime = graphics["animationTime"];
  691. animationTime["walk"].Float() = parser.readNumber();
  692. animationTime["attack"].Float() = parser.readNumber();
  693. parser.readNumber(); // unused value "Flight animation time" - H3 actually uses "Walk animation time" even for flying creatures
  694. animationTime["idle"].Float() = 10.0;
  695. JsonNode & missile = graphics["missile"];
  696. JsonNode & offsets = missile["offset"];
  697. offsets["upperX"].Float() = parser.readNumber();
  698. offsets["upperY"].Float() = parser.readNumber();
  699. offsets["middleX"].Float() = parser.readNumber();
  700. offsets["middleY"].Float() = parser.readNumber();
  701. offsets["lowerX"].Float() = parser.readNumber();
  702. offsets["lowerY"].Float() = parser.readNumber();
  703. for(int i=0; i<12; i++)
  704. {
  705. JsonNode entry;
  706. entry.Float() = parser.readNumber();
  707. missile["frameAngles"].Vector().push_back(entry);
  708. }
  709. // Unused property "troopCountLocationOffset"
  710. parser.readNumber();
  711. missile["attackClimaxFrame"].Float() = parser.readNumber();
  712. // assume that creature is not a shooter and should not have whole missile field
  713. if (missile["frameAngles"].Vector()[0].Integer() == 0 &&
  714. missile["attackClimaxFrame"].Integer() == 0)
  715. graphics.Struct().erase("missile");
  716. }
  717. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics) const
  718. {
  719. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  720. const JsonNode & animationTime = graphics["animationTime"];
  721. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  722. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  723. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  724. const JsonNode & missile = graphics["missile"];
  725. const JsonNode & offsets = missile["offset"];
  726. cre->animation.upperRightMissileOffsetX = static_cast<int>(offsets["upperX"].Float());
  727. cre->animation.upperRightMissileOffsetY = static_cast<int>(offsets["upperY"].Float());
  728. cre->animation.rightMissileOffsetX = static_cast<int>(offsets["middleX"].Float());
  729. cre->animation.rightMissileOffsetY = static_cast<int>(offsets["middleY"].Float());
  730. cre->animation.lowerRightMissileOffsetX = static_cast<int>(offsets["lowerX"].Float());
  731. cre->animation.lowerRightMissileOffsetY = static_cast<int>(offsets["lowerY"].Float());
  732. cre->animation.attackClimaxFrame = static_cast<int>(missile["attackClimaxFrame"].Float());
  733. cre->animation.missileFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  734. cre->smallIconName = graphics["iconSmall"].String();
  735. cre->largeIconName = graphics["iconLarge"].String();
  736. }
  737. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config) const
  738. {
  739. creature->animDefName = AnimationPath::fromJson(config["graphics"]["animation"]);
  740. for(const auto & ability : config["abilities"].Struct())
  741. {
  742. if (!ability.second.isNull())
  743. {
  744. auto b = JsonUtils::parseBonus(ability.second, creature->getBonusTextID(ability.first));
  745. b->source = BonusSource::CREATURE_ABILITY;
  746. b->sid = BonusSourceID(creature->getId());
  747. b->duration = BonusDuration::PERMANENT;
  748. creature->addNewBonus(b);
  749. }
  750. }
  751. LIBRARY->identifiers()->requestIdentifier("faction", config["faction"], [=](si32 faction)
  752. {
  753. creature->faction = FactionID(faction);
  754. });
  755. for(const JsonNode &value : config["upgrades"].Vector())
  756. {
  757. LIBRARY->identifiers()->requestIdentifier("creature", value, [=](si32 identifier)
  758. {
  759. creature->upgrades.insert(CreatureID(identifier));
  760. });
  761. }
  762. creature->animation.projectileImageName = AnimationPath::fromJson(config["graphics"]["missile"]["projectile"]);
  763. for(const JsonNode & value : config["graphics"]["missile"]["ray"].Vector())
  764. {
  765. CCreature::CreatureAnimation::RayColor color;
  766. color.start.r = value["start"].Vector()[0].Integer();
  767. color.start.g = value["start"].Vector()[1].Integer();
  768. color.start.b = value["start"].Vector()[2].Integer();
  769. color.start.a = value["start"].Vector()[3].Integer();
  770. color.end.r = value["end"].Vector()[0].Integer();
  771. color.end.g = value["end"].Vector()[1].Integer();
  772. color.end.b = value["end"].Vector()[2].Integer();
  773. color.end.a = value["end"].Vector()[3].Integer();
  774. creature->animation.projectileRay.push_back(color);
  775. }
  776. creature->special = config["special"].Bool() || config["disabled"].Bool();
  777. creature->excludeFromRandomization = config["excludeFromRandomization"].Bool();
  778. const JsonNode & sounds = config["sound"];
  779. creature->sounds.attack = AudioPath::fromJson(sounds["attack"]);
  780. creature->sounds.defend = AudioPath::fromJson(sounds["defend"]);
  781. creature->sounds.killed = AudioPath::fromJson(sounds["killed"]);
  782. creature->sounds.move = AudioPath::fromJson(sounds["move"]);
  783. creature->sounds.shoot = AudioPath::fromJson(sounds["shoot"]);
  784. creature->sounds.wince = AudioPath::fromJson(sounds["wince"]);
  785. creature->sounds.startMoving = AudioPath::fromJson(sounds["startMoving"]);
  786. creature->sounds.endMoving = AudioPath::fromJson(sounds["endMoving"]);
  787. }
  788. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input) const
  789. {
  790. for (const JsonNode &exp : input.Vector())
  791. {
  792. const JsonVector &values = exp["values"].Vector();
  793. int lowerLimit = 1;//, upperLimit = 255;
  794. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  795. {
  796. for (const JsonNode &val : values)
  797. {
  798. if(val.Bool())
  799. {
  800. // parse each bonus separately
  801. // we can not create copies since identifiers resolution does not tracks copies
  802. // leading to unset identifier values in copies
  803. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  804. bonus->source = BonusSource::STACK_EXPERIENCE;
  805. bonus->duration = BonusDuration::PERMANENT;
  806. bonus->addLimiter(std::make_shared<RankRangeLimiter>(lowerLimit));
  807. creature->addNewBonus (bonus);
  808. break; //TODO: allow bonuses to turn off?
  809. }
  810. ++lowerLimit;
  811. }
  812. }
  813. else
  814. {
  815. int lastVal = 0;
  816. for (const JsonNode &val : values)
  817. {
  818. if (val.Integer() != lastVal)
  819. {
  820. JsonNode bonusInput = exp["bonus"];
  821. bonusInput["val"].Float() = val.Integer() - lastVal;
  822. auto bonus = JsonUtils::parseBonus (bonusInput);
  823. bonus->source = BonusSource::STACK_EXPERIENCE;
  824. bonus->duration = BonusDuration::PERMANENT;
  825. bonus->addLimiter(std::make_shared<RankRangeLimiter>(lowerLimit));
  826. creature->addNewBonus (bonus);
  827. }
  828. lastVal = static_cast<int>(val.Float());
  829. ++lowerLimit;
  830. }
  831. }
  832. }
  833. }
  834. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) const//help function for parsing CREXPBON.txt
  835. {
  836. bool enable = false; //some bonuses are activated with values 2 or 1
  837. std::string buf = parser.readString();
  838. std::string mod = parser.readString();
  839. switch (buf[0])
  840. {
  841. case 'H':
  842. b.type = BonusType::STACK_HEALTH;
  843. b.valType = BonusValueType::PERCENT_TO_BASE;
  844. break;
  845. case 'A':
  846. b.type = BonusType::PRIMARY_SKILL;
  847. b.subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  848. break;
  849. case 'D':
  850. b.type = BonusType::PRIMARY_SKILL;
  851. b.subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  852. break;
  853. case 'M': //Max damage
  854. b.type = BonusType::CREATURE_DAMAGE;
  855. b.subtype = BonusCustomSubtype::creatureDamageMax;
  856. break;
  857. case 'm': //Min damage
  858. b.type = BonusType::CREATURE_DAMAGE;
  859. b.subtype = BonusCustomSubtype::creatureDamageMin;
  860. break;
  861. case 'S':
  862. b.type = BonusType::STACKS_SPEED; break;
  863. case 'O':
  864. b.type = BonusType::SHOTS; break;
  865. case 'b':
  866. b.type = BonusType::ENEMY_DEFENCE_REDUCTION; break;
  867. case 'C':
  868. b.type = BonusType::CHANGES_SPELL_COST_FOR_ALLY; break;
  869. case 'd':
  870. b.type = BonusType::DEFENSIVE_STANCE; break;
  871. case 'e':
  872. b.type = BonusType::DOUBLE_DAMAGE_CHANCE;
  873. break;
  874. case 'E':
  875. b.type = BonusType::DEATH_STARE;
  876. b.subtype = BonusCustomSubtype::deathStareGorgon;
  877. break;
  878. case 'F':
  879. b.type = BonusType::FEARFUL; break;
  880. case 'g':
  881. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  882. b.subtype = BonusSubtypeID(SpellSchool::ANY);
  883. break;
  884. case 'P':
  885. b.type = BonusType::CASTS; break;
  886. case 'R':
  887. b.type = BonusType::ADDITIONAL_RETALIATION; break;
  888. case 'W':
  889. b.type = BonusType::MAGIC_RESISTANCE;
  890. break;
  891. case 'f': //on-off skill
  892. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  893. switch (mod[0])
  894. {
  895. case 'A':
  896. b.type = BonusType::ATTACKS_ALL_ADJACENT; break;
  897. case 'b':
  898. b.type = BonusType::RETURN_AFTER_STRIKE; break;
  899. case 'B':
  900. b.type = BonusType::TWO_HEX_ATTACK_BREATH; break;
  901. case 'c':
  902. b.type = BonusType::JOUSTING;
  903. b.val = 5;
  904. break;
  905. case 'D':
  906. b.type = BonusType::ADDITIONAL_ATTACK; break;
  907. case 'f':
  908. b.type = BonusType::FEARFUL; break;
  909. case 'F':
  910. b.type = BonusType::FLYING; break;
  911. case 'm':
  912. b.type = BonusType::MORALE;
  913. b.val = 1;
  914. b.valType = BonusValueType::INDEPENDENT_MAX;
  915. break;
  916. case 'M':
  917. b.type = BonusType::NO_MORALE; break;
  918. case 'p': //Mind spells
  919. case 'P':
  920. b.type = BonusType::MIND_IMMUNITY; break;
  921. case 'r':
  922. b.type = BonusType::REBIRTH; //on/off? makes sense?
  923. b.subtype = BonusCustomSubtype::rebirthRegular;
  924. b.val = 20; //arbitrary value
  925. break;
  926. case 'R':
  927. b.type = BonusType::BLOCKS_RETALIATION; break;
  928. case 's':
  929. b.type = BonusType::FREE_SHOOTING; break;
  930. case 'u':
  931. b.type = BonusType::SPELL_RESISTANCE_AURA; break;
  932. case 'U':
  933. b.type = BonusType::UNDEAD; break;
  934. default:
  935. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  936. return;
  937. break;
  938. }
  939. break;
  940. case 'w': //specific spell immunities, enabled/disabled
  941. enable = true;
  942. switch (mod[0])
  943. {
  944. case 'B': //Blind
  945. b.type = BonusType::SPELL_IMMUNITY;
  946. b.subtype = BonusSubtypeID(SpellID(SpellID::BLIND));
  947. b.additionalInfo = 0;//normal immunity
  948. break;
  949. case 'H': //Hypnotize
  950. b.type = BonusType::SPELL_IMMUNITY;
  951. b.subtype = BonusSubtypeID(SpellID(SpellID::HYPNOTIZE));
  952. b.additionalInfo = 0;//normal immunity
  953. break;
  954. case 'I': //Implosion
  955. b.type = BonusType::SPELL_IMMUNITY;
  956. b.subtype = BonusSubtypeID(SpellID(SpellID::IMPLOSION));
  957. b.additionalInfo = 0;//normal immunity
  958. break;
  959. case 'K': //Berserk
  960. b.type = BonusType::SPELL_IMMUNITY;
  961. b.subtype = BonusSubtypeID(SpellID(SpellID::BERSERK));
  962. b.additionalInfo = 0;//normal immunity
  963. break;
  964. case 'M': //Meteor Shower
  965. b.type = BonusType::SPELL_IMMUNITY;
  966. b.subtype = BonusSubtypeID(SpellID(SpellID::METEOR_SHOWER));
  967. b.additionalInfo = 0;//normal immunity
  968. break;
  969. case 'N': //dispel beneficial spells
  970. b.type = BonusType::SPELL_IMMUNITY;
  971. b.subtype = BonusSubtypeID(SpellID(SpellID::DISPEL_HELPFUL_SPELLS));
  972. b.additionalInfo = 0;//normal immunity
  973. break;
  974. case 'R': //Armageddon
  975. b.type = BonusType::SPELL_IMMUNITY;
  976. b.subtype = BonusSubtypeID(SpellID(SpellID::ARMAGEDDON));
  977. b.additionalInfo = 0;//normal immunity
  978. break;
  979. case 'S': //Slow
  980. b.type = BonusType::SPELL_IMMUNITY;
  981. b.subtype = BonusSubtypeID(SpellID(SpellID::SLOW));
  982. b.additionalInfo = 0;//normal immunity
  983. break;
  984. case '6':
  985. case '7':
  986. case '8':
  987. case '9':
  988. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  989. b.val = std::atoi(mod.c_str()) - 5;
  990. break;
  991. case ':':
  992. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  993. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  994. break;
  995. case 'F':
  996. b.type = BonusType::NEGATIVE_EFFECTS_IMMUNITY;
  997. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  998. break;
  999. case 'O':
  1000. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1001. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1002. b.val = 100; //Full damage immunity
  1003. break;
  1004. case 'f':
  1005. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1006. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1007. break;
  1008. case 'C':
  1009. b.type = BonusType::NEGATIVE_EFFECTS_IMMUNITY;
  1010. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1011. break;
  1012. case 'W':
  1013. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1014. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1015. b.val = 100; //Full damage immunity
  1016. break;
  1017. case 'w':
  1018. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1019. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1020. break;
  1021. case 'E':
  1022. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1023. b.subtype = BonusSubtypeID(SpellSchool::EARTH);
  1024. b.val = 100; //Full damage immunity
  1025. break;
  1026. case 'e':
  1027. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1028. b.subtype = BonusSubtypeID(SpellSchool::EARTH);
  1029. break;
  1030. case 'A':
  1031. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1032. b.subtype = BonusSubtypeID(SpellSchool::AIR);
  1033. b.val = 100; //Full damage immunity
  1034. break;
  1035. case 'a':
  1036. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1037. b.subtype = BonusSubtypeID(SpellSchool::AIR);
  1038. break;
  1039. case 'D':
  1040. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1041. b.subtype = BonusSubtypeID(SpellSchool::ANY);
  1042. b.val = 100; //Full damage immunity
  1043. break;
  1044. case '0':
  1045. b.type = BonusType::RECEPTIVE;
  1046. break;
  1047. case 'm':
  1048. b.type = BonusType::MIND_IMMUNITY;
  1049. break;
  1050. default:
  1051. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1052. return;
  1053. }
  1054. break;
  1055. case 'i':
  1056. enable = true;
  1057. b.type = BonusType::NO_DISTANCE_PENALTY;
  1058. break;
  1059. case 'o':
  1060. enable = true;
  1061. b.type = BonusType::NO_WALL_PENALTY;
  1062. break;
  1063. case 'a':
  1064. case 'c':
  1065. case 'K':
  1066. case 'k':
  1067. b.type = BonusType::SPELL_AFTER_ATTACK;
  1068. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1069. break;
  1070. case 'h':
  1071. b.type = BonusType::HATE;
  1072. b.subtype = BonusSubtypeID(CreatureID(stringToNumber(mod)));
  1073. break;
  1074. case 'p':
  1075. case 'J':
  1076. b.type = BonusType::SPELL_BEFORE_ATTACK;
  1077. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1078. b.additionalInfo = 3; //always expert?
  1079. break;
  1080. case 'r':
  1081. b.type = BonusType::HP_REGENERATION;
  1082. b.val = stringToNumber(mod);
  1083. break;
  1084. case 's':
  1085. b.type = BonusType::ENCHANTED;
  1086. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1087. b.valType = BonusValueType::INDEPENDENT_MAX;
  1088. break;
  1089. default:
  1090. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1091. return;
  1092. break;
  1093. }
  1094. switch (mod[0])
  1095. {
  1096. case '+':
  1097. case '=': //should we allow percent values to stack or pick highest?
  1098. b.valType = BonusValueType::ADDITIVE_VALUE;
  1099. break;
  1100. }
  1101. //limiters, range
  1102. si32 lastVal;
  1103. si32 curVal;
  1104. si32 lastLev = 0;
  1105. if (enable) //0 and 2 means non-active, 1 - active
  1106. {
  1107. if (b.type != BonusType::REBIRTH)
  1108. b.val = 0; //on-off ability, no value specified
  1109. parser.readNumber(); // 0 level is never active
  1110. for (int i = 1; i < 11; ++i)
  1111. {
  1112. curVal = static_cast<si32>(parser.readNumber());
  1113. if (curVal == 1)
  1114. {
  1115. b.limiter.reset (new RankRangeLimiter(i));
  1116. bl.push_back(std::make_shared<Bonus>(b));
  1117. break; //never turned off it seems
  1118. }
  1119. }
  1120. }
  1121. else
  1122. {
  1123. lastVal = static_cast<si32>(parser.readNumber());
  1124. if (b.type == BonusType::HATE)
  1125. lastVal *= 10; //odd fix
  1126. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1127. for (int i = 1; i < 11; ++i)
  1128. {
  1129. curVal = static_cast<si32>(parser.readNumber());
  1130. if (b.type == BonusType::HATE)
  1131. curVal *= 10; //odd fix
  1132. if (curVal > lastVal) //threshold, add new bonus
  1133. {
  1134. b.val = curVal - lastVal;
  1135. lastVal = curVal;
  1136. b.limiter.reset (new RankRangeLimiter(i));
  1137. bl.push_back(std::make_shared<Bonus>(b));
  1138. lastLev = i; //start new range from here, i = previous rank
  1139. }
  1140. else if (curVal < lastVal)
  1141. {
  1142. b.val = lastVal;
  1143. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1144. }
  1145. }
  1146. }
  1147. }
  1148. int CCreatureHandler::stringToNumber(std::string & s) const
  1149. {
  1150. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1151. return std::atoi(s.c_str());
  1152. }
  1153. CCreatureHandler::~CCreatureHandler()
  1154. {
  1155. for(auto & p : skillRequirements)
  1156. p.first.clear();
  1157. }
  1158. void CCreatureHandler::afterLoadFinalization()
  1159. {
  1160. for(auto & creature : objects)
  1161. {
  1162. if (!creature)
  1163. continue;
  1164. auto natureBonuses = creature->getBonuses([](const Bonus * b){
  1165. return LIBRARY->bth->isCreatureNatureBonus(b->type);
  1166. });
  1167. if (natureBonuses->empty())
  1168. creature->addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::LIVING, BonusSource::CREATURE_ABILITY, 0, BonusSourceID(creature->getId())));
  1169. }
  1170. }
  1171. std::set<CreatureID> CCreatureHandler::getDefaultAllowed() const
  1172. {
  1173. std::set<CreatureID> result;
  1174. for(auto & creature : objects)
  1175. if (creature && !creature->special)
  1176. result.insert(creature->getId());
  1177. return result;
  1178. }
  1179. VCMI_LIB_NAMESPACE_END