CCreatureHandler.cpp 40 KB

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