CZonePlacer.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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. std::vector<RmgMap::Zones> zonesOnLevel;
  749. for(int level = 0; level < levels; level++)
  750. {
  751. zonesOnLevel.push_back(map.getZonesOnLevel(level));
  752. }
  753. int3 pos;
  754. for(pos.z = 0; pos.z < levels; pos.z++)
  755. {
  756. for(pos.x = 0; pos.x < width; pos.x++)
  757. {
  758. for(pos.y = 0; pos.y < height; pos.y++)
  759. {
  760. distances.clear();
  761. for(const auto & zone : zonesOnLevel[pos.z])
  762. {
  763. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  764. }
  765. boost::min_element(distances, compareByDistance)->first->area()->add(pos); //closest tile belongs to zone
  766. }
  767. }
  768. }
  769. for(const auto & zone : zones)
  770. {
  771. if(zone.second->area()->empty())
  772. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  773. moveZoneToCenterOfMass(zone.second);
  774. }
  775. for(const auto & zone : zones)
  776. zone.second->clearTiles(); //now populate them again
  777. PenroseTiling penrose;
  778. for (int level = 0; level < levels; level++)
  779. {
  780. //Create different tiling for each level
  781. auto vertices = penrose.generatePenroseTiling(zonesOnLevel[level].size(), rand);
  782. // Assign zones to closest Penrose vertex
  783. std::map<std::shared_ptr<Zone>, std::set<int3>> vertexMapping;
  784. for (const auto & vertex : vertices)
  785. {
  786. distances.clear();
  787. for(const auto & zone : zonesOnLevel[level])
  788. {
  789. distances.emplace_back(zone.second, zone.second->getCenter().dist2dSQ(float3(vertex.x(), vertex.y(), level)));
  790. }
  791. auto closestZone = boost::min_element(distances, compareByDistance)->first;
  792. vertexMapping[closestZone].insert(int3(vertex.x() * width, vertex.y() * height, level)); //Closest vertex belongs to zone
  793. }
  794. //Assign actual tiles to each zone
  795. pos.z = level;
  796. for (pos.x = 0; pos.x < width; pos.x++)
  797. {
  798. for (pos.y = 0; pos.y < height; pos.y++)
  799. {
  800. distances.clear();
  801. for(const auto & zoneVertex : vertexMapping)
  802. {
  803. auto zone = zoneVertex.first;
  804. for (const auto & vertex : zoneVertex.second)
  805. {
  806. distances.emplace_back(zone, metric(pos, vertex));
  807. }
  808. }
  809. //Tile closest to vertex belongs to zone
  810. auto closestZone = boost::min_element(distances, simpleCompareByDistance)->first;
  811. closestZone->area()->add(pos);
  812. map.setZoneID(pos, closestZone->getId());
  813. }
  814. }
  815. for(const auto & zone : zonesOnLevel[level])
  816. {
  817. if(zone.second->area()->empty())
  818. {
  819. // FIXME: Some vertices are duplicated, but it's not a source of problem
  820. logGlobal->error("Zone %d at %s is empty, dumping Penrose tiling", zone.second->getId(), zone.second->getCenter().toString());
  821. for (const auto & vertex : vertices)
  822. {
  823. logGlobal->warn("Penrose Vertex: %s", vertex.toString());
  824. }
  825. throw rmgException("Empty zone after Penrose tiling");
  826. }
  827. }
  828. }
  829. //set position (town position) to center of mass of irregular zone
  830. for(const auto & zone : zones)
  831. {
  832. moveZoneToCenterOfMass(zone.second);
  833. //TODO: similiar for islands
  834. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  835. if (zone.second->isUnderground())
  836. {
  837. if (!CREATE_FULL_UNDERGROUND)
  838. {
  839. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  840. for(const auto & t : discardTiles)
  841. zone.second->area()->erase(t);
  842. }
  843. //make sure that terrain inside zone is not a rock
  844. auto v = zone.second->area()->getTilesVector();
  845. map.getMapProxy()->drawTerrain(*rand, v, ETerrainId::SUBTERRANEAN);
  846. }
  847. }
  848. logGlobal->info("Finished zone colouring");
  849. }
  850. const TDistanceMap& CZonePlacer::getDistanceMap()
  851. {
  852. return distancesBetweenZones;
  853. }
  854. VCMI_LIB_NAMESPACE_END