CCreatureHandler.cpp 33 KB

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