CZonePlacer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. * CZonePlacer.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 "../CRandomGenerator.h"
  12. #include "CZonePlacer.h"
  13. #include "CRmgTemplateZone.h"
  14. #include "../mapping/CMap.h"
  15. #include "CZoneGraphGenerator.h"
  16. class CRandomGenerator;
  17. CPlacedZone::CPlacedZone(const CRmgTemplateZone * zone)
  18. {
  19. }
  20. CZonePlacer::CZonePlacer(CMapGenerator * Gen) : gen(Gen)
  21. {
  22. }
  23. CZonePlacer::~CZonePlacer()
  24. {
  25. }
  26. int3 CZonePlacer::cords (const float3 f) const
  27. {
  28. return int3(std::max(0.f, (f.x * gen->map->width)-1), std::max(0.f, (f.y * gen->map->height-1)), f.z);
  29. }
  30. void CZonePlacer::placeZones(const CMapGenOptions * mapGenOptions, CRandomGenerator * rand)
  31. {
  32. logGlobal->infoStream() << "Starting zone placement";
  33. int width = mapGenOptions->getWidth();
  34. int height = mapGenOptions->getHeight();
  35. auto zones = gen->getZones();
  36. bool underground = mapGenOptions->getHasTwoLevels();
  37. //gravity-based algorithm
  38. const float gravityConstant = 4e-3;
  39. const float stiffnessConstant = 4e-3;
  40. float zoneScale = 1.0f / std::sqrt(zones.size()); //zones starts small and then inflate. placing more zones is more difficult
  41. const float inflateModifier = 1.02;
  42. /*
  43. let's assume we try to fit N circular zones with radius = size on a map
  44. formula: sum((prescaler*n)^2)*pi = WH
  45. prescaler = sqrt((WH)/(sum(n^2)*pi))
  46. */
  47. std::vector<std::pair<TRmgTemplateZoneId, CRmgTemplateZone*>> zonesVector (zones.begin(), zones.end());
  48. assert (zonesVector.size());
  49. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  50. TRmgTemplateZoneId firstZone = zones.begin()->first; //we want lowest ID here
  51. bool undergroundFlag = false;
  52. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  53. const float radius = 0.4f;
  54. const float pi2 = 6.28f;
  55. for (auto zone : zonesVector)
  56. {
  57. //even distribution for surface / underground zones. Surface zones always have priority.
  58. int level = 0;
  59. if (underground) //only then consider underground zones
  60. {
  61. if (zone.first == firstZone)
  62. {
  63. level = 0;
  64. }
  65. else
  66. {
  67. level = undergroundFlag;
  68. undergroundFlag = !undergroundFlag; //toggle underground on/off
  69. }
  70. }
  71. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  72. float randomAngle = rand->nextDouble(0, pi2);
  73. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  74. }
  75. //prescale zones
  76. std::vector<float> prescaler = { 0, 0 };
  77. for (int i = 0; i < 2; i++)
  78. prescaler[i] = sqrt((width * height) / (totalSize[i] * 3.14f));
  79. float mapSize = sqrt (width * height);
  80. for (auto zone : zones)
  81. {
  82. zone.second->setSize (zone.second->getSize() * prescaler[zone.second->getCenter().z]);
  83. }
  84. //gravity-based algorithm. connected zones attract, intersceting zones and map boundaries push back
  85. //remember best solution
  86. float bestTotalDistance = 1e10;
  87. float bestTotalOverlap = 1e10;
  88. //float bestRatio = 1e10;
  89. std::map<CRmgTemplateZone *, float3> bestSolution;
  90. const int maxDistanceMovementRatio = zones.size() * zones.size(); //experimental - the more zones, the greater total distance expected
  91. auto getDistance = [](float distance) -> float
  92. {
  93. return (distance ? distance * distance : 1e-6);
  94. };
  95. std::map <CRmgTemplateZone *, float3> forces;
  96. std::map <CRmgTemplateZone *, float3> totalForces; // both attraction and pushback, overcomplicated?
  97. std::map <CRmgTemplateZone *, float> distances;
  98. std::map <CRmgTemplateZone *, float> overlaps;
  99. while (zoneScale < 1) //until zones reach their desired size and fill the map tightly
  100. {
  101. //1. attract connected zones
  102. for (auto zone : zones)
  103. {
  104. float3 forceVector(0, 0, 0);
  105. float3 pos = zone.second->getCenter();
  106. float totalDistance = 0;
  107. for (auto con : zone.second->getConnections())
  108. {
  109. auto otherZone = zones[con];
  110. float3 otherZoneCenter = otherZone->getCenter();
  111. float distance = pos.dist2d(otherZoneCenter);
  112. float minDistance = 0;
  113. if (pos.z != otherZoneCenter.z)
  114. minDistance = 0; //zones on different levels can overlap completely
  115. else
  116. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize * zoneScale; //scale down to (0,1) coordinates
  117. if (distance > minDistance)
  118. {
  119. //WARNING: compiler used to 'optimize' that line so it never actually worked
  120. float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
  121. forceVector += (((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance))) * gravityConstant; //positive value
  122. totalDistance += (distance - minDistance);
  123. }
  124. }
  125. distances[zone.second] = totalDistance;
  126. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  127. forces[zone.second] = forceVector;
  128. totalForces[zone.second] = forceVector; //replace old
  129. }
  130. //update positions 1
  131. for (auto zone : forces)
  132. {
  133. zone.first->setCenter(zone.first->getCenter() + zone.second);
  134. }
  135. //2. separate overlaping zones
  136. for (auto zone : zones)
  137. {
  138. float3 forceVector(0, 0, 0);
  139. float3 pos = zone.second->getCenter();
  140. float totalOverlap = 0;
  141. //separate overlaping zones
  142. for (auto otherZone : zones)
  143. {
  144. float3 otherZoneCenter = otherZone.second->getCenter();
  145. //zones on different levels don't push away
  146. if (zone == otherZone || pos.z != otherZoneCenter.z)
  147. continue;
  148. float distance = pos.dist2d (otherZoneCenter);
  149. float minDistance = (zone.second->getSize() + otherZone.second->getSize())/mapSize * zoneScale;
  150. if (distance < minDistance)
  151. {
  152. forceVector -= (((otherZoneCenter - pos)*(minDistance/(distance ? distance : 1e-3))) / getDistance(distance)) * stiffnessConstant; //negative value
  153. totalOverlap += (minDistance - distance) / (zoneScale * zoneScale); //overlapping of small zones hurts us more
  154. }
  155. }
  156. //move zones away from boundaries
  157. //do not scale boundary distance - zones tend to get squashed
  158. float size = zone.second->getSize() / mapSize;
  159. auto pushAwayFromBoundary = [&forceVector, pos, &getDistance, size, stiffnessConstant, &totalOverlap](float x, float y)
  160. {
  161. float3 boundary = float3 (x, y, pos.z);
  162. float distance = pos.dist2d(boundary);
  163. totalOverlap += distance; //overlapping map boundaries is wrong as well
  164. forceVector -= (boundary - pos) * (size - distance) / getDistance(distance) * stiffnessConstant; //negative value
  165. };
  166. if (pos.x < size)
  167. {
  168. pushAwayFromBoundary(0, pos.y);
  169. }
  170. if (pos.x > 1-size)
  171. {
  172. pushAwayFromBoundary(1, pos.y);
  173. }
  174. if (pos.y < size)
  175. {
  176. pushAwayFromBoundary(pos.x, 0);
  177. }
  178. if (pos.y > 1-size)
  179. {
  180. pushAwayFromBoundary(pos.x, 1);
  181. }
  182. overlaps[zone.second] = totalOverlap;
  183. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  184. forces[zone.second] = forceVector;
  185. totalForces[zone.second] += forceVector; //add
  186. }
  187. //update positions 2
  188. for (auto zone : forces)
  189. {
  190. zone.first->setCenter (zone.first->getCenter() + zone.second);
  191. }
  192. //now perform drastic movement of zone that is completely not linked
  193. float maxRatio = 0;
  194. CRmgTemplateZone * misplacedZone = nullptr;
  195. float totalDistance = 0;
  196. float totalOverlap = 0;
  197. for (auto zone : distances) //find most misplaced zone
  198. {
  199. totalDistance += zone.second;
  200. float overlap = overlaps[zone.first];
  201. totalOverlap += overlap;
  202. float ratio = (zone.second + overlap) / totalForces[zone.first].mag(); //if distance to actual movement is long, the zone is misplaced
  203. if (ratio > maxRatio)
  204. {
  205. maxRatio = ratio;
  206. misplacedZone = zone.first;
  207. }
  208. }
  209. logGlobal->traceStream() << boost::format("Total distance between zones in this iteration: %2.4f, Total overlap: %2.4f, Worst misplacement/movement ratio: %3.2f") % totalDistance % totalOverlap % maxRatio;
  210. //check fitness function
  211. bool improvement = false;
  212. if (bestTotalDistance > 0 && bestTotalOverlap > 0)
  213. {
  214. if (totalDistance * totalOverlap < bestTotalDistance * bestTotalOverlap) //multiplication is better for auto-scaling, but stops working if one factor is 0
  215. improvement = true;
  216. }
  217. else
  218. if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
  219. improvement = true;
  220. //save best solution before drastic jump
  221. if (improvement)
  222. {
  223. bestTotalDistance = totalDistance;
  224. bestTotalOverlap = totalOverlap;
  225. for (auto zone : zones)
  226. bestSolution[zone.second] = zone.second->getCenter();
  227. }
  228. if (maxRatio > maxDistanceMovementRatio)
  229. {
  230. CRmgTemplateZone * targetZone = nullptr;
  231. float3 ourCenter = misplacedZone->getCenter();
  232. if (totalDistance > totalOverlap)
  233. {
  234. //find most distant zone that should be attracted and move inside it
  235. float maxDistance = 0;
  236. for (auto con : misplacedZone->getConnections())
  237. {
  238. auto otherZone = zones[con];
  239. float distance = otherZone->getCenter().dist2dSQ(ourCenter);
  240. if (distance > maxDistance)
  241. {
  242. maxDistance = distance;
  243. targetZone = otherZone;
  244. }
  245. }
  246. float3 vec = targetZone->getCenter() - ourCenter;
  247. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) * zoneScale / mapSize;
  248. logGlobal->traceStream() << boost::format("Trying to move zone %d %s towards %d %s. Old distance %f") %
  249. misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxDistance;
  250. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  251. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  252. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter());
  253. }
  254. else
  255. {
  256. float maxOverlap = 0;
  257. for (auto otherZone : zones)
  258. {
  259. float3 otherZoneCenter = otherZone.second->getCenter();
  260. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  261. continue;
  262. float distance = otherZoneCenter.dist2dSQ(ourCenter);
  263. if (distance > maxOverlap)
  264. {
  265. maxOverlap = distance;
  266. targetZone = otherZone.second;
  267. }
  268. }
  269. float3 vec = ourCenter - targetZone->getCenter();
  270. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) * zoneScale / mapSize;
  271. logGlobal->traceStream() << boost::format("Trying to move zone %d %s away from %d %s. Old distance %f") %
  272. misplacedZone->getId() % ourCenter() % targetZone->getId() % targetZone->getCenter()() % maxOverlap;
  273. logGlobal->traceStream() << boost::format("direction is %s") % vec();
  274. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  275. logGlobal->traceStream() << boost::format("New distance %f") % targetZone->getCenter().dist2d(misplacedZone->getCenter());
  276. }
  277. }
  278. zoneScale *= inflateModifier; //increase size of zones so they
  279. }
  280. logGlobal->traceStream() << boost::format("Best fitness reached: total distance %2.4f, total overlap %2.4f") % bestTotalDistance % bestTotalOverlap;
  281. for (auto zone : zones) //finalize zone positions
  282. {
  283. zone.second->setPos (cords (bestSolution[zone.second]));
  284. logGlobal->traceStream() << boost::format ("Placed zone %d at relative position %s and coordinates %s") % zone.first % zone.second->getCenter() % zone.second->getPos();
  285. }
  286. }
  287. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  288. {
  289. /*
  290. Matlab code
  291. dx = abs(A(1) - B(1)); %distance must be symmetric
  292. dy = abs(A(2) - B(2));
  293. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  294. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  295. */
  296. float dx = abs(A.x - B.x) * scaleX;
  297. float dy = abs(A.y - B.y) * scaleY;
  298. //Horner scheme
  299. return dx * (1 + dx * (0.1 + dx * 0.01)) + dy * (1.618 + dy * (-0.1618 + dy * 0.01618));
  300. }
  301. void CZonePlacer::assignZones(const CMapGenOptions * mapGenOptions)
  302. {
  303. logGlobal->infoStream() << "Starting zone colouring";
  304. auto width = mapGenOptions->getWidth();
  305. auto height = mapGenOptions->getHeight();
  306. //scale to Medium map to ensure smooth results
  307. scaleX = 72.f / width;
  308. scaleY = 72.f / height;
  309. auto zones = gen->getZones();
  310. typedef std::pair<CRmgTemplateZone *, float> Dpair;
  311. std::vector <Dpair> distances;
  312. distances.reserve(zones.size());
  313. //now place zones correctly and assign tiles to each zone
  314. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  315. {
  316. return lhs.second < rhs.second;
  317. };
  318. auto moveZoneToCenterOfMass = [](CRmgTemplateZone * zone) -> void
  319. {
  320. int3 total(0, 0, 0);
  321. auto tiles = zone->getTileInfo();
  322. for (auto tile : tiles)
  323. {
  324. total += tile;
  325. }
  326. int size = tiles.size();
  327. assert(size);
  328. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  329. };
  330. int levels = gen->map->twoLevel ? 2 : 1;
  331. /*
  332. 1. Create Voronoi diagram
  333. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  334. */
  335. for (int i = 0; i<width; i++)
  336. {
  337. for (int j = 0; j<height; j++)
  338. {
  339. for (int k = 0; k < levels; k++)
  340. {
  341. distances.clear();
  342. int3 pos(i, j, k);
  343. for (auto zone : zones)
  344. {
  345. if (zone.second->getPos().z == k)
  346. distances.push_back(std::make_pair(zone.second, pos.dist2dSQ(zone.second->getPos())));
  347. else
  348. distances.push_back(std::make_pair(zone.second, std::numeric_limits<float>::max()));
  349. }
  350. boost::sort(distances, compareByDistance);
  351. distances.front().first->addTile(pos); //closest tile belongs to zone
  352. }
  353. }
  354. }
  355. for (auto zone : zones)
  356. moveZoneToCenterOfMass(zone.second);
  357. //assign actual tiles to each zone using nonlinear norm for fine edges
  358. for (auto zone : zones)
  359. zone.second->clearTiles(); //now populate them again
  360. for (int i=0; i<width; i++)
  361. {
  362. for(int j=0; j<height; j++)
  363. {
  364. for (int k = 0; k < levels; k++)
  365. {
  366. distances.clear();
  367. int3 pos(i, j, k);
  368. for (auto zone : zones)
  369. {
  370. if (zone.second->getPos().z == k)
  371. distances.push_back (std::make_pair(zone.second, metric(pos, zone.second->getPos())));
  372. else
  373. distances.push_back (std::make_pair(zone.second, std::numeric_limits<float>::max()));
  374. }
  375. boost::sort (distances, compareByDistance);
  376. distances.front().first->addTile(pos); //closest tile belongs to zone
  377. }
  378. }
  379. }
  380. //set position (town position) to center of mass of irregular zone
  381. for (auto zone : zones)
  382. {
  383. moveZoneToCenterOfMass(zone.second);
  384. //TODO: similiar for islands
  385. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  386. if (zone.second->getPos().z)
  387. {
  388. if (!CREATE_FULL_UNDERGROUND)
  389. zone.second->discardDistantTiles(gen, zone.second->getSize() + 1);
  390. //make sure that terrain inside zone is not a rock
  391. //FIXME: reorder actions?
  392. zone.second->paintZoneTerrain (gen, ETerrainType::SUBTERRANEAN);
  393. }
  394. }
  395. logGlobal->infoStream() << "Finished zone colouring";
  396. }