CCreatureHandler.cpp 38 KB

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