CCreatureHandler.cpp 41 KB

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