CCreatureHandler.cpp 40 KB

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