CRmgTemplateZone.cpp 62 KB

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