-
-
Notifications
You must be signed in to change notification settings - Fork 990
/
default_map_generator_job.cpp
1418 lines (1167 loc) · 47 KB
/
default_map_generator_job.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2003 - 2016 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program 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; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Map-generator, with standalone testprogram.
*/
#include "global.hpp"
#include "generators/default_map_generator_job.hpp"
#include "formula/string_utils.hpp"
#include "game_config_manager.hpp"
#include "gettext.hpp"
#include "language.hpp"
#include "log.hpp"
#include "map/map.hpp"
#include "generators/map_generator.hpp" // mapgen_exception
#include "pathfind/pathfind.hpp"
#include "pathutils.hpp"
#include "util.hpp"
#include "utils/name_generator_factory.hpp"
#include "seed_rng.hpp"
#include "wml_exception.hpp"
#include <SDL.h>
static lg::log_domain log_mapgen("mapgen");
#define ERR_NG LOG_STREAM(err, log_mapgen)
#define LOG_NG LOG_STREAM(info, log_mapgen)
typedef std::vector<std::vector<int> > height_map;
typedef t_translation::ter_map terrain_map;
namespace {
struct for_randomshuffle
{
for_randomshuffle(boost::random::mt19937& rng) : rng_(rng) {}
boost::random::mt19937& rng_;
uint32_t operator ()(uint32_t end) { return rng_() % end; }
};
/**
* Calculates the cost of building a road over terrain. For use in the
* a_star_search algorithm.
*/
struct road_path_calculator : pathfind::cost_calculator
{
road_path_calculator(const terrain_map& terrain, const config& cfg, int seed)
: calls(0)
, map_(terrain)
, cfg_(cfg)
, windiness_(std::max<int>(1, cfg["road_windiness"].to_int())) // Find out how windey roads should be.
, seed_(seed)
, cache_()
{
}
virtual double cost(const map_location& loc, const double so_far) const;
mutable int calls;
private:
const terrain_map& map_;
const config& cfg_;
int windiness_;
int seed_;
mutable std::map<t_translation::terrain_code, double> cache_;
};
double road_path_calculator::cost(const map_location& loc, const double /*so_far*/) const
{
++calls;
if(loc.x < 0 || loc.y < 0 || loc.x >= map_.w || loc.y >= map_.h) {
return (pathfind::cost_calculator::getNoPathValue());
}
// We multiply the cost by a random amount,
// depending upon how 'windy' the road should be.
// If windiness is 1, that will mean that the cost is always genuine,
// and so the road always takes the shortest path.
// If windiness is greater than 1, we sometimes over-report costs
// for some segments, to make the road wind a little.
double windiness = 1.0;
if(windiness_ > 1) {
// modified pseudo_random taken from builder.cpp
unsigned int a = (loc.x + 92872973) ^ 918273;
unsigned int b = (loc.y + 1672517) ^ 128123;
unsigned int c = a*b + a + b + seed_;
unsigned int random = c*c;
// this is just "big random number modulo windiness_"
// but avoid the "modulo by a low number (like 2)"
// because it can increase arithmetic patterns
int noise = random % (windiness_ * 137) / 137;
windiness += noise;
}
const t_translation::terrain_code c = map_[loc.x][loc.y];
const std::map<t_translation::terrain_code, double>::const_iterator itor = cache_.find(c);
if(itor != cache_.end()) {
return itor->second*windiness;
}
static std::string terrain;
terrain = t_translation::write_terrain_code(c);
double res = getNoPathValue();
if(const config &child = cfg_.find_child("road_cost", "terrain", terrain)) {
res = child["cost"].to_double();
}
cache_.insert(std::pair<t_translation::terrain_code, double>(c,res));
return windiness*res;
}
struct is_valid_terrain
{
is_valid_terrain(const t_translation::ter_map& map, const t_translation::ter_list& terrain_list);
bool operator()(int x, int y) const;
private:
t_translation::ter_map map_;
const t_translation::ter_list& terrain_;
};
is_valid_terrain::is_valid_terrain(const t_translation::ter_map& map, const t_translation::ter_list& terrain_list)
: map_(map), terrain_(terrain_list)
{
}
bool is_valid_terrain::operator()(int x, int y) const
{
if(x < 0 || x >= map_.w || y < 0 || y >= map_.h) {
return false;
}
return std::find(terrain_.begin(),terrain_.end(),map_[x][y]) != terrain_.end();
}
/* the configuration file should contain a number of [height] tags:
* [height]
* height=n
* terrain=x
* [/height]
* These should be in descending order of n.
* They are checked sequentially, and if height is greater than n for that tile,
* then the tile is set to terrain type x.
*/
class terrain_height_mapper
{
public:
explicit terrain_height_mapper(const config& cfg);
bool convert_terrain(const int height) const;
t_translation::terrain_code convert_to() const;
private:
int terrain_height;
t_translation::terrain_code to;
};
terrain_height_mapper::terrain_height_mapper(const config& cfg) :
terrain_height(cfg["height"]),
to(t_translation::GRASS_LAND)
{
const std::string& terrain = cfg["terrain"];
if(terrain != "") {
to = t_translation::read_terrain_code(terrain);
}
}
bool terrain_height_mapper::convert_terrain(const int height) const
{
return height >= terrain_height;
}
t_translation::terrain_code terrain_height_mapper::convert_to() const
{
return to;
}
class terrain_converter
{
public:
explicit terrain_converter(const config& cfg);
bool convert_terrain(const t_translation::terrain_code & terrain, const int height, const int temperature) const;
t_translation::terrain_code convert_to() const;
private:
int min_temp, max_temp, min_height, max_height;
t_translation::ter_list from;
t_translation::terrain_code to;
};
terrain_converter::terrain_converter(const config& cfg)
: min_temp(cfg["min_temperature"].to_int(-100000))
, max_temp(cfg["max_temperature"].to_int(100000))
, min_height(cfg["min_height"].to_int(-100000))
, max_height(cfg["max_height"].to_int(100000))
, from(t_translation::read_list(cfg["from"]))
, to(t_translation::NONE_TERRAIN)
{
const std::string& to_str = cfg["to"];
if(to_str != "") {
to = t_translation::read_terrain_code(to_str);
}
}
bool terrain_converter::convert_terrain(const t_translation::terrain_code & terrain,
const int height, const int temperature) const
{
return std::find(from.begin(),from.end(),terrain) != from.end() && height >= min_height && height <= max_height && temperature >= min_temp && temperature <= max_temp && to != t_translation::NONE_TERRAIN;
}
t_translation::terrain_code terrain_converter::convert_to() const
{
return to;
}
} // end anon namespace
default_map_generator_job::default_map_generator_job()
: rng_(seed_rng::next_seed())
, game_config_(game_config_manager::get()->game_config())
{
}
default_map_generator_job::default_map_generator_job(uint32_t seed)
: rng_(seed)
, game_config_(game_config_manager::get()->game_config())
{
}
/**
* Generate a height-map.
*
* Basically we generate a lot of hills, each hill being centered at a certain
* point, with a certain radius - being a half sphere. Hills are combined
* additively to form a bumpy surface. The size of each hill varies randomly
* from 1-hill_size. We generate 'iterations' hills in total. The range of
* heights is normalized to 0-1000. 'island_size' controls whether or not the
* map should tend toward an island shape, and if so, how large the island
* should be. Hills with centers that are more than 'island_size' away from
* the center of the map will be inverted (i.e. be valleys). 'island_size' as
* 0 indicates no island.
*/
height_map default_map_generator_job::generate_height_map(size_t width, size_t height, size_t iterations, size_t hill_size, size_t island_size, size_t island_off_center)
{
height_map res(width, std::vector<int>(height,0));
size_t center_x = width/2;
size_t center_y = height/2;
LOG_NG << "off-centering...\n";
if(island_off_center != 0) {
switch(rng_()%4) {
case 0:
center_x += island_off_center;
break;
case 1:
center_y += island_off_center;
break;
case 2:
if(center_x < island_off_center) {
center_x = 0;
} else {
center_x -= island_off_center;
}
break;
case 3:
if(center_y < island_off_center) {
center_y = 0;
} else {
center_y -= island_off_center;
}
break;
}
}
for(size_t i = 0; i != iterations; ++i) {
// (x1,y1) is the location of the hill,
// and 'radius' is the radius of the hill.
// We iterate over all points, (x2,y2).
// The formula for the amount the height is increased by is:
// radius - sqrt((x2-x1)^2 + (y2-y1)^2) with negative values ignored.
//
// Rather than iterate over every single point, we can reduce the points
// to a rectangle that contains all the positive values for this formula --
// the rectangle is given by min_x,max_x,min_y,max_y.
// Is this a negative hill? (i.e. a valley)
bool is_valley = false;
int x1 = island_size > 0 ? center_x - island_size + (rng_()%(island_size*2)) : int(rng_()%width);
int y1 = island_size > 0 ? center_y - island_size + (rng_()%(island_size*2)) : int(rng_()%height);
// We have to check whether this is actually a valley
if(island_size != 0) {
const size_t diffx = std::abs(x1 - int(center_x));
const size_t diffy = std::abs(y1 - int(center_y));
const size_t dist = size_t(std::sqrt(double(diffx*diffx + diffy*diffy)));
is_valley = dist > island_size;
}
const int radius = rng_()%hill_size + 1;
const int min_x = x1 - radius > 0 ? x1 - radius : 0;
const int max_x = x1 + radius < static_cast<long>(res.size()) ? x1 + radius : res.size();
const int min_y = y1 - radius > 0 ? y1 - radius : 0;
const int max_y = y1 + radius < static_cast<long>(res.front().size()) ? y1 + radius : res.front().size();
for(int x2 = min_x; x2 < max_x; ++x2) {
for(int y2 = min_y; y2 < max_y; ++y2) {
const int xdiff = (x2-x1);
const int ydiff = (y2-y1);
const int hill_height = radius - int(std::sqrt(double(xdiff*xdiff + ydiff*ydiff)));
if(hill_height > 0) {
if(is_valley) {
if(hill_height > res[x2][y2]) {
res[x2][y2] = 0;
} else {
res[x2][y2] -= hill_height;
}
} else {
res[x2][y2] += hill_height;
}
}
}
}
}
// Find the highest and lowest points on the map for normalization:
int heighest = 0, lowest = 100000, x;
for(x = 0; size_t(x) != res.size(); ++x) {
for(int y = 0; size_t(y) != res[x].size(); ++y) {
if(res[x][y] > heighest) {
heighest = res[x][y];
}
if(res[x][y] < lowest) {
lowest = res[x][y];
}
}
}
// Normalize the heights to the range 0-1000:
heighest -= lowest;
for(x = 0; size_t(x) != res.size(); ++x) {
for(int y = 0; size_t(y) != res[x].size(); ++y) {
res[x][y] -= lowest;
res[x][y] *= 1000;
if(heighest != 0) {
res[x][y] /= heighest;
}
}
}
return res;
}
/**
* Generate a lake.
*
* It will create water at (x,y), and then have 'lake_fall_off' % chance to
* make another water tile in each of the directions n,s,e,w. In each of the
* directions it does make another water tile, it will have 'lake_fall_off'/2 %
* chance to make another water tile in each of the directions. This will
* continue recursively.
*/
bool default_map_generator_job::generate_lake(terrain_map& terrain, int x, int y, int lake_fall_off, std::set<map_location>& locs_touched)
{
if(x < 0 || y < 0 || x >= terrain.w || y >= terrain.h || lake_fall_off < 0) {
return false;
}
//we checked for this eariler.
unsigned int ulake_fall_off = lake_fall_off;
terrain[x][y] = t_translation::SHALLOW_WATER;
locs_touched.insert(map_location(x,y));
if((rng_()%100) < ulake_fall_off) {
generate_lake(terrain,x+1,y,lake_fall_off/2,locs_touched);
}
if((rng_()%100) < ulake_fall_off) {
generate_lake(terrain,x-1,y,lake_fall_off/2,locs_touched);
}
if((rng_()%100) < ulake_fall_off) {
generate_lake(terrain,x,y+1,lake_fall_off/2,locs_touched);
}
if((rng_()%100) < ulake_fall_off) {
generate_lake(terrain,x,y-1,lake_fall_off/2,locs_touched);
}
return true;
}
/**
* River generation.
*
* Rivers have a source, and then keep on flowing until they meet another body
* of water, which they flow into, or until they reach the edge of the map.
* Rivers will always flow downhill, except that they can flow a maximum of
* 'river_uphill' uphill. This is to represent the water eroding the higher
* ground lower.
*
* Every possible path for a river will be attempted, in random order, and the
* first river path that can be found that makes the river flow into another
* body of water or off the map will be used.
*
* If no path can be found, then the river's generation will be aborted, and
* false will be returned. true is returned if the river is generated
* successfully.
*/
bool default_map_generator_job::generate_river_internal(const height_map& heights,
terrain_map& terrain, int x, int y, std::vector<map_location>& river,
std::set<map_location>& seen_locations, int river_uphill)
{
const bool on_map = x >= 0 && y >= 0 &&
x < static_cast<long>(heights.size()) &&
y < static_cast<long>(heights.back().size());
if(on_map && !river.empty() && heights[x][y] >
heights[river.back().x][river.back().y] + river_uphill) {
return false;
}
// If we're at the end of the river
if(!on_map || terrain[x][y] == t_translation::SHALLOW_WATER ||
terrain[x][y] == t_translation::DEEP_WATER) {
LOG_NG << "generating river...\n";
// Generate the river
for(auto i : river) {
terrain[i.x][i.y] = t_translation::SHALLOW_WATER;
}
LOG_NG << "done generating river\n";
return true;
}
map_location current_loc(x,y);
map_location adj[6];
get_adjacent_tiles(current_loc,adj);
int items[6] = {0,1,2,3,4,5};
for_randomshuffle shufflehelper(rng_);
std::random_shuffle(items, items + 4, shufflehelper);
// Mark that we have attempted from this map_location
seen_locations.insert(current_loc);
river.push_back(current_loc);
for(int a = 0; a != 6; ++a) {
const map_location& loc = adj[items[a]];
if(seen_locations.count(loc) == 0) {
const bool res = generate_river_internal(heights,terrain,loc.x,loc.y,river,seen_locations,river_uphill);
if(res) {
return true;
}
}
}
river.pop_back();
return false;
}
std::vector<map_location> default_map_generator_job::generate_river(const height_map& heights, terrain_map& terrain, int x, int y, int river_uphill)
{
std::vector<map_location> river;
std::set<map_location> seen_locations;
const bool res = generate_river_internal(heights,terrain,x,y,river,seen_locations,river_uphill);
if(!res) {
river.clear();
}
return river;
}
/**
* Returns a random tile at one of the borders of a map that is of the given
* dimensions.
*/
map_location default_map_generator_job::random_point_at_side(size_t width, size_t height)
{
const int side = rng_()%4;
if(side < 2) {
const int x = rng_()%width;
const int y = side == 0 ? 0 : height-1;
return map_location(x,y);
} else {
const int y = rng_()%height;
const int x = side == 2 ? 0 : width-1;
return map_location(x,y);
}
}
/** Function which, given the map will output it in a valid format. */
static std::string output_map(const terrain_map& terrain,
t_translation::starting_positions& starting_positions)
{
// Remember that we only want the middle 1/9th of the map.
// All other segments of the map are there only to give
// the important middle part some context.
// We also have a border so also adjust for that.
const size_t begin_x = terrain.w / 3 - gamemap::default_border ;
const size_t end_x = terrain.w * 2 / 3 + gamemap::default_border;
const size_t begin_y = terrain.h / 3 - gamemap::default_border;
const size_t end_y = terrain.h * 2 / 3 + gamemap::default_border;
terrain_map map(end_x - begin_x, end_y - begin_y);
for(size_t y = begin_y; y != end_y; ++y) {
for(size_t x = begin_x; x != end_x; ++x) {
map[x - begin_x][y - begin_y] = terrain[x][y];
}
}
// Since the map has been resized,
// the starting locations also need to be fixed
for (auto it = starting_positions.left.begin(); it != starting_positions.left.end(); ++it) {
starting_positions.left.modify_data(it, [=](t_translation::coordinate& pos) { pos.x -= begin_x; pos.y -= begin_y; });
}
return t_translation::write_game_map(map, starting_positions);
}
static int rank_castle_location(int x, int y, const is_valid_terrain& valid_terrain, int min_x, int max_x, int min_y, int max_y, size_t min_distance, const std::vector<map_location>& other_castles, int highest_ranking)
{
const map_location loc(x,y);
size_t avg_distance = 0, lowest_distance = 1000;
for(std::vector<map_location>::const_iterator c = other_castles.begin(); c != other_castles.end(); ++c) {
const size_t distance = distance_between(loc,*c);
if(distance < 6) {
return 0;
}
if(distance < lowest_distance) {
lowest_distance = distance;
}
if(distance < min_distance) {
avg_distance = 0;
return -1;
}
avg_distance += distance;
}
if(!other_castles.empty()) {
avg_distance /= other_castles.size();
}
for(int i = x-1; i <= x+1; ++i) {
for(int j = y-1; j <= y+1; ++j) {
if(!valid_terrain(i,j)) {
return 0;
}
}
}
const int x_from_border = std::min<int>(x - min_x,max_x - x);
const int y_from_border = std::min<int>(y - min_y,max_y - y);
const int border_ranking = min_distance - std::min<int>(x_from_border,y_from_border) + min_distance - x_from_border - y_from_border;
int current_ranking = border_ranking*2 + avg_distance*10 + lowest_distance*10;
static const int num_nearby_locations = 11*11;
const int max_possible_ranking = current_ranking + num_nearby_locations;
if(max_possible_ranking < highest_ranking) {
return current_ranking;
}
int surrounding_ranking = 0;
for(int xpos = x-5; xpos <= x+5; ++xpos) {
for(int ypos = y-5; ypos <= y+5; ++ypos) {
if(valid_terrain(xpos,ypos)) {
++surrounding_ranking;
}
}
}
return surrounding_ranking + current_ranking;
}
typedef std::map<t_translation::terrain_code, t_translation::ter_list> tcode_list_cache;
static map_location place_village(const t_translation::ter_map& map,
const size_t x, const size_t y, const size_t radius, const config& cfg,
tcode_list_cache &adj_liked_cache)
{
const map_location loc(x,y);
std::set<map_location> locs;
get_tiles_radius(loc,radius,locs);
map_location best_loc;
int best_rating = 0;
for(auto i : locs) {
if(i.x < 0 || i.y < 0 || i.x >= map.w ||
i.y >= map.h) {
continue;
}
const t_translation::terrain_code t = map[i.x][i.y];
const std::string str = t_translation::write_terrain_code(t);
if(const config &child = cfg.find_child("village", "terrain", str)) {
tcode_list_cache::iterator l = adj_liked_cache.find(t);
t_translation::ter_list *adjacent_liked;
if(l != adj_liked_cache.end()) {
adjacent_liked = &(l->second);
} else {
adj_liked_cache[t] = t_translation::read_list(child["adjacent_liked"]);
adjacent_liked = &(adj_liked_cache[t]);
}
int rating = child["rating"];
map_location adj[6];
get_adjacent_tiles(map_location(i.x,i.y),adj);
for(size_t n = 0; n != 6; ++n) {
if(adj[n].x < 0 || adj[n].y < 0 ||
adj[n].x >= map.w ||
adj[n].y >= map.h) {
continue;
}
const t_translation::terrain_code t2 = map[adj[n].x][adj[n].y];
rating += std::count(adjacent_liked->begin(),adjacent_liked->end(),t2);
}
if(rating > best_rating) {
best_loc = map_location(i.x,i.y);
best_rating = rating;
}
}
}
return best_loc;
}
// "flood fill" a tile name to adjacent tiles of certain terrain
static void flood_name(const map_location& start, const std::string& name, std::map<map_location,std::string>& tile_names,
const t_translation::ter_match& tile_types, const terrain_map& terrain,
unsigned width, unsigned height,
size_t label_count, std::map<map_location,std::string>* labels, const std::string& full_name) {
map_location adj[6];
get_adjacent_tiles(start,adj);
size_t n;
//if adjacent tiles are tiles and unnamed, name them
for(n = 0; n < 6; n++) {
//we do not care for tiles outside the middle part
//cast to unsigned to skip x < 0 || y < 0 as well.
if(unsigned(adj[n].x) >= width / 3 || unsigned(adj[n].y) >= height / 3) {
continue;
}
const t_translation::terrain_code terr = terrain[adj[n].x + (width / 3)][adj[n].y + (height / 3)];
const map_location loc(adj[n].x, adj[n].y);
if((t_translation::terrain_matches(terr, tile_types)) && (tile_names.find(loc) == tile_names.end())) {
tile_names.insert(std::pair<map_location, std::string>(loc, name));
//labeling decision: this is result of trial and error on what looks best in game
if(label_count % 6 == 0) { //ensure that labels do not occur more often than every 6 recursions
labels->insert(std::pair<map_location, std::string>(loc, full_name));
label_count++; //ensure that no adjacent tiles get labeled
}
flood_name(adj[n], name, tile_names, tile_types, terrain, width, height, label_count++, labels, full_name);
}
}
}
std::string default_map_generator_job::default_generate_map(generator_data data, std::map<map_location,std::string>* labels, const config& cfg)
{
log_scope("map generation");
// Odd widths are nasty
VALIDATE(is_even(data.width), _("Random maps with an odd data.width aren't supported."));
// Try to find configuration for castles
const config& castle_config = cfg.child("castle");
if(!castle_config) {
LOG_NG << "Could not find castle configuration\n";
return std::string();
}
int ticks = SDL_GetTicks();
// We want to generate a map that is 9 times bigger than the actual size desired.
// Only the middle part of the map will be used, but the rest is so that the map we
// end up using can have a context (e.g. rivers flowing from out of the map into the map,
// same for roads, etc.)
data.width *= 3;
data.height *= 3;
config naming = game_config_.child("naming");
if(cfg.has_child("naming")) {
naming.append_attributes(cfg.child("naming"));
}
// If the [naming] child is empty, we cannot provide good names.
std::map<map_location,std::string>* misc_labels = naming.empty() ? nullptr : labels;
std::shared_ptr<name_generator>
base_name_generator, river_name_generator, lake_name_generator,
road_name_generator, bridge_name_generator, mountain_name_generator,
forest_name_generator, swamp_name_generator;
if(misc_labels != nullptr) {
name_generator_factory base_generator_factory{ naming, {"male", "base", "bridge", "road", "river", "forest", "lake", "mountain", "swamp"} };
naming.get_old_attribute("base_names", "male_names", "[naming]male_names= is deprecated, use base_names= instead");
//Due to the attribute detection feature of the factory we also support male_name_generator= but keep it undocumented.
base_name_generator = base_generator_factory.get_name_generator( (naming.has_attribute("base_names") || naming.has_attribute("base_name_generator")) ? "base" : "male" );
river_name_generator = base_generator_factory.get_name_generator("river");
lake_name_generator = base_generator_factory.get_name_generator("lake");
road_name_generator = base_generator_factory.get_name_generator("road");
bridge_name_generator = base_generator_factory.get_name_generator("bridge");
mountain_name_generator = base_generator_factory.get_name_generator("mountain");
forest_name_generator = base_generator_factory.get_name_generator("forest");
swamp_name_generator = base_generator_factory.get_name_generator("swamp");
}
// Generate the height of everything.
const height_map heights = generate_height_map(data.width, data.height, data.iterations, data.hill_size, data.island_size, data.island_off_center);
LOG_NG << "Done generating height map. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
ticks = SDL_GetTicks();
// Find out what the 'flatland' on this map is, i.e. grassland.
std::string flatland = cfg["default_flatland"];
if(flatland.empty()) {
flatland = t_translation::write_terrain_code(t_translation::GRASS_LAND);
}
const t_translation::terrain_code grassland = t_translation::read_terrain_code(flatland);
std::vector<terrain_height_mapper> height_conversion;
for(const config& h : cfg.child_range("height")) {
height_conversion.push_back(terrain_height_mapper(h));
}
terrain_map terrain(data.width, data.height, grassland);
for(size_t x = 0; x != heights.size(); ++x) {
for(size_t y = 0; y != heights[x].size(); ++y) {
for(auto i : height_conversion) {
if(i.convert_terrain(heights[x][y])) {
terrain[x][y] = i.convert_to();
break;
}
}
}
}
t_translation::starting_positions starting_positions;
LOG_NG << output_map(terrain, starting_positions);
LOG_NG << "Placed landforms. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
ticks = SDL_GetTicks();
/* Now that we have our basic set of flatland/hills/mountains/water,
* we can place lakes and rivers on the map.
* All rivers are sourced at a lake.
* Lakes must be in high land - at least 'min_lake_height'.
* (Note that terrain below a certain altitude may be made into bodies of water
* in the code above - i.e. 'sea', but these are not considered 'lakes',
* because they are not sources of rivers).
*
* We attempt to place 'max_lakes' lakes.
* Each lake will be placed at a random location, if that random location meets theminimum
* terrain requirements for a lake. We will also attempt to source a river from each lake.
*/
std::set<map_location> lake_locs;
std::map<map_location, std::string> river_names, lake_names, road_names, bridge_names, mountain_names, forest_names, swamp_names;
const size_t nlakes = data.max_lakes > 0 ? (rng_()%data.max_lakes) : 0;
for(size_t lake = 0; lake != nlakes; ++lake) {
for(int tries = 0; tries != 100; ++tries) {
const int x = rng_()%data.width;
const int y = rng_()%data.height;
if(heights[x][y] <= cfg["min_lake_height"].to_int()) {
continue;
}
std::vector<map_location> river = generate_river(heights, terrain, x, y, cfg["river_frequency"]);
if(!river.empty() && misc_labels != nullptr) {
const std::string base_name = base_name_generator->generate();
const std::string& name = river_name_generator->generate({{"base", base_name}});
LOG_NG << "Named river '" << name << "'\n";
size_t name_frequency = 20;
for(std::vector<map_location>::const_iterator r = river.begin(); r != river.end(); ++r) {
const map_location loc(r->x-data.width/3,r->y-data.height/3);
if(((r - river.begin())%name_frequency) == name_frequency/2) {
misc_labels->insert(std::pair<map_location,std::string>(loc,name));
}
river_names.insert(std::pair<map_location,std::string>(loc,base_name));
}
}
LOG_NG << "Generating lake...\n";
std::set<map_location> locs;
if(generate_lake(terrain, x, y, cfg["lake_size"], locs) && misc_labels != nullptr) {
bool touches_other_lake = false;
std::string base_name = base_name_generator->generate();
const std::string& name = lake_name_generator->generate({{"base", base_name}});
// Only generate a name if the lake hasn't touched any other lakes,
// so that we don't end up with one big lake with multiple names.
for(auto i : locs) {
if(lake_locs.count(i) != 0) {
touches_other_lake = true;
// Reassign the name of this lake to be the same as the other lake
const map_location loc(i.x-data.width/3,i.y-data.height/3);
const std::map<map_location,std::string>::const_iterator other_name = lake_names.find(loc);
if(other_name != lake_names.end()) {
base_name = other_name->second;
}
}
lake_locs.insert(i);
}
if(!touches_other_lake) {
const map_location loc(x-data.width/3,y-data.height/3);
misc_labels->erase(loc);
misc_labels->insert(std::pair<map_location,std::string>(loc,name));
}
for(auto i : locs) {
const map_location loc(i.x-data.width/3,i.y-data.height/3);
lake_names.insert(std::pair<map_location, std::string>(loc, base_name));
}
}
break;
}
}
LOG_NG << "Generated rivers. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
ticks = SDL_GetTicks();
const size_t default_dimensions = 40*40*9;
/*
* Convert grassland terrain to other types of flat terrain.
*
* We generate a 'temperature map' which uses the height generation
* algorithm to generate the temperature levels all over the map. Then we
* can use a combination of height and terrain to divide terrain up into
* more interesting types than the default.
*/
const height_map temperature_map = generate_height_map(data.width,data.height,
cfg["temperature_iterations"].to_int() * data.width * data.height / default_dimensions,
cfg["temperature_size"], 0, 0);
LOG_NG << "Generated temperature map. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
ticks = SDL_GetTicks();
std::vector<terrain_converter> converters;
for(const config& cv : cfg.child_range("convert")) {
converters.push_back(terrain_converter(cv));
}
LOG_NG << "Created terrain converters. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
ticks = SDL_GetTicks();
// Iterate over every flatland tile, and determine what type of flatland it is, based on our [convert] tags.
for(int x = 0; x != data.width; ++x) {
for(int y = 0; y != data.height; ++y) {
for(auto i : converters) {
if(i.convert_terrain(terrain[x][y],heights[x][y],temperature_map[x][y])) {
terrain[x][y] = i.convert_to();
break;
}
}
}
}
LOG_NG << "Placing castles...\n";
/*
* Castle configuration tag contains a 'valid_terrain' attribute which is a
* list of terrains that the castle may appear on.
*/
const t_translation::ter_list list =
t_translation::read_list(castle_config["valid_terrain"]);
const is_valid_terrain terrain_tester(terrain, list);
/*
* Attempt to place castles at random.
*
* After they are placed, we run a sanity check to make sure no two castles
* are closer than 'min_distance' hexes apart, and that they appear on a
* terrain listed in 'valid_terrain'.
*
* If not, we attempt to place them again.
*/
std::vector<map_location> castles;
std::set<map_location> failed_locs;
for(int player = 0; player != data.nplayers; ++player) {
LOG_NG << "placing castle for " << player << "\n";
lg::scope_logger inner_scope_logging_object__(lg::general(), "placing castle");
const int min_x = data.width/3 + 3;
const int min_y = data.height/3 + 3;
const int max_x = (data.width/3)*2 - 4;
const int max_y = (data.height/3)*2 - 4;
int min_distance = castle_config["min_distance"];
map_location best_loc;
int best_ranking = 0;
for(int x = min_x; x != max_x; ++x) {
for(int y = min_y; y != max_y; ++y) {
const map_location loc(x,y);
if(failed_locs.count(loc)) {
continue;
}
const int ranking = rank_castle_location(x, y, terrain_tester, min_x, max_x, min_y, max_y, min_distance, castles, best_ranking);
if(ranking <= 0) {
failed_locs.insert(loc);
}
if(ranking > best_ranking) {
best_ranking = ranking;
best_loc = loc;
}
}
}
if(best_ranking == 0) {
ERR_NG << "No castle location found, aborting." << std::endl;
const std::string error = _("No valid castle location found. Too many or too few mountain hexes? (please check the 'max hill size' parameter)");
throw mapgen_exception(error);
}
assert(std::find(castles.begin(), castles.end(), best_loc) == castles.end());
castles.push_back(best_loc);
// Make sure the location can't get a second castle.
failed_locs.insert(best_loc);
}
LOG_NG << "Placing roads...\n";
ticks = SDL_GetTicks();
// Place roads.
// We select two tiles at random locations on the borders of the map
// and try to build roads between them.
int nroads = cfg["roads"];
if(data.link_castles) {
nroads += castles.size()*castles.size();
}
std::set<map_location> bridges;
road_path_calculator calc(terrain, cfg, rng_());
for(int road = 0; road != nroads; ++road) {
lg::scope_logger another_inner_scope_logging_object__(lg::general(), "creating road");