TreasurePlacer.cpp 27 KB

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