TreasurePlacer.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  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 "../CRmgTemplate.h"
  13. #include "../CMapGenerator.h"
  14. #include "../Functions.h"
  15. #include "ObjectManager.h"
  16. #include "RoadPlacer.h"
  17. #include "ConnectionsPlacer.h"
  18. #include "../RmgMap.h"
  19. #include "../TileInfo.h"
  20. #include "../CZonePlacer.h"
  21. #include "PrisonHeroPlacer.h"
  22. #include "QuestArtifactPlacer.h"
  23. #include "../../ArtifactUtils.h"
  24. #include "../../mapObjectConstructors/AObjectTypeHandler.h"
  25. #include "../../mapObjectConstructors/CObjectClassesHandler.h"
  26. #include "../../mapObjectConstructors/DwellingInstanceConstructor.h"
  27. #include "../../rewardable/Info.h"
  28. #include "../../mapObjects/CGHeroInstance.h"
  29. #include "../../mapObjects/CGPandoraBox.h"
  30. #include "../../mapObjects/CQuest.h"
  31. #include "../../mapObjects/MiscObjects.h"
  32. #include "../../CCreatureHandler.h"
  33. #include "../../spells/CSpellHandler.h" //for choosing random spells
  34. #include "../../mapping/CMap.h"
  35. #include "../../mapping/CMapEditManager.h"
  36. #include <vstd/RNG.h>
  37. VCMI_LIB_NAMESPACE_BEGIN
  38. void TreasurePlacer::process()
  39. {
  40. if (zone.getMaxTreasureValue() == 0)
  41. {
  42. //No treasures at all
  43. return;
  44. }
  45. // Get default objects
  46. addAllPossibleObjects();
  47. // Override with custom objects
  48. objects.patchWithZoneConfig(zone, this);
  49. auto * m = zone.getModificator<ObjectManager>();
  50. if(m)
  51. createTreasures(*m);
  52. }
  53. void TreasurePlacer::init()
  54. {
  55. maxPrisons = 0; //Should be in the constructor, but we use macro for that
  56. DEPENDENCY(ObjectManager);
  57. DEPENDENCY(ConnectionsPlacer);
  58. DEPENDENCY_ALL(PrisonHeroPlacer);
  59. DEPENDENCY(RoadPlacer);
  60. // FIXME: Starting zones get Pandoras with neutral creatures
  61. // Add all native creatures
  62. for(auto const & cre : VLC->creh->objects)
  63. {
  64. if(!cre->special && cre->getFaction() == zone.getTownType())
  65. {
  66. creatures.push_back(cre.get());
  67. }
  68. }
  69. tierValues = generator.getConfig().pandoraCreatureValues;
  70. }
  71. void TreasurePlacer::addObjectToRandomPool(const ObjectInfo& oi)
  72. {
  73. if (oi.templates.empty())
  74. {
  75. logGlobal->error("Attempt to add ObjectInfo with no templates! Value: %d", oi.value);
  76. return;
  77. }
  78. if (!oi.generateObject)
  79. {
  80. logGlobal->error("Attempt to add ObjectInfo with no generateObject function! Value: %d", oi.value);
  81. return;
  82. }
  83. if (!oi.maxPerZone)
  84. {
  85. logGlobal->warn("Attempt to add ObjectInfo with 0 maxPerZone! Value: %d", oi.value);
  86. return;
  87. }
  88. RecursiveLock lock(externalAccessMutex);
  89. objects.addObject(oi);
  90. }
  91. void TreasurePlacer::addAllPossibleObjects()
  92. {
  93. addCommonObjects();
  94. addDwellings();
  95. addPandoraBoxes();
  96. addSeerHuts();
  97. addPrisons();
  98. addScrolls();
  99. }
  100. void TreasurePlacer::addCommonObjects()
  101. {
  102. ObjectInfo oi;
  103. for(auto primaryID : VLC->objtypeh->knownObjects())
  104. {
  105. for(auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  106. {
  107. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  108. if(!handler->isStaticObject() && handler->getRMGInfo().value)
  109. {
  110. auto rmgInfo = handler->getRMGInfo();
  111. if (rmgInfo.mapLimit || rmgInfo.value > zone.getMaxTreasureValue())
  112. {
  113. //Skip objects with per-map limit here
  114. continue;
  115. }
  116. setBasicProperties(oi, CompoundMapObjectID(primaryID, secondaryID));
  117. oi.value = rmgInfo.value;
  118. oi.probability = rmgInfo.rarity;
  119. oi.maxPerZone = rmgInfo.zoneLimit;
  120. if(!oi.templates.empty())
  121. addObjectToRandomPool(oi);
  122. }
  123. }
  124. }
  125. }
  126. void TreasurePlacer::setBasicProperties(ObjectInfo & oi, CompoundMapObjectID objid) const
  127. {
  128. oi.generateObject = [this, objid]() -> CGObjectInstance *
  129. {
  130. return VLC->objtypeh->getHandlerFor(objid)->create(map.mapInstance->cb, nullptr);
  131. };
  132. oi.setTemplates(objid.primaryID, objid.secondaryID, zone.getTerrainType());
  133. }
  134. void TreasurePlacer::addPrisons()
  135. {
  136. //Generate Prison on water only if it has a template
  137. auto prisonTemplates = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(zone.getTerrainType());
  138. if (!prisonTemplates.empty())
  139. {
  140. PrisonHeroPlacer * prisonHeroPlacer = nullptr;
  141. for(auto & z : map.getZones())
  142. {
  143. prisonHeroPlacer = z.second->getModificator<PrisonHeroPlacer>();
  144. if (prisonHeroPlacer)
  145. {
  146. break;
  147. }
  148. }
  149. //prisons
  150. //levels 1, 5, 10, 20, 30
  151. static const int prisonsLevels = std::min(generator.getConfig().prisonExperience.size(), generator.getConfig().prisonValues.size());
  152. size_t prisonsLeft = getMaxPrisons();
  153. for (int i = prisonsLevels - 1; i >= 0; i--)
  154. {
  155. ObjectInfo oi; // Create new instance which will hold destructor operation
  156. oi.value = generator.getConfig().prisonValues[i];
  157. if (oi.value > zone.getMaxTreasureValue())
  158. {
  159. continue;
  160. }
  161. oi.generateObject = [i, this, prisonHeroPlacer]() -> CGObjectInstance*
  162. {
  163. HeroTypeID hid = prisonHeroPlacer->drawRandomHero();
  164. auto factory = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0);
  165. auto* obj = dynamic_cast<CGHeroInstance*>(factory->create(map.mapInstance->cb, nullptr));
  166. obj->setHeroType(hid); //will be initialized later
  167. obj->exp = generator.getConfig().prisonExperience[i];
  168. obj->setOwner(PlayerColor::NEUTRAL);
  169. return obj;
  170. };
  171. oi.destroyObject = [prisonHeroPlacer](CGObjectInstance* obj)
  172. {
  173. // Hero can be used again
  174. auto* hero = dynamic_cast<CGHeroInstance*>(obj);
  175. prisonHeroPlacer->restoreDrawnHero(hero->getHeroType());
  176. };
  177. oi.setTemplates(Obj::PRISON, 0, zone.getTerrainType());
  178. oi.value = generator.getConfig().prisonValues[i];
  179. oi.probability = 30;
  180. //Distribute all allowed prisons, starting from the most valuable
  181. oi.maxPerZone = (std::ceil((float)prisonsLeft / (i + 1)));
  182. prisonsLeft -= oi.maxPerZone;
  183. if(!oi.templates.empty())
  184. addObjectToRandomPool(oi);
  185. }
  186. }
  187. }
  188. void TreasurePlacer::addDwellings()
  189. {
  190. if(zone.getType() == ETemplateZoneType::WATER)
  191. return;
  192. ObjectInfo oi;
  193. //dwellings
  194. auto dwellingTypes = {Obj::CREATURE_GENERATOR1, Obj::CREATURE_GENERATOR4};
  195. for(auto dwellingType : dwellingTypes)
  196. {
  197. auto subObjects = VLC->objtypeh->knownSubObjects(dwellingType);
  198. if(dwellingType == Obj::CREATURE_GENERATOR1)
  199. {
  200. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  201. static const MapObjectSubID elementalConfluxROE[] = {7, 13, 16, 47};
  202. for(auto const & i : elementalConfluxROE)
  203. vstd::erase_if_present(subObjects, i);
  204. }
  205. for(auto secondaryID : subObjects)
  206. {
  207. const auto * dwellingHandler = dynamic_cast<const DwellingInstanceConstructor *>(VLC->objtypeh->getHandlerFor(dwellingType, secondaryID).get());
  208. auto creatures = dwellingHandler->getProducedCreatures();
  209. if(creatures.empty())
  210. continue;
  211. const auto * cre = creatures.front();
  212. if(cre->getFaction() == zone.getTownType())
  213. {
  214. auto nativeZonesCount = static_cast<float>(map.getZoneCount(cre->getFaction()));
  215. oi.value = static_cast<ui32>(cre->getAIValue() * cre->getGrowth() * (1 + (nativeZonesCount / map.getTotalZoneCount()) + (nativeZonesCount / 2)));
  216. oi.probability = 40;
  217. oi.generateObject = [this, secondaryID, dwellingType]() -> CGObjectInstance *
  218. {
  219. auto * obj = VLC->objtypeh->getHandlerFor(dwellingType, secondaryID)->create(map.mapInstance->cb, nullptr);
  220. obj->tempOwner = PlayerColor::NEUTRAL;
  221. return obj;
  222. };
  223. oi.setTemplates(dwellingType, secondaryID, zone.getTerrainType());
  224. if(!oi.templates.empty())
  225. addObjectToRandomPool(oi);
  226. }
  227. }
  228. }
  229. }
  230. void TreasurePlacer::addScrolls()
  231. {
  232. if(zone.getType() == ETemplateZoneType::WATER)
  233. return;
  234. ObjectInfo oi;
  235. for(int i = 0; i < generator.getConfig().scrollValues.size(); i++)
  236. {
  237. oi.generateObject = [i, this]() -> CGObjectInstance *
  238. {
  239. auto factory = VLC->objtypeh->getHandlerFor(Obj::SPELL_SCROLL, 0);
  240. auto * obj = dynamic_cast<CGArtifact *>(factory->create(map.mapInstance->cb, nullptr));
  241. std::vector<SpellID> out;
  242. for(auto spellID : VLC->spellh->getDefaultAllowed())
  243. {
  244. if(map.isAllowedSpell(spellID) && spellID.toSpell()->getLevel() == i + 1)
  245. out.push_back(spellID);
  246. }
  247. auto * a = ArtifactUtils::createScroll(*RandomGeneratorUtil::nextItem(out, zone.getRand()));
  248. obj->storedArtifact = a;
  249. return obj;
  250. };
  251. oi.setTemplates(Obj::SPELL_SCROLL, 0, zone.getTerrainType());
  252. oi.value = generator.getConfig().scrollValues[i];
  253. oi.probability = 30;
  254. if(!oi.templates.empty())
  255. addObjectToRandomPool(oi);
  256. }
  257. }
  258. void TreasurePlacer::addPandoraBoxes()
  259. {
  260. if(zone.getType() == ETemplateZoneType::WATER)
  261. return;
  262. addPandoraBoxesWithGold();
  263. addPandoraBoxesWithExperience();
  264. addPandoraBoxesWithCreatures();
  265. addPandoraBoxesWithSpells();
  266. }
  267. void TreasurePlacer::addPandoraBoxesWithGold()
  268. {
  269. ObjectInfo oi;
  270. //pandora box with gold
  271. for(int i = 1; i < 5; i++)
  272. {
  273. oi.generateObject = [this, i]() -> CGObjectInstance *
  274. {
  275. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  276. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create(map.mapInstance->cb, nullptr));
  277. Rewardable::VisitInfo reward;
  278. reward.reward.resources[EGameResID::GOLD] = i * 5000;
  279. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  280. obj->configuration.info.push_back(reward);
  281. return obj;
  282. };
  283. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  284. oi.value = i * generator.getConfig().pandoraMultiplierGold;
  285. oi.probability = 5;
  286. if(!oi.templates.empty())
  287. addObjectToRandomPool(oi);
  288. }
  289. }
  290. void TreasurePlacer::addPandoraBoxesWithExperience()
  291. {
  292. ObjectInfo oi;
  293. //pandora box with experience
  294. for(int i = 1; i < 5; i++)
  295. {
  296. oi.generateObject = [this, i]() -> CGObjectInstance *
  297. {
  298. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  299. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create(map.mapInstance->cb, nullptr));
  300. Rewardable::VisitInfo reward;
  301. reward.reward.heroExperience = i * 5000;
  302. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  303. obj->configuration.info.push_back(reward);
  304. return obj;
  305. };
  306. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  307. oi.value = i * generator.getConfig().pandoraMultiplierExperience;
  308. oi.probability = 20;
  309. if(!oi.templates.empty())
  310. addObjectToRandomPool(oi);
  311. }
  312. }
  313. void TreasurePlacer::addPandoraBoxesWithCreatures()
  314. {
  315. ObjectInfo oi;
  316. //pandora box with creatures
  317. for(auto * creature : creatures)
  318. {
  319. int creaturesAmount = creatureToCount(creature);
  320. if(!creaturesAmount)
  321. continue;
  322. oi.generateObject = [this, creature, creaturesAmount]() -> CGObjectInstance *
  323. {
  324. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  325. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create(map.mapInstance->cb, nullptr));
  326. Rewardable::VisitInfo reward;
  327. reward.reward.creatures.emplace_back(creature, creaturesAmount);
  328. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  329. obj->configuration.info.push_back(reward);
  330. return obj;
  331. };
  332. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  333. oi.value = static_cast<ui32>((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) / 3);
  334. oi.probability = 3;
  335. if(!oi.templates.empty())
  336. addObjectToRandomPool(oi);
  337. }
  338. }
  339. void TreasurePlacer::addPandoraBoxesWithSpells()
  340. {
  341. ObjectInfo oi;
  342. //Pandora with 12 spells of certain level
  343. for(int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  344. {
  345. oi.generateObject = [i, this]() -> CGObjectInstance *
  346. {
  347. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  348. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create(map.mapInstance->cb, nullptr));
  349. std::vector <const CSpell *> spells;
  350. for(auto spellID : VLC->spellh->getDefaultAllowed())
  351. {
  352. if(map.isAllowedSpell(spellID) && spellID.toSpell()->getLevel() == i)
  353. spells.push_back(spellID.toSpell());
  354. }
  355. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  356. Rewardable::VisitInfo reward;
  357. for(int j = 0; j < std::min(12, static_cast<int>(spells.size())); j++)
  358. {
  359. reward.reward.spells.push_back(spells[j]->id);
  360. }
  361. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  362. obj->configuration.info.push_back(reward);
  363. return obj;
  364. };
  365. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  366. oi.value = (i + 1) * generator.getConfig().pandoraMultiplierSpells; //5000 - 15000
  367. oi.probability = 2;
  368. if(!oi.templates.empty())
  369. addObjectToRandomPool(oi);
  370. }
  371. //Pandora with 15 spells of certain school
  372. for(int i = 0; i < 4; i++)
  373. {
  374. oi.generateObject = [i, this]() -> CGObjectInstance *
  375. {
  376. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  377. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create(map.mapInstance->cb, nullptr));
  378. std::vector <const CSpell *> spells;
  379. for(auto spellID : VLC->spellh->getDefaultAllowed())
  380. {
  381. if(map.isAllowedSpell(spellID) && spellID.toSpell()->hasSchool(SpellSchool(i)))
  382. spells.push_back(spellID.toSpell());
  383. }
  384. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  385. Rewardable::VisitInfo reward;
  386. for(int j = 0; j < std::min(15, static_cast<int>(spells.size())); j++)
  387. {
  388. reward.reward.spells.push_back(spells[j]->id);
  389. }
  390. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  391. obj->configuration.info.push_back(reward);
  392. return obj;
  393. };
  394. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  395. oi.value = generator.getConfig().pandoraSpellSchool;
  396. oi.probability = 2;
  397. if(!oi.templates.empty())
  398. addObjectToRandomPool(oi);
  399. }
  400. // Pandora box with 60 random spells
  401. oi.generateObject = [this]() -> CGObjectInstance *
  402. {
  403. auto factory = VLC->objtypeh->getHandlerFor(Obj::PANDORAS_BOX, 0);
  404. auto * obj = dynamic_cast<CGPandoraBox *>(factory->create(map.mapInstance->cb, nullptr));
  405. std::vector <const CSpell *> spells;
  406. for(auto spellID : VLC->spellh->getDefaultAllowed())
  407. {
  408. if(map.isAllowedSpell(spellID))
  409. spells.push_back(spellID.toSpell());
  410. }
  411. RandomGeneratorUtil::randomShuffle(spells, zone.getRand());
  412. Rewardable::VisitInfo reward;
  413. for(int j = 0; j < std::min(60, static_cast<int>(spells.size())); j++)
  414. {
  415. reward.reward.spells.push_back(spells[j]->id);
  416. }
  417. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  418. obj->configuration.info.push_back(reward);
  419. return obj;
  420. };
  421. oi.setTemplates(Obj::PANDORAS_BOX, 0, zone.getTerrainType());
  422. oi.value = generator.getConfig().pandoraSpell60;
  423. oi.probability = 2;
  424. if(!oi.templates.empty())
  425. addObjectToRandomPool(oi);
  426. }
  427. void TreasurePlacer::addSeerHuts()
  428. {
  429. //Seer huts with creatures or generic rewards
  430. ObjectInfo oi;
  431. if(zone.getConnectedZoneIds().size()) //Unlikely, but...
  432. {
  433. auto * qap = zone.getModificator<QuestArtifactPlacer>();
  434. if(!qap)
  435. {
  436. return; //TODO: throw?
  437. }
  438. const int questArtsRemaining = qap->getMaxQuestArtifactCount();
  439. if (!questArtsRemaining)
  440. {
  441. return;
  442. }
  443. //Generate Seer Hut one by one. Duplicated oi possible and should work fine.
  444. oi.maxPerZone = 1;
  445. std::vector<ObjectInfo> possibleSeerHuts;
  446. //14 creatures per town + 4 for each of gold / exp reward
  447. possibleSeerHuts.reserve(14 + 4 + 4);
  448. RandomGeneratorUtil::randomShuffle(creatures, zone.getRand());
  449. auto setRandomArtifact = [qap](CGSeerHut * obj)
  450. {
  451. ArtifactID artid = qap->drawRandomArtifact();
  452. obj->quest->mission.artifacts.push_back(artid);
  453. qap->addQuestArtifact(artid);
  454. };
  455. auto destroyObject = [qap](CGObjectInstance * obj)
  456. {
  457. auto * seer = dynamic_cast<CGSeerHut *>(obj);
  458. // Artifact can be used again
  459. ArtifactID artid = seer->quest->mission.artifacts.front();
  460. qap->addRandomArtifact(artid);
  461. qap->removeQuestArtifact(artid);
  462. };
  463. for(int i = 0; i < static_cast<int>(creatures.size()); i++)
  464. {
  465. auto * creature = creatures[i];
  466. int creaturesAmount = creatureToCount(creature);
  467. if(!creaturesAmount)
  468. continue;
  469. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  470. // FIXME: Remove duplicated code for gold, exp and creaure reward
  471. oi.generateObject = [cb=map.mapInstance->cb, creature, creaturesAmount, randomAppearance, setRandomArtifact]() -> CGObjectInstance *
  472. {
  473. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  474. auto * obj = dynamic_cast<CGSeerHut *>(factory->create(cb, nullptr));
  475. Rewardable::VisitInfo reward;
  476. reward.reward.creatures.emplace_back(creature->getId(), creaturesAmount);
  477. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  478. obj->configuration.info.push_back(reward);
  479. setRandomArtifact(obj);
  480. return obj;
  481. };
  482. oi.destroyObject = destroyObject;
  483. oi.probability = 3;
  484. oi.setTemplates(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  485. oi.value = static_cast<ui32>(((2 * (creature->getAIValue()) * creaturesAmount * (1 + static_cast<float>(map.getZoneCount(creature->getFaction())) / map.getTotalZoneCount())) - 4000) / 3);
  486. if (oi.value > zone.getMaxTreasureValue())
  487. {
  488. continue;
  489. }
  490. else
  491. {
  492. if(!oi.templates.empty())
  493. possibleSeerHuts.push_back(oi);
  494. }
  495. }
  496. static const int seerLevels = std::min(generator.getConfig().questValues.size(), generator.getConfig().questRewardValues.size());
  497. for(int i = 0; i < seerLevels; i++) //seems that code for exp and gold reward is similar
  498. {
  499. int randomAppearance = chooseRandomAppearance(zone.getRand(), Obj::SEER_HUT, zone.getTerrainType());
  500. oi.setTemplates(Obj::SEER_HUT, randomAppearance, zone.getTerrainType());
  501. oi.value = generator.getConfig().questValues[i];
  502. if (oi.value > zone.getMaxTreasureValue())
  503. {
  504. //Both variants have same value
  505. continue;
  506. }
  507. oi.probability = 10;
  508. oi.maxPerZone = 1;
  509. oi.generateObject = [i, randomAppearance, this, setRandomArtifact]() -> CGObjectInstance *
  510. {
  511. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  512. auto * obj = dynamic_cast<CGSeerHut *>(factory->create(map.mapInstance->cb, nullptr));
  513. Rewardable::VisitInfo reward;
  514. reward.reward.heroExperience = generator.getConfig().questRewardValues[i];
  515. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  516. obj->configuration.info.push_back(reward);
  517. setRandomArtifact(obj);
  518. return obj;
  519. };
  520. oi.destroyObject = destroyObject;
  521. if(!oi.templates.empty())
  522. possibleSeerHuts.push_back(oi);
  523. oi.generateObject = [i, randomAppearance, this, setRandomArtifact]() -> CGObjectInstance *
  524. {
  525. auto factory = VLC->objtypeh->getHandlerFor(Obj::SEER_HUT, randomAppearance);
  526. auto * obj = dynamic_cast<CGSeerHut *>(factory->create(map.mapInstance->cb, nullptr));
  527. Rewardable::VisitInfo reward;
  528. reward.reward.resources[EGameResID::GOLD] = generator.getConfig().questRewardValues[i];
  529. reward.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  530. obj->configuration.info.push_back(reward);
  531. setRandomArtifact(obj);
  532. return obj;
  533. };
  534. oi.destroyObject = destroyObject;
  535. if(!oi.templates.empty())
  536. possibleSeerHuts.push_back(oi);
  537. }
  538. if (possibleSeerHuts.empty())
  539. {
  540. return;
  541. }
  542. for (size_t i = 0; i < questArtsRemaining; i++)
  543. {
  544. addObjectToRandomPool(*RandomGeneratorUtil::nextItem(possibleSeerHuts, zone.getRand()));
  545. }
  546. }
  547. }
  548. void TreasurePlacer::setMaxPrisons(size_t count)
  549. {
  550. RecursiveLock lock(externalAccessMutex);
  551. maxPrisons = count;
  552. }
  553. size_t TreasurePlacer::getMaxPrisons() const
  554. {
  555. RecursiveLock lock(externalAccessMutex);
  556. return maxPrisons;
  557. }
  558. int TreasurePlacer::creatureToCount(const CCreature * creature) const
  559. {
  560. if(!creature->getAIValue() || tierValues.empty()) //bug #2681
  561. return 0; //this box won't be generated
  562. //Follow the rules from https://heroes.thelazy.net/index.php/Pandora%27s_Box
  563. int actualTier = creature->getLevel() > tierValues.size() ?
  564. tierValues.size() - 1 :
  565. creature->getLevel() - 1;
  566. float creaturesAmount = std::floor((static_cast<float>(tierValues[actualTier])) / creature->getAIValue());
  567. if (creaturesAmount < 1)
  568. {
  569. return 0;
  570. }
  571. else if(creaturesAmount <= 5)
  572. {
  573. //No change
  574. }
  575. else if(creaturesAmount <= 12)
  576. {
  577. creaturesAmount = std::ceil(creaturesAmount / 2) * 2;
  578. }
  579. else if(creaturesAmount <= 50)
  580. {
  581. creaturesAmount = std::round(creaturesAmount / 5) * 5;
  582. }
  583. else
  584. {
  585. creaturesAmount = std::round(creaturesAmount / 10) * 10;
  586. }
  587. return static_cast<int>(creaturesAmount);
  588. };
  589. bool TreasurePlacer::isGuardNeededForTreasure(int value)
  590. {// no guard in a zone with "monsters: none" and for small treasures; water zones cen get monster strength ZONE_NONE elsewhere if needed
  591. return zone.monsterStrength != EMonsterStrength::ZONE_NONE && value > minGuardedValue;
  592. }
  593. std::vector<ObjectInfo*> TreasurePlacer::prepareTreasurePile(const CTreasureInfo& treasureInfo)
  594. {
  595. std::vector<ObjectInfo*> objectInfos;
  596. int maxValue = treasureInfo.max;
  597. int minValue = treasureInfo.min;
  598. const ui32 desiredValue = zone.getRand().nextInt(minValue, maxValue);
  599. int currentValue = 0;
  600. bool hasLargeObject = false;
  601. while(currentValue <= static_cast<int>(desiredValue) - 100) //no objects with value below 100 are available
  602. {
  603. // FIXME: Pointer might be invalidated after this
  604. auto * oi = getRandomObject(desiredValue, currentValue, !hasLargeObject);
  605. if(!oi) //fail
  606. break;
  607. bool visitableFromTop = true;
  608. for(auto & t : oi->templates)
  609. if(!t->isVisitableFromTop())
  610. visitableFromTop = false;
  611. if(visitableFromTop)
  612. {
  613. objectInfos.push_back(oi);
  614. }
  615. else
  616. {
  617. objectInfos.insert(objectInfos.begin(), oi); //large object shall at first place
  618. hasLargeObject = true;
  619. }
  620. //remove from possible objects
  621. assert(oi->maxPerZone);
  622. oi->maxPerZone--;
  623. currentValue += oi->value;
  624. if (currentValue >= minValue)
  625. {
  626. // 50% chance to end right here
  627. if (zone.getRand().nextInt(0, 1) == 1)
  628. break;
  629. }
  630. }
  631. return objectInfos;
  632. }
  633. rmg::Object TreasurePlacer::constructTreasurePile(const std::vector<ObjectInfo*> & treasureInfos, bool densePlacement)
  634. {
  635. rmg::Object rmgObject;
  636. for(const auto & oi : treasureInfos)
  637. {
  638. auto blockedArea = rmgObject.getArea();
  639. auto entrableArea = rmgObject.getEntrableArea();
  640. auto accessibleArea = rmgObject.getAccessibleArea();
  641. if(rmgObject.instances().empty())
  642. {
  643. rmgObject.setValue(0);
  644. accessibleArea.add(int3());
  645. }
  646. CGObjectInstance * object = nullptr;
  647. if (oi->generateObject)
  648. {
  649. object = oi->generateObject();
  650. if(oi->templates.empty())
  651. {
  652. logGlobal->warn("Deleting randomized object with no templates: %s", object->getObjectName());
  653. oi->destroyObject(object);
  654. delete object;
  655. continue;
  656. }
  657. }
  658. else
  659. {
  660. logGlobal->error("ObjectInfo has no generateObject function! Templates: %d", oi->templates.size());
  661. continue;
  662. }
  663. auto templates = object->getObjectHandler()->getMostSpecificTemplates(zone.getTerrainType());
  664. if (templates.empty())
  665. {
  666. 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())));
  667. }
  668. object->appearance = *RandomGeneratorUtil::nextItem(templates, zone.getRand());
  669. //Put object in accessible area next to entrable area (excluding blockvis tiles)
  670. if (!entrableArea.empty())
  671. {
  672. auto entrableBorder = entrableArea.getBorderOutside();
  673. accessibleArea.erase_if([&](const int3 & tile)
  674. {
  675. return !entrableBorder.count(tile);
  676. });
  677. }
  678. auto & instance = rmgObject.addInstance(*object);
  679. rmgObject.setValue(rmgObject.getValue() + oi->value);
  680. instance.onCleared = oi->destroyObject;
  681. do
  682. {
  683. if(accessibleArea.empty())
  684. {
  685. //fail - fallback
  686. rmgObject.clear();
  687. return rmgObject;
  688. }
  689. std::vector<int3> bestPositions;
  690. if(densePlacement && !entrableArea.empty())
  691. {
  692. // Choose positon which has access to as many entrable tiles as possible
  693. int bestPositionsWeight = std::numeric_limits<int>::max();
  694. for(const auto & t : accessibleArea.getTilesVector())
  695. {
  696. instance.setPosition(t);
  697. auto currentAccessibleArea = rmgObject.getAccessibleArea();
  698. auto currentEntrableBorder = rmgObject.getEntrableArea().getBorderOutside();
  699. currentAccessibleArea.erase_if([&](const int3 & tile)
  700. {
  701. return !currentEntrableBorder.count(tile);
  702. });
  703. size_t w = currentAccessibleArea.getTilesVector().size();
  704. if(w > bestPositionsWeight)
  705. {
  706. // Minimum 1 position must be entrable
  707. bestPositions.clear();
  708. bestPositions.push_back(t);
  709. bestPositionsWeight = w;
  710. }
  711. else if(w == bestPositionsWeight)
  712. {
  713. bestPositions.push_back(t);
  714. }
  715. }
  716. }
  717. if (bestPositions.empty())
  718. {
  719. bestPositions = accessibleArea.getTilesVector();
  720. }
  721. int3 nextPos = *RandomGeneratorUtil::nextItem(bestPositions, zone.getRand());
  722. instance.setPosition(nextPos - rmgObject.getPosition());
  723. auto instanceAccessibleArea = instance.getAccessibleArea();
  724. if(instance.getBlockedArea().getTilesVector().size() == 1)
  725. {
  726. if(instance.object().appearance->isVisitableFromTop() && !instance.object().isBlockedVisitable())
  727. instanceAccessibleArea.add(instance.getVisitablePosition());
  728. }
  729. //Do not clean up after first object
  730. if(rmgObject.instances().size() == 1)
  731. break;
  732. if(!blockedArea.overlap(instance.getBlockedArea()) && accessibleArea.overlap(instanceAccessibleArea))
  733. break;
  734. //fail - new position
  735. accessibleArea.erase(nextPos);
  736. } while(true);
  737. }
  738. return rmgObject;
  739. }
  740. ObjectInfo * TreasurePlacer::getRandomObject(ui32 desiredValue, ui32 currentValue, bool allowLargeObjects)
  741. {
  742. std::vector<std::pair<ui32, ObjectInfo*>> thresholds; //handle complex object via pointer
  743. ui32 total = 0;
  744. //calculate actual treasure value range based on remaining value
  745. ui32 maxVal = desiredValue - currentValue;
  746. ui32 minValue = static_cast<ui32>(0.25f * (desiredValue - currentValue));
  747. for(ObjectInfo & oi : objects.getPossibleObjects()) //copy constructor turned out to be costly
  748. {
  749. if(oi.value > maxVal)
  750. break; //this assumes values are sorted in ascending order
  751. bool visitableFromTop = true;
  752. for(auto & t : oi.templates)
  753. if(!t->isVisitableFromTop())
  754. visitableFromTop = false;
  755. if(!visitableFromTop && !allowLargeObjects)
  756. continue;
  757. if(oi.value >= minValue && oi.maxPerZone > 0)
  758. {
  759. total += oi.probability;
  760. thresholds.emplace_back(total, &oi);
  761. }
  762. }
  763. if(thresholds.empty())
  764. {
  765. return nullptr;
  766. }
  767. else
  768. {
  769. int r = zone.getRand().nextInt(1, total);
  770. auto sorter = [](const std::pair<ui32, ObjectInfo *> & rhs, const ui32 lhs) -> bool
  771. {
  772. return static_cast<int>(rhs.first) < lhs;
  773. };
  774. //binary search = fastest
  775. auto it = std::lower_bound(thresholds.begin(), thresholds.end(), r, sorter);
  776. return it->second;
  777. }
  778. }
  779. void TreasurePlacer::createTreasures(ObjectManager& manager)
  780. {
  781. const int maxAttempts = 2;
  782. int mapMonsterStrength = map.getMapGenOptions().getMonsterStrength();
  783. 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
  784. static const int minGuardedValues[] = { 6500, 4167, 3000, 1833, 1333 };
  785. minGuardedValue = minGuardedValues[monsterStrength];
  786. const auto blockingGuardMaxValue = zone.getMaxTreasureValue() / 3;
  787. auto valueComparator = [](const CTreasureInfo& lhs, const CTreasureInfo& rhs) -> bool
  788. {
  789. return lhs.max > rhs.max;
  790. };
  791. auto restoreZoneLimits = [](const std::vector<ObjectInfo*>& treasurePile)
  792. {
  793. for (auto* oi : treasurePile)
  794. {
  795. oi->maxPerZone++;
  796. }
  797. };
  798. rmg::Area roads;
  799. auto rp = zone.getModificator<RoadPlacer>();
  800. if (rp)
  801. {
  802. roads = rp->getRoads();
  803. }
  804. rmg::Area nextToRoad(roads.getBorderOutside());
  805. //place biggest treasures first at large distance, place smaller ones inbetween
  806. auto treasureInfo = zone.getTreasureInfo();
  807. boost::sort(treasureInfo, valueComparator);
  808. //sort treasures by ascending value so we can stop checking treasures with too high value
  809. objects.sortPossibleObjects();
  810. const size_t size = zone.area()->getTilesVector().size();
  811. int totalDensity = 0;
  812. // FIXME: No need to use iterator here
  813. for (auto t = treasureInfo.begin(); t != treasureInfo.end(); t++)
  814. {
  815. std::vector<rmg::Object> treasures;
  816. //discard objects with too high value to be ever placed
  817. objects.discardObjectsAboveValue(t->max);
  818. totalDensity += t->density;
  819. const int DENSITY_CONSTANT = 400;
  820. size_t count = (size * t->density) / DENSITY_CONSTANT;
  821. const float minDistance = std::max<float>(std::sqrt(std::min<ui32>(t->min, 30000) / 10.0f / totalDensity), 1.0f);
  822. size_t emergencyLoopFinish = 0;
  823. while(treasures.size() < count && emergencyLoopFinish < count)
  824. {
  825. auto treasurePileInfos = prepareTreasurePile(*t);
  826. if (treasurePileInfos.empty())
  827. {
  828. emergencyLoopFinish++; //Exit potentially infinite loop for bad settings
  829. continue;
  830. }
  831. int value = std::accumulate(treasurePileInfos.begin(), treasurePileInfos.end(), 0,
  832. [](int v, const ObjectInfo* oi)
  833. {
  834. return v + oi->value;
  835. });
  836. const ui32 maxPileGenerationAttempts = 2;
  837. for (ui32 attempt = 0; attempt < maxPileGenerationAttempts; attempt++)
  838. {
  839. auto rmgObject = constructTreasurePile(treasurePileInfos, attempt == maxAttempts);
  840. if (rmgObject.instances().empty())
  841. {
  842. // Restore once if all attempts failed
  843. if (attempt == (maxPileGenerationAttempts - 1))
  844. {
  845. restoreZoneLimits(treasurePileInfos);
  846. }
  847. continue;
  848. }
  849. //guard treasure pile
  850. bool guarded = isGuardNeededForTreasure(value);
  851. if (guarded)
  852. guarded = manager.addGuard(rmgObject, value);
  853. treasures.push_back(rmgObject);
  854. break;
  855. }
  856. }
  857. for (auto& rmgObject : treasures)
  858. {
  859. const bool guarded = rmgObject.isGuarded();
  860. auto path = rmg::Path::invalid();
  861. {
  862. Zone::Lock lock(zone.areaMutex); //We are going to subtract this area
  863. auto searchArea = zone.areaPossible().get();
  864. searchArea.erase_if([this, &minDistance](const int3& tile) -> bool
  865. {
  866. auto ti = map.getTileInfo(tile);
  867. return (ti.getNearestObjectDistance() < minDistance);
  868. });
  869. if (guarded)
  870. {
  871. searchArea.subtract(roads);
  872. path = manager.placeAndConnectObject(searchArea, rmgObject, [this, &rmgObject, &minDistance, &manager, blockingGuardMaxValue, &roads, &nextToRoad](const int3& tile)
  873. {
  874. float bestDistance = 10e9;
  875. for (const auto& t : rmgObject.getArea().getTilesVector())
  876. {
  877. float distance = map.getTileInfo(t).getNearestObjectDistance();
  878. if (distance < minDistance)
  879. return -1.f;
  880. else
  881. vstd::amin(bestDistance, distance);
  882. }
  883. // Guard cannot be adjacent to road, but blocked side of an object could be
  884. if (rmgObject.getValue() > blockingGuardMaxValue && nextToRoad.contains(rmgObject.getGuardPos()))
  885. {
  886. return -1.f;
  887. }
  888. const auto & guardedArea = rmgObject.instances().back()->getAccessibleArea();
  889. const auto areaToBlock = rmgObject.getAccessibleArea(true) - guardedArea;
  890. if (zone.freePaths()->overlap(areaToBlock) || roads.overlap(areaToBlock) || manager.getVisitableArea().overlap(areaToBlock))
  891. return -1.f;
  892. // Add huge penalty for objects hiding roads
  893. if (rmgObject.getBorderAbove().overlap(roads))
  894. bestDistance /= 10.0f;
  895. return bestDistance;
  896. }, guarded, false, ObjectManager::OptimizeType::BOTH);
  897. }
  898. else
  899. {
  900. // Do not place non-removable objects on roads
  901. if (!rmgObject.getRemovableArea().contains(rmgObject.getArea()))
  902. {
  903. searchArea.subtract(roads);
  904. }
  905. path = manager.placeAndConnectObject(searchArea, rmgObject, minDistance, guarded, false, ObjectManager::OptimizeType::DISTANCE);
  906. }
  907. }
  908. if (path.valid())
  909. {
  910. #ifdef TREASURE_PLACER_LOG
  911. treasureArea.unite(rmgObject.getArea());
  912. if (guarded)
  913. {
  914. guards.unite(rmgObject.instances().back()->getBlockedArea());
  915. auto guardedArea = rmgObject.instances().back()->getAccessibleArea();
  916. auto areaToBlock = rmgObject.getAccessibleArea(true) - guardedArea;
  917. treasureBlockArea.unite(areaToBlock);
  918. }
  919. #endif
  920. zone.connectPath(path);
  921. manager.placeObject(rmgObject, guarded, true);
  922. }
  923. }
  924. }
  925. }
  926. char TreasurePlacer::dump(const int3 & t)
  927. {
  928. if(guards.contains(t))
  929. return '!';
  930. if(treasureArea.contains(t))
  931. return '$';
  932. if(treasureBlockArea.contains(t))
  933. return '*';
  934. return Modificator::dump(t);
  935. }
  936. void TreasurePlacer::ObjectPool::addObject(const ObjectInfo & info)
  937. {
  938. possibleObjects.push_back(info);
  939. }
  940. void TreasurePlacer::ObjectPool::updateObject(MapObjectID id, MapObjectSubID subid, ObjectInfo info)
  941. {
  942. /*
  943. Handle separately:
  944. - Dwellings
  945. - Prisons
  946. - Seer huts (quests)
  947. - Pandora Boxes
  948. */
  949. // FIXME: This will drop all templates
  950. customObjects[CompoundMapObjectID(id, subid)] = info;
  951. }
  952. void TreasurePlacer::ObjectPool::patchWithZoneConfig(const Zone & zone, TreasurePlacer * tp)
  953. {
  954. // FIXME: Wycina wszystkie obiekty poza pandorami i dwellami :?
  955. // Copy standard objects if they are not already modified
  956. /*
  957. for (const auto & object : possibleObjects)
  958. {
  959. for (const auto & templ : object.templates)
  960. {
  961. // FIXME: Objects with same temmplates (Pandora boxes) are not added
  962. CompoundMapObjectID key(templ->id, templ->subid);
  963. if (!vstd::contains(customObjects, key))
  964. {
  965. customObjects[key] = object;
  966. }
  967. }
  968. }
  969. */
  970. auto bannedObjectCategories = zone.getBannedObjectCategories();
  971. auto categoriesSet = std::unordered_set<ObjectConfig::EObjectCategory>(bannedObjectCategories.begin(), bannedObjectCategories.end());
  972. vstd::erase_if(possibleObjects, [this, &categoriesSet](const ObjectInfo & oi) -> bool
  973. {
  974. auto temp = oi.templates.front();
  975. auto category = getObjectCategory(CompoundMapObjectID(temp->id, temp->subid));
  976. if (categoriesSet.count(category))
  977. {
  978. logGlobal->info("Removing object %s from possible objects", oi.templates.front()->stringID);
  979. /* FIXME:
  980. Removing object normal from possible objects
  981. Removing object base from possible objects
  982. Removing object default from possible objects
  983. */
  984. return true;
  985. }
  986. return false;
  987. });
  988. auto bannedObjects = zone.getBannedObjects();
  989. auto bannedObjectsSet = std::set<CompoundMapObjectID>(bannedObjects.begin(), bannedObjects.end());
  990. vstd::erase_if(possibleObjects, [&bannedObjectsSet](const ObjectInfo & object)
  991. {
  992. for (const auto & templ : object.templates)
  993. {
  994. CompoundMapObjectID key(templ->id, templ->subid);
  995. if (bannedObjectsSet.count(key))
  996. {
  997. // FIXME: Stopped working, nothing is banned
  998. logGlobal->info("Banning object %s from possible objects", templ->stringID);
  999. return true;
  1000. }
  1001. }
  1002. return false;
  1003. });
  1004. auto configuredObjects = zone.getConfiguredObjects();
  1005. // FIXME: Access TreasurePlacer from ObjectPool
  1006. for (auto & object : configuredObjects)
  1007. {
  1008. auto temp = object.templates.front();
  1009. tp->setBasicProperties(object, CompoundMapObjectID(temp->id, temp->subid));
  1010. addObject(object);
  1011. logGlobal->info("Added custom object of type %d.%d", temp->id, temp->subid);
  1012. }
  1013. // TODO: Overwrite or add to possibleObjects
  1014. // FIXME: Protect with mutex as well?
  1015. /*
  1016. for (const auto & customObject : customObjects)
  1017. {
  1018. addObject(customObject.second);
  1019. }
  1020. */
  1021. // TODO: Consider adding custom Pandora boxes with arbitrary content
  1022. }
  1023. std::vector<ObjectInfo> & TreasurePlacer::ObjectPool::getPossibleObjects()
  1024. {
  1025. return possibleObjects;
  1026. }
  1027. void TreasurePlacer::ObjectPool::sortPossibleObjects()
  1028. {
  1029. boost::sort(possibleObjects, [](const ObjectInfo& oi1, const ObjectInfo& oi2) -> bool
  1030. {
  1031. return oi1.value < oi2.value;
  1032. });
  1033. }
  1034. void TreasurePlacer::ObjectPool::discardObjectsAboveValue(ui32 value)
  1035. {
  1036. vstd::erase_if(possibleObjects, [value](const ObjectInfo& oi) -> bool
  1037. {
  1038. return oi.value > value;
  1039. });
  1040. }
  1041. ObjectConfig::EObjectCategory TreasurePlacer::ObjectPool::getObjectCategory(CompoundMapObjectID id)
  1042. {
  1043. auto name = VLC->objtypeh->getObjectHandlerName(id.primaryID);
  1044. if (name == "configurable")
  1045. {
  1046. // TODO: Access Rewardable::Info by ID
  1047. auto handler = VLC->objtypeh->getHandlerFor(id.primaryID, id.secondaryID);
  1048. if (!handler)
  1049. {
  1050. return ObjectConfig::EObjectCategory::NONE;
  1051. }
  1052. auto temp = handler->getTemplates().front();
  1053. auto info = handler->getObjectInfo(temp);
  1054. if (info->givesResources())
  1055. {
  1056. return ObjectConfig::EObjectCategory::RESOURCE;
  1057. }
  1058. else if (info->givesArtifacts())
  1059. {
  1060. return ObjectConfig::EObjectCategory::RANDOM_ARTIFACT;
  1061. }
  1062. else if (info->givesBonuses())
  1063. {
  1064. return ObjectConfig::EObjectCategory::BONUS;
  1065. }
  1066. return ObjectConfig::EObjectCategory::OTHER;
  1067. }
  1068. else if (name == "dwelling" || name == "randomDwelling")
  1069. {
  1070. // TODO: Special handling for different tiers
  1071. return ObjectConfig::EObjectCategory::DWELLING;
  1072. }
  1073. else if (name == "bank")
  1074. return ObjectConfig::EObjectCategory::CREATURE_BANK;
  1075. else if (name == "market")
  1076. return ObjectConfig::EObjectCategory::OTHER;
  1077. else if (name == "hillFort")
  1078. return ObjectConfig::EObjectCategory::OTHER;
  1079. else if (name == "resource" || name == "randomResource")
  1080. return ObjectConfig::EObjectCategory::RESOURCE;
  1081. else if (name == "randomArtifact") //"artifact"
  1082. return ObjectConfig::EObjectCategory::RANDOM_ARTIFACT;
  1083. else if (name == "denOfThieves")
  1084. return ObjectConfig::EObjectCategory::OTHER;
  1085. else if (name == "lighthouse")
  1086. {
  1087. return ObjectConfig::EObjectCategory::BONUS;
  1088. }
  1089. else if (name == "magi")
  1090. {
  1091. // TODO: By default, both eye and hut are banned in every zone
  1092. return ObjectConfig::EObjectCategory::OTHER;
  1093. }
  1094. else if (name == "mine")
  1095. return ObjectConfig::EObjectCategory::RESOURCE_GENERATOR;
  1096. else if (name == "pandora")
  1097. return ObjectConfig::EObjectCategory::PANDORAS_BOX;
  1098. else if (name == "prison")
  1099. {
  1100. // TODO: Prisons should be configurable
  1101. return ObjectConfig::EObjectCategory::OTHER;
  1102. }
  1103. else if (name == "questArtifact")
  1104. {
  1105. // TODO: There are no dedicated quest artifacts, needs extra logic
  1106. return ObjectConfig::EObjectCategory::QUEST_ARTIFACT;
  1107. }
  1108. else if (name == "seerHut")
  1109. {
  1110. return ObjectConfig::EObjectCategory::SEER_HUT;
  1111. }
  1112. else if (name == "siren")
  1113. return ObjectConfig::EObjectCategory::BONUS;
  1114. else if (name == "obelisk")
  1115. return ObjectConfig::EObjectCategory::OTHER;
  1116. // TODO: ObjectConfig::EObjectCategory::SPELL_SCROLL
  1117. // Not interesting for us
  1118. return ObjectConfig::EObjectCategory::NONE;
  1119. }
  1120. VCMI_LIB_NAMESPACE_END