CZonePlacer.cpp 28 KB

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