The Battle for Wesnoth  1.15.0-dev
default_map_generator_job.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 /**
16  * @file
17  * Map-generator, with standalone testprogram.
18  */
19 
22 #include "game_config_manager.hpp"
23 #include "gettext.hpp"
24 #include "log.hpp"
25 #include "map/map.hpp"
26 #include "generators/map_generator.hpp" // mapgen_exception
27 #include "pathfind/pathfind.hpp"
28 #include "pathutils.hpp"
30 #include "seed_rng.hpp"
31 #include "wml_exception.hpp"
32 
33 #include <SDL_timer.h>
34 
35 static lg::log_domain log_mapgen("mapgen");
36 #define ERR_NG LOG_STREAM(err, log_mapgen)
37 #define LOG_NG LOG_STREAM(info, log_mapgen)
38 #define DBG_NG LOG_STREAM(debug, log_mapgen)
39 
40 typedef std::vector<std::vector<int>> height_map;
42 
43 namespace {
44  /**
45  * Calculates the cost of building a road over terrain. For use in the
46  * a_star_search algorithm.
47  */
48  struct road_path_calculator : pathfind::cost_calculator
49  {
50  road_path_calculator(const terrain_map& terrain, const config& cfg, int seed)
51  : calls(0)
52  , map_(terrain)
53  , cfg_(cfg)
54  , windiness_(std::max<int>(1, cfg["road_windiness"].to_int())) // Find out how windey roads should be.
55  , seed_(seed)
56  , cache_()
57  {
58  }
59 
60  virtual double cost(const map_location& loc, const double so_far) const;
61 
62  mutable int calls;
63  private:
64  const terrain_map& map_;
65  const config& cfg_;
66  int windiness_;
67  int seed_;
68  mutable std::map<t_translation::terrain_code, double> cache_;
69  };
70 
71  double road_path_calculator::cost(const map_location& loc, const double /*so_far*/) const
72  {
73  ++calls;
74  if(loc.x < 0 || loc.y < 0 || loc.x >= map_.w || loc.y >= map_.h) {
75 
77  }
78 
79  // We multiply the cost by a random amount,
80  // depending upon how 'windy' the road should be.
81  // If windiness is 1, that will mean that the cost is always genuine,
82  // and so the road always takes the shortest path.
83  // If windiness is greater than 1, we sometimes over-report costs
84  // for some segments, to make the road wind a little.
85 
86  double windiness = 1.0;
87 
88  if(windiness_ > 1) {
89  // modified pseudo_random taken from builder.cpp
90  unsigned int a = (loc.x + 92872973) ^ 918273;
91  unsigned int b = (loc.y + 1672517) ^ 128123;
92  unsigned int c = a*b + a + b + seed_;
93  unsigned int random = c*c;
94  // this is just "big random number modulo windiness_"
95  // but avoid the "modulo by a low number (like 2)"
96  // because it can increase arithmetic patterns
97  int noise = random % (windiness_ * 137) / 137;
98  windiness += noise;
99  }
100 
101  const t_translation::terrain_code c = map_[loc.x][loc.y];
102  const std::map<t_translation::terrain_code, double>::const_iterator itor = cache_.find(c);
103  if(itor != cache_.end()) {
104  return itor->second*windiness;
105  }
106 
107  static std::string terrain;
109  double res = getNoPathValue();
110  if(const config &child = cfg_.find_child("road_cost", "terrain", terrain)) {
111  res = child["cost"].to_double();
112  }
113 
114  cache_.emplace(c, res);
115  return windiness*res;
116  }
117 
118 
119  struct is_valid_terrain
120  {
121  is_valid_terrain(const t_translation::ter_map& map, const t_translation::ter_list& terrain_list);
122  bool operator()(int x, int y) const;
123  private:
125  const t_translation::ter_list& terrain_;
126  };
127 
129  : map_(map), terrain_(terrain_list)
130  {
131  }
132 
133  bool is_valid_terrain::operator()(int x, int y) const
134  {
135  if(x < 0 || x >= map_.w || y < 0 || y >= map_.h) {
136 
137  return false;
138  }
139 
140  return std::find(terrain_.begin(),terrain_.end(),map_[x][y]) != terrain_.end();
141  }
142 
143 
144  /* the configuration file should contain a number of [height] tags:
145  * [height]
146  * height=n
147  * terrain=x
148  * [/height]
149  * These should be in descending order of n.
150  * They are checked sequentially, and if height is greater than n for that tile,
151  * then the tile is set to terrain type x.
152  */
153  class terrain_height_mapper
154  {
155  public:
156  explicit terrain_height_mapper(const config& cfg);
157 
158  bool convert_terrain(const int height) const;
159  t_translation::terrain_code convert_to() const;
160 
161  private:
162  int terrain_height;
164  };
165 
166  terrain_height_mapper::terrain_height_mapper(const config& cfg) :
167  terrain_height(cfg["height"]),
169  {
170  const std::string& terrain = cfg["terrain"];
171  if(!terrain.empty()) {
172  to = t_translation::read_terrain_code(terrain);
173  }
174  }
175 
176  bool terrain_height_mapper::convert_terrain(const int height) const
177  {
178  return height >= terrain_height;
179  }
180 
181  t_translation::terrain_code terrain_height_mapper::convert_to() const
182  {
183  return to;
184  }
185 
186 
187  class terrain_converter
188  {
189  public:
190  explicit terrain_converter(const config& cfg);
191 
192  bool convert_terrain(const t_translation::terrain_code & terrain, const int height, const int temperature) const;
193  t_translation::terrain_code convert_to() const;
194 
195  private:
196  int min_temp, max_temp, min_height, max_height;
199  };
200 
201  terrain_converter::terrain_converter(const config& cfg)
202  : min_temp(cfg["min_temperature"].to_int(-100000))
203  , max_temp(cfg["max_temperature"].to_int(100000))
204  , min_height(cfg["min_height"].to_int(-100000))
205  , max_height(cfg["max_height"].to_int(100000))
206  , from(t_translation::read_list(cfg["from"].str()))
208  {
209  const std::string& to_str = cfg["to"];
210  if(!to_str.empty()) {
212  }
213  }
214 
215  bool terrain_converter::convert_terrain(const t_translation::terrain_code & terrain,
216  const int height, const int temperature) const
217  {
218  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;
219  }
220 
221  t_translation::terrain_code terrain_converter::convert_to() const
222  {
223  return to;
224  }
225 
226 } // end anon namespace
227 
228 
230  : rng_(seed_rng::next_seed())
231  , game_config_(game_config_manager::get()->game_config())
232 {
233 }
234 
236  : rng_(seed)
238 {
239 }
240 
241 /**
242  * Generate a height-map.
243  *
244  * Basically we generate a lot of hills, each hill being centered at a certain
245  * point, with a certain radius - being a half sphere. Hills are combined
246  * additively to form a bumpy surface. The size of each hill varies randomly
247  * from 1-hill_size. We generate 'iterations' hills in total. The range of
248  * heights is normalized to 0-1000. 'island_size' controls whether or not the
249  * map should tend toward an island shape, and if so, how large the island
250  * should be. Hills with centers that are more than 'island_size' away from
251  * the center of the map will be inverted (i.e. be valleys). 'island_size' as
252  * 0 indicates no island.
253  */
254 height_map default_map_generator_job::generate_height_map(std::size_t width, std::size_t height, std::size_t iterations, std::size_t hill_size, std::size_t island_size, std::size_t island_off_center)
255 {
256  height_map res(width, std::vector<int>(height,0));
257 
258  std::size_t center_x = width/2;
259  std::size_t center_y = height/2;
260 
261  LOG_NG << "off-centering...\n";
262 
263  if(island_off_center != 0) {
264  switch(rng_()%4) {
265  case 0:
266  center_x += island_off_center;
267  break;
268  case 1:
269  center_y += island_off_center;
270  break;
271  case 2:
272  if(center_x < island_off_center) {
273  center_x = 0;
274  } else {
275  center_x -= island_off_center;
276  }
277  break;
278  case 3:
279  if(center_y < island_off_center) {
280  center_y = 0;
281  } else {
282  center_y -= island_off_center;
283  }
284  break;
285  }
286  }
287 
288  DBG_NG << iterations << " iterations\n";
289  for(std::size_t i = 0; i != iterations; ++i) {
290 
291  // (x1,y1) is the location of the hill,
292  // and 'radius' is the radius of the hill.
293  // We iterate over all points, (x2,y2).
294  // The formula for the amount the height is increased by is:
295  // radius - sqrt((x2-x1)^2 + (y2-y1)^2) with negative values ignored.
296  //
297  // Rather than iterate over every single point, we can reduce the points
298  // to a rectangle that contains all the positive values for this formula --
299  // the rectangle is given by min_x,max_x,min_y,max_y.
300 
301  // Is this a negative hill? (i.e. a valley)
302  bool is_valley = false;
303 
304  int x1 = island_size > 0 ? center_x - island_size + (rng_()%(island_size*2)) : static_cast<int>(rng_()%width);
305  int y1 = island_size > 0 ? center_y - island_size + (rng_()%(island_size*2)) : static_cast<int>(rng_()%height);
306 
307  // We have to check whether this is actually a valley
308  if(island_size != 0) {
309  const std::size_t diffx = std::abs(x1 - static_cast<int>(center_x));
310  const std::size_t diffy = std::abs(y1 - static_cast<int>(center_y));
311  const std::size_t dist = std::size_t(std::sqrt(static_cast<double>(diffx*diffx + diffy*diffy)));
312  is_valley = dist > island_size;
313  }
314 
315  const int radius = rng_()%hill_size + 1;
316  DBG_NG << "placing hill at " << x1 << "," << y1 << " radius=" << radius << " is_valley=" << is_valley << "\n";
317 
318  const int min_x = x1 - radius > 0 ? x1 - radius : 0;
319  const int max_x = x1 + radius < static_cast<long>(res.size()) ? x1 + radius : res.size();
320  const int min_y = y1 - radius > 0 ? y1 - radius : 0;
321  const int max_y = y1 + radius < static_cast<long>(res.front().size()) ? y1 + radius : res.front().size();
322 
323  for(int x2 = min_x; x2 < max_x; ++x2) {
324  for(int y2 = min_y; y2 < max_y; ++y2) {
325  const int xdiff = (x2-x1);
326  const int ydiff = (y2-y1);
327 
328  const int hill_height = radius - static_cast<int>(std::sqrt(static_cast<double>(xdiff*xdiff + ydiff*ydiff)));
329 
330  if(hill_height > 0) {
331  if(is_valley) {
332  if(hill_height > res[x2][y2]) {
333  res[x2][y2] = 0;
334  } else {
335  res[x2][y2] -= hill_height;
336  }
337  } else {
338  res[x2][y2] += hill_height;
339  }
340  }
341  }
342  }
343  }
344 
345  // Find the highest and lowest points on the map for normalization:
346  int highest = 0, lowest = 100000, x;
347  for(x = 0; std::size_t(x) != res.size(); ++x) {
348  for(int y = 0; std::size_t(y) != res[x].size(); ++y) {
349  if(res[x][y] > highest) {
350  highest = res[x][y];
351  }
352 
353  if(res[x][y] < lowest) {
354  lowest = res[x][y];
355  }
356  }
357  }
358 
359  LOG_NG << "generate_height_map"
360  << " lowest=" << lowest
361  << " highest =" << highest << " \n";
362  // Normalize the heights to the range 0-1000:
363  highest -= lowest;
364  for(x = 0; std::size_t(x) != res.size(); ++x) {
365  for(int y = 0; std::size_t(y) != res[x].size(); ++y) {
366  res[x][y] -= lowest;
367  res[x][y] *= 1000;
368  if(highest != 0) {
369  res[x][y] /= highest;
370  }
371  }
372  }
373 
374  return res;
375 }
376 
377 /**
378  * Generate a lake.
379  *
380  * It will create water at (x,y), and then have 'lake_fall_off' % chance to
381  * make another water tile in each of the directions n,s,e,w. In each of the
382  * directions it does make another water tile, it will have 'lake_fall_off'/2 %
383  * chance to make another water tile in each of the directions. This will
384  * continue recursively.
385  */
386 bool default_map_generator_job::generate_lake(terrain_map& terrain, int x, int y, int lake_fall_off, std::set<map_location>& locs_touched)
387 {
388  if(x < 0 || y < 0 || x >= terrain.w || y >= terrain.h || lake_fall_off < 0) {
389  return false;
390  }
391  //we checked for this eariler.
392  unsigned int ulake_fall_off = lake_fall_off;
393  terrain[x][y] = t_translation::SHALLOW_WATER;
394  locs_touched.insert(map_location(x,y));
395 
396  if((rng_()%100) < ulake_fall_off) {
397  generate_lake(terrain,x+1,y,lake_fall_off/2,locs_touched);
398  }
399 
400  if((rng_()%100) < ulake_fall_off) {
401  generate_lake(terrain,x-1,y,lake_fall_off/2,locs_touched);
402  }
403 
404  if((rng_()%100) < ulake_fall_off) {
405  generate_lake(terrain,x,y+1,lake_fall_off/2,locs_touched);
406  }
407 
408  if((rng_()%100) < ulake_fall_off) {
409  generate_lake(terrain,x,y-1,lake_fall_off/2,locs_touched);
410  }
411 
412  return true;
413 }
414 
415 /**
416  * River generation.
417  *
418  * Rivers have a source, and then keep on flowing until they meet another body
419  * of water, which they flow into, or until they reach the edge of the map.
420  * Rivers will always flow downhill, except that they can flow a maximum of
421  * 'river_uphill' uphill. This is to represent the water eroding the higher
422  * ground lower.
423  *
424  * Every possible path for a river will be attempted, in random order, and the
425  * first river path that can be found that makes the river flow into another
426  * body of water or off the map will be used.
427  *
428  * If no path can be found, then the river's generation will be aborted, and
429  * false will be returned. true is returned if the river is generated
430  * successfully.
431  */
432 
434  terrain_map& terrain, int x, int y, std::vector<map_location>& river,
435  std::set<map_location>& seen_locations, int river_uphill)
436 {
437  const bool on_map = x >= 0 && y >= 0 &&
438  x < static_cast<long>(heights.size()) &&
439  y < static_cast<long>(heights.back().size());
440 
441  if(on_map && !river.empty() && heights[x][y] >
442  heights[river.back().x][river.back().y] + river_uphill) {
443 
444  return false;
445  }
446 
447  // If we're at the end of the river
448  if(!on_map || terrain[x][y] == t_translation::SHALLOW_WATER ||
449  terrain[x][y] == t_translation::DEEP_WATER) {
450 
451  LOG_NG << "generating river...\n";
452 
453  // Generate the river
454  for(auto i : river) {
455  terrain[i.x][i.y] = t_translation::SHALLOW_WATER;
456  }
457 
458  LOG_NG << "done generating river\n";
459 
460  return true;
461  }
462 
463  map_location current_loc(x,y);
465  get_adjacent_tiles(current_loc,adj.data());
466  std::shuffle(std::begin(adj), std::end(adj), rng_);
467 
468  // Mark that we have attempted from this map_location
469  seen_locations.insert(current_loc);
470  river.push_back(current_loc);
471  for(const map_location& loc : adj) {
472  if(seen_locations.count(loc) == 0) {
473  const bool res = generate_river_internal(heights,terrain,loc.x,loc.y,river,seen_locations,river_uphill);
474  if(res) {
475  return true;
476  }
477 
478  }
479  }
480 
481  river.pop_back();
482 
483  return false;
484 }
485 
486 std::vector<map_location> default_map_generator_job::generate_river(const height_map& heights, terrain_map& terrain, int x, int y, int river_uphill)
487 {
488  std::vector<map_location> river;
489  std::set<map_location> seen_locations;
490  const bool res = generate_river_internal(heights,terrain,x,y,river,seen_locations,river_uphill);
491  if(!res) {
492  river.clear();
493  }
494 
495  return river;
496 }
497 
498 /**
499  * Returns a random tile at one of the borders of a map that is of the given
500  * dimensions.
501  */
502 map_location default_map_generator_job::random_point_at_side(std::size_t width, std::size_t height)
503 {
504  const int side = rng_()%4;
505  if(side < 2) {
506  const int x = rng_()%width;
507  const int y = side == 0 ? 0 : height-1;
508  return map_location(x,y);
509  } else {
510  const int y = rng_()%height;
511  const int x = side == 2 ? 0 : width-1;
512  return map_location(x,y);
513  }
514 }
515 
516 /** Function which, given the map will output it in a valid format. */
517 static std::string output_map(const terrain_map& terrain,
519 {
520  // Remember that we only want the middle 1/9th of the map.
521  // All other segments of the map are there only to give
522  // the important middle part some context.
523  // We also have a border so also adjust for that.
524  const std::size_t begin_x = terrain.w / 3 - gamemap::default_border ;
525  const std::size_t end_x = terrain.w * 2 / 3 + gamemap::default_border;
526  const std::size_t begin_y = terrain.h / 3 - gamemap::default_border;
527  const std::size_t end_y = terrain.h * 2 / 3 + gamemap::default_border;
528 
529  terrain_map map(end_x - begin_x, end_y - begin_y);
530  for(std::size_t y = begin_y; y != end_y; ++y) {
531  for(std::size_t x = begin_x; x != end_x; ++x) {
532  map[x - begin_x][y - begin_y] = terrain[x][y];
533  }
534  }
535 
536  // Since the map has been resized,
537  // the starting locations also need to be fixed
538  for (auto it = starting_positions.left.begin(); it != starting_positions.left.end(); ++it) {
539  starting_positions.left.modify_data(it, [=](t_translation::coordinate& pos) { pos.x -= begin_x; pos.y -= begin_y; });
540  }
541  return t_translation::write_game_map(map, starting_positions);
542 }
543 
544 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, std::size_t min_distance, const std::vector<map_location>& other_castles, int highest_ranking)
545 {
546  const map_location loc(x,y);
547 
548  std::size_t avg_distance = 0, lowest_distance = 1000;
549 
550  for(std::vector<map_location>::const_iterator c = other_castles.begin(); c != other_castles.end(); ++c) {
551  const std::size_t distance = distance_between(loc,*c);
552  if(distance < 6) {
553  return 0;
554  }
555 
556  if(distance < lowest_distance) {
557  lowest_distance = distance;
558  }
559 
560  if(distance < min_distance) {
561  return -1;
562  }
563 
564  avg_distance += distance;
565  }
566 
567  if(!other_castles.empty()) {
568  avg_distance /= other_castles.size();
569  }
570 
571  for(int i = x-1; i <= x+1; ++i) {
572  for(int j = y-1; j <= y+1; ++j) {
573  if(!valid_terrain(i,j)) {
574  return 0;
575  }
576  }
577  }
578 
579  const int x_from_border = std::min<int>(x - min_x,max_x - x);
580  const int y_from_border = std::min<int>(y - min_y,max_y - y);
581 
582  const int border_ranking = min_distance - std::min<int>(x_from_border,y_from_border) + min_distance - x_from_border - y_from_border;
583 
584  int current_ranking = border_ranking*2 + avg_distance*10 + lowest_distance*10;
585  static const int num_nearby_locations = 11*11;
586 
587  const int max_possible_ranking = current_ranking + num_nearby_locations;
588 
589  if(max_possible_ranking < highest_ranking) {
590  return current_ranking;
591  }
592 
593  int surrounding_ranking = 0;
594 
595  for(int xpos = x-5; xpos <= x+5; ++xpos) {
596  for(int ypos = y-5; ypos <= y+5; ++ypos) {
597  if(valid_terrain(xpos,ypos)) {
598  ++surrounding_ranking;
599  }
600  }
601  }
602 
603  return surrounding_ranking + current_ranking;
604 }
605 
606 typedef std::map<t_translation::terrain_code, t_translation::ter_list> tcode_list_cache;
607 
609  const std::size_t x, const std::size_t y, const std::size_t radius, const config& cfg,
610  tcode_list_cache &adj_liked_cache)
611 {
612  const map_location loc(x,y);
613  std::set<map_location> locs;
614  get_tiles_radius(loc,radius,locs);
615  map_location best_loc;
616  int best_rating = 0;
617  for(auto i : locs) {
618  if(i.x < 0 || i.y < 0 || i.x >= map.w ||
619  i.y >= map.h) {
620 
621  continue;
622  }
623 
624  const t_translation::terrain_code t = map[i.x][i.y];
625  const std::string str = t_translation::write_terrain_code(t);
626  if(const config &child = cfg.find_child("village", "terrain", str)) {
627  tcode_list_cache::iterator l = adj_liked_cache.find(t);
628  t_translation::ter_list *adjacent_liked;
629  if(l != adj_liked_cache.end()) {
630  adjacent_liked = &(l->second);
631  } else {
632  adj_liked_cache[t] = t_translation::read_list(child["adjacent_liked"].str());
633  adjacent_liked = &(adj_liked_cache[t]);
634  }
635 
636  int rating = child["rating"];
638  get_adjacent_tiles(map_location(i.x,i.y),adj.data());
639  for(std::size_t n = 0; n < adj.size(); ++n) {
640  if(adj[n].x < 0 || adj[n].y < 0 ||
641  adj[n].x >= map.w ||
642  adj[n].y >= map.h) {
643 
644  continue;
645  }
646 
647  const t_translation::terrain_code t2 = map[adj[n].x][adj[n].y];
648  rating += std::count(adjacent_liked->begin(),adjacent_liked->end(),t2);
649  }
650 
651  if(rating > best_rating) {
652  best_loc = map_location(i.x,i.y);
653  best_rating = rating;
654  }
655  }
656  }
657 
658  return best_loc;
659 }
660 
661 // "flood fill" a tile name to adjacent tiles of certain terrain
662 static void flood_name(const map_location& start, const std::string& name, std::map<map_location,std::string>& tile_names,
663  const t_translation::ter_match& tile_types, const terrain_map& terrain,
664  unsigned width, unsigned height,
665  std::size_t label_count, std::map<map_location,std::string>* labels, const std::string& full_name) {
667  get_adjacent_tiles(start,adj.data());
668  std::size_t n;
669  //if adjacent tiles are tiles and unnamed, name them
670  for(n = 0; n < 6; n++) {
671  //we do not care for tiles outside the middle part
672  //cast to unsigned to skip x < 0 || y < 0 as well.
673  if(static_cast<unsigned>(adj[n].x) >= width / 3 || static_cast<unsigned>(adj[n].y) >= height / 3) {
674  continue;
675  }
676 
677  const t_translation::terrain_code terr = terrain[adj[n].x + (width / 3)][adj[n].y + (height / 3)];
678  const map_location loc(adj[n].x, adj[n].y);
679  if((t_translation::terrain_matches(terr, tile_types)) && (tile_names.find(loc) == tile_names.end())) {
680  tile_names.emplace(loc, name);
681  //labeling decision: this is result of trial and error on what looks best in game
682  if(label_count % 6 == 0) { //ensure that labels do not occur more often than every 6 recursions
683  labels->emplace(loc, full_name);
684  label_count++; //ensure that no adjacent tiles get labeled
685  }
686  flood_name(adj[n], name, tile_names, tile_types, terrain, width, height, label_count++, labels, full_name);
687  }
688  }
689 }
690 
691 std::string default_map_generator_job::default_generate_map(generator_data data, std::map<map_location,std::string>* labels, const config& cfg)
692 {
693  log_scope("map generation");
694 
695  LOG_NG << "default_generate_map parameters"
696  << " width=" << data.width
697  << " height=" << data.height
698  << " nplayers=" << data.nplayers
699  << " nvillages=" << data.nvillages
700  << " iterations=" << data.iterations
701  << " hill_size=" << data.hill_size
702  << " castle_size=" << data.castle_size
703  << " island_size=" << data.island_size
704  << " island_off_center=" << data.island_off_center
705  << " max_lakes=" << data.max_lakes
706  << " link_castles=" << data.link_castles
707  << " show_labels=" << data.show_labels << "\n";
708 
709  // Odd widths are nasty
710  VALIDATE(is_even(data.width), _("Random maps with an odd width aren't supported."));
711 
712  // Try to find configuration for castles
713  const config& castle_config = cfg.child("castle");
714 
715  int ticks = SDL_GetTicks();
716 
717  // We want to generate a map that is 9 times bigger than the actual size desired.
718  // Only the middle part of the map will be used, but the rest is so that the map we
719  // end up using can have a context (e.g. rivers flowing from out of the map into the map,
720  // same for roads, etc.)
721  data.width *= 3;
722  data.height *= 3;
723 
724  config naming;
725 
726  if(cfg.has_child("naming")) {
727  naming = game_config_.child("naming");
728  naming.append_attributes(cfg.child("naming"));
729  }
730 
731  // If the [naming] child is empty, we cannot provide good names.
732  std::map<map_location,std::string>* misc_labels = naming.empty() ? nullptr : labels;
733 
734  std::shared_ptr<name_generator>
735  base_name_generator, river_name_generator, lake_name_generator,
736  road_name_generator, bridge_name_generator, mountain_name_generator,
737  forest_name_generator, swamp_name_generator;
738 
739  if(misc_labels != nullptr) {
740  name_generator_factory base_generator_factory{ naming, {"male", "base", "bridge", "road", "river", "forest", "lake", "mountain", "swamp"} };
741 
742  naming.get_old_attribute("base_names", "male_names", "naming");
743  //Due to the attribute detection feature of the factory we also support male_name_generator= but keep it undocumented.
744 
745  base_name_generator = base_generator_factory.get_name_generator( (naming.has_attribute("base_names") || naming.has_attribute("base_name_generator")) ? "base" : "male" );
746  river_name_generator = base_generator_factory.get_name_generator("river");
747  lake_name_generator = base_generator_factory.get_name_generator("lake");
748  road_name_generator = base_generator_factory.get_name_generator("road");
749  bridge_name_generator = base_generator_factory.get_name_generator("bridge");
750  mountain_name_generator = base_generator_factory.get_name_generator("mountain");
751  forest_name_generator = base_generator_factory.get_name_generator("forest");
752  swamp_name_generator = base_generator_factory.get_name_generator("swamp");
753  }
754 
755  // Generate the height of everything.
756  const height_map heights = generate_height_map(data.width, data.height, data.iterations, data.hill_size, data.island_size, data.island_off_center);
757 
758  LOG_NG << "Done generating height map. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
759  ticks = SDL_GetTicks();
760 
761  // Find out what the 'flatland' on this map is, i.e. grassland.
762  std::string flatland = cfg["default_flatland"];
763  if(flatland.empty()) {
765  }
766 
768 
769  std::vector<terrain_height_mapper> height_conversion;
770  for(const config& h : cfg.child_range("height")) {
771  height_conversion.emplace_back(h);
772  }
773 
774  terrain_map terrain(data.width, data.height, grassland);
775  for(std::size_t x = 0; x != heights.size(); ++x) {
776  for(std::size_t y = 0; y != heights[x].size(); ++y) {
777  for(auto i : height_conversion) {
778  if(i.convert_terrain(heights[x][y])) {
779  terrain[x][y] = i.convert_to();
780  break;
781  }
782  }
783  }
784  }
785 
787  LOG_NG << output_map(terrain, starting_positions);
788  LOG_NG << "Placed landforms. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
789  ticks = SDL_GetTicks();
790 
791  /* Now that we have our basic set of flatland/hills/mountains/water,
792  * we can place lakes and rivers on the map.
793  * All rivers are sourced at a lake.
794  * Lakes must be in high land - at least 'min_lake_height'.
795  * (Note that terrain below a certain altitude may be made into bodies of water
796  * in the code above - i.e. 'sea', but these are not considered 'lakes',
797  * because they are not sources of rivers).
798  *
799  * We attempt to place 'max_lakes' lakes.
800  * Each lake will be placed at a random location, if that random location meets theminimum
801  * terrain requirements for a lake. We will also attempt to source a river from each lake.
802  */
803  std::set<map_location> lake_locs;
804 
805  std::map<map_location, std::string> river_names, lake_names, road_names, bridge_names, mountain_names, forest_names, swamp_names;
806 
807  const std::size_t nlakes = data.max_lakes > 0 ? (rng_()%data.max_lakes) : 0;
808  for(std::size_t lake = 0; lake != nlakes; ++lake) {
809  for(int tries = 0; tries != 100; ++tries) {
810  const int x = rng_()%data.width;
811  const int y = rng_()%data.height;
812 
813  if(heights[x][y] <= cfg["min_lake_height"].to_int()) {
814  continue;
815  }
816 
817  std::vector<map_location> river = generate_river(heights, terrain, x, y, cfg["river_frequency"]);
818 
819  if(!river.empty() && misc_labels != nullptr) {
820  const std::string base_name = base_name_generator->generate();
821  const std::string& name = river_name_generator->generate({{"base", base_name}});
822  LOG_NG << "Named river '" << name << "'\n";
823 
824  std::size_t name_frequency = 20;
825  for(std::vector<map_location>::const_iterator r = river.begin(); r != river.end(); ++r) {
826  const map_location loc(r->x-data.width/3,r->y-data.height/3);
827 
828  if(((r - river.begin())%name_frequency) == name_frequency/2) {
829  misc_labels->emplace(loc, name);
830  }
831 
832  river_names.emplace(loc, base_name);
833  }
834  }
835 
836  LOG_NG << "Generating lake...\n";
837 
838  std::set<map_location> locs;
839  if(generate_lake(terrain, x, y, cfg["lake_size"], locs) && misc_labels != nullptr) {
840  bool touches_other_lake = false;
841 
842  std::string base_name = base_name_generator->generate();
843  const std::string& name = lake_name_generator->generate({{"base", base_name}});
844 
845  // Only generate a name if the lake hasn't touched any other lakes,
846  // so that we don't end up with one big lake with multiple names.
847  for(auto i : locs) {
848  if(lake_locs.count(i) != 0) {
849  touches_other_lake = true;
850 
851  // Reassign the name of this lake to be the same as the other lake
852  const map_location loc(i.x-data.width/3,i.y-data.height/3);
853  const std::map<map_location,std::string>::const_iterator other_name = lake_names.find(loc);
854  if(other_name != lake_names.end()) {
855  base_name = other_name->second;
856  }
857  }
858 
859  lake_locs.insert(i);
860  }
861 
862  if(!touches_other_lake) {
863  const map_location loc(x-data.width/3,y-data.height/3);
864  misc_labels->erase(loc);
865  misc_labels->emplace(loc, name);
866  }
867 
868  for(auto i : locs) {
869  const map_location loc(i.x-data.width/3,i.y-data.height/3);
870  lake_names.emplace(loc, base_name);
871  }
872  }
873 
874  break;
875  }
876  }
877 
878  LOG_NG << "Generated rivers. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
879  ticks = SDL_GetTicks();
880 
881  const std::size_t default_dimensions = 40*40*9;
882 
883  /*
884  * Convert grassland terrain to other types of flat terrain.
885  *
886  * We generate a 'temperature map' which uses the height generation
887  * algorithm to generate the temperature levels all over the map. Then we
888  * can use a combination of height and terrain to divide terrain up into
889  * more interesting types than the default.
890  */
891  const height_map temperature_map = generate_height_map(data.width,data.height,
892  cfg["temperature_iterations"].to_int() * data.width * data.height / default_dimensions,
893  cfg["temperature_size"], 0, 0);
894 
895  LOG_NG << "Generated temperature map. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
896  ticks = SDL_GetTicks();
897 
898  std::vector<terrain_converter> converters;
899  for(const config& cv : cfg.child_range("convert")) {
900  converters.emplace_back(cv);
901  }
902 
903  LOG_NG << "Created terrain converters. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
904  ticks = SDL_GetTicks();
905 
906  // Iterate over every flatland tile, and determine what type of flatland it is, based on our [convert] tags.
907  for(int x = 0; x != data.width; ++x) {
908  for(int y = 0; y != data.height; ++y) {
909  for(auto i : converters) {
910  if(i.convert_terrain(terrain[x][y],heights[x][y],temperature_map[x][y])) {
911  terrain[x][y] = i.convert_to();
912  break;
913  }
914  }
915  }
916  }
917 
918  LOG_NG << "Placing castles...\n";
919 
920  /*
921  * Attempt to place castles at random.
922  *
923  * After they are placed, we run a sanity check to make sure no two castles
924  * are closer than 'min_distance' hexes apart, and that they appear on a
925  * terrain listed in 'valid_terrain'.
926  *
927  * If not, we attempt to place them again.
928  */
929  std::vector<map_location> castles;
930  std::set<map_location> failed_locs;
931 
932  if(castle_config) {
933  /*
934  * Castle configuration tag contains a 'valid_terrain' attribute which is a
935  * list of terrains that the castle may appear on.
936  */
937  const t_translation::ter_list list = t_translation::read_list(castle_config["valid_terrain"].str());
938 
939  const is_valid_terrain terrain_tester(terrain, list);
940 
941  for(int player = 0; player != data.nplayers; ++player) {
942  LOG_NG << "placing castle for " << player << "\n";
943  lg::scope_logger inner_scope_logging_object__(lg::general(), "placing castle");
944  const int min_x = data.width/3 + 3;
945  const int min_y = data.height/3 + 3;
946  const int max_x = (data.width/3)*2 - 4;
947  const int max_y = (data.height/3)*2 - 4;
948  int min_distance = castle_config["min_distance"];
949 
950  map_location best_loc;
951  int best_ranking = 0;
952  for(int x = min_x; x != max_x; ++x) {
953  for(int y = min_y; y != max_y; ++y) {
954  const map_location loc(x,y);
955  if(failed_locs.count(loc)) {
956  continue;
957  }
958 
959  const int ranking = rank_castle_location(x, y, terrain_tester, min_x, max_x, min_y, max_y, min_distance, castles, best_ranking);
960  if(ranking <= 0) {
961  failed_locs.insert(loc);
962  }
963 
964  if(ranking > best_ranking) {
965  best_ranking = ranking;
966  best_loc = loc;
967  }
968  }
969  }
970 
971  if(best_ranking == 0) {
972  ERR_NG << "No castle location found, aborting." << std::endl;
973  const std::string error = _("No valid castle location found. Too many or too few mountain hexes? (please check the 'max hill size' parameter)");
974  throw mapgen_exception(error);
975  }
976 
977  assert(std::find(castles.begin(), castles.end(), best_loc) == castles.end());
978  castles.push_back(best_loc);
979 
980  // Make sure the location can't get a second castle.
981  failed_locs.insert(best_loc);
982  }
983 
984  LOG_NG << "Placed castles. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
985  }
986  LOG_NG << "Placing roads...\n";
987  ticks = SDL_GetTicks();
988 
989  // Place roads.
990  // We select two tiles at random locations on the borders of the map
991  // and try to build roads between them.
992  int nroads = cfg["roads"];
993  if(data.link_castles) {
994  nroads += castles.size()*castles.size();
995  }
996 
997  std::set<map_location> bridges;
998 
999  road_path_calculator calc(terrain, cfg, rng_());
1000  for(int road = 0; road != nroads; ++road) {
1001  lg::scope_logger another_inner_scope_logging_object__(lg::general(), "creating road");
1002 
1003  /*
1004  * We want the locations to be on the portion of the map we're actually
1005  * going to use, since roads on other parts of the map won't have any
1006  * influence, and doing it like this will be quicker.
1007  */
1008  map_location src = random_point_at_side(data.width/3 + 2,data.height/3 + 2);
1009  map_location dst = random_point_at_side(data.width/3 + 2,data.height/3 + 2);
1010 
1011  src.x += data.width/3 - 1;
1012  src.y += data.height/3 - 1;
1013  dst.x += data.width/3 - 1;
1014  dst.y += data.height/3 - 1;
1015 
1016  if(data.link_castles && road < static_cast<int>(castles.size() * castles.size())) {
1017  const std::size_t src_castle = road/castles.size();
1018  const std::size_t dst_castle = road%castles.size();
1019  if(src_castle >= dst_castle) {
1020  continue;
1021  }
1022 
1023  src = castles[src_castle];
1024  dst = castles[dst_castle];
1025  } else if(src.x == dst.x || src.y == dst.y) {
1026  // If the road isn't very interesting (on the same border), don't draw it.
1027  continue;
1028  }
1029 
1030  if(calc.cost(src, 0.0) >= 1000.0 || calc.cost(dst, 0.0) >= 1000.0) {
1031  continue;
1032  }
1033 
1034  // Search a path out for the road
1035  pathfind::plain_route rt = pathfind::a_star_search(src, dst, 10000.0, calc, data.width, data.height);
1036 
1037  const std::string& road_base_name = misc_labels != nullptr
1038  ? base_name_generator->generate()
1039  : "";
1040  const std::string& road_name = misc_labels != nullptr
1041  ? road_name_generator->generate({{"base", road_base_name}})
1042  : "";
1043  const int name_frequency = 20;
1044  int name_count = 0;
1045 
1046  bool on_bridge = false;
1047 
1048  // Draw the road.
1049  // If the search failed, rt.steps will simply be empty.
1050  for(std::vector<map_location>::const_iterator step = rt.steps.begin();
1051  step != rt.steps.end(); ++step) {
1052 
1053  const int x = step->x;
1054  const int y = step->y;
1055 
1056  if(x < 0 || y < 0 || x >= static_cast<long>(data.width) || y >= static_cast<long>(data.height)) {
1057  continue;
1058  }
1059 
1060  // Find the configuration which tells us what to convert this tile to, to make it into a road.
1061  const config& child = cfg.find_child("road_cost", "terrain", t_translation::write_terrain_code(terrain[x][y]));
1062  if(child.empty()){
1063  continue;
1064  }
1065 
1066  /* Convert to bridge means that we want to convert depending on the direction of the road.
1067  * Typically it will be in a format like convert_to_bridge = \,|,/
1068  * '|' will be used if the road is going north-south
1069  * '/' will be used if the road is going south west-north east
1070  * '\' will be used if the road is going south east-north west
1071  * The terrain will be left unchanged otherwise (if there is no clear direction).
1072  */
1073  const std::string& convert_to_bridge = child["convert_to_bridge"];
1074  if(!convert_to_bridge.empty()) {
1075  if(step == rt.steps.begin() || step+1 == rt.steps.end()) {
1076  continue;
1077  }
1078 
1079  const map_location& last = *(step-1);
1080  const map_location& next = *(step+1);
1081 
1083  get_adjacent_tiles(*step,adj.data());
1084 
1085  int direction = -1;
1086 
1087  // If we are going north-south
1088  if((last == adj[0] && next == adj[3]) || (last == adj[3] && next == adj[0])) {
1089  direction = 0;
1090  }
1091 
1092  // If we are going south west-north east
1093  else if((last == adj[1] && next == adj[4]) || (last == adj[4] && next == adj[1])) {
1094  direction = 1;
1095  }
1096 
1097  // If we are going south east-north west
1098  else if((last == adj[2] && next == adj[5]) || (last == adj[5] && next == adj[2])) {
1099  direction = 2;
1100  }
1101 
1102  if(misc_labels != nullptr && !on_bridge) {
1103  on_bridge = true;
1104  std::string bridge_base_name = base_name_generator->generate();
1105  const std::string& name = bridge_name_generator->generate({{"base", bridge_base_name}});
1106  const map_location loc(x - data.width / 3, y-data.height/3);
1107  misc_labels->emplace(loc, name);
1108  bridge_names.emplace(loc, bridge_base_name); //add to use for village naming
1109  bridges.insert(loc);
1110  }
1111 
1112  if(direction != -1) {
1113  const std::vector<std::string> items = utils::split(convert_to_bridge);
1114  if(std::size_t(direction) < items.size() && !items[direction].empty()) {
1115  terrain[x][y] = t_translation::read_terrain_code(items[direction]);
1116  }
1117 
1118  continue;
1119  }
1120  } else {
1121  on_bridge = false;
1122  }
1123 
1124  // Just a plain terrain substitution for a road
1125  const std::string& convert_to = child["convert_to"];
1126  if(!convert_to.empty()) {
1128  if(misc_labels != nullptr && terrain[x][y] != letter && name_count++ == name_frequency && !on_bridge) {
1129  misc_labels->emplace(map_location(x - data.width / 3, y - data.height / 3), road_name);
1130  name_count = 0;
1131  }
1132 
1133  terrain[x][y] = letter;
1134  if(misc_labels != nullptr) {
1135  const map_location loc(x - data.width / 3, y - data.height / 3); //add to use for village naming
1136  if(!road_base_name.empty())
1137  road_names.emplace(loc, road_base_name);
1138  }
1139  }
1140  }
1141  }
1142 
1143  // Now that road drawing is done, we can plonk down the castles.
1144  for(std::vector<map_location>::const_iterator c = castles.begin(); c != castles.end(); ++c) {
1145  if(!c->valid()) {
1146  continue;
1147  }
1148 
1149  const int x = c->x;
1150  const int y = c->y;
1151  const int player = c - castles.begin() + 1;
1152  const t_translation::coordinate coord(x, y);
1153  starting_positions.insert(t_translation::starting_positions::value_type(std::to_string(player), coord));
1154  terrain[x][y] = t_translation::HUMAN_KEEP;
1155 
1156  static const std::array<std::array<int, 2>, 13> castle_array {{
1157  {{-1, 0}},
1158  {{-1, -1}},
1159  {{ 0, -1}},
1160  {{ 1, -1}},
1161  {{ 1, 0}},
1162  {{ 0, 1}},
1163  {{-1, 1}},
1164  {{-2, 1}},
1165  {{-2, 0}},
1166  {{-2, -1}},
1167  {{-1, -2}},
1168  {{ 0, -2}},
1169  {{ 1, -2}}
1170  }};
1171 
1172  for(int i = 0; i < data.castle_size - 1; i++) {
1173  terrain[x+ castle_array[i][0]][y+ castle_array[i][1]] = t_translation::HUMAN_CASTLE;
1174  }
1175 
1176  // Remove all labels under the castle tiles
1177  if(labels != nullptr) {
1178  labels->erase(map_location(x-data.width/3,y-data.height/3));
1179  for(int i = 0; i < data.castle_size - 1; i++) {
1180  labels->erase(map_location(x+ castle_array[i][0]-data.width/3, y+ castle_array[i][1]-data.height/3));
1181  }
1182  }
1183  }
1184 
1185  LOG_NG << "Placed roads. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
1186  ticks = SDL_GetTicks();
1187 
1188  /* Random naming for landforms: mountains, forests, swamps, hills
1189  * we name these now that everything else is placed (as e.g., placing
1190  * roads could split a forest)
1191  */
1192  if(misc_labels != nullptr) {
1193  for(int x = data.width / 3; x < (data.width / 3)*2; x++) {
1194  for(int y = data.height / 3; y < (data.height / 3) * 2;y++) {
1195  //check the terrain of the tile
1196  const map_location loc(x - data.width / 3, y - data.height / 3);
1197  const t_translation::terrain_code terr = terrain[x][y];
1198  std::string name, base_name;
1199  std::set<std::string> used_names;
1200 
1202  //name every 15th mountain
1203  if((rng_() % 15) == 0) {
1204  for(std::size_t ntry = 0; ntry != 30 && (ntry == 0 || used_names.count(name) > 0); ++ntry) {
1205  base_name = base_name_generator->generate();
1206  name = mountain_name_generator->generate({{"base", base_name}});
1207  }
1208  misc_labels->emplace(loc, name);
1209  mountain_names.emplace(loc, base_name);
1210  }
1212  // If the forest tile is not named yet, name it
1213  const std::map<map_location, std::string>::const_iterator forest_name = forest_names.find(loc);
1214  if(forest_name == forest_names.end()) {
1215  for(std::size_t ntry = 0; ntry != 30 && (ntry == 0 || used_names.count(name) > 0); ++ntry) {
1216  base_name = base_name_generator->generate();
1217  name = forest_name_generator->generate({{"base", base_name}});
1218  }
1219  forest_names.emplace(loc, base_name);
1220  // name all connected forest tiles accordingly
1221  flood_name(loc, base_name, forest_names, t_translation::ALL_FORESTS, terrain, data.width, data.height, 0, misc_labels, name);
1222  }
1224  // If the swamp tile is not named yet, name it
1225  const std::map<map_location, std::string>::const_iterator swamp_name = swamp_names.find(loc);
1226  if(swamp_name == swamp_names.end()) {
1227  for(std::size_t ntry = 0; ntry != 30 && (ntry == 0 || used_names.count(name) > 0); ++ntry) {
1228  base_name = base_name_generator->generate();
1229  name = swamp_name_generator->generate({{"base", base_name}});
1230  }
1231  swamp_names.emplace(loc, base_name);
1232  // name all connected swamp tiles accordingly
1233  flood_name(loc, base_name, swamp_names, t_translation::ALL_SWAMPS, terrain, data.width, data.height, 0, misc_labels, name);
1234  }
1235  }
1236  }
1237  }
1238  }
1239 
1240  LOG_NG << "Named landforms. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
1241  LOG_NG << "Placing villages...\n";
1242  ticks = SDL_GetTicks();
1243 
1244  /*
1245  * Place villages in a 'grid', to make placing fair, but with villages
1246  * displaced from their position according to terrain and randomness, to
1247  * add some variety.
1248  */
1249  std::set<map_location> villages;
1250 
1251  if(data.nvillages > 0) {
1252 
1253  // First we work out the size of the x and y distance between villages
1254  const std::size_t tiles_per_village = ((data.width*data.height)/9)/data.nvillages;
1255  std::size_t village_x = 1, village_y = 1;
1256 
1257  // Alternate between incrementing the x and y value.
1258  // When they are high enough to equal or exceed the tiles_per_village,
1259  // then we have them to the value we want them at.
1260  while(village_x*village_y < tiles_per_village) {
1261  if(village_x < village_y) {
1262  ++village_x;
1263  } else {
1264  ++village_y;
1265  }
1266  }
1267 
1268  std::set<std::string> used_names;
1269  tcode_list_cache adj_liked_cache;
1270 
1271  config village_naming = game_config_.child("village_naming");
1272 
1273  if(cfg.has_child("village_naming")) {
1274  village_naming.append_attributes(cfg.child("village_naming"));
1275  }
1276 
1277  // If the [village_naming] child is empty, we cannot provide good names.
1278  std::map<map_location,std::string>* village_labels = village_naming.empty() ? nullptr : labels;
1279 
1280  for(int vx = 0; vx < data.width; vx += village_x) {
1281  LOG_NG << "village at " << vx << "\n";
1282 
1283  for(int vy = rng_()%village_y; vy < data.height; vy += village_y) {
1284  const std::size_t add = rng_()%3;
1285  const std::size_t x = (vx + add) - 1;
1286  const std::size_t y = (vy + add) - 1;
1287 
1288  const map_location res = place_village(terrain, x, y, 2, cfg, adj_liked_cache);
1289 
1290  if(res.x < static_cast<long>(data.width ) / 3 ||
1291  res.x >= static_cast<long>(data.width * 2) / 3 ||
1292  res.y < static_cast<long>(data.height ) / 3 ||
1293  res.y >= static_cast<long>(data.height * 2) / 3) {
1294  continue;
1295  }
1296 
1297  const std::string str = t_translation::write_terrain_code(terrain[res.x][res.y]);
1298 
1299  const std::string& convert_to = cfg.find_child("village", "terrain", str)["convert_to"].str();
1300  if(convert_to.empty()) {
1301  continue;
1302  }
1303 
1304  terrain[res.x][res.y] = t_translation::read_terrain_code(convert_to);
1305 
1306  villages.insert(res);
1307 
1308  if(village_labels == nullptr) {
1309  continue;
1310  }
1311 
1312  name_generator_factory village_name_generator_factory{ village_naming,
1313  {"base", "male", "village", "lake", "river", "bridge", "grassland", "forest", "hill", "mountain", "mountain_anon", "road", "swamp"} };
1314 
1315  village_naming.get_old_attribute("base_names", "male_names", "village_naming");
1316  //Due to the attribute detection feature of the factory we also support male_name_generator= but keep it undocumented.
1317 
1318  base_name_generator = village_name_generator_factory.get_name_generator(
1319  (village_naming.has_attribute("base_names") || village_naming.has_attribute("base_name_generator")) ? "base" : "male" );
1320 
1321  const map_location loc(res.x-data.width/3,res.y-data.height/3);
1322 
1324  get_adjacent_tiles(loc,adj.data());
1325 
1326  std::string name_type = "village";
1332 
1333  std::size_t field_count = 0, forest_count = 0, mountain_count = 0, hill_count = 0;
1334 
1335  std::map<std::string,std::string> symbols;
1336 
1337  std::size_t n;
1338  for(n = 0; n != 6; ++n) {
1339  const std::map<map_location,std::string>::const_iterator road_name = road_names.find(adj[n]);
1340  if(road_name != road_names.end()) {
1341  symbols["road"] = road_name->second;
1342  name_type = "road";
1343  break;
1344  }
1345 
1346  const std::map<map_location,std::string>::const_iterator river_name = river_names.find(adj[n]);
1347  if(river_name != river_names.end()) {
1348  symbols["river"] = river_name->second;
1349  name_type = "river";
1350 
1351  const std::map<map_location,std::string>::const_iterator bridge_name = bridge_names.find(adj[n]);
1352  if(bridge_name != bridge_names.end()) {
1353  //we should always end up here, since if there is an adjacent bridge, there has to be an adjacent river too
1354  symbols["bridge"] = bridge_name->second;
1355  name_type = "river_bridge";
1356  }
1357 
1358  break;
1359  }
1360 
1361  const std::map<map_location,std::string>::const_iterator forest_name = forest_names.find(adj[n]);
1362  if(forest_name != forest_names.end()) {
1363  symbols["forest"] = forest_name->second;
1364  name_type = "forest";
1365  break;
1366  }
1367 
1368  const std::map<map_location,std::string>::const_iterator lake_name = lake_names.find(adj[n]);
1369  if(lake_name != lake_names.end()) {
1370  symbols["lake"] = lake_name->second;
1371  name_type = "lake";
1372  break;
1373  }
1374 
1375  const std::map<map_location,std::string>::const_iterator mountain_name = mountain_names.find(adj[n]);
1376  if(mountain_name != mountain_names.end()) {
1377  symbols["mountain"] = mountain_name->second;
1378  name_type = "mountain";
1379  break;
1380  }
1381 
1382  const std::map<map_location,std::string>::const_iterator swamp_name = swamp_names.find(adj[n]);
1383  if(swamp_name != swamp_names.end()) {
1384  symbols["swamp"] = swamp_name->second;
1385  name_type = "swamp";
1386  break;
1387  }
1388 
1389  const t_translation::terrain_code terr = terrain[adj[n].x+data.width/3][adj[n].y+data.height/3];
1390 
1391  if(std::count(field.begin(),field.end(),terr) > 0) {
1392  ++field_count;
1393  } else if(std::count(forest.begin(),forest.end(),terr) > 0) {
1394  ++forest_count;
1395  } else if(std::count(hill.begin(),hill.end(),terr) > 0) {
1396  ++hill_count;
1397  } else if(std::count(mountain.begin(),mountain.end(),terr) > 0) {
1398  ++mountain_count;
1399  }
1400  }
1401 
1402  if(n == 6) {
1403  if(field_count == 6) {
1404  name_type = "grassland";
1405  } else if(forest_count >= 2) {
1406  name_type = "forest";
1407  } else if(mountain_count >= 1) {
1408  name_type = "mountain_anon";
1409  } else if(hill_count >= 2) {
1410  name_type = "hill";
1411  }
1412  }
1413 
1414  std::string name;
1415 
1416  symbols["base"] = base_name_generator->generate();
1417  std::shared_ptr<name_generator> village_name_generator = village_name_generator_factory.get_name_generator(name_type);
1418 
1419  for(std::size_t ntry = 0; ntry != 30 && (ntry == 0 || used_names.count(name) > 0); ++ntry) {
1420  name = village_name_generator->generate(symbols);
1421  }
1422 
1423  used_names.insert(name);
1424  village_labels->emplace(loc, name);
1425  }
1426  }
1427  }
1428 
1429  LOG_NG << "Placed villages. " << (SDL_GetTicks() - ticks) << " ticks elapsed" << "\n";
1430 
1431  return output_map(terrain, starting_positions);
1432 }
static map_location place_village(const t_translation::ter_map &map, const std::size_t x, const std::size_t y, const std::size_t radius, const config &cfg, tcode_list_cache &adj_liked_cache)
config & child(config_key_type key, int n=0)
Returns the nth child with the given key, or a reference to an invalid config if there is none...
Definition: config.cpp:423
void append_attributes(const config &cfg)
Adds attributes from cfg.
Definition: config.cpp:274
const terrain_code NONE_TERRAIN
Definition: translation.hpp:59
#define DBG_NG
void get_adjacent_tiles(const map_location &a, map_location *res)
Function which, given a location, will place all adjacent locations in res.
Definition: location.cpp:517
const terrain_code FOREST
boost::bimaps::bimap< boost::bimaps::set_of< std::string >, boost::bimaps::multiset_of< coordinate > > starting_positions
config & find_child(config_key_type key, const std::string &name, const std::string &value)
Returns the first child of tag key with a name attribute containing value.
Definition: config.cpp:789
Add a special kind of assert to validate whether the input from WML doesn&#39;t contain any problems that...
#define ERR_NG
map_location random_point_at_side(std::size_t width, std::size_t height)
Returns a random tile at one of the borders of a map that is of the given dimensions.
bool terrain_matches(const terrain_code &src, const terrain_code &dest)
Tests whether a specific terrain matches an expression, for matching rules see above.
static l_noret error(LoadState *S, const char *why)
Definition: lundump.cpp:39
bool has_attribute(config_key_type key) const
Definition: config.cpp:217
#define a
bool has_child(config_key_type key) const
Determine whether a config has a child or not.
Definition: config.cpp:416
child_itors child_range(config_key_type key)
Definition: config.cpp:366
static const int default_border
The default border style for a map.
Definition: map.hpp:203
A terrain string which is converted to a terrain is a string with 1 or 2 layers the layers are separa...
Definition: translation.hpp:50
const attribute_value & get_old_attribute(config_key_type key, const std::string &old_key, const std::string &in_tag="") const
Function to handle backward compatibility Get the value of key and if missing try old_key and log msg...
Definition: config.cpp:715
#define h
const std::vector< std::string > items
const terrain_code HUMAN_KEEP
const terrain_code HILL
std::vector< std::string > split(const std::string &val, const char c, const int flags)
Splits a (comma-)separated string into a vector of pieces.
const ter_match ALL_MOUNTAINS("!,*^V*,!,M*")
bool 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)
River generation.
static double getNoPathValue()
Definition: pathfind.hpp:63
#define b
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:89
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, std::size_t min_distance, const std::vector< map_location > &other_castles, int highest_ranking)
const terrain_code MOUNTAIN
std::vector< map_location > steps
Definition: pathfind.hpp:134
#define VALIDATE(cond, message)
The macro to use for the validation of WML.
const t_string name
Structure which holds a single route between one location and another.
Definition: pathfind.hpp:131
bool is_even(T num)
Definition: math.hpp:31
static void field(LexState *ls, struct ConsControl *cc)
Definition: lparser.cpp:702
std::array< map_location, 6 > adjacent_loc_array_t
Definition: location.hpp:170
static std::string output_map(const terrain_map &terrain, t_translation::starting_positions &starting_positions)
Function which, given the map will output it in a valid format.
log_domain & general()
Definition: log.cpp:104
std::string write_terrain_code(const terrain_code &tcode)
Writes a single terrain code to a string.
const terrain_code HUMAN_CASTLE
Encapsulates the map of the game.
Definition: location.hpp:42
std::string default_generate_map(generator_data data, std::map< map_location, std::string > *labels, const config &cfg)
Generate the map.
#define LOG_NG
static lg::log_domain log_mapgen("mapgen")
std::size_t i
Definition: function.cpp:933
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, std::size_t label_count, std::map< map_location, std::string > *labels, const std::string &full_name)
const ter_match ALL_SWAMPS("!,*^V*,*^B*,!,S*")
Game configuration data as global variables.
Definition: build_info.cpp:46
height_map generate_height_map(std::size_t width, std::size_t height, std::size_t iterations, std::size_t hill_size, std::size_t island_size, std::size_t island_off_center)
Generate a height-map.
void get_tiles_radius(const map_location &center, std::size_t radius, std::set< map_location > &result)
Function that will add to result all locations within radius tiles of center (including center itself...
Definition: pathutils.cpp:68
static bool is_valid_terrain(const t_translation::terrain_code &c)
#define log_scope(description)
Definition: log.hpp:186
CURSOR_TYPE get()
Definition: cursor.cpp:213
t_translation::ter_map terrain_map
std::string write_game_map(const ter_map &map, const starting_positions &starting_positions, coordinate border_offset)
Write a gamemap in to a vector string.
std::string base_name(const std::string &file, const bool remove_extension)
Returns the base filename of a file, with directory name stripped.
const terrain_code DEEP_WATER
#define next(ls)
Definition: llex.cpp:32
std::size_t distance_between(const map_location &a, const map_location &b)
Function which gives the number of hexes between two tiles (i.e.
Definition: location.cpp:600
uint32_t next_seed()
Definition: seed_rng.cpp:45
std::vector< std::vector< int > > height_map
double t
Definition: astarsearch.cpp:63
virtual double cost(const map_location &loc, const double so_far) const =0
ter_list read_list(utils::string_view str, const ter_layer filler)
Reads a list of terrains from a string, when reading the.
Standard logging facilities (interface).
std::vector< terrain_code > ter_list
Definition: translation.hpp:78
EXIT_STATUS start(const std::string &filename, bool take_screenshot, const std::string &screenshot_filename)
Main interface for launching the editor from the title screen.
Definition: editor_main.cpp:28
const terrain_code SHALLOW_WATER
std::map< t_translation::terrain_code, t_translation::ter_list > tcode_list_cache
std::vector< game_tip > shuffle(const std::vector< game_tip > &tips)
Shuffles the tips.
Definition: tips.cpp:46
plain_route a_star_search(const map_location &src, const map_location &dst, double stop_at, const cost_calculator &calc, const std::size_t width, const std::size_t height, const teleport_map *teleports, bool border)
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
mock_char c
static map_location::DIRECTION n
This module contains various pathfinding functions and utilities.
This structure can be used for matching terrain strings.
std::string::const_iterator iterator
Definition: tokenizer.hpp:24
bool empty() const
Definition: config.cpp:837
const terrain_code GRASS_LAND
std::vector< map_location > generate_river(const height_map &heights, terrain_map &terrain, int x, int y, int river_uphill)
terrain_code read_terrain_code(const std::string &str, const ter_layer filler)
Reads a single terrain from a string.
std::vector< std::vector< int > > height_map
const ter_match ALL_FORESTS
bool generate_lake(t_translation::ter_map &terrain, int x, int y, int lake_fall_off, std::set< map_location > &locs_touched)
Generate a lake.