CZonePlacer.cpp 27 KB

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