CCreatureHandler.cpp 40 KB

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