TreasurePlacer.cpp 28 KB

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