CCreatureHandler.cpp 39 KB

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