CCreatureHandler.cpp 33 KB

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