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/>.
8 /** @file openttd.cpp Functions related to starting OpenTTD. */
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"
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"
31 #include "console_func.h"
32 #include "screenshot.h"
33 #include "network/network.h"
34 #include "network/network_func.h"
36 #include "ai/ai_config.hpp"
37 #include "settings_func.h"
40 #include "strings_func.h"
41 #include "date_func.h"
42 #include "vehicle_func.h"
44 #include "animated_tile_func.h"
45 #include "roadstop_base.h"
46 #include "elrail_func.h"
48 #include "highscore.h"
49 #include "station_base.h"
51 #include "engine_func.h"
52 #include "core/random_func.hpp"
55 #include "core/backup_type.hpp"
58 #include "misc/getoptdata.h"
59 #include "game/game.hpp"
60 #include "game/game_config.hpp"
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"
69 #include "linkgraph/linkgraphschedule.h"
72 #include <system_error>
74 #include "safeguards.h"
77 # include <emscripten.h>
78 # include <emscripten/html5.h>
81 void CallLandscapeTick();
83 void DoPaletteAnimations();
86 void CallWindowGameTickEvent();
87 bool HandleBootstrap();
89 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
90 extern void ShowOSErrorBox(const char *buf
, bool system
);
91 extern std::string _config_file
;
93 bool _save_config
= false;
96 * Error handling for fatal user errors.
97 * @param s the string to print.
98 * @note Does NEVER return.
100 void CDECL
usererror(const char *s
, ...)
106 vseprintf(buf
, lastof(buf
), s
, va
);
109 ShowOSErrorBox(buf
, false);
110 if (VideoDriver::GetInstance() != nullptr) VideoDriver::GetInstance()->Stop();
112 #ifdef __EMSCRIPTEN__
113 emscripten_exit_pointerlock();
114 /* In effect, the game ends here. As emscripten_set_main_loop() caused
115 * the stack to be unwound, the code after MainLoop() in
116 * openttd_main() is never executed. */
117 EM_ASM(if (window
["openttd_syncfs"]) openttd_syncfs());
118 EM_ASM(if (window
["openttd_abort"]) openttd_abort());
125 * Error handling for fatal non-user errors.
126 * @param s the string to print.
127 * @note Does NEVER return.
129 void CDECL
error(const char *s
, ...)
135 vseprintf(buf
, lastof(buf
), s
, va
);
138 if (VideoDriver::GetInstance() == nullptr || VideoDriver::GetInstance()->HasGUI()) {
139 ShowOSErrorBox(buf
, true);
142 /* Set the error message for the crash log and then invoke it. */
143 CrashLog::SetErrorMessage(buf
);
148 * Shows some information on the console/a popup box depending on the OS.
149 * @param str the text to show.
151 void CDECL
ShowInfoF(const char *str
, ...)
156 vseprintf(buf
, lastof(buf
), str
, va
);
162 * Show the help message when someone passed a wrong parameter.
164 static void ShowHelp()
169 p
+= seprintf(p
, lastof(buf
), "OpenTTD %s\n", _openttd_revision
);
173 "Command line options:\n"
174 " -v drv = Set video driver (see below)\n"
175 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
176 " -m drv = Set music driver (see below)\n"
177 " -b drv = Set the blitter to use (see below)\n"
178 " -r res = Set resolution (for instance 800x600)\n"
179 " -h = Display this help text\n"
180 " -t year = Set starting year\n"
181 " -d [[fac=]lvl[,...]]= Debug mode\n"
182 " -e = Start Editor\n"
183 " -g [savegame] = Start new/save game immediately\n"
184 " -G seed = Set random seed\n"
185 " -n [ip:port#company]= Join network game\n"
186 " -p password = Password to join server\n"
187 " -P password = Password to join company\n"
188 " -D [ip][:port] = Start dedicated server\n"
189 " -l ip[:port] = Redirect DEBUG()\n"
191 " -f = Fork into the background (dedicated only)\n"
193 " -I graphics_set = Force the graphics set (see below)\n"
194 " -S sounds_set = Force the sounds set (see below)\n"
195 " -M music_set = Force the music set (see below)\n"
196 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
197 " -x = Never save configuration changes to disk\n"
198 " -q savegame = Write some information about the savegame and exit\n"
203 /* List the graphics packs */
204 p
= BaseGraphics::GetSetsList(p
, lastof(buf
));
206 /* List the sounds packs */
207 p
= BaseSounds::GetSetsList(p
, lastof(buf
));
209 /* List the music packs */
210 p
= BaseMusic::GetSetsList(p
, lastof(buf
));
212 /* List the drivers */
213 p
= DriverFactoryBase::GetDriversInfo(p
, lastof(buf
));
215 /* List the blitters */
216 p
= BlitterFactory::GetBlittersInfo(p
, lastof(buf
));
218 /* List the debug facilities. */
219 p
= DumpDebugFacilityNames(p
, lastof(buf
));
221 /* We need to initialize the AI, so it finds the AIs */
223 p
= AI::GetConsoleList(p
, lastof(buf
), true);
224 AI::Uninitialize(true);
226 /* We need to initialize the GameScript, so it finds the GSs */
228 p
= Game::GetConsoleList(p
, lastof(buf
), true);
229 Game::Uninitialize(true);
231 /* ShowInfo put output to stderr, but version information should go
232 * to stdout; this is the only exception */
240 static void WriteSavegameInfo(const char *name
)
242 extern SaveLoadVersion _sl_version
;
243 uint32 last_ottd_rev
= 0;
244 byte ever_modified
= 0;
245 bool removed_newgrfs
= false;
247 GamelogInfo(_load_check_data
.gamelog_action
, _load_check_data
.gamelog_actions
, &last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
251 p
+= seprintf(p
, lastof(buf
), "Name: %s\n", name
);
252 p
+= seprintf(p
, lastof(buf
), "Savegame ver: %d\n", _sl_version
);
253 p
+= seprintf(p
, lastof(buf
), "NewGRF ver: 0x%08X\n", last_ottd_rev
);
254 p
+= seprintf(p
, lastof(buf
), "Modified: %d\n", ever_modified
);
256 if (removed_newgrfs
) {
257 p
+= seprintf(p
, lastof(buf
), "NewGRFs have been removed\n");
260 p
= strecpy(p
, "NewGRFs:\n", lastof(buf
));
261 if (_load_check_data
.HasNewGrfs()) {
262 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= nullptr; c
= c
->next
) {
264 md5sumToString(md5sum
, lastof(md5sum
), HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
);
265 p
+= seprintf(p
, lastof(buf
), "%08X %s %s\n", c
->ident
.grfid
, md5sum
, c
->filename
);
269 /* ShowInfo put output to stderr, but version information should go
270 * to stdout; this is the only exception */
280 * Extract the resolution from the given string and store
281 * it in the 'res' parameter.
282 * @param res variable to store the resolution in.
283 * @param s the string to decompose.
285 static void ParseResolution(Dimension
*res
, const char *s
)
287 const char *t
= strchr(s
, 'x');
289 ShowInfoF("Invalid resolution '%s'", s
);
293 res
->width
= std::max(strtoul(s
, nullptr, 0), 64UL);
294 res
->height
= std::max(strtoul(t
+ 1, nullptr, 0), 64UL);
299 * Uninitializes drivers, frees allocated memory, cleans pools, ...
300 * Generally, prepares the game for shutting down
302 static void ShutdownGame()
306 if (_network_available
) NetworkShutDown(); // Shut down the network and close any open connections
308 DriverFactoryBase::ShutdownDrivers();
310 UnInitWindowSystem();
312 /* stop the scripts */
313 AI::Uninitialize(false);
314 Game::Uninitialize(false);
316 /* Uninitialize variables that are allocated dynamically */
319 LinkGraphSchedule::Clear();
320 PoolBase::Clean(PT_ALL
);
322 /* No NewGRFs were loaded when it was still bootstrapping. */
323 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
325 /* Close all and any open filehandles */
332 * Load the introduction game.
333 * @param load_newgrfs Whether to load the NewGRFs or not.
335 static void LoadIntroGame(bool load_newgrfs
= true)
337 _game_mode
= GM_MENU
;
339 if (load_newgrfs
) ResetGRFConfig(false);
341 /* Setup main window */
343 SetupColoursAndInitialWindow();
345 /* Load the default opening screen savegame */
346 if (SaveOrLoad("opntitle.dat", SLO_LOAD
, DFT_GAME_FILE
, BASESET_DIR
) != SL_OK
) {
347 GenerateWorld(GWM_EMPTY
, 64, 64); // if failed loading, make empty world.
348 WaitTillGeneratedWorld();
349 SetLocalCompany(COMPANY_SPECTATOR
);
351 SetLocalCompany(COMPANY_FIRST
);
355 _pause_mode
= PM_UNPAUSED
;
356 _cursor
.fix_at
= false;
358 CheckForMissingGlyphs();
360 MusicLoop(); // ensure music is correct
363 void MakeNewgameSettingsLive()
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
];
370 if (_settings_game
.game_config
!= nullptr) {
371 delete _settings_game
.game_config
;
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
;
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);
388 _settings_game
.game_config
= nullptr;
389 if (_settings_newgame
.game_config
!= nullptr) {
390 _settings_game
.game_config
= new GameConfig(_settings_newgame
.game_config
);
394 void OpenBrowser(const char *url
)
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;
399 extern void OSOpenBrowser(const char *url
);
403 /** Callback structure of statements to be executed after the NewGRF scan. */
404 struct AfterNewGRFScan
: NewGRFScanCallback
{
405 Year startyear
; ///< The start year.
406 uint32 generation_seed
; ///< Seed for the new game.
407 char *dedicated_host
; ///< Hostname for the dedicated server.
408 uint16 dedicated_port
; ///< Port for the dedicated server.
409 char *network_conn
; ///< Information about the server to connect to, or nullptr.
410 const char *join_server_password
; ///< The password to join the server with.
411 const char *join_company_password
; ///< The password to join the company with.
412 bool save_config
; ///< The save config setting.
415 * Create a new callback.
418 startyear(INVALID_YEAR
), generation_seed(GENERATE_NEW_SEED
),
419 dedicated_host(nullptr), dedicated_port(0), network_conn(nullptr),
420 join_server_password(nullptr), join_company_password(nullptr),
423 /* Visual C++ 2015 fails compiling this line (AfterNewGRFScan::generation_seed undefined symbol)
424 * if it's placed outside a member function, directly in the struct body. */
425 static_assert(sizeof(generation_seed
) == sizeof(_settings_game
.game_creation
.generation_seed
));
428 virtual void OnNewGRFsScanned()
430 ResetGRFConfig(false);
432 TarScanner::DoScan(TarScanner::SCENARIO
);
437 /* We want the new (correct) NewGRF count to survive the loading. */
438 uint last_newgrf_count
= _settings_client
.gui
.last_newgrf_count
;
440 _settings_client
.gui
.last_newgrf_count
= last_newgrf_count
;
441 /* Since the default for the palette might have changed due to
442 * reading the configuration file, recalculate that now. */
443 UpdateNewGRFConfigPalette();
445 Game::Uninitialize(true);
446 AI::Uninitialize(true);
448 LoadHotkeysFromConfig();
449 WindowDesc::LoadFromConfig();
451 /* We have loaded the config, so we may possibly save it. */
452 _save_config
= save_config
;
454 /* restore saved music volume */
455 MusicDriver::GetInstance()->SetVolume(_settings_client
.music
.music_vol
);
457 if (startyear
!= INVALID_YEAR
) _settings_newgame
.game_creation
.starting_year
= startyear
;
458 if (generation_seed
!= GENERATE_NEW_SEED
) _settings_newgame
.game_creation
.generation_seed
= generation_seed
;
460 if (dedicated_host
!= nullptr) {
461 _network_bind_list
.clear();
462 _network_bind_list
.emplace_back(dedicated_host
);
464 if (dedicated_port
!= 0) _settings_client
.network
.server_port
= dedicated_port
;
466 /* initialize the ingame console */
469 IConsoleCmdExec("exec scripts/autoexec.scr 0");
471 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
472 if (_switch_mode
!= SM_NONE
) MakeNewgameSettingsLive();
474 if (_network_available
&& network_conn
!= nullptr) {
475 const char *port
= nullptr;
476 const char *company
= nullptr;
477 uint16 rport
= NETWORK_DEFAULT_PORT
;
478 CompanyID join_as
= COMPANY_NEW_COMPANY
;
480 ParseConnectionString(&company
, &port
, network_conn
);
482 if (company
!= nullptr) {
483 join_as
= (CompanyID
)atoi(company
);
485 if (join_as
!= COMPANY_SPECTATOR
) {
487 if (join_as
>= MAX_COMPANIES
) {
493 if (port
!= nullptr) rport
= atoi(port
);
496 _switch_mode
= SM_NONE
;
497 NetworkClientConnectGame(NetworkAddress(network_conn
, rport
), join_as
, join_server_password
, join_company_password
);
500 /* After the scan we're not used anymore. */
506 extern void DedicatedFork();
509 /** Options of OpenTTD. */
510 static const OptionData _options
[] = {
511 GETOPT_SHORT_VALUE('I'),
512 GETOPT_SHORT_VALUE('S'),
513 GETOPT_SHORT_VALUE('M'),
514 GETOPT_SHORT_VALUE('m'),
515 GETOPT_SHORT_VALUE('s'),
516 GETOPT_SHORT_VALUE('v'),
517 GETOPT_SHORT_VALUE('b'),
518 GETOPT_SHORT_OPTVAL('D'),
519 GETOPT_SHORT_OPTVAL('n'),
520 GETOPT_SHORT_VALUE('l'),
521 GETOPT_SHORT_VALUE('p'),
522 GETOPT_SHORT_VALUE('P'),
524 GETOPT_SHORT_NOVAL('f'),
526 GETOPT_SHORT_VALUE('r'),
527 GETOPT_SHORT_VALUE('t'),
528 GETOPT_SHORT_OPTVAL('d'),
529 GETOPT_SHORT_NOVAL('e'),
530 GETOPT_SHORT_OPTVAL('g'),
531 GETOPT_SHORT_VALUE('G'),
532 GETOPT_SHORT_VALUE('c'),
533 GETOPT_SHORT_NOVAL('x'),
534 GETOPT_SHORT_VALUE('q'),
535 GETOPT_SHORT_NOVAL('h'),
540 * Main entry point for this lovely game.
541 * @param argc The number of arguments passed to this game.
542 * @param argv The values of the arguments.
543 * @return 0 when there is no error.
545 int openttd_main(int argc
, char *argv
[])
547 std::string musicdriver
;
548 std::string sounddriver
;
549 std::string videodriver
;
551 std::string graphics_set
;
552 std::string sounds_set
;
553 std::string music_set
;
554 Dimension resolution
= {0, 0};
555 std::unique_ptr
<AfterNewGRFScan
> scanner(new AfterNewGRFScan());
556 bool dedicated
= false;
557 char *debuglog_conn
= nullptr;
559 extern bool _dedicated_forks
;
560 _dedicated_forks
= false;
562 std::unique_lock
<std::mutex
> modal_work_lock(_modal_progress_work_mutex
, std::defer_lock
);
563 std::unique_lock
<std::mutex
> modal_paint_lock(_modal_progress_paint_mutex
, std::defer_lock
);
565 _game_mode
= GM_MENU
;
566 _switch_mode
= SM_MENU
;
568 GetOptData
mgo(argc
- 1, argv
+ 1, _options
);
572 while ((i
= mgo
.GetOpt()) != -1) {
574 case 'I': graphics_set
= mgo
.opt
; break;
575 case 'S': sounds_set
= mgo
.opt
; break;
576 case 'M': music_set
= mgo
.opt
; break;
577 case 'm': musicdriver
= mgo
.opt
; break;
578 case 's': sounddriver
= mgo
.opt
; break;
579 case 'v': videodriver
= mgo
.opt
; break;
580 case 'b': blitter
= mgo
.opt
; break;
582 musicdriver
= "null";
583 sounddriver
= "null";
584 videodriver
= "dedicated";
587 SetDebugString("net=6");
588 if (mgo
.opt
!= nullptr) {
589 /* Use the existing method for parsing (openttd -n).
590 * However, we do ignore the #company part. */
591 const char *temp
= nullptr;
592 const char *port
= nullptr;
593 ParseConnectionString(&temp
, &port
, mgo
.opt
);
594 if (!StrEmpty(mgo
.opt
)) scanner
->dedicated_host
= mgo
.opt
;
595 if (port
!= nullptr) scanner
->dedicated_port
= atoi(port
);
598 case 'f': _dedicated_forks
= true; break;
600 scanner
->network_conn
= mgo
.opt
; // optional IP parameter, nullptr if unset
603 debuglog_conn
= mgo
.opt
;
606 scanner
->join_server_password
= mgo
.opt
;
609 scanner
->join_company_password
= mgo
.opt
;
611 case 'r': ParseResolution(&resolution
, mgo
.opt
); break;
612 case 't': scanner
->startyear
= atoi(mgo
.opt
); break;
617 if (mgo
.opt
!= nullptr) SetDebugString(mgo
.opt
);
620 case 'e': _switch_mode
= (_switch_mode
== SM_LOAD_GAME
|| _switch_mode
== SM_LOAD_SCENARIO
? SM_LOAD_SCENARIO
: SM_EDITOR
); break;
622 if (mgo
.opt
!= nullptr) {
623 _file_to_saveload
.SetName(mgo
.opt
);
624 bool is_scenario
= _switch_mode
== SM_EDITOR
|| _switch_mode
== SM_LOAD_SCENARIO
;
625 _switch_mode
= is_scenario
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
626 _file_to_saveload
.SetMode(SLO_LOAD
, is_scenario
? FT_SCENARIO
: FT_SAVEGAME
, DFT_GAME_FILE
);
628 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
629 auto t
= _file_to_saveload
.name
.find_last_of('.');
630 if (t
!= std::string::npos
) {
631 FiosType ft
= FiosGetSavegameListCallback(SLO_LOAD
, _file_to_saveload
.name
, _file_to_saveload
.name
.substr(t
).c_str(), nullptr, nullptr);
632 if (ft
!= FIOS_TYPE_INVALID
) _file_to_saveload
.SetMode(ft
);
638 _switch_mode
= SM_NEWGAME
;
639 /* Give a random map if no seed has been given */
640 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
641 scanner
->generation_seed
= InteractiveRandom();
645 DeterminePaths(argv
[0]);
646 if (StrEmpty(mgo
.opt
)) {
653 FiosGetSavegameListCallback(SLO_LOAD
, mgo
.opt
, strrchr(mgo
.opt
, '.'), title
, lastof(title
));
655 _load_check_data
.Clear();
656 SaveOrLoadResult res
= SaveOrLoad(mgo
.opt
, SLO_CHECK
, DFT_GAME_FILE
, SAVE_DIR
, false);
657 if (res
!= SL_OK
|| _load_check_data
.HasErrors()) {
658 fprintf(stderr
, "Failed to open savegame\n");
659 if (_load_check_data
.HasErrors()) {
661 SetDParamStr(0, _load_check_data
.error_data
);
662 GetString(buf
, _load_check_data
.error
, lastof(buf
));
663 fprintf(stderr
, "%s\n", buf
);
668 WriteSavegameInfo(title
);
671 case 'G': scanner
->generation_seed
= strtoul(mgo
.opt
, nullptr, 10); break;
672 case 'c': _config_file
= mgo
.opt
; break;
673 case 'x': scanner
->save_config
= false; break;
675 i
= -2; // Force printing of help.
681 if (i
== -2 || mgo
.numleft
> 0) {
682 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
683 * In all cases, print the help, and exit.
685 * The next two functions are needed to list the graphics sets. We can't do them earlier
686 * because then we cannot show it on the debug console as that hasn't been configured yet. */
687 DeterminePaths(argv
[0]);
688 TarScanner::DoScan(TarScanner::BASESET
);
689 BaseGraphics::FindSets();
690 BaseSounds::FindSets();
691 BaseMusic::FindSets();
696 DeterminePaths(argv
[0]);
697 TarScanner::DoScan(TarScanner::BASESET
);
699 if (dedicated
) DEBUG(net
, 0, "Starting dedicated version %s", _openttd_revision
);
700 if (_dedicated_forks
&& !dedicated
) _dedicated_forks
= false;
703 /* We must fork here, or we'll end up without some resources we need (like sockets) */
704 if (_dedicated_forks
) DedicatedFork();
707 LoadFromConfig(true);
709 if (resolution
.width
!= 0) _cur_resolution
= resolution
;
711 /* Limit width times height times bytes per pixel to fit a 32 bit
712 * integer, This way all internal drawing routines work correctly.
713 * A resolution that has one component as 0 is treated as a marker to
714 * auto-detect a good window size. */
715 _cur_resolution
.width
= std::min(_cur_resolution
.width
, UINT16_MAX
/ 2u);
716 _cur_resolution
.height
= std::min(_cur_resolution
.height
, UINT16_MAX
/ 2u);
718 /* Assume the cursor starts within the game as not all video drivers
719 * get an event that the cursor is within the window when it is opened.
720 * Saying the cursor is there makes no visible difference as it would
721 * just be out of the bounds of the window. */
722 _cursor
.in_window
= true;
724 /* enumerate language files */
725 InitializeLanguagePacks();
727 /* Initialize the regular font for FreeType */
730 /* This must be done early, since functions use the SetWindowDirty* calls */
733 BaseGraphics::FindSets();
734 if (graphics_set
.empty() && !BaseGraphics::ini_set
.empty()) graphics_set
= BaseGraphics::ini_set
;
735 if (!BaseGraphics::SetSet(graphics_set
)) {
736 if (!graphics_set
.empty()) {
737 BaseGraphics::SetSet({});
739 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
740 msg
.SetDParamStr(0, graphics_set
.c_str());
741 ScheduleErrorMessage(msg
);
745 /* Initialize game palette */
748 DEBUG(misc
, 1, "Loading blitter...");
749 if (blitter
.empty() && !_ini_blitter
.empty()) blitter
= _ini_blitter
;
750 _blitter_autodetected
= blitter
.empty();
751 /* Activate the initial blitter.
752 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
753 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
754 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
755 * - Use 8bpp blitter otherwise.
757 if (!_blitter_autodetected
||
758 (_support8bpp
!= S8BPP_NONE
&& (BaseGraphics::GetUsedSet() == nullptr || BaseGraphics::GetUsedSet()->blitter
== BLT_8BPP
)) ||
759 BlitterFactory::SelectBlitter("32bpp-anim") == nullptr) {
760 if (BlitterFactory::SelectBlitter(blitter
) == nullptr) {
762 usererror("Failed to autoprobe blitter") :
763 usererror("Failed to select requested blitter '%s'; does it exist?", blitter
.c_str());
767 if (videodriver
.empty() && !_ini_videodriver
.empty()) videodriver
= _ini_videodriver
;
768 DriverFactoryBase::SelectDriver(videodriver
, Driver::DT_VIDEO
);
770 InitializeSpriteSorter();
772 /* Initialize the zoom level of the screen to normal */
773 _screen
.zoom
= ZOOM_LVL_NORMAL
;
776 NetworkStartUp(); // initialize network-core
778 if (debuglog_conn
!= nullptr && _network_available
) {
779 const char *not_used
= nullptr;
780 const char *port
= nullptr;
783 rport
= NETWORK_DEFAULT_DEBUGLOG_PORT
;
785 ParseConnectionString(¬_used
, &port
, debuglog_conn
);
786 if (port
!= nullptr) rport
= atoi(port
);
788 NetworkStartDebugLog(NetworkAddress(debuglog_conn
, rport
));
791 if (!HandleBootstrap()) {
796 VideoDriver::GetInstance()->ClaimMousePointer();
798 /* initialize screenshot formats */
799 InitializeScreenshotFormats();
801 BaseSounds::FindSets();
802 if (sounds_set
.empty() && !BaseSounds::ini_set
.empty()) sounds_set
= BaseSounds::ini_set
;
803 if (!BaseSounds::SetSet(sounds_set
)) {
804 if (sounds_set
.empty() || !BaseSounds::SetSet({})) {
805 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 1.4 of README.md.");
807 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
808 msg
.SetDParamStr(0, sounds_set
.c_str());
809 ScheduleErrorMessage(msg
);
813 BaseMusic::FindSets();
814 if (music_set
.empty() && !BaseMusic::ini_set
.empty()) music_set
= BaseMusic::ini_set
;
815 if (!BaseMusic::SetSet(music_set
)) {
816 if (music_set
.empty() || !BaseMusic::SetSet({})) {
817 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 1.4 of README.md.");
819 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
820 msg
.SetDParamStr(0, music_set
.c_str());
821 ScheduleErrorMessage(msg
);
825 if (sounddriver
.empty() && !_ini_sounddriver
.empty()) sounddriver
= _ini_sounddriver
;
826 DriverFactoryBase::SelectDriver(sounddriver
, Driver::DT_SOUND
);
828 if (musicdriver
.empty() && !_ini_musicdriver
.empty()) musicdriver
= _ini_musicdriver
;
829 DriverFactoryBase::SelectDriver(musicdriver
, Driver::DT_MUSIC
);
831 /* Take our initial lock on whatever we might want to do! */
833 modal_work_lock
.lock();
834 modal_paint_lock
.lock();
835 } catch (const std::system_error
&) {
836 /* If there is some error we assume that threads aren't usable on the system we run. */
837 extern bool _use_threaded_modal_progress
; // From progress.cpp
838 _use_threaded_modal_progress
= false;
841 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
842 WaitTillGeneratedWorld();
844 LoadIntroGame(false);
846 CheckForMissingGlyphs();
848 /* ScanNewGRFFiles now has control over the scanner. */
849 ScanNewGRFFiles(scanner
.release());
851 VideoDriver::GetInstance()->MainLoop();
854 WaitTillGeneratedWorld(); // Make sure any generate world threads have been joined.
856 /* only save config if we have to */
859 SaveHotkeysToConfig();
860 WindowDesc::SaveToConfig();
864 /* Reset windowing system, stop drivers, free used memory, ... */
869 void HandleExitGameRequest()
871 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
873 } else if (_settings_client
.gui
.autosave_on_exit
) {
881 static void MakeNewGameDone()
883 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
885 /* In a dedicated server, the server does not play */
886 if (!VideoDriver::GetInstance()->HasGUI()) {
887 SetLocalCompany(COMPANY_SPECTATOR
);
888 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
889 IConsoleCmdExec("exec scripts/game_start.scr 0");
893 /* Create a single company */
894 DoStartupNewCompany(false);
896 Company
*c
= Company::Get(COMPANY_FIRST
);
897 c
->settings
= _settings_client
.company
;
899 /* Overwrite color from settings if needed
900 * COLOUR_END corresponds to Random colour */
901 if (_settings_client
.gui
.starting_colour
!= COLOUR_END
) {
902 c
->colour
= _settings_client
.gui
.starting_colour
;
903 ResetCompanyLivery(c
);
904 _company_colours
[c
->index
] = (Colours
)c
->colour
;
907 IConsoleCmdExec("exec scripts/game_start.scr 0");
909 SetLocalCompany(COMPANY_FIRST
);
914 /* We are the server, we start a new company (not dedicated),
915 * so set the default password *if* needed. */
916 if (_network_server
&& !StrEmpty(_settings_client
.network
.default_company_pass
)) {
917 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
920 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
924 MarkWholeScreenDirty();
927 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
929 _game_mode
= GM_NORMAL
;
930 if (!from_heightmap
) {
931 /* "reload" command needs to know what mode we were in. */
932 _file_to_saveload
.SetMode(SLO_INVALID
, FT_INVALID
, DFT_INVALID
);
935 ResetGRFConfig(true);
937 GenerateWorldSetCallback(&MakeNewGameDone
);
938 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
941 static void MakeNewEditorWorldDone()
943 SetLocalCompany(OWNER_NONE
);
946 static void MakeNewEditorWorld()
948 _game_mode
= GM_EDITOR
;
949 /* "reload" command needs to know what mode we were in. */
950 _file_to_saveload
.SetMode(SLO_INVALID
, FT_INVALID
, DFT_INVALID
);
952 ResetGRFConfig(true);
954 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
955 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
959 * Load the specified savegame but on error do different things.
960 * If loading fails due to corrupt savegame, bad version, etc. go back to
961 * a previous correct state. In the menu for example load the intro game again.
962 * @param filename file to be loaded
963 * @param fop mode of loading, always SLO_LOAD
964 * @param newgm switch to this mode of loading fails due to some unknown error
965 * @param subdir default directory to look for filename, set to 0 if not needed
966 * @param lf Load filter to use, if nullptr: use filename + subdir.
968 bool SafeLoad(const std::string
&filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= nullptr)
970 assert(fop
== SLO_LOAD
);
971 assert(dft
== DFT_GAME_FILE
|| (lf
== nullptr && dft
== DFT_OLD_GAME_FILE
));
972 GameMode ogm
= _game_mode
;
976 switch (lf
== nullptr ? SaveOrLoad(filename
, fop
, dft
, subdir
) : LoadWithFilter(lf
)) {
977 case SL_OK
: return true;
980 if (_network_dedicated
) {
982 * We need to reinit a network map...
983 * We can't simply load the intro game here as that game has many
984 * special cases which make clients desync immediately. So we fall
985 * back to just generating a new game with the current settings.
987 DEBUG(net
, 0, "Loading game failed, so a new (random) game will be started!");
988 MakeNewGame(false, true);
991 if (_network_server
) {
992 /* We can't load the intro game as server, so disconnect first. */
998 case GM_MENU
: LoadIntroGame(); break;
999 case GM_EDITOR
: MakeNewEditorWorld(); break;
1009 void SwitchToMode(SwitchMode new_mode
)
1011 /* If we are saving something, the network stays in his current state */
1012 if (new_mode
!= SM_SAVE_GAME
) {
1013 /* If the network is active, make it not-active */
1015 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1018 NetworkDisconnect();
1022 /* If we are a server, we restart the server */
1023 if (_is_network_server
) {
1024 /* But not if we are going to the menu */
1025 if (new_mode
!= SM_MENU
) {
1026 /* check if we should reload the config */
1027 if (_settings_client
.network
.reload_cfg
) {
1029 MakeNewgameSettingsLive();
1030 ResetGRFConfig(false);
1032 NetworkServerStart();
1034 /* This client no longer wants to be a network-server */
1035 _is_network_server
= false;
1040 /* Make sure all AI controllers are gone at quitting game */
1041 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1044 case SM_EDITOR
: // Switch to scenario editor
1045 MakeNewEditorWorld();
1048 case SM_RELOADGAME
: // Reload with what-ever started the game
1049 if (_file_to_saveload
.abstract_ftype
== FT_SAVEGAME
|| _file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1050 /* Reload current savegame/scenario */
1051 _switch_mode
= _game_mode
== GM_EDITOR
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
1052 SwitchToMode(_switch_mode
);
1054 } else if (_file_to_saveload
.abstract_ftype
== FT_HEIGHTMAP
) {
1055 /* Restart current heightmap */
1056 _switch_mode
= _game_mode
== GM_EDITOR
? SM_LOAD_HEIGHTMAP
: SM_RESTART_HEIGHTMAP
;
1057 SwitchToMode(_switch_mode
);
1061 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1064 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1065 case SM_NEWGAME
: // New Game --> 'Random game'
1066 if (_network_server
) {
1067 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "Random Map");
1069 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1072 case SM_LOAD_GAME
: { // Load game, Play Scenario
1073 ResetGRFConfig(true);
1074 ResetWindowSystem();
1076 if (!SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_NORMAL
, NO_DIRECTORY
)) {
1077 SetDParamStr(0, GetSaveLoadErrorString());
1078 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1080 if (_file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1081 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1082 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1084 /* Update the local company for a loaded game. It is either always
1085 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1086 SetLocalCompany(_network_dedicated
? COMPANY_SPECTATOR
: COMPANY_FIRST
);
1087 /* Execute the game-start script */
1088 IConsoleCmdExec("exec scripts/game_start.scr 0");
1089 /* Decrease pause counter (was increased from opening load dialog) */
1090 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1091 if (_network_server
) {
1092 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Loaded game)", _file_to_saveload
.title
);
1098 case SM_RESTART_HEIGHTMAP
: // Load a heightmap and start a new game from it with current settings
1099 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1100 if (_network_server
) {
1101 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Heightmap)", _file_to_saveload
.title
);
1103 MakeNewGame(true, new_mode
== SM_START_HEIGHTMAP
);
1106 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1107 SetLocalCompany(OWNER_NONE
);
1109 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1110 MarkWholeScreenDirty();
1113 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1114 if (SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_EDITOR
, NO_DIRECTORY
)) {
1115 SetLocalCompany(OWNER_NONE
);
1116 _settings_newgame
.game_creation
.starting_year
= _cur_year
;
1117 /* Cancel the saveload pausing */
1118 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1120 SetDParamStr(0, GetSaveLoadErrorString());
1121 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1126 case SM_MENU
: // Switch to game intro menu
1128 if (BaseSounds::ini_set
.empty() && BaseSounds::GetUsedSet()->fallback
&& SoundDriver::GetInstance()->HasOutput()) {
1129 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1130 BaseSounds::ini_set
= BaseSounds::GetUsedSet()->name
;
1134 case SM_SAVE_GAME
: // Save game.
1135 /* Make network saved games on pause compatible to singleplayer mode */
1136 if (SaveOrLoad(_file_to_saveload
.name
, SLO_SAVE
, DFT_GAME_FILE
, NO_DIRECTORY
) != SL_OK
) {
1137 SetDParamStr(0, GetSaveLoadErrorString());
1138 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1140 DeleteWindowById(WC_SAVELOAD
, 0);
1144 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1145 MakeHeightmapScreenshot(_file_to_saveload
.name
.c_str());
1146 DeleteWindowById(WC_SAVELOAD
, 0);
1149 case SM_GENRANDLAND
: // Generate random land within scenario editor
1150 SetLocalCompany(OWNER_NONE
);
1151 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1153 MarkWholeScreenDirty();
1156 default: NOT_REACHED();
1162 * Check the validity of some of the caches.
1163 * Especially in the sense of desyncs between
1164 * the cached value and what the value would
1165 * be when calculated from the 'base' data.
1167 static void CheckCaches()
1169 /* Return here so it is easy to add checks that are run
1170 * always to aid testing of caches. */
1171 if (_debug_desync_level
<= 1) return;
1173 /* Check the town caches. */
1174 std::vector
<TownCache
> old_town_caches
;
1175 for (const Town
*t
: Town::Iterate()) {
1176 old_town_caches
.push_back(t
->cache
);
1179 extern void RebuildTownCaches();
1180 RebuildTownCaches();
1181 RebuildSubsidisedSourceAndDestinationCache();
1184 for (Town
*t
: Town::Iterate()) {
1185 if (MemCmpT(old_town_caches
.data() + i
, &t
->cache
) != 0) {
1186 DEBUG(desync
, 2, "town cache mismatch: town %i", (int)t
->index
);
1191 /* Check company infrastructure cache. */
1192 std::vector
<CompanyInfrastructure
> old_infrastructure
;
1193 for (const Company
*c
: Company::Iterate()) old_infrastructure
.push_back(c
->infrastructure
);
1195 extern void AfterLoadCompanyStats();
1196 AfterLoadCompanyStats();
1199 for (const Company
*c
: Company::Iterate()) {
1200 if (MemCmpT(old_infrastructure
.data() + i
, &c
->infrastructure
) != 0) {
1201 DEBUG(desync
, 2, "infrastructure cache mismatch: company %i", (int)c
->index
);
1206 /* Strict checking of the road stop cache entries */
1207 for (const RoadStop
*rs
: RoadStop::Iterate()) {
1208 if (IsStandardRoadStopTile(rs
->xy
)) continue;
1210 assert(rs
->GetEntry(DIAGDIR_NE
) != rs
->GetEntry(DIAGDIR_NW
));
1211 rs
->GetEntry(DIAGDIR_NE
)->CheckIntegrity(rs
);
1212 rs
->GetEntry(DIAGDIR_NW
)->CheckIntegrity(rs
);
1215 for (Vehicle
*v
: Vehicle::Iterate()) {
1216 extern void FillNewGRFVehicleCache(const Vehicle
*v
);
1217 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1220 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) length
++;
1222 NewGRFCache
*grf_cache
= CallocT
<NewGRFCache
>(length
);
1223 VehicleCache
*veh_cache
= CallocT
<VehicleCache
>(length
);
1224 GroundVehicleCache
*gro_cache
= CallocT
<GroundVehicleCache
>(length
);
1225 TrainCache
*tra_cache
= CallocT
<TrainCache
>(length
);
1228 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1229 FillNewGRFVehicleCache(u
);
1230 grf_cache
[length
] = u
->grf_cache
;
1231 veh_cache
[length
] = u
->vcache
;
1234 gro_cache
[length
] = Train::From(u
)->gcache
;
1235 tra_cache
[length
] = Train::From(u
)->tcache
;
1238 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1247 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(CCF_TRACK
); break;
1248 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1249 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1250 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1255 for (const Vehicle
*u
= v
; u
!= nullptr; u
= u
->Next()) {
1256 FillNewGRFVehicleCache(u
);
1257 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1258 DEBUG(desync
, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v
->type
, v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1260 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1261 DEBUG(desync
, 2, "vehicle cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v
->type
, v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1265 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1266 DEBUG(desync
, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1268 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1269 DEBUG(desync
, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1273 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1274 DEBUG(desync
, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1289 /* Check whether the caches are still valid */
1290 for (Vehicle
*v
: Vehicle::Iterate()) {
1291 byte buff
[sizeof(VehicleCargoList
)];
1292 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1293 v
->cargo
.InvalidateCache();
1294 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1297 /* Backup stations_near */
1298 std::vector
<StationList
> old_town_stations_near
;
1299 for (Town
*t
: Town::Iterate()) old_town_stations_near
.push_back(t
->stations_near
);
1301 std::vector
<StationList
> old_industry_stations_near
;
1302 for (Industry
*ind
: Industry::Iterate()) old_industry_stations_near
.push_back(ind
->stations_near
);
1304 for (Station
*st
: Station::Iterate()) {
1305 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
1306 byte buff
[sizeof(StationCargoList
)];
1307 memcpy(buff
, &st
->goods
[c
].cargo
, sizeof(StationCargoList
));
1308 st
->goods
[c
].cargo
.InvalidateCache();
1309 assert(memcmp(&st
->goods
[c
].cargo
, buff
, sizeof(StationCargoList
)) == 0);
1312 /* Check docking tiles */
1314 std::map
<TileIndex
, bool> docking_tiles
;
1315 TILE_AREA_LOOP(tile
, st
->docking_station
) {
1317 docking_tiles
[tile
] = IsDockingTile(tile
);
1319 UpdateStationDockingTiles(st
);
1320 if (ta
.tile
!= st
->docking_station
.tile
|| ta
.w
!= st
->docking_station
.w
|| ta
.h
!= st
->docking_station
.h
) {
1321 DEBUG(desync
, 2, "station docking mismatch: station %i, company %i", st
->index
, (int)st
->owner
);
1323 TILE_AREA_LOOP(tile
, ta
) {
1324 if (docking_tiles
[tile
] != IsDockingTile(tile
)) {
1325 DEBUG(desync
, 2, "docking tile mismatch: tile %i", (int)tile
);
1329 /* Check industries_near */
1330 IndustryList industries_near
= st
->industries_near
;
1331 st
->RecomputeCatchment();
1332 if (st
->industries_near
!= industries_near
) {
1333 DEBUG(desync
, 2, "station industries near mismatch: station %i", st
->index
);
1337 /* Check stations_near */
1339 for (Town
*t
: Town::Iterate()) {
1340 if (t
->stations_near
!= old_town_stations_near
[i
]) {
1341 DEBUG(desync
, 2, "town stations near mismatch: town %i", t
->index
);
1346 for (Industry
*ind
: Industry::Iterate()) {
1347 if (ind
->stations_near
!= old_industry_stations_near
[i
]) {
1348 DEBUG(desync
, 2, "industry stations near mismatch: industry %i", ind
->index
);
1355 * State controlling game loop.
1356 * The state must not be changed from anywhere but here.
1357 * That check is enforced in DoCommand.
1359 void StateGameLoop()
1361 if (!_networking
|| _network_server
) {
1362 StateGameLoop_LinkGraphPauseControl();
1365 /* don't execute the state loop during pause */
1366 if (_pause_mode
!= PM_UNPAUSED
) {
1367 PerformanceMeasurer::Paused(PFE_GAMELOOP
);
1368 PerformanceMeasurer::Paused(PFE_GL_ECONOMY
);
1369 PerformanceMeasurer::Paused(PFE_GL_TRAINS
);
1370 PerformanceMeasurer::Paused(PFE_GL_ROADVEHS
);
1371 PerformanceMeasurer::Paused(PFE_GL_SHIPS
);
1372 PerformanceMeasurer::Paused(PFE_GL_AIRCRAFT
);
1373 PerformanceMeasurer::Paused(PFE_GL_LANDSCAPE
);
1375 UpdateLandscapingLimits();
1376 #ifndef DEBUG_DUMP_COMMANDS
1382 PerformanceMeasurer
framerate(PFE_GAMELOOP
);
1383 PerformanceAccumulator::Reset(PFE_GL_LANDSCAPE
);
1384 if (HasModalProgress()) return;
1386 Layouter::ReduceLineCache();
1388 if (_game_mode
== GM_EDITOR
) {
1389 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1392 CallLandscapeTick();
1393 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1394 UpdateLandscapingLimits();
1396 CallWindowGameTickEvent();
1399 if (_debug_desync_level
> 2 && _date_fract
== 0 && (_date
& 0x1F) == 0) {
1400 /* Save the desync savegame if needed. */
1401 char name
[MAX_PATH
];
1402 seprintf(name
, lastof(name
), "dmp_cmds_%08x_%08x.sav", _settings_game
.game_creation
.generation_seed
, _date
);
1403 SaveOrLoad(name
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
, false);
1408 /* All these actions has to be done from OWNER_NONE
1409 * for multiplayer compatibility */
1410 Backup
<CompanyID
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1412 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1413 AnimateAnimatedTiles();
1417 CallLandscapeTick();
1418 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1420 #ifndef DEBUG_DUMP_COMMANDS
1422 PerformanceMeasurer
framerate(PFE_ALLSCRIPTS
);
1427 UpdateLandscapingLimits();
1429 CallWindowGameTickEvent();
1431 cur_company
.Restore();
1434 assert(IsLocalCompany());
1438 * Create an autosave. The default name is "autosave#.sav". However with
1439 * the setting 'keep_all_autosave' the name defaults to company-name + date
1441 static void DoAutosave()
1445 if (_settings_client
.gui
.keep_all_autosave
) {
1446 GenerateDefaultSaveName(buf
, lastof(buf
));
1447 strecat(buf
, ".sav", lastof(buf
));
1449 static int _autosave_ctr
= 0;
1451 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1452 seprintf(buf
, lastof(buf
), "autosave%d.sav", _autosave_ctr
);
1454 if (++_autosave_ctr
>= _settings_client
.gui
.max_num_autosaves
) _autosave_ctr
= 0;
1457 DEBUG(sl
, 2, "Autosaving to '%s'", buf
);
1458 if (SaveOrLoad(buf
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
) != SL_OK
) {
1459 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
1465 if (_game_mode
== GM_BOOTSTRAP
) {
1466 /* Check for UDP stuff */
1467 if (_network_available
) NetworkBackgroundLoop();
1472 ProcessAsyncSaveFinish();
1474 /* autosave game? */
1477 _do_autosave
= false;
1478 SetWindowDirty(WC_STATUS_BAR
, 0);
1481 /* switch game mode? */
1482 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1483 SwitchToMode(_switch_mode
);
1484 _switch_mode
= SM_NONE
;
1487 IncreaseSpriteLRU();
1488 InteractiveRandom();
1490 /* Check for UDP stuff */
1491 if (_network_available
) NetworkBackgroundLoop();
1493 if (_networking
&& !HasModalProgress()) {
1497 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1498 /* This means that we want to reconnect to the last host
1499 * We do this here, because it means that the network is really closed */
1500 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), COMPANY_SPECTATOR
);
1506 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1510 SoundDriver::GetInstance()->MainLoop();