CCreatureHandler.cpp 40 KB

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