OpenTTD Source 20260311-master-g511d3794ce
tgp.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
141
142#include "stdafx.h"
143#include "clear_map.h"
144#include "void_map.h"
145#include "genworld.h"
146#include "core/random_func.hpp"
147#include "landscape_type.h"
148
149#include "safeguards.h"
150
152using Height = int16_t;
153static const int HEIGHT_DECIMAL_BITS = 4;
154
156using Amplitude = int;
157static const int AMPLITUDE_DECIMAL_BITS = 10;
158
161{
162 std::vector<Height> h;
163 /* Even though the sizes are always positive, there are many cases where
164 * X and Y need to be signed integers due to subtractions. */
165 int dim_x;
166 int size_x;
167 int size_y;
168
175 inline Height &height(uint x, uint y)
176 {
177 return h[x + y * dim_x];
178 }
179};
180
182static HeightMap _height_map = { {}, 0, 0, 0 };
183
189static Height I2H(int i)
190{
191 return i << HEIGHT_DECIMAL_BITS;
192}
193
199static int H2I(Height i)
200{
201 return i >> HEIGHT_DECIMAL_BITS;
202}
203
210{
211 return i >> (AMPLITUDE_DECIMAL_BITS - HEIGHT_DECIMAL_BITS);
212}
213
215static const int MAX_TGP_FREQUENCIES = 10;
216
217static constexpr int WATER_PERCENT_FACTOR = 1024;
218
220static const int64_t _water_percent[4] = {70, 170, 270, 420};
221
229{
230 if (_settings_game.difficulty.terrain_type == GenworldMaxHeight::Custom) {
231 /* TGP never reaches this height; this means that if a user inputs "2",
232 * it would create a flat map without the "+ 1". But that would
233 * overflow on "255". So we reduce it by 1 to get back in range. */
234 return I2H(_settings_game.game_creation.custom_terrain_type + 1) - 1;
235 }
236
247 static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
248 /* 64 128 256 512 1024 2048 4096 */
249 { 3, 3, 3, 3, 4, 5, 7 },
250 { 5, 7, 8, 9, 14, 19, 31 },
251 { 8, 9, 10, 15, 23, 37, 61 },
252 { 10, 11, 17, 19, 49, 63, 73 },
253 { 12, 19, 25, 31, 67, 75, 87 },
254 };
255
256 int map_size_bucket = std::min(Map::LogX(), Map::LogY()) - MIN_MAP_SIZE_BITS;
257 int max_height_from_table = max_height[to_underlying(_settings_game.difficulty.terrain_type)][map_size_bucket];
258
259 /* If there is a manual map height limit, clamp to it. */
260 if (_settings_game.construction.map_height_limit != 0) {
261 max_height_from_table = std::min<uint>(max_height_from_table, _settings_game.construction.map_height_limit);
262 }
263
264 return I2H(max_height_from_table);
265}
266
272{
273 return H2I(TGPGetMaxHeight());
274}
275
282static Amplitude GetAmplitude(int frequency)
283{
284 /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */
285 static const Amplitude amplitudes[][7] = {
286 /* lowest frequency ...... highest (every corner) */
287 {16000, 5600, 1968, 688, 240, 16, 16},
288 {24000, 12800, 6400, 2700, 1024, 128, 16},
289 {32000, 19200, 12800, 8000, 3200, 256, 64},
290 {48000, 24000, 19200, 16000, 8000, 512, 320},
291 };
292 /*
293 * Extrapolation factors for ranges before the table.
294 * The extrapolation is needed to account for the higher map heights. They need larger
295 * areas with a particular gradient so that we are able to create maps without too
296 * many steep slopes up to the wanted height level. It's definitely not perfect since
297 * it will bring larger rectangles with similar slopes which makes the rectangular
298 * behaviour of TGP more noticeable. However, these height differentiations cannot
299 * happen over much smaller areas; we basically double the "range" to give a similar
300 * slope for every doubling of map height.
301 */
302 static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
303
304 int smoothness = _settings_game.game_creation.tgen_smoothness;
305
306 /* Get the table index, and return that value if possible. */
307 int index = frequency - MAX_TGP_FREQUENCIES + static_cast<int>(std::size(amplitudes[smoothness]));
308 Amplitude amplitude = amplitudes[smoothness][std::max(0, index)];
309 if (index >= 0) return amplitude;
310
311 /* We need to extrapolate the amplitude. */
312 double extrapolation_factor = extrapolation_factors[smoothness];
313 int height_range = I2H(16);
314 do {
315 amplitude = (Amplitude)(extrapolation_factor * (double)amplitude);
316 height_range <<= 1;
317 index++;
318 } while (index < 0);
319
320 return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
321}
322
329static inline bool IsValidXY(int x, int y)
330{
331 return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
332}
333
334
338static inline void AllocHeightMap()
339{
340 assert(_height_map.h.empty());
341
342 _height_map.size_x = Map::SizeX();
343 _height_map.size_y = Map::SizeY();
344
345 /* Allocate memory block for height map row pointers */
346 size_t total_size = static_cast<size_t>(_height_map.size_x + 1) * (_height_map.size_y + 1);
347 _height_map.dim_x = _height_map.size_x + 1;
348 _height_map.h.resize(total_size);
349}
350
352static inline void FreeHeightMap()
353{
354 _height_map.h.clear();
355}
356
362static inline Height RandomHeight(Amplitude r_max)
363{
364 /* Spread height into range -r_max..+r_max */
365 return A2H(RandomRange(2 * r_max + 1) - r_max);
366}
367
375static void HeightMapGenerate()
376{
377 /* Trying to apply noise to uninitialized height map */
378 assert(!_height_map.h.empty());
379
380 int start = std::max(MAX_TGP_FREQUENCIES - (int)std::min(Map::LogX(), Map::LogY()), 0);
381 bool first = true;
382
383 for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
384 const Amplitude amplitude = GetAmplitude(frequency);
385
386 /* Ignore zero amplitudes; it means our map isn't height enough for this
387 * amplitude, so ignore it and continue with the next set of amplitude. */
388 if (amplitude == 0) continue;
389
390 const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
391
392 if (first) {
393 /* This is first round, we need to establish base heights with step = size_min */
394 for (int y = 0; y <= _height_map.size_y; y += step) {
395 for (int x = 0; x <= _height_map.size_x; x += step) {
396 Height height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
397 _height_map.height(x, y) = height;
398 }
399 }
400 first = false;
401 continue;
402 }
403
404 /* It is regular iteration round.
405 * Interpolate height values at odd x, even y tiles */
406 for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
407 for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
408 Height h00 = _height_map.height(x + 0 * step, y);
409 Height h02 = _height_map.height(x + 2 * step, y);
410 Height h01 = (h00 + h02) / 2;
411 _height_map.height(x + 1 * step, y) = h01;
412 }
413 }
414
415 /* Interpolate height values at odd y tiles */
416 for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
417 for (int x = 0; x <= _height_map.size_x; x += step) {
418 Height h00 = _height_map.height(x, y + 0 * step);
419 Height h20 = _height_map.height(x, y + 2 * step);
420 Height h10 = (h00 + h20) / 2;
421 _height_map.height(x, y + 1 * step) = h10;
422 }
423 }
424
425 /* Add noise for next higher frequency (smaller steps) */
426 for (int y = 0; y <= _height_map.size_y; y += step) {
427 for (int x = 0; x <= _height_map.size_x; x += step) {
428 _height_map.height(x, y) += RandomHeight(amplitude);
429 }
430 }
431 }
432}
433
441static int *HeightMapMakeHistogram(Height h_min, [[maybe_unused]] Height h_max, int *hist_buf)
442{
443 int *hist = hist_buf - h_min;
444
445 /* Count the heights and fill the histogram */
446 for (const Height &h : _height_map.h) {
447 assert(h >= h_min);
448 assert(h <= h_max);
449 hist[h]++;
450 }
451 return hist;
452}
453
459static double SineTransformLowlands(double fheight)
460{
461 double height = fheight;
462
463 /* Half of tiles should be at lowest (0..25%) heights */
464 double sine_lower_limit = 0.5;
465 double linear_compression = 2;
466 if (height <= sine_lower_limit) {
467 /* Under the limit we do linear compression down */
468 height = height / linear_compression;
469 } else {
470 double m = sine_lower_limit / linear_compression;
471 /* Get sine_lower_limit..1 into -1..1 */
472 height = 2.0 * ((height - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
473 /* Sine wave transform */
474 height = sin(height * M_PI_2);
475 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
476 height = 0.5 * ((1.0 - m) * height + (1.0 + m));
477 }
478
479 return height;
480}
481
487static double SineTransformNormal(double &fheight)
488{
489 double height = fheight;
490
491 /* Move and scale 0..1 into -1..+1 */
492 height = 2 * height - 1;
493 /* Sine transform */
494 height = sin(height * M_PI_2);
495 /* Transform it back from -1..1 into 0..1 space */
496 height = 0.5 * (height + 1);
497
498 return height;
499}
500
506static double SineTransformPlateaus(double &fheight)
507{
508 double height = fheight;
509
510 /* Redistribute heights to have more tiles at highest (75%..100%) range */
511 double sine_upper_limit = 0.75;
512 double linear_compression = 2;
513 if (height >= sine_upper_limit) {
514 /* Over the limit we do linear compression up */
515 height = 1.0 - (1.0 - height) / linear_compression;
516 } else {
517 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
518 /* Get 0..sine_upper_limit into -1..1 */
519 height = 2.0 * height / sine_upper_limit - 1.0;
520 /* Sine wave transform */
521 height = sin(height * M_PI_2);
522 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
523 height = 0.5 * (height + 1.0) * m;
524 }
525
526 return height;
527}
528
534static void HeightMapSineTransform(Height h_min, Height h_max)
535{
536 for (Height &h : _height_map.h) {
537 double fheight;
538
539 if (h < h_min) continue;
540
541 /* Transform height into 0..1 space */
542 fheight = (double)(h - h_min) / (double)(h_max - h_min);
543
544 switch (_settings_game.game_creation.average_height) {
545 case GenworldAverageHeight::Auto:
546 /* Apply sine transform depending on landscape type */
547 switch (_settings_game.game_creation.landscape) {
548 case LandscapeType::Temperate: fheight = SineTransformNormal(fheight); break;
549 case LandscapeType::Tropic: fheight = SineTransformLowlands(fheight); break;
550 case LandscapeType::Arctic: fheight = SineTransformPlateaus(fheight); break;
551 case LandscapeType::Toyland: fheight = SineTransformNormal(fheight); break;
552 default: NOT_REACHED();
553 }
554 break;
555
556 case GenworldAverageHeight::Lowlands: fheight = SineTransformLowlands(fheight); break;
557 case GenworldAverageHeight::Normal: fheight = SineTransformNormal(fheight); break;
558 case GenworldAverageHeight::Plateaus: fheight = SineTransformPlateaus(fheight); break;
559 default: NOT_REACHED();
560 }
561
562 /* Transform it back into h_min..h_max space */
563 h = static_cast<Height>(fheight * (h_max - h_min) + h_min);
564 if (h < 0) h = I2H(0);
565 if (h >= h_max) h = h_max - 1;
566 }
567}
568
585static void HeightMapCurves(uint level)
586{
587 Height mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only
588
590 struct ControlPoint {
591 Height x;
592 Height y;
593 };
595#define F(fraction) ((Height)(fraction * mh))
596 const ControlPoint curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } };
597 const ControlPoint curve_map_2[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.13) }, { F(0.8), F(0.27) }, { F(1.0), F(0.6) } };
598 const ControlPoint curve_map_3[] = { { F(0.0), F(0.0) }, { F(0.53), F(0.27) }, { F(0.8), F(0.57) }, { F(1.0), F(0.8) } };
599 const ControlPoint curve_map_4[] = { { F(0.0), F(0.0) }, { F(0.4), F(0.3) }, { F(0.7), F(0.8) }, { F(0.92), F(0.99) }, { F(1.0), F(0.99) } };
600#undef F
601
602 const std::span<const ControlPoint> curve_maps[] = { curve_map_1, curve_map_2, curve_map_3, curve_map_4 };
603
604 std::array<Height, std::size(curve_maps)> 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 std::vector<uint8_t> c(static_cast<size_t>(sx) * sy);
611
612 for (uint i = 0; i < sx * sy; i++) {
613 c[i] = RandomRange(static_cast<uint32_t>(std::size(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 *h = &_height_map.height(x, y);
665
666 /* Do not touch sea level */
667 if (*h < I2H(1)) continue;
668
669 /* Only scale above sea level */
670 *h -= I2H(1);
671
672 /* Apply all curve maps that are used on this tile. */
673 for (size_t t = 0; t < std::size(curve_maps); t++) {
674 if (!HasBit(corner_bits, static_cast<uint8_t>(t))) continue;
675
676 [[maybe_unused]] bool found = false;
677 auto &cm = curve_maps[t];
678 for (size_t i = 0; i < cm.size() - 1; i++) {
679 const ControlPoint &p1 = cm[i];
680 const ControlPoint &p2 = cm[i + 1];
681
682 if (*h >= p1.x && *h < p2.x) {
683 ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
684#ifdef WITH_ASSERT
685 found = true;
686#endif
687 break;
688 }
689 }
690 assert(found);
691 }
692
693 /* Apply interpolation of curve map results. */
694 *h = (Height)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
695
696 /* Re-add sea level */
697 *h += I2H(1);
698 }
699 }
700}
701
707static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new)
708{
709 Height h_water_level;
710 int64_t water_tiles, desired_water_tiles;
711 int *hist;
712
713 auto [h_min, h_max] = std::ranges::minmax(_height_map.h);
714
715 /* Allocate histogram buffer and clear its cells */
716 std::vector<int> hist_buf(h_max - h_min + 1);
717 /* Fill histogram */
718 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf.data());
719
720 /* How many water tiles do we want? */
721 desired_water_tiles = water_percent * _height_map.size_x * _height_map.size_y / WATER_PERCENT_FACTOR;
722
723 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
724 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
725 water_tiles += hist[h_water_level];
726 if (water_tiles >= desired_water_tiles) break;
727 }
728
729 /* We now have the proper water level value.
730 * Transform the height map into new (normalized) height map:
731 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
732 * values from range: h_water_level..h_max are transformed into 0..h_max_new
733 * where h_max_new is depending on terrain type and map size.
734 */
735 for (Height &h : _height_map.h) {
736 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
737 h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1);
738 /* Make sure all values are in the proper range (0..h_max_new) */
739 if (h < 0) h = I2H(0);
740 if (h >= h_max_new) h = h_max_new - 1;
741 }
742}
743
744static double PerlinCoastNoise2D(const double x, const double y, const double p, const int prime);
745
761static void HeightMapCoastLines(BorderFlags water_borders)
762{
763 /* Both map dimensions are powers of 2. Division by smaller powers of 2 will always result in an integer. */
764 const int smallest_size = std::min(_height_map.size_x, _height_map.size_y);
765 const int map_ratio = std::max(_height_map.size_x, _height_map.size_y) / smallest_size;
766
767 /* More jagged perlin noise is used to create inlets and craggier features. It scales with map size and ratio and quickly
768 * reaches the limit of 64. It scales both by the shortest side and the map ratio to try and balance variation in the
769 * coastline and the amount of water on the map.
770 */
771 const int jagged_distance = std::min(12 + (smallest_size * smallest_size / 4096) + std::min(map_ratio, 16), 64);
772
773 /* Smoother perlin noise is used to add more depth to the coastline as the smallest edge increases in length */
774 const int smooth_distance = std::min(smallest_size / 32, 32);
775
776 /* Function to get the distance from the edge at x (the coastline is actually 1D noise).
777 * p1, p2, p3 are small prime numbers so the sequences aren't identical.
778 */
779 auto get_depth = [&](int x, int p1, int p2, int p3) {
780 return 2 // we ensure a margin of two water tiles at the edge of the map
781 + smooth_distance * (1 + PerlinCoastNoise2D(x, x, 0.2, p1)) // +1 rather than abs reduces the number of V shaped inlets
782 + jagged_distance * abs(PerlinCoastNoise2D(x, x, 0.5, p2))
783 + 8 * abs(PerlinCoastNoise2D(x, x, 0.8, p3)); // Some unscaled jaggedness to breakup anything smoothed by scaling
784 };
785
786 int y, x;
787
788 /* Lower to sea level */
789 for (y = 0; y <= _height_map.size_y; y++) {
790 if (water_borders.Test(BorderFlag::NorthEast)) {
791 /* Top right */
792 for (x = 0; x < get_depth(y, 67, 179, 53); x++) {
793 _height_map.height(x, y) = 0;
794 }
795 }
796
797 if (water_borders.Test(BorderFlag::SouthWest)) {
798 /* Bottom left */
799 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - get_depth(y, 199, 67, 101)); x--) {
800 _height_map.height(x, y) = 0;
801 }
802 }
803 }
804
805 /* Lower to sea level */
806 for (x = 0; x <= _height_map.size_x; x++) {
807 if (water_borders.Test(BorderFlag::NorthWest)) {
808 /* Top left */
809 for (y = 0; y < get_depth(x, 179, 211, 167); y++) {
810 _height_map.height(x, y) = 0;
811 }
812 }
813
814 if (water_borders.Test(BorderFlag::SouthEast)) {
815 /* Bottom right */
816 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - get_depth(x, 101, 193, 71)); y--) {
817 _height_map.height(x, y) = 0;
818 }
819 }
820 }
821}
822
830static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
831{
832 const int max_coast_dist_from_edge = 100;
833 const int max_coast_smooth_depth = 35;
834
835 int x, y;
836 int ed; // coast distance from edge
837 int depth;
838
839 Height h_prev = I2H(1);
840 Height h;
841
842 assert(IsValidXY(org_x, org_y));
843
844 /* Search for the coast (first non-water tile) */
845 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++) {
846 /* Coast found? */
847 if (_height_map.height(x, y) >= I2H(1)) break;
848
849 /* Coast found in the neighbourhood? */
850 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
851
852 /* Coast found in the neighbourhood on the other side */
853 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
854 }
855
856 /* Coast found or max_coast_dist_from_edge has been reached.
857 * Soften the coast slope */
858 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_smooth_depth; depth++, x += dir_x, y += dir_y) {
859 h = _height_map.height(x, y);
860 h = static_cast<Height>(std::min<uint>(h, h_prev + (4 + depth))); // coast softening formula
861 _height_map.height(x, y) = h;
862 h_prev = h;
863 }
864}
865
870static void HeightMapSmoothCoasts(BorderFlags water_borders)
871{
872 int x, y;
873 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
874 for (x = 0; x < _height_map.size_x; x++) {
875 if (water_borders.Test(BorderFlag::NorthWest)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
876 if (water_borders.Test(BorderFlag::SouthEast)) HeightMapSmoothCoastInDirection(x, _height_map.size_y - 1, 0, -1);
877 }
878 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
879 for (y = 0; y < _height_map.size_y; y++) {
880 if (water_borders.Test(BorderFlag::NorthEast)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
881 if (water_borders.Test(BorderFlag::SouthWest)) HeightMapSmoothCoastInDirection(_height_map.size_x - 1, y, -1, 0);
882 }
883}
884
893static void HeightMapSmoothSlopes(Height dh_max)
894{
895 for (int y = 0; y <= (int)_height_map.size_y; y++) {
896 for (int x = 0; x <= (int)_height_map.size_x; x++) {
897 Height h_max = std::min(_height_map.height(x > 0 ? x - 1 : x, y), _height_map.height(x, y > 0 ? y - 1 : y)) + dh_max;
898 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
899 }
900 }
901 for (int y = _height_map.size_y; y >= 0; y--) {
902 for (int x = _height_map.size_x; x >= 0; x--) {
903 Height h_max = std::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;
904 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
905 }
906 }
907}
908
917{
918 const int64_t water_percent = _settings_game.difficulty.quantity_sea_lakes != CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY ? _water_percent[_settings_game.difficulty.quantity_sea_lakes] : _settings_game.game_creation.custom_sea_level * WATER_PERCENT_FACTOR / 100;
919 const Height h_max_new = TGPGetMaxHeight();
920 const Height roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
921
922 HeightMapAdjustWaterLevel(water_percent, h_max_new);
923
924 BorderFlags water_borders = _settings_game.construction.freeform_edges ? _settings_game.game_creation.water_borders : BORDERFLAGS_ALL;
925 if (water_borders == BorderFlag::Random) water_borders = static_cast<BorderFlags>(GB(Random(), 0, 4));
926
927 HeightMapCoastLines(water_borders);
928 HeightMapSmoothSlopes(roughness);
929
930 HeightMapSmoothCoasts(water_borders);
931 HeightMapSmoothSlopes(roughness);
932
933 HeightMapSineTransform(I2H(1), h_max_new);
934
935 if (_settings_game.game_creation.variety > 0) {
936 HeightMapCurves(_settings_game.game_creation.variety);
937 }
938}
939
951static double IntNoise(const long x, const long y, const int prime)
952{
953 long n = x + y * prime + _settings_game.game_creation.generation_seed;
954
955 n = (n << 13) ^ n;
956
957 /* Pseudo-random number generator, using several large primes */
958 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
959}
960
961
969static inline double LinearInterpolate(const double a, const double b, const double x)
970{
971 return a + x * (b - a);
972}
973
974
983static double InterpolatedNoise(const double x, const double y, const int prime)
984{
985 const int integer_x = (int)x;
986 const int integer_y = (int)y;
987
988 const double fractional_x = x - (double)integer_x;
989 const double fractional_y = y - (double)integer_y;
990
991 const double v1 = IntNoise(integer_x, integer_y, prime);
992 const double v2 = IntNoise(integer_x + 1, integer_y, prime);
993 const double v3 = IntNoise(integer_x, integer_y + 1, prime);
994 const double v4 = IntNoise(integer_x + 1, integer_y + 1, prime);
995
996 const double i1 = LinearInterpolate(v1, v2, fractional_x);
997 const double i2 = LinearInterpolate(v3, v4, fractional_x);
998
999 return LinearInterpolate(i1, i2, fractional_y);
1000}
1001
1013static double PerlinCoastNoise2D(const double x, const double y, const double p, const int prime)
1014{
1015 constexpr int OCTAVES = 6;
1016 constexpr double INITIAL_FREQUENCY = 1 << OCTAVES;
1017
1018 double total = 0.0;
1019 double max_value = 0.0;
1020 double frequency = 1.0 / INITIAL_FREQUENCY;
1021 double amplitude = 1.0;
1022 for (int i = 0; i < OCTAVES; i++) {
1023 total += InterpolatedNoise(x * frequency, y * frequency, prime) * amplitude;
1024 max_value += amplitude;
1025
1026 frequency *= 2.0;
1027 amplitude *= p;
1028 }
1029
1030 /* Bringing the output range into [-1, 1] makes it much easier to reason with */
1031 return total / max_value;
1032}
1033
1034
1040static void TgenSetTileHeight(TileIndex tile, int height)
1041{
1042 SetTileHeight(tile, height);
1043
1044 /* Only clear the tiles within the map area. */
1045 if (IsInnerTile(tile)) {
1046 MakeClear(tile, ClearGround::Grass, 3);
1047 }
1048}
1049
1058{
1061
1063
1065
1067
1069
1070 /* First make sure the tiles at the north border are void tiles if needed. */
1071 if (_settings_game.construction.freeform_edges) {
1072 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
1073 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
1074 }
1075
1076 int max_height = H2I(TGPGetMaxHeight());
1077
1078 /* Transfer height map into OTTD map */
1079 for (int y = 0; y < _height_map.size_y; y++) {
1080 for (int x = 0; x < _height_map.size_x; x++) {
1081 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1082 }
1083 }
1084
1085 FreeHeightMap();
1087}
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Map accessors for 'clear' tiles.
@ Grass
Plain grass with dirt transition (0-3).
Definition clear_map.h:22
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition clear_map.h:253
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted.
Definition genworld.cpp:253
Functions related to world/map generation.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
static const uint CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY
Value for custom sea level in difficulty settings.
Definition genworld.h:46
@ GWP_LANDSCAPE
Create the landscape.
Definition genworld.h:61
Types related to the landscape.
static constexpr BorderFlags BORDERFLAGS_ALL
Border on all sides.
@ Arctic
Landscape with snow levels.
@ Toyland
Landscape with funky industries and vehicles.
@ Tropic
Landscape with distinct rainforests and deserts,.
@ Temperate
Base landscape.
@ NorthWest
Border on North West.
@ Random
Randomise borders.
@ NorthEast
Border on North East.
@ SouthEast
Border on South East.
@ SouthWest
Border on South West.
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static const uint MIN_MAP_SIZE_BITS
Minimal and maximal map width and height.
Definition map_type.h:37
static const uint MAX_MAP_SIZE_BITS
Maximal size of map is equal to 2 ^ MAX_MAP_SIZE_BITS.
Definition map_type.h:38
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
Pseudo random number generator.
uint32_t RandomRange(uint32_t limit, const std::source_location location=std::source_location::current())
Pick a random number between 0 and limit - 1, inclusive.
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
Definition of base types and functions in a cross-platform compatible way.
Height map - allocated array of heights (Map::SizeX() + 1) * (Map::SizeY() + 1).
Definition tgp.cpp:161
int size_y
Map::SizeY().
Definition tgp.cpp:167
int size_x
Map::SizeX().
Definition tgp.cpp:166
std::vector< Height > h
array of heights
Definition tgp.cpp:162
int dim_x
height map size_x Map::SizeX() + 1
Definition tgp.cpp:165
Height & height(uint x, uint y)
Height map accessor.
Definition tgp.cpp:175
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:262
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:271
static uint LogX()
Logarithm of the map size along the X side.
Definition map_func.h:243
static uint LogY()
Logarithm of the map size along the y side.
Definition map_func.h:253
static double SineTransformNormal(double &fheight)
Adjust the landscape to create normal average height (temperate and toyland landscapes).
Definition tgp.cpp:487
static Height RandomHeight(Amplitude r_max)
Generates new random height in given amplitude (generated numbers will range from - amplitude to + am...
Definition tgp.cpp:362
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.
Definition tgp.cpp:830
static Height A2H(Amplitude i)
Convert Amplitude to fixed point Height.
Definition tgp.cpp:209
static void HeightMapGenerate()
Base Perlin noise generator - fills height map with raw Perlin noise.
Definition tgp.cpp:375
static Height TGPGetMaxHeight()
Gets the maximum allowed height while generating a map based on mapsize, terraintype,...
Definition tgp.cpp:228
static double LinearInterpolate(const double a, const double b, const double x)
This routine determines the interpolated value between a and b.
Definition tgp.cpp:969
static void HeightMapCoastLines(BorderFlags water_borders)
This routine sculpts in from the edge a random amount, again from Perlin sequences,...
Definition tgp.cpp:761
static Height I2H(int i)
Convert tile height to fixed point Height.
Definition tgp.cpp:189
static int H2I(Height i)
Convert fixed point Height to tile height.
Definition tgp.cpp:199
static double SineTransformPlateaus(double &fheight)
Adjust the landscape to create plateaus on average (arctic landscape).
Definition tgp.cpp:506
static void HeightMapSmoothSlopes(Height dh_max)
This routine provides the essential cleanup necessary before OTTD can display the terrain.
Definition tgp.cpp:893
static double PerlinCoastNoise2D(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 par...
Definition tgp.cpp:1013
static const int64_t _water_percent[4]
Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes.
Definition tgp.cpp:220
int16_t Height
Fixed point type for heights.
Definition tgp.cpp:152
static Amplitude GetAmplitude(int frequency)
Get the amplitude associated with the currently selected smoothness and maximum height level.
Definition tgp.cpp:282
static int * HeightMapMakeHistogram(Height h_min, Height h_max, int *hist_buf)
Create histogram and return pointer to its base point - to the count of zero heights.
Definition tgp.cpp:441
static void FreeHeightMap()
Free height map.
Definition tgp.cpp:352
int Amplitude
Fixed point array for amplitudes.
Definition tgp.cpp:156
uint GetEstimationTGPMapHeight()
Get an overestimation of the highest peak TGP wants to generate.
Definition tgp.cpp:271
static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new)
Adjusts heights in height map to contain required amount of water tiles.
Definition tgp.cpp:707
static double IntNoise(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 gen...
Definition tgp.cpp:951
static double InterpolatedNoise(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 surrou...
Definition tgp.cpp:983
static void HeightMapSineTransform(Height h_min, Height h_max)
Applies sine wave redistribution onto height map.
Definition tgp.cpp:534
static HeightMap _height_map
Global height map instance.
Definition tgp.cpp:182
static void HeightMapNormalize()
Height map terraform post processing:
Definition tgp.cpp:916
static void HeightMapSmoothCoasts(BorderFlags water_borders)
Smooth coasts by modulating height of tiles close to map edges with cosine of distance from edge.
Definition tgp.cpp:870
static bool IsValidXY(int x, int y)
Check if a X/Y set are within the map.
Definition tgp.cpp:329
static const int MAX_TGP_FREQUENCIES
Maximum number of TGP noise frequencies.
Definition tgp.cpp:215
static void TgenSetTileHeight(TileIndex tile, int height)
A small helper function to initialize the terrain.
Definition tgp.cpp:1040
void GenerateTerrainPerlin()
The main new land generator using Perlin noise.
Definition tgp.cpp:1057
static double SineTransformLowlands(double fheight)
Adjust the landscape to create lowlands on average (tropic landscape).
Definition tgp.cpp:459
static void HeightMapCurves(uint level)
Additional map variety is provided by applying different curve maps to different parts of the map.
Definition tgp.cpp:585
static void AllocHeightMap()
Allocate array of (Map::SizeX() + 1) * (Map::SizeY() + 1) heights and init the _height_map structure ...
Definition tgp.cpp:338
bool IsInnerTile(Tile tile)
Check if a tile is within the map (not a border).
Definition tile_map.h:109
void SetTileHeight(Tile tile, uint height)
Sets the height of a tile.
Definition tile_map.h:57
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;).
Definition void_map.h:19