CCreatureHandler.cpp 40 KB

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