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 openttd.cpp Functions related to starting OpenTTD. */
9 
10 #include "stdafx.h"
11 
12 #include "blitter/factory.hpp"
13 #include "sound/sound_driver.hpp"
14 #include "music/music_driver.hpp"
15 #include "video/video_driver.hpp"
16 
17 #include "fontcache.h"
18 #include "error.h"
19 #include "gui.h"
20 
21 #include "base_media_base.h"
22 #include "saveload/saveload.h"
23 #include "company_func.h"
24 #include "command_func.h"
25 #include "news_func.h"
26 #include "fios.h"
27 #include "aircraft.h"
28 #include "roadveh.h"
29 #include "train.h"
30 #include "ship.h"
31 #include "console_func.h"
32 #include "screenshot.h"
33 #include "network/network.h"
34 #include "network/network_func.h"
35 #include "ai/ai.hpp"
36 #include "ai/ai_config.hpp"
37 #include "settings_func.h"
38 #include "genworld.h"
39 #include "progress.h"
40 #include "strings_func.h"
41 #include "date_func.h"
42 #include "vehicle_func.h"
43 #include "gamelog.h"
44 #include "animated_tile_func.h"
45 #include "roadstop_base.h"
46 #include "elrail_func.h"
47 #include "rev.h"
48 #include "highscore.h"
49 #include "station_base.h"
50 #include "crashlog.h"
51 #include "engine_func.h"
52 #include "core/random_func.hpp"
53 #include "rail_gui.h"
54 #include "road_gui.h"
55 #include "core/backup_type.hpp"
56 #include "hotkeys.h"
57 #include "newgrf.h"
58 #include "misc/getoptdata.h"
59 #include "game/game.hpp"
60 #include "game/game_config.hpp"
61 #include "town.h"
62 #include "subsidy_func.h"
63 #include "gfx_layout.h"
64 #include "viewport_func.h"
65 #include "viewport_sprite_sorter.h"
66 #include "framerate_type.h"
67 #include "industry.h"
68 #include "network/network_gui.h"
69 
70 #include "linkgraph/linkgraphschedule.h"
71 
72 #include <stdarg.h>
73 #include <system_error>
74 
75 #include "safeguards.h"
76 
77 #ifdef __EMSCRIPTEN__
78 #	include <emscripten.h>
79 #	include <emscripten/html5.h>
80 #endif
81 
82 void CallLandscapeTick();
83 void IncreaseDate();
84 void DoPaletteAnimations();
85 void MusicLoop();
86 void ResetMusic();
87 void CallWindowGameTickEvent();
88 bool HandleBootstrap();
89 
90 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
91 extern void ShowOSErrorBox(const char *buf, bool system);
92 extern std::string _config_file;
93 
94 bool _save_config = false;
95 bool _request_newgrf_scan = false;
96 NewGRFScanCallback *_request_newgrf_scan_callback = nullptr;
97 
98 /**
99  * Error handling for fatal user errors.
100  * @param s the string to print.
101  * @note Does NEVER return.
102  */
usererror(const char * s,...)103 void CDECL usererror(const char *s, ...)
104 {
105 	va_list va;
106 	char buf[512];
107 
108 	va_start(va, s);
109 	vseprintf(buf, lastof(buf), s, va);
110 	va_end(va);
111 
112 	ShowOSErrorBox(buf, false);
113 	if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
114 
115 #ifdef __EMSCRIPTEN__
116 	emscripten_exit_pointerlock();
117 	/* In effect, the game ends here. As emscripten_set_main_loop() caused
118 	 * the stack to be unwound, the code after MainLoop() in
119 	 * openttd_main() is never executed. */
120 	EM_ASM(if (window["openttd_syncfs"]) openttd_syncfs());
121 	EM_ASM(if (window["openttd_abort"]) openttd_abort());
122 #endif
123 
124 	exit(1);
125 }
126 
127 /**
128  * Error handling for fatal non-user errors.
129  * @param s the string to print.
130  * @note Does NEVER return.
131  */
error(const char * s,...)132 void CDECL error(const char *s, ...)
133 {
134 	va_list va;
135 	char buf[2048];
136 
137 	va_start(va, s);
138 	vseprintf(buf, lastof(buf), s, va);
139 	va_end(va);
140 
141 	if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
142 		ShowOSErrorBox(buf, true);
143 	}
144 
145 	/* Set the error message for the crash log and then invoke it. */
146 	CrashLog::SetErrorMessage(buf);
147 	abort();
148 }
149 
150 /**
151  * Shows some information on the console/a popup box depending on the OS.
152  * @param str the text to show.
153  */
ShowInfoF(const char * str,...)154 void CDECL ShowInfoF(const char *str, ...)
155 {
156 	va_list va;
157 	char buf[1024];
158 	va_start(va, str);
159 	vseprintf(buf, lastof(buf), str, va);
160 	va_end(va);
161 	ShowInfo(buf);
162 }
163 
164 /**
165  * Show the help message when someone passed a wrong parameter.
166  */
ShowHelp()167 static void ShowHelp()
168 {
169 	char buf[8192];
170 	char *p = buf;
171 
172 	p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
173 	p = strecpy(p,
174 		"\n"
175 		"\n"
176 		"Command line options:\n"
177 		"  -v drv              = Set video driver (see below)\n"
178 		"  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
179 		"  -m drv              = Set music driver (see below)\n"
180 		"  -b drv              = Set the blitter to use (see below)\n"
181 		"  -r res              = Set resolution (for instance 800x600)\n"
182 		"  -h                  = Display this help text\n"
183 		"  -t year             = Set starting year\n"
184 		"  -d [[fac=]lvl[,...]]= Debug mode\n"
185 		"  -e                  = Start Editor\n"
186 		"  -g [savegame]       = Start new/save game immediately\n"
187 		"  -G seed             = Set random seed\n"
188 		"  -n [ip:port#company]= Join network game\n"
189 		"  -p password         = Password to join server\n"
190 		"  -P password         = Password to join company\n"
191 		"  -D [ip][:port]      = Start dedicated server\n"
192 		"  -l ip[:port]        = Redirect Debug()\n"
193 #if !defined(_WIN32)
194 		"  -f                  = Fork into the background (dedicated only)\n"
195 #endif
196 		"  -I graphics_set     = Force the graphics set (see below)\n"
197 		"  -S sounds_set       = Force the sounds set (see below)\n"
198 		"  -M music_set        = Force the music set (see below)\n"
199 		"  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
200 		"  -x                  = Never save configuration changes to disk\n"
201 		"  -X                  = Don't use global folders to search for files\n"
202 		"  -q savegame         = Write some information about the savegame and exit\n"
203 		"\n",
204 		lastof(buf)
205 	);
206 
207 	/* List the graphics packs */
208 	p = BaseGraphics::GetSetsList(p, lastof(buf));
209 
210 	/* List the sounds packs */
211 	p = BaseSounds::GetSetsList(p, lastof(buf));
212 
213 	/* List the music packs */
214 	p = BaseMusic::GetSetsList(p, lastof(buf));
215 
216 	/* List the drivers */
217 	p = DriverFactoryBase::GetDriversInfo(p, lastof(buf));
218 
219 	/* List the blitters */
220 	p = BlitterFactory::GetBlittersInfo(p, lastof(buf));
221 
222 	/* List the debug facilities. */
223 	p = DumpDebugFacilityNames(p, lastof(buf));
224 
225 	/* We need to initialize the AI, so it finds the AIs */
226 	AI::Initialize();
227 	p = AI::GetConsoleList(p, lastof(buf), true);
228 	AI::Uninitialize(true);
229 
230 	/* We need to initialize the GameScript, so it finds the GSs */
231 	Game::Initialize();
232 	p = Game::GetConsoleList(p, lastof(buf), true);
233 	Game::Uninitialize(true);
234 
235 	/* ShowInfo put output to stderr, but version information should go
236 	 * to stdout; this is the only exception */
237 #if !defined(_WIN32)
238 	printf("%s\n", buf);
239 #else
240 	ShowInfo(buf);
241 #endif
242 }
243 
WriteSavegameInfo(const char * name)244 static void WriteSavegameInfo(const char *name)
245 {
246 	extern SaveLoadVersion _sl_version;
247 	uint32 last_ottd_rev = 0;
248 	byte ever_modified = 0;
249 	bool removed_newgrfs = false;
250 
251 	GamelogInfo(_load_check_data.gamelog_action, _load_check_data.gamelog_actions, &last_ottd_rev, &ever_modified, &removed_newgrfs);
252 
253 	char buf[8192];
254 	char *p = buf;
255 	p += seprintf(p, lastof(buf), "Name:         %s\n", name);
256 	p += seprintf(p, lastof(buf), "Savegame ver: %d\n", _sl_version);
257 	p += seprintf(p, lastof(buf), "NewGRF ver:   0x%08X\n", last_ottd_rev);
258 	p += seprintf(p, lastof(buf), "Modified:     %d\n", ever_modified);
259 
260 	if (removed_newgrfs) {
261 		p += seprintf(p, lastof(buf), "NewGRFs have been removed\n");
262 	}
263 
264 	p = strecpy(p, "NewGRFs:\n", lastof(buf));
265 	if (_load_check_data.HasNewGrfs()) {
266 		for (GRFConfig *c = _load_check_data.grfconfig; c != nullptr; c = c->next) {
267 			char md5sum[33];
268 			md5sumToString(md5sum, lastof(md5sum), HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum);
269 			p += seprintf(p, lastof(buf), "%08X %s %s\n", c->ident.grfid, md5sum, c->filename);
270 		}
271 	}
272 
273 	/* ShowInfo put output to stderr, but version information should go
274 	 * to stdout; this is the only exception */
275 #if !defined(_WIN32)
276 	printf("%s\n", buf);
277 #else
278 	ShowInfo(buf);
279 #endif
280 }
281 
282 
283 /**
284  * Extract the resolution from the given string and store
285  * it in the 'res' parameter.
286  * @param res variable to store the resolution in.
287  * @param s   the string to decompose.
288  */
ParseResolution(Dimension * res,const char * s)289 static void ParseResolution(Dimension *res, const char *s)
290 {
291 	const char *t = strchr(s, 'x');
292 	if (t == nullptr) {
293 		ShowInfoF("Invalid resolution '%s'", s);
294 		return;
295 	}
296 
297 	res->width  = std::max(strtoul(s, nullptr, 0), 64UL);
298 	res->height = std::max(strtoul(t + 1, nullptr, 0), 64UL);
299 }
300 
301 
302 /**
303  * Uninitializes drivers, frees allocated memory, cleans pools, ...
304  * Generally, prepares the game for shutting down
305  */
ShutdownGame()306 static void ShutdownGame()
307 {
308 	IConsoleFree();
309 
310 	if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
311 
312 	DriverFactoryBase::ShutdownDrivers();
313 
314 	UnInitWindowSystem();
315 
316 	/* stop the scripts */
317 	AI::Uninitialize(false);
318 	Game::Uninitialize(false);
319 
320 	/* Uninitialize variables that are allocated dynamically */
321 	GamelogReset();
322 
323 	LinkGraphSchedule::Clear();
324 	PoolBase::Clean(PT_ALL);
325 
326 	/* No NewGRFs were loaded when it was still bootstrapping. */
327 	if (_game_mode != GM_BOOTSTRAP) ResetNewGRFData();
328 
329 	UninitFreeType();
330 }
331 
332 /**
333  * Load the introduction game.
334  * @param load_newgrfs Whether to load the NewGRFs or not.
335  */
LoadIntroGame(bool load_newgrfs=true)336 static void LoadIntroGame(bool load_newgrfs = true)
337 {
338 	_game_mode = GM_MENU;
339 
340 	if (load_newgrfs) ResetGRFConfig(false);
341 
342 	/* Setup main window */
343 	ResetWindowSystem();
344 	SetupColoursAndInitialWindow();
345 
346 	/* Load the default opening screen savegame */
347 	if (SaveOrLoad("opntitle.dat", SLO_LOAD, DFT_GAME_FILE, BASESET_DIR) != SL_OK) {
348 		GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
349 		SetLocalCompany(COMPANY_SPECTATOR);
350 	} else {
351 		SetLocalCompany(COMPANY_FIRST);
352 	}
353 
354 	FixTitleGameZoom();
355 	_pause_mode = PM_UNPAUSED;
356 	_cursor.fix_at = false;
357 
358 	CheckForMissingGlyphs();
359 
360 	MusicLoop(); // ensure music is correct
361 }
362 
MakeNewgameSettingsLive()363 void MakeNewgameSettingsLive()
364 {
365 	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
366 		if (_settings_game.ai_config[c] != nullptr) {
367 			delete _settings_game.ai_config[c];
368 		}
369 	}
370 	if (_settings_game.game_config != nullptr) {
371 		delete _settings_game.game_config;
372 	}
373 
374 	/* Copy newgame settings to active settings.
375 	 * Also initialise old settings needed for savegame conversion. */
376 	_settings_game = _settings_newgame;
377 	_old_vds = _settings_client.company.vehicle;
378 
379 	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
380 		_settings_game.ai_config[c] = nullptr;
381 		if (_settings_newgame.ai_config[c] != nullptr) {
382 			_settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
383 			if (!AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->HasScript()) {
384 				AIConfig::GetConfig(c, AIConfig::SSS_FORCE_GAME)->Change(nullptr);
385 			}
386 		}
387 	}
388 	_settings_game.game_config = nullptr;
389 	if (_settings_newgame.game_config != nullptr) {
390 		_settings_game.game_config = new GameConfig(_settings_newgame.game_config);
391 	}
392 }
393 
OpenBrowser(const char * url)394 void OpenBrowser(const char *url)
395 {
396 	/* Make sure we only accept urls that are sure to open a browser. */
397 	if (strstr(url, "http://") != url && strstr(url, "https://") != url) return;
398 
399 	extern void OSOpenBrowser(const char *url);
400 	OSOpenBrowser(url);
401 }
402 
403 /** Callback structure of statements to be executed after the NewGRF scan. */
404 struct AfterNewGRFScan : NewGRFScanCallback {
405 	Year startyear = INVALID_YEAR;              ///< The start year.
406 	uint32 generation_seed = GENERATE_NEW_SEED; ///< Seed for the new game.
407 	std::string dedicated_host;                 ///< Hostname for the dedicated server.
408 	uint16 dedicated_port = 0;                  ///< Port for the dedicated server.
409 	std::string connection_string;              ///< Information about the server to connect to
410 	std::string join_server_password;           ///< The password to join the server with.
411 	std::string join_company_password;          ///< The password to join the company with.
412 	bool save_config = true;                    ///< The save config setting.
413 
414 	/**
415 	 * Create a new callback.
416 	 */
AfterNewGRFScanAfterNewGRFScan417 	AfterNewGRFScan()
418 	{
419 		/* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
420 		 * if it's placed outside a member function, directly in the struct body. */
421 		static_assert(sizeof(generation_seed) == sizeof(_settings_game.game_creation.generation_seed));
422 	}
423 
OnNewGRFsScannedAfterNewGRFScan424 	virtual void OnNewGRFsScanned()
425 	{
426 		ResetGRFConfig(false);
427 
428 		TarScanner::DoScan(TarScanner::SCENARIO);
429 
430 		AI::Initialize();
431 		Game::Initialize();
432 
433 		/* We want the new (correct) NewGRF count to survive the loading. */
434 		uint last_newgrf_count = _settings_client.gui.last_newgrf_count;
435 		LoadFromConfig();
436 		_settings_client.gui.last_newgrf_count = last_newgrf_count;
437 		/* Since the default for the palette might have changed due to
438 		 * reading the configuration file, recalculate that now. */
439 		UpdateNewGRFConfigPalette();
440 
441 		Game::Uninitialize(true);
442 		AI::Uninitialize(true);
443 		LoadFromHighScore();
444 		LoadHotkeysFromConfig();
445 		WindowDesc::LoadFromConfig();
446 
447 		/* We have loaded the config, so we may possibly save it. */
448 		_save_config = save_config;
449 
450 		/* restore saved music volume */
451 		MusicDriver::GetInstance()->SetVolume(_settings_client.music.music_vol);
452 
453 		if (startyear != INVALID_YEAR) IConsoleSetSetting("game_creation.starting_year", startyear);
454 		if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
455 
456 		if (!dedicated_host.empty()) {
457 			_network_bind_list.clear();
458 			_network_bind_list.emplace_back(dedicated_host);
459 		}
460 		if (dedicated_port != 0) _settings_client.network.server_port = dedicated_port;
461 
462 		/* initialize the ingame console */
463 		IConsoleInit();
464 		InitializeGUI();
465 		IConsoleCmdExec("exec scripts/autoexec.scr 0");
466 
467 		/* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
468 		if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
469 
470 		if (_network_available && !connection_string.empty()) {
471 			LoadIntroGame();
472 			_switch_mode = SM_NONE;
473 
474 			NetworkClientConnectGame(connection_string, COMPANY_NEW_COMPANY, join_server_password, join_company_password);
475 		}
476 
477 		/* After the scan we're not used anymore. */
478 		delete this;
479 	}
480 };
481 
482 #if defined(UNIX)
483 extern void DedicatedFork();
484 #endif
485 
486 /** Options of OpenTTD. */
487 static const OptionData _options[] = {
488 	 GETOPT_SHORT_VALUE('I'),
489 	 GETOPT_SHORT_VALUE('S'),
490 	 GETOPT_SHORT_VALUE('M'),
491 	 GETOPT_SHORT_VALUE('m'),
492 	 GETOPT_SHORT_VALUE('s'),
493 	 GETOPT_SHORT_VALUE('v'),
494 	 GETOPT_SHORT_VALUE('b'),
495 	GETOPT_SHORT_OPTVAL('D'),
496 	GETOPT_SHORT_OPTVAL('n'),
497 	 GETOPT_SHORT_VALUE('l'),
498 	 GETOPT_SHORT_VALUE('p'),
499 	 GETOPT_SHORT_VALUE('P'),
500 #if !defined(_WIN32)
501 	 GETOPT_SHORT_NOVAL('f'),
502 #endif
503 	 GETOPT_SHORT_VALUE('r'),
504 	 GETOPT_SHORT_VALUE('t'),
505 	GETOPT_SHORT_OPTVAL('d'),
506 	 GETOPT_SHORT_NOVAL('e'),
507 	GETOPT_SHORT_OPTVAL('g'),
508 	 GETOPT_SHORT_VALUE('G'),
509 	 GETOPT_SHORT_VALUE('c'),
510 	 GETOPT_SHORT_NOVAL('x'),
511 	 GETOPT_SHORT_NOVAL('X'),
512 	 GETOPT_SHORT_VALUE('q'),
513 	 GETOPT_SHORT_NOVAL('h'),
514 	GETOPT_END()
515 };
516 
517 /**
518  * Main entry point for this lovely game.
519  * @param argc The number of arguments passed to this game.
520  * @param argv The values of the arguments.
521  * @return 0 when there is no error.
522  */
openttd_main(int argc,char * argv[])523 int openttd_main(int argc, char *argv[])
524 {
525 	std::string musicdriver;
526 	std::string sounddriver;
527 	std::string videodriver;
528 	std::string blitter;
529 	std::string graphics_set;
530 	std::string sounds_set;
531 	std::string music_set;
532 	Dimension resolution = {0, 0};
533 	std::unique_ptr<AfterNewGRFScan> scanner(new AfterNewGRFScan());
534 	bool dedicated = false;
535 	char *debuglog_conn = nullptr;
536 	bool only_local_path = false;
537 
538 	extern bool _dedicated_forks;
539 	_dedicated_forks = false;
540 
541 	_game_mode = GM_MENU;
542 	_switch_mode = SM_MENU;
543 
544 	GetOptData mgo(argc - 1, argv + 1, _options);
545 	int ret = 0;
546 
547 	int i;
548 	while ((i = mgo.GetOpt()) != -1) {
549 		switch (i) {
550 		case 'I': graphics_set = mgo.opt; break;
551 		case 'S': sounds_set = mgo.opt; break;
552 		case 'M': music_set = mgo.opt; break;
553 		case 'm': musicdriver = mgo.opt; break;
554 		case 's': sounddriver = mgo.opt; break;
555 		case 'v': videodriver = mgo.opt; break;
556 		case 'b': blitter = mgo.opt; break;
557 		case 'D':
558 			musicdriver = "null";
559 			sounddriver = "null";
560 			videodriver = "dedicated";
561 			blitter = "null";
562 			dedicated = true;
563 			SetDebugString("net=4");
564 			if (mgo.opt != nullptr) {
565 				scanner->dedicated_host = ParseFullConnectionString(mgo.opt, scanner->dedicated_port);
566 			}
567 			break;
568 		case 'f': _dedicated_forks = true; break;
569 		case 'n':
570 			scanner->connection_string = mgo.opt; // optional IP:port#company parameter
571 			break;
572 		case 'l':
573 			debuglog_conn = mgo.opt;
574 			break;
575 		case 'p':
576 			scanner->join_server_password = mgo.opt;
577 			break;
578 		case 'P':
579 			scanner->join_company_password = mgo.opt;
580 			break;
581 		case 'r': ParseResolution(&resolution, mgo.opt); break;
582 		case 't': scanner->startyear = atoi(mgo.opt); break;
583 		case 'd': {
584 #if defined(_WIN32)
585 				CreateConsole();
586 #endif
587 				if (mgo.opt != nullptr) SetDebugString(mgo.opt);
588 				break;
589 			}
590 		case 'e': _switch_mode = (_switch_mode == SM_LOAD_GAME || _switch_mode == SM_LOAD_SCENARIO ? SM_LOAD_SCENARIO : SM_EDITOR); break;
591 		case 'g':
592 			if (mgo.opt != nullptr) {
593 				_file_to_saveload.SetName(mgo.opt);
594 				bool is_scenario = _switch_mode == SM_EDITOR || _switch_mode == SM_LOAD_SCENARIO;
595 				_switch_mode = is_scenario ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
596 				_file_to_saveload.SetMode(SLO_LOAD, is_scenario ? FT_SCENARIO : FT_SAVEGAME, DFT_GAME_FILE);
597 
598 				/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
599 				auto t = _file_to_saveload.name.find_last_of('.');
600 				if (t != std::string::npos) {
601 					FiosType ft = FiosGetSavegameListCallback(SLO_LOAD, _file_to_saveload.name, _file_to_saveload.name.substr(t).c_str(), nullptr, nullptr);
602 					if (ft != FIOS_TYPE_INVALID) _file_to_saveload.SetMode(ft);
603 				}
604 
605 				break;
606 			}
607 
608 			_switch_mode = SM_NEWGAME;
609 			/* Give a random map if no seed has been given */
610 			if (scanner->generation_seed == GENERATE_NEW_SEED) {
611 				scanner->generation_seed = InteractiveRandom();
612 			}
613 			break;
614 		case 'q': {
615 			DeterminePaths(argv[0], only_local_path);
616 			if (StrEmpty(mgo.opt)) {
617 				ret = 1;
618 				return ret;
619 			}
620 
621 			char title[80];
622 			title[0] = '\0';
623 			FiosGetSavegameListCallback(SLO_LOAD, mgo.opt, strrchr(mgo.opt, '.'), title, lastof(title));
624 
625 			_load_check_data.Clear();
626 			SaveOrLoadResult res = SaveOrLoad(mgo.opt, SLO_CHECK, DFT_GAME_FILE, SAVE_DIR, false);
627 			if (res != SL_OK || _load_check_data.HasErrors()) {
628 				fprintf(stderr, "Failed to open savegame\n");
629 				if (_load_check_data.HasErrors()) {
630 					InitializeLanguagePacks(); // A language pack is needed for GetString()
631 					char buf[256];
632 					SetDParamStr(0, _load_check_data.error_data);
633 					GetString(buf, _load_check_data.error, lastof(buf));
634 					fprintf(stderr, "%s\n", buf);
635 				}
636 				return ret;
637 			}
638 
639 			WriteSavegameInfo(title);
640 			return ret;
641 		}
642 		case 'G': scanner->generation_seed = strtoul(mgo.opt, nullptr, 10); break;
643 		case 'c': _config_file = mgo.opt; break;
644 		case 'x': scanner->save_config = false; break;
645 		case 'X': only_local_path = true; break;
646 		case 'h':
647 			i = -2; // Force printing of help.
648 			break;
649 		}
650 		if (i == -2) break;
651 	}
652 
653 	if (i == -2 || mgo.numleft > 0) {
654 		/* Either the user typed '-h', they made an error, or they added unrecognized command line arguments.
655 		 * In all cases, print the help, and exit.
656 		 *
657 		 * The next two functions are needed to list the graphics sets. We can't do them earlier
658 		 * because then we cannot show it on the debug console as that hasn't been configured yet. */
659 		DeterminePaths(argv[0], only_local_path);
660 		TarScanner::DoScan(TarScanner::BASESET);
661 		BaseGraphics::FindSets();
662 		BaseSounds::FindSets();
663 		BaseMusic::FindSets();
664 		ShowHelp();
665 		return ret;
666 	}
667 
668 	DeterminePaths(argv[0], only_local_path);
669 	TarScanner::DoScan(TarScanner::BASESET);
670 
671 	if (dedicated) Debug(net, 3, "Starting dedicated server, version {}", _openttd_revision);
672 	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
673 
674 #if defined(UNIX)
675 	/* We must fork here, or we'll end up without some resources we need (like sockets) */
676 	if (_dedicated_forks) DedicatedFork();
677 #endif
678 
679 	LoadFromConfig(true);
680 
681 	if (resolution.width != 0) _cur_resolution = resolution;
682 
683 	/* Limit width times height times bytes per pixel to fit a 32 bit
684 	 * integer, This way all internal drawing routines work correctly.
685 	 * A resolution that has one component as 0 is treated as a marker to
686 	 * auto-detect a good window size. */
687 	_cur_resolution.width  = std::min(_cur_resolution.width, UINT16_MAX / 2u);
688 	_cur_resolution.height = std::min(_cur_resolution.height, UINT16_MAX / 2u);
689 
690 	/* Assume the cursor starts within the game as not all video drivers
691 	 * get an event that the cursor is within the window when it is opened.
692 	 * Saying the cursor is there makes no visible difference as it would
693 	 * just be out of the bounds of the window. */
694 	_cursor.in_window = true;
695 
696 	/* enumerate language files */
697 	InitializeLanguagePacks();
698 
699 	/* Initialize the regular font for FreeType */
700 	InitFreeType(false);
701 
702 	/* This must be done early, since functions use the SetWindowDirty* calls */
703 	InitWindowSystem();
704 
705 	BaseGraphics::FindSets();
706 	if (graphics_set.empty() && !BaseGraphics::ini_set.empty()) graphics_set = BaseGraphics::ini_set;
707 	if (!BaseGraphics::SetSet(graphics_set)) {
708 		if (!graphics_set.empty()) {
709 			BaseGraphics::SetSet({});
710 
711 			ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND);
712 			msg.SetDParamStr(0, graphics_set);
713 			ScheduleErrorMessage(msg);
714 		}
715 	}
716 
717 	/* Initialize game palette */
718 	GfxInitPalettes();
719 
720 	Debug(misc, 1, "Loading blitter...");
721 	if (blitter.empty() && !_ini_blitter.empty()) blitter = _ini_blitter;
722 	_blitter_autodetected = blitter.empty();
723 	/* Activate the initial blitter.
724 	 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
725 	 *  - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
726 	 *  - Use 32bpp blitter if baseset or 8bpp-support settings says so.
727 	 *  - Use 8bpp blitter otherwise.
728 	 */
729 	if (!_blitter_autodetected ||
730 			(_support8bpp != S8BPP_NONE && (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter == BLT_8BPP)) ||
731 			BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
732 		if (BlitterFactory::SelectBlitter(blitter) == nullptr) {
733 			blitter.empty() ?
734 				usererror("Failed to autoprobe blitter") :
735 				usererror("Failed to select requested blitter '%s'; does it exist?", blitter.c_str());
736 		}
737 	}
738 
739 	if (videodriver.empty() && !_ini_videodriver.empty()) videodriver = _ini_videodriver;
740 	DriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
741 
742 	InitializeSpriteSorter();
743 
744 	/* Initialize the zoom level of the screen to normal */
745 	_screen.zoom = ZOOM_LVL_NORMAL;
746 	UpdateGUIZoom();
747 
748 	NetworkStartUp(); // initialize network-core
749 
750 	if (debuglog_conn != nullptr && _network_available) {
751 		NetworkStartDebugLog(debuglog_conn);
752 	}
753 
754 	if (!HandleBootstrap()) {
755 		ShutdownGame();
756 		return ret;
757 	}
758 
759 	VideoDriver::GetInstance()->ClaimMousePointer();
760 
761 	/* initialize screenshot formats */
762 	InitializeScreenshotFormats();
763 
764 	BaseSounds::FindSets();
765 	if (sounds_set.empty() && !BaseSounds::ini_set.empty()) sounds_set = BaseSounds::ini_set;
766 	if (!BaseSounds::SetSet(sounds_set)) {
767 		if (sounds_set.empty() || !BaseSounds::SetSet({})) {
768 			usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
769 		} else {
770 			ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND);
771 			msg.SetDParamStr(0, sounds_set);
772 			ScheduleErrorMessage(msg);
773 		}
774 	}
775 
776 	BaseMusic::FindSets();
777 	if (music_set.empty() && !BaseMusic::ini_set.empty()) music_set = BaseMusic::ini_set;
778 	if (!BaseMusic::SetSet(music_set)) {
779 		if (music_set.empty() || !BaseMusic::SetSet({})) {
780 			usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
781 		} else {
782 			ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND);
783 			msg.SetDParamStr(0, music_set);
784 			ScheduleErrorMessage(msg);
785 		}
786 	}
787 
788 	if (sounddriver.empty() && !_ini_sounddriver.empty()) sounddriver = _ini_sounddriver;
789 	DriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
790 
791 	if (musicdriver.empty() && !_ini_musicdriver.empty()) musicdriver = _ini_musicdriver;
792 	DriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
793 
794 	GenerateWorld(GWM_EMPTY, 64, 64); // Make the viewport initialization happy
795 	LoadIntroGame(false);
796 
797 	CheckForMissingGlyphs();
798 
799 	/* ScanNewGRFFiles now has control over the scanner. */
800 	RequestNewGRFScan(scanner.release());
801 
802 	VideoDriver::GetInstance()->MainLoop();
803 
804 	WaitTillSaved();
805 
806 	/* only save config if we have to */
807 	if (_save_config) {
808 		SaveToConfig();
809 		SaveHotkeysToConfig();
810 		WindowDesc::SaveToConfig();
811 		SaveToHighScore();
812 	}
813 
814 	/* Reset windowing system, stop drivers, free used memory, ... */
815 	ShutdownGame();
816 	return ret;
817 }
818 
HandleExitGameRequest()819 void HandleExitGameRequest()
820 {
821 	if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP) { // do not ask to quit on the main screen
822 		_exit_game = true;
823 	} else if (_settings_client.gui.autosave_on_exit) {
824 		DoExitSave();
825 		_exit_game = true;
826 	} else {
827 		AskExitGame();
828 	}
829 }
830 
831 /**
832  * Triggers everything that should be triggered when starting a game.
833  * @param dedicated_server Whether this is a dedicated server or not.
834  */
OnStartGame(bool dedicated_server)835 static void OnStartGame(bool dedicated_server)
836 {
837 	/* Update the local company for a loaded game. It is either always
838 	 * company #1 (eg 0) or in the case of a dedicated server a spectator */
839 	SetLocalCompany(dedicated_server ? COMPANY_SPECTATOR : COMPANY_FIRST);
840 
841 	/* Update the static game info to set the values from the new game. */
842 	NetworkServerUpdateGameInfo();
843 	/* Execute the game-start script */
844 	IConsoleCmdExec("exec scripts/game_start.scr 0");
845 }
846 
MakeNewGameDone()847 static void MakeNewGameDone()
848 {
849 	SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
850 
851 	/* In a dedicated server, the server does not play */
852 	if (!VideoDriver::GetInstance()->HasGUI()) {
853 		OnStartGame(true);
854 		if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
855 		return;
856 	}
857 
858 	/* Create a single company */
859 	DoStartupNewCompany(false);
860 
861 	Company *c = Company::Get(COMPANY_FIRST);
862 	c->settings = _settings_client.company;
863 
864 	/* Overwrite color from settings if needed
865 	 * COLOUR_END corresponds to Random colour */
866 	if (_settings_client.gui.starting_colour != COLOUR_END) {
867 		c->colour = _settings_client.gui.starting_colour;
868 		ResetCompanyLivery(c);
869 		_company_colours[c->index] = (Colours)c->colour;
870 	}
871 
872 	OnStartGame(false);
873 
874 	InitializeRailGUI();
875 	InitializeRoadGUI();
876 
877 	/* We are the server, we start a new company (not dedicated),
878 	 * so set the default password *if* needed. */
879 	if (_network_server && !_settings_client.network.default_company_pass.empty()) {
880 		NetworkChangeCompanyPassword(_local_company, _settings_client.network.default_company_pass);
881 	}
882 
883 	if (_settings_client.gui.pause_on_newgame) DoCommandP(0, PM_PAUSED_NORMAL, 1, CMD_PAUSE);
884 
885 	CheckEngines();
886 	CheckIndustries();
887 	MarkWholeScreenDirty();
888 
889 	if (_network_server && !_network_dedicated) ShowClientList();
890 }
891 
MakeNewGame(bool from_heightmap,bool reset_settings)892 static void MakeNewGame(bool from_heightmap, bool reset_settings)
893 {
894 	_game_mode = GM_NORMAL;
895 	if (!from_heightmap) {
896 		/* "reload" command needs to know what mode we were in. */
897 		_file_to_saveload.SetMode(SLO_INVALID, FT_INVALID, DFT_INVALID);
898 	}
899 
900 	ResetGRFConfig(true);
901 
902 	GenerateWorldSetCallback(&MakeNewGameDone);
903 	GenerateWorld(from_heightmap ? GWM_HEIGHTMAP : GWM_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y, reset_settings);
904 }
905 
MakeNewEditorWorldDone()906 static void MakeNewEditorWorldDone()
907 {
908 	SetLocalCompany(OWNER_NONE);
909 }
910 
MakeNewEditorWorld()911 static void MakeNewEditorWorld()
912 {
913 	_game_mode = GM_EDITOR;
914 	/* "reload" command needs to know what mode we were in. */
915 	_file_to_saveload.SetMode(SLO_INVALID, FT_INVALID, DFT_INVALID);
916 
917 	ResetGRFConfig(true);
918 
919 	GenerateWorldSetCallback(&MakeNewEditorWorldDone);
920 	GenerateWorld(GWM_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
921 }
922 
923 /**
924  * Load the specified savegame but on error do different things.
925  * If loading fails due to corrupt savegame, bad version, etc. go back to
926  * a previous correct state. In the menu for example load the intro game again.
927  * @param filename file to be loaded
928  * @param fop mode of loading, always SLO_LOAD
929  * @param newgm switch to this mode of loading fails due to some unknown error
930  * @param subdir default directory to look for filename, set to 0 if not needed
931  * @param lf Load filter to use, if nullptr: use filename + subdir.
932  */
SafeLoad(const std::string & filename,SaveLoadOperation fop,DetailedFileType dft,GameMode newgm,Subdirectory subdir,struct LoadFilter * lf=nullptr)933 bool SafeLoad(const std::string &filename, SaveLoadOperation fop, DetailedFileType dft, GameMode newgm, Subdirectory subdir, struct LoadFilter *lf = nullptr)
934 {
935 	assert(fop == SLO_LOAD);
936 	assert(dft == DFT_GAME_FILE || (lf == nullptr && dft == DFT_OLD_GAME_FILE));
937 	GameMode ogm = _game_mode;
938 
939 	_game_mode = newgm;
940 
941 	switch (lf == nullptr ? SaveOrLoad(filename, fop, dft, subdir) : LoadWithFilter(lf)) {
942 		case SL_OK: return true;
943 
944 		case SL_REINIT:
945 			if (_network_dedicated) {
946 				/*
947 				 * We need to reinit a network map...
948 				 * We can't simply load the intro game here as that game has many
949 				 * special cases which make clients desync immediately. So we fall
950 				 * back to just generating a new game with the current settings.
951 				 */
952 				Debug(net, 0, "Loading game failed, so a new (random) game will be started");
953 				MakeNewGame(false, true);
954 				return false;
955 			}
956 			if (_network_server) {
957 				/* We can't load the intro game as server, so disconnect first. */
958 				NetworkDisconnect();
959 			}
960 
961 			switch (ogm) {
962 				default:
963 				case GM_MENU:   LoadIntroGame();      break;
964 				case GM_EDITOR: MakeNewEditorWorld(); break;
965 			}
966 			return false;
967 
968 		default:
969 			_game_mode = ogm;
970 			return false;
971 	}
972 }
973 
SwitchToMode(SwitchMode new_mode)974 void SwitchToMode(SwitchMode new_mode)
975 {
976 	/* If we are saving something, the network stays in its current state */
977 	if (new_mode != SM_SAVE_GAME) {
978 		/* If the network is active, make it not-active */
979 		if (_networking) {
980 			if (_network_server && (new_mode == SM_LOAD_GAME || new_mode == SM_NEWGAME || new_mode == SM_RESTARTGAME)) {
981 				NetworkReboot();
982 			} else {
983 				NetworkDisconnect();
984 			}
985 		}
986 
987 		/* If we are a server, we restart the server */
988 		if (_is_network_server) {
989 			/* But not if we are going to the menu */
990 			if (new_mode != SM_MENU) {
991 				/* check if we should reload the config */
992 				if (_settings_client.network.reload_cfg) {
993 					LoadFromConfig();
994 					MakeNewgameSettingsLive();
995 					ResetGRFConfig(false);
996 				}
997 				NetworkServerStart();
998 			} else {
999 				/* This client no longer wants to be a network-server */
1000 				_is_network_server = false;
1001 			}
1002 		}
1003 	}
1004 
1005 	/* Make sure all AI controllers are gone at quitting game */
1006 	if (new_mode != SM_SAVE_GAME) AI::KillAll();
1007 
1008 	switch (new_mode) {
1009 		case SM_EDITOR: // Switch to scenario editor
1010 			MakeNewEditorWorld();
1011 			break;
1012 
1013 		case SM_RELOADGAME: // Reload with what-ever started the game
1014 			if (_file_to_saveload.abstract_ftype == FT_SAVEGAME || _file_to_saveload.abstract_ftype == FT_SCENARIO) {
1015 				/* Reload current savegame/scenario */
1016 				_switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_SCENARIO : SM_LOAD_GAME;
1017 				SwitchToMode(_switch_mode);
1018 				break;
1019 			} else if (_file_to_saveload.abstract_ftype == FT_HEIGHTMAP) {
1020 				/* Restart current heightmap */
1021 				_switch_mode = _game_mode == GM_EDITOR ? SM_LOAD_HEIGHTMAP : SM_RESTART_HEIGHTMAP;
1022 				SwitchToMode(_switch_mode);
1023 				break;
1024 			}
1025 
1026 			MakeNewGame(false, new_mode == SM_NEWGAME);
1027 			break;
1028 
1029 		case SM_RESTARTGAME: // Restart --> 'Random game' with current settings
1030 		case SM_NEWGAME: // New Game --> 'Random game'
1031 			MakeNewGame(false, new_mode == SM_NEWGAME);
1032 			break;
1033 
1034 		case SM_LOAD_GAME: { // Load game, Play Scenario
1035 			ResetGRFConfig(true);
1036 			ResetWindowSystem();
1037 
1038 			if (!SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_NORMAL, NO_DIRECTORY)) {
1039 				SetDParamStr(0, GetSaveLoadErrorString());
1040 				ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1041 			} else {
1042 				if (_file_to_saveload.abstract_ftype == FT_SCENARIO) {
1043 					/* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1044 					EngineOverrideManager::ResetToCurrentNewGRFConfig();
1045 				}
1046 				OnStartGame(_network_dedicated);
1047 				/* Decrease pause counter (was increased from opening load dialog) */
1048 				DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1049 			}
1050 			break;
1051 		}
1052 
1053 		case SM_RESTART_HEIGHTMAP: // Load a heightmap and start a new game from it with current settings
1054 		case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
1055 			MakeNewGame(true, new_mode == SM_START_HEIGHTMAP);
1056 			break;
1057 
1058 		case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
1059 			SetLocalCompany(OWNER_NONE);
1060 
1061 			GenerateWorld(GWM_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1062 			MarkWholeScreenDirty();
1063 			break;
1064 
1065 		case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
1066 			if (SafeLoad(_file_to_saveload.name, _file_to_saveload.file_op, _file_to_saveload.detail_ftype, GM_EDITOR, NO_DIRECTORY)) {
1067 				SetLocalCompany(OWNER_NONE);
1068 				_settings_newgame.game_creation.starting_year = _cur_year;
1069 				/* Cancel the saveload pausing */
1070 				DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE);
1071 			} else {
1072 				SetDParamStr(0, GetSaveLoadErrorString());
1073 				ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1074 			}
1075 			break;
1076 		}
1077 
1078 		case SM_JOIN_GAME: // Join a multiplayer game
1079 			LoadIntroGame();
1080 			NetworkClientJoinGame();
1081 			break;
1082 
1083 		case SM_MENU: // Switch to game intro menu
1084 			LoadIntroGame();
1085 			if (BaseSounds::ini_set.empty() && BaseSounds::GetUsedSet()->fallback && SoundDriver::GetInstance()->HasOutput()) {
1086 				ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET, INVALID_STRING_ID, WL_CRITICAL);
1087 				BaseSounds::ini_set = BaseSounds::GetUsedSet()->name;
1088 			}
1089 			break;
1090 
1091 		case SM_SAVE_GAME: // Save game.
1092 			/* Make network saved games on pause compatible to singleplayer mode */
1093 			if (SaveOrLoad(_file_to_saveload.name, SLO_SAVE, DFT_GAME_FILE, NO_DIRECTORY) != SL_OK) {
1094 				SetDParamStr(0, GetSaveLoadErrorString());
1095 				ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR);
1096 			} else {
1097 				CloseWindowById(WC_SAVELOAD, 0);
1098 			}
1099 			break;
1100 
1101 		case SM_SAVE_HEIGHTMAP: // Save heightmap.
1102 			MakeHeightmapScreenshot(_file_to_saveload.name.c_str());
1103 			CloseWindowById(WC_SAVELOAD, 0);
1104 			break;
1105 
1106 		case SM_GENRANDLAND: // Generate random land within scenario editor
1107 			SetLocalCompany(OWNER_NONE);
1108 			GenerateWorld(GWM_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
1109 			/* XXX: set date */
1110 			MarkWholeScreenDirty();
1111 			break;
1112 
1113 		default: NOT_REACHED();
1114 	}
1115 }
1116 
1117 
1118 /**
1119  * Check the validity of some of the caches.
1120  * Especially in the sense of desyncs between
1121  * the cached value and what the value would
1122  * be when calculated from the 'base' data.
1123  */
CheckCaches()1124 static void CheckCaches()
1125 {
1126 	/* Return here so it is easy to add checks that are run
1127 	 * always to aid testing of caches. */
1128 	if (_debug_desync_level <= 1) return;
1129 
1130 	/* Check the town caches. */
1131 	std::vector<TownCache> old_town_caches;
1132 	for (const Town *t : Town::Iterate()) {
1133 		old_town_caches.push_back(t->cache);
1134 	}
1135 
1136 	extern void RebuildTownCaches();
1137 	RebuildTownCaches();
1138 	RebuildSubsidisedSourceAndDestinationCache();
1139 
1140 	uint i = 0;
1141 	for (Town *t : Town::Iterate()) {
1142 		if (MemCmpT(old_town_caches.data() + i, &t->cache) != 0) {
1143 			Debug(desync, 2, "town cache mismatch: town {}", t->index);
1144 		}
1145 		i++;
1146 	}
1147 
1148 	/* Check company infrastructure cache. */
1149 	std::vector<CompanyInfrastructure> old_infrastructure;
1150 	for (const Company *c : Company::Iterate()) old_infrastructure.push_back(c->infrastructure);
1151 
1152 	extern void AfterLoadCompanyStats();
1153 	AfterLoadCompanyStats();
1154 
1155 	i = 0;
1156 	for (const Company *c : Company::Iterate()) {
1157 		if (MemCmpT(old_infrastructure.data() + i, &c->infrastructure) != 0) {
1158 			Debug(desync, 2, "infrastructure cache mismatch: company {}", c->index);
1159 		}
1160 		i++;
1161 	}
1162 
1163 	/* Strict checking of the road stop cache entries */
1164 	for (const RoadStop *rs : RoadStop::Iterate()) {
1165 		if (IsStandardRoadStopTile(rs->xy)) continue;
1166 
1167 		assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
1168 		rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
1169 		rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
1170 	}
1171 
1172 	for (Vehicle *v : Vehicle::Iterate()) {
1173 		extern void FillNewGRFVehicleCache(const Vehicle *v);
1174 		if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;
1175 
1176 		uint length = 0;
1177 		for (const Vehicle *u = v; u != nullptr; u = u->Next()) length++;
1178 
1179 		NewGRFCache        *grf_cache = CallocT<NewGRFCache>(length);
1180 		VehicleCache       *veh_cache = CallocT<VehicleCache>(length);
1181 		GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
1182 		TrainCache         *tra_cache = CallocT<TrainCache>(length);
1183 
1184 		length = 0;
1185 		for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1186 			FillNewGRFVehicleCache(u);
1187 			grf_cache[length] = u->grf_cache;
1188 			veh_cache[length] = u->vcache;
1189 			switch (u->type) {
1190 				case VEH_TRAIN:
1191 					gro_cache[length] = Train::From(u)->gcache;
1192 					tra_cache[length] = Train::From(u)->tcache;
1193 					break;
1194 				case VEH_ROAD:
1195 					gro_cache[length] = RoadVehicle::From(u)->gcache;
1196 					break;
1197 				default:
1198 					break;
1199 			}
1200 			length++;
1201 		}
1202 
1203 		switch (v->type) {
1204 			case VEH_TRAIN:    Train::From(v)->ConsistChanged(CCF_TRACK); break;
1205 			case VEH_ROAD:     RoadVehUpdateCache(RoadVehicle::From(v)); break;
1206 			case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v));   break;
1207 			case VEH_SHIP:     Ship::From(v)->UpdateCache();             break;
1208 			default: break;
1209 		}
1210 
1211 		length = 0;
1212 		for (const Vehicle *u = v; u != nullptr; u = u->Next()) {
1213 			FillNewGRFVehicleCache(u);
1214 			if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
1215 				Debug(desync, 2, "newgrf cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->type, v->index, v->owner, v->unitnumber, length);
1216 			}
1217 			if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
1218 				Debug(desync, 2, "vehicle cache mismatch: type {}, vehicle {}, company {}, unit number {}, wagon {}", v->type, v->index, v->owner, v->unitnumber, length);
1219 			}
1220 			switch (u->type) {
1221 				case VEH_TRAIN:
1222 					if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1223 						Debug(desync, 2, "train ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1224 					}
1225 					if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
1226 						Debug(desync, 2, "train cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1227 					}
1228 					break;
1229 				case VEH_ROAD:
1230 					if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
1231 						Debug(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle {}, company {}, unit number {}, wagon {}", v->index, v->owner, v->unitnumber, length);
1232 					}
1233 					break;
1234 				default:
1235 					break;
1236 			}
1237 			length++;
1238 		}
1239 
1240 		free(grf_cache);
1241 		free(veh_cache);
1242 		free(gro_cache);
1243 		free(tra_cache);
1244 	}
1245 
1246 	/* Check whether the caches are still valid */
1247 	for (Vehicle *v : Vehicle::Iterate()) {
1248 		byte buff[sizeof(VehicleCargoList)];
1249 		memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
1250 		v->cargo.InvalidateCache();
1251 		assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
1252 	}
1253 
1254 	/* Backup stations_near */
1255 	std::vector<StationList> old_town_stations_near;
1256 	for (Town *t : Town::Iterate()) old_town_stations_near.push_back(t->stations_near);
1257 
1258 	std::vector<StationList> old_industry_stations_near;
1259 	for (Industry *ind : Industry::Iterate())  old_industry_stations_near.push_back(ind->stations_near);
1260 
1261 	for (Station *st : Station::Iterate()) {
1262 		for (CargoID c = 0; c < NUM_CARGO; c++) {
1263 			byte buff[sizeof(StationCargoList)];
1264 			memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
1265 			st->goods[c].cargo.InvalidateCache();
1266 			assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
1267 		}
1268 
1269 		/* Check docking tiles */
1270 		TileArea ta;
1271 		std::map<TileIndex, bool> docking_tiles;
1272 		for (TileIndex tile : st->docking_station) {
1273 			ta.Add(tile);
1274 			docking_tiles[tile] = IsDockingTile(tile);
1275 		}
1276 		UpdateStationDockingTiles(st);
1277 		if (ta.tile != st->docking_station.tile || ta.w != st->docking_station.w || ta.h != st->docking_station.h) {
1278 			Debug(desync, 2, "station docking mismatch: station {}, company {}", st->index, st->owner);
1279 		}
1280 		for (TileIndex tile : ta) {
1281 			if (docking_tiles[tile] != IsDockingTile(tile)) {
1282 				Debug(desync, 2, "docking tile mismatch: tile {}", tile);
1283 			}
1284 		}
1285 
1286 		/* Check industries_near */
1287 		IndustryList industries_near = st->industries_near;
1288 		st->RecomputeCatchment();
1289 		if (st->industries_near != industries_near) {
1290 			Debug(desync, 2, "station industries near mismatch: station {}", st->index);
1291 		}
1292 	}
1293 
1294 	/* Check stations_near */
1295 	i = 0;
1296 	for (Town *t : Town::Iterate()) {
1297 		if (t->stations_near != old_town_stations_near[i]) {
1298 			Debug(desync, 2, "town stations near mismatch: town {}", t->index);
1299 		}
1300 		i++;
1301 	}
1302 	i = 0;
1303 	for (Industry *ind : Industry::Iterate()) {
1304 		if (ind->stations_near != old_industry_stations_near[i]) {
1305 			Debug(desync, 2, "industry stations near mismatch: industry {}", ind->index);
1306 		}
1307 		i++;
1308 	}
1309 }
1310 
1311 /**
1312  * State controlling game loop.
1313  * The state must not be changed from anywhere but here.
1314  * That check is enforced in DoCommand.
1315  */
StateGameLoop()1316 void StateGameLoop()
1317 {
1318 	if (!_networking || _network_server) {
1319 		StateGameLoop_LinkGraphPauseControl();
1320 	}
1321 
1322 	/* Don't execute the state loop during pause or when modal windows are open. */
1323 	if (_pause_mode != PM_UNPAUSED || HasModalProgress()) {
1324 		PerformanceMeasurer::Paused(PFE_GAMELOOP);
1325 		PerformanceMeasurer::Paused(PFE_GL_ECONOMY);
1326 		PerformanceMeasurer::Paused(PFE_GL_TRAINS);
1327 		PerformanceMeasurer::Paused(PFE_GL_ROADVEHS);
1328 		PerformanceMeasurer::Paused(PFE_GL_SHIPS);
1329 		PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT);
1330 		PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE);
1331 
1332 		if (!HasModalProgress()) UpdateLandscapingLimits();
1333 #ifndef DEBUG_DUMP_COMMANDS
1334 		Game::GameLoop();
1335 #endif
1336 		return;
1337 	}
1338 
1339 	PerformanceMeasurer framerate(PFE_GAMELOOP);
1340 	PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE);
1341 
1342 	Layouter::ReduceLineCache();
1343 
1344 	if (_game_mode == GM_EDITOR) {
1345 		BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1346 		RunTileLoop();
1347 		CallVehicleTicks();
1348 		CallLandscapeTick();
1349 		BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1350 		UpdateLandscapingLimits();
1351 
1352 		CallWindowGameTickEvent();
1353 		NewsLoop();
1354 	} else {
1355 		if (_debug_desync_level > 2 && _date_fract == 0 && (_date & 0x1F) == 0) {
1356 			/* Save the desync savegame if needed. */
1357 			char name[MAX_PATH];
1358 			seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
1359 			SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
1360 		}
1361 
1362 		CheckCaches();
1363 
1364 		/* All these actions has to be done from OWNER_NONE
1365 		 *  for multiplayer compatibility */
1366 		Backup<CompanyID> cur_company(_current_company, OWNER_NONE, FILE_LINE);
1367 
1368 		BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
1369 		AnimateAnimatedTiles();
1370 		IncreaseDate();
1371 		RunTileLoop();
1372 		CallVehicleTicks();
1373 		CallLandscapeTick();
1374 		BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
1375 
1376 #ifndef DEBUG_DUMP_COMMANDS
1377 		{
1378 			PerformanceMeasurer framerate(PFE_ALLSCRIPTS);
1379 			AI::GameLoop();
1380 			Game::GameLoop();
1381 		}
1382 #endif
1383 		UpdateLandscapingLimits();
1384 
1385 		CallWindowGameTickEvent();
1386 		NewsLoop();
1387 		cur_company.Restore();
1388 	}
1389 
1390 	assert(IsLocalCompany());
1391 }
1392 
1393 /**
1394  * Create an autosave. The default name is "autosave#.sav". However with
1395  * the setting 'keep_all_autosave' the name defaults to company-name + date
1396  */
DoAutosave()1397 static void DoAutosave()
1398 {
1399 	static FiosNumberedSaveName _autosave_ctr("autosave");
1400 	DoAutoOrNetsave(_autosave_ctr);
1401 }
1402 
1403 /**
1404  * Request a new NewGRF scan. This will be executed on the next game-tick.
1405  * This is mostly needed to ensure NewGRF scans (which are blocking) are
1406  * done in the game-thread, and not in the draw-thread (which most often
1407  * triggers this request).
1408  * @param callback Optional callback to call when NewGRF scan is completed.
1409  * @return True when the NewGRF scan was actually requested, false when the scan was already running.
1410  */
RequestNewGRFScan(NewGRFScanCallback * callback)1411 bool RequestNewGRFScan(NewGRFScanCallback *callback)
1412 {
1413 	if (_request_newgrf_scan) return false;
1414 
1415 	_request_newgrf_scan = true;
1416 	_request_newgrf_scan_callback = callback;
1417 	return true;
1418 }
1419 
GameLoop()1420 void GameLoop()
1421 {
1422 	if (_game_mode == GM_BOOTSTRAP) {
1423 		/* Check for UDP stuff */
1424 		if (_network_available) NetworkBackgroundLoop();
1425 		return;
1426 	}
1427 
1428 	if (_request_newgrf_scan) {
1429 		ScanNewGRFFiles(_request_newgrf_scan_callback);
1430 		_request_newgrf_scan = false;
1431 		_request_newgrf_scan_callback = nullptr;
1432 		/* In case someone closed the game during our scan, don't do anything else. */
1433 		if (_exit_game) return;
1434 	}
1435 
1436 	ProcessAsyncSaveFinish();
1437 
1438 	/* autosave game? */
1439 	if (_do_autosave) {
1440 		DoAutosave();
1441 		_do_autosave = false;
1442 		SetWindowDirty(WC_STATUS_BAR, 0);
1443 	}
1444 
1445 	/* switch game mode? */
1446 	if (_switch_mode != SM_NONE && !HasModalProgress()) {
1447 		SwitchToMode(_switch_mode);
1448 		_switch_mode = SM_NONE;
1449 	}
1450 
1451 	IncreaseSpriteLRU();
1452 
1453 	/* Check for UDP stuff */
1454 	if (_network_available) NetworkBackgroundLoop();
1455 
1456 	DebugSendRemoteMessages();
1457 
1458 	if (_networking && !HasModalProgress()) {
1459 		/* Multiplayer */
1460 		NetworkGameLoop();
1461 	} else {
1462 		if (_network_reconnect > 0 && --_network_reconnect == 0) {
1463 			/* This means that we want to reconnect to the last host
1464 			 * We do this here, because it means that the network is really closed */
1465 			NetworkClientConnectGame(_settings_client.network.last_joined, COMPANY_SPECTATOR);
1466 		}
1467 		/* Singleplayer */
1468 		StateGameLoop();
1469 	}
1470 
1471 	if (!_pause_mode && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
1472 
1473 	SoundDriver::GetInstance()->MainLoop();
1474 	MusicLoop();
1475 }
1476