CCreatureHandler.cpp 32 KB

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