OpenTTD Source 20260129-master-g2bb01bd0e4
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
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
185static Height I2H(int i)
186{
187 return i << HEIGHT_DECIMAL_BITS;
188}
189
191static int H2I(Height i)
192{
193 return i >> HEIGHT_DECIMAL_BITS;
194}
195
198{
199 return i >> (AMPLITUDE_DECIMAL_BITS - HEIGHT_DECIMAL_BITS);
200}
201
203static const int MAX_TGP_FREQUENCIES = 10;
204
205static constexpr int WATER_PERCENT_FACTOR = 1024;
206
208static const int64_t _water_percent[4] = {70, 170, 270, 420};
209
217{
218 if (_settings_game.difficulty.terrain_type == GenworldMaxHeight::Custom) {
219 /* TGP never reaches this height; this means that if a user inputs "2",
220 * it would create a flat map without the "+ 1". But that would
221 * overflow on "255". So we reduce it by 1 to get back in range. */
223 }
224
235 static const int max_height[5][MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS + 1] = {
236 /* 64 128 256 512 1024 2048 4096 */
237 { 3, 3, 3, 3, 4, 5, 7 },
238 { 5, 7, 8, 9, 14, 19, 31 },
239 { 8, 9, 10, 15, 23, 37, 61 },
240 { 10, 11, 17, 19, 49, 63, 73 },
241 { 12, 19, 25, 31, 67, 75, 87 },
242 };
243
244 int map_size_bucket = std::min(Map::LogX(), Map::LogY()) - MIN_MAP_SIZE_BITS;
245 int max_height_from_table = max_height[to_underlying(_settings_game.difficulty.terrain_type)][map_size_bucket];
246
247 /* If there is a manual map height limit, clamp to it. */
249 max_height_from_table = std::min<uint>(max_height_from_table, _settings_game.construction.map_height_limit);
250 }
251
252 return I2H(max_height_from_table);
253}
254
259{
260 return H2I(TGPGetMaxHeight());
261}
262
269static Amplitude GetAmplitude(int frequency)
270{
271 /* Base noise amplitudes (multiplied by 1024) and indexed by "smoothness setting" and log2(frequency). */
272 static const Amplitude amplitudes[][7] = {
273 /* lowest frequency ...... highest (every corner) */
274 {16000, 5600, 1968, 688, 240, 16, 16},
275 {24000, 12800, 6400, 2700, 1024, 128, 16},
276 {32000, 19200, 12800, 8000, 3200, 256, 64},
277 {48000, 24000, 19200, 16000, 8000, 512, 320},
278 };
279 /*
280 * Extrapolation factors for ranges before the table.
281 * The extrapolation is needed to account for the higher map heights. They need larger
282 * areas with a particular gradient so that we are able to create maps without too
283 * many steep slopes up to the wanted height level. It's definitely not perfect since
284 * it will bring larger rectangles with similar slopes which makes the rectangular
285 * behaviour of TGP more noticeable. However, these height differentiations cannot
286 * happen over much smaller areas; we basically double the "range" to give a similar
287 * slope for every doubling of map height.
288 */
289 static const double extrapolation_factors[] = { 3.3, 2.8, 2.3, 1.8 };
290
292
293 /* Get the table index, and return that value if possible. */
294 int index = frequency - MAX_TGP_FREQUENCIES + static_cast<int>(std::size(amplitudes[smoothness]));
295 Amplitude amplitude = amplitudes[smoothness][std::max(0, index)];
296 if (index >= 0) return amplitude;
297
298 /* We need to extrapolate the amplitude. */
299 double extrapolation_factor = extrapolation_factors[smoothness];
300 int height_range = I2H(16);
301 do {
302 amplitude = (Amplitude)(extrapolation_factor * (double)amplitude);
303 height_range <<= 1;
304 index++;
305 } while (index < 0);
306
307 return Clamp((TGPGetMaxHeight() - height_range) / height_range, 0, 1) * amplitude;
308}
309
316static inline bool IsValidXY(int x, int y)
317{
318 return x >= 0 && x < _height_map.size_x && y >= 0 && y < _height_map.size_y;
319}
320
321
325static inline void AllocHeightMap()
326{
327 assert(_height_map.h.empty());
328
331
332 /* Allocate memory block for height map row pointers */
333 size_t total_size = static_cast<size_t>(_height_map.size_x + 1) * (_height_map.size_y + 1);
335 _height_map.h.resize(total_size);
336}
337
339static inline void FreeHeightMap()
340{
341 _height_map.h.clear();
342}
343
349static inline Height RandomHeight(Amplitude r_max)
350{
351 /* Spread height into range -r_max..+r_max */
352 return A2H(RandomRange(2 * r_max + 1) - r_max);
353}
354
362static void HeightMapGenerate()
363{
364 /* Trying to apply noise to uninitialized height map */
365 assert(!_height_map.h.empty());
366
367 int start = std::max(MAX_TGP_FREQUENCIES - (int)std::min(Map::LogX(), Map::LogY()), 0);
368 bool first = true;
369
370 for (int frequency = start; frequency < MAX_TGP_FREQUENCIES; frequency++) {
371 const Amplitude amplitude = GetAmplitude(frequency);
372
373 /* Ignore zero amplitudes; it means our map isn't height enough for this
374 * amplitude, so ignore it and continue with the next set of amplitude. */
375 if (amplitude == 0) continue;
376
377 const int step = 1 << (MAX_TGP_FREQUENCIES - frequency - 1);
378
379 if (first) {
380 /* This is first round, we need to establish base heights with step = size_min */
381 for (int y = 0; y <= _height_map.size_y; y += step) {
382 for (int x = 0; x <= _height_map.size_x; x += step) {
383 Height height = (amplitude > 0) ? RandomHeight(amplitude) : 0;
384 _height_map.height(x, y) = height;
385 }
386 }
387 first = false;
388 continue;
389 }
390
391 /* It is regular iteration round.
392 * Interpolate height values at odd x, even y tiles */
393 for (int y = 0; y <= _height_map.size_y; y += 2 * step) {
394 for (int x = 0; x <= _height_map.size_x - 2 * step; x += 2 * step) {
395 Height h00 = _height_map.height(x + 0 * step, y);
396 Height h02 = _height_map.height(x + 2 * step, y);
397 Height h01 = (h00 + h02) / 2;
398 _height_map.height(x + 1 * step, y) = h01;
399 }
400 }
401
402 /* Interpolate height values at odd y tiles */
403 for (int y = 0; y <= _height_map.size_y - 2 * step; y += 2 * step) {
404 for (int x = 0; x <= _height_map.size_x; x += step) {
405 Height h00 = _height_map.height(x, y + 0 * step);
406 Height h20 = _height_map.height(x, y + 2 * step);
407 Height h10 = (h00 + h20) / 2;
408 _height_map.height(x, y + 1 * step) = h10;
409 }
410 }
411
412 /* Add noise for next higher frequency (smaller steps) */
413 for (int y = 0; y <= _height_map.size_y; y += step) {
414 for (int x = 0; x <= _height_map.size_x; x += step) {
415 _height_map.height(x, y) += RandomHeight(amplitude);
416 }
417 }
418 }
419}
420
422static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ptr)
423{
424 Height h_min, h_max, h_avg;
425 int64_t h_accu = 0;
426 h_min = h_max = _height_map.height(0, 0);
427
428 /* Get h_min, h_max and accumulate heights into h_accu */
429 for (const Height &h : _height_map.h) {
430 if (h < h_min) h_min = h;
431 if (h > h_max) h_max = h;
432 h_accu += h;
433 }
434
435 /* Get average height */
436 h_avg = (Height)(h_accu / (_height_map.size_x * _height_map.size_y));
437
438 /* Return required results */
439 if (min_ptr != nullptr) *min_ptr = h_min;
440 if (max_ptr != nullptr) *max_ptr = h_max;
441 if (avg_ptr != nullptr) *avg_ptr = h_avg;
442}
443
445static int *HeightMapMakeHistogram(Height h_min, [[maybe_unused]] Height h_max, int *hist_buf)
446{
447 int *hist = hist_buf - h_min;
448
449 /* Count the heights and fill the histogram */
450 for (const Height &h : _height_map.h) {
451 assert(h >= h_min);
452 assert(h <= h_max);
453 hist[h]++;
454 }
455 return hist;
456}
457
463static double SineTransformLowlands(double fheight)
464{
465 double height = fheight;
466
467 /* Half of tiles should be at lowest (0..25%) heights */
468 double sine_lower_limit = 0.5;
469 double linear_compression = 2;
470 if (height <= sine_lower_limit) {
471 /* Under the limit we do linear compression down */
472 height = height / linear_compression;
473 } else {
474 double m = sine_lower_limit / linear_compression;
475 /* Get sine_lower_limit..1 into -1..1 */
476 height = 2.0 * ((height - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
477 /* Sine wave transform */
478 height = sin(height * M_PI_2);
479 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
480 height = 0.5 * ((1.0 - m) * height + (1.0 + m));
481 }
482
483 return height;
484}
485
491static double SineTransformNormal(double &fheight)
492{
493 double height = fheight;
494
495 /* Move and scale 0..1 into -1..+1 */
496 height = 2 * height - 1;
497 /* Sine transform */
498 height = sin(height * M_PI_2);
499 /* Transform it back from -1..1 into 0..1 space */
500 height = 0.5 * (height + 1);
501
502 return height;
503}
504
510static double SineTransformPlateaus(double &fheight)
511{
512 double height = fheight;
513
514 /* Redistribute heights to have more tiles at highest (75%..100%) range */
515 double sine_upper_limit = 0.75;
516 double linear_compression = 2;
517 if (height >= sine_upper_limit) {
518 /* Over the limit we do linear compression up */
519 height = 1.0 - (1.0 - height) / linear_compression;
520 } else {
521 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
522 /* Get 0..sine_upper_limit into -1..1 */
523 height = 2.0 * height / sine_upper_limit - 1.0;
524 /* Sine wave transform */
525 height = sin(height * M_PI_2);
526 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
527 height = 0.5 * (height + 1.0) * m;
528 }
529
530 return height;
531}
532
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
545 case GenworldAverageHeight::Auto:
546 /* Apply sine transform depending on landscape type */
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 };
594 /* Scaled curve maps; value is in height_ts. */
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
703static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new)
704{
705 Height h_min, h_max, h_avg, h_water_level;
706 int64_t water_tiles, desired_water_tiles;
707 int *hist;
708
709 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
710
711 /* Allocate histogram buffer and clear its cells */
712 std::vector<int> hist_buf(h_max - h_min + 1);
713 /* Fill histogram */
714 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf.data());
715
716 /* How many water tiles do we want? */
717 desired_water_tiles = water_percent * _height_map.size_x * _height_map.size_y / WATER_PERCENT_FACTOR;
718
719 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
720 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
721 water_tiles += hist[h_water_level];
722 if (water_tiles >= desired_water_tiles) break;
723 }
724
725 /* We now have the proper water level value.
726 * Transform the height map into new (normalized) height map:
727 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
728 * values from range: h_water_level..h_max are transformed into 0..h_max_new
729 * where h_max_new is depending on terrain type and map size.
730 */
731 for (Height &h : _height_map.h) {
732 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
733 h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1);
734 /* Make sure all values are in the proper range (0..h_max_new) */
735 if (h < 0) h = I2H(0);
736 if (h >= h_max_new) h = h_max_new - 1;
737 }
738}
739
740static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
741
762static void HeightMapCoastLines(BorderFlags water_borders)
763{
765 const int margin = 4;
766 int y, x;
767 double max_x;
768 double max_y;
769
770 /* Lower to sea level */
771 for (y = 0; y <= _height_map.size_y; y++) {
772 if (water_borders.Test(BorderFlag::NorthEast)) {
773 /* Top right */
774 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);
775 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
776 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
777 for (x = 0; x < max_x; x++) {
778 _height_map.height(x, y) = 0;
779 }
780 }
781
782 if (water_borders.Test(BorderFlag::SouthWest)) {
783 /* Bottom left */
784 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);
785 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
786 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
787 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
788 _height_map.height(x, y) = 0;
789 }
790 }
791 }
792
793 /* Lower to sea level */
794 for (x = 0; x <= _height_map.size_x; x++) {
795 if (water_borders.Test(BorderFlag::NorthWest)) {
796 /* Top left */
797 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);
798 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
799 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
800 for (y = 0; y < max_y; y++) {
801 _height_map.height(x, y) = 0;
802 }
803 }
804
805 if (water_borders.Test(BorderFlag::SouthEast)) {
806 /* Bottom right */
807 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);
808 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
809 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
810 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
811 _height_map.height(x, y) = 0;
812 }
813 }
814 }
815}
816
818static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
819{
820 const int max_coast_dist_from_edge = 35;
821 const int max_coast_smooth_depth = 35;
822
823 int x, y;
824 int ed; // coast distance from edge
825 int depth;
826
827 Height h_prev = I2H(1);
828 Height h;
829
830 assert(IsValidXY(org_x, org_y));
831
832 /* Search for the coast (first non-water tile) */
833 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++) {
834 /* Coast found? */
835 if (_height_map.height(x, y) >= I2H(1)) break;
836
837 /* Coast found in the neighbourhood? */
838 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
839
840 /* Coast found in the neighbourhood on the other side */
841 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
842 }
843
844 /* Coast found or max_coast_dist_from_edge has been reached.
845 * Soften the coast slope */
846 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_smooth_depth; depth++, x += dir_x, y += dir_y) {
847 h = _height_map.height(x, y);
848 h = static_cast<Height>(std::min<uint>(h, h_prev + (4 + depth))); // coast softening formula
849 _height_map.height(x, y) = h;
850 h_prev = h;
851 }
852}
853
855static void HeightMapSmoothCoasts(BorderFlags water_borders)
856{
857 int x, y;
858 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
859 for (x = 0; x < _height_map.size_x; x++) {
860 if (water_borders.Test(BorderFlag::NorthWest)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
862 }
863 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
864 for (y = 0; y < _height_map.size_y; y++) {
865 if (water_borders.Test(BorderFlag::NorthEast)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
867 }
868}
869
877static void HeightMapSmoothSlopes(Height dh_max)
878{
879 for (int y = 0; y <= (int)_height_map.size_y; y++) {
880 for (int x = 0; x <= (int)_height_map.size_x; x++) {
881 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;
882 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
883 }
884 }
885 for (int y = _height_map.size_y; y >= 0; y--) {
886 for (int x = _height_map.size_x; x >= 0; x--) {
887 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;
888 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
889 }
890 }
891}
892
901{
903 const Height h_max_new = TGPGetMaxHeight();
904 const Height roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
905
906 HeightMapAdjustWaterLevel(water_percent, h_max_new);
907
909 if (water_borders == BorderFlag::Random) water_borders = static_cast<BorderFlags>(GB(Random(), 0, 4));
910
911 HeightMapCoastLines(water_borders);
912 HeightMapSmoothSlopes(roughness);
913
914 HeightMapSmoothCoasts(water_borders);
915 HeightMapSmoothSlopes(roughness);
916
917 HeightMapSineTransform(I2H(1), h_max_new);
918
921 }
922}
923
931static double int_noise(const long x, const long y, const int prime)
932{
933 long n = x + y * prime + _settings_game.game_creation.generation_seed;
934
935 n = (n << 13) ^ n;
936
937 /* Pseudo-random number generator, using several large primes */
938 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
939}
940
941
945static inline double linear_interpolate(const double a, const double b, const double x)
946{
947 return a + x * (b - a);
948}
949
950
955static double interpolated_noise(const double x, const double y, const int prime)
956{
957 const int integer_x = (int)x;
958 const int integer_y = (int)y;
959
960 const double fractional_x = x - (double)integer_x;
961 const double fractional_y = y - (double)integer_y;
962
963 const double v1 = int_noise(integer_x, integer_y, prime);
964 const double v2 = int_noise(integer_x + 1, integer_y, prime);
965 const double v3 = int_noise(integer_x, integer_y + 1, prime);
966 const double v4 = int_noise(integer_x + 1, integer_y + 1, prime);
967
968 const double i1 = linear_interpolate(v1, v2, fractional_x);
969 const double i2 = linear_interpolate(v3, v4, fractional_x);
970
971 return linear_interpolate(i1, i2, fractional_y);
972}
973
974
981static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
982{
983 constexpr int OCTAVES = 6;
984 constexpr double INITIAL_FREQUENCY = 1 << OCTAVES;
985
986 double total = 0.0;
987 double frequency = 1.0 / INITIAL_FREQUENCY;
988 double amplitude = 1.0;
989 for (int i = 0; i < OCTAVES; i++) {
990 total += interpolated_noise(x * frequency, y * frequency, prime) * amplitude;
991 frequency *= 2.0;
992 amplitude *= p;
993 }
994 return total;
995}
996
997
999static void TgenSetTileHeight(TileIndex tile, int height)
1000{
1001 SetTileHeight(tile, height);
1002
1003 /* Only clear the tiles within the map area. */
1004 if (IsInnerTile(tile)) {
1005 MakeClear(tile, CLEAR_GRASS, 3);
1006 }
1007}
1008
1017{
1020
1022
1024
1026
1028
1029 /* First make sure the tiles at the north border are void tiles if needed. */
1031 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
1032 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
1033 }
1034
1035 int max_height = H2I(TGPGetMaxHeight());
1036
1037 /* Transfer height map into OTTD map */
1038 for (int y = 0; y < _height_map.size_y; y++) {
1039 for (int x = 0; x < _height_map.size_x; x++) {
1040 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1041 }
1042 }
1043
1044 FreeHeightMap();
1046}
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.
@ CLEAR_GRASS
0-3
Definition clear_map.h:20
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition clear_map.h:246
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23)
Definition enum_type.hpp:17
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:385
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.
bool freeform_edges
allow terraforming the tiles at the map edges
uint8_t map_height_limit
the maximum allowed heightlevel
GenworldMaxHeight terrain_type
the mountainousness of the landscape
uint8_t quantity_sea_lakes
the amount of seas/lakes
uint8_t custom_sea_level
manually entered percentage of water in the map
GenworldAverageHeight average_height
adjustment applied to TGP based on climate, or manually set by the player.
uint8_t variety
variety level applied to TGP
uint8_t custom_terrain_type
manually entered height for TGP to aim for
LandscapeType landscape
the landscape we're currently in
uint8_t map_x
X size of map.
uint8_t tgen_smoothness
how rough is the terrain from 0-3
uint8_t map_y
Y size of map.
BorderFlags water_borders
bitset of the borders that are water
uint32_t generation_seed
noise seed for world generation
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
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:272
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:281
static uint LogX()
Logarithm of the map size along the X side.
Definition map_func.h:253
static uint LogY()
Logarithm of the map size along the y side.
Definition map_func.h:263
static double SineTransformNormal(double &fheight)
Adjust the landscape to create normal average height (temperate and toyland landscapes).
Definition tgp.cpp:491
static Height RandomHeight(Amplitude r_max)
Generates new random height in given amplitude (generated numbers will range from - amplitude to + am...
Definition tgp.cpp:349
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:818
static Height A2H(Amplitude i)
Conversion: Amplitude to Height.
Definition tgp.cpp:197
static void HeightMapGenerate()
Base Perlin noise generator - fills height map with raw Perlin noise.
Definition tgp.cpp:362
static double linear_interpolate(const double a, const double b, const double x)
This routine determines the interpolated value between a and b.
Definition tgp.cpp:945
static Height TGPGetMaxHeight()
Gets the maximum allowed height while generating a map based on mapsize, terraintype,...
Definition tgp.cpp:216
static void HeightMapCoastLines(BorderFlags water_borders)
This routine sculpts in from the edge a random amount, again a Perlin sequence, to avoid the rigid fl...
Definition tgp.cpp:762
static Height I2H(int i)
Conversion: int to Height.
Definition tgp.cpp:185
static int H2I(Height i)
Conversion: Height to int.
Definition tgp.cpp:191
static double SineTransformPlateaus(double &fheight)
Adjust the landscape to create plateaus on average (arctic landscape).
Definition tgp.cpp:510
static void HeightMapGetMinMaxAvg(Height *min_ptr, Height *max_ptr, Height *avg_ptr)
Returns min, max and average height from height map.
Definition tgp.cpp:422
static void HeightMapSmoothSlopes(Height dh_max)
This routine provides the essential cleanup necessary before OTTD can display the terrain.
Definition tgp.cpp:877
static const int64_t _water_percent[4]
Desired water percentage (100% == 1024) - indexed by _settings_game.difficulty.quantity_sea_lakes.
Definition tgp.cpp:208
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:269
static int * HeightMapMakeHistogram(Height h_min, Height h_max, int *hist_buf)
Dill histogram and return pointer to its base point - to the count of zero heights.
Definition tgp.cpp:445
static void FreeHeightMap()
Free height map.
Definition tgp.cpp:339
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:258
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:703
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:900
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:855
static bool IsValidXY(int x, int y)
Check if a X/Y set are within the map.
Definition tgp.cpp:316
static const int MAX_TGP_FREQUENCIES
Maximum number of TGP noise frequencies.
Definition tgp.cpp:203
static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
This is a similar function to the main perlin noise calculation, but uses the value p passed as a par...
Definition tgp.cpp:981
static void TgenSetTileHeight(TileIndex tile, int height)
A small helper function to initialize the terrain.
Definition tgp.cpp:999
void GenerateTerrainPerlin()
The main new land generator using Perlin noise.
Definition tgp.cpp:1016
static double SineTransformLowlands(double fheight)
Adjust the landscape to create lowlands on average (tropic landscape).
Definition tgp.cpp:463
static double interpolated_noise(const double x, const double y, const int prime)
This routine returns the smoothed interpolated noise for an x and y, using the values from the surrou...
Definition tgp.cpp:955
static double int_noise(const long x, const long y, const int prime)
The Perlin Noise calculation using large primes The initial number is adjusted by two values; the gen...
Definition tgp.cpp:931
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:325
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
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;)
Definition void_map.h:19