OpenTTD Source: src/genworld.cpp Source File

OpenTTD Source 15.3

genworld.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
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 "newgrf_railtype.h"
41#include "newgrf_roadtype.h"
42#include "string_func.h"
43#include "thread.h"
44#include "tgp.h"
45
46#include "table/strings.h"
47
48#include "safeguards.h"
49
50
51void GenerateClearTile();
52void GenerateIndustries();
53void GenerateObjects();
54void GenerateTrees();
55
56void StartupEconomy();
57void StartupCompanies();
58void StartupDisasters();
59
60void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
61
63 struct GenWorldInfo {
64 static inline bool abort;
65 static inline GenWorldMode mode;
66 static inline CompanyID lc;
67 static inline uint size_x;
68 static inline uint size_y;
69 static inline GWDoneProc *proc;
70 static inline GWAbortProc *abortp;
71};
72
74 bool _generating_world;
75
76 class AbortGenerateWorldSignal { };
77
81 static void CleanupGeneration()
82{
83 _generating_world = false;
84
85 SetMouseCursorBusy(false);
86 SetModalProgress(false);
87 GenWorldInfo::proc = nullptr;
88 GenWorldInfo::abortp = nullptr;
89
90 CloseWindowByClass(WC_MODAL_PROGRESS);
91 ShowFirstError();
92 MarkWholeScreenDirty();
93}
94
98 static void _GenerateWorld()
99{
100 /* Make sure everything is done via OWNER_NONE. */
101 Backup<CompanyID> _cur_company(_current_company, OWNER_NONE);
102
103 try {
104 _generating_world = true;
105 if (_network_dedicated) Debug(net, 3, "Generating map, please wait...");
106 /* Set the Random() seed to generation_seed so we produce the same map with the same seed */
107 _random.SetSeed(_settings_game.game_creation.generation_seed);
108 SetGeneratingWorldProgress(GWP_MAP_INIT, 2);
109 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
110 ScriptObject::InitializeRandomizers();
111
112 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
113
114 IncreaseGeneratingWorldProgress(GWP_MAP_INIT);
115 /* Must start economy early because of the costs. */
116 StartupEconomy();
117 if (!CheckTownRoadTypes()) {
118 HandleGeneratingWorldAbortion();
119 return;
120 }
121
122 bool landscape_generated = false;
123
124 /* Don't generate landscape items when in the scenario editor. */
125 if (GenWorldInfo::mode != GWM_EMPTY) {
126 landscape_generated = GenerateLandscape(GenWorldInfo::mode);
127 }
128
129 if (!landscape_generated) {
130 SetGeneratingWorldProgress(GWP_OBJECT, 1);
131
132 /* Make sure the tiles at the north border are void tiles if needed. */
133 if (_settings_game.construction.freeform_edges) {
134 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, 0));
135 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(0, y));
136 }
137
138 /* Make the map the height of the setting */
139 if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
140
141 ConvertGroundTilesIntoWaterTiles();
142 Map::CountLandTiles();
143 IncreaseGeneratingWorldProgress(GWP_OBJECT);
144
145 _settings_game.game_creation.snow_line_height = DEF_SNOWLINE_HEIGHT;
146 } else {
147 GenerateClearTile();
148 Map::CountLandTiles();
149
150 /* Only generate towns, tree and industries in newgame mode. */
151 if (_game_mode != GM_EDITOR) {
152 if (!GenerateTowns(_settings_game.economy.town_layout)) {
153 HandleGeneratingWorldAbortion();
154 return;
155 }
156 GenerateIndustries();
157 GenerateObjects();
158 GenerateTrees();
159 }
160 }
161
162 /* These are probably pointless when inside the scenario editor. */
163 SetGeneratingWorldProgress(GWP_GAME_INIT, 3);
164 StartupCompanies();
165 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
166 StartupEngines();
167 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
168 StartupDisasters();
169 _generating_world = false;
170
171 Game::StartNew();
172
173 /* No need to run the tile loop in the scenario editor. */
174 if (GenWorldInfo::mode != GWM_EMPTY) {
175 uint i;
176
177 SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500);
178 for (i = 0; i < 0x500; i++) {
179 RunTileLoop();
180 TimerGameTick::counter++;
181 IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
182 }
183
184 if (_game_mode != GM_EDITOR) {
185 if (Game::GetInstance() != nullptr) {
186 SetGeneratingWorldProgress(GWP_RUNSCRIPT, 2500);
187 _generating_world = true;
188 for (i = 0; i < 2500; i++) {
189 Game::GameLoop();
190 IncreaseGeneratingWorldProgress(GWP_RUNSCRIPT);
191 if (Game::GetInstance()->IsSleeping()) break;
192 }
193 _generating_world = false;
194 }
195 }
196 }
197
198 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
199
200 ResetObjectToPlace();
201 _cur_company.Trash();
202 _current_company = _local_company = GenWorldInfo::lc;
203 /* Show all vital windows again, because we have hidden them. */
204 if (_game_mode != GM_MENU) ShowVitalWindows();
205
206 SetGeneratingWorldProgress(GWP_GAME_START, 1);
207 /* Call any callback */
208 if (GenWorldInfo::proc != nullptr) GenWorldInfo::proc();
209 IncreaseGeneratingWorldProgress(GWP_GAME_START);
210
211 CleanupGeneration();
212
213 ShowNewGRFError();
214
215 if (_network_dedicated) Debug(net, 3, "Map generated, starting game");
216 Debug(desync, 1, "new_map: {:08x}", _settings_game.game_creation.generation_seed);
217
218 if (_debug_desync_level > 0) {
219 std::string name = fmt::format("dmp_cmds_{:08x}_{:08x}.sav", _settings_game.game_creation.generation_seed, TimerGameEconomy::date);
220 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
221 }
222 } catch (AbortGenerateWorldSignal&) {
223 CleanupGeneration();
224
225 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP, true);
226 if (_cur_company.IsValid()) _cur_company.Restore();
227
228 if (_network_dedicated) {
229 /* Exit the game to prevent a return to main menu. */
230 Debug(net, 0, "Generating map failed; closing server");
231 _exit_game = true;
232 } else {
233 SwitchToMode(_switch_mode);
234 }
235 }
236}
237
243 void GenerateWorldSetCallback(GWDoneProc *proc)
244{
245 GenWorldInfo::proc = proc;
246}
247
253 void GenerateWorldSetAbortCallback(GWAbortProc *proc)
254{
255 GenWorldInfo::abortp = proc;
256}
257
261 void AbortGeneratingWorld()
262{
263 GenWorldInfo::abort = true;
264}
265
270 bool IsGeneratingWorldAborted()
271{
272 return GenWorldInfo::abort || _exit_game;
273}
274
278 void HandleGeneratingWorldAbortion()
279{
280 /* Clean up - in SE create an empty map, otherwise, go to intro menu */
281 _switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
282
283 if (GenWorldInfo::abortp != nullptr) GenWorldInfo::abortp();
284
285 throw AbortGenerateWorldSignal();
286}
287
295 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
296{
297 if (HasModalProgress()) return;
298 GenWorldInfo::mode = mode;
299 GenWorldInfo::size_x = size_x;
300 GenWorldInfo::size_y = size_y;
301 SetModalProgress(true);
302 GenWorldInfo::abort = false;
303 GenWorldInfo::abortp = nullptr;
304 GenWorldInfo::lc = _local_company;
305
306 /* This disables some commands and stuff */
307 SetLocalCompany(COMPANY_SPECTATOR);
308
309 InitializeGame(GenWorldInfo::size_x, GenWorldInfo::size_y, true, reset_settings);
310 PrepareGenerateWorldProgress();
311
312 if (_settings_game.construction.map_height_limit == 0) {
313 uint estimated_height = 0;
314
315 if (GenWorldInfo::mode == GWM_EMPTY && _game_mode != GM_MENU) {
316 estimated_height = _settings_game.game_creation.se_flat_world_height;
317 } else if (GenWorldInfo::mode == GWM_HEIGHTMAP) {
318 estimated_height = _settings_game.game_creation.heightmap_height;
319 } else if (_settings_game.game_creation.land_generator == LG_TERRAGENESIS) {
320 estimated_height = GetEstimationTGPMapHeight();
321 } else {
322 estimated_height = 0;
323 }
324
325 _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));
326 }
327
328 if (_settings_game.game_creation.generation_seed == GENERATE_NEW_SEED) _settings_game.game_creation.generation_seed = InteractiveRandom();
329
330 /* Load the right landscape stuff, and the NewGRFs! */
331 GfxLoadSprites();
332 SetCurrentRailTypeLabelList();
333 SetCurrentRoadTypeLabelList();
334 InitializeBuildingCounts();
335 LoadStringWidthTable();
336
337 /* Re-init the windowing system */
338 ResetWindowSystem();
339
340 /* Create toolbars */
341 SetupColoursAndInitialWindow();
342 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
343
344 UnshowCriticalError();
345 CloseAllNonVitalWindows();
346 HideVitalWindows();
347
348 ShowGenerateWorldProgress();
349
350 /* Centre the view on the map */
351 ScrollMainWindowToTile(TileXY(Map::SizeX() / 2, Map::SizeY() / 2), true);
352
353 _GenerateWorld();
354}
355
359 void LoadTownData()
360{
361 /* Load the JSON file as a string initially. We'll parse it soon. */
362 size_t filesize;
363 auto f = FioFOpenFile(_file_to_saveload.name, "rb", HEIGHTMAP_DIR, &filesize);
364
365 if (!f.has_value()) {
366 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED),
367 GetEncodedString(STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY), WL_ERROR);
368 return;
369 }
370
371 std::string text(filesize, '\0');
372 size_t len = fread(text.data(), filesize, 1, *f);
373 f.reset();
374 if (len != 1) {
375 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED),
376 GetEncodedString(STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY), WL_ERROR);
377 return;
378 }
379
380 /* Now parse the JSON. */
381 nlohmann::json town_data;
382 try {
383 town_data = nlohmann::json::parse(text);
384 } catch (nlohmann::json::exception &) {
385 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED), GetEncodedString(STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY), WL_ERROR);
386 return;
387 }
388
389 /* Check for JSON formatting errors with the array of towns. */
390 if (!town_data.is_array()) {
391 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED), GetEncodedString(STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY), WL_ERROR);
392 return;
393 }
394
395 std::vector<std::pair<Town *, uint> > towns;
396 uint failed_towns = 0;
397
398 /* Iterate through towns and attempt to found them. */
399 for (auto &feature : town_data) {
400 std::string name; // The name of the town.
401 uint population; // The target population of the town when created in OpenTTD. If input is blank, defaults to 0.
402 bool is_city; // Should it be created as a city in OpenTTD? If input is blank, defaults to false.
403 float x_proportion; // The X coordinate of the town, as a proportion 0..1 of the maximum X coordinate.
404 float y_proportion; // The Y coordinate of the town, as a proportion 0..1 of the maximum Y coordinate.
405
406 /* Ensure JSON is formatted properly. */
407 if (!feature.is_object()) {
408 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED), GetEncodedString(STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY), WL_ERROR);
409 return;
410 }
411
412 /* Check to ensure all fields exist and are of the correct type.
413 * If the town name is formatted wrong, all we can do is give a general warning. */
414 if (!feature.contains("name") || !feature.at("name").is_string()) {
415 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED), GetEncodedString(STR_TOWN_DATA_ERROR_JSON_FORMATTED_INCORRECTLY), WL_ERROR);
416 return;
417 }
418
419 /* If other fields are formatted wrong, we can actually inform the player which town is the problem. */
420 if (!feature.contains("population") || !feature.at("population").is_number() ||
421 !feature.contains("city") || !feature.at("city").is_boolean() ||
422 !feature.contains("x") || !feature.at("x").is_number() ||
423 !feature.contains("y") || !feature.at("y").is_number()) {
424 feature.at("name").get_to(name);
425 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED),
426 GetEncodedString(STR_TOWN_DATA_ERROR_TOWN_FORMATTED_INCORRECTLY, name), WL_ERROR);
427 return;
428 }
429
430 /* Set town properties. */
431 feature.at("name").get_to(name);
432 feature.at("population").get_to(population);
433 feature.at("city").get_to(is_city);
434
435 /* Set town coordinates. */
436 feature.at("x").get_to(x_proportion);
437 feature.at("y").get_to(y_proportion);
438
439 /* Check for improper coordinates and warn the player. */
440 if (x_proportion <= 0.0f || y_proportion <= 0.0f || x_proportion >= 1.0f || y_proportion >= 1.0f) {
441 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_LOAD_FAILED),
442 GetEncodedString(STR_TOWN_DATA_ERROR_BAD_COORDINATE, name), WL_ERROR);
443 return;
444 }
445
446 /* Find the target tile for the town. */
447 TileIndex target_tile;
448 switch (_settings_game.game_creation.heightmap_rotation) {
449 case HM_CLOCKWISE:
450 /* Tile coordinates align with what we expect. */
451 target_tile = TileXY(x_proportion * Map::MaxX(), y_proportion * Map::MaxY());
452 break;
453 case HM_COUNTER_CLOCKWISE:
454 /* Tile coordinates are rotated and must be adjusted. */
455 target_tile = TileXY((1 - y_proportion * Map::MaxX()), x_proportion * Map::MaxY());
456 break;
457 default: NOT_REACHED();
458 }
459
460 TownID town_id; // The TownID of the town in OpenTTD. Not imported, but set during the founding process and stored here for convenience.
461 /* Try founding on the target tile, and if that doesn't work, find the nearest suitable tile up to 16 tiles away.
462 * The target might be on water, blocked somehow, or on a steep slope that can't be terraformed by the founding command. */
463 for (auto tile : SpiralTileSequence(target_tile, 16, 0, 0)) {
464 std::tuple<CommandCost, Money, TownID> result = Command<CMD_FOUND_TOWN>::Do(DoCommandFlag::Execute, tile, TSZ_SMALL, is_city, _settings_game.economy.town_layout, false, 0, name);
465
466 town_id = std::get<TownID>(result);
467
468 /* Check if the command succeeded. */
469 if (town_id != TownID::Invalid()) break;
470 }
471
472 /* 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.
473 * This allows the player to diagnose a heightmap misalignment, if towns end up in the sea, or place towns manually, if in rough terrain. */
474 if (town_id == TownID::Invalid()) {
475 Command<CMD_PLACE_SIGN>::Post(target_tile, name);
476 failed_towns++;
477 continue;
478 }
479
480 towns.emplace_back(std::make_pair(Town::Get(town_id), population));
481 }
482
483 /* If we couldn't found a town (or multiple), display a message to the player with the number of failed towns. */
484 if (failed_towns > 0) {
485 ShowErrorMessage(GetEncodedString(STR_TOWN_DATA_ERROR_FAILED_TO_FOUND_TOWN, failed_towns), {}, WL_WARNING);
486 }
487
488 /* Now that we've created the towns, let's grow them to their target populations. */
489 for (const auto &item : towns) {
490 Town *t = item.first;
491 uint population = item.second;
492
493 /* Grid towns can grow almost forever, but the town growth algorithm gets less and less efficient as it wanders roads randomly,
494 * 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." */
495 int try_limit = 1000;
496
497 /* If a town repeatedly fails to grow, continuing to try only wastes time. */
498 int fail_limit = 10;
499
500 /* Grow by a constant number of houses each time, instead of growth based on current town size.
501 * We want our try limit to apply in a predictable way, no matter the road layout and other geography. */
502 const int HOUSES_TO_GROW = 10;
503
504 do {
505 uint before = t->cache.num_houses;
506 Command<CMD_EXPAND_TOWN>::Post(t->index, HOUSES_TO_GROW, {TownExpandMode::Buildings, TownExpandMode::Roads});
507 if (t->cache.num_houses <= before) fail_limit--;
508 } while (fail_limit > 0 && try_limit-- > 0 && t->cache.population < population);
509 }
510}
backup_type.hpp
Class for backupping variables and making sure they are restored later.
AbortGenerateWorldSignal
Definition genworld.cpp:76
Game::StartNew
static void StartNew()
Start up a new GameScript.
Definition game_core.cpp:72
Game::GetInstance
static class GameInstance * GetInstance()
Get the current active instance.
Definition game.hpp:96
Game::GameLoop
static void GameLoop()
Called every game-tick to let Game do something.
Definition game_core.cpp:31
SpiralTileSequence
Generate TileIndices around a center tile or tile area, with increasing distance.
Definition tilearea_type.h:316
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition timer_game_economy.h:38
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition timer_game_tick.h:60
DoCommandFlag::Execute
@ Execute
execute the given command
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition company_cmd.cpp:55
SetLocalCompany
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Definition company_cmd.cpp:119
_current_company
CompanyID _current_company
Company currently doing an action.
Definition company_cmd.cpp:56
company_func.h
Functions related to companies.
COMPANY_SPECTATOR
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
Definition company_type.h:21
OWNER_NONE
static constexpr Owner OWNER_NONE
The tile has no ownership.
Definition company_type.h:26
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
StartupEngines
void StartupEngines()
Start/initialise all our engines.
Definition engine.cpp:798
engine_func.h
Functions related to engines.
error.h
Functions related to errors.
UnshowCriticalError
void UnshowCriticalError()
Unshow the critical error.
Definition error_gui.cpp:278
WL_WARNING
@ WL_WARNING
Other information.
Definition error.h:25
WL_ERROR
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition error.h:26
ShowErrorMessage
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
Definition error_gui.cpp:296
ShowFirstError
void ShowFirstError()
Show the first error of the queue.
Definition error_gui.cpp:264
FioFOpenFile
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
Definition fileio.cpp:242
SLO_SAVE
@ SLO_SAVE
File is being saved.
Definition fileio_type.h:55
DFT_GAME_FILE
@ DFT_GAME_FILE
Save game or scenario file.
Definition fileio_type.h:31
HEIGHTMAP_DIR
@ HEIGHTMAP_DIR
Subdirectory of scenario for heightmaps.
Definition fileio_type.h:93
AUTOSAVE_DIR
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Definition fileio_type.h:91
game.hpp
Base functions for all Games.
game_instance.hpp
The GameInstance tracks games.
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition genworld.cpp:74
GenerateWorldSetCallback
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
Definition genworld.cpp:243
GenerateWorldSetAbortCallback
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted.
Definition genworld.cpp:253
HandleGeneratingWorldAbortion
void HandleGeneratingWorldAbortion()
Really handle the abortion, i.e.
Definition genworld.cpp:278
GenerateTrees
void GenerateTrees()
Place new trees.
Definition tree_cmd.cpp:469
_GenerateWorld
static void _GenerateWorld()
The internal, real, generate function.
Definition genworld.cpp:98
GenerateIndustries
void GenerateIndustries()
This function will create random industries during game creation.
Definition industry_cmd.cpp:2488
CleanupGeneration
static void CleanupGeneration()
Generation is done; show windows again and delete the progress window.
Definition genworld.cpp:81
GenerateWorld
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition genworld.cpp:295
AbortGeneratingWorld
void AbortGeneratingWorld()
Initializes the abortion process.
Definition genworld.cpp:261
IsGeneratingWorldAborted
bool IsGeneratingWorldAborted()
Is the generation being aborted?
Definition genworld.cpp:270
LoadTownData
void LoadTownData()
Load town data from _file_to_saveload, place towns at the appropriate locations, and expand them to t...
Definition genworld.cpp:359
StartupCompanies
void StartupCompanies()
Start of a new game.
Definition company_cmd.cpp:677
genworld.h
Functions related to world/map generation.
GWAbortProc
void GWAbortProc()
Called when genworld is aborted.
Definition genworld.h:58
IncreaseGeneratingWorldProgress
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Definition genworld_gui.cpp:1539
MAP_HEIGHT_LIMIT_AUTO_MINIMUM
static const uint MAP_HEIGHT_LIMIT_AUTO_MINIMUM
When map height limit is auto, make this the lowest possible map height limit.
Definition genworld.h:54
LG_TERRAGENESIS
@ LG_TERRAGENESIS
TerraGenesis Perlin landscape generator.
Definition genworld.h:22
ShowGenerateWorldProgress
void ShowGenerateWorldProgress()
Show the window where a user can follow the process of the map generation.
Definition genworld_gui.cpp:1457
GWP_OBJECT
@ GWP_OBJECT
Generate objects (radio tower, light houses)
Definition genworld.h:69
GWP_MAP_INIT
@ GWP_MAP_INIT
Initialize/allocate the map, start economy.
Definition genworld.h:62
GWP_RUNSCRIPT
@ GWP_RUNSCRIPT
Runs the game script at most 2500 times, or when ever the script sleeps.
Definition genworld.h:73
GWP_GAME_START
@ GWP_GAME_START
Really prepare to start the game.
Definition genworld.h:74
GWP_GAME_INIT
@ GWP_GAME_INIT
Initialize the game.
Definition genworld.h:71
GWP_RUNTILELOOP
@ GWP_RUNTILELOOP
Runs the tile loop 1280 times to make snow etc.
Definition genworld.h:72
GWDoneProc
void GWDoneProc()
Procedure called when the genworld process finishes.
Definition genworld.h:57
MAP_HEIGHT_LIMIT_AUTO_CEILING_ROOM
static const uint MAP_HEIGHT_LIMIT_AUTO_CEILING_ROOM
When map height limit is auto, the map height limit will be the highest peak plus this value.
Definition genworld.h:55
GENERATE_NEW_SEED
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
Definition genworld.h:25
SetGeneratingWorldProgress
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Definition genworld_gui.cpp:1525
PrepareGenerateWorldProgress
void PrepareGenerateWorldProgress()
Initializes the progress counters to the starting point.
Definition genworld_gui.cpp:1446
GenWorldMode
GenWorldMode
Modes for GenerateWorld.
Definition genworld.h:28
GWM_HEIGHTMAP
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
Definition genworld.h:32
GWM_EMPTY
@ GWM_EMPTY
Generate an empty map (sea-level)
Definition genworld.h:30
LoadStringWidthTable
void LoadStringWidthTable(FontSizes fontsizes)
Initialize _stringwidth_table cache for the specified font sizes.
Definition gfx.cpp:1256
SetMouseCursorBusy
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition gfx.cpp:1690
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:49
GfxLoadSprites
void GfxLoadSprites()
Initialise and load all the sprites.
Definition gfxinit.cpp:335
gfxinit.h
Functions related to the graphics initialization.
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1549
FlatEmptyWorld
void FlatEmptyWorld(uint8_t tile_height)
Make an empty world where all tiles are of height 'tile_height'.
Definition heightmap.cpp:542
heightmap.h
Functions related to creating heightmaps from files.
HM_CLOCKWISE
@ HM_CLOCKWISE
Rotate the map clockwise 45 degrees.
Definition heightmap.h:21
HM_COUNTER_CLOCKWISE
@ HM_COUNTER_CLOCKWISE
Rotate the map counter clockwise 45 degrees.
Definition heightmap.h:20
RunTileLoop
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every TILE_UPDATE_FREQU...
Definition landscape.cpp:798
GenerateLandscape
bool GenerateLandscape(uint8_t mode)
Definition landscape.cpp:1606
landscape.h
Functions related to OTTD's landscape.
ShowVitalWindows
void ShowVitalWindows()
Show the vital in-game windows.
Definition main_gui.cpp:582
SetupColoursAndInitialWindow
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition main_gui.cpp:553
TileXY
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:385
_network_dedicated
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:70
network.h
Basic functions/variables used all over the place.
newgrf.h
Base for the NewGRF implementation.
ShowNewGRFError
void ShowNewGRFError()
Show the first NewGRF error we can find.
Definition newgrf_gui.cpp:47
InitializeBuildingCounts
void InitializeBuildingCounts()
Initialise global building counts and all town building counts.
Definition newgrf_house.cpp:164
newgrf_house.h
Functions related to NewGRF houses.
SetCurrentRailTypeLabelList
void SetCurrentRailTypeLabelList()
Populate railtype label list with current values.
Definition newgrf_railtype.cpp:244
newgrf_railtype.h
NewGRF handling of rail types.
SetCurrentRoadTypeLabelList
void SetCurrentRoadTypeLabelList()
Populate road type label list with current values.
Definition newgrf_roadtype.cpp:270
newgrf_roadtype.h
NewGRF handling of road types.
PSM_ENTER_GAMELOOP
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
Definition newgrf_storage.h:21
PSM_LEAVE_GAMELOOP
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
Definition newgrf_storage.h:22
SM_MENU
@ SM_MENU
Switch to game intro menu.
Definition openttd.h:33
SM_EDITOR
@ SM_EDITOR
Switch to scenario editor.
Definition openttd.h:31
SetModalProgress
void SetModalProgress(bool state)
Set the modal progress state.
Definition progress.cpp:22
progress.h
Functions related to modal progress.
HasModalProgress
bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition progress.h:17
_random
Randomizer _random
Random used in the game state calculations.
Definition random_func.cpp:36
random_func.hpp
Pseudo random number generator.
safeguards.h
A number of safeguards to prevent using unsafe methods.
SaveOrLoad
SaveOrLoadResult SaveOrLoad(std::string_view filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition saveload.cpp:3258
_file_to_saveload
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:78
saveload.h
Functions/types related to saving and loading games.
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
signs_cmd.h
Command definitions related to signs.
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
string_func.h
Functions related to low-level strings.
GetEncodedString
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
strings_func.h
Functions related to OTTD's strings.
Backup
Class to backup a specific variable and restore it later.
Definition backup_type.hpp:21
Backup::IsValid
bool IsValid() const
Checks whether the variable was already restored.
Definition backup_type.hpp:61
Backup::Trash
void Trash()
Trash the backup.
Definition backup_type.hpp:101
Backup::Restore
void Restore()
Restore the variable.
Definition backup_type.hpp:110
BasePersistentStorageArray::SwitchMode
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
Definition newgrf_storage.cpp:53
CommandHelper
Definition command_func.h:84
ConstructionSettings::freeform_edges
bool freeform_edges
allow terraforming the tiles at the map edges
Definition settings_type.h:423
ConstructionSettings::map_height_limit
uint8_t map_height_limit
the maximum allowed heightlevel
Definition settings_type.h:410
EconomySettings::town_layout
TownLayout town_layout
select town layout,
Definition settings_type.h:555
FileToSaveLoad::name
std::string name
Name of the file.
Definition saveload.h:430
GameCreationSettings::snow_line_height
uint8_t snow_line_height
the configured snow line height (deduced from "snow_coverage")
Definition settings_type.h:386
GameCreationSettings::land_generator
uint8_t land_generator
the landscape generator
Definition settings_type.h:384
GameCreationSettings::se_flat_world_height
uint8_t se_flat_world_height
land height a flat world gets in SE
Definition settings_type.h:393
GameCreationSettings::heightmap_rotation
uint8_t heightmap_rotation
rotation director for the heightmap
Definition settings_type.h:392
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition settings_type.h:379
GameCreationSettings::heightmap_height
uint8_t heightmap_height
highest mountain for heightmap (towards what it scales)
Definition settings_type.h:389
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition settings_type.h:642
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition settings_type.h:635
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition settings_type.h:634
GenWorldInfo
Properties of current genworld process.
Definition genworld.cpp:63
GenWorldInfo::proc
static GWDoneProc * proc
Proc that is called when done (can be nullptr)
Definition genworld.cpp:69
GenWorldInfo::lc
static CompanyID lc
The local_company before generating.
Definition genworld.cpp:66
GenWorldInfo::size_x
static uint size_x
X-size of the map.
Definition genworld.cpp:67
GenWorldInfo::size_y
static uint size_y
Y-size of the map.
Definition genworld.cpp:68
GenWorldInfo::abort
static bool abort
Whether to abort the thread ASAP.
Definition genworld.cpp:64
GenWorldInfo::abortp
static GWAbortProc * abortp
Proc that is called when aborting (can be nullptr)
Definition genworld.cpp:70
GenWorldInfo::mode
static GenWorldMode mode
What mode are we making a world in.
Definition genworld.cpp:65
Map::SizeX
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:272
Map::SizeY
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:281
Map::MaxY
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition map_func.h:308
Map::MaxX
static uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition map_func.h:299
PoolID< uint8_t, struct CompanyIDTag, 0xF, 0xFF >
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
Randomizer::SetSeed
void SetSeed(uint32_t seed)
(Re)set the state of the random number generator.
Definition random_func.cpp:55
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
TownCache::population
uint32_t population
Current population of people.
Definition town.h:53
TownCache::num_houses
uint32_t num_houses
Amount of houses.
Definition town.h:52
Town
Town data structure.
Definition town.h:63
Town::cache
TownCache cache
Container for all cacheable data.
Definition town.h:66
GetEstimationTGPMapHeight
uint GetEstimationTGPMapHeight()
Get an overestimation of the highest peak TGP wants to generate.
Definition tgp.cpp:259
tgp.h
Functions for the Perlin noise enhanced map generator.
thread.h
Base of all threads.
DEF_SNOWLINE_HEIGHT
static constexpr uint DEF_SNOWLINE_HEIGHT
Default snowline height.
Definition tile_type.h:33
MAX_MAP_HEIGHT_LIMIT
static constexpr uint MAX_MAP_HEIGHT_LIMIT
Upper bound of maximum allowed heightlevel (in the construction settings)
Definition tile_type.h:30
tilehighlight_func.h
Functions related to tile highlights.
ResetObjectToPlace
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
Definition viewport.cpp:3573
SetObjectToPlace
void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
Definition viewport.cpp:3525
HT_NONE
@ HT_NONE
default
Definition tilehighlight_type.h:20
timer_game_calendar.h
Definition of the game-calendar-timer.
timer_game_tick.h
Definition of the tick-based game-timer.
town.h
Base of the town class.
GenerateTowns
bool GenerateTowns(TownLayout layout, std::optional< uint > number=std::nullopt)
Generate a number of towns with a given layout.
Definition town_cmd.cpp:2448
CheckTownRoadTypes
bool CheckTownRoadTypes()
Check if towns are able to build road.
Definition town_cmd.cpp:1015
town_cmd.h
Command definitions related to towns.
TSZ_SMALL
@ TSZ_SMALL
Small town.
Definition town_type.h:22
video_driver.hpp
Base of all video drivers.
ScrollMainWindowToTile
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Definition viewport.cpp:2592
viewport_func.h
Functions related to (drawing on) viewports.
void_map.h
Map accessors for void tiles.
MakeVoid
void MakeVoid(Tile t)
Make a nice void tile ;)
Definition void_map.h:19
water.h
Functions related to water (management)
CloseWindowByClass
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
Definition window.cpp:1207
ResetWindowSystem
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition window.cpp:1895
HideVitalWindows
void HideVitalWindows()
Close all always on-top windows to get an empty screen.
Definition window.cpp:3396
CloseAllNonVitalWindows
void CloseAllNonVitalWindows()
It is possible that a stickied window gets to a position where the 'close' button is outside the gami...
Definition window.cpp:3358
window_func.h
Window functions not directly related to making/drawing windows.
WC_MAIN_WINDOW
@ WC_MAIN_WINDOW
Main window; Window numbers:
Definition window_type.h:56
WC_MODAL_PROGRESS
@ WC_MODAL_PROGRESS
Progress report of landscape generation; Window numbers:
Definition window_type.h:474