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