TreasurePlacer.cpp 31 KB

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