Zone.cpp 10 KB

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