CCreatureHandler.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. #include "StdInc.h"
  2. #include "CCreatureHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/CResourceLoader.h"
  5. #include "VCMI_Lib.h"
  6. #include "CGameState.h"
  7. #include "CTownHandler.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. using namespace boost::assign;
  11. /*
  12. * CCreatureHandler.cpp, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. int CCreature::getQuantityID(const int & quantity)
  21. {
  22. if (quantity<5)
  23. return 1;
  24. if (quantity<10)
  25. return 2;
  26. if (quantity<20)
  27. return 3;
  28. if (quantity<50)
  29. return 4;
  30. if (quantity<100)
  31. return 5;
  32. if (quantity<250)
  33. return 6;
  34. if (quantity<500)
  35. return 7;
  36. if (quantity<1000)
  37. return 8;
  38. return 9;
  39. }
  40. int CCreature::estimateCreatureCount(ui32 countID)
  41. {
  42. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  43. if (countID > 9)
  44. assert("Wrong countID!");
  45. return creature_count[countID];
  46. }
  47. bool CCreature::isDoubleWide() const
  48. {
  49. return doubleWide;
  50. }
  51. bool CCreature::isFlying() const
  52. {
  53. return hasBonusOfType(Bonus::FLYING);
  54. }
  55. bool CCreature::isShooting() const
  56. {
  57. return hasBonusOfType(Bonus::SHOOTER);
  58. }
  59. bool CCreature::isUndead() const
  60. {
  61. return hasBonusOfType(Bonus::UNDEAD);
  62. }
  63. /**
  64. * Determines if the creature is of a good alignment.
  65. * @return true if the creture is good, false otherwise.
  66. */
  67. bool CCreature::isGood () const
  68. {
  69. return VLC->townh->factions[faction]->alignment == EAlignment::GOOD;
  70. }
  71. /**
  72. * Determines if the creature is of an evil alignment.
  73. * @return true if the creature is evil, false otherwise.
  74. */
  75. bool CCreature::isEvil () const
  76. {
  77. return VLC->townh->factions[faction]->alignment == EAlignment::EVIL;
  78. }
  79. si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
  80. {
  81. int ret = 2147483645;
  82. int resAmnt = std::min(res.size(),cost.size());
  83. for(int i=0;i<resAmnt;i++)
  84. if(cost[i])
  85. ret = std::min(ret,(int)(res[i]/cost[i]));
  86. return ret;
  87. }
  88. CCreature::CCreature()
  89. {
  90. doubleWide = false;
  91. setNodeType(CBonusSystemNode::CREATURE);
  92. }
  93. void CCreature::addBonus(int val, Bonus::BonusType type, int subtype /*= -1*/)
  94. {
  95. Bonus *added = new Bonus(Bonus::PERMANENT, type, Bonus::CREATURE_ABILITY, val, idNumber, subtype, Bonus::BASE_NUMBER);
  96. addNewBonus(added);
  97. }
  98. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  99. {
  100. //TODO upgrade of upgrade?
  101. return vstd::contains(upgrades, anotherCre->idNumber);
  102. }
  103. bool CCreature::valid() const
  104. {
  105. return this == VLC->creh->creatures[idNumber];
  106. }
  107. std::string CCreature::nodeName() const
  108. {
  109. return "\"" + namePl + "\"";
  110. }
  111. bool CCreature::isItNativeTerrain(int terrain) const
  112. {
  113. return VLC->townh->factions[faction]->nativeTerrain == terrain;
  114. }
  115. static void AddAbility(CCreature *cre, const JsonVector &ability_vec)
  116. {
  117. Bonus *nsf = new Bonus();
  118. std::string type = ability_vec[0].String();
  119. auto it = bonusNameMap.find(type);
  120. if (it == bonusNameMap.end()) {
  121. if (type == "DOUBLE_WIDE")
  122. cre->doubleWide = true;
  123. else if (type == "ENEMY_MORALE_DECREASING") {
  124. cre->addBonus(-1, Bonus::MORALE);
  125. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  126. }
  127. else if (type == "ENEMY_LUCK_DECREASING") {
  128. cre->addBonus(-1, Bonus::LUCK);
  129. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  130. } else
  131. logGlobal->errorStream() << "Error: invalid ability type " << type << " in creatures config";
  132. return;
  133. }
  134. nsf->type = it->second;
  135. JsonUtils::parseTypedBonusShort(ability_vec,nsf);
  136. nsf->source = Bonus::CREATURE_ABILITY;
  137. nsf->sid = cre->idNumber;
  138. cre->addNewBonus(nsf);
  139. }
  140. CCreatureHandler::CCreatureHandler()
  141. {
  142. VLC->creh = this;
  143. allCreatures.setDescription("All creatures");
  144. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  145. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  146. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  147. loadCommanders();
  148. }
  149. void CCreatureHandler::loadCommanders()
  150. {
  151. JsonNode data(ResourceID("config/commanders.json"));
  152. data.setMeta("core"); // assume that commanders are in core mod (for proper bonuses resolution)
  153. const JsonNode & config = data; // switch to const data accessors
  154. BOOST_FOREACH (auto bonus, config["bonusPerLevel"].Vector())
  155. {
  156. commanderLevelPremy.push_back(JsonUtils::parseBonus (bonus.Vector()));
  157. }
  158. int i = 0;
  159. BOOST_FOREACH (auto skill, config["skillLevels"].Vector())
  160. {
  161. skillLevels.push_back (std::vector<ui8>());
  162. BOOST_FOREACH (auto skillLevel, skill["levels"].Vector())
  163. {
  164. skillLevels[i].push_back (skillLevel.Float());
  165. }
  166. ++i;
  167. }
  168. BOOST_FOREACH (auto ability, config["abilityRequirements"].Vector())
  169. {
  170. std::pair <Bonus, std::pair <ui8, ui8> > a;
  171. a.first = *JsonUtils::parseBonus (ability["ability"].Vector());
  172. a.second.first = ability["skills"].Vector()[0].Float();
  173. a.second.second = ability["skills"].Vector()[1].Float();
  174. skillRequirements.push_back (a);
  175. }
  176. }
  177. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses)
  178. {
  179. auto makeBonusNode = [&](std::string type) -> JsonNode
  180. {
  181. JsonNode ret;
  182. ret["type"].String() = type;
  183. return ret;
  184. };
  185. static const std::map<std::string, JsonNode> abilityMap =
  186. boost::assign::map_list_of
  187. ("FLYING_ARMY", makeBonusNode("FLYING"))
  188. ("SHOOTING_ARMY", makeBonusNode("SHOOTER"))
  189. ("SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON"))
  190. ("const_free_attack", makeBonusNode("BLOCKS_RETALIATION"))
  191. ("IS_UNDEAD", makeBonusNode("UNDEAD"))
  192. ("const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY"))
  193. ("const_jousting", makeBonusNode("JOUSTING"))
  194. ("KING_1", makeBonusNode("KING1"))
  195. ("KING_2", makeBonusNode("KING2"))
  196. ("KING_3", makeBonusNode("KING3"))
  197. ("const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY"))
  198. ("CATAPULT", makeBonusNode("CATAPULT"))
  199. ("MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT"))
  200. ("IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY"))
  201. ("HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH"));
  202. auto hasAbility = [&](const std::string name) -> bool
  203. {
  204. return boost::algorithm::find_first(bonuses, name);
  205. };
  206. BOOST_FOREACH(auto a, abilityMap)
  207. {
  208. if(hasAbility(a.first))
  209. creature["abilities"][a.first] = a.second;
  210. }
  211. if(hasAbility("DOUBLE_WIDE"))
  212. creature["doubleWide"].Bool() = true;
  213. if(hasAbility("const_raises_morale"))
  214. {
  215. JsonNode node = makeBonusNode("MORALE");
  216. node["val"].Float() = 1;
  217. node["propagator"].String() = "HERO";
  218. creature["abilities"]["const_raises_morale"] = node;
  219. }
  220. if(hasAbility("const_lowers_morale"))
  221. {
  222. JsonNode node = makeBonusNode("MORALE");
  223. node["val"].Float() = 1;
  224. node["effectRange"].String() = "ONLY_ENEMY_ARMY";
  225. creature["abilities"]["const_lowers_morale"] = node;
  226. }
  227. }
  228. std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
  229. {
  230. creatures.resize(dataSize);
  231. std::vector<JsonNode> h3Data;
  232. h3Data.reserve(dataSize);
  233. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  234. parser.endLine(); // header
  235. parser.endLine();
  236. for (size_t i=0; i<dataSize; i++)
  237. {
  238. //loop till non-empty line
  239. while (parser.isNextEntryEmpty())
  240. parser.endLine();
  241. JsonNode data;
  242. data["name"]["singular"].String() = parser.readString();
  243. data["name"]["plural"].String() = parser.readString();
  244. for(int v=0; v<7; ++v)
  245. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  246. data["fightValue"].Float() = parser.readNumber();
  247. data["aiValue"].Float() = parser.readNumber();
  248. data["growth"].Float() = parser.readNumber();
  249. data["horde"].Float() = parser.readNumber();
  250. data["hitPoints"].Float() = parser.readNumber();
  251. data["speed"].Float() = parser.readNumber();
  252. data["attack"].Float() = parser.readNumber();
  253. data["defense"].Float() = parser.readNumber();
  254. data["damage"]["min"].Float() = parser.readNumber();
  255. data["damage"]["max"].Float() = parser.readNumber();
  256. if (float shots = parser.readNumber())
  257. data["shots"].Float() = shots;
  258. if (float spells = parser.readNumber())
  259. data["spellPoints"].Float() = spells;
  260. data["advMapAmount"]["min"].Float() = parser.readNumber();
  261. data["advMapAmount"]["max"].Float() = parser.readNumber();
  262. data["abilityText"].String() = parser.readString();
  263. loadBonuses(data, parser.readString()); //Attributes
  264. h3Data.push_back(data);
  265. }
  266. loadAnimationInfo(h3Data);
  267. return h3Data;
  268. }
  269. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  270. {
  271. auto object = loadFromJson(data);
  272. object->idNumber = CreatureID(creatures.size());
  273. object->iconIndex = object->idNumber + 2;
  274. creatures.push_back(object);
  275. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  276. BOOST_FOREACH(auto node, data["extraNames"].Vector())
  277. {
  278. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  279. }
  280. }
  281. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  282. {
  283. auto object = loadFromJson(data);
  284. object->idNumber = CreatureID(index);
  285. object->iconIndex = object->idNumber + 2;
  286. if(data["hasDoubleWeek"].Bool()) //
  287. {
  288. doubledCreatures.insert (object->idNumber); //we need to have id (or identifier) before it is inserted
  289. }
  290. assert(creatures[index] == nullptr); // ensure that this id was not loaded before
  291. creatures[index] = object;
  292. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  293. BOOST_FOREACH(auto node, data["extraNames"].Vector())
  294. {
  295. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  296. }
  297. }
  298. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  299. {
  300. std::vector<bool> ret;
  301. BOOST_FOREACH(const CCreature * crea, creatures)
  302. {
  303. ret.push_back(crea ? !crea->special : false);
  304. }
  305. return ret;
  306. }
  307. void CCreatureHandler::loadCrExpBon()
  308. {
  309. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  310. {
  311. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  312. Bonus b; //prototype with some default properties
  313. b.source = Bonus::STACK_EXPERIENCE;
  314. b.duration = Bonus::PERMANENT;
  315. b.valType = Bonus::ADDITIVE_VALUE;
  316. b.effectRange = Bonus::NO_LIMIT;
  317. b.additionalInfo = 0;
  318. b.turnsRemain = 0;
  319. BonusList bl;
  320. parser.endLine();
  321. parser.readString(); //ignore index
  322. loadStackExp(b, bl, parser);
  323. BOOST_FOREACH(Bonus * b, bl)
  324. addBonusForAllCreatures(b); //health bonus is common for all
  325. parser.endLine();
  326. for (int i = 1; i < 7; ++i)
  327. {
  328. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  329. {
  330. parser.readString(); //ignore index
  331. bl.clear();
  332. loadStackExp(b, bl, parser);
  333. BOOST_FOREACH(Bonus * b, bl)
  334. addBonusForTier(i, b);
  335. parser.endLine();
  336. }
  337. }
  338. for (int j = 0; j < 4; ++j) //tier 7
  339. {
  340. parser.readString(); //ignore index
  341. bl.clear();
  342. loadStackExp(b, bl, parser);
  343. BOOST_FOREACH(Bonus * b, bl)
  344. {
  345. addBonusForTier(7, b);
  346. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  347. }
  348. parser.endLine();
  349. }
  350. do //parse everything that's left
  351. {
  352. b.sid = parser.readNumber(); //id = this particular creature ID
  353. loadStackExp(b, creatures[b.sid]->getBonusList(), parser); //add directly to CCreature Node
  354. }
  355. while (parser.endLine());
  356. //Calculate rank exp values, formula appears complicated bu no parsing needed
  357. expRanks.resize(8);
  358. int dif = 0;
  359. int it = 8000; //ignore name of this variable
  360. expRanks[0].push_back(it);
  361. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  362. {
  363. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  364. dif += it/5;
  365. }
  366. for (int i = 1; i < 8; ++i)
  367. {
  368. dif = 0;
  369. it = 1000 * i;
  370. expRanks[i].push_back(it);
  371. for (int j = 1; j < 10; ++j)
  372. {
  373. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  374. dif += it/5;
  375. }
  376. }
  377. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  378. expBonParser.endLine(); //header
  379. maxExpPerBattle.resize(8);
  380. for (int i = 1; i < 8; ++i)
  381. {
  382. expBonParser.readString(); //index
  383. expBonParser.readString(); //float multiplier -> hardcoded
  384. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  385. expBonParser.readString(); //already calculated
  386. maxExpPerBattle[i] = expBonParser.readNumber();
  387. expRanks[i].push_back(expRanks[i].back() + expBonParser.readNumber());
  388. expBonParser.endLine();
  389. }
  390. //skeleton gets exp penalty
  391. creatures[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  392. creatures[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  393. //exp for tier >7, rank 11
  394. expRanks[0].push_back(147000);
  395. expAfterUpgrade = 75; //percent
  396. maxExpPerBattle[0] = maxExpPerBattle[7];
  397. }//end of Stack Experience
  398. }
  399. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  400. {
  401. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  402. parser.endLine(); // header
  403. parser.endLine();
  404. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++dd)
  405. {
  406. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  407. ;
  408. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  409. parser.endLine();
  410. }
  411. }
  412. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  413. {
  414. graphics["map"].String(); //create empty string. Real value will be loaded from H3 txt's
  415. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  416. JsonNode & animationTime = graphics["animationTime"];
  417. animationTime["walk"].Float() = parser.readNumber();
  418. animationTime["attack"].Float() = parser.readNumber();
  419. animationTime["flight"].Float() = parser.readNumber();
  420. JsonNode & missile = graphics["missile"];
  421. JsonNode & offsets = missile["offset"];
  422. offsets["upperX"].Float() = parser.readNumber();
  423. offsets["upperY"].Float() = parser.readNumber();
  424. offsets["middleX"].Float() = parser.readNumber();
  425. offsets["middleY"].Float() = parser.readNumber();
  426. offsets["lowerX"].Float() = parser.readNumber();
  427. offsets["lowerY"].Float() = parser.readNumber();
  428. for(int i=0; i<12; i++)
  429. {
  430. JsonNode entry;
  431. entry.Float() = parser.readNumber();
  432. missile["frameAngles"].Vector().push_back(entry);
  433. }
  434. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  435. missile["attackClimaxFrame"].Float() = parser.readNumber();
  436. // assume that creature is not a shooter and should not have whole missile field
  437. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  438. missile["attackClimaxFrame"].Float() == 0)
  439. graphics.Struct().erase("missile");
  440. }
  441. CCreature * CCreatureHandler::loadFromJson(const JsonNode & node)
  442. {
  443. CCreature * cre = new CCreature();
  444. const JsonNode & name = node["name"];
  445. cre->nameSing = name["singular"].String();
  446. cre->namePl = name["plural"].String();
  447. cre->cost = Res::ResourceSet(node["cost"]);
  448. cre->fightValue = node["fightValue"].Float();
  449. cre->AIValue = node["aiValue"].Float();
  450. cre->growth = node["growth"].Float();
  451. cre->hordeGrowth = node["horde"].Float(); // Needed at least until configurable buildings
  452. cre->addBonus(node["hitPoints"].Float(), Bonus::STACK_HEALTH);
  453. cre->addBonus(node["speed"].Float(), Bonus::STACKS_SPEED);
  454. cre->addBonus(node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  455. cre->addBonus(node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  456. cre->addBonus(node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
  457. cre->addBonus(node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
  458. cre->ammMin = node["advMapAmount"]["min"].Float();
  459. cre->ammMax = node["advMapAmount"]["max"].Float();
  460. assert(cre->ammMin <= cre->ammMax);
  461. if (!node["shots"].isNull())
  462. cre->addBonus(node["shots"].Float(), Bonus::SHOTS);
  463. if (node["spellPoints"].isNull())
  464. cre->addBonus(node["spellPoints"].Float(), Bonus::CASTS);
  465. cre->doubleWide = node["doubleWide"].Bool();
  466. loadStackExperience(cre, node["stackExperience"]);
  467. loadJsonAnimation(cre, node["graphics"]);
  468. loadCreatureJson(cre, node);
  469. return cre;
  470. }
  471. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  472. {
  473. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  474. cre->animation.troopCountLocationOffset = graphics["troopCountLocationOffset"].Float();
  475. const JsonNode & animationTime = graphics["animationTime"];
  476. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  477. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  478. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  479. const JsonNode & missile = graphics["missile"];
  480. const JsonNode & offsets = missile["offset"];
  481. cre->animation.upperRightMissleOffsetX = offsets["upperX"].Float();
  482. cre->animation.upperRightMissleOffsetY = offsets["upperY"].Float();
  483. cre->animation.rightMissleOffsetX = offsets["middleX"].Float();
  484. cre->animation.rightMissleOffsetY = offsets["middleY"].Float();
  485. cre->animation.lowerRightMissleOffsetX = offsets["lowerX"].Float();
  486. cre->animation.lowerRightMissleOffsetY = offsets["lowerY"].Float();
  487. cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float();
  488. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  489. cre->advMapDef = graphics["map"].String();
  490. cre->smallIconName = graphics["iconSmall"].String();
  491. cre->largeIconName = graphics["iconLarge"].String();
  492. }
  493. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  494. {
  495. creature->level = config["level"].Float();
  496. creature->animDefName = config["graphics"]["animation"].String();
  497. if (config["abilities"].getType() == JsonNode::DATA_STRUCT)
  498. {
  499. BOOST_FOREACH(auto &ability, config["abilities"].Struct())
  500. {
  501. if (!ability.second.isNull())
  502. {
  503. auto b = JsonUtils::parseBonus(ability.second);
  504. b->source = Bonus::CREATURE_ABILITY;
  505. b->duration = Bonus::PERMANENT;
  506. creature->addNewBonus(b);
  507. }
  508. }
  509. }
  510. else
  511. {
  512. BOOST_FOREACH(const JsonNode &ability, config["abilities"].Vector())
  513. {
  514. if (ability.getType() == JsonNode::DATA_VECTOR)
  515. {
  516. assert(0); // should be unused now
  517. AddAbility(creature, ability.Vector()); // used only for H3 creatures
  518. }
  519. else
  520. {
  521. auto b = JsonUtils::parseBonus(ability);
  522. b->source = Bonus::CREATURE_ABILITY;
  523. b->duration = Bonus::PERMANENT;
  524. creature->addNewBonus(b);
  525. }
  526. }
  527. }
  528. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  529. {
  530. creature->faction = faction;
  531. });
  532. BOOST_FOREACH(const JsonNode &value, config["upgrades"].Vector())
  533. {
  534. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  535. {
  536. creature->upgrades.insert(CreatureID(identifier));
  537. });
  538. }
  539. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  540. creature->special = config["special"].Bool() || config["disabled"].Bool();
  541. const JsonNode & sounds = config["sound"];
  542. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  543. GET_SOUND_VALUE(attack);
  544. GET_SOUND_VALUE(defend);
  545. GET_SOUND_VALUE(killed);
  546. GET_SOUND_VALUE(move);
  547. GET_SOUND_VALUE(shoot);
  548. GET_SOUND_VALUE(wince);
  549. GET_SOUND_VALUE(startMoving);
  550. GET_SOUND_VALUE(endMoving);
  551. #undef GET_SOUND_VALUE
  552. }
  553. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  554. {
  555. BOOST_FOREACH (const JsonNode &exp, input.Vector())
  556. {
  557. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  558. bonus->source = Bonus::STACK_EXPERIENCE;
  559. bonus->duration = Bonus::PERMANENT;
  560. const JsonVector &values = exp["values"].Vector();
  561. int lowerLimit = 1;//, upperLimit = 255;
  562. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  563. {
  564. BOOST_FOREACH (const JsonNode &val, values)
  565. {
  566. if (val.Bool() == true)
  567. {
  568. bonus->limiter = make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  569. creature->addNewBonus (new Bonus(*bonus)); //bonuses must be unique objects
  570. break; //TODO: allow bonuses to turn off?
  571. }
  572. ++lowerLimit;
  573. }
  574. }
  575. else
  576. {
  577. int lastVal = 0;
  578. BOOST_FOREACH (const JsonNode &val, values)
  579. {
  580. if (val.Float() != lastVal)
  581. {
  582. bonus->val = val.Float() - lastVal;
  583. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  584. creature->addNewBonus (new Bonus(*bonus));
  585. }
  586. lastVal = val.Float();
  587. ++lowerLimit;
  588. }
  589. }
  590. delete bonus;
  591. }
  592. }
  593. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  594. {
  595. bool enable = false; //some bonuses are activated with values 2 or 1
  596. std::string buf = parser.readString();
  597. std::string mod = parser.readString();
  598. switch (buf[0])
  599. {
  600. case 'H':
  601. b.type = Bonus::STACK_HEALTH;
  602. b.valType = Bonus::PERCENT_TO_BASE;
  603. break;
  604. case 'A':
  605. b.type = Bonus::PRIMARY_SKILL;
  606. b.subtype = PrimarySkill::ATTACK;
  607. break;
  608. case 'D':
  609. b.type = Bonus::PRIMARY_SKILL;
  610. b.subtype = PrimarySkill::DEFENSE;
  611. break;
  612. case 'M': //Max damage
  613. b.type = Bonus::CREATURE_DAMAGE;
  614. b.subtype = 2;
  615. break;
  616. case 'm': //Min damage
  617. b.type = Bonus::CREATURE_DAMAGE;
  618. b.subtype = 1;
  619. break;
  620. case 'S':
  621. b.type = Bonus::STACKS_SPEED; break;
  622. case 'O':
  623. b.type = Bonus::SHOTS; break;
  624. case 'b':
  625. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  626. case 'C':
  627. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  628. case 'd':
  629. b.type = Bonus::DEFENSIVE_STANCE; break;
  630. case 'e':
  631. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  632. b.subtype = 0;
  633. break;
  634. case 'E':
  635. b.type = Bonus::DEATH_STARE;
  636. b.subtype = 0; //Gorgon
  637. break;
  638. case 'F':
  639. b.type = Bonus::FEAR; break;
  640. case 'g':
  641. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  642. b.subtype = -1; //all magic schools
  643. break;
  644. case 'P':
  645. b.type = Bonus::CASTS; break;
  646. case 'R':
  647. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  648. case 'W':
  649. b.type = Bonus::MAGIC_RESISTANCE;
  650. b.subtype = 0; //otherwise creature window goes crazy
  651. break;
  652. case 'f': //on-off skill
  653. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  654. switch (mod[0])
  655. {
  656. case 'A':
  657. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  658. case 'b':
  659. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  660. case 'B':
  661. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  662. case 'c':
  663. b.type = Bonus::JOUSTING; break;
  664. case 'D':
  665. b.type = Bonus::ADDITIONAL_ATTACK; break;
  666. case 'f':
  667. b.type = Bonus::FEARLESS; break;
  668. case 'F':
  669. b.type = Bonus::FLYING; break;
  670. case 'm':
  671. b.type = Bonus::SELF_MORALE; break;
  672. case 'M':
  673. b.type = Bonus::NO_MORALE; break;
  674. case 'p': //Mind spells
  675. case 'P':
  676. b.type = Bonus::MIND_IMMUNITY; break;
  677. case 'r':
  678. b.type = Bonus::REBIRTH; //on/off? makes sense?
  679. b.subtype = 0;
  680. b.val = 20; //arbitrary value
  681. break;
  682. case 'R':
  683. b.type = Bonus::BLOCKS_RETALIATION; break;
  684. case 's':
  685. b.type = Bonus::FREE_SHOOTING; break;
  686. case 'u':
  687. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  688. case 'U':
  689. b.type = Bonus::UNDEAD; break;
  690. default:
  691. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  692. return;
  693. break;
  694. }
  695. break;
  696. case 'w': //specific spell immunities, enabled/disabled
  697. enable = true;
  698. switch (mod[0])
  699. {
  700. case 'B': //Blind
  701. b.type = Bonus::SPELL_IMMUNITY;
  702. b.subtype = SpellID::BLIND;
  703. break;
  704. case 'H': //Hypnotize
  705. b.type = Bonus::SPELL_IMMUNITY;
  706. b.subtype = SpellID::HYPNOTIZE;
  707. break;
  708. case 'I': //Implosion
  709. b.type = Bonus::SPELL_IMMUNITY;
  710. b.subtype = SpellID::IMPLOSION;
  711. break;
  712. case 'K': //Berserk
  713. b.type = Bonus::SPELL_IMMUNITY;
  714. b.subtype = SpellID::BERSERK;
  715. break;
  716. case 'M': //Meteor Shower
  717. b.type = Bonus::SPELL_IMMUNITY;
  718. b.subtype = SpellID::METEOR_SHOWER;
  719. break;
  720. case 'N': //dispell beneficial spells
  721. b.type = Bonus::SPELL_IMMUNITY;
  722. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  723. break;
  724. case 'R': //Armageddon
  725. b.type = Bonus::SPELL_IMMUNITY;
  726. b.subtype = SpellID::ARMAGEDDON;
  727. break;
  728. case 'S': //Slow
  729. b.type = Bonus::SPELL_IMMUNITY;
  730. b.subtype = SpellID::SLOW;
  731. break;
  732. case '6':
  733. case '7':
  734. case '8':
  735. case '9':
  736. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  737. b.val = std::atoi(mod.c_str()) - 5;
  738. break;
  739. case ':':
  740. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  741. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  742. break;
  743. case 'F':
  744. b.type = Bonus::FIRE_IMMUNITY;
  745. b.subtype = 1; //not positive
  746. break;
  747. case 'O':
  748. b.type = Bonus::FIRE_IMMUNITY;
  749. b.subtype = 2; //only direct damage
  750. break;
  751. case 'f':
  752. b.type = Bonus::FIRE_IMMUNITY;
  753. b.subtype = 0; //all
  754. break;
  755. case 'C':
  756. b.type = Bonus::WATER_IMMUNITY;
  757. b.subtype = 1; //not positive
  758. break;
  759. case 'W':
  760. b.type = Bonus::WATER_IMMUNITY;
  761. b.subtype = 2; //only direct damage
  762. break;
  763. case 'w':
  764. b.type = Bonus::WATER_IMMUNITY;
  765. b.subtype = 0; //all
  766. break;
  767. case 'E':
  768. b.type = Bonus::EARTH_IMMUNITY;
  769. b.subtype = 2; //only direct damage
  770. break;
  771. case 'e':
  772. b.type = Bonus::EARTH_IMMUNITY;
  773. b.subtype = 0; //all
  774. break;
  775. case 'A':
  776. b.type = Bonus::AIR_IMMUNITY;
  777. b.subtype = 2; //only direct damage
  778. break;
  779. case 'a':
  780. b.type = Bonus::AIR_IMMUNITY;
  781. b.subtype = 0; //all
  782. break;
  783. case 'D':
  784. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  785. break;
  786. case '0':
  787. b.type = Bonus::RECEPTIVE;
  788. break;
  789. case 'm':
  790. b.type = Bonus::MIND_IMMUNITY;
  791. break;
  792. default:
  793. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  794. return;
  795. }
  796. break;
  797. case 'i':
  798. enable = true;
  799. b.type = Bonus::NO_DISTANCE_PENALTY;
  800. break;
  801. case 'o':
  802. enable = true;
  803. b.type = Bonus::NO_WALL_PENALTY;
  804. break;
  805. case 'a':
  806. case 'c':
  807. case 'K':
  808. case 'k':
  809. b.type = Bonus::SPELL_AFTER_ATTACK;
  810. b.subtype = stringToNumber(mod);
  811. break;
  812. case 'h':
  813. b.type= Bonus::HATE;
  814. b.subtype = stringToNumber(mod);
  815. break;
  816. case 'p':
  817. case 'J':
  818. b.type = Bonus::SPELL_BEFORE_ATTACK;
  819. b.subtype = stringToNumber(mod);
  820. b.additionalInfo = 3; //always expert?
  821. break;
  822. case 'r':
  823. b.type = Bonus::HP_REGENERATION;
  824. b.val = stringToNumber(mod);
  825. break;
  826. case 's':
  827. b.type = Bonus::ENCHANTED;
  828. b.subtype = stringToNumber(mod);
  829. b.valType = Bonus::INDEPENDENT_MAX;
  830. break;
  831. default:
  832. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  833. return;
  834. break;
  835. }
  836. switch (mod[0])
  837. {
  838. case '+':
  839. case '=': //should we allow percent values to stack or pick highest?
  840. b.valType = Bonus::ADDITIVE_VALUE;
  841. break;
  842. }
  843. //limiters, range
  844. si32 lastVal, curVal, lastLev = 0;
  845. if (enable) //0 and 2 means non-active, 1 - active
  846. {
  847. if (b.type != Bonus::REBIRTH)
  848. b.val = 0; //on-off ability, no value specified
  849. curVal = parser.readNumber();// 0 level is never active
  850. for (int i = 1; i < 11; ++i)
  851. {
  852. curVal = parser.readNumber();
  853. if (curVal == 1)
  854. {
  855. b.limiter.reset (new RankRangeLimiter(i));
  856. bl.push_back(new Bonus(b));
  857. break; //never turned off it seems
  858. }
  859. }
  860. }
  861. else
  862. {
  863. lastVal = parser.readNumber(); //basic value, not particularly useful but existent
  864. for (int i = 1; i < 11; ++i)
  865. {
  866. curVal = parser.readNumber();
  867. if (b.type == Bonus::HATE)
  868. curVal *= 10; //odd fix
  869. if (curVal > lastVal) //threshold, add new bonus
  870. {
  871. b.val = curVal - lastVal;
  872. lastVal = curVal;
  873. b.limiter.reset (new RankRangeLimiter(i));
  874. bl.push_back(new Bonus(b));
  875. lastLev = i; //start new range from here, i = previous rank
  876. }
  877. else if (curVal < lastVal)
  878. {
  879. b.val = lastVal;
  880. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  881. }
  882. }
  883. }
  884. }
  885. int CCreatureHandler::stringToNumber(std::string & s)
  886. {
  887. boost::algorithm::replace_first(s,"#",""); //drop hash character
  888. return std::atoi(s.c_str());
  889. }
  890. CCreatureHandler::~CCreatureHandler()
  891. {
  892. BOOST_FOREACH(auto & creature, creatures)
  893. creature.dellNull();
  894. }
  895. CreatureID CCreatureHandler::pickRandomMonster(const boost::function<int()> &randGen, int tier) const
  896. {
  897. int r = 0;
  898. if(tier == -1) //pick any allowed creature
  899. {
  900. do
  901. {
  902. r = vstd::pickRandomElementOf(creatures, randGen)->idNumber;
  903. } while (VLC->creh->creatures[r] && VLC->creh->creatures[r]->special); // find first "not special" creature
  904. }
  905. else
  906. {
  907. assert(vstd::iswithin(tier, 1, 7));
  908. std::vector<CreatureID> allowed;
  909. BOOST_FOREACH(const CBonusSystemNode *b, creaturesOfLevel[tier].getChildrenNodes())
  910. {
  911. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  912. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  913. if(crea && !crea->special)
  914. allowed.push_back(crea->idNumber);
  915. }
  916. if(!allowed.size())
  917. {
  918. logGlobal->warnStream() << "Cannot pick a random creature of tier " << tier << "!";
  919. return CreatureID::NONE;
  920. }
  921. return vstd::pickRandomElementOf(allowed, randGen);
  922. }
  923. assert (r >= 0); //should always be, but it crashed
  924. return CreatureID(r);
  925. }
  926. void CCreatureHandler::addBonusForTier(int tier, Bonus *b)
  927. {
  928. assert(vstd::iswithin(tier, 1, 7));
  929. creaturesOfLevel[tier].addNewBonus(b);
  930. }
  931. void CCreatureHandler::addBonusForAllCreatures(Bonus *b)
  932. {
  933. allCreatures.addNewBonus(b);
  934. }
  935. void CCreatureHandler::buildBonusTreeForTiers()
  936. {
  937. BOOST_FOREACH(CCreature *c, creatures)
  938. {
  939. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  940. c->attachTo(&creaturesOfLevel[c->level]);
  941. else
  942. c->attachTo(&creaturesOfLevel[0]);
  943. }
  944. BOOST_FOREACH(CBonusSystemNode &b, creaturesOfLevel)
  945. b.attachTo(&allCreatures);
  946. }
  947. void CCreatureHandler::deserializationFix()
  948. {
  949. buildBonusTreeForTiers();
  950. }