# tgp.cpp File Reference

OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin. More...

`#include "stdafx.h"`
`#include <math.h>`
`#include "clear_map.h"`
`#include "void_map.h"`
`#include "genworld.h"`
`#include "core/alloc_func.hpp"`
`#include "core/random_func.hpp"`
`#include "landscape_type.h"`

Go to the source code of this file.

## Data Structures

struct | HeightMap
| Height map - allocated array of heights (MapSizeX() + 1) x (MapSizeY() + 1). More...
struct | control_point_t
struct | control_point_list_t

## Defines

#define | M_PI_2 1.57079632679489661923
#define | M_PI 3.14159265358979323846
#define | I2H(i) ((i) << height_decimal_bits)
| Conversion: int to height_t.
#define | H2I(i) ((i) >> height_decimal_bits)
| Conversion: height_t to int.
#define | I2A(i) ((i) << amplitude_decimal_bits)
| Conversion: int to amplitude_t.
#define | A2I(i) ((i) >> amplitude_decimal_bits)
| Conversion: amplitude_t to int.
#define | A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
| Conversion: amplitude_t to height_t.
#define | FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++)
| Walk through all items of _height_map.h.

## Typedefs

typedef int16 | height_t
| Fixed point type for heights.
typedef int | amplitude_t
| Fixed point array for amplitudes (and percent values).

## Functions

