CCreatureHandler.cpp 30 KB

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