CCreatureHandler.cpp 39 KB

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