TreasurePlacer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /*
  2. * TreasurePlacer.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 "TreasurePlacer.h"
  12. #include "CMapGenerator.h"
  13. #include "Functions.h"
  14. #include "ObjectManager.h"
  15. #include "RoadPlacer.h"
  16. #include "ConnectionsPlacer.h"
  17. #include "RmgMap.h"
  18. #include "TileInfo.h"
  19. #include "CZonePlacer.h"
  20. #include "QuestArtifactPlacer.h"
  21. #include "../mapObjects/CommonConstructors.h"
  22. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  23. #include "../CCreatureHandler.h"
  24. #include "../spells/CSpellHandler.h" //for choosing random spells
  25. #include "../mapping/CMap.h"
  26. #include "../mapping/CMapEditManager.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. void TreasurePlacer::process()
  29. {
  30. addAllPossibleObjects();
  31. auto * m = zone.getModificator<ObjectManager>();
  32. if(m)
  33. createTreasures(*m);
  34. }
  35. void TreasurePlacer::init()
  36. {
  37. DEPENDENCY(ObjectManager);
  38. DEPENDENCY(ConnectionsPlacer);
  39. POSTFUNCTION(RoadPlacer);
  40. }
  41. void TreasurePlacer::addObjectToRandomPool(const ObjectInfo& oi)
  42. {
  43. possibleObjects.push_back(oi);
  44. }
  45. void TreasurePlacer::addAllPossibleObjects()
  46. {
  47. ObjectInfo oi;
  48. for(auto primaryID : VLC->objtypeh->knownObjects())
  49. {
  50. for(auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  51. {
  52. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  53. if(!handler->isStaticObject() && handler->getRMGInfo().value)
  54. {
  55. auto rmgInfo = handler->getRMGInfo();
  56. if (rmgInfo.mapLimit || rmgInfo.value > zone.getMaxTreasureValue())
  57. {
  58. //Skip objects with per-map limit here
  59. continue;
  60. }
  61. auto templates = handler->getTemplates(zone.getTerrainType());
  62. if (templates.empty())
  63. continue;
  64. //Assume the template with fewest terrains is the most suitable
  65. auto temp = *boost::min_element(templates, [](std::shared_ptr<const ObjectTemplate> lhs, std::shared_ptr<const ObjectTemplate> rhs) -> bool
  66. {
  67. return lhs->getAllowedTerrains().size() < rhs->getAllowedTerrains().size();
  68. });
  69. oi.generateObject = [temp]() -> CGObjectInstance *
  70. {
  71. return VLC->objtypeh->getHandlerFor(temp->id, temp->subid)->create(temp);
  72. };
  73. oi.value = rmgInfo.value;
  74. oi.probability = rmgInfo.rarity;
  75. oi.templ = temp;
  76. oi.maxPerZone = rmgInfo.zoneLimit;
  77. addObjectToRandomPool(oi);
  78. }
  79. }
  80. }
  81. if(zone.getType() == ETemplateZoneType::WATER)
  82. return;
  83. //prisons
  84. //levels 1, 5, 10, 20, 30
  85. static int prisonsLevels = std::min(generator.getConfig().prisonExperience.size(), generator.getConfig().prisonValues.size());
  86. for(int i = 0; i < prisonsLevels; i++)
  87. {
  88. oi.generateObject = [i, this]() -> CGObjectInstance *
  89. {
  90. std::vector<ui32> possibleHeroes;
  91. for(int j = 0; j < map.map().allowedHeroes.size(); j++)
  92. {
  93. if(map.map().allowedHeroes[j])
  94. possibleHeroes.push_back(j);
  95. }
  96. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, generator.rand);
  97. auto factory = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0);
  98. auto * obj = dynamic_cast<CGHeroInstance *>(factory->create());
  99. obj->subID = hid; //will be initialized later
  100. obj->exp = generator.getConfig().prisonExperience[i];
  101. obj->setOwner(PlayerColor::NEUTRAL);
  102. map.map().allowedHeroes[hid] = false; //ban this hero
  103. generator.decreasePrisonsRemaining();
  104. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(zone.getTerrainType()).front(); //can't init template with hero subID
  105. return obj;
  106. };
  107. oi.setTemplate(Obj::PRISON, 0, zone.getTerrainType());
  108. oi.value = generator.getConfig().prisonValues[i];
  109. oi.probability = 30;
  110. oi.maxPerZone = generator.getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  111. addObjectToRandomPool(oi);
  112. }
  113. //all following objects are unlimited
  114. oi.maxPerZone = std::numeric_limits<ui32>::max();
  115. std::vector<CCreature *> creatures; //native creatures for this zone
  116. for(auto cre : VLC->creh->objects)
  117. {
  118. if(!cre->special && cre->getFaction() == zone.getTownType())
  119. {
  120. creatures.push_back(cre);
  121. }
  122. }
  123. //dwellings
  124. auto dwellingTypes = {Obj::CREATURE_GENERATOR1, Obj::CREATURE_GENERATOR4};
  125. for(auto dwellingType : dwellingTypes)
  126. {
  127. auto subObjects = VLC->objtypeh->knownSubObjects(dwellingType);
  128. if(dwellingType == Obj::CREATURE_GENERATOR1)
  129. {
  130. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  131. static int elementalConfluxROE[] = {7, 13, 16, 47};
  132. for(int & i : elementalConfluxROE)
  133. vstd::erase_if_present(subObjects, i);
  134. }
  135. for(auto secondaryID : subObjects)
  136. {
  137. const auto * dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(dwellingType, secondaryID).get());
  138. auto creatures = dwellingHandler->getProducedCreatures();
  139. if(creatures.empty())
  140. continue;
  141. const auto * cre = creatures.front();
  142. if(cre->getFaction() == zone.getTownType())
  143. {
  144. auto nativeZonesCount = static_cast<float>(map.getZoneCount(cre->getFaction()));
  145. oi.value = static_cast<ui32>(cre->getAIValue() * cre->getGrowth() * (1 + (nativeZonesCount / map.getTotalZoneCount()) + (nativeZonesCount / 2)));
  146. oi.probability = 40;
  147. for(const auto & tmplate : dwellingHandler->getTemplates())
  148. {
  149. if(tmplate->canBePlacedAt(zone.getTerrainType()))
  150. {
  151. oi.generateObject = [tmplate, secondaryID, dwellingType]() -> CGObjectInstance *
  152. {
  153. auto * obj = VLC->objtypeh->getHandlerFor(dwellingType, secondaryID)->create(tmplate);
  154. obj->tempOwner = PlayerColor::NEUTRAL;
  155. return obj;
  156. };
  157. oi.templ = tmplate;
  158. addObjectToRandomPool(oi);
  159. }
  160. }
  161. }
  162. }
  163. }
  164. for(int i = 0; i < generator.getConfig().scrollValues.size(); i++)
  165. {
  166. oi.generateObject = [i, this]() -> CGObjectInstance *
  167. {
  168. auto factory = VLC->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
  169. auto * obj = dynamic_cast<CGArtifact *>(factory->create());
  170. std::vector<SpellID> out;
  171. for(auto spell : VLC->spellh->objects) //spellh size appears to be greater (?)
  172. {
  173. if(map.isAllowedSpell(spell->id) && spell->level == i + 1)
  174. {
  175. out.push_back(spell->id);
  176. }
  177. }
  178. auto * a = CArtifactInstance::createScroll(*RandomGeneratorUtil::nextItem(out, generator.rand));
  179. obj->storedArtifact = a;
  180. return obj;
  181. };
  182. oi.setTemplate(Obj::SPELL_SCROLL, 0, zone.getTerrainType());
  183. oi.value = generator.getConfig().scrollValues[i];
  184. oi.probability = 30;
  185. addObjectToRandomPool(oi);
  186. }
  187. //pandora box with gold
  188. for(int i = 1; i < 5; i++)
  189. {
  190. oi.generateObject = [i]() -> CGObjectInstance *
  191. {
  192. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  193. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  194. obj->resources[EGameResID::GOLD] = i * 5000;
  195. return obj;
  196. };
  197. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  198. oi.value = i * generator.getConfig().pandoraMultiplierGold;
  199. oi.probability = 5;
  200. addObjectToRandomPool(oi);
  201. }
  202. //pandora box with experience
  203. for(int i = 1; i < 5; i++)
  204. {
  205. oi.generateObject = [i]() -> CGObjectInstance *
  206. {
  207. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  208. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  209. obj->gainedExp = i * 5000;
  210. return obj;
  211. };
  212. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  213. oi.value = i * generator.getConfig().pandoraMultiplierExperience;
  214. oi.probability = 20;
  215. addObjectToRandomPool(oi);
  216. }
  217. //pandora box with creatures
  218. const std::vector<int> & tierValues = generator.getConfig().pandoraCreatureValues;
  219. auto creatureToCount = [tierValues](CCreature * creature) -> int
  220. {
  221. if(!creature->getAIValue() || tierValues.empty()) //bug #2681
  222. return 0; //this box won't be generated
  223. //Follow the rules from https://heroes.thelazy.net/index.php/Pandora%27s_Box
  224. int actualTier = creature->getLevel() > tierValues.size() ?
  225. tierValues.size() - 1 :
  226. creature->getLevel() - 1;
  227. float creaturesAmount = std::floor((static_cast<float>(tierValues[actualTier])) / creature->getAIValue());
  228. if (creaturesAmount < 1)
  229. {
  230. return 0;
  231. }
  232. else if(creaturesAmount <= 5)
  233. {
  234. //No change
  235. }
  236. else if(creaturesAmount <= 12)
  237. {
  238. creaturesAmount = std::ceil(creaturesAmount / 2) * 2;
  239. }
  240. else if(creaturesAmount <= 50)
  241. {
  242. creaturesAmount = std::round(creaturesAmount / 5) * 5;
  243. }
  244. else
  245. {
  246. creaturesAmount = std::round(creaturesAmount / 10) * 10;
  247. }
  248. return static_cast<int>(creaturesAmount);
  249. };
  250. for(auto * creature : creatures)
  251. {
  252. int creaturesAmount = creatureToCount(creature);
  253. if(!creaturesAmount)
  254. continue;
  255. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  256. {
  257. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  258. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  259. auto * stack = new CStackInstance(creature, creaturesAmount);
  260. obj->creatures.putStack(SlotID(0), stack);
  261. return obj;
  262. };
  263. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  264. oi.value = static_cast<ui32>((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) / 3);
  265. oi.probability = 3;
  266. addObjectToRandomPool(oi);
  267. }
  268. //Pandora with 12 spells of certain level
  269. for(int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  270. {
  271. oi.generateObject = [i, this]() -> CGObjectInstance *
  272. {
  273. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  274. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  275. std::vector <CSpell *> spells;
  276. for(auto spell : VLC->spellh->objects)
  277. {
  278. if(map.isAllowedSpell(spell->id) && spell->level == i)
  279. spells.push_back(spell);
  280. }
  281. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  282. for(int j = 0; j < std::min(12, static_cast<int>(spells.size())); j++)
  283. {
  284. obj->spells.push_back(spells[j]->id);
  285. }
  286. return obj;
  287. };
  288. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  289. oi.value = (i + 1) * generator.getConfig().pandoraMultiplierSpells; //5000 - 15000
  290. oi.probability = 2;
  291. addObjectToRandomPool(oi);
  292. }
  293. //Pandora with 15 spells of certain school
  294. for(int i = 0; i < 4; i++)
  295. {
  296. oi.generateObject = [i, this]() -> CGObjectInstance *
  297. {
  298. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  299. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  300. std::vector <CSpell *> spells;
  301. for(auto spell : VLC->spellh->objects)
  302. {
  303. if(map.isAllowedSpell(spell->id) && spell->school[static_cast<ESpellSchool>(i)])
  304. spells.push_back(spell);
  305. }
  306. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  307. for(int j = 0; j < std::min(15, static_cast<int>(spells.size())); j++)
  308. {
  309. obj->spells.push_back(spells[j]->id);
  310. }
  311. return obj;
  312. };
  313. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  314. oi.value = generator.getConfig().pandoraSpellSchool;
  315. oi.probability = 2;
  316. addObjectToRandomPool(oi);
  317. }
  318. // Pandora box with 60 random spells
  319. oi.generateObject = [this]() -> CGObjectInstance *
  320. {
  321. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  322. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create());
  323. std::vector <CSpell *> spells;
  324. for(auto spell : VLC->spellh->objects)
  325. {
  326. if(map.isAllowedSpell(spell->id))
  327. spells.push_back(spell);
  328. }
  329. RandomGeneratorUtil::randomShuffle(spells, generator.rand);
  330. for(int j = 0; j < std::min(60, static_cast<int>(spells.size())); j++)
  331. {
  332. obj->spells.push_back(spells[j]->id);
  333. }
  334. return obj;
  335. };
  336. oi.setTemplate(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  337. oi.value = generator.getConfig().pandoraSpell60;
  338. oi.probability = 2;
  339. addObjectToRandomPool(oi);
  340. //seer huts with creatures or generic rewards
  341. if(zone.getConnections().size()) //Unlikely, but...
  342. {
  343. static const int genericSeerHuts = 8;
  344. int seerHutsPerType = 0;
  345. const int questArtsRemaining = static_cast<int>(generator.getQuestArtsRemaning().size());
  346. //general issue is that not many artifact types are available for quests
  347. if(questArtsRemaining >= genericSeerHuts + static_cast<int>(creatures.size()))
  348. {
  349. seerHutsPerType = questArtsRemaining / (genericSeerHuts + static_cast<int>(creatures.size()));
  350. }
  351. else if(questArtsRemaining >= genericSeerHuts)
  352. {
  353. seerHutsPerType = 1;
  354. }
  355. oi.maxPerZone = seerHutsPerType;
  356. RandomGeneratorUtil::randomShuffle(creatures, generator.rand);
  357. auto generateArtInfo = [this](const ArtifactID & id) -> ObjectInfo
  358. {
  359. ObjectInfo artInfo;
  360. artInfo.probability = std::numeric_limits<ui16>::max(); //99,9% to spawn that art in first treasure pile
  361. artInfo.maxPerZone = 1;
  362. artInfo.value = 2000; //treasure art
  363. artInfo.setTemplate(Obj::ARTIFACT, id, this->zone.getTerrainType());
  364. artInfo.generateObject = [id]() -> CGObjectInstance *
  365. {
  366. auto handler = VLC->objtypeh->getHandlerFor(Obj::ARTIFACT, id);
  367. return handler->create(handler->getTemplates().front());
  368. };
  369. return artInfo;
  370. };
  371. for(int i = 0; i < std::min(static_cast<int>(creatures.size()), questArtsRemaining - genericSeerHuts); i++)
  372. {
  373. auto * creature = creatures[i];
  374. int creaturesAmount = creatureToCount(creature);
  375. if(!creaturesAmount)
  376. continue;
  377. int randomAppearance = chooseRandomAppearance(generator.rand, Obj::SEER_HUT, zone.getTerrainType());
  378. oi.generateObject = [creature, creaturesAmount, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  379. {
  380. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  381. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  382. obj->rewardType = CGSeerHut::CREATURE;
  383. obj->rID = creature->getId();
  384. obj->rVal = creaturesAmount;
  385. obj->quest->missionType = CQuest::MISSION_ART;
  386. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  387. obj->quest->addArtifactID(artid);
  388. obj->quest->lastDay = -1;
  389. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  390. generator.banQuestArt(artid);
  391. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  392. return obj;
  393. };
  394. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  395. oi.value = static_cast<ui32>(((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) - 4000) / 3);
  396. oi.probability = 3;
  397. addObjectToRandomPool(oi);
  398. }
  399. static int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  400. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similiar
  401. {
  402. int randomAppearance = chooseRandomAppearance(generator.rand, Obj::SEER_HUT, zone.getTerrainType());
  403. oi.setTemplate(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  404. oi.value = generator.getConfig().questValues[i];
  405. oi.probability = 10;
  406. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  407. {
  408. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  409. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  410. obj->rewardType = CGSeerHut::EXPERIENCE;
  411. obj->rID = 0; //unitialized?
  412. obj->rVal = generator.getConfig().questRewardValues[i];
  413. obj->quest->missionType = CQuest::MISSION_ART;
  414. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  415. obj->quest->addArtifactID(artid);
  416. obj->quest->lastDay = -1;
  417. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  418. generator.banQuestArt(artid);
  419. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  420. return obj;
  421. };
  422. addObjectToRandomPool(oi);
  423. oi.generateObject = [i, randomAppearance, this, generateArtInfo]() -> CGObjectInstance *
  424. {
  425. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  426. auto * obj = dynamic_cast<CGSeerHut *>(factory->create());
  427. obj->rewardType = CGSeerHut::RESOURCES;
  428. obj->rID = GameResID(EGameResID::GOLD);
  429. obj->rVal = generator.getConfig().questRewardValues[i];
  430. obj->quest->missionType = CQuest::MISSION_ART;
  431. ArtifactID artid = *RandomGeneratorUtil::nextItem(generator.getQuestArtsRemaning(), generator.rand);
  432. obj->quest->addArtifactID(artid);
  433. obj->quest->lastDay = -1;
  434. obj->quest->isCustomFirst = obj->quest->isCustomNext = obj->quest->isCustomComplete = false;
  435. generator.banQuestArt(artid);
  436. zone.getModificator<QuestArtifactPlacer>()->addQuestArtifact(artid);
  437. return obj;
  438. };
  439. addObjectToRandomPool(oi);
  440. }
  441. }
  442. }
  443. size_t TreasurePlacer::getPossibleObjectsSize() const
  444. {
  445. return possibleObjects.size();
  446. }
  447. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  448. {
  449. return zone.getType() != ETemplateZoneType::WATER && value > minGuardedValue;
  450. }
  451. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  452. {
  453. std::vector<ObjectInfo*> objectInfos;
  454. int maxValue = treasureInfo.max;
  455. int minValue = treasureInfo.min;
  456. const ui32 desiredValue = generator.rand.nextInt(minValue, maxValue);
  457. int currentValue = 0;
  458. bool hasLargeObject = false;
  459. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  460. {
  461. auto * oi = getRandomObject(desiredValue, currentValue, maxValue, !hasLargeObject);
  462. if(!oi) //fail
  463. break;
  464. if(oi->templ->isVisitableFromTop())
  465. {
  466. objectInfos.push_back(oi);
  467. }
  468. else
  469. {
  470. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  471. hasLargeObject = true;
  472. }
  473. //remove from possible objects
  474. assert(oi->maxPerZone);
  475. oi->maxPerZone--;
  476. currentValue += oi->value;
  477. }
  478. return objectInfos;
  479. }
  480. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  481. {
  482. rmg::Object rmgObject;
  483. for(const auto & oi : treasureInfos)
  484. {
  485. auto blockedArea = rmgObject.getArea();
  486. auto accessibleArea = rmgObject.getAccessibleArea();
  487. if(rmgObject.instances().empty())
  488. accessibleArea.add(int3());
  489. auto * object = oi->generateObject();
  490. object->appearance = oi->templ;
  491. auto & instance = rmgObject.addInstance(*object);
  492. do
  493. {
  494. if(accessibleArea.empty())
  495. {
  496. //fail - fallback
  497. rmgObject.clear();
  498. return rmgObject;
  499. }
  500. std::vector<int3> bestPositions;
  501. if(densePlacement)
  502. {
  503. int bestPositionsWeight = std::numeric_limits<int>::max();
  504. for(const auto & t : accessibleArea.getTilesVector())
  505. {
  506. instance.setPosition(t);
  507. int w = rmgObject.getAccessibleArea().getTilesVector().size();
  508. if(w < bestPositionsWeight)
  509. {
  510. bestPositions.clear();
  511. bestPositions.push_back(t);
  512. bestPositionsWeight = w;
  513. }
  514. else if(w == bestPositionsWeight)
  515. {
  516. bestPositions.push_back(t);
  517. }
  518. }
  519. }
  520. else
  521. {
  522. bestPositions = accessibleArea.getTilesVector();
  523. }
  524. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, generator.rand);
  525. instance.setPosition(nextPos - rmgObject.getPosition());
  526. auto instanceAccessibleArea = instance.getAccessibleArea();
  527. if(instance.getBlockedArea().getTilesVector().size() == 1)
  528. {
  529. if(instance.object().appearance->isVisitableFromTop() && instance.object().ID != Obj::CORPSE)
  530. instanceAccessibleArea.add(instance.getVisitablePosition());
  531. }
  532. //first object is good
  533. if(rmgObject.instances().size() == 1)
  534. break;
  535. //condition for good position
  536. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  537. break;
  538. //fail - new position
  539. accessibleArea.erase(nextPos);
  540. } while(true);
  541. }
  542. return rmgObject;
  543. }
  544. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, ui32 maxValue, bool allowLargeObjects)
  545. {
  546. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  547. ui32 total = 0;
  548. //calculate actual treasure value range based on remaining value
  549. ui32 maxVal = maxValue - currentValue;
  550. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  551. for(ObjectInfo & oi : possibleObjects) //copy constructor turned out to be costly
  552. {
  553. if(oi.value > maxVal)
  554. break; //this assumes values are sorted in ascending order
  555. if(!oi.templ->isVisitableFromTop() && !allowLargeObjects)
  556. continue;
  557. if(oi.value >= minValue && oi.maxPerZone > 0)
  558. {
  559. total += oi.probability;
  560. thresholds.emplace_back(total, &oi);
  561. }
  562. }
  563. if(thresholds.empty())
  564. {
  565. return nullptr;
  566. }
  567. else
  568. {
  569. int r = generator.rand.nextInt(1, total);
  570. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  571. {
  572. return static_cast<int>(rhs.first) < lhs;
  573. };
  574. //binary search = fastest
  575. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  576. return it->second;
  577. }
  578. }
  579. void TreasurePlacer::createTreasures(ObjectManager & manager)
  580. {
  581. const int maxAttempts = 2;
  582. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  583. int monsterStrength = zone.zoneMonsterStrength + mapMonsterStrength - 1; //array index from 0 to 4
  584. static int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  585. minGuardedValue = minGuardedValues[monsterStrength];
  586. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  587. {
  588. return lhs.max > rhs.max;
  589. };
  590. auto restoreZoneLimits = [](const std::vector<ObjectInfo*> & treasurePile)
  591. {
  592. for(auto * oi : treasurePile)
  593. {
  594. oi->maxPerZone++;
  595. }
  596. };
  597. //place biggest treasures first at large distance, place smaller ones inbetween
  598. auto treasureInfo = zone.getTreasureInfo();
  599. boost::sort(treasureInfo, valueComparator);
  600. //sort treasures by ascending value so we can stop checking treasures with too high value
  601. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  602. {
  603. return oi1.value < oi2.value;
  604. });
  605. int totalDensity = 0;
  606. for (auto t : treasureInfo)
  607. {
  608. //discard objects with too high value to be ever placed
  609. vstd::erase_if(possibleObjects, [t](const ObjectInfo& oi) -> bool
  610. {
  611. return oi.value > t.max;
  612. });
  613. totalDensity += t.density;
  614. //treasure density is inversely proportional to zone size but must be scaled back to map size
  615. //also, normalize it to zone count - higher count means relatively smaller zones
  616. //this is squared distance for optimization purposes
  617. const float minDistance = std::max<float>((125.f / totalDensity), 2.0f);
  618. //distance lower than 2 causes objects to overlap and crash
  619. for(int attempt = 0; attempt <= maxAttempts;)
  620. {
  621. auto treasurePileInfos = prepareTreasurePile(t);
  622. if(treasurePileInfos.empty())
  623. {
  624. ++attempt;
  625. continue;
  626. }
  627. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0, [](int v, const ObjectInfo * oi){return v + oi->value;});
  628. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  629. if(rmgObject.instances().empty()) //handle incorrect placement
  630. {
  631. restoreZoneLimits(treasurePileInfos);
  632. continue;
  633. }
  634. //guard treasure pile
  635. bool guarded = isGuardNeededForTreasure(value);
  636. if(guarded)
  637. guarded = manager.addGuard(rmgObject, value);
  638. auto possibleArea = zone.areaPossible();
  639. auto path = rmg::Path::invalid();
  640. if(guarded)
  641. {
  642. path = manager.placeAndConnectObject(possibleArea, rmgObject, [this, &rmgObject, &minDistance, &manager](const int3 & tile)
  643. {
  644. auto ti = map.getTile(tile);
  645. if(ti.getNearestObjectDistance() < minDistance)
  646. return -1.f;
  647. for(const auto & t : rmgObject.getArea().getTilesVector())
  648. {
  649. if(map.getTile(t).getNearestObjectDistance() < minDistance)
  650. return -1.f;
  651. }
  652. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  653. auto areaToBlock = rmgObject.getAccessibleArea(true);
  654. areaToBlock.subtract(guardedArea);
  655. if(areaToBlock.overlap(zone.freePaths()) || areaToBlock.overlap(manager.getVisitableArea()))
  656. return -1.f;
  657. return ti.getNearestObjectDistance();
  658. }, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  659. }
  660. else
  661. {
  662. path = manager.placeAndConnectObject(possibleArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  663. }
  664. if(path.valid())
  665. {
  666. //debug purposes
  667. treasureArea.unite(rmgObject.getArea());
  668. if(guarded)
  669. {
  670. guards.unite(rmgObject.instances().back()->getBlockedArea());
  671. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  672. auto areaToBlock = rmgObject.getAccessibleArea(true);
  673. areaToBlock.subtract(guardedArea);
  674. treasureBlockArea.unite(areaToBlock);
  675. }
  676. zone.connectPath(path);
  677. manager.placeObject(rmgObject, guarded, true);
  678. attempt = 0;
  679. }
  680. else
  681. {
  682. restoreZoneLimits(treasurePileInfos);
  683. rmgObject.clear();
  684. ++attempt;
  685. }
  686. }
  687. }
  688. }
  689. char TreasurePlacer::dump(const int3 & t)
  690. {
  691. if(guards.contains(t))
  692. return '!';
  693. if(treasureArea.contains(t))
  694. return '$';
  695. if(treasureBlockArea.contains(t))
  696. return '*';
  697. return Modificator::dump(t);
  698. }
  699. void ObjectInfo::setTemplate(si32 type, si32 subtype, TerrainId terrainType)
  700. {
  701. auto templHandler = VLC->objtypeh->getHandlerFor(type, subtype);
  702. if(!templHandler)
  703. return;
  704. auto templates = templHandler->getTemplates(terrainType);
  705. if(templates.empty())
  706. return;
  707. templ = templates.front();
  708. }
  709. VCMI_LIB_NAMESPACE_END