TreasurePlacer.cpp 25 KB

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