CCreatureHandler.cpp 39 KB

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