OpenTTD
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 <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 #include "landscape.h"
12 #include "company_func.h"
13 #include "genworld.h"
14 #include "gfxinit.h"
15 #include "window_func.h"
16 #include "network/network.h"
17 #include "heightmap.h"
18 #include "viewport_func.h"
19 #include "date_func.h"
20 #include "engine_func.h"
21 #include "water.h"
22 #include "video/video_driver.hpp"
23 #include "tilehighlight_func.h"
24 #include "saveload/saveload.h"
25 #include "void_map.h"
26 #include "town.h"
27 #include "newgrf.h"
28 #include "core/random_func.hpp"
29 #include "core/backup_type.hpp"
30 #include "progress.h"
31 #include "error.h"
32 #include "game/game.hpp"
33 #include "game/game_instance.hpp"
34 #include "string_func.h"
35 #include "thread.h"
36 
37 #include "safeguards.h"
38 
39 
40 void GenerateClearTile();
41 void GenerateIndustries();
42 void GenerateObjects();
43 void GenerateTrees();
44 
45 void StartupEconomy();
46 void StartupCompanies();
47 void StartupDisasters();
48 
49 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
50 
58 
61 
67 {
68  return _gw.threaded && !_gw.quit_thread;
69 }
70 
75 static void CleanupGeneration()
76 {
77  _generating_world = false;
78 
79  SetMouseCursorBusy(false);
80  /* Show all vital windows again, because we have hidden them */
81  if (_gw.threaded && _game_mode != GM_MENU) ShowVitalWindows();
82  SetModalProgress(false);
83  _gw.proc = nullptr;
84  _gw.abortp = nullptr;
85  _gw.threaded = false;
86 
90 }
91 
95 static void _GenerateWorld()
96 {
97  /* Make sure everything is done via OWNER_NONE. */
98  Backup<CompanyID> _cur_company(_current_company, OWNER_NONE, FILE_LINE);
99 
100  std::unique_lock<std::mutex> lock(_modal_progress_work_mutex, std::defer_lock);
101  try {
102  _generating_world = true;
103  lock.lock();
104  if (_network_dedicated) DEBUG(net, 1, "Generating map, please wait...");
105  /* Set the Random() seed to generation_seed so we produce the same map with the same seed */
109  SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
110 
112 
114  /* Must start economy early because of the costs. */
115  StartupEconomy();
116 
117  /* Don't generate landscape items when in the scenario editor. */
118  if (_gw.mode == GWM_EMPTY) {
120 
121  /* Make sure the tiles at the north border are void tiles if needed. */
123  for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
124  for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
125  }
126 
127  /* Make the map the height of the setting */
129 
130  ConvertGroundTilesIntoWaterTiles();
132  } else {
133  GenerateLandscape(_gw.mode);
134  GenerateClearTile();
135 
136  /* Only generate towns, tree and industries in newgame mode. */
137  if (_game_mode != GM_EDITOR) {
139  _cur_company.Restore();
142  if (_network_dedicated) {
143  /* Exit the game to prevent a return to main menu. */
144  DEBUG(net, 0, "Generating map failed, aborting");
145  _exit_game = true;
146  }
147  return;
148  }
150  GenerateObjects();
151  GenerateTrees();
152  }
153  }
154 
155  /* These are probably pointless when inside the scenario editor. */
159  StartupEngines();
161  StartupDisasters();
162  _generating_world = false;
163 
164  /* No need to run the tile loop in the scenario editor. */
165  if (_gw.mode != GWM_EMPTY) {
166  uint i;
167 
169  for (i = 0; i < 0x500; i++) {
170  RunTileLoop();
171  _tick_counter++;
173  }
174 
175  if (_game_mode != GM_EDITOR) {
176  Game::StartNew();
177 
178  if (Game::GetInstance() != nullptr) {
180  _generating_world = true;
181  for (i = 0; i < 2500; i++) {
182  Game::GameLoop();
184  if (Game::GetInstance()->IsSleeping()) break;
185  }
186  _generating_world = false;
187  }
188  }
189  }
190 
192 
194  _cur_company.Trash();
196 
198  /* Call any callback */
199  if (_gw.proc != nullptr) _gw.proc();
201 
203  lock.unlock();
204 
205  ShowNewGRFError();
206 
207  if (_network_dedicated) DEBUG(net, 1, "Map generated, starting game");
208  DEBUG(desync, 1, "new_map: %08x", _settings_game.game_creation.generation_seed);
209 
210  if (_debug_desync_level > 0) {
211  char name[MAX_PATH];
212  seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
214  }
215  } catch (...) {
217  if (_cur_company.IsValid()) _cur_company.Restore();
218  _generating_world = false;
219  throw;
220  }
221 }
222 
229 {
230  _gw.proc = proc;
231 }
232 
239 {
240  _gw.abortp = proc;
241 }
242 
248 {
249  if (!_gw.thread.joinable()) return;
250 
253  _gw.quit_thread = true;
254  _gw.thread.join();
255  _gw.threaded = false;
258 }
259 
264 {
265  _gw.abort = true;
266 }
267 
273 {
274  return _gw.abort;
275 }
276 
281 {
282  /* Clean up - in SE create an empty map, otherwise, go to intro menu */
283  _switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
284 
285  if (_gw.abortp != nullptr) _gw.abortp();
286 
288 
289  if (_gw.thread.joinable() && _gw.thread.get_id() == std::this_thread::get_id()) throw OTTDThreadExitSignal();
290 
291  SwitchToMode(_switch_mode);
292 }
293 
301 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
302 {
303  if (HasModalProgress()) return;
304  _gw.mode = mode;
305  _gw.size_x = size_x;
306  _gw.size_y = size_y;
307  SetModalProgress(true);
308  _gw.abort = false;
309  _gw.abortp = nullptr;
310  _gw.lc = _local_company;
311  _gw.quit_thread = false;
312  _gw.threaded = true;
313 
314  /* This disables some commands and stuff */
316 
317  InitializeGame(_gw.size_x, _gw.size_y, true, reset_settings);
319 
320  /* Load the right landscape stuff, and the NewGRFs! */
321  GfxLoadSprites();
323 
324  /* Re-init the windowing system */
326 
327  /* Create toolbars */
329  SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
330 
331  if (_gw.thread.joinable()) _gw.thread.join();
332 
333  if (!UseThreadedModelProgress() || !VideoDriver::GetInstance()->HasGUI() || !StartNewThread(&_gw.thread, "ottd:genworld", &_GenerateWorld)) {
334  DEBUG(misc, 1, "Cannot create genworld thread, reverting to single-threaded mode");
335  _gw.threaded = false;
337  _GenerateWorld();
339  return;
340  }
341 
343  /* Remove any open window */
345  /* Hide vital windows, because we don't allow to use them */
347 
348  /* Don't show the dialog if we don't have a thread */
350 
351  /* Centre the view on the map */
352  if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) {
353  ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);
354  }
355 }
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows. ...
Definition: main_gui.cpp:552
void GenerateIndustries()
This function will create random industries during game creation.
void PrepareGenerateWorldProgress()
Initializes the progress counters to the starting point.
static uint MapSizeX()
Get the size of the map along the X.
Definition: map_func.h:72
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:79
Base of all video drivers.
static uint MapSizeY()
Get the size of the map along the Y.
Definition: map_func.h:82
static void MakeVoid(TileIndex t)
Make a nice void tile ;)
Definition: void_map.h:19
void GWDoneProc()
Procedure called when the genworld process finishes.
Definition: genworld.h:49
static void GameLoop()
Called every game-tick to let Game do something.
Definition: game_core.cpp:31
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition: gfx.cpp:1603
EconomySettings economy
settings to change the economy
Generate objects (radio tower, light houses)
Definition: genworld.h:74
Switch to game intro menu.
Definition: openttd.h:30
Functions related to dates.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
Progress report of landscape generation; Window numbers:
Definition: window_type.h:456
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition: window.cpp:1130
bool IsValid() const
Checks whether the variable was already restored.
Definition: backup_type.hpp:63
uint size_y
Y-size of the map.
Definition: genworld.h:60
GenWorldMode
Modes for GenerateWorld.
Definition: genworld.h:27
Initialize/allocate the map, start economy.
Definition: genworld.h:68
GenWorldInfo _gw
Please only use this variable in genworld.h and genworld.cpp and nowhere else.
Definition: genworld.cpp:57
std::thread thread
The thread we are in (joinable if a thread was created)
Definition: genworld.h:63
void ShowGenerateWorldProgress()
Show the window where a user can follow the process of the map generation.
void GenerateTrees()
Place new trees.
Definition: tree_cmd.cpp:298
bool IsGenerateWorldThreaded()
Tells if the world generation is done in a thread or not.
Definition: genworld.cpp:66
GenWorldMode mode
What mode are we making a world in.
Definition: genworld.h:57
bool IsGeneratingWorldAborted()
Is the generation being aborted?
Definition: genworld.cpp:272
bool quit_thread
Do we want to quit the active thread.
Definition: genworld.h:55
TownLayout town_layout
select town layout,
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
Functions related to world/map generation.
bool GenerateTowns(TownLayout layout)
This function will generate a certain amount of towns, with a certain layout It can be called from th...
Definition: town_cmd.cpp:2129
void AbortGeneratingWorld()
Initializes the abortion process.
Definition: genworld.cpp:263
void DeleteAllNonVitalWindows()
It is possible that a stickied window gets to a position where the &#39;close&#39; button is outside the gami...
Definition: window.cpp:3391
byte se_flat_world_height
land height a flat world gets in SE
File is being saved.
Definition: fileio_type.h:50
uint size_x
X-size of the map.
Definition: genworld.h:59
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:24
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:55
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
Functions related to (drawing on) viewports.
Pseudo random number generator.
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted...
Definition: genworld.cpp:238
std::mutex _modal_progress_work_mutex
Rights for the performing work.
Definition: progress.cpp:21
bool freeform_edges
allow terraforming the tiles at the map edges
Save game or scenario file.
Definition: fileio_type.h:31
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:48
bool abort
Whether to abort the thread ASAP.
Definition: genworld.h:54
Main window; Window numbers:
Definition: window_type.h:44
Functions related to low-level strings.
The tile has no ownership.
Definition: company_type.h:25
Functions/types related to saving and loading games.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition: genworld.cpp:301
Functions related to errors.
Base of all threads.
Switch to scenario editor.
Definition: openttd.h:28
void HideVitalWindows()
Delete all always on-top windows to get an empty screen.
Definition: window.cpp:3444
static bool UseThreadedModelProgress()
Check if we can use a thread for modal progress.
Definition: progress.h:31
GWDoneProc * proc
Proc that is called when done (can be nullptr)
Definition: genworld.h:61
The client is spectating.
Definition: company_type.h:35
Functions related to engines.
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...
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:34
Functions related to modal progress.
Definition of base types and functions in a cross-platform compatible way.
void LoadStringWidthTable(bool monospace)
Initialize _stringwidth_table cache.
Definition: gfx.cpp:1133
Enter the gameloop, changes will be permanent.
A number of safeguards to prevent using unsafe methods.
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...
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:80
Subdirectory of save for autosaves.
Definition: fileio_type.h:111
The GameInstance tracks games.
bool threaded
Whether we run _GenerateWorld threaded.
Definition: genworld.h:56
Properties of current genworld process.
Definition: genworld.h:53
Generate an empty map (sea-level)
Definition: genworld.h:29
Basic functions/variables used all over the place.
void SetSeed(uint32 seed)
(Re)set the state of the random number generator.
Definition: random_func.cpp:55
static class GameInstance * GetInstance()
Get the current active instance.
Definition: game.hpp:111
SaveOrLoadResult SaveOrLoad(const char *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:2717
Runs the tile loop 1280 times to make snow etc.
Definition: genworld.h:77
void GWAbortProc()
Called when genworld is aborted.
Definition: genworld.h:50
void DeleteWindowByClass(WindowClass cls)
Delete all windows of a given class.
Definition: window.cpp:1175
void StartupCompanies()
Start the next competitor now.
static void StartNew()
Start up a new GameScript.
Definition: game_core.cpp:72
GWAbortProc * abortp
Proc that is called when aborting (can be nullptr)
Definition: genworld.h:62
static void CleanupGeneration()
Clean up the &#39;mess&#39; of generation.
Definition: genworld.cpp:75
void WaitTillGeneratedWorld()
This will wait for the thread to finish up his work.
Definition: genworld.cpp:247
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
void StartupEngines()
Start/initialise all our engines.
Definition: engine.cpp:693
Functions related to the graphics initialization.
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:28
void ShowNewGRFError()
Show the first NewGRF error we can find.
Definition: newgrf_gui.cpp:44
void UnshowCriticalError()
Unshow the critical error.
Definition: error_gui.cpp:359
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done...
Definition: genworld.cpp:228
void Trash()
Trash the backup.
Functions related to companies.
default
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:60
Leave the gameloop, changes will be temporary.
uint32 generation_seed
noise seed for world generation
Functions related to creating heightmaps from files.
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:25
Map accessors for void tiles.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Runs the game script at most 2500 times, or when ever the script sleeps.
Definition: genworld.h:78
CompanyID lc
The local_company before generating.
Definition: genworld.h:58
void FlatEmptyWorld(byte tile_height)
Make an empty world where all tiles are of height &#39;tile_height&#39;.
Definition: heightmap.cpp:510
static void _GenerateWorld()
The internal, real, generate function.
Definition: genworld.cpp:95
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:46
Functions related to OTTD&#39;s landscape.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Definition: viewport.cpp:2396
Base functions for all Games.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:45
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:3305
ConstructionSettings construction
construction of things in-game
void SetModalProgress(bool state)
Set the modal progress state.
Definition: progress.cpp:30
void HandleGeneratingWorldAbortion()
Really handle the abortion, i.e.
Definition: genworld.cpp:280
void Restore()
Restore the variable.
Base of the town class.
std::mutex _modal_progress_paint_mutex
Rights for the painting.
Definition: progress.cpp:23
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks...
Definition: landscape.cpp:801
GameCreationSettings game_creation
settings used during the creation of a game (map)
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows)...
Definition: viewport.cpp:3353
Functions related to tile highlights.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition: window.cpp:1934
Window functions not directly related to making/drawing windows.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Functions related to water (management)
void GenerateLandscape(byte mode)
Definition: landscape.cpp:1293
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Initialize the game.
Definition: genworld.h:76
Date _date
Current date in days (day counter)
Definition: date.cpp:26
void ShowVitalWindows()
Show the vital in-game windows.
Definition: main_gui.cpp:580
Signal used for signalling we knowingly want to end the thread.
Definition: thread.h:18
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:44
Class for backupping variables and making sure they are restored later.
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:163
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:21
Really prepare to start the game.
Definition: genworld.h:79
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1462
void GfxLoadSprites()
Initialise and load all the sprites.
Definition: gfxinit.cpp:338
void ShowFirstError()
Show the first error of the queue.
Definition: error_gui.cpp:345
Base for the NewGRF implementation.