CZonePlacer.cpp 28 KB

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