CRmgTemplateZone.cpp 62 KB

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