Zone.cpp 9.2 KB

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