CommonConstructors.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /*
  2. * CommonConstructors.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CommonConstructors.h"
  12. #include "CGTownInstance.h"
  13. #include "CGHeroInstance.h"
  14. #include "CBank.h"
  15. #include "../mapping/CMap.h"
  16. #include "../CHeroHandler.h"
  17. #include "../CCreatureHandler.h"
  18. #include "JsonRandom.h"
  19. #include "../CModHandler.h"
  20. #include "../IGameCallback.h"
  21. CObstacleConstructor::CObstacleConstructor()
  22. {
  23. }
  24. bool CObstacleConstructor::isStaticObject()
  25. {
  26. return true;
  27. }
  28. CTownInstanceConstructor::CTownInstanceConstructor():
  29. faction(nullptr)
  30. {
  31. }
  32. void CTownInstanceConstructor::initTypeData(const JsonNode & input)
  33. {
  34. VLC->modh->identifiers.requestIdentifier("faction", input["faction"], [&](si32 index)
  35. {
  36. faction = VLC->townh->factions[index];
  37. });
  38. filtersJson = input["filters"];
  39. }
  40. void CTownInstanceConstructor::afterLoadFinalization()
  41. {
  42. assert(faction);
  43. for (auto entry : filtersJson.Struct())
  44. {
  45. filters[entry.first] = LogicalExpression<BuildingID>(entry.second, [this](const JsonNode & node)
  46. {
  47. return BuildingID(VLC->modh->identifiers.getIdentifier("building." + faction->identifier, node.Vector()[0]).get());
  48. });
  49. }
  50. }
  51. bool CTownInstanceConstructor::objectFilter(const CGObjectInstance * object, const ObjectTemplate & templ) const
  52. {
  53. auto town = dynamic_cast<const CGTownInstance *>(object);
  54. auto buildTest = [&](const BuildingID & id)
  55. {
  56. return town->hasBuilt(id);
  57. };
  58. if (filters.count(templ.stringID))
  59. return filters.at(templ.stringID).test(buildTest);
  60. return false;
  61. }
  62. CGObjectInstance * CTownInstanceConstructor::create(const ObjectTemplate & tmpl) const
  63. {
  64. CGTownInstance * obj = createTyped(tmpl);
  65. obj->town = faction->town;
  66. obj->tempOwner = PlayerColor::NEUTRAL;
  67. return obj;
  68. }
  69. void CTownInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
  70. {
  71. auto templ = getOverride(object->cb->getTile(object->pos)->terType, object);
  72. if (templ)
  73. object->appearance = templ.get();
  74. }
  75. CHeroInstanceConstructor::CHeroInstanceConstructor()
  76. :heroClass(nullptr)
  77. {
  78. }
  79. void CHeroInstanceConstructor::initTypeData(const JsonNode & input)
  80. {
  81. VLC->modh->identifiers.requestIdentifier("heroClass", input["heroClass"],
  82. [&](si32 index) { heroClass = VLC->heroh->classes.heroClasses[index]; });
  83. filtersJson = input["filters"];
  84. }
  85. void CHeroInstanceConstructor::afterLoadFinalization()
  86. {
  87. for (auto entry : filtersJson.Struct())
  88. {
  89. filters[entry.first] = LogicalExpression<HeroTypeID>(entry.second, [this](const JsonNode & node)
  90. {
  91. return HeroTypeID(VLC->modh->identifiers.getIdentifier("hero", node.Vector()[0]).get());
  92. });
  93. }
  94. }
  95. bool CHeroInstanceConstructor::objectFilter(const CGObjectInstance * object, const ObjectTemplate & templ) const
  96. {
  97. auto hero = dynamic_cast<const CGHeroInstance *>(object);
  98. auto heroTest = [&](const HeroTypeID & id)
  99. {
  100. return hero->type->ID == id;
  101. };
  102. if (filters.count(templ.stringID))
  103. {
  104. return filters.at(templ.stringID).test(heroTest);
  105. }
  106. return false;
  107. }
  108. CGObjectInstance * CHeroInstanceConstructor::create(const ObjectTemplate & tmpl) const
  109. {
  110. CGHeroInstance * obj = createTyped(tmpl);
  111. obj->type = nullptr; //FIXME: set to valid value. somehow.
  112. return obj;
  113. }
  114. void CHeroInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
  115. {
  116. }
  117. CDwellingInstanceConstructor::CDwellingInstanceConstructor()
  118. {
  119. }
  120. void CDwellingInstanceConstructor::initTypeData(const JsonNode & input)
  121. {
  122. const JsonVector & levels = input["creatures"].Vector();
  123. availableCreatures.resize(levels.size());
  124. for (size_t i=0; i<levels.size(); i++)
  125. {
  126. const JsonVector & creatures = levels[i].Vector();
  127. availableCreatures[i].resize(creatures.size());
  128. for (size_t j=0; j<creatures.size(); j++)
  129. {
  130. VLC->modh->identifiers.requestIdentifier("creature", creatures[j], [=] (si32 index)
  131. {
  132. availableCreatures[i][j] = VLC->creh->creatures[index];
  133. });
  134. }
  135. assert(!availableCreatures[i].empty());
  136. }
  137. guards = input["guards"];
  138. }
  139. bool CDwellingInstanceConstructor::objectFilter(const CGObjectInstance *, const ObjectTemplate &) const
  140. {
  141. return false;
  142. }
  143. CGObjectInstance * CDwellingInstanceConstructor::create(const ObjectTemplate & tmpl) const
  144. {
  145. CGDwelling * obj = createTyped(tmpl);
  146. obj->creatures.resize(availableCreatures.size());
  147. for (auto & entry : availableCreatures)
  148. {
  149. for (const CCreature * cre : entry)
  150. obj->creatures.back().second.push_back(cre->idNumber);
  151. }
  152. return obj;
  153. }
  154. void CDwellingInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator &rng) const
  155. {
  156. CGDwelling * dwelling = dynamic_cast<CGDwelling*>(object);
  157. dwelling->creatures.clear();
  158. dwelling->creatures.reserve(availableCreatures.size());
  159. for (auto & entry : availableCreatures)
  160. {
  161. dwelling->creatures.resize(dwelling->creatures.size() + 1);
  162. for (const CCreature * cre : entry)
  163. dwelling->creatures.back().second.push_back(cre->idNumber);
  164. }
  165. bool guarded = false; //TODO: serialize for sanity
  166. if (guards.getType() == JsonNode::DATA_BOOL) //simple switch
  167. {
  168. if (guards.Bool())
  169. {
  170. guarded = true;
  171. }
  172. }
  173. else if (guards.getType() == JsonNode::DATA_VECTOR) //custom guards (eg. Elemental Conflux)
  174. {
  175. for (auto & stack : JsonRandom::loadCreatures(guards, rng))
  176. {
  177. dwelling->putStack(SlotID(dwelling->stacksCount()), new CStackInstance(stack.type->idNumber, stack.count));
  178. }
  179. }
  180. else //default condition - creatures are of level 5 or higher
  181. {
  182. for (auto creatureEntry : availableCreatures)
  183. {
  184. if (creatureEntry.at(0)->level >= 5)
  185. {
  186. guarded = true;
  187. break;
  188. }
  189. }
  190. }
  191. if (guarded)
  192. {
  193. for (auto creatureEntry : availableCreatures)
  194. {
  195. const CCreature * crea = creatureEntry.at(0);
  196. dwelling->putStack (SlotID(dwelling->stacksCount()), new CStackInstance(crea->idNumber, crea->growth * 3));
  197. }
  198. }
  199. }
  200. bool CDwellingInstanceConstructor::producesCreature(const CCreature * crea) const
  201. {
  202. for (auto & entry : availableCreatures)
  203. {
  204. for (const CCreature * cre : entry)
  205. if (crea == cre)
  206. return true;
  207. }
  208. return false;
  209. }
  210. std::vector<const CCreature *> CDwellingInstanceConstructor::getProducedCreatures() const
  211. {
  212. std::vector<const CCreature *> creatures; //no idea why it's 2D, to be honest
  213. for (auto & entry : availableCreatures)
  214. {
  215. for (const CCreature * cre : entry)
  216. creatures.push_back(cre);
  217. }
  218. return creatures;
  219. }
  220. CBankInstanceConstructor::CBankInstanceConstructor()
  221. : bankResetDuration(0)
  222. {
  223. }
  224. void CBankInstanceConstructor::initTypeData(const JsonNode & input)
  225. {
  226. //TODO: name = input["name"].String();
  227. levels = input["levels"].Vector();
  228. bankResetDuration = input["resetDuration"].Float();
  229. }
  230. CGObjectInstance *CBankInstanceConstructor::create(const ObjectTemplate & tmpl) const
  231. {
  232. return createTyped(tmpl);
  233. }
  234. BankConfig CBankInstanceConstructor::generateConfig(const JsonNode & level, CRandomGenerator & rng) const
  235. {
  236. BankConfig bc;
  237. bc.chance = level["chance"].Float();
  238. bc.guards = JsonRandom::loadCreatures(level["guards"], rng);
  239. bc.upgradeChance = level["upgrade_chance"].Float();
  240. bc.combatValue = level["combat_value"].Float();
  241. std::vector<SpellID> spells;
  242. for (size_t i=0; i<6; i++)
  243. IObjectInterface::cb->getAllowedSpells(spells, i);
  244. bc.resources = Res::ResourceSet(level["reward"]["resources"]);
  245. bc.creatures = JsonRandom::loadCreatures(level["reward"]["creatures"], rng);
  246. bc.artifacts = JsonRandom::loadArtifacts(level["reward"]["artifacts"], rng);
  247. bc.spells = JsonRandom::loadSpells(level["reward"]["spells"], rng, spells);
  248. bc.value = level["value"].Float();
  249. return bc;
  250. }
  251. void CBankInstanceConstructor::configureObject(CGObjectInstance * object, CRandomGenerator & rng) const
  252. {
  253. //logGlobal->debugStream() << "Seed used to configure bank is " << rng.nextInt();
  254. auto bank = dynamic_cast<CBank*>(object);
  255. bank->resetDuration = bankResetDuration;
  256. si32 totalChance = 0;
  257. for (auto & node : levels)
  258. totalChance += node["chance"].Float();
  259. assert(totalChance != 0);
  260. si32 selectedChance = rng.nextInt(totalChance - 1);
  261. //logGlobal->debugStream() << "Selected chance for bank config is " << selectedChance;
  262. int cumulativeChance = 0;
  263. for (auto & node : levels)
  264. {
  265. cumulativeChance += node["chance"].Float();
  266. if (selectedChance < cumulativeChance)
  267. {
  268. bank->setConfig(generateConfig(node, rng));
  269. break;
  270. }
  271. }
  272. }
  273. CBankInfo::CBankInfo(const JsonVector & Config):
  274. config(Config)
  275. {
  276. assert(!Config.empty());
  277. }
  278. static void addStackToArmy(IObjectInfo::CArmyStructure & army, const CCreature * crea, si32 amount)
  279. {
  280. army.totalStrength += crea->fightValue * amount;
  281. bool walker = true;
  282. if (crea->hasBonusOfType(Bonus::SHOOTER))
  283. {
  284. army.shootersStrength += crea->fightValue * amount;
  285. walker = false;
  286. }
  287. if (crea->hasBonusOfType(Bonus::FLYING))
  288. {
  289. army.flyersStrength += crea->fightValue * amount;
  290. walker = false;
  291. }
  292. if (walker)
  293. army.walkersStrength += crea->fightValue * amount;
  294. }
  295. IObjectInfo::CArmyStructure CBankInfo::minGuards() const
  296. {
  297. std::vector<IObjectInfo::CArmyStructure> armies;
  298. for (auto configEntry : config)
  299. {
  300. auto stacks = JsonRandom::evaluateCreatures(configEntry["guards"]);
  301. IObjectInfo::CArmyStructure army;
  302. for (auto & stack : stacks)
  303. {
  304. assert(!stack.allowedCreatures.empty());
  305. auto weakest = boost::range::min_element(stack.allowedCreatures, [](const CCreature * a, const CCreature * b)
  306. {
  307. return a->fightValue < b->fightValue;
  308. });
  309. addStackToArmy(army, *weakest, stack.minAmount);
  310. }
  311. armies.push_back(army);
  312. }
  313. return *boost::range::min_element(armies);
  314. }
  315. IObjectInfo::CArmyStructure CBankInfo::maxGuards() const
  316. {
  317. std::vector<IObjectInfo::CArmyStructure> armies;
  318. for (auto configEntry : config)
  319. {
  320. auto stacks = JsonRandom::evaluateCreatures(configEntry["guards"]);
  321. IObjectInfo::CArmyStructure army;
  322. for (auto & stack : stacks)
  323. {
  324. assert(!stack.allowedCreatures.empty());
  325. auto strongest = boost::range::max_element(stack.allowedCreatures, [](const CCreature * a, const CCreature * b)
  326. {
  327. return a->fightValue < b->fightValue;
  328. });
  329. addStackToArmy(army, *strongest, stack.maxAmount);
  330. }
  331. armies.push_back(army);
  332. }
  333. return *boost::range::max_element(armies);
  334. }
  335. TPossibleGuards CBankInfo::getPossibleGuards() const
  336. {
  337. TPossibleGuards out;
  338. for (const JsonNode & configEntry : config)
  339. {
  340. const JsonNode & guardsInfo = configEntry["guards"];
  341. auto stacks = JsonRandom::evaluateCreatures(guardsInfo);
  342. IObjectInfo::CArmyStructure army;
  343. for (auto stack : stacks)
  344. {
  345. army.totalStrength += stack.allowedCreatures.front()->AIValue * (stack.minAmount + stack.maxAmount) / 2;
  346. //TODO: add fields for flyers, walkers etc...
  347. }
  348. ui8 chance = configEntry["chance"].Float();
  349. out.push_back(std::make_pair(chance, army));
  350. }
  351. return out;
  352. }
  353. bool CBankInfo::givesResources() const
  354. {
  355. for (const JsonNode & node : config)
  356. if (!node["reward"]["resources"].isNull())
  357. return true;
  358. return false;
  359. }
  360. bool CBankInfo::givesArtifacts() const
  361. {
  362. for (const JsonNode & node : config)
  363. if (!node["reward"]["artifacts"].isNull())
  364. return true;
  365. return false;
  366. }
  367. bool CBankInfo::givesCreatures() const
  368. {
  369. for (const JsonNode & node : config)
  370. if (!node["reward"]["creatures"].isNull())
  371. return true;
  372. return false;
  373. }
  374. bool CBankInfo::givesSpells() const
  375. {
  376. for (const JsonNode & node : config)
  377. if (!node["reward"]["spells"].isNull())
  378. return true;
  379. return false;
  380. }
  381. std::unique_ptr<IObjectInfo> CBankInstanceConstructor::getObjectInfo(const ObjectTemplate & tmpl) const
  382. {
  383. return std::unique_ptr<IObjectInfo>(new CBankInfo(levels));
  384. }