CZonePlacer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 <stack>
  12. #include "../CRandomGenerator.h"
  13. #include "CZonePlacer.h"
  14. #include "../TerrainHandler.h"
  15. #include "../mapping/CMap.h"
  16. #include "../mapping/CMapEditManager.h"
  17. #include "CMapGenOptions.h"
  18. #include "RmgMap.h"
  19. #include "Zone.h"
  20. #include "Functions.h"
  21. VCMI_LIB_NAMESPACE_BEGIN
  22. class CRandomGenerator;
  23. CZonePlacer::CZonePlacer(RmgMap & map)
  24. : width(0), height(0), scaleX(0), scaleY(0), mapSize(0),
  25. gravityConstant(1e-3f),
  26. stiffnessConstant(3e-3f),
  27. stifness(0),
  28. stiffnessIncreaseFactor(1.03f),
  29. bestTotalDistance(1e10),
  30. bestTotalOverlap(1e10),
  31. map(map)
  32. {
  33. }
  34. int3 CZonePlacer::cords(const float3 & f) const
  35. {
  36. return int3(static_cast<si32>(std::max(0.f, (f.x * map.width()) - 1)), static_cast<si32>(std::max(0.f, (f.y * map.height() - 1))), f.z);
  37. }
  38. float CZonePlacer::getDistance (float distance) const
  39. {
  40. return (distance ? distance * distance : 1e-6f);
  41. }
  42. void CZonePlacer::findPathsBetweenZones()
  43. {
  44. auto zones = map.getZones();
  45. std::set<std::shared_ptr<Zone>> zonesToCheck;
  46. // Iterate through each pair of nodes in the graph
  47. for (const auto& zone : zones)
  48. {
  49. int start = zone.first;
  50. distancesBetweenZones[start][start] = 0; // Distance from a node to itself is 0
  51. std::queue<int> q;
  52. std::map<int, bool> visited;
  53. visited[start] = true;
  54. q.push(start);
  55. // Perform Breadth-First Search from the starting node
  56. while (!q.empty())
  57. {
  58. int current = q.front();
  59. q.pop();
  60. const auto& currentZone = zones.at(current);
  61. const auto& connectedZoneIds = currentZone->getConnections();
  62. for (auto & connection : connectedZoneIds)
  63. {
  64. if (connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  65. {
  66. //Do not consider virtual connections for graph distance
  67. continue;
  68. }
  69. auto neighbor = connection.getOtherZoneId(current);
  70. if (!visited[neighbor])
  71. {
  72. visited[neighbor] = true;
  73. q.push(neighbor);
  74. distancesBetweenZones[start][neighbor] = distancesBetweenZones[start][current] + 1;
  75. }
  76. }
  77. }
  78. }
  79. }
  80. void CZonePlacer::placeOnGrid(CRandomGenerator* rand)
  81. {
  82. auto zones = map.getZones();
  83. assert(zones.size());
  84. //Make sure there are at least as many grid fields as the number of zones
  85. size_t gridSize = std::ceil(std::sqrt(zones.size()));
  86. typedef boost::multi_array<std::shared_ptr<Zone>, 2> GridType;
  87. GridType grid(boost::extents[gridSize][gridSize]);
  88. TZoneVector zonesVector(zones.begin(), zones.end());
  89. //Place first zone
  90. auto firstZone = zonesVector[0].second;
  91. size_t x = 0, y = 0;
  92. auto getRandomEdge = [rand, gridSize](size_t& x, size_t& y)
  93. {
  94. switch (rand->nextInt() % 4)
  95. {
  96. case 0:
  97. x = 0;
  98. y = gridSize / 2;
  99. break;
  100. case 1:
  101. x = gridSize - 1;
  102. y = gridSize / 2;
  103. break;
  104. case 2:
  105. x = gridSize / 2;
  106. y = 0;
  107. break;
  108. case 3:
  109. x = gridSize / 2;
  110. y = gridSize - 1;
  111. break;
  112. }
  113. };
  114. switch (firstZone->getType())
  115. {
  116. case ETemplateZoneType::PLAYER_START:
  117. case ETemplateZoneType::CPU_START:
  118. if (firstZone->getConnectedZoneIds().size() > 2)
  119. {
  120. getRandomEdge(x, y);
  121. }
  122. else
  123. {
  124. //Random corner
  125. if (rand->nextInt() % 2)
  126. {
  127. x = 0;
  128. }
  129. else
  130. {
  131. x = gridSize - 1;
  132. }
  133. if (rand->nextInt() % 2)
  134. {
  135. y = 0;
  136. }
  137. else
  138. {
  139. y = gridSize - 1;
  140. }
  141. }
  142. break;
  143. case ETemplateZoneType::TREASURE:
  144. if (gridSize & 1) //odd
  145. {
  146. x = y = (gridSize / 2);
  147. }
  148. else
  149. {
  150. //One of 4 squares in the middle
  151. x = (gridSize / 2) - 1 + rand->nextInt() % 2;
  152. y = (gridSize / 2) - 1 + rand->nextInt() % 2;
  153. }
  154. break;
  155. case ETemplateZoneType::JUNCTION:
  156. getRandomEdge(x, y);
  157. break;
  158. }
  159. grid[x][y] = firstZone;
  160. //Ignore z placement for simplicity
  161. for (size_t i = 1; i < zones.size(); i++)
  162. {
  163. auto zone = zonesVector[i].second;
  164. auto connectedZoneIds = zone->getConnectedZoneIds();
  165. float maxDistance = -1000.0;
  166. int3 mostDistantPlace;
  167. //Iterate over free positions
  168. for (size_t freeX = 0; freeX < gridSize; ++freeX)
  169. {
  170. for (size_t freeY = 0; freeY < gridSize; ++freeY)
  171. {
  172. if (!grid[freeX][freeY])
  173. {
  174. //There is free space left here
  175. int3 potentialPos(freeX, freeY, 0);
  176. //Compute distance to every existing zone
  177. float distance = 0;
  178. for (size_t existingX = 0; existingX < gridSize; ++existingX)
  179. {
  180. for (size_t existingY = 0; existingY < gridSize; ++existingY)
  181. {
  182. auto existingZone = grid[existingX][existingY];
  183. if (existingZone)
  184. {
  185. //There is already zone here
  186. float localDistance = 0.0f;
  187. auto graphDistance = distancesBetweenZones[zone->getId()][existingZone->getId()];
  188. if (graphDistance > 1)
  189. {
  190. //No direct connection
  191. localDistance = potentialPos.dist2d(int3(existingX, existingY, 0)) * graphDistance;
  192. }
  193. else
  194. {
  195. //Has direct connection - place as close as possible
  196. localDistance = -potentialPos.dist2d(int3(existingX, existingY, 0));
  197. }
  198. localDistance *= scaleForceBetweenZones(zone, existingZone);
  199. distance += localDistance;
  200. }
  201. }
  202. }
  203. if (distance > maxDistance)
  204. {
  205. maxDistance = distance;
  206. mostDistantPlace = potentialPos;
  207. }
  208. }
  209. }
  210. }
  211. //Place in a free slot
  212. grid[mostDistantPlace.x][mostDistantPlace.y] = zone;
  213. }
  214. //TODO: toggle with a flag
  215. logGlobal->info("Initial zone grid:");
  216. for (size_t x = 0; x < gridSize; ++x)
  217. {
  218. std::string s;
  219. for (size_t y = 0; y < gridSize; ++y)
  220. {
  221. if (grid[x][y])
  222. {
  223. s += (boost::format("%3d ") % grid[x][y]->getId()).str();
  224. }
  225. else
  226. {
  227. s += " -- ";
  228. }
  229. }
  230. logGlobal->info(s);
  231. }
  232. //Set initial position for zones - random position in square centered around (x, y)
  233. for (size_t x = 0; x < gridSize; ++x)
  234. {
  235. for (size_t y = 0; y < gridSize; ++y)
  236. {
  237. auto zone = grid[x][y];
  238. if (zone)
  239. {
  240. //i.e. for grid size 5 we get range (0.25 - 4.75)
  241. auto targetX = rand->nextDouble(x + 0.25f, x + 0.75f);
  242. vstd::abetween(targetX, 0.5, gridSize - 0.5);
  243. auto targetY = rand->nextDouble(y + 0.25f, y + 0.75f);
  244. vstd::abetween(targetY, 0.5, gridSize - 0.5);
  245. zone->setCenter(float3(targetX / gridSize, targetY / gridSize, zone->getPos().z));
  246. }
  247. }
  248. }
  249. }
  250. float CZonePlacer::scaleForceBetweenZones(const std::shared_ptr<Zone> zoneA, const std::shared_ptr<Zone> zoneB) const
  251. {
  252. if (zoneA->getOwner() && zoneB->getOwner()) //Players participate in game
  253. {
  254. int firstPlayer = zoneA->getOwner().value();
  255. int secondPlayer = zoneB->getOwner().value();
  256. //Players with lower indexes (especially 1 and 2) will be placed further apart
  257. return (1.0f + (2.0f / (firstPlayer * secondPlayer)));
  258. }
  259. else
  260. {
  261. return 1;
  262. }
  263. }
  264. void CZonePlacer::placeZones(CRandomGenerator * rand)
  265. {
  266. logGlobal->info("Starting zone placement");
  267. width = map.getMapGenOptions().getWidth();
  268. height = map.getMapGenOptions().getHeight();
  269. auto zones = map.getZones();
  270. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  271. {
  272. return pr.second->getType() == ETemplateZoneType::WATER;
  273. });
  274. bool underground = map.getMapGenOptions().getHasTwoLevels();
  275. findPathsBetweenZones();
  276. placeOnGrid(rand);
  277. /*
  278. Fruchterman-Reingold algorithm
  279. Let's assume we try to fit N circular zones with radius = size on a map
  280. Connected zones attract, intersecting zones and map boundaries push back
  281. */
  282. TZoneVector zonesVector(zones.begin(), zones.end());
  283. assert (zonesVector.size());
  284. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  285. //0. set zone sizes and surface / underground level
  286. prepareZones(zones, zonesVector, underground, rand);
  287. std::map<std::shared_ptr<Zone>, float3> bestSolution;
  288. TForceVector forces;
  289. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  290. TDistanceVector distances;
  291. TDistanceVector overlaps;
  292. auto evaluateSolution = [this, zones, &distances, &overlaps, &bestSolution]() -> bool
  293. {
  294. bool improvement = false;
  295. float totalDistance = 0;
  296. float totalOverlap = 0;
  297. for (const auto& zone : distances) //find most misplaced zone
  298. {
  299. totalDistance += zone.second;
  300. float overlap = overlaps[zone.first];
  301. totalOverlap += overlap;
  302. }
  303. //check fitness function
  304. if ((totalDistance + 1) * (totalOverlap + 1) < (bestTotalDistance + 1) * (bestTotalOverlap + 1))
  305. {
  306. //multiplication is better for auto-scaling, but stops working if one factor is 0
  307. improvement = true;
  308. }
  309. //Save best solution
  310. if (improvement)
  311. {
  312. bestTotalDistance = totalDistance;
  313. bestTotalOverlap = totalOverlap;
  314. for (const auto& zone : zones)
  315. bestSolution[zone.second] = zone.second->getCenter();
  316. }
  317. logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
  318. return improvement;
  319. };
  320. //Start with low stiffness. Bigger graphs need more time and more flexibility
  321. for (stifness = stiffnessConstant / zones.size(); stifness <= stiffnessConstant;)
  322. {
  323. //1. attract connected zones
  324. attractConnectedZones(zones, forces, distances);
  325. for(const auto & zone : forces)
  326. {
  327. zone.first->setCenter (zone.first->getCenter() + zone.second);
  328. totalForces[zone.first] = zone.second; //override
  329. }
  330. //2. separate overlapping zones
  331. separateOverlappingZones(zones, forces, overlaps);
  332. for(const auto & zone : forces)
  333. {
  334. zone.first->setCenter (zone.first->getCenter() + zone.second);
  335. totalForces[zone.first] += zone.second; //accumulate
  336. }
  337. bool improved = evaluateSolution();
  338. if (!improved)
  339. {
  340. //3. now perform drastic movement of zone that is completely not linked
  341. //TODO: Don't do this is fitness was improved
  342. moveOneZone(zones, totalForces, distances, overlaps);
  343. improved |= evaluateSolution();;
  344. }
  345. if (!improved)
  346. {
  347. //Only cool down if we didn't see any improvement
  348. stifness *= stiffnessIncreaseFactor;
  349. }
  350. }
  351. logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
  352. for(const auto & zone : zones) //finalize zone positions
  353. {
  354. zone.second->setPos (cords (bestSolution[zone.second]));
  355. logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
  356. }
  357. }
  358. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  359. {
  360. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  361. int zonesOnLevel[2] = { 0, 0 };
  362. //even distribution for surface / underground zones. Surface zones always have priority.
  363. TZoneVector zonesToPlace;
  364. std::map<TRmgTemplateZoneId, int> levels;
  365. //first pass - determine fixed surface for zones
  366. for(const auto & zone : zonesVector)
  367. {
  368. if (!underground) //this step is ignored
  369. zonesToPlace.push_back(zone);
  370. else //place players depending on their factions
  371. {
  372. if(std::optional<int> owner = zone.second->getOwner())
  373. {
  374. auto player = PlayerColor(*owner - 1);
  375. auto playerSettings = map.getMapGenOptions().getPlayersSettings();
  376. FactionID faction = FactionID::RANDOM;
  377. if (vstd::contains(playerSettings, player))
  378. {
  379. faction = playerSettings[player].getStartingTown();
  380. }
  381. else
  382. {
  383. logGlobal->trace("Player %d (starting zone %d) does not participate in game", player.getNum(), zone.first);
  384. }
  385. if (faction == FactionID::RANDOM) //TODO: check this after a town has already been randomized
  386. zonesToPlace.push_back(zone);
  387. else
  388. {
  389. auto & tt = (*VLC->townh)[faction]->nativeTerrain;
  390. if(tt == ETerrainId::NONE)
  391. {
  392. //any / random
  393. zonesToPlace.push_back(zone);
  394. }
  395. else
  396. {
  397. const auto & terrainType = VLC->terrainTypeHandler->getById(tt);
  398. if(terrainType->isUnderground() && !terrainType->isSurface())
  399. {
  400. //underground only
  401. zonesOnLevel[1]++;
  402. levels[zone.first] = 1;
  403. }
  404. else
  405. {
  406. //surface
  407. zonesOnLevel[0]++;
  408. levels[zone.first] = 0;
  409. }
  410. }
  411. }
  412. }
  413. else //no starting zone or no underground altogether
  414. {
  415. zonesToPlace.push_back(zone);
  416. }
  417. }
  418. }
  419. for(const auto & zone : zonesToPlace)
  420. {
  421. if (underground) //only then consider underground zones
  422. {
  423. int level = 0;
  424. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  425. level = 1;
  426. else
  427. level = 0;
  428. levels[zone.first] = level;
  429. zonesOnLevel[level]++;
  430. }
  431. else
  432. levels[zone.first] = 0;
  433. }
  434. for(const auto & zone : zonesVector)
  435. {
  436. int level = levels[zone.first];
  437. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  438. float3 center = zone.second->getCenter();
  439. center.z = level;
  440. zone.second->setCenter(center);
  441. }
  442. /*
  443. prescale zones
  444. formula: sum((prescaler*n)^2)*pi = WH
  445. prescaler = sqrt((WH)/(sum(n^2)*pi))
  446. */
  447. std::vector<float> prescaler = { 0, 0 };
  448. for (int i = 0; i < 2; i++)
  449. prescaler[i] = std::sqrt((width * height) / (totalSize[i] * 3.14f));
  450. mapSize = static_cast<float>(sqrt(width * height));
  451. for(const auto & zone : zones)
  452. {
  453. zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  454. }
  455. }
  456. void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
  457. {
  458. for(const auto & zone : zones)
  459. {
  460. float3 forceVector(0, 0, 0);
  461. float3 pos = zone.second->getCenter();
  462. float totalDistance = 0;
  463. for (const auto & connection : zone.second->getConnections())
  464. {
  465. if (connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  466. {
  467. continue;
  468. }
  469. auto otherZone = zones[connection.getOtherZoneId(zone.second->getId())];
  470. float3 otherZoneCenter = otherZone->getCenter();
  471. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  472. forceVector += (otherZoneCenter - pos) * distance * gravityConstant * scaleForceBetweenZones(zone.second, otherZone); //positive value
  473. //Attract zone centers always
  474. float minDistance = 0;
  475. if (pos.z != otherZoneCenter.z)
  476. minDistance = 0; //zones on different levels can overlap completely
  477. else
  478. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  479. if (distance > minDistance)
  480. totalDistance += (distance - minDistance);
  481. }
  482. distances[zone.second] = totalDistance;
  483. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  484. forces[zone.second] = forceVector;
  485. }
  486. }
  487. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  488. {
  489. for(const auto & zone : zones)
  490. {
  491. float3 forceVector(0, 0, 0);
  492. float3 pos = zone.second->getCenter();
  493. float overlap = 0;
  494. //separate overlapping zones
  495. for(const auto & otherZone : zones)
  496. {
  497. float3 otherZoneCenter = otherZone.second->getCenter();
  498. //zones on different levels don't push away
  499. if (zone == otherZone || pos.z != otherZoneCenter.z)
  500. continue;
  501. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  502. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  503. if (distance < minDistance)
  504. {
  505. float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
  506. //negative value
  507. localForce *= scaleForceBetweenZones(zone.second, otherZone.second);
  508. forceVector -= localForce * (distancesBetweenZones[zone.second->getId()][otherZone.second->getId()] / 2.0f);
  509. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  510. }
  511. }
  512. //move zones away from boundaries
  513. //do not scale boundary distance - zones tend to get squashed
  514. float size = zone.second->getSize() / mapSize;
  515. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  516. {
  517. float3 boundary = float3(x, y, pos.z);
  518. auto distance = static_cast<float>(pos.dist2d(boundary));
  519. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  520. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stifness; //negative value
  521. };
  522. if (pos.x < size)
  523. {
  524. pushAwayFromBoundary(0, pos.y);
  525. }
  526. if (pos.x > 1 - size)
  527. {
  528. pushAwayFromBoundary(1, pos.y);
  529. }
  530. if (pos.y < size)
  531. {
  532. pushAwayFromBoundary(pos.x, 0);
  533. }
  534. if (pos.y > 1 - size)
  535. {
  536. pushAwayFromBoundary(pos.x, 1);
  537. }
  538. //Always move repulsive zones away, no matter their distance
  539. //TODO: Consider z plane?
  540. for (auto& connection : zone.second->getConnections())
  541. {
  542. if (connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  543. {
  544. auto & otherZone = zones[connection.getOtherZoneId(zone.second->getId())];
  545. float3 otherZoneCenter = otherZone->getCenter();
  546. //TODO: Roll into lambda?
  547. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  548. float minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize;
  549. float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
  550. localForce *= (distancesBetweenZones[zone.second->getId()][otherZone->getId()]);
  551. forceVector -= localForce * scaleForceBetweenZones(zone.second, otherZone);
  552. }
  553. }
  554. overlaps[zone.second] = overlap;
  555. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  556. forces[zone.second] = forceVector;
  557. }
  558. }
  559. void CZonePlacer::moveOneZone(TZoneMap& zones, TForceVector& totalForces, TDistanceVector& distances, TDistanceVector& overlaps)
  560. {
  561. //The more zones, the greater total distance expected
  562. //Also, higher stiffness make expected movement lower
  563. const int maxDistanceMovementRatio = zones.size() * zones.size() * (stiffnessConstant / stifness);
  564. typedef std::pair<float, std::shared_ptr<Zone>> Misplacement;
  565. std::vector<Misplacement> misplacedZones;
  566. float totalDistance = 0;
  567. float totalOverlap = 0;
  568. for (const auto& zone : distances) //find most misplaced zone
  569. {
  570. if (vstd::contains(lastSwappedZones, zone.first->getId()))
  571. {
  572. continue;
  573. }
  574. totalDistance += zone.second;
  575. float overlap = overlaps[zone.first];
  576. totalOverlap += overlap;
  577. //if distance to actual movement is long, the zone is misplaced
  578. float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag());
  579. if (ratio > maxDistanceMovementRatio)
  580. {
  581. misplacedZones.emplace_back(std::make_pair(ratio, zone.first));
  582. }
  583. }
  584. if (misplacedZones.empty())
  585. return;
  586. boost::sort(misplacedZones, [](const Misplacement& lhs, Misplacement& rhs)
  587. {
  588. return lhs.first > rhs.first; //Largest dispalcement first
  589. });
  590. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", misplacedZones.front().first);
  591. if (misplacedZones.size() >= 2)
  592. {
  593. //Swap 2 misplaced zones
  594. auto firstZone = misplacedZones.front().second;
  595. std::shared_ptr<Zone> secondZone;
  596. std::set<TRmgTemplateZoneId> connectedZones;
  597. for (const auto& connection : firstZone->getConnections())
  598. {
  599. //FIXME: Should we also exclude fictive connections?
  600. if (connection.getConnectionType() != rmg::EConnectionType::REPULSIVE)
  601. {
  602. connectedZones.insert(connection.getOtherZoneId(firstZone->getId()));
  603. }
  604. }
  605. auto level = firstZone->getCenter().z;
  606. for (size_t i = 1; i < misplacedZones.size(); i++)
  607. {
  608. //Only swap zones on the same level
  609. //Don't swap zones that should be connected (Jebus)
  610. if (misplacedZones[i].second->getCenter().z == level &&
  611. !vstd::contains(connectedZones, misplacedZones[i].second->getId()))
  612. {
  613. secondZone = misplacedZones[i].second;
  614. break;
  615. }
  616. }
  617. if (secondZone)
  618. {
  619. logGlobal->trace("Swapping two misplaced zones %d and %d", firstZone->getId(), secondZone->getId());
  620. auto firstCenter = firstZone->getCenter();
  621. auto secondCenter = secondZone->getCenter();
  622. firstZone->setCenter(secondCenter);
  623. secondZone->setCenter(firstCenter);
  624. lastSwappedZones.insert(firstZone->getId());
  625. lastSwappedZones.insert(secondZone->getId());
  626. return;
  627. }
  628. }
  629. lastSwappedZones.clear(); //If we didn't swap zones in this iteration, we can do it in the next
  630. //find most distant zone that should be attracted and move inside it
  631. std::shared_ptr<Zone> targetZone;
  632. auto misplacedZone = misplacedZones.front().second;
  633. float3 ourCenter = misplacedZone->getCenter();
  634. if ((totalDistance / (bestTotalDistance + 1)) > (totalOverlap / (bestTotalOverlap + 1)))
  635. {
  636. //Move one zone towards most distant zone to reduce distance
  637. float maxDistance = 0;
  638. for (auto con : misplacedZone->getConnections())
  639. {
  640. if (con.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  641. {
  642. continue;
  643. }
  644. auto otherZone = zones[con.getOtherZoneId(misplacedZone->getId())];
  645. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  646. if (distance > maxDistance)
  647. {
  648. maxDistance = distance;
  649. targetZone = otherZone;
  650. }
  651. }
  652. if (targetZone)
  653. {
  654. float3 vec = targetZone->getCenter() - ourCenter;
  655. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  656. logGlobal->trace("Trying to move zone %d %s towards %d %s. Direction is %s", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), vec.toString());
  657. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  658. }
  659. }
  660. else
  661. {
  662. //Move misplaced zone away from overlapping zone
  663. float maxOverlap = 0;
  664. for(const auto & otherZone : zones)
  665. {
  666. float3 otherZoneCenter = otherZone.second->getCenter();
  667. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  668. continue;
  669. auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  670. if (distance > maxOverlap)
  671. {
  672. maxOverlap = distance;
  673. targetZone = otherZone.second;
  674. }
  675. }
  676. if (targetZone)
  677. {
  678. float3 vec = ourCenter - targetZone->getCenter();
  679. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  680. logGlobal->trace("Trying to move zone %d %s away from %d %s. Direction is %s", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), vec.toString());
  681. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  682. }
  683. }
  684. //Don't swap that zone in next iteration
  685. lastSwappedZones.insert(misplacedZone->getId());
  686. }
  687. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  688. {
  689. float dx = abs(A.x - B.x) * scaleX;
  690. float dy = abs(A.y - B.y) * scaleY;
  691. /*
  692. 1. Normal euclidean distance
  693. 2. Sinus for extra curves
  694. 3. Nonlinear mess for fuzzy edges
  695. */
  696. return dx * dx + dy * dy +
  697. 5 * std::sin(dx * dy / 10) +
  698. 25 * std::sin (std::sqrt(A.x * B.x) * (A.y - B.y) / 100 * (scaleX * scaleY));
  699. }
  700. void CZonePlacer::assignZones(CRandomGenerator * rand)
  701. {
  702. logGlobal->info("Starting zone colouring");
  703. auto width = map.getMapGenOptions().getWidth();
  704. auto height = map.getMapGenOptions().getHeight();
  705. //scale to Medium map to ensure smooth results
  706. scaleX = 72.f / width;
  707. scaleY = 72.f / height;
  708. auto zones = map.getZones();
  709. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  710. {
  711. return pr.second->getType() == ETemplateZoneType::WATER;
  712. });
  713. using Dpair = std::pair<std::shared_ptr<Zone>, float>;
  714. std::vector <Dpair> distances;
  715. distances.reserve(zones.size());
  716. //now place zones correctly and assign tiles to each zone
  717. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  718. {
  719. //bigger zones have smaller distance
  720. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  721. };
  722. auto moveZoneToCenterOfMass = [](const std::shared_ptr<Zone> & zone) -> void
  723. {
  724. int3 total(0, 0, 0);
  725. auto tiles = zone->area().getTiles();
  726. for(const auto & tile : tiles)
  727. {
  728. total += tile;
  729. }
  730. int size = static_cast<int>(tiles.size());
  731. assert(size);
  732. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  733. };
  734. int levels = map.levels();
  735. /*
  736. 1. Create Voronoi diagram
  737. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  738. */
  739. int3 pos;
  740. for(pos.z = 0; pos.z < levels; pos.z++)
  741. {
  742. for(pos.x = 0; pos.x < width; pos.x++)
  743. {
  744. for(pos.y = 0; pos.y < height; pos.y++)
  745. {
  746. distances.clear();
  747. for(const auto & zone : zones)
  748. {
  749. if (zone.second->getPos().z == pos.z)
  750. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  751. else
  752. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  753. }
  754. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  755. }
  756. }
  757. }
  758. for(const auto & zone : zones)
  759. {
  760. if(zone.second->area().empty())
  761. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  762. moveZoneToCenterOfMass(zone.second);
  763. }
  764. //assign actual tiles to each zone using nonlinear norm for fine edges
  765. for(const auto & zone : zones)
  766. zone.second->clearTiles(); //now populate them again
  767. for (pos.z = 0; pos.z < levels; pos.z++)
  768. {
  769. for (pos.x = 0; pos.x < width; pos.x++)
  770. {
  771. for (pos.y = 0; pos.y < height; pos.y++)
  772. {
  773. distances.clear();
  774. for(const auto & zone : zones)
  775. {
  776. if (zone.second->getPos().z == pos.z)
  777. distances.emplace_back(zone.second, metric(pos, zone.second->getPos()));
  778. else
  779. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  780. }
  781. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  782. zone->area().add(pos);
  783. map.setZoneID(pos, zone->getId());
  784. }
  785. }
  786. }
  787. //set position (town position) to center of mass of irregular zone
  788. for(const auto & zone : zones)
  789. {
  790. moveZoneToCenterOfMass(zone.second);
  791. //TODO: similiar for islands
  792. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  793. if (zone.second->isUnderground())
  794. {
  795. if (!CREATE_FULL_UNDERGROUND)
  796. {
  797. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  798. for(const auto & t : discardTiles)
  799. zone.second->area().erase(t);
  800. }
  801. //make sure that terrain inside zone is not a rock
  802. auto v = zone.second->getArea().getTilesVector();
  803. map.getMapProxy()->drawTerrain(*rand, v, ETerrainId::SUBTERRANEAN);
  804. }
  805. }
  806. logGlobal->info("Finished zone colouring");
  807. }
  808. const TDistanceMap& CZonePlacer::getDistanceMap()
  809. {
  810. return distancesBetweenZones;
  811. }
  812. VCMI_LIB_NAMESPACE_END