CCreatureHandler.cpp 40 KB

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