CCreatureHandler.cpp 33 KB

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