CCreatureHandler.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  542. {
  543. std::vector<bool> ret;
  544. ret.reserve(objects.size());
  545. for(const CCreature * crea : objects)
  546. {
  547. ret.push_back(crea ? !crea->special : false);
  548. }
  549. return ret;
  550. }
  551. void CCreatureHandler::loadCrExpMod()
  552. {
  553. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) //reading default stack experience values
  554. {
  555. //Calculate rank exp values, formula appears complicated bu no parsing needed
  556. expRanks.resize(8);
  557. int dif = 0;
  558. int it = 8000; //ignore name of this variable
  559. expRanks[0].push_back(it);
  560. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  561. {
  562. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  563. dif += it/5;
  564. }
  565. for (int i = 1; i < 8; ++i) //used for tiers 1-7
  566. {
  567. dif = 0;
  568. it = 1000 * i;
  569. expRanks[i].push_back(it);
  570. for (int j = 1; j < 10; ++j)
  571. {
  572. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  573. dif += it/5;
  574. }
  575. }
  576. CLegacyConfigParser expBonParser(TextPath::builtin("DATA/CREXPMOD.TXT"));
  577. expBonParser.endLine(); //header
  578. maxExpPerBattle.resize(8);
  579. for (int i = 1; i < 8; ++i)
  580. {
  581. expBonParser.readString(); //index
  582. expBonParser.readString(); //float multiplier -> hardcoded
  583. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  584. expBonParser.readString(); //already calculated
  585. maxExpPerBattle[i] = static_cast<ui32>(expBonParser.readNumber());
  586. expRanks[i].push_back(expRanks[i].back() + static_cast<ui32>(expBonParser.readNumber()));
  587. expBonParser.endLine();
  588. }
  589. //exp for tier >7, rank 11
  590. expRanks[0].push_back(147000);
  591. expAfterUpgrade = 75; //percent
  592. maxExpPerBattle[0] = maxExpPerBattle[7];
  593. }
  594. }
  595. void CCreatureHandler::loadCrExpBon(CBonusSystemNode & globalEffects)
  596. {
  597. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE)) //reading default stack experience bonuses
  598. {
  599. logGlobal->debug("\tLoading stack experience bonuses");
  600. auto addBonusForAllCreatures = [&](std::shared_ptr<Bonus> b) {
  601. auto limiter = std::make_shared<CreatureLevelLimiter>();
  602. b->addLimiter(limiter);
  603. globalEffects.addNewBonus(b);
  604. };
  605. auto addBonusForTier = [&](int tier, std::shared_ptr<Bonus> b) {
  606. assert(vstd::iswithin(tier, 1, 7));
  607. //bonuses from level 7 are given to high-level creatures too
  608. auto max = tier == GameConstants::CREATURES_PER_TOWN ? std::numeric_limits<int>::max() : tier + 1;
  609. auto limiter = std::make_shared<CreatureLevelLimiter>(tier, max);
  610. b->addLimiter(limiter);
  611. globalEffects.addNewBonus(b);
  612. };
  613. CLegacyConfigParser parser(TextPath::builtin("DATA/CREXPBON.TXT"));
  614. Bonus b; //prototype with some default properties
  615. b.source = BonusSource::STACK_EXPERIENCE;
  616. b.duration = BonusDuration::PERMANENT;
  617. b.valType = BonusValueType::ADDITIVE_VALUE;
  618. b.effectRange = BonusLimitEffect::NO_LIMIT;
  619. b.additionalInfo = 0;
  620. b.turnsRemain = 0;
  621. BonusList bl;
  622. parser.endLine();
  623. parser.readString(); //ignore index
  624. loadStackExp(b, bl, parser);
  625. for(const auto & b : bl)
  626. addBonusForAllCreatures(b); //health bonus is common for all
  627. parser.endLine();
  628. for (int i = 1; i < 7; ++i)
  629. {
  630. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  631. {
  632. parser.readString(); //ignore index
  633. bl.clear();
  634. loadStackExp(b, bl, parser);
  635. for(const auto & b : bl)
  636. addBonusForTier(i, b);
  637. parser.endLine();
  638. }
  639. }
  640. for (int j = 0; j < 4; ++j) //tier 7
  641. {
  642. parser.readString(); //ignore index
  643. bl.clear();
  644. loadStackExp(b, bl, parser);
  645. for(const auto & b : bl)
  646. addBonusForTier(7, b);
  647. parser.endLine();
  648. }
  649. do //parse everything that's left
  650. {
  651. CreatureID sid = static_cast<ui32>(parser.readNumber()); //id = this particular creature ID
  652. b.sid = BonusSourceID(sid);
  653. bl.clear();
  654. loadStackExp(b, bl, parser);
  655. for(const auto & b : bl)
  656. {
  657. objects[sid]->addNewBonus(b); //add directly to CCreature Node
  658. }
  659. }
  660. while (parser.endLine());
  661. }//end of Stack Experience
  662. }
  663. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data) const
  664. {
  665. CLegacyConfigParser parser(TextPath::builtin("DATA/CRANIM.TXT"));
  666. parser.endLine(); // header
  667. parser.endLine();
  668. for(int dd = 0; dd < VLC->settings()->getInteger(EGameSettings::TEXTS_CREATURE); ++dd)
  669. {
  670. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  671. ;
  672. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  673. parser.endLine();
  674. }
  675. }
  676. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser) const
  677. {
  678. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  679. JsonNode & animationTime = graphics["animationTime"];
  680. animationTime["walk"].Float() = parser.readNumber();
  681. animationTime["attack"].Float() = parser.readNumber();
  682. parser.readNumber(); // unused value "Flight animation time" - H3 actually uses "Walk animation time" even for flying creatures
  683. animationTime["idle"].Float() = 10.0;
  684. JsonNode & missile = graphics["missile"];
  685. JsonNode & offsets = missile["offset"];
  686. offsets["upperX"].Float() = parser.readNumber();
  687. offsets["upperY"].Float() = parser.readNumber();
  688. offsets["middleX"].Float() = parser.readNumber();
  689. offsets["middleY"].Float() = parser.readNumber();
  690. offsets["lowerX"].Float() = parser.readNumber();
  691. offsets["lowerY"].Float() = parser.readNumber();
  692. for(int i=0; i<12; i++)
  693. {
  694. JsonNode entry;
  695. entry.Float() = parser.readNumber();
  696. missile["frameAngles"].Vector().push_back(entry);
  697. }
  698. // Unused property "troopCountLocationOffset"
  699. parser.readNumber();
  700. missile["attackClimaxFrame"].Float() = parser.readNumber();
  701. // assume that creature is not a shooter and should not have whole missile field
  702. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  703. missile["attackClimaxFrame"].Float() == 0)
  704. graphics.Struct().erase("missile");
  705. }
  706. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics) const
  707. {
  708. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  709. const JsonNode & animationTime = graphics["animationTime"];
  710. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  711. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  712. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  713. const JsonNode & missile = graphics["missile"];
  714. const JsonNode & offsets = missile["offset"];
  715. cre->animation.upperRightMissleOffsetX = static_cast<int>(offsets["upperX"].Float());
  716. cre->animation.upperRightMissleOffsetY = static_cast<int>(offsets["upperY"].Float());
  717. cre->animation.rightMissleOffsetX = static_cast<int>(offsets["middleX"].Float());
  718. cre->animation.rightMissleOffsetY = static_cast<int>(offsets["middleY"].Float());
  719. cre->animation.lowerRightMissleOffsetX = static_cast<int>(offsets["lowerX"].Float());
  720. cre->animation.lowerRightMissleOffsetY = static_cast<int>(offsets["lowerY"].Float());
  721. cre->animation.attackClimaxFrame = static_cast<int>(missile["attackClimaxFrame"].Float());
  722. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  723. cre->smallIconName = graphics["iconSmall"].String();
  724. cre->largeIconName = graphics["iconLarge"].String();
  725. }
  726. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config) const
  727. {
  728. creature->animDefName = AnimationPath::fromJson(config["graphics"]["animation"]);
  729. //FIXME: MOD COMPATIBILITY
  730. if (config["abilities"].getType() == JsonNode::JsonType::DATA_STRUCT)
  731. {
  732. for(const auto & ability : config["abilities"].Struct())
  733. {
  734. if (!ability.second.isNull())
  735. {
  736. auto b = JsonUtils::parseBonus(ability.second);
  737. b->source = BonusSource::CREATURE_ABILITY;
  738. b->sid = BonusSourceID(creature->getId());
  739. b->duration = BonusDuration::PERMANENT;
  740. creature->addNewBonus(b);
  741. }
  742. }
  743. }
  744. else
  745. {
  746. for(const JsonNode &ability : config["abilities"].Vector())
  747. {
  748. if(ability.getType() == JsonNode::JsonType::DATA_VECTOR)
  749. {
  750. logMod->error("Ignored outdated creature ability format in %s", creature->getJsonKey());
  751. }
  752. else
  753. {
  754. auto b = JsonUtils::parseBonus(ability);
  755. b->source = BonusSource::CREATURE_ABILITY;
  756. b->sid = BonusSourceID(creature->getId());
  757. b->duration = BonusDuration::PERMANENT;
  758. creature->addNewBonus(b);
  759. }
  760. }
  761. }
  762. VLC->identifiers()->requestIdentifier("faction", config["faction"], [=](si32 faction)
  763. {
  764. creature->faction = FactionID(faction);
  765. });
  766. for(const JsonNode &value : config["upgrades"].Vector())
  767. {
  768. VLC->identifiers()->requestIdentifier("creature", value, [=](si32 identifier)
  769. {
  770. creature->upgrades.insert(CreatureID(identifier));
  771. });
  772. }
  773. creature->animation.projectileImageName = AnimationPath::fromJson(config["graphics"]["missile"]["projectile"]);
  774. for(const JsonNode & value : config["graphics"]["missile"]["ray"].Vector())
  775. {
  776. CCreature::CreatureAnimation::RayColor color;
  777. color.start.r = value["start"].Vector()[0].Integer();
  778. color.start.g = value["start"].Vector()[1].Integer();
  779. color.start.b = value["start"].Vector()[2].Integer();
  780. color.start.a = value["start"].Vector()[3].Integer();
  781. color.end.r = value["end"].Vector()[0].Integer();
  782. color.end.g = value["end"].Vector()[1].Integer();
  783. color.end.b = value["end"].Vector()[2].Integer();
  784. color.end.a = value["end"].Vector()[3].Integer();
  785. creature->animation.projectileRay.push_back(color);
  786. }
  787. creature->special = config["special"].Bool() || config["disabled"].Bool();
  788. const JsonNode & sounds = config["sound"];
  789. creature->sounds.attack = AudioPath::fromJson(sounds["attack"]);
  790. creature->sounds.defend = AudioPath::fromJson(sounds["defend"]);
  791. creature->sounds.killed = AudioPath::fromJson(sounds["killed"]);
  792. creature->sounds.move = AudioPath::fromJson(sounds["move"]);
  793. creature->sounds.shoot = AudioPath::fromJson(sounds["shoot"]);
  794. creature->sounds.wince = AudioPath::fromJson(sounds["wince"]);
  795. creature->sounds.startMoving = AudioPath::fromJson(sounds["startMoving"]);
  796. creature->sounds.endMoving = AudioPath::fromJson(sounds["endMoving"]);
  797. }
  798. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input) const
  799. {
  800. for (const JsonNode &exp : input.Vector())
  801. {
  802. const JsonVector &values = exp["values"].Vector();
  803. int lowerLimit = 1;//, upperLimit = 255;
  804. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  805. {
  806. for (const JsonNode &val : values)
  807. {
  808. if(val.Bool())
  809. {
  810. // parse each bonus separately
  811. // we can not create copies since identifiers resolution does not tracks copies
  812. // leading to unset identifier values in copies
  813. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  814. bonus->source = BonusSource::STACK_EXPERIENCE;
  815. bonus->duration = BonusDuration::PERMANENT;
  816. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  817. creature->addNewBonus (bonus);
  818. break; //TODO: allow bonuses to turn off?
  819. }
  820. ++lowerLimit;
  821. }
  822. }
  823. else
  824. {
  825. int lastVal = 0;
  826. for (const JsonNode &val : values)
  827. {
  828. if (val.Float() != lastVal)
  829. {
  830. JsonNode bonusInput = exp["bonus"];
  831. bonusInput["val"].Float() = static_cast<int>(val.Float()) - lastVal;
  832. auto bonus = JsonUtils::parseBonus (bonusInput);
  833. bonus->source = BonusSource::STACK_EXPERIENCE;
  834. bonus->duration = BonusDuration::PERMANENT;
  835. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  836. creature->addNewBonus (bonus);
  837. }
  838. lastVal = static_cast<int>(val.Float());
  839. ++lowerLimit;
  840. }
  841. }
  842. }
  843. }
  844. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) const//help function for parsing CREXPBON.txt
  845. {
  846. bool enable = false; //some bonuses are activated with values 2 or 1
  847. std::string buf = parser.readString();
  848. std::string mod = parser.readString();
  849. switch (buf[0])
  850. {
  851. case 'H':
  852. b.type = BonusType::STACK_HEALTH;
  853. b.valType = BonusValueType::PERCENT_TO_BASE;
  854. break;
  855. case 'A':
  856. b.type = BonusType::PRIMARY_SKILL;
  857. b.subtype = BonusSubtypeID(PrimarySkill::ATTACK);
  858. break;
  859. case 'D':
  860. b.type = BonusType::PRIMARY_SKILL;
  861. b.subtype = BonusSubtypeID(PrimarySkill::DEFENSE);
  862. break;
  863. case 'M': //Max damage
  864. b.type = BonusType::CREATURE_DAMAGE;
  865. b.subtype = BonusCustomSubtype::creatureDamageMax;
  866. break;
  867. case 'm': //Min damage
  868. b.type = BonusType::CREATURE_DAMAGE;
  869. b.subtype = BonusCustomSubtype::creatureDamageMin;
  870. break;
  871. case 'S':
  872. b.type = BonusType::STACKS_SPEED; break;
  873. case 'O':
  874. b.type = BonusType::SHOTS; break;
  875. case 'b':
  876. b.type = BonusType::ENEMY_DEFENCE_REDUCTION; break;
  877. case 'C':
  878. b.type = BonusType::CHANGES_SPELL_COST_FOR_ALLY; break;
  879. case 'd':
  880. b.type = BonusType::DEFENSIVE_STANCE; break;
  881. case 'e':
  882. b.type = BonusType::DOUBLE_DAMAGE_CHANCE;
  883. break;
  884. case 'E':
  885. b.type = BonusType::DEATH_STARE;
  886. b.subtype = BonusCustomSubtype::deathStareGorgon;
  887. break;
  888. case 'F':
  889. b.type = BonusType::FEAR; break;
  890. case 'g':
  891. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  892. b.subtype = BonusSubtypeID(SpellSchool::ANY);
  893. break;
  894. case 'P':
  895. b.type = BonusType::CASTS; break;
  896. case 'R':
  897. b.type = BonusType::ADDITIONAL_RETALIATION; break;
  898. case 'W':
  899. b.type = BonusType::MAGIC_RESISTANCE;
  900. break;
  901. case 'f': //on-off skill
  902. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  903. switch (mod[0])
  904. {
  905. case 'A':
  906. b.type = BonusType::ATTACKS_ALL_ADJACENT; break;
  907. case 'b':
  908. b.type = BonusType::RETURN_AFTER_STRIKE; break;
  909. case 'B':
  910. b.type = BonusType::TWO_HEX_ATTACK_BREATH; break;
  911. case 'c':
  912. b.type = BonusType::JOUSTING;
  913. b.val = 5;
  914. break;
  915. case 'D':
  916. b.type = BonusType::ADDITIONAL_ATTACK; break;
  917. case 'f':
  918. b.type = BonusType::FEARLESS; break;
  919. case 'F':
  920. b.type = BonusType::FLYING; break;
  921. case 'm':
  922. b.type = BonusType::MORALE;
  923. b.val = 1;
  924. b.valType = BonusValueType::INDEPENDENT_MAX;
  925. break;
  926. case 'M':
  927. b.type = BonusType::NO_MORALE; break;
  928. case 'p': //Mind spells
  929. case 'P':
  930. b.type = BonusType::MIND_IMMUNITY; break;
  931. case 'r':
  932. b.type = BonusType::REBIRTH; //on/off? makes sense?
  933. b.subtype = BonusCustomSubtype::rebirthRegular;
  934. b.val = 20; //arbitrary value
  935. break;
  936. case 'R':
  937. b.type = BonusType::BLOCKS_RETALIATION; break;
  938. case 's':
  939. b.type = BonusType::FREE_SHOOTING; break;
  940. case 'u':
  941. b.type = BonusType::SPELL_RESISTANCE_AURA; break;
  942. case 'U':
  943. b.type = BonusType::UNDEAD; break;
  944. default:
  945. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  946. return;
  947. break;
  948. }
  949. break;
  950. case 'w': //specific spell immunities, enabled/disabled
  951. enable = true;
  952. switch (mod[0])
  953. {
  954. case 'B': //Blind
  955. b.type = BonusType::SPELL_IMMUNITY;
  956. b.subtype = BonusSubtypeID(SpellID(SpellID::BLIND));
  957. b.additionalInfo = 0;//normal immunity
  958. break;
  959. case 'H': //Hypnotize
  960. b.type = BonusType::SPELL_IMMUNITY;
  961. b.subtype = BonusSubtypeID(SpellID(SpellID::HYPNOTIZE));
  962. b.additionalInfo = 0;//normal immunity
  963. break;
  964. case 'I': //Implosion
  965. b.type = BonusType::SPELL_IMMUNITY;
  966. b.subtype = BonusSubtypeID(SpellID(SpellID::IMPLOSION));
  967. b.additionalInfo = 0;//normal immunity
  968. break;
  969. case 'K': //Berserk
  970. b.type = BonusType::SPELL_IMMUNITY;
  971. b.subtype = BonusSubtypeID(SpellID(SpellID::BERSERK));
  972. b.additionalInfo = 0;//normal immunity
  973. break;
  974. case 'M': //Meteor Shower
  975. b.type = BonusType::SPELL_IMMUNITY;
  976. b.subtype = BonusSubtypeID(SpellID(SpellID::METEOR_SHOWER));
  977. b.additionalInfo = 0;//normal immunity
  978. break;
  979. case 'N': //dispell beneficial spells
  980. b.type = BonusType::SPELL_IMMUNITY;
  981. b.subtype = BonusSubtypeID(SpellID(SpellID::DISPEL_HELPFUL_SPELLS));
  982. b.additionalInfo = 0;//normal immunity
  983. break;
  984. case 'R': //Armageddon
  985. b.type = BonusType::SPELL_IMMUNITY;
  986. b.subtype = BonusSubtypeID(SpellID(SpellID::ARMAGEDDON));
  987. b.additionalInfo = 0;//normal immunity
  988. break;
  989. case 'S': //Slow
  990. b.type = BonusType::SPELL_IMMUNITY;
  991. b.subtype = BonusSubtypeID(SpellID(SpellID::SLOW));
  992. b.additionalInfo = 0;//normal immunity
  993. break;
  994. case '6':
  995. case '7':
  996. case '8':
  997. case '9':
  998. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  999. b.val = std::atoi(mod.c_str()) - 5;
  1000. break;
  1001. case ':':
  1002. b.type = BonusType::LEVEL_SPELL_IMMUNITY;
  1003. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  1004. break;
  1005. case 'F':
  1006. b.type = BonusType::NEGATIVE_EFFECTS_IMMUNITY;
  1007. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1008. break;
  1009. case 'O':
  1010. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1011. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1012. b.val = 100; //Full damage immunity
  1013. break;
  1014. case 'f':
  1015. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1016. b.subtype = BonusSubtypeID(SpellSchool::FIRE);
  1017. break;
  1018. case 'C':
  1019. b.type = BonusType::NEGATIVE_EFFECTS_IMMUNITY;
  1020. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1021. break;
  1022. case 'W':
  1023. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1024. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1025. b.val = 100; //Full damage immunity
  1026. break;
  1027. case 'w':
  1028. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1029. b.subtype = BonusSubtypeID(SpellSchool::WATER);
  1030. break;
  1031. case 'E':
  1032. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1033. b.subtype = BonusSubtypeID(SpellSchool::EARTH);
  1034. b.val = 100; //Full damage immunity
  1035. break;
  1036. case 'e':
  1037. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1038. b.subtype = BonusSubtypeID(SpellSchool::EARTH);
  1039. break;
  1040. case 'A':
  1041. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1042. b.subtype = BonusSubtypeID(SpellSchool::AIR);
  1043. b.val = 100; //Full damage immunity
  1044. break;
  1045. case 'a':
  1046. b.type = BonusType::SPELL_SCHOOL_IMMUNITY;
  1047. b.subtype = BonusSubtypeID(SpellSchool::AIR);
  1048. break;
  1049. case 'D':
  1050. b.type = BonusType::SPELL_DAMAGE_REDUCTION;
  1051. b.subtype = BonusSubtypeID(SpellSchool::ANY);
  1052. b.val = 100; //Full damage immunity
  1053. break;
  1054. case '0':
  1055. b.type = BonusType::RECEPTIVE;
  1056. break;
  1057. case 'm':
  1058. b.type = BonusType::MIND_IMMUNITY;
  1059. break;
  1060. default:
  1061. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1062. return;
  1063. }
  1064. break;
  1065. case 'i':
  1066. enable = true;
  1067. b.type = BonusType::NO_DISTANCE_PENALTY;
  1068. break;
  1069. case 'o':
  1070. enable = true;
  1071. b.type = BonusType::NO_WALL_PENALTY;
  1072. break;
  1073. case 'a':
  1074. case 'c':
  1075. case 'K':
  1076. case 'k':
  1077. b.type = BonusType::SPELL_AFTER_ATTACK;
  1078. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1079. break;
  1080. case 'h':
  1081. b.type = BonusType::HATE;
  1082. b.subtype = BonusSubtypeID(CreatureID(stringToNumber(mod)));
  1083. break;
  1084. case 'p':
  1085. case 'J':
  1086. b.type = BonusType::SPELL_BEFORE_ATTACK;
  1087. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1088. b.additionalInfo = 3; //always expert?
  1089. break;
  1090. case 'r':
  1091. b.type = BonusType::HP_REGENERATION;
  1092. b.val = stringToNumber(mod);
  1093. break;
  1094. case 's':
  1095. b.type = BonusType::ENCHANTED;
  1096. b.subtype = BonusSubtypeID(SpellID(stringToNumber(mod)));
  1097. b.valType = BonusValueType::INDEPENDENT_MAX;
  1098. break;
  1099. default:
  1100. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1101. return;
  1102. break;
  1103. }
  1104. switch (mod[0])
  1105. {
  1106. case '+':
  1107. case '=': //should we allow percent values to stack or pick highest?
  1108. b.valType = BonusValueType::ADDITIVE_VALUE;
  1109. break;
  1110. }
  1111. //limiters, range
  1112. si32 lastVal;
  1113. si32 curVal;
  1114. si32 lastLev = 0;
  1115. if (enable) //0 and 2 means non-active, 1 - active
  1116. {
  1117. if (b.type != BonusType::REBIRTH)
  1118. b.val = 0; //on-off ability, no value specified
  1119. parser.readNumber(); // 0 level is never active
  1120. for (int i = 1; i < 11; ++i)
  1121. {
  1122. curVal = static_cast<si32>(parser.readNumber());
  1123. if (curVal == 1)
  1124. {
  1125. b.limiter.reset (new RankRangeLimiter(i));
  1126. bl.push_back(std::make_shared<Bonus>(b));
  1127. break; //never turned off it seems
  1128. }
  1129. }
  1130. }
  1131. else
  1132. {
  1133. lastVal = static_cast<si32>(parser.readNumber());
  1134. if (b.type == BonusType::HATE)
  1135. lastVal *= 10; //odd fix
  1136. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1137. for (int i = 1; i < 11; ++i)
  1138. {
  1139. curVal = static_cast<si32>(parser.readNumber());
  1140. if (b.type == BonusType::HATE)
  1141. curVal *= 10; //odd fix
  1142. if (curVal > lastVal) //threshold, add new bonus
  1143. {
  1144. b.val = curVal - lastVal;
  1145. lastVal = curVal;
  1146. b.limiter.reset (new RankRangeLimiter(i));
  1147. bl.push_back(std::make_shared<Bonus>(b));
  1148. lastLev = i; //start new range from here, i = previous rank
  1149. }
  1150. else if (curVal < lastVal)
  1151. {
  1152. b.val = lastVal;
  1153. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1154. }
  1155. }
  1156. }
  1157. }
  1158. int CCreatureHandler::stringToNumber(std::string & s) const
  1159. {
  1160. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1161. return std::atoi(s.c_str());
  1162. }
  1163. CCreatureHandler::~CCreatureHandler()
  1164. {
  1165. for(auto & p : skillRequirements)
  1166. p.first = nullptr;
  1167. }
  1168. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1169. {
  1170. std::vector<CreatureID> allowed;
  1171. for(const auto & creature : objects)
  1172. {
  1173. if(creature->special)
  1174. continue;
  1175. if (creature->level == tier || tier == -1)
  1176. allowed.push_back(creature->getId());
  1177. }
  1178. if(allowed.empty())
  1179. {
  1180. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1181. return CreatureID::NONE;
  1182. }
  1183. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1184. }
  1185. void CCreatureHandler::afterLoadFinalization()
  1186. {
  1187. }
  1188. VCMI_LIB_NAMESPACE_END