CRmgTemplateZone.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. /*
  2. * CRmgTemplateZone.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 "CRmgTemplateZone.h"
  12. #include "../mapping/CMapEditManager.h"
  13. #include "../mapping/CMap.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../CTownHandler.h"
  16. #include "../CCreatureHandler.h"
  17. #include "../CSpellHandler.h" //for choosing random spells
  18. #include "../mapObjects/CommonConstructors.h"
  19. #include "../mapObjects/MapObjects.h" //needed to resolve templates for CommonConstructors.h
  20. #include "../mapObjects/CGPandoraBox.h"
  21. #include "../mapObjects/CRewardableObject.h"
  22. class CMap;
  23. class CMapEditManager;
  24. //class CGObjectInstance;
  25. CRmgTemplateZone::CTownInfo::CTownInfo() : townCount(0), castleCount(0), townDensity(0), castleDensity(0)
  26. {
  27. }
  28. int CRmgTemplateZone::CTownInfo::getTownCount() const
  29. {
  30. return townCount;
  31. }
  32. void CRmgTemplateZone::CTownInfo::setTownCount(int value)
  33. {
  34. if(value < 0)
  35. throw rmgException("Negative value for town count not allowed.");
  36. townCount = value;
  37. }
  38. int CRmgTemplateZone::CTownInfo::getCastleCount() const
  39. {
  40. return castleCount;
  41. }
  42. void CRmgTemplateZone::CTownInfo::setCastleCount(int value)
  43. {
  44. if(value < 0)
  45. throw rmgException("Negative value for castle count not allowed.");
  46. castleCount = value;
  47. }
  48. int CRmgTemplateZone::CTownInfo::getTownDensity() const
  49. {
  50. return townDensity;
  51. }
  52. void CRmgTemplateZone::CTownInfo::setTownDensity(int value)
  53. {
  54. if(value < 0)
  55. throw rmgException("Negative value for town density not allowed.");
  56. townDensity = value;
  57. }
  58. int CRmgTemplateZone::CTownInfo::getCastleDensity() const
  59. {
  60. return castleDensity;
  61. }
  62. void CRmgTemplateZone::CTownInfo::setCastleDensity(int value)
  63. {
  64. if(value < 0)
  65. throw rmgException("Negative value for castle density not allowed.");
  66. castleDensity = value;
  67. }
  68. CTileInfo::CTileInfo():nearestObjectDistance(INT_MAX), terrain(ETerrainType::WRONG)
  69. {
  70. occupied = ETileType::POSSIBLE; //all tiles are initially possible to place objects or passages
  71. }
  72. float CTileInfo::getNearestObjectDistance() const
  73. {
  74. return nearestObjectDistance;
  75. }
  76. void CTileInfo::setNearestObjectDistance(float value)
  77. {
  78. nearestObjectDistance = std::max<float>(0, value); //never negative (or unitialized)
  79. }
  80. bool CTileInfo::shouldBeBlocked() const
  81. {
  82. return occupied == ETileType::BLOCKED;
  83. }
  84. bool CTileInfo::isBlocked() const
  85. {
  86. return occupied == ETileType::BLOCKED || occupied == ETileType::USED;
  87. }
  88. bool CTileInfo::isPossible() const
  89. {
  90. return occupied == ETileType::POSSIBLE;
  91. }
  92. bool CTileInfo::isFree() const
  93. {
  94. return occupied == ETileType::FREE;
  95. }
  96. bool CTileInfo::isUsed() const
  97. {
  98. return occupied == ETileType::USED;
  99. }
  100. void CTileInfo::setOccupied(ETileType::ETileType value)
  101. {
  102. occupied = value;
  103. }
  104. ETerrainType CTileInfo::getTerrainType() const
  105. {
  106. return terrain;
  107. }
  108. void CTileInfo::setTerrainType(ETerrainType value)
  109. {
  110. terrain = value;
  111. }
  112. CRmgTemplateZone::CRmgTemplateZone() :
  113. id(0),
  114. type(ETemplateZoneType::PLAYER_START),
  115. size(1),
  116. townsAreSameType(false),
  117. matchTerrainToTown(true),
  118. townType(ETownType::NEUTRAL),
  119. terrainType (ETerrainType::GRASS),
  120. zoneMonsterStrength(EMonsterStrength::ZONE_NORMAL)
  121. {
  122. terrainTypes = getDefaultTerrainTypes();
  123. }
  124. TRmgTemplateZoneId CRmgTemplateZone::getId() const
  125. {
  126. return id;
  127. }
  128. void CRmgTemplateZone::setId(TRmgTemplateZoneId value)
  129. {
  130. if(value <= 0)
  131. throw rmgException(boost::to_string(boost::format("Zone %d id should be greater than 0.") %id));
  132. id = value;
  133. }
  134. ETemplateZoneType::ETemplateZoneType CRmgTemplateZone::getType() const
  135. {
  136. return type;
  137. }
  138. void CRmgTemplateZone::setType(ETemplateZoneType::ETemplateZoneType value)
  139. {
  140. type = value;
  141. }
  142. int CRmgTemplateZone::getSize() const
  143. {
  144. return size;
  145. }
  146. void CRmgTemplateZone::setSize(int value)
  147. {
  148. if(value <= 0)
  149. throw rmgException(boost::to_string(boost::format("Zone %d size needs to be greater than 0.") % id));
  150. size = value;
  151. }
  152. boost::optional<int> CRmgTemplateZone::getOwner() const
  153. {
  154. return owner;
  155. }
  156. void CRmgTemplateZone::setOwner(boost::optional<int> value)
  157. {
  158. if(!(*value >= 0 && *value <= PlayerColor::PLAYER_LIMIT_I))
  159. throw rmgException(boost::to_string(boost::format ("Owner of zone %d has to be in range 0 to max player count.") %id));
  160. owner = value;
  161. }
  162. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getPlayerTowns() const
  163. {
  164. return playerTowns;
  165. }
  166. void CRmgTemplateZone::setPlayerTowns(const CTownInfo & value)
  167. {
  168. playerTowns = value;
  169. }
  170. const CRmgTemplateZone::CTownInfo & CRmgTemplateZone::getNeutralTowns() const
  171. {
  172. return neutralTowns;
  173. }
  174. void CRmgTemplateZone::setNeutralTowns(const CTownInfo & value)
  175. {
  176. neutralTowns = value;
  177. }
  178. bool CRmgTemplateZone::getTownsAreSameType() const
  179. {
  180. return townsAreSameType;
  181. }
  182. void CRmgTemplateZone::setTownsAreSameType(bool value)
  183. {
  184. townsAreSameType = value;
  185. }
  186. const std::set<TFaction> & CRmgTemplateZone::getTownTypes() const
  187. {
  188. return townTypes;
  189. }
  190. void CRmgTemplateZone::setTownTypes(const std::set<TFaction> & value)
  191. {
  192. townTypes = value;
  193. }
  194. void CRmgTemplateZone::setMonsterTypes(const std::set<TFaction> & value)
  195. {
  196. monsterTypes = value;
  197. }
  198. std::set<TFaction> CRmgTemplateZone::getDefaultTownTypes() const
  199. {
  200. std::set<TFaction> defaultTowns;
  201. auto towns = VLC->townh->getDefaultAllowed();
  202. for(int i = 0; i < towns.size(); ++i)
  203. {
  204. if(towns[i]) defaultTowns.insert(i);
  205. }
  206. return defaultTowns;
  207. }
  208. bool CRmgTemplateZone::getMatchTerrainToTown() const
  209. {
  210. return matchTerrainToTown;
  211. }
  212. void CRmgTemplateZone::setMatchTerrainToTown(bool value)
  213. {
  214. matchTerrainToTown = value;
  215. }
  216. const std::set<ETerrainType> & CRmgTemplateZone::getTerrainTypes() const
  217. {
  218. return terrainTypes;
  219. }
  220. void CRmgTemplateZone::setTerrainTypes(const std::set<ETerrainType> & value)
  221. {
  222. assert(value.find(ETerrainType::WRONG) == value.end() && value.find(ETerrainType::BORDER) == value.end() &&
  223. value.find(ETerrainType::WATER) == value.end() && value.find(ETerrainType::ROCK) == value.end());
  224. terrainTypes = value;
  225. }
  226. std::set<ETerrainType> CRmgTemplateZone::getDefaultTerrainTypes() const
  227. {
  228. std::set<ETerrainType> terTypes;
  229. static const ETerrainType::EETerrainType allowedTerTypes[] = {ETerrainType::DIRT, ETerrainType::SAND, ETerrainType::GRASS, ETerrainType::SNOW,
  230. ETerrainType::SWAMP, ETerrainType::ROUGH, ETerrainType::SUBTERRANEAN, ETerrainType::LAVA};
  231. for (auto & allowedTerType : allowedTerTypes)
  232. terTypes.insert(allowedTerType);
  233. return terTypes;
  234. }
  235. void CRmgTemplateZone::setMinesAmount (TResource res, ui16 amount)
  236. {
  237. mines[res] = amount;
  238. }
  239. std::map<TResource, ui16> CRmgTemplateZone::getMinesInfo() const
  240. {
  241. return mines;
  242. }
  243. void CRmgTemplateZone::addConnection(TRmgTemplateZoneId otherZone)
  244. {
  245. connections.push_back (otherZone);
  246. }
  247. std::vector<TRmgTemplateZoneId> CRmgTemplateZone::getConnections() const
  248. {
  249. return connections;
  250. }
  251. void CRmgTemplateZone::setMonsterStrength (EMonsterStrength::EMonsterStrength val)
  252. {
  253. assert (vstd::iswithin(val, EMonsterStrength::ZONE_WEAK, EMonsterStrength::ZONE_STRONG));
  254. zoneMonsterStrength = val;
  255. }
  256. void CRmgTemplateZone::addTreasureInfo(CTreasureInfo & info)
  257. {
  258. treasureInfo.push_back(info);
  259. }
  260. std::vector<CTreasureInfo> CRmgTemplateZone::getTreasureInfo()
  261. {
  262. return treasureInfo;
  263. }
  264. std::set<int3>* CRmgTemplateZone::getFreePaths()
  265. {
  266. return &freePaths;
  267. }
  268. float3 CRmgTemplateZone::getCenter() const
  269. {
  270. return center;
  271. }
  272. void CRmgTemplateZone::setCenter(const float3 &f)
  273. {
  274. //limit boundaries to (0,1) square
  275. center = float3 (std::min(std::max(f.x, 0.f), 1.f), std::min(std::max(f.y, 0.f), 1.f), f.z);
  276. }
  277. bool CRmgTemplateZone::pointIsIn(int x, int y)
  278. {
  279. return true;
  280. }
  281. int3 CRmgTemplateZone::getPos() const
  282. {
  283. return pos;
  284. }
  285. void CRmgTemplateZone::setPos(const int3 &Pos)
  286. {
  287. pos = Pos;
  288. }
  289. void CRmgTemplateZone::addTile (const int3 &pos)
  290. {
  291. tileinfo.insert(pos);
  292. }
  293. std::set<int3> CRmgTemplateZone::getTileInfo () const
  294. {
  295. return tileinfo;
  296. }
  297. void CRmgTemplateZone::discardDistantTiles (CMapGenerator* gen, float distance)
  298. {
  299. //TODO: mark tiles beyond zone as unavailable, but allow to connect with adjacent zones
  300. //for (auto tile : tileinfo)
  301. //{
  302. // if (tile.dist2d(this->pos) > distance)
  303. // {
  304. // gen->setOccupied(tile, ETileType::USED);
  305. // //gen->setOccupied(tile, ETileType::BLOCKED); //fixme: crash at rendering?
  306. // }
  307. //}
  308. vstd::erase_if (tileinfo, [distance, this](const int3 &tile) -> bool
  309. {
  310. return tile.dist2d(this->pos) > distance;
  311. });
  312. }
  313. void CRmgTemplateZone::initFreeTiles (CMapGenerator* gen)
  314. {
  315. vstd::copy_if (tileinfo, vstd::set_inserter(possibleTiles), [gen](const int3 &tile) -> bool
  316. {
  317. return gen->isPossible(tile);
  318. });
  319. }
  320. void CRmgTemplateZone::createBorder(CMapGenerator* gen)
  321. {
  322. for (auto tile : tileinfo)
  323. {
  324. gen->foreach_neighbour (tile, [this, gen](int3 &pos)
  325. {
  326. if (!vstd::contains(this->tileinfo, pos))
  327. {
  328. gen->foreach_neighbour (pos, [this, gen](int3 &pos)
  329. {
  330. if (gen->isPossible(pos))
  331. gen->setOccupied (pos, ETileType::BLOCKED);
  332. });
  333. }
  334. });
  335. }
  336. }
  337. void CRmgTemplateZone::fractalize(CMapGenerator* gen)
  338. {
  339. for (auto tile : tileinfo)
  340. {
  341. if (gen->isFree(tile))
  342. freePaths.insert(tile);
  343. }
  344. std::vector<int3> clearedTiles (freePaths.begin(), freePaths.end());
  345. std::set<int3> possibleTiles;
  346. std::set<int3> tilesToClear; //will be set clear
  347. std::set<int3> tilesToIgnore; //will be erased in this iteration
  348. //the more treasure density, the greater distance between paths. Scaling is experimental.
  349. int totalDensity = 0;
  350. for (auto ti : treasureInfo)
  351. totalDensity =+ ti.density;
  352. const float minDistance = std::sqrt(totalDensity * 3);
  353. for (auto tile : tileinfo)
  354. {
  355. if (gen->isFree(tile))
  356. clearedTiles.push_back(tile);
  357. else if (gen->isPossible(tile))
  358. possibleTiles.insert(tile);
  359. }
  360. assert (clearedTiles.size()); //this should come from zone connections
  361. while (possibleTiles.size())
  362. {
  363. //link tiles in random order
  364. std::vector<int3> tilesToMakePath(possibleTiles.begin(), possibleTiles.end());
  365. RandomGeneratorUtil::randomShuffle(tilesToMakePath, gen->rand);
  366. for (auto tileToMakePath : tilesToMakePath)
  367. {
  368. //find closest free tile
  369. float currentDistance = 1e10;
  370. int3 closestTile (-1,-1,-1);
  371. for (auto clearTile : clearedTiles)
  372. {
  373. float distance = tileToMakePath.dist2d(clearTile);
  374. if (distance < currentDistance)
  375. {
  376. currentDistance = distance;
  377. closestTile = clearTile;
  378. }
  379. if (currentDistance <= minDistance)
  380. {
  381. //this tile is close enough. Forget about it and check next one
  382. tilesToIgnore.insert (tileToMakePath);
  383. break;
  384. }
  385. }
  386. //if tiles is not close enough, make path to it
  387. if (currentDistance > minDistance)
  388. {
  389. crunchPath (gen, tileToMakePath, closestTile, id, &tilesToClear);
  390. break; //next iteration - use already cleared tiles
  391. }
  392. }
  393. for (auto tileToClear : tilesToClear)
  394. {
  395. //move cleared tiles from one set to another
  396. clearedTiles.push_back(tileToClear);
  397. vstd::erase_if_present(possibleTiles, tileToClear);
  398. }
  399. for (auto tileToClear : tilesToIgnore)
  400. {
  401. //these tiles are already connected, ignore them
  402. vstd::erase_if_present(possibleTiles, tileToClear);
  403. }
  404. if (tilesToClear.empty()) //nothing else can be done (?)
  405. break;
  406. tilesToClear.clear(); //empty this container
  407. tilesToIgnore.clear();
  408. }
  409. for (auto tile : clearedTiles)
  410. {
  411. freePaths.insert(tile);
  412. }
  413. if (0) //enable to debug
  414. {
  415. std::ofstream out(boost::to_string(boost::format("zone %d") % id));
  416. int levels = gen->map->twoLevel ? 2 : 1;
  417. int width = gen->map->width;
  418. int height = gen->map->height;
  419. for (int k = 0; k < levels; k++)
  420. {
  421. for(int j=0; j<height; j++)
  422. {
  423. for (int i=0; i<width; i++)
  424. {
  425. out << (int)vstd::contains(freePaths, int3(i,j,k));
  426. }
  427. out << std::endl;
  428. }
  429. out << std::endl;
  430. }
  431. }
  432. //logGlobal->infoStream() << boost::format ("Zone %d subdivided fractally") %id;
  433. }
  434. bool CRmgTemplateZone::crunchPath (CMapGenerator* gen, const int3 &src, const int3 &dst, TRmgTemplateZoneId zone, std::set<int3>* clearedTiles)
  435. {
  436. /*
  437. make shortest path with free tiles, reachning dst or closest already free tile. Avoid blocks.
  438. do not leave zone border
  439. */
  440. bool result = false;
  441. bool end = false;
  442. int3 currentPos = src;
  443. float distance = currentPos.dist2dSQ (dst);
  444. while (!end)
  445. {
  446. if (currentPos == dst)
  447. {
  448. result = true;
  449. break;
  450. }
  451. auto lastDistance = distance;
  452. gen->foreach_neighbour (currentPos, [this, gen, &currentPos, dst, &distance, &result, &end, clearedTiles](int3 &pos)
  453. {
  454. if (!result) //not sure if lambda is worth it...
  455. {
  456. if (pos == dst)
  457. {
  458. result = true;
  459. end = true;
  460. }
  461. if (pos.dist2dSQ (dst) < distance)
  462. {
  463. if (!gen->isBlocked(pos))
  464. {
  465. if (vstd::contains (tileinfo, pos))
  466. {
  467. if (gen->isPossible(pos))
  468. {
  469. gen->setOccupied (pos, ETileType::FREE);
  470. if (clearedTiles)
  471. clearedTiles->insert(pos);
  472. currentPos = pos;
  473. distance = currentPos.dist2dSQ (dst);
  474. }
  475. else if (gen->isFree(pos))
  476. {
  477. end = true;
  478. result = true;
  479. }
  480. }
  481. }
  482. }
  483. }
  484. });
  485. int3 anotherPos(-1, -1, -1);
  486. if (!(result || distance < lastDistance)) //we do not advance, use more advaced pathfinding algorithm?
  487. {
  488. //try any nearby tiles, even if its not closer than current
  489. float lastDistance = 2 * distance; //start with significantly larger value
  490. gen->foreach_neighbour(currentPos, [this, gen, &currentPos, dst, &lastDistance, &anotherPos, &end, clearedTiles](int3 &pos)
  491. {
  492. if (currentPos.dist2dSQ(dst) < lastDistance) //try closest tiles from all surrounding unused tiles
  493. {
  494. if (vstd::contains(tileinfo, pos))
  495. {
  496. if (gen->isPossible(pos))
  497. {
  498. if (clearedTiles)
  499. clearedTiles->insert(pos);
  500. anotherPos = pos;
  501. lastDistance = currentPos.dist2dSQ(dst);
  502. }
  503. }
  504. }
  505. });
  506. if (anotherPos.valid())
  507. {
  508. if (clearedTiles)
  509. clearedTiles->insert(anotherPos);
  510. gen->setOccupied(anotherPos, ETileType::FREE);
  511. currentPos = anotherPos;
  512. }
  513. }
  514. if (!(result || distance < lastDistance || anotherPos.valid()))
  515. {
  516. logGlobal->warnStream() << boost::format("No tile closer than %s found on path from %s to %s") % currentPos %src %dst;
  517. break;
  518. }
  519. }
  520. return result;
  521. }
  522. void CRmgTemplateZone::addRequiredObject(CGObjectInstance * obj, si32 strength)
  523. {
  524. requiredObjects.push_back(std::make_pair(obj, strength));
  525. }
  526. void CRmgTemplateZone::addCloseObject(CGObjectInstance * obj, si32 strength)
  527. {
  528. closeObjects.push_back(std::make_pair(obj, strength));
  529. }
  530. bool CRmgTemplateZone::addMonster(CMapGenerator* gen, int3 &pos, si32 strength, bool clearSurroundingTiles, bool zoneGuard)
  531. {
  532. //precalculate actual (randomized) monster strength based on this post
  533. //http://forum.vcmi.eu/viewtopic.php?p=12426#12426
  534. int mapMonsterStrength = gen->mapGenOptions->getMonsterStrength();
  535. int monsterStrength = (zoneGuard ? 0 : zoneMonsterStrength) + mapMonsterStrength - 1; //array index from 0 to 4
  536. static const int value1[] = {2500, 1500, 1000, 500, 0};
  537. static const int value2[] = {7500, 7500, 7500, 5000, 5000};
  538. static const float multiplier1[] = {0.5, 0.75, 1.0, 1.5, 1.5};
  539. static const float multiplier2[] = {0.5, 0.75, 1.0, 1.0, 1.5};
  540. int strength1 = std::max(0.f, (strength - value1[monsterStrength]) * multiplier1[monsterStrength]);
  541. int strength2 = std::max(0.f, (strength - value2[monsterStrength]) * multiplier2[monsterStrength]);
  542. strength = strength1 + strength2;
  543. if (strength < 2000)
  544. return false; //no guard at all
  545. CreatureID creId = CreatureID::NONE;
  546. int amount = 0;
  547. std::vector<CreatureID> possibleCreatures;
  548. for (auto cre : VLC->creh->creatures)
  549. {
  550. if (cre->special)
  551. continue;
  552. if (!vstd::contains(monsterTypes, cre->faction))
  553. continue;
  554. if ((cre->AIValue * (cre->ammMin + cre->ammMax) / 2 < strength) && (strength < cre->AIValue * 100)) //at least one full monster. size between minimum size of given stack and 100
  555. {
  556. possibleCreatures.push_back(cre->idNumber);
  557. }
  558. }
  559. if (possibleCreatures.size())
  560. {
  561. creId = *RandomGeneratorUtil::nextItem(possibleCreatures, gen->rand);
  562. amount = strength / VLC->creh->creatures[creId]->AIValue;
  563. if (amount >= 4)
  564. amount *= gen->rand.nextDouble(0.75, 1.25);
  565. }
  566. else //just pick any available creature
  567. {
  568. creId = CreatureID(132); //Azure Dragon
  569. amount = strength / VLC->creh->creatures[creId]->AIValue;
  570. }
  571. auto guard = new CGCreature();
  572. guard->ID = Obj::MONSTER;
  573. guard->subID = creId;
  574. guard->character = 1; //MUST be initialized or switch will diverge
  575. auto hlp = new CStackInstance(creId, amount);
  576. //will be set during initialization
  577. guard->putStack(SlotID(0), hlp);
  578. //logGlobal->traceStream() << boost::format ("Adding stack of %d %s. Map monster strenght %d, zone monster strength %d, base monster value %d")
  579. // % amount % VLC->creh->creatures[creId]->namePl % mapMonsterStrength % zoneMonsterStrength % strength;
  580. placeObject(gen, guard, pos);
  581. if (clearSurroundingTiles)
  582. {
  583. //do not spawn anything near monster
  584. gen->foreach_neighbour (pos, [gen](int3 pos)
  585. {
  586. if (gen->isPossible(pos))
  587. gen->setOccupied(pos, ETileType::FREE);
  588. });
  589. }
  590. return true;
  591. }
  592. bool CRmgTemplateZone::createTreasurePile(CMapGenerator* gen, int3 &pos, float minDistance, const CTreasureInfo& treasureInfo)
  593. {
  594. CTreasurePileInfo info;
  595. std::map<int3, CGObjectInstance *> treasures;
  596. std::set<int3> boundary;
  597. int3 guardPos (-1,-1,-1);
  598. info.nextTreasurePos = pos;
  599. int maxValue = treasureInfo.max;
  600. int minValue = treasureInfo.min;
  601. ui32 desiredValue = gen->rand.nextInt(minValue, maxValue);
  602. //quantize value to let objects with value equal to max spawn too
  603. int currentValue = 0;
  604. CGObjectInstance * object = nullptr;
  605. while (currentValue < desiredValue)
  606. {
  607. treasures[info.nextTreasurePos] = nullptr;
  608. for (auto treasurePos : treasures)
  609. {
  610. gen->foreach_neighbour (treasurePos.first, [gen, &boundary](int3 pos)
  611. {
  612. boundary.insert(pos);
  613. });
  614. }
  615. for (auto treasurePos : treasures)
  616. {
  617. //leaving only boundary around objects
  618. vstd::erase_if_present (boundary, treasurePos.first);
  619. }
  620. for (auto tile : boundary)
  621. {
  622. //we can't extend boundary anymore
  623. if (!(gen->isBlocked(tile) || gen->isPossible(tile)))
  624. break;
  625. }
  626. ObjectInfo oi = getRandomObject(gen, info, desiredValue, maxValue, currentValue);
  627. if (!oi.value) //0 value indicates no object
  628. {
  629. vstd::erase_if_present(treasures, info.nextTreasurePos);
  630. break;
  631. }
  632. else
  633. {
  634. object = oi.generateObject();
  635. //remove from possible objects
  636. auto oiptr = std::find(possibleObjects.begin(), possibleObjects.end(), oi);
  637. assert (oiptr != possibleObjects.end());
  638. oiptr->maxPerZone--;
  639. if (!oiptr->maxPerZone)
  640. possibleObjects.erase(oiptr);
  641. //TODO
  642. //update treasure pile area
  643. int3 visitablePos = info.nextTreasurePos;
  644. //TODO: actually we need to check is object is either !blockVisit or removable after visit - this means object below can be accessed
  645. if (oi.templ.isVisitableFromTop())
  646. info.visitableFromTopPositions.insert(visitablePos); //can be accessed from any direction
  647. else
  648. info.visitableFromBottomPositions.insert(visitablePos); //can be accessed only from bottom or side
  649. for (auto blockedOffset : oi.templ.getBlockedOffsets())
  650. {
  651. int3 blockPos = info.nextTreasurePos + blockedOffset + oi.templ.getVisitableOffset(); //object will be moved to align vistable pos to treasure pos
  652. info.occupiedPositions.insert(blockPos);
  653. info.blockedPositions.insert(blockPos);
  654. }
  655. info.occupiedPositions.insert(visitablePos);
  656. currentValue += oi.value;
  657. treasures[info.nextTreasurePos] = object;
  658. //now find place for next object
  659. int3 placeFound(-1,-1,-1);
  660. //randomize next position from among possible ones
  661. std::vector<int3> boundaryCopy (boundary.begin(), boundary.end());
  662. //RandomGeneratorUtil::randomShuffle(boundaryCopy, gen->rand);
  663. auto chooseTopTile = [](const int3 & lhs, const int3 & rhs) -> bool
  664. {
  665. return lhs.y < rhs.y;
  666. };
  667. boost::sort(boundaryCopy, chooseTopTile); //start from top tiles to allow objects accessible from bottom
  668. for (auto tile : boundaryCopy)
  669. {
  670. if (gen->isPossible(tile)) //we can place new treasure only on possible tile
  671. {
  672. bool here = true;
  673. gen->foreach_neighbour (tile, [gen, &here, minDistance](int3 pos)
  674. {
  675. if (!(gen->isBlocked(pos) || gen->isPossible(pos)) || gen->getNearestObjectDistance(pos) < minDistance)
  676. here = false;
  677. });
  678. if (here)
  679. {
  680. placeFound = tile;
  681. break;
  682. }
  683. }
  684. }
  685. if (placeFound.valid())
  686. info.nextTreasurePos = placeFound;
  687. }
  688. }
  689. if (treasures.size())
  690. {
  691. //find object closest to zone center, then connect it to the middle of the zone
  692. int3 closestFreeTile (-1,-1,-1);
  693. if (info.visitableFromBottomPositions.size()) //get random treasure tile, starting from objects accessible only from bottom
  694. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromBottomPositions, gen->rand));
  695. else
  696. closestFreeTile = findClosestTile (freePaths, *RandomGeneratorUtil::nextItem(info.visitableFromTopPositions, gen->rand));
  697. int3 closestTile = int3(-1,-1,-1);
  698. float minDistance = 1e10;
  699. for (auto visitablePos : info.visitableFromBottomPositions) //objects that are not visitable from top must be accessible from bottom or side
  700. {
  701. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  702. {
  703. closestTile = visitablePos + int3 (0, 1, 0); //start below object (y+1), possibly even outside the map (?)
  704. minDistance = closestFreeTile.dist2d(visitablePos);
  705. }
  706. }
  707. if (!closestTile.valid())
  708. {
  709. for (auto visitablePos : info.visitableFromTopPositions) //all objects are accessible from any direction
  710. {
  711. if (closestFreeTile.dist2d(visitablePos) < minDistance)
  712. {
  713. closestTile = visitablePos;
  714. minDistance = closestFreeTile.dist2d(visitablePos);
  715. }
  716. }
  717. }
  718. assert (closestTile.valid());
  719. for (auto tile : info.occupiedPositions)
  720. {
  721. if (gen->map->isInTheMap(tile)) //pile boundary may reach map border
  722. gen->setOccupied(tile, ETileType::BLOCKED); //so that crunch path doesn't cut through objects
  723. }
  724. if (!crunchPath (gen, closestTile, closestFreeTile, id))
  725. {
  726. //we can't connect this pile, just block it off and start over
  727. for (auto treasure : treasures)
  728. {
  729. if (gen->isPossible(treasure.first))
  730. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  731. }
  732. return true;
  733. }
  734. //update boundary around our objects, including knowledge about objects visitable from bottom
  735. boundary.clear();
  736. for (auto tile : info.visitableFromBottomPositions)
  737. {
  738. gen->foreach_neighbour (tile, [tile, &boundary](int3 pos)
  739. {
  740. if (pos.y >= tile.y) //don't block these objects from above
  741. boundary.insert(pos);
  742. });
  743. }
  744. for (auto tile : info.visitableFromTopPositions)
  745. {
  746. gen->foreach_neighbour (tile, [&boundary](int3 pos)
  747. {
  748. boundary.insert(pos);
  749. });
  750. }
  751. for (auto tile : boundary) //guard must be standing there
  752. {
  753. if (gen->isFree(tile)) //this tile could be already blocked, don't place a monster here
  754. {
  755. guardPos = tile;
  756. break;
  757. }
  758. }
  759. if (guardPos.valid())
  760. {
  761. for (auto treasure : treasures)
  762. {
  763. int3 visitableOffset = treasure.second->getVisitableOffset();
  764. placeObject(gen, treasure.second, treasure.first + visitableOffset);
  765. }
  766. if (addMonster(gen, guardPos, currentValue, false))
  767. {//block only if the object is guarded
  768. for (auto tile : boundary)
  769. {
  770. if (gen->isPossible(tile))
  771. gen->setOccupied (tile, ETileType::BLOCKED);
  772. }
  773. //do not spawn anything near monster
  774. gen->foreach_neighbour (guardPos, [gen](int3 pos)
  775. {
  776. if (gen->isPossible(pos))
  777. gen->setOccupied(pos, ETileType::FREE);
  778. });
  779. }
  780. }
  781. else //we couldn't make a connection to this location, block it
  782. {
  783. for (auto treasure : treasures)
  784. {
  785. if (gen->isPossible(treasure.first))
  786. gen->setOccupied (treasure.first, ETileType::BLOCKED);
  787. delete treasure.second;
  788. }
  789. }
  790. return true;
  791. }
  792. else //we did not place eveyrthing successfully
  793. return false;
  794. }
  795. void CRmgTemplateZone::initTownType (CMapGenerator* gen)
  796. {
  797. //FIXME: handle case that this player is not present -> towns should be set to neutral
  798. int totalTowns = 0;
  799. auto cutPathAroundTown = [gen, this](const CGTownInstance * town)
  800. {
  801. //cut contour around town in case it was placed in a middle of path. TODO: find better solution
  802. for (auto tile : town->getBlockedPos())
  803. {
  804. gen->foreach_neighbour(tile, [gen, &tile](int3& pos)
  805. {
  806. if (gen->isPossible(pos))
  807. {
  808. gen->setOccupied(pos, ETileType::FREE);
  809. }
  810. });
  811. }
  812. };
  813. auto addNewTowns = [&totalTowns, gen, this, &cutPathAroundTown](int count, bool hasFort, PlayerColor player)
  814. {
  815. for (int i = 0; i < count; i++)
  816. {
  817. auto town = new CGTownInstance();
  818. town->ID = Obj::TOWN;
  819. if (this->townsAreSameType)
  820. town->subID = townType;
  821. else
  822. {
  823. if (townTypes.size())
  824. town->subID = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  825. else
  826. town->subID = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  827. }
  828. town->tempOwner = player;
  829. if (hasFort)
  830. town->builtBuildings.insert(BuildingID::FORT);
  831. town->builtBuildings.insert(BuildingID::DEFAULT);
  832. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  833. {
  834. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  835. town->possibleSpells.push_back(spell->id);
  836. }
  837. if (!totalTowns)
  838. {
  839. //first town in zone sets the facton of entire zone
  840. town->subID = townType;
  841. //register MAIN town of zone
  842. gen->registerZone(town->subID);
  843. //first town in zone goes in the middle
  844. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0);
  845. cutPathAroundTown(town);
  846. }
  847. else
  848. addRequiredObject (town);
  849. totalTowns++;
  850. }
  851. };
  852. if ((type == ETemplateZoneType::CPU_START) || (type == ETemplateZoneType::PLAYER_START))
  853. {
  854. //set zone types to player faction, generate main town
  855. logGlobal->infoStream() << "Preparing playing zone";
  856. int player_id = *owner - 1;
  857. auto & playerInfo = gen->map->players[player_id];
  858. if (playerInfo.canAnyonePlay())
  859. {
  860. PlayerColor player(player_id);
  861. townType = gen->mapGenOptions->getPlayersSettings().find(player)->second.getStartingTown();
  862. if (townType == CMapGenOptions::CPlayerSettings::RANDOM_TOWN)
  863. {
  864. if (townTypes.size())
  865. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  866. else
  867. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  868. }
  869. auto town = new CGTownInstance();
  870. town->ID = Obj::TOWN;
  871. town->subID = townType;
  872. town->tempOwner = player;
  873. town->builtBuildings.insert(BuildingID::FORT);
  874. town->builtBuildings.insert(BuildingID::DEFAULT);
  875. for (auto spell : VLC->spellh->objects) //add all regular spells to town
  876. {
  877. if (!spell->isSpecialSpell() && !spell->isCreatureAbility())
  878. town->possibleSpells.push_back(spell->id);
  879. }
  880. //towns are big objects and should be centered around visitable position
  881. placeAndGuardObject(gen, town, getPos() + town->getVisitableOffset(), 0); //generate no guards, but free path to entrance
  882. cutPathAroundTown(town);
  883. totalTowns++;
  884. //register MAIN town of zone only
  885. gen->registerZone (town->subID);
  886. logGlobal->traceStream() << "Fill player info " << player_id;
  887. // Update player info
  888. playerInfo.allowedFactions.clear();
  889. playerInfo.allowedFactions.insert (townType);
  890. playerInfo.hasMainTown = true;
  891. playerInfo.posOfMainTown = town->pos - town->getVisitableOffset();
  892. playerInfo.generateHeroAtMainTown = true;
  893. //now create actual towns
  894. addNewTowns (playerTowns.getCastleCount() - 1, true, player);
  895. addNewTowns (playerTowns.getTownCount(), false, player);
  896. //requiredObjects.push_back(town);
  897. }
  898. else
  899. {
  900. type = ETemplateZoneType::TREASURE;
  901. if (townTypes.size())
  902. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  903. else
  904. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  905. }
  906. }
  907. else //no player
  908. {
  909. if (townTypes.size())
  910. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  911. else
  912. townType = *RandomGeneratorUtil::nextItem(getDefaultTownTypes(), gen->rand); //it is possible to have zone with no towns allowed
  913. }
  914. addNewTowns (neutralTowns.getCastleCount(), true, PlayerColor::NEUTRAL);
  915. addNewTowns (neutralTowns.getTownCount(), false, PlayerColor::NEUTRAL);
  916. if (!totalTowns) //if there's no town present, get random faction for dwellings and pandoras
  917. {
  918. //25% chance for neutral
  919. if (gen->rand.nextInt(1, 100) <= 25)
  920. {
  921. townType = ETownType::NEUTRAL;
  922. }
  923. else
  924. {
  925. if (townTypes.size())
  926. townType = *RandomGeneratorUtil::nextItem(townTypes, gen->rand);
  927. else if (monsterTypes.size())
  928. townType = *RandomGeneratorUtil::nextItem(monsterTypes, gen->rand); //this happens in Clash of Dragons in treasure zones, where all towns are banned
  929. }
  930. }
  931. }
  932. void CRmgTemplateZone::initTerrainType (CMapGenerator* gen)
  933. {
  934. if (matchTerrainToTown && townType != ETownType::NEUTRAL)
  935. terrainType = VLC->townh->factions[townType]->nativeTerrain;
  936. else
  937. terrainType = *RandomGeneratorUtil::nextItem(terrainTypes, gen->rand);
  938. //TODO: allow new types of terrain?
  939. if (pos.z)
  940. {
  941. if (terrainType != ETerrainType::LAVA)
  942. terrainType = ETerrainType::SUBTERRANEAN;
  943. }
  944. else
  945. {
  946. if (terrainType == ETerrainType::SUBTERRANEAN)
  947. terrainType = ETerrainType::DIRT;
  948. }
  949. paintZoneTerrain (gen, terrainType);
  950. }
  951. void CRmgTemplateZone::paintZoneTerrain (CMapGenerator* gen, ETerrainType terrainType)
  952. {
  953. std::vector<int3> tiles;
  954. for (auto tile : tileinfo)
  955. {
  956. tiles.push_back (tile);
  957. }
  958. gen->editManager->getTerrainSelection().setSelection(tiles);
  959. gen->editManager->drawTerrain(terrainType, &gen->rand);
  960. }
  961. bool CRmgTemplateZone::placeMines (CMapGenerator* gen)
  962. {
  963. std::vector<Res::ERes> required_mines;
  964. required_mines.push_back(Res::ERes::WOOD);
  965. required_mines.push_back(Res::ERes::ORE);
  966. static const Res::ERes woodOre[] = {Res::ERes::WOOD, Res::ERes::ORE};
  967. static const Res::ERes preciousResources[] = {Res::ERes::GEMS, Res::ERes::CRYSTAL, Res::ERes::MERCURY, Res::ERes::SULFUR};
  968. for (const auto & res : woodOre)
  969. {
  970. for (int i = 0; i < mines[res]; i++)
  971. {
  972. auto mine = new CGMine();
  973. mine->ID = Obj::MINE;
  974. mine->subID = static_cast<si32>(res);
  975. mine->producedResource = res;
  976. mine->producedQuantity = mine->defaultResProduction();
  977. addCloseObject(mine, 1500);
  978. }
  979. }
  980. for (const auto & res : preciousResources)
  981. {
  982. for (int i = 0; i < mines[res]; i++)
  983. {
  984. auto mine = new CGMine();
  985. mine->ID = Obj::MINE;
  986. mine->subID = static_cast<si32>(res);
  987. mine->producedResource = res;
  988. mine->producedQuantity = mine->defaultResProduction();
  989. addRequiredObject(mine, 3500);
  990. }
  991. }
  992. for (int i = 0; i < mines[Res::GOLD]; i++)
  993. {
  994. auto mine = new CGMine();
  995. mine->ID = Obj::MINE;
  996. mine->subID = static_cast<si32>(Res::GOLD);
  997. mine->producedResource = Res::GOLD;
  998. mine->producedQuantity = mine->defaultResProduction();
  999. addRequiredObject(mine, 7000);
  1000. }
  1001. return true;
  1002. }
  1003. bool CRmgTemplateZone::createRequiredObjects(CMapGenerator* gen)
  1004. {
  1005. logGlobal->traceStream() << "Creating required objects";
  1006. for(const auto &obj : requiredObjects)
  1007. {
  1008. int3 pos;
  1009. if ( ! findPlaceForObject(gen, obj.first, 3, pos))
  1010. {
  1011. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") %id;
  1012. //TODO CLEANUP!
  1013. return false;
  1014. }
  1015. placeObject (gen, obj.first, pos);
  1016. guardObject (gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1017. //paths to required objects constitute main paths of zone. otherwise they just may lead to middle and create dead zones
  1018. }
  1019. for (const auto &obj : closeObjects)
  1020. {
  1021. std::vector<int3> tiles(possibleTiles.begin(), possibleTiles.end()); //new tiles vector after each object has been placed
  1022. // smallest distance to zone center, greatest distance to nearest object
  1023. auto isCloser = [this, gen](const int3 & lhs, const int3 & rhs) -> bool
  1024. {
  1025. return (this->pos.dist2dSQ(lhs) * 0.5f - gen->getNearestObjectDistance(lhs)) < (this->pos.dist2dSQ(rhs) * 0.5f - gen->getNearestObjectDistance(rhs));
  1026. };
  1027. boost::sort (tiles, isCloser);
  1028. setTemplateForObject(gen, obj.first);
  1029. auto tilesBlockedByObject = obj.first->getBlockedOffsets();
  1030. bool result = false;
  1031. for (auto tile : tiles)
  1032. {
  1033. //object must be accessible from at least one surounding tile
  1034. if (!isAccessibleFromAnywhere(gen, obj.first->appearance, tile, tilesBlockedByObject))
  1035. continue;
  1036. //avoid borders
  1037. if (gen->isPossible(tile))
  1038. {
  1039. if (areAllTilesAvailable(gen, obj.first, tile, tilesBlockedByObject))
  1040. {
  1041. placeObject(gen, obj.first, tile);
  1042. guardObject(gen, obj.first, obj.second, (obj.first->ID == Obj::MONOLITH_TWO_WAY), true);
  1043. result = true;
  1044. break;
  1045. }
  1046. }
  1047. }
  1048. if (!result)
  1049. {
  1050. logGlobal->errorStream() << boost::format("Failed to fill zone %d due to lack of space") % id;
  1051. //TODO CLEANUP!
  1052. return false;
  1053. }
  1054. }
  1055. return true;
  1056. }
  1057. void CRmgTemplateZone::createTreasures(CMapGenerator* gen)
  1058. {
  1059. auto valueComparator = [](const CTreasureInfo & lhs, const CTreasureInfo & rhs) -> bool
  1060. {
  1061. return lhs.max > rhs.max;
  1062. };
  1063. //place biggest treasures first at large distance, place smaller ones inbetween
  1064. boost::sort(treasureInfo, valueComparator);
  1065. int totalDensity = 0;
  1066. for (auto t : treasureInfo)
  1067. {
  1068. totalDensity += t.density;
  1069. //treasure density is inversely proportional to zone size but must be scaled back to map size
  1070. //also, normalize it to zone count - higher count means relatively smaller zones
  1071. //this is squared distance for optimization purposes
  1072. const double minDistance = std::max<float>((450.f * size * size * gen->getZones().size()) /
  1073. (gen->mapGenOptions->getWidth() * gen->mapGenOptions->getHeight() * totalDensity * (gen->map->twoLevel ? 2 : 1)), 2);
  1074. //distance lower than 2 causes objects to overlap and crash
  1075. do {
  1076. //optimization - don't check tiles which are not allowed
  1077. vstd::erase_if(possibleTiles, [gen](const int3 &tile) -> bool
  1078. {
  1079. return !gen->isPossible(tile);
  1080. });
  1081. int3 pos;
  1082. if (!findPlaceForTreasurePile(gen, minDistance, pos))
  1083. {
  1084. break;
  1085. }
  1086. createTreasurePile(gen, pos, minDistance, t);
  1087. } while (true);
  1088. }
  1089. }
  1090. void CRmgTemplateZone::createObstacles(CMapGenerator* gen)
  1091. {
  1092. //tighten obstacles to improve visuals
  1093. for (int i = 0; i < 3; ++i)
  1094. {
  1095. int blockedTiles = 0;
  1096. int freeTiles = 0;
  1097. for (auto tile : tileinfo)
  1098. {
  1099. if (!gen->isPossible(tile)) //only possible tiles can change
  1100. continue;
  1101. int blockedNeighbours = 0;
  1102. int freeNeighbours = 0;
  1103. gen->foreach_neighbour(tile, [gen, &blockedNeighbours, &freeNeighbours](int3 &pos)
  1104. {
  1105. if (gen->isBlocked(pos))
  1106. blockedNeighbours++;
  1107. if (gen->isFree(pos))
  1108. freeNeighbours++;
  1109. });
  1110. if (blockedNeighbours > 4)
  1111. {
  1112. gen->setOccupied(tile, ETileType::BLOCKED);
  1113. blockedTiles++;
  1114. }
  1115. else if (freeNeighbours > 4)
  1116. {
  1117. gen->setOccupied(tile, ETileType::FREE);
  1118. freeTiles++;
  1119. }
  1120. }
  1121. logGlobal->traceStream() << boost::format("Set %d tiles to BLOCKED and %d tiles to FREE") % blockedTiles % freeTiles;
  1122. }
  1123. #define MAKE_COOL_UNDERGROUND_TUNNELS false
  1124. if (pos.z && MAKE_COOL_UNDERGROUND_TUNNELS) //underground
  1125. {
  1126. std::vector<int3> rockTiles;
  1127. for (auto tile : tileinfo)
  1128. {
  1129. if (gen->shouldBeBlocked(tile))
  1130. {
  1131. bool placeRock = true;
  1132. gen->foreach_neighbour (tile, [gen, &placeRock](int3 &pos)
  1133. {
  1134. if (!(gen->shouldBeBlocked(pos) || gen->isPossible(pos)))
  1135. placeRock = false;
  1136. });
  1137. if (placeRock)
  1138. {
  1139. rockTiles.push_back(tile);
  1140. }
  1141. }
  1142. }
  1143. gen->editManager->getTerrainSelection().setSelection(rockTiles);
  1144. gen->editManager->drawTerrain(ETerrainType::ROCK, &gen->rand);
  1145. for (auto tile : rockTiles)
  1146. {
  1147. gen->setOccupied (tile, ETileType::USED); //don't place obstacles in a rock
  1148. //gen->foreach_neighbour (tile, [gen](int3 &pos)
  1149. //{
  1150. // if (!gen->isUsed(pos))
  1151. // gen->setOccupied (pos, ETileType::BLOCKED);
  1152. //});
  1153. }
  1154. }
  1155. typedef std::vector<ObjectTemplate> obstacleVector;
  1156. //obstacleVector possibleObstacles;
  1157. std::map <ui8, obstacleVector> obstaclesBySize;
  1158. typedef std::pair <ui8, obstacleVector> obstaclePair;
  1159. std::vector<obstaclePair> possibleObstacles;
  1160. //get all possible obstacles for this terrain
  1161. for (auto primaryID : VLC->objtypeh->knownObjects())
  1162. {
  1163. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1164. {
  1165. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1166. if (handler->isStaticObject())
  1167. {
  1168. for (auto temp : handler->getTemplates())
  1169. {
  1170. if (temp.canBePlacedAt(terrainType) && temp.getBlockMapOffset().valid())
  1171. obstaclesBySize[temp.getBlockedOffsets().size()].push_back(temp);
  1172. }
  1173. }
  1174. }
  1175. }
  1176. for (auto o : obstaclesBySize)
  1177. {
  1178. possibleObstacles.push_back (std::make_pair(o.first, o.second));
  1179. }
  1180. boost::sort (possibleObstacles, [](const obstaclePair &p1, const obstaclePair &p2) -> bool
  1181. {
  1182. return p1.first > p2.first; //bigger obstacles first
  1183. });
  1184. auto sel = gen->editManager->getTerrainSelection();
  1185. sel.clearSelection();
  1186. auto tryToPlaceObstacleHere = [this, gen, &possibleObstacles](int3& tile, int index)-> bool
  1187. {
  1188. auto temp = *RandomGeneratorUtil::nextItem(possibleObstacles[index].second, gen->rand);
  1189. int3 obstaclePos = tile - temp.getBlockMapOffset();
  1190. if (canObstacleBePlacedHere(gen, temp, obstaclePos)) //can be placed here
  1191. {
  1192. auto obj = VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1193. placeObject(gen, obj, obstaclePos, false);
  1194. return true;
  1195. }
  1196. return false;
  1197. };
  1198. //reverse order, since obstacles begin in bottom-right corner, while the map coordinates begin in top-left
  1199. for (auto tile : boost::adaptors::reverse(tileinfo))
  1200. {
  1201. //fill tiles that should be blocked with obstacles or are just possible (with some probability)
  1202. if (gen->shouldBeBlocked(tile) || (gen->isPossible(tile) && gen->rand.nextInt(1,100) < 60))
  1203. {
  1204. //start from biggets obstacles
  1205. for (int i = 0; i < possibleObstacles.size(); i++)
  1206. {
  1207. if (tryToPlaceObstacleHere(tile, i))
  1208. break;
  1209. }
  1210. }
  1211. }
  1212. }
  1213. bool CRmgTemplateZone::fill(CMapGenerator* gen)
  1214. {
  1215. initTerrainType(gen);
  1216. freePaths.insert(pos); //zone center should be always clear to allow other tiles to connect
  1217. addAllPossibleObjects (gen);
  1218. placeMines(gen);
  1219. createRequiredObjects(gen);
  1220. fractalize(gen); //after required objects are created and linked with their own paths
  1221. createTreasures(gen);
  1222. createObstacles(gen);
  1223. logGlobal->infoStream() << boost::format ("Zone %d filled successfully") %id;
  1224. return true;
  1225. }
  1226. bool CRmgTemplateZone::findPlaceForTreasurePile(CMapGenerator* gen, float min_dist, int3 &pos)
  1227. {
  1228. //si32 min_dist = sqrt(tileinfo.size()/density);
  1229. float best_distance = 0;
  1230. bool result = false;
  1231. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1232. for(auto tile : possibleTiles)
  1233. {
  1234. auto dist = gen->getNearestObjectDistance(tile);
  1235. if ((dist >= min_dist) && (dist > best_distance))
  1236. {
  1237. bool allTilesAvailable = true;
  1238. gen->foreach_neighbour (tile, [&gen, &allTilesAvailable](int3 neighbour)
  1239. {
  1240. if (!(gen->isPossible(neighbour) || gen->shouldBeBlocked(neighbour)))
  1241. {
  1242. allTilesAvailable = false; //all present tiles must be already blocked or ready for new objects
  1243. }
  1244. });
  1245. if (allTilesAvailable)
  1246. {
  1247. best_distance = dist;
  1248. pos = tile;
  1249. result = true;
  1250. }
  1251. }
  1252. }
  1253. if (result)
  1254. {
  1255. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1256. }
  1257. return result;
  1258. }
  1259. bool CRmgTemplateZone::canObstacleBePlacedHere(CMapGenerator* gen, ObjectTemplate &temp, int3 &pos)
  1260. {
  1261. if (!gen->map->isInTheMap(pos)) //blockmap may fit in the map, but botom-right corner does not
  1262. return false;
  1263. auto tilesBlockedByObject = temp.getBlockedOffsets();
  1264. for (auto blockingTile : tilesBlockedByObject)
  1265. {
  1266. int3 t = pos + blockingTile;
  1267. if (!gen->map->isInTheMap(t) || !(gen->isPossible(t) || gen->shouldBeBlocked(t)))
  1268. {
  1269. return false; //if at least one tile is not possible, object can't be placed here
  1270. }
  1271. }
  1272. return true;
  1273. }
  1274. bool CRmgTemplateZone::isAccessibleFromAnywhere (CMapGenerator* gen, ObjectTemplate &appearance, int3 &tile, const std::set<int3> &tilesBlockedByObject) const
  1275. {
  1276. bool accessible = false;
  1277. for (int x = -1; x < 2; x++)
  1278. {
  1279. for (int y = -1; y <2; y++)
  1280. {
  1281. if (x && y) //check only if object is visitable from another tile
  1282. {
  1283. int3 offset = appearance.getVisitableOffset() + int3(x, y, 0);
  1284. if (!vstd::contains(tilesBlockedByObject, offset))
  1285. {
  1286. int3 nearbyPos = tile + offset;
  1287. if (gen->map->isInTheMap(nearbyPos))
  1288. {
  1289. if (appearance.isVisitableFrom(x, y) && !gen->isBlocked(nearbyPos))
  1290. accessible = true;
  1291. }
  1292. }
  1293. }
  1294. };
  1295. }
  1296. return accessible;
  1297. }
  1298. void CRmgTemplateZone::setTemplateForObject(CMapGenerator* gen, CGObjectInstance* obj)
  1299. {
  1300. if (obj->appearance.id == Obj::NO_OBJ)
  1301. {
  1302. auto templates = VLC->objtypeh->getHandlerFor(obj->ID, obj->subID)->getTemplates(gen->map->getTile(getPos()).terType);
  1303. if (templates.empty())
  1304. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s") % obj->ID %obj->subID %pos));
  1305. obj->appearance = templates.front();
  1306. }
  1307. }
  1308. bool CRmgTemplateZone::areAllTilesAvailable(CMapGenerator* gen, CGObjectInstance* obj, int3& tile, std::set<int3>& tilesBlockedByObject) const
  1309. {
  1310. for (auto blockingTile : tilesBlockedByObject)
  1311. {
  1312. int3 t = tile + blockingTile;
  1313. if (!gen->map->isInTheMap(t) || !gen->isPossible(t))
  1314. {
  1315. //if at least one tile is not possible, object can't be placed here
  1316. return false;
  1317. }
  1318. }
  1319. return true;
  1320. }
  1321. bool CRmgTemplateZone::findPlaceForObject(CMapGenerator* gen, CGObjectInstance* obj, si32 min_dist, int3 &pos)
  1322. {
  1323. //we need object apperance to deduce free tile
  1324. setTemplateForObject(gen, obj);
  1325. //si32 min_dist = sqrt(tileinfo.size()/density);
  1326. int best_distance = 0;
  1327. bool result = false;
  1328. //si32 w = gen->map->width;
  1329. //si32 h = gen->map->height;
  1330. //logGlobal->infoStream() << boost::format("Min dist for density %f is %d") % density % min_dist;
  1331. auto tilesBlockedByObject = obj->getBlockedOffsets();
  1332. for (auto tile : tileinfo)
  1333. {
  1334. //object must be accessible from at least one surounding tile
  1335. if (!isAccessibleFromAnywhere(gen, obj->appearance, tile, tilesBlockedByObject))
  1336. continue;
  1337. auto ti = gen->getTile(tile);
  1338. auto dist = ti.getNearestObjectDistance();
  1339. //avoid borders
  1340. if (gen->isPossible(tile) && (dist >= min_dist) && (dist > best_distance))
  1341. {
  1342. if (areAllTilesAvailable(gen, obj, tile, tilesBlockedByObject))
  1343. {
  1344. best_distance = dist;
  1345. pos = tile;
  1346. result = true;
  1347. }
  1348. }
  1349. }
  1350. if (result)
  1351. {
  1352. gen->setOccupied(pos, ETileType::BLOCKED); //block that tile
  1353. }
  1354. return result;
  1355. }
  1356. void CRmgTemplateZone::checkAndPlaceObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos)
  1357. {
  1358. if (!gen->map->isInTheMap(pos))
  1359. throw rmgException(boost::to_string(boost::format("Position of object %d at %s is outside the map") % object->id % pos));
  1360. object->pos = pos;
  1361. if (object->isVisitable() && !gen->map->isInTheMap(object->visitablePos()))
  1362. throw rmgException(boost::to_string(boost::format("Visitable tile %s of object %d at %s is outside the map") % object->visitablePos() % object->id % object->pos()));
  1363. for (auto tile : object->getBlockedPos())
  1364. {
  1365. if (!gen->map->isInTheMap(tile))
  1366. throw rmgException(boost::to_string(boost::format("Tile %s of object %d at %s is outside the map") % tile() % object->id % object->pos()));
  1367. }
  1368. if (object->appearance.id == Obj::NO_OBJ)
  1369. {
  1370. auto terrainType = gen->map->getTile(pos).terType;
  1371. auto templates = VLC->objtypeh->getHandlerFor(object->ID, object->subID)->getTemplates(terrainType);
  1372. if (templates.empty())
  1373. throw rmgException(boost::to_string(boost::format("Did not find graphics for object (%d,%d) at %s (terrain %d)") %object->ID %object->subID %pos %terrainType));
  1374. object->appearance = templates.front();
  1375. }
  1376. gen->editManager->insertObject(object, pos);
  1377. //logGlobal->traceStream() << boost::format ("Successfully inserted object (%d,%d) at pos %s") %object->ID %object->subID %pos();
  1378. }
  1379. void CRmgTemplateZone::placeObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, bool updateDistance)
  1380. {
  1381. //logGlobal->traceStream() << boost::format("Inserting object at %d %d") % pos.x % pos.y;
  1382. checkAndPlaceObject (gen, object, pos);
  1383. auto points = object->getBlockedPos();
  1384. if (object->isVisitable())
  1385. points.insert(pos + object->getVisitableOffset());
  1386. points.insert(pos);
  1387. for(auto p : points)
  1388. {
  1389. if (gen->map->isInTheMap(p))
  1390. {
  1391. gen->setOccupied(p, ETileType::USED);
  1392. }
  1393. }
  1394. if (updateDistance)
  1395. {
  1396. for(auto tile : possibleTiles) //don't need to mark distance for not possible tiles
  1397. {
  1398. si32 d = pos.dist2dSQ(tile); //optimization, only relative distance is interesting
  1399. gen->setNearestObjectDistance(tile, std::min<float>(d, gen->getNearestObjectDistance(tile)));
  1400. }
  1401. }
  1402. }
  1403. void CRmgTemplateZone::placeAndGuardObject(CMapGenerator* gen, CGObjectInstance* object, const int3 &pos, si32 str, bool zoneGuard)
  1404. {
  1405. placeObject(gen, object, pos);
  1406. guardObject(gen, object, str, zoneGuard);
  1407. }
  1408. std::vector<int3> CRmgTemplateZone::getAccessibleOffsets (CMapGenerator* gen, CGObjectInstance* object)
  1409. {
  1410. //get all tiles from which this object can be accessed
  1411. int3 visitable = object->visitablePos();
  1412. std::vector<int3> tiles;
  1413. auto tilesBlockedByObject = object->getBlockedPos(); //absolue value, as object is already placed
  1414. gen->foreach_neighbour(visitable, [&](int3& pos)
  1415. {
  1416. if (gen->isPossible(pos))
  1417. {
  1418. if (!vstd::contains(tilesBlockedByObject, pos))
  1419. {
  1420. if (object->appearance.isVisitableFrom(pos.x - visitable.x, pos.y - visitable.y) && !gen->isBlocked(pos)) //TODO: refactor - info about visitability from absolute coordinates
  1421. {
  1422. tiles.push_back(pos);
  1423. }
  1424. }
  1425. };
  1426. });
  1427. return tiles;
  1428. }
  1429. bool CRmgTemplateZone::guardObject(CMapGenerator* gen, CGObjectInstance* object, si32 str, bool zoneGuard, bool addToFreePaths)
  1430. {
  1431. logGlobal->traceStream() << boost::format("Guard object at %s") % object->pos();
  1432. std::vector<int3> tiles = getAccessibleOffsets (gen, object);
  1433. int3 guardTile(-1,-1,-1);
  1434. for (auto tile : tiles)
  1435. {
  1436. //crunching path may fail if center of the zone is directly over wide object
  1437. //make sure object is accessible before surrounding it with blocked tiles
  1438. if (crunchPath (gen, tile, findClosestTile(freePaths, tile), id, addToFreePaths ? &freePaths : nullptr))
  1439. {
  1440. guardTile = tile;
  1441. break;
  1442. }
  1443. }
  1444. if (!guardTile.valid())
  1445. {
  1446. logGlobal->errorStream() << boost::format("Failed to crunch path to object at %s") % object->pos();
  1447. return false;
  1448. }
  1449. if (addMonster (gen, guardTile, str, false, zoneGuard)) //do not place obstacles around unguarded object
  1450. {
  1451. for (auto pos : tiles)
  1452. {
  1453. if (!gen->isFree(pos))
  1454. gen->setOccupied(pos, ETileType::BLOCKED);
  1455. }
  1456. gen->foreach_neighbour (guardTile, [&](int3& pos)
  1457. {
  1458. if (gen->isPossible(pos))
  1459. gen->setOccupied (pos, ETileType::FREE);
  1460. });
  1461. gen->setOccupied (guardTile, ETileType::USED);
  1462. }
  1463. else //allow no guard or other object in front of this object
  1464. {
  1465. for (auto tile : tiles)
  1466. if (gen->isPossible(tile))
  1467. gen->setOccupied (tile, ETileType::FREE);
  1468. }
  1469. return true;
  1470. }
  1471. ObjectInfo CRmgTemplateZone::getRandomObject(CMapGenerator* gen, CTreasurePileInfo &info, ui32 desiredValue, ui32 maxValue, ui32 currentValue)
  1472. {
  1473. //int objectsVisitableFromBottom = 0; //for debug
  1474. std::vector<std::pair<ui32, ObjectInfo>> tresholds;
  1475. ui32 total = 0;
  1476. //calculate actual treasure value range based on remaining value
  1477. ui32 maxVal = maxValue - currentValue;
  1478. ui32 minValue = 0.25f * (desiredValue - currentValue);
  1479. //roulette wheel
  1480. for (ObjectInfo &oi : possibleObjects) //copy constructor turned out to be costly
  1481. {
  1482. if (oi.value >= minValue && oi.value <= maxVal && oi.maxPerZone > 0)
  1483. {
  1484. int3 newVisitableOffset = oi.templ.getVisitableOffset(); //visitablePos assumes object will be shifter by visitableOffset
  1485. int3 newVisitablePos = info.nextTreasurePos;
  1486. if (!oi.templ.isVisitableFromTop())
  1487. {
  1488. //objectsVisitableFromBottom++;
  1489. //there must be free tiles under object
  1490. auto blockedOffsets = oi.templ.getBlockedOffsets();
  1491. if (!isAccessibleFromAnywhere(gen, oi.templ, newVisitablePos, blockedOffsets))
  1492. continue;
  1493. }
  1494. //NOTE: y coordinate grows downwards
  1495. if (info.visitableFromBottomPositions.size() + info.visitableFromTopPositions.size()) //do not try to match first object in zone
  1496. {
  1497. bool fitsHere = false;
  1498. if (oi.templ.isVisitableFromTop()) //new can be accessed from any direction
  1499. {
  1500. for (auto tile : info.visitableFromTopPositions)
  1501. {
  1502. int3 actualTile = tile + newVisitableOffset;
  1503. if (newVisitablePos.areNeighbours(actualTile)) //we access other removable object from any position
  1504. {
  1505. fitsHere = true;
  1506. break;
  1507. }
  1508. }
  1509. for (auto tile : info.visitableFromBottomPositions)
  1510. {
  1511. int3 actualTile = tile + newVisitableOffset;
  1512. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y >= actualTile.y) //we access existing static object from side or bottom only
  1513. {
  1514. fitsHere = true;
  1515. break;
  1516. }
  1517. }
  1518. }
  1519. else //if new object is not visitable from top, it must be accessible from below or side
  1520. {
  1521. for (auto tile : info.visitableFromTopPositions)
  1522. {
  1523. int3 actualTile = tile + newVisitableOffset;
  1524. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y <= actualTile.y) //we access existing removable object from top or side only
  1525. {
  1526. fitsHere = true;
  1527. break;
  1528. }
  1529. }
  1530. for (auto tile : info.visitableFromBottomPositions)
  1531. {
  1532. int3 actualTile = tile + newVisitableOffset;
  1533. if (newVisitablePos.areNeighbours(actualTile) && newVisitablePos.y == actualTile.y) //we access other static object from side only
  1534. {
  1535. fitsHere = true;
  1536. break;
  1537. }
  1538. }
  1539. }
  1540. if (!fitsHere)
  1541. continue;
  1542. }
  1543. //now check blockmap, including our already reserved pile area
  1544. bool fitsBlockmap = true;
  1545. std::set<int3> blockedOffsets = oi.templ.getBlockedOffsets();
  1546. blockedOffsets.insert (newVisitableOffset);
  1547. for (auto blockingTile : blockedOffsets)
  1548. {
  1549. int3 t = info.nextTreasurePos + newVisitableOffset + blockingTile;
  1550. if (!gen->map->isInTheMap(t) || vstd::contains(info.occupiedPositions, t))
  1551. {
  1552. fitsBlockmap = false; //if at least one tile is not possible, object can't be placed here
  1553. break;
  1554. }
  1555. if (!(gen->isPossible(t) || gen->isBlocked(t))) //blocked tiles of object may cover blocked tiles, but not used or free tiles
  1556. {
  1557. fitsBlockmap = false;
  1558. break;
  1559. }
  1560. }
  1561. if (!fitsBlockmap)
  1562. continue;
  1563. total += oi.probability;
  1564. //assert (oi.value > 0);
  1565. tresholds.push_back (std::make_pair (total, oi));
  1566. }
  1567. }
  1568. //logGlobal->infoStream() << boost::format ("Number of objects visitable from bottom: %d") % objectsVisitableFromBottom;
  1569. if (tresholds.empty())
  1570. {
  1571. ObjectInfo oi;
  1572. //Generate pandora Box with gold if the value is extremely high
  1573. if (minValue > 20000) //we don't have object valuable enough
  1574. {
  1575. oi.generateObject = [minValue]() -> CGObjectInstance *
  1576. {
  1577. auto obj = new CGPandoraBox();
  1578. obj->ID = Obj::PANDORAS_BOX;
  1579. obj->subID = 0;
  1580. obj->resources[Res::GOLD] = minValue;
  1581. return obj;
  1582. };
  1583. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType);
  1584. oi.value = minValue;
  1585. oi.probability = 0;
  1586. }
  1587. else //generate empty object with 0 value if the value if we can't spawn anything
  1588. {
  1589. oi.generateObject = [gen]() -> CGObjectInstance *
  1590. {
  1591. return nullptr;
  1592. };
  1593. oi.setTemplate(Obj::PANDORAS_BOX, 0, terrainType); //TODO: null template or something? should be never used, but hell knows
  1594. oi.value = 0; // this field is checked to determine no object
  1595. oi.probability = 0;
  1596. }
  1597. return oi;
  1598. }
  1599. else
  1600. {
  1601. int r = gen->rand.nextInt (1, total);
  1602. for (auto t : tresholds)
  1603. {
  1604. if (r <= t.first)
  1605. return t.second;
  1606. }
  1607. assert (0); //we should never be here
  1608. }
  1609. //FIXME: control reaches end of non-void function. Missing return?
  1610. }
  1611. void CRmgTemplateZone::addAllPossibleObjects (CMapGenerator* gen)
  1612. {
  1613. ObjectInfo oi;
  1614. oi.maxPerMap = std::numeric_limits<ui32>().max();
  1615. int numZones = gen->getZones().size();
  1616. for (auto primaryID : VLC->objtypeh->knownObjects())
  1617. {
  1618. for (auto secondaryID : VLC->objtypeh->knownSubObjects(primaryID))
  1619. {
  1620. auto handler = VLC->objtypeh->getHandlerFor(primaryID, secondaryID);
  1621. if (!handler->isStaticObject() && handler->getRMGInfo().value)
  1622. {
  1623. for (auto temp : handler->getTemplates())
  1624. {
  1625. if (temp.canBePlacedAt(terrainType))
  1626. {
  1627. oi.generateObject = [gen, temp]() -> CGObjectInstance *
  1628. {
  1629. return VLC->objtypeh->getHandlerFor(temp.id, temp.subid)->create(temp);
  1630. };
  1631. auto rmgInfo = handler->getRMGInfo();
  1632. oi.value = rmgInfo.value;
  1633. oi.probability = rmgInfo.rarity;
  1634. oi.templ = temp;
  1635. oi.maxPerZone = rmgInfo.zoneLimit;
  1636. vstd::amin (oi.maxPerZone, rmgInfo.mapLimit / numZones); //simple, but should distribute objects evenly on large maps
  1637. possibleObjects.push_back (oi);
  1638. }
  1639. }
  1640. }
  1641. }
  1642. }
  1643. //prisons
  1644. //levels 1, 5, 10, 20, 30
  1645. static int prisonExp[] = {0, 5000, 15000, 90000, 500000};
  1646. static int prisonValues[] = {2500, 5000, 10000, 20000, 30000};
  1647. for (int i = 0; i < 5; i++)
  1648. {
  1649. oi.generateObject = [i, gen, this]() -> CGObjectInstance *
  1650. {
  1651. auto obj = new CGHeroInstance;
  1652. obj->ID = Obj::PRISON;
  1653. std::vector<ui32> possibleHeroes;
  1654. for (int j = 0; j < gen->map->allowedHeroes.size(); j++)
  1655. {
  1656. if (gen->map->allowedHeroes[j])
  1657. possibleHeroes.push_back(j);
  1658. }
  1659. auto hid = *RandomGeneratorUtil::nextItem(possibleHeroes, gen->rand);
  1660. obj->subID = hid; //will be initialized later
  1661. obj->exp = prisonExp[i]; //game crashes at hero level up
  1662. //obj->exp = 0;
  1663. obj->setOwner(PlayerColor::NEUTRAL);
  1664. gen->map->allowedHeroes[hid] = false; //ban this hero
  1665. gen->decreasePrisonsRemaining();
  1666. obj->appearance = VLC->objtypeh->getHandlerFor(Obj::PRISON, 0)->getTemplates(terrainType).front(); //can't init template with hero subID
  1667. return obj;
  1668. };
  1669. oi.setTemplate (Obj::PRISON, 0, terrainType);
  1670. oi.value = prisonValues[i];
  1671. oi.probability = 30;
  1672. oi.maxPerZone = gen->getPrisonsRemaning() / 5; //probably not perfect, but we can't generate more prisons than hereos.
  1673. possibleObjects.push_back (oi);
  1674. }
  1675. //all following objects are unlimited
  1676. oi.maxPerZone = std::numeric_limits<ui32>().max();
  1677. //dwellings
  1678. auto subObjects = VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1);
  1679. //don't spawn original "neutral" dwellings that got replaced by Conflux dwellings in AB
  1680. static int elementalConfluxROE[] = {7, 13, 16, 47};
  1681. for (int i = 0; i < 4; i++)
  1682. vstd::erase_if_present(subObjects, elementalConfluxROE[i]);
  1683. for (auto secondaryID : subObjects)
  1684. {
  1685. auto dwellingHandler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID).get());
  1686. auto creatures = dwellingHandler->getProducedCreatures();
  1687. if (creatures.empty())
  1688. continue;
  1689. auto cre = creatures.front();
  1690. if (cre->faction == townType)
  1691. {
  1692. float nativeZonesCount = gen->getZoneCount(cre->faction);
  1693. oi.value = cre->AIValue * cre->growth * (1 + (nativeZonesCount / gen->getTotalZoneCount()) + (nativeZonesCount / 2));
  1694. oi.probability = 40;
  1695. for (auto temp : dwellingHandler->getTemplates())
  1696. {
  1697. if (temp.canBePlacedAt(terrainType))
  1698. {
  1699. oi.generateObject = [gen, temp, secondaryID, dwellingHandler]() -> CGObjectInstance *
  1700. {
  1701. auto obj = VLC->objtypeh->getHandlerFor(Obj::CREATURE_GENERATOR1, secondaryID)->create(temp);
  1702. //dwellingHandler->configureObject(obj, gen->rand);
  1703. obj->tempOwner = PlayerColor::NEUTRAL;
  1704. return obj;
  1705. };
  1706. oi.templ = temp;
  1707. possibleObjects.push_back (oi);
  1708. }
  1709. }
  1710. }
  1711. }
  1712. static const int scrollValues[] = {500, 2000, 3000, 4000, 5000};
  1713. for (int i = 0; i < 5; i++)
  1714. {
  1715. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1716. {
  1717. auto obj = new CGArtifact();
  1718. obj->ID = Obj::SPELL_SCROLL;
  1719. obj->subID = 0;
  1720. std::vector<SpellID> out;
  1721. //TODO: unify with cb->getAllowedSpells?
  1722. for (ui32 i = 0; i < gen->map->allowedSpell.size(); i++) //spellh size appears to be greater (?)
  1723. {
  1724. const CSpell *spell = SpellID(i).toSpell();
  1725. if (gen->map->allowedSpell[spell->id] && spell->level == i+1)
  1726. {
  1727. out.push_back(spell->id);
  1728. }
  1729. }
  1730. auto a = CArtifactInstance::createScroll(RandomGeneratorUtil::nextItem(out, gen->rand)->toSpell());
  1731. gen->map->addNewArtifactInstance(a);
  1732. obj->storedArtifact = a;
  1733. return obj;
  1734. };
  1735. oi.setTemplate (Obj::SPELL_SCROLL, 0, terrainType);
  1736. oi.value = scrollValues[i];
  1737. oi.probability = 30;
  1738. possibleObjects.push_back (oi);
  1739. }
  1740. //pandora box with gold
  1741. for (int i = 1; i < 5; i++)
  1742. {
  1743. oi.generateObject = [i]() -> CGObjectInstance *
  1744. {
  1745. auto obj = new CGPandoraBox();
  1746. obj->ID = Obj::PANDORAS_BOX;
  1747. obj->subID = 0;
  1748. obj->resources[Res::GOLD] = i * 5000;
  1749. return obj;
  1750. };
  1751. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1752. oi.value = i * 5000;;
  1753. oi.probability = 5;
  1754. possibleObjects.push_back (oi);
  1755. }
  1756. //pandora box with experience
  1757. for (int i = 1; i < 5; i++)
  1758. {
  1759. oi.generateObject = [i]() -> CGObjectInstance *
  1760. {
  1761. auto obj = new CGPandoraBox();
  1762. obj->ID = Obj::PANDORAS_BOX;
  1763. obj->subID = 0;
  1764. obj->gainedExp = i * 5000;
  1765. return obj;
  1766. };
  1767. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1768. oi.value = i * 6000;;
  1769. oi.probability = 20;
  1770. possibleObjects.push_back (oi);
  1771. }
  1772. //pandora box with creatures
  1773. static const int tierValues[] = {5000, 7000, 9000, 12000, 16000, 21000, 27000};
  1774. for (auto creature : VLC->creh->creatures)
  1775. {
  1776. if (!creature->special && creature->faction == townType)
  1777. {
  1778. int actualTier = creature->level > 7 ? 6 : creature->level-1;
  1779. float creaturesAmount = tierValues[actualTier] / creature->AIValue;
  1780. if (creaturesAmount <= 5)
  1781. {
  1782. creaturesAmount = boost::math::round(creaturesAmount); //allow single monsters
  1783. if (creaturesAmount < 1)
  1784. continue;
  1785. }
  1786. else if (creaturesAmount <= 12)
  1787. {
  1788. (creaturesAmount /= 2) *= 2;
  1789. }
  1790. else if (creaturesAmount <= 50)
  1791. {
  1792. creaturesAmount = boost::math::round(creaturesAmount / 5) * 5;
  1793. }
  1794. else
  1795. {
  1796. creaturesAmount = boost::math::round(creaturesAmount / 10) * 10;
  1797. }
  1798. oi.generateObject = [creature, creaturesAmount]() -> CGObjectInstance *
  1799. {
  1800. auto obj = new CGPandoraBox();
  1801. obj->ID = Obj::PANDORAS_BOX;
  1802. obj->subID = 0;
  1803. auto stack = new CStackInstance(creature, creaturesAmount);
  1804. obj->creatures.putStack(SlotID(0), stack);
  1805. return obj;
  1806. };
  1807. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1808. oi.value = (2 * (creature->AIValue) * creaturesAmount * (1 + (float)(gen->getZoneCount(creature->faction)) / gen->getTotalZoneCount()))/3; //TODO: count number of towns on the map
  1809. oi.probability = 3;
  1810. possibleObjects.push_back (oi);
  1811. }
  1812. }
  1813. //Pandora with 12 spells of certain level
  1814. for (int i = 1; i <= GameConstants::SPELL_LEVELS; i++)
  1815. {
  1816. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1817. {
  1818. auto obj = new CGPandoraBox();
  1819. obj->ID = Obj::PANDORAS_BOX;
  1820. obj->subID = 0;
  1821. std::vector <CSpell *> spells;
  1822. for (auto spell : VLC->spellh->objects)
  1823. {
  1824. if (!spell->isSpecialSpell() && spell->level == i)
  1825. spells.push_back(spell);
  1826. }
  1827. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1828. for (int j = 0; j < std::min<int>(12, spells.size()); j++)
  1829. {
  1830. obj->spells.push_back (spells[j]->id);
  1831. }
  1832. return obj;
  1833. };
  1834. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1835. oi.value = (i + 1) * 2500; //5000 - 15000
  1836. oi.probability = 2;
  1837. possibleObjects.push_back (oi);
  1838. }
  1839. //Pandora with 15 spells of certain school
  1840. for (int i = 1; i <= 4; i++)
  1841. {
  1842. oi.generateObject = [i, gen]() -> CGObjectInstance *
  1843. {
  1844. auto obj = new CGPandoraBox();
  1845. obj->ID = Obj::PANDORAS_BOX;
  1846. obj->subID = 0;
  1847. std::vector <CSpell *> spells;
  1848. for (auto spell : VLC->spellh->objects)
  1849. {
  1850. if (!spell->isSpecialSpell())
  1851. {
  1852. bool school = false; //TODO: we could have better interface for iterating schools
  1853. switch (i)
  1854. {
  1855. case 1:
  1856. school = spell->air;
  1857. break;
  1858. case 2:
  1859. school = spell->earth;
  1860. break;
  1861. case 3:
  1862. school = spell->fire;
  1863. break;
  1864. case 4:
  1865. school = spell->water;
  1866. break;
  1867. }
  1868. if (school)
  1869. spells.push_back(spell);
  1870. }
  1871. }
  1872. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1873. for (int j = 0; j < std::min<int>(15, spells.size()); j++)
  1874. {
  1875. obj->spells.push_back (spells[j]->id);
  1876. }
  1877. return obj;
  1878. };
  1879. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1880. oi.value = 15000;
  1881. oi.probability = 2;
  1882. possibleObjects.push_back (oi);
  1883. }
  1884. // Pandora box with 60 random spells
  1885. oi.generateObject = [gen]() -> CGObjectInstance *
  1886. {
  1887. auto obj = new CGPandoraBox();
  1888. obj->ID = Obj::PANDORAS_BOX;
  1889. obj->subID = 0;
  1890. std::vector <CSpell *> spells;
  1891. for (auto spell : VLC->spellh->objects)
  1892. {
  1893. if (!spell->isSpecialSpell())
  1894. spells.push_back(spell);
  1895. }
  1896. RandomGeneratorUtil::randomShuffle(spells, gen->rand);
  1897. for (int j = 0; j < std::min<int>(60, spells.size()); j++)
  1898. {
  1899. obj->spells.push_back (spells[j]->id);
  1900. }
  1901. return obj;
  1902. };
  1903. oi.setTemplate (Obj::PANDORAS_BOX, 0, terrainType);
  1904. oi.value = 3000;
  1905. oi.probability = 2;
  1906. possibleObjects.push_back (oi);
  1907. }
  1908. void ObjectInfo::setTemplate (si32 type, si32 subtype, ETerrainType terrainType)
  1909. {
  1910. templ = VLC->objtypeh->getHandlerFor(type, subtype)->getTemplates(terrainType).front();
  1911. }