Files
OpenRCT2-Web/src/openrct2/world/MapGen.cpp
T

898 lines
30 KiB
C++
Raw Normal View History

2014-09-25 02:39:17 +01:00
/*****************************************************************************
* Copyright (c) 2014-2024 OpenRCT2 developers
2014-09-25 02:39:17 +01:00
*
2018-06-15 14:07:34 +02:00
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
2014-09-25 02:39:17 +01:00
*
2018-06-15 14:07:34 +02:00
* OpenRCT2 is licensed under the GNU General Public License version 3.
2014-09-25 02:39:17 +01:00
*****************************************************************************/
2018-06-22 23:17:03 +02:00
#include "MapGen.h"
#include "../Context.h"
2024-07-09 16:23:31 +02:00
#include "../Diagnostic.h"
2018-06-22 23:17:03 +02:00
#include "../Game.h"
2024-02-12 21:32:08 +00:00
#include "../GameState.h"
2017-02-11 15:35:06 +01:00
#include "../core/Guard.hpp"
2018-06-22 23:17:03 +02:00
#include "../core/Imaging.h"
2017-11-17 10:22:54 +01:00
#include "../core/String.hpp"
2018-01-06 18:32:25 +01:00
#include "../localisation/StringIds.h"
2023-02-12 20:43:11 +00:00
#include "../object/ObjectEntryManager.h"
#include "../object/ObjectList.h"
#include "../object/ObjectManager.h"
#include "../object/SmallSceneryEntry.h"
#include "../object/TerrainEdgeObject.h"
#include "../object/TerrainSurfaceObject.h"
2022-02-18 21:57:00 +01:00
#include "../platform/Platform.h"
2017-12-13 13:02:24 +01:00
#include "../util/Util.h"
2024-05-02 23:31:01 +02:00
#include "../world/tile_element/Slope.h"
2018-01-03 14:56:08 +01:00
#include "Map.h"
2018-01-11 10:59:26 +01:00
#include "MapHelpers.h"
#include "Scenery.h"
2018-05-01 16:33:16 +02:00
#include "Surface.h"
2015-02-10 19:52:24 +00:00
2018-06-22 23:17:03 +02:00
#include <cmath>
#include <cstring>
2018-11-21 23:16:04 +01:00
#include <iterator>
2018-06-22 23:17:03 +02:00
#include <vector>
using namespace OpenRCT2;
2017-03-08 16:50:30 +01:00
#pragma region Height map struct
2015-02-10 19:52:24 +00:00
2017-11-17 10:22:54 +01:00
static struct
{
2021-02-12 20:20:51 +00:00
uint32_t width = 0;
uint32_t height = 0;
std::vector<uint8_t> mono_bitmap;
} _heightMapData;
2017-03-08 16:50:30 +01:00
#pragma endregion Height map struct
#pragma region Random objects
2018-06-22 23:17:03 +02:00
static constexpr const char* GrassTrees[] = {
2017-06-06 23:24:18 +02:00
// Dark
"rct2.scenery_small.tcf", // Caucasian Fir Tree
"rct2.scenery_small.trf", // Red Fir Tree
"rct2.scenery_small.trf2", // Red Fir Tree
"rct2.scenery_small.tsp", // Scots Pine Tree
"rct2.scenery_small.tmzp", // Montezuma Pine Tree
"rct2.scenery_small.tap", // Aleppo Pine Tree
"rct2.scenery_small.tcrp", // Corsican Pine Tree
"rct2.scenery_small.tbp", // Black Poplar Tree
2015-02-10 19:52:24 +00:00
2017-06-06 23:24:18 +02:00
// Light
"rct2.scenery_small.tcl", // Cedar of Lebanon Tree
"rct2.scenery_small.tel", // European Larch Tree
2015-02-10 19:52:24 +00:00
};
2018-06-22 23:17:03 +02:00
static constexpr const char* DesertTrees[] = {
"rct2.scenery_small.tmp", // Monkey-Puzzle Tree
"rct2.scenery_small.thl", // Honey Locust Tree
"rct2.scenery_small.th1", // Canary Palm Tree
"rct2.scenery_small.th2", // Palm Tree
"rct2.scenery_small.tpm", // Palm Tree
"rct2.scenery_small.tropt1", // Tree
"rct2.scenery_small.tbc", // Cactus
"rct2.scenery_small.tsc", // Cactus
2015-02-10 19:52:24 +00:00
};
2018-06-22 23:17:03 +02:00
static constexpr const char* SnowTrees[] = {
"rct2.scenery_small.tcfs", // Snow-covered Caucasian Fir Tree
"rct2.scenery_small.tnss", // Snow-covered Norway Spruce Tree
"rct2.scenery_small.trf3", // Snow-covered Red Fir Tree
"rct2.scenery_small.trfs", // Snow-covered Red Fir Tree
2015-02-10 19:52:24 +00:00
};
#pragma endregion
2014-09-25 02:39:17 +01:00
2015-02-11 00:02:09 +00:00
// Randomly chosen base terrains. We rarely want a whole map made out of chequerboard or rock.
static constexpr std::string_view BaseTerrain[] = {
2021-10-27 14:21:14 +02:00
"rct2.terrain_surface.grass", "rct2.terrain_surface.sand", "rct2.terrain_surface.sand_brown",
"rct2.terrain_surface.dirt", "rct2.terrain_surface.ice",
2021-10-17 15:31:56 +02:00
};
2015-02-11 00:02:09 +00:00
2022-10-04 20:24:38 +01:00
static void MapGenPlaceTrees();
static void MapGenSetWaterLevel(int32_t waterLevel);
static void MapGenSmoothHeight(int32_t iterations);
2023-01-19 15:13:23 +00:00
static void MapGenSetHeight(MapGenSettings* settings);
2014-09-25 18:57:13 +01:00
2022-10-04 20:24:38 +01:00
static float FractalNoise(int32_t x, int32_t y, float frequency, int32_t octaves, float lacunarity, float persistence);
2023-01-19 15:13:23 +00:00
static void MapGenSimplex(MapGenSettings* settings);
2022-06-04 19:56:31 +02:00
static TileCoordsXY _heightSize;
2018-06-22 23:17:03 +02:00
static uint8_t* _height;
2014-09-25 18:57:13 +01:00
2022-10-04 20:24:38 +01:00
static int32_t GetHeight(int32_t x, int32_t y)
2015-02-11 00:02:09 +00:00
{
2022-06-04 19:56:31 +02:00
if (x >= 0 && y >= 0 && x < _heightSize.x && y < _heightSize.y)
return _height[x + y * _heightSize.x];
2021-09-15 22:22:15 +02:00
return 0;
2015-02-11 00:02:09 +00:00
}
2014-09-25 18:57:13 +01:00
2022-10-04 20:24:38 +01:00
static void SetHeight(int32_t x, int32_t y, int32_t height)
2015-02-11 00:02:09 +00:00
{
2022-06-04 19:56:31 +02:00
if (x >= 0 && y >= 0 && x < _heightSize.x && y < _heightSize.y)
_height[x + y * _heightSize.x] = height;
2015-02-11 00:02:09 +00:00
}
2014-09-25 02:39:17 +01:00
2023-01-19 15:13:23 +00:00
void MapGenGenerateBlank(MapGenSettings* settings)
2014-09-25 02:39:17 +01:00
{
int32_t x, y;
MapClearAllElements();
MapInit(settings->mapSize);
2022-06-04 19:56:31 +02:00
for (y = 1; y < settings->mapSize.y - 1; y++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
for (x = 1; x < settings->mapSize.x - 1; x++)
2017-11-17 10:22:54 +01:00
{
auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y });
if (surfaceElement != nullptr)
{
surfaceElement->SetSurfaceObjectIndex(settings->floor);
surfaceElement->SetEdgeObjectIndex(settings->wall);
surfaceElement->BaseHeight = settings->height;
surfaceElement->ClearanceHeight = settings->height;
}
2017-06-06 23:24:18 +02:00
}
}
2023-04-05 23:37:18 +03:00
2022-10-04 20:24:38 +01:00
MapGenSetWaterLevel(settings->water_level);
2015-02-10 19:52:24 +00:00
}
2024-09-10 11:21:09 +02:00
void MapGenGenerateSimplex(MapGenSettings* settings)
2015-02-10 19:52:24 +00:00
{
2022-06-04 19:56:31 +02:00
const auto& mapSize = settings->mapSize;
auto waterLevel = settings->water_level;
const auto selectedFloor = TerrainSurfaceObject::GetById(settings->floor);
std::string_view floorTexture = selectedFloor != nullptr ? selectedFloor->GetIdentifier() : "";
const auto selectedEdge = TerrainEdgeObject::GetById(settings->wall);
std::string_view edgeTexture = selectedFloor != nullptr ? selectedEdge->GetIdentifier() : "";
2022-05-15 10:34:32 +02:00
auto& objectManager = OpenRCT2::GetContext()->GetObjectManager();
2015-02-10 19:52:24 +00:00
2021-03-31 19:15:33 +02:00
if (floorTexture.empty())
{
std::vector<std::string_view> availableTerrains;
2022-05-15 10:34:32 +02:00
std::copy_if(std::begin(BaseTerrain), std::end(BaseTerrain), std::back_inserter(availableTerrains), [&](auto terrain) {
return objectManager.GetLoadedObject(ObjectEntryDescriptor(terrain)) != nullptr;
});
if (availableTerrains.empty())
// Fall back to the first available surface texture that is available in the park
floorTexture = TerrainSurfaceObject::GetById(0)->GetIdentifier();
else
floorTexture = availableTerrains[UtilRand() % availableTerrains.size()];
}
2015-02-11 00:02:09 +00:00
2021-03-31 19:15:33 +02:00
if (edgeTexture.empty())
2017-11-17 10:22:54 +01:00
{
2017-06-06 23:24:18 +02:00
// Base edge type on surface type
2021-10-27 14:21:14 +02:00
if (floorTexture == "rct2.terrain_surface.dirt")
edgeTexture = "rct2.terrain_edge.wood_red";
else if (floorTexture == "rct2.terrain_surface.ice")
edgeTexture = "rct2.terrain_edge.ice";
else
2021-10-27 14:21:14 +02:00
edgeTexture = "rct2.terrain_edge.rock";
// Fall back to the first available edge texture that is available in the park
2022-05-15 10:34:32 +02:00
if (objectManager.GetLoadedObject(ObjectEntryDescriptor(edgeTexture)) == nullptr)
edgeTexture = TerrainEdgeObject::GetById(0)->GetIdentifier();
2017-06-06 23:24:18 +02:00
}
2015-02-10 19:52:24 +00:00
2022-05-15 10:34:32 +02:00
auto floorTextureId = objectManager.GetLoadedObjectEntryIndex(ObjectEntryDescriptor(floorTexture));
auto edgeTextureId = objectManager.GetLoadedObjectEntryIndex(ObjectEntryDescriptor(edgeTexture));
MapClearAllElements();
2017-06-06 23:24:18 +02:00
// Initialise the base map
MapInit(mapSize);
2022-06-04 19:56:31 +02:00
for (auto y = 1; y < mapSize.y - 1; y++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
for (auto x = 1; x < mapSize.x - 1; x++)
2017-11-17 10:22:54 +01:00
{
auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y });
if (surfaceElement != nullptr)
{
surfaceElement->SetSurfaceObjectIndex(floorTextureId);
surfaceElement->SetEdgeObjectIndex(edgeTextureId);
surfaceElement->BaseHeight = settings->height;
surfaceElement->ClearanceHeight = settings->height;
}
2017-06-06 23:24:18 +02:00
}
}
2014-09-25 02:39:17 +01:00
2017-06-06 23:24:18 +02:00
// Create the temporary height map and initialise
2022-06-04 19:56:31 +02:00
_heightSize = { mapSize.x * 2, mapSize.y * 2 };
_height = new uint8_t[_heightSize.y * _heightSize.x];
std::fill_n(_height, _heightSize.y * _heightSize.x, 0x00);
2014-09-25 02:39:17 +01:00
2022-10-04 20:24:38 +01:00
MapGenSimplex(settings);
MapGenSmoothHeight(2 + (UtilRand() % 6));
2015-02-11 00:02:09 +00:00
2017-06-06 23:24:18 +02:00
// Set the game map to the height map
2022-10-04 20:24:38 +01:00
MapGenSetHeight(settings);
2017-11-17 10:22:54 +01:00
delete[] _height;
2014-09-25 02:39:17 +01:00
2017-06-06 23:24:18 +02:00
// Set the tile slopes so that there are no cliffs
while (MapSmooth(1, 1, mapSize.x - 1, mapSize.y - 1))
2018-06-22 23:17:03 +02:00
{
}
2015-02-11 00:02:09 +00:00
2017-06-06 23:24:18 +02:00
// Add the water
2022-10-04 20:24:38 +01:00
MapGenSetWaterLevel(waterLevel);
2017-06-06 23:24:18 +02:00
// Add sandy beaches
std::string_view beachTexture = floorTexture;
if (settings->floor == -1 && floorTexture == "rct2.terrain_surface.grass" && (UtilRand() & 1))
2017-11-17 10:22:54 +01:00
{
std::vector<std::string_view> availableBeachTextures;
2022-05-15 10:34:32 +02:00
if (objectManager.GetLoadedObject(ObjectEntryDescriptor("rct2.terrain_surface.sand")) != nullptr)
availableBeachTextures.push_back("rct2.terrain_surface.sand");
2022-05-15 10:34:32 +02:00
if (objectManager.GetLoadedObject(ObjectEntryDescriptor("rct2.terrain_surface.sand_brown")) != nullptr)
availableBeachTextures.push_back("rct2.terrain_surface.sand_brown");
if (!availableBeachTextures.empty())
beachTexture = availableBeachTextures[UtilRand() % availableBeachTextures.size()];
2017-06-06 23:24:18 +02:00
}
2022-05-15 10:34:32 +02:00
auto beachTextureId = objectManager.GetLoadedObjectEntryIndex(ObjectEntryDescriptor(beachTexture));
2022-06-04 19:56:31 +02:00
for (auto y = 1; y < mapSize.y - 1; y++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
for (auto x = 1; x < mapSize.x - 1; x++)
2017-11-17 10:22:54 +01:00
{
auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y });
if (surfaceElement != nullptr && surfaceElement->BaseHeight < waterLevel + 6)
surfaceElement->SetSurfaceObjectIndex(beachTextureId);
2017-06-06 23:24:18 +02:00
}
}
2014-09-26 02:33:15 +01:00
2017-06-06 23:24:18 +02:00
// Place the trees
if (settings->trees != 0)
2022-10-04 20:24:38 +01:00
MapGenPlaceTrees();
2015-02-10 19:52:24 +00:00
}
2014-09-26 02:33:15 +01:00
2022-10-04 20:24:38 +01:00
static void MapGenPlaceTree(ObjectEntryIndex type, const CoordsXY& loc)
2014-09-26 02:33:15 +01:00
{
2023-02-12 20:43:11 +00:00
auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry<SmallSceneryEntry>(type);
if (sceneryEntry == nullptr)
{
return;
}
2020-03-07 23:20:21 +01:00
2022-10-12 06:35:20 +01:00
int32_t surfaceZ = TileElementHeight(loc.ToTileCentre());
auto* sceneryElement = TileElementInsert<SmallSceneryElement>({ loc, surfaceZ }, 0b1111);
Guard::Assert(sceneryElement != nullptr);
2021-06-04 02:14:41 +01:00
sceneryElement->SetClearanceZ(surfaceZ + sceneryEntry->height);
sceneryElement->SetDirection(UtilRand() & 3);
2018-09-13 17:26:36 +02:00
sceneryElement->SetEntryIndex(type);
sceneryElement->SetAge(0);
2018-09-13 18:12:20 +02:00
sceneryElement->SetPrimaryColour(COLOUR_YELLOW);
2014-09-26 02:33:15 +01:00
}
static bool MapGenSurfaceTakesGrassTrees(const TerrainSurfaceObject& surface)
{
const auto& id = surface.GetIdentifier();
2021-10-27 14:21:14 +02:00
return id == "rct2.terrain_surface.grass" || id == "rct2.terrain_surface.grass_clumps" || id == "rct2.terrain_surface.dirt";
}
static bool MapGenSurfaceTakesSandTrees(const TerrainSurfaceObject& surface)
{
const auto& id = surface.GetIdentifier();
2021-10-27 14:21:14 +02:00
return id == "rct2.terrain_surface.sand" || id == "rct2.terrain_surface.sand_brown"
|| id == "rct2.terrain_surface.sand_red";
}
static bool MapGenSurfaceTakesSnowTrees(const TerrainSurfaceObject& surface)
{
const auto& id = surface.GetIdentifier();
2021-10-27 14:21:14 +02:00
return id == "rct2.terrain_surface.ice";
}
2022-02-09 17:28:15 +00:00
template<typename T> static bool TryFindTreeInList(std::string_view id, const T& treeList)
{
for (size_t j = 0; j < std::size(treeList); j++)
{
if (treeList[j] == id)
return true;
}
return false;
}
2015-02-11 00:02:09 +00:00
/**
* Randomly places a selection of preset trees on the map. Picks the right tree for the terrain it is placing it on.
*/
2022-10-04 20:24:38 +01:00
static void MapGenPlaceTrees()
2014-09-26 02:33:15 +01:00
{
2022-02-09 17:28:15 +00:00
std::vector<int32_t> grassTreeIds;
std::vector<int32_t> desertTreeIds;
std::vector<int32_t> snowTreeIds;
2015-02-10 19:52:24 +00:00
for (auto i = 0u; i < getObjectEntryGroupCount(ObjectType::SmallScenery); i++)
2017-11-17 10:22:54 +01:00
{
2023-02-12 20:43:11 +00:00
auto* sceneryEntry = OpenRCT2::ObjectManager::GetObjectEntry<SmallSceneryEntry>(i);
2023-01-17 20:46:55 +01:00
auto entry = ObjectEntryGetObject(ObjectType::SmallScenery, i);
2015-02-10 19:52:24 +00:00
2017-11-17 10:22:54 +01:00
if (sceneryEntry == nullptr)
2017-06-06 23:24:18 +02:00
continue;
2015-02-10 19:52:24 +00:00
2022-02-09 17:28:15 +00:00
if (TryFindTreeInList(entry->GetIdentifier(), GrassTrees))
2017-11-17 10:22:54 +01:00
{
grassTreeIds.push_back(i);
2017-06-06 23:24:18 +02:00
}
2022-02-09 17:28:15 +00:00
else if (TryFindTreeInList(entry->GetIdentifier(), DesertTrees))
2017-11-17 10:22:54 +01:00
{
desertTreeIds.push_back(i);
2017-06-06 23:24:18 +02:00
}
2022-02-09 17:28:15 +00:00
else if (TryFindTreeInList(entry->GetIdentifier(), SnowTrees))
2017-11-17 10:22:54 +01:00
{
snowTreeIds.push_back(i);
2017-06-06 23:24:18 +02:00
}
}
2015-02-10 19:52:24 +00:00
// Place trees
CoordsXY pos;
float treeToLandRatio = (10 + (UtilRand() % 30)) / 100.0f;
2024-09-02 21:42:37 +01:00
auto& gameState = GetGameState();
2024-02-12 21:32:08 +00:00
for (int32_t y = 1; y < gameState.MapSize.y - 1; y++)
2017-11-17 10:22:54 +01:00
{
2024-02-12 21:32:08 +00:00
for (int32_t x = 1; x < gameState.MapSize.x - 1; x++)
2017-11-17 10:22:54 +01:00
{
2024-07-26 18:23:25 +10:00
pos.x = x * kCoordsXYStep;
pos.y = y * kCoordsXYStep;
auto* surfaceElement = MapGetSurfaceElementAt(pos);
if (surfaceElement == nullptr)
continue;
2014-09-26 02:33:15 +01:00
// Don't place on water
if (surfaceElement->GetWaterHeight() > 0)
2017-06-06 23:24:18 +02:00
continue;
2014-09-26 02:33:15 +01:00
// On sand surfaces, give the tile a score based on nearby water, to be used to determine whether to spawn
// vegetation
float oasisScore = 0.0f;
ObjectEntryIndex treeObjectEntryIndex = OBJECT_ENTRY_INDEX_NULL;
const auto& surfaceStyleObject = *TerrainSurfaceObject::GetById(surfaceElement->GetSurfaceObjectIndex());
if (MapGenSurfaceTakesSandTrees(surfaceStyleObject))
{
oasisScore = -0.5f;
constexpr auto maxOasisDistance = 4;
for (int32_t offsetY = -maxOasisDistance; offsetY <= maxOasisDistance; offsetY++)
{
for (int32_t offsetX = -maxOasisDistance; offsetX <= maxOasisDistance; offsetX++)
{
// Get map coord, clamped to the edges
2024-07-26 18:23:25 +10:00
const auto offset = CoordsXY{ offsetX * kCoordsXYStep, offsetY * kCoordsXYStep };
auto neighbourPos = pos + offset;
2024-07-26 18:23:25 +10:00
neighbourPos.x = std::clamp(neighbourPos.x, kCoordsXYStep, kCoordsXYStep * (gameState.MapSize.x - 1));
neighbourPos.y = std::clamp(neighbourPos.y, kCoordsXYStep, kCoordsXYStep * (gameState.MapSize.y - 1));
const auto neighboutSurface = MapGetSurfaceElementAt(neighbourPos);
if (neighboutSurface != nullptr && neighboutSurface->GetWaterHeight() > 0)
{
float distance = std::sqrt(offsetX * offsetX + offsetY * offsetY);
oasisScore += 0.5f / (maxOasisDistance * distance);
}
}
}
}
// Use tree:land ratio except when near an oasis
constexpr static auto randModulo = 0xFFFF;
if (static_cast<float>(UtilRand() & randModulo) / randModulo > std::max(treeToLandRatio, oasisScore))
continue;
// Use fractal noise to group tiles that are likely to spawn trees together
2022-10-04 20:24:38 +01:00
float noiseValue = FractalNoise(x, y, 0.025f, 2, 2.0f, 0.65f);
// Reduces the range to rarely stray further than 0.5 from the mean.
float noiseOffset = UtilRandNormalDistributed() * 0.25f;
if (noiseValue + oasisScore < noiseOffset)
continue;
if (!grassTreeIds.empty() && MapGenSurfaceTakesGrassTrees(surfaceStyleObject))
{
treeObjectEntryIndex = grassTreeIds[UtilRand() % grassTreeIds.size()];
}
else if (!desertTreeIds.empty() && MapGenSurfaceTakesSandTrees(surfaceStyleObject))
{
treeObjectEntryIndex = desertTreeIds[UtilRand() % desertTreeIds.size()];
}
else if (!snowTreeIds.empty() && MapGenSurfaceTakesSnowTrees(surfaceStyleObject))
{
treeObjectEntryIndex = snowTreeIds[UtilRand() % snowTreeIds.size()];
}
if (treeObjectEntryIndex != OBJECT_ENTRY_INDEX_NULL)
2022-10-04 20:24:38 +01:00
MapGenPlaceTree(treeObjectEntryIndex, pos);
2017-06-06 23:24:18 +02:00
}
}
2014-09-25 02:39:17 +01:00
}
2015-02-11 00:02:09 +00:00
/**
* Sets each tile's water level to the specified water level if underneath that water level.
*/
2022-10-04 20:24:38 +01:00
static void MapGenSetWaterLevel(int32_t waterLevel)
2014-09-25 02:39:17 +01:00
{
2024-09-02 21:42:37 +01:00
auto& gameState = GetGameState();
2024-02-12 21:32:08 +00:00
for (int32_t y = 1; y < gameState.MapSize.y - 1; y++)
2017-11-17 10:22:54 +01:00
{
2024-02-12 21:32:08 +00:00
for (int32_t x = 1; x < gameState.MapSize.x - 1; x++)
2017-11-17 10:22:54 +01:00
{
auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y });
if (surfaceElement != nullptr && surfaceElement->BaseHeight < waterLevel)
2024-07-26 18:23:25 +10:00
surfaceElement->SetWaterHeight(waterLevel * kCoordsZStep);
2017-06-06 23:24:18 +02:00
}
}
2014-09-25 18:57:13 +01:00
}
2015-02-11 00:02:09 +00:00
/**
* Smooths the height map.
*/
2022-10-04 20:24:38 +01:00
static void MapGenSmoothHeight(int32_t iterations)
2014-09-25 18:57:13 +01:00
{
int32_t i, x, y, xx, yy, avg;
2022-06-04 19:56:31 +02:00
int32_t arraySize = _heightSize.y * _heightSize.x * sizeof(uint8_t);
2018-06-22 23:17:03 +02:00
uint8_t* copyHeight = new uint8_t[arraySize];
2014-09-25 18:57:13 +01:00
2017-11-17 10:22:54 +01:00
for (i = 0; i < iterations; i++)
{
std::memcpy(copyHeight, _height, arraySize);
2022-06-04 19:56:31 +02:00
for (y = 1; y < _heightSize.y - 1; y++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
for (x = 1; x < _heightSize.x - 1; x++)
2017-11-17 10:22:54 +01:00
{
2018-06-22 23:17:03 +02:00
avg = 0;
2017-06-06 23:24:18 +02:00
for (yy = -1; yy <= 1; yy++)
2017-11-17 10:22:54 +01:00
{
2017-06-06 23:24:18 +02:00
for (xx = -1; xx <= 1; xx++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
avg += copyHeight[(y + yy) * _heightSize.x + (x + xx)];
2017-11-17 10:22:54 +01:00
}
}
2017-06-06 23:24:18 +02:00
avg /= 9;
2022-10-04 20:24:38 +01:00
SetHeight(x, y, avg);
2017-06-06 23:24:18 +02:00
}
}
}
2017-11-17 10:22:54 +01:00
delete[] copyHeight;
2014-09-25 18:57:13 +01:00
}
2015-02-11 00:02:09 +00:00
/**
* Sets the height of the actual game map tiles to the height map.
*/
2023-01-19 15:13:23 +00:00
static void MapGenSetHeight(MapGenSettings* settings)
2014-09-25 18:57:13 +01:00
{
2022-06-04 19:56:31 +02:00
int32_t x, y, heightX, heightY;
2014-09-25 18:57:13 +01:00
2022-06-04 19:56:31 +02:00
for (y = 1; y < _heightSize.y / 2 - 1; y++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
for (x = 1; x < _heightSize.x / 2 - 1; x++)
2017-11-17 10:22:54 +01:00
{
2017-06-06 23:24:18 +02:00
heightX = x * 2;
heightY = y * 2;
2014-09-25 18:57:13 +01:00
2022-10-04 20:24:38 +01:00
uint8_t q00 = GetHeight(heightX + 0, heightY + 0);
uint8_t q01 = GetHeight(heightX + 0, heightY + 1);
uint8_t q10 = GetHeight(heightX + 1, heightY + 0);
uint8_t q11 = GetHeight(heightX + 1, heightY + 1);
2014-09-25 18:57:13 +01:00
uint8_t baseHeight = (q00 + q01 + q10 + q11) / 4;
2015-10-20 20:16:30 +02:00
auto surfaceElement = MapGetSurfaceElementAt(TileCoordsXY{ x, y });
if (surfaceElement == nullptr)
continue;
surfaceElement->BaseHeight = std::max(2, baseHeight * 2);
// If base height is below water level, lower it to create more natural shorelines
if (surfaceElement->BaseHeight >= 4 && surfaceElement->BaseHeight <= settings->water_level)
surfaceElement->BaseHeight -= 2;
surfaceElement->ClearanceHeight = surfaceElement->BaseHeight;
2014-09-25 18:57:13 +01:00
uint8_t currentSlope = surfaceElement->GetSlope();
2018-09-14 14:54:12 +02:00
2017-06-06 23:24:18 +02:00
if (q00 > baseHeight)
2024-05-02 23:31:01 +02:00
currentSlope |= kTileSlopeSCornerUp;
2017-06-06 23:24:18 +02:00
if (q01 > baseHeight)
2024-05-02 23:31:01 +02:00
currentSlope |= kTileSlopeWCornerUp;
2017-06-06 23:24:18 +02:00
if (q10 > baseHeight)
2024-05-02 23:31:01 +02:00
currentSlope |= kTileSlopeECornerUp;
2017-06-06 23:24:18 +02:00
if (q11 > baseHeight)
2024-05-02 23:31:01 +02:00
currentSlope |= kTileSlopeNCornerUp;
2018-09-14 14:54:12 +02:00
surfaceElement->SetSlope(currentSlope);
2017-06-06 23:24:18 +02:00
}
}
}
#pragma region Noise
/**
* Simplex Noise Algorithm with Fractional Brownian Motion
* Based on:
* - https://code.google.com/p/simplexnoise/
* - https://code.google.com/p/fractalterraingeneration/wiki/Fractional_Brownian_Motion
*/
2022-10-04 20:24:38 +01:00
static float Generate(float x, float y);
static int32_t FastFloor(float x);
static float Grad(int32_t hash, float x, float y);
static uint8_t perm[512];
2022-10-04 20:24:38 +01:00
static void NoiseRand()
{
2018-06-22 23:17:03 +02:00
for (auto& i : perm)
2017-11-17 10:22:54 +01:00
{
i = UtilRand() & 0xFF;
2017-11-17 10:22:54 +01:00
}
}
2022-10-04 20:24:38 +01:00
static float FractalNoise(int32_t x, int32_t y, float frequency, int32_t octaves, float lacunarity, float persistence)
{
2018-06-22 23:17:03 +02:00
float total = 0.0f;
float amplitude = persistence;
for (int32_t i = 0; i < octaves; i++)
2017-11-17 10:22:54 +01:00
{
2022-10-04 20:24:38 +01:00
total += Generate(x * frequency, y * frequency) * amplitude;
2017-06-06 23:24:18 +02:00
frequency *= lacunarity;
amplitude *= persistence;
}
return total;
}
2022-10-04 20:24:38 +01:00
static float Generate(float x, float y)
{
2017-06-06 23:24:18 +02:00
const float F2 = 0.366025403f; // F2 = 0.5*(sqrt(3.0)-1.0)
2018-08-12 12:50:40 +01:00
const float G2 = 0.211324865f; // G2 = (3.0-sqrt(3.0))/6.0
2017-06-06 23:24:18 +02:00
float n0, n1, n2; // Noise contributions from the three corners
2017-06-06 23:24:18 +02:00
// Skew the input space to determine which simplex cell we're in
2018-06-22 23:17:03 +02:00
float s = (x + y) * F2; // Hairy factor for 2D
float xs = x + s;
float ys = y + s;
2022-10-04 20:24:38 +01:00
int32_t i = FastFloor(xs);
int32_t j = FastFloor(ys);
2020-04-17 16:08:22 -03:00
float t = static_cast<float>(i + j) * G2;
2017-06-06 23:24:18 +02:00
float X0 = i - t; // Unskew the cell origin back to (x,y) space
float Y0 = j - t;
float x0 = x - X0; // The x,y distances from the cell origin
float y0 = y - Y0;
2017-06-06 23:24:18 +02:00
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
int32_t i1, j1; // Offsets for second (middle) corner of simplex in (i,j) coords
2017-11-17 10:22:54 +01:00
if (x0 > y0)
{
i1 = 1;
j1 = 0;
} // lower triangle, XY order: (0,0)->(1,0)->(1,1)
else
{
i1 = 0;
j1 = 1;
2018-06-22 23:17:03 +02:00
} // upper triangle, YX order: (0,0)->(0,1)->(1,1)
2017-06-06 23:24:18 +02:00
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
2017-06-06 23:24:18 +02:00
float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
float y1 = y0 - j1 + G2;
float x2 = x0 - 1.0f + 2.0f * G2; // Offsets for last corner in (x,y) unskewed coords
float y2 = y0 - 1.0f + 2.0f * G2;
2017-06-06 23:24:18 +02:00
// Wrap the integer indices at 256, to avoid indexing perm[] out of bounds
int32_t ii = i % 256;
int32_t jj = j % 256;
2017-06-06 23:24:18 +02:00
// Calculate the contribution from the three corners
float t0 = 0.5f - x0 * x0 - y0 * y0;
2017-11-17 10:22:54 +01:00
if (t0 < 0.0f)
{
n0 = 0.0f;
}
else
{
2017-06-06 23:24:18 +02:00
t0 *= t0;
2022-10-04 20:24:38 +01:00
n0 = t0 * t0 * Grad(perm[ii + perm[jj]], x0, y0);
2017-06-06 23:24:18 +02:00
}
2017-06-06 23:24:18 +02:00
float t1 = 0.5f - x1 * x1 - y1 * y1;
2017-11-17 10:22:54 +01:00
if (t1 < 0.0f)
{
n1 = 0.0f;
}
else
{
2017-06-06 23:24:18 +02:00
t1 *= t1;
2022-10-04 20:24:38 +01:00
n1 = t1 * t1 * Grad(perm[ii + i1 + perm[jj + j1]], x1, y1);
2017-06-06 23:24:18 +02:00
}
2017-06-06 23:24:18 +02:00
float t2 = 0.5f - x2 * x2 - y2 * y2;
2017-11-17 10:22:54 +01:00
if (t2 < 0.0f)
{
n2 = 0.0f;
}
else
{
2017-06-06 23:24:18 +02:00
t2 *= t2;
2022-10-04 20:24:38 +01:00
n2 = t2 * t2 * Grad(perm[ii + 1 + perm[jj + 1]], x2, y2);
2017-06-06 23:24:18 +02:00
}
2017-06-06 23:24:18 +02:00
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 40.0f * (n0 + n1 + n2); // TODO: The scale factor is preliminary!
}
2022-10-04 20:24:38 +01:00
static int32_t FastFloor(float x)
{
2020-04-17 16:08:22 -03:00
return (x > 0) ? (static_cast<int32_t>(x)) : ((static_cast<int32_t>(x)) - 1);
}
2022-10-04 20:24:38 +01:00
static float Grad(int32_t hash, float x, float y)
{
2018-06-22 23:17:03 +02:00
int32_t h = hash & 7; // Convert low 3 bits of hash code
float u = h < 4 ? x : y; // into 8 simple gradient directions,
float v = h < 4 ? y : x; // and compute the dot product with (x,y).
2017-06-06 23:24:18 +02:00
return ((h & 1) != 0 ? -u : u) + ((h & 2) != 0 ? -2.0f * v : 2.0f * v);
}
2023-01-19 15:13:23 +00:00
static void MapGenSimplex(MapGenSettings* settings)
{
int32_t x, y;
2022-06-04 19:56:31 +02:00
float freq = settings->simplex_base_freq * (1.0f / _heightSize.x);
int32_t octaves = settings->simplex_octaves;
2018-06-22 23:17:03 +02:00
int32_t low = settings->simplex_low;
int32_t high = settings->simplex_high;
2022-10-04 20:24:38 +01:00
NoiseRand();
2022-06-04 19:56:31 +02:00
for (y = 0; y < _heightSize.y; y++)
2017-11-17 10:22:54 +01:00
{
2022-06-04 19:56:31 +02:00
for (x = 0; x < _heightSize.x; x++)
2017-11-17 10:22:54 +01:00
{
2022-10-04 20:24:38 +01:00
float noiseValue = std::clamp(FractalNoise(x, y, freq, octaves, 2.0f, 0.65f), -1.0f, 1.0f);
2017-06-06 23:24:18 +02:00
float normalisedNoiseValue = (noiseValue + 1.0f) / 2.0f;
2022-10-04 20:24:38 +01:00
SetHeight(x, y, low + static_cast<int32_t>(normalisedNoiseValue * high));
2017-06-06 23:24:18 +02:00
}
}
}
2015-08-04 00:57:51 +02:00
#pragma endregion
2017-02-09 23:24:19 +01:00
#pragma region Heightmap
/**
* Return the tile coordinate that matches the given pixel of a heightmap
*/
static TileCoordsXY MapgenHeightmapCoordToTileCoordsXY(uint32_t x, uint32_t y)
{
// The height map does not include the empty tiles around the map, so we add 1.
return TileCoordsXY(static_cast<int32_t>(y + 1), static_cast<int32_t>(x + 1));
}
2024-09-10 11:21:09 +02:00
bool MapGenLoadHeightmapImage(const utf8* path)
2017-02-11 16:37:07 +01:00
{
2018-05-08 21:41:41 +01:00
auto format = Imaging::GetImageFormatFromPath(path);
if (format == IMAGE_FORMAT::PNG)
2017-11-17 10:22:54 +01:00
{
2018-05-08 21:41:41 +01:00
// Promote to 32-bit
format = IMAGE_FORMAT::PNG_32;
}
try
{
auto image = Imaging::ReadFromFile(path, format);
auto width = std::min<uint32_t>(image.Width, kMaximumMapSizePractical);
auto height = std::min<uint32_t>(image.Height, kMaximumMapSizePractical);
if (width != image.Width || height != image.Height)
2017-11-17 10:22:54 +01:00
{
2022-11-06 20:49:07 +00:00
ContextShowError(STR_HEIGHT_MAP_ERROR, STR_ERROR_HEIHGT_MAP_TOO_BIG, {});
2017-06-06 23:24:18 +02:00
}
2017-03-08 16:50:30 +01:00
2018-05-08 21:41:41 +01:00
// Allocate memory for the height map values, one byte pixel
_heightMapData.mono_bitmap.resize(width * height);
_heightMapData.width = width;
_heightMapData.height = height;
2017-03-08 16:50:30 +01:00
2018-05-08 21:41:41 +01:00
// Copy average RGB value to mono bitmap
constexpr auto numChannels = 4;
const auto pitch = image.Stride;
const auto pixels = image.Pixels.data();
for (uint32_t x = 0; x < _heightMapData.width; x++)
2017-06-06 23:24:18 +02:00
{
for (uint32_t y = 0; y < _heightMapData.height; y++)
2018-05-08 21:41:41 +01:00
{
const auto red = pixels[x * numChannels + y * pitch];
const auto green = pixels[x * numChannels + y * pitch + 1];
const auto blue = pixels[x * numChannels + y * pitch + 2];
_heightMapData.mono_bitmap[x + y * _heightMapData.width] = (red + green + blue) / 3;
}
2017-06-06 23:24:18 +02:00
}
2018-05-08 21:41:41 +01:00
return true;
}
catch (const std::exception& e)
{
switch (format)
{
case IMAGE_FORMAT::BITMAP:
2022-11-06 20:49:07 +00:00
ContextShowError(STR_HEIGHT_MAP_ERROR, STR_ERROR_READING_BITMAP, {});
2018-05-08 21:41:41 +01:00
break;
case IMAGE_FORMAT::PNG_32:
2022-11-06 20:49:07 +00:00
ContextShowError(STR_HEIGHT_MAP_ERROR, STR_ERROR_READING_PNG, {});
2018-05-08 21:41:41 +01:00
break;
default:
LOG_ERROR("Unable to load height map image: %s", e.what());
2018-05-08 21:41:41 +01:00
break;
}
return false;
2017-06-06 23:24:18 +02:00
}
2017-03-08 16:50:30 +01:00
}
/**
* Frees the memory used to store the selected height map
*/
2024-09-10 11:21:09 +02:00
void MapGenUnloadHeightmapImage()
2017-03-08 16:50:30 +01:00
{
2021-02-12 20:20:51 +00:00
_heightMapData.mono_bitmap.clear();
2018-06-22 23:17:03 +02:00
_heightMapData.width = 0;
_heightMapData.height = 0;
2017-03-08 16:50:30 +01:00
}
/**
* Applies box blur to the surface N times
*/
2022-10-04 20:24:38 +01:00
static void MapGenSmoothHeightmap(std::vector<uint8_t>& src, int32_t strength)
2017-03-08 16:50:30 +01:00
{
2017-06-06 23:24:18 +02:00
// Create buffer to store one channel
2021-02-12 20:20:51 +00:00
std::vector<uint8_t> dest(src.size());
2017-03-08 16:50:30 +01:00
for (int32_t i = 0; i < strength; i++)
2017-06-06 23:24:18 +02:00
{
// Calculate box blur value to all pixels of the surface
for (uint32_t y = 0; y < _heightMapData.height; y++)
2017-06-06 23:24:18 +02:00
{
for (uint32_t x = 0; x < _heightMapData.width; x++)
2017-06-06 23:24:18 +02:00
{
uint32_t heightSum = 0;
2017-02-12 19:25:10 +01:00
2017-06-06 23:24:18 +02:00
// Loop over neighbour pixels, all of them have the same weight
for (int8_t offsetX = -1; offsetX <= 1; offsetX++)
2017-06-06 23:24:18 +02:00
{
for (int8_t offsetY = -1; offsetY <= 1; offsetY++)
2017-06-06 23:24:18 +02:00
{
// Clamp x and y so they stay within the image
// This assumes the height map is not tiled, and increases the weight of the edges
2018-08-12 12:50:40 +01:00
const int32_t readX = std::clamp<int32_t>(x + offsetX, 0, _heightMapData.width - 1);
const int32_t readY = std::clamp<int32_t>(y + offsetY, 0, _heightMapData.height - 1);
2017-06-06 23:24:18 +02:00
heightSum += src[readX + readY * _heightMapData.width];
}
}
2017-02-12 19:25:10 +01:00
2017-06-06 23:24:18 +02:00
// Take average
dest[x + y * _heightMapData.width] = heightSum / 9;
}
}
2017-02-11 16:37:07 +01:00
2017-06-06 23:24:18 +02:00
// Now apply the blur to the source pixels
for (uint32_t y = 0; y < _heightMapData.height; y++)
2017-06-06 23:24:18 +02:00
{
for (uint32_t x = 0; x < _heightMapData.width; x++)
2017-06-06 23:24:18 +02:00
{
src[x + y * _heightMapData.width] = dest[x + y * _heightMapData.width];
}
}
}
2017-02-11 16:37:07 +01:00
}
2024-09-10 11:21:09 +02:00
void MapGenGenerateFromHeightmapImage(MapGenSettings* settings)
2017-02-09 23:24:19 +01:00
{
Guard::Assert(!_heightMapData.mono_bitmap.empty(), "No height map loaded");
Guard::Assert(settings->simplex_high != settings->simplex_low, "Low and high setting cannot be the same");
2017-02-11 15:35:06 +01:00
2017-06-06 23:24:18 +02:00
// Make a copy of the original height map that we can edit
2021-02-12 20:20:51 +00:00
auto dest = _heightMapData.mono_bitmap;
2017-03-07 23:55:22 +01:00
// Get technical map size, +2 for the black tiles around the map
auto maxWidth = static_cast<int32_t>(_heightMapData.width + 2);
auto maxHeight = static_cast<int32_t>(_heightMapData.height + 2);
MapInit({ maxHeight, maxWidth });
2017-02-11 15:35:06 +01:00
2017-06-06 23:24:18 +02:00
if (settings->smooth_height_map)
{
2022-10-04 20:24:38 +01:00
MapGenSmoothHeightmap(dest, settings->smooth_strength);
2017-06-06 23:24:18 +02:00
}
2017-02-11 16:37:07 +01:00
uint8_t maxValue = 255;
uint8_t minValue = 0;
2017-03-08 16:50:30 +01:00
2017-06-06 23:24:18 +02:00
if (settings->normalize_height)
{
// Get highest and lowest pixel value
maxValue = 0;
minValue = 0xff;
for (uint32_t y = 0; y < _heightMapData.height; y++)
2017-06-06 23:24:18 +02:00
{
for (uint32_t x = 0; x < _heightMapData.width; x++)
2017-06-06 23:24:18 +02:00
{
uint8_t value = dest[x + y * _heightMapData.width];
2018-06-22 23:17:03 +02:00
maxValue = std::max(maxValue, value);
minValue = std::min(minValue, value);
2017-06-06 23:24:18 +02:00
}
}
2017-02-11 15:35:06 +01:00
2017-06-06 23:24:18 +02:00
if (minValue == maxValue)
{
2022-11-06 20:49:07 +00:00
ContextShowError(STR_HEIGHT_MAP_ERROR, STR_ERROR_CANNOT_NORMALIZE, {});
2017-06-06 23:24:18 +02:00
return;
}
}
2017-02-11 15:35:06 +01:00
Guard::Assert(maxValue > minValue, "Input range is invalid");
Guard::Assert(settings->simplex_high > settings->simplex_low, "Output range is invalid");
2017-02-11 15:35:06 +01:00
2018-06-22 23:17:03 +02:00
const uint8_t rangeIn = maxValue - minValue;
const uint8_t rangeOut = settings->simplex_high - settings->simplex_low;
2017-02-11 15:35:06 +01:00
for (uint32_t y = 0; y < _heightMapData.height; y++)
2017-06-06 23:24:18 +02:00
{
for (uint32_t x = 0; x < _heightMapData.width; x++)
2017-06-06 23:24:18 +02:00
{
// The x and y axis are flipped in the world, so this uses y for x and x for y.
auto tileCoords = MapgenHeightmapCoordToTileCoordsXY(x, y);
auto* const surfaceElement = MapGetSurfaceElementAt(tileCoords);
if (surfaceElement == nullptr)
continue;
2017-02-11 15:35:06 +01:00
2017-06-06 23:24:18 +02:00
// Read value from bitmap, and convert its range
uint8_t value = dest[x + y * _heightMapData.width];
2020-04-17 16:08:22 -03:00
value = static_cast<uint8_t>(static_cast<float>(value - minValue) / rangeIn * rangeOut) + settings->simplex_low;
surfaceElement->BaseHeight = value;
2017-02-11 15:35:06 +01:00
2017-06-06 23:24:18 +02:00
// Floor to even number
surfaceElement->BaseHeight /= 2;
surfaceElement->BaseHeight *= 2;
surfaceElement->ClearanceHeight = surfaceElement->BaseHeight;
2017-02-09 23:24:19 +01:00
2017-06-06 23:24:18 +02:00
// Set water level
if (surfaceElement->BaseHeight < settings->water_level)
2017-06-06 23:24:18 +02:00
{
2024-07-26 18:23:25 +10:00
surfaceElement->SetWaterHeight(settings->water_level * kCoordsZStep);
2017-06-06 23:24:18 +02:00
}
}
}
2017-02-09 23:24:19 +01:00
2017-06-06 23:24:18 +02:00
// Smooth map
if (settings->smooth)
{
// Keep smoothing the entire map until no tiles are changed anymore
while (true)
{
uint32_t numTilesChanged = 0;
for (uint32_t y = 0; y < _heightMapData.height; y++)
2017-06-06 23:24:18 +02:00
{
for (uint32_t x = 0; x < _heightMapData.width; x++)
2017-06-06 23:24:18 +02:00
{
auto tileCoords = MapgenHeightmapCoordToTileCoordsXY(x, y);
numTilesChanged += TileSmooth(tileCoords);
2017-06-06 23:24:18 +02:00
}
}
2017-02-11 16:37:07 +01:00
2017-06-06 23:24:18 +02:00
if (numTilesChanged == 0)
break;
}
}
2017-02-09 23:24:19 +01:00
}
#pragma endregion