OpenTTD
tgp.cpp
Go to the documentation of this file.
1 /* $Id: tgp.cpp 27232 2015-04-11 18:46:01Z alberth $ */
2 
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  */
9 
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/random_func.hpp"
18 #include "landscape_type.h"
19 
20 #include "safeguards.h"
21 
22 /*
23  *
24  * Quickie guide to Perlin Noise
25  * Perlin noise is a predictable pseudo random number sequence. By generating
26  * it in 2 dimensions, it becomes a useful random map that, for a given seed
27  * and starting X & Y, is entirely predictable. On the face of it, that may not
28  * be useful. However, it means that if you want to replay a map in a different
29  * terrain, or just vary the sea level, you just re-run the generator with the
30  * same seed. The seed is an int32, and is randomised on each run of New Game.
31  * The Scenario Generator does not randomise the value, so that you can
32  * experiment with one terrain until you are happy, or click "Random" for a new
33  * random seed.
34  *
35  * Perlin Noise is a series of "octaves" of random noise added together. By
36  * reducing the amplitude of the noise with each octave, the first octave of
37  * noise defines the main terrain sweep, the next the ripples on that, and the
38  * next the ripples on that. I use 6 octaves, with the amplitude controlled by
39  * a power ratio, usually known as a persistence or p value. This I vary by the
40  * smoothness selection, as can be seen in the table below. The closer to 1,
41  * the more of that octave is added. Each octave is however raised to the power
42  * of its position in the list, so the last entry in the "smooth" row, 0.35, is
43  * raised to the power of 6, so can only add 0.001838... of the amplitude to
44  * the running total.
45  *
46  * In other words; the first p value sets the general shape of the terrain, the
47  * second sets the major variations to that, ... until finally the smallest
48  * bumps are added.
49  *
50  * Usefully, this routine is totally scaleable; so when 32bpp comes along, the
51  * terrain can be as bumpy as you like! It is also infinitely expandable; a
52  * single random seed terrain continues in X & Y as far as you care to
53  * calculate. In theory, we could use just one seed value, but randomly select
54  * where in the Perlin XY space we use for the terrain. Personally I prefer
55  * using a simple (0, 0) to (X, Y), with a varying seed.
56  *
57  *
58  * Other things i have had to do: mountainous wasn't mountainous enough, and
59  * since we only have 0..15 heights available, I add a second generated map
60  * (with a modified seed), onto the original. This generally raises the
61  * terrain, which then needs scaling back down. Overall effect is a general
62  * uplift.
63  *
64  * However, the values on the top of mountains are then almost guaranteed to go
65  * too high, so large flat plateaus appeared at height 15. To counter this, I
66  * scale all heights above 12 to proportion up to 15. It still makes the
67  * mountains have flattish tops, rather than craggy peaks, but at least they
68  * aren't smooth as glass.
69  *
70  *
71  * For a full discussion of Perlin Noise, please visit:
72  * http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
73  *
74  *
75  * Evolution II
76  *
77  * The algorithm as described in the above link suggests to compute each tile height
78  * as composition of several noise waves. Some of them are computed directly by
79  * noise(x, y) function, some are calculated using linear approximation. Our
80  * first implementation of perlin_noise_2D() used 4 noise(x, y) calls plus
81  * 3 linear interpolations. It was called 6 times for each tile. This was a bit
82  * CPU expensive.
83  *
84  * The following implementation uses optimized algorithm that should produce
85  * the same quality result with much less computations, but more memory accesses.
86  * The overall speedup should be 300% to 800% depending on CPU and memory speed.
87  *
88  * I will try to explain it on the example below:
89  *
90  * Have a map of 4 x 4 tiles, our simplified noise generator produces only two
91  * values -1 and +1, use 3 octaves with wave length 1, 2 and 4, with amplitudes
92  * 3, 2, 1. Original algorithm produces:
93  *
94  * 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
95  * 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
96  * 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
97  * 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  *
99  * 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
100  * 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
101  * 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
102  * 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
103  *
104  *
105  * Optimization 1:
106  *
107  * 1) we need to allocate a bit more tiles: (size_x + 1) * (size_y + 1) = (5 * 5):
108  *
109  * 2) setup corner values using amplitude 3
110  * { -3.0 X X X 3.0 }
111  * { X X X X X }
112  * { X X X X X }
113  * { X X X X X }
114  * { 3.0 X X X -3.0 }
115  *
116  * 3a) interpolate values in the middle
117  * { -3.0 X 0.0 X 3.0 }
118  * { X X X X X }
119  * { 0.0 X 0.0 X 0.0 }
120  * { X X X X X }
121  * { 3.0 X 0.0 X -3.0 }
122  *
123  * 3b) add patches with amplitude 2 to them
124  * { -5.0 X 2.0 X 1.0 }
125  * { X X X X X }
126  * { 2.0 X -2.0 X 2.0 }
127  * { X X X X X }
128  * { 1.0 X 2.0 X -5.0 }
129  *
130  * 4a) interpolate values in the middle
131  * { -5.0 -1.5 2.0 1.5 1.0 }
132  * { -1.5 -0.75 0.0 0.75 1.5 }
133  * { 2.0 0.0 -2.0 0.0 2.0 }
134  * { 1.5 0.75 0.0 -0.75 -1.5 }
135  * { 1.0 1.5 2.0 -1.5 -5.0 }
136  *
137  * 4b) add patches with amplitude 1 to them
138  * { -6.0 -0.5 1.0 2.5 0.0 }
139  * { -0.5 -1.75 1.0 -0.25 2.5 }
140  * { 1.0 1.0 -3.0 1.0 1.0 }
141  * { 2.5 -0.25 1.0 -1.75 -0.5 }
142  * { 0.0 2.5 1.0 -0.5 -6.0 }
143  *
144  *
145  *
146  * Optimization 2:
147  *
148  * As you can see above, each noise function was called just once. Therefore
149  * we don't need to use noise function that calculates the noise from x, y and
150  * some prime. The same quality result we can obtain using standard Random()
151  * function instead.
152  *
153  */
154 
156 typedef int16 height_t;
157 static const int height_decimal_bits = 4;
158 
160 typedef int amplitude_t;
161 static const int amplitude_decimal_bits = 10;
162 
164 struct HeightMap
165 {
166  height_t *h; //< array of heights
167  /* Even though the sizes are always positive, there are many cases where
168  * X and Y need to be signed integers due to subtractions. */
169  int dim_x; //< height map size_x MapSizeX() + 1
170  int total_size; //< height map total size
171  int size_x; //< MapSizeX()
172  int size_y; //< MapSizeY()
173 
180  inline height_t &height(uint x, uint y)
181  {
182  return h[x + y * dim_x];
183  }
184 };
185 
187 static HeightMap _height_map = {NULL, 0, 0, 0, 0};
188 
190 #define I2H(i) ((i) << height_decimal_bits)
191 
192 #define H2I(i) ((i) >> height_decimal_bits)
193 
195 #define I2A(i) ((i) << amplitude_decimal_bits)
196 
197 #define A2I(i) ((i) >> amplitude_decimal_bits)
198 
200 #define A2H(a) ((a) >> (amplitude_decimal_bits - height_decimal_bits))
201 
202 
204 #define FOR_ALL_TILES_IN_HEIGHT(h) for (h = _height_map.h; h < &_height_map.h[_height_map.total_size]; h++)
205 
207 static const int MAX_TGP_FREQUENCIES = 10;
208 
210 static const amplitude_t _water_percent[4] = {70, 170, 270, 420};
211 
219 {
230  static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
231  /* 64 128 256 512 1024 2048 4096 */
232  { 3, 3, 3, 3, 4, 5, 7 },
233  { 5, 7, 8, 9, 14, 19, 31 },
234  { 8, 9, 10, 15, 23, 37, 61 },
235  { 10, 11, 17, 19, 49, 63, 73 },
236  { 12, 19, 25, 31, 67, 75, 87 },
237  };
238 
239  int max_height_from_table = max_height[_settings_game.difficulty.terrain_type][min(MapLogX(), MapLogY()) - MIN_MAP_SIZE_BITS];
240  return I2H(min(max_height_from_table, _settings_game.construction.max_heightlevel));
241 }
242 
249 static amplitude_t GetAmplitude(int frequency)
250 {
251  /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency).
252  * Used for maps that have their smallest side smaller than 512. */
253  static const amplitude_t amplitudes_small[][10] = {
254  /* lowest frequency ...... highest (every corner) */
255  {60000, 2273, 4142, 2253, 421, 213, 137, 177, 37, 16},
256  {50000, 2273, 4142, 2253, 421, 213, 137, 177, 37, 61},
257  {40000, 2273, 4142, 2253, 421, 213, 137, 177, 37, 91},
258  {30000, 2273, 4142, 2253, 421, 213, 137, 177, 37, 161},
259  };
260 
261  /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency).
262  * Used for maps that have their smallest side equal to 512. */
263  static const amplitude_t amplitudes_middle[][10] = {
264  {55000, 2273, 5142, 253, 2421, 213, 137, 177, 37, 16},
265  {45000, 2273, 5142, 253, 2421, 213, 137, 177, 37, 61},
266  {35000, 2273, 5142, 253, 2421, 213, 137, 177, 37, 91},
267  {25000, 2273, 5142, 253, 2421, 213, 137, 177, 37, 161},
268  };
269 
270  /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency).
271  * Used for maps that have their smallest side bigger than 512. */
272  static const amplitude_t amplitudes_large[][10] = {
273  /* lowest frequency ...... highest (every corner) */
274  {55000, 2273, 5142, 253, 421, 2213, 137, 177, 37, 16},
275  {45000, 2273, 5142, 253, 421, 2213, 137, 177, 37, 61},
276  {35000, 2273, 5142, 253, 421, 2213, 137, 177, 37, 91},
277  {25000, 2273, 5142, 253, 421, 2213, 137, 177, 37, 161},
278  };
279 
280  /* Make sure arrays cover all smoothness settings. */
281  assert_compile(lengthof(amplitudes_small) == TGEN_SMOOTHNESS_END);
282  assert_compile(lengthof(amplitudes_middle) == TGEN_SMOOTHNESS_END);
283  assert_compile(lengthof(amplitudes_large) == TGEN_SMOOTHNESS_END);
284 
285  /* Extrapolation factors for ranges before the table.
286  * The extrapolation is needed to account for the higher map heights. They need larger
287  * areas with a particular gradient so that we are able to create maps without too
288  * many steep slopes up to the wanted height level. It's definitely not perfect since
289  * it will bring larger rectangles with similar slopes which makes the rectangular
290  * behaviour of TGP more noticable. However, these height differentiations cannot
291  * happen over much smaller areas; we basically double the "range" to give a similar
292  * slope for every doubling of map height.
293  */
294  static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
295 
298 
299  int index;
300  amplitude_t amplitude;
301  if (smallest_size < 9) { // Smallest map side is less than 2^9 == 512.
302  index = frequency - MAX_TGP_FREQUENCIES + lengthof(amplitudes_small[0]);
303  amplitude = amplitudes_small[smoothness][max(0, index)];
304  } else if (smallest_size == 9) {
305  index = frequency - MAX_TGP_FREQUENCIES + lengthof(amplitudes_middle[0]);
306  amplitude = amplitudes_middle[smoothness][max(0, index)];
307  } else {
308  index = frequency - MAX_TGP_FREQUENCIES + lengthof(amplitudes_large[0]);
309  amplitude = amplitudes_large[smoothness][max(0, index)];
310  }
311  if (index >= 0) return amplitude;
312 
313  /* We need to extrapolate the amplitude. */
314  double extrapolation_factor = extrapolation_factors[smoothness];
315  int height_range = I2H(16);
316  do {
317  amplitude = (amplitude_t)(extrapolation_factor * (double)amplitude);
318  height_range <<= 1;
319  index++;
320  } while (index < 0);
321 
322  return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
323 }
324 
331 static inline bool IsValidXY(int x, int y)
332 {
333  return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
334 }
335 
336 
341 static inline bool AllocHeightMap()
342 {
343  height_t *h;
344 
345  _height_map.size_x = MapSizeX();
346  _height_map.size_y = MapSizeY();
347 
348  /* Allocate memory block for height map row pointers */
349  _height_map.total_size = (_height_map.size_x + 1) * (_height_map.size_y + 1);
350  _height_map.dim_x = _height_map.size_x + 1;
351  _height_map.h = CallocT<height_t>(_height_map.total_size);
352 
353  /* Iterate through height map and initialise values. */
354  FOR_ALL_TILES_IN_HEIGHT(h) *h = 0;
355 
356  return true;
357 }
358 
360 static inline void FreeHeightMap()
361 {
362  free(_height_map.h);
363  _height_map.h = NULL;
364 }
365 
371 static inline height_t RandomHeight(amplitude_t rMax)
372 {
373  /* Spread height into range -rMax..+rMax */
374  return A2H(RandomRange(2 * rMax + 1) - rMax);
375 }
376 
384 static void HeightMapGenerate()
385 {
386  /* Trying to apply noise to uninitialized height map */
387  assert(_height_map.h != NULL);
388 
389  int start = max(MAX_TGP_FREQUENCIES - (int)min(MapLogX(), MapLogY()), 0);
390  bool first = true;
391 
392  for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
393  const amplitude_t amplitude = GetAmplitude(frequency);
394 
395  /* Ignore zero amplitudes; it means our map isn't height enough for this
396  * amplitude, so ignore it and continue with the next set of amplitude. */
397  if (amplitude == 0) continue;
398 
399  const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
400 
401  if (first) {
402  /* This is first round, we need to establish base heights with step = size_min */
403  for (int y = 0; y <= _height_map.size_y; y += step) {
404  for (int x = 0; x <= _height_map.size_x; x += step) {
405  height_t height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
406  _height_map.height(x, y) = height;
407  }
408  }
409  first = false;
410  continue;
411  }
412 
413  /* It is regular iteration round.
414  * Interpolate height values at odd x, even y tiles */
415  for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
416  for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
417  height_t h00 = _height_map.height(x + 0 * step, y);
418  height_t h02 = _height_map.height(x + 2 * step, y);
419  height_t h01 = (h00 + h02) / 2;
420  _height_map.height(x + 1 * step, y) = h01;
421  }
422  }
423 
424  /* Interpolate height values at odd y tiles */
425  for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
426  for (int x = 0; x <= _height_map.size_x; x += step) {
427  height_t h00 = _height_map.height(x, y + 0 * step);
428  height_t h20 = _height_map.height(x, y + 2 * step);
429  height_t h10 = (h00 + h20) / 2;
430  _height_map.height(x, y + 1 * step) = h10;
431  }
432  }
433 
434  /* Add noise for next higher frequency (smaller steps) */
435  for (int y = 0; y <= _height_map.size_y; y += step) {
436  for (int x = 0; x <= _height_map.size_x; x += step) {
437  _height_map.height(x, y) += RandomHeight(amplitude);
438  }
439  }
440  }
441 }
442 
444 static void HeightMapGetMinMaxAvg(height_t *min_ptr, height_t *max_ptr, height_t *avg_ptr)
445 {
446  height_t h_min, h_max, h_avg, *h;
447  int64 h_accu = 0;
448  h_min = h_max = _height_map.height(0, 0);
449 
450  /* Get h_min, h_max and accumulate heights into h_accu */
452  if (*h < h_min) h_min = *h;
453  if (*h > h_max) h_max = *h;
454  h_accu += *h;
455  }
456 
457  /* Get average height */
458  h_avg = (height_t)(h_accu / (_height_map.size_x * _height_map.size_y));
459 
460  /* Return required results */
461  if (min_ptr != NULL) *min_ptr = h_min;
462  if (max_ptr != NULL) *max_ptr = h_max;
463  if (avg_ptr != NULL) *avg_ptr = h_avg;
464 }
465 
467 static int *HeightMapMakeHistogram(height_t h_min, height_t h_max, int *hist_buf)
468 {
469  int *hist = hist_buf - h_min;
470  height_t *h;
471 
472  /* Count the heights and fill the histogram */
474  assert(*h >= h_min);
475  assert(*h <= h_max);
476  hist[*h]++;
477  }
478  return hist;
479 }
480 
482 static void HeightMapSineTransform(height_t h_min, height_t h_max)
483 {
484  height_t *h;
485 
487  double fheight;
488 
489  if (*h < h_min) continue;
490 
491  /* Transform height into 0..1 space */
492  fheight = (double)(*h - h_min) / (double)(h_max - h_min);
493  /* Apply sine transform depending on landscape type */
495  case LT_TOYLAND:
496  case LT_TEMPERATE:
497  /* Move and scale 0..1 into -1..+1 */
498  fheight = 2 * fheight - 1;
499  /* Sine transform */
500  fheight = sin(fheight * M_PI_2);
501  /* Transform it back from -1..1 into 0..1 space */
502  fheight = 0.5 * (fheight + 1);
503  break;
504 
505  case LT_ARCTIC:
506  {
507  /* Arctic terrain needs special height distribution.
508  * Redistribute heights to have more tiles at highest (75%..100%) range */
509  double sine_upper_limit = 0.75;
510  double linear_compression = 2;
511  if (fheight >= sine_upper_limit) {
512  /* Over the limit we do linear compression up */
513  fheight = 1.0 - (1.0 - fheight) / linear_compression;
514  } else {
515  double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
516  /* Get 0..sine_upper_limit into -1..1 */
517  fheight = 2.0 * fheight / sine_upper_limit - 1.0;
518  /* Sine wave transform */
519  fheight = sin(fheight * M_PI_2);
520  /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
521  fheight = 0.5 * (fheight + 1.0) * m;
522  }
523  }
524  break;
525 
526  case LT_TROPIC:
527  {
528  /* Desert terrain needs special height distribution.
529  * Half of tiles should be at lowest (0..25%) heights */
530  double sine_lower_limit = 0.5;
531  double linear_compression = 2;
532  if (fheight <= sine_lower_limit) {
533  /* Under the limit we do linear compression down */
534  fheight = fheight / linear_compression;
535  } else {
536  double m = sine_lower_limit / linear_compression;
537  /* Get sine_lower_limit..1 into -1..1 */
538  fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
539  /* Sine wave transform */
540  fheight = sin(fheight * M_PI_2);
541  /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
542  fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
543  }
544  }
545  break;
546 
547  default:
548  NOT_REACHED();
549  break;
550  }
551  /* Transform it back into h_min..h_max space */
552  *h = (height_t)(fheight * (h_max - h_min) + h_min);
553  if (*h < 0) *h = I2H(0);
554  if (*h >= h_max) *h = h_max - 1;
555  }
556 }
557 
574 static void HeightMapCurves(uint level)
575 {
576  int mh = TGPGetMaxHeight();
577 
579  struct control_point_t {
580  height_t x;
581  height_t y;
582  };
583  /* Scaled curve maps; value is in height_ts. */
584 #define F(fraction) ((height_t)(fraction * mh))
585  const control_point_t curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.6 / 3), F(0.1) }, { F(2.4 / 3), F(0.4 / 3) }, { F(1.0), F(0.4) } };
586  const control_point_t curve_map_2[] = { { F(0.0), F(0.0) }, { F(0.2 / 3), F(0.1) }, { F(1.6 / 3), F(0.4 / 3) }, { F(2.4 / 3), F(0.8 / 3) }, { F(1.0), F(0.6) } };
587  const control_point_t curve_map_3[] = { { F(0.0), F(0.0) }, { F(0.2 / 3), F(0.1) }, { F(1.6 / 3), F(0.8 / 3) }, { F(2.4 / 3), F(1.8 / 3) }, { F(1.0), F(0.8) } };
588  const control_point_t curve_map_4[] = { { F(0.0), F(0.0) }, { F(0.2 / 3), F(0.1) }, { F(1.2 / 3), F(0.9 / 3) }, { F(2.0 / 3), F(2.4 / 3) } , { F(5.5 / 6), F(0.99) }, { F(1.0), F(0.99) } };
589 #undef F
590 
592  struct control_point_list_t {
593  size_t length;
594  const control_point_t *list;
595  };
596  const control_point_list_t curve_maps[] = {
597  { lengthof(curve_map_1), curve_map_1 },
598  { lengthof(curve_map_2), curve_map_2 },
599  { lengthof(curve_map_3), curve_map_3 },
600  { lengthof(curve_map_4), curve_map_4 },
601  };
602 
603  height_t ht[lengthof(curve_maps)];
604  MemSetT(ht, 0, lengthof(ht));
605 
606  /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
607  float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
608  uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
609  uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
610  byte *c = AllocaM(byte, sx * sy);
611 
612  for (uint i = 0; i < sx * sy; i++) {
613  c[i] = Random() % lengthof(curve_maps);
614  }
615 
616  /* Apply curves */
617  for (int x = 0; x < _height_map.size_x; x++) {
618 
619  /* Get our X grid positions and bi-linear ratio */
620  float fx = (float)(sx * x) / _height_map.size_x + 1.0f;
621  uint x1 = (uint)fx;
622  uint x2 = x1;
623  float xr = 2.0f * (fx - x1) - 1.0f;
624  xr = sin(xr * M_PI_2);
625  xr = sin(xr * M_PI_2);
626  xr = 0.5f * (xr + 1.0f);
627  float xri = 1.0f - xr;
628 
629  if (x1 > 0) {
630  x1--;
631  if (x2 >= sx) x2--;
632  }
633 
634  for (int y = 0; y < _height_map.size_y; y++) {
635 
636  /* Get our Y grid position and bi-linear ratio */
637  float fy = (float)(sy * y) / _height_map.size_y + 1.0f;
638  uint y1 = (uint)fy;
639  uint y2 = y1;
640  float yr = 2.0f * (fy - y1) - 1.0f;
641  yr = sin(yr * M_PI_2);
642  yr = sin(yr * M_PI_2);
643  yr = 0.5f * (yr + 1.0f);
644  float yri = 1.0f - yr;
645 
646  if (y1 > 0) {
647  y1--;
648  if (y2 >= sy) y2--;
649  }
650 
651  uint corner_a = c[x1 + sx * y1];
652  uint corner_b = c[x1 + sx * y2];
653  uint corner_c = c[x2 + sx * y1];
654  uint corner_d = c[x2 + sx * y2];
655 
656  /* Bitmask of which curve maps are chosen, so that we do not bother
657  * calculating a curve which won't be used. */
658  uint corner_bits = 0;
659  corner_bits |= 1 << corner_a;
660  corner_bits |= 1 << corner_b;
661  corner_bits |= 1 << corner_c;
662  corner_bits |= 1 << corner_d;
663 
664  height_t *h = &_height_map.height(x, y);
665 
666  /* Apply all curve maps that are used on this tile. */
667  for (uint t = 0; t < lengthof(curve_maps); t++) {
668  if (!HasBit(corner_bits, t)) continue;
669 
670  const control_point_t *cm = curve_maps[t].list;
671  for (uint i = 0; i < curve_maps[t].length - 1; i++) {
672  const control_point_t &p1 = cm[i];
673  const control_point_t &p2 = cm[i + 1];
674 
675  if (*h >= p1.x && *h < p2.x) {
676  ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
677  break;
678  }
679  }
680  }
681 
682  /* Apply interpolation of curve map results. */
683  *h = (height_t)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
684  }
685  }
686 }
687 
689 static void HeightMapAdjustWaterLevel(amplitude_t water_percent, height_t h_max_new)
690 {
691  height_t h_min, h_max, h_avg, h_water_level;
692  int64 water_tiles, desired_water_tiles;
693  height_t *h;
694  int *hist;
695 
696  HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
697 
698  /* Allocate histogram buffer and clear its cells */
699  int *hist_buf = CallocT<int>(h_max - h_min + 1);
700  /* Fill histogram */
701  hist = HeightMapMakeHistogram(h_min, h_max, hist_buf);
702 
703  /* How many water tiles do we want? */
704  desired_water_tiles = A2I(((int64)water_percent) * (int64)(_height_map.size_x * _height_map.size_y));
705 
706  /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
707  for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
708  water_tiles += hist[h_water_level];
709  if (water_tiles >= desired_water_tiles) break;
710  }
711 
712  /* We now have the proper water level value.
713  * Transform the height map into new (normalized) height map:
714  * values from range: h_min..h_water_level will become negative so it will be clamped to 0
715  * values from range: h_water_level..h_max are transformed into 0..h_max_new
716  * where h_max_new is depending on terrain type and map size.
717  */
719  /* Transform height from range h_water_level..h_max into 0..h_max_new range */
720  *h = (height_t)(((int)h_max_new) * (*h - h_water_level) / (h_max - h_water_level)) + I2H(1);
721  /* Make sure all values are in the proper range (0..h_max_new) */
722  if (*h < 0) *h = I2H(0);
723  if (*h >= h_max_new) *h = h_max_new - 1;
724  }
725 
726  free(hist_buf);
727 }
728 
729 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
730 
751 static void HeightMapCoastLines(uint8 water_borders)
752 {
754  const int margin = 4;
755  int y, x;
756  double max_x;
757  double max_y;
758 
759  /* Lower to sea level */
760  for (y = 0; y <= _height_map.size_y; y++) {
761  if (HasBit(water_borders, BORDER_NE)) {
762  /* Top right */
763  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);
764  max_x = max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
765  if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
766  for (x = 0; x < max_x; x++) {
767  _height_map.height(x, y) = 0;
768  }
769  }
770 
771  if (HasBit(water_borders, BORDER_SW)) {
772  /* Bottom left */
773  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);
774  max_x = max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
775  if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
776  for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
777  _height_map.height(x, y) = 0;
778  }
779  }
780  }
781 
782  /* Lower to sea level */
783  for (x = 0; x <= _height_map.size_x; x++) {
784  if (HasBit(water_borders, BORDER_NW)) {
785  /* Top left */
786  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);
787  max_y = max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
788  if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
789  for (y = 0; y < max_y; y++) {
790  _height_map.height(x, y) = 0;
791  }
792  }
793 
794  if (HasBit(water_borders, BORDER_SE)) {
795  /* Bottom right */
796  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);
797  max_y = max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
798  if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
799  for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
800  _height_map.height(x, y) = 0;
801  }
802  }
803  }
804 }
805 
807 static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
808 {
809  const int max_coast_dist_from_edge = 35;
810  const int max_coast_Smooth_depth = 35;
811 
812  int x, y;
813  int ed; // coast distance from edge
814  int depth;
815 
816  height_t h_prev = I2H(1);
817  height_t h;
818 
819  assert(IsValidXY(org_x, org_y));
820 
821  /* Search for the coast (first non-water tile) */
822  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++) {
823  /* Coast found? */
824  if (_height_map.height(x, y) >= I2H(1)) break;
825 
826  /* Coast found in the neighborhood? */
827  if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
828 
829  /* Coast found in the neighborhood on the other side */
830  if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
831  }
832 
833  /* Coast found or max_coast_dist_from_edge has been reached.
834  * Soften the coast slope */
835  for (depth = 0; IsValidXY(x, y) && depth <= max_coast_Smooth_depth; depth++, x += dir_x, y += dir_y) {
836  h = _height_map.height(x, y);
837  h = min(h, h_prev + (4 + depth)); // coast softening formula
838  _height_map.height(x, y) = h;
839  h_prev = h;
840  }
841 }
842 
844 static void HeightMapSmoothCoasts(uint8 water_borders)
845 {
846  int x, y;
847  /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
848  for (x = 0; x < _height_map.size_x; x++) {
849  if (HasBit(water_borders, BORDER_NW)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
850  if (HasBit(water_borders, BORDER_SE)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
851  }
852  /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
853  for (y = 0; y < _height_map.size_y; y++) {
854  if (HasBit(water_borders, BORDER_NE)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
855  if (HasBit(water_borders, BORDER_SW)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
856  }
857 }
858 
866 static void HeightMapSmoothSlopes(height_t dh_max)
867 {
868  for (int y = 0; y <= (int)_height_map.size_y; y++) {
869  for (int x = 0; x <= (int)_height_map.size_x; x++) {
870  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;
871  if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
872  }
873  }
874  for (int y = _height_map.size_y; y >= 0; y--) {
875  for (int x = _height_map.size_x; x >= 0; x--) {
876  height_t h_max = min(_height_map.height(x < _height_map.size_x ? x + 1 : x, y), _height_map.height(x, y < _height_map.size_y ? y + 1 : y)) + dh_max;
877  if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
878  }
879  }
880 }
881 
889 static void HeightMapNormalize()
890 {
891  int sea_level_setting = _settings_game.difficulty.quantity_sea_lakes;
892  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;
893  const height_t h_max_new = TGPGetMaxHeight();
894  const height_t roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
895 
896  HeightMapAdjustWaterLevel(water_percent, h_max_new);
897 
899  if (water_borders == BORDERS_RANDOM) water_borders = GB(Random(), 0, 4);
900 
901  HeightMapCoastLines(water_borders);
902  HeightMapSmoothSlopes(roughness);
903 
904  HeightMapSmoothCoasts(water_borders);
905  HeightMapSmoothSlopes(roughness);
906 
907  HeightMapSineTransform(12, h_max_new);
908 
911  }
912 
914 }
915 
923 static double int_noise(const long x, const long y, const int prime)
924 {
925  long n = x + y * prime + _settings_game.game_creation.generation_seed;
926 
927  n = (n << 13) ^ n;
928 
929  /* Pseudo-random number generator, using several large primes */
930  return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
931 }
932 
933 
937 static inline double linear_interpolate(const double a, const double b, const double x)
938 {
939  return a + x * (b - a);
940 }
941 
942 
947 static double interpolated_noise(const double x, const double y, const int prime)
948 {
949  const int integer_X = (int)x;
950  const int integer_Y = (int)y;
951 
952  const double fractional_X = x - (double)integer_X;
953  const double fractional_Y = y - (double)integer_Y;
954 
955  const double v1 = int_noise(integer_X, integer_Y, prime);
956  const double v2 = int_noise(integer_X + 1, integer_Y, prime);
957  const double v3 = int_noise(integer_X, integer_Y + 1, prime);
958  const double v4 = int_noise(integer_X + 1, integer_Y + 1, prime);
959 
960  const double i1 = linear_interpolate(v1, v2, fractional_X);
961  const double i2 = linear_interpolate(v3, v4, fractional_X);
962 
963  return linear_interpolate(i1, i2, fractional_Y);
964 }
965 
966 
973 static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
974 {
975  double total = 0.0;
976 
977  for (int i = 0; i < 6; i++) {
978  const double frequency = (double)(1 << i);
979  const double amplitude = pow(p, (double)i);
980 
981  total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude;
982  }
983 
984  return total;
985 }
986 
987 
989 static void TgenSetTileHeight(TileIndex tile, int height)
990 {
991  SetTileHeight(tile, height);
992 
993  /* Only clear the tiles within the map area. */
994  if (IsInnerTile(tile)) {
995  MakeClear(tile, CLEAR_GRASS, 3);
996  }
997 }
998 
1007 {
1008  if (!AllocHeightMap()) return;
1010 
1012 
1014 
1016 
1018 
1019  /* First make sure the tiles at the north border are void tiles if needed. */
1021  for (int y = 0; y < _height_map.size_y - 1; y++) MakeVoid(_height_map.size_x * y);
1022  for (int x = 0; x < _height_map.size_x; x++) MakeVoid(x);
1023  }
1024 
1025  int max_height = H2I(TGPGetMaxHeight());
1026 
1027  /* Transfer height map into OTTD map */
1028  for (int y = 0; y < _height_map.size_y; y++) {
1029  for (int x = 0; x < _height_map.size_x; x++) {
1030  TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1031  }
1032  }
1033 
1035 
1036  FreeHeightMap();
1038 }