4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file openttd.cpp Functions related to starting OpenTTD. */
14 #include "blitter/factory.hpp"
15 #include "sound/sound_driver.hpp"
16 #include "music/music_driver.hpp"
17 #include "video/video_driver.hpp"
19 #include "fontcache.h"
23 #include "base_media_base.h"
24 #include "saveload/saveload.h"
25 #include "company_func.h"
26 #include "command_func.h"
27 #include "news_func.h"
33 #include "console_func.h"
34 #include "screenshot.h"
35 #include "network/network.h"
36 #include "network/network_func.h"
38 #include "ai/ai_config.hpp"
39 #include "settings_func.h"
42 #include "strings_func.h"
43 #include "date_func.h"
44 #include "vehicle_func.h"
46 #include "animated_tile_func.h"
47 #include "roadstop_base.h"
48 #include "elrail_func.h"
50 #include "highscore.h"
51 #include "station_base.h"
53 #include "engine_func.h"
54 #include "core/random_func.hpp"
56 #include "core/backup_type.hpp"
59 #include "misc/getoptdata.h"
60 #include "game/game.hpp"
61 #include "game/game_config.hpp"
63 #include "subsidy_func.h"
64 #include "gfx_layout.h"
65 #include "viewport_sprite_sorter.h"
67 #include "linkgraph/linkgraphschedule.h"
71 #include "safeguards.h"
73 void CallLandscapeTick();
75 void DoPaletteAnimations();
78 void CallWindowTickEvent();
79 bool HandleBootstrap();
81 extern Company
*DoStartupNewCompany(bool is_ai
, CompanyID company
= INVALID_COMPANY
);
82 extern void ShowOSErrorBox(const char *buf
, bool system
);
83 extern char *_config_file
;
86 * Error handling for fatal user errors.
87 * @param s the string to print.
88 * @note Does NEVER return.
90 void CDECL
usererror(const char *s
, ...)
96 vseprintf(buf
, lastof(buf
), s
, va
);
99 ShowOSErrorBox(buf
, false);
100 if (VideoDriver::GetInstance() != NULL
) VideoDriver::GetInstance()->Stop();
106 * Error handling for fatal non-user errors.
107 * @param s the string to print.
108 * @note Does NEVER return.
110 void CDECL
error(const char *s
, ...)
116 vseprintf(buf
, lastof(buf
), s
, va
);
119 ShowOSErrorBox(buf
, true);
121 /* Set the error message for the crash log and then invoke it. */
122 CrashLog::SetErrorMessage(buf
);
127 * Shows some information on the console/a popup box depending on the OS.
128 * @param str the text to show.
130 void CDECL
ShowInfoF(const char *str
, ...)
135 vseprintf(buf
, lastof(buf
), str
, va
);
141 * Show the help message when someone passed a wrong parameter.
143 static void ShowHelp()
148 p
+= seprintf(p
, lastof(buf
), "OpenTTD %s\n", _openttd_revision
);
152 "Command line options:\n"
153 " -v drv = Set video driver (see below)\n"
154 " -s drv = Set sound driver (see below) (param bufsize,hz)\n"
155 " -m drv = Set music driver (see below)\n"
156 " -b drv = Set the blitter to use (see below)\n"
157 " -r res = Set resolution (for instance 800x600)\n"
158 " -h = Display this help text\n"
159 " -t year = Set starting year\n"
160 " -d [[fac=]lvl[,...]]= Debug mode\n"
161 " -e = Start Editor\n"
162 " -g [savegame] = Start new/save game immediately\n"
163 " -G seed = Set random seed\n"
164 #if defined(ENABLE_NETWORK)
165 " -n [ip:port#company]= Join network game\n"
166 " -p password = Password to join server\n"
167 " -P password = Password to join company\n"
168 " -D [ip][:port] = Start dedicated server\n"
169 " -l ip[:port] = Redirect DEBUG()\n"
170 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
171 " -f = Fork into the background (dedicated only)\n"
173 #endif /* ENABLE_NETWORK */
174 " -I graphics_set = Force the graphics set (see below)\n"
175 " -S sounds_set = Force the sounds set (see below)\n"
176 " -M music_set = Force the music set (see below)\n"
177 " -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
178 " -x = Do not automatically save to config file on exit\n"
179 " -q savegame = Write some information about the savegame and exit\n"
184 /* List the graphics packs */
185 p
= BaseGraphics::GetSetsList(p
, lastof(buf
));
187 /* List the sounds packs */
188 p
= BaseSounds::GetSetsList(p
, lastof(buf
));
190 /* List the music packs */
191 p
= BaseMusic::GetSetsList(p
, lastof(buf
));
193 /* List the drivers */
194 p
= DriverFactoryBase::GetDriversInfo(p
, lastof(buf
));
196 /* List the blitters */
197 p
= BlitterFactory::GetBlittersInfo(p
, lastof(buf
));
199 /* List the debug facilities. */
200 p
= DumpDebugFacilityNames(p
, lastof(buf
));
202 /* We need to initialize the AI, so it finds the AIs */
204 p
= AI::GetConsoleList(p
, lastof(buf
), true);
205 AI::Uninitialize(true);
207 /* We need to initialize the GameScript, so it finds the GSs */
209 p
= Game::GetConsoleList(p
, lastof(buf
), true);
210 Game::Uninitialize(true);
212 /* ShowInfo put output to stderr, but version information should go
213 * to stdout; this is the only exception */
214 #if !defined(WIN32) && !defined(WIN64)
221 static void WriteSavegameInfo(const char *name
)
223 extern uint16 _sl_version
;
224 uint32 last_ottd_rev
= 0;
225 byte ever_modified
= 0;
226 bool removed_newgrfs
= false;
228 GamelogInfo(_load_check_data
.gamelog_action
, _load_check_data
.gamelog_actions
, &last_ottd_rev
, &ever_modified
, &removed_newgrfs
);
232 p
+= seprintf(p
, lastof(buf
), "Name: %s\n", name
);
233 p
+= seprintf(p
, lastof(buf
), "Savegame ver: %d\n", _sl_version
);
234 p
+= seprintf(p
, lastof(buf
), "NewGRF ver: 0x%08X\n", last_ottd_rev
);
235 p
+= seprintf(p
, lastof(buf
), "Modified: %d\n", ever_modified
);
237 if (removed_newgrfs
) {
238 p
+= seprintf(p
, lastof(buf
), "NewGRFs have been removed\n");
241 p
= strecpy(p
, "NewGRFs:\n", lastof(buf
));
242 if (_load_check_data
.HasNewGrfs()) {
243 for (GRFConfig
*c
= _load_check_data
.grfconfig
; c
!= NULL
; c
= c
->next
) {
245 md5sumToString(md5sum
, lastof(md5sum
), HasBit(c
->flags
, GCF_COMPATIBLE
) ? c
->original_md5sum
: c
->ident
.md5sum
);
246 p
+= seprintf(p
, lastof(buf
), "%08X %s %s\n", c
->ident
.grfid
, md5sum
, c
->filename
);
250 /* ShowInfo put output to stderr, but version information should go
251 * to stdout; this is the only exception */
252 #if !defined(WIN32) && !defined(WIN64)
261 * Extract the resolution from the given string and store
262 * it in the 'res' parameter.
263 * @param res variable to store the resolution in.
264 * @param s the string to decompose.
266 static void ParseResolution(Dimension
*res
, const char *s
)
268 const char *t
= strchr(s
, 'x');
270 ShowInfoF("Invalid resolution '%s'", s
);
274 res
->width
= max(strtoul(s
, NULL
, 0), 64UL);
275 res
->height
= max(strtoul(t
+ 1, NULL
, 0), 64UL);
280 * Unitializes drivers, frees allocated memory, cleans pools, ...
281 * Generally, prepares the game for shutting down
283 static void ShutdownGame()
287 if (_network_available
) NetworkShutDown(); // Shut down the network and close any open connections
289 DriverFactoryBase::ShutdownDrivers();
291 UnInitWindowSystem();
293 /* stop the scripts */
294 AI::Uninitialize(false);
295 Game::Uninitialize(false);
297 /* Uninitialize variables that are allocated dynamically */
300 #ifdef ENABLE_NETWORK
304 LinkGraphSchedule::Clear();
305 PoolBase::Clean(PT_ALL
);
307 /* No NewGRFs were loaded when it was still bootstrapping. */
308 if (_game_mode
!= GM_BOOTSTRAP
) ResetNewGRFData();
310 /* Close all and any open filehandles */
317 * Load the introduction game.
318 * @param load_newgrfs Whether to load the NewGRFs or not.
320 static void LoadIntroGame(bool load_newgrfs
= true)
322 _game_mode
= GM_MENU
;
324 if (load_newgrfs
) ResetGRFConfig(false);
326 /* Setup main window */
328 SetupColoursAndInitialWindow();
330 /* Load the default opening screen savegame */
331 if (SaveOrLoad("opntitle.dat", SLO_LOAD
, DFT_GAME_FILE
, BASESET_DIR
) != SL_OK
) {
332 GenerateWorld(GWM_EMPTY
, 64, 64); // if failed loading, make empty world.
333 WaitTillGeneratedWorld();
334 SetLocalCompany(COMPANY_SPECTATOR
);
336 SetLocalCompany(COMPANY_FIRST
);
339 _pause_mode
= PM_UNPAUSED
;
340 _cursor
.fix_at
= false;
342 if (load_newgrfs
) CheckForMissingSprites();
343 CheckForMissingGlyphs();
345 /* Play main theme */
346 if (MusicDriver::GetInstance()->IsSongPlaying()) ResetMusic();
349 void MakeNewgameSettingsLive()
351 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
352 if (_settings_game
.ai_config
[c
] != NULL
) {
353 delete _settings_game
.ai_config
[c
];
356 if (_settings_game
.game_config
!= NULL
) {
357 delete _settings_game
.game_config
;
360 /* Copy newgame settings to active settings.
361 * Also initialise old settings needed for savegame conversion. */
362 _settings_game
= _settings_newgame
;
363 _old_vds
= _settings_client
.company
.vehicle
;
365 for (CompanyID c
= COMPANY_FIRST
; c
< MAX_COMPANIES
; c
++) {
366 _settings_game
.ai_config
[c
] = NULL
;
367 if (_settings_newgame
.ai_config
[c
] != NULL
) {
368 _settings_game
.ai_config
[c
] = new AIConfig(_settings_newgame
.ai_config
[c
]);
371 _settings_game
.game_config
= NULL
;
372 if (_settings_newgame
.game_config
!= NULL
) {
373 _settings_game
.game_config
= new GameConfig(_settings_newgame
.game_config
);
377 void OpenBrowser(const char *url
)
379 /* Make sure we only accept urls that are sure to open a browser. */
380 if (strstr(url
, "http://") != url
&& strstr(url
, "https://") != url
) return;
382 extern void OSOpenBrowser(const char *url
);
386 /** Callback structure of statements to be executed after the NewGRF scan. */
387 struct AfterNewGRFScan
: NewGRFScanCallback
{
388 Year startyear
; ///< The start year.
389 uint generation_seed
; ///< Seed for the new game.
390 char *dedicated_host
; ///< Hostname for the dedicated server.
391 uint16 dedicated_port
; ///< Port for the dedicated server.
392 char *network_conn
; ///< Information about the server to connect to, or NULL.
393 const char *join_server_password
; ///< The password to join the server with.
394 const char *join_company_password
; ///< The password to join the company with.
395 bool *save_config_ptr
; ///< The pointer to the save config setting.
396 bool save_config
; ///< The save config setting.
399 * Create a new callback.
400 * @param save_config_ptr Pointer to the save_config local variable which
401 * decides whether to save of exit or not.
403 AfterNewGRFScan(bool *save_config_ptr
) :
404 startyear(INVALID_YEAR
), generation_seed(GENERATE_NEW_SEED
),
405 dedicated_host(NULL
), dedicated_port(0), network_conn(NULL
),
406 join_server_password(NULL
), join_company_password(NULL
),
407 save_config_ptr(save_config_ptr
), save_config(true)
411 virtual void OnNewGRFsScanned()
413 ResetGRFConfig(false);
415 TarScanner::DoScan(TarScanner::SCENARIO
);
420 /* We want the new (correct) NewGRF count to survive the loading. */
421 uint last_newgrf_count
= _settings_client
.gui
.last_newgrf_count
;
423 _settings_client
.gui
.last_newgrf_count
= last_newgrf_count
;
424 /* Since the default for the palette might have changed due to
425 * reading the configuration file, recalculate that now. */
426 UpdateNewGRFConfigPalette();
428 Game::Uninitialize(true);
429 AI::Uninitialize(true);
432 LoadHotkeysFromConfig();
433 WindowDesc::LoadFromConfig();
435 /* We have loaded the config, so we may possibly save it. */
436 *save_config_ptr
= save_config
;
438 /* restore saved music volume */
439 MusicDriver::GetInstance()->SetVolume(_settings_client
.music
.music_vol
);
441 if (startyear
!= INVALID_YEAR
) _settings_newgame
.game_creation
.starting_year
= startyear
;
442 if (generation_seed
!= GENERATE_NEW_SEED
) _settings_newgame
.game_creation
.generation_seed
= generation_seed
;
444 #if defined(ENABLE_NETWORK)
445 if (dedicated_host
!= NULL
) {
446 _network_bind_list
.Clear();
447 *_network_bind_list
.Append() = stredup(dedicated_host
);
449 if (dedicated_port
!= 0) _settings_client
.network
.server_port
= dedicated_port
;
450 #endif /* ENABLE_NETWORK */
452 /* initialize the ingame console */
455 IConsoleCmdExec("exec scripts/autoexec.scr 0");
457 /* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
458 if (_switch_mode
!= SM_NONE
) MakeNewgameSettingsLive();
460 #ifdef ENABLE_NETWORK
461 if (_network_available
&& network_conn
!= NULL
) {
462 const char *port
= NULL
;
463 const char *company
= NULL
;
464 uint16 rport
= NETWORK_DEFAULT_PORT
;
465 CompanyID join_as
= COMPANY_NEW_COMPANY
;
467 ParseConnectionString(&company
, &port
, network_conn
);
469 if (company
!= NULL
) {
470 join_as
= (CompanyID
)atoi(company
);
472 if (join_as
!= COMPANY_SPECTATOR
) {
474 if (join_as
>= MAX_COMPANIES
) {
480 if (port
!= NULL
) rport
= atoi(port
);
483 _switch_mode
= SM_NONE
;
484 NetworkClientConnectGame(NetworkAddress(network_conn
, rport
), join_as
, join_server_password
, join_company_password
);
486 #endif /* ENABLE_NETWORK */
488 /* After the scan we're not used anymore. */
493 #if defined(UNIX) && !defined(__MORPHOS__)
494 extern void DedicatedFork();
497 /** Options of OpenTTD. */
498 static const OptionData _options
[] = {
499 GETOPT_SHORT_VALUE('I'),
500 GETOPT_SHORT_VALUE('S'),
501 GETOPT_SHORT_VALUE('M'),
502 GETOPT_SHORT_VALUE('m'),
503 GETOPT_SHORT_VALUE('s'),
504 GETOPT_SHORT_VALUE('v'),
505 GETOPT_SHORT_VALUE('b'),
506 #if defined(ENABLE_NETWORK)
507 GETOPT_SHORT_OPTVAL('D'),
508 GETOPT_SHORT_OPTVAL('n'),
509 GETOPT_SHORT_VALUE('l'),
510 GETOPT_SHORT_VALUE('p'),
511 GETOPT_SHORT_VALUE('P'),
512 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
513 GETOPT_SHORT_NOVAL('f'),
515 #endif /* ENABLE_NETWORK */
516 GETOPT_SHORT_VALUE('r'),
517 GETOPT_SHORT_VALUE('t'),
518 GETOPT_SHORT_OPTVAL('d'),
519 GETOPT_SHORT_NOVAL('e'),
520 GETOPT_SHORT_OPTVAL('g'),
521 GETOPT_SHORT_VALUE('G'),
522 GETOPT_SHORT_VALUE('c'),
523 GETOPT_SHORT_NOVAL('x'),
524 GETOPT_SHORT_VALUE('q'),
525 GETOPT_SHORT_NOVAL('h'),
530 * Main entry point for this lovely game.
531 * @param argc The number of arguments passed to this game.
532 * @param argv The values of the arguments.
533 * @return 0 when there is no error.
535 int openttd_main(int argc
, char *argv
[])
537 char *musicdriver
= NULL
;
538 char *sounddriver
= NULL
;
539 char *videodriver
= NULL
;
540 char *blitter
= NULL
;
541 char *graphics_set
= NULL
;
542 char *sounds_set
= NULL
;
543 char *music_set
= NULL
;
544 Dimension resolution
= {0, 0};
545 /* AfterNewGRFScan sets save_config to true after scanning completed. */
546 bool save_config
= false;
547 AfterNewGRFScan
*scanner
= new AfterNewGRFScan(&save_config
);
548 #if defined(ENABLE_NETWORK)
549 bool dedicated
= false;
550 char *debuglog_conn
= NULL
;
552 extern bool _dedicated_forks
;
553 _dedicated_forks
= false;
554 #endif /* ENABLE_NETWORK */
556 _game_mode
= GM_MENU
;
557 _switch_mode
= SM_MENU
;
560 GetOptData
mgo(argc
- 1, argv
+ 1, _options
);
564 while ((i
= mgo
.GetOpt()) != -1) {
566 case 'I': free(graphics_set
); graphics_set
= stredup(mgo
.opt
); break;
567 case 'S': free(sounds_set
); sounds_set
= stredup(mgo
.opt
); break;
568 case 'M': free(music_set
); music_set
= stredup(mgo
.opt
); break;
569 case 'm': free(musicdriver
); musicdriver
= stredup(mgo
.opt
); break;
570 case 's': free(sounddriver
); sounddriver
= stredup(mgo
.opt
); break;
571 case 'v': free(videodriver
); videodriver
= stredup(mgo
.opt
); break;
572 case 'b': free(blitter
); blitter
= stredup(mgo
.opt
); break;
573 #if defined(ENABLE_NETWORK)
579 musicdriver
= stredup("null");
580 sounddriver
= stredup("null");
581 videodriver
= stredup("dedicated");
582 blitter
= stredup("null");
584 SetDebugString("net=6");
585 if (mgo
.opt
!= NULL
) {
586 /* Use the existing method for parsing (openttd -n).
587 * However, we do ignore the #company part. */
588 const char *temp
= NULL
;
589 const char *port
= NULL
;
590 ParseConnectionString(&temp
, &port
, mgo
.opt
);
591 if (!StrEmpty(mgo
.opt
)) scanner
->dedicated_host
= mgo
.opt
;
592 if (port
!= NULL
) scanner
->dedicated_port
= atoi(port
);
595 case 'f': _dedicated_forks
= true; break;
597 scanner
->network_conn
= mgo
.opt
; // optional IP parameter, NULL if unset
600 debuglog_conn
= mgo
.opt
;
603 scanner
->join_server_password
= mgo
.opt
;
606 scanner
->join_company_password
= mgo
.opt
;
608 #endif /* ENABLE_NETWORK */
609 case 'r': ParseResolution(&resolution
, mgo
.opt
); break;
610 case 't': scanner
->startyear
= atoi(mgo
.opt
); break;
615 if (mgo
.opt
!= NULL
) SetDebugString(mgo
.opt
);
618 case 'e': _switch_mode
= (_switch_mode
== SM_LOAD_GAME
|| _switch_mode
== SM_LOAD_SCENARIO
? SM_LOAD_SCENARIO
: SM_EDITOR
); break;
620 if (mgo
.opt
!= NULL
) {
621 _file_to_saveload
.SetName(mgo
.opt
);
622 bool is_scenario
= _switch_mode
== SM_EDITOR
|| _switch_mode
== SM_LOAD_SCENARIO
;
623 _switch_mode
= is_scenario
? SM_LOAD_SCENARIO
: SM_LOAD_GAME
;
624 _file_to_saveload
.SetMode(SLO_LOAD
, is_scenario
? FT_SCENARIO
: FT_SAVEGAME
, DFT_GAME_FILE
);
626 /* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
627 const char *t
= strrchr(_file_to_saveload
.name
, '.');
629 FiosType ft
= FiosGetSavegameListCallback(SLO_LOAD
, _file_to_saveload
.name
, t
, NULL
, NULL
);
630 if (ft
!= FIOS_TYPE_INVALID
) _file_to_saveload
.SetMode(ft
);
636 _switch_mode
= SM_NEWGAME
;
637 /* Give a random map if no seed has been given */
638 if (scanner
->generation_seed
== GENERATE_NEW_SEED
) {
639 scanner
->generation_seed
= InteractiveRandom();
643 DeterminePaths(argv
[0]);
644 if (StrEmpty(mgo
.opt
)) {
646 goto exit_noshutdown
;
651 FiosGetSavegameListCallback(SLO_LOAD
, mgo
.opt
, strrchr(mgo
.opt
, '.'), title
, lastof(title
));
653 _load_check_data
.Clear();
654 SaveOrLoadResult res
= SaveOrLoad(mgo
.opt
, SLO_CHECK
, DFT_GAME_FILE
, SAVE_DIR
, false);
655 if (res
!= SL_OK
|| _load_check_data
.HasErrors()) {
656 fprintf(stderr
, "Failed to open savegame\n");
657 if (_load_check_data
.HasErrors()) {
659 SetDParamStr(0, _load_check_data
.error_data
);
660 GetString(buf
, _load_check_data
.error
, lastof(buf
));
661 fprintf(stderr
, "%s\n", buf
);
663 goto exit_noshutdown
;
666 WriteSavegameInfo(title
);
668 goto exit_noshutdown
;
670 case 'G': scanner
->generation_seed
= atoi(mgo
.opt
); break;
671 case 'c': free(_config_file
); _config_file
= stredup(mgo
.opt
); break;
672 case 'x': scanner
->save_config
= false; break;
674 i
= -2; // Force printing of help.
680 if (i
== -2 || mgo
.numleft
> 0) {
681 /* Either the user typed '-h', he made an error, or he added unrecognized command line arguments.
682 * In all cases, print the help, and exit.
684 * The next two functions are needed to list the graphics sets. We can't do them earlier
685 * because then we cannot show it on the debug console as that hasn't been configured yet. */
686 DeterminePaths(argv
[0]);
687 TarScanner::DoScan(TarScanner::BASESET
);
688 BaseGraphics::FindSets();
689 BaseSounds::FindSets();
690 BaseMusic::FindSets();
693 goto exit_noshutdown
;
696 #if defined(WINCE) && defined(_DEBUG)
697 /* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
701 DeterminePaths(argv
[0]);
702 TarScanner::DoScan(TarScanner::BASESET
);
704 #if defined(ENABLE_NETWORK)
705 if (dedicated
) DEBUG(net
, 0, "Starting dedicated version %s", _openttd_revision
);
706 if (_dedicated_forks
&& !dedicated
) _dedicated_forks
= false;
708 #if defined(UNIX) && !defined(__MORPHOS__)
709 /* We must fork here, or we'll end up without some resources we need (like sockets) */
710 if (_dedicated_forks
) DedicatedFork();
714 LoadFromConfig(true);
716 if (resolution
.width
!= 0) _cur_resolution
= resolution
;
719 * The width and height must be at least 1 pixel and width times
720 * height times bytes per pixel must still fit within a 32 bits
721 * integer, even for 32 bpp video modes. This way all internal
722 * drawing routines work correctly.
724 _cur_resolution
.width
= ClampU(_cur_resolution
.width
, 1, UINT16_MAX
/ 2);
725 _cur_resolution
.height
= ClampU(_cur_resolution
.height
, 1, UINT16_MAX
/ 2);
727 /* Assume the cursor starts within the game as not all video drivers
728 * get an event that the cursor is within the window when it is opened.
729 * Saying the cursor is there makes no visible difference as it would
730 * just be out of the bounds of the window. */
731 _cursor
.in_window
= true;
733 /* enumerate language files */
734 InitializeLanguagePacks();
736 /* Initialize the regular font for FreeType */
739 /* This must be done early, since functions use the SetWindowDirty* calls */
742 BaseGraphics::FindSets();
743 if (graphics_set
== NULL
&& BaseGraphics::ini_set
!= NULL
) graphics_set
= stredup(BaseGraphics::ini_set
);
744 if (!BaseGraphics::SetSet(graphics_set
)) {
745 if (!StrEmpty(graphics_set
)) {
746 BaseGraphics::SetSet(NULL
);
748 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_GRAPHICS_NOT_FOUND
);
749 msg
.SetDParamStr(0, graphics_set
);
750 ScheduleErrorMessage(msg
);
755 /* Initialize game palette */
758 DEBUG(misc
, 1, "Loading blitter...");
759 if (blitter
== NULL
&& _ini_blitter
!= NULL
) blitter
= stredup(_ini_blitter
);
760 _blitter_autodetected
= StrEmpty(blitter
);
761 /* Activate the initial blitter.
762 * This is only some initial guess, after NewGRFs have been loaded SwitchNewGRFBlitter may switch to a different one.
763 * - Never guess anything, if the user specified a blitter. (_blitter_autodetected)
764 * - Use 32bpp blitter if baseset or 8bpp-support settings says so.
765 * - Use 8bpp blitter otherwise.
767 if (!_blitter_autodetected
||
768 (_support8bpp
!= S8BPP_NONE
&& (BaseGraphics::GetUsedSet() == NULL
|| BaseGraphics::GetUsedSet()->blitter
== BLT_8BPP
)) ||
769 BlitterFactory::SelectBlitter("32bpp-anim") == NULL
) {
770 if (BlitterFactory::SelectBlitter(blitter
) == NULL
) {
772 usererror("Failed to autoprobe blitter") :
773 usererror("Failed to select requested blitter '%s'; does it exist?", blitter
);
778 if (videodriver
== NULL
&& _ini_videodriver
!= NULL
) videodriver
= stredup(_ini_videodriver
);
779 DriverFactoryBase::SelectDriver(videodriver
, Driver::DT_VIDEO
);
782 InitializeSpriteSorter();
784 /* Initialize the zoom level of the screen to normal */
785 _screen
.zoom
= ZOOM_LVL_NORMAL
;
787 NetworkStartUp(); // initialize network-core
789 #if defined(ENABLE_NETWORK)
790 if (debuglog_conn
!= NULL
&& _network_available
) {
791 const char *not_used
= NULL
;
792 const char *port
= NULL
;
795 rport
= NETWORK_DEFAULT_DEBUGLOG_PORT
;
797 ParseConnectionString(¬_used
, &port
, debuglog_conn
);
798 if (port
!= NULL
) rport
= atoi(port
);
800 NetworkStartDebugLog(NetworkAddress(debuglog_conn
, rport
));
802 #endif /* ENABLE_NETWORK */
804 if (!HandleBootstrap()) {
810 VideoDriver::GetInstance()->ClaimMousePointer();
812 /* initialize screenshot formats */
813 InitializeScreenshotFormats();
815 BaseSounds::FindSets();
816 if (sounds_set
== NULL
&& BaseSounds::ini_set
!= NULL
) sounds_set
= stredup(BaseSounds::ini_set
);
817 if (!BaseSounds::SetSet(sounds_set
)) {
818 if (StrEmpty(sounds_set
) || !BaseSounds::SetSet(NULL
)) {
819 usererror("Failed to find a sounds set. Please acquire a sounds set for OpenTTD. See section 4.1 of readme.txt.");
821 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_SOUNDS_NOT_FOUND
);
822 msg
.SetDParamStr(0, sounds_set
);
823 ScheduleErrorMessage(msg
);
828 BaseMusic::FindSets();
829 if (music_set
== NULL
&& BaseMusic::ini_set
!= NULL
) music_set
= stredup(BaseMusic::ini_set
);
830 if (!BaseMusic::SetSet(music_set
)) {
831 if (StrEmpty(music_set
) || !BaseMusic::SetSet(NULL
)) {
832 usererror("Failed to find a music set. Please acquire a music set for OpenTTD. See section 4.1 of readme.txt.");
834 ErrorMessageData
msg(STR_CONFIG_ERROR
, STR_CONFIG_ERROR_INVALID_BASE_MUSIC_NOT_FOUND
);
835 msg
.SetDParamStr(0, music_set
);
836 ScheduleErrorMessage(msg
);
841 if (sounddriver
== NULL
&& _ini_sounddriver
!= NULL
) sounddriver
= stredup(_ini_sounddriver
);
842 DriverFactoryBase::SelectDriver(sounddriver
, Driver::DT_SOUND
);
845 if (musicdriver
== NULL
&& _ini_musicdriver
!= NULL
) musicdriver
= stredup(_ini_musicdriver
);
846 DriverFactoryBase::SelectDriver(musicdriver
, Driver::DT_MUSIC
);
849 /* Take our initial lock on whatever we might want to do! */
850 _modal_progress_paint_mutex
->BeginCritical();
851 _modal_progress_work_mutex
->BeginCritical();
853 GenerateWorld(GWM_EMPTY
, 64, 64); // Make the viewport initialization happy
854 WaitTillGeneratedWorld();
856 LoadIntroGame(false);
858 CheckForMissingGlyphs();
860 /* ScanNewGRFFiles now has control over the scanner. */
861 ScanNewGRFFiles(scanner
);
864 VideoDriver::GetInstance()->MainLoop();
868 /* only save config if we have to */
871 SaveHotkeysToConfig();
872 WindowDesc::SaveToConfig();
876 /* Reset windowing system, stop drivers, free used memory, ... */
881 /* These three are normally freed before bootstrap. */
887 /* These are normally freed before exit, but after bootstrap. */
894 free(BaseGraphics::ini_set
);
895 free(BaseSounds::ini_set
);
896 free(BaseMusic::ini_set
);
898 free(_ini_musicdriver
);
899 free(_ini_sounddriver
);
900 free(_ini_videodriver
);
905 #ifdef ENABLE_NETWORK
906 extern FILE *_log_fd
;
907 if (_log_fd
!= NULL
) {
910 #endif /* ENABLE_NETWORK */
915 void HandleExitGameRequest()
917 if (_game_mode
== GM_MENU
|| _game_mode
== GM_BOOTSTRAP
) { // do not ask to quit on the main screen
919 } else if (_settings_client
.gui
.autosave_on_exit
) {
927 static void MakeNewGameDone()
929 SettingsDisableElrail(_settings_game
.vehicle
.disable_elrails
);
931 /* In a dedicated server, the server does not play */
932 if (!VideoDriver::GetInstance()->HasGUI()) {
933 SetLocalCompany(COMPANY_SPECTATOR
);
934 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
935 IConsoleCmdExec("exec scripts/game_start.scr 0");
939 /* Create a single company */
940 DoStartupNewCompany(false);
942 Company
*c
= Company::Get(COMPANY_FIRST
);
943 c
->settings
= _settings_client
.company
;
945 IConsoleCmdExec("exec scripts/game_start.scr 0");
947 SetLocalCompany(COMPANY_FIRST
);
951 #ifdef ENABLE_NETWORK
952 /* We are the server, we start a new company (not dedicated),
953 * so set the default password *if* needed. */
954 if (_network_server
&& !StrEmpty(_settings_client
.network
.default_company_pass
)) {
955 NetworkChangeCompanyPassword(_local_company
, _settings_client
.network
.default_company_pass
);
957 #endif /* ENABLE_NETWORK */
959 if (_settings_client
.gui
.pause_on_newgame
) DoCommandP(0, PM_PAUSED_NORMAL
, 1, CMD_PAUSE
);
963 MarkWholeScreenDirty();
966 static void MakeNewGame(bool from_heightmap
, bool reset_settings
)
968 _game_mode
= GM_NORMAL
;
970 ResetGRFConfig(true);
972 GenerateWorldSetCallback(&MakeNewGameDone
);
973 GenerateWorld(from_heightmap
? GWM_HEIGHTMAP
: GWM_NEWGAME
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
, reset_settings
);
976 static void MakeNewEditorWorldDone()
978 SetLocalCompany(OWNER_NONE
);
981 static void MakeNewEditorWorld()
983 _game_mode
= GM_EDITOR
;
985 ResetGRFConfig(true);
987 GenerateWorldSetCallback(&MakeNewEditorWorldDone
);
988 GenerateWorld(GWM_EMPTY
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
992 * Load the specified savegame but on error do different things.
993 * If loading fails due to corrupt savegame, bad version, etc. go back to
994 * a previous correct state. In the menu for example load the intro game again.
995 * @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
996 * @param newgm switch to this mode of loading fails due to some unknown error
997 * @param filename file to be loaded
998 * @param subdir default directory to look for filename, set to 0 if not needed
999 * @param lf Load filter to use, if NULL: use filename + subdir.
1001 bool SafeLoad(const char *filename
, SaveLoadOperation fop
, DetailedFileType dft
, GameMode newgm
, Subdirectory subdir
, struct LoadFilter
*lf
= NULL
)
1003 assert(fop
== SLO_LOAD
);
1004 assert(dft
== DFT_GAME_FILE
|| (lf
== NULL
&& dft
== DFT_OLD_GAME_FILE
));
1005 GameMode ogm
= _game_mode
;
1009 switch (lf
== NULL
? SaveOrLoad(filename
, fop
, dft
, subdir
) : LoadWithFilter(lf
)) {
1010 case SL_OK
: return true;
1013 #ifdef ENABLE_NETWORK
1014 if (_network_dedicated
) {
1016 * We need to reinit a network map...
1017 * We can't simply load the intro game here as that game has many
1018 * special cases which make clients desync immediately. So we fall
1019 * back to just generating a new game with the current settings.
1021 DEBUG(net
, 0, "Loading game failed, so a new (random) game will be started!");
1022 MakeNewGame(false, true);
1025 if (_network_server
) {
1026 /* We can't load the intro game as server, so disconnect first. */
1027 NetworkDisconnect();
1029 #endif /* ENABLE_NETWORK */
1033 case GM_MENU
: LoadIntroGame(); break;
1034 case GM_EDITOR
: MakeNewEditorWorld(); break;
1044 void SwitchToMode(SwitchMode new_mode
)
1046 #ifdef ENABLE_NETWORK
1047 /* If we are saving something, the network stays in his current state */
1048 if (new_mode
!= SM_SAVE_GAME
) {
1049 /* If the network is active, make it not-active */
1051 if (_network_server
&& (new_mode
== SM_LOAD_GAME
|| new_mode
== SM_NEWGAME
|| new_mode
== SM_RESTARTGAME
)) {
1054 NetworkDisconnect();
1058 /* If we are a server, we restart the server */
1059 if (_is_network_server
) {
1060 /* But not if we are going to the menu */
1061 if (new_mode
!= SM_MENU
) {
1062 /* check if we should reload the config */
1063 if (_settings_client
.network
.reload_cfg
) {
1065 MakeNewgameSettingsLive();
1066 ResetGRFConfig(false);
1068 NetworkServerStart();
1070 /* This client no longer wants to be a network-server */
1071 _is_network_server
= false;
1075 #endif /* ENABLE_NETWORK */
1076 /* Make sure all AI controllers are gone at quitting game */
1077 if (new_mode
!= SM_SAVE_GAME
) AI::KillAll();
1080 case SM_EDITOR
: // Switch to scenario editor
1081 MakeNewEditorWorld();
1084 case SM_RESTARTGAME
: // Restart --> 'Random game' with current settings
1085 case SM_NEWGAME
: // New Game --> 'Random game'
1086 #ifdef ENABLE_NETWORK
1087 if (_network_server
) {
1088 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "Random Map");
1090 #endif /* ENABLE_NETWORK */
1091 MakeNewGame(false, new_mode
== SM_NEWGAME
);
1094 case SM_LOAD_GAME
: { // Load game, Play Scenario
1095 ResetGRFConfig(true);
1096 ResetWindowSystem();
1098 if (!SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_NORMAL
, NO_DIRECTORY
)) {
1099 SetDParamStr(0, GetSaveLoadErrorString());
1100 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1102 if (_file_to_saveload
.abstract_ftype
== FT_SCENARIO
) {
1103 /* Reset engine pool to simplify changing engine NewGRFs in scenario editor. */
1104 EngineOverrideManager::ResetToCurrentNewGRFConfig();
1106 /* Update the local company for a loaded game. It is either always
1107 * company #1 (eg 0) or in the case of a dedicated server a spectator */
1108 SetLocalCompany(_network_dedicated
? COMPANY_SPECTATOR
: COMPANY_FIRST
);
1109 /* Execute the game-start script */
1110 IConsoleCmdExec("exec scripts/game_start.scr 0");
1111 /* Decrease pause counter (was increased from opening load dialog) */
1112 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1113 #ifdef ENABLE_NETWORK
1114 if (_network_server
) {
1115 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Loaded game)", _file_to_saveload
.title
);
1117 #endif /* ENABLE_NETWORK */
1122 case SM_START_HEIGHTMAP
: // Load a heightmap and start a new game from it
1123 #ifdef ENABLE_NETWORK
1124 if (_network_server
) {
1125 seprintf(_network_game_info
.map_name
, lastof(_network_game_info
.map_name
), "%s (Heightmap)", _file_to_saveload
.title
);
1127 #endif /* ENABLE_NETWORK */
1128 MakeNewGame(true, true);
1131 case SM_LOAD_HEIGHTMAP
: // Load heightmap from scenario editor
1132 SetLocalCompany(OWNER_NONE
);
1134 GenerateWorld(GWM_HEIGHTMAP
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1135 MarkWholeScreenDirty();
1138 case SM_LOAD_SCENARIO
: { // Load scenario from scenario editor
1139 if (SafeLoad(_file_to_saveload
.name
, _file_to_saveload
.file_op
, _file_to_saveload
.detail_ftype
, GM_EDITOR
, NO_DIRECTORY
)) {
1140 SetLocalCompany(OWNER_NONE
);
1141 _settings_newgame
.game_creation
.starting_year
= _cur_year
;
1142 /* Cancel the saveload pausing */
1143 DoCommandP(0, PM_PAUSED_SAVELOAD
, 0, CMD_PAUSE
);
1145 SetDParamStr(0, GetSaveLoadErrorString());
1146 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1151 case SM_MENU
: // Switch to game intro menu
1153 if (BaseSounds::ini_set
== NULL
&& BaseSounds::GetUsedSet()->fallback
) {
1154 ShowErrorMessage(STR_WARNING_FALLBACK_SOUNDSET
, INVALID_STRING_ID
, WL_CRITICAL
);
1155 BaseSounds::ini_set
= stredup(BaseSounds::GetUsedSet()->name
);
1159 case SM_SAVE_GAME
: // Save game.
1160 /* Make network saved games on pause compatible to singleplayer */
1161 if (SaveOrLoad(_file_to_saveload
.name
, SLO_SAVE
, DFT_GAME_FILE
, NO_DIRECTORY
) != SL_OK
) {
1162 SetDParamStr(0, GetSaveLoadErrorString());
1163 ShowErrorMessage(STR_JUST_RAW_STRING
, INVALID_STRING_ID
, WL_ERROR
);
1165 DeleteWindowById(WC_SAVELOAD
, 0);
1169 case SM_SAVE_HEIGHTMAP
: // Save heightmap.
1170 MakeHeightmapScreenshot(_file_to_saveload
.name
);
1171 DeleteWindowById(WC_SAVELOAD
, 0);
1174 case SM_GENRANDLAND
: // Generate random land within scenario editor
1175 SetLocalCompany(OWNER_NONE
);
1176 GenerateWorld(GWM_RANDOM
, 1 << _settings_game
.game_creation
.map_x
, 1 << _settings_game
.game_creation
.map_y
);
1178 MarkWholeScreenDirty();
1181 default: NOT_REACHED();
1187 * Check the validity of some of the caches.
1188 * Especially in the sense of desyncs between
1189 * the cached value and what the value would
1190 * be when calculated from the 'base' data.
1192 static void CheckCaches()
1194 /* Return here so it is easy to add checks that are run
1195 * always to aid testing of caches. */
1196 if (_debug_desync_level
<= 1) return;
1198 /* Check the town caches. */
1199 SmallVector
<TownCache
, 4> old_town_caches
;
1202 MemCpyT(old_town_caches
.Append(), &t
->cache
);
1205 extern void RebuildTownCaches();
1206 RebuildTownCaches();
1207 RebuildSubsidisedSourceAndDestinationCache();
1211 if (MemCmpT(old_town_caches
.Get(i
), &t
->cache
) != 0) {
1212 DEBUG(desync
, 2, "town cache mismatch: town %i", (int)t
->index
);
1217 /* Check company infrastructure cache. */
1218 SmallVector
<CompanyInfrastructure
, 4> old_infrastructure
;
1220 FOR_ALL_COMPANIES(c
) MemCpyT(old_infrastructure
.Append(), &c
->infrastructure
);
1222 extern void AfterLoadCompanyStats();
1223 AfterLoadCompanyStats();
1226 FOR_ALL_COMPANIES(c
) {
1227 if (MemCmpT(old_infrastructure
.Get(i
), &c
->infrastructure
) != 0) {
1228 DEBUG(desync
, 2, "infrastructure cache mismatch: company %i", (int)c
->index
);
1233 /* Strict checking of the road stop cache entries */
1235 FOR_ALL_ROADSTOPS(rs
) {
1236 if (IsStandardRoadStopTile(rs
->xy
)) continue;
1238 assert(rs
->GetEntry(DIAGDIR_NE
) != rs
->GetEntry(DIAGDIR_NW
));
1239 rs
->GetEntry(DIAGDIR_NE
)->CheckIntegrity(rs
);
1240 rs
->GetEntry(DIAGDIR_NW
)->CheckIntegrity(rs
);
1244 FOR_ALL_VEHICLES(v
) {
1245 extern void FillNewGRFVehicleCache(const Vehicle
*v
);
1246 if (v
!= v
->First() || v
->vehstatus
& VS_CRASHED
|| !v
->IsPrimaryVehicle()) continue;
1249 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) length
++;
1251 NewGRFCache
*grf_cache
= CallocT
<NewGRFCache
>(length
);
1252 VehicleCache
*veh_cache
= CallocT
<VehicleCache
>(length
);
1253 GroundVehicleCache
*gro_cache
= CallocT
<GroundVehicleCache
>(length
);
1254 TrainCache
*tra_cache
= CallocT
<TrainCache
>(length
);
1257 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1258 FillNewGRFVehicleCache(u
);
1259 grf_cache
[length
] = u
->grf_cache
;
1260 veh_cache
[length
] = u
->vcache
;
1263 gro_cache
[length
] = Train::From(u
)->gcache
;
1264 tra_cache
[length
] = Train::From(u
)->tcache
;
1267 gro_cache
[length
] = RoadVehicle::From(u
)->gcache
;
1276 case VEH_TRAIN
: Train::From(v
)->ConsistChanged(CCF_TRACK
); break;
1277 case VEH_ROAD
: RoadVehUpdateCache(RoadVehicle::From(v
)); break;
1278 case VEH_AIRCRAFT
: UpdateAircraftCache(Aircraft::From(v
)); break;
1279 case VEH_SHIP
: Ship::From(v
)->UpdateCache(); break;
1284 for (const Vehicle
*u
= v
; u
!= NULL
; u
= u
->Next()) {
1285 FillNewGRFVehicleCache(u
);
1286 if (memcmp(&grf_cache
[length
], &u
->grf_cache
, sizeof(NewGRFCache
)) != 0) {
1287 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
);
1289 if (memcmp(&veh_cache
[length
], &u
->vcache
, sizeof(VehicleCache
)) != 0) {
1290 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
);
1294 if (memcmp(&gro_cache
[length
], &Train::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1295 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
);
1297 if (memcmp(&tra_cache
[length
], &Train::From(u
)->tcache
, sizeof(TrainCache
)) != 0) {
1298 DEBUG(desync
, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v
->index
, (int)v
->owner
, v
->unitnumber
, length
);
1302 if (memcmp(&gro_cache
[length
], &RoadVehicle::From(u
)->gcache
, sizeof(GroundVehicleCache
)) != 0) {
1303 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
);
1318 /* Check whether the caches are still valid */
1319 FOR_ALL_VEHICLES(v
) {
1320 byte buff
[sizeof(VehicleCargoList
)];
1321 memcpy(buff
, &v
->cargo
, sizeof(VehicleCargoList
));
1322 v
->cargo
.InvalidateCache();
1323 assert(memcmp(&v
->cargo
, buff
, sizeof(VehicleCargoList
)) == 0);
1327 FOR_ALL_STATIONS(st
) {
1328 for (CargoID c
= 0; c
< NUM_CARGO
; c
++) {
1329 byte buff
[sizeof(StationCargoList
)];
1330 memcpy(buff
, &st
->goods
[c
].cargo
, sizeof(StationCargoList
));
1331 st
->goods
[c
].cargo
.InvalidateCache();
1332 assert(memcmp(&st
->goods
[c
].cargo
, buff
, sizeof(StationCargoList
)) == 0);
1338 * State controlling game loop.
1339 * The state must not be changed from anywhere but here.
1340 * That check is enforced in DoCommand.
1342 void StateGameLoop()
1344 /* don't execute the state loop during pause */
1345 if (_pause_mode
!= PM_UNPAUSED
) {
1346 UpdateLandscapingLimits();
1347 #ifndef DEBUG_DUMP_COMMANDS
1350 CallWindowTickEvent();
1353 if (HasModalProgress()) return;
1355 Layouter::ReduceLineCache();
1357 if (_game_mode
== GM_EDITOR
) {
1358 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1361 CallLandscapeTick();
1362 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1363 UpdateLandscapingLimits();
1365 CallWindowTickEvent();
1368 if (_debug_desync_level
> 2 && _date_fract
== 0 && (_date
& 0x1F) == 0) {
1369 /* Save the desync savegame if needed. */
1370 char name
[MAX_PATH
];
1371 seprintf(name
, lastof(name
), "dmp_cmds_%08x_%08x.sav", _settings_game
.game_creation
.generation_seed
, _date
);
1372 SaveOrLoad(name
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
, false);
1377 /* All these actions has to be done from OWNER_NONE
1378 * for multiplayer compatibility */
1379 Backup
<CompanyByte
> cur_company(_current_company
, OWNER_NONE
, FILE_LINE
);
1381 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP
);
1382 AnimateAnimatedTiles();
1386 CallLandscapeTick();
1387 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP
);
1389 #ifndef DEBUG_DUMP_COMMANDS
1393 UpdateLandscapingLimits();
1395 CallWindowTickEvent();
1397 cur_company
.Restore();
1400 assert(IsLocalCompany());
1404 * Create an autosave. The default name is "autosave#.sav". However with
1405 * the setting 'keep_all_autosave' the name defaults to company-name + date
1407 static void DoAutosave()
1412 /* Autosaving in networking is too time expensive for the PSP */
1413 if (_networking
) return;
1416 if (_settings_client
.gui
.keep_all_autosave
) {
1417 GenerateDefaultSaveName(buf
, lastof(buf
));
1418 strecat(buf
, ".sav", lastof(buf
));
1420 static int _autosave_ctr
= 0;
1422 /* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
1423 seprintf(buf
, lastof(buf
), "autosave%d.sav", _autosave_ctr
);
1425 if (++_autosave_ctr
>= _settings_client
.gui
.max_num_autosaves
) _autosave_ctr
= 0;
1428 DEBUG(sl
, 2, "Autosaving to '%s'", buf
);
1429 if (SaveOrLoad(buf
, SLO_SAVE
, DFT_GAME_FILE
, AUTOSAVE_DIR
) != SL_OK
) {
1430 ShowErrorMessage(STR_ERROR_AUTOSAVE_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
1436 if (_game_mode
== GM_BOOTSTRAP
) {
1437 #ifdef ENABLE_NETWORK
1438 /* Check for UDP stuff */
1439 if (_network_available
) NetworkBackgroundLoop();
1445 ProcessAsyncSaveFinish();
1447 /* autosave game? */
1450 _do_autosave
= false;
1451 SetWindowDirty(WC_STATUS_BAR
, 0);
1454 /* switch game mode? */
1455 if (_switch_mode
!= SM_NONE
&& !HasModalProgress()) {
1456 SwitchToMode(_switch_mode
);
1457 _switch_mode
= SM_NONE
;
1460 IncreaseSpriteLRU();
1461 InteractiveRandom();
1463 extern int _caret_timer
;
1467 #ifdef ENABLE_NETWORK
1468 /* Check for UDP stuff */
1469 if (_network_available
) NetworkBackgroundLoop();
1471 if (_networking
&& !HasModalProgress()) {
1475 if (_network_reconnect
> 0 && --_network_reconnect
== 0) {
1476 /* This means that we want to reconnect to the last host
1477 * We do this here, because it means that the network is really closed */
1478 NetworkClientConnectGame(NetworkAddress(_settings_client
.network
.last_host
, _settings_client
.network
.last_port
), COMPANY_SPECTATOR
);
1484 /* Check chat messages roughly once a second. */
1485 static uint check_message
= 0;
1486 if (++check_message
> 1000 / MILLISECONDS_PER_TICK
) {
1488 NetworkChatMessageLoop();
1492 #endif /* ENABLE_NETWORK */
1494 if (!_pause_mode
&& HasBit(_display_opt
, DO_FULL_ANIMATION
)) DoPaletteAnimations();
1496 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects();
1500 SoundDriver::GetInstance()->MainLoop();