(svn r23005) -Fix (r23004): Of course there's still the 16-sprite version for shore...
[openttd/fttd.git] / src / tgp.cpp
blob239cb17286096066cf7a37d97a2e1110c2d2e77e
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file tgp.cpp OTTD Perlin Noise Landscape Generator, aka TerraGenesis Perlin */
12 #include "stdafx.h"
13 #include <math.h>
14 #include "clear_map.h"
15 #include "void_map.h"
16 #include "genworld.h"
17 #include "core/alloc_func.hpp"
18 #include "core/random_func.hpp"
19 #include "landscape_type.h"
23 * Quickie guide to Perlin Noise
24 * Perlin noise is a predictable pseudo random number sequence. By generating
25 * it in 2 dimensions, it becomes a useful random map that, for a given seed
26 * and starting X & Y, is entirely predictable. On the face of it, that may not
27 * be useful. However, it means that if you want to replay a map in a different
28 * terrain, or just vary the sea level, you just re-run the generator with the
29 * same seed. The seed is an int32, and is randomised on each run of New Game.
30 * The Scenario Generator does not randomise the value, so that you can
31 * experiment with one terrain until you are happy, or click "Random" for a new
32 * random seed.
34 * Perlin Noise is a series of "octaves" of random noise added together. By
35 * reducing the amplitude of the noise with each octave, the first octave of
36 * noise defines the main terrain sweep, the next the ripples on that, and the
37 * next the ripples on that. I use 6 octaves, with the amplitude controlled by
38 * a power ratio, usually known as a persistence or p value. This I vary by the
39 * smoothness selection, as can be seen in the table below. The closer to 1,
40 * the more of that octave is added. Each octave is however raised to the power
41 * of its position in the list, so the last entry in the "smooth" row, 0.35, is
42 * raised to the power of 6, so can only add 0.001838... of the amplitude to
43 * the running total.
45 * In other words; the first p value sets the general shape of the terrain, the
46 * second sets the major variations to that, ... until finally the smallest
47 * bumps are added.
49 * Usefully, this routine is totally scaleable; so when 32bpp comes along, the
50 * terrain can be as bumpy as you like! It is also infinitely expandable; a
51 * single random seed terrain continues in X & Y as far as you care to
52 * calculate. In theory, we could use just one seed value, but randomly select
53 * where in the Perlin XY space we use for the terrain. Personally I prefer
54 * using a simple (0, 0) to (X, Y), with a varying seed.
57 * Other things i have had to do: mountainous wasnt mountainous enough, and
58 * since we only have 0..15 heights available, I add a second generated map
59 * (with a modified seed), onto the original. This generally raises the
60 * terrain, which then needs scaling back down. Overall effect is a general
61 * uplift.
63 * However, the values on the top of mountains are then almost guaranteed to go
64 * too high, so large flat plateaus appeared at height 15. To counter this, I
65 * scale all heights above 12 to proportion up to 15. It still makes the
66 * mountains have flatish tops, rather than craggy peaks, but at least they
67 * arent smooth as glass.
70 * For a full discussion of Perlin Noise, please visit:
71 * http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
74 * Evolution II
76 * The algorithm as described in the above link suggests to compute each tile height
77 * as composition of several noise waves. Some of them are computed directly by
78 * noise(x, y) function, some are calculated using linear approximation. Our
79 * first implementation of perlin_noise_2D() used 4 noise(x, y) calls plus
80 * 3 linear interpolations. It was called 6 times for each tile. This was a bit
81 * CPU expensive.
83 * The following implementation uses optimized algorithm that should produce
84 * the same quality result with much less computations, but more memory accesses.
85 * The overal speedup should be 300% to 800% depending on CPU and memory speed.
87 * I will try to explain it on the example below:
89 * Have a map of 4 x 4 tiles, our simplifiead noise generator produces only two
90 * values -1 and +1, use 3 octaves with wave lenght 1, 2 and 4, with amplitudes
91 * 3, 2, 1. Original algorithm produces:
93 * 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
94 * 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
95 * 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
96 * 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
98 * 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
99 * 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
100 * 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
101 * 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
104 * Optimization 1:
106 * 1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
108 * 2) setup corner values using amplitude 3
109 * { -3.0 X X X 3.0 }
110 * { X X X X X }
111 * { X X X X X }
112 * { X X X X X }
113 * { 3.0 X X X -3.0 }
115 * 3a) interpolate values in the middle
116 * { -3.0 X 0.0 X 3.0 }
117 * { X X X X X }
118 * { 0.0 X 0.0 X 0.0 }
119 * { X X X X X }
120 * { 3.0 X 0.0 X -3.0 }
122 * 3b) add patches with amplitude 2 to them
123 * { -5.0 X 2.0 X 1.0 }
124 * { X X X X X }
125 * { 2.0 X -2.0 X 2.0 }
126 * { X X X X X }
127 * { 1.0 X 2.0 X -5.0 }
129 * 4a) interpolate values in the middle
130 * { -5.0 -1.5 2.0 1.5 1.0 }
131 * { -1.5 -0.75 0.0 0.75 1.5 }
132 * { 2.0 0.0 -2.0 0.0 2.0 }
133 * { 1.5 0.75 0.0 -0.75 -1.5 }
134 * { 1.0 1.5 2.0 -1.5 -5.0 }
136 * 4b) add patches with amplitude 1 to them
137 * { -6.0 -0.5 1.0 2.5 0.0 }
138 * { -0.5 -1.75 1.0 -0.25 2.5 }
139 * { 1.0 1.0 -3.0 1.0 1.0 }
140 * { 2.5 -0.25 1.0 -1.75 -0.5 }
141 * { 0.0 2.5 1.0 -0.5 -6.0 }
145 * Optimization 2:
147 * As you can see above, each noise function was called just once. Therefore
148 * we don't need to use noise function that calculates the noise from x, y and
149 * some prime. The same quality result we can obtain using standard Random()
150 * function instead.
154 /** Fixed point type for heights */
155 typedef int16 height_t;
156 static const int height_decimal_bits = 4;
157 static const height_t _invalid_height = -32768;
159 /** Fixed point array for amplitudes (and percent values) */
160 typedef int amplitude_t;
161 static const int amplitude_decimal_bits = 10;
163 /** Height map - allocated array of heights (MapSizeX() + 1) x (MapSizeY() + 1) */
164 struct HeightMap
166 height_t *h; //< array of heights
167 uint dim_x; //< height map size_x MapSizeX() + 1
168 uint total_size; //< height map total size
169 uint size_x; //< MapSizeX()
170 uint size_y; //< MapSizeY()
173 * Height map accessor
174 * @param x X position
175 * @param y Y position
176 * @return height as fixed point number
178 inline height_t &height(uint x, uint y)
180 return h[x + y * dim_x];
184 /** Global height map instance */
185 static HeightMap _height_map = {NULL, 0, 0, 0, 0};
187 /** Conversion: int to height_t */
188 #define I2H(i) ((i) << height_decimal_bits)
189 /** Conversion: height_t to int */
190 #define H2I(i) ((i) >> height_decimal_bits)
192 /** Conversion: int to amplitude_t */
193 #define I2A(i) ((i) << amplitude_decimal_bits)
194 /** Conversion: amplitude_t to int */
195 #define A2I(i) ((i) >> amplitude_decimal_bits)
197 /** Conversion: amplitude_t to height_t */
198 #define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
201 /** Walk through all items of _height_map.h */
202 #define FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++)
204 /** Maximum index into array of noise amplitudes */
205 static const int TGP_FREQUENCY_MAX = 6;
208 * Noise amplitudes (multiplied by 1024)
209 * - indexed by "smoothness setting" and log2(frequency)
211 static const amplitude_t _amplitudes_by_smoothness_and_frequency[4][TGP_FREQUENCY_MAX + 1] = {
212 /* lowest frequncy.... ...highest (every corner) */
213 /* Very smooth */
214 {16000, 5600, 1968, 688, 240, 16, 16},
215 /* Smooth */
216 {16000, 16000, 6448, 3200, 1024, 128, 16},
217 /* Rough */
218 {16000, 19200, 12800, 8000, 3200, 256, 64},
219 /* Very Rough */
220 {24000, 16000, 19200, 16000, 8000, 512, 320},
223 /** Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes */
224 static const amplitude_t _water_percent[4] = {20, 80, 250, 400};
226 /** Desired maximum height - indexed by _settings_game.difficulty.terrain_type */
227 static const int8 _max_height[4] = {
228 6, ///< Very flat
229 9, ///< Flat
230 12, ///< Hilly
231 15 ///< Mountainous
235 * Check if a X/Y set are within the map.
236 * @param x coordinate x
237 * @param y coordinate y
238 * @return true if within the map
240 static inline bool IsValidXY(uint x, uint y)
242 return ((int)x) >= 0 && x < _height_map.size_x && ((int)y) >= 0 && y < _height_map.size_y;
247 * Allocate array of (MapSizeX()+1)*(MapSizeY()+1) heights and init the _height_map structure members
248 * @return true on success
250 static inline bool AllocHeightMap()
252 height_t *h;
254 _height_map.size_x = MapSizeX();
255 _height_map.size_y = MapSizeY();
257 /* Allocate memory block for height map row pointers */
258 _height_map.total_size = (_height_map.size_x + 1) * (_height_map.size_y + 1);
259 _height_map.dim_x = _height_map.size_x + 1;
260 _height_map.h = CallocT<height_t>(_height_map.total_size);
262 /* Iterate through height map initialize values */
263 FOR_ALL_TILES_IN_HEIGHT(h) *h = _invalid_height;
265 return true;
268 /** Free height map */
269 static inline void FreeHeightMap()
271 if (_height_map.h == NULL) return;
272 free(_height_map.h);
273 _height_map.h = NULL;
277 * Generates new random height in given amplitude (generated numbers will range from - amplitude to + amplitude)
278 * @param rMax Limit of result
279 * @return generated height
281 static inline height_t RandomHeight(amplitude_t rMax)
283 amplitude_t ra = (Random() << 16) | (Random() & 0x0000FFFF);
284 height_t rh;
285 /* Spread height into range -rMax..+rMax */
286 rh = A2H(ra % (2 * rMax + 1) - rMax);
287 return rh;
291 * One interpolation and noise round
293 * The heights on the map are generated in an iterative process.
294 * We start off with a frequency of 1 (log_frequency == 0), and generate heights only for corners on the most coarsly mesh
295 * (i.e. only for x/y coordinates which are multiples of the minimum edge length).
297 * After this initial step the frequency is doubled (log_frequency incremented) each iteration to generate corners on the next finer mesh.
298 * The heights of the newly added corners are first set by interpolating the heights from the previous iteration.
299 * Finally noise with the given amplitude is applied to all corners of the new mesh.
301 * Generation terminates, when the frequency has reached the map size. I.e. the mesh is as fine as the map, and every corner height
302 * has been set.
304 * @param log_frequency frequency (logarithmic) to apply noise for
305 * @param amplitude Amplitude for the noise
306 * @return false if we are finished (reached the minimal step size / highest frequency)
308 static bool ApplyNoise(uint log_frequency, amplitude_t amplitude)
310 uint size_min = min(_height_map.size_x, _height_map.size_y);
311 uint step = size_min >> log_frequency;
312 uint x, y;
314 /* Trying to apply noise to uninitialized height map */
315 assert(_height_map.h != NULL);
317 /* Are we finished? */
318 if (step == 0) return false;
320 if (log_frequency == 0) {
321 /* This is first round, we need to establish base heights with step = size_min */
322 for (y = 0; y <= _height_map.size_y; y += step) {
323 for (x = 0; x <= _height_map.size_x; x += step) {
324 height_t height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
325 _height_map.height(x, y) = height;
328 return true;
331 /* It is regular iteration round.
332 * Interpolate height values at odd x, even y tiles */
333 for (y = 0; y <= _height_map.size_y; y += 2 * step) {
334 for (x = 0; x < _height_map.size_x; x += 2 * step) {
335 height_t h00 = _height_map.height(x + 0 * step, y);
336 height_t h02 = _height_map.height(x + 2 * step, y);
337 height_t h01 = (h00 + h02) / 2;
338 _height_map.height(x + 1 * step, y) = h01;
342 /* Interpolate height values at odd y tiles */
343 for (y = 0; y < _height_map.size_y; y += 2 * step) {
344 for (x = 0; x <= _height_map.size_x; x += step) {
345 height_t h00 = _height_map.height(x, y + 0 * step);
346 height_t h20 = _height_map.height(x, y + 2 * step);
347 height_t h10 = (h00 + h20) / 2;
348 _height_map.height(x, y + 1 * step) = h10;
352 /* Add noise for next higher frequency (smaller steps) */
353 for (y = 0; y <= _height_map.size_y; y += step) {
354 for (x = 0; x <= _height_map.size_x; x += step) {
355 _height_map.height(x, y) += RandomHeight(amplitude);
359 return (step > 1);
362 /** Base Perlin noise generator - fills height map with raw Perlin noise */
363 static void HeightMapGenerate()
365 uint size_min = min(_height_map.size_x, _height_map.size_y);
366 uint iteration_round = 0;
367 amplitude_t amplitude;
368 bool continue_iteration;
369 int log_size_min, log_frequency_min;
370 int log_frequency;
372 /* Find first power of two that fits, so that later log_frequency == TGP_FREQUENCY_MAX in the last iteration */
373 for (log_size_min = TGP_FREQUENCY_MAX; (1U << log_size_min) < size_min; log_size_min++) { }
374 log_frequency_min = log_size_min - TGP_FREQUENCY_MAX;
376 /* Zero must be part of the iteration, else initialization will fail. */
377 assert(log_frequency_min >= 0);
379 /* Keep increasing the frequency until we reach the step size equal to one tile */
380 do {
381 log_frequency = iteration_round - log_frequency_min;
382 if (log_frequency >= 0) {
383 /* Apply noise for the next frequency */
384 assert(log_frequency <= TGP_FREQUENCY_MAX);
385 amplitude = _amplitudes_by_smoothness_and_frequency[_settings_game.game_creation.tgen_smoothness][log_frequency];
386 } else {
387 /* Amplitude for the low frequencies on big maps is 0, i.e. initialise with zero height */
388 amplitude = 0;
390 continue_iteration = ApplyNoise(iteration_round, amplitude);
391 iteration_round++;
392 } while (continue_iteration);
393 assert(log_frequency == TGP_FREQUENCY_MAX);
396 /** Returns min, max and average height from height map */
397 static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t *avg_ptr)
399 height_t h_min, h_max, h_avg, *h;
400 int64 h_accu = 0;
401 h_min = h_max = _height_map.height(0, 0);
403 /* Get h_min, h_max and accumulate heights into h_accu */
404 FOR_ALL_TILES_IN_HEIGHT(h) {
405 if (*h < h_min) h_min = *h;
406 if (*h > h_max) h_max = *h;
407 h_accu += *h;
410 /* Get average height */
411 h_avg = (height_t)(h_accu / (_height_map.size_x * _height_map.size_y));
413 /* Return required results */
414 if (min_ptr != NULL) *min_ptr = h_min;
415 if (max_ptr != NULL) *max_ptr = h_max;
416 if (avg_ptr != NULL) *avg_ptr = h_avg;
419 /** Dill histogram and return pointer to its base point - to the count of zero heights */
420 static int *HeightMapMakeHistogram(height_t h_min, height_t h_max, int *hist_buf)
422 int *hist = hist_buf - h_min;
423 height_t *h;
425 /* Count the heights and fill the histogram */
426 FOR_ALL_TILES_IN_HEIGHT(h) {
427 assert(*h >= h_min);
428 assert(*h <= h_max);
429 hist[*h]++;
431 return hist;
434 /** Applies sine wave redistribution onto height map */
435 static void HeightMapSineTransform(height_t h_min, height_t h_max)
437 height_t *h;
439 FOR_ALL_TILES_IN_HEIGHT(h) {
440 double fheight;
442 if (*h < h_min) continue;
444 /* Transform height into 0..1 space */
445 fheight = (double)(*h - h_min) / (double)(h_max - h_min);
446 /* Apply sine transform depending on landscape type */
447 switch (_settings_game.game_creation.landscape) {
448 case LT_TOYLAND:
449 case LT_TEMPERATE:
450 /* Move and scale 0..1 into -1..+1 */
451 fheight = 2 * fheight - 1;
452 /* Sine transform */
453 fheight = sin(fheight * M_PI_2);
454 /* Transform it back from -1..1 into 0..1 space */
455 fheight = 0.5 * (fheight + 1);
456 break;
458 case LT_ARCTIC:
460 /* Arctic terrain needs special height distribution.
461 * Redistribute heights to have more tiles at highest (75%..100%) range */
462 double sine_upper_limit = 0.75;
463 double linear_compression = 2;
464 if (fheight >= sine_upper_limit) {
465 /* Over the limit we do linear compression up */
466 fheight = 1.0 - (1.0 - fheight) / linear_compression;
467 } else {
468 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
469 /* Get 0..sine_upper_limit into -1..1 */
470 fheight = 2.0 * fheight / sine_upper_limit - 1.0;
471 /* Sine wave transform */
472 fheight = sin(fheight * M_PI_2);
473 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
474 fheight = 0.5 * (fheight + 1.0) * m;
477 break;
479 case LT_TROPIC:
481 /* Desert terrain needs special height distribution.
482 * Half of tiles should be at lowest (0..25%) heights */
483 double sine_lower_limit = 0.5;
484 double linear_compression = 2;
485 if (fheight <= sine_lower_limit) {
486 /* Under the limit we do linear compression down */
487 fheight = fheight / linear_compression;
488 } else {
489 double m = sine_lower_limit / linear_compression;
490 /* Get sine_lower_limit..1 into -1..1 */
491 fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
492 /* Sine wave transform */
493 fheight = sin(fheight * M_PI_2);
494 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
495 fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
498 break;
500 default:
501 NOT_REACHED();
502 break;
504 /* Transform it back into h_min..h_max space */
505 *h = (height_t)(fheight * (h_max - h_min) + h_min);
506 if (*h < 0) *h = I2H(0);
507 if (*h >= h_max) *h = h_max - 1;
511 /* Additional map variety is provided by applying different curve maps
512 * to different parts of the map. A randomized low resolution grid contains
513 * which curve map to use on each part of the make. This filtered non-linearly
514 * to smooth out transitions between curves, so each tile could have between
515 * 100% of one map applied or 25% of four maps.
517 * The curve maps define different land styles, i.e. lakes, low-lands, hills
518 * and mountain ranges, although these are dependent on the landscape style
519 * chosen as well.
521 * The level parameter dictates the resolution of the grid. A low resolution
522 * grid will result in larger continuous areas of a land style, a higher
523 * resolution grid splits the style into smaller areas.
525 * At this point in map generation, all height data has been normalized to 0
526 * to 239.
528 struct control_point_t {
529 height_t x;
530 height_t y;
533 struct control_point_list_t {
534 size_t length;
535 const control_point_t *list;
538 static const control_point_t _curve_map_1[] = {
539 { 0, 0 }, { 48, 24 }, { 192, 32 }, { 240, 96 }
542 static const control_point_t _curve_map_2[] = {
543 { 0, 0 }, { 16, 24 }, { 128, 32 }, { 192, 64 }, { 240, 144 }
546 static const control_point_t _curve_map_3[] = {
547 { 0, 0 }, { 16, 24 }, { 128, 64 }, { 192, 144 }, { 240, 192 }
550 static const control_point_t _curve_map_4[] = {
551 { 0, 0 }, { 16, 24 }, { 96, 72 }, { 160, 192 }, { 220, 239 }, { 240, 239 }
554 static const control_point_list_t _curve_maps[] = {
555 { lengthof(_curve_map_1), _curve_map_1 },
556 { lengthof(_curve_map_2), _curve_map_2 },
557 { lengthof(_curve_map_3), _curve_map_3 },
558 { lengthof(_curve_map_4), _curve_map_4 },
561 static void HeightMapCurves(uint level)
563 height_t ht[lengthof(_curve_maps)];
565 /* Set up a grid to choose curve maps based on location */
566 uint sx = Clamp(1 << level, 2, 32);
567 uint sy = Clamp(1 << level, 2, 32);
568 byte *c = (byte *)alloca(sx * sy);
570 for (uint i = 0; i < sx * sy; i++) {
571 c[i] = Random() % lengthof(_curve_maps);
574 /* Apply curves */
575 for (uint x = 0; x < _height_map.size_x; x++) {
577 /* Get our X grid positions and bi-linear ratio */
578 float fx = (float)(sx * x) / _height_map.size_x + 0.5f;
579 uint x1 = (uint)fx;
580 uint x2 = x1;
581 float xr = 2.0f * (fx - x1) - 1.0f;
582 xr = sin(xr * M_PI_2);
583 xr = sin(xr * M_PI_2);
584 xr = 0.5f * (xr + 1.0f);
585 float xri = 1.0f - xr;
587 if (x1 > 0) {
588 x1--;
589 if (x2 >= sx) x2--;
592 for (uint y = 0; y < _height_map.size_y; y++) {
594 /* Get our Y grid position and bi-linear ratio */
595 float fy = (float)(sy * y) / _height_map.size_y + 0.5f;
596 uint y1 = (uint)fy;
597 uint y2 = y1;
598 float yr = 2.0f * (fy - y1) - 1.0f;
599 yr = sin(yr * M_PI_2);
600 yr = sin(yr * M_PI_2);
601 yr = 0.5f * (yr + 1.0f);
602 float yri = 1.0f - yr;
604 if (y1 > 0) {
605 y1--;
606 if (y2 >= sy) y2--;
609 uint corner_a = c[x1 + sx * y1];
610 uint corner_b = c[x1 + sx * y2];
611 uint corner_c = c[x2 + sx * y1];
612 uint corner_d = c[x2 + sx * y2];
614 /* Bitmask of which curve maps are chosen, so that we do not bother
615 * calculating a curve which won't be used. */
616 uint corner_bits = 0;
617 corner_bits |= 1 << corner_a;
618 corner_bits |= 1 << corner_b;
619 corner_bits |= 1 << corner_c;
620 corner_bits |= 1 << corner_d;
622 height_t *h = &_height_map.height(x, y);
624 /* Apply all curve maps that are used on this tile. */
625 for (uint t = 0; t < lengthof(_curve_maps); t++) {
626 if (!HasBit(corner_bits, t)) continue;
628 const control_point_t *cm = _curve_maps[t].list;
629 for (uint i = 0; i < _curve_maps[t].length - 1; i++) {
630 const control_point_t &p1 = cm[i];
631 const control_point_t &p2 = cm[i + 1];
633 if (*h >= p1.x && *h < p2.x) {
634 ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
635 break;
640 /* Apply interpolation of curve map results. */
641 *h = (height_t)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
646 /** Adjusts heights in height map to contain required amount of water tiles */
647 static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_new)
649 height_t h_min, h_max, h_avg, h_water_level;
650 int64 water_tiles, desired_water_tiles;
651 height_t *h;
652 int *hist;
654 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
656 /* Allocate histogram buffer and clear its cells */
657 int *hist_buf = CallocT<int>(h_max - h_min + 1);
658 /* Fill histogram */
659 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf);
661 /* How many water tiles do we want? */
662 desired_water_tiles = A2I(((int64)water_percent) * (int64)(_height_map.size_x * _height_map.size_y));
664 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
665 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
666 water_tiles += hist[h_water_level];
667 if (water_tiles >= desired_water_tiles) break;
670 /* We now have the proper water level value.
671 * Transform the height map into new (normalized) height map:
672 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
673 * values from range: h_water_level..h_max are transformed into 0..h_max_new
674 * where h_max_new is 4, 8, 12 or 16 depending on terrain type (very flat, flat, hilly, mountains)
676 FOR_ALL_TILES_IN_HEIGHT(h) {
677 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
678 *h = (height_t)(((int)h_max_new) * (*h - h_water_level) / (h_max - h_water_level)) + I2H(1);
679 /* Make sure all values are in the proper range (0..h_max_new) */
680 if (*h < 0) *h = I2H(0);
681 if (*h >= h_max_new) *h = h_max_new - 1;
684 free(hist_buf);
687 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
690 * This routine sculpts in from the edge a random amount, again a Perlin
691 * sequence, to avoid the rigid flat-edge slopes that were present before. The
692 * Perlin noise map doesnt know where we are going to slice across, and so we
693 * often cut straight through high terrain. the smoothing routine makes it
694 * legal, gradually increasing up from the edge to the original terrain height.
695 * By cutting parts of this away, it gives a far more irregular edge to the
696 * map-edge. Sometimes it works beautifully with the existing sea & lakes, and
697 * creates a very realistic coastline. Other times the variation is less, and
698 * the map-edge shows its cliff-like roots.
700 * This routine may be extended to randomly sculpt the height of the terrain
701 * near the edge. This will have the coast edge at low level (1-3), rising in
702 * smoothed steps inland to about 15 tiles in. This should make it look as
703 * though the map has been built for the map size, rather than a slice through
704 * a larger map.
706 * Please note that all the small numbers; 53, 101, 167, etc. are small primes
707 * to help give the perlin noise a bit more of a random feel.
709 static void HeightMapCoastLines(uint8 water_borders)
711 int smallest_size = min(_settings_game.game_creation.map_x, _settings_game.game_creation.map_y);
712 const int margin = 4;
713 uint y, x;
714 double max_x;
715 double max_y;
717 /* Lower to sea level */
718 for (y = 0; y <= _height_map.size_y; y++) {
719 if (HasBit(water_borders, BORDER_NE)) {
720 /* Top right */
721 max_x = abs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.9, 53) + 0.25) * 5 + (perlin_coast_noise_2D(y, y, 0.35, 179) + 1) * 12);
722 max_x = max((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x);
723 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
724 for (x = 0; x < max_x; x++) {
725 _height_map.height(x, y) = 0;
729 if (HasBit(water_borders, BORDER_SW)) {
730 /* Bottom left */
731 max_x = abs((perlin_coast_noise_2D(_height_map.size_y - y, y, 0.85, 101) + 0.3) * 6 + (perlin_coast_noise_2D(y, y, 0.45, 67) + 0.75) * 8);
732 max_x = max((smallest_size * smallest_size / 16) + max_x, (smallest_size * smallest_size / 16) + margin - max_x);
733 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
734 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
735 _height_map.height(x, y) = 0;
740 /* Lower to sea level */
741 for (x = 0; x <= _height_map.size_x; x++) {
742 if (HasBit(water_borders, BORDER_NW)) {
743 /* Top left */
744 max_y = abs((perlin_coast_noise_2D(x, _height_map.size_y / 2, 0.9, 167) + 0.4) * 5 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.4, 211) + 0.7) * 9);
745 max_y = max((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y);
746 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
747 for (y = 0; y < max_y; y++) {
748 _height_map.height(x, y) = 0;
752 if (HasBit(water_borders, BORDER_SE)) {
753 /* Bottom right */
754 max_y = abs((perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.85, 71) + 0.25) * 6 + (perlin_coast_noise_2D(x, _height_map.size_y / 3, 0.35, 193) + 0.75) * 12);
755 max_y = max((smallest_size * smallest_size / 16) + max_y, (smallest_size * smallest_size / 16) + margin - max_y);
756 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
757 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
758 _height_map.height(x, y) = 0;
764 /** Start at given point, move in given direction, find and Smooth coast in that direction */
765 static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
767 const int max_coast_dist_from_edge = 35;
768 const int max_coast_Smooth_depth = 35;
770 int x, y;
771 int ed; // coast distance from edge
772 int depth;
774 height_t h_prev = 16;
775 height_t h;
777 assert(IsValidXY(org_x, org_y));
779 /* Search for the coast (first non-water tile) */
780 for (x = org_x, y = org_y, ed = 0; IsValidXY(x, y) && ed < max_coast_dist_from_edge; x += dir_x, y += dir_y, ed++) {
781 /* Coast found? */
782 if (_height_map.height(x, y) > 15) break;
784 /* Coast found in the neighborhood? */
785 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
787 /* Coast found in the neighborhood on the other side */
788 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
791 /* Coast found or max_coast_dist_from_edge has been reached.
792 * Soften the coast slope */
793 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_Smooth_depth; depth++, x += dir_x, y += dir_y) {
794 h = _height_map.height(x, y);
795 h = min(h, h_prev + (4 + depth)); // coast softening formula
796 _height_map.height(x, y) = h;
797 h_prev = h;
801 /** Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge */
802 static void HeightMapSmoothCoasts(uint8 water_borders)
804 uint x, y;
805 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
806 for (x = 0; x < _height_map.size_x; x++) {
807 if (HasBit(water_borders, BORDER_NW)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
808 if (HasBit(water_borders, BORDER_SE)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
810 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
811 for (y = 0; y < _height_map.size_y; y++) {
812 if (HasBit(water_borders, BORDER_NE)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
813 if (HasBit(water_borders, BORDER_SW)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
818 * This routine provides the essential cleanup necessary before OTTD can
819 * display the terrain. When generated, the terrain heights can jump more than
820 * one level between tiles. This routine smooths out those differences so that
821 * the most it can change is one level. When OTTD can support cliffs, this
822 * routine may not be necessary.
824 static void HeightMapSmoothSlopes(height_t dh_max)
826 int x, y;
827 for (y = 0; y <= (int)_height_map.size_y; y++) {
828 for (x = 0; x <= (int)_height_map.size_x; x++) {
829 height_t h_max = min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max;
830 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
833 for (y = _height_map.size_y; y >= 0; y--) {
834 for (x = _height_map.size_x; x >= 0; x--) {
835 height_t h_max = min(_height_map.height((uint)x < _height_map.size_x ? x + 1 : x, y), _height_map.height(x, (uint)y < _height_map.size_y ? y + 1 : y)) + dh_max;
836 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
842 * Height map terraform post processing:
843 * - water level adjusting
844 * - coast Smoothing
845 * - slope Smoothing
846 * - height histogram redistribution by sine wave transform
848 static void HeightMapNormalize()
850 int sea_level_setting = _settings_game.difficulty.quantity_sea_lakes;
851 const amplitude_t water_percent = sea_level_setting != (int)CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY ? _water_percent[sea_level_setting] : _settings_game.game_creation.custom_sea_level * 1024 / 100;
852 const height_t h_max_new = I2H(_max_height[_settings_game.difficulty.terrain_type]);
853 const height_t roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
855 HeightMapAdjustWaterLevel(water_percent, h_max_new);
857 byte water_borders = _settings_game.construction.freeform_edges ? _settings_game.game_creation.water_borders : 0xF;
858 if (water_borders == BORDERS_RANDOM) water_borders = GB(Random(), 0, 4);
860 HeightMapCoastLines(water_borders);
861 HeightMapSmoothSlopes(roughness);
863 HeightMapSmoothCoasts(water_borders);
864 HeightMapSmoothSlopes(roughness);
866 HeightMapSineTransform(12, h_max_new);
868 if (_settings_game.game_creation.variety > 0) {
869 HeightMapCurves(_settings_game.game_creation.variety);
872 HeightMapSmoothSlopes(16);
876 * The Perlin Noise calculation using large primes
877 * The initial number is adjusted by two values; the generation_seed, and the
878 * passed parameter; prime.
879 * prime is used to allow the perlin noise generator to create useful random
880 * numbers from slightly different series.
882 static double int_noise(const long x, const long y, const int prime)
884 long n = x + y * prime + _settings_game.game_creation.generation_seed;
886 n = (n << 13) ^ n;
888 /* Pseudo-random number generator, using several large primes */
889 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
894 * This routine determines the interpolated value between a and b
896 static inline double linear_interpolate(const double a, const double b, const double x)
898 return a + x * (b - a);
903 * This routine returns the smoothed interpolated noise for an x and y, using
904 * the values from the surrounding positions.
906 static double interpolated_noise(const double x, const double y, const int prime)
908 const int integer_X = (int)x;
909 const int integer_Y = (int)y;
911 const double fractional_X = x - (double)integer_X;
912 const double fractional_Y = y - (double)integer_Y;
914 const double v1 = int_noise(integer_X, integer_Y, prime);
915 const double v2 = int_noise(integer_X + 1, integer_Y, prime);
916 const double v3 = int_noise(integer_X, integer_Y + 1, prime);
917 const double v4 = int_noise(integer_X + 1, integer_Y + 1, prime);
919 const double i1 = linear_interpolate(v1, v2, fractional_X);
920 const double i2 = linear_interpolate(v3, v4, fractional_X);
922 return linear_interpolate(i1, i2, fractional_Y);
927 * This is a similar function to the main perlin noise calculation, but uses
928 * the value p passed as a parameter rather than selected from the predefined
929 * sequences. as you can guess by its title, i use this to create the indented
930 * coastline, which is just another perlin sequence.
932 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
934 double total = 0.0;
935 int i;
937 for (i = 0; i < 6; i++) {
938 const double frequency = (double)(1 << i);
939 const double amplitude = pow(p, (double)i);
941 total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude;
944 return total;
948 /** A small helper function to initialize the terrain */
949 static void TgenSetTileHeight(TileIndex tile, int height)
951 SetTileHeight(tile, height);
953 /* Only clear the tiles within the map area. */
954 if (TileX(tile) != MapMaxX() && TileY(tile) != MapMaxY() &&
955 (!_settings_game.construction.freeform_edges || (TileX(tile) != 0 && TileY(tile) != 0))) {
956 MakeClear(tile, CLEAR_GRASS, 3);
961 * The main new land generator using Perlin noise. Desert landscape is handled
962 * different to all others to give a desert valley between two high mountains.
963 * Clearly if a low height terrain (flat/very flat) is chosen, then the tropic
964 * areas wont be high enough, and there will be very little tropic on the map.
965 * Thus Tropic works best on Hilly or Mountainous.
967 void GenerateTerrainPerlin()
969 uint x, y;
971 if (!AllocHeightMap()) return;
972 GenerateWorldSetAbortCallback(FreeHeightMap);
974 HeightMapGenerate();
976 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
978 HeightMapNormalize();
980 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
982 /* First make sure the tiles at the north border are void tiles if needed. */
983 if (_settings_game.construction.freeform_edges) {
984 for (y = 0; y < _height_map.size_y - 1; y++) MakeVoid(_height_map.size_x * y);
985 for (x = 0; x < _height_map.size_x; x++) MakeVoid(x);
988 /* Transfer height map into OTTD map */
989 for (y = 0; y < _height_map.size_y; y++) {
990 for (x = 0; x < _height_map.size_x; x++) {
991 int height = H2I(_height_map.height(x, y));
992 if (height < 0) height = 0;
993 if (height > 15) height = 15;
994 TgenSetTileHeight(TileXY(x, y), height);
998 IncreaseGeneratingWorldProgress(GWP_LANDSCAPE);
1000 FreeHeightMap();
1001 GenerateWorldSetAbortCallback(NULL);