Zone.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 "../mapping/CMap.h"
  16. #include "../CStopWatch.h"
  17. #include "CMapGenerator.h"
  18. #include "RmgPath.h"
  19. std::function<bool(const int3 &)> AREA_NO_FILTER = [](const int3 & t)
  20. {
  21. return true;
  22. };
  23. Zone::Zone(RmgMap & map, CMapGenerator & generator)
  24. : ZoneOptions(),
  25. townType(ETownType::NEUTRAL),
  26. terrainType(Terrain("grass")),
  27. map(map),
  28. generator(generator)
  29. {
  30. }
  31. bool Zone::isUnderground() const
  32. {
  33. return getPos().z;
  34. }
  35. void Zone::setOptions(const ZoneOptions& options)
  36. {
  37. ZoneOptions::operator=(options);
  38. }
  39. float3 Zone::getCenter() const
  40. {
  41. return center;
  42. }
  43. void Zone::setCenter(const float3 &f)
  44. {
  45. //limit boundaries to (0,1) square
  46. //alternate solution - wrap zone around unitary square. If it doesn't fit on one side, will come out on the opposite side
  47. center = f;
  48. center.x = static_cast<float>(std::fmod(center.x, 1));
  49. center.y = static_cast<float>(std::fmod(center.y, 1));
  50. if(center.x < 0) //fmod seems to work only for positive numbers? we want to stay positive
  51. center.x = 1 - std::abs(center.x);
  52. if(center.y < 0)
  53. center.y = 1 - std::abs(center.y);
  54. }
  55. int3 Zone::getPos() const
  56. {
  57. return pos;
  58. }
  59. void Zone::setPos(const int3 &Pos)
  60. {
  61. pos = Pos;
  62. }
  63. const rmg::Area & Zone::getArea() const
  64. {
  65. return dArea;
  66. }
  67. rmg::Area & Zone::area()
  68. {
  69. return dArea;
  70. }
  71. rmg::Area & Zone::areaPossible()
  72. {
  73. return dAreaPossible;
  74. }
  75. rmg::Area & Zone::areaUsed()
  76. {
  77. return dAreaUsed;
  78. }
  79. void Zone::clearTiles()
  80. {
  81. dArea.clear();
  82. dAreaPossible.clear();
  83. dAreaFree.clear();
  84. }
  85. void Zone::initFreeTiles()
  86. {
  87. rmg::Tileset possibleTiles;
  88. vstd::copy_if(dArea.getTiles(), vstd::set_inserter(possibleTiles), [this](const int3 &tile) -> bool
  89. {
  90. return map.isPossible(tile);
  91. });
  92. dAreaPossible.assign(possibleTiles);
  93. if(dAreaFree.empty())
  94. {
  95. dAreaPossible.erase(pos);
  96. dAreaFree.add(pos); //zone must have at least one free tile where other paths go - for instance in the center
  97. }
  98. }
  99. rmg::Area & Zone::freePaths()
  100. {
  101. return dAreaFree;
  102. }
  103. si32 Zone::getTownType() const
  104. {
  105. return townType;
  106. }
  107. void Zone::setTownType(si32 town)
  108. {
  109. townType = town;
  110. }
  111. const Terrain & Zone::getTerrainType() const
  112. {
  113. return terrainType;
  114. }
  115. void Zone::setTerrainType(const Terrain & terrain)
  116. {
  117. terrainType = terrain;
  118. }
  119. rmg::Path Zone::searchPath(const rmg::Area & src, bool onlyStraight, std::function<bool(const int3 &)> areafilter) const
  120. ///connect current tile to any other free tile within zone
  121. {
  122. auto movementCost = [this](const int3 & s, const int3 & d)
  123. {
  124. if(map.isFree(d))
  125. return 1;
  126. else if (map.isPossible(d))
  127. return 2;
  128. return 3;
  129. };
  130. auto area = (dAreaPossible + dAreaFree).getSubarea(areafilter);
  131. rmg::Path freePath(area), resultPath(area);
  132. freePath.connect(dAreaFree);
  133. //connect to all pieces
  134. auto goals = connectedAreas(src, onlyStraight);
  135. for(auto & goal : goals)
  136. {
  137. auto path = freePath.search(goal, onlyStraight, movementCost);
  138. if(path.getPathArea().empty())
  139. return rmg::Path::invalid();
  140. freePath.connect(path.getPathArea());
  141. resultPath.connect(path.getPathArea());
  142. }
  143. return resultPath;
  144. }
  145. rmg::Path Zone::searchPath(const int3 & src, bool onlyStraight, std::function<bool(const int3 &)> areafilter) const
  146. ///connect current tile to any other free tile within zone
  147. {
  148. return searchPath(rmg::Area({src}), onlyStraight, areafilter);
  149. }
  150. void Zone::connectPath(const rmg::Path & path)
  151. ///connect current tile to any other free tile within zone
  152. {
  153. dAreaPossible.subtract(path.getPathArea());
  154. dAreaFree.unite(path.getPathArea());
  155. for(auto & t : path.getPathArea().getTilesVector())
  156. map.setOccupied(t, ETileType::FREE);
  157. }
  158. void Zone::fractalize()
  159. {
  160. rmg::Area clearedTiles(dAreaFree);
  161. rmg::Area possibleTiles(dAreaPossible);
  162. rmg::Area tilesToIgnore; //will be erased in this iteration
  163. //the more treasure density, the greater distance between paths. Scaling is experimental.
  164. int totalDensity = 0;
  165. for(auto ti : treasureInfo)
  166. totalDensity += ti.density;
  167. const float minDistance = 10 * 10; //squared
  168. if(type != ETemplateZoneType::JUNCTION)
  169. {
  170. //junction is not fractalized, has only one straight path
  171. //everything else remains blocked
  172. while(!possibleTiles.empty())
  173. {
  174. //link tiles in random order
  175. std::vector<int3> tilesToMakePath = possibleTiles.getTilesVector();
  176. RandomGeneratorUtil::randomShuffle(tilesToMakePath, generator.rand);
  177. int3 nodeFound(-1, -1, -1);
  178. for(auto tileToMakePath : tilesToMakePath)
  179. {
  180. //find closest free tile
  181. int3 closestTile = clearedTiles.nearest(tileToMakePath);
  182. if(closestTile.dist2dSQ(tileToMakePath) <= minDistance)
  183. tilesToIgnore.add(tileToMakePath);
  184. else
  185. {
  186. //if tiles are not close enough, make path to it
  187. nodeFound = tileToMakePath;
  188. clearedTiles.add(nodeFound); //from now on nearby tiles will be considered handled
  189. break; //next iteration - use already cleared tiles
  190. }
  191. }
  192. possibleTiles.subtract(tilesToIgnore);
  193. if(!nodeFound.valid()) //nothing else can be done (?)
  194. break;
  195. tilesToIgnore.clear();
  196. }
  197. }
  198. //cut straight paths towards the center. A* is too slow for that.
  199. auto areas = connectedAreas(clearedTiles, false);
  200. for(auto & area : areas)
  201. {
  202. if(dAreaFree.overlap(area))
  203. continue; //already found
  204. auto availableArea = dAreaPossible + dAreaFree;
  205. rmg::Path path(availableArea);
  206. path.connect(dAreaFree);
  207. auto res = path.search(area, false);
  208. if(res.getPathArea().empty())
  209. {
  210. dAreaPossible.subtract(area);
  211. dAreaFree.subtract(area);
  212. for(auto & t : area.getTiles())
  213. map.setOccupied(t, ETileType::BLOCKED);
  214. }
  215. else
  216. {
  217. dAreaPossible.subtract(res.getPathArea());
  218. dAreaFree.unite(res.getPathArea());
  219. for(auto & t : res.getPathArea().getTiles())
  220. map.setOccupied(t, ETileType::FREE);
  221. }
  222. }
  223. //now block most distant tiles away from passages
  224. float blockDistance = minDistance * 0.25f;
  225. auto areaToBlock = dArea.getSubarea([this, blockDistance](const int3 & t)
  226. {
  227. float distance = static_cast<float>(dAreaFree.distanceSqr(t));
  228. return distance > blockDistance;
  229. });
  230. dAreaPossible.subtract(areaToBlock);
  231. dAreaFree.subtract(areaToBlock);
  232. for(auto & t : areaToBlock.getTiles())
  233. map.setOccupied(t, ETileType::BLOCKED);
  234. }
  235. void Zone::initModificators()
  236. {
  237. for(auto & modificator : modificators)
  238. {
  239. modificator->init();
  240. }
  241. logGlobal->info("Zone %d modificators initialized", getId());
  242. }
  243. void Zone::processModificators()
  244. {
  245. for(auto & modificator : modificators)
  246. {
  247. try
  248. {
  249. modificator->run();
  250. }
  251. catch (const rmgException & e)
  252. {
  253. logGlobal->info("Zone %d, modificator %s - FAILED: %s", getId(), e.what());
  254. throw e;
  255. }
  256. }
  257. logGlobal->info("Zone %d filled successfully", getId());
  258. }
  259. Modificator::Modificator(Zone & zone, RmgMap & map, CMapGenerator & generator) : zone(zone), map(map), generator(generator)
  260. {
  261. }
  262. void Modificator::setName(const std::string & n)
  263. {
  264. name = n;
  265. }
  266. const std::string & Modificator::getName() const
  267. {
  268. return name;
  269. }
  270. bool Modificator::isFinished() const
  271. {
  272. return finished;
  273. }
  274. void Modificator::run()
  275. {
  276. started = true;
  277. if(!finished)
  278. {
  279. for(auto * modificator : preceeders)
  280. {
  281. if(!modificator->started)
  282. modificator->run();
  283. }
  284. logGlobal->info("Modificator zone %d - %s - started", zone.getId(), getName());
  285. CStopWatch processTime;
  286. try
  287. {
  288. process();
  289. }
  290. catch(rmgException &e)
  291. {
  292. logGlobal->error("Modificator %s, exception: %s", getName(), e.what());
  293. }
  294. #ifdef RMG_DUMP
  295. dump();
  296. #endif
  297. finished = true;
  298. logGlobal->info("Modificator zone %d - %s - done (%d ms)", zone.getId(), getName(), processTime.getDiff());
  299. }
  300. }
  301. void Modificator::dependency(Modificator * modificator)
  302. {
  303. if(modificator && modificator != this)
  304. {
  305. if(std::find(preceeders.begin(), preceeders.end(), modificator) == preceeders.end())
  306. preceeders.push_back(modificator);
  307. }
  308. }
  309. void Modificator::postfunction(Modificator * modificator)
  310. {
  311. if(modificator && modificator != this)
  312. {
  313. if(std::find(modificator->preceeders.begin(), modificator->preceeders.end(), this) == modificator->preceeders.end())
  314. modificator->preceeders.push_back(this);
  315. }
  316. }
  317. void Modificator::dump()
  318. {
  319. std::ofstream out(boost::to_string(boost::format("seed_%d_modzone_%d_%s.txt") % generator.getRandomSeed() % zone.getId() % getName()));
  320. auto & mapInstance = map.map();
  321. int levels = mapInstance.levels();
  322. int width = mapInstance.width;
  323. int height = mapInstance.height;
  324. for(int z = 0; z < levels; z++)
  325. {
  326. for(int j=0; j<height; j++)
  327. {
  328. for(int i=0; i<width; i++)
  329. {
  330. out << dump(int3(i, j, z));
  331. }
  332. out << std::endl;
  333. }
  334. out << std::endl;
  335. }
  336. out << std::endl;
  337. }
  338. char Modificator::dump(const int3 & t)
  339. {
  340. if(zone.freePaths().contains(t))
  341. return '.'; //free path
  342. if(zone.areaPossible().contains(t))
  343. return ' '; //possible
  344. if(zone.areaUsed().contains(t))
  345. return 'U'; //used
  346. if(zone.area().contains(t))
  347. {
  348. if(map.shouldBeBlocked(t))
  349. return '#'; //obstacle
  350. else
  351. return '^'; //visitable points?
  352. }
  353. return '?';
  354. }
  355. Modificator::~Modificator()
  356. {
  357. }