CZonePlacer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  377. if (vstd::contains(playerSettings, player))
  378. faction = playerSettings[player].getStartingTown();
  379. else
  380. logGlobal->error("Can't find info for player %d (starting zone)", player.getNum());
  381. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  382. zonesToPlace.push_back(zone);
  383. else
  384. {
  385. auto & tt = (*VLC->townh)[faction]->nativeTerrain;
  386. if(tt == ETerrainId::NONE)
  387. {
  388. //any / random
  389. zonesToPlace.push_back(zone);
  390. }
  391. else
  392. {
  393. const auto & terrainType = VLC->terrainTypeHandler->getById(tt);
  394. if(terrainType->isUnderground() && !terrainType->isSurface())
  395. {
  396. //underground only
  397. zonesOnLevel[1]++;
  398. levels[zone.first] = 1;
  399. }
  400. else
  401. {
  402. //surface
  403. zonesOnLevel[0]++;
  404. levels[zone.first] = 0;
  405. }
  406. }
  407. }
  408. }
  409. else //no starting zone or no underground altogether
  410. {
  411. zonesToPlace.push_back(zone);
  412. }
  413. }
  414. }
  415. for(const auto & zone : zonesToPlace)
  416. {
  417. if (underground) //only then consider underground zones
  418. {
  419. int level = 0;
  420. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  421. level = 1;
  422. else
  423. level = 0;
  424. levels[zone.first] = level;
  425. zonesOnLevel[level]++;
  426. }
  427. else
  428. levels[zone.first] = 0;
  429. }
  430. for(const auto & zone : zonesVector)
  431. {
  432. int level = levels[zone.first];
  433. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  434. float3 center = zone.second->getCenter();
  435. center.z = level;
  436. zone.second->setCenter(center);
  437. }
  438. /*
  439. prescale zones
  440. formula: sum((prescaler*n)^2)*pi = WH
  441. prescaler = sqrt((WH)/(sum(n^2)*pi))
  442. */
  443. std::vector<float> prescaler = { 0, 0 };
  444. for (int i = 0; i < 2; i++)
  445. prescaler[i] = std::sqrt((width * height) / (totalSize[i] * 3.14f));
  446. mapSize = static_cast<float>(sqrt(width * height));
  447. for(const auto & zone : zones)
  448. {
  449. zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  450. }
  451. }
  452. void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
  453. {
  454. for(const auto & zone : zones)
  455. {
  456. float3 forceVector(0, 0, 0);
  457. float3 pos = zone.second->getCenter();
  458. float totalDistance = 0;
  459. for (const auto & connection : zone.second->getConnections())
  460. {
  461. if (connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  462. {
  463. continue;
  464. }
  465. auto otherZone = zones[connection.getOtherZoneId(zone.second->getId())];
  466. float3 otherZoneCenter = otherZone->getCenter();
  467. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  468. forceVector += (otherZoneCenter - pos) * distance * gravityConstant * scaleForceBetweenZones(zone.second, otherZone); //positive value
  469. //Attract zone centers always
  470. float minDistance = 0;
  471. if (pos.z != otherZoneCenter.z)
  472. minDistance = 0; //zones on different levels can overlap completely
  473. else
  474. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  475. if (distance > minDistance)
  476. totalDistance += (distance - minDistance);
  477. }
  478. distances[zone.second] = totalDistance;
  479. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  480. forces[zone.second] = forceVector;
  481. }
  482. }
  483. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  484. {
  485. for(const auto & zone : zones)
  486. {
  487. float3 forceVector(0, 0, 0);
  488. float3 pos = zone.second->getCenter();
  489. float overlap = 0;
  490. //separate overlapping zones
  491. for(const auto & otherZone : zones)
  492. {
  493. float3 otherZoneCenter = otherZone.second->getCenter();
  494. //zones on different levels don't push away
  495. if (zone == otherZone || pos.z != otherZoneCenter.z)
  496. continue;
  497. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  498. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  499. if (distance < minDistance)
  500. {
  501. float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
  502. //negative value
  503. localForce *= scaleForceBetweenZones(zone.second, otherZone.second);
  504. forceVector -= localForce * (distancesBetweenZones[zone.second->getId()][otherZone.second->getId()] / 2.0f);
  505. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  506. }
  507. }
  508. //move zones away from boundaries
  509. //do not scale boundary distance - zones tend to get squashed
  510. float size = zone.second->getSize() / mapSize;
  511. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  512. {
  513. float3 boundary = float3(x, y, pos.z);
  514. auto distance = static_cast<float>(pos.dist2d(boundary));
  515. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  516. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stifness; //negative value
  517. };
  518. if (pos.x < size)
  519. {
  520. pushAwayFromBoundary(0, pos.y);
  521. }
  522. if (pos.x > 1 - size)
  523. {
  524. pushAwayFromBoundary(1, pos.y);
  525. }
  526. if (pos.y < size)
  527. {
  528. pushAwayFromBoundary(pos.x, 0);
  529. }
  530. if (pos.y > 1 - size)
  531. {
  532. pushAwayFromBoundary(pos.x, 1);
  533. }
  534. //Always move repulsive zones away, no matter their distance
  535. //TODO: Consider z plane?
  536. for (auto& connection : zone.second->getConnections())
  537. {
  538. if (connection.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  539. {
  540. auto & otherZone = zones[connection.getOtherZoneId(zone.second->getId())];
  541. float3 otherZoneCenter = otherZone->getCenter();
  542. //TODO: Roll into lambda?
  543. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  544. float minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize;
  545. float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
  546. localForce *= (distancesBetweenZones[zone.second->getId()][otherZone->getId()]);
  547. forceVector -= localForce * scaleForceBetweenZones(zone.second, otherZone);
  548. }
  549. }
  550. overlaps[zone.second] = overlap;
  551. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  552. forces[zone.second] = forceVector;
  553. }
  554. }
  555. void CZonePlacer::moveOneZone(TZoneMap& zones, TForceVector& totalForces, TDistanceVector& distances, TDistanceVector& overlaps)
  556. {
  557. //The more zones, the greater total distance expected
  558. //Also, higher stiffness make expected movement lower
  559. const int maxDistanceMovementRatio = zones.size() * zones.size() * (stiffnessConstant / stifness);
  560. typedef std::pair<float, std::shared_ptr<Zone>> Misplacement;
  561. std::vector<Misplacement> misplacedZones;
  562. float totalDistance = 0;
  563. float totalOverlap = 0;
  564. for (const auto& zone : distances) //find most misplaced zone
  565. {
  566. if (vstd::contains(lastSwappedZones, zone.first->getId()))
  567. {
  568. continue;
  569. }
  570. totalDistance += zone.second;
  571. float overlap = overlaps[zone.first];
  572. totalOverlap += overlap;
  573. //if distance to actual movement is long, the zone is misplaced
  574. float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag());
  575. if (ratio > maxDistanceMovementRatio)
  576. {
  577. misplacedZones.emplace_back(std::make_pair(ratio, zone.first));
  578. }
  579. }
  580. if (misplacedZones.empty())
  581. return;
  582. boost::sort(misplacedZones, [](const Misplacement& lhs, Misplacement& rhs)
  583. {
  584. return lhs.first > rhs.first; //Largest dispalcement first
  585. });
  586. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", misplacedZones.front().first);
  587. if (misplacedZones.size() >= 2)
  588. {
  589. //Swap 2 misplaced zones
  590. auto firstZone = misplacedZones.front().second;
  591. std::shared_ptr<Zone> secondZone;
  592. std::set<TRmgTemplateZoneId> connectedZones;
  593. for (const auto& connection : firstZone->getConnections())
  594. {
  595. //FIXME: Should we also exclude fictive connections?
  596. if (connection.getConnectionType() != rmg::EConnectionType::REPULSIVE)
  597. {
  598. connectedZones.insert(connection.getOtherZoneId(firstZone->getId()));
  599. }
  600. }
  601. auto level = firstZone->getCenter().z;
  602. for (size_t i = 1; i < misplacedZones.size(); i++)
  603. {
  604. //Only swap zones on the same level
  605. //Don't swap zones that should be connected (Jebus)
  606. if (misplacedZones[i].second->getCenter().z == level &&
  607. !vstd::contains(connectedZones, misplacedZones[i].second->getId()))
  608. {
  609. secondZone = misplacedZones[i].second;
  610. break;
  611. }
  612. }
  613. if (secondZone)
  614. {
  615. logGlobal->trace("Swapping two misplaced zones %d and %d", firstZone->getId(), secondZone->getId());
  616. auto firstCenter = firstZone->getCenter();
  617. auto secondCenter = secondZone->getCenter();
  618. firstZone->setCenter(secondCenter);
  619. secondZone->setCenter(firstCenter);
  620. lastSwappedZones.insert(firstZone->getId());
  621. lastSwappedZones.insert(secondZone->getId());
  622. return;
  623. }
  624. }
  625. lastSwappedZones.clear(); //If we didn't swap zones in this iteration, we can do it in the next
  626. //find most distant zone that should be attracted and move inside it
  627. std::shared_ptr<Zone> targetZone;
  628. auto misplacedZone = misplacedZones.front().second;
  629. float3 ourCenter = misplacedZone->getCenter();
  630. if ((totalDistance / (bestTotalDistance + 1)) > (totalOverlap / (bestTotalOverlap + 1)))
  631. {
  632. //Move one zone towards most distant zone to reduce distance
  633. float maxDistance = 0;
  634. for (auto con : misplacedZone->getConnections())
  635. {
  636. if (con.getConnectionType() == rmg::EConnectionType::REPULSIVE)
  637. {
  638. continue;
  639. }
  640. auto otherZone = zones[con.getOtherZoneId(misplacedZone->getId())];
  641. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  642. if (distance > maxDistance)
  643. {
  644. maxDistance = distance;
  645. targetZone = otherZone;
  646. }
  647. }
  648. if (targetZone)
  649. {
  650. float3 vec = targetZone->getCenter() - ourCenter;
  651. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  652. 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());
  653. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  654. }
  655. }
  656. else
  657. {
  658. //Move misplaced zone away from overlapping zone
  659. float maxOverlap = 0;
  660. for(const auto & otherZone : zones)
  661. {
  662. float3 otherZoneCenter = otherZone.second->getCenter();
  663. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  664. continue;
  665. auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  666. if (distance > maxOverlap)
  667. {
  668. maxOverlap = distance;
  669. targetZone = otherZone.second;
  670. }
  671. }
  672. if (targetZone)
  673. {
  674. float3 vec = ourCenter - targetZone->getCenter();
  675. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  676. 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());
  677. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  678. }
  679. }
  680. //Don't swap that zone in next iteration
  681. lastSwappedZones.insert(misplacedZone->getId());
  682. }
  683. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  684. {
  685. float dx = abs(A.x - B.x) * scaleX;
  686. float dy = abs(A.y - B.y) * scaleY;
  687. /*
  688. 1. Normal euclidean distance
  689. 2. Sinus for extra curves
  690. 3. Nonlinear mess for fuzzy edges
  691. */
  692. return dx * dx + dy * dy +
  693. 5 * std::sin(dx * dy / 10) +
  694. 25 * std::sin (std::sqrt(A.x * B.x) * (A.y - B.y) / 100 * (scaleX * scaleY));
  695. }
  696. void CZonePlacer::assignZones(CRandomGenerator * rand)
  697. {
  698. logGlobal->info("Starting zone colouring");
  699. auto width = map.getMapGenOptions().getWidth();
  700. auto height = map.getMapGenOptions().getHeight();
  701. //scale to Medium map to ensure smooth results
  702. scaleX = 72.f / width;
  703. scaleY = 72.f / height;
  704. auto zones = map.getZones();
  705. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  706. {
  707. return pr.second->getType() == ETemplateZoneType::WATER;
  708. });
  709. using Dpair = std::pair<std::shared_ptr<Zone>, float>;
  710. std::vector <Dpair> distances;
  711. distances.reserve(zones.size());
  712. //now place zones correctly and assign tiles to each zone
  713. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  714. {
  715. //bigger zones have smaller distance
  716. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  717. };
  718. auto moveZoneToCenterOfMass = [](const std::shared_ptr<Zone> & zone) -> void
  719. {
  720. int3 total(0, 0, 0);
  721. auto tiles = zone->area().getTiles();
  722. for(const auto & tile : tiles)
  723. {
  724. total += tile;
  725. }
  726. int size = static_cast<int>(tiles.size());
  727. assert(size);
  728. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  729. };
  730. int levels = map.levels();
  731. /*
  732. 1. Create Voronoi diagram
  733. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  734. */
  735. int3 pos;
  736. for(pos.z = 0; pos.z < levels; pos.z++)
  737. {
  738. for(pos.x = 0; pos.x < width; pos.x++)
  739. {
  740. for(pos.y = 0; pos.y < height; pos.y++)
  741. {
  742. distances.clear();
  743. for(const auto & zone : zones)
  744. {
  745. if (zone.second->getPos().z == pos.z)
  746. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  747. else
  748. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  749. }
  750. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  751. }
  752. }
  753. }
  754. for(const auto & zone : zones)
  755. {
  756. if(zone.second->area().empty())
  757. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  758. moveZoneToCenterOfMass(zone.second);
  759. }
  760. //assign actual tiles to each zone using nonlinear norm for fine edges
  761. for(const auto & zone : zones)
  762. zone.second->clearTiles(); //now populate them again
  763. for (pos.z = 0; pos.z < levels; pos.z++)
  764. {
  765. for (pos.x = 0; pos.x < width; pos.x++)
  766. {
  767. for (pos.y = 0; pos.y < height; pos.y++)
  768. {
  769. distances.clear();
  770. for(const auto & zone : zones)
  771. {
  772. if (zone.second->getPos().z == pos.z)
  773. distances.emplace_back(zone.second, metric(pos, zone.second->getPos()));
  774. else
  775. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  776. }
  777. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  778. zone->area().add(pos);
  779. map.setZoneID(pos, zone->getId());
  780. }
  781. }
  782. }
  783. //set position (town position) to center of mass of irregular zone
  784. for(const auto & zone : zones)
  785. {
  786. moveZoneToCenterOfMass(zone.second);
  787. //TODO: similiar for islands
  788. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  789. if (zone.second->isUnderground())
  790. {
  791. if (!CREATE_FULL_UNDERGROUND)
  792. {
  793. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  794. for(const auto & t : discardTiles)
  795. zone.second->area().erase(t);
  796. }
  797. //make sure that terrain inside zone is not a rock
  798. auto v = zone.second->getArea().getTilesVector();
  799. map.getMapProxy()->drawTerrain(*rand, v, ETerrainId::SUBTERRANEAN);
  800. }
  801. }
  802. logGlobal->info("Finished zone colouring");
  803. }
  804. const TDistanceMap& CZonePlacer::getDistanceMap()
  805. {
  806. return distancesBetweenZones;
  807. }
  808. VCMI_LIB_NAMESPACE_END