Update: Translations from eints
[openttd-github.git] / src / genworld.cpp
blobd16a017c1f0e86a79c622577caea1471d3ebedaa
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file genworld.cpp Functions to generate a map. */
10 #include "stdafx.h"
11 #include "landscape.h"
12 #include "company_func.h"
13 #include "town_cmd.h"
14 #include "signs_cmd.h"
15 #include "3rdparty/nlohmann/json.hpp"
16 #include "strings_func.h"
17 #include "genworld.h"
18 #include "gfxinit.h"
19 #include "window_func.h"
20 #include "network/network.h"
21 #include "heightmap.h"
22 #include "viewport_func.h"
23 #include "timer/timer_game_calendar.h"
24 #include "timer/timer_game_tick.h"
25 #include "engine_func.h"
26 #include "water.h"
27 #include "video/video_driver.hpp"
28 #include "tilehighlight_func.h"
29 #include "saveload/saveload.h"
30 #include "void_map.h"
31 #include "town.h"
32 #include "newgrf.h"
33 #include "newgrf_house.h"
34 #include "core/random_func.hpp"
35 #include "core/backup_type.hpp"
36 #include "progress.h"
37 #include "error.h"
38 #include "game/game.hpp"
39 #include "game/game_instance.hpp"
40 #include "string_func.h"
41 #include "thread.h"
42 #include "tgp.h"
44 #include "safeguards.h"
47 void GenerateClearTile();
48 void GenerateIndustries();
49 void GenerateObjects();
50 void GenerateTrees();
52 void StartupEconomy();
53 void StartupCompanies();
54 void StartupDisasters();
56 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
58 /**
59 * Please only use this variable in genworld.h and genworld.cpp and
60 * nowhere else. For speed improvements we need it to be global, but
61 * in no way the meaning of it is to use it anywhere else besides
62 * in the genworld.h and genworld.cpp!
64 GenWorldInfo _gw;
66 /** Whether we are generating the map or not. */
67 bool _generating_world;
69 class AbortGenerateWorldSignal { };
71 /**
72 * Generation is done; show windows again and delete the progress window.
74 static void CleanupGeneration()
76 _generating_world = false;
78 SetMouseCursorBusy(false);
79 SetModalProgress(false);
80 _gw.proc = nullptr;
81 _gw.abortp = nullptr;
83 CloseWindowByClass(WC_MODAL_PROGRESS);
84 ShowFirstError();
85 MarkWholeScreenDirty();
88 /**
89 * The internal, real, generate function.
91 static void _GenerateWorld()
93 /* Make sure everything is done via OWNER_NONE. */
94 Backup<CompanyID> _cur_company(_current_company, OWNER_NONE);
96 try {
97 _generating_world = true;
98 if (_network_dedicated) Debug(net, 3, "Generating map, please wait...");
99 /* Set the Random() seed to generation_seed so we produce the same map with the same seed */
100 _random.SetSeed(_settings_game.game_creation.generation_seed);
101 SetGeneratingWorldProgress(GWP_MAP_INIT, 2);
102 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
103 ScriptObject::InitializeRandomizers();
105 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
107 IncreaseGeneratingWorldProgress(GWP_MAP_INIT);
108 /* Must start economy early because of the costs. */
109 StartupEconomy();
110 if (!CheckTownRoadTypes()) {
111 HandleGeneratingWorldAbortion();
112 return;
115 bool landscape_generated = false;
117 /* Don't generate landscape items when in the scenario editor. */
118 if (_gw.mode != GWM_EMPTY) {
119 landscape_generated = GenerateLandscape(_gw.mode);
122 if (!landscape_generated) {
123 SetGeneratingWorldProgress(GWP_OBJECT, 1);
125 /* Make sure the tiles at the north border are void tiles if needed. */
126 if (_settings_game.construction.freeform_edges) {
127 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
128 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
131 /* Make the map the height of the setting */
132 if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
134 ConvertGroundTilesIntoWaterTiles();
135 IncreaseGeneratingWorldProgress(GWP_OBJECT);
137 _settings_game.game_creation.snow_line_height = DEF_SNOWLINE_HEIGHT;
138 } else {
139 GenerateClearTile();
141 /* Only generate towns, tree and industries in newgame mode. */
142 if (_game_mode != GM_EDITOR) {
143 if (!GenerateTowns(_settings_game.economy.town_layout)) {
144 HandleGeneratingWorldAbortion();
145 return;
147 GenerateIndustries();
148 GenerateObjects();
149 GenerateTrees();
153 /* These are probably pointless when inside the scenario editor. */
154 SetGeneratingWorldProgress(GWP_GAME_INIT, 3);
155 StartupCompanies();
156 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
157 StartupEngines();
158 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
159 StartupDisasters();
160 _generating_world = false;
162 /* No need to run the tile loop in the scenario editor. */
163 if (_gw.mode != GWM_EMPTY) {
164 uint i;
166 SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500);
167 for (i = 0; i < 0x500; i++) {
168 RunTileLoop();
169 TimerGameTick::counter++;
170 IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
173 if (_game_mode != GM_EDITOR) {
174 Game::StartNew();
176 if (Game::GetInstance() != nullptr) {
177 SetGeneratingWorldProgress(GWP_RUNSCRIPT, 2500);
178 _generating_world = true;
179 for (i = 0; i < 2500; i++) {
180 Game::GameLoop();
181 IncreaseGeneratingWorldProgress(GWP_RUNSCRIPT);
182 if (Game::GetInstance()->IsSleeping()) break;
184 _generating_world = false;
189 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
191 ResetObjectToPlace();
192 _cur_company.Trash();
193 _current_company = _local_company = _gw.lc;
194 /* Show all vital windows again, because we have hidden them. */
195 if (_game_mode != GM_MENU) ShowVitalWindows();
197 SetGeneratingWorldProgress(GWP_GAME_START, 1);
198 /* Call any callback */
199 if (_gw.proc != nullptr) _gw.proc();
200 IncreaseGeneratingWorldProgress(GWP_GAME_START);
202 CleanupGeneration();
204 ShowNewGRFError();
206 if (_network_dedicated) Debug(net, 3, "Map generated, starting game");
207 Debug(desync, 1, "new_map: {:08x}", _settings_game.game_creation.generation_seed);
209 if (_debug_desync_level > 0) {
210 std::string name = fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game.game_creation.generation_seed, TimerGameEconomy::date);
211 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
213 } catch (AbortGenerateWorldSignal&) {
214 CleanupGeneration();
216 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP, true);
217 if (_cur_company.IsValid()) _cur_company.Restore();
219 if (_network_dedicated) {
220 /* Exit the game to prevent a return to main menu. */
221 Debug(net, 0, "Generating map failed; closing server");
222 _exit_game = true;
223 } else {
224 SwitchToMode(_switch_mode);
230 * Set here the function, if any, that you want to be called when landscape
231 * generation is done.
232 * @param proc callback procedure
234 void GenerateWorldSetCallback(GWDoneProc *proc)
236 _gw.proc = proc;
240 * Set here the function, if any, that you want to be called when landscape
241 * generation is aborted.
242 * @param proc callback procedure
244 void GenerateWorldSetAbortCallback(GWAbortProc *proc)
246 _gw.abortp = proc;
250 * Initializes the abortion process
252 void AbortGeneratingWorld()
254 _gw.abort = true;
258 * Is the generation being aborted?
259 * @return the 'aborted' status
261 bool IsGeneratingWorldAborted()
263 return _gw.abort || _exit_game;
267 * Really handle the abortion, i.e. clean up some of the mess
269 void HandleGeneratingWorldAbortion()
271 /* Clean up - in SE create an empty map, otherwise, go to intro menu */
272 _switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
274 if (_gw.abortp != nullptr) _gw.abortp();
276 throw AbortGenerateWorldSignal();
280 * Generate a world.
281 * @param mode The mode of world generation (see GenWorldMode).
282 * @param size_x The X-size of the map.
283 * @param size_y The Y-size of the map.
284 * @param reset_settings Whether to reset the game configuration (used for restart)
286 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
288 if (HasModalProgress()) return;
289 _gw.mode = mode;
290 _gw.size_x = size_x;
291 _gw.size_y = size_y;
292 SetModalProgress(true);
293 _gw.abort = false;
294 _gw.abortp = nullptr;
295 _gw.lc = _local_company;
297 /* This disables some commands and stuff */
298 SetLocalCompany(COMPANY_SPECTATOR);
300 InitializeGame(_gw.size_x, _gw.size_y, true, reset_settings);
301 PrepareGenerateWorldProgress();
303 if (_settings_game.construction.map_height_limit == 0) {
304 uint estimated_height = 0;
306 if (_gw.mode == GWM_EMPTY && _game_mode != GM_MENU) {
307 estimated_height = _settings_game.game_creation.se_flat_world_height;
308 } else if (_gw.mode == GWM_HEIGHTMAP) {
309 estimated_height = _settings_game.game_creation.heightmap_height;
310 } else if (_settings_game.game_creation.land_generator == LG_TERRAGENESIS) {
311 estimated_height = GetEstimationTGPMapHeight();
312 } else {
313 estimated_height = 0;
316 _settings_game.construction.map_height_limit = std::max(MAP_HEIGHT_LIMIT_AUTO_MINIMUM, std::min(MAX_MAP_HEIGHT_LIMIT, estimated_height + MAP_HEIGHT_LIMIT_AUTO_CEILING_ROOM));
319 if (_settings_game.game_creation.generation_seed == GENERATE_NEW_SEED) _settings_game.game_creation.generation_seed = InteractiveRandom();
321 /* Load the right landscape stuff, and the NewGRFs! */
322 GfxLoadSprites();
323 InitializeBuildingCounts();
324 LoadStringWidthTable();
326 /* Re-init the windowing system */
327 ResetWindowSystem();
329 /* Create toolbars */
330 SetupColoursAndInitialWindow();
331 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
333 UnshowCriticalError();
334 CloseAllNonVitalWindows();
335 HideVitalWindows();
337 ShowGenerateWorldProgress();
339 /* Centre the view on the map */
340 ScrollMainWindowToTile(TileXY(Map::SizeX() / 2, Map::SizeY() / 2), true);
342 _GenerateWorld();
345 /** Town data imported from JSON files and used to place towns. */
346 struct ExternalTownData {
347 TownID town_id; ///< The TownID of the town in OpenTTD. Not imported, but set during the founding proceess and stored here for convenience.
348 std::string name; ///< The name of the town.
349 uint population; ///< The target population of the town when created in OpenTTD. If input is blank, defaults to 0.
350 bool is_city; ///< Should it be created as a city in OpenTTD? If input is blank, defaults to false.
351 float x_proportion; ///< The X coordinate of the town, as a proportion 0..1 of the maximum X coordinate.
352 float y_proportion; ///< The Y coordinate of the town, as a proportion 0..1 of the maximum Y coordinate.
356 * Helper for CircularTileSearch to found a town on or near a given tile.
357 * @param tile The tile to try founding the town upon.
358 * @param user_data The ExternalTownData to attempt to found.
359 * @return True if the town was founded successfully.
361 static bool TryFoundTownNearby(TileIndex tile, void *user_data)
363 ExternalTownData &town = *static_cast<ExternalTownData *>(user_data);
364 std::tuple<CommandCost, Money, TownID> result = Command<CMD_FOUND_TOWN>::Do(DC_EXEC, tile, TSZ_SMALL, town.is_city, _settings_game.economy.town_layout, false, 0, town.name);
366 TownID id = std::get<TownID>(result);
368 /* Check if the command failed. */
369 if (id == INVALID_TOWN) return false;
371 /* The command succeeded, send the ID back through user_data. */
372 town.town_id = id;
373 return true;
377 * Load town data from _file_to_saveload, place towns at the appropriate locations, and expand them to their target populations.
379 void LoadTownData()
381 /* Load the JSON file as a string initially. We'll parse it soon. */
382 size_t filesize;
383 auto f = FioFOpenFile(_file_to_saveload.name, "rb", HEIGHTMAP_DIR, &filesize);
385 if (!f.has_value()) {
386 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY, WL_ERROR);
387 return;
390 std::string text(filesize, '\0');
391 size_t len = fread(text.data(), filesize, 1, *f);
392 f.reset();
393 if (len != 1) {
394 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY, WL_ERROR);
395 return;
398 /* Now parse the JSON. */
399 nlohmann::json town_data;
400 try {
401 town_data = nlohmann::json::parse(text);
402 } catch (nlohmann::json::exception &) {
403 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY, WL_ERROR);
404 return;
407 /* Check for JSON formatting errors with the array of towns. */
408 if (!town_data.is_array()) {
409 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY, WL_ERROR);
410 return;
413 std::vector<std::pair<Town *, uint> > towns;
414 uint failed_towns = 0;
416 /* Iterate through towns and attempt to found them. */
417 for (auto &feature : town_data) {
418 ExternalTownData town;
420 /* Ensure JSON is formatted properly. */
421 if (!feature.is_object()) {
422 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY, WL_ERROR);
423 return;
426 /* Check to ensure all fields exist and are of the correct type.
427 * If the town name is formatted wrong, all we can do is give a general warning. */
428 if (!feature.contains("name") || !feature.at("name").is_string()) {
429 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY, WL_ERROR);
430 return;
433 /* If other fields are formatted wrong, we can actually inform the player which town is the problem. */
434 if (!feature.contains("population") || !feature.at("population").is_number() ||
435 !feature.contains("city") || !feature.at("city").is_boolean() ||
436 !feature.contains("x") || !feature.at("x").is_number() ||
437 !feature.contains("y") || !feature.at("y").is_number()) {
438 feature.at("name").get_to(town.name);
439 SetDParamStr(0, town.name);
440 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_TOWN_FORMATTED_INCORRECTLY, WL_ERROR);
441 return;
444 /* Set town properties. */
445 feature.at("name").get_to(town.name);
446 feature.at("population").get_to(town.population);
447 feature.at("city").get_to(town.is_city);
449 /* Set town coordinates. */
450 feature.at("x").get_to(town.x_proportion);
451 feature.at("y").get_to(town.y_proportion);
453 /* Check for improper coordinates and warn the player. */
454 if (town.x_proportion <= 0.0f || town.y_proportion <= 0.0f || town.x_proportion >= 1.0f || town.y_proportion >= 1.0f) {
455 SetDParamStr(0, town.name);
456 ShowErrorMessage(STR_TOWN_DATA_ERROR_LOAD_FAILED, STR_TOWN_DATA_ERROR_BAD_COORDINATE, WL_ERROR);
457 return;
460 /* Find the target tile for the town. */
461 TileIndex tile;
462 switch (_settings_game.game_creation.heightmap_rotation) {
463 case HM_CLOCKWISE:
464 /* Tile coordinates align with what we expect. */
465 tile = TileXY(town.x_proportion * Map::MaxX(), town.y_proportion * Map::MaxY());
466 break;
467 case HM_COUNTER_CLOCKWISE:
468 /* Tile coordinates are rotated and must be adjusted. */
469 tile = TileXY((1 - town.y_proportion * Map::MaxX()), town.x_proportion * Map::MaxY());
470 break;
471 default: NOT_REACHED();
474 /* Try founding on the target tile, and if that doesn't work, find the nearest suitable tile up to 16 tiles away.
475 * The target might be on water, blocked somehow, or on a steep slope that can't be terraformed by the founding command. */
476 TileIndex search_tile = tile;
477 bool success = CircularTileSearch(&search_tile, 16, 0, 0, TryFoundTownNearby, &town);
479 /* If we still fail to found the town, we'll create a sign at the intended location and tell the player how many towns we failed to create in an error message.
480 * This allows the player to diagnose a heightmap misalignment, if towns end up in the sea, or place towns manually, if in rough terrain. */
481 if (!success) {
482 Command<CMD_PLACE_SIGN>::Post(tile, town.name);
483 failed_towns++;
484 continue;
487 towns.emplace_back(std::make_pair(Town::Get(town.town_id), town.population));
490 /* If we couldn't found a town (or multiple), display a message to the player with the number of failed towns. */
491 if (failed_towns > 0) {
492 SetDParam(0, failed_towns);
493 ShowErrorMessage(STR_TOWN_DATA_ERROR_FAILED_TO_FOUND_TOWN, INVALID_STRING_ID, WL_WARNING);
496 /* Now that we've created the towns, let's grow them to their target populations. */
497 for (const auto &item : towns) {
498 Town *t = item.first;
499 uint population = item.second;
501 /* Grid towns can grow almost forever, but the town growth algorithm gets less and less efficient as it wanders roads randomly,
502 * so we set an arbitrary limit. With a flat map and a 3x3 grid layout this results in about 4900 houses, or 2800 houses with "Better roads." */
503 int try_limit = 1000;
505 /* If a town repeatedly fails to grow, continuing to try only wastes time. */
506 int fail_limit = 10;
508 /* Grow by a constant number of houses each time, instead of growth based on current town size.
509 * We want our try limit to apply in a predictable way, no matter the road layout and other geography. */
510 const int HOUSES_TO_GROW = 10;
512 do {
513 uint before = t->cache.num_houses;
514 Command<CMD_EXPAND_TOWN>::Post(t->index, HOUSES_TO_GROW);
515 if (t->cache.num_houses <= before) fail_limit--;
516 } while (fail_limit > 0 && try_limit-- > 0 && t->cache.population < population);