static bool | IsValidXY (uint x, uint y)
| Check if a X/Y set are within the map.
static bool | AllocHeightMap ()
| Allocate array of (MapSizeX()+1)*(MapSizeY()+1) heights and init the _height_map structure members.
static void | FreeHeightMap ()
| Free height map.
static height_t | RandomHeight (amplitude_t rMax)
| Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude).
static bool | ApplyNoise (uint log_frequency, amplitude_t amplitude)
| One interpolation and noise round.
static void | HeightMapGenerate ()
| Base Perlin noise generator - fills height map with raw Perlin noise.
static void | HeightMapGetMinMaxAvg (height_t *min_ptr, height_t *max_ptr, height_t *avg_ptr)
| Returns min, max and average height from height map.
static int * | HeightMapMakeHistogram (height_t h_min, height_t h_max, int *hist_buf)
| Dill histogram and return pointer to its base point - to the count of zero heights.
static void | HeightMapSineTransform (height_t h_min, height_t h_max)
| Applies sine wave redistribution onto height map.
static void | HeightMapCurves (uint level)
static void | HeightMapAdjustWaterLevel (amplitude_t water_percent, height_t 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 (uint8 water_borders)
| This routine sculpts in from the edge a random amount, again a Perlin sequence, to avoid the rigid flat-edge slopes that were present before.
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 (uint8 water_borders)
| Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge.
static void | HeightMapSmoothSlopes (height_t dh_max)
| This routine provides the essential cleanup necessary before OTTD can display the terrain.
static void | HeightMapNormalize ()

Height map terraform post processing:

- water level adjusting
- coast Smoothing
- slope Smoothing
- height histogram redistribution by sine wave transform.

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 | smoothed_noise (const int x, const int y, const int prime)
| Hj.
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 height_t | _invalid_height = -32768
static const int | amplitude_decimal_bits = 10
static HeightMap | _height_map = {NULL, 0, 0, 0, 0}
| Global height map instance.
static const int | TGP_FREQUENCY_MAX = 6
| Maximum index into array of noise amplitudes.
static const amplitude_t | _amplitudes_by_smoothness_and_frequency [4][TGP_FREQUENCY_MAX+1]

Noise amplitudes (multiplied by 1024)

- indexed by "smoothness setting" and log2(frequency).

static const amplitude_t | _water_percent [4] = {20, 80, 250, 400}
| Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes.
static const int8 | _max_height [4]
| Desired maximum height - indexed by _settings_game.difficulty.terrain_type.
static const control_point_t | _curve_map_1 []
static const control_point_t | _curve_map_2 []
static const control_point_t | _curve_map_3 []
static const control_point_t | _curve_map_4 []
static const control_point_list_t | _curve_maps []

## Detailed Description

OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin.

Definition in file tgp.cpp.

## Function Documentation

static bool AllocHeightMap | ( |  | ) | `[inline, static]`

Allocate array of (MapSizeX()+1)*(MapSizeY()+1) heights and init the _height_map structure members.

Returns:
  true on success

Definition at line 252 of file tgp.cpp.

References HeightMap::dim_x, FOR_ALL_TILES_IN_HEIGHT, HeightMap::h, MapSizeX(), MapSizeY(), HeightMap::size_x, HeightMap::size_y, and HeightMap::total_size.

Referenced by GenerateTerrainPerlin().

static bool ApplyNoise | ( | uint | log_frequency,
|  | amplitude_t | amplitude |
| ) |  |  | `[static]`

One interpolation and noise round.

The heights on the map are generated in an iterative process. We start off with a frequency of 1 (log_frequency == 0), and generate heights only for corners on the most coarsly mesh (i.e. only for x/y coordinates which are multiples of the minimum edge length).

After this initial step the frequency is doubled (log_frequency incremented) each iteration to generate corners on the next finer mesh. The heights of the newly added corners are first set by interpolating the heights from the previous iteration. Finally noise with the given amplitude is applied to all corners of the new mesh.

Generation terminates, when the frequency has reached the map size. I.e. the mesh is as fine as the map, and every corner height has been set.

Parameters:

  | log_frequency | frequency (logarithmic) to apply noise for
  | amplitude | Amplitude for the noise

Returns:
  false if we are finished (reached the minimal step size / highest frequency)

Definition at line 310 of file tgp.cpp.

References HeightMap::h, HeightMap::height(), min(), RandomHeight(), HeightMap::size_x, and HeightMap::size_y.

Referenced by HeightMapGenerate().

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 wont be high enough, and there will be very little tropic on the map. Thus Tropic works best on Hilly or Mountainous.

Definition at line 986 of file tgp.cpp.

References _settings_game, AllocHeightMap(), GameSettings::construction, ConstructionSettings::freeform_edges, FreeHeightMap(), GenerateWorldSetAbortCallback(), GWP_LANDSCAPE, H2I, HeightMap::height(), HeightMapGenerate(), HeightMapNormalize(), IncreaseGeneratingWorldProgress(), MakeVoid(), HeightMap::size_x, HeightMap::size_y, TgenSetTileHeight(), and TileXY().

static void HeightMapCoastLines | ( | uint8 | water_borders | ) | `[static]`

This routine sculpts in from the edge a random amount, again a Perlin sequence, to avoid the rigid flat-edge slopes that were present before.

The Perlin noise map doesnt know where we are going to slice across, and so we often cut straight through high terrain. the smoothing routine makes it legal, gradually increasing up from the edge to the original terrain height. By cutting parts of this away, it gives a far more irregular edge to the map-edge. Sometimes it works beautifully with the existing sea & lakes, and creates a very realistic coastline. Other times the variation is less, and the map-edge shows its cliff-like roots.

This routine may be extended to randomly sculpt the height of the terrain near the edge. This will have the coast edge at low level (1-3), rising in smoothed steps inland to about 15 tiles in. This should make it look as though the map has been built for the map size, rather than a slice through a larger map.

Please note that all the small numbers; 53, 101, 167, etc. are small primes to help give the perlin noise a bit more of a random feel.

Definition at line 711 of file tgp.cpp.

References _settings_game, abs(), GameSettings::game_creation, HasBit(), HeightMap::height(), GameCreationSettings::map_x, GameCreationSettings::map_y, max(), min(), perlin_coast_noise_2D(), HeightMap::size_x, and HeightMap::size_y.

Referenced by HeightMapNormalize().

static void HeightMapSmoothSlopes | ( | height_t | dh_max | ) | `[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 826 of file tgp.cpp.

References HeightMap::height(), min(), HeightMap::size_x, and HeightMap::size_y.

Referenced by HeightMapNormalize().

static double int_noise | ( | const long | x,
|  | const long | y,
|  | const int | prime |
| ) |  |  | `[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 881 of file tgp.cpp.

References _settings_game, GameSettings::game_creation, and GameCreationSettings::generation_seed.

Referenced by smoothed_noise().

static bool IsValidXY | ( | uint | x,
|  | uint | y |
| ) |  |  | `[inline, static]`

Check if a X/Y set are within the map.

Parameters:

  | x | coordinate x
  | y | coordinate y

Returns:
  true if within the map

Definition at line 242 of file tgp.cpp.

References HeightMap::size_x, and HeightMap::size_y.

Referenced by HeightMapSmoothCoastInDirection().

static double perlin_coast_noise_2D | ( | const double | x,
|  | const double | y,
|  | const double | p,
|  | const int | prime |
| ) |  |  | `[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 951 of file tgp.cpp.

References interpolated_noise().

Referenced by HeightMapCoastLines().

static height_t RandomHeight | ( | amplitude_t | rMax | ) | `[inline, static]`

Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude).

Parameters:

  | rMax | Limit of result

Returns:
  generated height

Definition at line 283 of file tgp.cpp.

References A2H.

Referenced by ApplyNoise().

static double smoothed_noise | ( | const int | x,
|  | const int | y,
|  | const int | prime |
| ) |  |  | `[static]`

Hj.

Malthaner's routine included 2 different noise smoothing methods. We now use the "raw" int_noise one. However, it may be useful to move to the other routine in future. So it is included too.

Definition at line 898 of file tgp.cpp.

References int_noise().

Referenced by interpolated_noise().

## Variable Documentation

const amplitude_t _amplitudes_by_smoothness_and_frequency[4][TGP_FREQUENCY_MAX+1]`[static]`

Initial value:

     {

      {16000,  5600,  1968,   688,   240,    16,    16},

      {16000, 16000,  6448,  3200,  1024,   128,    16},

      {16000, 19200, 12800,  8000,  3200,   256,    64},

      {24000, 16000, 19200, 16000,  8000,   512,   320},
    }

Noise amplitudes (multiplied by 1024)

- indexed by "smoothness setting" and log2(frequency).

Definition at line 214 of file tgp.cpp.

Referenced by HeightMapGenerate().

const control_point_t _curve_map_1[]`[static]`

Initial value:

     {
      { 0, 0 }, { 48, 24 }, { 192, 32 }, { 240, 96 }
    }

Definition at line 540 of file tgp.cpp.

const control_point_t _curve_map_2[]`[static]`

Initial value:

     {
      { 0, 0 }, { 16, 24 }, { 128, 32 }, { 192, 64 }, { 240, 144 }
    }

Definition at line 544 of file tgp.cpp.

const control_point_t _curve_map_3[]`[static]`

Initial value:

     {
      { 0, 0 }, { 16, 24 }, { 128, 64 }, { 192, 144 }, { 240, 192 }
    }

Definition at line 548 of file tgp.cpp.

const control_point_t _curve_map_4[]`[static]`

Initial value:

     {
      { 0, 0 }, { 16, 24 }, { 96, 72 }, { 160, 192 }, { 220, 239 }, { 240, 239 }
    }

Definition at line 552 of file tgp.cpp.

const control_point_list_t _curve_maps[]`[static]`

Initial value:

     {
      { lengthof(_curve_map_1), _curve_map_1 },
      { lengthof(_curve_map_2), _curve_map_2 },
      { lengthof(_curve_map_3), _curve_map_3 },
      { lengthof(_curve_map_4), _curve_map_4 },
    }

Definition at line 556 of file tgp.cpp.

const int8 _max_height[4]`[static]`

Initial value:

     {
      6,
      9,
      12,
      15
    }

Desired maximum height - indexed by _settings_game.difficulty.terrain_type.

Definition at line 230 of file tgp.cpp.

Referenced by HeightMapNormalize().