CZonePlacer.cpp 18 KB

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