CCreatureHandler.cpp 40 KB

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