CCreatureHandler.cpp 41 KB

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