CCreatureHandler.cpp 40 KB

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