CRmgTemplateZone.cpp 66 KB

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