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