CCreatureHandler.cpp 40 KB

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