CZonePlacer.cpp 29 KB

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