CCreatureHandler.cpp 30 KB

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