CZonePlacer.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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 "../TerrainHandler.h"
  14. #include "../mapping/CMap.h"
  15. #include "../mapping/CMapEditManager.h"
  16. #include "CMapGenOptions.h"
  17. #include "RmgMap.h"
  18. #include "Zone.h"
  19. #include "Functions.h"
  20. VCMI_LIB_NAMESPACE_BEGIN
  21. class CRandomGenerator;
  22. CZonePlacer::CZonePlacer(RmgMap & map)
  23. : width(0), height(0), scaleX(0), scaleY(0), mapSize(0), gravityConstant(0), stiffnessConstant(0),
  24. map(map)
  25. {
  26. }
  27. int3 CZonePlacer::cords(const float3 & f) const
  28. {
  29. return int3(static_cast<si32>(std::max(0.f, (f.x * map.map().width) - 1)), static_cast<si32>(std::max(0.f, (f.y * map.map().height - 1))), f.z);
  30. }
  31. float CZonePlacer::getDistance (float distance) const
  32. {
  33. return (distance ? distance * distance : 1e-6f);
  34. }
  35. void CZonePlacer::placeZones(CRandomGenerator * rand)
  36. {
  37. logGlobal->info("Starting zone placement");
  38. width = map.getMapGenOptions().getWidth();
  39. height = map.getMapGenOptions().getHeight();
  40. auto zones = map.getZones();
  41. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  42. {
  43. return pr.second->getType() == ETemplateZoneType::WATER;
  44. });
  45. bool underground = map.getMapGenOptions().getHasTwoLevels();
  46. /*
  47. gravity-based algorithm
  48. let's assume we try to fit N circular zones with radius = size on a map
  49. */
  50. gravityConstant = 4e-3f;
  51. stiffnessConstant = 4e-3f;
  52. TZoneVector zonesVector(zones.begin(), zones.end());
  53. assert (zonesVector.size());
  54. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  55. //0. set zone sizes and surface / underground level
  56. prepareZones(zones, zonesVector, underground, rand);
  57. //gravity-based algorithm. connected zones attract, intersecting zones and map boundaries push back
  58. //remember best solution
  59. float bestTotalDistance = 1e10;
  60. float bestTotalOverlap = 1e10;
  61. std::map<std::shared_ptr<Zone>, float3> bestSolution;
  62. TForceVector forces;
  63. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  64. TDistanceVector distances;
  65. TDistanceVector overlaps;
  66. const int MAX_ITERATIONS = 100;
  67. for (int i = 0; i < MAX_ITERATIONS; ++i) //until zones reach their desired size and fill the map tightly
  68. {
  69. //1. attract connected zones
  70. attractConnectedZones(zones, forces, distances);
  71. for(const auto & zone : forces)
  72. {
  73. zone.first->setCenter (zone.first->getCenter() + zone.second);
  74. totalForces[zone.first] = zone.second; //override
  75. }
  76. //2. separate overlapping zones
  77. separateOverlappingZones(zones, forces, overlaps);
  78. for(const auto & zone : forces)
  79. {
  80. zone.first->setCenter (zone.first->getCenter() + zone.second);
  81. totalForces[zone.first] += zone.second; //accumulate
  82. }
  83. //3. now perform drastic movement of zone that is completely not linked
  84. moveOneZone(zones, totalForces, distances, overlaps);
  85. //4. NOW after everything was moved, re-evaluate zone positions
  86. attractConnectedZones(zones, forces, distances);
  87. separateOverlappingZones(zones, forces, overlaps);
  88. float totalDistance = 0;
  89. float totalOverlap = 0;
  90. for(const auto & zone : distances) //find most misplaced zone
  91. {
  92. totalDistance += zone.second;
  93. float overlap = overlaps[zone.first];
  94. totalOverlap += overlap;
  95. }
  96. //check fitness function
  97. bool improvement = false;
  98. if (bestTotalDistance > 0 && bestTotalOverlap > 0)
  99. {
  100. if (totalDistance * totalOverlap < bestTotalDistance * bestTotalOverlap) //multiplication is better for auto-scaling, but stops working if one factor is 0
  101. improvement = true;
  102. }
  103. else
  104. {
  105. if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
  106. improvement = true;
  107. }
  108. logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
  109. //save best solution
  110. if (improvement)
  111. {
  112. bestTotalDistance = totalDistance;
  113. bestTotalOverlap = totalOverlap;
  114. for(const auto & zone : zones)
  115. bestSolution[zone.second] = zone.second->getCenter();
  116. }
  117. }
  118. logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
  119. for(const auto & zone : zones) //finalize zone positions
  120. {
  121. zone.second->setPos (cords (bestSolution[zone.second]));
  122. logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
  123. }
  124. }
  125. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  126. {
  127. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  128. const float radius = 0.4f;
  129. const float pi2 = 6.28f;
  130. int zonesOnLevel[2] = { 0, 0 };
  131. //even distribution for surface / underground zones. Surface zones always have priority.
  132. TZoneVector zonesToPlace;
  133. std::map<TRmgTemplateZoneId, int> levels;
  134. //first pass - determine fixed surface for zones
  135. for(const auto & zone : zonesVector)
  136. {
  137. if (!underground) //this step is ignored
  138. zonesToPlace.push_back(zone);
  139. else //place players depending on their factions
  140. {
  141. if (boost::optional<int> owner = zone.second->getOwner())
  142. {
  143. auto player = PlayerColor(*owner - 1);
  144. auto playerSettings = map.getMapGenOptions().getPlayersSettings();
  145. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  146. if (vstd::contains(playerSettings, player))
  147. faction = playerSettings[player].getStartingTown();
  148. else
  149. logGlobal->error("Can't find info for player %d (starting zone)", player.getNum());
  150. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  151. zonesToPlace.push_back(zone);
  152. else
  153. {
  154. auto & tt = (*VLC->townh)[faction]->nativeTerrain;
  155. if(tt == ETerrainId::NONE)
  156. {
  157. //any / random
  158. zonesToPlace.push_back(zone);
  159. }
  160. else
  161. {
  162. const auto & terrainType = VLC->terrainTypeHandler->getById(tt);
  163. if(terrainType->isUnderground() && !terrainType->isSurface())
  164. {
  165. //underground only
  166. zonesOnLevel[1]++;
  167. levels[zone.first] = 1;
  168. }
  169. else
  170. {
  171. //surface
  172. zonesOnLevel[0]++;
  173. levels[zone.first] = 0;
  174. }
  175. }
  176. }
  177. }
  178. else //no starting zone or no underground altogether
  179. {
  180. zonesToPlace.push_back(zone);
  181. }
  182. }
  183. }
  184. for(const auto & zone : zonesToPlace)
  185. {
  186. if (underground) //only then consider underground zones
  187. {
  188. int level = 0;
  189. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  190. level = 1;
  191. else
  192. level = 0;
  193. levels[zone.first] = level;
  194. zonesOnLevel[level]++;
  195. }
  196. else
  197. levels[zone.first] = 0;
  198. }
  199. for(const auto & zone : zonesVector)
  200. {
  201. int level = levels[zone.first];
  202. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  203. auto randomAngle = static_cast<float>(rand->nextDouble(0, pi2));
  204. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  205. }
  206. /*
  207. prescale zones
  208. formula: sum((prescaler*n)^2)*pi = WH
  209. prescaler = sqrt((WH)/(sum(n^2)*pi))
  210. */
  211. std::vector<float> prescaler = { 0, 0 };
  212. for (int i = 0; i < 2; i++)
  213. prescaler[i] = std::sqrt((width * height) / (totalSize[i] * 3.14f));
  214. mapSize = static_cast<float>(sqrt(width * height));
  215. for(const auto & zone : zones)
  216. {
  217. zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  218. }
  219. }
  220. void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
  221. {
  222. for(const auto & zone : zones)
  223. {
  224. float3 forceVector(0, 0, 0);
  225. float3 pos = zone.second->getCenter();
  226. float totalDistance = 0;
  227. for (auto con : zone.second->getConnections())
  228. {
  229. auto otherZone = zones[con];
  230. float3 otherZoneCenter = otherZone->getCenter();
  231. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  232. float minDistance = 0;
  233. if (pos.z != otherZoneCenter.z)
  234. minDistance = 0; //zones on different levels can overlap completely
  235. else
  236. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  237. if (distance > minDistance)
  238. {
  239. //WARNING: compiler used to 'optimize' that line so it never actually worked
  240. float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
  241. forceVector += ((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance)) * gravityConstant; //positive value
  242. totalDistance += (distance - minDistance);
  243. }
  244. }
  245. distances[zone.second] = totalDistance;
  246. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  247. forces[zone.second] = forceVector;
  248. }
  249. }
  250. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  251. {
  252. for(const auto & zone : zones)
  253. {
  254. float3 forceVector(0, 0, 0);
  255. float3 pos = zone.second->getCenter();
  256. float overlap = 0;
  257. //separate overlapping zones
  258. for(const auto & otherZone : zones)
  259. {
  260. float3 otherZoneCenter = otherZone.second->getCenter();
  261. //zones on different levels don't push away
  262. if (zone == otherZone || pos.z != otherZoneCenter.z)
  263. continue;
  264. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  265. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  266. if (distance < minDistance)
  267. {
  268. forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stiffnessConstant; //negative value
  269. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  270. }
  271. }
  272. //move zones away from boundaries
  273. //do not scale boundary distance - zones tend to get squashed
  274. float size = zone.second->getSize() / mapSize;
  275. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  276. {
  277. float3 boundary = float3(x, y, pos.z);
  278. auto distance = static_cast<float>(pos.dist2d(boundary));
  279. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  280. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value
  281. };
  282. if (pos.x < size)
  283. {
  284. pushAwayFromBoundary(0, pos.y);
  285. }
  286. if (pos.x > 1 - size)
  287. {
  288. pushAwayFromBoundary(1, pos.y);
  289. }
  290. if (pos.y < size)
  291. {
  292. pushAwayFromBoundary(pos.x, 0);
  293. }
  294. if (pos.y > 1 - size)
  295. {
  296. pushAwayFromBoundary(pos.x, 1);
  297. }
  298. overlaps[zone.second] = overlap;
  299. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  300. forces[zone.second] = forceVector;
  301. }
  302. }
  303. void CZonePlacer::moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDistanceVector & distances, TDistanceVector & overlaps) const
  304. {
  305. float maxRatio = 0;
  306. const int maxDistanceMovementRatio = static_cast<int>(zones.size() * zones.size()); //experimental - the more zones, the greater total distance expected
  307. std::shared_ptr<Zone> misplacedZone;
  308. float totalDistance = 0;
  309. float totalOverlap = 0;
  310. for(const auto & zone : distances) //find most misplaced zone
  311. {
  312. totalDistance += zone.second;
  313. float overlap = overlaps[zone.first];
  314. totalOverlap += overlap;
  315. float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag()); //if distance to actual movement is long, the zone is misplaced
  316. if (ratio > maxRatio)
  317. {
  318. maxRatio = ratio;
  319. misplacedZone = zone.first;
  320. }
  321. }
  322. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", maxRatio);
  323. if (maxRatio > maxDistanceMovementRatio && misplacedZone)
  324. {
  325. std::shared_ptr<Zone> targetZone;
  326. float3 ourCenter = misplacedZone->getCenter();
  327. if (totalDistance > totalOverlap)
  328. {
  329. //find most distant zone that should be attracted and move inside it
  330. float maxDistance = 0;
  331. for (auto con : misplacedZone->getConnections())
  332. {
  333. auto otherZone = zones[con];
  334. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  335. if (distance > maxDistance)
  336. {
  337. maxDistance = distance;
  338. targetZone = otherZone;
  339. }
  340. }
  341. if (targetZone) //TODO: consider refactoring duplicated code
  342. {
  343. float3 vec = targetZone->getCenter() - ourCenter;
  344. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  345. logGlobal->trace("Trying to move zone %d %s towards %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxDistance);
  346. logGlobal->trace("direction is %s", vec.toString());
  347. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  348. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  349. }
  350. }
  351. else
  352. {
  353. float maxOverlap = 0;
  354. for(const auto & otherZone : zones)
  355. {
  356. float3 otherZoneCenter = otherZone.second->getCenter();
  357. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  358. continue;
  359. auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  360. if (distance > maxOverlap)
  361. {
  362. maxOverlap = distance;
  363. targetZone = otherZone.second;
  364. }
  365. }
  366. if (targetZone)
  367. {
  368. float3 vec = ourCenter - targetZone->getCenter();
  369. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  370. logGlobal->trace("Trying to move zone %d %s away from %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxOverlap);
  371. logGlobal->trace("direction is %s", vec.toString());
  372. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  373. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  374. }
  375. }
  376. }
  377. }
  378. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  379. {
  380. /*
  381. Matlab code
  382. dx = abs(A(1) - B(1)); %distance must be symmetric
  383. dy = abs(A(2) - B(2));
  384. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  385. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  386. */
  387. float dx = abs(A.x - B.x) * scaleX;
  388. float dy = abs(A.y - B.y) * scaleY;
  389. //Horner scheme
  390. return dx * (1.0f + dx * (0.1f + dx * 0.01f)) + dy * (1.618f + dy * (-0.1618f + dy * 0.01618f));
  391. }
  392. void CZonePlacer::assignZones(CRandomGenerator * rand)
  393. {
  394. logGlobal->info("Starting zone colouring");
  395. auto width = map.getMapGenOptions().getWidth();
  396. auto height = map.getMapGenOptions().getHeight();
  397. //scale to Medium map to ensure smooth results
  398. scaleX = 72.f / width;
  399. scaleY = 72.f / height;
  400. auto zones = map.getZones();
  401. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  402. {
  403. return pr.second->getType() == ETemplateZoneType::WATER;
  404. });
  405. using Dpair = std::pair<std::shared_ptr<Zone>, float>;
  406. std::vector <Dpair> distances;
  407. distances.reserve(zones.size());
  408. //now place zones correctly and assign tiles to each zone
  409. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  410. {
  411. //bigger zones have smaller distance
  412. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  413. };
  414. auto moveZoneToCenterOfMass = [](const std::shared_ptr<Zone> & zone) -> void
  415. {
  416. int3 total(0, 0, 0);
  417. auto tiles = zone->area().getTiles();
  418. for(const auto & tile : tiles)
  419. {
  420. total += tile;
  421. }
  422. int size = static_cast<int>(tiles.size());
  423. assert(size);
  424. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  425. };
  426. int levels = map.map().levels();
  427. /*
  428. 1. Create Voronoi diagram
  429. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  430. */
  431. int3 pos;
  432. for(pos.z = 0; pos.z < levels; pos.z++)
  433. {
  434. for(pos.x = 0; pos.x < width; pos.x++)
  435. {
  436. for(pos.y = 0; pos.y < height; pos.y++)
  437. {
  438. distances.clear();
  439. for(const auto & zone : zones)
  440. {
  441. if (zone.second->getPos().z == pos.z)
  442. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  443. else
  444. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  445. }
  446. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  447. }
  448. }
  449. }
  450. for(const auto & zone : zones)
  451. {
  452. if(zone.second->area().empty())
  453. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  454. moveZoneToCenterOfMass(zone.second);
  455. }
  456. //assign actual tiles to each zone using nonlinear norm for fine edges
  457. for(const auto & zone : zones)
  458. zone.second->clearTiles(); //now populate them again
  459. for (pos.z = 0; pos.z < levels; pos.z++)
  460. {
  461. for (pos.x = 0; pos.x < width; pos.x++)
  462. {
  463. for (pos.y = 0; pos.y < height; pos.y++)
  464. {
  465. distances.clear();
  466. for(const auto & zone : zones)
  467. {
  468. if (zone.second->getPos().z == pos.z)
  469. distances.emplace_back(zone.second, metric(pos, zone.second->getPos()));
  470. else
  471. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  472. }
  473. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  474. zone->area().add(pos);
  475. map.setZoneID(pos, zone->getId());
  476. }
  477. }
  478. }
  479. //set position (town position) to center of mass of irregular zone
  480. for(const auto & zone : zones)
  481. {
  482. moveZoneToCenterOfMass(zone.second);
  483. //TODO: similiar for islands
  484. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  485. if (zone.second->isUnderground())
  486. {
  487. if (!CREATE_FULL_UNDERGROUND)
  488. {
  489. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  490. for(const auto & t : discardTiles)
  491. zone.second->area().erase(t);
  492. }
  493. //make sure that terrain inside zone is not a rock
  494. //FIXME: reorder actions?
  495. paintZoneTerrain(*zone.second, *rand, map, ETerrainId::SUBTERRANEAN);
  496. }
  497. }
  498. logGlobal->info("Finished zone colouring");
  499. }
  500. VCMI_LIB_NAMESPACE_END