1
0
mirror of https://github.com/vcmi/vcmi.git synced 2025-08-13 19:54:17 +02:00

Merge pull request #2025 from vcmi/zone_placement2

No interest or objections - merging.
This commit is contained in:
DjWarmonger
2023-04-22 14:45:53 +02:00
committed by GitHub
2 changed files with 407 additions and 111 deletions

View File

@@ -9,6 +9,7 @@
*/
#include "StdInc.h"
#include <stack>
#include "../CRandomGenerator.h"
#include "CZonePlacer.h"
#include "../TerrainHandler.h"
@@ -24,10 +25,15 @@ VCMI_LIB_NAMESPACE_BEGIN
class CRandomGenerator;
CZonePlacer::CZonePlacer(RmgMap & map)
: width(0), height(0), scaleX(0), scaleY(0), mapSize(0), gravityConstant(0), stiffnessConstant(0),
: width(0), height(0), scaleX(0), scaleY(0), mapSize(0),
gravityConstant(1e-3f),
stiffnessConstant(3e-3f),
stifness(0),
stiffnessIncreaseFactor(1.03f),
bestTotalDistance(1e10),
bestTotalOverlap(1e10),
map(map)
{
}
int3 CZonePlacer::cords(const float3 & f) const
@@ -40,6 +46,251 @@ float CZonePlacer::getDistance (float distance) const
return (distance ? distance * distance : 1e-6f);
}
void CZonePlacer::findPathsBetweenZones()
{
auto zones = map.getZones();
std::set<std::shared_ptr<Zone>> zonesToCheck;
// Iterate through each pair of nodes in the graph
for (const auto& zone : zones)
{
int start = zone.first;
distancesBetweenZones[start][start] = 0; // Distance from a node to itself is 0
std::queue<int> q;
std::map<int, bool> visited;
visited[start] = true;
q.push(start);
// Perform Breadth-First Search from the starting node
while (!q.empty())
{
int current = q.front();
q.pop();
const auto& currentZone = zones.at(current);
const auto& connections = currentZone->getConnections();
for (uint32_t neighbor : connections)
{
if (!visited[neighbor])
{
visited[neighbor] = true;
q.push(neighbor);
distancesBetweenZones[start][neighbor] = distancesBetweenZones[start][current] + 1;
}
}
}
}
}
void CZonePlacer::placeOnGrid(CRandomGenerator* rand)
{
auto zones = map.getZones();
assert(zones.size());
//Make sure there are at least as many grid fields as the number of zones
size_t gridSize = std::ceil(std::sqrt(zones.size()));
typedef boost::multi_array<std::shared_ptr<Zone>, 2> GridType;
GridType grid(boost::extents[gridSize][gridSize]);
TZoneVector zonesVector(zones.begin(), zones.end());
RandomGeneratorUtil::randomShuffle(zonesVector, *rand);
//Place first zone
auto firstZone = zonesVector[0].second;
size_t x = 0, y = 0;
auto getRandomEdge = [rand, gridSize](size_t& x, size_t& y)
{
switch (rand->nextInt() % 4)
{
case 0:
x = 0;
y = gridSize / 2;
break;
case 1:
x = gridSize - 1;
y = gridSize / 2;
break;
case 2:
x = gridSize / 2;
y = 0;
break;
case 3:
x = gridSize / 2;
y = gridSize - 1;
break;
}
};
switch (firstZone->getType())
{
case ETemplateZoneType::PLAYER_START:
case ETemplateZoneType::CPU_START:
if (firstZone->getConnections().size() > 2)
{
getRandomEdge(x, y);
}
else
{
//Random corner
if (rand->nextInt() % 2)
{
x = 0;
}
else
{
x = gridSize - 1;
}
if (rand->nextInt() % 2)
{
y = 0;
}
else
{
y = gridSize - 1;
}
}
break;
case ETemplateZoneType::TREASURE:
if (gridSize & 1) //odd
{
x = y = (gridSize / 2);
}
else
{
//One of 4 squares in the middle
x = (gridSize / 2) - 1 + rand->nextInt() % 2;
y = (gridSize / 2) - 1 + rand->nextInt() % 2;
}
break;
case ETemplateZoneType::JUNCTION:
getRandomEdge(x, y);
break;
}
grid[x][y] = firstZone;
//Ignore z placement for simplicity
for (size_t i = 1; i < zones.size(); i++)
{
auto zone = zonesVector[i].second;
auto connections = zone->getConnections();
float maxDistance = -1000.0;
int3 mostDistantPlace;
//Iterate over free positions
for (size_t freeX = 0; freeX < gridSize; ++freeX)
{
for (size_t freeY = 0; freeY < gridSize; ++freeY)
{
if (!grid[freeX][freeY])
{
//There is free space left here
int3 potentialPos(freeX, freeY, 0);
//Compute distance to every existing zone
float distance = 0;
for (size_t existingX = 0; existingX < gridSize; ++existingX)
{
for (size_t existingY = 0; existingY < gridSize; ++existingY)
{
auto existingZone = grid[existingX][existingY];
if (existingZone)
{
//There is already zone here
float localDistance = 0.0f;
auto graphDistance = distancesBetweenZones[zone->getId()][existingZone->getId()];
if (graphDistance > 1)
{
//No direct connection
localDistance = potentialPos.dist2d(int3(existingX, existingY, 0)) * graphDistance;
}
else
{
//Has direct connection - place as close as possible
localDistance = -potentialPos.dist2d(int3(existingX, existingY, 0));
}
//Spread apart player starting zones
auto zoneType = zone->getType();
auto existingZoneType = existingZone->getType();
if ((zoneType == ETemplateZoneType::PLAYER_START || zoneType == ETemplateZoneType::CPU_START) &&
(existingZoneType == ETemplateZoneType::PLAYER_START || existingZoneType == ETemplateZoneType::CPU_START))
{
int firstPlayer = zone->getOwner().value();
int secondPlayer = existingZone->getOwner().value();
//Players with lower indexes (especially 1 and 2) will be placed further apart
localDistance *= (1.0f + (2.0f / (firstPlayer * secondPlayer)));
}
distance += localDistance;
}
}
}
if (distance > maxDistance)
{
maxDistance = distance;
mostDistantPlace = potentialPos;
}
}
}
}
//Place in a free slot
grid[mostDistantPlace.x][mostDistantPlace.y] = zone;
}
//TODO: toggle with a flag
logGlobal->info("Initial zone grid:");
for (size_t x = 0; x < gridSize; ++x)
{
std::string s;
for (size_t y = 0; y < gridSize; ++y)
{
if (grid[x][y])
{
s += (boost::format("%3d ") % grid[x][y]->getId()).str();
}
else
{
s += " -- ";
}
}
logGlobal->info(s);
}
//Set initial position for zones - random position in square centered around (x, y)
for (size_t x = 0; x < gridSize; ++x)
{
for (size_t y = 0; y < gridSize; ++y)
{
auto zone = grid[x][y];
if (zone)
{
//i.e. for grid size 5 we get range (0.25 - 4.75)
auto targetX = rand->nextDouble(x + 0.25f, x + 0.75f);
vstd::abetween(targetX, 0.5, gridSize - 0.5);
auto targetY = rand->nextDouble(y + 0.25f, y + 0.75f);
vstd::abetween(targetY, 0.5, gridSize - 0.5);
zone->setCenter(float3(targetX / gridSize, targetY / gridSize, zone->getPos().z));
}
}
}
}
void CZonePlacer::placeZones(CRandomGenerator * rand)
{
logGlobal->info("Starting zone placement");
@@ -54,15 +305,16 @@ void CZonePlacer::placeZones(CRandomGenerator * rand)
});
bool underground = map.getMapGenOptions().getHasTwoLevels();
findPathsBetweenZones();
placeOnGrid(rand);
/*
gravity-based algorithm
Fruchterman-Reingold algorithm
let's assume we try to fit N circular zones with radius = size on a map
Let's assume we try to fit N circular zones with radius = size on a map
Connected zones attract, intersecting zones and map boundaries push back
*/
gravityConstant = 4e-3f;
stiffnessConstant = 4e-3f;
TZoneVector zonesVector(zones.begin(), zones.end());
assert (zonesVector.size());
@@ -71,12 +323,6 @@ void CZonePlacer::placeZones(CRandomGenerator * rand)
//0. set zone sizes and surface / underground level
prepareZones(zones, zonesVector, underground, rand);
//gravity-based algorithm. connected zones attract, intersecting zones and map boundaries push back
//remember best solution
float bestTotalDistance = 1e10;
float bestTotalOverlap = 1e10;
std::map<std::shared_ptr<Zone>, float3> bestSolution;
TForceVector forces;
@@ -84,8 +330,8 @@ void CZonePlacer::placeZones(CRandomGenerator * rand)
TDistanceVector distances;
TDistanceVector overlaps;
const int MAX_ITERATIONS = 100;
for (int i = 0; i < MAX_ITERATIONS; ++i) //until zones reach their desired size and fill the map tightly
//Start with low stiffness. Bigger graphs need more time and more flexibility
for (stifness = stiffnessConstant / zones.size(); stifness <= stiffnessConstant; stifness *= stiffnessIncreaseFactor)
{
//1. attract connected zones
attractConnectedZones(zones, forces, distances);
@@ -122,14 +368,9 @@ void CZonePlacer::placeZones(CRandomGenerator * rand)
//check fitness function
bool improvement = false;
if (bestTotalDistance > 0 && bestTotalOverlap > 0)
if ((totalDistance + 1) * (totalOverlap + 1) < (bestTotalDistance + 1) * (bestTotalOverlap + 1))
{
if (totalDistance * totalOverlap < bestTotalDistance * bestTotalOverlap) //multiplication is better for auto-scaling, but stops working if one factor is 0
improvement = true;
}
else
{
if (totalDistance + totalOverlap < bestTotalDistance + bestTotalOverlap)
//multiplication is better for auto-scaling, but stops working if one factor is 0
improvement = true;
}
@@ -158,9 +399,6 @@ void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const
{
std::vector<float> totalSize = { 0, 0 }; //make sure that sum of zone sizes on surface and uderground match size of the map
const float radius = 0.4f;
const float pi2 = 6.28f;
int zonesOnLevel[2] = { 0, 0 };
//even distribution for surface / underground zones. Surface zones always have priority.
@@ -235,12 +473,14 @@ void CZonePlacer::prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const
else
levels[zone.first] = 0;
}
for(const auto & zone : zonesVector)
{
int level = levels[zone.first];
totalSize[level] += (zone.second->getSize() * zone.second->getSize());
auto randomAngle = static_cast<float>(rand->nextDouble(0, pi2));
zone.second->setCenter(float3(0.5f + std::sin(randomAngle) * radius, 0.5f + std::cos(randomAngle) * radius, level)); //place zones around circle
float3 center = zone.second->getCenter();
center.z = level;
zone.second->setCenter(center);
}
/*
@@ -274,6 +514,11 @@ void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces,
auto otherZone = zones[con];
float3 otherZoneCenter = otherZone->getCenter();
auto distance = static_cast<float>(pos.dist2d(otherZoneCenter));
forceVector += (otherZoneCenter - pos) * distance * gravityConstant; //positive value
//Attract zone centers always
float minDistance = 0;
if (pos.z != otherZoneCenter.z)
@@ -282,13 +527,8 @@ void CZonePlacer::attractConnectedZones(TZoneMap & zones, TForceVector & forces,
minDistance = (zone.second->getSize() + otherZone->getSize()) / mapSize; //scale down to (0,1) coordinates
if (distance > minDistance)
{
//WARNING: compiler used to 'optimize' that line so it never actually worked
float overlapMultiplier = (pos.z == otherZoneCenter.z) ? (minDistance / distance) : 1.0f;
forceVector += ((otherZoneCenter - pos)* overlapMultiplier / getDistance(distance)) * gravityConstant; //positive value
totalDistance += (distance - minDistance);
}
}
distances[zone.second] = totalDistance;
forceVector.z = 0; //operator - doesn't preserve z coordinate :/
forces[zone.second] = forceVector;
@@ -315,7 +555,9 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces
float minDistance = (zone.second->getSize() + otherZone.second->getSize()) / mapSize;
if (distance < minDistance)
{
forceVector -= (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stiffnessConstant; //negative value
float3 localForce = (((otherZoneCenter - pos)*(minDistance / (distance ? distance : 1e-3f))) / getDistance(distance)) * stifness;
//negative value
forceVector -= localForce * (distancesBetweenZones[zone.second->getId()][otherZone.second->getId()] / 2.0f);
overlap += (minDistance - distance); //overlapping of small zones hurts us more
}
}
@@ -329,7 +571,7 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces
float3 boundary = float3(x, y, pos.z);
auto distance = static_cast<float>(pos.dist2d(boundary));
overlap += std::max<float>(0, distance - size); //check if we're closer to map boundary than value of zone size
forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stiffnessConstant; //negative value
forceVector -= (boundary - pos) * (size - distance) / this->getDistance(distance) * this->stifness; //negative value
};
if (pos.x < size)
{
@@ -353,36 +595,86 @@ void CZonePlacer::separateOverlappingZones(TZoneMap &zones, TForceVector &forces
}
}
void CZonePlacer::moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDistanceVector & distances, TDistanceVector & overlaps) const
void CZonePlacer::moveOneZone(TZoneMap& zones, TForceVector& totalForces, TDistanceVector& distances, TDistanceVector& overlaps)
{
float maxRatio = 0;
const int maxDistanceMovementRatio = static_cast<int>(zones.size() * zones.size()); //experimental - the more zones, the greater total distance expected
std::shared_ptr<Zone> misplacedZone;
const int maxDistanceMovementRatio = zones.size() * zones.size(); //The more zones, the greater total distance expected
typedef std::pair<float, std::shared_ptr<Zone>> Misplacement;
std::vector<Misplacement> misplacedZones;
float totalDistance = 0;
float totalOverlap = 0;
for(const auto & zone : distances) //find most misplaced zone
for (const auto& zone : distances) //find most misplaced zone
{
if (vstd::contains(lastSwappedZones, zone.first->getId()))
{
continue;
}
totalDistance += zone.second;
float overlap = overlaps[zone.first];
totalOverlap += overlap;
float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag()); //if distance to actual movement is long, the zone is misplaced
if (ratio > maxRatio)
//if distance to actual movement is long, the zone is misplaced
float ratio = (zone.second + overlap) / static_cast<float>(totalForces[zone.first].mag());
if (ratio > maxDistanceMovementRatio)
{
maxRatio = ratio;
misplacedZone = zone.first;
misplacedZones.emplace_back(std::make_pair(ratio, zone.first));
}
}
logGlobal->trace("Worst misplacement/movement ratio: %3.2f", maxRatio);
if (maxRatio > maxDistanceMovementRatio && misplacedZone)
if (misplacedZones.empty())
return;
boost::sort(misplacedZones, [](const Misplacement& lhs, Misplacement& rhs)
{
return lhs.first > rhs.first; //Biggest first
});
logGlobal->trace("Worst misplacement/movement ratio: %3.2f", misplacedZones.front().first);
if (misplacedZones.size() >= 2)
{
//Swap 2 misplaced zones
auto firstZone = misplacedZones.front().second;
std::shared_ptr<Zone> secondZone;
auto level = firstZone->getCenter().z;
for (size_t i = 1; i < misplacedZones.size(); i++)
{
//Only swap zones on the same level
//Don't swap zones that should be connected (Jebus)
if (misplacedZones[i].second->getCenter().z == level &&
!vstd::contains(firstZone->getConnections(), misplacedZones[i].second->getId()))
{
secondZone = misplacedZones[i].second;
break;
}
}
if (secondZone)
{
logGlobal->trace("Swapping two misplaced zones %d and %d", firstZone->getId(), secondZone->getId());
auto firstCenter = firstZone->getCenter();
auto secondCenter = secondZone->getCenter();
firstZone->setCenter(secondCenter);
secondZone->setCenter(firstCenter);
lastSwappedZones.insert(firstZone->getId());
lastSwappedZones.insert(secondZone->getId());
return;
}
}
lastSwappedZones.clear(); //If we didn't swap zones in this iteration, we can do it in the next
//find most distant zone that should be attracted and move inside it
std::shared_ptr<Zone> targetZone;
auto misplacedZone = misplacedZones.front().second;
float3 ourCenter = misplacedZone->getCenter();
if (totalDistance > totalOverlap)
if ((totalDistance / (bestTotalDistance + 1)) > (totalOverlap / (bestTotalOverlap + 1)))
{
//find most distant zone that should be attracted and move inside it
//Move one zone towards most distant zone to reduce distance
float maxDistance = 0;
for (auto con : misplacedZone->getConnections())
{
@@ -394,19 +686,19 @@ void CZonePlacer::moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDis
targetZone = otherZone;
}
}
if (targetZone) //TODO: consider refactoring duplicated code
if (targetZone)
{
float3 vec = targetZone->getCenter() - ourCenter;
float newDistanceBetweenZones = (std::max(misplacedZone->getSize(), targetZone->getSize())) / mapSize;
logGlobal->trace("Trying to move zone %d %s towards %d %s. Old distance %f", misplacedZone->getId(), ourCenter.toString(), targetZone->getId(), targetZone->getCenter().toString(), maxDistance);
logGlobal->trace("direction is %s", vec.toString());
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());
misplacedZone->setCenter(targetZone->getCenter() - vec.unitVector() * newDistanceBetweenZones); //zones should now overlap by half size
logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
}
}
else
{
//Move misplaced zone away from overlapping zone
float maxOverlap = 0;
for(const auto & otherZone : zones)
{
@@ -426,34 +718,29 @@ void CZonePlacer::moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDis
{
float3 vec = ourCenter - targetZone->getCenter();
float newDistanceBetweenZones = (misplacedZone->getSize() + targetZone->getSize()) / mapSize;
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);
logGlobal->trace("direction is %s", vec.toString());
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());
misplacedZone->setCenter(targetZone->getCenter() + vec.unitVector() * newDistanceBetweenZones); //zones should now be just separated
logGlobal->trace("New distance %f", targetZone->getCenter().dist2d(misplacedZone->getCenter()));
}
}
}
//Don't swap that zone in next iteration
lastSwappedZones.insert(misplacedZone->getId());
}
float CZonePlacer::metric (const int3 &A, const int3 &B) const
{
/*
Matlab code
dx = abs(A(1) - B(1)); %distance must be symmetric
dy = abs(A(2) - B(2));
d = 0.01 * dx^3 - 0.1618 * dx^2 + 1 * dx + ...
0.01618 * dy^3 + 0.1 * dy^2 + 0.168 * dy;
*/
float dx = abs(A.x - B.x) * scaleX;
float dy = abs(A.y - B.y) * scaleY;
//Horner scheme
return dx * (1.0f + dx * (0.1f + dx * 0.01f)) + dy * (1.618f + dy * (-0.1618f + dy * 0.01618f));
/*
1. Normal euclidean distance
2. Sinus for extra curves
3. Nonlinear mess for fuzzy edges
*/
return dx * dx + dy * dy +
5 * std::sin(dx * dy / 10) +
25 * std::sin (std::sqrt(A.x * B.x) * (A.y - B.y) / 100 * (scaleX * scaleY));
}
void CZonePlacer::assignZones(CRandomGenerator * rand)

