CCreatureHandler.cpp 40 KB

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