CCreatureHandler.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  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. int32_t CCreature::getIndex() const
  24. {
  25. return idNumber.toEnum();
  26. }
  27. int32_t CCreature::getIconIndex() const
  28. {
  29. return iconIndex;
  30. }
  31. std::string CCreature::getJsonKey() const
  32. {
  33. return modScope + ':' + identifier;
  34. }
  35. void CCreature::registerIcons(const IconRegistar & cb) const
  36. {
  37. cb(getIconIndex(), 0, "CPRSMALL", smallIconName);
  38. cb(getIconIndex(), 0, "TWCRPORT", largeIconName);
  39. }
  40. CreatureID CCreature::getId() const
  41. {
  42. return idNumber;
  43. }
  44. const IBonusBearer * CCreature::accessBonuses() const
  45. {
  46. return this;
  47. }
  48. uint32_t CCreature::getMaxHealth() const
  49. {
  50. return CBonusSystemNode::MaxHealth();
  51. }
  52. int32_t CCreature::getAdvMapAmountMin() const
  53. {
  54. return ammMin;
  55. }
  56. int32_t CCreature::getAdvMapAmountMax() const
  57. {
  58. return ammMax;
  59. }
  60. int32_t CCreature::getAIValue() const
  61. {
  62. return AIValue;
  63. }
  64. int32_t CCreature::getFightValue() const
  65. {
  66. return fightValue;
  67. }
  68. int32_t CCreature::getLevel() const
  69. {
  70. return level;
  71. }
  72. int32_t CCreature::getGrowth() const
  73. {
  74. return growth;
  75. }
  76. int32_t CCreature::getHorde() const
  77. {
  78. return hordeGrowth;
  79. }
  80. int32_t CCreature::getFactionIndex() const
  81. {
  82. return faction;
  83. }
  84. int32_t CCreature::getBaseAttack() const
  85. {
  86. static const auto SELECTOR = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  87. return getExportedBonusList().valOfBonuses(SELECTOR);
  88. }
  89. int32_t CCreature::getBaseDefense() const
  90. {
  91. static const auto SELECTOR = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  92. return getExportedBonusList().valOfBonuses(SELECTOR);
  93. }
  94. int32_t CCreature::getBaseDamageMin() const
  95. {
  96. static const auto SELECTOR = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  97. return getExportedBonusList().valOfBonuses(SELECTOR);
  98. }
  99. int32_t CCreature::getBaseDamageMax() const
  100. {
  101. static const auto SELECTOR = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  102. return getExportedBonusList().valOfBonuses(SELECTOR);
  103. }
  104. int32_t CCreature::getBaseHitPoints() const
  105. {
  106. static const auto SELECTOR = Selector::type()(Bonus::STACK_HEALTH).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  107. return getExportedBonusList().valOfBonuses(SELECTOR);
  108. }
  109. int32_t CCreature::getBaseSpellPoints() const
  110. {
  111. static const auto SELECTOR = Selector::type()(Bonus::CASTS).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  112. return getExportedBonusList().valOfBonuses(SELECTOR);
  113. }
  114. int32_t CCreature::getBaseSpeed() const
  115. {
  116. static const auto SELECTOR = Selector::type()(Bonus::STACKS_SPEED).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  117. return getExportedBonusList().valOfBonuses(SELECTOR);
  118. }
  119. int32_t CCreature::getBaseShots() const
  120. {
  121. static const auto SELECTOR = Selector::type()(Bonus::SHOTS).And(Selector::sourceTypeSel(Bonus::CREATURE_ABILITY));
  122. return getExportedBonusList().valOfBonuses(SELECTOR);
  123. }
  124. int32_t CCreature::getCost(int32_t resIndex) const
  125. {
  126. if(resIndex >= 0 && resIndex < cost.size())
  127. return cost[resIndex];
  128. else
  129. return 0;
  130. }
  131. std::string CCreature::getNameTranslated() const
  132. {
  133. return getNameSingularTranslated();
  134. }
  135. std::string CCreature::getNamePluralTranslated() const
  136. {
  137. return VLC->generaltexth->translate(getNamePluralTextID());
  138. }
  139. std::string CCreature::getNameSingularTranslated() const
  140. {
  141. return VLC->generaltexth->translate(getNameSingularTextID());
  142. }
  143. std::string CCreature::getNameTextID() const
  144. {
  145. return getNameSingularTextID();
  146. }
  147. std::string CCreature::getNamePluralTextID() const
  148. {
  149. return TextIdentifier("creatures", modScope, identifier, "name", "plural" ).get();
  150. }
  151. std::string CCreature::getNameSingularTextID() const
  152. {
  153. return TextIdentifier("creatures", modScope, identifier, "name", "singular" ).get();
  154. }
  155. int CCreature::getQuantityID(const int & quantity)
  156. {
  157. if (quantity<5)
  158. return 1;
  159. if (quantity<10)
  160. return 2;
  161. if (quantity<20)
  162. return 3;
  163. if (quantity<50)
  164. return 4;
  165. if (quantity<100)
  166. return 5;
  167. if (quantity<250)
  168. return 6;
  169. if (quantity<500)
  170. return 7;
  171. if (quantity<1000)
  172. return 8;
  173. return 9;
  174. }
  175. int CCreature::estimateCreatureCount(ui32 countID)
  176. {
  177. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  178. if(countID > 9)
  179. {
  180. logGlobal->error("Wrong countID %d!", countID);
  181. return 0;
  182. }
  183. else
  184. return creature_count[countID];
  185. }
  186. bool CCreature::isDoubleWide() const
  187. {
  188. return doubleWide;
  189. }
  190. /**
  191. * Determines if the creature is of a good alignment.
  192. * @return true if the creture is good, false otherwise.
  193. */
  194. bool CCreature::isGood () const
  195. {
  196. return (*VLC->townh)[faction]->alignment == EAlignment::GOOD;
  197. }
  198. /**
  199. * Determines if the creature is of an evil alignment.
  200. * @return true if the creature is evil, false otherwise.
  201. */
  202. bool CCreature::isEvil () const
  203. {
  204. return (*VLC->townh)[faction]->alignment == EAlignment::EVIL;
  205. }
  206. si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
  207. {
  208. int ret = 2147483645;
  209. int resAmnt = static_cast<int>(std::min(res.size(),cost.size()));
  210. for(int i=0;i<resAmnt;i++)
  211. if(cost[i])
  212. ret = std::min(ret,(int)(res[i]/cost[i]));
  213. return ret;
  214. }
  215. CCreature::CCreature()
  216. {
  217. setNodeType(CBonusSystemNode::CREATURE);
  218. faction = 0;
  219. level = 0;
  220. fightValue = AIValue = growth = hordeGrowth = ammMin = ammMax = 0;
  221. doubleWide = false;
  222. special = true;
  223. iconIndex = -1;
  224. }
  225. void CCreature::addBonus(int val, Bonus::BonusType type, int subtype)
  226. {
  227. auto selector = Selector::typeSubtype(type, subtype).And(Selector::source(Bonus::CREATURE_ABILITY, getIndex()));
  228. BonusList & exported = getExportedBonusList();
  229. BonusList existing;
  230. exported.getBonuses(existing, selector, Selector::all);
  231. if(existing.empty())
  232. {
  233. auto added = std::make_shared<Bonus>(Bonus::PERMANENT, type, Bonus::CREATURE_ABILITY, val, getIndex(), subtype, Bonus::BASE_NUMBER);
  234. addNewBonus(added);
  235. }
  236. else
  237. {
  238. std::shared_ptr<Bonus> b = existing[0];
  239. b->val = val;
  240. }
  241. }
  242. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  243. {
  244. //TODO upgrade of upgrade?
  245. return vstd::contains(upgrades, anotherCre->idNumber);
  246. }
  247. bool CCreature::valid() const
  248. {
  249. return this == VLC->creh->objects[idNumber];
  250. }
  251. std::string CCreature::nodeName() const
  252. {
  253. return "\"" + getNamePluralTextID() + "\"";
  254. }
  255. bool CCreature::isItNativeTerrain(TerrainId terrain) const
  256. {
  257. auto native = getNativeTerrain();
  258. return native == terrain || native == ETerrainId::ANY_TERRAIN;
  259. }
  260. TerrainId CCreature::getNativeTerrain() const
  261. {
  262. const std::string cachingStringNoTerrainPenalty = "type_NO_TERRAIN_PENALTY";
  263. static const auto selectorNoTerrainPenalty = Selector::type()(Bonus::NO_TERRAIN_PENALTY);
  264. //this code is used in the CreatureTerrainLimiter::limit to setup battle bonuses
  265. //and in the CGHeroInstance::getNativeTerrain() to setup mevement bonuses or/and penalties.
  266. return hasBonus(selectorNoTerrainPenalty, selectorNoTerrainPenalty)
  267. ? TerrainId(ETerrainId::ANY_TERRAIN)
  268. : (*VLC->townh)[faction]->nativeTerrain;
  269. }
  270. void CCreature::updateFrom(const JsonNode & data)
  271. {
  272. JsonUpdater handler(nullptr, data);
  273. {
  274. auto configScope = handler.enterStruct("config");
  275. const JsonNode & configNode = handler.getCurrent();
  276. serializeJson(handler);
  277. if(!configNode["hitPoints"].isNull())
  278. addBonus(configNode["hitPoints"].Integer(), Bonus::STACK_HEALTH);
  279. if(!configNode["speed"].isNull())
  280. addBonus(configNode["speed"].Integer(), Bonus::STACKS_SPEED);
  281. if(!configNode["attack"].isNull())
  282. addBonus(configNode["attack"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  283. if(!configNode["defense"].isNull())
  284. addBonus(configNode["defense"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  285. if(!configNode["damage"]["min"].isNull())
  286. addBonus(configNode["damage"]["min"].Integer(), Bonus::CREATURE_DAMAGE, 1);
  287. if(!configNode["damage"]["max"].isNull())
  288. addBonus(configNode["damage"]["max"].Integer(), Bonus::CREATURE_DAMAGE, 2);
  289. if(!configNode["shots"].isNull())
  290. addBonus(configNode["shots"].Integer(), Bonus::SHOTS);
  291. if(!configNode["spellPoints"].isNull())
  292. addBonus(configNode["spellPoints"].Integer(), Bonus::CASTS);
  293. }
  294. handler.serializeBonuses("bonuses", this);
  295. }
  296. void CCreature::serializeJson(JsonSerializeFormat & handler)
  297. {
  298. handler.serializeInt("fightValue", fightValue);
  299. handler.serializeInt("aiValue", AIValue);
  300. handler.serializeInt("growth", growth);
  301. handler.serializeInt("horde", hordeGrowth);// Needed at least until configurable buildings
  302. {
  303. auto advMapNode = handler.enterStruct("advMapAmount");
  304. handler.serializeInt("min", ammMin);
  305. handler.serializeInt("max", ammMax);
  306. }
  307. if(handler.updating)
  308. {
  309. cost.serializeJson(handler, "cost");
  310. handler.serializeInt("faction", faction);//TODO: unify with deferred resolve
  311. }
  312. handler.serializeInt("level", level);
  313. handler.serializeBool("doubleWide", doubleWide);
  314. if(!handler.saving)
  315. {
  316. if(ammMin > ammMax)
  317. logMod->error("Invalid creature '%s' configuration, advMapAmount.min > advMapAmount.max", identifier);
  318. }
  319. }
  320. void CCreature::fillWarMachine()
  321. {
  322. switch (idNumber)
  323. {
  324. case CreatureID::CATAPULT: //Catapult
  325. warMachine = ArtifactID::CATAPULT;
  326. break;
  327. case CreatureID::BALLISTA: //Ballista
  328. warMachine = ArtifactID::BALLISTA;
  329. break;
  330. case CreatureID::FIRST_AID_TENT: //First Aid tent
  331. warMachine = ArtifactID::FIRST_AID_TENT;
  332. break;
  333. case CreatureID::AMMO_CART: //Ammo cart
  334. warMachine = ArtifactID::AMMO_CART;
  335. break;
  336. }
  337. warMachine = ArtifactID::NONE; //this creature is not artifact
  338. }
  339. CCreatureHandler::CCreatureHandler()
  340. : expAfterUpgrade(0)
  341. {
  342. VLC->creh = this;
  343. allCreatures.setDescription("All creatures");
  344. allCreatures.setNodeType(CBonusSystemNode::ENodeTypes::ALL_CREATURES);
  345. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  346. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  347. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  348. loadCommanders();
  349. }
  350. const CCreature * CCreatureHandler::getCreature(const std::string & scope, const std::string & identifier) const
  351. {
  352. boost::optional<si32> index = VLC->modh->identifiers.getIdentifier(scope, "creature", identifier);
  353. if(!index)
  354. throw std::runtime_error("Creature not found "+identifier);
  355. return objects[*index];
  356. }
  357. void CCreatureHandler::loadCommanders()
  358. {
  359. JsonNode data(ResourceID("config/commanders.json"));
  360. data.setMeta(CModHandler::scopeBuiltin()); // assume that commanders are in core mod (for proper bonuses resolution)
  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.push_back (std::vector<ui8>());
  370. for (auto skillLevel : skill["levels"].Vector())
  371. {
  372. skillLevels[i].push_back ((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)
  386. {
  387. auto makeBonusNode = [&](std::string type) -> JsonNode
  388. {
  389. JsonNode ret;
  390. ret["type"].String() = type;
  391. return ret;
  392. };
  393. static const std::map<std::string, JsonNode> abilityMap =
  394. {
  395. {"FLYING_ARMY", makeBonusNode("FLYING")},
  396. {"SHOOTING_ARMY", makeBonusNode("SHOOTER")},
  397. {"SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON")},
  398. {"const_free_attack", makeBonusNode("BLOCKS_RETALIATION")},
  399. {"IS_UNDEAD", makeBonusNode("UNDEAD")},
  400. {"const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY")},
  401. {"const_jousting", makeBonusNode("JOUSTING")},
  402. {"KING_1", makeBonusNode("KING1")},
  403. {"KING_2", makeBonusNode("KING2")},
  404. {"KING_3", makeBonusNode("KING3")},
  405. {"const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY")},
  406. {"CATAPULT", makeBonusNode("CATAPULT")},
  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(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(size_t dataSize)
  431. {
  432. objects.resize(dataSize);
  433. std::vector<JsonNode> h3Data;
  434. h3Data.reserve(dataSize);
  435. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  436. parser.endLine(); // header
  437. // this file is a bit different in some of Russian localisations:
  438. //ENG: Singular Plural Wood ...
  439. //RUS: Singular Plural Plural2 Wood ...
  440. // Try to detect which version this is by header
  441. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  442. size_t namesCount;
  443. {
  444. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  445. throw std::runtime_error("Incorrect format of CrTraits.txt");
  446. if (parser.readString() == "Plural2")
  447. namesCount = 3;
  448. else
  449. namesCount = 2;
  450. parser.endLine();
  451. }
  452. for (size_t i=0; i<dataSize; i++)
  453. {
  454. //loop till non-empty line
  455. while (parser.isNextEntryEmpty())
  456. parser.endLine();
  457. JsonNode data;
  458. data["name"]["singular"].String() = parser.readString();
  459. if (namesCount == 3)
  460. parser.readString();
  461. data["name"]["plural"].String() = parser.readString();
  462. for(int v=0; v<7; ++v)
  463. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  464. data["fightValue"].Float() = parser.readNumber();
  465. data["aiValue"].Float() = parser.readNumber();
  466. data["growth"].Float() = parser.readNumber();
  467. data["horde"].Float() = parser.readNumber();
  468. data["hitPoints"].Float() = parser.readNumber();
  469. data["speed"].Float() = parser.readNumber();
  470. data["attack"].Float() = parser.readNumber();
  471. data["defense"].Float() = parser.readNumber();
  472. data["damage"]["min"].Float() = parser.readNumber();
  473. data["damage"]["max"].Float() = parser.readNumber();
  474. if (float shots = parser.readNumber())
  475. data["shots"].Float() = shots;
  476. if (float spells = parser.readNumber())
  477. data["spellPoints"].Float() = spells;
  478. data["advMapAmount"]["min"].Float() = parser.readNumber();
  479. data["advMapAmount"]["max"].Float() = parser.readNumber();
  480. data["abilityText"].String() = parser.readString();
  481. loadBonuses(data, parser.readString()); //Attributes
  482. h3Data.push_back(data);
  483. }
  484. loadAnimationInfo(h3Data);
  485. return h3Data;
  486. }
  487. CCreature * CCreatureHandler::loadFromJson(const std::string & scope, const JsonNode & node, const std::string & identifier, size_t index)
  488. {
  489. assert(identifier.find(':') == std::string::npos);
  490. assert(!scope.empty());
  491. auto cre = new CCreature();
  492. if(node["hasDoubleWeek"].Bool())
  493. {
  494. doubledCreatures.insert(CreatureID(index));
  495. }
  496. cre->idNumber = CreatureID(index);
  497. cre->iconIndex = cre->getIndex() + 2;
  498. cre->identifier = identifier;
  499. cre->modScope = scope;
  500. JsonDeserializer handler(nullptr, node);
  501. cre->serializeJson(handler);
  502. cre->cost = Res::ResourceSet(node["cost"]);
  503. VLC->generaltexth->registerString(cre->getNameSingularTextID(), node["name"]["singular"].String());
  504. VLC->generaltexth->registerString(cre->getNamePluralTextID(), node["name"]["plural"].String());
  505. cre->addBonus(node["hitPoints"].Integer(), Bonus::STACK_HEALTH);
  506. cre->addBonus(node["speed"].Integer(), Bonus::STACKS_SPEED);
  507. cre->addBonus(node["attack"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  508. cre->addBonus(node["defense"].Integer(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  509. cre->addBonus(node["damage"]["min"].Integer(), Bonus::CREATURE_DAMAGE, 1);
  510. cre->addBonus(node["damage"]["max"].Integer(), Bonus::CREATURE_DAMAGE, 2);
  511. assert(node["damage"]["min"].Integer() <= node["damage"]["max"].Integer());
  512. if(!node["shots"].isNull())
  513. cre->addBonus(node["shots"].Integer(), Bonus::SHOTS);
  514. loadStackExperience(cre, node["stackExperience"]);
  515. loadJsonAnimation(cre, node["graphics"]);
  516. loadCreatureJson(cre, node);
  517. for(auto & extraName : node["extraNames"].Vector())
  518. {
  519. for(auto type_name : getTypeNames())
  520. registerObject(scope, type_name, extraName.String(), cre->getIndex());
  521. }
  522. VLC->modh->identifiers.requestIdentifier(scope, "object", "monster", [=](si32 index)
  523. {
  524. JsonNode conf;
  525. conf.setMeta(scope);
  526. VLC->objtypeh->loadSubObject(cre->identifier, conf, Obj::MONSTER, cre->idNumber.num);
  527. if (!cre->advMapDef.empty())
  528. {
  529. JsonNode templ;
  530. templ["animation"].String() = cre->advMapDef;
  531. templ.setMeta(scope);
  532. VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->idNumber.num)->addTemplate(templ);
  533. }
  534. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  535. if (VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->idNumber.num)->getTemplates().empty())
  536. VLC->objtypeh->removeSubObject(Obj::MONSTER, cre->idNumber.num);
  537. });
  538. return cre;
  539. }
  540. const std::vector<std::string> & CCreatureHandler::getTypeNames() const
  541. {
  542. static const std::vector<std::string> typeNames = { "creature" };
  543. return typeNames;
  544. }
  545. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  546. {
  547. std::vector<bool> ret;
  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->modh->modules.STACK_EXP) //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(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(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(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(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() + (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)
  653. {
  654. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  655. parser.endLine(); // header
  656. parser.endLine();
  657. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++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)
  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)
  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)
  717. {
  718. creature->animDefName = config["graphics"]["animation"].String();
  719. //FIXME: MOD COMPATIBILITY
  720. if (config["abilities"].getType() == JsonNode::JsonType::DATA_STRUCT)
  721. {
  722. for(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)
  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() == true)
  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 = (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) //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; break;
  900. case 'D':
  901. b.type = Bonus::ADDITIONAL_ATTACK; break;
  902. case 'f':
  903. b.type = Bonus::FEARLESS; break;
  904. case 'F':
  905. b.type = Bonus::FLYING; break;
  906. case 'm':
  907. b.type = Bonus::SELF_MORALE; break;
  908. case 'M':
  909. b.type = Bonus::NO_MORALE; break;
  910. case 'p': //Mind spells
  911. case 'P':
  912. b.type = Bonus::MIND_IMMUNITY; break;
  913. case 'r':
  914. b.type = Bonus::REBIRTH; //on/off? makes sense?
  915. b.subtype = 0;
  916. b.val = 20; //arbitrary value
  917. break;
  918. case 'R':
  919. b.type = Bonus::BLOCKS_RETALIATION; break;
  920. case 's':
  921. b.type = Bonus::FREE_SHOOTING; break;
  922. case 'u':
  923. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  924. case 'U':
  925. b.type = Bonus::UNDEAD; break;
  926. default:
  927. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  928. return;
  929. break;
  930. }
  931. break;
  932. case 'w': //specific spell immunities, enabled/disabled
  933. enable = true;
  934. switch (mod[0])
  935. {
  936. case 'B': //Blind
  937. b.type = Bonus::SPELL_IMMUNITY;
  938. b.subtype = SpellID::BLIND;
  939. b.additionalInfo = 0;//normal immunity
  940. break;
  941. case 'H': //Hypnotize
  942. b.type = Bonus::SPELL_IMMUNITY;
  943. b.subtype = SpellID::HYPNOTIZE;
  944. b.additionalInfo = 0;//normal immunity
  945. break;
  946. case 'I': //Implosion
  947. b.type = Bonus::SPELL_IMMUNITY;
  948. b.subtype = SpellID::IMPLOSION;
  949. b.additionalInfo = 0;//normal immunity
  950. break;
  951. case 'K': //Berserk
  952. b.type = Bonus::SPELL_IMMUNITY;
  953. b.subtype = SpellID::BERSERK;
  954. b.additionalInfo = 0;//normal immunity
  955. break;
  956. case 'M': //Meteor Shower
  957. b.type = Bonus::SPELL_IMMUNITY;
  958. b.subtype = SpellID::METEOR_SHOWER;
  959. b.additionalInfo = 0;//normal immunity
  960. break;
  961. case 'N': //dispell beneficial spells
  962. b.type = Bonus::SPELL_IMMUNITY;
  963. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  964. b.additionalInfo = 0;//normal immunity
  965. break;
  966. case 'R': //Armageddon
  967. b.type = Bonus::SPELL_IMMUNITY;
  968. b.subtype = SpellID::ARMAGEDDON;
  969. b.additionalInfo = 0;//normal immunity
  970. break;
  971. case 'S': //Slow
  972. b.type = Bonus::SPELL_IMMUNITY;
  973. b.subtype = SpellID::SLOW;
  974. b.additionalInfo = 0;//normal immunity
  975. break;
  976. case '6':
  977. case '7':
  978. case '8':
  979. case '9':
  980. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  981. b.val = std::atoi(mod.c_str()) - 5;
  982. break;
  983. case ':':
  984. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  985. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  986. break;
  987. case 'F':
  988. b.type = Bonus::FIRE_IMMUNITY;
  989. b.subtype = 1; //not positive
  990. break;
  991. case 'O':
  992. b.type = Bonus::FIRE_IMMUNITY;
  993. b.subtype = 2; //only direct damage
  994. break;
  995. case 'f':
  996. b.type = Bonus::FIRE_IMMUNITY;
  997. b.subtype = 0; //all
  998. break;
  999. case 'C':
  1000. b.type = Bonus::WATER_IMMUNITY;
  1001. b.subtype = 1; //not positive
  1002. break;
  1003. case 'W':
  1004. b.type = Bonus::WATER_IMMUNITY;
  1005. b.subtype = 2; //only direct damage
  1006. break;
  1007. case 'w':
  1008. b.type = Bonus::WATER_IMMUNITY;
  1009. b.subtype = 0; //all
  1010. break;
  1011. case 'E':
  1012. b.type = Bonus::EARTH_IMMUNITY;
  1013. b.subtype = 2; //only direct damage
  1014. break;
  1015. case 'e':
  1016. b.type = Bonus::EARTH_IMMUNITY;
  1017. b.subtype = 0; //all
  1018. break;
  1019. case 'A':
  1020. b.type = Bonus::AIR_IMMUNITY;
  1021. b.subtype = 2; //only direct damage
  1022. break;
  1023. case 'a':
  1024. b.type = Bonus::AIR_IMMUNITY;
  1025. b.subtype = 0; //all
  1026. break;
  1027. case 'D':
  1028. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  1029. break;
  1030. case '0':
  1031. b.type = Bonus::RECEPTIVE;
  1032. break;
  1033. case 'm':
  1034. b.type = Bonus::MIND_IMMUNITY;
  1035. break;
  1036. default:
  1037. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1038. return;
  1039. }
  1040. break;
  1041. case 'i':
  1042. enable = true;
  1043. b.type = Bonus::NO_DISTANCE_PENALTY;
  1044. break;
  1045. case 'o':
  1046. enable = true;
  1047. b.type = Bonus::NO_WALL_PENALTY;
  1048. break;
  1049. case 'a':
  1050. case 'c':
  1051. case 'K':
  1052. case 'k':
  1053. b.type = Bonus::SPELL_AFTER_ATTACK;
  1054. b.subtype = stringToNumber(mod);
  1055. break;
  1056. case 'h':
  1057. b.type= Bonus::HATE;
  1058. b.subtype = stringToNumber(mod);
  1059. break;
  1060. case 'p':
  1061. case 'J':
  1062. b.type = Bonus::SPELL_BEFORE_ATTACK;
  1063. b.subtype = stringToNumber(mod);
  1064. b.additionalInfo = 3; //always expert?
  1065. break;
  1066. case 'r':
  1067. b.type = Bonus::HP_REGENERATION;
  1068. b.val = stringToNumber(mod);
  1069. break;
  1070. case 's':
  1071. b.type = Bonus::ENCHANTED;
  1072. b.subtype = stringToNumber(mod);
  1073. b.valType = Bonus::INDEPENDENT_MAX;
  1074. break;
  1075. default:
  1076. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1077. return;
  1078. break;
  1079. }
  1080. switch (mod[0])
  1081. {
  1082. case '+':
  1083. case '=': //should we allow percent values to stack or pick highest?
  1084. b.valType = Bonus::ADDITIVE_VALUE;
  1085. break;
  1086. }
  1087. //limiters, range
  1088. si32 lastVal, curVal, lastLev = 0;
  1089. if (enable) //0 and 2 means non-active, 1 - active
  1090. {
  1091. if (b.type != Bonus::REBIRTH)
  1092. b.val = 0; //on-off ability, no value specified
  1093. parser.readNumber(); // 0 level is never active
  1094. for (int i = 1; i < 11; ++i)
  1095. {
  1096. curVal = static_cast<si32>(parser.readNumber());
  1097. if (curVal == 1)
  1098. {
  1099. b.limiter.reset (new RankRangeLimiter(i));
  1100. bl.push_back(std::make_shared<Bonus>(b));
  1101. break; //never turned off it seems
  1102. }
  1103. }
  1104. }
  1105. else
  1106. {
  1107. lastVal = static_cast<si32>(parser.readNumber());
  1108. if (b.type == Bonus::HATE)
  1109. lastVal *= 10; //odd fix
  1110. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1111. for (int i = 1; i < 11; ++i)
  1112. {
  1113. curVal = static_cast<si32>(parser.readNumber());
  1114. if (b.type == Bonus::HATE)
  1115. curVal *= 10; //odd fix
  1116. if (curVal > lastVal) //threshold, add new bonus
  1117. {
  1118. b.val = curVal - lastVal;
  1119. lastVal = curVal;
  1120. b.limiter.reset (new RankRangeLimiter(i));
  1121. bl.push_back(std::make_shared<Bonus>(b));
  1122. lastLev = i; //start new range from here, i = previous rank
  1123. }
  1124. else if (curVal < lastVal)
  1125. {
  1126. b.val = lastVal;
  1127. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1128. }
  1129. }
  1130. }
  1131. }
  1132. int CCreatureHandler::stringToNumber(std::string & s)
  1133. {
  1134. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1135. return std::atoi(s.c_str());
  1136. }
  1137. CCreatureHandler::~CCreatureHandler()
  1138. {
  1139. for(auto & p : skillRequirements)
  1140. p.first = nullptr;
  1141. }
  1142. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1143. {
  1144. int r = 0;
  1145. if(tier == -1) //pick any allowed creature
  1146. {
  1147. do
  1148. {
  1149. r = (*RandomGeneratorUtil::nextItem(objects, rand))->idNumber;
  1150. } while (objects[r] && objects[r]->special); // find first "not special" creature
  1151. }
  1152. else
  1153. {
  1154. assert(vstd::iswithin(tier, 1, 7));
  1155. std::vector<CreatureID> allowed;
  1156. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  1157. {
  1158. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  1159. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  1160. if(crea && !crea->special)
  1161. allowed.push_back(crea->idNumber);
  1162. }
  1163. if(!allowed.size())
  1164. {
  1165. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1166. return CreatureID::NONE;
  1167. }
  1168. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1169. }
  1170. assert (r >= 0); //should always be, but it crashed
  1171. return CreatureID(r);
  1172. }
  1173. void CCreatureHandler::addBonusForTier(int tier, const std::shared_ptr<Bonus> & b)
  1174. {
  1175. assert(vstd::iswithin(tier, 1, 7));
  1176. creaturesOfLevel[tier].addNewBonus(b);
  1177. }
  1178. void CCreatureHandler::addBonusForAllCreatures(const std::shared_ptr<Bonus> & b)
  1179. {
  1180. const auto & exportedBonuses = allCreatures.getExportedBonusList();
  1181. for(const auto & bonus : exportedBonuses)
  1182. {
  1183. if(bonus->type == b->type && bonus->subtype == b->subtype)
  1184. return;
  1185. }
  1186. allCreatures.addNewBonus(b);
  1187. }
  1188. void CCreatureHandler::removeBonusesFromAllCreatures()
  1189. {
  1190. allCreatures.removeBonuses(Selector::all);
  1191. }
  1192. void CCreatureHandler::buildBonusTreeForTiers()
  1193. {
  1194. for(CCreature * c : objects)
  1195. {
  1196. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  1197. c->attachTo(creaturesOfLevel[c->level]);
  1198. else
  1199. c->attachTo(creaturesOfLevel[0]);
  1200. }
  1201. for(CBonusSystemNode &b : creaturesOfLevel)
  1202. b.attachTo(allCreatures);
  1203. }
  1204. void CCreatureHandler::afterLoadFinalization()
  1205. {
  1206. }
  1207. void CCreatureHandler::deserializationFix()
  1208. {
  1209. buildBonusTreeForTiers();
  1210. }
  1211. VCMI_LIB_NAMESPACE_END