View File

@@ -37,27 +37,36 @@ public:
~CZonePlacer() = default;
void placeZones(CRandomGenerator * rand);
void findPathsBetweenZones();
void placeOnGrid(CRandomGenerator* rand);
void assignZones(CRandomGenerator * rand);
private:
void prepareZones(TZoneMap &zones, TZoneVector &zonesVector, const bool underground, CRandomGenerator * rand);
void attractConnectedZones(TZoneMap & zones, TForceVector & forces, TDistanceVector & distances) const;
void separateOverlappingZones(TZoneMap &zones, TForceVector &forces, TDistanceVector &overlaps);
void moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDistanceVector & distances, TDistanceVector & overlaps) const;
void moveOneZone(TZoneMap & zones, TForceVector & totalForces, TDistanceVector & distances, TDistanceVector & overlaps);
private:
int width;
int height;
//metric coefiicients
//metric coeficients
float scaleX;
float scaleY;
float mapSize;
float gravityConstant;
float stiffnessConstant;
//float a1, b1, c1, a2, b2, c2;
//CMap * map;
//std::unique_ptr<CZoneGraph> graph;
float stifness;
float stiffnessIncreaseFactor;
//remember best solution
float bestTotalDistance;
float bestTotalOverlap;
//distance [a][b] = number of zone connections required to travel between the zones
std::map<int, std::map<int, size_t>> distancesBetweenZones;
std::set<TRmgTemplateZoneId> lastSwappedZones;
RmgMap & map;
};