|
OpenTTD Source 20260206-master-g4d4e37dbf1
|
OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin. More...
#include "stdafx.h"#include "clear_map.h"#include "void_map.h"#include "genworld.h"#include "core/random_func.hpp"#include "landscape_type.h"#include "safeguards.h"Go to the source code of this file.
Data Structures | |
| struct | HeightMap |
| Height map - allocated array of heights (Map::SizeX() + 1) * (Map::SizeY() + 1). More... | |
Macros | |
| #define | F(fraction) |
Typedefs | |
| using | Height = int16_t |
| Fixed point type for heights. | |
| using | Amplitude = int |
| Fixed point array for amplitudes. | |
Functions | |
| static Height | I2H (int i) |
| Conversion: int to Height. | |
| static int | H2I (Height i) |
| Conversion: Height to int. | |
| static Height | A2H (Amplitude i) |
| Conversion: Amplitude to Height. | |
| static Height | TGPGetMaxHeight () |
| Gets the maximum allowed height while generating a map based on mapsize, terraintype, and the maximum height level. | |
| uint | GetEstimationTGPMapHeight () |
| Get an overestimation of the highest peak TGP wants to generate. | |
| static Amplitude | GetAmplitude (int frequency) |
| Get the amplitude associated with the currently selected smoothness and maximum height level. | |
| static bool | IsValidXY (int x, int y) |
| Check if a X/Y set are within the map. | |
| static void | AllocHeightMap () |
| Allocate array of (Map::SizeX() + 1) * (Map::SizeY() + 1) heights and init the _height_map structure members. | |
| static void | FreeHeightMap () |
| Free height map. | |
| static Height | RandomHeight (Amplitude r_max) |
| Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude). | |
| static void | HeightMapGenerate () |
| Base Perlin noise generator - fills height map with raw Perlin noise. | |
| static void | HeightMapGetMinMaxAvg (Height *min_ptr, Height *max_ptr, Height *avg_ptr) |
| Returns min, max and average height from height map. | |
| static int * | HeightMapMakeHistogram (Height h_min, Height h_max, int *hist_buf) |
| Dill histogram and return pointer to its base point - to the count of zero heights. | |
| static double | SineTransformLowlands (double fheight) |
| Adjust the landscape to create lowlands on average (tropic landscape). | |
| static double | SineTransformNormal (double &fheight) |
| Adjust the landscape to create normal average height (temperate and toyland landscapes). | |
| static double | SineTransformPlateaus (double &fheight) |
| Adjust the landscape to create plateaus on average (arctic landscape). | |
| static void | HeightMapSineTransform (Height h_min, Height h_max) |
| Applies sine wave redistribution onto height map. | |
| static void | HeightMapCurves (uint level) |
| Additional map variety is provided by applying different curve maps to different parts of the map. | |
| static void | HeightMapAdjustWaterLevel (int64_t water_percent, Height h_max_new) |
| Adjusts heights in height map to contain required amount of water tiles. | |
| static double | perlin_coast_noise_2D (const double x, const double y, const double p, const int prime) |
| This is a similar function to the main perlin noise calculation, but uses the value p passed as a parameter rather than selected from the predefined sequences. | |
| static void | HeightMapCoastLines (BorderFlags water_borders) |
| This routine sculpts in from the edge a random amount, again from Perlin sequences, to avoid rigid flat-edge slopes and add an irregular edge to the land. | |
| static void | HeightMapSmoothCoastInDirection (int org_x, int org_y, int dir_x, int dir_y) |
| Start at given point, move in given direction, find and Smooth coast in that direction. | |
| static void | HeightMapSmoothCoasts (BorderFlags water_borders) |
| Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge. | |
| static void | HeightMapSmoothSlopes (Height dh_max) |
| This routine provides the essential cleanup necessary before OTTD can display the terrain. | |
| static void | HeightMapNormalize () |
| Height map terraform post processing: | |
| static double | int_noise (const long x, const long y, const int prime) |
| The Perlin Noise calculation using large primes The initial number is adjusted by two values; the generation_seed, and the passed parameter; prime. | |
| static double | linear_interpolate (const double a, const double b, const double x) |
| This routine determines the interpolated value between a and b. | |
| static double | interpolated_noise (const double x, const double y, const int prime) |
| This routine returns the smoothed interpolated noise for an x and y, using the values from the surrounding positions. | |
| static void | TgenSetTileHeight (TileIndex tile, int height) |
| A small helper function to initialize the terrain. | |
| void | GenerateTerrainPerlin () |
| The main new land generator using Perlin noise. | |
Variables | |
| static const int | HEIGHT_DECIMAL_BITS = 4 |
| static const int | AMPLITUDE_DECIMAL_BITS = 10 |
| static HeightMap | _height_map = { {}, 0, 0, 0 } |
| Global height map instance. | |
| static const int | MAX_TGP_FREQUENCIES = 10 |
| Maximum number of TGP noise frequencies. | |
| static constexpr int | WATER_PERCENT_FACTOR = 1024 |
| static const int64_t | _water_percent [4] = {70, 170, 270, 420} |
| Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes. | |
OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin.
Quickie guide to Perlin Noise Perlin noise is a predictable pseudo random number sequence. By generating it in 2 dimensions, it becomes a useful random map that, for a given seed and starting X & Y, is entirely predictable. On the face of it, that may not be useful. However, it means that if you want to replay a map in a different terrain, or just vary the sea level, you just re-run the generator with the same seed. The seed is an int32_t, and is randomised on each run of New Game. The Scenario Generator does not randomise the value, so that you can experiment with one terrain until you are happy, or click "Random" for a new random seed.
Perlin Noise is a series of "octaves" of random noise added together. By reducing the amplitude of the noise with each octave, the first octave of noise defines the main terrain sweep, the next the ripples on that, and the next the ripples on that. I use 6 octaves, with the amplitude controlled by a power ratio, usually known as a persistence or p value. This I vary by the smoothness selection, as can be seen in the table below. The closer to 1, the more of that octave is added. Each octave is however raised to the power of its position in the list, so the last entry in the "smooth" row, 0.35, is raised to the power of 6, so can only add 0.001838... of the amplitude to the running total.
In other words; the first p value sets the general shape of the terrain, the second sets the major variations to that, ... until finally the smallest bumps are added.
Usefully, this routine is totally scalable; so when 32bpp comes along, the terrain can be as bumpy as you like! It is also infinitely expandable; a single random seed terrain continues in X & Y as far as you care to calculate. In theory, we could use just one seed value, but randomly select where in the Perlin XY space we use for the terrain. Personally I prefer using a simple (0, 0) to (X, Y), with a varying seed.
Other things i have had to do: mountainous wasn't mountainous enough, and since we only have 0..15 heights available, I add a second generated map (with a modified seed), onto the original. This generally raises the terrain, which then needs scaling back down. Overall effect is a general uplift.
However, the values on the top of mountains are then almost guaranteed to go too high, so large flat plateaus appeared at height 15. To counter this, I scale all heights above 12 to proportion up to 15. It still makes the mountains have flattish tops, rather than craggy peaks, but at least they aren't smooth as glass.
For a full discussion of Perlin Noise, please visit: http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
Evolution II
The algorithm as described in the above link suggests to compute each tile height as composition of several noise waves. Some of them are computed directly by noise(x, y) function, some are calculated using linear approximation. Our first implementation of perlin_noise_2D() used 4 noise(x, y) calls plus 3 linear interpolations. It was called 6 times for each tile. This was a bit CPU expensive.
The following implementation uses optimized algorithm that should produce the same quality result with much less computations, but more memory accesses. The overall speedup should be 300% to 800% depending on CPU and memory speed.
I will try to explain it on the example below:
Have a map of 4x4 tiles, our simplified noise generator produces only two values -1 and +1, use 3 octaves with wave length 1, 2 and 4, with amplitudes 3, 2, 1. Original algorithm produces:
h00 = lerp(lerp(-3, 3, 0/4), lerp(3, -3, 0/4), 0/4) + lerp(lerp(-2, 2, 0/2), lerp( 2, -2, 0/2), 0/2) + -1 = lerp(-3.0, 3.0, 0/4) + lerp(-2, 2, 0/2) + -1 = -3.0 + -2 + -1 = -6.0 h01 = lerp(lerp(-3, 3, 1/4), lerp(3, -3, 1/4), 0/4) + lerp(lerp(-2, 2, 1/2), lerp( 2, -2, 1/2), 0/2) + 1 = lerp(-1.5, 1.5, 0/4) + lerp( 0, 0, 0/2) + 1 = -1.5 + 0 + 1 = -0.5 h02 = lerp(lerp(-3, 3, 2/4), lerp(3, -3, 2/4), 0/4) + lerp(lerp( 2, -2, 0/2), lerp(-2, 2, 0/2), 0/2) + -1 = lerp( 0, 0, 0/4) + lerp( 2, -2, 0/2) + -1 = 0 + 2 + -1 = 1.0 h03 = lerp(lerp(-3, 3, 3/4), lerp(3, -3, 3/4), 0/4) + lerp(lerp( 2, -2, 1/2), lerp(-2, 2, 1/2), 0/2) + 1 = lerp( 1.5, -1.5, 0/4) + lerp( 0, 0, 0/2) + 1 = 1.5 + 0 + 1 = 2.5
h10 = lerp(lerp(-3, 3, 0/4), lerp(3, -3, 0/4), 1/4) + lerp(lerp(-2, 2, 0/2), lerp( 2, -2, 0/2), 1/2) + 1 = lerp(-3.0, 3.0, 1/4) + lerp(-2, 2, 1/2) + 1 = -1.5 + 0 + 1 = -0.5 h11 = lerp(lerp(-3, 3, 1/4), lerp(3, -3, 1/4), 1/4) + lerp(lerp(-2, 2, 1/2), lerp( 2, -2, 1/2), 1/2) + -1 = lerp(-1.5, 1.5, 1/4) + lerp( 0, 0, 1/2) + -1 = -0.75 + 0 + -1 = -1.75 h12 = lerp(lerp(-3, 3, 2/4), lerp(3, -3, 2/4), 1/4) + lerp(lerp( 2, -2, 0/2), lerp(-2, 2, 0/2), 1/2) + 1 = lerp( 0, 0, 1/4) + lerp( 2, -2, 1/2) + 1 = 0 + 0 + 1 = 1.0 h13 = lerp(lerp(-3, 3, 3/4), lerp(3, -3, 3/4), 1/4) + lerp(lerp( 2, -2, 1/2), lerp(-2, 2, 1/2), 1/2) + -1 = lerp( 1.5, -1.5, 1/4) + lerp( 0, 0, 1/2) + -1 = 0.75 + 0 + -1 = -0.25
Optimization 1:
1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
2) setup corner values using amplitude 3 { -3.0 X X X 3.0 } { X X X X X } { X X X X X } { X X X X X } { 3.0 X X X -3.0 }
3a) interpolate values in the middle { -3.0 X 0.0 X 3.0 } { X X X X X } { 0.0 X 0.0 X 0.0 } { X X X X X } { 3.0 X 0.0 X -3.0 }
3b) add patches with amplitude 2 to them { -5.0 X 2.0 X 1.0 } { X X X X X } { 2.0 X -2.0 X 2.0 } { X X X X X } { 1.0 X 2.0 X -5.0 }
4a) interpolate values in the middle { -5.0 -1.5 2.0 1.5 1.0 } { -1.5 -0.75 0.0 0.75 1.5 } { 2.0 0.0 -2.0 0.0 2.0 } { 1.5 0.75 0.0 -0.75 -1.5 } { 1.0 1.5 2.0 -1.5 -5.0 }
4b) add patches with amplitude 1 to them { -6.0 -0.5 1.0 2.5 0.0 } { -0.5 -1.75 1.0 -0.25 2.5 } { 1.0 1.0 -3.0 1.0 1.0 } { 2.5 -0.25 1.0 -1.75 -0.5 } { 0.0 2.5 1.0 -0.5 -6.0 }
Optimization 2:
As you can see above, each noise function was called just once. Therefore we don't need to use noise function that calculates the noise from x, y and some prime. The same quality result we can obtain using standard Random() function instead.
Definition in file tgp.cpp.
| #define F | ( | fraction | ) |
Conversion: Amplitude to Height.
Definition at line 197 of file tgp.cpp.
Referenced by RandomHeight().
|
inlinestatic |
Allocate array of (Map::SizeX() + 1) * (Map::SizeY() + 1) heights and init the _height_map structure members.
Definition at line 325 of file tgp.cpp.
References _height_map, Map::SizeX(), and Map::SizeY().
Referenced by GenerateTerrainPerlin().
|
inlinestatic |
Free height map.
Definition at line 339 of file tgp.cpp.
References _height_map.
Referenced by GenerateTerrainPerlin().
| void GenerateTerrainPerlin | ( | ) |
The main new land generator using Perlin noise.
Desert landscape is handled different to all others to give a desert valley between two high mountains. Clearly if a low height terrain (flat/very flat) is chosen, then the tropic areas won't be high enough, and there will be very little tropic on the map. Thus Tropic works best on Hilly or Mountainous.
Definition at line 1021 of file tgp.cpp.
References _height_map, _settings_game, AllocHeightMap(), Clamp(), FreeHeightMap(), GenerateWorldSetAbortCallback(), GWP_LANDSCAPE, H2I(), HeightMapGenerate(), HeightMapNormalize(), IncreaseGeneratingWorldProgress(), MakeVoid(), Map::SizeX(), Map::SizeY(), TgenSetTileHeight(), TGPGetMaxHeight(), and TileXY().
Referenced by GenerateLandscape().
|
static |
Get the amplitude associated with the currently selected smoothness and maximum height level.
| frequency | The frequency to get the amplitudes for |
< Very smooth
< Smooth
< Rough
< Very rough
Definition at line 269 of file tgp.cpp.
References _settings_game, Clamp(), I2H(), MAX_TGP_FREQUENCIES, and TGPGetMaxHeight().
Referenced by HeightMapGenerate().
| uint GetEstimationTGPMapHeight | ( | ) |
Get an overestimation of the highest peak TGP wants to generate.
Definition at line 258 of file tgp.cpp.
References H2I(), and TGPGetMaxHeight().
Referenced by GenerateWorld().
|
static |
Conversion: Height to int.
Definition at line 191 of file tgp.cpp.
Referenced by GenerateTerrainPerlin(), and GetEstimationTGPMapHeight().
|
static |
Adjusts heights in height map to contain required amount of water tiles.
Definition at line 703 of file tgp.cpp.
References _height_map, HeightMapGetMinMaxAvg(), HeightMapMakeHistogram(), and I2H().
Referenced by HeightMapNormalize().
|
static |
This routine sculpts in from the edge a random amount, again from Perlin sequences, to avoid rigid flat-edge slopes and add an irregular edge to the land.
The smoothing routines makes it legal, gradually increasing up from the edge to the original terrain.
More varied coastlines on large maps require coastal features that would turn small maps into tiny islands. To avoid this, multiple perlin sequences with different persistence values are scaled based on the map dimensions.
The constants used are based on what looks right. If you're changing the limits or the persistence values you'll want to experiment with various map sizes.
Definition at line 756 of file tgp.cpp.
References _height_map, abs(), NorthEast, NorthWest, perlin_coast_noise_2D(), SouthEast, SouthWest, and BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test().
Referenced by HeightMapNormalize().
|
static |
Additional map variety is provided by applying different curve maps to different parts of the map.
A randomized low resolution grid contains which curve map to use on each part of the make. This filtered non-linearly to smooth out transitions between curves, so each tile could have between 100% of one map applied or 25% of four maps.
The curve maps define different land styles, i.e. lakes, low-lands, hills and mountain ranges, although these are dependent on the landscape style chosen as well.
The level parameter dictates the resolution of the grid. A low resolution grid will result in larger continuous areas of a land style, a higher resolution grid splits the style into smaller areas.
| level | Rough indication of the size of the grid sections to style. Small level means large grid sections. |
Basically scale height X to height Y. Everything in between is interpolated.
< The height to scale from.
< The height to scale to.
Definition at line 585 of file tgp.cpp.
References _height_map, Clamp(), HasBit(), I2H(), RandomRange(), and TGPGetMaxHeight().
Referenced by HeightMapNormalize().
|
static |
Base Perlin noise generator - fills height map with raw Perlin noise.
This runs several iterations with increasing precision; the last iteration looks at areas of 1 by 1 tiles, the second to last at 2 by 2 tiles and the initial 2**MAX_TGP_FREQUENCIES by 2**MAX_TGP_FREQUENCIES tiles.
Definition at line 362 of file tgp.cpp.
References _height_map, GetAmplitude(), Map::LogX(), Map::LogY(), MAX_TGP_FREQUENCIES, and RandomHeight().
Referenced by GenerateTerrainPerlin().
Returns min, max and average height from height map.
Definition at line 422 of file tgp.cpp.
References _height_map.
Referenced by HeightMapAdjustWaterLevel().
Dill histogram and return pointer to its base point - to the count of zero heights.
Definition at line 445 of file tgp.cpp.
References _height_map.
Referenced by HeightMapAdjustWaterLevel().
|
static |
Height map terraform post processing:
Definition at line 901 of file tgp.cpp.
References _settings_game, _water_percent, BORDERFLAGS_ALL, CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY, GB(), HeightMapAdjustWaterLevel(), HeightMapCoastLines(), HeightMapCurves(), HeightMapSineTransform(), HeightMapSmoothCoasts(), HeightMapSmoothSlopes(), I2H(), Random, and TGPGetMaxHeight().
Referenced by GenerateTerrainPerlin().
Applies sine wave redistribution onto height map.
Definition at line 534 of file tgp.cpp.
References _height_map, _settings_game, Arctic, I2H(), SineTransformLowlands(), SineTransformNormal(), SineTransformPlateaus(), Temperate, Toyland, and Tropic.
Referenced by HeightMapNormalize().
|
static |
Start at given point, move in given direction, find and Smooth coast in that direction.
Definition at line 819 of file tgp.cpp.
References _height_map, I2H(), and IsValidXY().
Referenced by HeightMapSmoothCoasts().
|
static |
Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge.
Definition at line 856 of file tgp.cpp.
References _height_map, HeightMapSmoothCoastInDirection(), NorthEast, NorthWest, SouthEast, SouthWest, and BaseBitSet< Timpl, Tvalue_type, Tstorage, Tmask >::Test().
Referenced by HeightMapNormalize().
|
static |
This routine provides the essential cleanup necessary before OTTD can display the terrain.
When generated, the terrain heights can jump more than one level between tiles. This routine smooths out those differences so that the most it can change is one level. When OTTD can support cliffs, this routine may not be necessary.
Definition at line 878 of file tgp.cpp.
References _height_map.
Referenced by HeightMapNormalize().
|
static |
Conversion: int to Height.
Definition at line 185 of file tgp.cpp.
Referenced by GetAmplitude(), HeightMapAdjustWaterLevel(), HeightMapCurves(), HeightMapNormalize(), HeightMapSineTransform(), HeightMapSmoothCoastInDirection(), and TGPGetMaxHeight().
|
static |
The Perlin Noise calculation using large primes The initial number is adjusted by two values; the generation_seed, and the passed parameter; prime.
prime is used to allow the perlin noise generator to create useful random numbers from slightly different series.
Definition at line 932 of file tgp.cpp.
References _settings_game.
Referenced by interpolated_noise().
|
static |
This routine returns the smoothed interpolated noise for an x and y, using the values from the surrounding positions.
Definition at line 956 of file tgp.cpp.
References int_noise(), and linear_interpolate().
Referenced by perlin_coast_noise_2D().
|
inlinestatic |
Check if a X/Y set are within the map.
| x | coordinate x |
| y | coordinate y |
Definition at line 316 of file tgp.cpp.
References _height_map.
Referenced by HeightMapSmoothCoastInDirection().
|
inlinestatic |
This routine determines the interpolated value between a and b.
Definition at line 946 of file tgp.cpp.
Referenced by interpolated_noise().
|
static |
This is a similar function to the main perlin noise calculation, but uses the value p passed as a parameter rather than selected from the predefined sequences.
as you can guess by its title, i use this to create the indented coastline, which is just another perlin sequence.
Definition at line 981 of file tgp.cpp.
References interpolated_noise().
Referenced by HeightMapCoastLines().
Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude).
| r_max | Limit of result |
Definition at line 349 of file tgp.cpp.
References A2H(), and RandomRange().
Referenced by HeightMapGenerate().
|
static |
Adjust the landscape to create lowlands on average (tropic landscape).
| fheight | The height to adjust. |
Definition at line 463 of file tgp.cpp.
Referenced by HeightMapSineTransform().
|
static |
Adjust the landscape to create normal average height (temperate and toyland landscapes).
| fheight | The height to adjust. |
Definition at line 491 of file tgp.cpp.
Referenced by HeightMapSineTransform().
|
static |
Adjust the landscape to create plateaus on average (arctic landscape).
| fheight | The height to adjust. |
Definition at line 510 of file tgp.cpp.
Referenced by HeightMapSineTransform().
|
static |
A small helper function to initialize the terrain.
Definition at line 1004 of file tgp.cpp.
References Grass, IsInnerTile(), MakeClear(), and SetTileHeight().
Referenced by GenerateTerrainPerlin().
|
static |
Gets the maximum allowed height while generating a map based on mapsize, terraintype, and the maximum height level.
Desired maximum height - indexed by:
It is indexed by map size as well as terrain type since the map size limits the height of a usable mountain. For example, on a 64x64 map a 24 high single peak mountain (as if you raised land 24 times in the center of the map) will leave only a ring of about 10 tiles around the mountain to build on. On a 4096x4096 map, it won't cover any major part of the map.
< Very flat
< Flat
< Hilly
< Mountainous
< Alpinist
Definition at line 216 of file tgp.cpp.
References _settings_game, I2H(), Map::LogX(), Map::LogY(), MAX_MAP_SIZE_BITS, MIN_MAP_SIZE_BITS, and to_underlying().
Referenced by GenerateTerrainPerlin(), GetAmplitude(), GetEstimationTGPMapHeight(), HeightMapCurves(), and HeightMapNormalize().
|
static |
Global height map instance.
Definition at line 182 of file tgp.cpp.
Referenced by AllocHeightMap(), FreeHeightMap(), GenerateTerrainPerlin(), HeightMapAdjustWaterLevel(), HeightMapCoastLines(), HeightMapCurves(), HeightMapGenerate(), HeightMapGetMinMaxAvg(), HeightMapMakeHistogram(), HeightMapSineTransform(), HeightMapSmoothCoastInDirection(), HeightMapSmoothCoasts(), HeightMapSmoothSlopes(), and IsValidXY().
|
static |
Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes.
Definition at line 208 of file tgp.cpp.
Referenced by HeightMapNormalize().
|
static |
Maximum number of TGP noise frequencies.
Definition at line 203 of file tgp.cpp.
Referenced by GetAmplitude(), and HeightMapGenerate().