Zone.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * Zone.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 "Zone.h"
  12. #include "RmgMap.h"
  13. #include "Functions.h"
  14. #include "TileInfo.h"
  15. #include "CMapGenerator.h"
  16. #include "RmgPath.h"
  17. #include "modificators/ObjectManager.h"
  18. #include "../CRandomGenerator.h"
  19. #include <vstd/RNG.h>
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. const std::function<bool(const int3 &)> AREA_NO_FILTER = [](const int3 & t)
  22. {
  23. return true;
  24. };
  25. Zone::Zone(RmgMap & map, CMapGenerator & generator, vstd::RNG & r)
  26. : finished(false)
  27. , townType(ETownType::NEUTRAL)
  28. , terrainType(ETerrainId::GRASS)
  29. , map(map)
  30. , rand(std::make_unique<CRandomGenerator>(r.nextInt()))
  31. , generator(generator)
  32. {
  33. }
  34. Zone::~Zone() = default;
  35. bool Zone::isUnderground() const
  36. {
  37. return getPos().z;
  38. }
  39. void Zone::setOptions(const ZoneOptions& options)
  40. {
  41. ZoneOptions::operator=(options);
  42. }
  43. float3 Zone::getCenter() const
  44. {
  45. return center;
  46. }
  47. void Zone::setCenter(const float3 &f)
  48. {
  49. //limit boundaries to (0,1) square
  50. //alternate solution - wrap zone around unitary square. If it doesn't fit on one side, will come out on the opposite side
  51. center = f;
  52. center.x = static_cast<float>(std::fmod(center.x, 1));
  53. center.y = static_cast<float>(std::fmod(center.y, 1));
  54. if(center.x < 0) //fmod seems to work only for positive numbers? we want to stay positive
  55. center.x = 1 - std::abs(center.x);
  56. if(center.y < 0)
  57. center.y = 1 - std::abs(center.y);
  58. }
  59. int3 Zone::getPos() const
  60. {
  61. return pos;
  62. }
  63. void Zone::setPos(const int3 &Pos)
  64. {
  65. pos = Pos;
  66. }
  67. ThreadSafeProxy<rmg::Area> Zone::area()
  68. {
  69. return ThreadSafeProxy<rmg::Area>(dArea, areaMutex);
  70. }
  71. ThreadSafeProxy<const rmg::Area> Zone::area() const
  72. {
  73. return ThreadSafeProxy<const rmg::Area>(dArea, areaMutex);
  74. }
  75. ThreadSafeProxy<rmg::Area> Zone::areaPossible()
  76. {
  77. return ThreadSafeProxy<rmg::Area>(dAreaPossible, areaMutex);
  78. }
  79. ThreadSafeProxy<const rmg::Area> Zone::areaPossible() const
  80. {
  81. return ThreadSafeProxy<const rmg::Area>(dAreaPossible, areaMutex);
  82. }
  83. ThreadSafeProxy<rmg::Area> Zone::freePaths()
  84. {
  85. return ThreadSafeProxy<rmg::Area>(dAreaFree, areaMutex);
  86. }
  87. ThreadSafeProxy<const rmg::Area> Zone::freePaths() const
  88. {
  89. return ThreadSafeProxy<const rmg::Area>(dAreaFree, areaMutex);
  90. }
  91. ThreadSafeProxy<rmg::Area> Zone::areaUsed()
  92. {
  93. return ThreadSafeProxy<rmg::Area>(dAreaUsed, areaMutex);
  94. }
  95. ThreadSafeProxy<const rmg::Area> Zone::areaUsed() const
  96. {
  97. return ThreadSafeProxy<const rmg::Area>(dAreaUsed, areaMutex);
  98. }
  99. rmg::Area Zone::areaForRoads() const
  100. {
  101. return areaPossible() + freePaths();
  102. }
  103. void Zone::clearTiles()
  104. {
  105. Lock lock(areaMutex);
  106. dArea.clear();
  107. dAreaPossible.clear();
  108. dAreaFree.clear();
  109. }
  110. void Zone::initFreeTiles()
  111. {
  112. rmg::Tileset possibleTiles;
  113. vstd::copy_if(dArea.getTiles(), vstd::set_inserter(possibleTiles), [this](const int3 &tile) -> bool
  114. {
  115. return map.isPossible(tile);
  116. });
  117. dAreaPossible.assign(possibleTiles);
  118. if(dAreaFree.empty() && getType() != ETemplateZoneType::SEALED)
  119. {
  120. // Fixme: This might fail fot water zone, which doesn't need to have a tile in its center of the mass
  121. dAreaPossible.erase(pos);
  122. dAreaFree.add(pos); //zone must have at least one free tile where other paths go - for instance in the center
  123. }
  124. }
  125. FactionID Zone::getTownType() const
  126. {
  127. return townType;
  128. }
  129. void Zone::setTownType(FactionID town)
  130. {
  131. townType = town;
  132. }
  133. TerrainId Zone::getTerrainType() const
  134. {
  135. return terrainType;
  136. }
  137. void Zone::setTerrainType(TerrainId terrain)
  138. {
  139. terrainType = terrain;
  140. }
  141. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, const std::function<bool(const int3 &)> & areafilter) const
  142. ///connect current tile to any other free tile within zone
  143. {
  144. auto movementCost = [this](const int3 & s, const int3 & d)
  145. {
  146. if(map.isFree(d))
  147. return 1;
  148. else if (map.isPossible(d))
  149. return 2;
  150. return 3;
  151. };
  152. auto area = (dAreaPossible + dAreaFree).getSubarea(areafilter);
  153. rmg::Path freePath(area);
  154. rmg::Path resultPath(area);
  155. freePath.connect(dAreaFree);
  156. //connect to all pieces
  157. auto goals = connectedAreas(src, onlyStraight);
  158. for(auto & goal : goals)
  159. {
  160. auto path = freePath.search(goal, onlyStraight, movementCost);
  161. if(path.getPathArea().empty())
  162. return rmg::Path::invalid();
  163. freePath.connect(path.getPathArea());
  164. resultPath.connect(path.getPathArea());
  165. }
  166. return resultPath;
  167. }
  168. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, const rmg::Area & searchArea) const
  169. ///connect current tile to any other free tile within searchArea
  170. {
  171. auto movementCost = [this](const int3 & s, const int3 & d)
  172. {
  173. if(map.isFree(d))
  174. return 1;
  175. else if (map.isPossible(d))
  176. return 2;
  177. return 3;
  178. };
  179. rmg::Path freePath(searchArea);
  180. rmg::Path resultPath(searchArea);
  181. freePath.connect(dAreaFree);
  182. //connect to all pieces
  183. auto goals = connectedAreas(src, onlyStraight);
  184. for(auto & goal : goals)
  185. {
  186. auto path = freePath.search(goal, onlyStraight, movementCost);
  187. if(path.getPathArea().empty())
  188. return rmg::Path::invalid();
  189. freePath.connect(path.getPathArea());
  190. resultPath.connect(path.getPathArea());
  191. }
  192. return resultPath;
  193. }
  194. rmg::Path Zone::searchPath(const int3 & src, bool onlyStraight, const std::function<bool(const int3 &)> & areafilter) const
  195. ///connect current tile to any other free tile within zone
  196. {
  197. return searchPath(rmg::Area({ src }), onlyStraight, areafilter);
  198. }
  199. TModificators Zone::getModificators()
  200. {
  201. return modificators;
  202. }
  203. void Zone::connectPath(const rmg::Path & path)
  204. ///connect current tile to any other free tile within zone
  205. {
  206. areaPossible()->subtract(path.getPathArea());
  207. freePaths()->unite(path.getPathArea());
  208. for(const auto & t : path.getPathArea().getTilesVector())
  209. map.setOccupied(t, ETileType::FREE);
  210. }
  211. void Zone::fractalize()
  212. {
  213. //Squared
  214. float minDistance = 9 * 9;
  215. float freeDistance = pos.z ? (10 * 10) : (9 * 9);
  216. float spanFactor = (pos.z ? 0.3f : 0.45f); //Narrower passages in the Underground
  217. float marginFactor = 1.0f;
  218. int treasureValue = 0;
  219. int treasureDensity = 0;
  220. for (const auto & t : treasureInfo)
  221. {
  222. treasureValue += ((t.min + t.max) / 2) * t.density / 1000.f; //Thousands
  223. treasureDensity += t.density;
  224. }
  225. if (getType() == ETemplateZoneType::WATER)
  226. {
  227. // Set very little obstacles on water
  228. spanFactor = 0.2;
  229. }
  230. else //Scale with treasure density
  231. {
  232. if (treasureValue > 250)
  233. {
  234. // A quarter at max density - means more free space
  235. marginFactor = (0.6f + ((std::max(0, (600 - treasureValue))) / (600.f - 250)) * 0.4f);
  236. // Low value - dense obstacles
  237. spanFactor *= (0.6f + ((std::max(0, (600 - treasureValue))) / (600.f - 250)) * 0.4f);
  238. }
  239. else if (treasureValue < 100)
  240. {
  241. //Dense obstacles
  242. spanFactor *= (0.5 + 0.5 * (treasureValue / 100.f));
  243. vstd::amax(spanFactor, 0.15f);
  244. }
  245. if (treasureDensity <= 10)
  246. {
  247. vstd::amin(spanFactor, 0.1f + 0.01f * treasureDensity); //Add extra obstacles to fill up space
  248. }
  249. }
  250. float blockDistance = minDistance * spanFactor; //More obstacles in the Underground
  251. freeDistance = freeDistance * marginFactor;
  252. vstd::amax(freeDistance, 4 * 4);
  253. logGlobal->trace("Zone %d: treasureValue %d blockDistance: %2.f, freeDistance: %2.f", getId(), treasureValue, blockDistance, freeDistance);
  254. Lock lock(areaMutex);
  255. rmg::Area clearedTiles(dAreaFree);
  256. rmg::Area possibleTiles(dAreaPossible);
  257. rmg::Area tilesToIgnore; //will be erased in this iteration
  258. if(type != ETemplateZoneType::JUNCTION)
  259. {
  260. //junction is not fractalized, has only one straight path
  261. //everything else remains blocked
  262. while(!possibleTiles.empty())
  263. {
  264. //link tiles in random order
  265. std::vector<int3> tilesToMakePath = possibleTiles.getTilesVector();
  266. // Do not fractalize tiles near the edge of the map to avoid paths adjacent to map edge
  267. const auto h = map.height();
  268. const auto w = map.width();
  269. const size_t MARGIN = 3;
  270. vstd::erase_if(tilesToMakePath, [&, h, w](const int3 & tile)
  271. {
  272. return tile.x < MARGIN || tile.x > (w - MARGIN) ||
  273. tile.y < MARGIN || tile.y > (h - MARGIN);
  274. });
  275. RandomGeneratorUtil::randomShuffle(tilesToMakePath, getRand());
  276. int3 nodeFound(-1, -1, -1);
  277. for(const auto & tileToMakePath : tilesToMakePath)
  278. {
  279. //find closest free tile
  280. int3 closestTile = clearedTiles.nearest(tileToMakePath);
  281. if(closestTile.dist2dSQ(tileToMakePath) <= freeDistance)
  282. tilesToIgnore.add(tileToMakePath);
  283. else
  284. {
  285. //if tiles are not close enough, make path to it
  286. nodeFound = tileToMakePath;
  287. clearedTiles.add(nodeFound); //from now on nearby tiles will be considered handled
  288. break; //next iteration - use already cleared tiles
  289. }
  290. }
  291. possibleTiles.subtract(tilesToIgnore);
  292. if(!nodeFound.valid()) //nothing else can be done (?)
  293. break;
  294. tilesToIgnore.clear();
  295. }
  296. }
  297. else if (type == ETemplateZoneType::SEALED)
  298. {
  299. //Completely block all the tiles in the zone
  300. auto tiles = areaPossible()->getTiles();
  301. for(const auto & t : tiles)
  302. map.setOccupied(t, ETileType::BLOCKED);
  303. possibleTiles.clear();
  304. dAreaFree.clear();
  305. return;
  306. }
  307. else
  308. {
  309. // Handle special case - place Monoliths at the edge of a zone
  310. auto objectManager = getModificator<ObjectManager>();
  311. if (objectManager)
  312. {
  313. objectManager->createMonoliths();
  314. }
  315. }
  316. //Connect with free areas
  317. auto areas = connectedAreas(clearedTiles, true);
  318. for(auto & area : areas)
  319. {
  320. if(dAreaFree.overlap(area))
  321. continue; //already found
  322. auto availableArea = dAreaPossible + dAreaFree;
  323. rmg::Path path(availableArea);
  324. path.connect(dAreaFree);
  325. auto res = path.search(area, true);
  326. if(res.getPathArea().empty())
  327. {
  328. dAreaPossible.subtract(area);
  329. dAreaFree.subtract(area);
  330. for(const auto & t : area.getTiles())
  331. map.setOccupied(t, ETileType::BLOCKED);
  332. }
  333. else
  334. {
  335. dAreaPossible.subtract(res.getPathArea());
  336. dAreaFree.unite(res.getPathArea());
  337. for(const auto & t : res.getPathArea().getTiles())
  338. map.setOccupied(t, ETileType::FREE);
  339. }
  340. }
  341. //now block most distant tiles away from passages
  342. auto areaToBlock = dArea.getSubarea([this, blockDistance](const int3 & t)
  343. {
  344. auto distance = static_cast<float>(dAreaFree.distanceSqr(t));
  345. return distance > blockDistance;
  346. });
  347. dAreaPossible.subtract(areaToBlock);
  348. dAreaFree.subtract(areaToBlock);
  349. lock.unlock();
  350. for(const auto & t : areaToBlock.getTiles())
  351. map.setOccupied(t, ETileType::BLOCKED);
  352. }
  353. void Zone::initModificators()
  354. {
  355. for(auto & modificator : modificators)
  356. {
  357. modificator->init();
  358. }
  359. }
  360. vstd::RNG& Zone::getRand()
  361. {
  362. return *rand;
  363. }
  364. VCMI_LIB_NAMESPACE_END