CZonePlacer.cpp 17 KB

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