CZonePlacer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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 <stack>
  12. #include "../CRandomGenerator.h"
  13. #include "CZonePlacer.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. VCMI_LIB_NAMESPACE_BEGIN
  22. class CRandomGenerator;
  23. CZonePlacer::CZonePlacer(RmgMap & map)
  24. : width(0), height(0), scaleX(0), scaleY(0), mapSize(0), gravityConstant(0), stiffnessConstant(0),
  25. map(map)
  26. {
  27. }
  28. int3 CZonePlacer::cords(const float3 & f) const
  29. {
  30. return int3(static_cast<si32>(std::max(0.f, (f.x * map.map().width) - 1)), static_cast<si32>(std::max(0.f, (f.y * map.map().height - 1))), f.z);
  31. }
  32. float CZonePlacer::getDistance (float distance) const
  33. {
  34. return (distance ? distance * distance : 1e-6f);
  35. }
  36. void CZonePlacer::findPathsBetweenZones()
  37. {
  38. typedef std::pair<int, int> ConnectionIndex;
  39. auto zones = map.getZones();
  40. std::set<std::shared_ptr<Zone>> zonesToCheck;
  41. //Initialize direct connections
  42. for (auto zone : zones)
  43. {
  44. auto zoneId = zone.second->getId();
  45. for (auto connection : zone.second->getConnections())
  46. {
  47. if (!vstd::contains(distancesBetweenZones[zoneId], connection))
  48. {
  49. distancesBetweenZones[zoneId][connection] = 1;
  50. distancesBetweenZones[connection][zoneId] = 1;
  51. }
  52. }
  53. }
  54. for (auto startZone : zones)
  55. {
  56. size_t start = startZone.second->getId();
  57. for (auto endZone : zones)
  58. {
  59. size_t end = endZone.second->getId();
  60. if (start != end)
  61. {
  62. auto currentEnd = end;
  63. while (!vstd::contains(distancesBetweenZones[start], end))
  64. {
  65. size_t distance = 10; //Some large but not infinite number to not blow up the weights
  66. std::stack<int> nearbyZones;
  67. std::set<int> checkedZones;
  68. //FIXME: we may know the path from previous iterations, but can't be sure if it's optimal :?
  69. for (auto nearbyZone : startZone.second->getConnections())
  70. {
  71. nearbyZones.push(nearbyZone);
  72. }
  73. while (!nearbyZones.empty())
  74. {
  75. auto currentZone = nearbyZones.top();
  76. nearbyZones.pop();
  77. checkedZones.insert(currentZone);
  78. for (auto neighbourZone : distancesBetweenZones[currentZone])
  79. {
  80. if (neighbourZone.first == currentEnd)
  81. {
  82. //This zone has connection to our end zone
  83. if (!vstd::contains(distancesBetweenZones[currentZone], currentEnd))
  84. {
  85. //Initialize the connection of adjacent zones
  86. distancesBetweenZones[currentZone][currentEnd] = 1;
  87. }
  88. if ((distancesBetweenZones[currentZone][currentEnd] + 1) < distance)
  89. {
  90. //We found new, shorter path
  91. distance = distancesBetweenZones[currentZone][currentEnd] + 1;
  92. //Add just found connection
  93. distancesBetweenZones[start][currentEnd] = distance;
  94. //Connection is bidirectional
  95. distancesBetweenZones[currentEnd][start] = distance;
  96. //Unwind the stack, find the path between start previous-to-last zone
  97. currentEnd = currentZone;
  98. }
  99. }
  100. else
  101. {
  102. if (!vstd::contains(checkedZones, neighbourZone.first))
  103. {
  104. //We didn't check that zone yet
  105. nearbyZones.push(neighbourZone.first);
  106. }
  107. }
  108. }
  109. }
  110. //At the very least after this step we will find 1 more step connecting the two zones
  111. }
  112. }
  113. }
  114. }
  115. //Dump debug
  116. for (auto startZone : zones)
  117. {
  118. auto startId = startZone.second->getId();
  119. for (auto endZone : zones)
  120. {
  121. auto endId = endZone.second->getId();
  122. if (startId >= endId)
  123. {
  124. //Print only conections in one way
  125. continue;
  126. }
  127. logGlobal->info((boost::format("Distance between zone %2d and %2d: %d")
  128. % startId % endId % distancesBetweenZones[startId][endId]).str());
  129. }
  130. }
  131. }
  132. void CZonePlacer::placeOnGrid(CRandomGenerator* rand)
  133. {
  134. auto zones = map.getZones();
  135. assert(zones.size());
  136. //TODO: determine all the distances between zones on a graph
  137. //Make sure there are at least as many grid fields as the number of zones
  138. size_t gridSize = std::ceil(std::sqrt(zones.size()));
  139. typedef boost::multi_array<std::shared_ptr<Zone>, 2> GridType;
  140. GridType grid(boost::extents[gridSize][gridSize]);
  141. TZoneVector zonesVector(zones.begin(), zones.end());
  142. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  143. //Place first zone
  144. auto firstZone = zonesVector[0].second;
  145. size_t x = 0, y = 0;
  146. auto getRandomEdge = [rand, gridSize](size_t& x, size_t& y)
  147. {
  148. switch (rand->nextInt() % 4)
  149. {
  150. case 0:
  151. x = 0;
  152. y = gridSize / 2;
  153. break;
  154. case 1:
  155. x = gridSize - 1;
  156. y = gridSize / 2;
  157. break;
  158. case 2:
  159. x = gridSize / 2;
  160. y = 0;
  161. break;
  162. case 3:
  163. x = gridSize / 2;
  164. y = gridSize - 1;
  165. break;
  166. }
  167. };
  168. switch (firstZone->getType())
  169. {
  170. case ETemplateZoneType::PLAYER_START:
  171. case ETemplateZoneType::CPU_START:
  172. if (firstZone->getConnections().size() > 2)
  173. {
  174. getRandomEdge(x, y);
  175. }
  176. else
  177. {
  178. //Random corner
  179. if (rand->nextInt() % 2)
  180. {
  181. x = 0;
  182. }
  183. else
  184. {
  185. x = gridSize - 1;
  186. }
  187. if (rand->nextInt() % 2)
  188. {
  189. y = 0;
  190. }
  191. else
  192. {
  193. y = gridSize - 1;
  194. }
  195. }
  196. break;
  197. case ETemplateZoneType::TREASURE:
  198. if (gridSize && 1) //odd
  199. {
  200. x = y = (gridSize / 2);
  201. }
  202. else
  203. {
  204. //One of 4 squares in the middle
  205. x = (gridSize / 2) - 1 + rand->nextInt() % 2;
  206. y = (gridSize / 2) - 1 + rand->nextInt() % 2;
  207. }
  208. break;
  209. case ETemplateZoneType::JUNCTION:
  210. getRandomEdge(x, y);
  211. break;
  212. }
  213. grid[x][y] = firstZone;
  214. //Ignore z placement for simplicity
  215. for (size_t i = 1; i < zones.size(); i++)
  216. {
  217. auto zone = zonesVector[i].second;
  218. auto connections = zone->getConnections();
  219. float maxDistance = 0.0;
  220. int3 mostDistantPlace;
  221. //Iterate over free positions
  222. for (size_t freeX = 0; freeX < gridSize; ++freeX)
  223. {
  224. for (size_t freeY = 0; freeY < gridSize; ++freeY)
  225. {
  226. if (!grid[freeX][freeY])
  227. {
  228. //There is free space left here
  229. int3 potentialPos(freeX, freeY, 0);
  230. //Compute distance to every existing zone
  231. for (size_t existingX = 0; existingX < gridSize; ++existingX)
  232. {
  233. for (size_t existingY = 0; existingY < gridSize; ++existingY)
  234. {
  235. float distance = 0.0;
  236. auto existingZone = grid[existingX][existingY];
  237. if (existingZone )
  238. {
  239. //There is already zone here
  240. if (distancesBetweenZones[zone->getId()][existingZone->getId()] > 1)
  241. {
  242. //No direct connection
  243. distance += potentialPos.dist2d(int3(existingX, existingY, 0));
  244. //TODO: Multiply by weight - the distance from A*
  245. }
  246. else
  247. {
  248. //Has direct connection
  249. distance -= (gridSize - 1);
  250. }
  251. //TODO: Multiply if zones belong to players, especially humans.
  252. //Starting zones should be as far away from eahc other as possible
  253. if (distance > maxDistance)
  254. {
  255. distance = maxDistance;
  256. mostDistantPlace = potentialPos;
  257. }
  258. }
  259. }
  260. }
  261. }
  262. }
  263. }
  264. //Place in a free slot
  265. grid[mostDistantPlace.x][mostDistantPlace.y] = zone;
  266. }
  267. //TODO: toggle with a flag
  268. logGlobal->info("Initial zone grid:");
  269. for (size_t x = 0; x < gridSize; ++x)
  270. {
  271. std::string s;
  272. for (size_t y = 0; y < gridSize; ++y)
  273. {
  274. if (grid[x][y])
  275. {
  276. s += (boost::format("%3d ") % grid[x][y]->getId()).str();
  277. }
  278. else
  279. {
  280. s += " -- ";
  281. }
  282. }
  283. logGlobal->info(s);
  284. }
  285. //Set initial position for zones - random position in square centered around (x, y)
  286. for (size_t x = 0; x < gridSize; ++x)
  287. {
  288. for (size_t y = 0; y < gridSize; ++y)
  289. {
  290. auto zone = grid[x][y];
  291. if (zone)
  292. {
  293. auto targetX = rand->nextDouble(x - 0.5f, x + 0.5f);
  294. vstd::clamp(targetX, 0, gridSize);
  295. auto targetY = rand->nextDouble(y - 0.5f, y + 0.5f);
  296. vstd::clamp(targetY, 0, gridSize);
  297. zone->setCenter(float3(targetX / gridSize, targetY / gridSize, zone->getPos().z));
  298. }
  299. }
  300. }
  301. }
  302. void CZonePlacer::placeZones(CRandomGenerator * rand)
  303. {
  304. logGlobal->info("Starting zone placement");
  305. width = map.getMapGenOptions().getWidth();
  306. height = map.getMapGenOptions().getHeight();
  307. auto zones = map.getZones();
  308. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  309. {
  310. return pr.second->getType() == ETemplateZoneType::WATER;
  311. });
  312. bool underground = map.getMapGenOptions().getHasTwoLevels();
  313. findPathsBetweenZones();
  314. placeOnGrid(rand);
  315. /*
  316. gravity-based algorithm
  317. let's assume we try to fit N circular zones with radius = size on a map
  318. */
  319. gravityConstant = 4e-3f;
  320. stiffnessConstant = 4e-3f;
  321. TZoneVector zonesVector(zones.begin(), zones.end());
  322. assert (zonesVector.size());
  323. RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
  324. //0. set zone sizes and surface / underground level
  325. prepareZones(zones, zonesVector, underground, rand);
  326. //gravity-based algorithm. connected zones attract, intersecting zones and map boundaries push back
  327. //remember best solution
  328. float bestTotalDistance = 1e10;
  329. float bestTotalOverlap = 1e10;
  330. std::map<std::shared_ptr<Zone>, float3> bestSolution;
  331. TForceVector forces;
  332. TForceVector totalForces; // both attraction and pushback, overcomplicated?
  333. TDistanceVector distances;
  334. TDistanceVector overlaps;
  335. const int MAX_ITERATIONS = 100;
  336. for (int i = 0; i < MAX_ITERATIONS; ++i) //until zones reach their desired size and fill the map tightly
  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. //3. now perform drastic movement of zone that is completely not linked
  353. moveOneZone(zones, totalForces, distances, overlaps);
  354. //4. NOW after everything was moved, re-evaluate zone positions
  355. attractConnectedZones(zones, forces, distances);
  356. separateOverlappingZones(zones, forces, overlaps);
  357. float totalDistance = 0;
  358. float totalOverlap = 0;
  359. for(const auto & zone : distances) //find most misplaced zone
  360. {
  361. totalDistance += zone.second;
  362. float overlap = overlaps[zone.first];
  363. totalOverlap += overlap;
  364. }
  365. //check fitness function
  366. bool improvement = false;
  367. if (bestTotalDistance > 0 && bestTotalOverlap > 0)
  368. {
  369. if (totalDistance * totalOverlap < bestTotalDistance * bestTotalOverlap) //multiplication is better for auto-scaling, but stops working if one factor is 0
  370. improvement = true;
  371. }
  372. else
  373. {
  374. if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
  375. improvement = true;
  376. }
  377. logGlobal->trace("Total distance between zones after this iteration: %2.4f, Total overlap: %2.4f, Improved: %s", totalDistance, totalOverlap , improvement);
  378. //save best solution
  379. if (improvement)
  380. {
  381. bestTotalDistance = totalDistance;
  382. bestTotalOverlap = totalOverlap;
  383. for(const auto & zone : zones)
  384. bestSolution[zone.second] = zone.second->getCenter();
  385. }
  386. }
  387. logGlobal->trace("Best fitness reached: total distance %2.4f, total overlap %2.4f", bestTotalDistance, bestTotalOverlap);
  388. for(const auto & zone : zones) //finalize zone positions
  389. {
  390. zone.second->setPos (cords (bestSolution[zone.second]));
  391. logGlobal->trace("Placed zone %d at relative position %s and coordinates %s", zone.first, zone.second->getCenter().toString(), zone.second->getPos().toString());
  392. }
  393. }
  394. void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand)
  395. {
  396. std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
  397. const float radius = 0.4f;
  398. const float pi2 = 6.28f;
  399. int zonesOnLevel[2] = { 0, 0 };
  400. //even distribution for surface / underground zones. Surface zones always have priority.
  401. TZoneVector zonesToPlace;
  402. std::map<TRmgTemplateZoneId, int> levels;
  403. //first pass - determine fixed surface for zones
  404. for(const auto & zone : zonesVector)
  405. {
  406. if (!underground) //this step is ignored
  407. zonesToPlace.push_back(zone);
  408. else //place players depending on their factions
  409. {
  410. if(std::optional<int> owner = zone.second->getOwner())
  411. {
  412. auto player = PlayerColor(*owner - 1);
  413. auto playerSettings = map.getMapGenOptions().getPlayersSettings();
  414. si32 faction = CMapGenOptions::CPlayerSettings::RANDOM_TOWN;
  415. if (vstd::contains(playerSettings, player))
  416. faction = playerSettings[player].getStartingTown();
  417. else
  418. logGlobal->error("Can't find info for player %d (starting zone)", player.getNum());
  419. if (faction == CMapGenOptions::CPlayerSettings::RANDOM_TOWN) //TODO: check this after a town has already been randomized
  420. zonesToPlace.push_back(zone);
  421. else
  422. {
  423. auto & tt = (*VLC->townh)[faction]->nativeTerrain;
  424. if(tt == ETerrainId::NONE)
  425. {
  426. //any / random
  427. zonesToPlace.push_back(zone);
  428. }
  429. else
  430. {
  431. const auto & terrainType = VLC->terrainTypeHandler->getById(tt);
  432. if(terrainType->isUnderground() && !terrainType->isSurface())
  433. {
  434. //underground only
  435. zonesOnLevel[1]++;
  436. levels[zone.first] = 1;
  437. }
  438. else
  439. {
  440. //surface
  441. zonesOnLevel[0]++;
  442. levels[zone.first] = 0;
  443. }
  444. }
  445. }
  446. }
  447. else //no starting zone or no underground altogether
  448. {
  449. zonesToPlace.push_back(zone);
  450. }
  451. }
  452. }
  453. for(const auto & zone : zonesToPlace)
  454. {
  455. if (underground) //only then consider underground zones
  456. {
  457. int level = 0;
  458. if (zonesOnLevel[1] < zonesOnLevel[0]) //only if there are less underground zones
  459. level = 1;
  460. else
  461. level = 0;
  462. levels[zone.first] = level;
  463. zonesOnLevel[level]++;
  464. }
  465. else
  466. levels[zone.first] = 0;
  467. }
  468. for(const auto & zone : zonesVector)
  469. {
  470. int level = levels[zone.first];
  471. totalSize[level] += (zone.second->getSize() * zone.second->getSize());
  472. auto randomAngle = static_cast<float>(rand->nextDouble(0, pi2));
  473. zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
  474. }
  475. /*
  476. prescale zones
  477. formula: sum((prescaler*n)^2)*pi = WH
  478. prescaler = sqrt((WH)/(sum(n^2)*pi))
  479. */
  480. std::vector<float> prescaler = { 0, 0 };
  481. for (int i = 0; i < 2; i++)
  482. prescaler[i] = std::sqrt((width * height) / (totalSize[i] * 3.14f));
  483. mapSize = static_cast<float>(sqrt(width * height));
  484. for(const auto & zone : zones)
  485. {
  486. zone.second->setSize(static_cast<int>(zone.second->getSize() * prescaler[zone.second->getCenter().z]));
  487. }
  488. }
  489. void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const
  490. {
  491. for(const auto & zone : zones)
  492. {
  493. float3 forceVector(0, 0, 0);
  494. float3 pos = zone.second->getCenter();
  495. float totalDistance = 0;
  496. for (auto con : zone.second->getConnections())
  497. {
  498. auto otherZone = zones[con];
  499. float3 otherZoneCenter = otherZone->getCenter();
  500. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  501. float minDistance = 0;
  502. if (pos.z != otherZoneCenter.z)
  503. minDistance = 0; //zones on different levels can overlap completely
  504. else
  505. minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
  506. if (distance > minDistance)
  507. {
  508. //WARNING: compiler used to 'optimize' that line so it never actually worked
  509. float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
  510. forceVector += ((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance)) * gravityConstant; //positive value
  511. totalDistance += (distance - minDistance);
  512. }
  513. }
  514. distances[zone.second] = totalDistance;
  515. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  516. forces[zone.second] = forceVector;
  517. }
  518. }
  519. void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps)
  520. {
  521. for(const auto & zone : zones)
  522. {
  523. float3 forceVector(0, 0, 0);
  524. float3 pos = zone.second->getCenter();
  525. float overlap = 0;
  526. //separate overlapping zones
  527. for(const auto & otherZone : zones)
  528. {
  529. float3 otherZoneCenter = otherZone.second->getCenter();
  530. //zones on different levels don't push away
  531. if (zone == otherZone || pos.z != otherZoneCenter.z)
  532. continue;
  533. auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
  534. float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
  535. if (distance < minDistance)
  536. {
  537. forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stiffnessConstant; //negative value
  538. overlap += (minDistance - distance); //overlapping of small zones hurts us more
  539. }
  540. }
  541. //move zones away from boundaries
  542. //do not scale boundary distance - zones tend to get squashed
  543. float size = zone.second->getSize() / mapSize;
  544. auto pushAwayFromBoundary = [&forceVector, pos, size, &overlap, this](float x, float y)
  545. {
  546. float3 boundary = float3(x, y, pos.z);
  547. auto distance = static_cast<float>(pos.dist2d(boundary));
  548. overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
  549. forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value
  550. };
  551. if (pos.x < size)
  552. {
  553. pushAwayFromBoundary(0, pos.y);
  554. }
  555. if (pos.x > 1 - size)
  556. {
  557. pushAwayFromBoundary(1, pos.y);
  558. }
  559. if (pos.y < size)
  560. {
  561. pushAwayFromBoundary(pos.x, 0);
  562. }
  563. if (pos.y > 1 - size)
  564. {
  565. pushAwayFromBoundary(pos.x, 1);
  566. }
  567. overlaps[zone.second] = overlap;
  568. forceVector.z = 0; //operator - doesn't preserve z coordinate :/
  569. forces[zone.second] = forceVector;
  570. }
  571. }
  572. void CZonePlacer::moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDistanceVector & distances, TDistanceVector & overlaps) const
  573. {
  574. float maxRatio = 0;
  575. const int maxDistanceMovementRatio = static_cast<int>(zones.size() * zones.size()); //experimental - the more zones, the greater total distance expected
  576. std::shared_ptr<Zone> misplacedZone;
  577. float totalDistance = 0;
  578. float totalOverlap = 0;
  579. for(const auto & zone : distances) //find most misplaced zone
  580. {
  581. totalDistance += zone.second;
  582. float overlap = overlaps[zone.first];
  583. totalOverlap += overlap;
  584. float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag()); //if distance to actual movement is long, the zone is misplaced
  585. if (ratio > maxRatio)
  586. {
  587. maxRatio = ratio;
  588. misplacedZone = zone.first;
  589. }
  590. }
  591. logGlobal->trace("Worst misplacement/movement ratio: %3.2f", maxRatio);
  592. if (maxRatio > maxDistanceMovementRatio && misplacedZone)
  593. {
  594. std::shared_ptr<Zone> targetZone;
  595. float3 ourCenter = misplacedZone->getCenter();
  596. if (totalDistance > totalOverlap)
  597. {
  598. //find most distant zone that should be attracted and move inside it
  599. float maxDistance = 0;
  600. for (auto con : misplacedZone->getConnections())
  601. {
  602. auto otherZone = zones[con];
  603. float distance = static_cast<float>(otherZone->getCenter().dist2dSQ(ourCenter));
  604. if (distance > maxDistance)
  605. {
  606. maxDistance = distance;
  607. targetZone = otherZone;
  608. }
  609. }
  610. if (targetZone) //TODO: consider refactoring duplicated code
  611. {
  612. float3 vec = targetZone->getCenter() - ourCenter;
  613. float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
  614. logGlobal->trace("Trying to move zone %d %s towards %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxDistance);
  615. logGlobal->trace("direction is %s", vec.toString());
  616. misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
  617. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  618. }
  619. }
  620. else
  621. {
  622. float maxOverlap = 0;
  623. for(const auto & otherZone : zones)
  624. {
  625. float3 otherZoneCenter = otherZone.second->getCenter();
  626. if (otherZone.second == misplacedZone || otherZoneCenter.z != ourCenter.z)
  627. continue;
  628. auto distance = static_cast<float>(otherZoneCenter.dist2dSQ(ourCenter));
  629. if (distance > maxOverlap)
  630. {
  631. maxOverlap = distance;
  632. targetZone = otherZone.second;
  633. }
  634. }
  635. if (targetZone)
  636. {
  637. float3 vec = ourCenter - targetZone->getCenter();
  638. float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
  639. logGlobal->trace("Trying to move zone %d %s away from %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxOverlap);
  640. logGlobal->trace("direction is %s", vec.toString());
  641. misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
  642. logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
  643. }
  644. }
  645. }
  646. }
  647. float CZonePlacer::metric (const int3 &A, const int3 &B) const
  648. {
  649. /*
  650. Matlab code
  651. dx = abs(A(1) - B(1)); %distance must be symmetric
  652. dy = abs(A(2) - B(2));
  653. d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
  654. 0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
  655. */
  656. float dx = abs(A.x - B.x) * scaleX;
  657. float dy = abs(A.y - B.y) * scaleY;
  658. //Horner scheme
  659. return dx * (1.0f + dx * (0.1f + dx * 0.01f)) + dy * (1.618f + dy * (-0.1618f + dy * 0.01618f));
  660. }
  661. void CZonePlacer::assignZones(CRandomGenerator * rand)
  662. {
  663. logGlobal->info("Starting zone colouring");
  664. auto width = map.getMapGenOptions().getWidth();
  665. auto height = map.getMapGenOptions().getHeight();
  666. //scale to Medium map to ensure smooth results
  667. scaleX = 72.f / width;
  668. scaleY = 72.f / height;
  669. auto zones = map.getZones();
  670. vstd::erase_if(zones, [](const std::pair<TRmgTemplateZoneId, std::shared_ptr<Zone>> & pr)
  671. {
  672. return pr.second->getType() == ETemplateZoneType::WATER;
  673. });
  674. using Dpair = std::pair<std::shared_ptr<Zone>, float>;
  675. std::vector <Dpair> distances;
  676. distances.reserve(zones.size());
  677. //now place zones correctly and assign tiles to each zone
  678. auto compareByDistance = [](const Dpair & lhs, const Dpair & rhs) -> bool
  679. {
  680. //bigger zones have smaller distance
  681. return lhs.second / lhs.first->getSize() < rhs.second / rhs.first->getSize();
  682. };
  683. auto moveZoneToCenterOfMass = [](const std::shared_ptr<Zone> & zone) -> void
  684. {
  685. int3 total(0, 0, 0);
  686. auto tiles = zone->area().getTiles();
  687. for(const auto & tile : tiles)
  688. {
  689. total += tile;
  690. }
  691. int size = static_cast<int>(tiles.size());
  692. assert(size);
  693. zone->setPos(int3(total.x / size, total.y / size, total.z / size));
  694. };
  695. int levels = map.map().levels();
  696. /*
  697. 1. Create Voronoi diagram
  698. 2. find current center of mass for each zone. Move zone to that center to balance zones sizes
  699. */
  700. int3 pos;
  701. for(pos.z = 0; pos.z < levels; pos.z++)
  702. {
  703. for(pos.x = 0; pos.x < width; pos.x++)
  704. {
  705. for(pos.y = 0; pos.y < height; pos.y++)
  706. {
  707. distances.clear();
  708. for(const auto & zone : zones)
  709. {
  710. if (zone.second->getPos().z == pos.z)
  711. distances.emplace_back(zone.second, static_cast<float>(pos.dist2dSQ(zone.second->getPos())));
  712. else
  713. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  714. }
  715. boost::min_element(distances, compareByDistance)->first->area().add(pos); //closest tile belongs to zone
  716. }
  717. }
  718. }
  719. for(const auto & zone : zones)
  720. {
  721. if(zone.second->area().empty())
  722. throw rmgException("Empty zone is generated, probably RMG template is inappropriate for map size");
  723. moveZoneToCenterOfMass(zone.second);
  724. }
  725. //assign actual tiles to each zone using nonlinear norm for fine edges
  726. for(const auto & zone : zones)
  727. zone.second->clearTiles(); //now populate them again
  728. for (pos.z = 0; pos.z < levels; pos.z++)
  729. {
  730. for (pos.x = 0; pos.x < width; pos.x++)
  731. {
  732. for (pos.y = 0; pos.y < height; pos.y++)
  733. {
  734. distances.clear();
  735. for(const auto & zone : zones)
  736. {
  737. if (zone.second->getPos().z == pos.z)
  738. distances.emplace_back(zone.second, metric(pos, zone.second->getPos()));
  739. else
  740. distances.emplace_back(zone.second, std::numeric_limits<float>::max());
  741. }
  742. auto zone = boost::min_element(distances, compareByDistance)->first; //closest tile belongs to zone
  743. zone->area().add(pos);
  744. map.setZoneID(pos, zone->getId());
  745. }
  746. }
  747. }
  748. //set position (town position) to center of mass of irregular zone
  749. for(const auto & zone : zones)
  750. {
  751. moveZoneToCenterOfMass(zone.second);
  752. //TODO: similiar for islands
  753. #define CREATE_FULL_UNDERGROUND true //consider linking this with water amount
  754. if (zone.second->isUnderground())
  755. {
  756. if (!CREATE_FULL_UNDERGROUND)
  757. {
  758. auto discardTiles = collectDistantTiles(*zone.second, zone.second->getSize() + 1.f);
  759. for(const auto & t : discardTiles)
  760. zone.second->area().erase(t);
  761. }
  762. //make sure that terrain inside zone is not a rock
  763. //FIXME: reorder actions?
  764. paintZoneTerrain(*zone.second, *rand, map, ETerrainId::SUBTERRANEAN);
  765. }
  766. }
  767. logGlobal->info("Finished zone colouring");
  768. }
  769. VCMI_LIB_NAMESPACE_END