TreasurePlacer.cpp 25 KB

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