CZonePlacer.cpp 17 KB

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