CRmgTemplateZone.cpp 59 KB

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