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 
8 /** @file genworld.cpp Functions to generate a map. */
9 
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 #include "tgp.h"
37 
38 #include "safeguards.h"
39 
40 
41 void GenerateClearTile();
42 void GenerateIndustries();
43 void GenerateObjects();
44 void GenerateTrees();
45 
46 void StartupEconomy();
47 void StartupCompanies();
48 void StartupDisasters();
49 
50 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
51 
52 /**
53  * Please only use this variable in genworld.h and genworld.cpp and
54  *  nowhere else. For speed improvements we need it to be global, but
55  *  in no way the meaning of it is to use it anywhere else besides
56  *  in the genworld.h and genworld.cpp!
57  */
58 GenWorldInfo _gw;
59 
60 /** Whether we are generating the map or not. */
61 bool _generating_world;
62 
63 class AbortGenerateWorldSignal { };
64 
65 /**
66  * Generation is done; show windows again and delete the progress window.
67  */
CleanupGeneration()68 static void CleanupGeneration()
69 {
70 	_generating_world = false;
71 
72 	SetMouseCursorBusy(false);
73 	/* Show all vital windows again, because we have hidden them */
74 	if (_game_mode != GM_MENU) ShowVitalWindows();
75 	SetModalProgress(false);
76 	_gw.proc     = nullptr;
77 	_gw.abortp   = nullptr;
78 
79 	CloseWindowByClass(WC_MODAL_PROGRESS);
80 	ShowFirstError();
81 	MarkWholeScreenDirty();
82 }
83 
84 /**
85  * The internal, real, generate function.
86  */
_GenerateWorld()87 static void _GenerateWorld()
88 {
89 	/* Make sure everything is done via OWNER_NONE. */
90 	Backup<CompanyID> _cur_company(_current_company, OWNER_NONE, FILE_LINE);
91 
92 	try {
93 		_generating_world = true;
94 		if (_network_dedicated) Debug(net, 3, "Generating map, please wait...");
95 		/* Set the Random() seed to generation_seed so we produce the same map with the same seed */
96 		if (_settings_game.game_creation.generation_seed == GENERATE_NEW_SEED) _settings_game.game_creation.generation_seed = _settings_newgame.game_creation.generation_seed = InteractiveRandom();
97 		_random.SetSeed(_settings_game.game_creation.generation_seed);
98 		SetGeneratingWorldProgress(GWP_MAP_INIT, 2);
99 		SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
100 
101 		BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
102 
103 		IncreaseGeneratingWorldProgress(GWP_MAP_INIT);
104 		/* Must start economy early because of the costs. */
105 		StartupEconomy();
106 
107 		/* Don't generate landscape items when in the scenario editor. */
108 		if (_gw.mode == GWM_EMPTY) {
109 			SetGeneratingWorldProgress(GWP_OBJECT, 1);
110 
111 			/* Make sure the tiles at the north border are void tiles if needed. */
112 			if (_settings_game.construction.freeform_edges) {
113 				for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
114 				for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
115 			}
116 
117 			/* Make the map the height of the setting */
118 			if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
119 
120 			ConvertGroundTilesIntoWaterTiles();
121 			IncreaseGeneratingWorldProgress(GWP_OBJECT);
122 
123 			_settings_game.game_creation.snow_line_height = DEF_SNOWLINE_HEIGHT;
124 		} else {
125 			GenerateLandscape(_gw.mode);
126 			GenerateClearTile();
127 
128 			/* Only generate towns, tree and industries in newgame mode. */
129 			if (_game_mode != GM_EDITOR) {
130 				if (!GenerateTowns(_settings_game.economy.town_layout)) {
131 					HandleGeneratingWorldAbortion();
132 					return;
133 				}
134 				GenerateIndustries();
135 				GenerateObjects();
136 				GenerateTrees();
137 			}
138 		}
139 
140 		/* These are probably pointless when inside the scenario editor. */
141 		SetGeneratingWorldProgress(GWP_GAME_INIT, 3);
142 		StartupCompanies();
143 		IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
144 		StartupEngines();
145 		IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
146 		StartupDisasters();
147 		_generating_world = false;
148 
149 		/* No need to run the tile loop in the scenario editor. */
150 		if (_gw.mode != GWM_EMPTY) {
151 			uint i;
152 
153 			SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500);
154 			for (i = 0; i < 0x500; i++) {
155 				RunTileLoop();
156 				_tick_counter++;
157 				IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
158 			}
159 
160 			if (_game_mode != GM_EDITOR) {
161 				Game::StartNew();
162 
163 				if (Game::GetInstance() != nullptr) {
164 					SetGeneratingWorldProgress(GWP_RUNSCRIPT, 2500);
165 					_generating_world = true;
166 					for (i = 0; i < 2500; i++) {
167 						Game::GameLoop();
168 						IncreaseGeneratingWorldProgress(GWP_RUNSCRIPT);
169 						if (Game::GetInstance()->IsSleeping()) break;
170 					}
171 					_generating_world = false;
172 				}
173 			}
174 		}
175 
176 		BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
177 
178 		ResetObjectToPlace();
179 		_cur_company.Trash();
180 		_current_company = _local_company = _gw.lc;
181 
182 		SetGeneratingWorldProgress(GWP_GAME_START, 1);
183 		/* Call any callback */
184 		if (_gw.proc != nullptr) _gw.proc();
185 		IncreaseGeneratingWorldProgress(GWP_GAME_START);
186 
187 		CleanupGeneration();
188 
189 		ShowNewGRFError();
190 
191 		if (_network_dedicated) Debug(net, 3, "Map generated, starting game");
192 		Debug(desync, 1, "new_map: {:08x}", _settings_game.game_creation.generation_seed);
193 
194 		if (_debug_desync_level > 0) {
195 			char name[MAX_PATH];
196 			seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
197 			SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
198 		}
199 	} catch (AbortGenerateWorldSignal&) {
200 		CleanupGeneration();
201 
202 		BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP, true);
203 		if (_cur_company.IsValid()) _cur_company.Restore();
204 
205 		if (_network_dedicated) {
206 			/* Exit the game to prevent a return to main menu.  */
207 			Debug(net, 0, "Generating map failed; closing server");
208 			_exit_game = true;
209 		} else {
210 			SwitchToMode(_switch_mode);
211 		}
212 	}
213 }
214 
215 /**
216  * Set here the function, if any, that you want to be called when landscape
217  * generation is done.
218  * @param proc callback procedure
219  */
GenerateWorldSetCallback(GWDoneProc * proc)220 void GenerateWorldSetCallback(GWDoneProc *proc)
221 {
222 	_gw.proc = proc;
223 }
224 
225 /**
226  * Set here the function, if any, that you want to be called when landscape
227  * generation is aborted.
228  * @param proc callback procedure
229  */
GenerateWorldSetAbortCallback(GWAbortProc * proc)230 void GenerateWorldSetAbortCallback(GWAbortProc *proc)
231 {
232 	_gw.abortp = proc;
233 }
234 
235 /**
236  * Initializes the abortion process
237  */
AbortGeneratingWorld()238 void AbortGeneratingWorld()
239 {
240 	_gw.abort = true;
241 }
242 
243 /**
244  * Is the generation being aborted?
245  * @return the 'aborted' status
246  */
IsGeneratingWorldAborted()247 bool IsGeneratingWorldAborted()
248 {
249 	return _gw.abort || _exit_game;
250 }
251 
252 /**
253  * Really handle the abortion, i.e. clean up some of the mess
254  */
HandleGeneratingWorldAbortion()255 void HandleGeneratingWorldAbortion()
256 {
257 	/* Clean up - in SE create an empty map, otherwise, go to intro menu */
258 	_switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
259 
260 	if (_gw.abortp != nullptr) _gw.abortp();
261 
262 	throw AbortGenerateWorldSignal();
263 }
264 
265 /**
266  * Generate a world.
267  * @param mode The mode of world generation (see GenWorldMode).
268  * @param size_x The X-size of the map.
269  * @param size_y The Y-size of the map.
270  * @param reset_settings Whether to reset the game configuration (used for restart)
271  */
GenerateWorld(GenWorldMode mode,uint size_x,uint size_y,bool reset_settings)272 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
273 {
274 	if (HasModalProgress()) return;
275 	_gw.mode   = mode;
276 	_gw.size_x = size_x;
277 	_gw.size_y = size_y;
278 	SetModalProgress(true);
279 	_gw.abort  = false;
280 	_gw.abortp = nullptr;
281 	_gw.lc     = _local_company;
282 
283 	/* This disables some commands and stuff */
284 	SetLocalCompany(COMPANY_SPECTATOR);
285 
286 	InitializeGame(_gw.size_x, _gw.size_y, true, reset_settings);
287 	PrepareGenerateWorldProgress();
288 
289 	if (_settings_game.construction.map_height_limit == 0) {
290 		uint estimated_height = 0;
291 
292 		if (_gw.mode == GWM_EMPTY && _game_mode != GM_MENU) {
293 			estimated_height = _settings_game.game_creation.se_flat_world_height;
294 		} else if (_gw.mode == GWM_HEIGHTMAP) {
295 			estimated_height = _settings_game.game_creation.heightmap_height;
296 		} else if (_settings_game.game_creation.land_generator == LG_TERRAGENESIS) {
297 			estimated_height = GetEstimationTGPMapHeight();
298 		} else {
299 			estimated_height = 0;
300 		}
301 
302 		_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));
303 	}
304 
305 	/* Load the right landscape stuff, and the NewGRFs! */
306 	GfxLoadSprites();
307 	LoadStringWidthTable();
308 
309 	/* Re-init the windowing system */
310 	ResetWindowSystem();
311 
312 	/* Create toolbars */
313 	SetupColoursAndInitialWindow();
314 	SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
315 
316 	UnshowCriticalError();
317 	CloseAllNonVitalWindows();
318 	HideVitalWindows();
319 
320 	ShowGenerateWorldProgress();
321 
322 	/* Centre the view on the map */
323 	if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) {
324 		ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);
325 	}
326 
327 	_GenerateWorld();
328 }
329