CZonePlacer.cpp 28 KB

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