Skip to content

Commit

Permalink
generateRiverbed: Allocate buffer on heap, enumerate in row order
Browse files Browse the repository at this point in the history
  • Loading branch information
past-due committed Feb 16, 2024
1 parent f2658eb commit fb7604c
Showing 1 changed file with 26 additions and 22 deletions.
48 changes: 26 additions & 22 deletions src/map.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -756,16 +756,18 @@ static bool isWaterVertex(int x, int y)
static void generateRiverbed()
{
MersenneTwister mt(12345); // 12345 = random seed.
int maxIdx = 1, idx[MAP_MAXWIDTH][MAP_MAXHEIGHT];
int i, j, l = 0;
int maxIdx = 1;
std::vector<int> idx(mapWidth * mapHeight, 0);

Check failure

Code scanning / CodeQL

Multiplication result converted to larger type High

Multiplication result may overflow 'int' before it is converted to 'size_type'.
int x, y, l = 0;

for (i = 0; i < mapWidth; i++)
for (y = 0; y < mapHeight; y++)
{
for (j = 0; j < mapHeight; j++)
for (x = 0; x < mapWidth; x++)
{
// initially set the seabed index to 0 for ground and 100 for water
idx[i][j] = 100 * isWaterVertex(i, j);
if (idx[i][j] > 0)
int val = 100 * isWaterVertex(x, y);
idx[x + (y * mapWidth)] = val;
if (val > 0)
{
l++;
}
Expand All @@ -780,17 +782,18 @@ static void generateRiverbed()
do
{
maxIdx = 1;
for (i = 1; i < mapWidth - 2; i++)
for (y = 1; y < mapHeight - 2; y++)
{
for (j = 1; j < mapHeight - 2; j++)
for (x = 1; x < mapWidth - 2; x++)
{

if (idx[i][j] > 0)
int rowOffset = (y * mapWidth);
auto& idxVal = idx[x + rowOffset];
if (idxVal > 0)
{
idx[i][j] = (idx[i - 1][j] + idx[i][j - 1] + idx[i][j + 1] + idx[i + 1][j]) / 4;
if (idx[i][j] > maxIdx)
idxVal = (idx[(x - 1) + rowOffset] + idx[x + ((y - 1) * mapWidth)] + idx[x + ((y + 1) * mapWidth)] + idx[(x + 1) + rowOffset]) / 4;
if (idxVal > maxIdx)
{
maxIdx = idx[i][j];
maxIdx = idxVal;
}
}
}
Expand All @@ -800,22 +803,23 @@ static void generateRiverbed()
}
while (maxIdx > 90 && l < 20);

for (i = 0; i < mapWidth; i++)
for (y = 0; y < mapHeight; y++)
{
for (j = 0; j < mapHeight; j++)
for (x = 0; x < mapWidth; x++)
{
if (idx[i][j] > maxIdx)
auto& idxVal = idx[x + (y * mapWidth)];
if (idxVal > maxIdx)
{
idx[i][j] = maxIdx;
idxVal = maxIdx;
}
if (idx[i][j] < 1)
if (idxVal < 1)
{
idx[i][j] = 1;
idxVal = 1;
}
if (isWaterVertex(i, j))
if (isWaterVertex(x, y))
{
l = (WATER_MAX_DEPTH + 1 - WATER_MIN_DEPTH) * (maxIdx - idx[i][j] - mt.u32() % (maxIdx / 6 + 1));
mapTile(i, j)->height -= WATER_MIN_DEPTH - (l / maxIdx);
l = (WATER_MAX_DEPTH + 1 - WATER_MIN_DEPTH) * (maxIdx - idxVal - mt.u32() % (maxIdx / 6 + 1));
mapTile(x, y)->height -= WATER_MIN_DEPTH - (l / maxIdx);
}
}
}
Expand Down

0 comments on commit fb7604c

Please sign in to comment.