CCreatureHandler.cpp 38 KB

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