TreasurePlacer.cpp 27 KB

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