OpenTTD Source 20260108-master-g8ba1860eaa
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{
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[_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
459static void HeightMapSineTransform(Height h_min, Height h_max)
460{
461 for (Height &h : _height_map.h) {
462 double fheight;
463
464 if (h < h_min) continue;
465
466 /* Transform height into 0..1 space */
467 fheight = (double)(h - h_min) / (double)(h_max - h_min);
468 /* Apply sine transform depending on landscape type */
470 case LandscapeType::Toyland:
471 case LandscapeType::Temperate:
472 /* Move and scale 0..1 into -1..+1 */
473 fheight = 2 * fheight - 1;
474 /* Sine transform */
475 fheight = sin(fheight * M_PI_2);
476 /* Transform it back from -1..1 into 0..1 space */
477 fheight = 0.5 * (fheight + 1);
478 break;
479
480 case LandscapeType::Arctic:
481 {
482 /* Arctic terrain needs special height distribution.
483 * Redistribute heights to have more tiles at highest (75%..100%) range */
484 double sine_upper_limit = 0.75;
485 double linear_compression = 2;
486 if (fheight >= sine_upper_limit) {
487 /* Over the limit we do linear compression up */
488 fheight = 1.0 - (1.0 - fheight) / linear_compression;
489 } else {
490 double m = 1.0 - (1.0 - sine_upper_limit) / linear_compression;
491 /* Get 0..sine_upper_limit into -1..1 */
492 fheight = 2.0 * fheight / sine_upper_limit - 1.0;
493 /* Sine wave transform */
494 fheight = sin(fheight * M_PI_2);
495 /* Get -1..1 back to 0..(1 - (1 - sine_upper_limit) / linear_compression) == 0.0..m */
496 fheight = 0.5 * (fheight + 1.0) * m;
497 }
498 }
499 break;
500
501 case LandscapeType::Tropic:
502 {
503 /* Desert terrain needs special height distribution.
504 * Half of tiles should be at lowest (0..25%) heights */
505 double sine_lower_limit = 0.5;
506 double linear_compression = 2;
507 if (fheight <= sine_lower_limit) {
508 /* Under the limit we do linear compression down */
509 fheight = fheight / linear_compression;
510 } else {
511 double m = sine_lower_limit / linear_compression;
512 /* Get sine_lower_limit..1 into -1..1 */
513 fheight = 2.0 * ((fheight - sine_lower_limit) / (1.0 - sine_lower_limit)) - 1.0;
514 /* Sine wave transform */
515 fheight = sin(fheight * M_PI_2);
516 /* Get -1..1 back to (sine_lower_limit / linear_compression)..1.0 */
517 fheight = 0.5 * ((1.0 - m) * fheight + (1.0 + m));
518 }
519 }
520 break;
521
522 default:
523 NOT_REACHED();
524 break;
525 }
526 /* Transform it back into h_min..h_max space */
527 h = (Height)(fheight * (h_max - h_min) + h_min);
528 if (h < 0) h = I2H(0);
529 if (h >= h_max) h = h_max - 1;
530 }
531}
532
549static void HeightMapCurves(uint level)
550{
551 Height mh = TGPGetMaxHeight() - I2H(1); // height levels above sea level only
552
554 struct ControlPoint {
555 Height x;
556 Height y;
557 };
558 /* Scaled curve maps; value is in height_ts. */
559#define F(fraction) ((Height)(fraction * mh))
560 const ControlPoint curve_map_1[] = { { F(0.0), F(0.0) }, { F(0.8), F(0.13) }, { F(1.0), F(0.4) } };
561 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) } };
562 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) } };
563 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) } };
564#undef F
565
566 const std::span<const ControlPoint> curve_maps[] = { curve_map_1, curve_map_2, curve_map_3, curve_map_4 };
567
568 std::array<Height, std::size(curve_maps)> ht{};
569
570 /* Set up a grid to choose curve maps based on location; attempt to get a somewhat square grid */
571 float factor = sqrt((float)_height_map.size_x / (float)_height_map.size_y);
572 uint sx = Clamp((int)(((1 << level) * factor) + 0.5), 1, 128);
573 uint sy = Clamp((int)(((1 << level) / factor) + 0.5), 1, 128);
574 std::vector<uint8_t> c(static_cast<size_t>(sx) * sy);
575
576 for (uint i = 0; i < sx * sy; i++) {
577 c[i] = RandomRange(static_cast<uint32_t>(std::size(curve_maps)));
578 }
579
580 /* Apply curves */
581 for (int x = 0; x < _height_map.size_x; x++) {
582
583 /* Get our X grid positions and bi-linear ratio */
584 float fx = (float)(sx * x) / _height_map.size_x + 1.0f;
585 uint x1 = (uint)fx;
586 uint x2 = x1;
587 float xr = 2.0f * (fx - x1) - 1.0f;
588 xr = sin(xr * M_PI_2);
589 xr = sin(xr * M_PI_2);
590 xr = 0.5f * (xr + 1.0f);
591 float xri = 1.0f - xr;
592
593 if (x1 > 0) {
594 x1--;
595 if (x2 >= sx) x2--;
596 }
597
598 for (int y = 0; y < _height_map.size_y; y++) {
599
600 /* Get our Y grid position and bi-linear ratio */
601 float fy = (float)(sy * y) / _height_map.size_y + 1.0f;
602 uint y1 = (uint)fy;
603 uint y2 = y1;
604 float yr = 2.0f * (fy - y1) - 1.0f;
605 yr = sin(yr * M_PI_2);
606 yr = sin(yr * M_PI_2);
607 yr = 0.5f * (yr + 1.0f);
608 float yri = 1.0f - yr;
609
610 if (y1 > 0) {
611 y1--;
612 if (y2 >= sy) y2--;
613 }
614
615 uint corner_a = c[x1 + sx * y1];
616 uint corner_b = c[x1 + sx * y2];
617 uint corner_c = c[x2 + sx * y1];
618 uint corner_d = c[x2 + sx * y2];
619
620 /* Bitmask of which curve maps are chosen, so that we do not bother
621 * calculating a curve which won't be used. */
622 uint corner_bits = 0;
623 corner_bits |= 1 << corner_a;
624 corner_bits |= 1 << corner_b;
625 corner_bits |= 1 << corner_c;
626 corner_bits |= 1 << corner_d;
627
628 Height *h = &_height_map.height(x, y);
629
630 /* Do not touch sea level */
631 if (*h < I2H(1)) continue;
632
633 /* Only scale above sea level */
634 *h -= I2H(1);
635
636 /* Apply all curve maps that are used on this tile. */
637 for (size_t t = 0; t < std::size(curve_maps); t++) {
638 if (!HasBit(corner_bits, static_cast<uint8_t>(t))) continue;
639
640 [[maybe_unused]] bool found = false;
641 auto &cm = curve_maps[t];
642 for (size_t i = 0; i < cm.size() - 1; i++) {
643 const ControlPoint &p1 = cm[i];
644 const ControlPoint &p2 = cm[i + 1];
645
646 if (*h >= p1.x && *h < p2.x) {
647 ht[t] = p1.y + (*h - p1.x) * (p2.y - p1.y) / (p2.x - p1.x);
648#ifdef WITH_ASSERT
649 found = true;
650#endif
651 break;
652 }
653 }
654 assert(found);
655 }
656
657 /* Apply interpolation of curve map results. */
658 *h = (Height)((ht[corner_a] * yri + ht[corner_b] * yr) * xri + (ht[corner_c] * yri + ht[corner_d] * yr) * xr);
659
660 /* Re-add sea level */
661 *h += I2H(1);
662 }
663 }
664}
665
667static void HeightMapAdjustWaterLevel(int64_t water_percent, Height h_max_new)
668{
669 Height h_min, h_max, h_avg, h_water_level;
670 int64_t water_tiles, desired_water_tiles;
671 int *hist;
672
673 HeightMapGetMinMaxAvg(&h_min, &h_max, &h_avg);
674
675 /* Allocate histogram buffer and clear its cells */
676 std::vector<int> hist_buf(h_max - h_min + 1);
677 /* Fill histogram */
678 hist = HeightMapMakeHistogram(h_min, h_max, hist_buf.data());
679
680 /* How many water tiles do we want? */
681 desired_water_tiles = water_percent * _height_map.size_x * _height_map.size_y / WATER_PERCENT_FACTOR;
682
683 /* Raise water_level and accumulate values from histogram until we reach required number of water tiles */
684 for (h_water_level = h_min, water_tiles = 0; h_water_level < h_max; h_water_level++) {
685 water_tiles += hist[h_water_level];
686 if (water_tiles >= desired_water_tiles) break;
687 }
688
689 /* We now have the proper water level value.
690 * Transform the height map into new (normalized) height map:
691 * values from range: h_min..h_water_level will become negative so it will be clamped to 0
692 * values from range: h_water_level..h_max are transformed into 0..h_max_new
693 * where h_max_new is depending on terrain type and map size.
694 */
695 for (Height &h : _height_map.h) {
696 /* Transform height from range h_water_level..h_max into 0..h_max_new range */
697 h = (Height)(((int)h_max_new) * (h - h_water_level) / (h_max - h_water_level)) + I2H(1);
698 /* Make sure all values are in the proper range (0..h_max_new) */
699 if (h < 0) h = I2H(0);
700 if (h >= h_max_new) h = h_max_new - 1;
701 }
702}
703
704static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime);
705
726static void HeightMapCoastLines(BorderFlags water_borders)
727{
729 const int margin = 4;
730 int y, x;
731 double max_x;
732 double max_y;
733
734 /* Lower to sea level */
735 for (y = 0; y <= _height_map.size_y; y++) {
736 if (water_borders.Test(BorderFlag::NorthEast)) {
737 /* Top right */
738 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);
739 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
740 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
741 for (x = 0; x < max_x; x++) {
742 _height_map.height(x, y) = 0;
743 }
744 }
745
746 if (water_borders.Test(BorderFlag::SouthWest)) {
747 /* Bottom left */
748 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);
749 max_x = std::max((smallest_size * smallest_size / 64) + max_x, (smallest_size * smallest_size / 64) + margin - max_x);
750 if (smallest_size < 8 && max_x > 5) max_x /= 1.5;
751 for (x = _height_map.size_x; x > (_height_map.size_x - 1 - max_x); x--) {
752 _height_map.height(x, y) = 0;
753 }
754 }
755 }
756
757 /* Lower to sea level */
758 for (x = 0; x <= _height_map.size_x; x++) {
759 if (water_borders.Test(BorderFlag::NorthWest)) {
760 /* Top left */
761 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);
762 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
763 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
764 for (y = 0; y < max_y; y++) {
765 _height_map.height(x, y) = 0;
766 }
767 }
768
769 if (water_borders.Test(BorderFlag::SouthEast)) {
770 /* Bottom right */
771 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);
772 max_y = std::max((smallest_size * smallest_size / 64) + max_y, (smallest_size * smallest_size / 64) + margin - max_y);
773 if (smallest_size < 8 && max_y > 5) max_y /= 1.5;
774 for (y = _height_map.size_y; y > (_height_map.size_y - 1 - max_y); y--) {
775 _height_map.height(x, y) = 0;
776 }
777 }
778 }
779}
780
782static void HeightMapSmoothCoastInDirection(int org_x, int org_y, int dir_x, int dir_y)
783{
784 const int max_coast_dist_from_edge = 35;
785 const int max_coast_smooth_depth = 35;
786
787 int x, y;
788 int ed; // coast distance from edge
789 int depth;
790
791 Height h_prev = I2H(1);
792 Height h;
793
794 assert(IsValidXY(org_x, org_y));
795
796 /* Search for the coast (first non-water tile) */
797 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++) {
798 /* Coast found? */
799 if (_height_map.height(x, y) >= I2H(1)) break;
800
801 /* Coast found in the neighbourhood? */
802 if (IsValidXY(x + dir_y, y + dir_x) && _height_map.height(x + dir_y, y + dir_x) > 0) break;
803
804 /* Coast found in the neighbourhood on the other side */
805 if (IsValidXY(x - dir_y, y - dir_x) && _height_map.height(x - dir_y, y - dir_x) > 0) break;
806 }
807
808 /* Coast found or max_coast_dist_from_edge has been reached.
809 * Soften the coast slope */
810 for (depth = 0; IsValidXY(x, y) && depth <= max_coast_smooth_depth; depth++, x += dir_x, y += dir_y) {
811 h = _height_map.height(x, y);
812 h = static_cast<Height>(std::min<uint>(h, h_prev + (4 + depth))); // coast softening formula
813 _height_map.height(x, y) = h;
814 h_prev = h;
815 }
816}
817
819static void HeightMapSmoothCoasts(BorderFlags water_borders)
820{
821 int x, y;
822 /* First Smooth NW and SE coasts (y close to 0 and y close to size_y) */
823 for (x = 0; x < _height_map.size_x; x++) {
824 if (water_borders.Test(BorderFlag::NorthWest)) HeightMapSmoothCoastInDirection(x, 0, 0, 1);
826 }
827 /* First Smooth NE and SW coasts (x close to 0 and x close to size_x) */
828 for (y = 0; y < _height_map.size_y; y++) {
829 if (water_borders.Test(BorderFlag::NorthEast)) HeightMapSmoothCoastInDirection(0, y, 1, 0);
831 }
832}
833
841static void HeightMapSmoothSlopes(Height dh_max)
842{
843 for (int y = 0; y <= (int)_height_map.size_y; y++) {
844 for (int x = 0; x <= (int)_height_map.size_x; x++) {
845 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;
846 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
847 }
848 }
849 for (int y = _height_map.size_y; y >= 0; y--) {
850 for (int x = _height_map.size_x; x >= 0; x--) {
851 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;
852 if (_height_map.height(x, y) > h_max) _height_map.height(x, y) = h_max;
853 }
854 }
855}
856
865{
867 const Height h_max_new = TGPGetMaxHeight();
868 const Height roughness = 7 + 3 * _settings_game.game_creation.tgen_smoothness;
869
870 HeightMapAdjustWaterLevel(water_percent, h_max_new);
871
873 if (water_borders == BorderFlag::Random) water_borders = static_cast<BorderFlags>(GB(Random(), 0, 4));
874
875 HeightMapCoastLines(water_borders);
876 HeightMapSmoothSlopes(roughness);
877
878 HeightMapSmoothCoasts(water_borders);
879 HeightMapSmoothSlopes(roughness);
880
881 HeightMapSineTransform(I2H(1), h_max_new);
882
885 }
886}
887
895static double int_noise(const long x, const long y, const int prime)
896{
897 long n = x + y * prime + _settings_game.game_creation.generation_seed;
898
899 n = (n << 13) ^ n;
900
901 /* Pseudo-random number generator, using several large primes */
902 return 1.0 - (double)((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0;
903}
904
905
909static inline double linear_interpolate(const double a, const double b, const double x)
910{
911 return a + x * (b - a);
912}
913
914
919static double interpolated_noise(const double x, const double y, const int prime)
920{
921 const int integer_x = (int)x;
922 const int integer_y = (int)y;
923
924 const double fractional_x = x - (double)integer_x;
925 const double fractional_y = y - (double)integer_y;
926
927 const double v1 = int_noise(integer_x, integer_y, prime);
928 const double v2 = int_noise(integer_x + 1, integer_y, prime);
929 const double v3 = int_noise(integer_x, integer_y + 1, prime);
930 const double v4 = int_noise(integer_x + 1, integer_y + 1, prime);
931
932 const double i1 = linear_interpolate(v1, v2, fractional_x);
933 const double i2 = linear_interpolate(v3, v4, fractional_x);
934
935 return linear_interpolate(i1, i2, fractional_y);
936}
937
938
945static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime)
946{
947 constexpr int OCTAVES = 6;
948 constexpr double INITIAL_FREQUENCY = 1 << OCTAVES;
949
950 double total = 0.0;
951 double frequency = 1.0 / INITIAL_FREQUENCY;
952 double amplitude = 1.0;
953 for (int i = 0; i < OCTAVES; i++) {
954 total += interpolated_noise(x * frequency, y * frequency, prime) * amplitude;
955 frequency *= 2.0;
956 amplitude *= p;
957 }
958 return total;
959}
960
961
963static void TgenSetTileHeight(TileIndex tile, int height)
964{
965 SetTileHeight(tile, height);
966
967 /* Only clear the tiles within the map area. */
968 if (IsInnerTile(tile)) {
969 MakeClear(tile, CLEAR_GRASS, 3);
970 }
971}
972
981{
984
986
988
990
992
993 /* First make sure the tiles at the north border are void tiles if needed. */
995 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
996 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
997 }
998
999 int max_height = H2I(TGPGetMaxHeight());
1000
1001 /* Transfer height map into OTTD map */
1002 for (int y = 0; y < _height_map.size_y; y++) {
1003 for (int x = 0; x < _height_map.size_x; x++) {
1004 TgenSetTileHeight(TileXY(x, y), Clamp(H2I(_height_map.height(x, y)), 0, max_height));
1005 }
1006 }
1007
1008 FreeHeightMap();
1010}
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:247
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:48
@ GWP_LANDSCAPE
Create the landscape.
Definition genworld.h:63
static const uint CUSTOM_TERRAIN_TYPE_NUMBER_DIFFICULTY
Value for custom terrain type in difficulty settings.
Definition genworld.h:46
Types related to the landscape.
static constexpr BorderFlags BORDERFLAGS_ALL
Border on all sides.
@ 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
uint8_t 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
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 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:782
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:909
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:726
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 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:841
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:667
static void HeightMapSineTransform(Height h_min, Height h_max)
Applies sine wave redistribution onto height map.
Definition tgp.cpp:459
static HeightMap _height_map
Global height map instance.
Definition tgp.cpp:182
static void HeightMapNormalize()
Height map terraform post processing:
Definition tgp.cpp:864
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:819
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:945
static void TgenSetTileHeight(TileIndex tile, int height)
A small helper function to initialize the terrain.
Definition tgp.cpp:963
void GenerateTerrainPerlin()
The main new land generator using Perlin noise.
Definition tgp.cpp:980
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:919
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:895
static void HeightMapCurves(uint level)
Additional map variety is provided by applying different curve maps to different parts of the map.
Definition tgp.cpp:549
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