TreasurePlacer.cpp 38 KB

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