CCreatureHandler.cpp 40 KB

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