Codechange: Use cached town, station, industry names for list window sorting
[openttd-github.git] / src / genworld.cpp
blobc76fe309d9bcf4fb093882c6a3492a0a5096093f
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 "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"
37 #include "safeguards.h"
40 void GenerateClearTile();
41 void GenerateIndustries();
42 void GenerateObjects();
43 void GenerateTrees();
45 void StartupEconomy();
46 void StartupCompanies();
47 void StartupDisasters();
49 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
51 /**
52 * Please only use this variable in genworld.h and genworld.cpp and
53 * nowhere else. For speed improvements we need it to be global, but
54 * in no way the meaning of it is to use it anywhere else besides
55 * in the genworld.h and genworld.cpp!
57 GenWorldInfo _gw;
59 /** Whether we are generating the map or not. */
60 bool _generating_world;
62 /**
63 * Tells if the world generation is done in a thread or not.
64 * @return the 'threaded' status
66 bool IsGenerateWorldThreaded()
68 return _gw.threaded && !_gw.quit_thread;
71 /**
72 * Clean up the 'mess' of generation. That is, show windows again, reset
73 * thread variables, and delete the progress window.
75 static void CleanupGeneration()
77 _generating_world = false;
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;
87 DeleteWindowByClass(WC_MODAL_PROGRESS);
88 ShowFirstError();
89 MarkWholeScreenDirty();
92 /**
93 * The internal, real, generate function.
95 static void _GenerateWorld()
97 /* Make sure everything is done via OWNER_NONE. */
98 Backup<CompanyID> _cur_company(_current_company, OWNER_NONE, FILE_LINE);
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 */
106 if (_settings_game.game_creation.generation_seed == GENERATE_NEW_SEED) _settings_game.game_creation.generation_seed = _settings_newgame.game_creation.generation_seed = InteractiveRandom();
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);
111 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
113 IncreaseGeneratingWorldProgress(GWP_MAP_INIT);
114 /* Must start economy early because of the costs. */
115 StartupEconomy();
117 /* Don't generate landscape items when in the scenario editor. */
118 if (_gw.mode == GWM_EMPTY) {
119 SetGeneratingWorldProgress(GWP_OBJECT, 1);
121 /* Make sure the tiles at the north border are void tiles if needed. */
122 if (_settings_game.construction.freeform_edges) {
123 for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
124 for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
127 /* Make the map the height of the setting */
128 if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
130 ConvertGroundTilesIntoWaterTiles();
131 IncreaseGeneratingWorldProgress(GWP_OBJECT);
132 } else {
133 GenerateLandscape(_gw.mode);
134 GenerateClearTile();
136 /* Only generate towns, tree and industries in newgame mode. */
137 if (_game_mode != GM_EDITOR) {
138 if (!GenerateTowns(_settings_game.economy.town_layout)) {
139 _cur_company.Restore();
140 HandleGeneratingWorldAbortion();
141 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
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;
147 return;
149 GenerateIndustries();
150 GenerateObjects();
151 GenerateTrees();
155 /* These are probably pointless when inside the scenario editor. */
156 SetGeneratingWorldProgress(GWP_GAME_INIT, 3);
157 StartupCompanies();
158 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
159 StartupEngines();
160 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
161 StartupDisasters();
162 _generating_world = false;
164 /* No need to run the tile loop in the scenario editor. */
165 if (_gw.mode != GWM_EMPTY) {
166 uint i;
168 SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500);
169 for (i = 0; i < 0x500; i++) {
170 RunTileLoop();
171 _tick_counter++;
172 IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
175 if (_game_mode != GM_EDITOR) {
176 Game::StartNew();
178 if (Game::GetInstance() != nullptr) {
179 SetGeneratingWorldProgress(GWP_RUNSCRIPT, 2500);
180 _generating_world = true;
181 for (i = 0; i < 2500; i++) {
182 Game::GameLoop();
183 IncreaseGeneratingWorldProgress(GWP_RUNSCRIPT);
184 if (Game::GetInstance()->IsSleeping()) break;
186 _generating_world = false;
191 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
193 ResetObjectToPlace();
194 _cur_company.Trash();
195 _current_company = _local_company = _gw.lc;
197 SetGeneratingWorldProgress(GWP_GAME_START, 1);
198 /* Call any callback */
199 if (_gw.proc != nullptr) _gw.proc();
200 IncreaseGeneratingWorldProgress(GWP_GAME_START);
202 CleanupGeneration();
203 lock.unlock();
205 ShowNewGRFError();
207 if (_network_dedicated) DEBUG(net, 1, "Map generated, starting game");
208 DEBUG(desync, 1, "new_map: %08x", _settings_game.game_creation.generation_seed);
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);
213 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
215 } catch (...) {
216 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP, true);
217 if (_cur_company.IsValid()) _cur_company.Restore();
218 _generating_world = false;
219 throw;
224 * Set here the function, if any, that you want to be called when landscape
225 * generation is done.
226 * @param proc callback procedure
228 void GenerateWorldSetCallback(GWDoneProc *proc)
230 _gw.proc = proc;
234 * Set here the function, if any, that you want to be called when landscape
235 * generation is aborted.
236 * @param proc callback procedure
238 void GenerateWorldSetAbortCallback(GWAbortProc *proc)
240 _gw.abortp = proc;
244 * This will wait for the thread to finish up his work. It will not continue
245 * till the work is done.
247 void WaitTillGeneratedWorld()
249 if (!_gw.thread.joinable()) return;
251 _modal_progress_work_mutex.unlock();
252 _modal_progress_paint_mutex.unlock();
253 _gw.quit_thread = true;
254 _gw.thread.join();
255 _gw.threaded = false;
256 _modal_progress_work_mutex.lock();
257 _modal_progress_paint_mutex.lock();
261 * Initializes the abortion process
263 void AbortGeneratingWorld()
265 _gw.abort = true;
269 * Is the generation being aborted?
270 * @return the 'aborted' status
272 bool IsGeneratingWorldAborted()
274 return _gw.abort;
278 * Really handle the abortion, i.e. clean up some of the mess
280 void HandleGeneratingWorldAbortion()
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;
285 if (_gw.abortp != nullptr) _gw.abortp();
287 CleanupGeneration();
289 if (_gw.thread.joinable() && _gw.thread.get_id() == std::this_thread::get_id()) throw OTTDThreadExitSignal();
291 SwitchToMode(_switch_mode);
295 * Generate a world.
296 * @param mode The mode of world generation (see GenWorldMode).
297 * @param size_x The X-size of the map.
298 * @param size_y The Y-size of the map.
299 * @param reset_settings Whether to reset the game configuration (used for restart)
301 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
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;
314 /* This disables some commands and stuff */
315 SetLocalCompany(COMPANY_SPECTATOR);
317 InitializeGame(_gw.size_x, _gw.size_y, true, reset_settings);
318 PrepareGenerateWorldProgress();
320 /* Load the right landscape stuff, and the NewGRFs! */
321 GfxLoadSprites();
322 LoadStringWidthTable();
324 /* Re-init the windowing system */
325 ResetWindowSystem();
327 /* Create toolbars */
328 SetupColoursAndInitialWindow();
329 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
331 if (_gw.thread.joinable()) _gw.thread.join();
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;
336 _modal_progress_work_mutex.unlock();
337 _GenerateWorld();
338 _modal_progress_work_mutex.lock();
339 return;
342 UnshowCriticalError();
343 /* Remove any open window */
344 DeleteAllNonVitalWindows();
345 /* Hide vital windows, because we don't allow to use them */
346 HideVitalWindows();
348 /* Don't show the dialog if we don't have a thread */
349 ShowGenerateWorldProgress();
351 /* Centre the view on the map */
352 if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) {
353 ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);