CCreatureHandler.cpp 40 KB

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