CCreatureHandler.cpp 41 KB

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