TreasurePlacer.cpp 25 KB

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