Zone.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. void Zone::clearTiles()
  100. {
  101. Lock lock(areaMutex);
  102. dArea.clear();
  103. dAreaPossible.clear();
  104. dAreaFree.clear();
  105. }
  106. void Zone::initFreeTiles()
  107. {
  108. rmg::Tileset possibleTiles;
  109. vstd::copy_if(dArea.getTiles(), vstd::set_inserter(possibleTiles), [this](const int3 &tile) -> bool
  110. {
  111. return map.isPossible(tile);
  112. });
  113. dAreaPossible.assign(possibleTiles);
  114. if(dAreaFree.empty())
  115. {
  116. // Fixme: This might fail fot water zone, which doesn't need to have a tile in its center of the mass
  117. dAreaPossible.erase(pos);
  118. dAreaFree.add(pos); //zone must have at least one free tile where other paths go - for instance in the center
  119. }
  120. }
  121. FactionID Zone::getTownType() const
  122. {
  123. return townType;
  124. }
  125. void Zone::setTownType(FactionID town)
  126. {
  127. townType = town;
  128. }
  129. TerrainId Zone::getTerrainType() const
  130. {
  131. return terrainType;
  132. }
  133. void Zone::setTerrainType(TerrainId terrain)
  134. {
  135. terrainType = terrain;
  136. }
  137. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, const std::function<bool(const int3 &)> & areafilter) const
  138. ///connect current tile to any other free tile within zone
  139. {
  140. auto movementCost = [this](const int3 & s, const int3 & d)
  141. {
  142. if(map.isFree(d))
  143. return 1;
  144. else if (map.isPossible(d))
  145. return 2;
  146. return 3;
  147. };
  148. auto area = (dAreaPossible + dAreaFree).getSubarea(areafilter);
  149. rmg::Path freePath(area);
  150. rmg::Path resultPath(area);
  151. freePath.connect(dAreaFree);
  152. //connect to all pieces
  153. auto goals = connectedAreas(src, onlyStraight);
  154. for(auto & goal : goals)
  155. {
  156. auto path = freePath.search(goal, onlyStraight, movementCost);
  157. if(path.getPathArea().empty())
  158. return rmg::Path::invalid();
  159. freePath.connect(path.getPathArea());
  160. resultPath.connect(path.getPathArea());
  161. }
  162. return resultPath;
  163. }
  164. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, const rmg::Area & searchArea) const
  165. ///connect current tile to any other free tile within searchArea
  166. {
  167. auto movementCost = [this](const int3 & s, const int3 & d)
  168. {
  169. if(map.isFree(d))
  170. return 1;
  171. else if (map.isPossible(d))
  172. return 2;
  173. return 3;
  174. };
  175. rmg::Path freePath(searchArea);
  176. rmg::Path resultPath(searchArea);
  177. freePath.connect(dAreaFree);
  178. //connect to all pieces
  179. auto goals = connectedAreas(src, onlyStraight);
  180. for(auto & goal : goals)
  181. {
  182. auto path = freePath.search(goal, onlyStraight, movementCost);
  183. if(path.getPathArea().empty())
  184. return rmg::Path::invalid();
  185. freePath.connect(path.getPathArea());
  186. resultPath.connect(path.getPathArea());
  187. }
  188. return resultPath;
  189. }
  190. rmg::Path Zone::searchPath(const int3 & src, bool onlyStraight, const std::function<bool(const int3 &)> & areafilter) const
  191. ///connect current tile to any other free tile within zone
  192. {
  193. return searchPath(rmg::Area({ src }), onlyStraight, areafilter);
  194. }
  195. TModificators Zone::getModificators()
  196. {
  197. return modificators;
  198. }
  199. void Zone::connectPath(const rmg::Path & path)
  200. ///connect current tile to any other free tile within zone
  201. {
  202. areaPossible()->subtract(path.getPathArea());
  203. freePaths()->unite(path.getPathArea());
  204. for(const auto & t : path.getPathArea().getTilesVector())
  205. map.setOccupied(t, ETileType::FREE);
  206. }
  207. void Zone::fractalize()
  208. {
  209. //Squared
  210. float minDistance = 9 * 9;
  211. float freeDistance = pos.z ? (10 * 10) : (9 * 9);
  212. float spanFactor = (pos.z ? 0.3f : 0.45f); //Narrower passages in the Underground
  213. float marginFactor = 1.0f;
  214. int treasureValue = 0;
  215. int treasureDensity = 0;
  216. for (const auto & t : treasureInfo)
  217. {
  218. treasureValue += ((t.min + t.max) / 2) * t.density / 1000.f; //Thousands
  219. treasureDensity += t.density;
  220. }
  221. if (getType() == ETemplateZoneType::WATER)
  222. {
  223. // Set very little obstacles on water
  224. spanFactor = 0.2;
  225. }
  226. else //Scale with treasure density
  227. {
  228. if (treasureValue > 250)
  229. {
  230. // A quarter at max density - means more free space
  231. marginFactor = (0.6f + ((std::max(0, (600 - treasureValue))) / (600.f - 250)) * 0.4f);
  232. // Low value - dense obstacles
  233. spanFactor *= (0.6f + ((std::max(0, (600 - treasureValue))) / (600.f - 250)) * 0.4f);
  234. }
  235. else if (treasureValue < 100)
  236. {
  237. //Dense obstacles
  238. spanFactor *= (0.5 + 0.5 * (treasureValue / 100.f));
  239. vstd::amax(spanFactor, 0.15f);
  240. }
  241. if (treasureDensity <= 10)
  242. {
  243. vstd::amin(spanFactor, 0.1f + 0.01f * treasureDensity); //Add extra obstacles to fill up space
  244. }
  245. }
  246. float blockDistance = minDistance * spanFactor; //More obstacles in the Underground
  247. freeDistance = freeDistance * marginFactor;
  248. vstd::amax(freeDistance, 4 * 4);
  249. logGlobal->trace("Zone %d: treasureValue %d blockDistance: %2.f, freeDistance: %2.f", getId(), treasureValue, blockDistance, freeDistance);
  250. Lock lock(areaMutex);
  251. // FIXME: Do not access Area directly
  252. rmg::Area clearedTiles(dAreaFree);
  253. rmg::Area possibleTiles(dAreaPossible);
  254. rmg::Area tilesToIgnore; //will be erased in this iteration
  255. if(type != ETemplateZoneType::JUNCTION)
  256. {
  257. //junction is not fractalized, has only one straight path
  258. //everything else remains blocked
  259. while(!possibleTiles.empty())
  260. {
  261. //link tiles in random order
  262. std::vector<int3> tilesToMakePath = possibleTiles.getTilesVector();
  263. // Do not fractalize tiles near the edge of the map to avoid paths adjacent to map edge
  264. const auto h = map.height();
  265. const auto w = map.width();
  266. const size_t MARGIN = 3;
  267. vstd::erase_if(tilesToMakePath, [&, h, w](const int3 & tile)
  268. {
  269. return tile.x < MARGIN || tile.x > (w - MARGIN) ||
  270. tile.y < MARGIN || tile.y > (h - MARGIN);
  271. });
  272. RandomGeneratorUtil::randomShuffle(tilesToMakePath, getRand());
  273. int3 nodeFound(-1, -1, -1);
  274. for(const auto & tileToMakePath : tilesToMakePath)
  275. {
  276. //find closest free tile
  277. int3 closestTile = clearedTiles.nearest(tileToMakePath);
  278. if(closestTile.dist2dSQ(tileToMakePath) <= freeDistance)
  279. tilesToIgnore.add(tileToMakePath);
  280. else
  281. {
  282. //if tiles are not close enough, make path to it
  283. nodeFound = tileToMakePath;
  284. clearedTiles.add(nodeFound); //from now on nearby tiles will be considered handled
  285. break; //next iteration - use already cleared tiles
  286. }
  287. }
  288. possibleTiles.subtract(tilesToIgnore);
  289. if(!nodeFound.valid()) //nothing else can be done (?)
  290. break;
  291. tilesToIgnore.clear();
  292. }
  293. }
  294. else
  295. {
  296. // Handle special case - place Monoliths at the edge of a zone
  297. auto objectManager = getModificator<ObjectManager>();
  298. if (objectManager)
  299. {
  300. objectManager->createMonoliths();
  301. }
  302. }
  303. //Connect with free areas
  304. auto areas = connectedAreas(clearedTiles, true);
  305. for(auto & area : areas)
  306. {
  307. if(dAreaFree.overlap(area))
  308. continue; //already found
  309. auto availableArea = dAreaPossible + dAreaFree;
  310. rmg::Path path(availableArea);
  311. path.connect(dAreaFree);
  312. auto res = path.search(area, true);
  313. if(res.getPathArea().empty())
  314. {
  315. dAreaPossible.subtract(area);
  316. dAreaFree.subtract(area);
  317. for(const auto & t : area.getTiles())
  318. map.setOccupied(t, ETileType::BLOCKED);
  319. }
  320. else
  321. {
  322. dAreaPossible.subtract(res.getPathArea());
  323. dAreaFree.unite(res.getPathArea());
  324. for(const auto & t : res.getPathArea().getTiles())
  325. map.setOccupied(t, ETileType::FREE);
  326. }
  327. }
  328. //now block most distant tiles away from passages
  329. auto areaToBlock = dArea.getSubarea([this, blockDistance](const int3 & t)
  330. {
  331. auto distance = static_cast<float>(dAreaFree.distanceSqr(t));
  332. return distance > blockDistance;
  333. });
  334. dAreaPossible.subtract(areaToBlock);
  335. dAreaFree.subtract(areaToBlock);
  336. lock.unlock();
  337. for(const auto & t : areaToBlock.getTiles())
  338. map.setOccupied(t, ETileType::BLOCKED);
  339. }
  340. void Zone::initModificators()
  341. {
  342. for(auto & modificator : modificators)
  343. {
  344. modificator->init();
  345. }
  346. }
  347. vstd::RNG& Zone::getRand()
  348. {
  349. return *rand;
  350. }
  351. VCMI_LIB_NAMESPACE_END